UNPKG

1.83 kBJavaScriptView Raw
1/* @flow */
2
3import { warn } from './util'
4
5export default {
6 name: 'i18n',
7 functional: true,
8 props: {
9 tag: {
10 type: String,
11 default: 'span'
12 },
13 path: {
14 type: String,
15 required: true
16 },
17 locale: {
18 type: String
19 },
20 places: {
21 type: [Array, Object]
22 }
23 },
24 render (h: Function, { props, data, children, parent }: Object) {
25 const i18n = parent.$i18n
26
27 children = (children || []).filter(child => {
28 return child.tag || (child.text = child.text.trim())
29 })
30
31 if (!i18n) {
32 if (process.env.NODE_ENV !== 'production') {
33 warn('Cannot find VueI18n instance!')
34 }
35 return children
36 }
37
38 const path: Path = props.path
39 const locale: ?Locale = props.locale
40
41 const params: Object = {}
42 const places: Array<any> | Object = props.places || {}
43
44 const hasPlaces: boolean = Array.isArray(places)
45 ? places.length > 0
46 : Object.keys(places).length > 0
47
48 const everyPlace: boolean = children.every(child => {
49 if (child.data && child.data.attrs) {
50 const place = child.data.attrs.place
51 return (typeof place !== 'undefined') && place !== ''
52 }
53 })
54
55 if (process.env.NODE_ENV !== 'production' && hasPlaces && children.length > 0 && !everyPlace) {
56 warn('If places prop is set, all child elements must have place prop set.')
57 }
58
59 if (Array.isArray(places)) {
60 places.forEach((el, i) => {
61 params[i] = el
62 })
63 } else {
64 Object.keys(places).forEach(key => {
65 params[key] = places[key]
66 })
67 }
68
69 children.forEach((child, i: number) => {
70 const key: string = everyPlace
71 ? `${child.data.attrs.place}`
72 : `${i}`
73 params[key] = child
74 })
75
76 return h(props.tag, data, i18n.i(path, locale, params))
77 }
78}