Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: tolgee SDK v6 #793

Merged
merged 17 commits into from
Jan 8, 2025
Merged
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
75 changes: 75 additions & 0 deletions blog/2025-01-06-sdk-v6.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
---
slug: sdk-v6
title: 'Tolgee SDK Version 6 released!'
description: "Supercharge your localization with Tolgee SDK V6! Simplified Next.js integration, smarter translation fetching, and minimal breaking changes for a seamless transition!"
image: /img/blog/sdk-v6/SDK6-light.webp
authors: [sgranat]
tags: ['tolgee', 'sdk', 'release']
---

import ThemedImage from '@theme/ThemedImage';
import useBaseUrl from '@docusaurus/useBaseUrl';

<ThemedImage
alt="SDK v6"
sources={{
light: useBaseUrl(
'/img/blog/sdk-v6/SDK6-light.webp'
),
dark: useBaseUrl(
'/img/blog/sdk-v6/SDK6-dark.webp'
),
}}
/>

With Tolgee SDK Version 6, fetching translations for your Next.js applications is easier than ever. You can prefetch translation data on the server and seamlessly pass it to the client, ensuring smooth and efficient localization.

<!-- truncate-->

### Fetching Required Translations with `loadRequired`

The `loadRequired` method fetches translations based on the current language and namespace settings. Use it on the server to prefetch data and on the client to avoid extra fetches:

```ts
// Server-side
const translations = JSON.stringify(await tolgee.loadRequired());

// Client-side
tolgee.addStaticData(JSON.parse(translations));
```

This approach ensures the client has the translations ready without additional requests.
Check the [next.js integration guide](/js-sdk/integrations/react/next/app-router) to see how it's used.

### Advanced Prefetching with `loadMatrix`

For greater control, use `loadMatrix` to prefetch specific languages and namespaces.

```ts
// Fetch translations for multiple languages and namespaces
const translations = await tolgee.loadMatrix({
languages: ['en', 'cs'],
namespaces: ['common', 'info']
});
```

To prefetch all namespaces for a language:

```ts
await tolgee.loadMatrix({
languages: ['en'],
namespaces: 'all'
});
t('app_title', { ns: 'info' });
```

These tools make it simple to fetch and render translations, streamlining the localization process for server-rendered and server components.

## Breaking changes

Version 6 is just a mild update, so breaking changes are minimal.

Read the [migration guide](/js-sdk/migration_to_v6) to see what has changed.

