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