imp
v0.1.1

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.

OptionWhat it does
themesThe theme choices of the app - see the theming guide.
themeThe theme to start in - a choice of themes, a built-in name or a theme object.
translationsLanguage code -> loader. The starting language's messages load before init ends.
langThe language to start in. Defaults to <html lang>, then the browser's language.
persisttrue remembers the theme and the language that the person picks - see below.
dirPins the text direction. Left out, it follows the language - see below.
defaultsDefault 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.

KeyRead byFalls back to
imp.button.morebutton({ items })More actions
imp.dialog.closedialogClose
imp.dialog.movedialog({ modal: false })Move this window with the arrow keys
imp.drawer.closedrawerClose
imp.splitPane.resizesplitPaneResize the panes
imp.shell.navshellNavigation
imp.shell.menushellMenu
imp.shell.sectionshellSection
imp.shell.moreshellMore
imp.shell.moreInshellMore in {section}
imp.shell.collapseshellCollapse the sidebar
imp.shell.expandshellExpand the sidebar
imp.shell.closeshellClose
imp.shell.skipshellSkip to the content
imp.state.emptyemptyStateNothing here yet
imp.state.noResultsemptyState({ variant: 'noResults' })No results
imp.form.requiredevery form controlThis field is required
imp.form.minLengthevery form controlUse at least {min} characters
imp.form.maxLengthevery form controlUse at most {max} characters
imp.form.minevery form controlMust be {min} or more
imp.form.maxevery form controlMust be {max} or less
imp.form.patternevery form controlCheck the format
imp.form.numbertextField of type 'number'Enter a number
imp.form.colorcolorPickerEnter a colour as #rrggbb
imp.form.checkFailedevery form controlWe could not check this - try again
imp.form.submitFailedformWe could not send the form - try again
imp.form.optionalevery form controloptional
imp.breadcrumbs.labelbreadcrumbsBreadcrumb
imp.breadcrumbs.changebreadcrumbs, a crumb with optionsChange {label}
imp.breadcrumbs.loadingbreadcrumbs, a crumb with loadingLoading
imp.theme.labelthemeSelectTheme
imp.theme.systemthemeSelectSystem
imp.theme.lightthemeSelectLight
imp.theme.darkthemeSelectDark
imp.theme.currentthemeSelectTheme: {theme}
imp.lang.labellangSelectLanguage
imp.lang.currentlangSelectLanguage: {language}
imp.org.labelorgSelectOrganization
imp.org.currentorgSelectOrganization: {org}
imp.bugReport.triggerbugReportReport a problem
imp.bugReport.pickingbugReportClick the part of the page the problem is about
imp.bugReport.pickingHintbugReportEscape cancels
imp.bugReport.titlebugReportReport a problem
imp.bugReport.commentbugReportWhat went wrong?
imp.bugReport.placeholderbugReportDescribe what you expected and what happened instead
imp.bugReport.sendbugReportSend report
imp.bugReport.cancelbugReportCancel
imp.bugReport.needsCommentbugReportDescribe the problem before sending it
imp.bugReport.failedbugReportThe report could not be sent - try again
imp.bugReport.sentbugReportThanks - your report was sent
imp.code.copycodeBlock, codeEditorCopy code
imp.code.copiedcodeBlock, codeEditorCopied
imp.code.linecodeBlock({ lineNumbers: true })Line {number}
imp.codeEditor.keyscodeEditorTab indents. Press Escape, then Tab, to leave the editor.
imp.richTextEditor.toolbarrichTextEditorFormatting
imp.richTextEditor.boldrichTextEditorBold
imp.richTextEditor.italicrichTextEditorItalic
imp.richTextEditor.strikerichTextEditorStrikethrough
imp.richTextEditor.coderichTextEditorCode
imp.richTextEditor.heading1richTextEditorHeading 1
imp.richTextEditor.heading2richTextEditorHeading 2
imp.richTextEditor.heading3richTextEditorHeading 3
imp.richTextEditor.quoterichTextEditorQuote
imp.richTextEditor.codeBlockrichTextEditorCode block
imp.richTextEditor.bulletsrichTextEditorBulleted list
imp.richTextEditor.numbersrichTextEditorNumbered list
imp.richTextEditor.linkrichTextEditorLink
imp.richTextEditor.imagerichTextEditorImage
imp.richTextEditor.emojirichTextEditorEmoji
imp.richTextEditor.alignStartrichTextEditorAlign start
imp.richTextEditor.alignCenterrichTextEditorAlign center
imp.richTextEditor.alignEndrichTextEditorAlign end
imp.richTextEditor.linkAddressrichTextEditorLink address
imp.richTextEditor.linkApplyrichTextEditorApply link
imp.richTextEditor.linkRemoverichTextEditorRemove link
imp.richTextEditor.imageAddingrichTextEditorAdding image...
imp.richTextEditor.imageFailedrichTextEditorThe image could not be added
imp.richTextEditor.heifFailedrichTextEditorThis browser cannot open the HEIC photo {name}. Save it as a JPEG and add it again.
imp.richTextEditor.keysrichTextEditorTab indents a list item. Press Escape, then Tab, to leave the editor.
imp.calendar.todaycalendarToday
imp.calendar.monthcalendarMonth
imp.calendar.weekcalendarWeek
imp.calendar.daycalendarDay
imp.calendar.previouscalendarPrevious
imp.calendar.nextcalendarNext
imp.calendar.morecalendar+{count} more
imp.calendar.allDaycalendarAll day
imp.calendar.viewcalendarView
imp.gantt.rangegantt{start} to {end}
imp.gantt.milestoneganttMilestone on {date}
imp.gantt.progressgantt{progress}% complete
imp.map.zoomInmapZoom in
imp.map.zoomOutmapZoom out
imp.table.selectRowtableSelect row {row}
imp.table.selectAlltableSelect all rows
imp.table.selectiontableSelection
imp.notice.dismissnoticeDismiss
imp.toast.dismisstoast, notificationsDismiss
imp.notifications.labelnotifications, toastNotifications
imp.comboBox.noMatchescomboBoxNo matches
imp.comboBox.searchingcomboBoxSearching
imp.comboBox.removecomboBoxRemove {label}
imp.treeSelect.searchtreeSelectSearch
imp.treeSelect.noMatchestreeSelectNo matches
imp.treeSelect.moretreeSelect{label} +{count}
imp.treeSelect.cleartreeSelectClear
imp.treeSelect.selectedtreeSelect{count} selected
imp.treeSelect.withChildrentreeSelectEverything below is selected too
imp.treeSelect.onlySelftreeSelectOnly this item is selected
imp.treeSelect.withSometreeSelectSome items below are selected too
imp.colorPicker.pickcolorPickerPick {label}
imp.datePicker.choosedatePickerChoose a date
imp.datePicker.cleardatePickerClear the date
imp.datePicker.previousMonthdatePicker, dateRangePickerPrevious month
imp.datePicker.nextMonthdatePicker, dateRangePickerNext month
imp.datePicker.timedatePickerTime
imp.datePicker.donedatePickerDone
imp.datePicker.mindatePickerChoose {min} or a later date
imp.datePicker.maxdatePickerChoose {max} or an earlier date
imp.dateRangePicker.relativedateRangePickerRelative
imp.dateRangePicker.customdateRangePickerCustom
imp.dateRangePicker.fromdateRangePickerFrom
imp.dateRangePicker.todateRangePickerTo
imp.dateRangePicker.applydateRangePickerApply
imp.dateRangePicker.canceldateRangePickerCancel
imp.dateRangePicker.choosedateRangePickerChoose a date range
imp.dateRangePicker.pickDaydateRangePickerPick a day
imp.dateRangePicker.startTimedateRangePickerStart time
imp.dateRangePicker.endTimedateRangePickerEnd time
imp.dateRangePicker.mindateRangePickerChoose a range that starts on {min} or later
imp.dateRangePicker.maxdateRangePickerChoose a range that ends on {max} or earlier
imp.emojiPicker.chooseemojiPickerChoose an emoji
imp.emojiPicker.clearemojiPickerClear the emoji
imp.reactions.labelreactionsReactions
imp.reactions.addreactionsAdd a reaction
imp.emoji.searchemojiPicker, reactions, richTextEditorSearch emoji
imp.emoji.noMatchesemojiPicker, reactions, richTextEditorNo emoji found
imp.emoji.smileysemojiPicker, reactions, richTextEditorSmileys
imp.emoji.peopleemojiPicker, reactions, richTextEditorPeople and gestures
imp.emoji.natureemojiPicker, reactions, richTextEditorAnimals and nature
imp.emoji.foodemojiPicker, reactions, richTextEditorFood and drink
imp.emoji.activitiesemojiPicker, reactions, richTextEditorActivities
imp.emoji.travelemojiPicker, reactions, richTextEditorTravel and places
imp.emoji.objectsemojiPicker, reactions, richTextEditorObjects
imp.emoji.symbolsemojiPicker, reactions, richTextEditorSymbols
imp.fileUpload.promptfileUploadDrop files here, or browse
imp.fileUpload.acceptsfileUploadAccepts {types}
imp.fileUpload.maxSizefileUploadUp to {size} for each file
imp.fileUpload.removefileUploadRemove {name}
imp.fileUpload.tooLargefileUpload{name} is larger than {size}
imp.fileUpload.wrongTypefileUpload{name} is not an accepted file type
imp.imageUpload.promptimageUploadDrop an image here, or browse
imp.imageUpload.maxSizeimageUploadUp to {size}
imp.imageUpload.tooLargeimageUpload{name} is larger than {size}
imp.imageUpload.wrongTypeimageUpload{name} is not an accepted image type
imp.imageUpload.unreadableimageUpload{name} could not be read as an image
imp.imageUpload.heifUnreadableimageUploadThis browser cannot open the HEIC photo {name}. Save it as a JPEG and pick it again.
imp.imageUpload.preparingimageUploadPreparing the image...
imp.imageUpload.frameimageUploadPicture position. Use the arrow keys to move the frame over the picture, and plus or minus to zoom.
imp.imageUpload.zoomimageUploadZoom
imp.imageUpload.doneimageUploadDone
imp.imageUpload.cancelimageUploadCancel
imp.imageUpload.changeimageUploadChange
imp.imageUpload.adjustimageUploadAdjust
imp.imageUpload.removeimageUploadRemove
imp.imageUpload.previewimageUploadThe chosen image
imp.steps.donestepsCompleted
imp.steps.currentstepsCurrent
imp.steps.upcomingstepsUpcoming
imp.steps.errorstepsError
imp.qrCode.labelqrCodeQR code
imp.loadMore.loadingtable, listLoading more
imp.loadMore.failedtable, listCould not load more
imp.loadMore.retrytable, listTry again
imp.notifications.emptynotifications, toastNo notifications
imp.notifications.clearAllnotifications, toastClear all
imp.notifications.labelUnreadnotifications, toastNotifications, {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.