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