JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
remove obsolete debugging code
[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 (scrolling)
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                 to_collapse: 'nowrap'
63         'pre-wrap':
64                 space: true
65                 newline: true
66                 wrap: true
67                 to_collapse: 'normal'
68
69 # xml 1.0 spec, chromium and firefox accept these, plus lots of unicode chars
70 valid_attr_regex = new RegExp '^[a-zA-Z_:][-a-zA-Z0-9_:.]*$'
71 # html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
72 js_attr_regex = new RegExp '^[oO][nN].'
73 # html5 spec says that only these characters are collapsable
74 multi_sp_regex = new RegExp '[\u0020\u0009\u000a\u000c\u000d][\u0020\u0009\u000a\u000c\u000d]'
75
76 str_has_ws_run = (str) ->
77         return multi_sp_regex.test str
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 # done traversing
322                 return false # not done traversing
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 # done traversing
339                 if node is cursor.n
340                         state_before = false
341                 return false # not done traversing
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 # not done traversing
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 # done traversing
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 # not done traversing
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 # not done traversing
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 # remove whitespace that would be trimmed
521 # replace whitespace that would collapse with a single space
522 # FIXME delete this, use @collapse_whitespace instead
523 collapse_whitespace = (tree) ->
524         prev = cur = next = null
525         prev_i = cur_i = next_i = 0
526         prev_pos = pos = next_pos = null
527         prev_px = cur_px = next_px = null
528         first = true
529         removed_char = null
530
531         tree_remove_empty_text_nodes(tree)
532
533         iterate = (tree, cb) ->
534                 for n in tree
535                         if n.type is 'text'
536                                 i = 0
537                                 while i < n.text.length # don't foreach, cb might remove chars
538                                         advance = cb n, i
539                                         if advance
540                                                 i += 1
541                         if n.type is 'tag'
542                                 block = is_display_block n.el
543                                 if block
544                                         cb null
545                                 if n.children.length > 0
546                                         iterate n.children, cb
547                                 if block
548                                         cb null
549         # remove cur char
550         remove = (undo) ->
551                 if undo
552                         cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
553                         if next is cur # in same text node
554                                 next_i += 1
555                         return -1
556                 else
557                         removed_char = cur.text.charAt(cur_i)
558                         cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
559                         if next is cur # in same text node
560                                 if next_i is 0
561                                         throw "how is this possible?"
562                                 next_i -= 1
563                         return 1
564         replace_with_space = (undo) ->
565                 if undo
566                         cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i + 1)
567                         cur.el.textContent = cur.text
568                 else
569                         removed_char = cur.text.charAt(cur_i)
570                         if removed_char isnt ' '
571                                 cur.text = (cur.text.substr 0, cur_i) + ' ' + (cur.text.substr cur_i + 1)
572                                 cur.el.textContent = cur.text
573                 return 0
574         # return true if cur was removed from the dom (ie re-use same prev)
575         operate = ->
576                 # cur definitately set
577                 # prev and/or next might be null, indicating the start/end of a display:block
578                 return false unless is_space_code cur.text.charCodeAt cur_i
579                 fixers = [remove, replace_with_space]
580                 # check for common case: single whitespace surrounded by non-whitespace chars
581                 if prev? and next?
582                         unless (is_space_code prev.text.charCodeAt prev_i) or (is_space_code next.text.charCodeAt next_i)
583                                 dbg = cur.text.charCodeAt cur_i
584                                 if cur.text.charAt(cur_i) is ' ' # perens required
585                                         # single space can't collapse, doesn't need fixin'
586                                         return false
587                                 else
588                                         # tab, newline, etc, can't collapse, but maybe should be replaced
589                                         fixers = [replace_with_space]
590                 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
591                 # consistent cases:
592                 # 1. zero rects returned by getClientRects() means collapsed space
593                 if bounds is null
594                         return remove()
595                 # 2. width greater than zero means visible space
596                 if bounds.w > 0
597                         # has bounds, don't try removing
598                         fixers = [replace_with_space]
599                 # now the weird edge cases...
600                 #
601                 # firefox and chromium both report zero width for characters at the end
602                 # of a line where the text wraps (automatically, due to word-wrap) to
603                 # the next line. These do not appear to be distinguishable from
604                 # collapsed spaces via the range/bounds api, so...
605                 #
606                 # remove it from the dom, and if prev or next moves, put it back.
607                 #
608                 # this block (try changing it, put it back if something moves) is also
609                 # used on collapsable whitespace characters besides space. In this case
610                 # the character is replaced with a normal space character instead of
611                 # removed
612                 if prev? and not prev_px?
613                         prev_px = new_cursor_position n: prev, i: prev_i
614                 if next? and not next_px?
615                         next_px = new_cursor_position n: next, i: next_i
616                 #if prev is null and next is null
617                 #       parent_px = cur.parent.el.getBoundingClientRect()
618                 undo_arg = true # just for readabality
619                 removed = 0
620                 for fixer in fixers
621                         break if removed > 0
622                         removed += fixer()
623                         need_undo = false
624                         if prev?
625                                 if prev_px?
626                                         new_prev_px = new_cursor_position n: prev, i: prev_i
627                                         if new_prev_px?
628                                                 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
629                                                         need_undo = true
630                                         else
631                                                 need_undo = true
632                                 else
633                                         console.log "this shouldn't happen, we remove spaces that don't locate"
634                         if next? and not need_undo
635                                 if next_px?
636                                         new_next_px = new_cursor_position n: next, i: next_i
637                                         if new_next_px?
638                                                 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
639                                                         need_undo = true
640                                         else
641                                                 need_undo = true
642                                 #else
643                                 #       console.log "removing space becase space after it is collapsed"
644                         if need_undo
645                                 removed += fixer undo_arg
646                 if removed > 0
647                         return true
648                 else
649                         return false
650         # pass null at start/end of display:block
651         queue = (n, i) ->
652                 next = n
653                 next_i = i
654                 next_px = null
655                 advance = true
656                 if cur?
657                         removed = operate()
658                         # don't advance (to the next character next time) if we removed a
659                         # character from the same text node as ``next``, because doing so
660                         # renumbers the indexes in that string
661                         if removed and cur is next
662                                 advance = false
663                 else
664                         removed = false
665                 unless removed
666                         prev = cur
667                         prev_i = cur_i
668                         prev_px = cur_px
669                 cur = next
670                 cur_i = next_i
671                 cur_px = next_px
672                 return advance
673         queue null
674         iterate tree, queue
675         queue null
676
677         tree_remove_empty_text_nodes(tree)
678
679 class PeachHTML5Editor
680         # Options: (all optional)
681         #   editor_id: "id" attribute for outer-most element created by/for editor
682         #   css_file: filename of a css file to style editable content
683         #   on_init: callback for when the editable content is in place
684         constructor: (in_el, options) ->
685                 @options = options ? {}
686                 @in_el = in_el
687                 @tree = null # array of Nodes, all editable content
688                 @tree_parent = null # @tree is this.children. .el might === @idoc.body
689                 @matting = []
690                 @init_1_called = false # when iframes have loaded
691                 @outer_iframe # iframe to hold editor
692                 @outer_idoc # "document" object for @outer_iframe
693                 @wrap2 = null # scrollbar is on this
694                 @wrap2_offset = null
695                 @wrap2_height = null # including padding
696                 @iframe = null # iframe to hold editable content
697                 @idoc = null # "document" object for @iframe
698                 @cursor = null
699                 @cursor_el = null
700                 @cursor_visible = false
701                 @cursor_ideal_x = null
702                 @poll_for_blur_timeout = null
703                 opt_fragment = @options.fragment ? true
704                 @parser_opts = {}
705                 if opt_fragment
706                         @parser_opts.fragment = 'body'
707
708                 @outer_iframe = domify document, iframe: {}
709                 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
710                 if @options.editor_id?
711                         @outer_iframe.setAttribute 'id', @options.editor_id
712                 @outer_iframe.onload = =>
713                         @outer_idoc = @outer_iframe.contentDocument
714                         icss = domify @outer_idoc, style: children: [
715                                 domify @outer_idoc, text: css
716                         ]
717                         @outer_idoc.head.appendChild icss
718                         @iframe = domify @outer_idoc, iframe: sandbox: 'allow-same-origin allow-scripts'
719                         @iframe.onload = =>
720                                 @init_1()
721                         timeout 200, => # firefox never fires this onload
722                                 @init_1() unless @init_1_called
723                         @outer_idoc.body.appendChild(
724                                 domify @outer_idoc, div: id: 'wrap1', children: [
725                                         domify @outer_idoc, div: style: "position: absolute; top: 0; left: 1px; font-size: 10px", children: [ domify @outer_idoc, text: "Peach HTML5 Editor" ]
726                                         @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
727                                                 domify @outer_idoc, div: id: 'wrap3', children: [
728                                                         @iframe
729                                                         @overlay = domify @outer_idoc, div: id: 'overlay'
730                                                 ]
731                                         ]
732                                 ]
733                         )
734                 outer_wrap = domify document, div: class: 'peach_html5_editor'
735                 @in_el.parentNode.appendChild outer_wrap
736                 outer_bounds = get_el_bounds outer_wrap
737                 if outer_bounds.w < 300
738                         outer_bounds.w = 300
739                 if outer_bounds.h < 300
740                         outer_bounds.h = 300
741                 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
742                 @outer_iframe.setAttribute 'style', outer_iframe_style
743                 css = @generate_outer_css w: outer_bounds.w, h: outer_bounds.h
744                 outer_wrap.appendChild @outer_iframe
745         init_1: -> # @iframe has loaded (but not it's css)
746                 @idoc = @iframe.contentDocument
747                 @init_1_called = true
748                 # chromium doesn't resolve relative urls as though they were at the same domain
749                 # so add a <base> tag
750                 @idoc.head.appendChild domify @idoc, base: href: this_url_sans_path()
751                 # don't let @iframe have scrollbars
752                 @idoc.head.appendChild domify @idoc, style: children: [domify @idoc, text: "body { overflow: hidden; }"]
753                 # load css file
754                 if @options.css_file
755                         istyle = domify @idoc, link: rel: 'stylesheet', href: @options.css_file
756                         istyle.onload = =>
757                                 @init_2()
758                         @idoc.head.appendChild istyle
759                 else
760                         @init_2()
761         init_2: -> # @iframe and it's css file(s) are ready
762                 @overlay.onclick = (e) =>
763                         @have_focus()
764                         return event_return e, @onclick e
765                 @overlay.ondoubleclick = (e) =>
766                         @have_focus()
767                         return event_return e, @ondoubleclick e
768                 @outer_idoc.body.onkeyup = (e) =>
769                         @have_focus()
770                         return event_return e, @onkeyup e
771                 @outer_idoc.body.onkeydown = (e) =>
772                         @have_focus()
773                         return event_return e, @onkeydown e
774                 @outer_idoc.body.onkeypress = (e) =>
775                         @have_focus()
776                         return event_return e, @onkeypress e
777                 @load_html @in_el.value
778                 if @options.on_init?
779                         @options.on_init()
780         generate_outer_css: (args) ->
781                 w = args.w ? 300
782                 h = args.h ? 300
783                 inner_padding = args.inner_padding ? overlay_padding
784                 frame_width = args.frame_width ? inner_padding
785                 occupy = (left, top = left, right = left, bottom = top) ->
786                         w -= left + right
787                         h -= top + bottom
788                         return Math.max(left, top, right, bottom)
789                 ret = ''
790                 ret += 'body {'
791                 ret +=     'margin: 0;'
792                 ret +=     'padding: 0;'
793                 ret +=     'color: black;'
794                 ret +=     'background: white;'
795                 ret += '}'
796                 ret += '#wrap1 {'
797                 ret +=     "border: #{occupy 1}px solid black;"
798                 ret +=     "padding: #{occupy frame_width}px;"
799                 ret += '}'
800                 ret += '#wrap2 {'
801                 ret +=     "border: #{occupy 1}px solid black;"
802                 @wrap2_height = h # including padding because padding scrolls
803                 ret +=     "padding: #{occupy inner_padding}px;"
804                 ret +=     "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
805                 ret +=     "width: #{w}px;"
806                 ret +=     "height: #{h}px;"
807                 ret +=     'overflow-x: hidden;'
808                 ret +=     'overflow-y: scroll;'
809                 ret += '}'
810                 ret += '#wrap3 {'
811                 ret +=     'position: relative;'
812                 ret +=     "width: #{w}px;"
813                 ret +=     "min-height: #{h}px;"
814                 ret += '}'
815                 ret += 'iframe {'
816                 ret +=     'box-sizing: border-box;'
817                 ret +=     'margin: 0;'
818                 ret +=     'border: none;'
819                 ret +=     'padding: 0;'
820                 ret +=     "width: #{w}px;"
821                 #ret +=     "height: #{h}px;" # height auto-set when content set/changed
822                 ret +=     '-ms-user-select: none;'
823                 ret +=     '-webkit-user-select: none;'
824                 ret +=     '-moz-user-select: none;'
825                 ret +=     'user-select: none;'
826                 ret += '}'
827                 ret += '#overlay {'
828                 ret +=     'position: absolute;'
829                 ret +=     "left: -#{inner_padding}px;"
830                 ret +=     "top: -#{inner_padding}px;"
831                 ret +=     "right: -#{inner_padding}px;"
832                 ret +=     "bottom: -#{inner_padding}px;"
833                 ret +=     'overflow: hidden;'
834                 ret += '}'
835                 ret += '.lightbox {'
836                 ret +=     'position: absolute;'
837                 ret +=     'background: rgba(100,100,100,0.2);'
838                 ret += '}'
839                 ret += '#cursor {'
840                 ret +=     'position: absolute;'
841                 ret +=     'width: 2px;'
842                 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));'
843                 ret +=     'background-size: 200% 200%;'
844                 ret +=     '-webkit-animation: blink 1s linear normal infinite;'
845                 ret +=     'animation: blink 1s linear normal infinite;'
846                 ret += '}'
847                 ret += '@-webkit-keyframes blink {'
848                 ret +=     '0%{background-position:0% 0%}'
849                 ret +=     '100%{background-position:0% -100%}'
850                 ret += '}'
851                 ret += '@keyframes blink { '
852                 ret +=     '0%{background-position:0% 0%}'
853                 ret +=     '100%{background-position:0% -100%}'
854                 ret += '}'
855                 ret += '.ann_box {'
856                 ret +=     'z-index: 5;'
857                 ret +=     'position: absolute;'
858                 ret +=     'border: 1px solid rgba(0,0,0,0.1);'
859                 ret +=     'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
860                 ret += '}'
861                 ret += '.ann_tag {'
862                 ret +=     'z-index: 10;'
863                 ret +=     'position: absolute;'
864                 ret +=     'font-size: 8px;'
865                 ret +=     'white-space: pre;'
866                 ret +=     'background: rgba(255,255,255,0.4);'
867                 ret +=     '-ms-user-select: none;'
868                 ret +=     '-webkit-user-select: none;'
869                 ret +=     '-moz-user-select: none;'
870                 ret +=     'user-select: none;'
871                 ret += '}'
872                 return ret
873         overlay_event_to_inner_xy: (e) ->
874                 unless @wrap2_offset?
875                         @wrap2_offset = get_el_bounds @wrap2
876                 x = e.pageX - overlay_padding
877                 y = e.pageY - overlay_padding + @wrap2.scrollTop
878                 return x: x - @wrap2_offset.x, y: y - @wrap2_offset.y
879         onclick: (e) ->
880                 xy = @overlay_event_to_inner_xy e
881                 new_cursor = xy_to_cursor @tree, xy
882                 if new_cursor?
883                         @move_cursor new_cursor
884                 else
885                         @kill_cursor()
886                 return false
887         ondoubleclick: (e) ->
888                 return false
889         onkeyup: (e) ->
890                 return if e.ctrlKey
891                 return false if ignore_key_codes[e.keyCode]?
892                 #return false if control_key_codes[e.keyCode]?
893         onkeydown: (e) ->
894                 return if e.ctrlKey
895                 return false if ignore_key_codes[e.keyCode]?
896                 #return false if control_key_codes[e.keyCode]?
897                 switch e.keyCode
898                         when KEY_LEFT
899                                 if @cursor?
900                                         new_cursor = find_prev_cursor_position @tree, @cursor
901                                 else
902                                         new_cursor = first_cursor_position @tree
903                                 if new_cursor?
904                                         @move_cursor new_cursor
905                                 return false
906                         when KEY_RIGHT
907                                 if @cursor?
908                                         new_cursor = find_next_cursor_position @tree, @cursor
909                                 else
910                                         new_cursor = last_cursor_position @tree
911                                 if new_cursor?
912                                         @move_cursor new_cursor
913                                 return false
914                         when KEY_UP
915                                 if @cursor?
916                                         new_cursor = find_up_cursor_position @tree, @cursor, @cursor_ideal_x
917                                         if new_cursor?
918                                                 saved_ideal_x = @cursor_ideal_x
919                                                 @move_cursor new_cursor
920                                                 @cursor_ideal_x = saved_ideal_x
921                                 else
922                                         # move cursor to first position in document
923                                         new_cursor = first_cursor_position @tree
924                                         if new_cursor?
925                                                 @move_cursor new_cursor
926                                 return false
927                         when KEY_DOWN
928                                 if @cursor?
929                                         new_cursor = find_down_cursor_position @tree, @cursor, @cursor_ideal_x
930                                         if new_cursor?
931                                                 saved_ideal_x = @cursor_ideal_x
932                                                 @move_cursor new_cursor
933                                                 @cursor_ideal_x = saved_ideal_x
934                                 else
935                                         # move cursor to first position in document
936                                         new_cursor = last_cursor_position @tree
937                                         if new_cursor?
938                                                 @move_cursor new_cursor
939                                 return false
940                         when KEY_END
941                                 new_cursor = last_cursor_position @tree
942                                 if new_cursor?
943                                         @move_cursor new_cursor
944                                 return false
945                         when KEY_BACKSPACE
946                                 @on_key_backspace e
947                                 return false
948                         when KEY_DELETE
949                                 return false unless @cursor?
950                                 new_cursor = find_next_cursor_position @tree, n: @cursor.n, i: @cursor.i
951                                 # try moving cursor right and then running backspace code
952                                 # TODO replace this hack with a real implementation
953                                 if new_cursor?
954                                         # try to detect common case where cursor goes inside an block,
955                                         # but doesn't pass a character (and advance one more in that case)
956                                         if new_cursor.n isnt @cursor.n and new_cursor.i is 0
957                                                 if new_cursor.n.type is 'text' and new_cursor.n.text.length > 0
958                                                         if new_cursor.n.parent?
959                                                                 unless @is_display_block new_cursor.n.parent
960                                                                         # FIXME should test run sibling
961                                                                         new_cursor = new_cursor_position n: new_cursor.n, i: new_cursor.i + 1
962                                 if new_cursor?
963                                         if new_cursor.n isnt @cursor.n or new_cursor.i isnt @cursor.i
964                                                 @move_cursor new_cursor
965                                                 @on_key_backspace e
966                                 return false
967                         when KEY_ENTER
968                                 @on_key_enter e
969                                 return false
970                         when KEY_ESCAPE
971                                 @kill_cursor()
972                                 return false
973                         when KEY_HOME
974                                 new_cursor = first_cursor_position @tree
975                                 if new_cursor?
976                                         @move_cursor new_cursor
977                                 return false
978                         when KEY_INSERT
979                                 return false
980                         when KEY_PAGE_UP
981                                 @on_page_up_key e
982                                 return false
983                         when KEY_PAGE_DOWN
984                                 @on_page_down_key e
985                                 return false
986                         when KEY_TAB
987                                 return false
988         onkeypress: (e) ->
989                 return if e.ctrlKey
990                 return false if ignore_key_codes[e.keyCode]?
991                 char = e.charCode ? e.keyCode
992                 if char and @cursor?
993                         char = String.fromCharCode char
994                         @insert_character @cursor.n, @cursor.i, char
995                         @text_cleanup @cursor.n
996                         @changed()
997                         new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i + 1
998                         if new_cursor
999                                 @move_cursor new_cursor
1000                         else
1001                                 console.log "ERROR: couldn't find cursor position after insert"
1002                                 @kill_cursor()
1003                 return false
1004         on_key_enter: (e) -> # enter key pressed
1005                 return unless @cursor_visible
1006                 cur_block = @cursor.n
1007                 loop
1008                         if cur_block.type is 'tag'
1009                                 if is_display_block cur_block.el
1010                                         break
1011                         return unless cur_block.parent?
1012                         cur_block = cur_block.parent
1013                 # find array to insert new element into
1014                 if cur_block.parent is @tree_parent # top-level
1015                         parent_el = @idoc.body
1016                         pc = @tree
1017                 else
1018                         parent_el = cur_block.parent.el
1019                         pc = cur_block.parent.children
1020                 # find index of current block in its parent
1021                 for n, i in pc
1022                         break if n is cur_block
1023                 i += 1 # we want to be after it
1024                 if i < pc.length
1025                         before = pc[i].el
1026                 else
1027                         before = null
1028                 # TODO if content after cursor
1029                 #       TODO new block is empty
1030                 new_text = new peach_parser.Node 'text', text: ' '
1031                 new_node = new peach_parser.Node 'tag', name: 'p', parent: cur_block.parent, attrs: {style: 'white-space: pre-wrap'}, children: [new_text]
1032                 new_text.parent = new_node
1033                 new_text.el = domify @idoc, text: ' '
1034                 new_node.el = domify @idoc, p: style: 'white-space: pre-wrap', children: [new_text.el]
1035                 pc.splice i, 0, new_node
1036                 parent_el.insertBefore new_node.el, before
1037                 @changed()
1038                 new_cursor = new_cursor_position n: new_text, i: 0
1039                 throw 'bork bork' unless new_cursor?
1040                 @move_cursor new_cursor
1041                 # TODO move content past cursor into this new block
1042         # unlike the global function, this takes a Node, not an element
1043         is_display_block: (n) ->
1044                 # TODO stop calling global function, merge it into here, use iframe's window object
1045                 return false unless n.type is 'tag'
1046                 return is_display_block n.el
1047         find_block_parent: (n) ->
1048                 loop
1049                         n = n.parent
1050                         return null unless n?
1051                         return n if @is_display_block n
1052                         return n if n is @tree_parent
1053                 return null
1054         # return a flat array of nodes (text, <br>, and later also inline-block)
1055         # that are flowing/wrapping together. n can be the containing block, or any
1056         # element inside it.
1057         get_text_run: (n) ->
1058                 ret = []
1059                 if @is_display_block n
1060                         block = n
1061                 else
1062                         block = @find_block_parent n
1063                         return ret unless block?
1064                 traverse_tree block.children, (n) =>
1065                         if n.type is 'text'
1066                                 ret.push n
1067                         else if n.type is 'tag'
1068                                 if n.name is 'br'
1069                                         ret.push n
1070                                 else
1071                                         disp = @computed_style n
1072                                         if disp is 'inline-block'
1073                                                 ret.push n
1074                         return false # not done traversing
1075                 return ret
1076         node_is_decendant: (young, old) ->
1077                 while young? and young != @tree_parent
1078                         return true if young is old
1079                         young = young.parent
1080                 return false
1081         # helper for on_key_backspace
1082         _merge_left: (state) ->
1083                 # the node prev to n was not prev to it a moment ago, merge with it if reasonable
1084                 pi = state.n.parent.children.indexOf(state.n)
1085                 if pi > 0
1086                         prev = state.n.parent.children[pi - 1]
1087                         if prev.type is 'text'
1088                                 state.i = prev.text.length
1089                                 prev.text = prev.el.textContent = prev.text + state.n.text
1090                                 @remove_node state.n
1091                                 state.n = prev
1092                                 state.changed = true
1093                                 state.moved_cursor = true
1094                 # else # TODO merge possible consecutive matching inline tags at @cursor
1095                 return state
1096         # helper for on_key_backspace
1097         # remove n from the dom, also remove its inline parents that are emptied by removing n
1098         _backspace_node_helper: (n, run = @get_text_run(n), run_i = run.indexOf(n)) ->
1099                 block = @find_block_parent n
1100                 # delete text node
1101                 @remove_node n
1102                 # delete any inline parents
1103                 n = n.parent
1104                 while n? and n isnt block
1105                         # bail if the previous node in this run is also inside the same parent
1106                         if run_i > 0
1107                                 break if @node_is_decendant run[run_i - 1], n
1108                         # bail if the next node in this run is also inside the same parent
1109                         if run_i + 1 < run.length
1110                                 break if @node_is_decendant run[run_i + 1], n
1111                         # move any sibling nodes to parent. These nodes are not in the text run
1112                         while n.children.length > 0
1113                                 @move_node n.children[0], n.parent, n
1114                         # remove (now completely empty) inline parent
1115                         @remove_node n
1116                         # proceed to outer parent
1117                         n = n.parent
1118                 return
1119         on_key_backspace: (e) ->
1120                 return unless @cursor?
1121                 new_cursor = null
1122                 run = null
1123                 changed = true
1124                 if @cursor.i is 0 # cursor is at start of text node
1125                         run ?= @get_text_run @cursor.n
1126                         run_i = run.indexOf(@cursor.n)
1127                         if run_i is 0 # if at start of text run
1128                                 block = @find_block_parent @cursor.n
1129                                 prev_cursor = find_prev_cursor_position @tree, n: @cursor.n, i: 0
1130                                 if prev_cursor is null # if in first text run of document
1131                                         # do nothing (there's nothing text-like to the left of the cursor)
1132                                         return
1133                                 # else merge with prev/outer text run
1134                                 pcb = @find_block_parent prev_cursor.n
1135                                 while block.children.length > 0
1136                                         @move_node block.children[0], pcb
1137                                 @remove_node block
1138                                 # merge possible consecutive text nodes at @cursor
1139                                 merge_state = n: @cursor.n
1140                                 @_merge_left merge_state
1141                                 @text_cleanup merge_state.n
1142                                 new_cursor = new_cursor_position n: merge_state.n, i: merge_state.i
1143                         else # at start of text node, but not start of text run
1144                                 prev = run[run_i - 1]
1145                                 if prev.type is 'text' # if previous in text run is text
1146                                         if prev.text.length is 1 # if emptying prev (in text run)
1147                                                 @_backspace_node_helper prev, run, run_i
1148                                                 merge_state = n: @cursor.n, i: @cursor.i
1149                                                 @_merge_left merge_state
1150                                                 @text_cleanup merge_state.n
1151                                                 new_cursor = new_cursor_position n: merge_state.n, i: merge_state.i
1152                                         else # prev in run is text with muliple chars
1153                                                 # delete last character in prev
1154                                                 prev.text = prev.text.substr(0, prev.text.length - 1)
1155                                                 prev.el.textContent = prev.text
1156                                                 @text_cleanup @cursor.n
1157                                                 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i
1158                                 else if prev.name is 'br' or prev.name is 'hr'
1159                                         @_backspace_node_helper prev, run, run_i
1160                                         merge_state = n: @cursor.n, i: @cursor.i
1161                                         @_merge_left merge_state
1162                                         @text_cleanup merge_state.n
1163                                         new_cursor = new_cursor_position n: merge_state.n, i: merge_state.i
1164                                 # FIXME implement this:
1165                                 # else # if prev (in run) is inline-block
1166                                         # if that inline-block has text in it
1167                                                 # delete last char in prev inlineblock
1168                                                 # if that empties it
1169                                                         # delete it
1170                                                         # merge left
1171                                                 # else
1172                                                         # move cursor inside
1173                                         # else
1174                                                 # delete prev (inline) block
1175                                                 # merge left
1176                                         # auto-delete this @cursor.parent(s) if this empties them
1177                 else # cursor is not at start of text node
1178                         run ?= @get_text_run @cursor.n
1179                         if @cursor.n.text.length is 1 # if emptying text node
1180                                 if run.length is 1 # if emptying text run (of text/br/hr/inline-block)
1181                                         # remove inline-parents of @cursor.n
1182                                         block = @find_block_parent @cursor.n
1183                                         changed = false
1184                                         n = @cursor.n.parent
1185                                         # note: this doesn't use _backspace_node_helper because:
1186                                         # 1. we don't want to delete the target node (we're replacing it's contents)
1187                                         # 2. we want to track whether anything was removed
1188                                         # 3. we know already know there's no other text from this run anywhere
1189                                         while n and n isnt block
1190                                                 changed = true
1191                                                 while n.children.length > 0
1192                                                         @move_node n.children[0], n.parent, n
1193                                                 @remove_node n
1194                                                 n = n.parent
1195                                         # replace @cursor.n with a single (preserved) space
1196                                         if @cursor.n.text != ' '
1197                                                 changed = true
1198                                                 @cursor.n.text = @cursor.n.el.textContent = ' '
1199                                         if changed
1200                                                 @text_cleanup @cursor.n
1201                                         # place the cursor to the left of that space
1202                                         new_cursor = new_cursor_position n: @cursor.n, i: 0
1203                                 else # emptying a text node (but not a whole text run)
1204                                         # figure out where cursor should land
1205                                         block = @find_block_parent @cursor.n
1206                                         new_cursor = find_prev_cursor_position @tree, n: @cursor.n, i: 0
1207                                         ncb = @find_block_parent new_cursor.n
1208                                         if ncb isnt block
1209                                                 new_cursor = find_next_cursor_position @tree, n: @cursor.n, i: 1
1210                                         # delete text node and cleanup emptied parents
1211                                         run_i = run.indexOf @cursor.n
1212                                         @_backspace_node_helper @cursor.n, run, run_i
1213                                         # see if new adjacent siblings should merge
1214                                         # TODO make smarter
1215                                         if run_i > 0 and run_i + 1 < run.length
1216                                                 if run[run_i - 1].type is 'text' and run[run_i + 1].type is 'text'
1217                                                         merge_state = n: run[run_i + 1]
1218                                                         @_merge_left merge_state
1219                                                         if merge_state.moved_cursor
1220                                                                 new_cursor = merge_state
1221                                         # update whitespace preservation
1222                                         @text_cleanup(block)
1223                                         # update cursor x/y in case things moved around
1224                                         if new_cursor?
1225                                                 if new_cursor.n.el.parentNode # still in dom after cleanup
1226                                                         new_cursor = new_cursor_position n: new_cursor.n, i: new_cursor.i
1227                                                 else
1228                                                         new_cursor = null
1229                         else # there's a char left of cursor that we can delete without emptying anything
1230                                 # delete character
1231                                 need_text_cleanup = true
1232                                 if @cursor.i > 1 and @cursor.i < @cursor.n.text.length
1233                                         pre = @cursor.n.text.substr(@cursor.i - 2, 3)
1234                                         post = pre.charAt(0) + pre.charAt(2)
1235                                         if str_has_ws_run(pre) is str_has_ws_run(post)
1236                                                 need_text_cleanup = false
1237                                 @remove_character(@cursor.n, @cursor.i - 1)
1238                                 # call text_cleanup if whe created/removed a whitespace run
1239                                 if need_text_cleanup
1240                                         @text_cleanup @cursor.n
1241                                 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i - 1
1242                 # mark document changed and move the cursor
1243                 if changed?
1244                         @changed()
1245                 if new_cursor?
1246                         @move_cursor new_cursor
1247                 else
1248                         @kill_cursor()
1249                 return
1250         on_page_up_key: (e) ->
1251                 if @wrap2.scrollTop is 0
1252                         return unless @cursor?
1253                         new_cursor = first_cursor_position @tree
1254                         if new_cursor?
1255                                 if new_cursor.n isnt @cursor.n or new_cursor.i isnt @cursor.i
1256                                         @move_cursor new_cursor
1257                         return
1258                 if @cursor?
1259                         screen_y = @cursor.y - @wrap2.scrollTop
1260                 scroll_amount = @wrap2_height - breathing_room
1261                 @wrap2.scrollTop = Math.max 0, @wrap2.scrollTop - scroll_amount
1262                 if @cursor?
1263                         @move_cursor_into_view screen_y + @wrap2.scrollTop
1264         on_page_down_key: (e) ->
1265                 lowest_scrollpos = @wrap2.scrollHeight - @wrap2_height
1266                 if @wrap2.scrollTop is lowest_scrollpos
1267                         return unless @cursor?
1268                         new_cursor = last_cursor_position @tree
1269                         if new_cursor?
1270                                 if new_cursor.n isnt @cursor.n or new_cursor.i isnt @cursor.i
1271                                         @move_cursor new_cursor
1272                         return
1273                 if @cursor?
1274                         screen_y = @cursor.y - @wrap2.scrollTop
1275                 scroll_amount = @wrap2_height - breathing_room
1276                 @wrap2.scrollTop = Math.min lowest_scrollpos, @wrap2.scrollTop + scroll_amount
1277                 if @cursor?
1278                         @move_cursor_into_view screen_y + @wrap2.scrollTop
1279                 return
1280         move_cursor_into_view: (y_target) ->
1281                 return if y_target is @cursor.y
1282                 was = @cursor
1283                 y_min = @wrap2.scrollTop
1284                 unless @wrap2.scrollTop is 0
1285                         y_min += breathing_room
1286                 y_max = @wrap2.scrollTop + @wrap2_height
1287                 unless @wrap2.scrollTop is @wrap2.scrollHeight - @wrap2_height # downmost
1288                         y_max -= breathing_room
1289                 y_target = Math.min y_target, y_max
1290                 y_target = Math.max y_target, y_min
1291                 if y_target < @cursor.y
1292                         finder = find_up_cursor_position
1293                         far_enough = (cur, target_y) ->
1294                                 return cur.y + cur.h <= target_y
1295                 else
1296                         finder = find_down_cursor_position
1297                         far_enough = (cur, y_target) ->
1298                                 return cur.y >= y_target
1299                 loop
1300                         cur = finder @tree, was, @cursor_ideal_x
1301                         break unless cur?
1302                         break if far_enough cur, y_target
1303                         was = cur
1304                 if was is @cursor
1305                         was = null
1306                 if was?
1307                         if was.y + was.h > y_max
1308                                 was = null
1309                         else if was.y < y_min
1310                                 was = null
1311                 if cur?
1312                         if cur.y + cur.h > y_max
1313                                 cur = null
1314                         else if cur.y < y_min
1315                                 cur = null
1316                 if cur? and was?
1317                         # both valid, pick best
1318                         if cur.y < y_min
1319                                 new_cursor = was
1320                         else if was.y + was.h > y_max
1321                                 new_cursor = cur
1322                         else if cur.y - y_target < y_target - was.y
1323                                 new_cursor = cur
1324                         else
1325                                 new_cursor = was
1326                 else
1327                         new_cursor = was ? cur
1328                 if new_cursor?
1329                         saved_ideal_x = @cursor_ideal_x
1330                         @move_cursor new_cursor
1331                         @cursor_ideal_x = saved_ideal_x
1332                 return
1333         clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
1334                 while @idoc.body.childNodes.length
1335                         @idoc.body.removeChild @idoc.body.childNodes[0]
1336                 @kill_cursor()
1337                 return
1338         load_html: (html) ->
1339                 @tree = peach_parser.parse html, @parser_opts
1340                 if !@tree[0]?.parent
1341                         @tree = peach_parser.parse '<p style="white-space: pre-wrap"> </p>', @parser_opts
1342                 @tree_parent = @tree[0]?.parent
1343                 @tree_parent.el = @idoc.body
1344                 @clear_dom()
1345                 instantiate_tree @tree, @tree_parent.el
1346                 @collapse_whitespace @tree
1347                 @changed()
1348         changed: ->
1349                 @in_el.onchange = null
1350                 @in_el.value = @pretty_html @tree
1351                 @in_el.onchange = =>
1352                         @load_html @in_el.value
1353                 @adjust_iframe_height()
1354         adjust_iframe_height: ->
1355                 s = @wrap2.scrollTop
1356                 # when the content gets shorter, the idoc's body tag will continue to
1357                 # report the old (too big) height in Chrome. The workaround is to
1358                 # shrink the iframe before the content height:
1359                 @iframe.style.height = "10px"
1360                 h = parseInt(@idoc.body.scrollHeight, 10)
1361                 @iframe.style.height = "#{h}px"
1362                 @wrap2.scrollTop = s
1363         # does this node have whitespace that would be collapsed by white-space: normal?
1364         # note: this checks direct text children, and does _not_ recurse into child tags
1365         # tag is a node with type:"tag"
1366         # FIXME use new textrun api
1367         has_collapsable_space: (tag) ->
1368                 for n in tag.children
1369                         if n.type is 'text'
1370                                 for i in [0...n.text.length]
1371                                         code = n.text.charCodeAt i
1372                                         if code isnt 32 and is_space_code code
1373                                                 # tab, return
1374                                                 return true
1375                                         # check for double spaces that don't surround insert location
1376                                         continue if i is 0
1377                                         if n.text.substr(i - 1, 2) is '  '
1378                                                 return true
1379                                 if n.text.length > 0
1380                                         if is_space_code n.text.charCodeAt 0
1381                                                 return true
1382                                         if is_space_code n.text.charCodeAt n.text.length - 1
1383                                                 return true
1384                 return false
1385         # true if n is text node with only one caracter, and the only child of a tag
1386         is_only_char_in_tag: (n, i) ->
1387                 return false unless n.type is 'text'
1388                 return false unless n.text.length is 1
1389                 return false if n.parent is @tree_parent
1390                 return false unless n.parent.children.length is 1
1391                 return true
1392         # true if n is text node with just a space in it, and the only child of a tag
1393         is_lone_space: (n, i) ->
1394                 return false unless n.type is 'text'
1395                 return false unless n.text is ' '
1396                 return false if n.parent is @tree_parent
1397                 return false unless n.parent.children.length is 1
1398                 return true
1399         # detect special case: typing before a space that's the only thing in a block/doc
1400         # reason: enter key creates blocks with just a space in them
1401         insert_should_replace: (n, i) ->
1402                 return false unless i is 0
1403                 return false unless n.text is ' '
1404                 return true if n.parent is @tree_parent
1405                 if n.parent.children.length is 1
1406                         if n.parent.children[0] is n
1407                                 # n is only child
1408                                 return true
1409                 return false
1410         # after calling this, you MUST call changed() and text_cleanup()
1411         insert_character: (n, i, char) ->
1412                 return if n.parent is @tree_parent # FIXME implement text nodes at top level
1413                 # insert the character
1414                 if @insert_should_replace n, i
1415                         n.text = char
1416                 else if i is 0
1417                         n.text = char + n.text
1418                 else if i is n.text.length
1419                         # replace the space
1420                         n.text += char
1421                 else
1422                         n.text =
1423                                 n.text.substr(0, i) +
1424                                 char +
1425                                 n.text.substr(i)
1426                 n.el.nodeValue = n.text
1427         # WARNING: after calling this, you MUST call changed() and text_cleanup()
1428         remove_character: (n, i) ->
1429                 n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1430                 n.el.nodeValue = n.text
1431         computed_style: (n, prop) ->
1432                 if n.type is 'text'
1433                         n = n.parent
1434                 style = @iframe.contentWindow.getComputedStyle n.el, null
1435                 return style.getPropertyValue prop
1436         # returns the new white-space value that will preserve spaces for node n
1437         preserve_space: (n, ideal_target) ->
1438                 if n.type is 'text'
1439                         target = n.parent
1440                 else
1441                         target = n
1442                 while target isnt ideal_target and not target.el.style.whiteSpace
1443                         unless target?
1444                                 console.log "bug #967123"
1445                                 return
1446                         target = target.parent
1447                 ws = ws_props[target.el.style.whiteSpace]?.to_preserve
1448                 ws ?= 'pre-wrap'
1449                 target.el.style.whiteSpace = ws
1450                 @update_style_from_el target
1451                 return ws
1452         update_style_from_el: (n) ->
1453                 style = n.el.getAttribute 'style'
1454                 if style?
1455                         n.attrs.style = style
1456                 else
1457                         if n.attrs.style?
1458                                 delete n.attrs.style
1459         # remove whitespace that would be trimmed
1460         # replace whitespace that would collapse with a single space
1461         collapse_whitespace: (tree = @tree) ->
1462                 return collapse_whitespace tree # FIXME CONTINUE
1463                 return
1464         # call this after you insert or remove inline nodes. It will:
1465         #    merge consecutive text nodes
1466         #    remove empty text nodes
1467         #    adjust white-space property
1468         # note: this assumes that all whitespace in text nodes should be displayed
1469         # (ie not collapse or be trimmed) and will change the white-space property
1470         # as needed to achieve this.
1471         text_cleanup: (n) ->
1472                 if @is_display_block n
1473                         block = n
1474                 else
1475                         block = @find_block_parent n
1476                         return unless block?
1477                 run = @get_text_run block
1478                 return unless run?
1479                 # merge consecutive text nodes
1480                 if run.length > 1
1481                         i = 1
1482                         prev = run[0]
1483                         while i < run.length
1484                                 n = run[i]
1485                                 if prev.type is 'text' and n.type is 'text'
1486                                         if prev.parent is n.parent
1487                                                 prev_i = n.parent.children.indexOf prev
1488                                                 n_i =    n.parent.children.indexOf n
1489                                                 if n_i is prev_i + 1
1490                                                         prev.text = prev.text + n.text
1491                                                         prev.el.textContent = prev.text
1492                                                         @remove_node n
1493                                                         run.splice i, 1
1494                                                         continue # don't increment i or change prev
1495                                 i += 1
1496                                 prev = n
1497                 # remove empty text nodes
1498                 i = 0
1499                 while i < run.length
1500                         n = run[i]
1501                         if n.type is 'text'
1502                                 if n.text is ''
1503                                         @remove_node n
1504                                         # FIXME maybe remove parents recursively if this makes them empty
1505                                         run.splice i, 1
1506                                         continue # don't increment i
1507                         i += 1
1508                 # note: inline tags can have white-space:pre-line/etc
1509                 # note: inline-blocks have their whitespace collapsed independantly of outer run
1510                 # note: inline-blocks are treated like non-whitespace char even if empty
1511                 if block.el.style.whiteSpace?
1512                         ws = block.el.style.whiteSpace
1513                         if ws_props[ws]
1514                                 if ws_props[ws].space
1515                                         if ws_props[ws].to_collapse is 'normal'
1516                                                 block.el.style.whiteSpace = null
1517                                         else
1518                                                 block.el.style.whiteSpace = ws_props[ws].to_collapse
1519                                         @update_style_from_el block
1520                 # note: space after <br> colapses, but not space before
1521                 # check for spaces that would collapse without help
1522                 eats_start_sp = true # if the next node starts with space it collapses (unless pre)
1523                 prev = null
1524                 for n in run
1525                         if n.type is 'tag'
1526                                 if n.name is 'br'
1527                                         eats_start_sp = true
1528                                 else
1529                                         eats_start_sp = false
1530                         else # TEXT
1531                                 need_preserve = false
1532                                 if n.type isnt 'text'
1533                                         console.log "bug #232308"
1534                                         return
1535                                 if eats_start_sp
1536                                         if is_space_code n.text.charCodeAt 0
1537                                                 need_preserve = true
1538                                 unless need_preserve
1539                                         need_preserve = multi_sp_regex.test n.text
1540                                 if need_preserve
1541                                         # do we have it already?
1542                                         ws = @computed_style n, 'white-space' # FIXME implement this
1543                                         unless ws_props[ws]?.space
1544                                                 # 2nd arg is ideal target for css rule
1545                                                 ws = @preserve_space n, block
1546                                         eats_start_sp = false
1547                                 else
1548                                         if is_space_code n.text.charCodeAt(n.text.length - 1)
1549                                                 ws = @computed_style n, 'white-space' # FIXME implement this
1550                                                 if ws_props[ws]?.space
1551                                                         eats_start_sp = false
1552                                                 else
1553                                                         eats_start_sp = true
1554                                         else
1555                                                 eats_start_sp = false
1556                 # check if text ends with a collapsable space
1557                 if run.length > 0
1558                         last = run[run.length - 1]
1559                         if last.type is 'text'
1560                                 if eats_start_sp
1561                                         @preserve_space last, block
1562                 return
1563         css_clear: (n, prop) ->
1564                 return unless n.attrs.style?
1565                 return if n.attrs.style is ''
1566                 css_delimiter_regex = new RegExp('\s*;\s*', 'g') # FIXME make this global
1567                 styles = n.attrs.style.trim().split css_delimiter
1568                 return unless styles.length > 0
1569                 if styles[styles.length - 1] is ''
1570                         styles.pop()
1571                         return unless styles.length > 0
1572                 i = 0
1573                 while i < styles.length
1574                         if styles[i].substr(0, 12) is 'white-space:'
1575                                 styles.splice i, 1
1576                         else
1577                                 i += 1
1578                 return
1579         # WARNING: after calling this one or more times, you MUST:
1580         #    if it's inline: call @text_cleanup
1581         #    call @changed()
1582         remove_node: (n) ->
1583                 i = n.parent.children.indexOf n
1584                 if i is -1
1585                         throw "BUG #9187112313"
1586                 n.el.parentNode.removeChild n.el
1587                 n.parent.children.splice i, 1
1588                 return
1589         # remove a node from the tree/dom, insert into new_parent before insert_before?end
1590         # WARNING: after calling this one or more times, you MUST:
1591         #    if it's inline: call @text_cleanup
1592         #    call @changed()
1593         move_node: (n, new_parent, insert_before = null) ->
1594                 i = n.parent.children.indexOf n
1595                 if i is -1
1596                         throw "Error: tried to remove node, but it's not in it's parents list of children"
1597                         return
1598                 if insert_before?
1599                         before_i = new_parent.children.indexOf insert_before
1600                         if i is -1
1601                                 throw "Error: tried to move a node to be before a non-existent node"
1602                         insert_before = insert_before.el
1603                 @remove_node n
1604                 if insert_before?
1605                         new_parent.el.insertBefore n.el, insert_before
1606                         new_parent.children.splice before_i, 0, n
1607                 else
1608                         new_parent.el.appendChild n.el, insert_before
1609                         new_parent.children.push n
1610                 n.parent = new_parent
1611                 return
1612         kill_cursor: -> # remove it, forget where it was
1613                 if @cursor_visible
1614                         @cursor_el.parentNode.removeChild @cursor_el
1615                         @cursor_visible = false
1616                 @cursor = null
1617                 @annotate null
1618                 return
1619         move_cursor: (cursor) ->
1620                 @cursor_ideal_x = cursor.x
1621                 @cursor = cursor
1622                 unless @cursor_visible
1623                         @cursor_el = domify @outer_idoc, div: id: 'cursor'
1624                         @overlay.appendChild @cursor_el
1625                         @cursor_visible = true
1626                 @cursor_el.style.left = "#{cursor.x + overlay_padding - 1}px"
1627                 if cursor.h < 5
1628                         height = 12
1629                 else
1630                         height = cursor.h
1631                 @cursor_el.style.top = "#{cursor.y + overlay_padding + Math.round(height * .07)}px"
1632                 @cursor_el.style.height = "#{Math.round height * 0.82}px"
1633                 @annotate cursor.n
1634                 @scroll_into_view cursor.y, height
1635                 return
1636         scroll_into_view: (y, h = 0) ->
1637                 y += overlay_padding # convert units from @idoc to @wrap2
1638                 # very top of document
1639                 if y <= breathing_room
1640                         @wrap2.scrollTop = 0
1641                         return
1642                 # very bottom of document
1643                 if y + h >= @wrap2.scrollHeight - breathing_room
1644                         @wrap2.scrollTop = @wrap2.scrollHeight - @wrap2_height
1645                         return
1646                 # The most scrolled up (lowest value for scrollTop) that would be OK
1647                 upmost = y + h + breathing_room - @wrap2_height
1648                 upmost = Math.max(upmost, 0)
1649                 # the most scrolled down (highest value for scrollTop) that would be OK
1650                 downmost = y - breathing_room
1651                 downmost = Math.min(downmost, @wrap2.scrollHeight - @wrap2_height)
1652                 if upmost > downmost # means h is too big to fit
1653                         # scroll so top is visible
1654                         @wrap2.scrollTop = downmost
1655                         return
1656                 if @wrap2.scrollTop < upmost
1657                         @wrap2.scrollTop = upmost
1658                         return
1659                 if @wrap2.scrollTop > downmost
1660                         @wrap2.scrollTop = downmost
1661                         return
1662                 return
1663         annotate: (n) ->
1664                 while @matting.length > 0
1665                         @overlay.removeChild @matting[0]
1666                         @matting.shift()
1667                 return unless n?
1668                 prev_bounds = x: 0, y: 0, w: 0, h: 0
1669                 alpha = 0.1
1670                 while n?.el? and n isnt @tree_parent
1671                         if n.type is 'text'
1672                                 n = n.parent
1673                                 continue
1674                         bounds = get_el_bounds n.el
1675                         return unless bounds?
1676                         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
1677                                 n = n.parent
1678                                 continue
1679                         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});
1680                         @overlay.appendChild ann_box
1681                         @matting.push ann_box
1682                         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} "]
1683                         @overlay.appendChild ann_tag
1684                         @matting.push ann_tag
1685                         n = n.parent
1686                         alpha *= 1.5
1687         pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
1688                 ret = ''
1689                 want_nl = parent_flags.want_nl
1690                 prev_in_flow_is_text = false
1691                 prev_in_flow_is_block = false
1692                 for n, i in tree
1693                         # figure out flags
1694                         inner_flags = want_nl: true
1695                         is_br = false
1696                         switch n.type
1697                                 when 'tag'
1698                                         if n.name is 'br'
1699                                                 is_br = true
1700                                         is_text = false
1701                                         if n.el.currentStyle?
1702                                                 cs = n.el.currentStyle
1703                                                 whitespace = cs['white-space']
1704                                                 display = cs['display']
1705                                                 position = cs['position']
1706                                                 float = cs['float']
1707                                                 visibility = cs['visibility']
1708                                         else
1709                                                 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
1710                                                 whitespace = cs.getPropertyValue 'white-space'
1711                                                 display = cs.getPropertyValue 'display'
1712                                                 position = cs.getPropertyValue 'position'
1713                                                 float = cs.getPropertyValue 'float'
1714                                                 visibility = cs.getPropertyValue 'visibility'
1715                                         if n.name is 'textarea'
1716                                                 inner_flags.pre_ish = true
1717                                         else
1718                                                 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
1719                                         switch float
1720                                                 when 'left', 'right'
1721                                                         in_flow = false
1722                                                 else
1723                                                         switch position
1724                                                                 when 'absolute', 'fixed'
1725                                                                         in_flow = false
1726                                                                 else
1727                                                                         if 'display' is 'none'
1728                                                                                 in_flow = false
1729                                                                         else
1730                                                                                 switch visibility
1731                                                                                         when 'hidden', 'collapse'
1732                                                                                                 in_flow = false
1733                                                                                         else # visible
1734                                                                                                 in_flow = true
1735                                         switch display
1736                                                 when 'inline', 'none'
1737                                                         inner_flags.block = false
1738                                                         is_block = in_flow_block = false
1739                                                 when 'inline-black'
1740                                                         inner_flags.block = true
1741                                                         is_block = in_flow_block = false
1742                                                 else # block, table, etc
1743                                                         inner_flags.block = true
1744                                                         is_block = true
1745                                                         in_flow_block = in_flow
1746                                 when 'text'
1747                                         is_text = true
1748                                         is_block = false
1749                                         in_flow = true
1750                                         in_flow_block = false
1751                                 else # 'comment', 'doctype'
1752                                         is_text = false
1753                                         is_block = false
1754                                         in_flow = false
1755                                         in_flow_block = false
1756                         # print whitespace if we can
1757                         unless parent_flags.pre_ish
1758                                 unless prev_in_flow_is_text and is_br
1759                                         if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
1760                                                 if want_nl
1761                                                         ret += "\n"
1762                                                 ret += indent
1763                         switch n.type
1764                                 when 'tag'
1765                                         ret += '<' + n.name
1766                                         attr_keys = []
1767                                         for k of n.attrs
1768                                                 attr_keys.unshift k
1769                                         #attr_keys.sort()
1770                                         for k in attr_keys
1771                                                 ret += " #{k}"
1772                                                 if n.attrs[k].length > 0
1773                                                         ret += "=\"#{enc_attr n.attrs[k]}\""
1774                                         ret += '>'
1775                                         unless void_elements[n.name]?
1776                                                 if inner_flags.block
1777                                                         next_indent = indent + '    '
1778                                                 else
1779                                                         next_indent = indent
1780                                                 if n.children.length
1781                                                         ret += @pretty_html n.children, next_indent, inner_flags
1782                                                 ret += "</#{n.name}>"
1783                                 when 'text'
1784                                         ret += enc_text n.text
1785                                 when 'comment'
1786                                         ret += "<!--#{n.text}-->" # TODO encode?
1787                                 when 'doctype'
1788                                         ret += "<!DOCTYPE #{n.name}"
1789                                         if n.public_identifier? and n.public_identifier.length > 0
1790                                                 ret += " \"#{n.public_identifier}\""
1791                                         if n.system_identifier? and n.system_identifier.length > 0
1792                                                 ret += " \"#{n.system_identifier}\""
1793                                         ret += ">"
1794                         want_nl = true
1795                         if in_flow
1796                                 prev_in_flow_is_text = is_text
1797                                 prev_in_flow_is_block = is_block or (in_flow and is_br)
1798                 if tree.length
1799                         # output final newline if allowed
1800                         unless parent_flags.pre_ish
1801                                 if prev_in_flow_is_block or parent_flags.block
1802                                         ret += "\n#{indent.substr 4}"
1803                 return ret
1804         onblur: ->
1805                 @kill_cursor()
1806         have_focus: ->
1807                 @editor_is_focused = true
1808                 @poll_for_blur()
1809         poll_for_blur: ->
1810                 return if @poll_for_blur_timeout? # already polling
1811                 @poll_for_blur_timeout = timeout 150, =>
1812                         next_frame => # pause polling when browser knows we're not active/visible/etc.
1813                                 @poll_for_blur_timeout = null
1814                                 if document.activeElement is @outer_iframe
1815                                         @poll_for_blur()
1816                                 else
1817                                         @editor_is_focused = false
1818                                         @onblur()
1819
1820 window.peach_html5_editor = (args...) ->
1821         return new PeachHTML5Editor args...
1822
1823 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])