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