This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 318
/
hallo.coffee
449 lines (381 loc) · 13.2 KB
/
hallo.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
###
Hallo {{ VERSION }} - a rich text editing jQuery UI widget
(c) 2011 Henri Bergius, IKS Consortium
Hallo may be freely distributed under the MIT license
http://hallojs.org
###
((jQuery) ->
# Hallo provides a jQuery UI widget `hallo`. Usage:
#
# jQuery('p').hallo();
#
# Getting out of the editing state:
#
# jQuery('p').hallo({editable: false});
#
# When content is in editable state, users can just click on
# an editable element in order to start modifying it. This
# relies on browser having support for the HTML5 contentEditable
# functionality, which means that some mobile browsers are not
# supported.
#
# If plugins providing toolbar buttons have been enabled for
# Hallo, then a toolbar will be rendered when an area is active.
#
# ## Toolbar
#
# Hallo ships with different toolbar options, including:
#
# * `halloToolbarContextual`: a toolbar that appears as a popover
# dialog when user makes a selection
# * `halloToolbarFixed`: a toolbar that is constantly visible above
# the editable area when the area is activated
#
# The toolbar can be defined by the `toolbar` configuration key,
# which has to conform to the toolbar widget being used.
#
# Just like with plugins, it is possible to use Hallo with your own
# custom toolbar implementation.
#
# ## Events
#
# The Hallo editor provides several jQuery events that web
# applications can use for integration:
#
# ### Activated
#
# When user activates an editable (usually by clicking or tabbing
# to an editable element), a `halloactivated` event will be fired.
#
# jQuery('p').on('halloactivated', function() {
# console.log("Activated");
# });
#
# ### Deactivated
#
# When user gets out of an editable element, a `hallodeactivated`
# event will be fired.
#
# jQuery('p').on('hallodeactivated', function() {
# console.log("Deactivated");
# });
#
# ### Modified
#
# When contents in an editable have been modified, a
# `hallomodified` event will be fired.
#
# jQuery('p').on('hallomodified', function(event, data) {
# console.log("New contents are " + data.content);
# });
#
# ### Restored
#
# When contents are restored through calling
# `.hallo("restoreOriginalContent")` or the user pressing ESC while
# the cursor is in the editable element, a 'hallorestored' event will
# be fired.
#
# jQuery('p').on('hallorestored', function(event, data) {
# console.log("The thrown contents are " + data.thrown);
# console.log("The restored contents are " + data.content);
# });
#
jQuery.widget 'IKS.hallo',
toolbar: null
bound: false
originalContent: ''
previousContent: ''
uuid: ''
selection: null
_keepActivated: false
originalHref: null
options:
editable: true
plugins: {}
toolbar: 'halloToolbarContextual'
parentElement: 'body'
buttonCssClass: null
toolbarCssClass: null
toolbarPositionAbove: false
toolbarOptions: {}
placeholder: ''
forceStructured: true
checkTouch: true
touchScreen: null
_create: ->
@id = @_generateUUID()
@checkTouch() if @options.checkTouch and @options.touchScreen is null
for plugin, options of @options.plugins
options = {} unless jQuery.isPlainObject options
jQuery.extend options,
editable: this
uuid: @id
buttonCssClass: @options.buttonCssClass
jQuery(@element)[plugin] options
@element.one 'halloactivated', =>
# We will populate the toolbar the first time this
# editable is activated. This will make multiple
# Hallo instances on same page load much faster
@_prepareToolbar()
@originalContent = @getContents()
_init: ->
if @options.editable
@enable()
else
@disable()
destroy: ->
@disable()
if @toolbar
@toolbar.remove()
@element[@options.toolbar] 'destroy'
for plugin, options of @options.plugins
jQuery(@element)[plugin] 'destroy'
jQuery.Widget::destroy.call @
# Disable an editable
disable: ->
@element.attr "contentEditable", false
@element.off "focus", @_activated
@element.off "blur", @_deactivated
@element.off "keyup paste change", @_checkModified
@element.off "keyup", @_keys
@element.off "keyup mouseup", @_checkSelection
@bound = false
jQuery(@element).removeClass 'isModified'
jQuery(@element).removeClass 'inEditMode'
@element.parents('a').addBack().each (idx, elem) =>
element = jQuery elem
return unless element.is 'a'
return unless @originalHref
element.attr 'href', @originalHref
@_trigger "disabled", null
# Enable an editable
enable: ->
@element.parents('a[href]').addBack().each (idx, elem) =>
element = jQuery elem
return unless element.is 'a[href]'
@originalHref = element.attr 'href'
element.removeAttr 'href'
@element.attr "contentEditable", true
unless jQuery.parseHTML(@element.html())
@element.html this.options.placeholder
jQuery(@element).addClass 'inPlaceholderMode'
@element.css
'min-width': @element.innerWidth()
'min-height': @element.innerHeight()
unless @bound
@element.on "focus", this, @_activated
@element.on "blur", this, @_deactivated
@element.on "keyup paste change", this, @_checkModified
@element.on "keyup", this, @_keys
@element.on "keyup mouseup", this, @_checkSelection
@bound = true
@_forceStructured() if @options.forceStructured
@_trigger "enabled", null
# Activate an editable for editing
activate: ->
@element.focus()
# Checks whether the editable element contains the current selection
containsSelection: ->
range = @getSelection()
return @element.has(range.startContainer).length > 0
# Only supports one range for now (i.e. no multiselection)
getSelection: ->
sel = rangy.getSelection()
range = null
if sel.rangeCount > 0
range = sel.getRangeAt(0)
else
range = rangy.createRange()
return range
restoreSelection: (range) ->
sel = rangy.getSelection()
sel.setSingleRange(range)
replaceSelection: (cb) ->
if navigator.appName is 'Microsoft Internet Explorer'
t = document.selection.createRange().text
r = document.selection.createRange()
r.pasteHTML(cb(t))
else
sel = window.getSelection()
range = sel.getRangeAt(0)
newTextNode = document.createTextNode(cb(range.extractContents()))
range.insertNode(newTextNode)
range.setStartAfter(newTextNode)
sel.removeAllRanges()
sel.addRange(range)
removeAllSelections: () ->
if navigator.appName is 'Microsoft Internet Explorer'
range.empty()
else
window.getSelection().removeAllRanges()
getPluginInstance: (plugin) ->
# jQuery UI 1.10 or newer
instance = jQuery(@element).data "IKS-#{plugin}"
return instance if instance
# Older jQuery UI
instance = jQuery(@element).data plugin
return instance if instance
throw new Error "Plugin #{plugin} not found"
# Get contents of an editable as HTML string
getContents: ->
for plugin of @options.plugins
instance = @getPluginInstance(plugin)
continue unless instance
cleanup = instance.cleanupContentClone
continue unless jQuery.isFunction cleanup
jQuery(@element)[plugin] 'cleanupContentClone', @element
@element.html()
# Set the contents of an editable
setContents: (contents) ->
@element.html contents
# Check whether the editable has been modified
isModified: ->
@previousContent = @originalContent unless @previousContent
@previousContent isnt @getContents()
# Set the editable as unmodified
setUnmodified: ->
jQuery(@element).removeClass 'isModified'
@previousContent = @getContents()
# Set the editable as modified
setModified: ->
jQuery(@element).addClass 'isModified'
@._trigger 'modified', null,
editable: @
content: @getContents()
# Restore the content original
restoreOriginalContent: () ->
@element.html(@originalContent)
# Execute a contentEditable command
execute: (command, value) ->
if document.execCommand command, false, value
@element.trigger "change"
protectFocusFrom: (el) ->
el.on "mousedown", (event) =>
event.preventDefault()
@_protectToolbarFocus = true
setTimeout =>
@_protectToolbarFocus = false
, 300
keepActivated: (@_keepActivated) ->
_generateUUID: ->
S4 = ->
((1 + Math.random()) * 0x10000|0).toString(16).substring 1
"#{S4()}#{S4()}-#{S4()}-#{S4()}-#{S4()}-#{S4()}#{S4()}#{S4()}"
_prepareToolbar: ->
@toolbar = jQuery('<div class="hallotoolbar"></div>').hide()
@toolbar.addClass @options.toolbarCssClass if @options.toolbarCssClass
defaults =
editable: @
parentElement: @options.parentElement
toolbar: @toolbar
positionAbove: @options.toolbarPositionAbove
toolbarOptions = jQuery.extend({}, defaults, @options.toolbarOptions)
@element[@options.toolbar] toolbarOptions
for plugin of @options.plugins
instance = @getPluginInstance(plugin)
continue unless instance
populate = instance.populateToolbar
continue unless jQuery.isFunction populate
@element[plugin] 'populateToolbar', @toolbar
@element[@options.toolbar] 'setPosition'
@protectFocusFrom @toolbar
changeToolbar: (element, toolbar, hide = false) ->
originalToolbar = @options.toolbar
@options.parentElement = element
@options.toolbar = toolbar if toolbar
return unless @toolbar
@element[originalToolbar] 'destroy'
do @toolbar.remove
do @_prepareToolbar
@toolbar.hide() if hide
_checkModified: (event) ->
widget = event.data
widget.setModified() if widget.isModified()
_keys: (event) ->
widget = event.data
if event.keyCode == 27
old = widget.getContents()
widget.restoreOriginalContent(event)
widget._trigger "restored", null,
editable: widget
content: widget.getContents()
thrown: old
widget.turnOff()
_rangesEqual: (r1, r2) ->
return false unless r1.startContainer is r2.startContainer
return false unless r1.startOffset is r2.startOffset
return false unless r1.endContainer is r2.endContainer
return false unless r1.endOffset is r2.endOffset
true
# Check if some text is selected, and if this selection has changed.
# If it changed, trigger the "halloselected" event
_checkSelection: (event) ->
if event.keyCode == 27
return
widget = event.data
# The mouseup event triggers before the text selection is updated.
# I did not find a better solution than setTimeout in 0 ms
setTimeout ->
sel = widget.getSelection()
if widget._isEmptySelection(sel) or widget._isEmptyRange(sel)
if widget.selection
widget.selection = null
widget._trigger "unselected", null,
editable: widget
originalEvent: event
return
if !widget.selection or not widget._rangesEqual sel, widget.selection
widget.selection = sel.cloneRange()
widget._trigger "selected", null,
editable: widget
selection: widget.selection
ranges: [widget.selection]
originalEvent: event
, 0
_isEmptySelection: (selection) ->
if selection.type is "Caret"
return true
return false
_isEmptyRange: (range) ->
if range.collapsed
return true
if range.isCollapsed
return range.isCollapsed() if typeof range.isCollapsed is 'function'
return range.isCollapsed
return false
turnOn: () ->
if this.getContents() is this.options.placeholder
this.setContents ''
jQuery(@element).removeClass 'inPlaceholderMode'
jQuery(@element).addClass 'inEditMode'
@_trigger "activated", null, @
turnOff: () ->
jQuery(@element).removeClass 'inEditMode'
@_trigger "deactivated", null, @
unless @getContents()
jQuery(@element).addClass 'inPlaceholderMode'
@setContents @options.placeholder
_activated: (event) ->
event.data.turnOn()
_deactivated: (event) ->
return if event.data._keepActivated
unless event.data._protectToolbarFocus is true
event.data.turnOff()
else
setTimeout ->
jQuery(event.data.element).focus()
, 300
_forceStructured: (event) ->
try
document.execCommand 'styleWithCSS', 0, false
catch e
try
document.execCommand 'useCSS', 0, true
catch e
try
document.execCommand 'styleWithCSS', false, false
catch e
checkTouch: ->
@options.touchScreen = !!('createTouch' of document)
)(jQuery)