JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
7ef8e37cc3ba42548625da61ec02ccdafcb3747b
[peach-html5-editor.git] / editor.coffee
1 # Copyright 2015 Jason Woofenden
2 # This file implements an WYSIWYG editor in the browser (no contenteditable)
3 #
4 # This program is free software: you can redistribute it and/or modify it under
5 # the terms of the GNU Affero General Public License as published by the Free
6 # Software Foundation, either version 3 of the License, or (at your option) any
7 # later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 # SETTINGS
18 overlay_padding = 10
19
20 timeout = (ms, cb) -> return setTimeout cb, ms
21
22 # xml 1.0 says:
23 valid_attr_regex = new RegExp '^[a-zA-Z_:][-a-zA-Z0-9_:.]*$'
24 # html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
25 js_attr_regex = new RegExp '^[oO][nN].'
26
27 debug_dot_at = (doc, x, y) ->
28         return # disabled
29         el = doc.createElement 'div'
30         el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
31         doc.body.appendChild el
32         #console.log(new Error().stack)
33
34 # text nodes don't have getBoundingClientRect(), so use selection api to find
35 # it.
36 get_el_bounds = (el) ->
37         if el.getBoundingClientRect?
38                 rect = el.getBoundingClientRect()
39         else
40                 # text nodes don't have getBoundingClientRect(), so use range api
41                 range = el.ownerDocument.createRange()
42                 range.selectNodeContents el
43                 rect = range.getBoundingClientRect()
44         doc = el.ownerDocument.documentElement
45         win = el.ownerDocument.defaultView
46         y_fix = win.pageYOffset - doc.clientTop
47         x_fix = win.pageXOffset - doc.clientLeft
48         return {
49                 x: rect.left + x_fix
50                 y: rect.top + y_fix
51                 w: rect.width ? (rect.right - rect.left)
52                 h: rect.height ? (rect.top - rect.bottom)
53         }
54
55 is_display_block = (el) ->
56         if el.currentStyle?
57                 return el.currentStyle.display is 'block'
58         else
59                 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
60
61 # Pass return value from dom event handlers to this.
62 # If they return false, this will addinionally stop propagation and default.
63 event_return = (e, bool) ->
64         if bool is false
65                 if e.stopPropagation?
66                         e.stopPropagation()
67                 if e.preventDefault?
68                         e.preventDefault()
69         return bool
70 # Warning: currently assumes you're asking about a single character
71 # Note: chromium returns multiple bounding rects for a space at a line-break
72 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
73 # Note: sometimes returns null (eg for whitespace that is not visible)
74 text_range_bounds = (el, start, end) ->
75         range = document.createRange()
76         range.setStart el, start
77         range.setEnd el, end
78         rects = range.getClientRects()
79         if rects.length > 0
80                 rect = rects[0]
81         else
82                 return null
83         doc = el.ownerDocument.documentElement
84         win = el.ownerDocument.defaultView
85         y_fix = win.pageYOffset - doc.clientTop
86         x_fix = win.pageXOffset - doc.clientLeft
87         return {
88                 x: rect.left + x_fix
89                 y: rect.top + y_fix
90                 w: rect.width ? (rect.right - rect.left)
91                 h: rect.height ? (rect.top - rect.bottom)
92                 rects: rects
93                 bounding: range.getBoundingClientRect()
94         }
95
96 # figure out the x/y coordinates of where the cursor should be if it's at
97 # position ``i`` within text node ``n``
98 # sometimes returns null (eg for whitespace that is not visible)
99 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
100         range = document.createRange()
101         if n.text.length is 0
102                 ret = text_range_bounds n.el, 0, 0
103         else if i is n.text.length
104                 ret = text_range_bounds n.el, i - 1, i
105                 if ret?
106                         ret.x += ret.w
107         else
108                 ret = text_range_bounds n.el, i, i + 1
109         if ret?
110                 debug_dot_at n.el.ownerDocument, ret.x, ret.y
111         return ret
112
113 # encode text so it can be safely placed inside an html attribute
114 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
115 enc_attr = (txt) ->
116         return txt.replace enc_attr_regex, (match, amp, quote) ->
117                 return '&amp;' if (amp)
118                 return '&quot;' if (quote)
119                 return '&nbsp;'
120 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
121 enc_text = (txt) ->
122         return txt.replace enc_text_regex, (match, amp, lt) ->
123                 return '&amp;' if (amp)
124                 return '&lt;' if (lt)
125                 return '&nbsp;'
126
127 void_elements = {
128         area: true
129         base: true
130         br: true
131         col: true
132         embed: true
133         hr: true
134         img: true
135         input: true
136         keygen: true
137         link: true
138         meta: true
139         param: true
140         source: true
141         track: true
142         wbr: true
143 }
144 # TODO make these always pretty-print (on the inside) like blocks
145 no_text_elements = { # these elements never contain text
146         select: true
147         table: true
148         tr: true
149         thead: true
150         tbody: true
151         ul: true
152         ol: true
153 }
154
155 domify = (doc, hash) ->
156         for tag, attrs of hash
157                 if tag is 'text'
158                         return document.createTextNode attrs
159                 el = document.createElement tag
160                 for k, v of attrs
161                         if k is 'children'
162                                 for child in v
163                                         el.appendChild child
164                         else
165                                 el.setAttribute k, v
166         return el
167
168 outer_css = (args) ->
169         w = args.w ? 300
170         h = args.h ? 300
171         inner_padding = args.inner_padding ? overlay_padding
172         frame_width = args.frame_width ? inner_padding
173         # TODO editor controls height...
174         occupy = (left, top = left, right = left, bottom = top) ->
175                 w -= left + right
176                 h -= top + bottom
177                 return Math.max(left, top, right, bottom)
178         ret = ''
179         ret += 'body {'
180         ret +=     'margin: 0;'
181         ret +=     'padding: 0;'
182         ret += '}'
183         ret += '#wrap1 {'
184         ret +=     "border: #{occupy 1}px solid black;"
185         ret +=     "padding: #{occupy frame_width}px;"
186         ret += '}'
187         ret += '#wrap2 {'
188         ret +=     "border: #{occupy 1}px solid black;"
189         ret +=     "padding: #{occupy inner_padding}px;"
190         ret +=     "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
191         ret +=     "width: #{w}px;"
192         ret +=     "height: #{h}px;"
193         ret +=     'overflow-x: hidden;'
194         ret +=     'overflow-y: scroll;'
195         ret += '}'
196         ret += '#wrap3 {'
197         ret +=     'position: relative;'
198         ret +=     "width: #{w}px;"
199         ret +=     "min-height: #{h}px;"
200         ret += '}'
201         ret += 'iframe {'
202         ret +=     'box-sizing: border-box;'
203         ret +=     'margin: 0;'
204         ret +=     'border: none;'
205         ret +=     'padding: 0;'
206         ret +=     "width: #{w}px;"
207         #ret +=     "height: #{h}px;" # height auto-set when content set/changed
208         ret +=     '-ms-user-select: none;'
209         ret +=     '-webkit-user-select: none;'
210         ret +=     '-moz-user-select: none;'
211         ret +=     'user-select: none;'
212         ret += '}'
213         ret += '#overlay {'
214         ret +=     'position: absolute;'
215         ret +=     "left: -#{inner_padding}px;"
216         ret +=     "top: -#{inner_padding}px;"
217         ret +=     "right: -#{inner_padding}px;"
218         ret +=     "bottom: -#{inner_padding}px;"
219         ret +=     'overflow: hidden;'
220         ret += '}'
221         ret += '.lightbox {'
222         ret +=     'position: absolute;'
223         ret +=     'background: rgba(100,100,100,0.2);'
224         ret += '}'
225         ret += '#cursor {'
226         ret +=     'position: absolute;'
227         ret +=     'height: 1em;' # FIXME adjust for hight of text
228         ret +=     'width: 2px;'
229         ret +=     'background: #444;'
230         ret +=     '-webkit-animation: blink 1s steps(2, start) infinite;'
231         ret +=     'animation: blink 1s steps(2, start) infinite;'
232         ret += '}'
233         ret += '@-webkit-keyframes blink {'
234         ret +=     'to { visibility: hidden; }'
235         ret += '}'
236         ret += '@keyframes blink {'
237         ret +=     'to { visibility: hidden; }'
238         ret += '}'
239         ret += '.ann_box {'
240         ret +=     'z-index: 5;'
241         ret +=     'position: absolute;'
242         ret +=     'border: 1px solid rgba(0,0,0,0.1);'
243         ret +=     'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
244         ret += '}'
245         ret += '.ann_tag {'
246         ret +=     'z-index: 10;'
247         ret +=     'position: absolute;'
248         ret +=     'font-size: 8px;'
249         ret +=     'white-space: pre;'
250         ret +=     'background: rgba(255,255,255,0.4);'
251         ret += '}'
252         return ret
253
254 # key codes:
255 KEY_LEFT = 37
256 KEY_UP = 38
257 KEY_RIGHT = 39
258 KEY_DOWN = 40
259 KEY_BACKSPACE = 8 # <--
260 KEY_DELETE = 46 # -->
261 KEY_END = 35
262 KEY_ENTER = 13
263 KEY_ESCAPE = 27
264 KEY_HOME = 36
265 KEY_INSERT = 45
266 KEY_PAGE_UP = 33
267 KEY_PAGE_DOWN = 34
268 KEY_TAB = 9
269
270 ignore_key_codes =
271         '18': true # alt
272         '20': true # capslock
273         '17': true # ctrl
274         '144': true # numlock
275         '16': true # shift
276         '91': true # windows "start" key
277 control_key_codes = # we react to these, but they aren't typing
278         '37': KEY_LEFT
279         '38': KEY_UP
280         '39': KEY_RIGHT
281         '40': KEY_DOWN
282         '35': KEY_END
283         '8':  KEY_BACKSPACE
284         '46': KEY_DELETE
285         '13': KEY_ENTER
286         '27': KEY_ESCAPE
287         '36': KEY_HOME
288         '45': KEY_INSERT
289         '33': KEY_PAGE_UP
290         '34': KEY_PAGE_DOWN
291         '9':  KEY_TAB
292
293 instantiate_tree = (tree, parent) ->
294         remove = []
295         for c, i in tree
296                 switch c.type
297                         when 'text'
298                                 c.el = parent.ownerDocument.createTextNode c.text
299                                 parent.appendChild c.el
300                         when 'tag'
301                                 if c.name in ['script', 'object', 'iframe', 'link']
302                                         # TODO put placeholders instead
303                                         remove.unshift i
304                                         continue
305                                 # TODO create in correct namespace
306                                 c.el = parent.ownerDocument.createElement c.name
307                                 for k, v of c.attrs
308                                         # FIXME if attr_whitelist[k]?
309                                         if valid_attr_regex.test k
310                                                 unless js_attr_regex.test k
311                                                         c.el.setAttribute k, v
312                                 parent.appendChild c.el
313                                 if c.children.length
314                                         instantiate_tree c.children, c.el
315         for i in remove
316                 tree.splice i, 1
317
318 traverse_tree = (tree, cb) ->
319         done = false
320         for c in tree
321                 done = cb c
322                 return done if done
323                 if c.children.length
324                         done = traverse_tree c.children, cb
325                         return done if done
326         return done
327
328 find_next_cursor_position = (tree, n, i) ->
329         if n.type is 'text' and n.text.length > i
330                 orig_xyh = cursor_to_xyh n, i
331                 unless orig_xyh?
332                         console.log "ERROR: couldn't find xy for current cursor location"
333                         return
334                 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
335                         next_xyh = cursor_to_xyh n, next_i
336                         if next_xyh?
337                                 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
338                                         return [n, next_i]
339         state_before = true
340         found = null
341         traverse_tree tree, (node, state) ->
342                 if node.type is 'text' and state_before is false
343                         if cursor_to_xyh(node, 0)?
344                                 found = node
345                                 return true
346                 if node is n
347                         state_before = false
348                 return false
349         if found?
350                 return [found, 0]
351         return null
352
353 find_prev_cursor_position = (tree, n, i) ->
354         if n? and n.type is 'text' and i > 0
355                 orig_xyh = cursor_to_xyh n, i
356                 unless orig_xyh?
357                         console.log "ERROR: couldn't find xy for current cursor location"
358                         return
359                 for prev_i in [i-1 .. 0]
360                         prev_xyh = cursor_to_xyh n, prev_i
361                         if prev_xyh?
362                                 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
363                                         return [n, prev_i]
364                 return [n, i - 1]
365         found_prev = n?
366         found = null
367         traverse_tree tree, (node) ->
368                 if node.type is 'text'
369                         if node is n
370                                 if found_prev?
371                                         found = found_prev
372                                 return true
373                         found_prev = node
374                 return false
375         if found?
376                 if cursor_to_xyh found, found.text.length # text visible?
377                         return [found, found.text.length]
378                 return find_prev_cursor_position tree, found, 0
379         return null
380
381 find_loc_cursor_position = (tree, loc) ->
382         for c in tree
383                 if c.type is 'tag' or c.type is 'text'
384                         bounds = get_el_bounds c.el
385                         continue if loc.x < bounds.x
386                         continue if loc.x > bounds.x + bounds.w
387                         continue if loc.y < bounds.y
388                         continue if loc.y > bounds.y + bounds.h
389                         if c.children.length
390                                 ret = find_loc_cursor_position c.children, loc
391                                 return ret if ret?
392                         if c.type is 'text'
393                                 # click is within bounding box that contains all text.
394                                 return [c, 0] if c.text.length is 0
395                                 before_i = 0
396                                 before = cursor_to_xyh c, before_i
397                                 unless before?
398                                         console.log "error: failed to find cursor pixel location for start of", c
399                                         return
400                                 after_i = c.text.length
401                                 after = cursor_to_xyh c, after_i
402                                 unless after?
403                                         console.log "error: failed to find cursor pixel location for end of", c
404                                         return
405                                 if loc.y < before.y + before.h and loc.x < before.x
406                                         # console.log 'before first char on first line'
407                                         continue
408                                 if loc.y > after.y and loc.x > after.x
409                                         # console.log 'after last char on last line'
410                                         continue
411                                 if loc.y < before.y
412                                         console.log "Warning: click in bounding box but above first line"
413                                         continue # above first line (runaround?)
414                                 if loc.y > after.y + after.h
415                                         console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
416                                         continue # below last line (shouldn't happen?)
417                                 while after_i - before_i > 1
418                                         cur_i = Math.round((before_i + after_i) / 2)
419                                         cur = cursor_to_xyh c, cur_i
420                                         unless loc?
421                                                 console.log "error: failed to find cursor pixel location for", c, cur_i
422                                                 return
423                                         if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
424                                                 after_i = cur_i
425                                                 after = cur
426                                         else
427                                                 before_i = cur_i
428                                                 before = cur
429                                 # which one is closest?
430                                 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
431                                         return [c, before_i]
432                                 else
433                                         return [c, after_i]
434         return null
435
436 # browsers collapse these (html5 spec calls these "space characters")
437 is_space_code = (char_code) ->
438         switch char_code
439                 when 9, 10, 12, 13, 32
440                         return true
441         return false
442 is_space = (chr) ->
443         return is_space_code chr.charCodeAt 0
444
445 tree_remove_empty_text_nodes = (tree) ->
446         empties = []
447         traverse_tree tree, (n) ->
448                 if n.type is 'text'
449                         if n.text.length is 0
450                                 empties.unshift n
451                 return false
452         for n in empties
453                 # don't completely empty the tree
454                 if tree.length is 1
455                         if tree[0].type is 'text'
456                                 console.log "oop, leaving a blank node because it's the only thing"
457                                 return
458                 n.el.parentNode.removeChild n.el
459                 for c, i in n.parent.children
460                         if c is n
461                                 n.parent.children.splice i, 1
462                                 break
463
464 # pass a array of nodes (from parser library, ie it should have .el and .text)
465 tree_dedup_space = (tree) ->
466         prev = cur = next = null
467         prev_i = cur_i = next_i = 0
468         prev_pos = pos = next_pos = null
469         prev_px = cur_px = next_px = null
470         first = true
471         removed_char = null
472
473         tree_remove_empty_text_nodes(tree)
474
475         iterate = (tree, cb) ->
476                 for n in tree
477                         if n.type is 'text'
478                                 i = 0
479                                 while i < n.text.length # don't foreach, cb might remove chars
480                                         advance = cb n, i
481                                         if advance
482                                                 i += 1
483                         if n.type is 'tag'
484                                 block = is_display_block n.el
485                                 if block
486                                         cb null
487                                 if n.children.length > 0
488                                         iterate n.children, cb
489                                 if block
490                                         cb null
491         # remove cur char
492         remove = ->
493                 removed_char = cur.text.charAt(cur_i)
494                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
495                 if next is cur # in same text node
496                         if next_i is 0
497                                 throw "how is this possible?"
498                         next_i -= 1
499                 return true
500         # undo remove()
501         put_it_back = ->
502                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
503                 if next is cur # in same text node
504                         next_i += 1
505                 return false
506         # return true if cur was removed from the dom (ie re-use same prev)
507         operate = ->
508                 # cur definitately set
509                 # prev and/or next might be null, indicating the start/end of a display:block
510                 return false unless is_space_code cur.text.charCodeAt cur_i
511                 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
512                 # consistent cases:
513                 # 1. zero rects returned by getClientRects() means collapsed space
514                 if bounds is null
515                         return remove()
516                 # 2. width greater than zero means visible space
517                 if bounds.w > 0
518                         return false
519                 # now the weird edge cases...
520                 #
521                 # firefox and chromium both report zero width for characters at the end
522                 # of a line where the text wraps (automatically, due to word-wrap) to
523                 # the next line. These do not appear to be distinguishable from
524                 # collapsed spaces via the range/bounds api, so...
525                 #
526                 # remove it from the dom, and if prev or next moves, put it back.
527                 if prev? and not prev_px?
528                         prev_px = cursor_to_xyh prev, prev_i
529                 if next? and not next_px?
530                         next_px = cursor_to_xyh next, next_i
531                 #if prev is null and next is null
532                 #       parent_px = cur.parent.el.getBoundingClientRect()
533                 remove()
534                 if prev?
535                         if prev_px?
536                                 new_prev_px = cursor_to_xyh prev, prev_i
537                                 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
538                                         return put_it_back()
539                         else
540                                 console.log "this shouldn't happen, we remove spaces that don't locate"
541                 if next?
542                         if next_px?
543                                 new_next_px = cursor_to_xyh next, next_i
544                                 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
545                                         return put_it_back()
546                         #else
547                         #       console.log "removing space becase space after it is collapsed"
548                 return true
549         # pass null at start/end of display:block
550         queue = (n, i) ->
551                 next = n
552                 next_i = i
553                 next_px = null
554                 advance = true
555                 if cur?
556                         removed = operate()
557                         # don't advance (to the next character next time) if we removed a
558                         # character from the same text node as ``next``, because doing so
559                         # renumbers the indexes in that string
560                         if removed and cur is next
561                                 advance = false
562                 else
563                         removed = false
564                 unless removed
565                         prev = cur
566                         prev_i = cur_i
567                         prev_px = cur_px
568                 cur = next
569                 cur_i = next_i
570                 cur_px = next_px
571                 return advance
572         queue null
573         iterate tree, queue
574         queue null
575
576         tree_remove_empty_text_nodes(tree)
577
578 class PeachHTML5Editor
579         # Options: (all optional)
580         #   editor_id: "id" attribute for outer-most element created by/for editor
581         #   on_init: callback for when the editable content is in place
582         constructor: (in_el, options) ->
583                 @options = options ? {}
584                 @in_el = in_el
585                 @tree = []
586                 @matting = []
587                 @inited = false # when iframes have loaded
588                 @outer_iframe # iframe to hold editor
589                 @outer_idoc # "document" object for @outer_iframe
590                 @wrap2 = null # scrollbar is on this
591                 @iframe = null # iframe to hold editable content
592                 @idoc = null # "document" object for @iframe
593                 @cursor = null
594                 @cursor_el = null
595                 @cursor_visible = false
596                 @iframe_offset = null
597                 opt_fragment = @options.fragment ? true
598                 @parser_opts = {}
599                 if opt_fragment
600                         @parser_opts.fragment = 'body'
601
602                 @outer_iframe = domify document, iframe: {}
603                 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
604                 if @options.editor_id?
605                         @outer_iframe.setAttribute 'id', @options.editor_id
606                 @outer_iframe.onload = =>
607                         @outer_idoc = @outer_iframe.contentDocument
608                         icss = domify @outer_idoc, style: children: [
609                                 domify @outer_idoc, text: css
610                         ]
611                         @outer_idoc.head.appendChild icss
612                         @iframe = domify @outer_idoc, iframe: {}
613                         @iframe.onload = =>
614                                 @init()
615                         setTimeout (=> @init() unless @inited), 200 # firefox never fires this onload
616                         @outer_idoc.body.appendChild(
617                                 domify @outer_idoc, div: id: 'wrap1', children: [
618                                         @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
619                                                 domify @outer_idoc, div: id: 'wrap3', children: [
620                                                         @iframe
621                                                         @overlay = domify @outer_idoc, div: id: 'overlay'
622                                                 ]
623                                         ]
624                                 ]
625                         )
626                 outer_wrap = domify document, div: class: 'peach_html5_editor'
627                 @in_el.parentNode.appendChild outer_wrap
628                 outer_bounds = get_el_bounds outer_wrap
629                 if outer_bounds.w < 300
630                         outer_bounds.w = 300
631                 if outer_bounds.h < 300
632                         outer_bounds.h = 300
633                 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
634                 @outer_iframe.setAttribute 'style', outer_iframe_style
635                 css = outer_css w: outer_bounds.w, h: outer_bounds.h
636                 outer_wrap.appendChild @outer_iframe
637         init: -> # called by @iframe's onload (or timeout on firefox)
638                 @idoc = @iframe.contentDocument
639                 @overlay.onclick = (e) =>
640                         return event_return e, @onclick e
641                 @overlay.ondoubleclick = (e) =>
642                         return event_return e, @ondoubleclick e
643                 @outer_idoc.body.onkeyup = (e) =>
644                         return event_return e, @onkeyup e
645                 @outer_idoc.body.onkeydown = (e) =>
646                         return event_return e, @onkeydown e
647                 @outer_idoc.body.onkeypress = (e) =>
648                         return event_return e, @onkeypress e
649                 if @options.stylesheet
650                         # TODO test this
651                         @idoc.head.appendChild domify @idoc, style: src: @options.stylesheet
652                 @load_html @in_el.value
653                 @inited = true
654                 if @options.on_init?
655                         @options.on_init()
656         overlay_event_to_inner_xy: (e) ->
657                 unless @iframe_offset?
658                         @iframe_offset = get_el_bounds @iframe
659                 x = e.pageX # TODO ?cross-browserify
660                 y = e.pageY + @wrap2.scrollTop # TODO ?cross-browserify
661                 # TODO adjust for scrolling
662                 return x: x - @iframe_offset.x, y: y - @iframe_offset.y
663         onclick: (e) ->
664                 xy = @overlay_event_to_inner_xy e
665                 new_cursor = find_loc_cursor_position @tree, xy
666                 if new_cursor?
667                         @move_cursor new_cursor
668                 else
669                         @kill_cursor()
670                 return false
671         ondoubleclick: (e) ->
672                 return false
673         onkeyup: (e) ->
674                 return if e.ctrlKey
675                 return false if ignore_key_codes[e.keyCode]?
676                 #return false if control_key_codes[e.keyCode]?
677         onkeydown: (e) ->
678                 return if e.ctrlKey
679                 return false if ignore_key_codes[e.keyCode]?
680                 #return false if control_key_codes[e.keyCode]?
681                 switch e.keyCode
682                         when KEY_LEFT
683                                 if @cursor?
684                                         new_cursor = find_prev_cursor_position @tree, @cursor...
685                                         if new_cursor?
686                                                 @move_cursor new_cursor
687                                 else
688                                         for c in @tree
689                                                 new_cursor = find_next_cursor_position @tree, c, -1
690                                                 if new_cursor?
691                                                         @move_cursor new_cursor
692                                                         break
693                                 return false
694                         when KEY_UP
695                                 return false
696                         when KEY_RIGHT
697                                 if @cursor?
698                                         new_cursor = find_next_cursor_position @tree, @cursor...
699                                         if new_cursor?
700                                                 @move_cursor new_cursor
701                                 else
702                                         for c in @tree
703                                                 new_cursor = find_prev_cursor_position @tree, c, -1
704                                                 if new_cursor?
705                                                         @move_cursor new_cursor
706                                                         break
707                                 return false
708                         when KEY_DOWN
709                                 return false
710                         when KEY_END
711                                 return false
712                         when KEY_BACKSPACE
713                                 return false unless @cursor?
714                                 return false unless @cursor[1] > 0
715                                 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
716                                 @cursor[0].el.nodeValue = @cursor[0].text
717                                 @move_cursor [@cursor[0], @cursor[1] - 1]
718                                 @changed()
719                                 return false
720                         when KEY_DELETE
721                                 return false unless @cursor?
722                                 return false unless @cursor[1] < @cursor[0].text.length
723                                 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
724                                 @cursor[0].el.nodeValue = @cursor[0].text
725                                 @move_cursor [@cursor[0], @cursor[1]]
726                                 @changed()
727                                 return false
728                         when KEY_ENTER
729                                 return false
730                         when KEY_ESCAPE
731                                 return false
732                         when KEY_HOME
733                                 return false
734                         when KEY_INSERT
735                                 return false
736                         when KEY_PAGE_UP
737                                 return false
738                         when KEY_PAGE_DOWN
739                                 return false
740                         when KEY_TAB
741                                 return false
742         onkeypress: (e) ->
743                 return if e.ctrlKey
744                 return false if ignore_key_codes[e.keyCode]?
745                 return false if control_key_codes[e.keyCode]? # handled in keydown
746                 char = e.charCode ? e.keyCode
747                 if char and @cursor?
748                         char = String.fromCharCode char
749                         if @cursor[1] is 0
750                                 @cursor[0].text = char + @cursor[0].text
751                         else if @cursor[1] is @cursor[0].text.length - 1
752                                 @cursor[0].text += char
753                         else
754                                 @cursor[0].text =
755                                         @cursor[0].text.substr(0, @cursor[1]) +
756                                         char +
757                                         @cursor[0].text.substr(@cursor[1])
758                         @cursor[0].el.nodeValue = @cursor[0].text
759                         @move_cursor [@cursor[0], @cursor[1] + 1]
760                         @changed()
761                 return false
762         clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
763                 while @idoc.body.childNodes.length
764                         @idoc.body.removeChild @idoc.body.childNodes[0]
765                 @kill_cursor()
766                 return
767         load_html: (html) ->
768                 @tree = peach_parser.parse html, @parser_opts
769                 @clear_dom()
770                 instantiate_tree @tree, @idoc.body
771                 tree_dedup_space @tree
772                 @changed()
773         changed: ->
774                 @in_el.onchange = null
775                 @in_el.value = @pretty_html @tree
776                 @in_el.onchange = =>
777                         @load_html @in_el.value
778                 @iframe.style.height = "0"
779                 @iframe.style.height = "#{@idoc.body.scrollHeight}px"
780         kill_cursor: -> # remove it, forget where it was
781                 if @cursor_visible
782                         @cursor_el.parentNode.removeChild @cursor_el
783                         @cursor_visible = false
784                 @cursor = null
785                 @matt null
786         move_cursor: (cursor) ->
787                 loc = cursor_to_xyh cursor[0], cursor[1]
788                 unless loc?
789                         console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
790                         return
791                 @cursor = cursor
792                 # replace cursor element, to reset blink animation
793                 if @cursor_visible
794                         @cursor_el.parentNode.removeChild @cursor_el
795                 @cursor_el = domify @outer_idoc, div: id: 'cursor'
796                 @overlay.appendChild @cursor_el
797                 @cursor_visible = true
798                 @cursor_el.style.left = "#{loc.x + overlay_padding - 1}px"
799                 if loc.h < 5
800                         height = 12
801                 else
802                         height = loc.h
803                 @cursor_el.style.top = "#{loc.y + overlay_padding + Math.round(height * .07)}px"
804                 @cursor_el.style.height = "#{Math.round height * 0.82}px"
805                 @matt cursor[0]
806         matt: (n) ->
807                 while @matting.length > 0
808                         @overlay.removeChild @matting[0]
809                         @matting.shift()
810                 return unless n?
811                 prev_bounds = x: 0, y: 0, w: 0, h: 0
812                 alpha = 0.1
813                 while n?.el?
814                         if n.type is 'text'
815                                 n = n.parent
816                                 continue
817                         bounds = get_el_bounds n.el
818                         return unless bounds?
819                         if bounds.x is prev_bounds.x and bounds.y is prev_bounds.y and bounds.w is prev_bounds.w and bounds.h is prev_bounds.h
820                                 n = n.parent
821                                 continue
822                         matt = domify @outer_idoc, div: class: 'ann_box', style: "left: #{bounds.x - 1 + overlay_padding}px; top: #{bounds.y - 2 + overlay_padding}px; width: #{bounds.w}px; height: #{bounds.h}px" # outline: 1000px solid rgba(0,153,255,#{alpha});
823                         @overlay.appendChild matt
824                         @matting.push matt
825                         ann = domify @outer_idoc, div: class: 'ann_tag', style: "left: #{bounds.x + 1 + overlay_padding}px; top: #{bounds.y - 7 + overlay_padding}px", children: [domify @outer_idoc, text: " #{n.name} "]
826                         @overlay.appendChild ann
827                         @matting.push ann
828                         n = n.parent
829                         alpha *= 1.5
830         pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
831                 ret = ''
832                 want_nl = parent_flags.want_nl
833                 prev_in_flow_is_text = false
834                 prev_in_flow_is_block = false
835                 for n, i in tree
836                         # figure out flags
837                         inner_flags = want_nl: true
838                         is_br = false
839                         switch n.type
840                                 when 'tag'
841                                         if n.name is 'br'
842                                                 is_br = true
843                                         is_text = false
844                                         if n.el.currentStyle?
845                                                 cs = n.el.currentStyle
846                                                 whitespace = cs['white-space']
847                                                 display = cs['display']
848                                                 position = cs['position']
849                                                 float = cs['float']
850                                         else
851                                                 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
852                                                 whitespace = cs.getPropertyValue 'white-space'
853                                                 display = cs.getPropertyValue 'display'
854                                                 position = cs.getPropertyValue 'position'
855                                                 float = cs.getPropertyValue 'float'
856                                         if n.name is 'textarea'
857                                                 inner_flags.pre_ish = true
858                                         else
859                                                 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
860                                         switch float
861                                                 when 'left', 'right'
862                                                         in_flow = false
863                                                 else
864                                                         switch position
865                                                                 when 'absolute', 'fixed'
866                                                                         in_flow = false
867                                                                 else
868                                                                         if 'display' is 'none'
869                                                                                 in_flow = false
870                                                                         else
871                                                                                 in_flow = true
872                                         switch display
873                                                 when 'inline', 'none'
874                                                         inner_flags.block = false
875                                                         is_block = in_flow_block = false
876                                                 when 'inline-black'
877                                                         inner_flags.block = true
878                                                         is_block = in_flow_block = false
879                                                 else # block, table, etc
880                                                         inner_flags.block = true
881                                                         is_block = true
882                                                         in_flow_block = in_flow
883                                 when 'text'
884                                         is_text = true
885                                         is_block = false
886                                         in_flow = true
887                                         in_flow_block = false
888                                 else # 'comment', 'doctype'
889                                         is_text = false
890                                         is_block = false
891                                         in_flow = false
892                                         in_flow_block = false
893                         # print whitespace if we can
894                         unless parent_flags.pre_ish
895                                 unless prev_in_flow_is_text and is_br
896                                         if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
897                                                 if want_nl
898                                                         ret += "\n"
899                                                 ret += indent
900                         switch n.type
901                                 when 'tag'
902                                         ret += '<' + n.name
903                                         attr_keys = []
904                                         for k of n.attrs
905                                                 attr_keys.unshift k
906                                         #attr_keys.sort()
907                                         for k in attr_keys
908                                                 ret += " #{k}"
909                                                 if n.attrs[k].length > 0
910                                                         ret += "=\"#{enc_attr n.attrs[k]}\""
911                                         ret += '>'
912                                         unless void_elements[n.name]?
913                                                 if inner_flags.block
914                                                         next_indent = indent + '    '
915                                                 else
916                                                         next_indent = indent
917                                                 if n.children.length
918                                                         ret += @pretty_html n.children, next_indent, inner_flags
919                                                 ret += "</#{n.name}>"
920                                 when 'text'
921                                         ret += enc_text n.text
922                                 when 'comment'
923                                         ret += "<!--#{n.text}-->" # TODO encode?
924                                 when 'doctype'
925                                         ret += "<!DOCTYPE #{n.name}"
926                                         if n.public_identifier? and n.public_identifier.length > 0
927                                                 ret += " \"#{n.public_identifier}\""
928                                         if n.system_identifier? and n.system_identifier.length > 0
929                                                 ret += " \"#{n.system_identifier}\""
930                                         ret += ">"
931                         want_nl = true
932                         if in_flow
933                                 prev_in_flow_is_text = is_text
934                                 prev_in_flow_is_block = is_block or (in_flow and is_br)
935                 if tree.length
936                         # output final newline if allowed
937                         unless parent_flags.pre_ish
938                                 if prev_in_flow_is_block or parent_flags.block
939                                         ret += "\n#{indent.substr 4}"
940                 return ret
941
942 window.peach_html5_editor = (args...) ->
943         return new PeachHTML5Editor args...
944
945 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])