@sheet-i18n/react 1.0.2 → 1.0.4

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.
Files changed (2) hide show
  1. package/README.md +139 -12
  2. package/package.json +4 -4
package/README.md CHANGED
@@ -9,7 +9,8 @@ This package provides tools to handle translations in React applications using c
9
9
  - **`I18nStore`**: _Store Creation Class_ for managing translation data.
10
10
  - **`createI18nContext`**: _React Context_ to generate providers and hooks for translation.
11
11
  - **`IntlProvider`**: _React Translation Provider_ for managing current locale.
12
- - **`useTranslation`**: _Translation Hook_ for easy access to translation messages.
12
+ - **`useTranslation`**: _Client Side Translation Hook_ for easy access to translation messages on the client side.
13
+ - **`getTranslation`**: _Static Translation Function_ for easy access to translation messages on Static module files.
13
14
 
14
15
  ## 🚀 Getting Started
15
16
 
@@ -37,7 +38,7 @@ Prepare locale JSON files:
37
38
  }
38
39
  ```
39
40
 
40
- #### 2. Initialize i18n Store
41
+ #### 2. Initialize i18nStore
41
42
 
42
43
  this store will be used as a core translations module.
43
44
 
@@ -63,7 +64,8 @@ export const i18nStore = new I18nStore({
63
64
  import { i18nStore } from './file-path-of-i18nStore-initiated';
64
65
  import { createI18nContext } from '@sheet-i18n/react';
65
66
 
66
- export const { IntlProvider, useTranslation } = createI18nContext(i18nStore);
67
+ export const { IntlProvider, useTranslation, getTranslation } =
68
+ createI18nContext(i18nStore);
67
69
  ```
68
70
 
69
71
  #### 4. Mount Intl Context Provider in your App
@@ -99,11 +101,11 @@ const YourComponent = () => {
99
101
  };
100
102
  ```
101
103
 
102
- ---
104
+ <br/>
103
105
 
104
- ## 📦 API Reference
106
+ ## 📦 Base API Reference
105
107
 
106
- ### `I18nStore`
108
+ ### `I18nStore(core)`
107
109
 
108
110
  The `I18nStore` manages type-safe translation states, ensuring consistency across locales.
109
111
 
@@ -112,6 +114,25 @@ The `I18nStore` manages type-safe translation states, ensuring consistency acros
112
114
  - **`supportedLocales`**: Array of supported locale strings.
113
115
  - **`defaultLocale`**: The default locale, included in `supportedLocales`.
114
116
  - **`localeSet`**: An object where keys match `supportedLocales`, and values are translation sets.
117
+ - **`typeSafe(optional, default = true)`**: An optional boolean indicating whether to use type-safe translations.
118
+
119
+ > 💡 **typeSafe?** <br/>
120
+ > I18nStore is type-safe by default. So, basically, you can't add the translation data that is not defined in the locale Json files. However, for fast development, you can off the typeSafe option manually.
121
+ >
122
+ > ```tsx
123
+ > // typeSafe: false
124
+ > const YourComponent = () => {
125
+ > // useTranslation(sheetTitle: string)
126
+ > const { t } = useTranslation('header');
127
+ >
128
+ > return (
129
+ > <div>
130
+ > {/* t(key: string): any */}
131
+ > <button>{t('login')}</button>
132
+ > </div>
133
+ > );
134
+ > };
135
+ > ```
115
136
 
116
137
  > ⚠️ Caveats:
117
138
  >
@@ -157,15 +178,15 @@ const { IntlProvider, useTranslation } = createI18nContext(i18nStore);
157
178
 
158
179
  ### `IntlProvider`
159
180
 
160
- A React component to provide translations to child components.
181
+ A Context provider to provide translations to child components.
161
182
 
162
183
  #### Properties:
163
184
 
164
185
  - **`currentLocale`** (optional):
165
186
 
166
187
  - A key representing the current locale to use for translations.
167
- - If not provided, the user's preferred language is automatically detected based on their browser settings.
168
- - Falls back to the default locale in **i18nStore** if the detected language is unsupported.
188
+ - If not provided, the user's preferred language is automatically detected based on the browser setting.
189
+ - The fallback is the default locale in **i18nStore** if the detected language is unsupported.
169
190
 
170
191
  - **`children`**: React children.
171
192
 
@@ -174,9 +195,7 @@ A React component to provide translations to child components.
174
195
  ```tsx
175
196
  // Add currentLocale if you want to manually handle the locale
176
197
 
