-
Notifications
You must be signed in to change notification settings - Fork 487
/
main.coffee
427 lines (330 loc) · 12.4 KB
/
main.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
class FormbuilderModel extends Backbone.DeepModel
sync: -> # noop
indexInDOM: ->
$wrapper = $(".fb-field-wrapper").filter ( (_, el) => $(el).data('cid') == @cid )
$(".fb-field-wrapper").index $wrapper
is_input: ->
Formbuilder.inputFields[@get(Formbuilder.options.mappings.FIELD_TYPE)]?
class FormbuilderCollection extends Backbone.Collection
initialize: ->
@on 'add', @copyCidToModel
model: FormbuilderModel
comparator: (model) ->
model.indexInDOM()
copyCidToModel: (model) ->
model.attributes.cid = model.cid
class ViewFieldView extends Backbone.View
className: "fb-field-wrapper"
events:
'click .subtemplate-wrapper': 'focusEditView'
'click .js-duplicate': 'duplicate'
'click .js-clear': 'clear'
initialize: (options) ->
{@parentView} = options
@listenTo @model, "change", @render
@listenTo @model, "destroy", @remove
render: ->
@$el.addClass('response-field-' + @model.get(Formbuilder.options.mappings.FIELD_TYPE))
.data('cid', @model.cid)
.html(Formbuilder.templates["view/base#{if !@model.is_input() then '_non_input' else ''}"]({rf: @model}))
return @
focusEditView: ->
@parentView.createAndShowEditView(@model)
clear: (e) ->
e.preventDefault()
e.stopPropagation()
cb = =>
@parentView.handleFormUpdate()
@model.destroy()
x = Formbuilder.options.CLEAR_FIELD_CONFIRM
switch typeof x
when 'string'
if confirm(x) then cb()
when 'function'
x(cb)
else
cb()
duplicate: ->
attrs = _.clone(@model.attributes)
delete attrs['id']
attrs['label'] += ' Copy'
@parentView.createField attrs, { position: @model.indexInDOM() + 1 }
class EditFieldView extends Backbone.View
className: "edit-response-field"
events:
'click .js-add-option': 'addOption'
'click .js-remove-option': 'removeOption'
'click .js-default-updated': 'defaultUpdated'
'input .option-label-input': 'forceRender'
initialize: (options) ->
{@parentView} = options
@listenTo @model, "destroy", @remove
render: ->
@$el.html(Formbuilder.templates["edit/base#{if !@model.is_input() then '_non_input' else ''}"]({rf: @model}))
rivets.bind @$el, { model: @model }
return @
remove: ->
@parentView.editView = undefined
@parentView.$el.find("[data-target=\"#addField\"]").click()
super
# @todo this should really be on the model, not the view
addOption: (e) ->
$el = $(e.currentTarget)
i = @$el.find('.option').index($el.closest('.option'))
options = @model.get(Formbuilder.options.mappings.OPTIONS) || []
newOption = {label: "", checked: false}
if i > -1
options.splice(i + 1, 0, newOption)
else
options.push newOption
@model.set Formbuilder.options.mappings.OPTIONS, options
@model.trigger "change:#{Formbuilder.options.mappings.OPTIONS}"
@forceRender()
removeOption: (e) ->
$el = $(e.currentTarget)
index = @$el.find(".js-remove-option").index($el)
options = @model.get Formbuilder.options.mappings.OPTIONS
options.splice index, 1
@model.set Formbuilder.options.mappings.OPTIONS, options
@model.trigger "change:#{Formbuilder.options.mappings.OPTIONS}"
@forceRender()
defaultUpdated: (e) ->
$el = $(e.currentTarget)
unless @model.get(Formbuilder.options.mappings.FIELD_TYPE) == 'checkboxes' # checkboxes can have multiple options selected
@$el.find(".js-default-updated").not($el).attr('checked', false).trigger('change')
@forceRender()
forceRender: ->
@model.trigger('change')
class BuilderView extends Backbone.View
SUBVIEWS: []
events:
'click .js-save-form': 'saveForm'
'click .fb-tabs a': 'showTab'
'click .fb-add-field-types a': 'addField'
'mouseover .fb-add-field-types': 'lockLeftWrapper'
'mouseout .fb-add-field-types': 'unlockLeftWrapper'
initialize: (options) ->
{selector, @formBuilder, @bootstrapData} = options
# This is a terrible idea because it's not scoped to this view.
if selector?
@setElement $(selector)
# Create the collection, and bind the appropriate events
@collection = new FormbuilderCollection
@collection.bind 'add', @addOne, @
@collection.bind 'reset', @reset, @
@collection.bind 'change', @handleFormUpdate, @
@collection.bind 'destroy add reset', @hideShowNoResponseFields, @
@collection.bind 'destroy', @ensureEditViewScrolled, @
@render()
@collection.reset(@bootstrapData)
@bindSaveEvent()
bindSaveEvent: ->
@formSaved = true
@saveFormButton = @$el.find(".js-save-form")
@saveFormButton.attr('disabled', true).text(Formbuilder.options.dict.ALL_CHANGES_SAVED)
unless !Formbuilder.options.AUTOSAVE
setInterval =>
@saveForm.call(@)
, 5000
$(window).bind 'beforeunload', =>
if @formSaved then undefined else Formbuilder.options.dict.UNSAVED_CHANGES
reset: ->
@$responseFields.html('')
@addAll()
render: ->
@$el.html Formbuilder.templates['page']()
# Save jQuery objects for easy use
@$fbLeft = @$el.find('.fb-left')
@$responseFields = @$el.find('.fb-response-fields')
@bindWindowScrollEvent()
@hideShowNoResponseFields()
# Render any subviews (this is an easy way of extending the Formbuilder)
new subview({parentView: @}).render() for subview in @SUBVIEWS
return @
bindWindowScrollEvent: ->
$(window).on 'scroll', =>
return if @$fbLeft.data('locked') == true
newMargin = Math.max(0, $(window).scrollTop() - @$el.offset().top)
maxMargin = @$responseFields.height()
@$fbLeft.css
'margin-top': Math.min(maxMargin, newMargin)
showTab: (e) ->
$el = $(e.currentTarget)
target = $el.data('target')
$el.closest('li').addClass('active').siblings('li').removeClass('active')
$(target).addClass('active').siblings('.fb-tab-pane').removeClass('active')
@unlockLeftWrapper() unless target == '#editField'
if target == '#editField' && !@editView && (first_model = @collection.models[0])
@createAndShowEditView(first_model)
addOne: (responseField, _, options) ->
view = new ViewFieldView
model: responseField
parentView: @
#####
# Calculates where to place this new field.
#
# Are we replacing a temporarily drag placeholder?
if options.$replaceEl?
options.$replaceEl.replaceWith(view.render().el)
# Are we adding to the bottom?
else if !options.position? || options.position == -1
@$responseFields.append view.render().el
# Are we adding to the top?
else if options.position == 0
@$responseFields.prepend view.render().el
# Are we adding below an existing field?
else if ($replacePosition = @$responseFields.find(".fb-field-wrapper").eq(options.position))[0]
$replacePosition.before view.render().el
# Catch-all: add to bottom
else
@$responseFields.append view.render().el
setSortable: ->
@$responseFields.sortable('destroy') if @$responseFields.hasClass('ui-sortable')
@$responseFields.sortable
forcePlaceholderSize: true
placeholder: 'sortable-placeholder'
stop: (e, ui) =>
if ui.item.data('field-type')
rf = @collection.create Formbuilder.helpers.defaultFieldAttrs(ui.item.data('field-type')), {$replaceEl: ui.item}
@createAndShowEditView(rf)
@handleFormUpdate()
return true
update: (e, ui) =>
# ensureEditViewScrolled, unless we're updating from the draggable
@ensureEditViewScrolled() unless ui.item.data('field-type')
@setDraggable()
setDraggable: ->
$addFieldButtons = @$el.find("[data-field-type]")
$addFieldButtons.draggable
connectToSortable: @$responseFields
helper: =>
$helper = $("<div class='response-field-draggable-helper' />")
$helper.css
width: @$responseFields.width() # hacky, won't get set without inline style
height: '80px'
$helper
addAll: ->
@collection.each @addOne, @
@setSortable()
hideShowNoResponseFields: ->
@$el.find(".fb-no-response-fields")[if @collection.length > 0 then 'hide' else 'show']()
addField: (e) ->
field_type = $(e.currentTarget).data('field-type')
@createField Formbuilder.helpers.defaultFieldAttrs(field_type)
createField: (attrs, options) ->
rf = @collection.create attrs, options
@createAndShowEditView(rf)
@handleFormUpdate()
createAndShowEditView: (model) ->
$responseFieldEl = @$el.find(".fb-field-wrapper").filter( -> $(@).data('cid') == model.cid )
$responseFieldEl.addClass('editing').siblings('.fb-field-wrapper').removeClass('editing')
if @editView
if @editView.model.cid is model.cid
@$el.find(".fb-tabs a[data-target=\"#editField\"]").click()
@scrollLeftWrapper($responseFieldEl)
return
@editView.remove()
@editView = new EditFieldView
model: model
parentView: @
$newEditEl = @editView.render().$el
@$el.find(".fb-edit-field-wrapper").html $newEditEl
@$el.find(".fb-tabs a[data-target=\"#editField\"]").click()
@scrollLeftWrapper($responseFieldEl)
return @
ensureEditViewScrolled: ->
return unless @editView
@scrollLeftWrapper $(".fb-field-wrapper.editing")
scrollLeftWrapper: ($responseFieldEl) ->
@unlockLeftWrapper()
return unless $responseFieldEl[0]
$.scrollWindowTo ((@$el.offset().top + $responseFieldEl.offset().top) - @$responseFields.offset().top), 200, =>
@lockLeftWrapper()
lockLeftWrapper: ->
@$fbLeft.data('locked', true)
unlockLeftWrapper: ->
@$fbLeft.data('locked', false)
handleFormUpdate: ->
return if @updatingBatch
@formSaved = false
@saveFormButton.removeAttr('disabled').text(Formbuilder.options.dict.SAVE_FORM)
saveForm: (e) ->
return if @formSaved
@formSaved = true
@saveFormButton.attr('disabled', true).text(Formbuilder.options.dict.ALL_CHANGES_SAVED)
@collection.sort()
payload = JSON.stringify fields: @collection.toJSON()
if Formbuilder.options.HTTP_ENDPOINT then @doAjaxSave(payload)
@formBuilder.trigger 'save', payload
doAjaxSave: (payload) ->
$.ajax
url: Formbuilder.options.HTTP_ENDPOINT
type: Formbuilder.options.HTTP_METHOD
data: payload
contentType: "application/json"
success: (data) =>
@updatingBatch = true
for datum in data
# set the IDs of new response fields, returned from the server
@collection.get(datum.cid)?.set({id: datum.id})
@collection.trigger 'sync'
@updatingBatch = undefined
class Formbuilder
@helpers:
defaultFieldAttrs: (field_type) ->
attrs = {}
attrs[Formbuilder.options.mappings.LABEL] = 'Untitled'
attrs[Formbuilder.options.mappings.FIELD_TYPE] = field_type
attrs[Formbuilder.options.mappings.REQUIRED] = true
attrs['field_options'] = {}
Formbuilder.fields[field_type].defaultAttributes?(attrs) || attrs
simple_format: (x) ->
x?.replace(/\n/g, '<br />')
@options:
BUTTON_CLASS: 'fb-button'
HTTP_ENDPOINT: ''
HTTP_METHOD: 'POST'
AUTOSAVE: true
CLEAR_FIELD_CONFIRM: false
mappings:
SIZE: 'field_options.size'
UNITS: 'field_options.units'
LABEL: 'label'
FIELD_TYPE: 'field_type'
REQUIRED: 'required'
ADMIN_ONLY: 'admin_only'
OPTIONS: 'field_options.options'
DESCRIPTION: 'field_options.description'
INCLUDE_OTHER: 'field_options.include_other_option'
INCLUDE_BLANK: 'field_options.include_blank_option'
INTEGER_ONLY: 'field_options.integer_only'
MIN: 'field_options.min'
MAX: 'field_options.max'
MINLENGTH: 'field_options.minlength'
MAXLENGTH: 'field_options.maxlength'
LENGTH_UNITS: 'field_options.min_max_length_units'
dict:
ALL_CHANGES_SAVED: 'All changes saved'
SAVE_FORM: 'Save form'
UNSAVED_CHANGES: 'You have unsaved changes. If you leave this page, you will lose those changes!'
@fields: {}
@inputFields: {}
@nonInputFields: {}
@registerField: (name, opts) ->
for x in ['view', 'edit']
opts[x] = _.template(opts[x])
opts.field_type = name
Formbuilder.fields[name] = opts
if opts.type == 'non_input'
Formbuilder.nonInputFields[name] = opts
else
Formbuilder.inputFields[name] = opts
constructor: (opts={}) ->
_.extend @, Backbone.Events
args = _.extend opts, {formBuilder: @}
@mainView = new BuilderView args
window.Formbuilder = Formbuilder
if module?
module.exports = Formbuilder
else
window.Formbuilder = Formbuilder