forked from danxexe/sms-counter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sms_counter.js.coffee
64 lines (50 loc) · 1.7 KB
/
sms_counter.js.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
window.SmsCounter = class SmsCounter
@gsm7bitChars = "@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà"
@gsm7bitExChar = "^{}\\[~]|€"
@gsm7bitRegExp = RegExp("^[#{(@gsm7bitChars)}]*$")
@gsm7bitExRegExp = RegExp("^[#{ (@gsm7bitChars)}#{(@gsm7bitExChar)}]*$")
@gsm7bitExOnlyRegExp = RegExp("^[\\#{(@gsm7bitExChar)}]*$")
@GSM_7BIT = 'GSM_7BIT'
@GSM_7BIT_EX = 'GSM_7BIT_EX'
@UTF16 = 'UTF16'
@messageLength =
GSM_7BIT: 160
GSM_7BIT_EX: 160
UTF16: 70
@multiMessageLength =
GSM_7BIT: 153
GSM_7BIT_EX: 153
UTF16: 67
@count: (text) ->
encoding = @detectEncoding(text)
length = text.length
length += @countGsm7bitEx(text) if encoding == @GSM_7BIT_EX
per_message = @messageLength[encoding]
per_message = @multiMessageLength[encoding] if length > per_message
messages = Math.ceil(length / per_message)
remaining = (per_message * messages) - length
count =
encoding: encoding
length: length
per_message: per_message
remaining: remaining
messages: messages
@detectEncoding: (text) ->
switch
when text.match(@gsm7bitRegExp)? then @GSM_7BIT
when text.match(@gsm7bitExRegExp)? then @GSM_7BIT_EX
else @UTF16
@countGsm7bitEx: (text) ->
chars = (char2 for char2 in text when char2.match(@gsm7bitExOnlyRegExp)?)
chars.length
if jQuery?
$ = jQuery
$.fn.countSms = (target) ->
input = @
target = $(target)
count_sms = ->
count = SmsCounter.count(input.val())
for k, v of count
target.find(".#{k}").text(v)
@.on 'keyup', count_sms
count_sms()