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