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