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