0
# Translation
1
2
This module provides comprehensive internationalization (i18n) support for Superset applications, enabling multi-language user interfaces with proper pluralization, locale-specific formatting, and dynamic translation loading. The translation system is built on the Jed library and provides both singleton and instance-based APIs.
3
4
## Overview
5
6
The translation module uses a singleton pattern to manage a global translation instance while supporting custom translator configurations for specific use cases. It supports 10+ languages including English, Spanish, French, German, Italian, Japanese, Korean, Portuguese, Russian, and Chinese.
7
8
## Core Translation Functions
9
10
### Basic Translation Functions { .api }
11
12
Primary functions for translating text in your application:
13
14
```typescript
15
import { t, tn } from '@superset-ui/core';
16
17
// Basic translation
18
function t(text: string, ...args: unknown[]): string;
19
20
// Pluralized translation with count
21
function tn(
22
singular: string,
23
plural: string,
24
count: number,
25
...args: unknown[]
26
): string;
27
```
28
29
### Configuration Functions { .api }
30
31
Functions for configuring the global translator instance:
32
33
```typescript
34
import {
35
configure,
36
addTranslation,
37
addTranslations,
38
addLocaleData,
39
resetTranslation
40
} from '@superset-ui/core';
41
42
// Configure global translator
43
function configure(config?: TranslatorConfig): Translator;
44
45
// Add individual translations
46
function addTranslation(key: string, translations: string[]): Translator;
47
48
// Add multiple translations at once
49
function addTranslations(translations: Translations): Translator;
50
51
// Add locale-specific data
52
function addLocaleData(data: LocaleData): Translator;
53
54
// Reset translation system
55
function resetTranslation(): void;
56
```
57
58
## Types and Interfaces
59
60
### Core Types { .api }
61
62
Type definitions for the translation system:
63
64
```typescript
65
// Supported locales
66
type Locale =
67
| 'de' // German
68
| 'en' // English
69
| 'es' // Spanish
70
| 'fr' // French
71
| 'it' // Italian
72
| 'ja' // Japanese
73
| 'ko' // Korean
74
| 'pt' // Portuguese
75
| 'pt_BR' // Portuguese (Brazil)
76
| 'ru' // Russian
77
| 'zh'; // Chinese
78
79
// Translation configuration
80
interface TranslatorConfig {
81
languagePack?: LanguagePack;
82
}
83
84
// Language pack structure
85
interface LanguagePack extends JedOptions {
86
locale_data: {
87
superset: DomainData & {
88
'': {
89
domain: 'superset';
90
lang: Locale;
91
plural_forms: string;
92
};
93
};
94
};
95
}
96
97
// Translation mappings
98
type Translations = { [key: string]: string | string[] };
99
100
// Locale-specific data
101
type LocaleData = Partial<Record<Locale, Translations>>;
102
```
103
104
### Jed Integration { .api }
105
106
Extended Jed instance with Superset-specific typing:
107
108
```typescript
109
interface Jed extends BaseJed {
110
options: LanguagePack;
111
112
// Core Jed methods
113
gettext(key: string): string;
114
ngettext(singular: string, plural: string, count: number): string;
115
pgettext(context: string, key: string): string;
116
npgettext(context: string, singular: string, plural: string, count: number): string;
117
}
118
119
// Jed domain data structure
120
interface DomainData {
121
[msgid: string]: string | string[];
122
}
123
124
// Jed configuration options
125
interface JedOptions {
126
domain?: string;
127
locale_data?: { [domain: string]: DomainData };
128
debug?: boolean;
129
}
130
```
131
132
## Translator Class
133
134
### Translator { .api }
135
136
Core translator class that manages translations for a specific locale:
137
138
```typescript
139
import { Translator } from '@superset-ui/core';
140
141
class Translator {
142
readonly i18n: Jed;
143
readonly locale: Locale;
144
145
constructor(config?: TranslatorConfig);
146
147
// Translation methods
148
translate(text: string, ...args: unknown[]): string;
149
translateWithNumber(
150
singular: string,
151
plural: string,
152
count: number,
153
...args: unknown[]
154
): string;
155
156
// Dynamic translation management
157
addTranslation(key: string, texts: ReadonlyArray<string>): this;
158
addTranslations(translations: Translations): this;
159
addLocaleData(data: LocaleData): this;
160
161
// Locale management
162
getLocale(): Locale;
163
}
164
```
165
166
## Usage Examples
167
168
### Basic Translation
169
170
```typescript
171
import { t, tn, configure } from '@superset-ui/core';
172
173
// Configure with language pack
174
configure({
175
languagePack: {
176
domain: 'superset',
177
locale_data: {
178
superset: {
179
'': {
180
domain: 'superset',
181
lang: 'es',
182
plural_forms: 'nplurals=2; plural=(n != 1)'
183
},
184
'Hello World': ['Hola Mundo'],
185
'Save': ['Guardar'],
186
'Delete': ['Eliminar']
187
}
188
}
189
}
190
});
191
192
// Basic translation
193
const greeting = t('Hello World'); // "Hola Mundo"
194
const saveButton = t('Save'); // "Guardar"
195
196
// Pluralized translation
197
const itemCount = tn('item', 'items', 1); // "item"
198
const itemsCount = tn('item', 'items', 5); // "items"
199
```
200
201
### Dynamic Translation Loading
202
203
```typescript
204
import {
205
addTranslation,
206
addTranslations,
207
addLocaleData
208
} from '@superset-ui/core';
209
210
// Add single translation
211
addTranslation('New Feature', ['Nueva Característica']);
212
213
// Add multiple translations
214
addTranslations({
215
'Dashboard': ['Panel de Control'],
216
'Charts': ['Gráficos'],
217
'Datasets': ['Conjuntos de Datos']
218
});
219
220
// Add locale-specific data
221
addLocaleData({
222
'es': {
223
'Welcome': 'Bienvenido',
224
'Goodbye': 'Adiós'
225
},
226
'fr': {
227
'Welcome': 'Bienvenue',
228
'Goodbye': 'Au revoir'
229
}
230
});
231
```
232
233
### Plugin Translation Integration
234
235
```typescript
236
import { Plugin, addTranslations } from '@superset-ui/core';
237
238
class ChartPlugin extends Plugin {
239
constructor(config: { translations?: Translations }) {
240
super();
241
this.configure(config);
242
}
243
244
register() {
245
// Add plugin-specific translations
246
if (this.config.translations) {
247
addTranslations(this.config.translations);
248
}
249
250
return super.register();
251
}
252
}
253
254
// Register plugin with translations
255
const myChartPlugin = new ChartPlugin({
256
translations: {
257
'My Chart': ['Mi Gráfico'],
258
'Configure Chart': ['Configurar Gráfico'],
259
'No data available': ['No hay datos disponibles']
260
}
261
});
262
263
myChartPlugin.register();
264
```
265
266
### Custom Translator Instance
267
268
```typescript
269
import { Translator } from '@superset-ui/core';
270
271
// Create custom translator for specific module
272
const moduleTranslator = new Translator({
273
languagePack: {
274
domain: 'my-module',
275
locale_data: {
276
superset: {
277
'': {
278
domain: 'my-module',
279
lang: 'fr',
280
plural_forms: 'nplurals=2; plural=(n > 1)'
281
},
282
'Settings': ['Paramètres'],
283
'Options': ['Options']
284
}
285
}
286
}
287
});
288
289
// Use custom translator
290
const settingsLabel = moduleTranslator.translate('Settings'); // "Paramètres"
291
```
292
293
### React Component Integration
294
295
```typescript
296
import React from 'react';
297
import { t, tn } from '@superset-ui/core';
298
299
interface NotificationProps {
300
count: number;
301
type: string;
302
}
303
304
const NotificationComponent: React.FC<NotificationProps> = ({ count, type }) => {
305
return (
306
<div>
307
<h3>{t('Notifications')}</h3>
308
<p>
309
{tn(
310
`You have ${count} ${type} notification`,
311
`You have ${count} ${type} notifications`,
312
count
313
)}
314
</p>
315
</div>
316
);
317
};
318
```
319
320
### Template String Interpolation
321
322
```typescript
323
import { t } from '@superset-ui/core';
324
325
// Add translations with placeholders
326
addTranslations({
327
'Welcome back, {name}!': ['¡Bienvenido de nuevo, {name}!'],
328
'You have {count} new messages': ['Tienes {count} mensajes nuevos']
329
});
330
331
// Use with interpolation
332
const welcomeMessage = t('Welcome back, {name}!', { name: 'John' });
333
const messageCount = t('You have {count} new messages', { count: 5 });
334
```
335
336
## Advanced Usage
337
338
### Multi-Domain Translation Management
339
340
```typescript
341
import { Translator } from '@superset-ui/core';
342
343
// Create specialized translators for different domains
344
const dashboardTranslator = new Translator({
345
languagePack: {
346
domain: 'dashboard',
347
locale_data: {
348
superset: {
349
'': { domain: 'dashboard', lang: 'de', plural_forms: 'nplurals=2; plural=(n != 1)' },
350
'Dashboard': ['Dashboard'],
351
'Edit': ['Bearbeiten']
352
}
353
}
354
}
355
});
356
357
const chartTranslator = new Translator({
358
languagePack: {
359
domain: 'charts',
360
locale_data: {
361
superset: {
362
'': { domain: 'charts', lang: 'de', plural_forms: 'nplurals=2; plural=(n != 1)' },
363
'Chart': ['Diagramm'],
364
'Visualization': ['Visualisierung']
365
}
366
}
367
}
368
});
369
```
370
371
### Runtime Language Switching
372
373
```typescript
374
import { configure, resetTranslation, t } from '@superset-ui/core';
375
376
async function switchLanguage(locale: Locale) {
377
// Reset current translations
378
resetTranslation();
379
380
// Load new language pack
381
const languagePack = await import(`../locales/${locale}.json`);
382
383
// Configure with new language
384
configure({ languagePack });
385
386
// Trigger UI re-render
387
dispatchLanguageChangeEvent();
388
}
389
390
// Usage
391
switchLanguage('fr').then(() => {
392
console.log(t('Welcome')); // "Bienvenue"
393
});
394
```
395
396
## Best Practices
397
398
### Translation Key Management
399
400
```typescript
401
// Use descriptive, hierarchical keys
402
const translations = {
403
'dashboard.title': ['Panel de Control'],
404
'dashboard.actions.save': ['Guardar'],
405
'dashboard.actions.delete': ['Eliminar'],
406
'chart.config.title': ['Configuración del Gráfico'],
407
'chart.config.axes.x_label': ['Etiqueta del Eje X']
408
};
409
410
// Avoid dynamic key generation
411
// ❌ Bad
412
const dynamicKey = `message.${type}.${status}`;
413
const text = t(dynamicKey);
414
415
// ✅ Good
416
const messageMap = {
417
'success': t('message.success'),
418
'error': t('message.error'),
419
'warning': t('message.warning')
420
};
421
const text = messageMap[type];
422
```
423
424
### Performance Optimization
425
426
```typescript
427
// Lazy load translations for large applications
428
const loadTranslations = async (locale: Locale) => {
429
const { default: translations } = await import(`../i18n/${locale}.json`);
430
return translations;
431
};
432
433
// Memoize translated strings in components
434
const TranslatedComponent = React.memo(() => {
435
const title = useMemo(() => t('Dashboard Title'), []);
436
const description = useMemo(() => t('Dashboard Description'), []);
437
438
return <div>{title}: {description}</div>;
439
});
440
```
441
442
## Related Documentation
443
444
- [Core Models & Utilities](./core-models.md) - Plugin system and configuration
445
- [UI & Styling](./ui-styling.md) - Theme system integration
446
- [Dashboard Components](./dashboard.md) - Dashboard-specific translations