@nkzw/eslint-plugin-fbtee 1.7.6 → 2.0.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.
Files changed (3) hide show
  1. package/README.md +223 -505
  2. package/lib/index.mjs +1 -1
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,701 +1,419 @@
1
1
  # fbtee
2
2
 
3
- _**fbtee** (Far Better Translations, Extended Edition) is an internationalization framework for JavaScript & React designed to be **powerful**, **flexible**, and **intuitive**._
4
-
5
- fbtee features inline translations and supports dynamic content, pluralization, lists, and more. It is built on top of Facebook's `fbt` library, which has been used in production for over a decade, serving billions of users.
3
+ **_fbtee_** is an internationalization framework for JavaScript and React. It lets you write translatable text inline, keep translator context next to the UI, and compile strings into a small runtime format for production.
6
4
 
7
5
  ```tsx
8
6
  const Greeting = ({ name }) => (
9
- <div>
10
- <fbt desc="Greeting">
11
- Hello, <Name name={name} />!
12
- </fbt>
13
- </div>
7
+ <fbt desc="Greeting on the home screen">
8
+ Hello, <Name name={name} />!
9
+ </fbt>
14
10
  );
15
11
  ```
16
12
 
17
- ## Why choose **fbtee**?
13
+ _fbtee_ is a modern continuation of Facebook's `fbt`, rebuilt for TypeScript, ESM, React 19, Vite, Next.js, Babel & SWC.
14
+
15
+ ## Features
18
16
 
19
17
  - **Inline translations for Better Developer Experience:** Embed translations directly into your code. No need to manage translation keys or wrap your code with `t()` functions. **fbtee** uses a compiler to extract strings from your code and prepare them for translation providers.
20
- - **Proven in Production:** Built on Facebook's `fbt`, with over a decade of production usage, serving billions of users and two years of production usage in [Athena Crisis](https://athenacrisis.com).
18
+ - **Proven in Production:** Built on Facebook's `fbt`, with over a decade of production usage serving billions of users, plus years in production at [Athena Crisis](https://athenacrisis.com).
21
19
  - **Optimized Performance with IR:** Compiles translations into an Intermediate Representation (IR) for extracting strings, then optimizes the runtime output for performance.
22
- - **Easy Setup:** Quick integration with tools like Babel and Vite means you can get started instantly.
20
+ - **Easy Setup:** Quick integration with Babel, SWC, Vite, Next.js, and Expo.
23
21
 
24
22
  ## Getting Started
25
23
 
26
- Tired of setting up new projects? Check out these templates for web and React Native that come with **fbtee** pre-configured:
24
+ Use one of the templates if you are starting fresh:
27
25
 
