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