1
// Extensions
2
import { Service } from '../service'
3

4
// Utilities
5
import { getObjectValueByPath } from '../../util/helpers'
6
import { consoleError, consoleWarn } from '../../util/console'
7

8
// Types
9
import { VuetifyPreset } from 'vuetify/types/services/presets'
10
import {
11
  VuetifyLocale,
12
  Lang as ILang,
13
} from 'vuetify/types/services/lang'
14

15 1
const LANG_PREFIX = '$vuetify.'
16 1
const fallback = Symbol('Lang fallback')
17

18
function getTranslation (
19
  locale: VuetifyLocale,
20
  key: string,
21 1
  usingDefault = false,
22
  defaultLocale: VuetifyLocale
23 1
): string {
24 1
  const shortKey = key.replace(LANG_PREFIX, '')
25 1
  let translation = getObjectValueByPath(locale, shortKey, fallback) as string | typeof fallback
26

27 1
  if (translation === fallback) {
28 1
    if (usingDefault) {
29 1
      consoleError(`Translation key "${shortKey}" not found in fallback`)
30 1
      translation = key
31
    } else {
32 1
      consoleWarn(`Translation key "${shortKey}" not found, falling back to default`)
33 1
      translation = getTranslation(defaultLocale, key, true, defaultLocale)
34
    }
35
  }
36

37 1
  return translation
38
}
39

40
export class Lang extends Service implements ILang {
41 1
  static property: 'lang' = 'lang'
42

43
  public current: ILang['current']
44

45 1
  public defaultLocale = 'en'
46

47
  public locales: ILang['locales']
48

49
  private translator: ILang['t']
50

51 1
  constructor (preset: VuetifyPreset) {
52 1
    super()
53

54
    const {
55
      current,
56
      locales,
57
      t,
58 1
    } = preset[Lang.property]
59

60 1
    this.current = current
61 1
    this.locales = locales
62 1
    this.translator = t || this.defaultTranslator
63
  }
64

65 1
  public currentLocale (key: string) {
66 1
    const translation = this.locales[this.current]
67 1
    const defaultLocale = this.locales[this.defaultLocale]
68

69 1
    return getTranslation(translation, key, false, defaultLocale)
70
  }
71

72 1
  public t (key: string, ...params: any[]) {
73 1
    if (!key.startsWith(LANG_PREFIX)) return this.replace(key, params)
74

75 1
    return this.translator(key, ...params)
76
  }
77

78 1
  private defaultTranslator (key: string, ...params: any[]) {
79 1
    return this.replace(this.currentLocale(key), params)
80
  }
81

82 1
  private replace (str: string, params: any[]) {
83 1
    return str.replace(/\{(\d+)\}/g, (match: string, index: string) => {
84
      /* istanbul ignore next */
85
      return String(params[+index])
86
    })
87
  }
88
}

Read our documentation on viewing source code .

Loading