JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
nother iframe, auto-generate css, fix typing, break scrolling
[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
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 css = ''
179 css += 'body {'
180 css +=     'margin: 0;'
181 css +=     'padding: 0;'
182 css += '}'
183 css += '#wrap1 {'
184 css +=     'border: 1px solid black;'
185 css +=     "padding: #{overlay_padding}px;"
186 css += '}'
187 css += '#wrap2 {'
188 css +=     'border: 1px solid black;'
189 css +=     "padding: #{overlay_padding}px;"
190 css += '}'
191 css += '#wrap3 {'
192 css +=     'position: relative;'
193 css += '}'
194 css += 'iframe {'
195 css +=     'box-sizing: border-box;'
196 css +=     'margin: 0;'
197 css +=     'border: none;'
198 css +=     'padding: 0;'
199 css +=     "width: #{300 - 4 - 4 * overlay_padding}px;"
200 css +=     "height: #{300 - 4 - 4 * overlay_padding}px;"
201 css += '}'
202 css += '#overlay {'
203 css +=     'position: absolute;'
204 css +=     "left: -#{overlay_padding}px;"
205 css +=     "top: -#{overlay_padding}px;"
206 css +=     "right: -#{overlay_padding}px;"
207 css +=     "bottom: -#{overlay_padding}px;"
208 css +=     'overflow: hidden;'
209 css += '}'
210 css += '.lightbox {'
211 css +=     'position: absolute;'
212 css +=     'background: rgba(100,100,100,0.2);'
213 css += '}'
214 css += '#cursor {'
215 css +=     'position: absolute;'
216 css +=     'height: 1em;'
217 css +=     'width: 2px;'
218 css +=     'margin-left: -1px;'
219 css +=     'margin-right: -1px;'
220 css +=     'background: #444;'
221 css +=     '-webkit-animation: blink 1s steps(2, start) infinite;'
222 css +=     'animation: blink 1s steps(2, start) infinite;'
223 css += '}'
224 css += '@-webkit-keyframes blink {'
225 css +=     'to { visibility: hidden; }'
226 css += '}'
227 css += '@keyframes blink {'
228 css +=     'to { visibility: hidden; }'
229 css += '}'
230
231 # key codes:
232 KEY_LEFT = 37
233 KEY_UP = 38
234 KEY_RIGHT = 39
235 KEY_DOWN = 40
236 KEY_BACKSPACE = 8 # <--
237 KEY_DELETE = 46 # -->
238 KEY_END = 35
239 KEY_ENTER = 13
240 KEY_ESCAPE = 27
241 KEY_HOME = 36
242 KEY_INSERT = 45
243 KEY_PAGE_UP = 33
244 KEY_PAGE_DOWN = 34
245 KEY_TAB = 9
246
247 ignore_key_codes =
248         '18': true # alt
249         '20': true # capslock
250         '17': true # ctrl
251         '144': true # numlock
252         '16': true # shift
253         '91': true # windows "start" key
254 control_key_codes = # we react to these, but they aren't typing
255         '37': KEY_LEFT
256         '38': KEY_UP
257         '39': KEY_RIGHT
258         '40': KEY_DOWN
259         '35': KEY_END
260         '8':  KEY_BACKSPACE
261         '46': KEY_DELETE
262         '13': KEY_ENTER
263         '27': KEY_ESCAPE
264         '36': KEY_HOME
265         '45': KEY_INSERT
266         '33': KEY_PAGE_UP
267         '34': KEY_PAGE_DOWN
268         '9':  KEY_TAB
269
270 instantiate_tree = (tree, parent) ->
271         for c in tree
272                 switch c.type
273                         when TYPE_TEXT
274                                 c.el = parent.ownerDocument.createTextNode c.text
275                                 parent.appendChild c.el
276                         when TYPE_TAG
277                                 # TODO create in correct namespace
278                                 c.el = parent.ownerDocument.createElement c.name
279                                 for k, v of c.attrs
280                                         # FIXME if attr_whitelist[k]?
281                                         c.el.setAttribute k, v
282                                 parent.appendChild c.el
283                                 if c.children.length
284                                         instantiate_tree c.children, c.el
285
286 traverse_tree = (tree, state, cb) ->
287         for c in tree
288                 cb c, state
289                 break if state.done?
290                 if c.children.length
291                         traverse_tree c.children, state, cb
292                         break if state.done?
293         return state
294 # find the next element in tree (and decendants) that is after n and can contain text
295 # TODO make it so cursor can go places that don't have text but could
296 find_next_cursor_position = (tree, n, i) ->
297         if n? and n.type is TYPE_TEXT and n.text.length > i
298                 orig_xyh = cursor_to_xyh n, i
299                 unless orig_xyh?
300                         console.log "ERROR: couldn't find xy for current cursor location"
301                         return
302                 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
303                         next_xyh = cursor_to_xyh n, next_i
304                         if next_xyh?
305                                 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
306                                         return [n, next_i]
307         found = traverse_tree tree, before: n?, (node, state) ->
308                 if node.type is TYPE_TEXT and state.before is false
309                         state.node = node
310                         state.done = true
311                 if node is n
312                         state.before = false
313         if found.node?
314                 return [found.node, 0]
315         return null
316
317 # TODO make it so cursor can go places that don't have text but could
318 find_prev_cursor_position = (tree, n, i) ->
319         if n? and n.type is TYPE_TEXT and i > 0
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 prev_i in [i-1 .. 0]
325                         prev_xyh = cursor_to_xyh n, prev_i
326                         if prev_xyh?
327                                 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
328                                         return [n, prev_i]
329                 return [n, i - 1]
330         found = traverse_tree tree, before: n?, (node, state) ->
331                 if node.type is TYPE_TEXT
332                         unless n?
333                                 state.node = node
334                                 state.done = true
335                         if node is n
336                                 if state.prev?
337                                         state.node = state.prev
338                                 state.done = true
339                         if node
340                                 state.prev = node
341         if found.node?
342                 return [found.node, found.node.text.length]
343         return null
344
345 find_loc_cursor_position = (tree, loc) ->
346         for c in tree
347                 if c.type is TYPE_TAG or c.type is TYPE_TEXT
348                         bounds = get_el_bounds c.el
349                         continue if loc.x < bounds.x
350                         continue if loc.x > bounds.x + bounds.w
351                         continue if loc.y < bounds.y
352                         continue if loc.y > bounds.y + bounds.h
353                         if c.children.length
354                                 ret = find_loc_cursor_position c.children, loc
355                                 return ret if ret?
356                         if c.type is TYPE_TEXT
357                                 # click is within bounding box that contains all text.
358                                 return [c, 0] if c.text.length is 0
359                                 before_i = 0
360                                 before = cursor_to_xyh c, before_i
361                                 unless before?
362                                         console.log "error: failed to find cursor pixel location for start of", c
363                                         return
364                                 after_i = c.text.length
365                                 after = cursor_to_xyh c, after_i
366                                 unless after?
367                                         console.log "error: failed to find cursor pixel location for end of", c
368                                         return
369                                 if loc.y < before.y + before.h and loc.x < before.x
370                                         # console.log 'before first char on first line'
371                                         continue
372                                 if loc.y > after.y and loc.x > after.x
373                                         # console.log 'after last char on last line'
374                                         continue
375                                 if loc.y < before.y
376                                         console.log "Warning: click in bounding box but above first line"
377                                         continue # above first line (runaround?)
378                                 if loc.y > after.y + after.h
379                                         console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
380                                         continue # below last line (shouldn't happen?)
381                                 while after_i - before_i > 1
382                                         cur_i = Math.round((before_i + after_i) / 2)
383                                         cur = cursor_to_xyh c, cur_i
384                                         unless loc?
385                                                 console.log "error: failed to find cursor pixel location for", c, cur_i
386                                                 return
387                                         if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
388                                                 after_i = cur_i
389                                                 after = cur
390                                         else
391                                                 before_i = cur_i
392                                                 before = cur
393                                 # which one is closest?
394                                 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
395                                         return [c, before_i]
396                                 else
397                                         return [c, after_i]
398         return null
399
400 # browsers collapse these (html5 spec calls these "space characters")
401 is_space_code = (char_code) ->
402         switch char_code
403                 when 9, 10, 12, 13, 32
404                         return true
405         return false
406 is_space = (chr) ->
407         return is_space_code chr.charCodeAt 0
408
409 # pass a array of nodes (from parser library, ie it should have .el and .text)
410 tree_dedup_space = (tree) ->
411         prev = cur = next = null
412         prev_i = cur_i = next_i = 0
413         prev_pos = pos = next_pos = null
414         prev_px = cur_px = next_px = null
415         first = true
416         removed_char = null
417
418         iterate = (tree, cb) ->
419                 for n in tree
420                         if n.type is TYPE_TEXT
421                                 i = 0
422                                 while i < n.text.length # don't foreach, cb might remove chars
423                                         advance = cb n, i
424                                         if advance
425                                                 i += 1
426                         if n.type is TYPE_TAG
427                                 block = is_display_block n.el
428                                 if block
429                                         cb null
430                                 if n.children.length > 0
431                                         iterate n.children, cb
432                                 if block
433                                         cb null
434         # remove cur char
435         remove = ->
436                 removed_char = cur.text.charAt(cur_i)
437                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
438                 if next is cur # in same text node
439                         if next_i is 0
440                                 throw "how is this possible?"
441                         next_i -= 1
442                 return true
443         # undo remove()
444         put_it_back = ->
445                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
446                 if next is cur # in same text node
447                         next_i += 1
448                 return false
449         # return true if cur was removed from the dom (ie re-use same prev)
450         operate = ->
451                 # cur definitately set
452                 # prev and/or next might be null, indicating the start/end of a display:block
453                 return false unless is_space_code cur.text.charCodeAt cur_i
454                 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
455                 # consistent cases:
456                 # 1. zero rects returned by getClientRects() means collapsed space
457                 if bounds is null
458                         return remove()
459                 # 2. width greater than zero means visible space
460                 if bounds.w > 0
461                         return false
462                 # now the weird edge cases...
463                 #
464                 # firefox and chromium both report zero width for characters at the end
465                 # of a line where the text wraps (automatically, due to word-wrap) to
466                 # the next line. These do not appear to be distinguishable from
467                 # collapsed spaces via the range/bounds api, so...
468                 #
469                 # remove it from the dom, and if prev or next moves, put it back.
470                 if prev? and not prev_px?
471                         prev_px = cursor_to_xyh prev, prev_i
472                 if next? and not next_px?
473                         next_px = cursor_to_xyh next, next_i
474                 #if prev is null and next is null
475                 #       parent_px = cur.parent.el.getBoundingClientRect()
476                 remove()
477                 if prev?
478                         if prev_px?
479                                 new_prev_px = cursor_to_xyh prev, prev_i
480                                 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
481                                         return put_it_back()
482                         else
483                                 console.log "this shouldn't happen, we remove spaces that don't locate"
484                 if next?
485                         if next_px?
486                                 new_next_px = cursor_to_xyh next, next_i
487                                 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
488                                         return put_it_back()
489                         #else
490                         #       console.log "removing space becase space after it is collapsed"
491                 # if there's no prev or next (single space inside a block-level element?) check
492                 # TODO scrapt this, or fix it so it works when there's no parent
493                 # if prev is null and next is null
494                 #       new_parent_px = cur.parent.el.getBoundingClientRect()
495                 #       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
496                 #               console.log "WEIRD: parent moved"
497                 #               return put_it_back()
498                 # we didn't put it back
499                 return true
500         # pass null at start/end of display:block
501         queue = (n, i) ->
502                 next = n
503                 next_i = i
504                 next_px = null
505                 advance = true
506                 if cur?
507                         removed = operate()
508                         # don't advance (to the next character next time) if we removed a
509                         # character from the same text node as ``next``, because doing so
510                         # renumbers the indexes in that string
511                         if removed and cur is next
512                                 advance = false
513                 else
514                         removed = false
515                 unless removed
516                         prev = cur
517                         prev_i = cur_i
518                         prev_px = cur_px
519                 cur = next
520                 cur_i = next_i
521                 cur_px = next_px
522                 return advance
523         queue null
524         iterate tree, queue
525         queue null
526
527 class PeachHTML5Editor
528         # Options: (all optional)
529         #   editor_id: "id" attribute for outer-most element created by/for editor
530         constructor: (in_el, options) ->
531                 @options = options ? {}
532                 @in_el = in_el
533                 @tree = []
534                 @initialized = false # when iframes have loaded
535                 @outer_iframe # iframe to hold editor
536                 @outer_idoc # "document" object for @outer_iframe
537                 @iframe = null # iframe to hold editable content
538                 @idoc = null # "document" object for @iframe
539                 @cursor = null
540                 @cursor_el = null
541                 @cursor_visible = false
542                 opt_fragment = @options.fragment ? true
543                 @parser_opts = {}
544                 if opt_fragment
545                         @parser_opts.fragment = 'body'
546
547                 @outer_iframe = domify document, iframe: class: 'peach_html5_editor'
548                 if @options.editor_id?
549                         @outer_iframe.setAttribute 'id', @options.editor_id
550                 @outer_iframe.onload = =>
551                         @outer_idoc = @outer_iframe.contentDocument
552                         icss = domify @outer_idoc, style: children: [
553                                 domify @outer_idoc, text: css
554                         ]
555                         @outer_idoc.head.appendChild icss
556                         # FIXME continue
557
558                         @iframe = domify @outer_idoc, iframe: {}
559                         @iframe.onload = =>
560                                 @init()
561                         @outer_idoc.body.appendChild(
562                                 domify @outer_idoc, div: id: 'wrap1', children: [
563                                         domify @outer_idoc, div: id: 'wrap2', children: [
564                                                 domify @outer_idoc, div: id: 'wrap3', children: [
565                                                         @iframe
566                                                         @overlay = domify @outer_idoc, div: id: 'overlay'
567                                                 ]
568                                         ]
569                                 ]
570                         )
571                 @in_el.parentNode.appendChild @outer_iframe
572         init: -> # called by @iframe's onload
573                 @idoc = @iframe.contentDocument
574                 @overlay.onclick = (e) =>
575                         return @onclick e
576                 @outer_idoc.body.onkeyup = (e) =>
577                         return @onkeyup e
578                 @outer_idoc.body.onkeydown = (e) =>
579                         return @onkeydown e
580                 @outer_idoc.body.onkeypress = (e) =>
581                         return @onkeypress e
582                 if @options.stylesheet
583                         # TODO test this
584                         @idoc.head.appendChild domify @idoc, style: src: @options.stylesheet
585                 @load_html @in_el.value
586                 @initialized = true
587                 if @options.initialized_cb?
588                         @options.initialized_cb()
589         onclick: (e) ->
590                 x = (e.offsetX ? e.layerX) - overlay_padding
591                 y = (e.offsetY ? e.layerY) - overlay_padding
592                 new_cursor = find_loc_cursor_position @tree, x: x, y: y
593                 if new_cursor?
594                         @move_cursor new_cursor
595         onkeyup: (e) ->
596                 return if e.ctrlKey
597                 return false if ignore_key_codes[e.keyCode]?
598                 #return false if control_key_codes[e.keyCode]?
599         onkeydown: (e) ->
600                 return if e.ctrlKey
601                 return false if ignore_key_codes[e.keyCode]?
602                 #return false if control_key_codes[e.keyCode]?
603                 switch e.keyCode
604                         when KEY_LEFT
605                                 if @cursor?
606                                         new_cursor = find_prev_cursor_position @tree, @cursor...
607                                         if new_cursor?
608                                                 @move_cursor new_cursor
609                                 else
610                                         for c in @tree
611                                                 new_cursor = find_next_cursor_position @tree, c, -1
612                                                 if new_cursor?
613                                                         @move_cursor new_cursor
614                                                         break
615                                 return false
616                         when KEY_UP
617                                 return false
618                         when KEY_RIGHT
619                                 if @cursor?
620                                         new_cursor = find_next_cursor_position @tree, @cursor...
621                                         if new_cursor?
622                                                 @move_cursor new_cursor
623                                 else
624                                         for c in @tree
625                                                 new_cursor = find_prev_cursor_position @tree, c, -1
626                                                 if new_cursor?
627                                                         @move_cursor new_cursor
628                                                         break
629                                 return false
630                         when KEY_DOWN
631                                 return false
632                         when KEY_END
633                                 return false
634                         when KEY_BACKSPACE
635                                 return false unless @cursor?
636                                 return false unless @cursor[1] > 0
637                                 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
638                                 @cursor[0].el.nodeValue = @cursor[0].text
639                                 @move_cursor [@cursor[0], @cursor[1] - 1]
640                                 return false
641                         when KEY_DELETE
642                                 return false unless @cursor?
643                                 return false unless @cursor[1] < @cursor[0].text.length
644                                 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
645                                 @cursor[0].el.nodeValue = @cursor[0].text
646                                 @move_cursor [@cursor[0], @cursor[1]]
647                                 return false
648                         when KEY_ENTER
649                                 return false
650                         when KEY_ESCAPE
651                                 return false
652                         when KEY_HOME
653                                 return false
654                         when KEY_INSERT
655                                 return false
656                         when KEY_PAGE_UP
657                                 return false
658                         when KEY_PAGE_DOWN
659                                 return false
660                         when KEY_TAB
661                                 return false
662         onkeypress: (e) ->
663                 return if e.ctrlKey
664                 return false if ignore_key_codes[e.keyCode]?
665                 return false if control_key_codes[e.keyCode]? # handled in keydown
666                 char = e.charCode ? e.keyCode
667                 if char and @cursor?
668                         char = String.fromCharCode char
669                         if @cursor[1] is 0
670                                 @cursor[0].text = char + @cursor[0].text
671                         else if @cursor[1] is @cursor[0].text.length - 1
672                                 @cursor[0].text += char
673                         else
674                                 @cursor[0].text =
675                                         @cursor[0].text.substr(0, @cursor[1]) +
676                                         char +
677                                         @cursor[0].text.substr(@cursor[1])
678                         @cursor[0].el.nodeValue = @cursor[0].text
679                         @move_cursor [@cursor[0], @cursor[1] + 1]
680                         @changed()
681                 return false
682         clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
683                 while @idoc.body.childNodes.length
684                         @idoc.body.removeChild @idoc.body.childNodes[0]
685                 @kill_cursor()
686                 return
687         load_html: (html) ->
688                 @tree = peach_parser.parse html, @parser_opts
689                 @clear_dom()
690                 instantiate_tree @tree, @idoc.body
691                 tree_dedup_space @tree
692                 @changed()
693         changed: ->
694                 # FIXME don't export cursor placeholder (when cursor is between space characters)
695                 @in_el.onchange = null
696                 @in_el.value = dom_to_html @tree
697                 @in_el.onchange = =>
698                         @load_html @in_el.value
699         kill_cursor: -> # remove it, forget where it was
700                 if @cursor_visible
701                         @cursor_el.parentNode.removeChild @cursor_el
702                         @cursor_visible = false
703                 @cursor = null
704         move_cursor: (cursor) ->
705                 loc = cursor_to_xyh cursor[0], cursor[1]
706                 unless loc?
707                         console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
708                         return
709                 @cursor = cursor
710                 # replace cursor, to reset blink animation
711                 if @cursor_visible
712                         @cursor_el.parentNode.removeChild @cursor_el
713                 @cursor_el = domify @outer_idoc, div: id: 'cursor'
714                 @overlay.appendChild @cursor_el
715                 @cursor_visible = true
716                 # TODO figure out x,y coords for cursor
717                 @cursor_el.style.left = "#{loc.x + overlay_padding}px"
718                 @cursor_el.style.top = "#{loc.y + overlay_padding}px"
719
720 window.peach_html5_editor = (args...) ->
721         return new PeachHTML5Editor args...
722
723 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])