File size: 1,058 Bytes
4d70170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { simpleGet } from '@vue-devtools/shared-utils'
import type { Plugin } from 'vue'

const reg = /\{\{\s*([\w.-]+)\s*\}\}/g

interface StringMap { [key: string]: string | StringMap }
interface ValuesMap { [key: string]: any }
type Replacer = (text: string) => string

let strings: StringMap
let defaultValues: ValuesMap
let replacer: Replacer

export function translate(path: string | string[], values: ValuesMap = {}) {
  values = Object.assign({}, defaultValues, values)
  let text = simpleGet(strings, path)
  text = text.replace(reg, (substring, matched) => {
    const value = simpleGet(values, matched)
    return typeof value !== 'undefined' ? value : substring
  })
  replacer && (text = replacer(text))
  return text
}

interface Options {
  strings: StringMap
  defaultValues: ValuesMap
  replacer: Replacer
}

export default {
  install(app, options: Options) {
    strings = options.strings || {}
    defaultValues = options.defaultValues || {}
    replacer = options.replacer
    app.config.globalProperties.$t = translate
  },
} as Plugin