JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
fix whitespace preservation
[peach-html5-editor.git] / editor.js
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 (function() {
18 var KEY_BACKSPACE, KEY_DELETE, KEY_DOWN, KEY_END, KEY_ENTER, KEY_ESCAPE, KEY_HOME, KEY_INSERT, KEY_LEFT, KEY_PAGE_DOWN, KEY_PAGE_UP, KEY_RIGHT, KEY_TAB, KEY_UP, breathing_room, control_key_codes, enc_attr_regex, enc_text_regex, event_return, find_prev_cursor_position, find_up_cursor_position, get_el_bounds, ignore_key_codes, js_attr_regex, multi_sp_regex, no_text_elements, overlay_padding, text_range_bounds, valid_attr_regex, void_elements, ws_props, xy_to_cursor, slice = [].slice
19
20 // SETTINGS
21 overlay_padding = 10
22 breathing_room = 30 // minimum pixels above/below cursor (scrolling)
23
24 function timeout (ms, cb) {
25         return setTimeout(cb, ms)
26 }
27
28 function next_frame (cb) {
29         if (window.requestAnimationFrame != null) {
30                 window.requestAnimationFrame(cb)
31         } else {
32                 timeout(16, cb)
33         }
34 }
35
36 function this_url_sans_path () {
37         var clip, ret
38         ret = "" + window.location.href
39         clip = ret.lastIndexOf('#')
40         if (clip > -1) {
41                 ret = ret.substr(0, clip)
42         }
43         clip = ret.lastIndexOf('?')
44         if (clip > -1) {
45                 ret = ret.substr(0, clip)
46         }
47         clip = ret.lastIndexOf('/')
48         if (clip > -1) {
49                 ret = ret.substr(0, clip + 1)
50         }
51         return ret
52 }
53
54 // table too look up the properties of various values for css's white-space
55 ws_props = {
56         normal: {
57                 space: false,           // spaces are not preserved/rendered
58                 newline: false,         // newlines are not preserved/rendered
59                 wrap: true,             // text is word-wrapped
60                 to_preserve: 'pre-wrap' // to preservespaces, change white-space to this
61         },
62         nowrap: {
63                 space: false,
64                 newline: false,
65                 wrap: false,
66                 to_preserve: 'pre'
67         },
68         'pre-line': {
69                 space: false,
70                 newline: true,
71                 wrap: true,
72                 to_preserve: 'pre-wrap'
73         },
74         pre: {
75                 space: true,
76                 newline: true,
77                 wrap: false,
78                 to_collapse: 'nowrap'
79         },
80         'pre-wrap': {
81                 space: true,
82                 newline: true,
83                 wrap: true,
84                 to_collapse: 'normal'
85         }
86 }
87
88 // xml 1.0 spec, chromium and firefox accept these, plus lots of unicode chars
89 valid_attr_regex = new RegExp('^[a-zA-Z_:][-a-zA-Z0-9_:.]*$')
90 // html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
91 js_attr_regex = new RegExp('^[oO][nN].')
92 // html5 spec says that only these characters are collapsable
93 multi_sp_regex = new RegExp('[\u0020\u0009\u000a\u000c\u000d][\u0020\u0009\u000a\u000c\u000d]')
94
95 function str_has_ws_run (str) {
96         return multi_sp_regex.test(str)
97 }
98
99 // text nodes don't have getBoundingClientRect(), so use selection api to find
100 // it.
101 get_el_bounds = window.bounds = function(el) {
102         var doc, range, rect, win, x_fix, y_fix
103         if (el.getBoundingClientRect != null) {
104                 rect = el.getBoundingClientRect()
105         } else {
106                 // text nodes don't have getBoundingClientRect(), so use range api
107                 range = el.ownerDocument.createRange()
108                 range.selectNodeContents(el)
109                 rect = range.getBoundingClientRect()
110         }
111         doc = el.ownerDocument.documentElement
112         win = el.ownerDocument.defaultView
113         y_fix = win.pageYOffset - doc.clientTop
114         x_fix = win.pageXOffset - doc.clientLeft
115         return {
116                 x: rect.left + x_fix,
117                 y: rect.top + y_fix,
118                 w: rect.width != null ? rect.width : rect.right - rect.left,
119                 h: rect.height != null ? rect.height : rect.top - rect.bottom
120         }
121 }
122
123 function is_display_block (el) {
124         if (el.currentStyle != null) {
125                 return el.currentStyle.display === 'block'
126         } else {
127                 return window.getComputedStyle(el, null).getPropertyValue('display') === 'block'
128         }
129 }
130
131 // Pass return value from dom event handlers to this.
132 // If they return false, this will addinionally stop propagation and default.
133 function event_return (e, bool) {
134         if (bool === false) {
135                 if (e.stopPropagation != null) {
136                         e.stopPropagation()
137                 }
138                 if (e.preventDefault != null) {
139                         e.preventDefault()
140                 }
141         }
142         return bool
143 }
144
145 // Warning: currently assumes you're asking about a single character
146 // Note: chromium returns multiple bounding rects for a space at a line-break
147 // Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
148 // Note: sometimes returns null (eg for whitespace that is not visible)
149 text_range_bounds = function(el, start, end) {
150         var doc, range, rect, rects, win, x_fix, y_fix
151         range = document.createRange()
152         range.setStart(el, start)
153         range.setEnd(el, end)
154         rects = range.getClientRects()
155         if (rects.length > 0) {
156                 if (rects.length > 1) {
157                         if (rects[1].width > rects[0].width) {
158                                 rect = rects[1]
159                         } else {
160                                 rect = rects[0]
161                         }
162                 } else {
163                         rect = rects[0]
164                 }
165         } else {
166                 return null
167         }
168         doc = el.ownerDocument.documentElement
169         win = el.ownerDocument.defaultView
170         y_fix = win.pageYOffset - doc.clientTop
171         x_fix = win.pageXOffset - doc.clientLeft
172         return {
173                 x: rect.left + x_fix,
174                 y: rect.top + y_fix,
175                 w: rect.width != null ? rect.width : rect.right - rect.left,
176                 h: rect.height != null ? rect.height : rect.top - rect.bottom,
177                 rects: rects,
178                 bounding: range.getBoundingClientRect()
179         }
180 }
181
182 function CursorPosition(args) {
183         this.n = args.n != null ? args.n : null
184         this.i = args.i != null ? args.i : null
185         if (args.x != null) {
186                 this.x = args.x
187                 this.y = args.y
188                 this.h = args.h
189         } else {
190                 this.set_xyh()
191         }
192 }
193
194 CursorPosition.prototype.set_xyh = function() {
195         var range, ret
196         range = document.createRange()
197         if (this.n.text.length === 0) {
198                 ret = text_range_bounds(this.n.el, 0, 0)
199         } else if (this.i === this.n.text.length) {
200                 ret = text_range_bounds(this.n.el, this.i - 1, this.i)
201                 if (ret != null) {
202                         ret.x += ret.w
203                 }
204         } else {
205                 ret = text_range_bounds(this.n.el, this.i, this.i + 1)
206         }
207         if (ret != null) {
208                 this.x = ret.x
209                 this.y = ret.y
210                 this.h = ret.h
211         } else {
212                 this.x = null
213                 this.y = null
214                 this.h = null
215         }
216         return ret
217 }
218
219 function new_cursor_position (args) {
220         var ret
221         ret = new CursorPosition(args)
222         if (ret.x != null) {
223                 return ret
224         }
225         return null
226 }
227
228 // encode text so it can be safely placed inside an html attribute
229 enc_attr_regex = new RegExp('(&)|(")|(\u00A0)', 'g')
230 function enc_attr (txt) {
231         return txt.replace(enc_attr_regex, function(match, amp, quote) {
232                 if (amp) {
233                         return '&amp;'
234                 }
235                 if (quote) {
236                         return '&quot;'
237                 }
238                 return '&nbsp;'
239         })
240 }
241 enc_text_regex = new RegExp('(&)|(<)|(\u00A0)', 'g')
242 function enc_text (txt) {
243         return txt.replace(enc_text_regex, function(match, amp, lt) {
244                 if (amp) {
245                         return '&amp;'
246                 }
247                 if (lt) {
248                         return '&lt;'
249                 }
250                 return '&nbsp;'
251         })
252 }
253
254 void_elements = {
255         area: true,
256         base: true,
257         br: true,
258         col: true,
259         embed: true,
260         hr: true,
261         img: true,
262         input: true,
263         keygen: true,
264         link: true,
265         meta: true,
266         param: true,
267         source: true,
268         track: true,
269         wbr: true
270 }
271
272 // this does not pretty-print
273 function nodes_to_html (tree) {
274         var attr_keys, i, k, n, ret
275         ret = ''
276         for (i = 0; i < tree.length; ++i) {
277                 n = tree[i]
278                 switch (n.type) {
279                         case 'tag':
280                                 ret += '<' + n.name
281                                 attr_keys = []
282                                 for (k in n.attrs) {
283                                         ret += " " + k
284                                         if (n.attrs[k].length > 0) {
285                                                 ret += "=\"" + (enc_attr(n.attrs[k])) + "\""
286                                         }
287                                 }
288                                 ret += '>'
289                                 if (void_elements[n.name] == null) {
290                                         if (n.children.length) {
291                                                 ret += nodes_to_html(n.children)
292                                         }
293                                         ret += "</" + n.name + ">"
294                                 }
295                                 break
296                         case 'text':
297                                 ret += enc_text(n.text)
298                                 break
299                         case 'comment':
300                                 ret += "<!--" + n.text + "-->" // TODO encode?
301                                 break
302                         case 'doctype':
303                                 ret += "<!DOCTYPE " + n.name
304                                 if ((n.public_identifier != null) && n.public_identifier.length > 0) {
305                                         ret += " \"" + n.public_identifier + "\""
306                                 }
307                                 if ((n.system_identifier != null) && n.system_identifier.length > 0) {
308                                         ret += " \"" + n.system_identifier + "\""
309                                 }
310                                 ret += ">"
311                 }
312         }
313         return ret
314 }
315
316 // TODO make these always pretty-print (on the inside) like blocks
317 // TODO careful though: whitespace might get pushed to parent, which might be rendered
318 no_text_elements = { // these elements never contain text
319         select: true,
320         table: true,
321         tr: true,
322         thead: true,
323         tbody: true,
324         ul: true,
325         ol: true
326 }
327
328 function domify (doc, hash) {
329         var attrs, el, i, k, tag, v
330         for (tag in hash) {
331                 attrs = hash[tag]
332                 if (tag === 'text') {
333                         return document.createTextNode(attrs)
334                 }
335                 el = document.createElement(tag)
336                 for (k in attrs) {
337                         v = attrs[k]
338                         if (k === 'children') {
339                                 for (i = 0; i < v.length; i++) {
340                                         el.appendChild(v[i])
341                                 }
342                         } else {
343                                 el.setAttribute(k, v)
344                         }
345                 }
346         }
347         return el
348 }
349
350 ignore_key_codes = {
351         '18': true,  // alt
352         '20': true,  // capslock
353         '17': true,  // ctrl
354         '144': true, // numlock
355         '16': true,  // shift
356         '91': true   // windows "start" key
357 }
358 // key codes: (valid on keydown, not keypress)
359 KEY_LEFT = 37
360 KEY_UP = 38
361 KEY_RIGHT = 39
362 KEY_DOWN = 40
363 KEY_BACKSPACE = 8 // <--
364 KEY_DELETE = 46 // -->
365 KEY_END = 35
366 KEY_ENTER = 13
367 KEY_ESCAPE = 27
368 KEY_HOME = 36
369 KEY_INSERT = 45
370 KEY_PAGE_UP = 33
371 KEY_PAGE_DOWN = 34
372 KEY_TAB = 9
373 control_key_codes = { // we react to these, but they aren't typing
374         '37': KEY_LEFT,
375         '38': KEY_UP,
376         '39': KEY_RIGHT,
377         '40': KEY_DOWN,
378         '35': KEY_END,
379          '8': KEY_BACKSPACE,
380         '46': KEY_DELETE,
381         '13': KEY_ENTER,
382         '27': KEY_ESCAPE,
383         '36': KEY_HOME,
384         '45': KEY_INSERT,
385         '33': KEY_PAGE_UP,
386         '34': KEY_PAGE_DOWN,
387          '9': KEY_TAB
388 }
389
390 function instantiate_tree (tree, parent) {
391         var c, i, k, remove, results, v
392         remove = []
393         for (i = 0; i < tree.length; ++i) {
394                 c = tree[i]
395                 switch (c.type) {
396                         case 'text':
397                                 c.el = parent.ownerDocument.createTextNode(c.text)
398                                 parent.appendChild(c.el)
399                         break
400                         case 'tag':
401                                 if (c.name === 'script' || c.name === 'object' || c.name === 'iframe' || c.name === 'link') {
402                                         // TODO put placeholders instead
403                                         remove.unshift(i)
404                                         continue
405                                 }
406                                 // TODO create in correct namespace
407                                 c.el = parent.ownerDocument.createElement(c.name)
408                                 ref1 = c.attrs
409                                 for (k in ref1) {
410                                         v = ref1[k]
411                                         // FIXME if attr_whitelist[k]?
412                                         if (valid_attr_regex.test(k)) {
413                                                 if (!js_attr_regex.test(k)) {
414                                                         c.el.setAttribute(k, v)
415                                                 }
416                                         }
417                                 }
418                                 parent.appendChild(c.el)
419                                 if (c.children.length) {
420                                         instantiate_tree(c.children, c.el)
421                                 }
422                 }
423         }
424         results = []
425         for (i = 0; i < remove.length; i++) {
426                 // FIXME this deletes the wrong node when siblings are removed
427                 index = remove[i]
428                 results.push(tree.splice(index, 1))
429         }
430         return results
431 }
432
433 function traverse_tree (tree, cb) {
434         var c, done, i
435         done = false
436         for (i = 0; i < tree.length; i++) {
437                 c = tree[i]
438                 done = cb(c)
439                 if (done) {
440                         return done
441                 }
442                 if (c.children.length) {
443                         done = traverse_tree(c.children, cb)
444                         if (done) {
445                                 return done
446                         }
447                 }
448         }
449         return done
450 }
451
452 function first_cursor_position (tree) {
453         var found
454         found = null
455         traverse_tree(tree, function(node, state) {
456                 var cursor
457                 if (node.type === 'text') {
458                         cursor = new_cursor_position({n: node, i: 0})
459                         if (cursor != null) {
460                                 found = cursor
461                                 return true // done traversing
462                         }
463                 }
464                 return false // not done traversing
465         })
466         return found // maybe null
467 }
468
469 // this will fail when text has non-locatable cursor positions (eg collapsed whitespace)
470 function find_next_cursor_position (tree, cursor) {
471         var found, new_cursor, state_before
472         if (cursor.n.type === 'text' && cursor.n.text.length > cursor.i) {
473                 new_cursor = new_cursor_position({n: cursor.n, i: cursor.i + 1})
474                 if (new_cursor != null) {
475                         return new_cursor
476                 }
477         }
478         state_before = true
479         found = null
480         traverse_tree(tree, function(node, state) {
481                 if (node.type === 'text' && state_before === false) {
482                         new_cursor = new_cursor_position({n: node, i: 0})
483                         if (new_cursor != null) {
484                                 found = new_cursor
485                                 return true // done traversing
486                         }
487                 }
488                 if (node === cursor.n) {
489                         state_before = false
490                 }
491                 return false // not done traversing
492         })
493         if (found != null) {
494                 return found
495         }
496         return null
497 }
498
499 function last_cursor_position (tree) {
500         var found
501         found = null
502         traverse_tree(tree, function(node) {
503                 var cursor
504                 if (node.type === 'text') {
505                         cursor = new_cursor_position({n: node, i: node.text.length})
506                         if (cursor != null) {
507                                 found = cursor
508                         }
509                 }
510                 return false // not done traversing
511         })
512         return found // maybe null
513 }
514
515 // this will fail when text has non-locatable cursor positions (eg collapsed whitespace)
516 function find_prev_cursor_position (tree, cursor) {
517         var found, found_prev, new_cursor
518         if (cursor.n.type === 'text' && cursor.i > 0) {
519                 new_cursor = new_cursor_position({n: cursor.n, i: cursor.i - 1})
520                 if (new_cursor != null) {
521                         return new_cursor
522                 }
523         }
524         found_prev = null
525         found = null
526         traverse_tree(tree, function(node) {
527                 if (node === cursor.n) {
528                         found = found_prev // maybe null
529                         return true // done traversing
530                 }
531                 if (node.type === 'text') {
532                         new_cursor = new_cursor_position({n: node, i: node.text.length})
533                         if (new_cursor != null) {
534                                 found_prev = new_cursor
535                         }
536                 }
537                 return false // not done traversing
538         })
539         return found // maybe null
540 }
541
542 function find_up_cursor_position (tree, cursor, ideal_x) {
543         var new_cursor, prev_cursor, target_y
544         new_cursor = cursor
545         // go prev until we're higher on y axis
546         while (new_cursor.y >= cursor.y) {
547                 new_cursor = find_prev_cursor_position(tree, new_cursor)
548                 if (new_cursor == null) {
549                         return null
550                 }
551         }
552         // done early if we're already left of old cursor position
553         if (new_cursor.x <= ideal_x) {
554                 return new_cursor
555         }
556         target_y = new_cursor.y
557         // search leftward, until we find the closest position
558         // new_cursor is the prev-most position we've checked
559         // prev_cursor is the older value, so it's not as prev as new_cursor
560         while (new_cursor.x > ideal_x && new_cursor.y === target_y) {
561                 prev_cursor = new_cursor
562                 new_cursor = find_prev_cursor_position(tree, new_cursor)
563                 if (new_cursor == null) {
564                         break
565                 }
566         }
567         // move cursor to prev_cursor or new_cursor
568         if (new_cursor != null) {
569                 if (new_cursor.y === target_y) {
570                         // both valid, and on the same line, use closest
571                         if ((ideal_x - new_cursor.x) < (prev_cursor.x - ideal_x)) {
572                                 return new_cursor
573                         } else {
574                                 return prev_cursor
575                         }
576                 } else {
577                         // new_cursor on wrong line, use prev_cursor
578                         return prev_cursor
579                 }
580         } else {
581                 // can't go any further prev, use prev_cursor
582                 return prev_cursor
583         }
584 }
585
586 function find_down_cursor_position (tree, cursor, ideal_x) {
587         var new_cursor, prev_cursor, target_y
588         new_cursor = cursor
589         // go next until we move on the y axis
590         while (new_cursor.y <= cursor.y) {
591                 new_cursor = find_next_cursor_position(tree, new_cursor)
592                 if (new_cursor == null) {
593                         return null
594                 }
595         }
596         // done early if we're already right of old cursor position
597         if (new_cursor.x >= ideal_x) {
598                 // this would be strange, but could happen due to runaround
599                 return new_cursor
600         }
601         target_y = new_cursor.y
602         // search rightward, until we find the closest position
603         // new_cursor is the next-most position we've checked
604         // prev_cursor is the older value, so it's not as next as new_cursor
605         while (new_cursor.x < ideal_x && new_cursor.y === target_y) {
606                 prev_cursor = new_cursor
607                 new_cursor = find_next_cursor_position(tree, new_cursor)
608                 if (new_cursor == null) {
609                         break
610                 }
611         }
612         if (new_cursor != null) {
613                 if (new_cursor.y === target_y) {
614                         // both valid, and on the same line, use closest
615                         if ((new_cursor.x - ideal_x) < (ideal_x - prev_cursor.x)) {
616                                 return new_cursor
617                         } else {
618                                 return prev_cursor
619                         }
620                 } else {
621                         // new_cursor on wrong line, use prev_cursor
622                         return prev_cursor
623                 }
624         } else {
625                 // can't go any further prev, use prev_cursor
626                 return prev_cursor
627         }
628 }
629
630 function xy_to_cursor (tree, xy) {
631         var after, before, bounds, cur, guess_i, i, n, ret
632         for (i = 0; i < tree.length; i++) {
633                 n = tree[i]
634                 if (n.type === 'tag' || n.type === 'text') {
635                         bounds = get_el_bounds(n.el)
636                         if (xy.x < bounds.x) {
637                                 continue
638                         }
639                         if (xy.x > bounds.x + bounds.w) {
640                                 continue
641                         }
642                         if (xy.y < bounds.y) {
643                                 continue
644                         }
645                         if (xy.y > bounds.y + bounds.h) {
646                                 continue
647                         }
648                         if (n.children.length) {
649                                 ret = xy_to_cursor(n.children, xy)
650                                 if (ret != null) {
651                                         return ret
652                                 }
653                         }
654                         if (n.type === 'text') {
655                                 // click is within bounding box that contains all text.
656                                 if (n.text.length === 0) {
657                                         ret = new_cursor_position({n: n, i: 0})
658                                         if (ret != null) {
659                                                 return ret
660                                         }
661                                         continue
662                                 }
663                                 before = new_cursor_position({n: n, i: 0})
664                                 if (before == null) {
665                                         continue
666                                 }
667                                 after = new_cursor_position({n: n, i: n.text.length})
668                                 if (after == null) {
669                                         continue
670                                 }
671                                 if (xy.y < before.y + before.h && xy.x < before.x) {
672                                         // console.log 'before first char on first line'
673                                         continue
674                                 }
675                                 if (xy.y > after.y && xy.x > after.x) {
676                                         // console.log 'after last char on last line'
677                                         continue
678                                 }
679                                 if (xy.y < before.y) {
680                                         console.log("Warning: click in text bounding box but above first line")
681                                         continue // above first line (runaround?)
682                                 }
683                                 if (xy.y > after.y + after.h) {
684                                         console.log("Warning: click in text bounding box but below last line", xy.y, after.y, after.h)
685                                         continue // below last line (shouldn't happen?)
686                                 }
687                                 while (after.i - before.i > 1) {
688                                         guess_i = Math.round((before.i + after.i) / 2)
689                                         cur = new_cursor_position({n: n, i: guess_i})
690                                         if (cur == null) {
691                                                 console.log("error: failed to find cursor pixel location for", n, guess_i)
692                                                 before = null
693                                                 break
694                                         }
695                                         if (xy.y < cur.y || (xy.y <= cur.y + cur.h && xy.x < cur.x)) {
696                                                 after = cur
697                                         } else {
698                                                 before = cur
699                                         }
700                                 }
701                                 if (before == null) { // signals failure to find a cursor position
702                                         continue
703                                 }
704                                 // which one is closest?
705                                 if (Math.abs(before.x - xy.x) < Math.abs(after.x - xy.x)) {
706                                         return before
707                                 } else {
708                                         return after
709                                 }
710                         }
711                 }
712         }
713         return null
714 }
715
716 // browsers collapse these (html5 spec calls these "space characters")
717 function is_space_code (char_code) {
718         switch (char_code) {
719                 case 9:
720                 case 10:
721                 case 12:
722                 case 13:
723                 case 32:
724                         return true
725         }
726         return false
727 }
728 function is_space (chr) {
729         return is_space_code(chr.charCodeAt(0))
730 }
731
732 function tree_remove_empty_text_nodes (tree) {
733         var c, empties, i, j, n
734         empties = []
735         traverse_tree(tree, function(n) {
736                 if (n.type === 'text') {
737                         if (n.text.length === 0) {
738                                 empties.unshift(n)
739                         }
740                 }
741                 return false // not done traversing
742         })
743         for (i = 0; i < empties.length; i++) {
744                 n = empties[i]
745                 // don't completely empty the tree
746                 if (tree.length === 1) {
747                         if (tree[0].type === 'text') {
748                                 console.log("oop, leaving a blank node because it's the only thing")
749                                 return
750                         }
751                 }
752                 n.el.parentNode.removeChild(n.el)
753                 ref = n.parent.children
754                 for (j = 0; j < ref.length; ++j) {
755                         c = ref[j]
756                         if (c === n) {
757                                 n.parent.children.splice(j, 1)
758                                 break
759                         }
760                 }
761         }
762 }
763
764 function PeachHTML5Editor (in_el, options) {
765         // Options: (all optional)
766         //   editor_id: "id" attribute for outer-most element created by/for editor
767         //   css_file: filename of a css file to style editable content
768         //   on_init: callback for when the editable content is in place
769         var css, opt_fragment, outer_bounds, outer_iframe_style, outer_wrap
770         this.options = options != null ? options : {}
771         this.in_el = in_el
772         this.tree = null // array of Nodes, all editable content
773         this.tree_parent = null // this.tree is this.children. .el might === this.idoc.body
774         this.matting = []
775         this.init_1_called = false // when iframes have loaded
776         this.outer_iframe // iframe to hold editor
777         this.outer_idoc // "document" object for this.outer_iframe
778         this.wrap2 = null // scrollbar is on this
779         this.wrap2_offset = null
780         this.wrap2_height = null // including padding
781         this.iframe = null // iframe to hold editable content
782         this.idoc = null // "document" object for this.iframe
783         this.cursor = null
784         this.cursor_el = null
785         this.cursor_visible = false
786         this.cursor_ideal_x = null
787         this.poll_for_blur_timeout = null
788         opt_fragment = this.options.fragment != null ? this.options.fragment : true
789         this.parser_opts = {}
790         if (opt_fragment) {
791                 this.parser_opts.fragment = 'body'
792         }
793         this.outer_iframe = domify(document, {iframe: {}})
794         outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
795         if (this.options.editor_id != null) {
796                 this.outer_iframe.setAttribute('id', this.options.editor_id)
797         }
798         this.outer_iframe.onload = (function(_this) {
799                 return function() {
800                         var icss
801                         _this.outer_idoc = _this.outer_iframe.contentDocument
802                         icss = domify(_this.outer_idoc, { style: { children: [
803                                 domify(_this.outer_idoc, {text: css})
804                         ]}})
805                         _this.outer_idoc.head.appendChild(icss)
806                         _this.iframe = domify(_this.outer_idoc, {iframe: {sandbox: 'allow-same-origin allow-scripts'}})
807                         _this.iframe.onload = function() {
808                                 return _this.init_1()
809                         }
810                         timeout(200, function() { // firefox never fires this onload
811                                 if (!_this.init_1_called) {
812                                         return _this.init_1()
813                                 }
814                         })
815                         _this.outer_idoc.body.appendChild(
816                                 domify(_this.outer_idoc, {div: {id: 'wrap1', children: [
817                                         domify(_this.outer_idoc, {div: {
818                                                 style: "position: absolute; top: 0; left: 1px; font-size: 10px",
819                                                 children: [domify(_this.outer_idoc, {text: "Peach HTML5 Editor"})]
820                                         }}),
821                                         _this.wrap2 = domify(_this.outer_idoc, {div: {id: 'wrap2', children: [
822                                                 domify(_this.outer_idoc, {div: {id: 'wrap3', children: [
823                                                         _this.iframe,
824                                                         _this.overlay = domify(_this.outer_idoc, { div: { id: 'overlay' }})
825                                                 ]}})
826                                         ]}})
827                                 ]}})
828                         )
829                 }
830         })(this)
831         outer_wrap = domify(document, {div: {"class": 'peach_html5_editor' }})
832         this.in_el.parentNode.appendChild(outer_wrap)
833         outer_bounds = get_el_bounds(outer_wrap)
834         if (outer_bounds.w < 300) {
835                 outer_bounds.w = 300
836         }
837         if (outer_bounds.h < 300) {
838                 outer_bounds.h = 300
839         }
840         outer_iframe_style += "width: " + outer_bounds.w + "px; height: " + outer_bounds.h + "px;"
841         this.outer_iframe.setAttribute('style', outer_iframe_style)
842         css = this.generate_outer_css({w: outer_bounds.w, h: outer_bounds.h})
843         outer_wrap.appendChild(this.outer_iframe)
844 }
845 PeachHTML5Editor.prototype.init_1 = function() { // this.iframe has loaded (but not it's css)
846         var istyle
847         this.idoc = this.iframe.contentDocument
848         this.init_1_called = true
849         // chromium doesn't resolve relative urls as though they were at the same domain
850         // so add a <base> tag
851         this.idoc.head.appendChild(domify(this.idoc, {base: {href: this_url_sans_path()}}))
852         // don't let @iframe have scrollbars
853         this.idoc.head.appendChild(domify(this.idoc, {style: {children: [
854                 domify(this.idoc, {text: "body { overflow: hidden; }"})
855         ]}}))
856         if (this.options.css_file) {
857                 istyle = domify(this.idoc, {link: {rel: 'stylesheet', href: this.options.css_file}})
858                 istyle.onload = (function(_this) {
859                         return function() {
860                                 return _this.init_2()
861                         }
862                 })(this)
863                 this.idoc.head.appendChild(istyle)
864         } else {
865                 this.init_2()
866         }
867 }
868 PeachHTML5Editor.prototype.init_2 = function() { // this.iframe and it's css file(s) are ready
869         this.overlay.onclick = (function(_this) {
870                 return function(e) {
871                         _this.have_focus()
872                         return event_return(e, _this.onclick(e))
873                 }
874         })(this)
875         this.overlay.ondoubleclick = (function(_this) {
876                 return function(e) {
877                         _this.have_focus()
878                         return event_return(e, _this.ondoubleclick(e))
879                 }
880         })(this)
881         this.outer_idoc.body.onkeyup = (function(_this) {
882                 return function(e) {
883                         _this.have_focus()
884                         return event_return(e, _this.onkeyup(e))
885                 }
886         })(this)
887         this.outer_idoc.body.onkeydown = (function(_this) {
888                 return function(e) {
889                         _this.have_focus()
890                         return event_return(e, _this.onkeydown(e))
891                 }
892         })(this)
893         this.outer_idoc.body.onkeypress = (function(_this) {
894                 return function(e) {
895                         _this.have_focus()
896                         return event_return(e, _this.onkeypress(e))
897                 }
898         })(this)
899         this.load_html(this.in_el.value)
900         if (this.options.on_init != null) {
901                 return this.options.on_init()
902         }
903 }
904 PeachHTML5Editor.prototype.generate_outer_css = function(args) {
905         var frame_width, h, inner_padding, occupy, ret, w
906         w = args.w != null ? args.w : 300
907         h = args.h != null ? args.h : 300
908         inner_padding = args.inner_padding != null ? args.inner_padding : overlay_padding
909         frame_width = args.frame_width != null ? args.frame_width : inner_padding
910         occupy = function(left, top, right, bottom) {
911                 if (top == null) {
912                         top = left
913                 }
914                 if (right == null) {
915                         right = left
916                 }
917                 if (bottom == null) {
918                         bottom = top
919                 }
920                 w -= left + right
921                 h -= top + bottom
922                 return Math.max(left, top, right, bottom)
923         }
924         ret = ''
925         ret += 'body {'
926         ret +=     'margin: 0;'
927         ret +=     'padding: 0;'
928         ret +=     'color: black;'
929         ret +=     'background: white;'
930         ret += '}'
931         ret += '#wrap1 {'
932         ret +=     "border: " + (occupy(1)) + "px solid black;"
933         ret +=     "padding: " + (occupy(frame_width)) + "px;"
934         ret += '}'
935         ret += '#wrap2 {'
936         ret +=     "border: " + (occupy(1)) + "px solid black;"
937         this.wrap2_height = h // including padding because padding scrolls
938         ret +=     "padding: " + (occupy(inner_padding)) + "px;"
939         ret +=     "padding-right: " + (inner_padding + occupy(0, 0, 15, 0)) + "px;"
940         ret +=     "width: " + w + "px;"
941         ret +=     "height: " + h + "px;"
942         ret += 'overflow-x: hidden;'
943         ret += 'overflow-y: scroll;'
944         ret += '}'
945         ret += '#wrap3 {'
946         ret += 'position: relative;'
947         ret +=     "width: " + w + "px;"
948         ret +=     "min-height: " + h + "px;"
949         ret += '}'
950         ret += 'iframe {'
951         ret += 'box-sizing: border-box;'
952         ret += 'margin: 0;'
953         ret += 'border: none;'
954         ret += 'padding: 0;'
955         ret +=     "width: " + w + "px;"
956         //ret +=     "height: " + h + "px;" // height auto-set when content set/changed
957         ret +=     '-ms-user-select: none;'
958         ret +=     '-webkit-user-select: none;'
959         ret +=     '-moz-user-select: none;'
960         ret +=     'user-select: none;'
961         ret += '}'
962         ret += '#overlay {'
963         ret +=     'position: absolute;'
964         ret +=     "left: -" + inner_padding + "px;"
965         ret +=     "top: -" + inner_padding + "px;"
966         ret +=     "right: -" + inner_padding + "px;"
967         ret +=     "bottom: -" + inner_padding + "px;"
968         ret +=     'overflow: hidden;'
969         ret += '}'
970         ret += '.lightbox {'
971         ret +=     'position: absolute;'
972         ret +=     'background: rgba(100,100,100,0.2);'
973         ret += '}'
974         ret += '#cursor {'
975         ret +=     'position: absolute;'
976         ret +=     'width: 2px;'
977         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));'
978         ret +=     'background-size: 200% 200%;'
979         ret +=     '-webkit-animation: blink 1s linear normal infinite;'
980         ret +=     'animation: blink 1s linear normal infinite;'
981         ret += '}'
982         ret += '@-webkit-keyframes blink {'
983         ret +=     '0%{background-position:0% 0%}'
984         ret +=     '100%{background-position:0% -100%}'
985         ret += '}'
986         ret += '@keyframes blink { '
987         ret +=     '0%{background-position:0% 0%}'
988         ret +=     '100%{background-position:0% -100%}'
989         ret += '}'
990         ret += '.ann_box {'
991         ret +=     'z-index: 5;'
992         ret +=     'position: absolute;'
993         ret +=     'border: 1px solid rgba(0,0,0,0.1);'
994         ret +=     'outline: 1px solid rgba(255,255,255,0.1);' // in case there's a black background
995         ret += '}'
996         ret += '.ann_tag {'
997         ret +=     'z-index: 10;'
998         ret +=     'position: absolute;'
999         ret +=     'font-size: 8px;'
1000         ret +=     'white-space: pre;'
1001         ret +=     'background: rgba(255,255,255,0.4);'
1002         ret +=     '-ms-user-select: none;'
1003         ret +=     '-webkit-user-select: none;'
1004         ret +=     '-moz-user-select: none;'
1005         ret +=     'user-select: none;'
1006         ret += '}'
1007         return ret
1008 }
1009 PeachHTML5Editor.prototype.overlay_event_to_inner_xy = function(e) {
1010         var x, y
1011         if (this.wrap2_offset == null) {
1012                 this.wrap2_offset = get_el_bounds(this.wrap2)
1013         }
1014         x = e.pageX - overlay_padding
1015         y = e.pageY - overlay_padding + this.wrap2.scrollTop
1016         return {
1017                 x: x - this.wrap2_offset.x,
1018                 y: y - this.wrap2_offset.y
1019         }
1020 }
1021 PeachHTML5Editor.prototype.onclick = function(e) {
1022         var new_cursor, xy
1023         xy = this.overlay_event_to_inner_xy(e)
1024         new_cursor = xy_to_cursor(this.tree, xy)
1025         if (new_cursor != null) {
1026                 this.move_cursor(new_cursor)
1027         } else {
1028                 this.kill_cursor()
1029         }
1030         return false
1031 }
1032 PeachHTML5Editor.prototype.ondoubleclick = function(e) {
1033         return false
1034 }
1035 PeachHTML5Editor.prototype.onkeyup = function(e) {
1036         if (e.ctrlKey) {
1037                 return
1038         }
1039         if (ignore_key_codes[e.keyCode] != null) {
1040                 return false
1041         }
1042         //return false if control_key_codes[e.keyCode] != null
1043 }
1044 PeachHTML5Editor.prototype.onkeydown = function(e) {
1045         var new_cursor, saved_ideal_x
1046         if (e.ctrlKey) {
1047                 return
1048         }
1049         if (ignore_key_codes[e.keyCode] != null) {
1050                 return false
1051         }
1052         //return false if control_key_codes[e.keyCode] != null
1053         switch (e.keyCode) {
1054                 case KEY_LEFT:
1055                         if (this.cursor != null) {
1056                                 new_cursor = find_prev_cursor_position(this.tree, this.cursor)
1057                         } else {
1058                                 new_cursor = first_cursor_position(this.tree)
1059                         }
1060                         if (new_cursor != null) {
1061                                 this.move_cursor(new_cursor)
1062                         }
1063                         return false
1064                 case KEY_RIGHT:
1065                         if (this.cursor != null) {
1066                                 new_cursor = find_next_cursor_position(this.tree, this.cursor)
1067                         } else {
1068                                 new_cursor = last_cursor_position(this.tree)
1069                         }
1070                         if (new_cursor != null) {
1071                                 this.move_cursor(new_cursor)
1072                         }
1073                         return false
1074                 case KEY_UP:
1075                         if (this.cursor != null) {
1076                                 new_cursor = find_up_cursor_position(this.tree, this.cursor, this.cursor_ideal_x)
1077                                 if (new_cursor != null) {
1078                                         saved_ideal_x = this.cursor_ideal_x
1079                                         this.move_cursor(new_cursor)
1080                                         this.cursor_ideal_x = saved_ideal_x
1081                                 }
1082                         } else {
1083                                 // move cursor to first position in document
1084                                 new_cursor = first_cursor_position(this.tree)
1085                                 if (new_cursor != null) {
1086                                         this.move_cursor(new_cursor)
1087                                 }
1088                         }
1089                         return false
1090                 case KEY_DOWN:
1091                         if (this.cursor != null) {
1092                                 new_cursor = find_down_cursor_position(this.tree, this.cursor, this.cursor_ideal_x)
1093                                 if (new_cursor != null) {
1094                                         saved_ideal_x = this.cursor_ideal_x
1095                                         this.move_cursor(new_cursor)
1096                                         this.cursor_ideal_x = saved_ideal_x
1097                                 }
1098                         } else {
1099                                 // move cursor to first position in document
1100                                 new_cursor = last_cursor_position(this.tree)
1101                                 if (new_cursor != null) {
1102                                         this.move_cursor(new_cursor)
1103                                 }
1104                         }
1105                         return false
1106                 case KEY_END:
1107                         new_cursor = last_cursor_position(this.tree)
1108                         if (new_cursor != null) {
1109                                 this.move_cursor(new_cursor)
1110                         }
1111                         return false
1112                 case KEY_BACKSPACE:
1113                         this.on_key_backspace(e)
1114                         return false
1115                 case KEY_DELETE:
1116                         if (this.cursor == null) {
1117                                 return false
1118                         }
1119                         new_cursor = find_next_cursor_position(this.tree, {n: this.cursor.n, i: this.cursor.i})
1120                         // try moving cursor right and then running backspace code
1121                         // TODO replace this hack with a real implementation
1122                         if (new_cursor != null) {
1123                                 // try to detect common case where cursor goes inside an block,
1124                                 // but doesn't pass a character (and advance one more in that case)
1125                                 if (new_cursor.n !== this.cursor.n && new_cursor.i === 0) {
1126                                         if (new_cursor.n.type === 'text' && new_cursor.n.text.length > 0) {
1127                                                 if (new_cursor.n.parent != null) {
1128                                                         if (!this.is_display_block(new_cursor.n.parent)) {
1129                                                                 // FIXME should test run sibling
1130                                                                 new_cursor = new_cursor_position({n: new_cursor.n, i: new_cursor.i + 1})
1131                                                         }
1132                                                 }
1133                                         }
1134                                 }
1135                         }
1136                         if (new_cursor != null) {
1137                                 if (new_cursor.n !== this.cursor.n || new_cursor.i !== this.cursor.i) {
1138                                         this.move_cursor(new_cursor)
1139                                         this.on_key_backspace(e)
1140                                 }
1141                         }
1142                         return false
1143                 case KEY_ENTER:
1144                         this.on_key_enter(e)
1145                         return false
1146                 case KEY_ESCAPE:
1147                         this.kill_cursor()
1148                         return false
1149                 case KEY_HOME:
1150                         new_cursor = first_cursor_position(this.tree)
1151                         if (new_cursor != null) {
1152                                 this.move_cursor(new_cursor)
1153                         }
1154                         return false
1155                 case KEY_INSERT:
1156                         return false
1157                 case KEY_PAGE_UP:
1158                         this.on_page_up_key(e)
1159                         return false
1160                 case KEY_PAGE_DOWN:
1161                         this.on_page_down_key(e)
1162                         return false
1163                 case KEY_TAB:
1164                         return false
1165         }
1166 }
1167 PeachHTML5Editor.prototype.onkeypress = function(e) {
1168         var char, new_cursor
1169         if (e.ctrlKey) {
1170                 return
1171         }
1172         if (ignore_key_codes[e.keyCode] != null) {
1173                 return false
1174         }
1175         char = e.charCode != null ? e.charCode : e.keyCode
1176         if (char && (this.cursor != null)) {
1177                 char = String.fromCharCode(char)
1178                 this.insert_character(this.cursor.n, this.cursor.i, char)
1179                 this.text_cleanup(this.cursor.n)
1180                 this.changed()
1181                 new_cursor = new_cursor_position({n: this.cursor.n, i: this.cursor.i + 1})
1182                 if (new_cursor) {
1183                         this.move_cursor(new_cursor)
1184                 } else {
1185                         console.log("ERROR: couldn't find cursor position after insert")
1186                         this.kill_cursor()
1187                 }
1188         }
1189         return false
1190 }
1191 PeachHTML5Editor.prototype.on_key_enter = function(e) { // enter key pressed
1192         var before, cur_block, i, n, new_cursor, new_node, new_text, parent_el, pc
1193         if (!this.cursor_visible) {
1194                 return
1195         }
1196         cur_block = this.cursor.n
1197         while (true) {
1198                 if (cur_block.type === 'tag') {
1199                         if (is_display_block(cur_block.el)) {
1200                                 break
1201                         }
1202                 }
1203                 if (cur_block.parent == null) {
1204                         return
1205                 }
1206                 cur_block = cur_block.parent
1207         }
1208         // find array to insert new element into
1209         if (cur_block.parent === this.tree_parent) {
1210                 parent_el = this.idoc.body
1211                 pc = this.tree
1212         } else {
1213                 parent_el = cur_block.parent.el
1214                 pc = cur_block.parent.children
1215         }
1216         for (i = 0; i < pc.length; ++i) {
1217                 n = pc[i]
1218                 if (n === cur_block) {
1219                         break
1220                 }
1221         }
1222         i += 1 // we want to be after it
1223         if (i < pc.length) {
1224                 before = pc[i].el
1225         } else {
1226                 before = null
1227         }
1228         // TODO if content after cursor
1229         // TODO new block is empty
1230         new_text = new peach_parser.Node('text', {text: ' '})
1231         new_node = new peach_parser.Node('tag', {
1232                 name: 'p',
1233                 parent: cur_block.parent,
1234                 attrs: {style: 'white-space: pre-wrap'},
1235                 children: [new_text]
1236         })
1237         new_text.parent = new_node
1238         new_text.el = domify(this.idoc, {text: ' '})
1239         new_node.el = domify(this.idoc, {p: {style: 'white-space: pre-wrap', children: [new_text.el]}})
1240         pc.splice(i, 0, new_node)
1241         parent_el.insertBefore(new_node.el, before)
1242         this.changed()
1243         new_cursor = new_cursor_position({
1244                 n: new_text,
1245                 i: 0
1246         })
1247         if (new_cursor == null) {
1248                 throw 'bork bork'
1249         }
1250         this.move_cursor(new_cursor)
1251         // TODO move content past cursor into this new block
1252         return false
1253 }
1254 // unlike the global function, this takes a Node, not an element
1255 PeachHTML5Editor.prototype.is_display_block = function(n) {
1256         // TODO stop calling global function, merge it into here, use iframe's window object
1257         if (n.type !== 'tag') {
1258                 return false
1259         }
1260         return is_display_block(n.el)
1261 }
1262 PeachHTML5Editor.prototype.find_block_parent = function(n) {
1263         while (true) {
1264                 n = n.parent
1265                 if (n == null) {
1266                         return null
1267                 }
1268                 if (this.is_display_block(n)) {
1269                         return n
1270                 }
1271                 if (n === this.tree_parent) {
1272                         return n
1273                 }
1274         }
1275         return null
1276 }
1277 // return a flat array of nodes (text, <br>, and later also inline-block)
1278 // that are flowing/wrapping together. n can be the containing block, or any
1279 // element inside it.
1280 PeachHTML5Editor.prototype.get_text_run = function(n) {
1281         var block, ret
1282         ret = []
1283         if (this.is_display_block(n)) {
1284                 block = n
1285         } else {
1286                 block = this.find_block_parent(n)
1287                 if (block == null) {
1288                         return ret
1289                 }
1290         }
1291         traverse_tree(block.children, (function(_this) { return function(n) {
1292                 var disp
1293                 if (n.type === 'text') {
1294                         ret.push(n)
1295                 } else if (n.type === 'tag') {
1296                         if (n.name === 'br') {
1297                                 ret.push(n)
1298                         } else {
1299                                 disp = _this.computed_style(n)
1300                                 if (disp === 'inline-block') {
1301                                         ret.push(n)
1302                                 }
1303                         }
1304                 }
1305                 return false // not done traversing
1306         }})(this))
1307         return ret
1308 }
1309 PeachHTML5Editor.prototype.node_is_decendant = function(young, old) {
1310         while (young != null && young !== this.tree_parent) {
1311                 if (young === old) {
1312                         return true
1313                 }
1314                 young = young.parent
1315         }
1316         return false
1317 }
1318 // helper for on_key_backspace
1319 PeachHTML5Editor.prototype._merge_left = function(state) {
1320         var pi, prev
1321         // the node prev to n was not prev to it a moment ago, merge with it if reasonable
1322         pi = state.n.parent.children.indexOf(state.n)
1323         if (pi > 0) {
1324                 prev = state.n.parent.children[pi - 1]
1325                 if (prev.type === 'text') {
1326                         state.i = prev.text.length
1327                         prev.text = prev.el.textContent = prev.text + state.n.text
1328                         this.remove_node(state.n)
1329                         state.n = prev
1330                         state.changed = true
1331                         state.moved_cursor = true
1332                 }
1333         }
1334         // else // TODO merge possible consecutive matching inline tags at @cursor
1335         return state
1336 }
1337 // helper for on_key_backspace
1338 // remove n from the dom, also remove its inline parents that are emptied by removing n
1339 PeachHTML5Editor.prototype._backspace_node_helper = function(n, run, run_i) {
1340         var block
1341         if (run == null) {
1342                 run = this.get_text_run(n)
1343         }
1344         if (run_i == null) {
1345                 run_i = run.indexOf(n)
1346         }
1347         block = this.find_block_parent(n)
1348         this.remove_node(n)
1349         n = n.parent
1350         while (n != null && n !== block) {
1351                 // bail if the previous node in this run is also inside the same parent
1352                 if (run_i > 0) {
1353                         if (this.node_is_decendant(run[run_i - 1], n)) {
1354                                 break
1355                         }
1356                 }
1357                 // bail if the next node in this run is also inside the same parent
1358                 if (run_i + 1 < run.length) {
1359                         if (this.node_is_decendant(run[run_i + 1], n)) {
1360                                 break
1361                         }
1362                 }
1363                 // move any sibling nodes to parent. These nodes are not in the text run
1364                 while (n.children.length > 0) {
1365                         this.move_node(n.children[0], n.parent, n)
1366                 }
1367                 // remove (now completely empty) inline parent
1368                 this.remove_node(n)
1369                 // proceed to outer parent
1370                 n = n.parent
1371         }
1372 }
1373 PeachHTML5Editor.prototype.on_key_backspace = function(e) {
1374         var block, changed, merge_state, n, ncb, need_text_cleanup, new_cursor, pcb, post, pre, prev, prev_cursor, run, run_i
1375         if (this.cursor == null) {
1376                 return
1377         }
1378         new_cursor = null
1379         run = null
1380         changed = true
1381         if (this.cursor.i === 0) { // cursor is at start of text node
1382                 if (run == null) {
1383                         run = this.get_text_run(this.cursor.n)
1384                 }
1385                 run_i = run.indexOf(this.cursor.n)
1386                 if (run_i === 0) { // if at start of text run
1387                         block = this.find_block_parent(this.cursor.n)
1388                         prev_cursor = find_prev_cursor_position(this.tree, {n: this.cursor.n, i: 0})
1389                         if (prev_cursor === null) { // if in first text run of document
1390                                 // do nothing (there's nothing text-like to the left of the cursor)
1391                                 return
1392                         }
1393                         // else merge with prev/outer text run
1394                         pcb = this.find_block_parent(prev_cursor.n)
1395                         while (block.children.length > 0) {
1396                                 this.move_node(block.children[0], pcb)
1397                         }
1398                         this.remove_node(block)
1399                         // merge possible consecutive text nodes at @cursor
1400                         merge_state = {n: this.cursor.n}
1401                         this._merge_left(merge_state)
1402                         this.text_cleanup(merge_state.n)
1403                         new_cursor = new_cursor_position({n: merge_state.n, i: merge_state.i})
1404                 } else { // at start of text node, but not start of text run
1405                         prev = run[run_i - 1]
1406                         if (prev.type === 'text') { // if previous in text run is text
1407                                 if (prev.text.length === 1) { // if emptying prev (in text run)
1408                                         this._backspace_node_helper(prev, run, run_i)
1409                                         merge_state = {n: this.cursor.n, i: this.cursor.i}
1410                                         this._merge_left(merge_state)
1411                                         this.text_cleanup(merge_state.n)
1412                                         new_cursor = new_cursor_position({n: merge_state.n, i: merge_state.i})
1413                                 } else { // prev in run is text with muliple chars
1414                                         // delete last character in prev
1415                                         prev.text = prev.text.substr(0, prev.text.length - 1)
1416                                         prev.el.textContent = prev.text
1417                                         this.text_cleanup(this.cursor.n)
1418                                         new_cursor = new_cursor_position({n: this.cursor.n, i: this.cursor.i})
1419                                 }
1420                         } else if (prev.name === 'br' || prev.name === 'hr') {
1421                                 this._backspace_node_helper(prev, run, run_i)
1422                                 merge_state = {n: this.cursor.n, i: this.cursor.i}
1423                                 this._merge_left(merge_state)
1424                                 this.text_cleanup(merge_state.n)
1425                                 new_cursor = new_cursor_position({n: merge_state.n, i: merge_state.i})
1426                         }
1427                         // FIXME implement this:
1428                         // else // if prev (in run) is inline-block
1429                                 // if that inline-block has text in it
1430                                         // delete last char in prev inlineblock
1431                                         // if that empties it
1432                                                 // delete it
1433                                                 // merge left
1434                                         // else
1435                                                 // move cursor inside
1436                                 // else
1437                                         // delete prev (inline) block
1438                                         // merge left
1439                                 // auto-delete this @cursor.parent(s) if this empties them
1440                 }
1441         } else { // cursor is not at start of text node
1442                 if (run == null) {
1443                         run = this.get_text_run(this.cursor.n)
1444                 }
1445                 if (this.cursor.n.text.length === 1) { // if emptying text node
1446                         if (run.length === 1) { // if emptying text run (of text/br/hr/inline-block)
1447                                 // remove inline-parents of @cursor.n
1448                                 block = this.find_block_parent(this.cursor.n)
1449                                 changed = false
1450                                 n = this.cursor.n.parent
1451                                 // note: this doesn't use _backspace_node_helper because:
1452                                 // 1. we don't want to delete the target node (we're replacing it's contents)
1453                                 // 2. we want to track whether anything was removed
1454                                 // 3. we know already know there's no other text from this run anywhere
1455                                 while (n && n !== block) {
1456                                         changed = true
1457                                         while (n.children.length > 0) {
1458                                                 this.move_node(n.children[0], n.parent, n)
1459                                         }
1460                                         this.remove_node(n)
1461                                         n = n.parent
1462                                 }
1463                                 // replace @cursor.n with a single (preserved) space
1464                                 if (this.cursor.n.text !== ' ') {
1465                                         changed = true
1466                                         this.cursor.n.text = this.cursor.n.el.textContent = ' '
1467                                 }
1468                                 if (changed) {
1469                                         this.text_cleanup(this.cursor.n)
1470                                 }
1471                                 // place the cursor to the left of that space
1472                                 new_cursor = new_cursor_position({n: this.cursor.n, i: 0})
1473                         } else { // emptying a text node (but not a whole text run)
1474                                 // figure out where cursor should land
1475                                 block = this.find_block_parent(this.cursor.n)
1476                                 new_cursor = find_prev_cursor_position(this.tree, {n: this.cursor.n, i: 0})
1477                                 ncb = this.find_block_parent(new_cursor.n)
1478                                 if (ncb !== block) {
1479                                         new_cursor = find_next_cursor_position(this.tree, {n: this.cursor.n, i: 1})
1480                                 }
1481                                 // delete text node and cleanup emptied parents
1482                                 run_i = run.indexOf(this.cursor.n)
1483                                 this._backspace_node_helper(this.cursor.n, run, run_i)
1484                                 // see if new adjacent siblings should merge
1485                                 // TODO make smarter
1486                                 if (run_i > 0 && run_i + 1 < run.length) {
1487                                         if (run[run_i - 1].type === 'text' && run[run_i + 1].type === 'text') {
1488                                                 merge_state = {n: run[run_i + 1]}
1489                                                 this._merge_left(merge_state)
1490                                                 if (merge_state.moved_cursor) {
1491                                                         new_cursor = merge_state
1492                                                 }
1493                                         }
1494                                 }
1495                                 // update whitespace preservation
1496                                 this.text_cleanup(block)
1497                                 // update cursor x/y in case things moved around
1498                                 if (new_cursor != null) {
1499                                         if (new_cursor.n.el.parentNode) { // still in dom after cleanup
1500                                                 new_cursor = new_cursor_position({n: new_cursor.n, i: new_cursor.i})
1501                                         } else {
1502                                                 new_cursor = null
1503                                         }
1504                                 }
1505                         }
1506                 } else { // there's a char left of cursor that we can delete without emptying anything
1507                         // delete character
1508                         need_text_cleanup = true
1509                         if (this.cursor.i > 1 && this.cursor.i < this.cursor.n.text.length) {
1510                                 pre = this.cursor.n.text.substr(this.cursor.i - 2, 3)
1511                                 post = pre.charAt(0) + pre.charAt(2)
1512                                 if (str_has_ws_run(pre) === str_has_ws_run(post)) {
1513                                         need_text_cleanup = false
1514                                 }
1515                         }
1516                         this.remove_character(this.cursor.n, this.cursor.i - 1)
1517                         // call text_cleanup if whe created/removed a whitespace run
1518                         if (need_text_cleanup) {
1519                                 this.text_cleanup(this.cursor.n)
1520                         }
1521                         new_cursor = new_cursor_position({n: this.cursor.n, i: this.cursor.i - 1})
1522                 }
1523         }
1524         // mark document changed and move the cursor
1525         if (changed != null) {
1526                 this.changed()
1527         }
1528         if (new_cursor != null) {
1529                 this.move_cursor(new_cursor)
1530         } else {
1531                 this.kill_cursor()
1532         }
1533 }
1534 PeachHTML5Editor.prototype.on_page_up_key = function(e) {
1535         var new_cursor, screen_y, scroll_amount
1536         if (this.wrap2.scrollTop === 0) {
1537                 if (this.cursor == null) {
1538                         return
1539                 }
1540                 new_cursor = first_cursor_position(this.tree)
1541                 if (new_cursor != null) {
1542                         if (new_cursor.n !== this.cursor.n || new_cursor.i !== this.cursor.i) {
1543                                 this.move_cursor(new_cursor)
1544                         }
1545                 }
1546                 return
1547         }
1548         if (this.cursor != null) {
1549                 screen_y = this.cursor.y - this.wrap2.scrollTop
1550         }
1551         scroll_amount = this.wrap2_height - breathing_room
1552         this.wrap2.scrollTop = Math.max(0, this.wrap2.scrollTop - scroll_amount)
1553         if (this.cursor != null) {
1554                 return this.move_cursor_into_view(screen_y + this.wrap2.scrollTop)
1555         }
1556 }
1557 PeachHTML5Editor.prototype.on_page_down_key = function(e) {
1558         var lowest_scrollpos, new_cursor, screen_y, scroll_amount
1559         lowest_scrollpos = this.wrap2.scrollHeight - this.wrap2_height
1560         if (this.wrap2.scrollTop === lowest_scrollpos) {
1561                 if (this.cursor == null) {
1562                         return
1563                 }
1564                 new_cursor = last_cursor_position(this.tree)
1565                 if (new_cursor != null) {
1566                         if (new_cursor.n !== this.cursor.n || new_cursor.i !== this.cursor.i) {
1567                                 this.move_cursor(new_cursor)
1568                         }
1569                 }
1570                 return
1571         }
1572         if (this.cursor != null) {
1573                 screen_y = this.cursor.y - this.wrap2.scrollTop
1574         }
1575         scroll_amount = this.wrap2_height - breathing_room
1576         this.wrap2.scrollTop = Math.min(lowest_scrollpos, this.wrap2.scrollTop + scroll_amount)
1577         if (this.cursor != null) {
1578                 this.move_cursor_into_view(screen_y + this.wrap2.scrollTop)
1579         }
1580 }
1581 PeachHTML5Editor.prototype.move_cursor_into_view = function(y_target) {
1582         var cur, far_enough, finder, new_cursor, saved_ideal_x, was, y_max, y_min
1583         if (y_target === this.cursor.y) {
1584                 return
1585         }
1586         was = this.cursor
1587         y_min = this.wrap2.scrollTop
1588         if (this.wrap2.scrollTop !== 0) {
1589                 y_min += breathing_room
1590         }
1591         y_max = this.wrap2.scrollTop + this.wrap2_height
1592         if (this.wrap2.scrollTop !== this.wrap2.scrollHeight - this.wrap2_height) { // downmost
1593                 y_max -= breathing_room
1594         }
1595         y_target = Math.min(y_target, y_max)
1596         y_target = Math.max(y_target, y_min)
1597         if (y_target < this.cursor.y) {
1598                 finder = find_up_cursor_position
1599                 far_enough = function(cur, target_y) {
1600                         return cur.y + cur.h <= target_y
1601                 }
1602         } else {
1603                 finder = find_down_cursor_position
1604                 far_enough = function(cur, y_target) {
1605                         return cur.y >= y_target
1606                 }
1607         }
1608         while (true) {
1609                 cur = finder(this.tree, was, this.cursor_ideal_x)
1610                 if (cur == null) {
1611                         break
1612                 }
1613                 if (far_enough(cur, y_target)) {
1614                         break
1615                 }
1616                 was = cur
1617         }
1618         if (was === this.cursor) {
1619                 was = null
1620         }
1621         if (was != null) {
1622                 if (was.y + was.h > y_max) {
1623                         was = null
1624                 } else if (was.y < y_min) {
1625                         was = null
1626                 }
1627         }
1628         if (cur != null) {
1629                 if (cur.y + cur.h > y_max) {
1630                         cur = null
1631                 } else if (cur.y < y_min) {
1632                         cur = null
1633                 }
1634         }
1635         if ((cur != null) && (was != null)) {
1636                 // both valid, pick best
1637                 if (cur.y < y_min) {
1638                         new_cursor = was
1639                 } else if (was.y + was.h > y_max) {
1640                         new_cursor = cur
1641                 } else if (cur.y - y_target < y_target - was.y) {
1642                         new_cursor = cur
1643                 } else {
1644                         new_cursor = was
1645                 }
1646         } else {
1647                 new_cursor = was != null ? was : cur
1648         }
1649         if (new_cursor != null) {
1650                 saved_ideal_x = this.cursor_ideal_x
1651                 this.move_cursor(new_cursor)
1652                 this.cursor_ideal_x = saved_ideal_x
1653         }
1654 }
1655 // remove all the editable content (and cursor, overlays, etc)
1656 PeachHTML5Editor.prototype.clear_dom = function() {
1657         while (this.idoc.body.childNodes.length) {
1658                 this.idoc.body.removeChild(this.idoc.body.childNodes[0])
1659         }
1660         this.kill_cursor()
1661 }
1662 PeachHTML5Editor.prototype.load_html = function(html) {
1663         this.tree = peach_parser(html, this.parser_opts)
1664         if (this.tree[0] == null ? true : this.tree[0].parent == null) {
1665                 this.tree = peach_parser('<p style="white-space: pre-wrap"> </p>', this.parser_opts)
1666         }
1667         this.tree_parent = this.tree[0].parent
1668         this.tree_parent.el = this.idoc.body
1669         this.clear_dom()
1670         instantiate_tree(this.tree, this.tree_parent.el)
1671         this.collapse_whitespace(this.tree)
1672         return this.changed()
1673 }
1674 PeachHTML5Editor.prototype.changed = function() {
1675         this.in_el.onchange = null
1676         this.in_el.value = this.pretty_html(this.tree)
1677         // TODO make option for not pretty-printing: nodes_to_html(tree)
1678         this.in_el.onchange = (function(_this) { return function() {
1679                 return _this.load_html(_this.in_el.value)
1680         }})(this)
1681         return this.adjust_iframe_height()
1682 }
1683 PeachHTML5Editor.prototype.adjust_iframe_height = function() {
1684         var h, s
1685         s = this.wrap2.scrollTop
1686         // when the content gets shorter, the idoc's body tag will continue to
1687         // report the old (too big) height in Chrome. The workaround is to
1688         // shrink the iframe before the content height:
1689         this.iframe.style.height = "10px"
1690         h = parseInt(this.idoc.body.scrollHeight, 10)
1691         this.iframe.style.height = h + "px"
1692         return this.wrap2.scrollTop = s
1693 }
1694 // true if n is text node with only one caracter, and the only child of a tag
1695 PeachHTML5Editor.prototype.is_only_char_in_tag = function(n, i) {
1696         if (n.type !== 'text') {
1697                 return false
1698         }
1699         if (n.text.length !== 1) {
1700                 return false
1701         }
1702         if (n.parent === this.tree_parent) {
1703                 return false
1704         }
1705         if (n.parent.children.length !== 1) {
1706                 return false
1707         }
1708         return true
1709 }
1710 // true if n is text node with just a space in it, and the only child of a tag
1711 PeachHTML5Editor.prototype.is_lone_space = function(n, i) {
1712         if (n.type !== 'text') {
1713                 return false
1714         }
1715         if (n.text !== ' ') {
1716                 return false
1717         }
1718         if (n.parent === this.tree_parent) {
1719                 return false
1720         }
1721         if (n.parent.children.length !== 1) {
1722                 return false
1723         }
1724         return true
1725 }
1726 // detect special case: typing before a space that's the only thing in a block/doc
1727 // reason: enter key creates blocks with just a space in them
1728 PeachHTML5Editor.prototype.insert_should_replace = function(n, i) {
1729         if (i !== 0) {
1730                 return false
1731         }
1732         if (n.text !== ' ') {
1733                 return false
1734         }
1735         if (n.parent === this.tree_parent) {
1736                 return true
1737         }
1738         if (n.parent.children.length === 1) {
1739                 if (n.parent.children[0] === n) {
1740                         // n is only child
1741                         return true
1742                 }
1743         }
1744         return false
1745 }
1746 // WARNING:  after calling this, you MUST call changed() and text_cleanup()
1747 PeachHTML5Editor.prototype.insert_character = function(n, i, char) {
1748         if (n.parent === this.tree_parent) {
1749                 // FIXME implement text nodes at top level
1750                 return
1751         }
1752         // insert the character
1753         if (this.insert_should_replace(n, i)) {
1754                 n.text = char
1755         } else if (i === 0) {
1756                 n.text = char + n.text
1757         } else if (i === n.text.length) {
1758                 n.text += char
1759         } else {
1760                 n.text = n.text.substr(0, i) + char + n.text.substr(i)
1761         }
1762         return n.el.nodeValue = n.text
1763 }
1764 // WARNING: after calling this, you MUST call changed() and text_cleanup()
1765 PeachHTML5Editor.prototype.remove_character = function(n, i) {
1766         n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1767         return n.el.nodeValue = n.text
1768 }
1769 PeachHTML5Editor.prototype.computed_style = function(n, prop) {
1770         var style
1771         if (n.type === 'text') {
1772                 n = n.parent
1773         }
1774         style = this.iframe.contentWindow.getComputedStyle(n.el, null)
1775         return style.getPropertyValue(prop)
1776 }
1777 // returns the new white-space value that will preserve spaces for node n
1778 PeachHTML5Editor.prototype.preserve_space = function(n, ideal_target) {
1779         var target, ws, ref
1780         if (n.type === 'text') {
1781                 target = n.parent
1782         } else {
1783                 target = n
1784         }
1785         while (target !== ideal_target && !target.el.style.whiteSpace) {
1786                 if (target == null) {
1787                         console.log("bug #967123")
1788                         return
1789                 }
1790                 target = target.parent
1791         }
1792         ws = (ref = ws_props[target.el.style.whiteSpace]) != null ? ref.to_preserve : null
1793         if (ws == null) {
1794                 ws = 'pre-wrap'
1795         }
1796         target.el.style.whiteSpace = ws
1797         this.update_style_from_el(target)
1798         return ws
1799 }
1800 PeachHTML5Editor.prototype.update_style_from_el = function(n) {
1801         var style
1802         style = n.el.getAttribute('style')
1803         if (style != null) {
1804                 return n.attrs.style = style
1805         } else {
1806                 if (n.attrs.style != null) {
1807                         return delete n.attrs.style
1808                 }
1809         }
1810 }
1811 // remove whitespace that would be trimmed
1812 // replace whitespace that would collapse with a single space
1813 // FIXME remove whitespace from after <br> (but not before)
1814 // FIXME rewrite to
1815 //     check computed white-space prop on txt parents
1816 //     batch replace txt node contents (ie don't loop for each char)
1817 PeachHTML5Editor.prototype.collapse_whitespace = function(tree) {
1818         var cur, cur_i, cur_px, first, iterate, next, next_i, next_pos, next_px, operate, pos, prev, prev_i, prev_pos, prev_px, queue, remove, removed_char, replace_with_space
1819         if (tree == null) {
1820                 tree = this.tree
1821         }
1822         prev = cur = next = null
1823         prev_i = cur_i = next_i = 0
1824         prev_pos = pos = next_pos = null
1825         prev_px = cur_px = next_px = null
1826         first = true
1827         removed_char = null
1828
1829         tree_remove_empty_text_nodes(tree)
1830
1831         iterate = function(tree, cb) {
1832                 var advance, block, i, j, n
1833                 for (j = 0; j < tree.length; j++) {
1834                         n = tree[j]
1835                         if (n.type === 'text') {
1836                                 i = 0
1837                                 while (i < n.text.length) { // don't foreach, cb might remove chars
1838                                         advance = cb(n, i)
1839                                         if (advance) {
1840                                                 i += 1
1841                                         }
1842                                 }
1843                         }
1844                         if (n.type === 'tag') {
1845                                 block = is_display_block(n.el)
1846                                 if (block) {
1847                                         cb(null)
1848                                 }
1849                                 if (n.children.length > 0) {
1850                                         iterate(n.children, cb)
1851                                 }
1852                                 if (block) {
1853                                         cb(null)
1854                                 }
1855                         }
1856                 }
1857         }
1858         // remove cur char
1859         remove = function(undo) {
1860                 if (undo) {
1861                         cur.el.textContent = cur.text = (cur.text.substr(0, cur_i)) + removed_char + (cur.text.substr(cur_i))
1862                         if (next === cur) { // in same text node
1863                                 next_i += 1
1864                         }
1865                         return -1
1866                 } else {
1867                         removed_char = cur.text.charAt(cur_i)
1868                         cur.el.textContent = cur.text = (cur.text.substr(0, cur_i)) + (cur.text.substr(cur_i + 1))
1869                         if (next === cur) { // in same text node
1870                                 if (next_i === 0) {
1871                                         throw "how is this possible?"
1872                                 }
1873                                 next_i -= 1
1874                         }
1875                         return 1
1876                 }
1877         }
1878         replace_with_space = function(undo) {
1879                 if (undo) {
1880                         cur.text = (cur.text.substr(0, cur_i)) + removed_char + (cur.text.substr(cur_i + 1))
1881                         cur.el.textContent = cur.text
1882                 } else {
1883                         removed_char = cur.text.charAt(cur_i)
1884                         if (removed_char !== ' ') {
1885                                 cur.text = (cur.text.substr(0, cur_i)) + ' ' + (cur.text.substr(cur_i + 1))
1886                                 cur.el.textContent = cur.text
1887                         }
1888                 }
1889                 return 0
1890         }
1891         // return true if cur was removed from the dom (ie re-use same prev)
1892         operate = function() {
1893                 // cur definitately set
1894                 // prev and/or next might be null, indicating the start/end of a display:block
1895                 var bounds, dbg, fixer, fixers, i, need_undo, new_next_px, new_prev_px, removed, undo_arg
1896                 if (!is_space_code(cur.text.charCodeAt(cur_i))) {
1897                         return false
1898                 }
1899                 fixers = [remove, replace_with_space]
1900                 // check for common case: single whitespace surrounded by non-whitespace chars
1901                 if ((prev != null) && (next != null)) {
1902                         if (!((is_space_code(prev.text.charCodeAt(prev_i))) || (is_space_code(next.text.charCodeAt(next_i))))) {
1903                                 dbg = cur.text.charCodeAt(cur_i)
1904                                 if (cur.text.charAt(cur_i) === ' ') {
1905                                         return false
1906                                 } else {
1907                                         fixers = [replace_with_space]
1908                                 }
1909                         }
1910                 }
1911                 bounds = text_range_bounds(cur.el, cur_i, cur_i + 1)
1912                 // consistent cases:
1913                 // 1. zero rects returned by getClientRects() means collapsed space
1914                 if (bounds === null) {
1915                         return remove()
1916                 }
1917                 // 2. width greater than zero means visible space
1918                 if (bounds.w > 0) {
1919                         // has bounds, don't try removing
1920                         fixers = [replace_with_space]
1921                 }
1922                 // now the weird edge cases...
1923                 //
1924                 // firefox and chromium both report zero width for characters at the end
1925                 // of a line where the text wraps (automatically, due to word-wrap) to
1926                 // the next line. These do not appear to be distinguishable from
1927                 // collapsed spaces via the range/bounds api, so...
1928                 //
1929                 // remove it from the dom, and if prev or next moves, put it back.
1930                 //
1931                 // this block (try changing it, put it back if something moves) is also
1932                 // used on collapsable whitespace characters besides space. In this case
1933                 // the character is replaced with a normal space character instead of
1934                 // removed
1935                 if ((prev != null) && (prev_px == null)) {
1936                         prev_px = new_cursor_position({n: prev, i: prev_i})
1937                 }
1938                 if ((next != null) && (next_px == null)) {
1939                         next_px = new_cursor_position({n: next, i: next_i})
1940                 }
1941                 //if prev is null and next is null
1942                 //      parent_px = cur.parent.el.getBoundingClientRect()
1943                 undo_arg = true // just for readabality
1944                 removed = 0
1945                 for (i = 0; i < fixers.length; i++) {
1946                         fixer = fixers[i]
1947                         if (removed > 0) {
1948                                 break
1949                         }
1950                         removed += fixer()
1951                         need_undo = false
1952                         if (prev != null) {
1953                                 if (prev_px != null) {
1954                                         new_prev_px = new_cursor_position({n: prev, i: prev_i})
1955                                         if (new_prev_px != null) {
1956                                                 if (new_prev_px.x !== prev_px.x || new_prev_px.y !== prev_px.y) {
1957                                                         need_undo = true
1958                                                 }
1959                                         } else {
1960                                                 need_undo = true
1961                                         }
1962                                 } else {
1963                                         console.log("this shouldn't happen, we remove spaces that don't locate")
1964                                 }
1965                         }
1966                         if ((next != null) && !need_undo) {
1967                                 if (next_px != null) {
1968                                         new_next_px = new_cursor_position({n: next, i: next_i})
1969                                         if (new_next_px != null) {
1970                                                 if (new_next_px.x !== next_px.x || new_next_px.y !== next_px.y) {
1971                                                         need_undo = true
1972                                                 }
1973                                         } else {
1974                                                 need_undo = true
1975                                         }
1976                                 }
1977                                 //else
1978                                 //      console.log "removing space becase space after it is collapsed"
1979                         }
1980                         if (need_undo) {
1981                                 removed += fixer(undo_arg)
1982                         }
1983                 }
1984                 if (removed > 0) {
1985                         return true
1986                 } else {
1987                         return false
1988                 }
1989         }
1990         // pass null at start/end of display:block
1991         queue = function(n, i) {
1992                 var advance, removed
1993                 next = n
1994                 next_i = i
1995                 next_px = null
1996                 advance = true
1997                 if (cur != null) {
1998                         removed = operate()
1999                         // don't advance (to the next character next time) if we removed a
2000                         // character from the same text node as ``next``, because doing so
2001                         // renumbers the indexes in that string
2002                         if (removed && cur === next) {
2003                                 advance = false
2004                         }
2005                 } else {
2006                         removed = false
2007                 }
2008                 if (!removed) {
2009                         prev = cur
2010                         prev_i = cur_i
2011                         prev_px = cur_px
2012                 }
2013                 cur = next
2014                 cur_i = next_i
2015                 cur_px = next_px
2016                 return advance
2017         }
2018         queue(null)
2019         iterate(tree, queue)
2020         queue(null)
2021
2022         tree_remove_empty_text_nodes(tree)
2023 }
2024 // call this after you insert or remove inline nodes. It will:
2025 //    merge consecutive text nodes
2026 //    remove empty text nodes
2027 //    adjust white-space property
2028 // note: this assumes that all whitespace in text nodes should be displayed
2029 // (ie not collapse or be trimmed) and will change the white-space property
2030 // as needed to achieve this.
2031 PeachHTML5Editor.prototype.text_cleanup = function(n) {
2032         var block, eats_start_sp, i, last, n_i, need_preserve, prev, prev_i, run, ws
2033         if (this.is_display_block(n)) {
2034                 block = n
2035         } else {
2036                 block = this.find_block_parent(n)
2037                 if (block == null) {
2038                         return
2039                 }
2040         }
2041         run = this.get_text_run(block)
2042         if (run == null) {
2043                 return
2044         }
2045         // merge consecutive text elements
2046         if (run.length > 1) {
2047                 i = 1
2048                 prev = run[0]
2049                 while (i < run.length) {
2050                         n = run[i]
2051                         if (prev.type === 'text' && n.type === 'text') {
2052                                 if (prev.parent === n.parent) {
2053                                         prev_i = n.parent.children.indexOf(prev)
2054                                         n_i = n.parent.children.indexOf(n)
2055                                         if (n_i === prev_i + 1) {
2056                                                 prev.text = prev.text + n.text
2057                                                 prev.el.textContent = prev.text
2058                                                 this.remove_node(n)
2059                                                 run.splice(i, 1)
2060                                                 continue // don't increment i or change prev
2061                                         }
2062                                 }
2063                         }
2064                         i += 1
2065                         prev = n
2066                 }
2067         }
2068         // remove empty text nodes
2069         i = 0
2070         while (i < run.length) {
2071                 n = run[i]
2072                 if (n.type === 'text') {
2073                         if (n.text === '') {
2074                                 this.remove_node(n)
2075                                 // FIXME maybe remove parents recursively if this makes them empty
2076                                 run.splice(i, 1)
2077                                 continue // don't increment i
2078                         }
2079                 }
2080                 i += 1
2081         }
2082         // note: inline tags can have white-space:pre-line/etc
2083         // note: inline-blocks have their whitespace collapsed independantly of outer run
2084         // note: inline-blocks are treated like non-whitespace char even if empty
2085         if (block.el.style.whiteSpace != null) {
2086                 ws = block.el.style.whiteSpace
2087                 if (ws_props[ws]) {
2088                         if (ws_props[ws].space) {
2089                                 if (ws_props[ws].to_collapse === 'normal') {
2090                                         block.el.style.whiteSpace = null
2091                                 } else {
2092                                         block.el.style.whiteSpace = ws_props[ws].to_collapse
2093                                 }
2094                                 this.update_style_from_el(block)
2095                         }
2096                 }
2097         }
2098         // note: space after <br> colapses, but not space before
2099         // check for spaces that would collapse without help
2100         eats_start_sp = true // if the next node starts with space it collapses (unless pre)
2101         prev = null
2102         for (i = 0; i < run.length; ++i) {
2103                 n = run[i]
2104                 if (n.type === 'tag') {
2105                         if (n.name === 'br') {
2106                                 eats_start_sp = true
2107                         } else {
2108                                 eats_start_sp = false
2109                         }
2110                 } else {
2111                         need_preserve = false
2112                         if (n.type !== 'text') {
2113                                 console.log("bug #232308")
2114                                 return
2115                         }
2116                         if (eats_start_sp) {
2117                                 if (is_space_code(n.text.charCodeAt(0))) {
2118                                         need_preserve = true
2119                                 }
2120                         }
2121                         if (!need_preserve) {
2122                                 need_preserve = multi_sp_regex.test(n.text)
2123                         }
2124                         if (need_preserve) {
2125                                 // do we have it already?
2126                                 ws = this.computed_style(n, 'white-space') // FIXME implement this
2127                                 if (ws_props[ws] != null ? !ws_props[ws].space : true) {
2128                                         // 2nd arg is ideal target for css rule
2129                                         ws = this.preserve_space(n, block)
2130                                 }
2131                                 eats_start_sp = false
2132                         } else {
2133                                 if (is_space_code(n.text.charCodeAt(n.text.length - 1))) {
2134                                         ws = this.computed_style(n, 'white-space') // FIXME implement this
2135                                         if ((ref1 = ws_props[ws]) != null ? ref1.space : void 0) {
2136                                                 eats_start_sp = false
2137                                         } else {
2138                                                 eats_start_sp = true
2139                                         }
2140                                 } else {
2141                                         eats_start_sp = false
2142                                 }
2143                         }
2144                 }
2145         }
2146         // check if text ends with a collapsable space
2147         if (run.length > 0) {
2148                 last = run[run.length - 1]
2149                 if (last.type === 'text') {
2150                         if (eats_start_sp) {
2151                                 this.preserve_space(last, block)
2152                         }
2153                 }
2154         }
2155 }
2156 PeachHTML5Editor.prototype.css_clear = function(n, prop) {
2157         var css_delimiter_regex, i, styles
2158         if (n.attrs.style == null) {
2159                 return
2160         }
2161         if (n.attrs.style === '') {
2162                 return
2163         }
2164         css_delimiter_regex = new RegExp('\s*;\s*', 'g') // FIXME make this global
2165         styles = n.attrs.style.trim().split(css_delimiter)
2166         if (!(styles.length > 0)) {
2167                 return
2168         }
2169         if (styles[styles.length - 1] === '') {
2170                 styles.pop()
2171                 if (!(styles.length > 0)) {
2172                         return
2173                 }
2174         }
2175         i = 0
2176         while (i < styles.length) {
2177                 if (styles[i].substr(0, 12) === 'white-space:') {
2178                         styles.splice(i, 1)
2179                 } else {
2180                         i += 1
2181                 }
2182         }
2183 }
2184 // WARNING: after calling this one or more times, you MUST:
2185 //    if it's inline: call @text_cleanup
2186 //    call @changed()
2187 PeachHTML5Editor.prototype.remove_node = function(n) {
2188         var i
2189         i = n.parent.children.indexOf(n)
2190         if (i === -1) {
2191                 throw "BUG #9187112313"
2192         }
2193         n.el.parentNode.removeChild(n.el)
2194         n.parent.children.splice(i, 1)
2195 }
2196 // remove a node from the tree/dom, insert into new_parent before insert_before?end
2197 // WARNING: after calling this one or more times, you MUST:
2198 //    if it's inline: call @text_cleanup
2199 //    call @changed()
2200 PeachHTML5Editor.prototype.move_node = function(n, new_parent, insert_before) {
2201         var before_i, i
2202         if (insert_before == null) {
2203                 insert_before = null
2204         }
2205         i = n.parent.children.indexOf(n)
2206         if (i === -1) {
2207                 throw "Error: tried to remove node, but it's not in it's parents list of children"
2208                 return
2209         }
2210         if (insert_before != null) {
2211                 before_i = new_parent.children.indexOf(insert_before)
2212                 if (i === -1) {
2213                         throw "Error: tried to move a node to be before a non-existent node"
2214                 }
2215                 insert_before = insert_before.el
2216         }
2217         this.remove_node(n)
2218         if (insert_before != null) {
2219                 new_parent.el.insertBefore(n.el, insert_before)
2220                 new_parent.children.splice(before_i, 0, n)
2221         } else {
2222                 new_parent.el.appendChild(n.el, insert_before)
2223                 new_parent.children.push(n)
2224         }
2225         n.parent = new_parent
2226 }
2227 // remove it, forget where it was
2228 PeachHTML5Editor.prototype.kill_cursor = function() {
2229         if (this.cursor_visible) {
2230                 this.cursor_el.parentNode.removeChild(this.cursor_el)
2231                 this.cursor_visible = false
2232         }
2233         this.cursor = null
2234         this.annotate(null)
2235 }
2236 PeachHTML5Editor.prototype.move_cursor = function(cursor) {
2237         var height
2238         this.cursor_ideal_x = cursor.x
2239         this.cursor = cursor
2240         if (!this.cursor_visible) {
2241                 this.cursor_el = domify(this.outer_idoc, {div: { id: 'cursor'}})
2242                 this.overlay.appendChild(this.cursor_el)
2243                 this.cursor_visible = true
2244         }
2245         this.cursor_el.style.left = (cursor.x + overlay_padding - 1) + "px"
2246         if (cursor.h < 5) {
2247                 height = 12
2248         } else {
2249                 height = cursor.h
2250         }
2251         this.cursor_el.style.top = (cursor.y + overlay_padding + Math.round(height * .07)) + "px"
2252         this.cursor_el.style.height = (Math.round(height * 0.82)) + "px"
2253         this.annotate(cursor.n)
2254         this.scroll_into_view(cursor.y, height)
2255 }
2256 PeachHTML5Editor.prototype.scroll_into_view = function(y, h) {
2257         var downmost, upmost
2258         if (h == null) {
2259                 h = 0
2260         }
2261         y += overlay_padding // convert units from @idoc to @wrap2
2262         // very top of document
2263         if (y <= breathing_room) {
2264                 this.wrap2.scrollTop = 0
2265                 return
2266         }
2267         // very bottom of document
2268         if (y + h >= this.wrap2.scrollHeight - breathing_room) {
2269                 this.wrap2.scrollTop = this.wrap2.scrollHeight - this.wrap2_height
2270                 return
2271         }
2272         // The most scrolled up (lowest value for scrollTop) that would be OK
2273         upmost = y + h + breathing_room - this.wrap2_height
2274         upmost = Math.max(upmost, 0)
2275         // the most scrolled down (highest value for scrollTop) that would be OK
2276         downmost = y - breathing_room
2277         downmost = Math.min(downmost, this.wrap2.scrollHeight - this.wrap2_height)
2278         if (upmost > downmost) { // means h is too big to fit
2279                 // scroll so top is visible
2280                 this.wrap2.scrollTop = downmost
2281                 return
2282         }
2283         if (this.wrap2.scrollTop < upmost) {
2284                 this.wrap2.scrollTop = upmost
2285                 return
2286         }
2287         if (this.wrap2.scrollTop > downmost) {
2288                 this.wrap2.scrollTop = downmost
2289                 return
2290         }
2291 }
2292 PeachHTML5Editor.prototype.annotate = function(n) {
2293         var alpha, ann_box, ann_tag, bounds, prev_bounds
2294         while (this.matting.length > 0) {
2295                 this.overlay.removeChild(this.matting[0])
2296                 this.matting.shift()
2297         }
2298         if (n == null) {
2299                 return
2300         }
2301         prev_bounds = {x: 0, y: 0, w: 0, h: 0}
2302         alpha = 0.1
2303         while (((n != null ? n.el : void 0) != null) && n !== this.tree_parent) {
2304                 if (n.type === 'text') {
2305                         n = n.parent
2306                         continue
2307                 }
2308                 bounds = get_el_bounds(n.el)
2309                 if (bounds == null) {
2310                         return
2311                 }
2312                 if (bounds.x === prev_bounds.x && bounds.y === prev_bounds.y && bounds.w === prev_bounds.w && bounds.h === prev_bounds.h) {
2313                         n = n.parent
2314                         continue
2315                 }
2316                 ann_box = domify(this.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});
2317                 this.overlay.appendChild(ann_box)
2318                 this.matting.push(ann_box)
2319                 ann_tag = domify(this.outer_idoc, {div: {"class": 'ann_tag', style: "left: " + (bounds.x + 1 + overlay_padding) + "px; top: " + (bounds.y - 7 + overlay_padding) + "px",children: [domify(this.outer_idoc, {text: " " + n.name + " "})]}})
2320                 this.overlay.appendChild(ann_tag)
2321                 this.matting.push(ann_tag)
2322                 n = n.parent
2323                 alpha *= 1.5
2324         }
2325 }
2326 PeachHTML5Editor.prototype.pretty_html = function(tree, indent, parent_flags) {
2327         var attr_keys, cs, display, float, i, j, in_flow, in_flow_block, inner_flags, is_block, is_br, is_text, k, n, next_indent, position, prev_in_flow_is_block, prev_in_flow_is_text, ret, visibility, want_nl, whitespace
2328         if (indent == null) {
2329                 indent = ''
2330         }
2331         if (parent_flags == null) {
2332                 parent_flags = {
2333                         pre_ish: false,
2334                         block: true,
2335                         want_nl: false
2336                 }
2337         }
2338         ret = ''
2339         want_nl = parent_flags.want_nl
2340         prev_in_flow_is_text = false
2341         prev_in_flow_is_block = false
2342         for (i = 0; i < tree.length; ++i) {
2343                 n = tree[i]
2344                 inner_flags = {
2345                         want_nl: true
2346                 }
2347                 is_br = false
2348                 switch (n.type) {
2349                         case 'tag':
2350                                 if (n.name === 'br') {
2351                                         is_br = true
2352                                 }
2353                                 is_text = false
2354                                 if (n.el.currentStyle != null) {
2355                                         cs = n.el.currentStyle
2356                                         whitespace = cs['white-space']
2357                                         display = cs['display']
2358                                         position = cs['position']
2359                                         float = cs['float']
2360                                         visibility = cs['visibility']
2361                                 } else {
2362                                         cs = this.iframe.contentWindow.getComputedStyle(n.el, null)
2363                                         whitespace = cs.getPropertyValue('white-space')
2364                                         display = cs.getPropertyValue('display')
2365                                         position = cs.getPropertyValue('position')
2366                                         float = cs.getPropertyValue('float')
2367                                         visibility = cs.getPropertyValue('visibility')
2368                                 }
2369                                 if (n.name === 'textarea') {
2370                                         inner_flags.pre_ish = true
2371                                 } else {
2372                                         inner_flags.pre_ish = whitespace.substr(0, 3) === 'pre'
2373                                 }
2374                                 switch (float) {
2375                                         case 'left':
2376                                         case 'right':
2377                                                 in_flow = false
2378                                         break
2379                                         default:
2380                                                 switch (position) {
2381                                                         case 'absolute':
2382                                                         case 'fixed':
2383                                                                 in_flow = false
2384                                                         break
2385                                                         default:
2386                                                                 if ('display' === 'none') {
2387                                                                         in_flow = false
2388                                                                 } else {
2389                                                                         switch (visibility) {
2390                                                                                 case 'hidden':
2391                                                                                 case 'collapse':
2392                                                                                         in_flow = false
2393                                                                                 break
2394                                                                                 default:
2395                                                                                         in_flow = true
2396                                                                         }
2397                                                                 }
2398                                                 }
2399                                 }
2400                                 switch (display) {
2401                                         case 'inline':
2402                                         case 'none':
2403                                                 inner_flags.block = false
2404                                                 is_block = in_flow_block = false
2405                                         break
2406                                         case 'inline-black':
2407                                                 inner_flags.block = true
2408                                                 is_block = in_flow_block = false
2409                                         break
2410                                         default:
2411                                                 inner_flags.block = true
2412                                                 is_block = true
2413                                                 in_flow_block = in_flow
2414                                 }
2415                         break
2416                         case 'text':
2417                                 is_text = true
2418                                 is_block = false
2419                                 in_flow = true
2420                                 in_flow_block = false
2421                                 break
2422                         default: // 'comment', 'doctype'
2423                                 is_text = false
2424                                 is_block = false
2425                                 in_flow = false
2426                                 in_flow_block = false
2427                 }
2428                 // print whitespace if we can
2429                 if (!parent_flags.pre_ish) {
2430                         if (!(prev_in_flow_is_text && is_br)) {
2431                                 if ((i === 0 && parent_flags.block) || in_flow_block || prev_in_flow_is_block) {
2432                                         if (want_nl) {
2433                                                 ret += "\n"
2434                                         }
2435                                         ret += indent
2436                                 }
2437                         }
2438                 }
2439                 switch (n.type) {
2440                         case 'tag':
2441                                 ret += '<' + n.name
2442                                 attr_keys = []
2443                                 for (k in n.attrs) {
2444                                         attr_keys.unshift(k)
2445                                 }
2446                                 //attr_keys.sort()
2447                                 for (j = 0; j < attr_keys.length; ++j) {
2448                                         k = attr_keys[j]
2449                                         ret += " " + k
2450                                         if (n.attrs[k].length > 0) {
2451                                                 ret += "=\"" + (enc_attr(n.attrs[k])) + "\""
2452                                         }
2453                                 }
2454                                 ret += '>'
2455                                 if (void_elements[n.name] == null) {
2456                                         if (inner_flags.block) {
2457                                                 next_indent = indent + '    '
2458                                         } else {
2459                                                 next_indent = indent
2460                                         }
2461                                         if (n.children.length) {
2462                                                 ret += this.pretty_html(n.children, next_indent, inner_flags)
2463                                         }
2464                                         ret += "</" + n.name + ">"
2465                                 }
2466                                 break
2467                         case 'text':
2468                                 ret += enc_text(n.text)
2469                                 break
2470                         case 'comment':
2471                                 ret += "<!--" + n.text + "-->" // TODO encode?
2472                                 break
2473                         case 'doctype':
2474                                 ret += "<!DOCTYPE " + n.name
2475                                 if ((n.public_identifier != null) && n.public_identifier.length > 0) {
2476                                         ret += " \"" + n.public_identifier + "\""
2477                                 }
2478                                 if ((n.system_identifier != null) && n.system_identifier.length > 0) {
2479                                         ret += " \"" + n.system_identifier + "\""
2480                                 }
2481                                 ret += ">"
2482                 }
2483                 want_nl = true
2484                 if (in_flow) {
2485                         prev_in_flow_is_text = is_text
2486                         prev_in_flow_is_block = is_block || (in_flow && is_br)
2487                 }
2488         }
2489         if (tree.length) {
2490                 // output final newline if allowed
2491                 if (!parent_flags.pre_ish) {
2492                         if (prev_in_flow_is_block || parent_flags.block) {
2493                                 ret += "\n" + (indent.substr(4))
2494                         }
2495                 }
2496         }
2497         return ret
2498 }
2499 PeachHTML5Editor.prototype.onblur = function() {
2500         this.kill_cursor()
2501 }
2502 PeachHTML5Editor.prototype.have_focus = function() {
2503         this.editor_is_focused = true
2504         this.poll_for_blur()
2505 }
2506 PeachHTML5Editor.prototype.poll_for_blur = function() {
2507         if (this.poll_for_blur_timeout != null) {
2508                 return
2509         }
2510         this.poll_for_blur_timeout = timeout(150, (function(_this) { return function() {
2511                 next_frame(function() { // pause polling when browser knows we're not active/visible/etc.
2512                         _this.poll_for_blur_timeout = null
2513                         if (document.activeElement === _this.outer_iframe) {
2514                                 _this.poll_for_blur()
2515                         } else {
2516                                 _this.editor_is_focused = false
2517                                 _this.onblur()
2518                         }
2519                 })
2520         }})(this))
2521 }
2522
2523 window.peach_html5_editor = function() {
2524         // coffeescript: return new PeachHTML5Editor args...
2525         // compiles to below... there must be a better way
2526         var args
2527         args = 1 <= arguments.length ? slice.call(arguments, 0) : []
2528         return (function(func, args, ctor) {
2529                 ctor.prototype = func.prototype
2530                 var child = new ctor, result = func.apply(child, args)
2531                 return Object(result) === result ? result : child
2532         })(PeachHTML5Editor, args, function(){})
2533 }
2534
2535 }).call(this)
2536
2537 // test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])