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