forked from RobertLowe/autoform-pickadate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
autoform-pickadate.coffee
96 lines (85 loc) · 2.84 KB
/
autoform-pickadate.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
89
90
91
92
93
94
95
96
utcToLocal = (utcDate) ->
localDateObj = new Date
localDateObj.setDate utcDate.getUTCDate()
localDateObj.setMonth utcDate.getUTCMonth()
localDateObj.setFullYear utcDate.getUTCFullYear()
localDateObj.setHours 0
localDateObj.setMinutes 0
localDateObj.setSeconds 0
localDateObj.setMilliseconds 0
localDateObj
addInputType = (type) ->
template = 'af' + (type.slice(0, 1).toUpperCase() + type.slice(1))
options =
template: template
valueOut: ->
if @val()
picker = @pickadate('picker')
if picker
val = picker.get('select').obj
else
val = @val()
return if val instanceof Date then val else @val()
return ""
valueConverters:
'string': (val) ->
if val instanceof Date then AutoForm.Utility.dateToDateStringUTC(val) else val
'stringArray': (val) ->
if val instanceof Date
return [ AutoForm.Utility.dateToDateStringUTC(val) ]
val
'number': (val) ->
if val instanceof Date then val.getTime() else val
'numberArray': (val) ->
if val instanceof Date
return [ val.getTime() ]
val
'dateArray': (val) ->
if val instanceof Date
return [ val ]
val
AutoForm.addInputType type, options
Template[template].helpers
atts: ->
atts = _.clone(@atts)
atts = AutoForm.Utility.addClass(atts, 'form-control')
# cannot have nested atts or Blaze explodes
delete atts["#{type}Options"]
atts
Template[template].rendered = ->
$input = @$('input')
data = @data
$input[type](data.atts["#{type}Options"])
$picker = $input[type]('picker')
# After selection ensure focus is lost, fixes an issue when switching tabs
# and returning to the window would open the picker
$picker.on 'close', ()->
$(document.activeElement).blur()
@autorun ->
data = Template.currentData()
# set field value
if data.value instanceof Date
$picker.set 'select', data.value
else if typeof data.value == 'string'
if data.value != ""
$picker.set 'select', data.value
# set start date if there's a min in the schema
if data.min instanceof Date
# datepicker plugin expects local Date object,
# so convert UTC Date object to local
startDate = utcToLocal(data.min)
$picker.set 'min', startDate
# set end date if there's a max in the schema
if data.max instanceof Date
# datepicker plugin expects local Date object,
# so convert UTC Date object to local
endDate = utcToLocal(data.max)
$picker.set 'max', startDate
Template[template].destroyed = ->
$input = @$('input')
if $input
$picker = $input[type]('picker')
if $picker && $picker.stop
$picker.stop()
addInputType 'pickadate'
addInputType 'pickatime'