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