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