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