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