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