Skip to content

Commit

Permalink
feat(I18n): Add useExtendI18n to be able to add locales to existing ones
Browse files Browse the repository at this point in the history
  • Loading branch information
JF-Cozy authored and zatteo committed Mar 12, 2024
1 parent 7770e7b commit ad388b4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
2 changes: 1 addition & 1 deletion react/providers/I18n/index.jsx
Expand Up @@ -89,7 +89,7 @@ I18n.childContextTypes = {
lang: PropTypes.string
}

export { initTranslation, extend } from './translation'
export { initTranslation, extend, useExtendI18n } from './translation'
export { default as translate } from './translate'
export { default as createUseI18n } from './createUseI18n'

Expand Down
36 changes: 34 additions & 2 deletions react/providers/I18n/translation.jsx
@@ -1,5 +1,6 @@
import Polyglot from 'node-polyglot'
import { DEFAULT_LANG } from '.'

import { DEFAULT_LANG, useI18n } from '.'

export let _polyglot

Expand Down Expand Up @@ -38,4 +39,35 @@ export const initTranslation = (
return _polyglot
}

export const extend = dict => _polyglot && _polyglot.extend(dict)
export const extend = (dict, polyglot) => (polyglot || _polyglot)?.extend(dict)

// Use to determine if we need to merge locales again, and to avoid useless calls
let useExtendI18nLang = ''

/**
* Hook to merge app locales with cozy-ui locales
* @param {object} locales - Locales sorted by lang `{ fr: {...}, en: {...} }`
* @returns {void}
*/
export const useExtendI18n = locales => {
const { lang, polyglot } = useI18n()

if (!locales || !lang || !polyglot) return

// To simplify code we use Polyglot.extend to merge
// locales from object and from polyglot.phrases
// rather than native JS or lodash. this is why we have two extend.
if (useExtendI18nLang !== lang) {
const _polyglot = new Polyglot({
phrases: locales[lang],
locale: lang
})

// merge locales from app and cozy-ui, without replacing existing one in app
extend(polyglot.phrases, _polyglot)
// use merged locales in app
extend(_polyglot.phrases, polyglot)
// set the sitch to avoid useless merge
useExtendI18nLang = lang
}
}

0 comments on commit ad388b4

Please sign in to comment.