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