@oxog/i18n-react 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -285
- package/dist/index.d.mts +24 -22
- package/dist/index.d.ts +24 -22
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +27 -11
package/README.md
CHANGED
|
@@ -1,49 +1,31 @@
|
|
|
1
1
|
# @oxog/i18n-react
|
|
2
2
|
|
|
3
|
-
React bindings for @oxog/i18n
|
|
4
|
-
|
|
5
|
-
## Features
|
|
6
|
-
|
|
7
|
-
- 🎯 **React Hooks**: Modern hooks API for translations
|
|
8
|
-
- 🔄 **Context Provider**: Share i18n instance across your app
|
|
9
|
-
- 🎨 **Components**: Ready-to-use translation components
|
|
10
|
-
- 📦 **TypeScript Support**: Full type safety with TypeScript
|
|
11
|
-
- ⚡ **Performance**: Optimized re-renders with memoization
|
|
12
|
-
- 🔌 **SSR Compatible**: Works with Next.js and server-side rendering
|
|
3
|
+
React bindings for [@oxog/i18n](https://www.npmjs.com/package/@oxog/i18n): a context provider,
|
|
4
|
+
hooks and components that re-render when the locale changes or when messages are loaded later.
|
|
13
5
|
|
|
14
6
|
## Installation
|
|
15
7
|
|
|
16
8
|
```bash
|
|
17
9
|
npm install @oxog/i18n @oxog/i18n-react
|
|
18
|
-
# or
|
|
19
|
-
pnpm add @oxog/i18n @oxog/i18n-react
|
|
20
|
-
# or
|
|
21
|
-
yarn add @oxog/i18n @oxog/i18n-react
|
|
22
10
|
```
|
|
23
11
|
|
|
24
|
-
|
|
12
|
+
React 18 or newer is required. The bundle carries a `'use client'` directive, so it can be
|
|
13
|
+
imported from Next.js App Router client components and layouts.
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
25
16
|
|
|
26
17
|
```tsx
|
|
27
|
-
import React from 'react';
|
|
28
18
|
import { createI18n } from '@oxog/i18n';
|
|
29
|
-
import { I18nProvider,
|
|
19
|
+
import { I18nProvider, Trans, useTranslation } from '@oxog/i18n-react';
|
|
30
20
|
|
|
31
|
-
// Create i18n instance
|
|
32
21
|
const i18n = createI18n({
|
|
33
22
|
locale: 'en',
|
|
34
23
|
messages: {
|
|
35
|
-
en: {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
},
|
|
39
|
-
es: {
|
|
40
|
-
greeting: '¡Hola, {name}!',
|
|
41
|
-
description: 'Bienvenido a <bold>React</bold> i18n'
|
|
42
|
-
}
|
|
43
|
-
}
|
|
24
|
+
en: { greeting: 'Hello, {{name}}!', description: 'Welcome to <bold>React</bold> i18n' },
|
|
25
|
+
es: { greeting: '¡Hola, {{name}}!', description: 'Bienvenido a <bold>React</bold> i18n' },
|
|
26
|
+
},
|
|
44
27
|
});
|
|
45
28
|
|
|
46
|
-
// Wrap your app with I18nProvider
|
|
47
29
|
function App() {
|
|
48
30
|
return (
|
|
49
31
|
<I18nProvider i18n={i18n}>
|
|
@@ -52,296 +34,80 @@ function App() {
|
|
|
52
34
|
);
|
|
53
35
|
}
|
|
54
36
|
|
|
55
|
-
// Use translations in your components
|
|
56
37
|
function MyComponent() {
|
|
57
38
|
const { t, locale, setLocale } = useTranslation();
|
|
58
|
-
|
|
59
39
|
return (
|
|
60
40
|
<div>
|
|
61
41
|
<h1>{t('greeting', { name: 'World' })}</h1>
|
|
62
|
-
<Trans
|
|
63
|
-
<button onClick={() => setLocale(locale === 'en' ? 'es' : 'en')}>
|
|
64
|
-
Switch Language
|
|
65
|
-
</button>
|
|
42
|
+
<Trans id="description" components={{ bold: <strong /> }} />
|
|
43
|
+
<button onClick={() => setLocale(locale === 'en' ? 'es' : 'en')}>Switch language</button>
|
|
66
44
|
</div>
|
|
67
45
|
);
|
|
68
46
|
}
|
|
69
47
|
```
|
|
70
48
|
|
|
71
|
-
## API
|
|
49
|
+
## API
|
|
72
50
|
|
|
73
|
-
### `<I18nProvider>`
|
|
51
|
+
### `<I18nProvider i18n={instance}>`
|
|
74
52
|
|
|
75
|
-
|
|
53
|
+
Makes an instance created with `createI18n()` available to the hooks and components below.
|
|
54
|
+
Create the instance once, outside components.
|
|
76
55
|
|
|
77
|
-
|
|
78
|
-
import { I18nProvider } from '@oxog/i18n-react';
|
|
79
|
-
|
|
80
|
-
<I18nProvider i18n={i18nInstance}>
|
|
81
|
-
<App />
|
|
82
|
-
</I18nProvider>
|
|
83
|
-
```
|
|
56
|
+
### `useTranslation(namespace?)`
|
|
84
57
|
|
|
85
|
-
|
|
86
|
-
- `i18n`: The i18n instance created with `createI18n()`
|
|
87
|
-
- `children`: Your React components
|
|
58
|
+
Returns `{ t, locale, setLocale, formatNumber, formatDate, formatRelativeTime }`.
|
|
88
59
|
|
|
89
|
-
|
|
60
|
+
- `t` gets a new identity whenever the visible text changes (locale switch or
|
|
61
|
+
`i18n.addMessages()` for the active/fallback locale), so `memo` children and effects that
|
|
62
|
+
depend on `t` update too.
|
|
63
|
+
- `useTranslation('feature')` prefixes keys: `t('title')` translates `feature.title`.
|
|
64
|
+
- Pass your catalog type for checked keys: `useTranslation<AppMessages>()`.
|
|
90
65
|
|
|
91
|
-
|
|
66
|
+
### `useI18n()`, `useLocale()`, `useHasTranslation()`, `useI18nContext()`
|
|
92
67
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
```
|
|
68
|
+
`useI18n()` returns the instance and subscribes the component to changes; `useLocale()`
|
|
69
|
+
returns `[locale, setLocale]`; `useHasTranslation()` returns `(key, locale?) => boolean`.
|
|
96
70
|
|
|
97
|
-
|
|
98
|
-
- `t`: Translation function
|
|
99
|
-
- `locale`: Current locale
|
|
100
|
-
- `setLocale`: Function to change locale
|
|
101
|
-
- `i18n`: The i18n instance
|
|
71
|
+
### `<T id values? as? className? />`
|
|
102
72
|
|
|
103
|
-
|
|
73
|
+
Renders a translated string inside a `<span>` (or the element given by `as`). Other HTML
|
|
74
|
+
attributes (`title`, `role`, `aria-*`, `data-*`) are forwarded.
|
|
104
75
|
|
|
105
|
-
|
|
76
|
+
### `<Trans id values? components? as? />`
|
|
106
77
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
78
|
+
Renders a translation that contains tags. Tags are matched to `components` by name or
|
|
79
|
+
index: `'Read <0>the docs</0>'` with `components={{ 0: <a href="/docs" /> }}`, or
|
|
80
|
+
`<bold>…</bold>` with `components={{ bold: <strong /> }}`. Tags without a matching component
|
|
81
|
+
are rendered as text.
|
|
110
82
|
|
|
111
|
-
|
|
83
|
+
Interpolated `values` are always rendered as text: a value such as `"<0>x</0>"` or
|
|
84
|
+
`"<img src=x>"` is neither turned into a component nor parsed as HTML.
|
|
112
85
|
|
|
113
|
-
|
|
86
|
+
### `<NumberFormat>`, `<DateFormat>`, `<RelativeTime>`
|
|
114
87
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
i18nKey="message"
|
|
118
|
-
values={{ count: 5 }}
|
|
119
|
-
components={{
|
|
120
|
-
bold: <strong />,
|
|
121
|
-
link: <a href="/docs" />
|
|
122
|
-
}}
|
|
123
|
-
/>
|
|
124
|
-
```
|
|
88
|
+
Format numbers, dates (Date, timestamp or ISO string) and relative times with the active
|
|
89
|
+
locale; the formats come from `createI18n({ formats })`.
|
|
125
90
|
|
|
126
|
-
|
|
127
|
-
- `i18nKey`: Translation key
|
|
128
|
-
- `values`: Interpolation values
|
|
129
|
-
- `components`: Components to embed in translation
|
|
130
|
-
- `defaultValue`: Fallback value
|
|
131
|
-
|
|
132
|
-
## Advanced Usage
|
|
133
|
-
|
|
134
|
-
### TypeScript Support
|
|
91
|
+
## Loading messages later
|
|
135
92
|
|
|
136
93
|
```tsx
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
welcome: string;
|
|
142
|
-
profile: string;
|
|
143
|
-
};
|
|
144
|
-
};
|
|
145
|
-
|
|
146
|
-
// Create typed hooks
|
|
147
|
-
const { useTranslation } = createI18nReact<MessageSchema>();
|
|
148
|
-
|
|
149
|
-
// Use with full type safety
|
|
150
|
-
function Component() {
|
|
151
|
-
const { t } = useTranslation();
|
|
152
|
-
|
|
153
|
-
t('greeting'); // ✅ Valid
|
|
154
|
-
t('user.welcome'); // ✅ Valid
|
|
155
|
-
t('invalid.key'); // ❌ TypeScript error
|
|
94
|
+
async function loadGerman() {
|
|
95
|
+
const { default: de } = await import('./locales/de.json');
|
|
96
|
+
i18n.addMessages('de', de);
|
|
97
|
+
i18n.setLocale('de');
|
|
156
98
|
}
|
|
157
99
|
```
|
|
158
100
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
```tsx
|
|
164
|
-
function FeatureComponent() {
|
|
165
|
-
const { t } = useTranslation('feature');
|
|
166
|
-
|
|
167
|
-
return <div>{t('title')}</div>; // Translates 'feature.title'
|
|
168
|
-
}
|
|
169
|
-
```
|
|
170
|
-
|
|
171
|
-
### Suspense Support
|
|
172
|
-
|
|
173
|
-
Load translations asynchronously:
|
|
101
|
+
Components re-render after `addMessages()` for the active locale, so messages can also be
|
|
102
|
+
added after the first render. There is no Suspense integration: render a fallback yourself
|
|
103
|
+
while the import is pending.
|
|
174
104
|
|
|
175
|
-
|
|
176
|
-
import { Suspense } from 'react';
|
|
177
|
-
import { I18nProvider, useLazyTranslation } from '@oxog/i18n-react';
|
|
178
|
-
|
|
179
|
-
function AsyncComponent() {
|
|
180
|
-
const { t } = useLazyTranslation();
|
|
181
|
-
return <div>{t('async.message')}</div>;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function App() {
|
|
185
|
-
return (
|
|
186
|
-
<I18nProvider i18n={i18n}>
|
|
187
|
-
<Suspense fallback={<div>Loading translations...</div>}>
|
|
188
|
-
<AsyncComponent />
|
|
189
|
-
</Suspense>
|
|
190
|
-
</I18nProvider>
|
|
191
|
-
);
|
|
192
|
-
}
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
### Server-Side Rendering (SSR)
|
|
196
|
-
|
|
197
|
-
```tsx
|
|
198
|
-
// Next.js example
|
|
199
|
-
import { GetServerSideProps } from 'next';
|
|
200
|
-
|
|
201
|
-
export const getServerSideProps: GetServerSideProps = async ({ locale }) => {
|
|
202
|
-
const messages = await import(`../locales/${locale}.json`);
|
|
203
|
-
|
|
204
|
-
return {
|
|
205
|
-
props: {
|
|
206
|
-
locale,
|
|
207
|
-
messages: messages.default
|
|
208
|
-
}
|
|
209
|
-
};
|
|
210
|
-
};
|
|
211
|
-
|
|
212
|
-
function MyApp({ Component, pageProps }) {
|
|
213
|
-
const i18n = createI18n({
|
|
214
|
-
locale: pageProps.locale,
|
|
215
|
-
messages: {
|
|
216
|
-
[pageProps.locale]: pageProps.messages
|
|
217
|
-
}
|
|
218
|
-
});
|
|
219
|
-
|
|
220
|
-
return (
|
|
221
|
-
<I18nProvider i18n={i18n}>
|
|
222
|
-
<Component {...pageProps} />
|
|
223
|
-
</I18nProvider>
|
|
224
|
-
);
|
|
225
|
-
}
|
|
226
|
-
```
|
|
105
|
+
## Server-side rendering
|
|
227
106
|
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
import { memo } from 'react';
|
|
232
|
-
import { useTranslation } from '@oxog/i18n-react';
|
|
233
|
-
|
|
234
|
-
// Component only re-renders when translation changes
|
|
235
|
-
const TranslatedComponent = memo(function TranslatedComponent() {
|
|
236
|
-
const { t } = useTranslation();
|
|
237
|
-
|
|
238
|
-
return (
|
|
239
|
-
<div>
|
|
240
|
-
<h1>{t('expensive.computation')}</h1>
|
|
241
|
-
</div>
|
|
242
|
-
);
|
|
243
|
-
});
|
|
244
|
-
|
|
245
|
-
// Selective subscription
|
|
246
|
-
function OptimizedComponent() {
|
|
247
|
-
// Only subscribe to locale changes, not translation updates
|
|
248
|
-
const { locale, setLocale } = useTranslation({ subscribe: ['locale'] });
|
|
249
|
-
|
|
250
|
-
return (
|
|
251
|
-
<select value={locale} onChange={(e) => setLocale(e.target.value)}>
|
|
252
|
-
<option value="en">English</option>
|
|
253
|
-
<option value="es">Español</option>
|
|
254
|
-
</select>
|
|
255
|
-
);
|
|
256
|
-
}
|
|
257
|
-
```
|
|
258
|
-
|
|
259
|
-
### Custom Components
|
|
260
|
-
|
|
261
|
-
Create your own translation components:
|
|
262
|
-
|
|
263
|
-
```tsx
|
|
264
|
-
import { useTranslation } from '@oxog/i18n-react';
|
|
265
|
-
|
|
266
|
-
function FormattedDate({ date, format = 'short' }) {
|
|
267
|
-
const { t, locale } = useTranslation();
|
|
268
|
-
|
|
269
|
-
const formatted = new Intl.DateTimeFormat(locale, {
|
|
270
|
-
dateStyle: format
|
|
271
|
-
}).format(date);
|
|
272
|
-
|
|
273
|
-
return <time dateTime={date.toISOString()}>{formatted}</time>;
|
|
274
|
-
}
|
|
275
|
-
```
|
|
276
|
-
|
|
277
|
-
## Best Practices
|
|
278
|
-
|
|
279
|
-
1. **Initialize i18n outside components** to prevent recreation on each render
|
|
280
|
-
2. **Use `Trans` component** for translations with embedded React components
|
|
281
|
-
3. **Memoize components** that use translations to optimize performance
|
|
282
|
-
4. **Load translations asynchronously** for code splitting
|
|
283
|
-
5. **Type your translations** for better developer experience
|
|
284
|
-
|
|
285
|
-
## Examples
|
|
286
|
-
|
|
287
|
-
### Language Switcher
|
|
288
|
-
|
|
289
|
-
```tsx
|
|
290
|
-
function LanguageSwitcher() {
|
|
291
|
-
const { locale, setLocale } = useTranslation();
|
|
292
|
-
const languages = [
|
|
293
|
-
{ code: 'en', name: 'English' },
|
|
294
|
-
{ code: 'es', name: 'Español' },
|
|
295
|
-
{ code: 'fr', name: 'Français' }
|
|
296
|
-
];
|
|
297
|
-
|
|
298
|
-
return (
|
|
299
|
-
<select value={locale} onChange={(e) => setLocale(e.target.value)}>
|
|
300
|
-
{languages.map(lang => (
|
|
301
|
-
<option key={lang.code} value={lang.code}>
|
|
302
|
-
{lang.name}
|
|
303
|
-
</option>
|
|
304
|
-
))}
|
|
305
|
-
</select>
|
|
306
|
-
);
|
|
307
|
-
}
|
|
308
|
-
```
|
|
309
|
-
|
|
310
|
-
### Pluralization
|
|
311
|
-
|
|
312
|
-
```tsx
|
|
313
|
-
function ItemCount({ count }) {
|
|
314
|
-
const { t } = useTranslation();
|
|
315
|
-
|
|
316
|
-
return (
|
|
317
|
-
<div>
|
|
318
|
-
{t('items.count', { count })}
|
|
319
|
-
</div>
|
|
320
|
-
);
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
// Translation file:
|
|
324
|
-
// {
|
|
325
|
-
// "items": {
|
|
326
|
-
// "count": {
|
|
327
|
-
// "zero": "No items",
|
|
328
|
-
// "one": "One item",
|
|
329
|
-
// "other": "{count} items"
|
|
330
|
-
// }
|
|
331
|
-
// }
|
|
332
|
-
// }
|
|
333
|
-
```
|
|
107
|
+
The provider reads the instance synchronously (`useSyncExternalStore` with the same server
|
|
108
|
+
and client snapshot), so the server markup matches the first client render as long as the
|
|
109
|
+
client instance is created with the same locale and messages as on the server.
|
|
334
110
|
|
|
335
111
|
## License
|
|
336
112
|
|
|
337
113
|
MIT © Ersin Koç
|
|
338
|
-
|
|
339
|
-
## Contributing
|
|
340
|
-
|
|
341
|
-
Contributions are welcome! Please read our [Contributing Guide](https://github.com/ersinkoc/i18n/blob/main/CONTRIBUTING.md) for details.
|
|
342
|
-
|
|
343
|
-
## Links
|
|
344
|
-
|
|
345
|
-
- [GitHub Repository](https://github.com/ersinkoc/i18n)
|
|
346
|
-
- [NPM Package](https://www.npmjs.com/package/@oxog/i18n-react)
|
|
347
|
-
- [Documentation](https://github.com/ersinkoc/i18n#readme)
|
package/dist/index.d.mts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import { Messages, I18nInstance, ExtractTranslationKeys, TranslationFunction, ExtractTranslationParams } from '@oxog/i18n';
|
|
3
|
-
import React from 'react';
|
|
3
|
+
import React, { JSX } from 'react';
|
|
4
4
|
|
|
5
|
-
interface I18nContextValue<TMessages extends
|
|
5
|
+
interface I18nContextValue<TMessages extends object = Messages> {
|
|
6
6
|
i18n: I18nInstance<TMessages>;
|
|
7
7
|
}
|
|
8
|
-
interface I18nProviderProps<TMessages extends
|
|
8
|
+
interface I18nProviderProps<TMessages extends object = Messages> {
|
|
9
9
|
i18n: I18nInstance<TMessages>;
|
|
10
10
|
children: React.ReactNode;
|
|
11
11
|
}
|
|
12
|
-
declare function I18nProvider<TMessages extends
|
|
13
|
-
declare function useI18nContext<TMessages extends
|
|
14
|
-
declare function useI18n<TMessages extends
|
|
12
|
+
declare function I18nProvider<TMessages extends object = Messages>({ i18n, children, }: I18nProviderProps<TMessages>): react_jsx_runtime.JSX.Element;
|
|
13
|
+
declare function useI18nContext<TMessages extends object = Messages>(): I18nContextValue<TMessages>;
|
|
14
|
+
declare function useI18n<TMessages extends object = Messages>(): I18nInstance<TMessages>;
|
|
15
15
|
|
|
16
|
-
interface UseTranslationResult<TMessages extends
|
|
16
|
+
interface UseTranslationResult<TMessages extends object = Messages> {
|
|
17
17
|
t: TranslationFunction<TMessages>;
|
|
18
18
|
locale: string;
|
|
19
19
|
setLocale: (locale: string) => void;
|
|
@@ -21,45 +21,47 @@ interface UseTranslationResult<TMessages extends Messages = Messages> {
|
|
|
21
21
|
formatDate: (value: Date, format?: string) => string;
|
|
22
22
|
formatRelativeTime: (value: Date, baseDate?: Date) => string;
|
|
23
23
|
}
|
|
24
|
-
declare function useTranslation<TMessages extends
|
|
24
|
+
declare function useTranslation<TMessages extends object = Messages>(namespace?: string): UseTranslationResult<TMessages>;
|
|
25
25
|
declare function useLocale(): [string, (locale: string) => void];
|
|
26
|
-
declare function useHasTranslation<TMessages extends
|
|
26
|
+
declare function useHasTranslation<TMessages extends object = Messages>(): (key: ExtractTranslationKeys<TMessages>, locale?: string) => boolean;
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
/** HTML attributes forwarded to the rendered element (`title`, `role`, `aria-*`, ...). */
|
|
29
|
+
type ForwardedAttributes = Omit<React.HTMLAttributes<HTMLElement>, 'id' | 'children' | 'className'>;
|
|
30
|
+
interface TProps<TMessages extends object = Messages, TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>> extends ForwardedAttributes {
|
|
29
31
|
id: TKey;
|
|
30
32
|
values?: ExtractTranslationParams<TMessages, TKey>;
|
|
31
33
|
as?: keyof JSX.IntrinsicElements;
|
|
32
34
|
className?: string;
|
|
33
35
|
}
|
|
34
|
-
declare function T<TMessages extends
|
|
35
|
-
interface TransProps<TMessages extends
|
|
36
|
+
declare function T<TMessages extends object = Messages, TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>>({ id, values, as: tag, className, ...props }: TProps<TMessages, TKey>): react_jsx_runtime.JSX.Element | null;
|
|
37
|
+
interface TransProps<TMessages extends object = Messages, TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>> extends ForwardedAttributes {
|
|
36
38
|
id: TKey;
|
|
37
39
|
values?: ExtractTranslationParams<TMessages, TKey>;
|
|
38
40
|
components?: Record<string, React.ReactElement>;
|
|
39
41
|
as?: keyof JSX.IntrinsicElements;
|
|
40
42
|
className?: string;
|
|
41
43
|
}
|
|
42
|
-
declare function Trans<TMessages extends
|
|
43
|
-
interface NumberFormatProps {
|
|
44
|
+
declare function Trans<TMessages extends object = Messages, TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>>({ id, values, components, as: tag, className, ...props }: TransProps<TMessages, TKey>): react_jsx_runtime.JSX.Element;
|
|
45
|
+
interface NumberFormatProps extends ForwardedAttributes {
|
|
44
46
|
value: number;
|
|
45
47
|
format?: string;
|
|
46
48
|
as?: keyof JSX.IntrinsicElements;
|
|
47
49
|
className?: string;
|
|
48
50
|
}
|
|
49
|
-
declare function NumberFormat({ value, format, as:
|
|
50
|
-
interface DateFormatProps {
|
|
51
|
-
value: Date |
|
|
51
|
+
declare function NumberFormat({ value, format, as: tag, className, ...props }: NumberFormatProps): react_jsx_runtime.JSX.Element;
|
|
52
|
+
interface DateFormatProps extends ForwardedAttributes {
|
|
53
|
+
value: Date | string | number;
|
|
52
54
|
format?: string;
|
|
53
55
|
as?: keyof JSX.IntrinsicElements;
|
|
54
56
|
className?: string;
|
|
55
57
|
}
|
|
56
|
-
declare function DateFormat({ value, format, as:
|
|
57
|
-
interface RelativeTimeProps {
|
|
58
|
-
value: Date |
|
|
59
|
-
baseDate?: Date |
|
|
58
|
+
declare function DateFormat({ value, format, as: tag, className, ...props }: DateFormatProps): react_jsx_runtime.JSX.Element;
|
|
59
|
+
interface RelativeTimeProps extends ForwardedAttributes {
|
|
60
|
+
value: Date | string | number;
|
|
61
|
+
baseDate?: Date | string | number;
|
|
60
62
|
as?: keyof JSX.IntrinsicElements;
|
|
61
63
|
className?: string;
|
|
62
64
|
}
|
|
63
|
-
declare function RelativeTime({ value, baseDate, as:
|
|
65
|
+
declare function RelativeTime({ value, baseDate, as: tag, className, ...props }: RelativeTimeProps): react_jsx_runtime.JSX.Element;
|
|
64
66
|
|
|
65
67
|
export { DateFormat, type DateFormatProps, type I18nContextValue, I18nProvider, type I18nProviderProps, NumberFormat, type NumberFormatProps, RelativeTime, type RelativeTimeProps, T, type TProps, Trans, type TransProps, type UseTranslationResult, useHasTranslation, useI18n, useI18nContext, useLocale, useTranslation };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import { Messages, I18nInstance, ExtractTranslationKeys, TranslationFunction, ExtractTranslationParams } from '@oxog/i18n';
|
|
3
|
-
import React from 'react';
|
|
3
|
+
import React, { JSX } from 'react';
|
|
4
4
|
|
|
5
|
-
interface I18nContextValue<TMessages extends
|
|
5
|
+
interface I18nContextValue<TMessages extends object = Messages> {
|
|
6
6
|
i18n: I18nInstance<TMessages>;
|
|
7
7
|
}
|
|
8
|
-
interface I18nProviderProps<TMessages extends
|
|
8
|
+
interface I18nProviderProps<TMessages extends object = Messages> {
|
|
9
9
|
i18n: I18nInstance<TMessages>;
|
|
10
10
|
children: React.ReactNode;
|
|
11
11
|
}
|
|
12
|
-
declare function I18nProvider<TMessages extends
|
|
13
|
-
declare function useI18nContext<TMessages extends
|
|
14
|
-
declare function useI18n<TMessages extends
|
|
12
|
+
declare function I18nProvider<TMessages extends object = Messages>({ i18n, children, }: I18nProviderProps<TMessages>): react_jsx_runtime.JSX.Element;
|
|
13
|
+
declare function useI18nContext<TMessages extends object = Messages>(): I18nContextValue<TMessages>;
|
|
14
|
+
declare function useI18n<TMessages extends object = Messages>(): I18nInstance<TMessages>;
|
|
15
15
|
|
|
16
|
-
interface UseTranslationResult<TMessages extends
|
|
16
|
+
interface UseTranslationResult<TMessages extends object = Messages> {
|
|
17
17
|
t: TranslationFunction<TMessages>;
|
|
18
18
|
locale: string;
|
|
19
19
|
setLocale: (locale: string) => void;
|
|
@@ -21,45 +21,47 @@ interface UseTranslationResult<TMessages extends Messages = Messages> {
|
|
|
21
21
|
formatDate: (value: Date, format?: string) => string;
|
|
22
22
|
formatRelativeTime: (value: Date, baseDate?: Date) => string;
|
|
23
23
|
}
|
|
24
|
-
declare function useTranslation<TMessages extends
|
|
24
|
+
declare function useTranslation<TMessages extends object = Messages>(namespace?: string): UseTranslationResult<TMessages>;
|
|
25
25
|
declare function useLocale(): [string, (locale: string) => void];
|
|
26
|
-
declare function useHasTranslation<TMessages extends
|
|
26
|
+
declare function useHasTranslation<TMessages extends object = Messages>(): (key: ExtractTranslationKeys<TMessages>, locale?: string) => boolean;
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
/** HTML attributes forwarded to the rendered element (`title`, `role`, `aria-*`, ...). */
|
|
29
|
+
type ForwardedAttributes = Omit<React.HTMLAttributes<HTMLElement>, 'id' | 'children' | 'className'>;
|
|
30
|
+
interface TProps<TMessages extends object = Messages, TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>> extends ForwardedAttributes {
|
|
29
31
|
id: TKey;
|
|
30
32
|
values?: ExtractTranslationParams<TMessages, TKey>;
|
|
31
33
|
as?: keyof JSX.IntrinsicElements;
|
|
32
34
|
className?: string;
|
|
33
35
|
}
|
|
34
|
-
declare function T<TMessages extends
|
|
35
|
-
interface TransProps<TMessages extends
|
|
36
|
+
declare function T<TMessages extends object = Messages, TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>>({ id, values, as: tag, className, ...props }: TProps<TMessages, TKey>): react_jsx_runtime.JSX.Element | null;
|
|
37
|
+
interface TransProps<TMessages extends object = Messages, TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>> extends ForwardedAttributes {
|
|
36
38
|
id: TKey;
|
|
37
39
|
values?: ExtractTranslationParams<TMessages, TKey>;
|
|
38
40
|
components?: Record<string, React.ReactElement>;
|
|
39
41
|
as?: keyof JSX.IntrinsicElements;
|
|
40
42
|
className?: string;
|
|
41
43
|
}
|
|
42
|
-
declare function Trans<TMessages extends
|
|
43
|
-
interface NumberFormatProps {
|
|
44
|
+
declare function Trans<TMessages extends object = Messages, TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>>({ id, values, components, as: tag, className, ...props }: TransProps<TMessages, TKey>): react_jsx_runtime.JSX.Element;
|
|
45
|
+
interface NumberFormatProps extends ForwardedAttributes {
|
|
44
46
|
value: number;
|
|
45
47
|
format?: string;
|
|
46
48
|
as?: keyof JSX.IntrinsicElements;
|
|
47
49
|
className?: string;
|
|
48
50
|
}
|
|
49
|
-
declare function NumberFormat({ value, format, as:
|
|
50
|
-
interface DateFormatProps {
|
|
51
|
-
value: Date |
|
|
51
|
+
declare function NumberFormat({ value, format, as: tag, className, ...props }: NumberFormatProps): react_jsx_runtime.JSX.Element;
|
|
52
|
+
interface DateFormatProps extends ForwardedAttributes {
|
|
53
|
+
value: Date | string | number;
|
|
52
54
|
format?: string;
|
|
53
55
|
as?: keyof JSX.IntrinsicElements;
|
|
54
56
|
className?: string;
|
|
55
57
|
}
|
|
56
|
-
declare function DateFormat({ value, format, as:
|
|
57
|
-
interface RelativeTimeProps {
|
|
58
|
-
value: Date |
|
|
59
|
-
baseDate?: Date |
|
|
58
|
+
declare function DateFormat({ value, format, as: tag, className, ...props }: DateFormatProps): react_jsx_runtime.JSX.Element;
|
|
59
|
+
interface RelativeTimeProps extends ForwardedAttributes {
|
|
60
|
+
value: Date | string | number;
|
|
61
|
+
baseDate?: Date | string | number;
|
|
60
62
|
as?: keyof JSX.IntrinsicElements;
|
|
61
63
|
className?: string;
|
|
62
64
|
}
|
|
63
|
-
declare function RelativeTime({ value, baseDate, as:
|
|
65
|
+
declare function RelativeTime({ value, baseDate, as: tag, className, ...props }: RelativeTimeProps): react_jsx_runtime.JSX.Element;
|
|
64
66
|
|
|
65
67
|
export { DateFormat, type DateFormatProps, type I18nContextValue, I18nProvider, type I18nProviderProps, NumberFormat, type NumberFormatProps, RelativeTime, type RelativeTimeProps, T, type TProps, Trans, type TransProps, type UseTranslationResult, useHasTranslation, useI18n, useI18nContext, useLocale, useTranslation };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
'use
|
|
1
|
+
'use client';
|
|
2
|
+
"use strict";var G=Object.create;var D=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty;var te=(e,t)=>{for(var n in t)D(e,n,{get:t[n],enumerable:!0})},S=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of W(t))!ee.call(e,r)&&r!==n&&D(e,r,{get:()=>t[r],enumerable:!(s=Q(t,r))||s.enumerable});return e};var j=(e,t,n)=>(n=e!=null?G(Y(e)):{},S(t||!e||!e.__esModule?D(n,"default",{value:e,enumerable:!0}):n,e)),ne=e=>S(D({},"__esModule",{value:!0}),e);var re={};te(re,{DateFormat:()=>_,I18nProvider:()=>V,NumberFormat:()=>$,RelativeTime:()=>U,T:()=>q,Trans:()=>J,useHasTranslation:()=>H,useI18n:()=>M,useI18nContext:()=>R,useLocale:()=>X,useTranslation:()=>T});module.exports=ne(re);var g=j(require("react"));function l(){try{return process.env.NODE_ENV!=="production"}catch{return!1}}var A=require("react/jsx-runtime"),L=(0,g.createContext)(null);function V({i18n:e,children:t}){if(!e)throw new Error("[i18n] I18nProvider requires a valid i18n instance");let n=(0,g.useMemo)(()=>({i18n:e}),[e]);return(0,A.jsx)(L.Provider,{value:n,children:t})}function R(){let e=(0,g.useContext)(L);if(!e||!e.i18n)throw new Error("[i18n] useI18nContext must be used within an I18nProvider with a valid i18n instance");return e}function C(){let{i18n:e}=R(),t=g.default.useCallback(r=>typeof e.subscribe!="function"?(l()&&console.error("[i18n] i18n instance missing subscribe method - reactivity will not work properly"),()=>{}):e.subscribe(r),[e]),n=()=>`${e.locale||"en"}\0${e.revision??0}`,s=(0,g.useSyncExternalStore)(t,n,n);return g.default.useDebugValue(e.locale),{i18n:e,snapshot:s}}function M(){return C().i18n}var p=require("react");function T(e){let{i18n:t,snapshot:n}=C(),s=(0,p.useCallback)((o,...u)=>{let P=e?`${e}.${String(o)}`:String(o);return t.t(P,...u)},[t,e,n]),r=(0,p.useCallback)(o=>{t.setLocale(o)},[t]),a=(0,p.useCallback)((o,u)=>t.formatNumber(o,u),[t]),m=(0,p.useCallback)((o,u)=>t.formatDate(o,u),[t]),i=(0,p.useCallback)((o,u)=>t.formatRelativeTime(o,u),[t]);return(0,p.useMemo)(()=>({t:s,locale:t.locale,setLocale:r,formatNumber:a,formatDate:m,formatRelativeTime:i}),[s,t.locale,r,a,m,i])}function X(){let e=M(),t=(0,p.useCallback)(n=>{e.setLocale(n)},[e]);return[e.locale,t]}function H(){let e=M();return(0,p.useCallback)((t,n)=>e.hasTranslation(t,n),[e])}var h=j(require("react"));var c=require("react/jsx-runtime");function q({id:e,values:t,as:n="span",className:s,...r}){let a=n,{t:m}=T();if(!e)return l()&&console.error("[i18n] T component requires an id prop"),null;try{let i=m,o=t?i(e,t):i(e);return(0,c.jsx)(a,{...r,className:s,children:o})}catch(i){return l()&&console.error("[i18n] T component translation error:",i),(0,c.jsx)(a,{...r,className:s,children:String(e)})}}function J({id:e,values:t,components:n={},as:s="span",className:r,...a}){let m=s,{t:i}=T(),o=t?se(t):void 0,u=i,P=o?u(e,o):u(e);function w(f,k=0){if(k>10)return l()&&console.error("[i18n] Max nesting depth exceeded in Trans component"),[f];let d=[],x=0,Z=/<([A-Za-z0-9_]+)>([\s\S]*?)<\/\1>/g,I;for(;(I=Z.exec(f))!==null;){let[F,E,B]=I,b=I.index;b>x&&d.push(N(f.slice(x,b)));let K=Object.prototype.hasOwnProperty.call(n,E)?n[E]:void 0;if(h.default.isValidElement(K)){let y=w(B,k+1);d.push(h.default.cloneElement(K,{key:`component-${E}-${b}`},y.length===1&&typeof y[0]=="string"?y[0]:y))}else d.push(N(F));x=b+F.length}return x<f.length&&d.push(N(f.slice(x))),d}let z=w(P);return(0,c.jsx)(m,{...a,className:r,children:z})}var O="\uE000";function se(e){let t={};for(let n of Object.keys(e)){let s=e[n];t[n]=typeof s=="string"?s.split("<").join(O):s}return t}function N(e){return e.split(O).join("<")}function $({value:e,format:t,as:n="span",className:s,...r}){let a=n,{formatNumber:m}=T();if(typeof e!="number"||isNaN(e))return l()&&console.error("[i18n] NumberFormat component requires a valid number"),(0,c.jsx)(a,{...r,className:s,children:String(e)});try{return(0,c.jsx)(a,{...r,className:s,children:m(e,t)})}catch(i){return l()&&console.error("[i18n] NumberFormat component error:",i),(0,c.jsx)(a,{...r,className:s,children:String(e)})}}function v(e){if(e instanceof Date)return isNaN(e.getTime())?null:e;if(typeof e=="number"){let t=new Date(e);return isNaN(t.getTime())?null:t}if(typeof e=="string"){let t=new Date(e);return isNaN(t.getTime())?null:t}return null}function _({value:e,format:t,as:n="span",className:s,...r}){let a=n,{formatDate:m}=T(),i=v(e);if(!i)return l()&&console.error("[i18n] DateFormat component requires a valid Date, timestamp, or date string"),(0,c.jsx)(a,{...r,className:s,children:String(e)});try{return(0,c.jsx)(a,{...r,className:s,children:m(i,t)})}catch(o){return l()&&console.error("[i18n] DateFormat component error:",o),(0,c.jsx)(a,{...r,className:s,children:i.toLocaleDateString()})}}function U({value:e,baseDate:t,as:n="span",className:s,...r}){let a=n,{formatRelativeTime:m}=T(),i=v(e);if(!i)return l()&&console.error("[i18n] RelativeTime component requires a valid Date, timestamp, or date string for value"),(0,c.jsx)(a,{...r,className:s,children:String(e)});let o;if(t!==void 0&&(o=v(t)??void 0,!o))return l()&&console.error("[i18n] RelativeTime component requires a valid Date, timestamp, or date string for baseDate"),(0,c.jsx)(a,{...r,className:s,children:String(e)});try{return(0,c.jsx)(a,{...r,className:s,children:m(i,o)})}catch(u){return l()&&console.error("[i18n] RelativeTime component error:",u),(0,c.jsx)(a,{...r,className:s,children:i.toLocaleDateString()})}}0&&(module.exports={DateFormat,I18nProvider,NumberFormat,RelativeTime,T,Trans,useHasTranslation,useI18n,useI18nContext,useLocale,useTranslation});
|
|
2
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context.tsx","../src/hooks.ts","../src/components.tsx"],"names":["I18nContext","createContext","I18nProvider","i18n","children","value","jsx","useI18nContext","context","useContext","useI18n","locale","useSyncExternalStore","React","callback","useTranslation","namespace","useCallback","key","args","fullKey","useMemo","useLocale","useHasTranslation","T","id","values","Component","className","props","t","translatedText","error","Trans","components","translation","parseTranslation","text","result","lastIndex","regex","match","fullMatch","componentIndex","innerContent","startIndex","elements","NumberFormat","format","formatNumber","DateFormat","formatDate","RelativeTime","baseDate","formatRelativeTime"],"mappings":"4LAOO,IAAMA,CAAAA,CAAcC,gBAA4C,IAAI,CAAA,CAOpE,SAASC,CAAAA,CAAoD,CAClE,IAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CACF,EAAiC,CAC/B,GAAI,CAACD,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,oD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,OAAA,CAAQ,KAAA,CAAM,sCAAA,CAAwCA,CAAK,CAAA,CAG3D1B,eAACqB,CAAAA,CAAA,CAAU,UAAWC,CAAAA,CAAY,GAAGC,EAClC,QAAA,CAAA,MAAA,CAAOxB,CAAK,CAAA,CACf,CAEJ,CACF","file":"index.js","sourcesContent":["import type { I18nInstance, Messages } from '@oxog/i18n';\nimport React, { createContext, useContext, useSyncExternalStore } from 'react';\n\nexport interface I18nContextValue<TMessages extends Messages = Messages> {\n i18n: I18nInstance<TMessages>;\n}\n\nexport const I18nContext = createContext<I18nContextValue<any> | null>(null);\n\nexport interface I18nProviderProps<TMessages extends Messages = Messages> {\n i18n: I18nInstance<TMessages>;\n children: React.ReactNode;\n}\n\nexport function I18nProvider<TMessages extends Messages = Messages>({\n i18n,\n children,\n}: I18nProviderProps<TMessages>) {\n if (!i18n) {\n throw new Error('[i18n] I18nProvider requires a valid i18n instance');\n }\n \n const value: I18nContextValue<any> = { i18n };\n \n return (\n <I18nContext.Provider value={value}>\n {children}\n </I18nContext.Provider>\n );\n}\n\nexport function useI18nContext<TMessages extends Messages = Messages>(): I18nContextValue<TMessages> {\n const context = useContext(I18nContext);\n if (!context || !context.i18n) {\n throw new Error('[i18n] useI18nContext must be used within an I18nProvider with a valid i18n instance');\n }\n return context as I18nContextValue<TMessages>;\n}\n\nexport function useI18n<TMessages extends Messages = Messages>(): I18nInstance<TMessages> {\n const { i18n } = useI18nContext<TMessages>();\n \n if (!i18n) {\n throw new Error('[i18n] useI18n requires a valid i18n instance');\n }\n \n // Use useSyncExternalStore for optimal performance and concurrent features\n const locale = useSyncExternalStore(\n React.useCallback((callback) => {\n if (typeof i18n.subscribe === 'function') {\n return i18n.subscribe(callback);\n }\n // Fallback for instances without subscribe\n return () => {};\n }, [i18n]),\n () => i18n.locale || 'en',\n () => i18n.locale || 'en'\n );\n \n // Force re-render when locale changes\n React.useDebugValue(locale);\n \n return i18n;\n}","import type { ExtractTranslationKeys, Messages, TranslationFunction } from '@oxog/i18n';\nimport { useCallback, useMemo } from 'react';\nimport { useI18n } from './context';\n\nexport interface UseTranslationResult<TMessages extends Messages = Messages> {\n t: TranslationFunction<TMessages>;\n locale: string;\n setLocale: (locale: string) => void;\n formatNumber: (value: number, format?: string) => string;\n formatDate: (value: Date, format?: string) => string;\n formatRelativeTime: (value: Date, baseDate?: Date) => string;\n}\n\nexport function useTranslation<TMessages extends Messages = Messages>(\n namespace?: string\n): UseTranslationResult<TMessages> {\n const i18n = useI18n<TMessages>();\n \n const t = useCallback<TranslationFunction<TMessages>>(\n (key, ...args) => {\n const fullKey = namespace ? `${namespace}.${String(key)}` : String(key);\n return i18n.t(fullKey as any, ...args);\n },\n [i18n, namespace]\n );\n \n return useMemo(\n () => ({\n t,\n locale: i18n.locale,\n setLocale: i18n.setLocale.bind(i18n),\n formatNumber: i18n.formatNumber.bind(i18n),\n formatDate: i18n.formatDate.bind(i18n),\n formatRelativeTime: i18n.formatRelativeTime.bind(i18n),\n }),\n [i18n, t, i18n.locale]\n );\n}\n\nexport function useLocale(): [string, (locale: string) => void] {\n const i18n = useI18n();\n return [i18n.locale, i18n.setLocale.bind(i18n)];\n}\n\nexport function useHasTranslation<TMessages extends Messages = Messages>() {\n const i18n = useI18n<TMessages>();\n \n return useCallback(\n (key: ExtractTranslationKeys<TMessages>, locale?: string) => {\n return i18n.hasTranslation(key, locale);\n },\n [i18n]\n );\n}","import type { ExtractTranslationKeys, ExtractTranslationParams, Messages } from '@oxog/i18n';\nimport React from 'react';\nimport { useTranslation } from './hooks';\n\nexport interface TProps<\n TMessages extends Messages = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n> {\n id: TKey;\n values?: ExtractTranslationParams<TMessages, TKey>;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function T<\n TMessages extends Messages = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n>({ id, values, as: Component = 'span', className, ...props }: TProps<TMessages, TKey>) {\n const { t } = useTranslation<TMessages>();\n \n if (!id) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] T component requires an id prop');\n }\n return null;\n }\n \n try {\n const translatedText = values ? (t as any)(id, values) : (t as any)(id);\n \n return (\n <Component className={className} {...props}>\n {translatedText}\n </Component>\n );\n } catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] T component translation error:', error);\n }\n return (\n <Component className={className} {...props}>\n {String(id)}\n </Component>\n );\n }\n}\n\nexport interface TransProps<\n TMessages extends Messages = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n> {\n id: TKey;\n values?: ExtractTranslationParams<TMessages, TKey>;\n components?: Record<string, React.ReactElement>;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function Trans<\n TMessages extends Messages = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n>({ id, values, components = {}, as: Component = 'span', className, ...props }: TransProps<TMessages, TKey>) {\n const { t } = useTranslation<TMessages>();\n \n const translation = values ? (t as any)(id, values) : (t as any)(id);\n \n // Parse the translation and replace component placeholders\n function parseTranslation(text: string): React.ReactNode[] {\n const result: React.ReactNode[] = [];\n let lastIndex = 0;\n \n // Find all component tags\n const regex = /<(\\d+)>(.*?)<\\/\\1>/g;\n let match;\n \n while ((match = regex.exec(text)) !== null) {\n const [fullMatch, componentIndex, innerContent] = match;\n const startIndex = match.index;\n \n // Add text before the component\n if (startIndex > lastIndex) {\n result.push(text.slice(lastIndex, startIndex));\n }\n \n // Process the component\n const Component = components[componentIndex];\n if (Component) {\n // Recursively parse inner content for nested components\n const children = parseTranslation(innerContent);\n result.push(\n React.cloneElement(\n Component,\n { key: `component-${componentIndex}-${startIndex}` },\n children.length === 1 && typeof children[0] === 'string' ? children[0] : children\n )\n );\n } else {\n // If component not found, keep the original text\n result.push(fullMatch);\n }\n \n lastIndex = startIndex + fullMatch.length;\n }\n \n // Add any remaining text\n if (lastIndex < text.length) {\n result.push(text.slice(lastIndex));\n }\n \n return result;\n }\n \n const elements = parseTranslation(translation);\n \n return (\n <Component className={className} {...props}>\n {elements}\n </Component>\n );\n}\n\nexport interface NumberFormatProps {\n value: number;\n format?: string;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function NumberFormat({ value, format, as: Component = 'span', className, ...props }: NumberFormatProps) {\n const { formatNumber } = useTranslation();\n \n if (typeof value !== 'number' || isNaN(value)) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] NumberFormat component requires a valid number');\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n \n try {\n return (\n <Component className={className} {...props}>\n {formatNumber(value, format)}\n </Component>\n );\n } catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] NumberFormat component error:', error);\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n}\n\nexport interface DateFormatProps {\n value: Date | any;\n format?: string;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function DateFormat({ value, format, as: Component = 'span', className, ...props }: DateFormatProps) {\n const { formatDate } = useTranslation();\n \n if (!(value instanceof Date) || isNaN((value as Date).getTime())) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] DateFormat component requires a valid Date object');\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n \n try {\n return (\n <Component className={className} {...props}>\n {formatDate(value, format)}\n </Component>\n );\n } catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] DateFormat component error:', error);\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n}\n\nexport interface RelativeTimeProps {\n value: Date | any;\n baseDate?: Date | any;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function RelativeTime({ value, baseDate, as: Component = 'span', className, ...props }: RelativeTimeProps) {\n const { formatRelativeTime } = useTranslation();\n \n if (!(value instanceof Date) || isNaN((value as Date).getTime())) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] RelativeTime component requires a valid Date object for value');\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n \n if (baseDate !== undefined && (!(baseDate instanceof Date) || isNaN((baseDate as Date).getTime()))) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] RelativeTime component requires a valid Date object for baseDate');\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n \n try {\n return (\n <Component className={className} {...props}>\n {formatRelativeTime(value, baseDate)}\n </Component>\n );\n } catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] RelativeTime component error:', error);\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n}"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/context.tsx","../src/env.ts","../src/hooks.ts","../src/components.tsx"],"sourcesContent":["export { I18nProvider, useI18n, useI18nContext } from './context';\nexport type { I18nContextValue, I18nProviderProps } from './context';\n\nexport { useHasTranslation, useLocale, useTranslation } from './hooks';\nexport type { UseTranslationResult } from './hooks';\n\nexport { DateFormat, NumberFormat, RelativeTime, T, Trans } from './components';\nexport type { DateFormatProps, NumberFormatProps, RelativeTimeProps, TProps, TransProps } from './components';","import type { I18nInstance, Messages } from '@oxog/i18n';\nimport React, { createContext, useContext, useMemo, useSyncExternalStore } from 'react';\nimport { isDevelopment } from './env';\n\nexport interface I18nContextValue<TMessages extends object = Messages> {\n i18n: I18nInstance<TMessages>;\n}\n\n// The context is shared by every catalog type; hooks narrow it with their type parameter.\nexport const I18nContext = createContext<I18nContextValue<object> | null>(null);\n\nexport interface I18nProviderProps<TMessages extends object = Messages> {\n i18n: I18nInstance<TMessages>;\n children: React.ReactNode;\n}\n\nexport function I18nProvider<TMessages extends object = Messages>({\n i18n,\n children,\n}: I18nProviderProps<TMessages>) {\n if (!i18n) {\n throw new Error('[i18n] I18nProvider requires a valid i18n instance');\n }\n\n const value = useMemo(() => ({ i18n }) as unknown as I18nContextValue<object>, [i18n]);\n\n return (\n <I18nContext.Provider value={value}>\n {children}\n </I18nContext.Provider>\n );\n}\n\nexport function useI18nContext<TMessages extends object = Messages>(): I18nContextValue<TMessages> {\n const context = useContext(I18nContext);\n if (!context || !context.i18n) {\n throw new Error('[i18n] useI18nContext must be used within an I18nProvider with a valid i18n instance');\n }\n return context as unknown as I18nContextValue<TMessages>;\n}\n\n/**\n * Subscribes to the instance and returns a snapshot that changes whenever the visible\n * translations change: on locale switches and, for instances that expose `revision`\n * (all `createI18n` instances), when messages are added for the active locale.\n * @internal\n */\nexport function useI18nSnapshot<TMessages extends object = Messages>(): {\n i18n: I18nInstance<TMessages>;\n snapshot: string;\n} {\n const { i18n } = useI18nContext<TMessages>();\n\n const subscribe = React.useCallback(\n (callback: () => void) => {\n if (typeof i18n.subscribe !== 'function') {\n if (isDevelopment()) {\n console.error('[i18n] i18n instance missing subscribe method - reactivity will not work properly');\n }\n return () => {};\n }\n return i18n.subscribe(callback);\n },\n [i18n]\n );\n const getSnapshot = () => `${i18n.locale || 'en'}\\u0000${i18n.revision ?? 0}`;\n\n // useSyncExternalStore keeps concurrent rendering, StrictMode and SSR hydration\n // consistent: the server snapshot is the instance's current state.\n const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n React.useDebugValue(i18n.locale);\n\n return { i18n, snapshot };\n}\n\nexport function useI18n<TMessages extends object = Messages>(): I18nInstance<TMessages> {\n return useI18nSnapshot<TMessages>().i18n;\n}\n","/**\n * True when NODE_ENV is not \"production\". Bundlers replace `process.env.NODE_ENV`\n * statically; where no `process` global exists (ESM loaded directly in a browser)\n * this returns false instead of throwing a ReferenceError.\n * @internal\n */\nexport function isDevelopment(): boolean {\n try {\n return process.env.NODE_ENV !== 'production';\n } catch {\n return false;\n }\n}\n","import type { ExtractTranslationKeys, Messages, TranslationFunction, TranslationParams } from '@oxog/i18n';\nimport { useCallback, useMemo } from 'react';\nimport { useI18n, useI18nSnapshot } from './context';\n\nexport interface UseTranslationResult<TMessages extends object = Messages> {\n t: TranslationFunction<TMessages>;\n locale: string;\n setLocale: (locale: string) => void;\n formatNumber: (value: number, format?: string) => string;\n formatDate: (value: Date, format?: string) => string;\n formatRelativeTime: (value: Date, baseDate?: Date) => string;\n}\n\nexport function useTranslation<TMessages extends object = Messages>(\n namespace?: string\n): UseTranslationResult<TMessages> {\n const { i18n, snapshot } = useI18nSnapshot<TMessages>();\n\n // `snapshot` changes with the locale and with lazily added messages, so `t` gets a new\n // identity and memoized children/effects that depend on it re-render with new text.\n const t = useCallback(\n (key: string, ...args: [params?: TranslationParams]) => {\n const fullKey = namespace ? `${namespace}.${String(key)}` : String(key);\n return (i18n.t as (key: string, ...args: [params?: TranslationParams]) => string)(fullKey, ...args);\n },\n [i18n, namespace, snapshot]\n ) as unknown as TranslationFunction<TMessages>;\n\n const setLocale = useCallback((locale: string) => {\n i18n.setLocale(locale);\n }, [i18n]);\n\n const formatNumber = useCallback((value: number, format?: string) => {\n return i18n.formatNumber(value, format);\n }, [i18n]);\n\n const formatDate = useCallback((value: Date, format?: string) => {\n return i18n.formatDate(value, format);\n }, [i18n]);\n\n const formatRelativeTime = useCallback((value: Date, baseDate?: Date) => {\n return i18n.formatRelativeTime(value, baseDate);\n }, [i18n]);\n\n return useMemo<UseTranslationResult<TMessages>>(\n () => ({\n t,\n locale: i18n.locale,\n setLocale,\n formatNumber,\n formatDate,\n formatRelativeTime,\n }),\n // `t as unknown` avoids an expensive structural comparison of the generic `t` type.\n [t as unknown, i18n.locale, setLocale, formatNumber, formatDate, formatRelativeTime]\n );\n}\n\nexport function useLocale(): [string, (locale: string) => void] {\n const i18n = useI18n();\n const setLocale = useCallback((locale: string) => {\n i18n.setLocale(locale);\n }, [i18n]);\n return [i18n.locale, setLocale];\n}\n\nexport function useHasTranslation<TMessages extends object = Messages>() {\n const i18n = useI18n<TMessages>();\n \n return useCallback(\n (key: ExtractTranslationKeys<TMessages>, locale?: string) => {\n return i18n.hasTranslation(key, locale);\n },\n [i18n]\n );\n}","import type { ExtractTranslationKeys, ExtractTranslationParams, Messages, TranslationParams } from '@oxog/i18n';\nimport React from 'react';\nimport type { JSX } from 'react';\nimport { isDevelopment } from './env';\nimport { useTranslation } from './hooks';\n\n/** HTML attributes forwarded to the rendered element (`title`, `role`, `aria-*`, ...). */\ntype ForwardedAttributes = Omit<React.HTMLAttributes<HTMLElement>, 'id' | 'children' | 'className'>;\n\nexport interface TProps<\n TMessages extends object = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n> extends ForwardedAttributes {\n id: TKey;\n values?: ExtractTranslationParams<TMessages, TKey>;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function T<\n TMessages extends object = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n>({ id, values, as: tag = 'span', className, ...props }: TProps<TMessages, TKey>) {\n const Component = tag as React.ElementType;\n const { t } = useTranslation<TMessages>();\n \n if (!id) {\n if (isDevelopment()) {\n console.error('[i18n] T component requires an id prop');\n }\n return null;\n }\n \n try {\n const translate = t as unknown as (key: string, params?: TranslationParams) => string;\n const translatedText = values ? translate(id, values as TranslationParams) : translate(id);\n \n return (\n <Component {...props} className={className}>\n {translatedText}\n </Component>\n );\n } catch (error) {\n if (isDevelopment()) {\n console.error('[i18n] T component translation error:', error);\n }\n return (\n <Component {...props} className={className}>\n {String(id)}\n </Component>\n );\n }\n}\n\nexport interface TransProps<\n TMessages extends object = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n> extends ForwardedAttributes {\n id: TKey;\n values?: ExtractTranslationParams<TMessages, TKey>;\n components?: Record<string, React.ReactElement>;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function Trans<\n TMessages extends object = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n>({ id, values, components = {}, as: tag = 'span', className, ...props }: TransProps<TMessages, TKey>) {\n const Component = tag as React.ElementType;\n const { t } = useTranslation<TMessages>();\n \n // Interpolated values must stay plain text: a value such as \"<0>admin</0>\" must not be\n // turned into one of the developer-supplied components. Hide \"<\" in string values\n // behind a private-use character while parsing and restore it in text nodes.\n const protectedValues = values ? protectValues(values as Record<string, unknown>) : undefined;\n const translate = t as unknown as (key: string, params?: TranslationParams) => string;\n const translation = protectedValues ? translate(id, protectedValues as TranslationParams) : translate(id);\n\n // Parse the translation and replace component placeholders\n function parseTranslation(text: string, depth: number = 0): React.ReactNode[] {\n const MAX_DEPTH = 10; // Prevent stack overflow from malicious or malformed translations\n\n if (depth > MAX_DEPTH) {\n if (isDevelopment()) {\n console.error('[i18n] Max nesting depth exceeded in Trans component');\n }\n return [text];\n }\n\n const result: React.ReactNode[] = [];\n let lastIndex = 0;\n\n // Find all component tags\n const regex = /<([A-Za-z0-9_]+)>([\\s\\S]*?)<\\/\\1>/g;\n let match;\n\n while ((match = regex.exec(text)) !== null) {\n const [fullMatch, componentIndex, innerContent] = match;\n const startIndex = match.index;\n\n // Add text before the component\n if (startIndex > lastIndex) {\n result.push(restoreText(text.slice(lastIndex, startIndex)));\n }\n\n // Process the component (renamed to avoid shadowing)\n const ChildComponent = Object.prototype.hasOwnProperty.call(components, componentIndex)\n ? components[componentIndex]\n : undefined;\n if (React.isValidElement(ChildComponent)) {\n // Recursively parse inner content for nested components with depth tracking\n const children = parseTranslation(innerContent, depth + 1);\n result.push(\n React.cloneElement(\n ChildComponent,\n { key: `component-${componentIndex}-${startIndex}` },\n children.length === 1 && typeof children[0] === 'string' ? children[0] : children\n )\n );\n } else {\n // If component not found, keep the original text\n result.push(restoreText(fullMatch));\n }\n\n lastIndex = startIndex + fullMatch.length;\n }\n\n // Add any remaining text\n if (lastIndex < text.length) {\n result.push(restoreText(text.slice(lastIndex)));\n }\n\n return result;\n }\n \n const elements = parseTranslation(translation);\n \n return (\n <Component {...props} className={className}>\n {elements}\n </Component>\n );\n}\n\nconst LT_PLACEHOLDER = '\\uE000';\n\nfunction protectValues(values: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(values)) {\n const value = values[key];\n result[key] = typeof value === 'string' ? value.split('<').join(LT_PLACEHOLDER) : value;\n }\n return result;\n}\n\nfunction restoreText(text: string): string {\n return text.split(LT_PLACEHOLDER).join('<');\n}\n\nexport interface NumberFormatProps extends ForwardedAttributes {\n value: number;\n format?: string;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function NumberFormat({ value, format, as: tag = 'span', className, ...props }: NumberFormatProps) {\n const Component = tag as React.ElementType;\n const { formatNumber } = useTranslation();\n \n if (typeof value !== 'number' || isNaN(value)) {\n if (isDevelopment()) {\n console.error('[i18n] NumberFormat component requires a valid number');\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n\n try {\n return (\n <Component {...props} className={className}>\n {formatNumber(value, format)}\n </Component>\n );\n } catch (error) {\n if (isDevelopment()) {\n console.error('[i18n] NumberFormat component error:', error);\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n}\n\nexport interface DateFormatProps extends ForwardedAttributes {\n value: Date | string | number;\n format?: string;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\n// BUG-031 FIX: Helper function to convert string|number to Date\nfunction toDate(value: Date | string | number): Date | null {\n if (value instanceof Date) {\n return isNaN(value.getTime()) ? null : value;\n }\n if (typeof value === 'number') {\n const date = new Date(value);\n return isNaN(date.getTime()) ? null : date;\n }\n if (typeof value === 'string') {\n const date = new Date(value);\n return isNaN(date.getTime()) ? null : date;\n }\n return null;\n}\n\nexport function DateFormat({ value, format, as: tag = 'span', className, ...props }: DateFormatProps) {\n const Component = tag as React.ElementType;\n const { formatDate } = useTranslation();\n\n // BUG-031 FIX: Convert string|number to Date before validation\n const dateValue = toDate(value);\n\n if (!dateValue) {\n if (isDevelopment()) {\n console.error('[i18n] DateFormat component requires a valid Date, timestamp, or date string');\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n\n try {\n return (\n <Component {...props} className={className}>\n {formatDate(dateValue, format)}\n </Component>\n );\n } catch (error) {\n if (isDevelopment()) {\n console.error('[i18n] DateFormat component error:', error);\n }\n return (\n <Component {...props} className={className}>\n {dateValue.toLocaleDateString()}\n </Component>\n );\n }\n}\n\nexport interface RelativeTimeProps extends ForwardedAttributes {\n value: Date | string | number;\n baseDate?: Date | string | number;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function RelativeTime({ value, baseDate, as: tag = 'span', className, ...props }: RelativeTimeProps) {\n const Component = tag as React.ElementType;\n const { formatRelativeTime } = useTranslation();\n\n // BUG-032 FIX: Convert string|number to Date before validation\n const dateValue = toDate(value);\n\n if (!dateValue) {\n if (isDevelopment()) {\n console.error('[i18n] RelativeTime component requires a valid Date, timestamp, or date string for value');\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n\n // BUG-032 FIX: Also convert baseDate if provided\n let baseDateValue: Date | undefined;\n if (baseDate !== undefined) {\n baseDateValue = toDate(baseDate) ?? undefined;\n if (!baseDateValue) {\n if (isDevelopment()) {\n console.error('[i18n] RelativeTime component requires a valid Date, timestamp, or date string for baseDate');\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n }\n\n try {\n return (\n <Component {...props} className={className}>\n {formatRelativeTime(dateValue, baseDateValue)}\n </Component>\n );\n } catch (error) {\n if (isDevelopment()) {\n console.error('[i18n] RelativeTime component error:', error);\n }\n return (\n <Component {...props} className={className}>\n {dateValue.toLocaleDateString()}\n </Component>\n );\n }\n}\n"],"mappings":";8jBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,gBAAAE,EAAA,iBAAAC,EAAA,iBAAAC,EAAA,iBAAAC,EAAA,MAAAC,EAAA,UAAAC,EAAA,sBAAAC,EAAA,YAAAC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GAAGD,EAAO,UAAWD,EAC9B,SAAAwC,EAAU,mBAAmB,EAChC,CAEJ,CACF,CASO,SAASC,EAAa,CAAE,MAAAT,EAAO,SAAAU,EAAU,GAAI3C,EAAM,OAAQ,UAAAC,EAAW,GAAGC,CAAM,EAAsB,CAC1G,IAAMC,EAAYH,EACZ,CAAE,mBAAA4C,CAAmB,EAAIvC,EAAe,EAGxCoC,EAAYJ,EAAOJ,CAAK,EAE9B,GAAI,CAACQ,EACH,OAAInC,EAAc,GAChB,QAAQ,MAAM,0FAA0F,KAGxG,OAACH,EAAA,CAAW,GAAGD,EAAO,UAAWD,EAC9B,gBAAOgC,CAAK,EACf,EAKJ,IAAIY,EACJ,GAAIF,IAAa,SACfE,EAAgBR,EAAOM,CAAQ,GAAK,OAChC,CAACE,GACH,OAAIvC,EAAc,GAChB,QAAQ,MAAM,6FAA6F,KAG3G,OAACH,EAAA,CAAW,GAAGD,EAAO,UAAWD,EAC9B,gBAAOgC,CAAK,EACf,EAKN,GAAI,CACF,SACE,OAAC9B,EAAA,CAAW,GAAGD,EAAO,UAAWD,EAC9B,SAAA2C,EAAmBH,EAAWI,CAAa,EAC9C,CAEJ,OAASpC,EAAO,CACd,OAAIH,EAAc,GAChB,QAAQ,MAAM,uCAAwCG,CAAK,KAG3D,OAACN,EAAA,CAAW,GAAGD,EAAO,UAAWD,EAC9B,SAAAwC,EAAU,mBAAmB,EAChC,CAEJ,CACF","names":["index_exports","__export","DateFormat","I18nProvider","NumberFormat","RelativeTime","T","Trans","useHasTranslation","useI18n","useI18nContext","useLocale","useTranslation","__toCommonJS","import_react","isDevelopment","import_jsx_runtime","I18nContext","I18nProvider","i18n","children","value","useI18nContext","context","useI18nSnapshot","subscribe","React","callback","isDevelopment","getSnapshot","snapshot","useI18n","import_react","useTranslation","namespace","i18n","snapshot","useI18nSnapshot","t","key","args","fullKey","setLocale","locale","formatNumber","value","format","formatDate","formatRelativeTime","baseDate","useLocale","useI18n","useHasTranslation","import_react","import_jsx_runtime","T","id","values","tag","className","props","Component","t","useTranslation","isDevelopment","translate","translatedText","error","Trans","components","protectedValues","protectValues","translation","parseTranslation","text","depth","result","lastIndex","regex","match","fullMatch","componentIndex","innerContent","startIndex","restoreText","ChildComponent","React","children","elements","LT_PLACEHOLDER","key","value","NumberFormat","format","formatNumber","toDate","date","DateFormat","formatDate","dateValue","RelativeTime","baseDate","formatRelativeTime","baseDateValue"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
'use client';
|
|
2
|
+
import w,{createContext as A,useContext as X,useMemo as H,useSyncExternalStore as q}from"react";function c(){try{return process.env.NODE_ENV!=="production"}catch{return!1}}import{jsx as O}from"react/jsx-runtime";var k=A(null);function J({i18n:e,children:t}){if(!e)throw new Error("[i18n] I18nProvider requires a valid i18n instance");let s=H(()=>({i18n:e}),[e]);return O(k.Provider,{value:s,children:t})}function F(){let e=X(k);if(!e||!e.i18n)throw new Error("[i18n] useI18nContext must be used within an I18nProvider with a valid i18n instance");return e}function I(){let{i18n:e}=F(),t=w.useCallback(r=>typeof e.subscribe!="function"?(c()&&console.error("[i18n] i18n instance missing subscribe method - reactivity will not work properly"),()=>{}):e.subscribe(r),[e]),s=()=>`${e.locale||"en"}\0${e.revision??0}`,n=q(t,s,s);return w.useDebugValue(e.locale),{i18n:e,snapshot:n}}function b(){return I().i18n}import{useCallback as g,useMemo as $}from"react";function p(e){let{i18n:t,snapshot:s}=I(),n=g((o,...u)=>{let y=e?`${e}.${String(o)}`:String(o);return t.t(y,...u)},[t,e,s]),r=g(o=>{t.setLocale(o)},[t]),a=g((o,u)=>t.formatNumber(o,u),[t]),m=g((o,u)=>t.formatDate(o,u),[t]),i=g((o,u)=>t.formatRelativeTime(o,u),[t]);return $(()=>({t:n,locale:t.locale,setLocale:r,formatNumber:a,formatDate:m,formatRelativeTime:i}),[n,t.locale,r,a,m,i])}function _(){let e=b(),t=g(s=>{e.setLocale(s)},[e]);return[e.locale,t]}function U(){let e=b();return g((t,s)=>e.hasTranslation(t,s),[e])}import K from"react";import{jsx as l}from"react/jsx-runtime";function z({id:e,values:t,as:s="span",className:n,...r}){let a=s,{t:m}=p();if(!e)return c()&&console.error("[i18n] T component requires an id prop"),null;try{let i=m,o=t?i(e,t):i(e);return l(a,{...r,className:n,children:o})}catch(i){return c()&&console.error("[i18n] T component translation error:",i),l(a,{...r,className:n,children:String(e)})}}function Z({id:e,values:t,components:s={},as:n="span",className:r,...a}){let m=n,{t:i}=p(),o=t?B(t):void 0,u=i,y=o?u(e,o):u(e);function C(T,N=0){if(N>10)return c()&&console.error("[i18n] Max nesting depth exceeded in Trans component"),[T];let f=[],d=0,L=/<([A-Za-z0-9_]+)>([\s\S]*?)<\/\1>/g,D;for(;(D=L.exec(T))!==null;){let[h,P,V]=D,x=D.index;x>d&&f.push(E(T.slice(d,x)));let v=Object.prototype.hasOwnProperty.call(s,P)?s[P]:void 0;if(K.isValidElement(v)){let M=C(V,N+1);f.push(K.cloneElement(v,{key:`component-${P}-${x}`},M.length===1&&typeof M[0]=="string"?M[0]:M))}else f.push(E(h));d=x+h.length}return d<T.length&&f.push(E(T.slice(d))),f}let j=C(y);return l(m,{...a,className:r,children:j})}var S="\uE000";function B(e){let t={};for(let s of Object.keys(e)){let n=e[s];t[s]=typeof n=="string"?n.split("<").join(S):n}return t}function E(e){return e.split(S).join("<")}function G({value:e,format:t,as:s="span",className:n,...r}){let a=s,{formatNumber:m}=p();if(typeof e!="number"||isNaN(e))return c()&&console.error("[i18n] NumberFormat component requires a valid number"),l(a,{...r,className:n,children:String(e)});try{return l(a,{...r,className:n,children:m(e,t)})}catch(i){return c()&&console.error("[i18n] NumberFormat component error:",i),l(a,{...r,className:n,children:String(e)})}}function R(e){if(e instanceof Date)return isNaN(e.getTime())?null:e;if(typeof e=="number"){let t=new Date(e);return isNaN(t.getTime())?null:t}if(typeof e=="string"){let t=new Date(e);return isNaN(t.getTime())?null:t}return null}function Q({value:e,format:t,as:s="span",className:n,...r}){let a=s,{formatDate:m}=p(),i=R(e);if(!i)return c()&&console.error("[i18n] DateFormat component requires a valid Date, timestamp, or date string"),l(a,{...r,className:n,children:String(e)});try{return l(a,{...r,className:n,children:m(i,t)})}catch(o){return c()&&console.error("[i18n] DateFormat component error:",o),l(a,{...r,className:n,children:i.toLocaleDateString()})}}function W({value:e,baseDate:t,as:s="span",className:n,...r}){let a=s,{formatRelativeTime:m}=p(),i=R(e);if(!i)return c()&&console.error("[i18n] RelativeTime component requires a valid Date, timestamp, or date string for value"),l(a,{...r,className:n,children:String(e)});let o;if(t!==void 0&&(o=R(t)??void 0,!o))return c()&&console.error("[i18n] RelativeTime component requires a valid Date, timestamp, or date string for baseDate"),l(a,{...r,className:n,children:String(e)});try{return l(a,{...r,className:n,children:m(i,o)})}catch(u){return c()&&console.error("[i18n] RelativeTime component error:",u),l(a,{...r,className:n,children:i.toLocaleDateString()})}}export{Q as DateFormat,J as I18nProvider,G as NumberFormat,W as RelativeTime,z as T,Z as Trans,U as useHasTranslation,b as useI18n,F as useI18nContext,_ as useLocale,p as useTranslation};
|
|
2
3
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context.tsx","../src/hooks.ts","../src/components.tsx"],"names":["I18nContext","createContext","I18nProvider","i18n","children","value","jsx","useI18nContext","context","useContext","useI18n","locale","useSyncExternalStore","React","callback","useTranslation","namespace","useCallback","key","args","fullKey","useMemo","useLocale","useHasTranslation","T","id","values","Component","className","props","t","translatedText","error","Trans","components","translation","parseTranslation","text","result","lastIndex","regex","match","fullMatch","componentIndex","innerContent","startIndex","elements","NumberFormat","format","formatNumber","DateFormat","formatDate","RelativeTime","baseDate","formatRelativeTime"],"mappings":"4HAOO,IAAMA,CAAAA,CAAcC,cAA4C,IAAI,CAAA,CAOpE,SAASC,CAAAA,CAAoD,CAClE,IAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,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AAAA,CAAO,CACd,OAAI,OAAA,CAAQ,GAAA,CAAI,WAAa,YAAA,EAC3B,OAAA,CAAQ,KAAA,CAAM,sCAAA,CAAwCA,CAAK,CAAA,CAG3D1B,IAACqB,CAAAA,CAAA,CAAU,UAAWC,CAAAA,CAAY,GAAGC,EAClC,QAAA,CAAA,MAAA,CAAOxB,CAAK,CAAA,CACf,CAEJ,CACF","file":"index.mjs","sourcesContent":["import type { I18nInstance, Messages } from '@oxog/i18n';\nimport React, { createContext, useContext, useSyncExternalStore } from 'react';\n\nexport interface I18nContextValue<TMessages extends Messages = Messages> {\n i18n: I18nInstance<TMessages>;\n}\n\nexport const I18nContext = createContext<I18nContextValue<any> | null>(null);\n\nexport interface I18nProviderProps<TMessages extends Messages = Messages> {\n i18n: I18nInstance<TMessages>;\n children: React.ReactNode;\n}\n\nexport function I18nProvider<TMessages extends Messages = Messages>({\n i18n,\n children,\n}: I18nProviderProps<TMessages>) {\n if (!i18n) {\n throw new Error('[i18n] I18nProvider requires a valid i18n instance');\n }\n \n const value: I18nContextValue<any> = { i18n };\n \n return (\n <I18nContext.Provider value={value}>\n {children}\n </I18nContext.Provider>\n );\n}\n\nexport function useI18nContext<TMessages extends Messages = Messages>(): I18nContextValue<TMessages> {\n const context = useContext(I18nContext);\n if (!context || !context.i18n) {\n throw new Error('[i18n] useI18nContext must be used within an I18nProvider with a valid i18n instance');\n }\n return context as I18nContextValue<TMessages>;\n}\n\nexport function useI18n<TMessages extends Messages = Messages>(): I18nInstance<TMessages> {\n const { i18n } = useI18nContext<TMessages>();\n \n if (!i18n) {\n throw new Error('[i18n] useI18n requires a valid i18n instance');\n }\n \n // Use useSyncExternalStore for optimal performance and concurrent features\n const locale = useSyncExternalStore(\n React.useCallback((callback) => {\n if (typeof i18n.subscribe === 'function') {\n return i18n.subscribe(callback);\n }\n // Fallback for instances without subscribe\n return () => {};\n }, [i18n]),\n () => i18n.locale || 'en',\n () => i18n.locale || 'en'\n );\n \n // Force re-render when locale changes\n React.useDebugValue(locale);\n \n return i18n;\n}","import type { ExtractTranslationKeys, Messages, TranslationFunction } from '@oxog/i18n';\nimport { useCallback, useMemo } from 'react';\nimport { useI18n } from './context';\n\nexport interface UseTranslationResult<TMessages extends Messages = Messages> {\n t: TranslationFunction<TMessages>;\n locale: string;\n setLocale: (locale: string) => void;\n formatNumber: (value: number, format?: string) => string;\n formatDate: (value: Date, format?: string) => string;\n formatRelativeTime: (value: Date, baseDate?: Date) => string;\n}\n\nexport function useTranslation<TMessages extends Messages = Messages>(\n namespace?: string\n): UseTranslationResult<TMessages> {\n const i18n = useI18n<TMessages>();\n \n const t = useCallback<TranslationFunction<TMessages>>(\n (key, ...args) => {\n const fullKey = namespace ? `${namespace}.${String(key)}` : String(key);\n return i18n.t(fullKey as any, ...args);\n },\n [i18n, namespace]\n );\n \n return useMemo(\n () => ({\n t,\n locale: i18n.locale,\n setLocale: i18n.setLocale.bind(i18n),\n formatNumber: i18n.formatNumber.bind(i18n),\n formatDate: i18n.formatDate.bind(i18n),\n formatRelativeTime: i18n.formatRelativeTime.bind(i18n),\n }),\n [i18n, t, i18n.locale]\n );\n}\n\nexport function useLocale(): [string, (locale: string) => void] {\n const i18n = useI18n();\n return [i18n.locale, i18n.setLocale.bind(i18n)];\n}\n\nexport function useHasTranslation<TMessages extends Messages = Messages>() {\n const i18n = useI18n<TMessages>();\n \n return useCallback(\n (key: ExtractTranslationKeys<TMessages>, locale?: string) => {\n return i18n.hasTranslation(key, locale);\n },\n [i18n]\n );\n}","import type { ExtractTranslationKeys, ExtractTranslationParams, Messages } from '@oxog/i18n';\nimport React from 'react';\nimport { useTranslation } from './hooks';\n\nexport interface TProps<\n TMessages extends Messages = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n> {\n id: TKey;\n values?: ExtractTranslationParams<TMessages, TKey>;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function T<\n TMessages extends Messages = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n>({ id, values, as: Component = 'span', className, ...props }: TProps<TMessages, TKey>) {\n const { t } = useTranslation<TMessages>();\n \n if (!id) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] T component requires an id prop');\n }\n return null;\n }\n \n try {\n const translatedText = values ? (t as any)(id, values) : (t as any)(id);\n \n return (\n <Component className={className} {...props}>\n {translatedText}\n </Component>\n );\n } catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] T component translation error:', error);\n }\n return (\n <Component className={className} {...props}>\n {String(id)}\n </Component>\n );\n }\n}\n\nexport interface TransProps<\n TMessages extends Messages = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n> {\n id: TKey;\n values?: ExtractTranslationParams<TMessages, TKey>;\n components?: Record<string, React.ReactElement>;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function Trans<\n TMessages extends Messages = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n>({ id, values, components = {}, as: Component = 'span', className, ...props }: TransProps<TMessages, TKey>) {\n const { t } = useTranslation<TMessages>();\n \n const translation = values ? (t as any)(id, values) : (t as any)(id);\n \n // Parse the translation and replace component placeholders\n function parseTranslation(text: string): React.ReactNode[] {\n const result: React.ReactNode[] = [];\n let lastIndex = 0;\n \n // Find all component tags\n const regex = /<(\\d+)>(.*?)<\\/\\1>/g;\n let match;\n \n while ((match = regex.exec(text)) !== null) {\n const [fullMatch, componentIndex, innerContent] = match;\n const startIndex = match.index;\n \n // Add text before the component\n if (startIndex > lastIndex) {\n result.push(text.slice(lastIndex, startIndex));\n }\n \n // Process the component\n const Component = components[componentIndex];\n if (Component) {\n // Recursively parse inner content for nested components\n const children = parseTranslation(innerContent);\n result.push(\n React.cloneElement(\n Component,\n { key: `component-${componentIndex}-${startIndex}` },\n children.length === 1 && typeof children[0] === 'string' ? children[0] : children\n )\n );\n } else {\n // If component not found, keep the original text\n result.push(fullMatch);\n }\n \n lastIndex = startIndex + fullMatch.length;\n }\n \n // Add any remaining text\n if (lastIndex < text.length) {\n result.push(text.slice(lastIndex));\n }\n \n return result;\n }\n \n const elements = parseTranslation(translation);\n \n return (\n <Component className={className} {...props}>\n {elements}\n </Component>\n );\n}\n\nexport interface NumberFormatProps {\n value: number;\n format?: string;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function NumberFormat({ value, format, as: Component = 'span', className, ...props }: NumberFormatProps) {\n const { formatNumber } = useTranslation();\n \n if (typeof value !== 'number' || isNaN(value)) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] NumberFormat component requires a valid number');\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n \n try {\n return (\n <Component className={className} {...props}>\n {formatNumber(value, format)}\n </Component>\n );\n } catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] NumberFormat component error:', error);\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n}\n\nexport interface DateFormatProps {\n value: Date | any;\n format?: string;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function DateFormat({ value, format, as: Component = 'span', className, ...props }: DateFormatProps) {\n const { formatDate } = useTranslation();\n \n if (!(value instanceof Date) || isNaN((value as Date).getTime())) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] DateFormat component requires a valid Date object');\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n \n try {\n return (\n <Component className={className} {...props}>\n {formatDate(value, format)}\n </Component>\n );\n } catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] DateFormat component error:', error);\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n}\n\nexport interface RelativeTimeProps {\n value: Date | any;\n baseDate?: Date | any;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function RelativeTime({ value, baseDate, as: Component = 'span', className, ...props }: RelativeTimeProps) {\n const { formatRelativeTime } = useTranslation();\n \n if (!(value instanceof Date) || isNaN((value as Date).getTime())) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] RelativeTime component requires a valid Date object for value');\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n \n if (baseDate !== undefined && (!(baseDate instanceof Date) || isNaN((baseDate as Date).getTime()))) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] RelativeTime component requires a valid Date object for baseDate');\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n \n try {\n return (\n <Component className={className} {...props}>\n {formatRelativeTime(value, baseDate)}\n </Component>\n );\n } catch (error) {\n if (process.env.NODE_ENV !== 'production') {\n console.error('[i18n] RelativeTime component error:', error);\n }\n return (\n <Component className={className} {...props}>\n {String(value)}\n </Component>\n );\n }\n}"]}
|
|
1
|
+
{"version":3,"sources":["../src/context.tsx","../src/env.ts","../src/hooks.ts","../src/components.tsx"],"sourcesContent":["import type { I18nInstance, Messages } from '@oxog/i18n';\nimport React, { createContext, useContext, useMemo, useSyncExternalStore } from 'react';\nimport { isDevelopment } from './env';\n\nexport interface I18nContextValue<TMessages extends object = Messages> {\n i18n: I18nInstance<TMessages>;\n}\n\n// The context is shared by every catalog type; hooks narrow it with their type parameter.\nexport const I18nContext = createContext<I18nContextValue<object> | null>(null);\n\nexport interface I18nProviderProps<TMessages extends object = Messages> {\n i18n: I18nInstance<TMessages>;\n children: React.ReactNode;\n}\n\nexport function I18nProvider<TMessages extends object = Messages>({\n i18n,\n children,\n}: I18nProviderProps<TMessages>) {\n if (!i18n) {\n throw new Error('[i18n] I18nProvider requires a valid i18n instance');\n }\n\n const value = useMemo(() => ({ i18n }) as unknown as I18nContextValue<object>, [i18n]);\n\n return (\n <I18nContext.Provider value={value}>\n {children}\n </I18nContext.Provider>\n );\n}\n\nexport function useI18nContext<TMessages extends object = Messages>(): I18nContextValue<TMessages> {\n const context = useContext(I18nContext);\n if (!context || !context.i18n) {\n throw new Error('[i18n] useI18nContext must be used within an I18nProvider with a valid i18n instance');\n }\n return context as unknown as I18nContextValue<TMessages>;\n}\n\n/**\n * Subscribes to the instance and returns a snapshot that changes whenever the visible\n * translations change: on locale switches and, for instances that expose `revision`\n * (all `createI18n` instances), when messages are added for the active locale.\n * @internal\n */\nexport function useI18nSnapshot<TMessages extends object = Messages>(): {\n i18n: I18nInstance<TMessages>;\n snapshot: string;\n} {\n const { i18n } = useI18nContext<TMessages>();\n\n const subscribe = React.useCallback(\n (callback: () => void) => {\n if (typeof i18n.subscribe !== 'function') {\n if (isDevelopment()) {\n console.error('[i18n] i18n instance missing subscribe method - reactivity will not work properly');\n }\n return () => {};\n }\n return i18n.subscribe(callback);\n },\n [i18n]\n );\n const getSnapshot = () => `${i18n.locale || 'en'}\\u0000${i18n.revision ?? 0}`;\n\n // useSyncExternalStore keeps concurrent rendering, StrictMode and SSR hydration\n // consistent: the server snapshot is the instance's current state.\n const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n React.useDebugValue(i18n.locale);\n\n return { i18n, snapshot };\n}\n\nexport function useI18n<TMessages extends object = Messages>(): I18nInstance<TMessages> {\n return useI18nSnapshot<TMessages>().i18n;\n}\n","/**\n * True when NODE_ENV is not \"production\". Bundlers replace `process.env.NODE_ENV`\n * statically; where no `process` global exists (ESM loaded directly in a browser)\n * this returns false instead of throwing a ReferenceError.\n * @internal\n */\nexport function isDevelopment(): boolean {\n try {\n return process.env.NODE_ENV !== 'production';\n } catch {\n return false;\n }\n}\n","import type { ExtractTranslationKeys, Messages, TranslationFunction, TranslationParams } from '@oxog/i18n';\nimport { useCallback, useMemo } from 'react';\nimport { useI18n, useI18nSnapshot } from './context';\n\nexport interface UseTranslationResult<TMessages extends object = Messages> {\n t: TranslationFunction<TMessages>;\n locale: string;\n setLocale: (locale: string) => void;\n formatNumber: (value: number, format?: string) => string;\n formatDate: (value: Date, format?: string) => string;\n formatRelativeTime: (value: Date, baseDate?: Date) => string;\n}\n\nexport function useTranslation<TMessages extends object = Messages>(\n namespace?: string\n): UseTranslationResult<TMessages> {\n const { i18n, snapshot } = useI18nSnapshot<TMessages>();\n\n // `snapshot` changes with the locale and with lazily added messages, so `t` gets a new\n // identity and memoized children/effects that depend on it re-render with new text.\n const t = useCallback(\n (key: string, ...args: [params?: TranslationParams]) => {\n const fullKey = namespace ? `${namespace}.${String(key)}` : String(key);\n return (i18n.t as (key: string, ...args: [params?: TranslationParams]) => string)(fullKey, ...args);\n },\n [i18n, namespace, snapshot]\n ) as unknown as TranslationFunction<TMessages>;\n\n const setLocale = useCallback((locale: string) => {\n i18n.setLocale(locale);\n }, [i18n]);\n\n const formatNumber = useCallback((value: number, format?: string) => {\n return i18n.formatNumber(value, format);\n }, [i18n]);\n\n const formatDate = useCallback((value: Date, format?: string) => {\n return i18n.formatDate(value, format);\n }, [i18n]);\n\n const formatRelativeTime = useCallback((value: Date, baseDate?: Date) => {\n return i18n.formatRelativeTime(value, baseDate);\n }, [i18n]);\n\n return useMemo<UseTranslationResult<TMessages>>(\n () => ({\n t,\n locale: i18n.locale,\n setLocale,\n formatNumber,\n formatDate,\n formatRelativeTime,\n }),\n // `t as unknown` avoids an expensive structural comparison of the generic `t` type.\n [t as unknown, i18n.locale, setLocale, formatNumber, formatDate, formatRelativeTime]\n );\n}\n\nexport function useLocale(): [string, (locale: string) => void] {\n const i18n = useI18n();\n const setLocale = useCallback((locale: string) => {\n i18n.setLocale(locale);\n }, [i18n]);\n return [i18n.locale, setLocale];\n}\n\nexport function useHasTranslation<TMessages extends object = Messages>() {\n const i18n = useI18n<TMessages>();\n \n return useCallback(\n (key: ExtractTranslationKeys<TMessages>, locale?: string) => {\n return i18n.hasTranslation(key, locale);\n },\n [i18n]\n );\n}","import type { ExtractTranslationKeys, ExtractTranslationParams, Messages, TranslationParams } from '@oxog/i18n';\nimport React from 'react';\nimport type { JSX } from 'react';\nimport { isDevelopment } from './env';\nimport { useTranslation } from './hooks';\n\n/** HTML attributes forwarded to the rendered element (`title`, `role`, `aria-*`, ...). */\ntype ForwardedAttributes = Omit<React.HTMLAttributes<HTMLElement>, 'id' | 'children' | 'className'>;\n\nexport interface TProps<\n TMessages extends object = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n> extends ForwardedAttributes {\n id: TKey;\n values?: ExtractTranslationParams<TMessages, TKey>;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function T<\n TMessages extends object = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n>({ id, values, as: tag = 'span', className, ...props }: TProps<TMessages, TKey>) {\n const Component = tag as React.ElementType;\n const { t } = useTranslation<TMessages>();\n \n if (!id) {\n if (isDevelopment()) {\n console.error('[i18n] T component requires an id prop');\n }\n return null;\n }\n \n try {\n const translate = t as unknown as (key: string, params?: TranslationParams) => string;\n const translatedText = values ? translate(id, values as TranslationParams) : translate(id);\n \n return (\n <Component {...props} className={className}>\n {translatedText}\n </Component>\n );\n } catch (error) {\n if (isDevelopment()) {\n console.error('[i18n] T component translation error:', error);\n }\n return (\n <Component {...props} className={className}>\n {String(id)}\n </Component>\n );\n }\n}\n\nexport interface TransProps<\n TMessages extends object = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n> extends ForwardedAttributes {\n id: TKey;\n values?: ExtractTranslationParams<TMessages, TKey>;\n components?: Record<string, React.ReactElement>;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function Trans<\n TMessages extends object = Messages,\n TKey extends ExtractTranslationKeys<TMessages> = ExtractTranslationKeys<TMessages>\n>({ id, values, components = {}, as: tag = 'span', className, ...props }: TransProps<TMessages, TKey>) {\n const Component = tag as React.ElementType;\n const { t } = useTranslation<TMessages>();\n \n // Interpolated values must stay plain text: a value such as \"<0>admin</0>\" must not be\n // turned into one of the developer-supplied components. Hide \"<\" in string values\n // behind a private-use character while parsing and restore it in text nodes.\n const protectedValues = values ? protectValues(values as Record<string, unknown>) : undefined;\n const translate = t as unknown as (key: string, params?: TranslationParams) => string;\n const translation = protectedValues ? translate(id, protectedValues as TranslationParams) : translate(id);\n\n // Parse the translation and replace component placeholders\n function parseTranslation(text: string, depth: number = 0): React.ReactNode[] {\n const MAX_DEPTH = 10; // Prevent stack overflow from malicious or malformed translations\n\n if (depth > MAX_DEPTH) {\n if (isDevelopment()) {\n console.error('[i18n] Max nesting depth exceeded in Trans component');\n }\n return [text];\n }\n\n const result: React.ReactNode[] = [];\n let lastIndex = 0;\n\n // Find all component tags\n const regex = /<([A-Za-z0-9_]+)>([\\s\\S]*?)<\\/\\1>/g;\n let match;\n\n while ((match = regex.exec(text)) !== null) {\n const [fullMatch, componentIndex, innerContent] = match;\n const startIndex = match.index;\n\n // Add text before the component\n if (startIndex > lastIndex) {\n result.push(restoreText(text.slice(lastIndex, startIndex)));\n }\n\n // Process the component (renamed to avoid shadowing)\n const ChildComponent = Object.prototype.hasOwnProperty.call(components, componentIndex)\n ? components[componentIndex]\n : undefined;\n if (React.isValidElement(ChildComponent)) {\n // Recursively parse inner content for nested components with depth tracking\n const children = parseTranslation(innerContent, depth + 1);\n result.push(\n React.cloneElement(\n ChildComponent,\n { key: `component-${componentIndex}-${startIndex}` },\n children.length === 1 && typeof children[0] === 'string' ? children[0] : children\n )\n );\n } else {\n // If component not found, keep the original text\n result.push(restoreText(fullMatch));\n }\n\n lastIndex = startIndex + fullMatch.length;\n }\n\n // Add any remaining text\n if (lastIndex < text.length) {\n result.push(restoreText(text.slice(lastIndex)));\n }\n\n return result;\n }\n \n const elements = parseTranslation(translation);\n \n return (\n <Component {...props} className={className}>\n {elements}\n </Component>\n );\n}\n\nconst LT_PLACEHOLDER = '\\uE000';\n\nfunction protectValues(values: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(values)) {\n const value = values[key];\n result[key] = typeof value === 'string' ? value.split('<').join(LT_PLACEHOLDER) : value;\n }\n return result;\n}\n\nfunction restoreText(text: string): string {\n return text.split(LT_PLACEHOLDER).join('<');\n}\n\nexport interface NumberFormatProps extends ForwardedAttributes {\n value: number;\n format?: string;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function NumberFormat({ value, format, as: tag = 'span', className, ...props }: NumberFormatProps) {\n const Component = tag as React.ElementType;\n const { formatNumber } = useTranslation();\n \n if (typeof value !== 'number' || isNaN(value)) {\n if (isDevelopment()) {\n console.error('[i18n] NumberFormat component requires a valid number');\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n\n try {\n return (\n <Component {...props} className={className}>\n {formatNumber(value, format)}\n </Component>\n );\n } catch (error) {\n if (isDevelopment()) {\n console.error('[i18n] NumberFormat component error:', error);\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n}\n\nexport interface DateFormatProps extends ForwardedAttributes {\n value: Date | string | number;\n format?: string;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\n// BUG-031 FIX: Helper function to convert string|number to Date\nfunction toDate(value: Date | string | number): Date | null {\n if (value instanceof Date) {\n return isNaN(value.getTime()) ? null : value;\n }\n if (typeof value === 'number') {\n const date = new Date(value);\n return isNaN(date.getTime()) ? null : date;\n }\n if (typeof value === 'string') {\n const date = new Date(value);\n return isNaN(date.getTime()) ? null : date;\n }\n return null;\n}\n\nexport function DateFormat({ value, format, as: tag = 'span', className, ...props }: DateFormatProps) {\n const Component = tag as React.ElementType;\n const { formatDate } = useTranslation();\n\n // BUG-031 FIX: Convert string|number to Date before validation\n const dateValue = toDate(value);\n\n if (!dateValue) {\n if (isDevelopment()) {\n console.error('[i18n] DateFormat component requires a valid Date, timestamp, or date string');\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n\n try {\n return (\n <Component {...props} className={className}>\n {formatDate(dateValue, format)}\n </Component>\n );\n } catch (error) {\n if (isDevelopment()) {\n console.error('[i18n] DateFormat component error:', error);\n }\n return (\n <Component {...props} className={className}>\n {dateValue.toLocaleDateString()}\n </Component>\n );\n }\n}\n\nexport interface RelativeTimeProps extends ForwardedAttributes {\n value: Date | string | number;\n baseDate?: Date | string | number;\n as?: keyof JSX.IntrinsicElements;\n className?: string;\n}\n\nexport function RelativeTime({ value, baseDate, as: tag = 'span', className, ...props }: RelativeTimeProps) {\n const Component = tag as React.ElementType;\n const { formatRelativeTime } = useTranslation();\n\n // BUG-032 FIX: Convert string|number to Date before validation\n const dateValue = toDate(value);\n\n if (!dateValue) {\n if (isDevelopment()) {\n console.error('[i18n] RelativeTime component requires a valid Date, timestamp, or date string for value');\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n\n // BUG-032 FIX: Also convert baseDate if provided\n let baseDateValue: Date | undefined;\n if (baseDate !== undefined) {\n baseDateValue = toDate(baseDate) ?? undefined;\n if (!baseDateValue) {\n if (isDevelopment()) {\n console.error('[i18n] RelativeTime component requires a valid Date, timestamp, or date string for baseDate');\n }\n return (\n <Component {...props} className={className}>\n {String(value)}\n </Component>\n );\n }\n }\n\n try {\n return (\n <Component {...props} className={className}>\n {formatRelativeTime(dateValue, baseDateValue)}\n </Component>\n );\n } catch (error) {\n if (isDevelopment()) {\n console.error('[i18n] RelativeTime component error:', error);\n }\n return (\n <Component {...props} className={className}>\n {dateValue.toLocaleDateString()}\n </Component>\n );\n }\n}\n"],"mappings":";AACA,OAAOA,GAAS,iBAAAC,EAAe,cAAAC,EAAY,WAAAC,EAAS,wBAAAC,MAA4B,QCKzE,SAASC,GAAyB,CACvC,GAAI,CACF,OAAO,QAAQ,IAAI,WAAa,YAClC,MAAQ,CACN,MAAO,EACT,CACF,CDeI,cAAAC,MAAA,oBAlBG,IAAMC,EAAcC,EAA+C,IAAI,EAOvE,SAASC,EAAkD,CAChE,KAAAC,EACA,SAAAC,CACF,EAAiC,CAC/B,GAAI,CAACD,EACH,MAAM,I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AAInC,EAAc,GAChB,QAAQ,MAAM,0FAA0F,EAGxGV,EAACO,EAAA,CAAW,GAAGD,EAAO,UAAWD,EAC9B,gBAAOgC,CAAK,EACf,EAKJ,IAAIY,EACJ,GAAIF,IAAa,SACfE,EAAgBR,EAAOM,CAAQ,GAAK,OAChC,CAACE,GACH,OAAIvC,EAAc,GAChB,QAAQ,MAAM,6FAA6F,EAG3GV,EAACO,EAAA,CAAW,GAAGD,EAAO,UAAWD,EAC9B,gBAAOgC,CAAK,EACf,EAKN,GAAI,CACF,OACErC,EAACO,EAAA,CAAW,GAAGD,EAAO,UAAWD,EAC9B,SAAA2C,EAAmBH,EAAWI,CAAa,EAC9C,CAEJ,OAASpC,EAAO,CACd,OAAIH,EAAc,GAChB,QAAQ,MAAM,uCAAwCG,CAAK,EAG3Db,EAACO,EAAA,CAAW,GAAGD,EAAO,UAAWD,EAC9B,SAAAwC,EAAU,mBAAmB,EAChC,CAEJ,CACF","names":["React","createContext","useContext","useMemo","useSyncExternalStore","isDevelopment","jsx","I18nContext","createContext","I18nProvider","i18n","children","value","useMemo","useI18nContext","context","useContext","useI18nSnapshot","subscribe","React","callback","isDevelopment","getSnapshot","snapshot","useSyncExternalStore","useI18n","useCallback","useMemo","useTranslation","namespace","i18n","snapshot","useI18nSnapshot","t","useCallback","key","args","fullKey","setLocale","locale","formatNumber","value","format","formatDate","formatRelativeTime","baseDate","useMemo","useLocale","useI18n","useHasTranslation","React","jsx","T","id","values","tag","className","props","Component","t","useTranslation","isDevelopment","translate","translatedText","error","Trans","components","protectedValues","protectValues","translation","parseTranslation","text","depth","result","lastIndex","regex","match","fullMatch","componentIndex","innerContent","startIndex","restoreText","ChildComponent","React","children","elements","LT_PLACEHOLDER","key","value","NumberFormat","format","formatNumber","toDate","date","DateFormat","formatDate","dateValue","RelativeTime","baseDate","formatRelativeTime","baseDateValue"]}
|
package/package.json
CHANGED
|
@@ -1,22 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oxog/i18n-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "React bindings for @oxog/i18n",
|
|
5
5
|
"author": "Ersin Koç",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
9
|
-
"url": "https://github.com/ersinkoc/i18n",
|
|
9
|
+
"url": "git+https://github.com/ersinkoc/i18n.git",
|
|
10
10
|
"directory": "packages/react"
|
|
11
11
|
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/ersinkoc/i18n/issues"
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://github.com/ersinkoc/i18n/tree/main/packages/react#readme",
|
|
12
16
|
"main": "./dist/index.js",
|
|
13
17
|
"module": "./dist/index.mjs",
|
|
14
18
|
"types": "./dist/index.d.ts",
|
|
15
19
|
"exports": {
|
|
16
20
|
".": {
|
|
17
|
-
"
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
"import": {
|
|
22
|
+
"types": "./dist/index.d.mts",
|
|
23
|
+
"default": "./dist/index.mjs"
|
|
24
|
+
},
|
|
25
|
+
"require": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
}
|
|
20
29
|
},
|
|
21
30
|
"./package.json": "./package.json"
|
|
22
31
|
},
|
|
@@ -25,20 +34,21 @@
|
|
|
25
34
|
],
|
|
26
35
|
"peerDependencies": {
|
|
27
36
|
"react": ">=18.0.0",
|
|
28
|
-
"@oxog/i18n": "0.
|
|
37
|
+
"@oxog/i18n": "^0.2.0"
|
|
29
38
|
},
|
|
30
39
|
"devDependencies": {
|
|
31
40
|
"@testing-library/jest-dom": "^6.2.0",
|
|
32
41
|
"@testing-library/react": "^14.1.2",
|
|
33
42
|
"@types/react": "^18.2.48",
|
|
34
|
-
"@
|
|
43
|
+
"@types/react-dom": "^18.3.7",
|
|
44
|
+
"@vitest/coverage-v8": "^4.0.8",
|
|
35
45
|
"jsdom": "^23.2.0",
|
|
36
46
|
"react": "^18.2.0",
|
|
37
47
|
"react-dom": "^18.2.0",
|
|
38
48
|
"tsup": "^8.0.1",
|
|
39
49
|
"typescript": "^5.3.3",
|
|
40
|
-
"vitest": "^
|
|
41
|
-
"@oxog/i18n": "0.
|
|
50
|
+
"vitest": "^4.0.8",
|
|
51
|
+
"@oxog/i18n": "^0.2.0"
|
|
42
52
|
},
|
|
43
53
|
"sideEffects": false,
|
|
44
54
|
"keywords": [
|
|
@@ -49,12 +59,18 @@
|
|
|
49
59
|
"translation",
|
|
50
60
|
"typescript"
|
|
51
61
|
],
|
|
62
|
+
"engines": {
|
|
63
|
+
"node": ">=18.0.0"
|
|
64
|
+
},
|
|
65
|
+
"publishConfig": {
|
|
66
|
+
"access": "public"
|
|
67
|
+
},
|
|
52
68
|
"scripts": {
|
|
53
|
-
"dev": "tsup --watch",
|
|
54
69
|
"build": "tsup",
|
|
70
|
+
"dev": "tsup --watch",
|
|
55
71
|
"test": "vitest run",
|
|
56
72
|
"test:watch": "vitest",
|
|
57
73
|
"test:coverage": "vitest run --coverage",
|
|
58
|
-
"typecheck": "tsc --noEmit"
|
|
74
|
+
"typecheck": "tsc --noEmit -p tsconfig.test.json"
|
|
59
75
|
}
|
|
60
76
|
}
|