Skip to content

Commit

Permalink
Merge pull request #2116 from adnotam/fix_translations_5_2
Browse files Browse the repository at this point in the history
Backport #2114 to v5.2
  • Loading branch information
tvdeyen authored Jun 8, 2021
2 parents 9ca1ce5 + e79c2dd commit f95af6e
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
2 changes: 2 additions & 0 deletions package/admin.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import translate from "./src/i18n"
import translationData from "./src/translations"
import NodeTree from "./src/node_tree"

// Global Alchemy object
Expand All @@ -10,5 +11,6 @@ if (typeof window.Alchemy === "undefined") {
Object.assign(Alchemy, {
// Global utility method for translating a given string
t: translate,
translations: Object.assign(Alchemy.translations || {}, translationData),
NodeTree
})
23 changes: 23 additions & 0 deletions package/src/__tests__/i18n.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,20 @@ describe("translate", () => {
})

describe("if translation is present", () => {
beforeEach(() => {
Alchemy.translations = { en: { help: "Help" } }
})

it("Returns translated string", () => {
expect(translate("help")).toEqual("Help")
})

describe("if key includes a period", () => {
describe("that is translated", () => {
beforeEach(() => {
Alchemy.translations = { en: { formats: { date: "Y-m-d" } } }
})

it("splits into group", () => {
expect(translate("formats.date")).toEqual("Y-m-d")
})
Expand All @@ -40,6 +48,10 @@ describe("translate", () => {
})

describe("if replacement is given", () => {
beforeEach(() => {
Alchemy.translations = { en: { allowed_chars: "of %{number} chars" } }
})

it("replaces it", () => {
expect(translate("allowed_chars", 5)).toEqual("of 5 chars")
})
Expand Down Expand Up @@ -67,4 +79,15 @@ describe("translate", () => {
spy.mockRestore()
})
})

describe("if Alchemy.translations is not set", () => {
it("Returns passed string and logs a warning", () => {
const spy = jest.spyOn(console, "warn").mockImplementation(() => {})
expect(translate("help")).toEqual("help")
expect(spy.mock.calls).toEqual([
["Translations for locale kl not found!"]
])
spy.mockRestore()
})
})
})
4 changes: 1 addition & 3 deletions package/src/i18n.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import translationData from "./translations"

const KEY_SEPARATOR = /\./

function currentLocale() {
Expand All @@ -11,7 +9,7 @@ function currentLocale() {

function getTranslations() {
const locale = currentLocale()
const translations = translationData[locale]
const translations = Alchemy.translations && Alchemy.translations[locale]

if (translations) {
return translations
Expand Down

0 comments on commit f95af6e

Please sign in to comment.