Skip to content
ФреймворкJavaScript

i18n API: перевод интерфейса Blok

Поддержка интернационализации для перевода строк интерфейса, а также метод `i18n.update()` для смены языка на лету.

Как получить экземпляр редактора

Методы ниже вызываются на редакторе, созданном через new Blok(). Они доступны после того, как разрешится editor.isReady.

TypeScript
// You already hold the instance returned by the constructor.
const editor = new Blok({ holder: 'editor' });
await editor.isReady;

// Call any API method on it.
editor.caret.setToLastBlock('end');

Методы

i18n.t(dictKey, vars?)

string

Translate a key from the global dictionary, optionally interpolating string or number values.

Когда использовать

Берёт строку UI из активного словаря внутри инструмента, чтобы он локализовался вместе с редактором.

TypeScript
const text = editor.i18n.t('toolNames.text');
console.log(text); // 'Text' (or translated string)

const limit = editor.i18n.t('tools.image.emptyMaxSize', { size: '10 MB' });
console.log(limit); // 'max 10 MB' (or translated string)

i18n.has(dictKey)

boolean

Check if a translation exists for the given key.

Когда использовать

Проверяет наличие ключа перед переводом, чтобы корректно подстраховаться при неполных словарях инструмента.

TypeScript
if (editor.i18n.has('toolNames.text')) {
  const translation = editor.i18n.t('toolNames.text');
}

i18n.getEnglishTranslation(key)

string

Get the English translation for a key (used for multilingual search).

Когда использовать

Возвращает английское значение независимо от локали — используется для индексации контента в мультиязычном поиске.

TypeScript
const english = editor.i18n.getEnglishTranslation('toolNames.heading');
console.log(english); // 'Heading'

i18n.getLocale()

string

Get the active locale code (e.g. 'en').

Когда использовать

Возвращает код активной локали (например, 'en'), чтобы инструмент мог ветвиться по текущему языку редактора.

TypeScript
const locale = editor.i18n.getLocale();
console.log(locale); // 'en'

i18n.getDirection()

'ltr' | 'rtl'

Get the text direction currently in effect — derived from the active locale unless an explicit `direction` override was set.

Когда использовать

Возвращает 'ltr' или 'rtl' для активной локали, чтобы интерфейс вокруг редактора зеркалился вместе с ним.

TypeScript
if (editor.i18n.getDirection() === 'rtl') {
  // mirror your own chrome next to the editor
}

i18n.update({ locale?, messages?, direction? })

Promise<void>

Switch language at runtime. `config.i18n` is otherwise read once during boot, so a host with a language switcher had to recreate the editor to relabel it — losing caret, focus, selection and undo history. `update()` relabels in place instead: no recreation, nothing lost. `locale` accepts any supported code or `'auto'` to re-run browser detection; `messages` merges host overrides over the locale dictionary and is re-applied automatically after every later locale change (a bare locale flip never silently drops your custom strings); `direction` overrides the direction implied by the locale, which you normally do not need. Calls are serialized internally, so lazily-loaded locale chunks cannot land out of order — the last call wins. Scope: everything. Chrome built on demand (block settings, the convert menu, notifications, screen-reader announcements) picks up the new locale the next time it opens; the eagerly-stamped chrome (toolbar and plus-button labels, tooltips, the toolbox list) is relabelled immediately; and block content — placeholders, media-toolbar labels, cell controls, anything a tool resolved while rendering — is repainted from your data, including tools that know nothing about locale changes. The repaint is invisible to you: `onChange` does not fire, scroll is kept, and the caret returns to the block that had it. Fires the `i18n:changed` event with `{ locale, direction }`. Available synchronously after construction — a call made before `isReady` is applied once the editor has booted. `update()` is exposed on the editor instance only, not on the `api.i18n` handed to tools, so a third-party tool cannot flip the host's locale. The React/Vue/Angular adapters drive it reactively: change the `i18n` prop/input and the editor follows in place. Note `defaultLocale` is not accepted — it only decides the fallback while resolving the initial locale.

Когда использовать

Меняет локаль и пользовательские переводы на лету: редактор переименовывает интерфейс на месте, так что переключателю языка больше не нужно пересоздавать редактор и терять каретку, фокус и историю отмен.

TypeScript
// Host language switcher — no remount, caret and undo survive.
await editor.i18n.update({ locale: 'ru' });

// Locale plus your own overrides on top of it.
await editor.i18n.update({
  locale: 'fr',
  messages: { 'toolNames.text': 'Paragraphe' },
});

// Follow the browser again.
await editor.i18n.update({ locale: 'auto' });

editor.events.on('i18n:changed', ({ locale, direction }) => {
  document.documentElement.dir = direction;
});