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