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