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