JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
restyle annotations
[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         ret += '.ann_box {'
235         ret +=     'z-index: 5;'
236         ret +=     'position: absolute;'
237         ret +=     'border: 1px solid rgba(0,0,0,.1);'
238         ret += '}'
239         ret += '.ann_tag {'
240         ret +=     'z-index: 10;'
241         ret +=     'position: absolute;'
242         ret +=     'font-size: 8px;'
243         ret +=     'white-space: pre;'
244         ret +=     'background: rgba(255,255,255,0.4);'
245         ret += '}'
246         return ret
247
248 # key codes:
249 KEY_LEFT = 37
250 KEY_UP = 38
251 KEY_RIGHT = 39
252 KEY_DOWN = 40
253 KEY_BACKSPACE = 8 # <--
254 KEY_DELETE = 46 # -->
255 KEY_END = 35
256 KEY_ENTER = 13
257 KEY_ESCAPE = 27
258 KEY_HOME = 36
259 KEY_INSERT = 45
260 KEY_PAGE_UP = 33
261 KEY_PAGE_DOWN = 34
262 KEY_TAB = 9
263
264 ignore_key_codes =
265         '18': true # alt
266         '20': true # capslock
267         '17': true # ctrl
268         '144': true # numlock
269         '16': true # shift
270         '91': true # windows "start" key
271 control_key_codes = # we react to these, but they aren't typing
272         '37': KEY_LEFT
273         '38': KEY_UP
274         '39': KEY_RIGHT
275         '40': KEY_DOWN
276         '35': KEY_END
277         '8':  KEY_BACKSPACE
278         '46': KEY_DELETE
279         '13': KEY_ENTER
280         '27': KEY_ESCAPE
281         '36': KEY_HOME
282         '45': KEY_INSERT
283         '33': KEY_PAGE_UP
284         '34': KEY_PAGE_DOWN
285         '9':  KEY_TAB
286
287 instantiate_tree = (tree, parent) ->
288         remove = []
289         for c, i in tree
290                 switch c.type
291                         when 'text'
292                                 c.el = parent.ownerDocument.createTextNode c.text
293                                 parent.appendChild c.el
294                         when 'tag'
295                                 if c.name in ['script', 'object', 'iframe', 'link']
296                                         # TODO put placeholders instead
297                                         remove.unshift i
298                                 # TODO create in correct namespace
299                                 c.el = parent.ownerDocument.createElement c.name
300                                 for k, v of c.attrs
301                                         # FIXME if attr_whitelist[k]?
302                                         c.el.setAttribute k, v
303                                 parent.appendChild c.el
304                                 if c.children.length
305                                         instantiate_tree c.children, c.el
306         for i in remove
307                 tree.splice i, 1
308
309 traverse_tree = (tree, cb) ->
310         done = false
311         for c in tree
312                 done = cb c
313                 return done if done
314                 if c.children.length
315                         done = traverse_tree c.children, cb
316                         return done if done
317         return done
318
319 find_next_cursor_position = (tree, n, i) ->
320         if n.type is 'text' and n.text.length > i
321                 orig_xyh = cursor_to_xyh n, i
322                 unless orig_xyh?
323                         console.log "ERROR: couldn't find xy for current cursor location"
324                         return
325                 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
326                         next_xyh = cursor_to_xyh n, next_i
327                         if next_xyh?
328                                 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
329                                         return [n, next_i]
330         state_before = true
331         found = null
332         traverse_tree tree, (node, state) ->
333                 if node.type is 'text' and state_before is false
334                         if cursor_to_xyh(node, 0)?
335                                 found = node
336                                 return true
337                 if node is n
338                         state_before = false
339                 return false
340         if found?
341                 return [found, 0]
342         return null
343
344 find_prev_cursor_position = (tree, n, i) ->
345         if n? and n.type is 'text' and i > 0
346                 orig_xyh = cursor_to_xyh n, i
347                 unless orig_xyh?
348                         console.log "ERROR: couldn't find xy for current cursor location"
349                         return
350                 for prev_i in [i-1 .. 0]
351                         prev_xyh = cursor_to_xyh n, prev_i
352                         if prev_xyh?
353                                 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
354                                         return [n, prev_i]
355                 return [n, i - 1]
356         found_prev = n?
357         found = null
358         traverse_tree tree, (node) ->
359                 if node.type is 'text'
360                         if node is n
361                                 if found_prev?
362                                         found = found_prev
363                                 return true
364                         found_prev = node
365                 return false
366         if found?
367                 if cursor_to_xyh found, found.text.length # text visible?
368                         return [found, found.text.length]
369                 return find_prev_cursor_position tree, found, 0
370         return null
371
372 find_loc_cursor_position = (tree, loc) ->
373         for c in tree
374                 if c.type is 'tag' or c.type is 'text'
375                         bounds = get_el_bounds c.el
376                         continue if loc.x < bounds.x
377                         continue if loc.x > bounds.x + bounds.w
378                         continue if loc.y < bounds.y
379                         continue if loc.y > bounds.y + bounds.h
380                         if c.children.length
381                                 ret = find_loc_cursor_position c.children, loc
382                                 return ret if ret?
383                         if c.type is 'text'
384                                 # click is within bounding box that contains all text.
385                                 return [c, 0] if c.text.length is 0
386                                 before_i = 0
387                                 before = cursor_to_xyh c, before_i
388                                 unless before?
389                                         console.log "error: failed to find cursor pixel location for start of", c
390                                         return
391                                 after_i = c.text.length
392                                 after = cursor_to_xyh c, after_i
393                                 unless after?
394                                         console.log "error: failed to find cursor pixel location for end of", c
395                                         return
396                                 if loc.y < before.y + before.h and loc.x < before.x
397                                         # console.log 'before first char on first line'
398                                         continue
399                                 if loc.y > after.y and loc.x > after.x
400                                         # console.log 'after last char on last line'
401                                         continue
402                                 if loc.y < before.y
403                                         console.log "Warning: click in bounding box but above first line"
404                                         continue # above first line (runaround?)
405                                 if loc.y > after.y + after.h
406                                         console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
407                                         continue # below last line (shouldn't happen?)
408                                 while after_i - before_i > 1
409                                         cur_i = Math.round((before_i + after_i) / 2)
410                                         cur = cursor_to_xyh c, cur_i
411                                         unless loc?
412                                                 console.log "error: failed to find cursor pixel location for", c, cur_i
413                                                 return
414                                         if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
415                                                 after_i = cur_i
416                                                 after = cur
417                                         else
418                                                 before_i = cur_i
419                                                 before = cur
420                                 # which one is closest?
421                                 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
422                                         return [c, before_i]
423                                 else
424                                         return [c, after_i]
425         return null
426
427 # browsers collapse these (html5 spec calls these "space characters")
428 is_space_code = (char_code) ->
429         switch char_code
430                 when 9, 10, 12, 13, 32
431                         return true
432         return false
433 is_space = (chr) ->
434         return is_space_code chr.charCodeAt 0
435
436 tree_remove_empty_text_nodes = (tree) ->
437         empties = []
438         traverse_tree tree, (n) ->
439                 if n.type is 'text'
440                         if n.text.length is 0
441                                 empties.unshift n
442                 return false
443         for n in empties
444                 # don't completely empty the tree
445                 if tree.length is 1
446                         if tree[0].type is 'text'
447                                 console.log "oop, leaving a blank node because it's the only thing"
448                                 return
449                 n.el.parentNode.removeChild n.el
450                 for c, i in n.parent.children
451                         if c is n
452                                 n.parent.children.splice i, 1
453                                 break
454
455 # pass a array of nodes (from parser library, ie it should have .el and .text)
456 tree_dedup_space = (tree) ->
457         prev = cur = next = null
458         prev_i = cur_i = next_i = 0
459         prev_pos = pos = next_pos = null
460         prev_px = cur_px = next_px = null
461         first = true
462         removed_char = null
463
464         tree_remove_empty_text_nodes(tree)
465
466         iterate = (tree, cb) ->
467                 for n in tree
468                         if n.type is 'text'
469                                 i = 0
470                                 while i < n.text.length # don't foreach, cb might remove chars
471                                         advance = cb n, i
472                                         if advance
473                                                 i += 1
474                         if n.type is 'tag'
475                                 block = is_display_block n.el
476                                 if block
477                                         cb null
478                                 if n.children.length > 0
479                                         iterate n.children, cb
480                                 if block
481                                         cb null
482         # remove cur char
483         remove = ->
484                 removed_char = cur.text.charAt(cur_i)
485                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
486                 if next is cur # in same text node
487                         if next_i is 0
488                                 throw "how is this possible?"
489                         next_i -= 1
490                 return true
491         # undo remove()
492         put_it_back = ->
493                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
494                 if next is cur # in same text node
495                         next_i += 1
496                 return false
497         # return true if cur was removed from the dom (ie re-use same prev)
498         operate = ->
499                 # cur definitately set
500                 # prev and/or next might be null, indicating the start/end of a display:block
501                 return false unless is_space_code cur.text.charCodeAt cur_i
502                 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
503                 # consistent cases:
504                 # 1. zero rects returned by getClientRects() means collapsed space
505                 if bounds is null
506                         return remove()
507                 # 2. width greater than zero means visible space
508                 if bounds.w > 0
509                         return false
510                 # now the weird edge cases...
511                 #
512                 # firefox and chromium both report zero width for characters at the end
513                 # of a line where the text wraps (automatically, due to word-wrap) to
514                 # the next line. These do not appear to be distinguishable from
515                 # collapsed spaces via the range/bounds api, so...
516                 #
517                 # remove it from the dom, and if prev or next moves, put it back.
518                 if prev? and not prev_px?
519                         prev_px = cursor_to_xyh prev, prev_i
520                 if next? and not next_px?
521                         next_px = cursor_to_xyh next, next_i
522                 #if prev is null and next is null
523                 #       parent_px = cur.parent.el.getBoundingClientRect()
524                 remove()
525                 if prev?
526                         if prev_px?
527                                 new_prev_px = cursor_to_xyh prev, prev_i
528                                 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
529                                         return put_it_back()
530                         else
531                                 console.log "this shouldn't happen, we remove spaces that don't locate"
532                 if next?
533                         if next_px?
534                                 new_next_px = cursor_to_xyh next, next_i
535                                 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
536                                         return put_it_back()
537                         #else
538                         #       console.log "removing space becase space after it is collapsed"
539                 return true
540         # pass null at start/end of display:block
541         queue = (n, i) ->
542                 next = n
543                 next_i = i
544                 next_px = null
545                 advance = true
546                 if cur?
547                         removed = operate()
548                         # don't advance (to the next character next time) if we removed a
549                         # character from the same text node as ``next``, because doing so
550                         # renumbers the indexes in that string
551                         if removed and cur is next
552                                 advance = false
553                 else
554                         removed = false
555                 unless removed
556                         prev = cur
557                         prev_i = cur_i
558                         prev_px = cur_px
559                 cur = next
560                 cur_i = next_i
561                 cur_px = next_px
562                 return advance
563         queue null
564         iterate tree, queue
565         queue null
566
567         tree_remove_empty_text_nodes(tree)
568
569 class PeachHTML5Editor
570         # Options: (all optional)
571         #   editor_id: "id" attribute for outer-most element created by/for editor
572         #   on_init: callback for when the editable content is in place
573         constructor: (in_el, options) ->
574                 @options = options ? {}
575                 @in_el = in_el
576                 @tree = []
577                 @matting = []
578                 @inited = false # when iframes have loaded
579                 @outer_iframe # iframe to hold editor
580                 @outer_idoc # "document" object for @outer_iframe
581                 @wrap2 = null # scrollbar is on this
582                 @iframe = null # iframe to hold editable content
583                 @idoc = null # "document" object for @iframe
584                 @cursor = null
585                 @cursor_el = null
586                 @cursor_visible = false
587                 @iframe_offset = null
588                 opt_fragment = @options.fragment ? true
589                 @parser_opts = {}
590                 if opt_fragment
591                         @parser_opts.fragment = 'body'
592
593                 @outer_iframe = domify document, iframe: {}
594                 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
595                 if @options.editor_id?
596                         @outer_iframe.setAttribute 'id', @options.editor_id
597                 @outer_iframe.onload = =>
598                         @outer_idoc = @outer_iframe.contentDocument
599                         icss = domify @outer_idoc, style: children: [
600                                 domify @outer_idoc, text: css
601                         ]
602                         @outer_idoc.head.appendChild icss
603                         @iframe = domify @outer_idoc, iframe: {}
604                         @iframe.onload = =>
605                                 @init()
606                         setTimeout (=> @init() unless @inited), 200 # firefox never fires this onload
607                         @outer_idoc.body.appendChild(
608                                 domify @outer_idoc, div: id: 'wrap1', children: [
609                                         @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
610                                                 domify @outer_idoc, div: id: 'wrap3', children: [
611                                                         @iframe
612                                                         @overlay = domify @outer_idoc, div: id: 'overlay'
613                                                 ]
614                                         ]
615                                 ]
616                         )
617                 outer_wrap = domify document, div: class: 'peach_html5_editor'
618                 @in_el.parentNode.appendChild outer_wrap
619                 outer_bounds = get_el_bounds outer_wrap
620                 if outer_bounds.w < 300
621                         outer_bounds.w = 300
622                 if outer_bounds.h < 300
623                         outer_bounds.h = 300
624                 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
625                 @outer_iframe.setAttribute 'style', outer_iframe_style
626                 css = outer_css w: outer_bounds.w, h: outer_bounds.h
627                 outer_wrap.appendChild @outer_iframe
628         init: -> # called by @iframe's onload (or timeout on firefox)
629                 @idoc = @iframe.contentDocument
630                 @overlay.onclick = (e) =>
631                         return event_return e, @onclick e
632                 @overlay.ondoubleclick = (e) =>
633                         return event_return e, @ondoubleclick e
634                 @outer_idoc.body.onkeyup = (e) =>
635                         return event_return e, @onkeyup e
636                 @outer_idoc.body.onkeydown = (e) =>
637                         return event_return e, @onkeydown e
638                 @outer_idoc.body.onkeypress = (e) =>
639                         return event_return e, @onkeypress e
640                 if @options.stylesheet
641                         # TODO test this
642                         @idoc.head.appendChild domify @idoc, style: src: @options.stylesheet
643                 @load_html @in_el.value
644                 @inited = true
645                 if @options.on_init?
646                         @options.on_init()
647         overlay_event_to_inner_xy: (e) ->
648                 unless @iframe_offset?
649                         @iframe_offset = get_el_bounds @iframe
650                 x = e.pageX # TODO ?cross-browserify
651                 y = e.pageY + @wrap2.scrollTop # TODO ?cross-browserify
652                 # TODO adjust for scrolling
653                 return x: x - @iframe_offset.x, y: y - @iframe_offset.y
654         onclick: (e) ->
655                 xy = @overlay_event_to_inner_xy e
656                 new_cursor = find_loc_cursor_position @tree, xy
657                 if new_cursor?
658                         @move_cursor new_cursor
659                 return false
660         ondoubleclick: (e) ->
661                 return false
662         onkeyup: (e) ->
663                 return if e.ctrlKey
664                 return false if ignore_key_codes[e.keyCode]?
665                 #return false if control_key_codes[e.keyCode]?
666         onkeydown: (e) ->
667                 return if e.ctrlKey
668                 return false if ignore_key_codes[e.keyCode]?
669                 #return false if control_key_codes[e.keyCode]?
670                 switch e.keyCode
671                         when KEY_LEFT
672                                 if @cursor?
673                                         new_cursor = find_prev_cursor_position @tree, @cursor...
674                                         if new_cursor?
675                                                 @move_cursor new_cursor
676                                 else
677                                         for c in @tree
678                                                 new_cursor = find_next_cursor_position @tree, c, -1
679                                                 if new_cursor?
680                                                         @move_cursor new_cursor
681                                                         break
682                                 return false
683                         when KEY_UP
684                                 return false
685                         when KEY_RIGHT
686                                 if @cursor?
687                                         new_cursor = find_next_cursor_position @tree, @cursor...
688                                         if new_cursor?
689                                                 @move_cursor new_cursor
690                                 else
691                                         for c in @tree
692                                                 new_cursor = find_prev_cursor_position @tree, c, -1
693                                                 if new_cursor?
694                                                         @move_cursor new_cursor
695                                                         break
696                                 return false
697                         when KEY_DOWN
698                                 return false
699                         when KEY_END
700                                 return false
701                         when KEY_BACKSPACE
702                                 return false unless @cursor?
703                                 return false unless @cursor[1] > 0
704                                 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
705                                 @cursor[0].el.nodeValue = @cursor[0].text
706                                 @move_cursor [@cursor[0], @cursor[1] - 1]
707                                 @changed()
708                                 return false
709                         when KEY_DELETE
710                                 return false unless @cursor?
711                                 return false unless @cursor[1] < @cursor[0].text.length
712                                 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
713                                 @cursor[0].el.nodeValue = @cursor[0].text
714                                 @move_cursor [@cursor[0], @cursor[1]]
715                                 @changed()
716                                 return false
717                         when KEY_ENTER
718                                 return false
719                         when KEY_ESCAPE
720                                 return false
721                         when KEY_HOME
722                                 return false
723                         when KEY_INSERT
724                                 return false
725                         when KEY_PAGE_UP
726                                 return false
727                         when KEY_PAGE_DOWN
728                                 return false
729                         when KEY_TAB
730                                 return false
731         onkeypress: (e) ->
732                 return if e.ctrlKey
733                 return false if ignore_key_codes[e.keyCode]?
734                 return false if control_key_codes[e.keyCode]? # handled in keydown
735                 char = e.charCode ? e.keyCode
736                 if char and @cursor?
737                         char = String.fromCharCode char
738                         if @cursor[1] is 0
739                                 @cursor[0].text = char + @cursor[0].text
740                         else if @cursor[1] is @cursor[0].text.length - 1
741                                 @cursor[0].text += char
742                         else
743                                 @cursor[0].text =
744                                         @cursor[0].text.substr(0, @cursor[1]) +
745                                         char +
746                                         @cursor[0].text.substr(@cursor[1])
747                         @cursor[0].el.nodeValue = @cursor[0].text
748                         @move_cursor [@cursor[0], @cursor[1] + 1]
749                         @changed()
750                 return false
751         clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
752                 while @idoc.body.childNodes.length
753                         @idoc.body.removeChild @idoc.body.childNodes[0]
754                 @kill_cursor()
755                 return
756         load_html: (html) ->
757                 @tree = peach_parser.parse html, @parser_opts
758                 @clear_dom()
759                 instantiate_tree @tree, @idoc.body
760                 tree_dedup_space @tree
761                 @changed()
762         changed: ->
763                 @in_el.onchange = null
764                 @in_el.value = @pretty_html @tree
765                 @in_el.onchange = =>
766                         @load_html @in_el.value
767                 @iframe.style.height = "0"
768                 @iframe.style.height = "#{@idoc.body.scrollHeight}px"
769         kill_cursor: -> # remove it, forget where it was
770                 if @cursor_visible
771                         @cursor_el.parentNode.removeChild @cursor_el
772                         @cursor_visible = false
773                 @cursor = null
774                 @matt null
775         move_cursor: (cursor) ->
776                 loc = cursor_to_xyh cursor[0], cursor[1]
777                 unless loc?
778                         console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
779                         return
780                 @cursor = cursor
781                 # replace cursor element, to reset blink animation
782                 if @cursor_visible
783                         @cursor_el.parentNode.removeChild @cursor_el
784                 @cursor_el = domify @outer_idoc, div: id: 'cursor'
785                 @overlay.appendChild @cursor_el
786                 @cursor_visible = true
787                 @cursor_el.style.left = "#{loc.x + overlay_padding - 1}px"
788                 @cursor_el.style.top = "#{loc.y + overlay_padding}px"
789                 @matt cursor[0]
790         matt: (n) ->
791                 while @matting.length > 0
792                         @overlay.removeChild @matting[0]
793                         @matting.shift()
794                 return unless n?
795                 prev_bounds = x: 0, y: 0, w: 0, h: 0
796                 alpha = 0.1
797                 while n?.el?
798                         if n.type is 'text'
799                                 n = n.parent
800                                 continue
801                         bounds = get_el_bounds n.el
802                         return unless bounds?
803                         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
804                                 n = n.parent
805                                 continue
806                         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});
807                         @overlay.appendChild matt
808                         @matting.push matt
809                         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} "]
810                         @overlay.appendChild ann
811                         @matting.push ann
812                         n = n.parent
813                         alpha *= 1.5
814         pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
815                 ret = ''
816                 want_nl = parent_flags.want_nl
817                 prev_in_flow_is_text = false
818                 prev_in_flow_is_block = false
819                 for n, i in tree
820                         # figure out flags
821                         inner_flags = want_nl: true
822                         is_br = false
823                         switch n.type
824                                 when 'tag'
825                                         if n.name is 'br'
826                                                 is_br = true
827                                         is_text = false
828                                         if n.el.currentStyle?
829                                                 cs = n.el.currentStyle
830                                                 whitespace = cs['white-space']
831                                                 display = cs['display']
832                                                 position = cs['position']
833                                                 float = cs['float']
834                                         else
835                                                 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
836                                                 whitespace = cs.getPropertyValue 'white-space'
837                                                 display = cs.getPropertyValue 'display'
838                                                 position = cs.getPropertyValue 'position'
839                                                 float = cs.getPropertyValue 'float'
840                                         if n.name is 'textarea'
841                                                 inner_flags.pre_ish = true
842                                         else
843                                                 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
844                                         switch float
845                                                 when 'left', 'right'
846                                                         in_flow = false
847                                                 else
848                                                         switch position
849                                                                 when 'absolute', 'fixed'
850                                                                         in_flow = false
851                                                                 else
852                                                                         if 'display' is 'none'
853                                                                                 in_flow = false
854                                                                         else
855                                                                                 in_flow = true
856                                         switch display
857                                                 when 'inline', 'none'
858                                                         inner_flags.block = false
859                                                         is_block = in_flow_block = false
860                                                 when 'inline-black'
861                                                         inner_flags.block = true
862                                                         is_block = in_flow_block = false
863                                                 else # block, table, etc
864                                                         inner_flags.block = true
865                                                         is_block = true
866                                                         in_flow_block = in_flow
867                                 when 'text'
868                                         is_text = true
869                                         is_block = false
870                                         in_flow = true
871                                         in_flow_block = false
872                                 else # 'comment', 'doctype'
873                                         is_text = false
874                                         is_block = false
875                                         in_flow = false
876                                         in_flow_block = false
877                         # print whitespace if we can
878                         unless parent_flags.pre_ish
879                                 unless prev_in_flow_is_text and is_br
880                                         if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
881                                                 if want_nl
882                                                         ret += "\n"
883                                                 ret += indent
884                         switch n.type
885                                 when 'tag'
886                                         ret += '<' + n.name
887                                         attr_keys = []
888                                         for k of n.attrs
889                                                 attr_keys.unshift k
890                                         #attr_keys.sort()
891                                         for k in attr_keys
892                                                 ret += " #{k}"
893                                                 if n.attrs[k].length > 0
894                                                         ret += "=\"#{enc_attr n.attrs[k]}\""
895                                         ret += '>'
896                                         unless void_elements[n.name]?
897                                                 if inner_flags.block
898                                                         next_indent = indent + '    '
899                                                 else
900                                                         next_indent = indent
901                                                 if n.children.length
902                                                         ret += @pretty_html n.children, next_indent, inner_flags
903                                                 ret += "</#{n.name}>"
904                                 when 'text'
905                                         ret += enc_text n.text
906                                 when 'comment'
907                                         ret += "<!--#{n.text}-->" # TODO encode?
908                                 when 'doctype'
909                                         ret += "<!DOCTYPE #{n.name}"
910                                         if n.public_identifier? and n.public_identifier.length > 0
911                                                 ret += " \"#{n.public_identifier}\""
912                                         if n.system_identifier? and n.system_identifier.length > 0
913                                                 ret += " \"#{n.system_identifier}\""
914                                         ret += ">"
915                         want_nl = true
916                         if in_flow
917                                 prev_in_flow_is_text = is_text
918                                 prev_in_flow_is_block = is_block or (in_flow and is_br)
919                 if tree.length
920                         # output final newline if allowed
921                         unless parent_flags.pre_ish
922                                 if prev_in_flow_is_block or parent_flags.block
923                                         ret += "\n#{indent.substr 4}"
924                 return ret
925
926 window.peach_html5_editor = (args...) ->
927         return new PeachHTML5Editor args...
928
929 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])