-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-Authored-By: John Bakhmat <johnbakhmat@gmail.com>
- Loading branch information
1 parent
51adb33
commit 4f5c462
Showing
3 changed files
with
287 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
# t-react | ||
|
||
> Seamless React integration for [`@wluwd/t`](https://github.com/wluwd/t) 🌐 | ||
## Install | ||
|
||
Using your favorite package manager, install: `@wluwd/t-react @wluwd/t-utils`. | ||
|
||
> [!NOTE] | ||
> You're not required to install `@wluwd/t-utils`, but we recommend it as a helpful starting point for additional utilities and features. | ||
The React adapter has two peer dependencies which you need to install: the first is `react` itself, the second is [`jotai`](https://jotai.org). | ||
|
||
> [!NOTE] | ||
> We will likely transition from Jotai to [Nano Stores](https://github.com/nanostores/nanostores) once [`use`](https://react.dev/reference/react/use) lands in a stable release. | ||
## Usage | ||
|
||
<!-- eslint-skip --> | ||
|
||
```ts | ||
// translations.ts | ||
import { defineTranslationsConfig } from "@wluwd/t-react"; | ||
import { browser, lazyTranslations, formatter } from "@wluwd/t-utils"; | ||
|
||
export const { | ||
setLocale, | ||
getLocale, | ||
useLocale, | ||
getTranslations, | ||
useTranslations, | ||
t, | ||
} = defineTranslationsConfig( | ||
{ | ||
"en-US": lazyTranslations(() => import("./en-us.ts")), | ||
"it-IT": lazyTranslations(() => import("./it-it.ts")), | ||
}, | ||
{ | ||
formatter, | ||
localeFrom: [browser(), "en-US"], | ||
}, | ||
); | ||
``` | ||
|
||
<!-- eslint-skip --> | ||
|
||
```tsx | ||
// article/published-by.tsx | ||
import { useTranslations, t } from "../translations.ts"; | ||
|
||
const PublishedBy = ({ name }) => { | ||
const heading = useTranslations("article.heading"); | ||
|
||
return <span>{t(heading.publishedBy, { name })}</span>; | ||
}; | ||
``` | ||
|
||
## API | ||
|
||
### `defineTranslationsConfig(loaders, options, lazy?)` | ||
|
||
Creates the functions and hooks needed to localize your React application. | ||
|
||
#### `loaders` | ||
|
||
Extends: `Record<Locale, () => Promise<Translations>>` | ||
|
||
An object whose keys will be used as the available locales and their values as loaders. | ||
|
||
We recommend using the [UTS 35](https://www.unicode.org/reports/tr35/#Locale_Extension_Key_and_Type_Data) definition of Unicode Locale Identifier for keys as this allows an easier integration with [negotiators](#localefrom). | ||
|
||
#### `options` | ||
|
||
- ##### `formatter` | ||
|
||
Extends: `(translation: string, data: any) => string` | ||
|
||
A function that replaces placeholders within a string using values from `data`. | ||
|
||
- ##### `localeFrom` | ||
|
||
Extends: `[] | [...LocaleNegotiator[], Locale]` | ||
|
||
An empty tuple, or a tuple with zero or more [`LocaleNegotiator`s](../t-utils) and, as the last element, one of `loaders`' keys. | ||
|
||
The negotiators are evaluated sequentially and the loop stops as soon as one returns a locale. | ||
|
||
- ##### `cache` | ||
|
||
Extends: `Partial<Record<Locale, Translations>>` | ||
|
||
An object that can have `loaders`' keys and the **loaded** translations for that locale. | ||
|
||
Instead of loading the translations when one of these locales is active, the value from this object will be used. | ||
|
||
#### `lazy` | ||
|
||
Extends: `boolean | undefined` | ||
|
||
When this is set to `true`, initiates the translator in _lazy mode_. | ||
|
||
Alongside the other functions and hooks, `defineTranslationsConfig` will return an `init` function with the following signature: | ||
|
||
<!-- eslint-skip --> | ||
|
||
```ts | ||
type Init = (negotiators?: LocaleNegotiators<Locale>) => void; | ||
``` | ||
|
||
You **have to** call this function manually before using any of the other functions. | ||
|
||
It's possible to pass a list of locale negotiators that will override the ones provided in `options`, if no negotiators are provided here, the ones provided in `options` will be used. | ||
|
||
This is useful when a user's preferred locale comes from an HTTP request or a DB query. | ||
|
||
--- | ||
|
||
Other than the `init` function described above, `defineTranslationsConfig` returns the following functions and hooks. | ||
|
||
### `setLocale(locale)` | ||
|
||
Sets the active locale to the provided one. | ||
|
||
### `getLocale()` | ||
|
||
A function that returns the active locale. | ||
|
||
This function is not reactive and it's **not meant for use in _client_ components**. | ||
|
||
### `useLocale()` | ||
|
||
A hook that returns the active locale. | ||
|
||
### `getTranslations(prefix)` | ||
|
||
An `async` function that returns a slice of the active translations. | ||
|
||
This function is not reactive and it's **not meant for use in _client_ components**. | ||
|
||
### `useTranslations(prefix)` | ||
|
||
A hook that returns a slice of the active translations. | ||
|
||
This hook triggers a `Suspense`. | ||
|
||
### `t(translation, data?)` | ||
|
||
[`formatter`](#formatter), returned for convenience. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
# t-utils | ||
|
||
> Smart utilities that turn translation challenges into smooth solutions ❤️🔥 | ||
## Install | ||
|
||
Using your favorite package manager, install: `@wluwd/t-utils`. | ||
|
||
## API | ||
|
||
### `formatter(translation, data?)` | ||
|
||
Generates a formatted string by replacing placeholders with values from the provided `data`. | ||
|
||
Placeholders, denoted by `{{` and `}}`, indicate the locations where replacement will occur. The content within the curly braces must correspond to a mandatory key in the `data` object. | ||
|
||
**Example:** | ||
|
||
<!-- eslint-skip --> | ||
|
||
```ts | ||
const translation = "Hello, {{name}}! Welcome to {{city}}."; | ||
const data = { | ||
name: "John", | ||
city: "New York", | ||
}; | ||
|
||
formatter(translation, data); // -> "Hello, John! Welcome to New York." | ||
``` | ||
|
||
### `lazyTranslations(loader)` | ||
|
||
Lazy loads translations using the provided loader function and returns the `default` import value. | ||
|
||
The loader function should be an asynchronous function that imports a translation module and returns a promise. The `default` import of the module is then returned by `lazyTranslations` once it's resolved. | ||
|
||
**Example:** | ||
|
||
<!-- eslint-skip --> | ||
|
||
```ts | ||
lazyTranslations(async () => ({ | ||
default: { | ||
some: "string", | ||
}, | ||
})); // -> Promise<{ some: "string" }>; | ||
``` | ||
|
||
### `browser()` | ||
|
||
A locale negotiator that automatically uses the browser's preferred languages obtained from `navigator.languages`. | ||
|
||
This negotiator is useful for scenarios where you want to set the default locale based on the user's browser language preferences. | ||
|
||
**Example:** | ||
|
||
<!-- eslint-skip --> | ||
|
||
```ts | ||
import { defineTranslationsConfig } from "@wluwd/t-[adapter]"; | ||
import { browser } from "@wluwd/t-utils"; | ||
|
||
defineTranslationsConfig( | ||
{ | ||
// loaders | ||
}, | ||
{ | ||
localeFrom: [ | ||
browser(), | ||
// fallback locale | ||
], | ||
// ... other options | ||
}, | ||
); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
# t | ||
|
||
> A lightweight, unopinionated, framework-agnostic, and type-safe localization library 🌐 | ||
[![badge for the default branch's pipeline status](https://github.com/wluwd/t/actions/workflows/ci.yml/badge.svg?branch=trunk)](https://github.com/wluwd/t/actions/workflows/ci.yml) | ||
|
||
## Features | ||
|
||
- 📦 **Type-safety**: no generators needed when using TypeScript files; bidirectional reference search (`Go to Definition` and `Go to References` for each translation), autocomplete, mandatory placeholders, and more. | ||
- 🦺 **Safe**: catch bugs early, it throws on common error scenarios like: | ||
- setting an unknown fallback locale; | ||
- using translations before a locale is set; | ||
- using translations after setting an unknown locale. | ||
- 🫧 **Unopinionated:** we strive to offer the best experience possible when using our utilities, but you can bring your own: | ||
- formatter - so that you can write your translations in whatever format you like! | ||
- translations - as long as you provide types and a loader, they'll work! | ||
- ✨ **No boilerplate**: start using this library with minimal effort. | ||
|
||
## Getting Started | ||
|
||
There's something important you need to know: `@wluwd/t` is a factory that provides a common interface and does the heavy lifting to provide working types. In most cases, you won't need to interact with this package directly; instead, you'll want to choose an **adapter** that suits your needs. | ||
|
||
You have two options: | ||
|
||
- #### Build Your Own Adapter | ||
|
||
If you have specific requirements or preferences, you can create a custom adapter. Check out the [documentation](packages/t) for guidance on building your own. | ||
|
||
- #### Use an Official Adapter | ||
|
||
We provide official adapters to simplify the integration process. Choose an adapter that aligns with your project's needs. | ||
|
||
Here are the links to every adapter we maintain: | ||
|
||
- [`@wluwd/t-react`](packages/t-react) | ||
|
||
> [!TIP] | ||
> Thoroughly read the documentation for the selected adapter. | ||
Here's a glimpse of what your code could look like: | ||
|
||
<!-- eslint-skip --> | ||
|
||
```ts | ||
import { defineTranslationsConfig } from "@wluwd/t-[adapter]"; | ||
import { browser, lazyTranslations, formatter } from "@wluwd/t-utils"; | ||
|
||
export const { setLocale, useLocale, useTranslations, t } = | ||
defineTranslationsConfig( | ||
{ | ||
"en-US": lazyTranslations(() => import("./en-us.ts")), | ||
"it-IT": lazyTranslations(() => import("./it-it.ts")), | ||
}, | ||
{ | ||
localeFrom: [browser(), "en-US"], | ||
formatter, | ||
}, | ||
); | ||
``` | ||
|
||
## Acknowledgements | ||
|
||
- [Nano Stores i18n](https://github.com/nanostores/i18n) for inspiring the `cache`, `localeFrom`, and negotiator API. | ||
- [fluent.js team](https://github.com/projectfluent/fluent.js) for providing an awesome locale negotiating algorithm. |