forked from softwarerero/meteor-accounts-t9n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
t9n.coffee
88 lines (75 loc) · 2.39 KB
/
t9n.coffee
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
Meteor?.startup ->
if Meteor.isClient
Template?.registerHelper 't9n', (x, params) ->
T9n.get(x, true, params.hash)
class T9n
@maps: {}
@defaultLanguage: 'en'
@language: ''
@dep: undefined
@depLanguage: undefined
@missingPrefix = ">"
@missingPostfix = "<"
@setTracker = (tracker) ->
@tracker = tracker
@dep = new tracker.Tracker.Dependency()
@depLanguage = new @tracker.Tracker.Dependency()
@map: (language, map) ->
if(!@maps[language])
@maps[language] = {}
@registerMap(language, '', false, map)
@dep?.changed()
@get: (label, markIfMissing = true, args = {}, language) ->
@dep?.depend()
@depLanguage?.depend()
if typeof label != 'string' then return ''
language ?= @language
ret = @maps[language]?[label]
unless ret
index = language.lastIndexOf '_'
if index
parent = language.substring 0, index
if parent
return @get label, markIfMissing, args, parent
unless ret
ret = @maps[@defaultLanguage]?[label]
unless ret
return if markIfMissing then @missingPrefix + label + @missingPostfix else label
if Object.keys(args).length == 0 then ret else @replaceParams ret, args
@registerMap = (language, prefix, dot, map) ->
if typeof map == 'string'
@maps[language][prefix] = map
else if typeof map == 'object'
if dot
prefix = prefix + '.'
for key, value of map
@registerMap(language, prefix + key, true, value)
@getLanguage: () ->
@depLanguage?.depend()
return @language
@getLanguages: () ->
@dep?.depend()
return Object.keys(@maps).sort()
@getLanguageInfo: () ->
@dep?.depend()
keys = Object.keys(@maps).sort()
for k in keys
{name: @maps[k]['t9Name'], code: k}
@setLanguage: (language) ->
if @language is language then return # silent
language = language.replace(new RegExp('-', 'g'), '_')
unless @maps[language] # try parent variants
return if language.indexOf('_') > 1
@setLanguage language.substring 0, language.lastIndexOf '_'
else
throw Error "language #{language} does not exist"
@language = language
@depLanguage?.changed()
@replaceParams = (str, args) ->
for key, value of args
re = new RegExp "@{#{key}}", 'g'
str = str.replace re, value
str
@T9n = T9n
@t9n = (x, includePrefix, params) -> T9n.get(x)
module?.exports.T9n = T9n