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