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