Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions docs-templates/api/components/t.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@ Make sure to follow the [deployment guide here](__DOCS_PATH__/tutorials/quickdep
type: 'any',
optional: false,
},
"id": {
"id?": {
type: 'string',
optional: false,
optional: true,
default: 'undefined',
},
"context?": {
type: 'string',
Expand All @@ -59,14 +60,14 @@ Make sure to follow the [deployment guide here](__DOCS_PATH__/tutorials/quickdep
| Prop | Description |
|-----------------|-------------------------------------------------------------------------------------------------|
| `children` | The content to be translated. This can include plain text or JSX structures. |
| `id` | A unique identifier for the translation string. This ensures consistent translation across your app. |
| `id` | An optional identifier for the translation, sent to the GT platform as descriptive metadata. It does not affect how translations are looked up. |
| `context` | Additional context to refine the translation. Useful for resolving ambiguous phrases. |
| `requiresReview` | When `true`, the translation is withheld from serving until it is approved in a human-review step. Must be a boolean literal. `$requiresReview` is an equivalent alias. |

### Returns


`React.JSX.Element|undefined` which contains the rendered translation or fallback content based on the provided configuration.
`React.JSX.Element|undefined` which contains the rendered translation, or the source content when no translation is available.

---

Expand All @@ -83,12 +84,13 @@ If a translation is not found, it will fallback to the original content.
Make sure to follow the [deployment guide here](__DOCS_PATH__/tutorials/quickdeploy).

### Development
During development, the `<T>` function will translate content on demand.
During development, the `<T>` component will translate content on demand.
This is useful for prototyping what your app will look like in different languages.
Remember to add a Dev API key to your environment to enable this behavior.

While loading, `<T>` will return undefined unless languages are similar (en-US vs en-GB), though this behavior can be customized with render settings.
If an error occurs, `<T>` will return the original content.
`<T>` renders synchronously from the loaded translation snapshot.
While an updated translation is loading during hot reload, `<T>` keeps showing the previous output.
If no translation is available, `<T>` renders the original content.

You will see a delay during on-demand translation in development.
This delay will not occur in production builds as everything will already be translated.
Expand All @@ -99,7 +101,7 @@ This delay will not occur in production builds as everything will already be tra

### Basic usage

The `<T>` component can translate simple strings using an `id` and its children.
The `<T>` component translates its children.
Remember, the `<T>` component must be used inside a [`<GTProvider>`](__DOCS_PATH__/api/components/gtprovider) to access the translations.

```jsx title="SimpleTranslation.jsx" copy
Expand Down Expand Up @@ -218,6 +220,7 @@ export default function Example() {
* The `<T>` component is designed for translating content in your application. It is the primary method for localization in `__PACKAGE_NAME__`.
* Use the `<T>` component to translate plain text or JSX structures, including variables and pluralization.
* Ensure the `<T>` component is wrapped in a [`<GTProvider>`](__DOCS_PATH__/api/components/gtprovider) to access the translation context.
* Translations are looked up by a hash computed from the message content plus `context` and `maxChars` (and review metadata). The `id` prop does not change this hash; it is descriptive metadata sent to the GT platform.
* The `requiresReview` prop only accepts a boolean literal. Only the value `true` changes the content hash and withholds the translation until it is approved.

## Next steps
Expand Down
3 changes: 2 additions & 1 deletion docs-templates/api/config/gt-config-json.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ The `files.gt.parsingFlags` object controls how the compiler parses your source
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `enableAutoJsxInjection` | `boolean` | `false` | Automatically wrap translatable JSX text in translation components at build time. See [auto JSX injection](/docs/cli/features/auto-jsx-injection). |
| `autoderive` | `boolean` | `false` | Automatically treat interpolated values in `t()`, `gt()`, and `msg()` calls as [`derive()`](__DOCS_PATH__/api/strings/derive) calls. See [autoderive](/docs/cli/features/autoderive). |
| `autoderive` | `boolean \| { jsx?: boolean; strings?: boolean }` | `false` | Automatically treat interpolated values in `t()`, `gt()`, and `msg()` calls as [`derive()`](__DOCS_PATH__/api/strings/derive) calls. Pass an object to enable it selectively for JSX or strings. See [autoderive](/docs/cli/features/autoderive). |
| `legacyGtReactImportSource` | `boolean` | `false` | Emit compiler-injected imports from `gt-react/browser` instead of `gt-react`, for compatibility with older `gt-react` majors. |

```json title="gt.config.json"
{
Expand Down
27 changes: 20 additions & 7 deletions docs-templates/api/config/load-dictionary.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ description: API reference for the loadDictionary() function

`loadDictionary` will load a translation json file for a given locale.

This function is intended for those who which to use `__PACKAGE_NAME__` as a stand-alone i18n library.
This function is intended for those who wish to use `__PACKAGE_NAME__` as a stand-alone i18n library.

This function is primarily used to migrate existing projects with i18n to General Translation while keeping their existing translations.

`loadDictionary` only runs for non-default locales.
The default locale's dictionary must be available synchronously: bundle it with your app and pass it via the `dictionary` option.

If multiple translations exist, translations from dictionaries loaded by `loadDictionary` will always take precedence over others.
`loadDictionary` only supports the use of JSON files with string translations.
Expand Down Expand Up @@ -53,17 +55,27 @@ export default async function loadDictionary(locale) {
}
```

Then pass it to your `<GTProvider>` component:
Then pass it to `initializeGT()` at startup, along with the bundled default-locale dictionary.
It is not a `<GTProvider>` prop.

```jsx title="src/App.js"
import { GTProvider } from '__PACKAGE_NAME__';
```jsx title="src/index.js"
import { initializeGT } from '__PACKAGE_NAME__';
import dictionary from '../public/locales/en.json';
import loadDictionary from './loadDictionary';

<GTProvider loadDictionary={loadDictionary}>
<App />
</GTProvider>
initializeGT({
defaultLocale: 'en',
locales: ['en', 'es', 'fr'],
dictionary, // default-locale dictionary, bundled synchronously
loadDictionary, // loads dictionaries for non-default locales
});
```

<Callout type="info">
**Default locale:** `loadDictionary` is never called for the default locale.
Always pass the default-locale dictionary through the `dictionary` option so it is available synchronously.
</Callout>


<Callout>
**Question:** What's the difference between [`loadTranslations`](__DOCS_PATH__/api/config/load-translations) and [`loadDictionary`](__DOCS_PATH__/api/config/load-dictionary)?
Expand All @@ -79,6 +91,7 @@ import loadDictionary from './loadDictionary';

## Notes
* `loadDictionary` is used to load custom translations for your app.
* `loadDictionary` only runs for non-default locales. The default locale's dictionary comes from the `dictionary` option and must be available synchronously.
* Dictionaries loaded by `loadDictionary` will take precedence over translations loaded by [`loadTranslations`](__DOCS_PATH__/api/config/load-translations).

## Next steps
Expand Down
16 changes: 8 additions & 8 deletions docs-templates/api/config/load-translations.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,18 @@ A `Promise<any>` that resolves to either a string or JSX object containing the t

## Setup

You must import the `loadTranslations` function and assign it as a prop to the `<GTProvider>` component.
Import the `loadTranslations` function and pass it to `initializeGT()` at startup.
It is not a `<GTProvider>` prop.

```jsx title="src/index.js"
import { initializeGT } from '__PACKAGE_NAME__';
import loadTranslations from './loadTranslations';

createRoot(document.getElementById("root")!).render(
<StrictMode>
<GTProvider locales={['es', 'fr']} loadTranslations={loadTranslations}> // [!code highlight]
<App />
</GTProvider>
</StrictMode>
);
initializeGT({
defaultLocale: 'en',
locales: ['en', 'es', 'fr'],
loadTranslations, // [!code highlight]
});
```

---
Expand Down
43 changes: 32 additions & 11 deletions docs-templates/api/dictionary/use-translations.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,27 @@ t('greeting.hello'); // pass the id to get a translation

### Returns

A translation function `d` that, given an id, will return the translated version of the corresponding entry
A translation function `t` that, given an id, returns the translated version of the corresponding entry

```jsx
(id: string, options?: DictionaryTranslationOptions) => React.ReactNode
(id: string, options?: TranslationVariables) => string
```

| Name | Type | Description |
|-----------------------|--|-----------------------------------------------------------------------------|
| `id` | `string` | The id of the entry to be translated |
| `options?` | [`DictionaryTranslationOptions`](__DOCS_PATH__/api/types/dictionary-translation-options) | Translation options to customize the behavior of `d`. |
| `options?` | [`TranslationVariables`](__DOCS_PATH__/api/types/dictionary-translation-options) | Variables to interpolate into the translated entry. |

Metadata such as context does not go in the `t()` call.
Instead, it lives in the dictionary entry itself, e.g. `greeting: ['Hello!', { $context: 'a friendly greeting' }]`.

### Throws

`t(id)` and `t.obj(id)` throw an `Error` (`Dictionary entry ${id} cannot be found`) when the entry does not exist in the default locale's dictionary.
This applies in both development and production.

If the source entry exists but the current locale's translation is missing, `t` does not throw.
It falls back to the source entry, translating it at runtime in development when possible.

---

Expand All @@ -72,26 +83,33 @@ export default dictionary;
When we want to access these entries, we call `useTranslations`.
This returns a function that accepts the key of a translation from the dictionary.

You must pass the dictionary to the `GTProvider` component.
You must pass the dictionary to `initializeGT()` via the `dictionary` option.

```jsx title="src/index.js" copy
import { initializeGT } from '__PACKAGE_NAME__';
import dictionary from './dictionary';

initializeGT({
// ...your config
dictionary, // [!code highlight]
});
```

```jsx title="TranslateGreeting.jsx" copy
import { useTranslations } from '__PACKAGE_NAME__';
import dictionary from "./dictionary.json"

export default function TranslateGreeting() {
const t = useTranslations(); // [!code highlight]
return (
<GTProvider dictionary={dictionary}>
<p>
{t('greeting')} // [!code highlight]
</p>
</GTProvider>
<p>
{t('greeting')} // [!code highlight]
</p>
);
}
```

### Using variables [#variables]
In order to pass values, you must (1) assign an identifier and (2) reference the identifier when calling the `d` function.
In order to pass values, you must (1) assign an identifier and (2) reference the identifier when calling the `t` function.

In this example, we use `{}` to pass variables to the translations.
In the dictionary, we assign identifier `{userName}`.
Expand Down Expand Up @@ -152,5 +170,8 @@ export default function UserDetails() {
## Notes
* The `useTranslations` function allows you to access dictionary translations.
* The `useTranslations` hook can only be used within a component wrapped by a [`<GTProvider>` component](__DOCS_PATH__/api/components/gtprovider).
* The `t()` function throws when the requested entry is missing from the default locale's dictionary. Make sure every id you reference exists in the source dictionary.
* When only the current locale's translation is missing, `t()` falls back to the source entry instead of throwing.
* Entry metadata (`$context`, `$format`, `$maxChars`) belongs in the dictionary entry, not in the `t()` call.

## Next steps
2 changes: 1 addition & 1 deletion docs-templates/api/strings/msg.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ console.log(decodedString); // "Hello, world!"
| Name | Type | Description |
|-----------------------|--|-----------------------------------------------------------------------------|
| `content` | `string` | The string content to be encoded. |
| `options?` | [`InlineTranslationOptions`](__DOCS_PATH__/api/types/inline-translation-options) | Translation options to customize the behavior of `msg`. |
| `options?` | [`GTTranslationOptions`](__DOCS_PATH__/api/types/inline-translation-options) | Translation options to customize the behavior of `msg`. |

### Returns

Expand Down
19 changes: 2 additions & 17 deletions docs-templates/api/strings/use-gt.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ None
A callback function, `gt`, which translates the provided content.

```jsx
(content: string, options?: InlineTranslationOptions) => string
(content: string, options?: GTTranslationOptions) => string
```

| Name | Type | Description |
| ---------- | -------------------------------------------------------------------------------- | ----------------------------------------------------- |
| `content` | `string` | The string content to be translated. |
| `options?` | [`InlineTranslationOptions`](__DOCS_PATH__/api/types/inline-translation-options) | Translation options to customize the behavior of `gt`. |
| `options?` | [`GTTranslationOptions`](__DOCS_PATH__/api/types/inline-translation-options) | Translation options to customize the behavior of `gt`. |

---

Expand Down Expand Up @@ -124,21 +124,6 @@ export default function TranslateGreeting() {
documentation](https://unicode-org.github.io/icu/userguide/format_parse/messages/).
</Callout>

### Importing from `__PACKAGE_NAME__`

If operating under the `"use client"` directive, you should import from `__PACKAGE_NAME__` instead of `__PACKAGE_NAME__`.

```jsx copy
'use client';
import { useGT } from '__PACKAGE_NAME__';

export default function TranslateGreeting() {
const gt = useGT();

return <p>{gt('Hello, Alice!')}</p>;
}
```

---

## Notes
Expand Down
21 changes: 2 additions & 19 deletions docs-templates/api/strings/use-messages.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ None
A callback function, `m`, which translates the provided encoded content from `msg`.

```jsx
(encodedContent: string, options?: Record<string, any>) => string
(encodedContent: string, options?: GTTranslationOptions) => string
```

| Name | Type | Description |
| ---------------- | --------------------- | ------------------------------------------------------------ |
| `encodedContent` | `string` | The encoded string content from `msg` to be translated. |
| `options?` | `Record<string, any>` | Optional parameters to pass variables to the encoded string. |
| `options?` | [`GTTranslationOptions`](__DOCS_PATH__/api/types/inline-translation-options) | Translation options to customize the behavior of `m`. |

---

Expand Down Expand Up @@ -146,23 +146,6 @@ export default function TranslateGreeting() {
documentation](https://unicode-org.github.io/icu/userguide/format_parse/messages/).
</Callout>

### Importing from `__PACKAGE_NAME__`

If operating under the `"use client"` directive, you should import from `__PACKAGE_NAME__` instead of `__PACKAGE_NAME__`.

```jsx copy
'use client';
import { msg, useMessages } from '__PACKAGE_NAME__';

const encodedGreeting = msg('Hello, Alice!');

export default function TranslateGreeting() {
const m = useMessages();

return <p>{m(encodedGreeting)}</p>;
}
```

---

## Notes
Expand Down
Loading
Loading