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