[![React banner](/img/blog/blog-banners/banner-demo.webp)](https://app.tolgee.io/sign_up)

2 changes: 1 addition & 1 deletion docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const docs = [
versions: {
current: {
banner: 'none',
label: '5.x.x',
label: '6.x.x',
},
},
},
Expand Down
29 changes: 18 additions & 11 deletions js-sdk/api/core_package/events.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,64 +11,71 @@ Tolgee events which can be listened through `tolgee.on` method.
Emitted on language change.

```ts
tolgee.on('language', handler: ListenerHandler<string>)
tolgee.on('language', handler: Handler<LanguageEvent>)
```

### pendingLanguage

Emitted on language change. Before languages are loaded (when tolgee is running).

```ts
tolgee.on('pendingLanguage', handler: ListenerHandler<string>)
tolgee.on('pendingLanguage', handler: Handler<PendingLanguageEvent>)
```

### loading

Emitted on loading change. Changes when tolgee is loading some data for the first time.

```ts
tolgee.on('loading', handler: ListenerHandler<boolean>)
tolgee.on('loading', handler: Handler<LoadingEvent>)
```

### fetching

Emitted on fetching change. Changes when tolgee is fetching any data.

```ts
tolgee.on('fetching', handler: ListenerHandler<boolean>)
tolgee.on('fetching', handler: Handler<FetchingEvent>)
```

### initialLoad

Emitted when `run` method finishes.

```ts
tolgee.on('initialLoad', handler: ListenerHandler<void>)
tolgee.on('initialLoad', handler: Handler<InitialLoadEvent>)
```

### running

Emitted when internal `running` state changes.

```ts
tolgee.on('initialLoad', handler: ListenerHandler<boolean>)
tolgee.on('running', handler: Handler<RunningEvent>)
```

### cache

Emitted when cache changes.

```ts
tolgee.on('cache', handler: ListenerHandler<CacheDescriptorWithKey>)
tolgee.on('cache', handler: Handler<CacheEvent>)
```

### update

Emitted when any key needs (or might need) to be re-rendered. Similar to `tolgee.onNsUpdate`,
except we intercept all events, not just selection.
Emitted when any key needs (or might need) to be re-rendered. It's derrived from other events
(`initialLoad`, `language`, `cache`), the events are grouped when multiple happen at the same time,
so it only results to one `update` event being emitted.

```ts
tolgee.on('update', handler: ListenerHandler<void>)
tolgee.on('update', handler: CombinedHandler<UpdateEvent>)
```

You can check what events triggered this change event from the first argument of the handler.

```ts
tolgee.on('update', (events) => events.forEach(e => ...))
```

### error
Expand All @@ -79,6 +86,6 @@ Emitted when there is an error. You can intercept different types of errors, con
- `LanguageStorageError` - error when loading/saving language through language storage plugin

```ts
tolgee.on('error', handler: ListenerHandler<TolgeeError>)
tolgee.on('error', handler: Handler<ErrorEvent>)
```

12 changes: 10 additions & 2 deletions js-sdk/api/core_package/options.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ projectId: number | string;

### availableLanguages

Languages which can be used for language detection
and also limits which values can be stored. Is derrived from `staticData` keys if not provided.
Specify all available languages. Required for language detection or loading all languages at once ([loadMatrix](./tolgee.mdx#loadmatrix)).
It also limits which values can be stored. Is derrived from `staticData` keys if not provided.

```ts
availableLanguages: string[];
Expand Down Expand Up @@ -99,6 +99,14 @@ Default namespace when no namespace defined (default: empty string)
defaultNs: string;
```

### availableNs

Specify all available namespaces. Required for loading all namespaces at once ([loadMatrix](./tolgee.mdx#loadmatrix)).

```ts
availableNs: string[];
```

### staticData

These data go directly to cache or you can specify async
Expand Down
97 changes: 67 additions & 30 deletions js-sdk/api/core_package/tolgee.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -102,27 +102,6 @@ listener.unsubscribe()

Check [Events](./events) for details.

### onNsUpdate

Allows you to listen to key changes of namespaces that you pick.

```ts
tolgee.onNsUpdate(handler: ListenerHandler): ListenerSelective
```

Returns object, which allows you to subscribe to namespaces.

```ts
const listener = tolgee.onNsUpdate(...)
// subscribes namespace
listener.subscribeNs(ns)
// unsubscribe completely
listener.unsubscribe()
```

Use this when you want to make sure, you always update translation when it's necessary.
It internally stores list of namespaces that you are interested in and calls the handler, when necessary.

### t

Returns formatted translation based on current language. If `Observer` is present and tolgee is running, `wraps` the result to be identifiable in the DOM.
Expand Down Expand Up @@ -274,15 +253,16 @@ when you need to find out if tolgee has all the necessary data before `run` func
tolgee.isLoaded(ns?: FallbackNsTranslation): boolean
```

### getRequiredRecords
### getRequiredDescriptors

Returns records needed for instance to be `loaded`
Returns descriptors of records needed for instance to be `loaded`

```ts
tolgee.getRequiredRecords(): CacheDescriptor[]
tolgee.getRequiredDescriptors(lang?: string, ns?: NsFallback): CacheDescriptorInternal[]
```

- `ns`: `string` | `string[]` - optional list of namespaces that you are interested in
- `lang`: `string` - optional language (if not present, takes current language)
- `ns`: `string` | `string[]` - optional list of namespaces that you are interested in (if not present takes current active namespaces)

### isDev

Expand Down Expand Up @@ -335,24 +315,81 @@ Returns wrapped translation info.
tolgee.unwrap(text: string): Unwrapped
```

### loadRecord

Manually load record from `Backend` (or `DevBackend` when in dev mode).
### loadRequired

Load records required by current settings (influenced by current language and active namespaces).

```ts
tolgee.loadRecord(descriptors: CacheDescriptor): Promise<TranslationsFlat>
loadRequired(options?: LoadRequiredOptions): Promise<CacheInternalRecord[]>
```

In most cases can be called without any options and will return records which would be loaded
by `run` method initially.

Options:
- `language`: `string` - optionally override instance language (can be used when you don't know the language at the initialization time)
- `noDev`: `boolean` - load production translations only - skips DevBackend (false by default)
- `useCache`: `boolean` - skip fetching already loaded records (false by default)

### loadMatrix

Loads all combinations of specified languages and namespaces.

```ts
loadRequired(options?: LoadRequiredOptions): Promise<CacheInternalRecord[]>
```

Example usage:
```ts
const result = await tolgee.loadMatrix({
languages: ['en', 'cs'],
namespaces: ['']
})
// loads `en` and `cs` languages for empty namespace

const result = await tolgee.loadMatrix({
languages: ['en', 'cs'],
namespaces: ['common', 'info']
})
// loads `en:common`, `en:info`, `cs:common` and `cs:info` records
```

Options:
- `languages`: `string[] | 'all'` - languages that should be loaded
- use `all` value to load all [`availableLanguages`](./options.mdx#availablelanguages)
- `namespaces`: `string[] | 'all'` - namespaces that should be loaded
- use `all` value to load all [`availableNs`](./options.mdx#availablens)
- `noDev`: `boolean` - load production translations only - skips DevBackend (false by default)
- `useCache`: `boolean` - skip fetching already loaded records (false by default)


### loadRecords

Manually load multiple records from `Backend` (or `DevBackend` when in dev mode).
Load records by specifying it's descriptors (language and namespace).

```ts
tolgee.loadRecords(descriptors: CacheDescriptor[]): Promise<TranslationsFlat[]>
tolgee.loadRecords(descriptors: CacheDescriptor[], options?: LoadOptions): Promise<TranslationsFlat[]>
```

It loads data together and adds them to cache in one operation, to prevent partly loaded state.

Options:
- `noDev`: `boolean` - load production translations only - skips DevBackend (false by default)
- `useCache`: `boolean` - skip fetching already loaded records (false by default)

### loadRecord

Load record by specifying it's descriptor (language and namespace).

```ts
tolgee.loadRecord(descriptor: CacheDescriptor, options?: LoadOptions): Promise<TranslationsFlat>
```

Options:
- `noDev`: `boolean` - load production translations only - skips DevBackend (false by default)
- `useCache`: `boolean` - skip fetching already loaded records (false by default)

### getRecord

Get record from cache.
Expand Down
4 changes: 0 additions & 4 deletions js-sdk/api/web_package/tools.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ slug: tools

As `DevTools` are automatically omitted on production, `@tolgee/web/tools` can be used to include it unconditionally.

:::info
Tools were moved from `@tolgee/web` in version 5.2.0.
:::

## `InContextTools`


Expand Down
Loading
Loading