JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
e32d6623cc6dded2b53c8193294b2346ddd8ea2a
[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 timeout = (ms, cb) -> return setTimeout cb, ms
21 next_frame = (cb) ->
22         if (window.requestAnimationFrame?)
23                 window.requestAnimationFrame cb
24         else
25                 timeout 16, cb
26
27 this_url_sans_path = ->
28         ret = "#{window.location.href}"
29         clip = ret.lastIndexOf '#'
30         if clip > -1
31                 ret = ret.substr 0, clip
32         clip = ret.lastIndexOf '?'
33         if clip > -1
34                 ret = ret.substr 0, clip
35         clip = ret.lastIndexOf '/'
36         if clip > -1
37                 ret = ret.substr 0, clip + 1
38         return ret
39
40 # table too look up the properties of various values for css's white-space
41 ws_props =
42         normal:
43                 space: false            # spaces are not preserved/rendered
44                 newline: false          # newlines are not preserved/rendered
45                 wrap: true              # text is word-wrapped
46                 to_preserve: 'pre-wrap' # to preservespaces, change white-space to this
47         nowrap:
48                 space: false
49                 newline: false
50                 wrap: false
51                 to_preserve: 'pre'
52         'pre-line':
53                 space: false
54                 newline: true
55                 wrap: true
56                 to_preserve: 'pre-wrap'
57         pre:
58                 space: true
59                 newline: true
60                 wrap: false
61         'pre-wrap':
62                 space: true
63                 newline: true
64                 wrap: true
65
66 # xml 1.0 spec, chromium and firefox accept these, plus lots of unicode chars
67 valid_attr_regex = new RegExp '^[a-zA-Z_:][-a-zA-Z0-9_:.]*$'
68 # html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
69 js_attr_regex = new RegExp '^[oO][nN].'
70
71 debug_dot_at = (doc, x, y) ->
72         return # disabled
73         el = doc.createElement 'div'
74         el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
75         doc.body.appendChild el
76         #console.log(new Error().stack)
77
78 # text nodes don't have getBoundingClientRect(), so use selection api to find
79 # it.
80 get_el_bounds = window.bounds = (el) ->
81         if el.getBoundingClientRect?
82                 rect = el.getBoundingClientRect()
83         else
84                 # text nodes don't have getBoundingClientRect(), so use range api
85                 range = el.ownerDocument.createRange()
86                 range.selectNodeContents el
87                 rect = range.getBoundingClientRect()
88         doc = el.ownerDocument.documentElement
89         win = el.ownerDocument.defaultView
90         y_fix = win.pageYOffset - doc.clientTop
91         x_fix = win.pageXOffset - doc.clientLeft
92         return {
93                 x: rect.left + x_fix
94                 y: rect.top + y_fix
95                 w: rect.width ? (rect.right - rect.left)
96                 h: rect.height ? (rect.top - rect.bottom)
97         }
98
99 is_display_block = (el) ->
100         if el.currentStyle?
101                 return el.currentStyle.display is 'block'
102         else
103                 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
104
105 # Pass return value from dom event handlers to this.
106 # If they return false, this will addinionally stop propagation and default.
107 event_return = (e, bool) ->
108         if bool is false
109                 if e.stopPropagation?
110                         e.stopPropagation()
111                 if e.preventDefault?
112                         e.preventDefault()
113         return bool
114 # Warning: currently assumes you're asking about a single character
115 # Note: chromium returns multiple bounding rects for a space at a line-break
116 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
117 # Note: sometimes returns null (eg for whitespace that is not visible)
118 text_range_bounds = (el, start, end) ->
119         range = document.createRange()
120         range.setStart el, start
121         range.setEnd el, end
122         rects = range.getClientRects()
123         if rects.length > 0
124                 rect = rects[0]
125         else
126                 return null
127         doc = el.ownerDocument.documentElement
128         win = el.ownerDocument.defaultView
129         y_fix = win.pageYOffset - doc.clientTop
130         x_fix = win.pageXOffset - doc.clientLeft
131         return {
132                 x: rect.left + x_fix
133                 y: rect.top + y_fix
134                 w: rect.width ? (rect.right - rect.left)
135                 h: rect.height ? (rect.top - rect.bottom)
136                 rects: rects
137                 bounding: range.getBoundingClientRect()
138         }
139
140 class CursorPosition
141         constructor: (args) ->
142                 @n = args.n ? null
143                 @i = args.i ? null
144                 if args.x?
145                         @x = args.x
146                         @y = args.y
147                         @h = args.h
148                 else
149                         @set_xyh()
150                 return
151         set_xyh: ->
152                 range = document.createRange()
153                 if @n.text.length is 0
154                         ret = text_range_bounds @n.el, 0, 0
155                 else if @i is @n.text.length
156                         ret = text_range_bounds @n.el, @i - 1, @i
157                         if ret?
158                                 ret.x += ret.w
159                 else
160                         ret = text_range_bounds @n.el, @i, @i + 1
161                 if ret?
162                         @x = ret.x
163                         @y = ret.y
164                         @h = ret.h
165                 else
166                         @x = null
167                         @y = null
168                         @h = null
169                 return ret
170
171 new_cursor_position = (args) ->
172         ret = new CursorPosition args
173         if ret.x?
174                 return ret
175         return null
176
177 # encode text so it can be safely placed inside an html attribute
178 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
179 enc_attr = (txt) ->
180         return txt.replace enc_attr_regex, (match, amp, quote) ->
181                 return '&amp;' if (amp)
182                 return '&quot;' if (quote)
183                 return '&nbsp;'
184 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
185 enc_text = (txt) ->
186         return txt.replace enc_text_regex, (match, amp, lt) ->
187                 return '&amp;' if (amp)
188                 return '&lt;' if (lt)
189                 return '&nbsp;'
190
191 void_elements = {
192         area: true
193         base: true
194         br: true
195         col: true
196         embed: true
197         hr: true
198         img: true
199         input: true
200         keygen: true
201         link: true
202         meta: true
203         param: true
204         source: true
205         track: true
206         wbr: true
207 }
208 # TODO make these always pretty-print (on the inside) like blocks
209 no_text_elements = { # these elements never contain text
210         select: true
211         table: true
212         tr: true
213         thead: true
214         tbody: true
215         ul: true
216         ol: true
217 }
218
219 domify = (doc, hash) ->
220         for tag, attrs of hash
221                 if tag is 'text'
222                         return document.createTextNode attrs
223                 el = document.createElement tag
224                 for k, v of attrs
225                         if k is 'children'
226                                 for child in v
227                                         el.appendChild child
228                         else
229                                 el.setAttribute k, v
230         return el
231
232 outer_css = (args) ->
233         w = args.w ? 300
234         h = args.h ? 300
235         inner_padding = args.inner_padding ? overlay_padding
236         frame_width = args.frame_width ? inner_padding
237         # TODO editor controls height...
238         occupy = (left, top = left, right = left, bottom = top) ->
239                 w -= left + right
240                 h -= top + bottom
241                 return Math.max(left, top, right, bottom)
242         ret = ''
243         ret += 'body {'
244         ret +=     'margin: 0;'
245         ret +=     'padding: 0;'
246         ret +=     'color: black;'
247         ret +=     'background: white;'
248         ret += '}'
249         ret += '#wrap1 {'
250         ret +=     "border: #{occupy 1}px solid black;"
251         ret +=     "padding: #{occupy frame_width}px;"
252         ret += '}'
253         ret += '#wrap2 {'
254         ret +=     "border: #{occupy 1}px solid black;"
255         ret +=     "padding: #{occupy inner_padding}px;"
256         ret +=     "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
257         ret +=     "width: #{w}px;"
258         ret +=     "height: #{h}px;"
259         ret +=     'overflow-x: hidden;'
260         ret +=     'overflow-y: scroll;'
261         ret += '}'
262         ret += '#wrap3 {'
263         ret +=     'position: relative;'
264         ret +=     "width: #{w}px;"
265         ret +=     "min-height: #{h}px;"
266         ret += '}'
267         ret += 'iframe {'
268         ret +=     'box-sizing: border-box;'
269         ret +=     'margin: 0;'
270         ret +=     'border: none;'
271         ret +=     'padding: 0;'
272         ret +=     "width: #{w}px;"
273         #ret +=     "height: #{h}px;" # height auto-set when content set/changed
274         ret +=     '-ms-user-select: none;'
275         ret +=     '-webkit-user-select: none;'
276         ret +=     '-moz-user-select: none;'
277         ret +=     'user-select: none;'
278         ret += '}'
279         ret += '#overlay {'
280         ret +=     'position: absolute;'
281         ret +=     "left: -#{inner_padding}px;"
282         ret +=     "top: -#{inner_padding}px;"
283         ret +=     "right: -#{inner_padding}px;"
284         ret +=     "bottom: -#{inner_padding}px;"
285         ret +=     'overflow: hidden;'
286         ret += '}'
287         ret += '.lightbox {'
288         ret +=     'position: absolute;'
289         ret +=     'background: rgba(100,100,100,0.2);'
290         ret += '}'
291         ret += '#cursor {'
292         ret +=     'position: absolute;'
293         ret +=     'width: 2px;'
294         ret +=     'background: linear-gradient(0deg, rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1));'
295         ret +=     'background-size: 200% 200%;'
296         ret +=     '-webkit-animation: blink 1s linear normal infinite;'
297         ret +=     'animation: blink 1s linear normal infinite;'
298         ret += '}'
299         ret += '@-webkit-keyframes blink {'
300         ret +=     '0%{background-position:0% 0%}'
301         ret +=     '100%{background-position:0% -100%}'
302         ret += '}'
303         ret += '@keyframes blink { '
304         ret +=     '0%{background-position:0% 0%}'
305         ret +=     '100%{background-position:0% -100%}'
306         ret += '}'
307         ret += '.ann_box {'
308         ret +=     'z-index: 5;'
309         ret +=     'position: absolute;'
310         ret +=     'border: 1px solid rgba(0,0,0,0.1);'
311         ret +=     'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
312         ret += '}'
313         ret += '.ann_tag {'
314         ret +=     'z-index: 10;'
315         ret +=     'position: absolute;'
316         ret +=     'font-size: 8px;'
317         ret +=     'white-space: pre;'
318         ret +=     'background: rgba(255,255,255,0.4);'
319         ret +=     '-ms-user-select: none;'
320         ret +=     '-webkit-user-select: none;'
321         ret +=     '-moz-user-select: none;'
322         ret +=     'user-select: none;'
323         ret += '}'
324         return ret
325
326
327 ignore_key_codes =
328         '18': true # alt
329         '20': true # capslock
330         '17': true # ctrl
331         '144': true # numlock
332         '16': true # shift
333         '91': true # windows "start" key
334 # key codes: (valid on keydown, not keypress)
335 KEY_LEFT = 37
336 KEY_UP = 38
337 KEY_RIGHT = 39
338 KEY_DOWN = 40
339 KEY_BACKSPACE = 8 # <--
340 KEY_DELETE = 46 # -->
341 KEY_END = 35
342 KEY_ENTER = 13
343 KEY_ESCAPE = 27
344 KEY_HOME = 36
345 KEY_INSERT = 45
346 KEY_PAGE_UP = 33
347 KEY_PAGE_DOWN = 34
348 KEY_TAB = 9
349 control_key_codes = # we react to these, but they aren't typing
350         '37': KEY_LEFT
351         '38': KEY_UP
352         '39': KEY_RIGHT
353         '40': KEY_DOWN
354         '35': KEY_END
355         '8':  KEY_BACKSPACE
356         '46': KEY_DELETE
357         '13': KEY_ENTER
358         '27': KEY_ESCAPE
359         '36': KEY_HOME
360         '45': KEY_INSERT
361         '33': KEY_PAGE_UP
362         '34': KEY_PAGE_DOWN
363         '9':  KEY_TAB
364
365 instantiate_tree = (tree, parent) ->
366         remove = []
367         for c, i in tree
368                 switch c.type
369                         when 'text'
370                                 c.el = parent.ownerDocument.createTextNode c.text
371                                 parent.appendChild c.el
372                         when 'tag'
373                                 if c.name in ['script', 'object', 'iframe', 'link']
374                                         # TODO put placeholders instead
375                                         remove.unshift i
376                                         continue
377                                 # TODO create in correct namespace
378                                 c.el = parent.ownerDocument.createElement c.name
379                                 for k, v of c.attrs
380                                         # FIXME if attr_whitelist[k]?
381                                         if valid_attr_regex.test k
382                                                 unless js_attr_regex.test k
383                                                         c.el.setAttribute k, v
384                                 parent.appendChild c.el
385                                 if c.children.length
386                                         instantiate_tree c.children, c.el
387         for i in remove
388                 tree.splice i, 1
389
390 traverse_tree = (tree, cb) ->
391         done = false
392         for c in tree
393                 done = cb c
394                 return done if done
395                 if c.children.length
396                         done = traverse_tree c.children, cb
397                         return done if done
398         return done
399
400 first_cursor_position = (tree) ->
401         found = null
402         traverse_tree tree, (node, state) ->
403                 if node.type is 'text'
404                         cursor = new_cursor_position n: node, i: 0
405                         if cursor?
406                                 found = cursor
407                                 return true
408                 return false
409         return found # maybe null
410
411 # this will fail when text has non-locatable cursor positions
412 find_next_cursor_position = (tree, cursor) ->
413         if cursor.n.type is 'text' and cursor.n.text.length > cursor.i
414                 new_cursor = new_cursor_position n: cursor.n, i: cursor.i + 1
415                 if new_cursor?
416                         return new_cursor
417         state_before = true
418         found = null
419         traverse_tree tree, (node, state) ->
420                 if node.type is 'text' and state_before is false
421                         new_cursor = new_cursor_position n: node, i: 0
422                         if new_cursor?
423                                 found = new_cursor
424                                 return true
425                 if node is cursor.n
426                         state_before = false
427                 return false
428         if found?
429                 return found
430         return null
431
432 last_cursor_position = (tree) ->
433         found = null
434         traverse_tree tree, (node) ->
435                 if node.type is 'text'
436                         cursor = new_cursor_position n: node, i: node.text.length
437                         if cursor?
438                                 found = cursor
439                 return false
440         return found # maybe null
441
442 # this will fail when text has non-locatable cursor positions
443 find_prev_cursor_position = (tree, cursor) ->
444         if cursor.n.type is 'text' and cursor.i > 0
445                 new_cursor = new_cursor_position n: cursor.n, i: cursor.i - 1
446                 if new_cursor?
447                         return new_cursor
448         found_prev = null
449         found = null
450         traverse_tree tree, (node) ->
451                 if node is cursor.n
452                         found = found_prev # maybe null
453                         return true
454                 if node.type is 'text'
455                         new_cursor = new_cursor_position n: node, i: node.text.length
456                         if new_cursor?
457                                 found_prev = new_cursor
458                 return false
459         return found # maybe null
460
461 xy_to_cursor = (tree, xy) ->
462         for n in tree
463                 if n.type is 'tag' or n.type is 'text'
464                         bounds = get_el_bounds n.el
465                         continue if xy.x < bounds.x
466                         continue if xy.x > bounds.x + bounds.w
467                         continue if xy.y < bounds.y
468                         continue if xy.y > bounds.y + bounds.h
469                         if n.children.length
470                                 ret = xy_to_cursor n.children, xy
471                                 return ret if ret?
472                         if n.type is 'text'
473                                 # click is within bounding box that contains all text.
474                                 if n.text.length is 0
475                                         ret = new_cursor_position n: n, i: 0
476                                         return ret if ret?
477                                         continue
478                                 before = new_cursor_position n: n, i: 0
479                                 continue unless before?
480                                 after = new_cursor_position n: n, i: n.text.length
481                                 continue unless after?
482                                 if xy.y < before.y + before.h and xy.x < before.x
483                                         # console.log 'before first char on first line'
484                                         continue
485                                 if xy.y > after.y and xy.x > after.x
486                                         # console.log 'after last char on last line'
487                                         continue
488                                 if xy.y < before.y
489                                         console.log "Warning: click in text bounding box but above first line"
490                                         continue # above first line (runaround?)
491                                 if xy.y > after.y + after.h
492                                         console.log "Warning: click in text bounding box but below last line", xy.y, after.y, after.h
493                                         continue # below last line (shouldn't happen?)
494                                 while after.i - before.i > 1
495                                         guess_i = Math.round((before.i + after.i) / 2)
496                                         cur = new_cursor_position n: n, i: guess_i
497                                         unless cur?
498                                                 console.log "error: failed to find cursor pixel location for", n, guess_i
499                                                 before = null
500                                                 break
501                                         if xy.y < cur.y or (xy.y <= cur.y + cur.h and xy.x < cur.x)
502                                                 after = cur
503                                         else
504                                                 before = cur
505                                 continue unless before? # signals failure to find a cursor position
506                                 # which one is closest?
507                                 if Math.abs(before.x - xy.x) < Math.abs(after.x - xy.x)
508                                         return before
509                                 else
510                                         return after
511         return null
512
513 # browsers collapse these (html5 spec calls these "space characters")
514 is_space_code = (char_code) ->
515         switch char_code
516                 when 9, 10, 12, 13, 32
517                         return true
518         return false
519 is_space = (chr) ->
520         return is_space_code chr.charCodeAt 0
521
522 tree_remove_empty_text_nodes = (tree) ->
523         empties = []
524         traverse_tree tree, (n) ->
525                 if n.type is 'text'
526                         if n.text.length is 0
527                                 empties.unshift n
528                 return false
529         for n in empties
530                 # don't completely empty the tree
531                 if tree.length is 1
532                         if tree[0].type is 'text'
533                                 console.log "oop, leaving a blank node because it's the only thing"
534                                 return
535                 n.el.parentNode.removeChild n.el
536                 for c, i in n.parent.children
537                         if c is n
538                                 n.parent.children.splice i, 1
539                                 break
540
541 # pass a array of nodes (from parser library, ie it should have .el and .text)
542 tree_dedup_space = (tree) ->
543         prev = cur = next = null
544         prev_i = cur_i = next_i = 0
545         prev_pos = pos = next_pos = null
546         prev_px = cur_px = next_px = null
547         first = true
548         removed_char = null
549
550         tree_remove_empty_text_nodes(tree)
551
552         iterate = (tree, cb) ->
553                 for n in tree
554                         if n.type is 'text'
555                                 i = 0
556                                 while i < n.text.length # don't foreach, cb might remove chars
557                                         advance = cb n, i
558                                         if advance
559                                                 i += 1
560                         if n.type is 'tag'
561                                 block = is_display_block n.el
562                                 if block
563                                         cb null
564                                 if n.children.length > 0
565                                         iterate n.children, cb
566                                 if block
567                                         cb null
568         # remove cur char
569         remove = ->
570                 removed_char = cur.text.charAt(cur_i)
571                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
572                 if next is cur # in same text node
573                         if next_i is 0
574                                 throw "how is this possible?"
575                         next_i -= 1
576                 return true
577         # undo remove()
578         put_it_back = ->
579                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
580                 if next is cur # in same text node
581                         next_i += 1
582                 return false
583         # return true if cur was removed from the dom (ie re-use same prev)
584         operate = ->
585                 # cur definitately set
586                 # prev and/or next might be null, indicating the start/end of a display:block
587                 return false unless is_space_code cur.text.charCodeAt cur_i
588                 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
589                 # consistent cases:
590                 # 1. zero rects returned by getClientRects() means collapsed space
591                 if bounds is null
592                         return remove()
593                 # 2. width greater than zero means visible space
594                 if bounds.w > 0
595                         return false
596                 # now the weird edge cases...
597                 #
598                 # firefox and chromium both report zero width for characters at the end
599                 # of a line where the text wraps (automatically, due to word-wrap) to
600                 # the next line. These do not appear to be distinguishable from
601                 # collapsed spaces via the range/bounds api, so...
602                 #
603                 # remove it from the dom, and if prev or next moves, put it back.
604                 if prev? and not prev_px?
605                         prev_px = new_cursor_position n: prev, i: prev_i
606                 if next? and not next_px?
607                         next_px = new_cursor_position n: next, i: next_i
608                 #if prev is null and next is null
609                 #       parent_px = cur.parent.el.getBoundingClientRect()
610                 remove()
611                 if prev?
612                         if prev_px?
613                                 new_prev_px = new_cursor_position n: prev, i: prev_i
614                                 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
615                                         return put_it_back()
616                         else
617                                 console.log "this shouldn't happen, we remove spaces that don't locate"
618                 if next?
619                         if next_px?
620                                 new_next_px = new_cursor_position n: next, i: next_i
621                                 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
622                                         return put_it_back()
623                         #else
624                         #       console.log "removing space becase space after it is collapsed"
625                 return true
626         # pass null at start/end of display:block
627         queue = (n, i) ->
628                 next = n
629                 next_i = i
630                 next_px = null
631                 advance = true
632                 if cur?
633                         removed = operate()
634                         # don't advance (to the next character next time) if we removed a
635                         # character from the same text node as ``next``, because doing so
636                         # renumbers the indexes in that string
637                         if removed and cur is next
638                                 advance = false
639                 else
640                         removed = false
641                 unless removed
642                         prev = cur
643                         prev_i = cur_i
644                         prev_px = cur_px
645                 cur = next
646                 cur_i = next_i
647                 cur_px = next_px
648                 return advance
649         queue null
650         iterate tree, queue
651         queue null
652
653         tree_remove_empty_text_nodes(tree)
654
655 class PeachHTML5Editor
656         # Options: (all optional)
657         #   editor_id: "id" attribute for outer-most element created by/for editor
658         #   css_file: filename of a css file to style editable content
659         #   on_init: callback for when the editable content is in place
660         constructor: (in_el, options) ->
661                 @options = options ? {}
662                 @in_el = in_el
663                 @tree = null
664                 @matting = []
665                 @init_1_called = false # when iframes have loaded
666                 @outer_iframe # iframe to hold editor
667                 @outer_idoc # "document" object for @outer_iframe
668                 @wrap2 = null # scrollbar is on this
669                 @iframe = null # iframe to hold editable content
670                 @idoc = null # "document" object for @iframe
671                 @cursor = null
672                 @cursor_el = null
673                 @cursor_visible = false
674                 @poll_for_blur_timeout = null
675                 @wrap2_offset = null
676                 @iframe_height = null
677                 opt_fragment = @options.fragment ? true
678                 @parser_opts = {}
679                 if opt_fragment
680                         @parser_opts.fragment = 'body'
681
682                 @outer_iframe = domify document, iframe: {}
683                 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
684                 if @options.editor_id?
685                         @outer_iframe.setAttribute 'id', @options.editor_id
686                 @outer_iframe.onload = =>
687                         @outer_idoc = @outer_iframe.contentDocument
688                         icss = domify @outer_idoc, style: children: [
689                                 domify @outer_idoc, text: css
690                         ]
691                         @outer_idoc.head.appendChild icss
692                         @iframe = domify @outer_idoc, iframe: sandbox: 'allow-same-origin allow-scripts'
693                         @iframe.onload = =>
694                                 @init_1()
695                         timeout 200, => # firefox never fires this onload
696                                 @init_1() unless @init_1_called
697                         @outer_idoc.body.appendChild(
698                                 domify @outer_idoc, div: id: 'wrap1', children: [
699                                         domify @outer_idoc, div: style: "position: absolute; top: 0; left: 1px; font-size: 10px", children: [ domify @outer_idoc, text: "Peach HTML5 Editor" ]
700                                         @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
701                                                 domify @outer_idoc, div: id: 'wrap3', children: [
702                                                         @iframe
703                                                         @overlay = domify @outer_idoc, div: id: 'overlay'
704                                                 ]
705                                         ]
706                                 ]
707                         )
708                 outer_wrap = domify document, div: class: 'peach_html5_editor'
709                 @in_el.parentNode.appendChild outer_wrap
710                 outer_bounds = get_el_bounds outer_wrap
711                 if outer_bounds.w < 300
712                         outer_bounds.w = 300
713                 if outer_bounds.h < 300
714                         outer_bounds.h = 300
715                 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
716                 @outer_iframe.setAttribute 'style', outer_iframe_style
717                 css = outer_css w: outer_bounds.w, h: outer_bounds.h
718                 outer_wrap.appendChild @outer_iframe
719         init_1: -> # @iframe has loaded (but not it's css)
720                 @idoc = @iframe.contentDocument
721                 @init_1_called = true
722                 # chromium doesn't resolve relative urls as though they were at the same domain
723                 # so add a <base> tag
724                 @idoc.head.appendChild domify @idoc, base: href: this_url_sans_path()
725                 # don't let @iframe have scrollbars
726                 @idoc.head.appendChild domify @idoc, style: children: [domify @idoc, text: "body { overflow: hidden; }"]
727                 # load css file
728                 if @options.css_file
729                         istyle = domify @idoc, link: rel: 'stylesheet', href: @options.css_file
730                         istyle.onload = =>
731                                 @init_2()
732                         @idoc.head.appendChild istyle
733                 else
734                         @init_2()
735         init_2: -> # @iframe and it's css file(s) are ready
736                 @overlay.onclick = (e) =>
737                         @have_focus()
738                         return event_return e, @onclick e
739                 @overlay.ondoubleclick = (e) =>
740                         @have_focus()
741                         return event_return e, @ondoubleclick e
742                 @outer_idoc.body.onkeyup = (e) =>
743                         @have_focus()
744                         return event_return e, @onkeyup e
745                 @outer_idoc.body.onkeydown = (e) =>
746                         @have_focus()
747                         return event_return e, @onkeydown e
748                 @outer_idoc.body.onkeypress = (e) =>
749                         @have_focus()
750                         return event_return e, @onkeypress e
751                 @load_html @in_el.value
752                 if @options.on_init?
753                         @options.on_init()
754         overlay_event_to_inner_xy: (e) ->
755                 unless @wrap2_offset?
756                         @wrap2_offset = get_el_bounds @wrap2
757                 x = e.pageX - overlay_padding
758                 y = e.pageY - overlay_padding + @wrap2.scrollTop
759                 return x: x - @wrap2_offset.x, y: y - @wrap2_offset.y
760         onclick: (e) ->
761                 xy = @overlay_event_to_inner_xy e
762                 new_cursor = xy_to_cursor @tree, xy
763                 if new_cursor?
764                         @move_cursor new_cursor
765                 else
766                         @kill_cursor()
767                 return false
768         ondoubleclick: (e) ->
769                 return false
770         onkeyup: (e) ->
771                 return if e.ctrlKey
772                 return false if ignore_key_codes[e.keyCode]?
773                 #return false if control_key_codes[e.keyCode]?
774         onkeydown: (e) ->
775                 return if e.ctrlKey
776                 return false if ignore_key_codes[e.keyCode]?
777                 #return false if control_key_codes[e.keyCode]?
778                 switch e.keyCode
779                         when KEY_LEFT
780                                 if @cursor?
781                                         new_cursor = find_prev_cursor_position @tree, @cursor
782                                 else
783                                         new_cursor = first_cursor_position @tree
784                                 if new_cursor?
785                                         @move_cursor new_cursor
786                                 return false
787                         when KEY_RIGHT
788                                 if @cursor?
789                                         new_cursor = find_next_cursor_position @tree, @cursor
790                                 else
791                                         new_cursor = last_cursor_position @tree
792                                 if new_cursor?
793                                         @move_cursor new_cursor
794                                 return false
795                         when KEY_UP
796                                 if @cursor?
797                                         new_cursor = @cursor
798                                         # go prev until we're higher on y axis
799                                         while new_cursor.y >= @cursor.y
800                                                 new_cursor = find_prev_cursor_position @tree, new_cursor
801                                                 return false unless new_cursor?
802                                         # done early if we're already left of old cursor position
803                                         if new_cursor.x <= @cursor.x
804                                                 @move_cursor new_cursor
805                                                 return false
806                                         target_y = new_cursor.y
807                                         # search leftward, until we find the closest position
808                                         # new_cursor is the prev-most position we've checked
809                                         # prev_cursor is the older value, so it's not as prev as new_cursor
810                                         while new_cursor.x > @cursor.x and new_cursor.y is target_y
811                                                 prev_cursor = new_cursor
812                                                 new_cursor = find_prev_cursor_position @tree, new_cursor
813                                                 break unless new_cursor?
814                                         # move cursor to prev_cursor or new_cursor
815                                         if new_cursor?
816                                                 if new_cursor.y is target_y
817                                                         # both valid, and on the same line, use closest
818                                                         if (@cursor.x - new_cursor.x) < (prev_cursor.x - @cursor.x)
819                                                                 @move_cursor new_cursor
820                                                         else
821                                                                 @move_cursor prev_cursor
822                                                 else
823                                                         # new_cursor on wrong line, use prev_cursor
824                                                         @move_cursor prev_cursor
825                                         else
826                                                 # can't go any further prev, use prev_cursor
827                                                 @move_cursor prev_cursor
828                                 else
829                                         # move cursor to first position in document
830                                         new_cursor = first_cursor_position @tree
831                                         if new_cursor?
832                                                 @move_cursor new_cursor
833                                 return false
834                         when KEY_DOWN
835                                 if @cursor?
836                                         new_cursor = @cursor
837                                         # go next until we move on the y axis
838                                         while new_cursor.y <= @cursor.y
839                                                 new_cursor = find_next_cursor_position @tree, new_cursor
840                                                 return false unless new_cursor?
841                                         # done early if we're already right of old cursor position
842                                         if new_cursor.x >= @cursor.x
843                                                 # this would be strange, but could happen due to runaround
844                                                 @move_cursor new_cursor
845                                                 return false
846                                         target_y = new_cursor.y
847                                         # search rightward, until we find the closest position
848                                         # new_cursor is the next-most position we've checked
849                                         # prev_cursor is the older value, so it's not as next as new_cursor
850                                         while new_cursor.x < @cursor.x and new_cursor.y is target_y
851                                                 prev_cursor = new_cursor
852                                                 new_cursor = find_next_cursor_position @tree, new_cursor
853                                                 break unless new_cursor?
854                                         # move cursor to prev_cursor or new_cursor
855                                         if new_cursor?
856                                                 if new_cursor.y is target_y
857                                                         # both valid, and on the same line, use closest
858                                                         if (new_cursor.x - @cursor.x) < (@cursor.x - prev_cursor.x)
859                                                                 @move_cursor new_cursor
860                                                         else
861                                                                 @move_cursor prev_cursor
862                                                 else
863                                                         # new_cursor on wrong line, use prev_cursor
864                                                         @move_cursor prev_cursor
865                                         else
866                                                 # can't go any further prev, use prev_cursor
867                                                 @move_cursor prev_cursor
868                                 else
869                                         # move cursor to first position in document
870                                         new_cursor = last_cursor_position @tree
871                                         if new_cursor?
872                                                 @move_cursor new_cursor
873                                 return false
874                         when KEY_END
875                                 return false
876                         when KEY_BACKSPACE
877                                 return false unless @cursor?
878                                 return false unless @cursor.i > 0
879                                 @cursor.n.text = @cursor.n.text.substr(0, @cursor.i - 1) + @cursor.n.text.substr(@cursor.i)
880                                 @cursor.n.el.nodeValue = @cursor.n.text
881                                 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i - 1
882                                 if new_cursor?
883                                         @move_cursor new_cursor
884                                 else
885                                         @kill_cursor()
886                                 @changed()
887                                 return false
888                         when KEY_DELETE
889                                 return false unless @cursor?
890                                 return false unless @cursor.i < @cursor.n.text.length
891                                 @cursor.n.text = @cursor.n.text.substr(0, @cursor.i) + @cursor.n.text.substr(@cursor.i + 1)
892                                 @cursor.n.el.nodeValue = @cursor.n.text
893                                 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i
894                                 if new_cursor?
895                                         @move_cursor new_cursor
896                                 else
897                                         @kill_cursor()
898                                 @changed()
899                                 return false
900                         when KEY_ENTER
901                                 return false
902                         when KEY_ESCAPE
903                                 return false
904                         when KEY_HOME
905                                 return false
906                         when KEY_INSERT
907                                 return false
908                         when KEY_PAGE_UP
909                                 return false
910                         when KEY_PAGE_DOWN
911                                 return false
912                         when KEY_TAB
913                                 return false
914         onkeypress: (e) ->
915                 return if e.ctrlKey
916                 return false if ignore_key_codes[e.keyCode]?
917                 char = e.charCode ? e.keyCode
918                 if char and @cursor?
919                         char = String.fromCharCode char
920                         @insert_character @cursor.n, @cursor.i, char
921                         new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i + 1
922                         if new_cursor
923                                 @move_cursor new_cursor
924                         else
925                                 console.log "ERROR: couldn't find cursor position after insert"
926                                 @kill_cursor()
927                         @changed()
928                 return false
929         clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
930                 while @idoc.body.childNodes.length
931                         @idoc.body.removeChild @idoc.body.childNodes[0]
932                 @kill_cursor()
933                 return
934         load_html: (html) ->
935                 @tree = peach_parser.parse html, @parser_opts
936                 @clear_dom()
937                 instantiate_tree @tree, @idoc.body
938                 tree_dedup_space @tree
939                 @changed()
940         changed: ->
941                 @in_el.onchange = null
942                 @in_el.value = @pretty_html @tree
943                 @in_el.onchange = =>
944                         @load_html @in_el.value
945                 @adjust_iframe_height()
946         adjust_iframe_height: ->
947                 h = parseInt(@idoc.body.scrollHeight, 10)
948                 if @iframe_height isnt h
949                         @iframe_height = h
950                         s = @wrap2.scrollTop
951                         @iframe.style.height = "0"
952                         @iframe.style.height = "#{h}px"
953                         @wrap2.scrollTop = s
954         # Warning: this does not call changed() for you
955         insert_character: (n, i, char) ->
956                 # TODO handle newlines, tabs, etc
957                 parent = @cursor.n.parent
958                 return unless parent
959                 return unless parent.el?
960                 style = @iframe.contentWindow.getComputedStyle parent.el, null
961                 ws = style.getPropertyValue 'white-space'
962                 if char is ' '
963                         unless ws_props[ws].space
964                                 change = false
965                                 if i is 0
966                                         # TODO check if a space at the beginning would actually get collapsed
967                                         change = true
968                                 else if i is n.text.length
969                                         change = true
970                                         # TODO check if a space at the end would actually get collapsed
971                                 else
972                                         if n.text.charAt(i - 1) is ' ' or n.text.charAt(i) is ' '
973                                                 change = true
974                                 if change
975                                         rule = "white-space: #{ws_props[ws].to_preserve}"
976                                         if parent.attrs[style]?
977                                                 parent.attrs.style += "; #{rule}"
978                                         else
979                                                 parent.attrs.style = rule
980                                         parent.el.setAttribute 'style', parent.attrs.style
981                 else
982                         # TODO test this
983                         # inserting a visible (non-space) character
984                         if ws_props[ws].space
985                                 if parent.el.style?['white-space']
986                                         # This node has a "white-space" property on it
987                                         # probably created automatically by this editor
988                                         # when the user pressed space.
989                                         # Check if that's no longer needed.
990                                         need = false
991                                         for ti in [0...n.text.length]
992                                                 code = n.text.charCodeAt ti
993                                                 if code isnt 32 and is_space_code code
994                                                         # tab, return
995                                                         need = true
996                                                         break
997                                                 # check for double spaces that don't surround insert location
998                                                 continue if ti is i
999                                                 continue if ti is 0
1000                                                 if n.text.substr(ti - 1, 2) is '  '
1001                                                         need = true
1002                                                         break
1003                                         if i > 0
1004                                                 if 32 is n.text.charCodeAt 0
1005                                                         need = true
1006                                         if i < n.text.length
1007                                                 if 32 is n.text.charCodeAt n.text.length - 1
1008                                                         need = true
1009                                         unless need
1010                                                 # TODO don't assume whitespace is just so
1011                                                 if parent.attrs.style is "white-space: #{ws}"
1012                                                         delete parent.attrs.style
1013                                                         parent.el.removeAttribute 'style'
1014                                                 else
1015                                                         # FIXME find it in the middle and at the start
1016                                                         needle = "; white-space: #{ws}"
1017                                                         if needle is parent.attrs.style.substr parent.attrs.style.length - needle
1018                                                                 parent.attrs.style = parent.attrs.style.substr 0, parent.attrs.style.length - needle
1019                                                                 parent.el.setAttribute parent.attrs.style
1020                 # TODO insert the character now
1021                 if i is 0
1022                         n.text = char + n.text
1023                 else if i is n.text.length - 1
1024                         n.text += char
1025                 else
1026                         n.text =
1027                                 n.text.substr(0, i) +
1028                                 char +
1029                                 n.text.substr(i)
1030                 n.el.nodeValue = n.text
1031                 # TODO call this when the user types
1032                 # TODO detect when typing produces a collapsing space
1033         remove_character: (n, i) ->
1034                 # TODO call this from delete and backspace key handlers
1035                 # TODO detect if this would result in collapsing space
1036         kill_cursor: -> # remove it, forget where it was
1037                 if @cursor_visible
1038                         @cursor_el.parentNode.removeChild @cursor_el
1039                         @cursor_visible = false
1040                 @cursor = null
1041                 @annotate null
1042         move_cursor: (cursor) ->
1043                 @cursor = cursor
1044                 unless @cursor_visible
1045                         @cursor_el = domify @outer_idoc, div: id: 'cursor'
1046                         @overlay.appendChild @cursor_el
1047                         @cursor_visible = true
1048                 @cursor_el.style.left = "#{cursor.x + overlay_padding - 1}px"
1049                 if cursor.h < 5
1050                         height = 12
1051                 else
1052                         height = cursor.h
1053                 @cursor_el.style.top = "#{cursor.y + overlay_padding + Math.round(height * .07)}px"
1054                 @cursor_el.style.height = "#{Math.round height * 0.82}px"
1055                 @annotate cursor.n
1056         annotate: (n) ->
1057                 while @matting.length > 0
1058                         @overlay.removeChild @matting[0]
1059                         @matting.shift()
1060                 return unless n?
1061                 prev_bounds = x: 0, y: 0, w: 0, h: 0
1062                 alpha = 0.1
1063                 while n?.el?
1064                         if n.type is 'text'
1065                                 n = n.parent
1066                                 continue
1067                         bounds = get_el_bounds n.el
1068                         return unless bounds?
1069                         if bounds.x is prev_bounds.x and bounds.y is prev_bounds.y and bounds.w is prev_bounds.w and bounds.h is prev_bounds.h
1070                                 n = n.parent
1071                                 continue
1072                         ann_box = domify @outer_idoc, div: class: 'ann_box', style: "left: #{bounds.x - 1 + overlay_padding}px; top: #{bounds.y - 2 + overlay_padding}px; width: #{bounds.w}px; height: #{bounds.h}px" # outline: 1000px solid rgba(0,153,255,#{alpha});
1073                         @overlay.appendChild ann_box
1074                         @matting.push ann_box
1075                         ann_tag = domify @outer_idoc, div: class: 'ann_tag', style: "left: #{bounds.x + 1 + overlay_padding}px; top: #{bounds.y - 7 + overlay_padding}px", children: [domify @outer_idoc, text: " #{n.name} "]
1076                         @overlay.appendChild ann_tag
1077                         @matting.push ann_tag
1078                         n = n.parent
1079                         alpha *= 1.5
1080         pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
1081                 ret = ''
1082                 want_nl = parent_flags.want_nl
1083                 prev_in_flow_is_text = false
1084                 prev_in_flow_is_block = false
1085                 for n, i in tree
1086                         # figure out flags
1087                         inner_flags = want_nl: true
1088                         is_br = false
1089                         switch n.type
1090                                 when 'tag'
1091                                         if n.name is 'br'
1092                                                 is_br = true
1093                                         is_text = false
1094                                         if n.el.currentStyle?
1095                                                 cs = n.el.currentStyle
1096                                                 whitespace = cs['white-space']
1097                                                 display = cs['display']
1098                                                 position = cs['position']
1099                                                 float = cs['float']
1100                                                 visibility = cs['visibility']
1101                                         else
1102                                                 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
1103                                                 whitespace = cs.getPropertyValue 'white-space'
1104                                                 display = cs.getPropertyValue 'display'
1105                                                 position = cs.getPropertyValue 'position'
1106                                                 float = cs.getPropertyValue 'float'
1107                                                 visibility = cs.getPropertyValue 'visibility'
1108                                         if n.name is 'textarea'
1109                                                 inner_flags.pre_ish = true
1110                                         else
1111                                                 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
1112                                         switch float
1113                                                 when 'left', 'right'
1114                                                         in_flow = false
1115                                                 else
1116                                                         switch position
1117                                                                 when 'absolute', 'fixed'
1118                                                                         in_flow = false
1119                                                                 else
1120                                                                         if 'display' is 'none'
1121                                                                                 in_flow = false
1122                                                                         else
1123                                                                                 switch visibility
1124                                                                                         when 'hidden', 'collapse'
1125                                                                                                 in_flow = false
1126                                                                                         else # visible
1127                                                                                                 in_flow = true
1128                                         switch display
1129                                                 when 'inline', 'none'
1130                                                         inner_flags.block = false
1131                                                         is_block = in_flow_block = false
1132                                                 when 'inline-black'
1133                                                         inner_flags.block = true
1134                                                         is_block = in_flow_block = false
1135                                                 else # block, table, etc
1136                                                         inner_flags.block = true
1137                                                         is_block = true
1138                                                         in_flow_block = in_flow
1139                                 when 'text'
1140                                         is_text = true
1141                                         is_block = false
1142                                         in_flow = true
1143                                         in_flow_block = false
1144                                 else # 'comment', 'doctype'
1145                                         is_text = false
1146                                         is_block = false
1147                                         in_flow = false
1148                                         in_flow_block = false
1149                         # print whitespace if we can
1150                         unless parent_flags.pre_ish
1151                                 unless prev_in_flow_is_text and is_br
1152                                         if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
1153                                                 if want_nl
1154                                                         ret += "\n"
1155                                                 ret += indent
1156                         switch n.type
1157                                 when 'tag'
1158                                         ret += '<' + n.name
1159                                         attr_keys = []
1160                                         for k of n.attrs
1161                                                 attr_keys.unshift k
1162                                         #attr_keys.sort()
1163                                         for k in attr_keys
1164                                                 ret += " #{k}"
1165                                                 if n.attrs[k].length > 0
1166                                                         ret += "=\"#{enc_attr n.attrs[k]}\""
1167                                         ret += '>'
1168                                         unless void_elements[n.name]?
1169                                                 if inner_flags.block
1170                                                         next_indent = indent + '    '
1171                                                 else
1172                                                         next_indent = indent
1173                                                 if n.children.length
1174                                                         ret += @pretty_html n.children, next_indent, inner_flags
1175                                                 ret += "</#{n.name}>"
1176                                 when 'text'
1177                                         ret += enc_text n.text
1178                                 when 'comment'
1179                                         ret += "<!--#{n.text}-->" # TODO encode?
1180                                 when 'doctype'
1181                                         ret += "<!DOCTYPE #{n.name}"
1182                                         if n.public_identifier? and n.public_identifier.length > 0
1183                                                 ret += " \"#{n.public_identifier}\""
1184                                         if n.system_identifier? and n.system_identifier.length > 0
1185                                                 ret += " \"#{n.system_identifier}\""
1186                                         ret += ">"
1187                         want_nl = true
1188                         if in_flow
1189                                 prev_in_flow_is_text = is_text
1190                                 prev_in_flow_is_block = is_block or (in_flow and is_br)
1191                 if tree.length
1192                         # output final newline if allowed
1193                         unless parent_flags.pre_ish
1194                                 if prev_in_flow_is_block or parent_flags.block
1195                                         ret += "\n#{indent.substr 4}"
1196                 return ret
1197         onblur: ->
1198                 @kill_cursor()
1199         have_focus: ->
1200                 @editor_is_focused = true
1201                 @poll_for_blur()
1202         poll_for_blur: ->
1203                 return if @poll_for_blur_timeout? # already polling
1204                 @poll_for_blur_timeout = timeout 150, =>
1205                         next_frame => # pause polling when browser knows we're not active/visible/etc.
1206                                 @poll_for_blur_timeout = null
1207                                 if document.activeElement is @outer_iframe
1208                                         @poll_for_blur()
1209                                 else
1210                                         @editor_is_focused = false
1211                                         @onblur()
1212
1213 window.peach_html5_editor = (args...) ->
1214         return new PeachHTML5Editor args...
1215
1216 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])