Skip to content

Commit

Permalink
feat: raise event on missing translation (#993)
Browse files Browse the repository at this point in the history
Event is raised when a message id with no loaded
translation is requested with i18n._
  • Loading branch information
donocode committed Mar 4, 2021
1 parent 5533ea6 commit ecf83c3
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
12 changes: 12 additions & 0 deletions docs/ref/core.rst
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,15 @@ change
------

Triggered **after** locale is changed or new catalog is loaded. There are no arguments.

missing
------

Triggered when a translation is requested with ``i18n._`` that does not exist in the active locale's messages.
Information about the locale and message are available from the event.

.. code-block:: js
i18n.on('missing', (event) => {
alert(`alert(`Translation in ${event.locale} for ${event.id} is missing!`)`)
})
18 changes: 18 additions & 0 deletions packages/core/src/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,24 @@ describe("I18n", function () {
})
})

it("._ should emit missing event for missing translation", () => {
const i18n = setupI18n({
locale: "en",
messages: { en: { exists: "exists" } },
})

const handler = jest.fn()
i18n.on("missing", handler)
i18n._("exists")
expect(handler).toHaveBeenCalledTimes(0)
i18n._("missing")
expect(handler).toHaveBeenCalledTimes(1)
expect(handler).toHaveBeenCalledWith({
id: "missing",
locale: "en",
})
})

describe("params.missing - handling missing translations", function () {
it("._ should return custom string for missing translations", function () {
const i18n = setupI18n({
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ export type MessageDescriptor = {
values?: Record<string, unknown>
}

export type MissingMessageEvent = {
locale: Locale
id: string
}

type setupI18nProps = {
locale?: Locale
locales?: Locales
Expand All @@ -45,6 +50,7 @@ type setupI18nProps = {

type Events = {
change: () => void
missing: (event: MissingMessageEvent) => void
}

export class I18n extends EventEmitter<Events> {
Expand Down Expand Up @@ -175,6 +181,10 @@ export class I18n extends EventEmitter<Events> {
return isFunction(missing) ? missing(this.locale, id) : missing
}

if (!this.messages[id]) {
this.emit("missing", { id, locale: this._locale })
}

if (process.env.NODE_ENV !== "production") {
translation = isString(translation)
? icu.compile(translation)
Expand Down

1 comment on commit ecf83c3

@vercel
Copy link

@vercel vercel bot commented on ecf83c3 Mar 4, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.