177
- // The example is Next.js app routing
178
- import { i18nStore } from './file-path-of-i18nStore-initiated';
179
-
198
+ // This example is Next.js app routing
180
199
  interface LayoutProps {
181
200
  params: {
182
201
  locale: Locale;
@@ -206,6 +225,35 @@ const { t } = useTranslation('header');
206
225
  const translatedMessage = t('login');
207
226
  ```
208
227
 
228
+ ### `getTranslation`
229
+
230
+ A hook to access translations in static modules.
231
+
232
+ #### Parameters:
233
+
234
+ - **`sheetTitle`**: The sheet title of the translation group.
235
+
236
+ #### Example:
237
+
238
+ ```tsx
239
+ // data.ts
240
+ import { getTranslation } from './i18nContext';
241
+
242
+ const { t } = getTranslation('header');
243
+
244
+ export const STATUS_CATEGORY = [
245
+ t('Total Energy Usage'),
246
+ t('Total Waste Usage'),
247
+ ];
248
+
249
+ // App.tsx
250
+ import { STATUS_CATEGORY } from './data';
251
+
252
+ export default function App() {
253
+ return STATUS_CATEGORY.map((item) => <div>{item}</div>);
254
+ }
255
+ ```
256
+
209
257
  ### `t Function`
210
258
 
211
259
  The t function is used to retrieve a translation string based on a key and optionally interpolate variables. It provides flexibility to include dynamic values, such as plain strings or React components, for enhanced localization capabilities.
@@ -232,6 +280,85 @@ const translatedMessage = t('{username} shown', { username: 'John Doe' });
232
280
  const translatedMessage = t('{username} shown', { username: <Username /> });
233
281
  ```
234
282
 
283
+ <br/>
284
+
285
+ ## 📄 Best Practices of Translation utilities
286
+
287
+ A robust and flexible translation library designed for efficient handling of translations in React applications.
288
+
289
+ ### Features
290
+
291
+ - **Client-Side Translation (Explicit Strings)**: Translate explicit string keys directly in your components.
292
+ - **Client-Side Translation (Dynamic Strings)**: Dynamically match translations from JSON for unknown variables.
293
+ - **Static Module Translation**: Use translations in static modules for configuration constants.
294
+
295
+ ### Usage
296
+
297
+ #### 1. **Client-Side Translation (Explicit Strings)**
298
+
299
+ Retrieve translations for explicit keys in your React components using `useTranslation`.
300
+
301
+ ```tsx
302
+ import React from 'react';
303
+ import { useTranslation } from './i18nContext';
304
+
305
+ const YourComponent = () => {
306
+ const { t } = useTranslation('header');
307
+
308
+ return (
309
+ <div>
310
+ <button>{t('login')}</button>
311
+ <button>{t('logout')}</button>
312
+ </div>
313
+ );
314
+ };
315
+ ```
316
+
317
+ #### 2. **Client-Side Translation (Dynamic Strings)**
318
+
319
+ For scenarios where the string key is not explicitly known (e.g., coming from a server), use `t.dynamic`. Ensure that your translation JSON and sheet are updated to include the variable values.
320
+ </br></br>
321
+ The **t.dynamic** function will automatically match the values from the JSON with the provided arguments and display the result.
322
+
323
+ ```tsx
324
+ // App.tsx
325
+ import { useTranslation } from './i18nContext';
326
+
327
+ const { t } = useTranslation('header');
328
+ const { data } = useQuery(...queryOptions);
329
+
330
+ const deviceName = data?.device?.name;
331
+
332
+ return <div>{t.dynamic(deviceName)}</div>;
333
+ ```
334
+
335
+ #### 3. **Static Module Translation**
336
+
337
+ Use `getTranslation` to initialize translations for static configurations, constants, or data that needs to be translated.
338
+
339
+ The **"t"** function from `getTranslation` returns a **Promise** that resolves to the translated string.
340
+
341
+ > 💡 Note <br/>
342
+ > The **`t`** function returned by **`getTranslation`** resolves its Promise in the background. For display purposes, you don't need to wait for the Promise to resolve, allowing you to use it without async/await.<br/> However, if you need to work with the fulfilled translated value during runtime, you have use async/await to retrieve it.
343
+
344
+ ```tsx
345
+ // data.ts
346
+ import { getTranslation } from './i18nContext';
347
+ const { t } = getTranslation('header');
348
+
349
+ export const STATUS_CATEGORY = [
350
+ t('Total Energy Usage'),
351
+ t('Total Waste Usage'),
352
+ ];
353
+
354
+ // App.tsx
355
+ import { STATUS_CATEGORY } from './data';
356
+
357
+ export default function App() {
358
+ return STATUS_CATEGORY.map((item) => <div>{item}</div>);
359
+ }
360
+ ```
361
+
235
362
  ## 🛠 Error Handling
236
363
 
237
364
  Custom error messages help identify misconfigurations:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sheet-i18n/react",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "i18n client logic based on react",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -29,11 +29,11 @@
29
29
  "license": "ISC",
30
30
  "devDependencies": {
31
31
  "@swc/core": "^1.10.2",
32
- "@sheet-i18n/typescript-config": "1.3.3"
32
+ "@sheet-i18n/typescript-config": "1.3.5"
33
33
  },
34
34
  "dependencies": {
35
- "@sheet-i18n/react-core": "1.0.1",
36
- "@sheet-i18n/react-client": "1.0.2"
35
+ "@sheet-i18n/react-core": "1.0.3",
36
+ "@sheet-i18n/react-client": "1.0.4"
37
37
  },
38
38
  "scripts": {
39
39
  "build": "tsup",