Skip to content

Commit

Permalink
refactor: getTranslations, prepare for hash-based ids
Browse files Browse the repository at this point in the history
  • Loading branch information
timofei-iatsenko committed Feb 17, 2023
1 parent 5ba7460 commit 19ad935
Show file tree
Hide file tree
Showing 11 changed files with 525 additions and 194 deletions.
7 changes: 0 additions & 7 deletions packages/cli/src/api/__snapshots__/catalog.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,6 @@ Object {
}
`;

exports[`Catalog POT Flow Should merge source messages from template if provided 1`] = `
Object {
Hello World: Cześć świat,
Test String: Test String,
}
`;

exports[`Catalog collect should extract messages from source files 1`] = `
Object {
Component A: Object {
Expand Down
35 changes: 5 additions & 30 deletions packages/cli/src/api/catalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
cleanObsolete,
order,
normalizeRelativePath,
CatalogProps,
} from "./catalog"
import { createCompiledCatalog } from "./compile"

Expand Down Expand Up @@ -144,32 +145,6 @@ describe("Catalog", () => {
})

describe("POT Flow", () => {
it("Should merge source messages from template if provided", () => {
const catalog = new Catalog(
{
name: "messages",
path: path.resolve(
__dirname,
path.join("fixtures", "pot-template", "{locale}")
),
include: [],
exclude: [],
},
mockConfig({
locales: ["en", "pl"],
})
)

const translations = catalog.getTranslations("pl", {
sourceLocale: "en",
fallbackLocales: {
default: "en",
},
})

expect(translations).toMatchSnapshot()
})

it("Should get translations from template if locale file not presented", () => {
const catalog = new Catalog(
{
Expand Down Expand Up @@ -664,13 +639,13 @@ describe("Catalog", () => {
},
})

const fileContent = (format) =>
const fileContent = (format: string) =>
fs
.readFileSync("./en/messages." + (format === "po" ? "po" : "json"))
.toString()
.trim()

const catalogConfig = {
const catalogConfig: CatalogProps = {
name: "messages",
path: "{locale}/messages",
include: [],
Expand Down Expand Up @@ -1018,7 +993,7 @@ describe("getCatalogForMerge", () => {
try {
getCatalogForMerge(config)
} catch (e) {
expect(e.message).toBe(
expect((e as Error).message).toBe(
'Remove trailing slash from "locales/{locale}/bad/path/". Catalog path isn\'t a directory, but translation file without extension. For example, catalog path "locales/{locale}/bad/path" results in translation file "locales/en/bad/path.po".'
)
}
Expand All @@ -1032,7 +1007,7 @@ describe("getCatalogForMerge", () => {
try {
getCatalogForMerge(config)
} catch (e) {
expect(e.message).toBe(
expect((e as Error).message).toBe(
"Invalid catalog path: {locale} variable is missing"
)
}
Expand Down
86 changes: 6 additions & 80 deletions packages/cli/src/api/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import { CliExtractTemplateOptions } from "../lingui-extract-template"
import { CompiledCatalogNamespace } from "./compile"
import { prettyOrigin } from "./utils"
import chalk from "chalk"
import {
getTranslationsForCatalog,
GetTranslationsOptions,
} from "./getTranslationsForCatalog"

const NAME = "{name}"
const NAME_REPLACE_RE = /{name}/g
Expand Down Expand Up @@ -72,12 +76,7 @@ export type MergeOptions = {
files?: string[]
}

export type GetTranslationsOptions = {
sourceLocale: string
fallbackLocales: FallbackLocales
}

type CatalogProps = {
export type CatalogProps = {
name?: string
path: string
include: Array<string>
Expand Down Expand Up @@ -276,80 +275,7 @@ export class Catalog {
}

getTranslations(locale: string, options: GetTranslationsOptions) {
const catalogs = this.readAll()
const template = this.readTemplate() || {}

return R.mapObjIndexed(
(_value, key) => this.getTranslation(catalogs, locale, key, options),
{ ...template, ...catalogs[locale] }
)
}

getTranslation(
catalogs: AllCatalogsType,
locale: string,
key: string,
{ fallbackLocales, sourceLocale }: GetTranslationsOptions
) {
const getTranslation = (_locale: string) => {
const configLocales = this.config.locales.join('", "')
const localeCatalog = catalogs[_locale] || {}

if (!localeCatalog) {
console.warn(`
Catalog "${_locale}" isn't present in locales config parameter
Add "${_locale}" to your lingui.config.js:
{
locales: ["${configLocales}", "${_locale}"]
}
`)
return null
}
if (!localeCatalog.hasOwnProperty(key)) {
return null
}

if (catalogs[_locale]) {
return catalogs[_locale][key].translation
}

return null
}

const getMultipleFallbacks = (_locale: string) => {
const fL = fallbackLocales && fallbackLocales[_locale]

// some probably the fallback will be undefined, so just search by locale
if (!fL) return null

if (Array.isArray(fL)) {
for (const fallbackLocale of fL) {
if (catalogs[fallbackLocale]) {
return getTranslation(fallbackLocale)
}
}
} else {
return getTranslation(fL)
}
}

return (
// Get translation in target locale
getTranslation(locale) ||
// We search in fallbackLocales as dependent of each locale
getMultipleFallbacks(locale) ||
// Get translation in fallbackLocales.default (if any)
(fallbackLocales?.default && getTranslation(fallbackLocales.default)) ||
// Get message default
// If sourceLocale is either target locale of fallback one, use key
(sourceLocale && sourceLocale === locale && key) ||
(sourceLocale &&
fallbackLocales?.default &&
sourceLocale === fallbackLocales.default &&
key) ||
// Otherwise no translation is available
undefined
)
return getTranslationsForCatalog(this, locale, options)
}

write(
Expand Down
Loading

0 comments on commit 19ad935

Please sign in to comment.