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