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