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