forked from lingui/js-lingui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathI18nProvider.js
111 lines (90 loc) · 2.46 KB
/
I18nProvider.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// @flow
import * as React from "react"
import PropTypes from "prop-types"
import hashSum from "hash-sum"
import { setupI18n } from "@lingui/core"
import type { I18n, Catalogs, Locales } from "@lingui/core"
export type I18nProviderProps = {
children?: any,
language: string,
locales?: Locales,
catalogs?: Catalogs,
i18n?: I18n,
missing?: string | Function,
defaultRender: ?any
}
/*
* I18nPublisher - Connects to lingui-i18n/I18n class
* Allows listeners to subscribe for changes
*/
export function LinguiPublisher(i18n: I18n) {
let subscribers: Array<Function> = []
return {
i18n,
i18nHash: null,
getSubscribers() {
return subscribers
},
subscribe(callback: Function) {
subscribers.push(callback)
},
unsubscribe(callback: Function) {
subscribers = subscribers.filter(cb => cb !== callback)
},
update({
catalogs,
language,
locales
}: { catalogs?: Catalogs, language?: string, locales?: string } = {}) {
if (!catalogs && !language && !locales) return
if (catalogs) i18n.load(catalogs)
if (language) i18n.activate(language, locales)
this.i18nHash = hashSum([i18n.language, i18n.messages])
subscribers.forEach(f => f())
}
}
}
export default class I18nProvider extends React.Component<I18nProviderProps> {
props: I18nProviderProps
linguiPublisher: LinguiPublisher
static defaultProps = {
defaultRender: null
}
static childContextTypes = {
linguiPublisher: PropTypes.object.isRequired,
linguiDefaultRender: PropTypes.any
}
constructor(props: I18nProviderProps) {
super(props)
const { language, locales, catalogs, missing } = props
const i18n =
props.i18n ||
setupI18n({
language,
locales,
catalogs
})
this.linguiPublisher = new LinguiPublisher(i18n)
this.linguiPublisher.i18n._missing = this.props.missing
}
componentDidUpdate(prevProps: I18nProviderProps) {
const { language, locales, catalogs } = this.props
if (
language !== prevProps.language ||
locales !== prevProps.locales ||
catalogs !== prevProps.catalogs
) {
this.linguiPublisher.update({ language, catalogs, locales })
}
this.linguiPublisher.i18n._missing = this.props.missing
}
getChildContext() {
return {
linguiPublisher: this.linguiPublisher,
linguiDefaultRender: this.props.defaultRender
}
}
render() {
return this.props.children
}
}