imp-ui - Translations
Every imp app is translatable by default. Your translations are plain JavaScript files that you
write. t('some.key') finds a message in them. The current language is the lang attribute on
<html>, the same place the browser already uses. There is no i18n library to install, no message
format to compile, and no store to configure. The text direction follows the language on its own.
You declare which translations your app has. Do this in init for the app, and in area for a
section that loads lazily. imp then loads the correct translations at the correct time. A small set
of names does everything else:
import { init } from 'imp'
import { defaultMessages, dir, lang, missingMessages, t } from 'imp/i18n'
A translation is a file
Write your messages as an ordinary module. Its default export is a plain object:
// locales/en.js
export default {
todo: {
title: 'Todos',
greeting: 'Hi, {name}',
remaining: '{total} left',
},
}
// locales/pl.js
export default {
todo: {
title: 'Zadania',
greeting: 'Czesc, {name}',
remaining: 'Pozostalo: {total}',
},
}
The file holds keys and strings, nothing else. Nest the groups in the way that suits your app. The
shape is yours. t() addresses a message by its dotted path, such as todo.title. A translation
file is an ordinary module, so you can split it across files, import one lazily, or build one at
runtime.
Set up the app - init
At your entry point, tell imp how the app is configured. init applies the theme and loads the
translations of the starting language before you mount, so the first paint is already translated:
import { init, mount } from 'imp'
await init({
theme: 'imp-light',
translations: {
en: () => import('./locales/en.js'),
pl: () => import('./locales/pl.js'),
},
})
mount('#app', app())
translations is a map of language code to loader, not a set of messages. imp calls only the loader
of the language the app starts in. The browser does not download another language until someone asks
for it. So an app that speaks twelve languages ships one.
A loader is a function that calls import() on the file. The bundler gives each loader its own
chunk. The browser downloads the chunk when imp calls for it. imp unwraps the default export of
the module for you.
init takes seven options. All of them are optional.
| Option | What it does |
|---|---|
themes | The theme choices of the app - see the theming guide. |
theme | The theme to start in - a choice of themes, a built-in name or a theme object. |
translations | Language code -> loader. The starting language's messages load before init ends. |
lang | The language to start in. Defaults to <html lang>, then the browser's language. |
persist | true remembers the theme and the language that the person picks - see below. |
dir | Pins the text direction. Left out, it follows the language - see below. |
defaults | Default props of the standard components, keyed by component name. |
This is the only place where an app declares its translations. There is no separate register call.
For defaults, see Standard components.
Look up a message - t
t('todo.title') // -> 'Todos'
Placeholders. imp fills a {name} in a message from a plain object of values:
t('todo.greeting', { name: 'Ada' }) // -> 'Hi, Ada'
imp inserts a value as it is, and turns a number into a string. imp leaves a placeholder with no matching value as it is, so a spelling mistake shows up in the output instead of disappearing.
A message is a string. t() looks up a key and fills its placeholders. It does not choose
between variants. Format a number and a date yourself, and pick the correct wording for a count. Use
the platform's Intl object for this:
const total = new Intl.NumberFormat(lang.get()).format(1234.5)
t('todo.remaining', { total })
A missing message never throws. When no language has a key, t() returns the key itself and
warns once in the console. A gap then shows as a visible string you can search for, not as a crash.
A key with default wording shows that wording instead. Standard components read such keys, and your
own components can declare them too. See the next section.
The words that a component brings with it
Some text on the screen is not yours to write. Examples are the No results of an empty table,
the Cancel of a dialog, and the Loading... of a spinner. This works like
design tokens work. A component reads its colors from a token that falls back to a
built-in value when your theme does not set it. Component words follow the same pattern. imp looks
for them under an imp. key, and falls back to the English wording of the component. So an app with
no translation file still reads correctly:
emptyState() // -> "Nothing here yet"
Your translation wins. Write the key in your own translation files, and the component uses your words:
// locales/pl.js
export default {
imp: { state: { empty: 'Nic tu jeszcze nie ma' } },
}
That is the whole rule. It applies per key and per language. Translate imp.state.empty in Polish
only, and a Polish reader sees your wording while every other language keeps the component's
English. To add a language, you do not need to fill in a list of framework strings first. Override
only the keys whose wording you want to change.
These are the keys in use today, with the wording each one falls back to. Like the token list, it grows one component at a time.
| Key | Read by | Falls back to |
|---|---|---|
imp.button.more | button({ items }) | More actions |
imp.dialog.close | dialog | Close |
imp.dialog.move | dialog({ modal: false }) | Move this window with the arrow keys |
imp.drawer.close | drawer | Close |
imp.splitPane.resize | splitPane | Resize the panes |
imp.shell.nav | shell | Navigation |
imp.shell.menu | shell | Menu |
imp.shell.section | shell | Section |
imp.shell.more | shell | More |
imp.shell.moreIn | shell | More in {section} |
imp.shell.collapse | shell | Collapse the sidebar |
imp.shell.expand | shell | Expand the sidebar |
imp.shell.close | shell | Close |
imp.shell.skip | shell | Skip to the content |
imp.state.empty | emptyState | Nothing here yet |
imp.state.noResults | emptyState({ variant: 'noResults' }) | No results |
imp.form.required | every form control | This field is required |
imp.form.minLength | every form control | Use at least {min} characters |
imp.form.maxLength | every form control | Use at most {max} characters |
imp.form.min | every form control | Must be {min} or more |
imp.form.max | every form control | Must be {max} or less |
imp.form.pattern | every form control | Check the format |
imp.form.number | textField of type 'number' | Enter a number |
imp.form.color | colorPicker | Enter a colour as #rrggbb |
imp.form.checkFailed | every form control | We could not check this - try again |
imp.form.submitFailed | form | We could not send the form - try again |
imp.form.optional | every form control | optional |
imp.breadcrumbs.label | breadcrumbs | Breadcrumb |
imp.breadcrumbs.change | breadcrumbs, a crumb with options | Change {label} |
imp.breadcrumbs.loading | breadcrumbs, a crumb with loading | Loading |
imp.theme.label | themeSelect | Theme |
imp.theme.system | themeSelect | System |
imp.theme.light | themeSelect | Light |
imp.theme.dark | themeSelect | Dark |
imp.theme.current | themeSelect | Theme: {theme} |
imp.lang.label | langSelect | Language |
imp.lang.current | langSelect | Language: {language} |
imp.org.label | orgSelect | Organization |
imp.org.current | orgSelect | Organization: {org} |
imp.bugReport.trigger | bugReport | Report a problem |
imp.bugReport.picking | bugReport | Click the part of the page the problem is about |
imp.bugReport.pickingHint | bugReport | Escape cancels |
imp.bugReport.title | bugReport | Report a problem |
imp.bugReport.comment | bugReport | What went wrong? |
imp.bugReport.placeholder | bugReport | Describe what you expected and what happened instead |
imp.bugReport.send | bugReport | Send report |
imp.bugReport.cancel | bugReport | Cancel |
imp.bugReport.needsComment | bugReport | Describe the problem before sending it |
imp.bugReport.failed | bugReport | The report could not be sent - try again |
imp.bugReport.sent | bugReport | Thanks - your report was sent |
imp.code.copy | codeBlock, codeEditor | Copy code |
imp.code.copied | codeBlock, codeEditor | Copied |
imp.code.line | codeBlock({ lineNumbers: true }) | Line {number} |
imp.codeEditor.keys | codeEditor | Tab indents. Press Escape, then Tab, to leave the editor. |
imp.richTextEditor.toolbar | richTextEditor | Formatting |
imp.richTextEditor.bold | richTextEditor | Bold |
imp.richTextEditor.italic | richTextEditor | Italic |
imp.richTextEditor.strike | richTextEditor | Strikethrough |
imp.richTextEditor.code | richTextEditor | Code |
imp.richTextEditor.heading1 | richTextEditor | Heading 1 |
imp.richTextEditor.heading2 | richTextEditor | Heading 2 |
imp.richTextEditor.heading3 | richTextEditor | Heading 3 |
imp.richTextEditor.quote | richTextEditor | Quote |
imp.richTextEditor.codeBlock | richTextEditor | Code block |
imp.richTextEditor.bullets | richTextEditor | Bulleted list |
imp.richTextEditor.numbers | richTextEditor | Numbered list |
imp.richTextEditor.link | richTextEditor | Link |
imp.richTextEditor.image | richTextEditor | Image |
imp.richTextEditor.emoji | richTextEditor | Emoji |
imp.richTextEditor.alignStart | richTextEditor | Align start |
imp.richTextEditor.alignCenter | richTextEditor | Align center |
imp.richTextEditor.alignEnd | richTextEditor | Align end |
imp.richTextEditor.linkAddress | richTextEditor | Link address |
imp.richTextEditor.linkApply | richTextEditor | Apply link |
imp.richTextEditor.linkRemove | richTextEditor | Remove link |
imp.richTextEditor.imageAdding | richTextEditor | Adding image... |
imp.richTextEditor.imageFailed | richTextEditor | The image could not be added |
imp.richTextEditor.heifFailed | richTextEditor | This browser cannot open the HEIC photo {name}. Save it as a JPEG and add it again. |
imp.richTextEditor.keys | richTextEditor | Tab indents a list item. Press Escape, then Tab, to leave the editor. |
imp.calendar.today | calendar | Today |
imp.calendar.month | calendar | Month |
imp.calendar.week | calendar | Week |
imp.calendar.day | calendar | Day |
imp.calendar.previous | calendar | Previous |
imp.calendar.next | calendar | Next |
imp.calendar.more | calendar | +{count} more |
imp.calendar.allDay | calendar | All day |
imp.calendar.view | calendar | View |
imp.gantt.range | gantt | {start} to {end} |
imp.gantt.milestone | gantt | Milestone on {date} |
imp.gantt.progress | gantt | {progress}% complete |
imp.map.zoomIn | map | Zoom in |
imp.map.zoomOut | map | Zoom out |
imp.table.selectRow | table | Select row {row} |
imp.table.selectAll | table | Select all rows |
imp.table.selection | table | Selection |
imp.notice.dismiss | notice | Dismiss |
imp.toast.dismiss | toast, notifications | Dismiss |
imp.notifications.label | notifications, toast | Notifications |
imp.comboBox.noMatches | comboBox | No matches |
imp.comboBox.searching | comboBox | Searching |
imp.comboBox.remove | comboBox | Remove {label} |
imp.treeSelect.search | treeSelect | Search |
imp.treeSelect.noMatches | treeSelect | No matches |
imp.treeSelect.more | treeSelect | {label} +{count} |
imp.treeSelect.clear | treeSelect | Clear |
imp.treeSelect.selected | treeSelect | {count} selected |
imp.treeSelect.withChildren | treeSelect | Everything below is selected too |
imp.treeSelect.onlySelf | treeSelect | Only this item is selected |
imp.treeSelect.withSome | treeSelect | Some items below are selected too |
imp.colorPicker.pick | colorPicker | Pick {label} |
imp.datePicker.choose | datePicker | Choose a date |
imp.datePicker.clear | datePicker | Clear the date |
imp.datePicker.previousMonth | datePicker, dateRangePicker | Previous month |
imp.datePicker.nextMonth | datePicker, dateRangePicker | Next month |
imp.datePicker.time | datePicker | Time |
imp.datePicker.done | datePicker | Done |
imp.datePicker.min | datePicker | Choose {min} or a later date |
imp.datePicker.max | datePicker | Choose {max} or an earlier date |
imp.dateRangePicker.relative | dateRangePicker | Relative |
imp.dateRangePicker.custom | dateRangePicker | Custom |
imp.dateRangePicker.from | dateRangePicker | From |
imp.dateRangePicker.to | dateRangePicker | To |
imp.dateRangePicker.apply | dateRangePicker | Apply |
imp.dateRangePicker.cancel | dateRangePicker | Cancel |
imp.dateRangePicker.choose | dateRangePicker | Choose a date range |
imp.dateRangePicker.pickDay | dateRangePicker | Pick a day |
imp.dateRangePicker.startTime | dateRangePicker | Start time |
imp.dateRangePicker.endTime | dateRangePicker | End time |
imp.dateRangePicker.min | dateRangePicker | Choose a range that starts on {min} or later |
imp.dateRangePicker.max | dateRangePicker | Choose a range that ends on {max} or earlier |
imp.emojiPicker.choose | emojiPicker | Choose an emoji |
imp.emojiPicker.clear | emojiPicker | Clear the emoji |
imp.reactions.label | reactions | Reactions |
imp.reactions.add | reactions | Add a reaction |
imp.emoji.search | emojiPicker, reactions, richTextEditor | Search emoji |
imp.emoji.noMatches | emojiPicker, reactions, richTextEditor | No emoji found |
imp.emoji.smileys | emojiPicker, reactions, richTextEditor | Smileys |
imp.emoji.people | emojiPicker, reactions, richTextEditor | People and gestures |
imp.emoji.nature | emojiPicker, reactions, richTextEditor | Animals and nature |
imp.emoji.food | emojiPicker, reactions, richTextEditor | Food and drink |
imp.emoji.activities | emojiPicker, reactions, richTextEditor | Activities |
imp.emoji.travel | emojiPicker, reactions, richTextEditor | Travel and places |
imp.emoji.objects | emojiPicker, reactions, richTextEditor | Objects |
imp.emoji.symbols | emojiPicker, reactions, richTextEditor | Symbols |
imp.fileUpload.prompt | fileUpload | Drop files here, or browse |
imp.fileUpload.accepts | fileUpload | Accepts {types} |
imp.fileUpload.maxSize | fileUpload | Up to {size} for each file |
imp.fileUpload.remove | fileUpload | Remove {name} |
imp.fileUpload.tooLarge | fileUpload | {name} is larger than {size} |
imp.fileUpload.wrongType | fileUpload | {name} is not an accepted file type |
imp.imageUpload.prompt | imageUpload | Drop an image here, or browse |
imp.imageUpload.maxSize | imageUpload | Up to {size} |
imp.imageUpload.tooLarge | imageUpload | {name} is larger than {size} |
imp.imageUpload.wrongType | imageUpload | {name} is not an accepted image type |
imp.imageUpload.unreadable | imageUpload | {name} could not be read as an image |
imp.imageUpload.heifUnreadable | imageUpload | This browser cannot open the HEIC photo {name}. Save it as a JPEG and pick it again. |
imp.imageUpload.preparing | imageUpload | Preparing the image... |
imp.imageUpload.frame | imageUpload | Picture position. Use the arrow keys to move the frame over the picture, and plus or minus to zoom. |
imp.imageUpload.zoom | imageUpload | Zoom |
imp.imageUpload.done | imageUpload | Done |
imp.imageUpload.cancel | imageUpload | Cancel |
imp.imageUpload.change | imageUpload | Change |
imp.imageUpload.adjust | imageUpload | Adjust |
imp.imageUpload.remove | imageUpload | Remove |
imp.imageUpload.preview | imageUpload | The chosen image |
imp.steps.done | steps | Completed |
imp.steps.current | steps | Current |
imp.steps.upcoming | steps | Upcoming |
imp.steps.error | steps | Error |
imp.qrCode.label | qrCode | QR code |
imp.loadMore.loading | table, list | Loading more |
imp.loadMore.failed | table, list | Could not load more |
imp.loadMore.retry | table, list | Try again |
imp.notifications.empty | notifications, toast | No notifications |
imp.notifications.clearAll | notifications, toast | Clear all |
imp.notifications.labelUnread | notifications, toast | Notifications, {count} unread |
imp fills placeholders in default wording the same way it does in your own messages.
Check your coverage. To learn which of these keys your current language does not translate yet,
call missingMessages(). It returns an empty array when you have covered them all:
import { missingMessages } from 'imp/i18n'
missingMessages() // -> ['imp.state.empty']
Nothing is broken while a key is on that list. The reader sees English. A component registers its wording the first time you render it, so render the screens you care about before you check.
Default wording for your own components - defaultMessages
A component you write can carry wording the same way. This makes a shared component library usable in an app that has not translated it yet:
import { component } from 'imp'
import { div } from 'imp/html'
import { defaultMessages, lang, t } from 'imp/i18n'
const messages = {
'billing.trialEnded': 'Your trial has ended',
'billing.daysLeft': '{days} days left',
}
const definition = {
setup: () => div(lang.text(() => t('billing.trialEnded'))),
}
let create = null
export const trialNotice = (...args) => {
if (!create) {
defaultMessages(messages)
create = component('my-app-trial-notice', definition)
}
return create(...args)
}
defaultMessages takes a flat object that maps a dotted key to wording. Write the key exactly as
t() reads it, and the value as a plain string. Call the function where the component defines
itself, not at the top of the module, so a module nobody renders has no side effect.
Everything else follows the rules above. A translation of the same key overrides the wording, and
imp fills a {placeholder} in both cases.
The current language - <html lang>
The language of your app is the lang attribute on the <html> element. This is the same attribute
that tells a browser how to hyphenate text, which dictionary to check spelling against, and how a
screen reader must pronounce your page. imp reads the attribute and keeps no language of its own:
await lang.set('pl')
lang.set is async because a change of language first loads the messages of that language. It loads
the translations of the app from init, and the translations of the area you are in. Only then does
it write <html lang="pl"> and swap the messages. imp never shows untranslated text during a
switch, and it releases the messages of the previous language at the same time.
You can also set the attribute yourself. imp notices the change, loads that language, and swaps it in a moment:
document.documentElement.lang = 'pl'
When you never set the attribute, imp uses the visitor's browser language. So declaring your translations is enough to serve a person in their own language.
Which language a message comes from. A regional language also loads its base language, and its
own messages override the base messages. Declare both en and en-GB, and en-GB can hold just
three overrides instead of a full copy. A language you have not translated falls back to the first
language you declared.
Note what this does not do. Only the active language is in memory, so a key missing from it cannot fall back to the text of another language. It shows the key, or the default wording when the key has any. Every language you declare must carry the messages your app needs.
Text direction - <html dir>
Some languages read from right to left. imp treats the direction the way it treats the language: the
platform already has an attribute for it, <html dir>, and imp keeps it in step with <html lang>.
You write nothing. init sets the direction for the language the app starts in, and every change of
language updates it:
await lang.set('ar') // <html lang="ar" dir="rtl">
await lang.set('en') // <html lang="en" dir="ltr">
The starting language defaults to the visitor's browser language. So an app that declares Arabic or
Hebrew translations, and never calls lang.set, already lays out right to left for readers of those
languages.
The direction comes from the script, not from a list of languages. imp handles a language that uses
more than one alphabet correctly: az-Arab is right to left, and az-Latn is left to right. A
regional code such as fa-IR follows its base language.
Read the direction - dir. dir is a read-only state with the same shape as lang, so you can bind to it wherever the direction matters:
dir.get() // -> 'rtl'
dir.watch(self, (direction) => ...)
div(dir.text((direction) => direction === 'rtl' ? '<-' : '->'))
dir changes only when the language changes, so a binding to dir costs nothing on a page that
never changes language.
Write your CSS in logical properties. The attribute is the small half of the work. The rest is
making your styles follow it. Use margin-inline-start instead of margin-left. Use
padding-inline-end instead of padding-right. Use inset-inline-start instead of left. Use
text-align: start and text-align: end instead of left and right. Each of these follows the
direction on its own, so one stylesheet serves both directions. Every standard component already
uses this pattern. A physical property is the only kind that ignores the attribute.
The layout components follow the direction too. flex and stack take
horizontalAlign: 'start' and 'end', not 'left' and 'right'. A row lays its children out from
the edge where the language starts. So a header you write once reads correctly in English and in
Arabic, with no dir branch and no reversed child list. Design your screens in start and end
from the beginning, and right-to-left support costs you nothing later.
Pin the direction. A screen whose direction must not follow the language pins it. Examples are a code editor, a terminal view and a column of file paths:
await init({ dir: 'ltr' })
A pinned direction wins against the language for as long as the app runs. To pin one part of a page,
not the whole app, put dir on that element. It is an ordinary HTML attribute:
pre({ dir: 'ltr' }, sourceCode)
Text that you did not write. A comment typed in Arabic inside an otherwise English page is a
different problem: the direction depends on the text, not on the app. The platform solves it. Give
the element that holds the text dir: 'auto'. The browser then takes the direction from the first
strongly directional character in the content:
p({ dir: 'auto' }, comment.body)
Use this on anything a user typed. Leave the rest to <html dir>.
Before the first paint. imp sets the attribute in init, which runs before your app mounts, so
imp never lays out its content in the wrong direction. The browser lays out your index.html shell
before that. If your shell has visible markup, put the direction on it directly. An app in one
language can write <html lang="ar" dir="rtl">, and imp agrees with it.
Change the language
There are two ways to do this. The simple one suits most apps.
Reload the page. Store the choice, reload, and let init start the app in that language.
Nothing in your UI must be reactive, because imp builds everything once, in the correct language:
const chooseLanguage = (code) => {
localStorage.setItem('lang', code)
location.reload()
}
// entry point
await init({
lang: localStorage.getItem('lang') ?? undefined,
translations: {
en: () => import('./locales/en.js'),
pl: () => import('./locales/pl.js'),
},
})
Or change the language in place. lang is an app-wide state, like theme. Bind a text node to
it. The text localizes again the moment the language changes, and imp updates only that text node.
Nothing renders again, and nothing reloads:
import { component } from 'imp'
import { button, div, h1 } from 'imp/html'
import { lang, t } from 'imp/i18n'
export const header = component('app-header', {
setup: () =>
div(
h1(lang.text(() => t('todo.title'))),
button({ events: { click: () => lang.set('pl') } }, 'Polski'),
),
})
For a translated prop, such as a label, a title or a placeholder, derive the value from lang with
computed and pass that. The attribute then updates on its own when the language changes:
import { computed } from 'imp/state'
button({ 'aria-label': computed([lang], () => t('todo.add')) }, '+')
You can also react to a change of language directly:
lang.watch(self, (code) => console.log('now showing', code))
The standard components follow the same rule: every string they show is bound through lang, so
they localize again in place on a change of language, with no reload. Do the same in your own
components. Write lang.text(() => t('key')), not a bare t('key'). This keeps a change-in-place
as an option you can add later, without rewriting your screens.
A language setting on a settings page
Write persist: true in init. imp stores the language that the person picks, and the next load
starts in it. init loads that language before the first render, so nothing changes on screen.
imp ignores a stored language that your translations do not offer.
// entry point
import { init, mount } from 'imp'
await init({ translations, persist: true })
mount('#app', root())
Put langSelect() where it fits the app: in the bar, in the account menu, or on a settings page.
With no languages, it offers the languages of your translations. It sets the app-wide lang
state, so the language is correct on every page, also where no picker shows:
import { component } from 'imp'
import { langSelect } from 'imp/std/shell'
export const languageSetting = component('app-language-setting', {
setup: () => langSelect(),
})
A change switches the language in place. Bind your text through lang, as shown above, and it
translates again. To keep the language on the account of the person, call await lang.set(user.lang)
after sign-in, and send each change from lang.watch. persist: { lang: true } stores the language
and not the theme. The theme works the same way, see the theming guide.
The words of the application map
The nav, the breadcrumb trail and the document title take their
words from the application map. See Routing. Translate them in the same files as the
rest of the app, under the key appMap. The rest of the key is the id of the node, then label or
description. The root has no id, so appMap.label names the root:
// locales/pl.js
export default {
appMap: {
label: 'Start',
projects: { label: 'Projekty' },
admin: {
label: 'Administracja',
users: { label: 'Uzytkownicy', description: 'Kazdy, kto ma login' },
},
},
acme: { nav: { accounts: 'Konta' } },
}
A message wins over the description that the map writes, and over the name of the node. When no
message exists, the map's own words show. So an app in one language writes no message at all, and
the map file never calls t().
A param crumb, such as the name of a project, is not a message. The data names it, through the
state imp.routeLabels. See Routing.
A heading over a group of sidebar rows is a node of the map, marked with group: true in the nav
of the shell. Its label message translates it like any other node. So
appMap: { admin: { accounts: { label: 'Konta' } } } shows "Konta" over the rows of
app.admin.accounts in Polish.
Put these keys in the translations of the app, not in the translations of an area. A section row in the nav shows before the code of its area has loaded, so its message must already be in memory.
Translations for a lazily loaded area
A route area, see Routing, is a section of the app the browser downloads the first time someone navigates into it. Its messages belong to it. An area declares them the same way as the root app, as a map of language to loader:
// admin/area.js
import { area } from 'imp/router'
import { app } from '../app-map.js'
export default area({
screens: {
[app.admin]: () => dashboard(),
[app.admin.users]: () => users(),
},
translations: {
en: () => import('./locales/en.js'),
pl: () => import('./locales/pl.js'),
},
})
// main.js
router({
map: app,
screens: {
[app]: () => home(),
[app.admin]: area(() => import('./admin/area.js')),
},
})
You call nothing to make this work. Entering /admin loads the chunk of the area and the one
translation file that matches the app's current language, before the first screen of the area
paints. Moving between screens inside the area keeps it loaded. Leaving the area drops it. Changing
the language while inside the area loads the area's messages for the new language, along with the
app's messages, so both change together.
Put the messages of each area under its own key, such as admin.users.title, not title. All
messages share one namespace, and on a collision the last loaded key wins. That is what you want
when an area overrides a message of the app on purpose. It is not what you want when two areas both
claim title. Nest the messages of each area under its own top-level key, and the two never
collide.
What "dropped" means. When you leave an area, or change the language, imp drops its reference to
the messages it no longer needs, and those messages stop resolving. Outside the admin area,
t('admin.title') gives you back the key. This does not shrink the heap. A module the browser has
loaded stays in its registry for the life of the page. The same note in Routing about
the code of an area applies to its messages.
So what you gain is about what you download, not about what you hold. A visitor who never opens the admin section never downloads its messages. A visitor who reads in Polish never downloads English. The drop also keeps lookups honest: the keys of an area stop resolving as soon as you leave it, so a missing message appears while you develop, instead of resolving to the text of another section.
Watch for messages that can disappear. t() returns the key for a message it cannot find, or
the default wording when the key has any, and it never throws. Anything that lives longer than an
area must read from the messages of the app, not from the messages of an area. A header, a
breadcrumb trail and a toast queue are examples. A node bound with lang.text(...) that outlives
its area starts to render raw keys.
Test translated text
Translated text is ordinary text, so you need nothing special. Call init once at the top of the
test file, change the language with lang.set, and assert on what renders:
import { init } from 'imp'
import { lang, t } from 'imp/i18n'
import { beforeAll, expect, test } from 'imp/test'
beforeAll(() =>
init({
translations: {
en: () => import('./locales/en.js'),
pl: () => import('./locales/pl.js'),
},
}),
)
test('greets in the active language', async () => {
await lang.set('pl')
expect(t('greet')).toEqual('Czesc')
})
Always await lang.set. It loads the language before it changes it.