28
26
  - [Web App Template](https://github.com/nkzw-tech/web-app-template)
29
27
  - [Expo App Template](https://github.com/nkzw-tech/expo-app-template)
30
28
 
31
- ### Examples
32
-
33
- Sometimes it's easiest to learn by example and copy-paste the setup from existing projects. Here are some examples of using **fbtee**:
34
-
35
- - [Next.js App fbtee Example](https://github.com/cpojer/nextjs-fbtee-example) - A Next.js App Router example using **fbtee** with Server Components.
36
- - [Athena Crisis](https://github.com/nkzw-tech/athena-crisis) - an open source video game using **fbtee**
37
-
38
- ### Installation
39
-
40
- **fbtee** requires at least Node 22, and React 19 if you are using React.
29
+ For an existing app, install the runtime:
41
30
 
42
31
  ```bash
43
32
  npm install fbtee
44
33
  ```
45
34
 
46
- In addition to `fbtee`, you need to install the Babel preset.
47
-
48
- ```bash
49
- npm install -D @nkzw/babel-preset-fbtee
50
- ```
35
+ _fbtee_ requires Node 22+. React apps should use React 19+.
51
36
 
52
- ### Tooling Setup
37
+ ### Babel, Vite and React
53
38
 
54
- If you are using Vite, install the React plugin for Vite:
39
+ Install the Babel preset and the Rolldown Babel plugin:
55
40
 
56
41
  ```bash
57
- npm install -D @vitejs/plugin-react
42
+ npm install -D @nkzw/babel-preset-fbtee @rolldown/plugin-babel
58
43
  ```
59
44
 
60
- In your `vite.config.ts`:
45
+ With Vite, `@rolldown/plugin-babel`, and `@vitejs/plugin-react`:
61
46
 
62
47
  ```ts
63
48
  import fbteePreset from '@nkzw/babel-preset-fbtee';
49
+ import babel from '@rolldown/plugin-babel';
64
50
  import react from '@vitejs/plugin-react';
65
-
66
- export default {
67
- plugins: [
68
- react({
69
- babel: {
70
- presets: [fbteePreset],
71
- },
72
- }),
73
- ],
74
- };
75
- ```
76
-
77
- #### Using Babel directly instead of Vite's React Plugin
78
-
79
- If you are not using `@vitejs/plugin-react`, for example, because you are using the latest version of React Router in framework mode, you can use `vite-plugin-babel` instead:
80
-
81
- ```tsx
82
- import fbteePreset from '@nkzw/babel-preset-fbtee';
83
- import { reactRouter } from '@react-router/dev/vite';
84
51
  import { defineConfig } from 'vite';
85
- import babel from 'vite-plugin-babel';
86
52
 
87
53
  export default defineConfig({
88
54
  plugins: [
89
55
  babel({
90
- babelConfig: { presets: [fbteePreset] },
56
+ presets: [fbteePreset],
91
57
  }),
92
- reactRouter(),
58
+ react(),
93
59
  ],
94
60
  });
95
61
  ```
96
62
 
97
- #### Using **fbtee** with Next.js
63
+ With a direct Babel setup:
98
64
 
99
- Create a `babel.config.js` file in the root of your Next.js project and add the **fbtee** preset:
100
-
101
- ```tsx
65
+ ```js
102
66
  export default {
103
- presets: ['next/babel', '@nkzw/babel-preset-fbtee'],
67
+ presets: ['@nkzw/babel-preset-fbtee'],
104
68
  };
105
69
  ```
106
70
 
107
- #### Scripts
108
-
109
- **fbtee** uses two scripts to manage translations. These scripts help automate the process of collecting, creating, and compiling translations.
110
-
111
- - `fbtee collect`: This command reads your source files and extracts all the translatable strings into a `source_strings.json` file. This file should be uploaded to your translation provider as the source for your translations.
112
- - `fbtee translate`: This command takes the collected strings and your translations, and compiles them into an optimized format for use in your application.
113
-
114
- By default, **fbtee** expects your source code to be anywhere within your project, your translations in a `translations` folder, and the generated translations in `src/translations`. You can customize these paths using command line arguments:
115
-
116
- - The `--translations` parameter can be specified to `fbtee translate` to customize the path to the input translation files.
117
- - The `--output-dir` parameter defines where the output translation files per language should be written (one file per locale), so they can be lazy loaded in your app.
118
- - The `--output-file` parameter outputs all translations in a single combined file, which can be used directly in your app without loading individual files.
119
-
120
- If you want to use different paths, it is recommended to define custom commands in your `package.json`:
121
-
122
- ```json
123
- {
124
- "scripts": {
125
- "fbtee:collect": "fbtee collect --src src",
126
- "fbtee:translate": "fbtee translate --translations translations/*.json -o src/translations/"
127
- }
128
- }
129
- ```
130
-
131
- Now, run the collect command to set up the initial strings for translation:
71
+ With Next.js and Babel:
132
72
 
133
- ```bash
134
- pnpm fbtee collect
73
+ ```js
74
+ export default {
75
+ presets: ['next/babel', '@nkzw/babel-preset-fbtee'],
76
+ };
135
77
  ```
136
78
 
137
- Add the files generated by these commands to your `.gitignore`:
79
+ ### SWC and Turbopack
138
80
 
139
- ```
140
- .enum_manifest.json
141
- source_strings.json
142
- src/translations/
143
- ```
144
-
145
- Because no translations exist yet, you can run this command to create an empty file for now:
81
+ Install the SWC runtime compiler and the CLI:
146
82
 
147
83
  ```bash
148
- mkdir -p translations
149
- echo '{"fb-locale": "ja_JP", "translations": {}}' > translations/ja_JP.json
84
+ npm install -D @nkzw/swc-plugin-fbtee @nkzw/fbtee-cli
150
85
  ```
151
86
 
152
- If you are not using a translation provider, you can also run `fbtee prepare-translations --locales ja_JP` to generate a JSON file that can be edited directly.
153
-
154
- ### App Setup
155
-
156
- **fbtee**'s runtime can manage the currently selected locale for you through the `<LocaleContext />` component. All you need to do is define the available languages, the locales provided by the browser or device, and a function to load translations for a given locale:
157
-
158
- ```tsx
159
- import { getLocales } from 'expo-localization';
160
- import { createLocaleContext } from 'fbtee';
161
-
162
- // Define the available languages in your app:
163
- const availableLanguages = new Map([
164
- ['en_US', 'English'],
165
- ['ja_JP', '日本語 (Japanese)'],
166
- ]);
87
+ For Next.js SWC plugins:
167
88
 
168
- // Web:
169
- const clientLocalesWeb = [navigator.language, ...navigator.languages];
170
- // React Native:
171
- const clientLocalesRN = getLocales().map(({ languageTag }) => languageTag);
172
-
173
- // A loader function to fetch translations for a given locale:
174
- const loadLocale = async (locale: string) => {
175
- if (locale === 'ja_JP') {
176
- return (await import('./translations/ja_JP.json')).default.ja_JP;
177
- }
178
-
179
- return {};
89
+ ```js
90
+ export default {
91
+ experimental: {
92
+ swcPlugins: [
93
+ [
94
+ '@nkzw/swc-plugin-fbtee',
95
+ {
96
+ fbtCommon: {
97
+ Accept: 'Button label for accepting terms',
98
+ },
99
+ fbtEnumManifest: {},
100
+ },
101
+ ],
102
+ ],
103
+ },
180
104
  };
181
-
182
- const LocaleContext = createLocaleContext({
183
- availableLanguages,
184
- clientLocales: clientLocalesWeb, // or clientLocalesRN for React Native
185
- loadLocale,
186
- });
187
-
188
- // Now wrap your app with `LocaleContext`:
189
- const MyAppEntryPoint = () => (
190
- <LocaleContext>
191
- <App />
192
- </LocaleContext>
193
- );
194
105
  ```
195
106
 
196
- If you need to access the current locale or set the locale, you can use the `useLocaleContext` hook:
197
-
198
- ```tsx
199
- import { useLocaleContext } from 'fbtee';
107
+ Use the SWC plugin to compile app code. Use `fbtee collect` to extract phrases. Do not pass `collectFbt: true` to the SWC plugin.
200
108
 
201
- const MyComponent = () => {
202
- const { locale, setLocale } = useLocaleContext();
109
+ ### TypeScript JSX Types
203
110
 
204
- return (
205
- <div>
206
- <p>Current Locale: {locale}</p>
207
- <button onClick={() => setLocale('ja_JP')}>Switch to Japanese</button>
208
- </div>
209
- );
210
- };
211
- ```
212
-
213
- Next up, if you are using React and TypeScript in your project, you need to add TypeScript types for **fbtee** to enable proper type checking in JSX. You can do this by referencing the `ReactTypes.d.ts` file in your main `index.tsx` file or a global type declaration file (e.g., `types.d.ts`):
111
+ React TypeScript projects should include the JSX declarations once in a global type file or app entry point:
214
112
 
215
113
  ```tsx
216
114
  /// <reference types="fbtee/ReactTypes.d.ts" />
217
115
  ```
218
116
 
219
- _You’re now ready to define your first translatable element!_
220
-
221
- ### Alternative Setup Methods
117
+ ## Writing Strings
222
118
 
223
- If you need to build your own locale context with custom functionality, you can use the `setupLocaleContext` function. It takes the same arguments as the `LocaleContext` component, but gives you full control over how you manage locales.
119
+ Every user-facing string should be wrapped in `<fbt>`, `fbt()`, or `fbs()`. Descriptions are required because they are the translator's context.
224
120
 
225
121
  ```tsx
226
- const { getLocale, setLocale } = setupLocaleContext({
227
- availableLanguages: AvailableLanguages,
228
- clientLocales,
229
- fallbackLocale,
230
- hooks,
231
- loadLocale,
232
- translations,
233
- });
234
-
235
- // Now you can call `getLocale` and `setLocale` anytime, even outside of React components.
236
- if (getLocale() === 'en_US') {
237
- setLocale('ja_JP'); // Switch to Japanese locale
238
- }
122
+ <fbt desc="Empty state title when a project has no tasks">No tasks yet</fbt>
239
123
  ```
240
124
 
241
- A full example of using `setupLocaleContext` to build your own `LocaleContext` abstraction can be found in the [Athena Crisis](https://github.com/nkzw-tech/athena-crisis/blob/main/hera/i18n/LocaleContext.tsx#L41) repository.
242
-
243
- ### Gender Variations
244
-
245
- `createLocaleContext` and `setupLocaleContext` also support setting the user's gender:
125
+ Use `fbt()` outside JSX:
246
126
 
247
127
  ```tsx
248
- createLocaleContext({
249
- …
250
- gender: 'female', // 'male', 'female' or 'unknown' are supported.
251
- });
128
+ import { fbt } from 'fbtee';
129
+
130
+ const title = fbt(
131
+ 'No tasks yet',
132
+ 'Empty state title when a project has no tasks',
133
+ );
252
134
  ```
253
135
 
254
- If you need to adjust the user's gender dynamically, you can use the `setGender` function provided by the `useLocaleContext` hook:
136
+ Use `fbs()` when you need a plain string:
255
137
 
256
138
  ```tsx
257
- import { useLocaleContext } from 'fbtee';
139
+ import { fbs } from 'fbtee';
258
140
 
259
- const GenderSelector = () => {
260
- const { gender, setGender } = useLocaleContext();
261
-
262
- return (
263
- <div>
264
- <button onClick={() => setGender('male')}>
265
- <fbt desc="Male gender">Male</fbt>
266
- </button>
267
- <button onClick={() => setGender('female')}>
268
- <fbt desc="Female gender">Female</fbt>
269
- </button>
270
- <button onClick={() => setGender('unknown')}>
271
- <fbt desc="Unknown gender">Unknown</fbt>
272
- </button>
273
- </div>
274
- );
275
- };
141
+ <input
142
+ placeholder={fbs('Search projects', 'Project search input placeholder')}
143
+ />;
276
144
  ```
277
145
 
278
- #### Full Customization
146
+ ## Dynamic Content
279
147
 
280
- Finally, if you are using something other than React, or need even more control over how **fbtee** is configured, you can use the `setupFbtee` function. This function allows you to set up **fbtee** with custom hooks and translations:
148
+ Use `<fbt:param>` for dynamic values. Token names should describe the value, not its current English position.
281
149
 
282
150
  ```tsx
283
- import { IntlVariations, setupFbtee } from 'fbtee';
284
- import translations from './translations.json';
285
-
286
- setupFbtee({
287
- hooks: {
288
- getViewerContext: () => ({
289
- GENDER: IntlVariations.GENDER_UNKNOWN,
290
- locale: 'en_US',
291
- }),
292
- },
293
- translations,
294
- });
151
+ <fbt desc="Greeting with the viewer name">
152
+ Hello, <fbt:param name="viewerName">{viewer.name}</fbt:param>!
153
+ </fbt>
295
154
  ```
296
155
 
297
- ### Usage with Next.js
298
-
299
- If you are using Next.js with App Router, check out the [Next.js App fbtee Example](https://github.com/cpojer/nextjs-fbtee-example). You'll need to set up a `<LocaleContext />` as a Client Component, and call `setupFbtee` in the root layout of your app for Server Component support.
300
-
301
- When using Next.js with **fbtee**, translated strings are inserted when your Server Components are rendered. This means that changing locales on the client will not automatically update the Server Component's translated strings. To handle locale changes, you need to call a server action that updates the locale, and then re-render your app with the new locale, for example by reloading the page.
302
-
303
- If you are exclusively using **fbtee** within Client Components, you can handle locale changes directly on the client only.
156
+ React elements inside `<fbt>` are automatically turned into implicit params:
304
157
 
305
- ## Usage
158
+ ```tsx
159
+ <fbt desc="Greeting with a linked viewer name">
160
+ Hello, <UserLink user={viewer} />!
161
+ </fbt>
162
+ ```
306
163
 
307
- _If you want to learn by example, check out the [examples](https://github.com/nkzw-tech/fbtee/tree/main/example) directory. You can also check out [Athena Crisis](https://github.com/nkzw-tech/athena-crisis), a large open source video game using **fbtee**_
164
+ Use `fbt.sameParam()` or `<fbt:same-param>` when the same token appears more than once.
308
165
 
309
- With **fbtee**, all strings must be wrapped using `<fbt>` (for React/JSX) or `fbt()` (for JavaScript). This ensures strings can be extracted and translated properly. The `desc` attribute is required and provides context for translators, helping them understand the intended meaning of the string.
166
+ ## Plurals
310
167
 
311
- Here are some basic examples:
168
+ Use `<fbt:plural>` when a count controls grammar. _fbtee_ handles locale-specific plural rules.
312
169
 
313
170
  ```tsx
314
- const Greeting = () => <div>Hello, World!</div>;
171
+ <fbt desc="Inbox unread count">
172
+ You have{' '}
173
+ <fbt:plural
174
+ count={count}
175
+ many="unread messages"
176
+ name="unreadCount"
177
+ showCount="yes"
178
+ >
179
+ an unread message
180
+ </fbt:plural>
181
+ .
182
+ </fbt>
315
183
  ```
316
184
 
317
- You can wrap the string with `<fbt>`:
185
+ `showCount` can be `yes`, `ifMany`, or `no`.
186
+
187
+ ## Lists
188
+
189
+ Use `<fbt:list>` for locale-aware lists:
318
190
 
319
191
  ```tsx
320
- const Greeting = () => (
321
- <div>
322
- <fbt desc="Greeting">Hello, World!</fbt>
323
- </div>
324
- );
192
+ <fbt desc="People assigned to a task">
193
+ Assigned to <fbt:list items={assignees} name="assigneeList" />.
194
+ </fbt>
325
195
  ```
326
196
 
327
- `<fbt>` is a special React component that marks text for translation. The **fbtee** compiler analyzes them to extract strings, and compiles them into an Intermediate Representation (IR). Here is a more complex example of what you can do with **fbtee**:
197
+ The standalone `list()` helper is available for non-React code:
328
198
 
329
199
  ```tsx
330
- <fbt desc="Feed item">
331
- <fbt:list items={users} name="userList" />{' '}
332
- won the game against
333
- <fbt:plural count={bots} many="bots" name="numberOfBots" showCount="ifMany">
334
- a bot
335
- </fbt:plural> on the map
336
- <fbt:param name="mapName">{game.mapName}</fbt:param>.
337
- </fbt:plural>
338
- // Example Output: "Alice, Bob and Charlie won the game against 2 bots on the map Forest Battle."
200
+ import { list } from 'fbtee';
201
+
202
+ const names = list(['Alice', 'Bob', 'Charlie'], 'or', 'comma');
339
203
  ```
340
204
 
341
- _Note: `<fbt>` is auto-imported for you by the `@nkzw/babel-preset-fbtee` plugin._
205
+ ## Enums
342
206
 
343
- This example highlights several features of **fbtee**:
207
+ Use enums when runtime values map to a fixed set of translatable labels:
344
208
 
345
- - `<fbt:list>`: Renders a list of items, automatically handling conjunctions and delimiters.
346
- - `<fbt:plural>`: Handles singular and plural forms based on a count value.
347
- - `<fbt:param>`: Allows you to insert dynamic content into your strings, such as variables or React components.
209
+ ```tsx
210
+ const StatusLabels = {
211
+ done: 'done',
212
+ open: 'open',
213
+ };
348
214
 
349
- With the above components, you can handle complex strings that are translatable into multiple languages while maintaining clarity and context for translators. This sentence structure supports many variations, such as "Alice is playing on Forest Battle.", or "Alice, Bob and Charlie are playing on Giant Crisis".
215
+ <fbt desc="Task status label">
216
+ This task is <fbt:enum enum-range={StatusLabels} value={status} />.
217
+ </fbt>;
218
+ ```
350
219
 
351
- Let's look at each of these features in detail:
220
+ For shared enum modules, use the `$FbtEnum` suffix so the collector can resolve them.
352
221
 
353
- ### Dynamic Content
222
+ ## Pronouns and Gender
354
223
 
355
- **fbtee** supports dynamic content through <fbt:param> or by using other React components within your text. For example, if you want to greet a specific user based on a name passed as a prop, you can use `<fbt:param>`:
224
+ Use `<fbt:pronoun>` when a phrase depends on a person's gender:
356
225
 
357
226
  ```tsx
358
- const Greeting = ({ name }) => (
359
- <div>
360
- <fbt desc="Greeting">
361
- Hello, <fbt:param name="name">{name}</fbt:param>!
362
- </fbt>
363
- </div>
364
- );
227
+ <fbt desc="Photo sharing notification">
228
+ <fbt:param name="name">{user.name}</fbt:param> shared{' '}
229
+ <fbt:pronoun gender={user.gender} human type="possessive" /> photo.
230
+ </fbt>
365
231
  ```
366
232
 
367
- **fbtee** allows you to use regular React Components inside of `<fbt>` which will automatically create `<fbt:param>` calls for you:
368
-
369
- ```tsx
370
- const Greeting = ({ name }) => (
371
- <div>
372
- <fbt desc="Greeting">
373
- Hello, <Name name={name} />!
374
- </fbt>
375
- </div>
376
- );
377
- ```
233
+ Supported pronoun types are `subject`, `object`, `possessive`, and `reflexive`.
378
234
 
379
- ### Lists
235
+ ## Common Strings
380
236
 
381
- `<fbt:list>` is used to render a list of items with conjunctions and delimiters. It automatically handles the grammatical structure of the list based on the locale:
237
+ Common strings are reusable source strings with shared descriptions:
382
238
 
383
239
  ```tsx
384
- <fbt:list
385
- conjunction="or"
386
- delimiter="comma"
387
- items={['Alice', 'Bob', <CharlieNameExampleComponent key="charlieUserID" />]}
388
- name="userList"
389
- /> // "Alice, Bob, or Charlie"
240
+ <fbt common>Save</fbt>
390
241
  ```
391
242
 
392
- The default conjunction is "and", and the default delimiter is "comma". You can use "or" or "none" as conjunction, and "bullet", "comma", or "semicolon" as delimiters. The `name` attribute is required to provide context for translators. **fbtee** also exports a `list` function that can be used in contexts outside of React:
393
-
394
- ```tsx
395
- import { list } from 'fbtee';
243
+ Pass common strings to the compiler as `fbtCommon`:
396
244
 
397
- const userList = list(['Alice', 'Bob', 'Charlie'], 'or', 'comma');
245
+ ```js
246
+ {
247
+ fbtCommon: {
248
+ Save: 'Button label for saving changes',
249
+ },
250
+ }
398
251
  ```
399
252
 
400
- ### Singular & Plural Forms
253
+ ## Runtime Setup
401
254
 
402
- **fbtee** supports singular and plural forms using the `<fbt:plural>` component. While in English, the plural form is often just an "s" at the end of a word, in other languages, it can be more complex. **fbtee** handles this automatically based on the count value you provide. Here's an example:
255
+ Most React apps should use `createLocaleContext`:
403
256
 
404
257
  ```tsx
405
- <fbt desc="end turn confirmation">
406
- Do you want to play against
407
- <fbt:plural count={bots} many="bots" name="numberOfBots" showCount="ifMany">
408
- a bot
409
- </fbt:plural>?
410
- </fbt>
411
- ```
258
+ import { createLocaleContext } from 'fbtee';
412
259
 
413
- This sentence might be translated to one of the following variations:
260
+ const availableLanguages = new Map([
261
+ ['en-US', 'English'],
262
+ ['de-DE', 'Deutsch'],
263
+ ['ja-JP', '日本語'],
264
+ ]);
414
265
 
415
- - "Do you want to play against 1 bot?"
416
- - "Do you want to play against 2 bots?"
266
+ const loadLocale = async (locale: string) => {
267
+ switch (locale) {
268
+ case 'de-DE':
269
+ return (await import('./translations/de-DE.json')).default['de-DE'];
270
+ case 'ja-JP':
271
+ return (await import('./translations/ja-JP.json')).default['ja-JP'];
272
+ default:
273
+ return {};
274
+ }
275
+ };
417
276
 
418
- `<fbt:plural>` expects the singular phrase as children, and an item `count` as prop. You can provide the plural form using the `many` prop. The `showCount` prop can be used to control whether the count should be displayed in the string. `ifMany` only shows the count in the plural case, while `yes` shows it in all cases, and `no` hides it completely. The `name` prop is required to provide context for translators.
277
+ const LocaleContext = createLocaleContext({
278
+ availableLanguages,
279
+ clientLocales: [navigator.language, ...navigator.languages],
280
+ loadLocale,
281
+ });
419
282
 
420
- ### Using Pronouns
283
+ export const Root = () => (
284
+ <LocaleContext>
285
+ <App />
286
+ </LocaleContext>
287
+ );
288
+ ```
421
289
 
422
- You can use `<fbt:pronoun>` to handle pronouns in your strings. This is particularly useful for gendered languages where the pronoun changes based on the subject:
290
+ Use `useLocaleContext` to read or change the locale:
423
291
 
424
292
  ```tsx
425
- <fbt desc="Photo sharing text">
426
- <fbt:param name="name">{user.name}</fbt:param>
427
- shared
428
- <fbt:pronoun type="possessive" gender={user.pronounGender} human />
429
- photo with you.
430
- </fbt>
293
+ import { useLocaleContext } from 'fbtee';
294
+
295
+ const LanguageButton = () => {
296
+ const { locale, setLocale } = useLocaleContext();
297
+ return <button onClick={() => setLocale('de-DE')}>{locale}</button>;
298
+ };
431
299
  ```
432
300
 
433
- ### Plain Text Usage
301
+ If you need full control, use `setupLocaleContext` or `setupFbtee` directly.
434
302
 
435
- In some situations, you may want to use **fbtee** to represent plain text strings without any React components, for example when using alert dialogs or HTML attributes like `placeholder`. For these situations, you can use the `fbs()` function, which is a subset of `fbt` that only supports plain text.
303
+ ### Next.js App Router
436
304
 
437
- ```tsx
438
- import { fbs } from 'fbtee';
305
+ For App Router, put the locale context in a Client Component. If you render translated strings in Server Components, call `setupFbtee` on the server and re-render the route when the locale changes. Client-only strings can switch locale fully on the client.
439
306
 
440
- <input
441
- type="text"
442
- placeholder={fbs('Enter your name', 'Placeholder for name input')}
443
- />;
444
- ```
307
+ See the [Next.js fbtee example](https://github.com/cpojer/nextjs-fbtee-example) for a complete setup.
445
308
 
446
- ### Extracting Strings & Translating
309
+ ## Translation Workflow
447
310
 
448
- After marking your strings for translation with `<fbt>`, run the following commands to extract, and compile translations:
311
+ Extract source strings:
449
312
 
450
313
  ```bash
451
314
  pnpm fbtee collect
452
315
  ```
453
316
 
454
- You can now upload the `source_strings.json` file to your translation provider, for example [Crowdin](https://crowdin.com/). If you'd like to manually edit the strings, you can use the `fbtee prepare-translations --locales de_DE` to generate a JSON file that can be edited directly. Pass `--sort-by-hash` to keep entries in a deterministic order for cleaner diffs when the file is committed.
317
+ This writes `source_strings.json`.
455
318
 
456
- #### Generated File Structure
319
+ Prepare editable translation files:
457
320
 
458
- Your `source_strings.json` might look like this:
459
-
460
- ```json
461
- {
462
- "childParentMappings": {},
463
- "phrases": [
464
- {
465
- "hashToLeaf": {
466
- "MB6OYuvCF1VzjOmqinI42g==": {
467
- "desc": "What's next question",
468
- "text": "What's next?"
469
- }
470
- },
471
- "col_beg": 12,
472
- "col_end": 68,
473
- "filepath": "app/welcome/welcome.tsx",
474
- "line_beg": 43,
475
- "line_end": 43,
476
- "project": "",
477
- "jsfbt": {
478
- "m": [],
479
- "t": {
480
- "desc": "What's next question",
481
- "text": "What's next?"
482
- }
483
- }
484
- }
485
- ]
486
- }
487
- ```
488
-
489
- Based on the above source string, the US English translation (ie. `translations/en_US.json`) might look like this:
490
-
491
- ```json
492
- {
493
- "fb-locale": "en_US",
494
- "translations": {
495
- "MB6OYuvCF1VzjOmqinI42g==": {
496
- "tokens": [],
497
- "types": [],
498
- "translations": [
499
- {
500
- "translation": "What's next?",
501
- "variations": []
502
- }
503
- ]
504
- }
505
- }
506
- }
321
+ ```bash
322
+ pnpm fbtee prepare-translations --source-strings source_strings.json --output-dir translations --locales de-DE fr-FR ja-JP
507
323
  ```
508
324
 
509
- And German (`translations/de_DE.json`) might look like this:
510
-
511
- ```json
512
- {
513
- "fb-locale": "de_DE",
514
- "translations": {
515
- "MB6OYuvCF1VzjOmqinI42g==": {
516
- "tokens": [],
517
- "types": [],
518
- "translations": [
519
- {
520
- "translation": "Was kommt jetzt?",
521
- "variations": []
522
- }
523
- ]
524
- }
525
- }
526
- }
527
- ```
325
+ `prepare-translations` merges source strings into existing locale files, preserves translated entries, and marks new work with `"status": "new"`. New files use BCP 47 locale identifiers by default, such as `de-DE.json` and `es-419.json`.
528
326
 
529
- Once you have the translated strings stored in a `translations/` folder as JSON files using the locale name, for example `en_US.json` or `de_DE.json`, you can run the following command to generate the translations for use in your app:
327
+ Compile translations for the app:
530
328
 
531
329
  ```bash
532
- pnpm fbtee translate
330
+ pnpm fbtee translate --source-strings source_strings.json --translations 'translations/*.json' --output-dir src/translations
533
331
  ```
534
332
 
535
- By default, **fbtee** outputs the generated translations in `src/translations`. It will create one JSON file per locale. For example, if you have `translations/en_US.json` and `translations/de_DE.json`, it will generate `src/translations/en_US.json` and `src/translations/de_DE.json`. These files are an optimized representation of your translation file, ready to be used in your app:
333
+ fbtee accepts both modern BCP 47 locale identifiers (`de-DE`, `es-419`) and legacy Facebook-style identifiers (`de_DE`, `es_LA`). If both aliasing files exist, for example `translations/de_DE.json` and `translations/de-DE.json`, fbtee throws and asks you to keep one. Existing legacy files are updated in place; new generated files default to BCP 47. To force a specific output style, pass `--output-locale-style=bcp47`, `--output-locale-style=legacy`, or `--output-locale-style=preserve`.
536
334
 
537
- ```json
538
- {
539
- "de_DE": {
540
- "2HVYhv": "Was kommt jetzt?"
541
- }
542
- }
543
- ```
335
+ To migrate editable translation files and generated runtime files to BCP 47 names:
544
336
 
545
- After generating the translation files, your app is ready to display translated content in other languages. Since the `src/translations` folder is auto-generated, it should be ignored by version control and be part of your build process.
337
+ ```bash
338
+ pnpm fbtee migrate-locales --to bcp47 --dir translations --dir src/translations
339
+ pnpm fbtee translate --output-locale-style=bcp47
340
+ ```
546
341
 
547
- ## Setting the initial locale
342
+ Use `--dry-run` first to preview file renames.
548
343
 
549
- If you know the user's locale ahead of time, you can set it when creating the `LocaleContext` by passing the locale as the first item in the `clientLocales` array:
344
+ Commit the human-authored translation files. Ignore generated runtime output:
550
345
 
551
- ```tsx
552
- // Read the user locale from localStorage etc.
553
- const userLocale = localStorage.getItem('locale');
554
- const LocaleContext = createLocaleContext({
555
- availableLanguages,
556
- clientLocales: [userLocale, navigator.language, ...navigator.languages],
557
- loadLocale,
558
- });
346
+ ```gitignore
347
+ .enum_manifest.json
348
+ source_strings.json
349
+ src/translations/
559
350
  ```
560
351
 
561
- Note that if you are picking the locale ahead of time like this, you need to manually load the translations. This is because the `loadLocale` function is only called when the locale changes, and not when the context is first created. This gives you full control over your app's startup:
352
+ ## Translating Strings with Coding Agents
562
353
 
563
- ```tsx
564
- const loadLocale = async (locale: string) => {
565
- if (locale === 'ja_JP') {
566
- return (await import('./translations/ja_JP.json')).default.ja_JP;
567
- }
568
- return {};
569
- };
354
+ Coding agents are great at updating _fbtee_ translation files because all the context is in the repository:
570
355
 
571
- const translations = {
572
- [userLocale]: await loadLocale(userLocale),
573
- };
574
-
575
- const LocaleContext = createLocaleContext({
576
- availableLanguages,
577
- clientLocales: [userLocale, navigator.language, ...navigator.languages],
578
- loadLocale,
579
- translations,
580
- });
581
- ```
356
+ 1. `fbtee prepare-translations` adds every missing translation and marks it with `"status": "new"`.
357
+ 1. The agent edits only entries with `"status": "new"`.
358
+ 1. The agent removes `"status": "new"` after the translation is complete.
359
+ 1. Code review shows a clean diff of the new localized strings.
582
360
 
583
- If you have to wait for data from your server to determine the user's locale, you can use the `setLocale` function provided by `useLocaleContext` to set the locale after the initial render:
361
+ This works best when the app already has translated strings. The agent can infer tone, voice, capitalization, punctuation, and product vocabulary from the existing locale files.
584
362
 
585
- ```tsx
586
- import { useLocaleContext } from 'fbtee';
363
+ ### Coding Agent prompt:
587
364
 
588
- const Root = () => {
589
- // Fetch the locale from the server.
590
- const userLocale = useUserLocale();
591
- const { locale, setLocale } = useLocaleContext();
365
+ ```md
366
+ Run `fbtee prepare-translations --source-strings source_strings.json --output-dir ares/translations --locales de-DE fr-FR ja-JP pl-PL ru-RU zh-CN es-ES it-IT ko-KR pt-BR uk-UA` for all the translations the app supports.
592
367
 
593
- useEffect(() => {
594
- if (locale !== userLocale) {
595
- setLocale(userLocale);
596
- }
597
- }, [locale, setLocale, userLocale]);
368
+ Look at all updated translation files. For every entry with `"status": "new"`, write a translation that matches the tone, voice, and language already used in the app and in the current locale.
598
369
 
599
- return children;
600
- };
370
+ Remove `"status": "new"` from each completed translation entry.
601
371
  ```
602
372
 
603
- ## ESLint Plugin
373
+ ## ESLint
604
374
 
605
- You can install the optional ESLint plugin to catch common mistakes and enforce best practices when using **fbtee**:
375
+ Install the optional ESLint plugin:
606
376
 
607
377
  ```bash
608
378
  npm install -D @nkzw/eslint-plugin-fbtee
609
379
  ```
610
380
 
611
- Add the following configuration to your ESLint configuration:
381
+ Use the recommended config:
612
382
 
613
383
  ```js
614
384
  import fbtee from '@nkzw/eslint-plugin-fbtee';
615
385
 
616
- export default [
617
- fbtee.configs.recommended,
618
- {
619
- plugins: {
620
- '@nkzw/fbtee': fbtee,
621
- },
622
- },
623
- ];
386
+ export default [fbtee.configs.recommended];
624
387
  ```
625
388
 
626
- If you want stricter enforcement of translation rules, you can use the strict configuration, which enables the `no-untranslated-strings` rule. This ensures that all strings in your codebase are marked for translation.
389
+ Use the strict config if you want every user-facing string to be wrapped:
627
390
 
628
391
  ```js
629
392
  import fbtee from '@nkzw/eslint-plugin-fbtee';
630
393
 
631
- export default [
632
- fbtee.configs.strict,
633
- {
634
- plugins: {
635
- '@nkzw/fbtee': fbtee,
636
- },
637
- },
638
- ];
394
+ export default [fbtee.configs.strict];
639
395
  ```
640
396
 
641
- Alternatively, if you'd like more granular control over the rules:
642
-
643
- ```js
644
- import fbtee from '@nkzw/eslint-plugin-fbtee';
645
-
646
- export default [
647
- fbtee,
648
- {
649
- plugins: {
650
- '@nkzw/fbtee': fbtee,
651
- },
652
- rules: {
653
- '@nkzw/fbtee/no-empty-strings': [
654
- 'error',
655
- {
656
- ignoredWords: ['Banana', 'pnpm install fbtee'],
657
- },
658
- ],
659
- '@nkzw/fbtee/no-unhelpful-desc': 'error',
660
- '@nkzw/fbtee/no-untranslated-strings': 'error',
661
- },
662
- },
663
- ];
664
- ```
665
-
666
- ## What's better about `fbtee` than `fbt`?
667
-
668
- Facebook has done an amazing job with `fbt`, an internationalization library that has been successfully used in production at Facebook for over 10 years. Their work provided a strong foundation for modern localization tools.
669
-
670
- The open-source version of `fbt`, however, became unmaintained, difficult to set up, and incompatible with modern tools. It was eventually archived in November 2024. **fbtee** builds on this foundation with several improvements:
671
-
672
- - **Easier Setup:** fbtee works with modern tools like Vite.
673
- - **Statically Typed:** The fbtee compiler ensures correct usage of fbtee, library TypeScript types are provided, and an eslint plugin helps fix common mistakes.
674
- - **Improved React Compatibility:** Removed React-specific hacks and added support for implicit React fragments (`<>`).
675
- - **Enhanced Features:** Fixed and exported `intlList` as a new `<fbt:list>` construct, which was not functional in the original `fbt`.
676
- - **Modernized Codebase:** Rewritten using TypeScript, ES modules (ESM), eslint, and modern JavaScript standards. Removed cruft and legacy code.
677
- - **Updated Tooling:** Uses modern tools like pnpm, Vite, and esbuild for faster and more efficient development of **fbtee**.
678
-
679
- **fbtee** remains compatible with `fbt` and migration is straightforward.
397
+ ## Migration from fbt
680
398
 
681
- ## Migration from `fbt`
399
+ _fbtee_ is compatible with the core `fbt` programming model:
682
400
 
683
- **fbtee** is compatible with `fbt`. If you are already using `fbt`, migrating to fbtee is straightforward:
401
+ 1. Replace `fbt` packages with `fbtee` and the matching compiler package.
402
+ 1. Replace imports from `fbt` with imports from `fbtee`.
403
+ 1. Use `fbtee collect`, `fbtee prepare-translations`, and `fbtee translate`.
404
+ 1. Convert CommonJS common strings or enum modules to ESM when needed.
405
+ 1. Replace legacy setup calls with `setupFbtee`, `createLocaleContext`, or `setupLocaleContext`.
684
406
 
685
- - Follow the "Getting Started" guide above and remove all "fbt" related packages.
686
- - Make sure you are using React 19.
687
- - Replace `import { fbt } from 'fbt'` with `import { fbt } from 'fbtee'`.
688
- - Rename commands from `fbt-collect`, and `fbt-translate` to `fbtee-collect`, and `fbtee-translate`. `fbt manifest` was removed and `fbtee collect` now handles this step automatically.
689
- - If you were using CommonJS modules for common strings or enums, convert them to ES modules.
690
- - Ensure you are using the latest version of Node.js 22 or later.
691
- - Rename your `init({})` call to `setupFbtee({})`.
407
+ Some archived `fbt` options and legacy behaviors were intentionally removed. The compiler errors should point to the modern replacement when one exists.
692
408
 
693
- After these changes, your project should work seamlessly with **fbtee**.
409
+ ## Examples
694
410
 
695
- _Note: Some legacy behavior and options were removed from `fbtee`. If you have a complex setup, please consider [reaching out to us for help](mailto:fbtee@nakazawa.dev)._
411
+ - [Example App](https://github.com/nkzw-tech/fbtee/tree/main/example)
412
+ - [Next.js App Router Example](https://github.com/cpojer/nextjs-fbtee-example)
413
+ - [Athena Crisis](https://github.com/nkzw-tech/athena-crisis)
696
414
 
697
415
  ## Credits
698
416
 
699
417
  - `fbt` was originally created by [Facebook](https://github.com/facebook/fbt).
700
418
  - The auto-import plugin was created by [@alexandernanberg](https://github.com/alexandernanberg).
701
- - [Nakazawa Tech](https://nkzw.tech) rewrote `fbt` into `fbtee` and continues to maintain this project.
419
+ - [Nakazawa Tech](https://nkzw.tech) rewrote `fbt` into _fbtee_ and maintains this project.
package/lib/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ESLintUtils } from "@typescript-eslint/utils";
2
2
  //#region package.json
3
3
  var name = "@nkzw/eslint-plugin-fbtee";
4
- var version = "1.7.6";
4
+ var version = "2.0.0";
5
5
  //#endregion
6
6
  //#region src/utils.tsx
7
7
  const createRule = ESLintUtils.RuleCreator((name) => `https://github.com/nkzw-tech/fbtee/blob/main/packages/eslint-plugin-fbtee/docs/rules/${name}.md`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nkzw/eslint-plugin-fbtee",
3
- "version": "1.7.6",
3
+ "version": "2.0.0",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "repository": {