JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
fix backspace of last character in a block
[peach-html5-editor.git] / editor.coffee
1 # Copyright 2015 Jason Woofenden
2 # This file implements an WYSIWYG editor in the browser (no contenteditable)
3 #
4 # This program is free software: you can redistribute it and/or modify it under
5 # the terms of the GNU Affero General Public License as published by the Free
6 # Software Foundation, either version 3 of the License, or (at your option) any
7 # later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 # SETTINGS
18 overlay_padding = 10
19
20 timeout = (ms, cb) -> return setTimeout cb, ms
21 next_frame = (cb) ->
22         if (window.requestAnimationFrame?)
23                 window.requestAnimationFrame cb
24         else
25                 timeout 16, cb
26
27 this_url_sans_path = ->
28         ret = "#{window.location.href}"
29         clip = ret.lastIndexOf '#'
30         if clip > -1
31                 ret = ret.substr 0, clip
32         clip = ret.lastIndexOf '?'
33         if clip > -1
34                 ret = ret.substr 0, clip
35         clip = ret.lastIndexOf '/'
36         if clip > -1
37                 ret = ret.substr 0, clip + 1
38         return ret
39
40 # table too look up the properties of various values for css's white-space
41 ws_props =
42         normal:
43                 space: false            # spaces are not preserved/rendered
44                 newline: false          # newlines are not preserved/rendered
45                 wrap: true              # text is word-wrapped
46                 to_preserve: 'pre-wrap' # to preservespaces, change white-space to this
47         nowrap:
48                 space: false
49                 newline: false
50                 wrap: false
51                 to_preserve: 'pre'
52         'pre-line':
53                 space: false
54                 newline: true
55                 wrap: true
56                 to_preserve: 'pre-wrap'
57         pre:
58                 space: true
59                 newline: true
60                 wrap: false
61         'pre-wrap':
62                 space: true
63                 newline: true
64                 wrap: true
65
66 # xml 1.0 spec, chromium and firefox accept these, plus lots of unicode chars
67 valid_attr_regex = new RegExp '^[a-zA-Z_:][-a-zA-Z0-9_:.]*$'
68 # html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
69 js_attr_regex = new RegExp '^[oO][nN].'
70
71 debug_dot_at = (doc, x, y) ->
72         return # disabled
73         el = doc.createElement 'div'
74         el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
75         doc.body.appendChild el
76         #console.log(new Error().stack)
77
78 # text nodes don't have getBoundingClientRect(), so use selection api to find
79 # it.
80 get_el_bounds = window.bounds = (el) ->
81         if el.getBoundingClientRect?
82                 rect = el.getBoundingClientRect()
83         else
84                 # text nodes don't have getBoundingClientRect(), so use range api
85                 range = el.ownerDocument.createRange()
86                 range.selectNodeContents el
87                 rect = range.getBoundingClientRect()
88         doc = el.ownerDocument.documentElement
89         win = el.ownerDocument.defaultView
90         y_fix = win.pageYOffset - doc.clientTop
91         x_fix = win.pageXOffset - doc.clientLeft
92         return {
93                 x: rect.left + x_fix
94                 y: rect.top + y_fix
95                 w: rect.width ? (rect.right - rect.left)
96                 h: rect.height ? (rect.top - rect.bottom)
97         }
98
99 is_display_block = (el) ->
100         if el.currentStyle?
101                 return el.currentStyle.display is 'block'
102         else
103                 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
104
105 # Pass return value from dom event handlers to this.
106 # If they return false, this will addinionally stop propagation and default.
107 event_return = (e, bool) ->
108         if bool is false
109                 if e.stopPropagation?
110                         e.stopPropagation()
111                 if e.preventDefault?
112                         e.preventDefault()
113         return bool
114 # Warning: currently assumes you're asking about a single character
115 # Note: chromium returns multiple bounding rects for a space at a line-break
116 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
117 # Note: sometimes returns null (eg for whitespace that is not visible)
118 text_range_bounds = (el, start, end) ->
119         range = document.createRange()
120         range.setStart el, start
121         range.setEnd el, end
122         rects = range.getClientRects()
123         if rects.length > 0
124                 if rects.length > 1
125                         if rects[1].width > rects[0].width
126                                 rect = rects[1]
127                         else
128                                 rect = rects[0]
129                 else
130                         rect = rects[0]
131         else
132                 return null
133         doc = el.ownerDocument.documentElement
134         win = el.ownerDocument.defaultView
135         y_fix = win.pageYOffset - doc.clientTop
136         x_fix = win.pageXOffset - doc.clientLeft
137         return {
138                 x: rect.left + x_fix
139                 y: rect.top + y_fix
140                 w: rect.width ? (rect.right - rect.left)
141                 h: rect.height ? (rect.top - rect.bottom)
142                 rects: rects
143                 bounding: range.getBoundingClientRect()
144         }
145
146 class CursorPosition
147         constructor: (args) ->
148                 @n = args.n ? null
149                 @i = args.i ? null
150                 if args.x?
151                         @x = args.x
152                         @y = args.y
153                         @h = args.h
154                 else
155                         @set_xyh()
156                 return
157         set_xyh: ->
158                 range = document.createRange()
159                 if @n.text.length is 0
160                         ret = text_range_bounds @n.el, 0, 0
161                 else if @i is @n.text.length
162                         ret = text_range_bounds @n.el, @i - 1, @i
163                         if ret?
164                                 ret.x += ret.w
165                 else
166                         ret = text_range_bounds @n.el, @i, @i + 1
167                 if ret?
168                         @x = ret.x
169                         @y = ret.y
170                         @h = ret.h
171                 else
172                         @x = null
173                         @y = null
174                         @h = null
175                 return ret
176
177 new_cursor_position = (args) ->
178         ret = new CursorPosition args
179         if ret.x?
180                 return ret
181         return null
182
183 # encode text so it can be safely placed inside an html attribute
184 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
185 enc_attr = (txt) ->
186         return txt.replace enc_attr_regex, (match, amp, quote) ->
187                 return '&amp;' if (amp)
188                 return '&quot;' if (quote)
189                 return '&nbsp;'
190 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
191 enc_text = (txt) ->
192         return txt.replace enc_text_regex, (match, amp, lt) ->
193                 return '&amp;' if (amp)
194                 return '&lt;' if (lt)
195                 return '&nbsp;'
196
197 void_elements = {
198         area: true
199         base: true
200         br: true
201         col: true
202         embed: true
203         hr: true
204         img: true
205         input: true
206         keygen: true
207         link: true
208         meta: true
209         param: true
210         source: true
211         track: true
212         wbr: true
213 }
214 # TODO make these always pretty-print (on the inside) like blocks
215 no_text_elements = { # these elements never contain text
216         select: true
217         table: true
218         tr: true
219         thead: true
220         tbody: true
221         ul: true
222         ol: true
223 }
224
225 domify = (doc, hash) ->
226         for tag, attrs of hash
227                 if tag is 'text'
228                         return document.createTextNode attrs
229                 el = document.createElement tag
230                 for k, v of attrs
231                         if k is 'children'
232                                 for child in v
233                                         el.appendChild child
234                         else
235                                 el.setAttribute k, v
236         return el
237
238
239
240 ignore_key_codes =
241         '18': true # alt
242         '20': true # capslock
243         '17': true # ctrl
244         '144': true # numlock
245         '16': true # shift
246         '91': true # windows "start" key
247 # key codes: (valid on keydown, not keypress)
248 KEY_LEFT = 37
249 KEY_UP = 38
250 KEY_RIGHT = 39
251 KEY_DOWN = 40
252 KEY_BACKSPACE = 8 # <--
253 KEY_DELETE = 46 # -->
254 KEY_END = 35
255 KEY_ENTER = 13
256 KEY_ESCAPE = 27
257 KEY_HOME = 36
258 KEY_INSERT = 45
259 KEY_PAGE_UP = 33
260 KEY_PAGE_DOWN = 34
261 KEY_TAB = 9
262 control_key_codes = # we react to these, but they aren't typing
263         '37': KEY_LEFT
264         '38': KEY_UP
265         '39': KEY_RIGHT
266         '40': KEY_DOWN
267         '35': KEY_END
268         '8':  KEY_BACKSPACE
269         '46': KEY_DELETE
270         '13': KEY_ENTER
271         '27': KEY_ESCAPE
272         '36': KEY_HOME
273         '45': KEY_INSERT
274         '33': KEY_PAGE_UP
275         '34': KEY_PAGE_DOWN
276         '9':  KEY_TAB
277
278 instantiate_tree = (tree, parent) ->
279         remove = []
280         for c, i in tree
281                 switch c.type
282                         when 'text'
283                                 c.el = parent.ownerDocument.createTextNode c.text
284                                 parent.appendChild c.el
285                         when 'tag'
286                                 if c.name in ['script', 'object', 'iframe', 'link']
287                                         # TODO put placeholders instead
288                                         remove.unshift i
289                                         continue
290                                 # TODO create in correct namespace
291                                 c.el = parent.ownerDocument.createElement c.name
292                                 for k, v of c.attrs
293                                         # FIXME if attr_whitelist[k]?
294                                         if valid_attr_regex.test k
295                                                 unless js_attr_regex.test k
296                                                         c.el.setAttribute k, v
297                                 parent.appendChild c.el
298                                 if c.children.length
299                                         instantiate_tree c.children, c.el
300         for i in remove
301                 tree.splice i, 1
302
303 traverse_tree = (tree, cb) ->
304         done = false
305         for c in tree
306                 done = cb c
307                 return done if done
308                 if c.children.length
309                         done = traverse_tree c.children, cb
310                         return done if done
311         return done
312
313 first_cursor_position = (tree) ->
314         found = null
315         traverse_tree tree, (node, state) ->
316                 if node.type is 'text'
317                         cursor = new_cursor_position n: node, i: 0
318                         if cursor?
319                                 found = cursor
320                                 return true
321                 return false
322         return found # maybe null
323
324 # this will fail when text has non-locatable cursor positions
325 find_next_cursor_position = (tree, cursor) ->
326         if cursor.n.type is 'text' and cursor.n.text.length > cursor.i
327                 new_cursor = new_cursor_position n: cursor.n, i: cursor.i + 1
328                 if new_cursor?
329                         return new_cursor
330         state_before = true
331         found = null
332         traverse_tree tree, (node, state) ->
333                 if node.type is 'text' and state_before is false
334                         new_cursor = new_cursor_position n: node, i: 0
335                         if new_cursor?
336                                 found = new_cursor
337                                 return true
338                 if node is cursor.n
339                         state_before = false
340                 return false
341         if found?
342                 return found
343         return null
344
345 last_cursor_position = (tree) ->
346         found = null
347         traverse_tree tree, (node) ->
348                 if node.type is 'text'
349                         cursor = new_cursor_position n: node, i: node.text.length
350                         if cursor?
351                                 found = cursor
352                 return false
353         return found # maybe null
354
355 # this will fail when text has non-locatable cursor positions
356 find_prev_cursor_position = (tree, cursor) ->
357         if cursor.n.type is 'text' and cursor.i > 0
358                 new_cursor = new_cursor_position n: cursor.n, i: cursor.i - 1
359                 if new_cursor?
360                         return new_cursor
361         found_prev = null
362         found = null
363         traverse_tree tree, (node) ->
364                 if node is cursor.n
365                         found = found_prev # maybe null
366                         return true
367                 if node.type is 'text'
368                         new_cursor = new_cursor_position n: node, i: node.text.length
369                         if new_cursor?
370                                 found_prev = new_cursor
371                 return false
372         return found # maybe null
373
374 find_up_cursor_position = (tree, cursor, ideal_x) ->
375         new_cursor = cursor
376         # go prev until we're higher on y axis
377         while new_cursor.y >= cursor.y
378                 new_cursor = find_prev_cursor_position tree, new_cursor
379                 return null unless new_cursor?
380         # done early if we're already left of old cursor position
381         if new_cursor.x <= ideal_x
382                 return new_cursor
383         target_y = new_cursor.y
384         # search leftward, until we find the closest position
385         # new_cursor is the prev-most position we've checked
386         # prev_cursor is the older value, so it's not as prev as new_cursor
387         while new_cursor.x > ideal_x and new_cursor.y is target_y
388                 prev_cursor = new_cursor
389                 new_cursor = find_prev_cursor_position tree, new_cursor
390                 break unless new_cursor?
391         # move cursor to prev_cursor or new_cursor
392         if new_cursor?
393                 if new_cursor.y is target_y
394                         # both valid, and on the same line, use closest
395                         if (ideal_x - new_cursor.x) < (prev_cursor.x - ideal_x)
396                                 return new_cursor
397                         else
398                                 return prev_cursor
399                 else
400                         # new_cursor on wrong line, use prev_cursor
401                         return prev_cursor
402         else
403                 # can't go any further prev, use prev_cursor
404                 return prev_cursor
405
406 find_down_cursor_position = (tree, cursor, ideal_x) ->
407         new_cursor = cursor
408         # go next until we move on the y axis
409         while new_cursor.y <= cursor.y
410                 new_cursor = find_next_cursor_position tree, new_cursor
411                 return null unless new_cursor?
412         # done early if we're already right of old cursor position
413         if new_cursor.x >= ideal_x
414                 # this would be strange, but could happen due to runaround
415                 return new_cursor
416         target_y = new_cursor.y
417         # search rightward, until we find the closest position
418         # new_cursor is the next-most position we've checked
419         # prev_cursor is the older value, so it's not as next as new_cursor
420         while new_cursor.x < ideal_x and new_cursor.y is target_y
421                 prev_cursor = new_cursor
422                 new_cursor = find_next_cursor_position tree, new_cursor
423                 break unless new_cursor?
424         # move cursor to prev_cursor or new_cursor
425         if new_cursor?
426                 if new_cursor.y is target_y
427                         # both valid, and on the same line, use closest
428                         if (new_cursor.x - ideal_x) < (ideal_x - prev_cursor.x)
429                                 return new_cursor
430                         else
431                                 return prev_cursor
432                 else
433                         # new_cursor on wrong line, use prev_cursor
434                         return prev_cursor
435         else
436                 # can't go any further prev, use prev_cursor
437                 return prev_cursor
438
439 xy_to_cursor = (tree, xy) ->
440         for n in tree
441                 if n.type is 'tag' or n.type is 'text'
442                         bounds = get_el_bounds n.el
443                         continue if xy.x < bounds.x
444                         continue if xy.x > bounds.x + bounds.w
445                         continue if xy.y < bounds.y
446                         continue if xy.y > bounds.y + bounds.h
447                         if n.children.length
448                                 ret = xy_to_cursor n.children, xy
449                                 return ret if ret?
450                         if n.type is 'text'
451                                 # click is within bounding box that contains all text.
452                                 if n.text.length is 0
453                                         ret = new_cursor_position n: n, i: 0
454                                         return ret if ret?
455                                         continue
456                                 before = new_cursor_position n: n, i: 0
457                                 continue unless before?
458                                 after = new_cursor_position n: n, i: n.text.length
459                                 continue unless after?
460                                 if xy.y < before.y + before.h and xy.x < before.x
461                                         # console.log 'before first char on first line'
462                                         continue
463                                 if xy.y > after.y and xy.x > after.x
464                                         # console.log 'after last char on last line'
465                                         continue
466                                 if xy.y < before.y
467                                         console.log "Warning: click in text bounding box but above first line"
468                                         continue # above first line (runaround?)
469                                 if xy.y > after.y + after.h
470                                         console.log "Warning: click in text bounding box but below last line", xy.y, after.y, after.h
471                                         continue # below last line (shouldn't happen?)
472                                 while after.i - before.i > 1
473                                         guess_i = Math.round((before.i + after.i) / 2)
474                                         cur = new_cursor_position n: n, i: guess_i
475                                         unless cur?
476                                                 console.log "error: failed to find cursor pixel location for", n, guess_i
477                                                 before = null
478                                                 break
479                                         if xy.y < cur.y or (xy.y <= cur.y + cur.h and xy.x < cur.x)
480                                                 after = cur
481                                         else
482                                                 before = cur
483                                 continue unless before? # signals failure to find a cursor position
484                                 # which one is closest?
485                                 if Math.abs(before.x - xy.x) < Math.abs(after.x - xy.x)
486                                         return before
487                                 else
488                                         return after
489         return null
490
491 # browsers collapse these (html5 spec calls these "space characters")
492 is_space_code = (char_code) ->
493         switch char_code
494                 when 9, 10, 12, 13, 32
495                         return true
496         return false
497 is_space = (chr) ->
498         return is_space_code chr.charCodeAt 0
499
500 tree_remove_empty_text_nodes = (tree) ->
501         empties = []
502         traverse_tree tree, (n) ->
503                 if n.type is 'text'
504                         if n.text.length is 0
505                                 empties.unshift n
506                 return false
507         for n in empties
508                 # don't completely empty the tree
509                 if tree.length is 1
510                         if tree[0].type is 'text'
511                                 console.log "oop, leaving a blank node because it's the only thing"
512                                 return
513                 n.el.parentNode.removeChild n.el
514                 for c, i in n.parent.children
515                         if c is n
516                                 n.parent.children.splice i, 1
517                                 break
518
519 # pass a array of nodes (from parser library, ie it should have .el and .text)
520 tree_dedup_space = (tree) ->
521         prev = cur = next = null
522         prev_i = cur_i = next_i = 0
523         prev_pos = pos = next_pos = null
524         prev_px = cur_px = next_px = null
525         first = true
526         removed_char = null
527
528         tree_remove_empty_text_nodes(tree)
529
530         iterate = (tree, cb) ->
531                 for n in tree
532                         if n.type is 'text'
533                                 i = 0
534                                 while i < n.text.length # don't foreach, cb might remove chars
535                                         advance = cb n, i
536                                         if advance
537                                                 i += 1
538                         if n.type is 'tag'
539                                 block = is_display_block n.el
540                                 if block
541                                         cb null
542                                 if n.children.length > 0
543                                         iterate n.children, cb
544                                 if block
545                                         cb null
546         # remove cur char
547         remove = (undo) ->
548                 if undo
549                         cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
550                         if next is cur # in same text node
551                                 next_i += 1
552                         return -1
553                 else
554                         removed_char = cur.text.charAt(cur_i)
555                         cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
556                         if next is cur # in same text node
557                                 if next_i is 0
558                                         throw "how is this possible?"
559                                 next_i -= 1
560                         return 1
561         whitespace_to_space = (undo) ->
562                 if undo
563                         cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i + 1)
564                         cur.el.textContent = cur.text
565                 else
566                         removed_char = cur.text.charAt(cur_i)
567                         cur.text = (cur.text.substr 0, cur_i) + ' ' + (cur.text.substr cur_i + 1)
568                         cur.el.textContent = cur.text
569                 return 0
570         # return true if cur was removed from the dom (ie re-use same prev)
571         operate = ->
572                 # cur definitately set
573                 # prev and/or next might be null, indicating the start/end of a display:block
574                 return false unless is_space_code cur.text.charCodeAt cur_i
575                 fixers = [remove, whitespace_to_space]
576                 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
577                 # consistent cases:
578                 # 1. zero rects returned by getClientRects() means collapsed space
579                 if bounds is null
580                         return remove()
581                 # 2. width greater than zero means visible space
582                 if bounds.w > 0
583                         fixers.shift() # don't try removing
584                 # now the weird edge cases...
585                 #
586                 # firefox and chromium both report zero width for characters at the end
587                 # of a line where the text wraps (automatically, due to word-wrap) to
588                 # the next line. These do not appear to be distinguishable from
589                 # collapsed spaces via the range/bounds api, so...
590                 #
591                 # remove it from the dom, and if prev or next moves, put it back.
592                 if prev? and not prev_px?
593                         prev_px = new_cursor_position n: prev, i: prev_i
594                 if next? and not next_px?
595                         next_px = new_cursor_position n: next, i: next_i
596                 #if prev is null and next is null
597                 #       parent_px = cur.parent.el.getBoundingClientRect()
598                 undo_arg = true # just for readabality
599                 removed = 0
600                 for fixer in fixers
601                         break if removed > 0
602                         removed += fixer()
603                         need_undo = false
604                         if prev?
605                                 if prev_px?
606                                         new_prev_px = new_cursor_position n: prev, i: prev_i
607                                         if new_prev_px?
608                                                 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
609                                                         need_undo = true
610                                         else
611                                                 need_undo = true
612                                 else
613                                         console.log "this shouldn't happen, we remove spaces that don't locate"
614                         if next? and not need_undo
615                                 if next_px?
616                                         new_next_px = new_cursor_position n: next, i: next_i
617                                         if new_next_px?
618                                                 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
619                                                         need_undo = true
620                                         else
621                                                 need_undo = true
622                                 #else
623                                 #       console.log "removing space becase space after it is collapsed"
624                         if need_undo
625                                 removed += fixer undo_arg
626                 if removed > 0
627                         return true
628                 else
629                         return false
630         # pass null at start/end of display:block
631         queue = (n, i) ->
632                 next = n
633                 next_i = i
634                 next_px = null
635                 advance = true
636                 if cur?
637                         removed = operate()
638                         # don't advance (to the next character next time) if we removed a
639                         # character from the same text node as ``next``, because doing so
640                         # renumbers the indexes in that string
641                         if removed and cur is next
642                                 advance = false
643                 else
644                         removed = false
645                 unless removed
646                         prev = cur
647                         prev_i = cur_i
648                         prev_px = cur_px
649                 cur = next
650                 cur_i = next_i
651                 cur_px = next_px
652                 return advance
653         queue null
654         iterate tree, queue
655         queue null
656
657         tree_remove_empty_text_nodes(tree)
658
659 class PeachHTML5Editor
660         # Options: (all optional)
661         #   editor_id: "id" attribute for outer-most element created by/for editor
662         #   css_file: filename of a css file to style editable content
663         #   on_init: callback for when the editable content is in place
664         constructor: (in_el, options) ->
665                 @options = options ? {}
666                 @in_el = in_el
667                 @tree = null # array of Nodes, all editable content
668                 @tree_parent = null # @tree is this.children. .el might === @idoc.body
669                 @matting = []
670                 @init_1_called = false # when iframes have loaded
671                 @outer_iframe # iframe to hold editor
672                 @outer_idoc # "document" object for @outer_iframe
673                 @wrap2 = null # scrollbar is on this
674                 @wrap2_offset = null
675                 @wrap2_height = null # including padding
676                 @iframe = null # iframe to hold editable content
677                 @idoc = null # "document" object for @iframe
678                 @cursor = null
679                 @cursor_el = null
680                 @cursor_visible = false
681                 @cursor_ideal_x = null
682                 @poll_for_blur_timeout = null
683                 opt_fragment = @options.fragment ? true
684                 @parser_opts = {}
685                 if opt_fragment
686                         @parser_opts.fragment = 'body'
687
688                 @outer_iframe = domify document, iframe: {}
689                 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
690                 if @options.editor_id?
691                         @outer_iframe.setAttribute 'id', @options.editor_id
692                 @outer_iframe.onload = =>
693                         @outer_idoc = @outer_iframe.contentDocument
694                         icss = domify @outer_idoc, style: children: [
695                                 domify @outer_idoc, text: css
696                         ]
697                         @outer_idoc.head.appendChild icss
698                         @iframe = domify @outer_idoc, iframe: sandbox: 'allow-same-origin allow-scripts'
699                         @iframe.onload = =>
700                                 @init_1()
701                         timeout 200, => # firefox never fires this onload
702                                 @init_1() unless @init_1_called
703                         @outer_idoc.body.appendChild(
704                                 domify @outer_idoc, div: id: 'wrap1', children: [
705                                         domify @outer_idoc, div: style: "position: absolute; top: 0; left: 1px; font-size: 10px", children: [ domify @outer_idoc, text: "Peach HTML5 Editor" ]
706                                         @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
707                                                 domify @outer_idoc, div: id: 'wrap3', children: [
708                                                         @iframe
709                                                         @overlay = domify @outer_idoc, div: id: 'overlay'
710                                                 ]
711                                         ]
712                                 ]
713                         )
714                 outer_wrap = domify document, div: class: 'peach_html5_editor'
715                 @in_el.parentNode.appendChild outer_wrap
716                 outer_bounds = get_el_bounds outer_wrap
717                 if outer_bounds.w < 300
718                         outer_bounds.w = 300
719                 if outer_bounds.h < 300
720                         outer_bounds.h = 300
721                 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
722                 @outer_iframe.setAttribute 'style', outer_iframe_style
723                 css = @generate_outer_css w: outer_bounds.w, h: outer_bounds.h
724                 outer_wrap.appendChild @outer_iframe
725         init_1: -> # @iframe has loaded (but not it's css)
726                 @idoc = @iframe.contentDocument
727                 @init_1_called = true
728                 # chromium doesn't resolve relative urls as though they were at the same domain
729                 # so add a <base> tag
730                 @idoc.head.appendChild domify @idoc, base: href: this_url_sans_path()
731                 # don't let @iframe have scrollbars
732                 @idoc.head.appendChild domify @idoc, style: children: [domify @idoc, text: "body { overflow: hidden; }"]
733                 # load css file
734                 if @options.css_file
735                         istyle = domify @idoc, link: rel: 'stylesheet', href: @options.css_file
736                         istyle.onload = =>
737                                 @init_2()
738                         @idoc.head.appendChild istyle
739                 else
740                         @init_2()
741         init_2: -> # @iframe and it's css file(s) are ready
742                 @overlay.onclick = (e) =>
743                         @have_focus()
744                         return event_return e, @onclick e
745                 @overlay.ondoubleclick = (e) =>
746                         @have_focus()
747                         return event_return e, @ondoubleclick e
748                 @outer_idoc.body.onkeyup = (e) =>
749                         @have_focus()
750                         return event_return e, @onkeyup e
751                 @outer_idoc.body.onkeydown = (e) =>
752                         @have_focus()
753                         return event_return e, @onkeydown e
754                 @outer_idoc.body.onkeypress = (e) =>
755                         @have_focus()
756                         return event_return e, @onkeypress e
757                 @load_html @in_el.value
758                 if @options.on_init?
759                         @options.on_init()
760         generate_outer_css: (args) ->
761                 w = args.w ? 300
762                 h = args.h ? 300
763                 inner_padding = args.inner_padding ? overlay_padding
764                 frame_width = args.frame_width ? inner_padding
765                 occupy = (left, top = left, right = left, bottom = top) ->
766                         w -= left + right
767                         h -= top + bottom
768                         return Math.max(left, top, right, bottom)
769                 ret = ''
770                 ret += 'body {'
771                 ret +=     'margin: 0;'
772                 ret +=     'padding: 0;'
773                 ret +=     'color: black;'
774                 ret +=     'background: white;'
775                 ret += '}'
776                 ret += '#wrap1 {'
777                 ret +=     "border: #{occupy 1}px solid black;"
778                 ret +=     "padding: #{occupy frame_width}px;"
779                 ret += '}'
780                 ret += '#wrap2 {'
781                 ret +=     "border: #{occupy 1}px solid black;"
782                 @wrap2_height = h # including padding because padding scrolls
783                 ret +=     "padding: #{occupy inner_padding}px;"
784                 ret +=     "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
785                 ret +=     "width: #{w}px;"
786                 ret +=     "height: #{h}px;"
787                 ret +=     'overflow-x: hidden;'
788                 ret +=     'overflow-y: scroll;'
789                 ret += '}'
790                 ret += '#wrap3 {'
791                 ret +=     'position: relative;'
792                 ret +=     "width: #{w}px;"
793                 ret +=     "min-height: #{h}px;"
794                 ret += '}'
795                 ret += 'iframe {'
796                 ret +=     'box-sizing: border-box;'
797                 ret +=     'margin: 0;'
798                 ret +=     'border: none;'
799                 ret +=     'padding: 0;'
800                 ret +=     "width: #{w}px;"
801                 #ret +=     "height: #{h}px;" # height auto-set when content set/changed
802                 ret +=     '-ms-user-select: none;'
803                 ret +=     '-webkit-user-select: none;'
804                 ret +=     '-moz-user-select: none;'
805                 ret +=     'user-select: none;'
806                 ret += '}'
807                 ret += '#overlay {'
808                 ret +=     'position: absolute;'
809                 ret +=     "left: -#{inner_padding}px;"
810                 ret +=     "top: -#{inner_padding}px;"
811                 ret +=     "right: -#{inner_padding}px;"
812                 ret +=     "bottom: -#{inner_padding}px;"
813                 ret +=     'overflow: hidden;'
814                 ret += '}'
815                 ret += '.lightbox {'
816                 ret +=     'position: absolute;'
817                 ret +=     'background: rgba(100,100,100,0.2);'
818                 ret += '}'
819                 ret += '#cursor {'
820                 ret +=     'position: absolute;'
821                 ret +=     'width: 2px;'
822                 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));'
823                 ret +=     'background-size: 200% 200%;'
824                 ret +=     '-webkit-animation: blink 1s linear normal infinite;'
825                 ret +=     'animation: blink 1s linear normal infinite;'
826                 ret += '}'
827                 ret += '@-webkit-keyframes blink {'
828                 ret +=     '0%{background-position:0% 0%}'
829                 ret +=     '100%{background-position:0% -100%}'
830                 ret += '}'
831                 ret += '@keyframes blink { '
832                 ret +=     '0%{background-position:0% 0%}'
833                 ret +=     '100%{background-position:0% -100%}'
834                 ret += '}'
835                 ret += '.ann_box {'
836                 ret +=     'z-index: 5;'
837                 ret +=     'position: absolute;'
838                 ret +=     'border: 1px solid rgba(0,0,0,0.1);'
839                 ret +=     'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
840                 ret += '}'
841                 ret += '.ann_tag {'
842                 ret +=     'z-index: 10;'
843                 ret +=     'position: absolute;'
844                 ret +=     'font-size: 8px;'
845                 ret +=     'white-space: pre;'
846                 ret +=     'background: rgba(255,255,255,0.4);'
847                 ret +=     '-ms-user-select: none;'
848                 ret +=     '-webkit-user-select: none;'
849                 ret +=     '-moz-user-select: none;'
850                 ret +=     'user-select: none;'
851                 ret += '}'
852                 return ret
853         overlay_event_to_inner_xy: (e) ->
854                 unless @wrap2_offset?
855                         @wrap2_offset = get_el_bounds @wrap2
856                 x = e.pageX - overlay_padding
857                 y = e.pageY - overlay_padding + @wrap2.scrollTop
858                 return x: x - @wrap2_offset.x, y: y - @wrap2_offset.y
859         onclick: (e) ->
860                 xy = @overlay_event_to_inner_xy e
861                 new_cursor = xy_to_cursor @tree, xy
862                 if new_cursor?
863                         @move_cursor new_cursor
864                 else
865                         @kill_cursor()
866                 return false
867         ondoubleclick: (e) ->
868                 return false
869         onkeyup: (e) ->
870                 return if e.ctrlKey
871                 return false if ignore_key_codes[e.keyCode]?
872                 #return false if control_key_codes[e.keyCode]?
873         onkeydown: (e) ->
874                 return if e.ctrlKey
875                 return false if ignore_key_codes[e.keyCode]?
876                 #return false if control_key_codes[e.keyCode]?
877                 switch e.keyCode
878                         when KEY_LEFT
879                                 if @cursor?
880                                         new_cursor = find_prev_cursor_position @tree, @cursor
881                                 else
882                                         new_cursor = first_cursor_position @tree
883                                 if new_cursor?
884                                         @move_cursor new_cursor
885                                 return false
886                         when KEY_RIGHT
887                                 if @cursor?
888                                         new_cursor = find_next_cursor_position @tree, @cursor
889                                 else
890                                         new_cursor = last_cursor_position @tree
891                                 if new_cursor?
892                                         @move_cursor new_cursor
893                                 return false
894                         when KEY_UP
895                                 if @cursor?
896                                         new_cursor = find_up_cursor_position @tree, @cursor, @cursor_ideal_x
897                                         if new_cursor?
898                                                 saved_ideal_x = @cursor_ideal_x
899                                                 @move_cursor new_cursor
900                                                 @cursor_ideal_x = saved_ideal_x
901                                 else
902                                         # move cursor to first position in document
903                                         new_cursor = first_cursor_position @tree
904                                         if new_cursor?
905                                                 @move_cursor new_cursor
906                                 return false
907                         when KEY_DOWN
908                                 if @cursor?
909                                         new_cursor = find_down_cursor_position @tree, @cursor, @cursor_ideal_x
910                                         if new_cursor?
911                                                 saved_ideal_x = @cursor_ideal_x
912                                                 @move_cursor new_cursor
913                                                 @cursor_ideal_x = saved_ideal_x
914                                 else
915                                         # move cursor to first position in document
916                                         new_cursor = last_cursor_position @tree
917                                         if new_cursor?
918                                                 @move_cursor new_cursor
919                                 return false
920                         when KEY_END
921                                 new_cursor = last_cursor_position @tree
922                                 if new_cursor?
923                                         @move_cursor new_cursor
924                                 return false
925                         when KEY_BACKSPACE
926                                 @on_key_backspace e
927                                 return false
928                         when KEY_DELETE
929                                 return false unless @cursor?
930                                 return false unless @cursor.i < @cursor.n.text.length
931                                 @remove_character @cursor.n, @cursor.i
932                                 @adjust_whitespace_style @cursor.n
933                                 @changed()
934                                 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i
935                                 if new_cursor?
936                                         @move_cursor new_cursor
937                                 else
938                                         @kill_cursor()
939                                 return false
940                         when KEY_ENTER
941                                 @on_key_enter e
942                                 return false
943                         when KEY_ESCAPE
944                                 @kill_cursor()
945                                 return false
946                         when KEY_HOME
947                                 new_cursor = first_cursor_position @tree
948                                 if new_cursor?
949                                         @move_cursor new_cursor
950                                 return false
951                         when KEY_INSERT
952                                 return false
953                         when KEY_PAGE_UP
954                                 return false
955                         when KEY_PAGE_DOWN
956                                 return false
957                         when KEY_TAB
958                                 return false
959         onkeypress: (e) ->
960                 return if e.ctrlKey
961                 return false if ignore_key_codes[e.keyCode]?
962                 char = e.charCode ? e.keyCode
963                 if char and @cursor?
964                         char = String.fromCharCode char
965                         @insert_character @cursor.n, @cursor.i, char
966                         @adjust_whitespace_style @cursor.n
967                         @changed()
968                         new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i + 1
969                         if new_cursor
970                                 @move_cursor new_cursor
971                         else
972                                 console.log "ERROR: couldn't find cursor position after insert"
973                                 @kill_cursor()
974                 return false
975         on_key_enter: (e) -> # enter key pressed
976                 return unless @cursor_visible
977                 cur_block = @cursor.n
978                 loop
979                         if cur_block.type is 'tag'
980                                 if is_display_block cur_block.el
981                                         break
982                         return unless cur_block.parent?
983                         cur_block = cur_block.parent
984                 # find array to insert new element into
985                 if cur_block.parent is @tree_parent # top-level
986                         parent_el = @idoc.body
987                         pc = @tree
988                 else
989                         parent_el = cur_block.parent.el
990                         pc = cur_block.parent.children
991                 # find index of current block in its parent
992                 for n, i in pc
993                         break if n is cur_block
994                 i += 1 # we want to be after it
995                 if i < pc.length
996                         before = pc[i].el
997                 else
998                         before = null
999                 # TODO if content after cursor
1000                 #       TODO new block is empty
1001                 new_text = new peach_parser.Node 'text', text: ' '
1002                 new_node = new peach_parser.Node 'tag', name: 'p', parent: cur_block.parent, attrs: {style: 'white-space: pre-wrap'}, children: [new_text]
1003                 new_text.parent = new_node
1004                 new_text.el = domify @idoc, text: ' '
1005                 new_node.el = domify @idoc, p: style: 'white-space: pre-wrap', children: [new_text.el]
1006                 pc.splice i, 0, new_node
1007                 parent_el.insertBefore new_node.el, before
1008                 @changed()
1009                 new_cursor = new_cursor_position n: new_text, i: 0
1010                 throw 'bork bork' unless new_cursor?
1011                 @move_cursor new_cursor
1012                 # TODO move content past cursor into this new block
1013         on_key_backspace: (e) ->
1014                 return false unless @cursor?
1015                 if @is_lone_space @cursor.n # false if it's not in a tag
1016                         if @cursor.i is 1
1017                                 # don't delete the space, because then it would collapse
1018                                 # instead leave a space after the cursor
1019                                 new_cursor = new_cursor_position n: @cursor.n, i: 0
1020                                 if new_cursor?
1021                                         @move_cursor new_cursor
1022                                 else
1023                                         @kill_cursor()
1024                         else
1025                                 parent = @cursor.n.parent
1026                                 new_cursor = find_prev_cursor_position @tree, @cursor
1027                                 if new_cursor?
1028                                         if new_cursor.n is @cursor.n or new_cursor.n is parent
1029                                                 new_cursor = null
1030                                 tag = @cursor.n.parent
1031                                 if tag is @tree_parent
1032                                         console.log "top-level text not supported" # FIXME
1033                                         return false
1034                                 for n, i in tag.parent.children
1035                                         if n is tag
1036                                                 tag.parent.el.removeChild tag.el
1037                                                 tag.parent.children.splice i, 1
1038                                                 break
1039                                 @changed()
1040                                 if new_cursor?
1041                                         # re-check, in case it moved or is invalid now
1042                                         new_cursor = new_cursor_position n: new_cursor.n, i: new_cursor.i
1043                                         if new_cursor?
1044                                                 @move_cursor new_cursor
1045                                                 return
1046                                 new_cursor = first_cursor_position @tree
1047                                 if new_cursor?
1048                                         @move_cursor new_cursor
1049                                 else
1050                                         @kill_cursor
1051                                 return
1052                 else if @cursor.i is 0
1053                         console.log 'unimplemented: backspace at start of non-empty tag'
1054                         # TODO if block, merge parent into prev
1055                         # TODO if inline, delete char from prev text node
1056                         return false
1057                 else
1058                         # TODO handle case of removing last char
1059                         # CONTINUE
1060                         if @is_only_char_in_tag @cursor.n
1061                                 if is_display_block @cursor.n.parent.el
1062                                         @cursor.n.el.textContent = @cursor.n.text = ' '
1063                                 else
1064                                         console.log "unimplemented: delete last char in inline" # FIXME
1065                                         return
1066                         else
1067                                 @remove_character @cursor.n, @cursor.i - 1
1068                         @adjust_whitespace_style @cursor.n
1069                         @changed()
1070                         new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i - 1
1071                         if new_cursor?
1072                                 @move_cursor new_cursor
1073                         else
1074                                 @kill_cursor()
1075                 return
1076         clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
1077                 while @idoc.body.childNodes.length
1078                         @idoc.body.removeChild @idoc.body.childNodes[0]
1079                 @kill_cursor()
1080                 return
1081         load_html: (html) ->
1082                 @tree = peach_parser.parse html, @parser_opts
1083                 if !@tree[0]?.parent
1084                         @tree = peach_parser.parse '<p style="white-space: pre-wrap"> </p>', @parser_opts
1085                 @tree_parent = @tree[0]?.parent
1086                 @tree_parent.el = @idoc.body
1087                 @clear_dom()
1088                 instantiate_tree @tree, @tree_parent.el
1089                 tree_dedup_space @tree
1090                 @changed()
1091         changed: ->
1092                 @in_el.onchange = null
1093                 @in_el.value = @pretty_html @tree
1094                 @in_el.onchange = =>
1095                         @load_html @in_el.value
1096                 @adjust_iframe_height()
1097         adjust_iframe_height: ->
1098                 s = @wrap2.scrollTop
1099                 # when the content gets shorter, the idoc's body tag will continue to
1100                 # report the old (too big) height in Chrome. The workaround is to
1101                 # shrink the iframe before the content height:
1102                 @iframe.style.height = "10px"
1103                 h = parseInt(@idoc.body.scrollHeight, 10)
1104                 @iframe.style.height = "#{h}px"
1105                 @wrap2.scrollTop = s
1106         # does this node have whitespace that would be collapsed by white-space: normal?
1107         # note: this checks direct text children, and does _not_ recurse into child tags
1108         # tag is a node with type:"tag"
1109         has_collapsable_space: (tag) ->
1110                 for n in tag.children
1111                         if n.type is 'text'
1112                                 for i in [0...n.text.length]
1113                                         code = n.text.charCodeAt i
1114                                         if code isnt 32 and is_space_code code
1115                                                 # tab, return
1116                                                 return true
1117                                         # check for double spaces that don't surround insert location
1118                                         continue if i is 0
1119                                         if n.text.substr(i - 1, 2) is '  '
1120                                                 return true
1121                                 if n.text.length > 0
1122                                         if is_space_code n.text.charCodeAt 0
1123                                                 return true
1124                                         if is_space_code n.text.charCodeAt n.text.length - 1
1125                                                 return true
1126         # add/remove "white-space: pre[-wrap]" to/from style="" on tags with direct
1127         # child text nodes with multiple spaces in a row, or spaces at the
1128         # start/end.
1129         #
1130         # text inside child tags are not consulted. Child tags are expected to have
1131         # this function applied to them when their content changes.
1132         adjust_whitespace_style: (n) ->
1133                 if n.type is 'text'
1134                         n = n.parent
1135                         return unless n?.el?
1136                 # which css rule should be used to preserve spaces (should we need to)
1137                 style = @iframe.contentWindow.getComputedStyle n.el, null
1138                 ws = style.getPropertyValue 'white-space'
1139                 if ws_props[ws].space
1140                         preserve_rule = ws
1141                 else
1142                         preserve_rule = ws_props[ws].to_preserve
1143                 preserve_rule = "white-space: #{preserve_rule}"
1144                 if @has_collapsable_space n
1145                         # make sure preserve_rule exists
1146                         if n.el.style['white-space']
1147                                 # FIXME check that it matches
1148                                 return
1149                         if n.attrs[style]?
1150                                 n.attrs.style += "; #{preserve_rule}"
1151                         else
1152                                 n.attrs.style = preserve_rule
1153                         n.el.setAttribute 'style', n.attrs.style
1154                 else
1155                         # remove preserve_rule if it exists
1156                         return unless n.attrs.style?
1157                         # FIXME don't assume whitespace is just so
1158                         if n.attrs.style is "white-space: #{ws}"
1159                                 delete n.attrs.style
1160                                 n.el.removeAttribute 'style'
1161                         else
1162                                 # FIXME find it in the middle and at the start
1163                                 needle = "; white-space: #{ws}"
1164                                 if needle is n.attrs.style.substr n.attrs.style.length - needle
1165                                         n.attrs.style = n.attrs.style.substr 0, n.attrs.style.length - needle
1166                                         n.el.setAttribute n.attrs.style
1167         # true if n is text node with only one caracter, and the only child of a tag
1168         is_only_char_in_tag: (n, i) ->
1169                 return false unless n.type is 'text'
1170                 return false unless n.text.length is 1
1171                 return false if n.parent is @tree_parent
1172                 return false unless n.parent.children.length is 1
1173                 return true
1174         # true if n is text node with just a space in it, and the only child of a tag
1175         is_lone_space: (n, i) ->
1176                 return false unless n.type is 'text'
1177                 return false unless n.text is ' '
1178                 return false if n.parent is @tree_parent
1179                 return false unless n.parent.children.length is 1
1180                 return true
1181         # detect special case: typing before a space that's the only thing in a block/doc
1182         # reason: enter key creates blocks with just a space in them
1183         insert_should_replace: (n, i) ->
1184                 return false unless i is 0
1185                 return false unless n.text is ' '
1186                 return true if n.parent is @tree_parent
1187                 if n.parent.children.length is 1
1188                         if n.parent.children[0] is n
1189                                 # n is only child
1190                                 return true
1191                 return false
1192         # after calling this, you MUST call changed() and adjust_whitespace_style()
1193         insert_character: (n, i, char) ->
1194                 return if @cursor.n.parent is @tree_parent # FIXME implement text nodes at top level
1195                 parent = @cursor.n.parent
1196                 # insert the character
1197                 if @insert_should_replace n, i
1198                         n.text = char
1199                 else if i is 0
1200                         n.text = char + n.text
1201                 else if i is n.text.length
1202                         # replace the space
1203                         n.text += char
1204                 else
1205                         n.text =
1206                                 n.text.substr(0, i) +
1207                                 char +
1208                                 n.text.substr(i)
1209                 n.el.nodeValue = n.text
1210         # after calling this, you MUST call changed() and adjust_whitespace_style()
1211         remove_character: (n, i) ->
1212                 n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1213                 n.el.nodeValue = n.text
1214         kill_cursor: -> # remove it, forget where it was
1215                 if @cursor_visible
1216                         @cursor_el.parentNode.removeChild @cursor_el
1217                         @cursor_visible = false
1218                 @cursor = null
1219                 @annotate null
1220         move_cursor: (cursor) ->
1221                 @cursor_ideal_x = cursor.x
1222                 @cursor = cursor
1223                 unless @cursor_visible
1224                         @cursor_el = domify @outer_idoc, div: id: 'cursor'
1225                         @overlay.appendChild @cursor_el
1226                         @cursor_visible = true
1227                 @cursor_el.style.left = "#{cursor.x + overlay_padding - 1}px"
1228                 if cursor.h < 5
1229                         height = 12
1230                 else
1231                         height = cursor.h
1232                 @cursor_el.style.top = "#{cursor.y + overlay_padding + Math.round(height * .07)}px"
1233                 @cursor_el.style.height = "#{Math.round height * 0.82}px"
1234                 @annotate cursor.n
1235                 @scroll_into_view cursor.y, height
1236         scroll_into_view: (y, h = 0) ->
1237                 closest = 30 # setting: smallest pixels from top/bottom of screet that's OK
1238                 y += overlay_padding # convert units from @idoc to @wrap2
1239                 # very top of document
1240                 if y <= closest
1241                         @wrap2.scrollTop = 0
1242                         return
1243                 # very bottom of document
1244                 if y + h >= @wrap2.scrollHeight - closest
1245                         @wrap2.scrollTop = @wrap2.scrollHeight - @wrap2_height
1246                         return
1247                 # The most scrolled up (lowest value for scrollTop) that would be OK
1248                 upmost = y + h + closest - @wrap2_height
1249                 upmost = Math.max(upmost, 0)
1250                 # the most scrolled down (highest value for scrollTop) that would be OK
1251                 downmost = y - closest
1252                 downmost = Math.min(downmost, @wrap2.scrollHeight - @wrap2_height)
1253                 if upmost > downmost # means h is too big to fit
1254                         # scroll so top is visible
1255                         @wrap2.scrollTop = downmost
1256                         return
1257                 if @wrap2.scrollTop < upmost
1258                         @wrap2.scrollTop = upmost
1259                         return
1260                 if @wrap2.scrollTop > downmost
1261                         @wrap2.scrollTop = downmost
1262                         return
1263                 return
1264         annotate: (n) ->
1265                 while @matting.length > 0
1266                         @overlay.removeChild @matting[0]
1267                         @matting.shift()
1268                 return unless n?
1269                 prev_bounds = x: 0, y: 0, w: 0, h: 0
1270                 alpha = 0.1
1271                 while n?.el? and n isnt @tree_parent
1272                         if n.type is 'text'
1273                                 n = n.parent
1274                                 continue
1275                         bounds = get_el_bounds n.el
1276                         return unless bounds?
1277                         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
1278                                 n = n.parent
1279                                 continue
1280                         ann_box = domify @outer_idoc, div: class: 'ann_box', style: "left: #{bounds.x - 1 + overlay_padding}px; top: #{bounds.y - 2 + overlay_padding}px; width: #{bounds.w}px; height: #{bounds.h}px" # outline: 1000px solid rgba(0,153,255,#{alpha});
1281                         @overlay.appendChild ann_box
1282                         @matting.push ann_box
1283                         ann_tag = domify @outer_idoc, div: class: 'ann_tag', style: "left: #{bounds.x + 1 + overlay_padding}px; top: #{bounds.y - 7 + overlay_padding}px", children: [domify @outer_idoc, text: " #{n.name} "]
1284                         @overlay.appendChild ann_tag
1285                         @matting.push ann_tag
1286                         n = n.parent
1287                         alpha *= 1.5
1288         pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
1289                 ret = ''
1290                 want_nl = parent_flags.want_nl
1291                 prev_in_flow_is_text = false
1292                 prev_in_flow_is_block = false
1293                 for n, i in tree
1294                         # figure out flags
1295                         inner_flags = want_nl: true
1296                         is_br = false
1297                         switch n.type
1298                                 when 'tag'
1299                                         if n.name is 'br'
1300                                                 is_br = true
1301                                         is_text = false
1302                                         if n.el.currentStyle?
1303                                                 cs = n.el.currentStyle
1304                                                 whitespace = cs['white-space']
1305                                                 display = cs['display']
1306                                                 position = cs['position']
1307                                                 float = cs['float']
1308                                                 visibility = cs['visibility']
1309                                         else
1310                                                 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
1311                                                 whitespace = cs.getPropertyValue 'white-space'
1312                                                 display = cs.getPropertyValue 'display'
1313                                                 position = cs.getPropertyValue 'position'
1314                                                 float = cs.getPropertyValue 'float'
1315                                                 visibility = cs.getPropertyValue 'visibility'
1316                                         if n.name is 'textarea'
1317                                                 inner_flags.pre_ish = true
1318                                         else
1319                                                 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
1320                                         switch float
1321                                                 when 'left', 'right'
1322                                                         in_flow = false
1323                                                 else
1324                                                         switch position
1325                                                                 when 'absolute', 'fixed'
1326                                                                         in_flow = false
1327                                                                 else
1328                                                                         if 'display' is 'none'
1329                                                                                 in_flow = false
1330                                                                         else
1331                                                                                 switch visibility
1332                                                                                         when 'hidden', 'collapse'
1333                                                                                                 in_flow = false
1334                                                                                         else # visible
1335                                                                                                 in_flow = true
1336                                         switch display
1337                                                 when 'inline', 'none'
1338                                                         inner_flags.block = false
1339                                                         is_block = in_flow_block = false
1340                                                 when 'inline-black'
1341                                                         inner_flags.block = true
1342                                                         is_block = in_flow_block = false
1343                                                 else # block, table, etc
1344                                                         inner_flags.block = true
1345                                                         is_block = true
1346                                                         in_flow_block = in_flow
1347                                 when 'text'
1348                                         is_text = true
1349                                         is_block = false
1350                                         in_flow = true
1351                                         in_flow_block = false
1352                                 else # 'comment', 'doctype'
1353                                         is_text = false
1354                                         is_block = false
1355                                         in_flow = false
1356                                         in_flow_block = false
1357                         # print whitespace if we can
1358                         unless parent_flags.pre_ish
1359                                 unless prev_in_flow_is_text and is_br
1360                                         if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
1361                                                 if want_nl
1362                                                         ret += "\n"
1363                                                 ret += indent
1364                         switch n.type
1365                                 when 'tag'
1366                                         ret += '<' + n.name
1367                                         attr_keys = []
1368                                         for k of n.attrs
1369                                                 attr_keys.unshift k
1370                                         #attr_keys.sort()
1371                                         for k in attr_keys
1372                                                 ret += " #{k}"
1373                                                 if n.attrs[k].length > 0
1374                                                         ret += "=\"#{enc_attr n.attrs[k]}\""
1375                                         ret += '>'
1376                                         unless void_elements[n.name]?
1377                                                 if inner_flags.block
1378                                                         next_indent = indent + '    '
1379                                                 else
1380                                                         next_indent = indent
1381                                                 if n.children.length
1382                                                         ret += @pretty_html n.children, next_indent, inner_flags
1383                                                 ret += "</#{n.name}>"
1384                                 when 'text'
1385                                         ret += enc_text n.text
1386                                 when 'comment'
1387                                         ret += "<!--#{n.text}-->" # TODO encode?
1388                                 when 'doctype'
1389                                         ret += "<!DOCTYPE #{n.name}"
1390                                         if n.public_identifier? and n.public_identifier.length > 0
1391                                                 ret += " \"#{n.public_identifier}\""
1392                                         if n.system_identifier? and n.system_identifier.length > 0
1393                                                 ret += " \"#{n.system_identifier}\""
1394                                         ret += ">"
1395                         want_nl = true
1396                         if in_flow
1397                                 prev_in_flow_is_text = is_text
1398                                 prev_in_flow_is_block = is_block or (in_flow and is_br)
1399                 if tree.length
1400                         # output final newline if allowed
1401                         unless parent_flags.pre_ish
1402                                 if prev_in_flow_is_block or parent_flags.block
1403                                         ret += "\n#{indent.substr 4}"
1404                 return ret
1405         onblur: ->
1406                 @kill_cursor()
1407         have_focus: ->
1408                 @editor_is_focused = true
1409                 @poll_for_blur()
1410         poll_for_blur: ->
1411                 return if @poll_for_blur_timeout? # already polling
1412                 @poll_for_blur_timeout = timeout 150, =>
1413                         next_frame => # pause polling when browser knows we're not active/visible/etc.
1414                                 @poll_for_blur_timeout = null
1415                                 if document.activeElement is @outer_iframe
1416                                         @poll_for_blur()
1417                                 else
1418                                         @editor_is_focused = false
1419                                         @onblur()
1420
1421 window.peach_html5_editor = (args...) ->
1422         return new PeachHTML5Editor args...
1423
1424 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])