1 // Copyright 2015 Jason Woofenden
2 // This file implements an WYSIWYG editor in the browser (no contenteditable)
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
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
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/>.
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
22 breathing_room = 30 // minimum pixels above/below cursor (scrolling)
24 function timeout (ms, cb) {
25 return setTimeout(cb, ms)
28 function next_frame (cb) {
29 if (window.requestAnimationFrame != null) {
30 window.requestAnimationFrame(cb)
36 function this_url_sans_path () {
38 ret = "" + window.location.href
39 clip = ret.lastIndexOf('#')
41 ret = ret.substr(0, clip)
43 clip = ret.lastIndexOf('?')
45 ret = ret.substr(0, clip)
47 clip = ret.lastIndexOf('/')
49 ret = ret.substr(0, clip + 1)
54 // table too look up the properties of various values for css's white-space
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
72 to_preserve: 'pre-wrap'
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]')
95 function str_has_ws_run (str) {
96 return multi_sp_regex.test(str)
99 // text nodes don't have getBoundingClientRect(), so use selection api to find
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()
106 // text nodes don't have getBoundingClientRect(), so use range api
107 range = el.ownerDocument.createRange()
108 range.selectNodeContents(el)
109 rect = range.getBoundingClientRect()
111 doc = el.ownerDocument.documentElement
112 win = el.ownerDocument.defaultView
113 y_fix = win.pageYOffset - doc.clientTop
114 x_fix = win.pageXOffset - doc.clientLeft
116 x: rect.left + x_fix,
118 w: rect.width != null ? rect.width : rect.right - rect.left,
119 h: rect.height != null ? rect.height : rect.top - rect.bottom
123 function is_display_block (el) {
124 if (el.currentStyle != null) {
125 return el.currentStyle.display === 'block'
127 return window.getComputedStyle(el, null).getPropertyValue('display') === 'block'
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) {
138 if (e.preventDefault != null) {
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) {
168 doc = el.ownerDocument.documentElement
169 win = el.ownerDocument.defaultView
170 y_fix = win.pageYOffset - doc.clientTop
171 x_fix = win.pageXOffset - doc.clientLeft
173 x: rect.left + x_fix,
175 w: rect.width != null ? rect.width : rect.right - rect.left,
176 h: rect.height != null ? rect.height : rect.top - rect.bottom,
178 bounding: range.getBoundingClientRect()
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) {
194 CursorPosition.prototype.set_xyh = function() {
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)
205 ret = text_range_bounds(this.n.el, this.i, this.i + 1)
219 function new_cursor_position (args) {
221 ret = new CursorPosition(args)
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) {
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) {
257 // no closing tag, cannot have children
276 // contents are not html encoded
277 var plaintext_elements = {
288 // parser deletes a starting newline inside:
289 var newline_eating_elements = {
295 // this does not pretty-print
296 function nodes_to_html (tree) {
297 var attr_keys, i, k, n, ret
299 for (i = 0; i < tree.length; ++i) {
307 if (n.attrs[k].length > 0) {
308 ret += "=\"" + (enc_attr(n.attrs[k])) + "\""
312 if (void_elements[n.name] == null) {
313 if (n.children.length) {
314 ret += nodes_to_html(n.children)
316 ret += "</" + n.name + ">"
320 if (n.parent != null ? plaintext_elements[n.parent.name] : false) {
322 } else if (n.parent != null ? newline_eating_elements[n.parent.name] && n.text.charAt(0) === "\n" : false) {
323 ret += enc_text("\n" + n.text)
325 ret += enc_text(n.text)
329 ret += "<!--" + n.text + "-->" // TODO encode?
332 ret += "<!DOCTYPE " + n.name
333 if ((n.public_identifier != null) && n.public_identifier.length > 0) {
334 ret += " \"" + n.public_identifier + "\""
336 if ((n.system_identifier != null) && n.system_identifier.length > 0) {
337 ret += " \"" + n.system_identifier + "\""
345 // TODO make these always pretty-print (on the inside) like blocks
346 // TODO careful though: whitespace might get pushed to parent, which might be rendered
347 no_text_elements = { // these elements never contain text
357 function domify (doc, hash) {
358 var attrs, el, i, k, tag, v
361 if (tag === 'text') {
362 return document.createTextNode(attrs)
364 el = document.createElement(tag)
367 if (k === 'children') {
368 for (i = 0; i < v.length; i++) {
372 el.setAttribute(k, v)
381 '20': true, // capslock
383 '144': true, // numlock
385 '91': true // windows "start" key
387 // key codes: (valid on keydown, not keypress)
392 KEY_BACKSPACE = 8 // <--
393 KEY_DELETE = 46 // -->
402 control_key_codes = { // we react to these, but they aren't typing
419 function instantiate_tree (tree, parent) {
420 var c, i, k, remove, results, v
422 for (i = 0; i < tree.length; ++i) {
426 c.el = parent.ownerDocument.createTextNode(c.text)
427 parent.appendChild(c.el)
430 if (c.name === 'script' || c.name === 'object' || c.name === 'iframe' || c.name === 'link') {
431 // TODO put placeholders instead
435 // TODO create in correct namespace
436 c.el = parent.ownerDocument.createElement(c.name)
440 // FIXME if attr_whitelist[k]?
441 if (valid_attr_regex.test(k)) {
442 if (!js_attr_regex.test(k)) {
443 c.el.setAttribute(k, v)
447 parent.appendChild(c.el)
448 if (c.children.length) {
449 instantiate_tree(c.children, c.el)
454 for (i = 0; i < remove.length; i++) {
455 // FIXME this deletes the wrong node when siblings are removed
457 results.push(tree.splice(index, 1))
462 function traverse_tree (tree, cb) {
465 for (i = 0; i < tree.length; i++) {
471 if (c.children.length) {
472 done = traverse_tree(c.children, cb)
481 function first_cursor_position (tree) {
484 traverse_tree(tree, function(node, state) {
486 if (node.type === 'text') {
487 cursor = new_cursor_position({n: node, i: 0})
488 if (cursor != null) {
490 return true // done traversing
493 return false // not done traversing
495 return found // maybe null
498 // this will fail when text has non-locatable cursor positions (eg collapsed whitespace)
499 function find_next_cursor_position (tree, cursor) {
500 var found, new_cursor, state_before
501 if (cursor.n.type === 'text' && cursor.n.text.length > cursor.i) {
502 new_cursor = new_cursor_position({n: cursor.n, i: cursor.i + 1})
503 if (new_cursor != null) {
509 traverse_tree(tree, function(node, state) {
510 if (node.type === 'text' && state_before === false) {
511 new_cursor = new_cursor_position({n: node, i: 0})
512 if (new_cursor != null) {
514 return true // done traversing
517 if (node === cursor.n) {
520 return false // not done traversing
528 function last_cursor_position (tree) {
531 traverse_tree(tree, function(node) {
533 if (node.type === 'text') {
534 cursor = new_cursor_position({n: node, i: node.text.length})
535 if (cursor != null) {
539 return false // not done traversing
541 return found // maybe null
544 // this will fail when text has non-locatable cursor positions (eg collapsed whitespace)
545 function find_prev_cursor_position (tree, cursor) {
546 var found, found_prev, new_cursor
547 if (cursor.n.type === 'text' && cursor.i > 0) {
548 new_cursor = new_cursor_position({n: cursor.n, i: cursor.i - 1})
549 if (new_cursor != null) {
555 traverse_tree(tree, function(node) {
556 if (node === cursor.n) {
557 found = found_prev // maybe null
558 return true // done traversing
560 if (node.type === 'text') {
561 new_cursor = new_cursor_position({n: node, i: node.text.length})
562 if (new_cursor != null) {
563 found_prev = new_cursor
566 return false // not done traversing
568 return found // maybe null
571 function find_up_cursor_position (tree, cursor, ideal_x) {
572 var new_cursor, prev_cursor, target_y
574 // go prev until we're higher on y axis
575 while (new_cursor.y >= cursor.y) {
576 new_cursor = find_prev_cursor_position(tree, new_cursor)
577 if (new_cursor == null) {
581 // done early if we're already left of old cursor position
582 if (new_cursor.x <= ideal_x) {
585 target_y = new_cursor.y
586 // search leftward, until we find the closest position
587 // new_cursor is the prev-most position we've checked
588 // prev_cursor is the older value, so it's not as prev as new_cursor
589 while (new_cursor.x > ideal_x && new_cursor.y === target_y) {
590 prev_cursor = new_cursor
591 new_cursor = find_prev_cursor_position(tree, new_cursor)
592 if (new_cursor == null) {
596 // move cursor to prev_cursor or new_cursor
597 if (new_cursor != null) {
598 if (new_cursor.y === target_y) {
599 // both valid, and on the same line, use closest
600 if ((ideal_x - new_cursor.x) < (prev_cursor.x - ideal_x)) {
606 // new_cursor on wrong line, use prev_cursor
610 // can't go any further prev, use prev_cursor
615 function find_down_cursor_position (tree, cursor, ideal_x) {
616 var new_cursor, prev_cursor, target_y
618 // go next until we move on the y axis
619 while (new_cursor.y <= cursor.y) {
620 new_cursor = find_next_cursor_position(tree, new_cursor)
621 if (new_cursor == null) {
625 // done early if we're already right of old cursor position
626 if (new_cursor.x >= ideal_x) {
627 // this would be strange, but could happen due to runaround
630 target_y = new_cursor.y
631 // search rightward, until we find the closest position
632 // new_cursor is the next-most position we've checked
633 // prev_cursor is the older value, so it's not as next as new_cursor
634 while (new_cursor.x < ideal_x && new_cursor.y === target_y) {
635 prev_cursor = new_cursor
636 new_cursor = find_next_cursor_position(tree, new_cursor)
637 if (new_cursor == null) {
641 if (new_cursor != null) {
642 if (new_cursor.y === target_y) {
643 // both valid, and on the same line, use closest
644 if ((new_cursor.x - ideal_x) < (ideal_x - prev_cursor.x)) {
650 // new_cursor on wrong line, use prev_cursor
654 // can't go any further prev, use prev_cursor
659 function xy_to_cursor (tree, xy) {
660 var after, before, bounds, cur, guess_i, i, n, ret
661 for (i = 0; i < tree.length; i++) {
663 if (n.type === 'tag' || n.type === 'text') {
664 bounds = get_el_bounds(n.el)
665 if (xy.x < bounds.x) {
668 if (xy.x > bounds.x + bounds.w) {
671 if (xy.y < bounds.y) {
674 if (xy.y > bounds.y + bounds.h) {
677 if (n.children.length) {
678 ret = xy_to_cursor(n.children, xy)
683 if (n.type === 'text') {
684 // click is within bounding box that contains all text.
685 if (n.text.length === 0) {
686 ret = new_cursor_position({n: n, i: 0})
692 before = new_cursor_position({n: n, i: 0})
693 if (before == null) {
696 after = new_cursor_position({n: n, i: n.text.length})
700 if (xy.y < before.y + before.h && xy.x < before.x) {
701 // console.log 'before first char on first line'
704 if (xy.y > after.y && xy.x > after.x) {
705 // console.log 'after last char on last line'
708 if (xy.y < before.y) {
709 console.log("Warning: click in text bounding box but above first line")
710 continue // above first line (runaround?)
712 if (xy.y > after.y + after.h) {
713 console.log("Warning: click in text bounding box but below last line", xy.y, after.y, after.h)
714 continue // below last line (shouldn't happen?)
716 while (after.i - before.i > 1) {
717 guess_i = Math.round((before.i + after.i) / 2)
718 cur = new_cursor_position({n: n, i: guess_i})
720 console.log("error: failed to find cursor pixel location for", n, guess_i)
724 if (xy.y < cur.y || (xy.y <= cur.y + cur.h && xy.x < cur.x)) {
730 if (before == null) { // signals failure to find a cursor position
733 // which one is closest?
734 if (Math.abs(before.x - xy.x) < Math.abs(after.x - xy.x)) {
745 // browsers collapse these (html5 spec calls these "space characters")
746 function is_space_code (char_code) {
757 function is_space (chr) {
758 return is_space_code(chr.charCodeAt(0))
761 function tree_remove_empty_text_nodes (tree) {
762 var c, empties, i, j, n
764 traverse_tree(tree, function(n) {
765 if (n.type === 'text') {
766 if (n.text.length === 0) {
770 return false // not done traversing
772 for (i = 0; i < empties.length; i++) {
774 // don't completely empty the tree
775 if (tree.length === 1) {
776 if (tree[0].type === 'text') {
777 console.log("oop, leaving a blank node because it's the only thing")
781 n.el.parentNode.removeChild(n.el)
782 ref = n.parent.children
783 for (j = 0; j < ref.length; ++j) {
786 n.parent.children.splice(j, 1)
793 function PeachHTML5Editor (in_el, options) {
794 // Options: (all optional)
795 // editor_id: "id" attribute for outer-most element created by/for editor
796 // css_file: filename of a css file to style editable content
797 // on_init: callback for when the editable content is in place
798 var css, opt_fragment, outer_bounds, outer_iframe_style, outer_wrap
799 this.options = options != null ? options : {}
800 this.pretty_print = options.pretty_print != null ? options.pretty_print : true
802 this.tree = null // array of Nodes, all editable content
803 this.tree_parent = null // this.tree is this.children. .el might === this.idoc.body
805 this.init_1_called = false // when iframes have loaded
806 this.outer_iframe // iframe to hold editor
807 this.outer_idoc // "document" object for this.outer_iframe
809 this.wrap2 = null // scrollbar is on this
810 this.wrap2_offset = null
811 this.wrap2_height = null // including padding
812 this.iframe = null // iframe to hold editable content
813 this.idoc = null // "document" object for this.iframe
815 this.cursor_el = null
816 this.cursor_visible = false
817 this.cursor_ideal_x = null
818 opt_fragment = this.options.fragment != null ? this.options.fragment : true
819 this.parser_opts = {}
821 this.parser_opts.fragment = 'body'
823 this.outer_iframe = domify(document, {iframe: {}})
824 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
825 if (this.options.editor_id != null) {
826 this.outer_iframe.setAttribute('id', this.options.editor_id)
828 this.outer_iframe.onload = (function(_this) { return function() {
830 _this.outer_idoc = _this.outer_iframe.contentDocument
831 icss = domify(_this.outer_idoc, { style: { children: [
832 domify(_this.outer_idoc, {text: css})
834 _this.outer_idoc.head.appendChild(icss)
835 _this.input_el = domify(_this.outer_idoc, {textarea: {style: "position: relative; left: 100px"}}) // {style: "display: block; position: absolute; top: -1000px; left: 0; height: 500px; width 50em"}})
836 _this.input_el.onblur = _this.onblur.bind(_this)
837 _this.outer_idoc.body.appendChild(_this.input_el)
838 _this.iframe = domify(_this.outer_idoc, {iframe: {sandbox: 'allow-same-origin allow-scripts'}})
839 _this.iframe.onload = function() {
840 return _this.init_1()
842 timeout(200, function() { // firefox never fires this onload
843 if (!_this.init_1_called) {
844 return _this.init_1()
847 _this.outer_idoc.body.appendChild(
848 domify(_this.outer_idoc, {div: {id: 'wrap1', children: [
849 domify(_this.outer_idoc, {div: {
850 style: "position: absolute; top: 0; left: 1px; font-size: 10px",
851 children: [domify(_this.outer_idoc, {text: "Peach HTML5 Editor"})]
853 _this.wrap2 = domify(_this.outer_idoc, {div: {id: 'wrap2', children: [
854 domify(_this.outer_idoc, {div: {id: 'wrap3', children: [
856 _this.overlay = domify(_this.outer_idoc, { div: { id: 'overlay' }})
862 outer_wrap = domify(document, {div: {"class": 'peach_html5_editor' }})
863 this.in_el.parentNode.appendChild(outer_wrap)
864 outer_bounds = get_el_bounds(outer_wrap)
865 if (outer_bounds.w < 300) {
868 if (outer_bounds.h < 300) {
871 outer_iframe_style += "width: " + outer_bounds.w + "px; height: " + outer_bounds.h + "px;"
872 this.outer_iframe.setAttribute('style', outer_iframe_style)
873 css = this.generate_outer_css({w: outer_bounds.w, h: outer_bounds.h})
874 outer_wrap.appendChild(this.outer_iframe)
876 PeachHTML5Editor.prototype.init_1 = function() { // this.iframe has loaded (but not it's css)
878 this.idoc = this.iframe.contentDocument
879 this.init_1_called = true
880 // chromium doesn't resolve relative urls as though they were at the same domain
881 // so add a <base> tag
882 this.idoc.head.appendChild(domify(this.idoc, {base: {href: this_url_sans_path()}}))
883 // don't let @iframe have scrollbars
884 this.idoc.head.appendChild(domify(this.idoc, {style: {children: [
885 domify(this.idoc, {text: "body { overflow: hidden; }"})
887 if (this.options.css_file) {
888 istyle = domify(this.idoc, {link: {rel: 'stylesheet', href: this.options.css_file}})
889 istyle.onload = (function(_this) {
891 return _this.init_2()
894 this.idoc.head.appendChild(istyle)
899 PeachHTML5Editor.prototype.init_2 = function() { // this.iframe and it's css file(s) are ready
901 var this_event_bind = function (cb) {
902 return function (e) {
904 event_return(e, _this[cb](e))
907 this.overlay.onmousedown = this_event_bind('onclick')
908 this.overlay.ondoubleclick = this_event_bind('ondoubleclick')
909 this.outer_idoc.body.onkeyup = this_event_bind('onkeyup')
910 this.outer_idoc.body.onkeydown = this_event_bind('onkeydown')
911 this.outer_idoc.body.onkeypress = this_event_bind('onkeypress')
912 this.load_html(this.in_el.value)
913 if (this.options.on_init != null) {
914 return this.options.on_init()
917 PeachHTML5Editor.prototype.generate_outer_css = function(args) {
918 var frame_width, h, inner_padding, occupy, ret, w
919 w = args.w != null ? args.w : 300
920 h = args.h != null ? args.h : 300
921 inner_padding = args.inner_padding != null ? args.inner_padding : overlay_padding
922 frame_width = args.frame_width != null ? args.frame_width : inner_padding
923 occupy = function(left, top, right, bottom) {
930 if (bottom == null) {
935 return Math.max(left, top, right, bottom)
941 ret += 'color: black;'
942 ret += 'background: white;'
943 ret += 'font-family: sans;'
946 ret += "border: " + (occupy(1)) + "px solid black;"
947 ret += "padding: " + (occupy(frame_width)) + "px;"
950 ret += "border: " + (occupy(1)) + "px solid black;"
951 this.wrap2_height = h // including padding because padding scrolls
952 ret += "padding: " + (occupy(inner_padding)) + "px;"
953 ret += "padding-right: " + (inner_padding + occupy(0, 0, 15, 0)) + "px;"
954 ret += "width: " + w + "px;"
955 ret += "height: " + h + "px;"
956 ret += 'overflow-x: hidden;'
957 ret += 'overflow-y: scroll;'
960 ret += 'position: relative;'
961 ret += "width: " + w + "px;"
962 ret += "min-height: " + h + "px;"
965 ret += 'box-sizing: border-box;'
967 ret += 'border: none;'
969 ret += "width: " + w + "px;"
970 //ret += "height: " + h + "px;" // height auto-set when content set/changed
971 ret += '-ms-user-select: none;'
972 ret += '-webkit-user-select: none;'
973 ret += '-moz-user-select: none;'
974 ret += 'user-select: none;'
977 ret += 'position: absolute;'
978 ret += "left: -" + inner_padding + "px;"
979 ret += "top: -" + inner_padding + "px;"
980 ret += "right: -" + inner_padding + "px;"
981 ret += "bottom: -" + inner_padding + "px;"
982 ret += 'overflow: hidden;'
985 ret += 'position: absolute;'
986 ret += 'background: rgba(100,100,100,0.2);'
989 ret += 'position: absolute;'
991 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));'
992 ret += 'background-size: 200% 200%;'
993 ret += '-webkit-animation: blink 1s linear normal infinite;'
994 ret += 'animation: blink 1s linear normal infinite;'
996 ret += '@-webkit-keyframes blink {'
997 ret += '0%{background-position:0% 0%}'
998 ret += '100%{background-position:0% -100%}'
1000 ret += '@keyframes blink { '
1001 ret += '0%{background-position:0% 0%}'
1002 ret += '100%{background-position:0% -100%}'
1005 ret += 'z-index: 5;'
1006 ret += 'position: absolute;'
1007 ret += 'border: 1px solid rgba(0,0,0,0.1);'
1008 ret += 'outline: 1px solid rgba(255,255,255,0.1);' // in case there's a black background
1011 ret += 'z-index: 10;'
1012 ret += 'position: absolute;'
1013 ret += 'font-size: 8px;'
1014 ret += 'white-space: pre;'
1015 ret += 'background: rgba(255,255,255,0.4);'
1016 ret += '-ms-user-select: none;'
1017 ret += '-webkit-user-select: none;'
1018 ret += '-moz-user-select: none;'
1019 ret += 'user-select: none;'
1023 PeachHTML5Editor.prototype.overlay_event_to_inner_xy = function(e) {
1025 if (this.wrap2_offset == null) {
1026 this.wrap2_offset = get_el_bounds(this.wrap2)
1028 x = e.pageX - overlay_padding
1029 y = e.pageY - overlay_padding + this.wrap2.scrollTop
1031 x: x - this.wrap2_offset.x,
1032 y: y - this.wrap2_offset.y
1035 PeachHTML5Editor.prototype.onclick = function(e) {
1037 xy = this.overlay_event_to_inner_xy(e)
1038 new_cursor = xy_to_cursor(this.tree, xy)
1039 if (new_cursor != null) {
1040 this.move_cursor(new_cursor)
1046 PeachHTML5Editor.prototype.ondoubleclick = function(e) {
1049 PeachHTML5Editor.prototype.onkeyup = function(e) {
1053 if (ignore_key_codes[e.keyCode] != null) {
1056 //return false if control_key_codes[e.keyCode] != null
1058 PeachHTML5Editor.prototype.onkeydown = function(e) {
1059 var new_cursor, saved_ideal_x
1063 if (ignore_key_codes[e.keyCode] != null) {
1066 //return false if control_key_codes[e.keyCode] != null
1067 switch (e.keyCode) {
1069 if (this.cursor != null) {
1070 new_cursor = find_prev_cursor_position(this.tree, this.cursor)
1072 new_cursor = first_cursor_position(this.tree)
1074 if (new_cursor != null) {
1075 this.move_cursor(new_cursor)
1079 if (this.cursor != null) {
1080 new_cursor = find_next_cursor_position(this.tree, this.cursor)
1082 new_cursor = last_cursor_position(this.tree)
1084 if (new_cursor != null) {
1085 this.move_cursor(new_cursor)
1089 if (this.cursor != null) {
1090 new_cursor = find_up_cursor_position(this.tree, this.cursor, this.cursor_ideal_x)
1091 if (new_cursor != null) {
1092 saved_ideal_x = this.cursor_ideal_x
1093 this.move_cursor(new_cursor)
1094 this.cursor_ideal_x = saved_ideal_x
1097 // move cursor to first position in document
1098 new_cursor = first_cursor_position(this.tree)
1099 if (new_cursor != null) {
1100 this.move_cursor(new_cursor)
1105 if (this.cursor != null) {
1106 new_cursor = find_down_cursor_position(this.tree, this.cursor, this.cursor_ideal_x)
1107 if (new_cursor != null) {
1108 saved_ideal_x = this.cursor_ideal_x
1109 this.move_cursor(new_cursor)
1110 this.cursor_ideal_x = saved_ideal_x
1113 // move cursor to first position in document
1114 new_cursor = last_cursor_position(this.tree)
1115 if (new_cursor != null) {
1116 this.move_cursor(new_cursor)
1121 new_cursor = last_cursor_position(this.tree)
1122 if (new_cursor != null) {
1123 this.move_cursor(new_cursor)
1127 this.on_key_backspace(e)
1130 if (this.cursor == null) {
1133 new_cursor = find_next_cursor_position(this.tree, {n: this.cursor.n, i: this.cursor.i})
1134 // try moving cursor right and then running backspace code
1135 // TODO replace this hack with a real implementation
1136 if (new_cursor != null) {
1137 // try to detect common case where cursor goes inside an block,
1138 // but doesn't pass a character (and advance one more in that case)
1139 if (new_cursor.n !== this.cursor.n && new_cursor.i === 0) {
1140 if (new_cursor.n.type === 'text' && new_cursor.n.text.length > 0) {
1141 if (new_cursor.n.parent != null) {
1142 if (!this.is_display_block(new_cursor.n.parent)) {
1143 // FIXME should test run sibling
1144 new_cursor = new_cursor_position({n: new_cursor.n, i: new_cursor.i + 1})
1150 if (new_cursor != null) {
1151 if (new_cursor.n !== this.cursor.n || new_cursor.i !== this.cursor.i) {
1152 this.move_cursor(new_cursor)
1153 this.on_key_backspace(e)
1158 this.on_key_enter(e)
1164 new_cursor = first_cursor_position(this.tree)
1165 if (new_cursor != null) {
1166 this.move_cursor(new_cursor)
1172 this.on_page_up_key(e)
1175 this.on_page_down_key(e)
1181 PeachHTML5Editor.prototype.onkeypress = function(e) {
1182 var char, new_cursor
1186 if (ignore_key_codes[e.keyCode] != null) {
1189 char = e.charCode != null ? e.charCode : e.keyCode
1190 if (char && (this.cursor != null)) {
1191 char = String.fromCharCode(char)
1192 this.insert_character(this.cursor.n, this.cursor.i, char)
1193 this.text_cleanup(this.cursor.n)
1195 new_cursor = new_cursor_position({n: this.cursor.n, i: this.cursor.i + 1})
1197 this.move_cursor(new_cursor)
1199 console.log("ERROR: couldn't find cursor position after insert")
1205 PeachHTML5Editor.prototype.on_key_enter = function(e) { // enter key pressed
1206 var before, cur_block, i, n, new_cursor, new_node, new_text, parent_el, pc
1207 if (!this.cursor_visible) {
1210 cur_block = this.cursor.n
1212 if (cur_block.type === 'tag') {
1213 if (is_display_block(cur_block.el)) {
1217 if (cur_block.parent == null) {
1220 cur_block = cur_block.parent
1222 // find array to insert new element into
1223 if (cur_block.parent === this.tree_parent) {
1224 parent_el = this.idoc.body
1227 parent_el = cur_block.parent.el
1228 pc = cur_block.parent.children
1230 for (i = 0; i < pc.length; ++i) {
1232 if (n === cur_block) {
1236 i += 1 // we want to be after it
1237 if (i < pc.length) {
1242 // TODO if content after cursor
1243 // TODO new block is empty
1244 new_text = new peach_parser.Node('text', {text: ' '})
1245 new_node = new peach_parser.Node('tag', {
1247 parent: cur_block.parent,
1248 attrs: {style: 'white-space: pre-wrap'},
1249 children: [new_text]
1251 new_text.parent = new_node
1252 new_text.el = domify(this.idoc, {text: ' '})
1253 new_node.el = domify(this.idoc, {p: {style: 'white-space: pre-wrap', children: [new_text.el]}})
1254 pc.splice(i, 0, new_node)
1255 parent_el.insertBefore(new_node.el, before)
1257 new_cursor = new_cursor_position({
1261 if (new_cursor == null) {
1264 this.move_cursor(new_cursor)
1265 // TODO move content past cursor into this new block
1268 // unlike the global function, this takes a Node, not an element
1269 PeachHTML5Editor.prototype.is_display_block = function(n) {
1270 // TODO stop calling global function, merge it into here, use iframe's window object
1271 if (n.type !== 'tag') {
1274 return is_display_block(n.el)
1276 PeachHTML5Editor.prototype.find_block_parent = function(n) {
1282 if (this.is_display_block(n)) {
1285 if (n === this.tree_parent) {
1291 // return a flat array of nodes (text, <br>, and later also inline-block)
1292 // that are flowing/wrapping together. n can be the containing block, or any
1293 // element inside it.
1294 PeachHTML5Editor.prototype.get_text_run = function(n) {
1297 if (this.is_display_block(n)) {
1300 block = this.find_block_parent(n)
1301 if (block == null) {
1305 traverse_tree(block.children, (function(_this) { return function(n) {
1307 if (n.type === 'text') {
1309 } else if (n.type === 'tag') {
1310 if (n.name === 'br') {
1313 disp = _this.computed_style(n)
1314 if (disp === 'inline-block') {
1319 return false // not done traversing
1323 PeachHTML5Editor.prototype.node_is_decendant = function(young, old) {
1324 while (young != null && young !== this.tree_parent) {
1325 if (young === old) {
1328 young = young.parent
1332 // helper for on_key_backspace
1333 PeachHTML5Editor.prototype._merge_left = function(state) {
1335 // the node prev to n was not prev to it a moment ago, merge with it if reasonable
1336 pi = state.n.parent.children.indexOf(state.n)
1338 prev = state.n.parent.children[pi - 1]
1339 if (prev.type === 'text') {
1340 state.i = prev.text.length
1341 prev.text = prev.el.textContent = prev.text + state.n.text
1342 this.remove_node(state.n)
1344 state.changed = true
1345 state.moved_cursor = true
1348 // else // TODO merge possible consecutive matching inline tags at @cursor
1351 // helper for on_key_backspace
1352 // remove n from the dom, also remove its inline parents that are emptied by removing n
1353 PeachHTML5Editor.prototype._backspace_node_helper = function(n, run, run_i) {
1356 run = this.get_text_run(n)
1358 if (run_i == null) {
1359 run_i = run.indexOf(n)
1361 block = this.find_block_parent(n)
1364 while (n != null && n !== block) {
1365 // bail if the previous node in this run is also inside the same parent
1367 if (this.node_is_decendant(run[run_i - 1], n)) {
1371 // bail if the next node in this run is also inside the same parent
1372 if (run_i + 1 < run.length) {
1373 if (this.node_is_decendant(run[run_i + 1], n)) {
1377 // move any sibling nodes to parent. These nodes are not in the text run
1378 while (n.children.length > 0) {
1379 this.move_node(n.children[0], n.parent, n)
1381 // remove (now completely empty) inline parent
1383 // proceed to outer parent
1387 PeachHTML5Editor.prototype.on_key_backspace = function(e) {
1388 var block, changed, merge_state, n, ncb, need_text_cleanup, new_cursor, pcb, post, pre, prev, prev_cursor, run, run_i
1389 if (this.cursor == null) {
1395 if (this.cursor.i === 0) { // cursor is at start of text node
1397 run = this.get_text_run(this.cursor.n)
1399 run_i = run.indexOf(this.cursor.n)
1400 if (run_i === 0) { // if at start of text run
1401 block = this.find_block_parent(this.cursor.n)
1402 prev_cursor = find_prev_cursor_position(this.tree, {n: this.cursor.n, i: 0})
1403 if (prev_cursor === null) { // if in first text run of document
1404 // do nothing (there's nothing text-like to the left of the cursor)
1407 // else merge with prev/outer text run
1408 pcb = this.find_block_parent(prev_cursor.n)
1409 while (block.children.length > 0) {
1410 this.move_node(block.children[0], pcb)
1412 this.remove_node(block)
1413 // merge possible consecutive text nodes at @cursor
1414 merge_state = {n: this.cursor.n}
1415 this._merge_left(merge_state)
1416 this.text_cleanup(merge_state.n)
1417 new_cursor = new_cursor_position({n: merge_state.n, i: merge_state.i})
1418 } else { // at start of text node, but not start of text run
1419 prev = run[run_i - 1]
1420 if (prev.type === 'text') { // if previous in text run is text
1421 if (prev.text.length === 1) { // if emptying prev (in text run)
1422 this._backspace_node_helper(prev, run, run_i)
1423 merge_state = {n: this.cursor.n, i: this.cursor.i}
1424 this._merge_left(merge_state)
1425 this.text_cleanup(merge_state.n)
1426 new_cursor = new_cursor_position({n: merge_state.n, i: merge_state.i})
1427 } else { // prev in run is text with muliple chars
1428 // delete last character in prev
1429 prev.text = prev.text.substr(0, prev.text.length - 1)
1430 prev.el.textContent = prev.text
1431 this.text_cleanup(this.cursor.n)
1432 new_cursor = new_cursor_position({n: this.cursor.n, i: this.cursor.i})
1434 } else if (prev.name === 'br' || prev.name === 'hr') {
1435 this._backspace_node_helper(prev, run, run_i)
1436 merge_state = {n: this.cursor.n, i: this.cursor.i}
1437 this._merge_left(merge_state)
1438 this.text_cleanup(merge_state.n)
1439 new_cursor = new_cursor_position({n: merge_state.n, i: merge_state.i})
1441 // FIXME implement this:
1442 // else // if prev (in run) is inline-block
1443 // if that inline-block has text in it
1444 // delete last char in prev inlineblock
1445 // if that empties it
1449 // move cursor inside
1451 // delete prev (inline) block
1453 // auto-delete this @cursor.parent(s) if this empties them
1455 } else { // cursor is not at start of text node
1457 run = this.get_text_run(this.cursor.n)
1459 if (this.cursor.n.text.length === 1) { // if emptying text node
1460 if (run.length === 1) { // if emptying text run (of text/br/hr/inline-block)
1461 // remove inline-parents of @cursor.n
1462 block = this.find_block_parent(this.cursor.n)
1464 n = this.cursor.n.parent
1465 // note: this doesn't use _backspace_node_helper because:
1466 // 1. we don't want to delete the target node (we're replacing it's contents)
1467 // 2. we want to track whether anything was removed
1468 // 3. we know already know there's no other text from this run anywhere
1469 while (n && n !== block) {
1471 while (n.children.length > 0) {
1472 this.move_node(n.children[0], n.parent, n)
1477 // replace @cursor.n with a single (preserved) space
1478 if (this.cursor.n.text !== ' ') {
1480 this.cursor.n.text = this.cursor.n.el.textContent = ' '
1483 this.text_cleanup(this.cursor.n)
1485 // place the cursor to the left of that space
1486 new_cursor = new_cursor_position({n: this.cursor.n, i: 0})
1487 } else { // emptying a text node (but not a whole text run)
1488 // figure out where cursor should land
1489 block = this.find_block_parent(this.cursor.n)
1490 new_cursor = find_prev_cursor_position(this.tree, {n: this.cursor.n, i: 0})
1491 ncb = this.find_block_parent(new_cursor.n)
1492 if (ncb !== block) {
1493 new_cursor = find_next_cursor_position(this.tree, {n: this.cursor.n, i: 1})
1495 // delete text node and cleanup emptied parents
1496 run_i = run.indexOf(this.cursor.n)
1497 this._backspace_node_helper(this.cursor.n, run, run_i)
1498 // see if new adjacent siblings should merge
1499 // TODO make smarter
1500 if (run_i > 0 && run_i + 1 < run.length) {
1501 if (run[run_i - 1].type === 'text' && run[run_i + 1].type === 'text') {
1502 merge_state = {n: run[run_i + 1]}
1503 this._merge_left(merge_state)
1504 if (merge_state.moved_cursor) {
1505 new_cursor = merge_state
1509 // update whitespace preservation
1510 this.text_cleanup(block)
1511 // update cursor x/y in case things moved around
1512 if (new_cursor != null) {
1513 if (new_cursor.n.el.parentNode) { // still in dom after cleanup
1514 new_cursor = new_cursor_position({n: new_cursor.n, i: new_cursor.i})
1520 } else { // there's a char left of cursor that we can delete without emptying anything
1522 need_text_cleanup = true
1523 if (this.cursor.i > 1 && this.cursor.i < this.cursor.n.text.length) {
1524 pre = this.cursor.n.text.substr(this.cursor.i - 2, 3)
1525 post = pre.charAt(0) + pre.charAt(2)
1526 if (str_has_ws_run(pre) === str_has_ws_run(post)) {
1527 need_text_cleanup = false
1530 this.remove_character(this.cursor.n, this.cursor.i - 1)
1531 // call text_cleanup if whe created/removed a whitespace run
1532 if (need_text_cleanup) {
1533 this.text_cleanup(this.cursor.n)
1535 new_cursor = new_cursor_position({n: this.cursor.n, i: this.cursor.i - 1})
1538 // mark document changed and move the cursor
1539 if (changed != null) {
1542 if (new_cursor != null) {
1543 this.move_cursor(new_cursor)
1548 PeachHTML5Editor.prototype.on_page_up_key = function(e) {
1549 var new_cursor, screen_y, scroll_amount
1550 if (this.wrap2.scrollTop === 0) {
1551 if (this.cursor == null) {
1554 new_cursor = first_cursor_position(this.tree)
1555 if (new_cursor != null) {
1556 if (new_cursor.n !== this.cursor.n || new_cursor.i !== this.cursor.i) {
1557 this.move_cursor(new_cursor)
1562 if (this.cursor != null) {
1563 screen_y = this.cursor.y - this.wrap2.scrollTop
1565 scroll_amount = this.wrap2_height - breathing_room
1566 this.wrap2.scrollTop = Math.max(0, this.wrap2.scrollTop - scroll_amount)
1567 if (this.cursor != null) {
1568 return this.move_cursor_into_view(screen_y + this.wrap2.scrollTop)
1571 PeachHTML5Editor.prototype.on_page_down_key = function(e) {
1572 var lowest_scrollpos, new_cursor, screen_y, scroll_amount
1573 lowest_scrollpos = this.wrap2.scrollHeight - this.wrap2_height
1574 if (this.wrap2.scrollTop === lowest_scrollpos) {
1575 if (this.cursor == null) {
1578 new_cursor = last_cursor_position(this.tree)
1579 if (new_cursor != null) {
1580 if (new_cursor.n !== this.cursor.n || new_cursor.i !== this.cursor.i) {
1581 this.move_cursor(new_cursor)
1586 if (this.cursor != null) {
1587 screen_y = this.cursor.y - this.wrap2.scrollTop
1589 scroll_amount = this.wrap2_height - breathing_room
1590 this.wrap2.scrollTop = Math.min(lowest_scrollpos, this.wrap2.scrollTop + scroll_amount)
1591 if (this.cursor != null) {
1592 this.move_cursor_into_view(screen_y + this.wrap2.scrollTop)
1595 PeachHTML5Editor.prototype.move_cursor_into_view = function(y_target) {
1596 var cur, far_enough, finder, new_cursor, saved_ideal_x, was, y_max, y_min
1597 if (y_target === this.cursor.y) {
1601 y_min = this.wrap2.scrollTop
1602 if (this.wrap2.scrollTop !== 0) {
1603 y_min += breathing_room
1605 y_max = this.wrap2.scrollTop + this.wrap2_height
1606 if (this.wrap2.scrollTop !== this.wrap2.scrollHeight - this.wrap2_height) { // downmost
1607 y_max -= breathing_room
1609 y_target = Math.min(y_target, y_max)
1610 y_target = Math.max(y_target, y_min)
1611 if (y_target < this.cursor.y) {
1612 finder = find_up_cursor_position
1613 far_enough = function(cur, target_y) {
1614 return cur.y + cur.h <= target_y
1617 finder = find_down_cursor_position
1618 far_enough = function(cur, y_target) {
1619 return cur.y >= y_target
1623 cur = finder(this.tree, was, this.cursor_ideal_x)
1627 if (far_enough(cur, y_target)) {
1632 if (was === this.cursor) {
1636 if (was.y + was.h > y_max) {
1638 } else if (was.y < y_min) {
1643 if (cur.y + cur.h > y_max) {
1645 } else if (cur.y < y_min) {
1649 if ((cur != null) && (was != null)) {
1650 // both valid, pick best
1651 if (cur.y < y_min) {
1653 } else if (was.y + was.h > y_max) {
1655 } else if (cur.y - y_target < y_target - was.y) {
1661 new_cursor = was != null ? was : cur
1663 if (new_cursor != null) {
1664 saved_ideal_x = this.cursor_ideal_x
1665 this.move_cursor(new_cursor)
1666 this.cursor_ideal_x = saved_ideal_x
1669 // remove all the editable content (and cursor, overlays, etc)
1670 PeachHTML5Editor.prototype.clear_dom = function() {
1671 while (this.idoc.body.childNodes.length) {
1672 this.idoc.body.removeChild(this.idoc.body.childNodes[0])
1676 PeachHTML5Editor.prototype.load_html = function(html) {
1677 this.tree = peach_parser.parse(html, this.parser_opts)
1678 if (this.tree[0] == null ? true : this.tree[0].parent == null) {
1679 this.tree = peach_parser.parse('<p style="white-space: pre-wrap"> </p>', this.parser_opts)
1681 this.tree_parent = this.tree[0].parent
1682 this.tree_parent.el = this.idoc.body
1684 instantiate_tree(this.tree, this.tree_parent.el)
1685 this.collapse_whitespace(this.tree)
1686 return this.changed()
1688 PeachHTML5Editor.prototype.changed = function() {
1689 this.in_el.onchange = null
1690 if (this.pretty_print) {
1691 this.in_el.value = this.pretty_html(this.tree)
1693 this.in_el.value = nodes_to_html(this.tree)
1695 this.in_el.onchange = (function(_this) { return function() {
1696 return _this.load_html(_this.in_el.value)
1698 return this.adjust_iframe_height()
1700 PeachHTML5Editor.prototype.adjust_iframe_height = function() {
1702 s = this.wrap2.scrollTop
1703 // when the content gets shorter, the idoc's body tag will continue to
1704 // report the old (too big) height in Chrome. The workaround is to
1705 // shrink the iframe before the content height:
1706 this.iframe.style.height = "10px"
1707 h = parseInt(this.idoc.body.scrollHeight, 10)
1708 this.iframe.style.height = h + "px"
1709 return this.wrap2.scrollTop = s
1711 // true if n is text node with only one caracter, and the only child of a tag
1712 PeachHTML5Editor.prototype.is_only_char_in_tag = function(n, i) {
1713 if (n.type !== 'text') {
1716 if (n.text.length !== 1) {
1719 if (n.parent === this.tree_parent) {
1722 if (n.parent.children.length !== 1) {
1727 // true if n is text node with just a space in it, and the only child of a tag
1728 PeachHTML5Editor.prototype.is_lone_space = function(n, i) {
1729 if (n.type !== 'text') {
1732 if (n.text !== ' ') {
1735 if (n.parent === this.tree_parent) {
1738 if (n.parent.children.length !== 1) {
1743 // detect special case: typing before a space that's the only thing in a block/doc
1744 // reason: enter key creates blocks with just a space in them
1745 PeachHTML5Editor.prototype.insert_should_replace = function(n, i) {
1749 if (n.text !== ' ') {
1752 if (n.parent === this.tree_parent) {
1755 if (n.parent.children.length === 1) {
1756 if (n.parent.children[0] === n) {
1763 // WARNING: after calling this, you MUST call changed() and text_cleanup()
1764 PeachHTML5Editor.prototype.insert_character = function(n, i, char) {
1765 if (n.parent === this.tree_parent) {
1766 // FIXME implement text nodes at top level
1769 // insert the character
1770 if (this.insert_should_replace(n, i)) {
1772 } else if (i === 0) {
1773 n.text = char + n.text
1774 } else if (i === n.text.length) {
1777 n.text = n.text.substr(0, i) + char + n.text.substr(i)
1779 return n.el.nodeValue = n.text
1781 // WARNING: after calling this, you MUST call changed() and text_cleanup()
1782 PeachHTML5Editor.prototype.remove_character = function(n, i) {
1783 n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1784 return n.el.nodeValue = n.text
1786 PeachHTML5Editor.prototype.computed_style = function(n, prop) {
1788 if (n.type === 'text') {
1791 style = this.iframe.contentWindow.getComputedStyle(n.el, null)
1792 return style.getPropertyValue(prop)
1794 // returns the new white-space value that will preserve spaces for node n
1795 PeachHTML5Editor.prototype.preserve_space = function(n, ideal_target) {
1797 if (n.type === 'text') {
1802 while (target !== ideal_target && !target.el.style.whiteSpace) {
1803 if (target == null) {
1804 console.log("bug #967123")
1807 target = target.parent
1809 ws = (ref = ws_props[target.el.style.whiteSpace]) != null ? ref.to_preserve : null
1813 target.el.style.whiteSpace = ws
1814 this.update_style_from_el(target)
1817 PeachHTML5Editor.prototype.update_style_from_el = function(n) {
1819 style = n.el.getAttribute('style')
1820 if (style != null && style != '') {
1821 return n.attrs.style = style
1823 if (n.attrs.style != null) {
1824 return delete n.attrs.style
1828 // remove whitespace that would be trimmed
1829 // replace whitespace that would collapse with a single space
1830 // FIXME remove whitespace from after <br> (but not before)
1832 // check computed white-space prop on txt parents
1833 // batch replace txt node contents (ie don't loop for each char)
1834 PeachHTML5Editor.prototype.collapse_whitespace = function(tree) {
1835 var cur, cur_i, cur_px, first, iterate, next, next_i, next_pos, next_px, operate, pos, prev, prev_i, prev_pos, prev_px, queue, remove, removed_char, replace_with_space
1839 prev = cur = next = null
1840 prev_i = cur_i = next_i = 0
1841 prev_pos = pos = next_pos = null
1842 prev_px = cur_px = next_px = null
1846 tree_remove_empty_text_nodes(tree)
1848 iterate = function(tree, cb) {
1849 var advance, block, i, j, n
1850 for (j = 0; j < tree.length; j++) {
1852 if (n.type === 'text') {
1854 while (i < n.text.length) { // don't foreach, cb might remove chars
1861 if (n.type === 'tag') {
1862 block = is_display_block(n.el)
1866 if (n.children.length > 0) {
1867 iterate(n.children, cb)
1876 remove = function(undo) {
1878 cur.el.textContent = cur.text = (cur.text.substr(0, cur_i)) + removed_char + (cur.text.substr(cur_i))
1879 if (next === cur) { // in same text node
1884 removed_char = cur.text.charAt(cur_i)
1885 cur.el.textContent = cur.text = (cur.text.substr(0, cur_i)) + (cur.text.substr(cur_i + 1))
1886 if (next === cur) { // in same text node
1888 throw "how is this possible?"
1895 replace_with_space = function(undo) {
1897 cur.text = (cur.text.substr(0, cur_i)) + removed_char + (cur.text.substr(cur_i + 1))
1898 cur.el.textContent = cur.text
1900 removed_char = cur.text.charAt(cur_i)
1901 if (removed_char !== ' ') {
1902 cur.text = (cur.text.substr(0, cur_i)) + ' ' + (cur.text.substr(cur_i + 1))
1903 cur.el.textContent = cur.text
1908 // return true if cur was removed from the dom (ie re-use same prev)
1909 operate = function() {
1910 // cur definitately set
1911 // prev and/or next might be null, indicating the start/end of a display:block
1912 var bounds, dbg, fixer, fixers, i, need_undo, new_next_px, new_prev_px, removed, undo_arg
1913 if (!is_space_code(cur.text.charCodeAt(cur_i))) {
1916 fixers = [remove, replace_with_space]
1917 // check for common case: single whitespace surrounded by non-whitespace chars
1918 if ((prev != null) && (next != null)) {
1919 if (!((is_space_code(prev.text.charCodeAt(prev_i))) || (is_space_code(next.text.charCodeAt(next_i))))) {
1920 dbg = cur.text.charCodeAt(cur_i)
1921 if (cur.text.charAt(cur_i) === ' ') {
1924 fixers = [replace_with_space]
1928 bounds = text_range_bounds(cur.el, cur_i, cur_i + 1)
1929 // consistent cases:
1930 // 1. zero rects returned by getClientRects() means collapsed space
1931 if (bounds === null) {
1934 // 2. width greater than zero means visible space
1936 // has bounds, don't try removing
1937 fixers = [replace_with_space]
1939 // now the weird edge cases...
1941 // firefox and chromium both report zero width for characters at the end
1942 // of a line where the text wraps (automatically, due to word-wrap) to
1943 // the next line. These do not appear to be distinguishable from
1944 // collapsed spaces via the range/bounds api, so...
1946 // remove it from the dom, and if prev or next moves, put it back.
1948 // this block (try changing it, put it back if something moves) is also
1949 // used on collapsable whitespace characters besides space. In this case
1950 // the character is replaced with a normal space character instead of
1952 if ((prev != null) && (prev_px == null)) {
1953 prev_px = new_cursor_position({n: prev, i: prev_i})
1955 if ((next != null) && (next_px == null)) {
1956 next_px = new_cursor_position({n: next, i: next_i})
1958 //if prev is null and next is null
1959 // parent_px = cur.parent.el.getBoundingClientRect()
1960 undo_arg = true // just for readabality
1962 for (i = 0; i < fixers.length; i++) {
1970 if (prev_px != null) {
1971 new_prev_px = new_cursor_position({n: prev, i: prev_i})
1972 if (new_prev_px != null) {
1973 if (new_prev_px.x !== prev_px.x || new_prev_px.y !== prev_px.y) {
1980 console.log("this shouldn't happen, we remove spaces that don't locate")
1983 if ((next != null) && !need_undo) {
1984 if (next_px != null) {
1985 new_next_px = new_cursor_position({n: next, i: next_i})
1986 if (new_next_px != null) {
1987 if (new_next_px.x !== next_px.x || new_next_px.y !== next_px.y) {
1995 // console.log "removing space becase space after it is collapsed"
1998 removed += fixer(undo_arg)
2007 // pass null at start/end of display:block
2008 queue = function(n, i) {
2009 var advance, removed
2016 // don't advance (to the next character next time) if we removed a
2017 // character from the same text node as ``next``, because doing so
2018 // renumbers the indexes in that string
2019 if (removed && cur === next) {
2036 iterate(tree, queue)
2039 tree_remove_empty_text_nodes(tree)
2041 // call this after you insert or remove inline nodes. It will:
2042 // merge consecutive text nodes
2043 // remove empty text nodes
2044 // adjust white-space property
2045 // note: this assumes that all whitespace in text nodes should be displayed
2046 // (ie not collapse or be trimmed) and will change the white-space property
2047 // as needed to achieve this.
2048 PeachHTML5Editor.prototype.text_cleanup = function(n) {
2049 var block, eats_start_sp, i, last, n_i, need_preserve, prev, prev_i, run, ws
2050 if (this.is_display_block(n)) {
2053 block = this.find_block_parent(n)
2054 if (block == null) {
2058 run = this.get_text_run(block)
2062 // merge consecutive text elements
2063 if (run.length > 1) {
2066 while (i < run.length) {
2068 if (prev.type === 'text' && n.type === 'text') {
2069 if (prev.parent === n.parent) {
2070 prev_i = n.parent.children.indexOf(prev)
2071 n_i = n.parent.children.indexOf(n)
2072 if (n_i === prev_i + 1) {
2073 prev.text = prev.text + n.text
2074 prev.el.textContent = prev.text
2077 continue // don't increment i or change prev
2085 // remove empty text nodes
2087 while (i < run.length) {
2089 if (n.type === 'text') {
2090 if (n.text === '') {
2092 // FIXME maybe remove parents recursively if this makes them empty
2094 continue // don't increment i
2099 // note: inline tags can have white-space:pre-line/etc
2100 // note: inline-blocks have their whitespace collapsed independantly of outer run
2101 // note: inline-blocks are treated like non-whitespace char even if empty
2102 if (block.el.style.whiteSpace != null) {
2103 ws = block.el.style.whiteSpace
2105 if (ws_props[ws].space) {
2106 if (ws_props[ws].to_collapse === 'normal') {
2107 block.el.style.whiteSpace = null
2109 block.el.style.whiteSpace = ws_props[ws].to_collapse
2111 this.update_style_from_el(block)
2115 // note: space after <br> colapses, but not space before
2116 // check for spaces that would collapse without help
2117 eats_start_sp = true // if the next node starts with space it collapses (unless pre)
2119 for (i = 0; i < run.length; ++i) {
2121 if (n.type === 'tag') {
2122 if (n.name === 'br') {
2123 eats_start_sp = true
2125 eats_start_sp = false
2128 need_preserve = false
2129 if (n.type !== 'text') {
2130 console.log("bug #232308")
2133 if (eats_start_sp) {
2134 if (is_space_code(n.text.charCodeAt(0))) {
2135 need_preserve = true
2138 if (!need_preserve) {
2139 need_preserve = multi_sp_regex.test(n.text)
2141 if (need_preserve) {
2142 // do we have it already?
2143 ws = this.computed_style(n, 'white-space')
2144 if (ws_props[ws] != null ? !ws_props[ws].space : true) {
2145 // 2nd arg is ideal target for css rule
2146 ws = this.preserve_space(n, block)
2148 eats_start_sp = false
2150 if (is_space_code(n.text.charCodeAt(n.text.length - 1))) {
2151 ws = this.computed_style(n, 'white-space')
2152 if ((ref1 = ws_props[ws]) != null ? ref1.space : void 0) {
2153 eats_start_sp = false
2155 eats_start_sp = true
2158 eats_start_sp = false
2163 // check if text ends with a collapsable space
2164 if (run.length > 0) {
2165 last = run[run.length - 1]
2166 if (last.type === 'text') {
2167 if (eats_start_sp) {
2168 this.preserve_space(last, block)
2173 PeachHTML5Editor.prototype.css_clear = function(n, prop) {
2174 var css_delimiter_regex, i, styles
2175 if (n.attrs.style == null) {
2178 if (n.attrs.style === '') {
2181 css_delimiter_regex = new RegExp('\s*;\s*', 'g') // FIXME make this global
2182 styles = n.attrs.style.trim().split(css_delimiter)
2183 if (!(styles.length > 0)) {
2186 if (styles[styles.length - 1] === '') {
2188 if (!(styles.length > 0)) {
2193 while (i < styles.length) {
2194 if (styles[i].substr(0, 12) === 'white-space:') {
2201 // WARNING: after calling this one or more times, you MUST:
2202 // if it's inline: call @text_cleanup
2204 PeachHTML5Editor.prototype.remove_node = function(n) {
2206 i = n.parent.children.indexOf(n)
2208 throw "BUG #9187112313"
2210 n.el.parentNode.removeChild(n.el)
2211 n.parent.children.splice(i, 1)
2213 // remove a node from the tree/dom, insert into new_parent before insert_before?end
2214 // WARNING: after calling this one or more times, you MUST:
2215 // if it's inline: call @text_cleanup
2217 PeachHTML5Editor.prototype.move_node = function(n, new_parent, insert_before) {
2219 if (insert_before == null) {
2220 insert_before = null
2222 i = n.parent.children.indexOf(n)
2224 throw "Error: tried to remove node, but it's not in it's parents list of children"
2227 if (insert_before != null) {
2228 before_i = new_parent.children.indexOf(insert_before)
2230 throw "Error: tried to move a node to be before a non-existent node"
2232 insert_before = insert_before.el
2235 if (insert_before != null) {
2236 new_parent.el.insertBefore(n.el, insert_before)
2237 new_parent.children.splice(before_i, 0, n)
2239 new_parent.el.appendChild(n.el, insert_before)
2240 new_parent.children.push(n)
2242 n.parent = new_parent
2244 // remove it, forget where it was
2245 PeachHTML5Editor.prototype.kill_cursor = function() {
2246 if (this.cursor_visible) {
2247 this.cursor_el.parentNode.removeChild(this.cursor_el)
2248 this.cursor_visible = false
2253 PeachHTML5Editor.prototype.move_cursor = function(cursor) {
2255 this.cursor_ideal_x = cursor.x
2256 this.cursor = cursor
2257 if (!this.cursor_visible) {
2258 this.cursor_el = domify(this.outer_idoc, {div: { id: 'cursor'}})
2259 this.overlay.appendChild(this.cursor_el)
2260 this.cursor_visible = true
2262 this.cursor_el.style.left = (cursor.x + overlay_padding - 1) + "px"
2268 this.cursor_el.style.top = (cursor.y + overlay_padding + Math.round(height * .07)) + "px"
2269 this.cursor_el.style.height = (Math.round(height * 0.82)) + "px"
2270 this.annotate(cursor.n)
2271 this.scroll_into_view(cursor.y, height)
2273 PeachHTML5Editor.prototype.scroll_into_view = function(y, h) {
2274 var downmost, upmost
2278 y += overlay_padding // convert units from @idoc to @wrap2
2279 // very top of document
2280 if (y <= breathing_room) {
2281 this.wrap2.scrollTop = 0
2284 // very bottom of document
2285 if (y + h >= this.wrap2.scrollHeight - breathing_room) {
2286 this.wrap2.scrollTop = this.wrap2.scrollHeight - this.wrap2_height
2289 // The most scrolled up (lowest value for scrollTop) that would be OK
2290 upmost = y + h + breathing_room - this.wrap2_height
2291 upmost = Math.max(upmost, 0)
2292 // the most scrolled down (highest value for scrollTop) that would be OK
2293 downmost = y - breathing_room
2294 downmost = Math.min(downmost, this.wrap2.scrollHeight - this.wrap2_height)
2295 if (upmost > downmost) { // means h is too big to fit
2296 // scroll so top is visible
2297 this.wrap2.scrollTop = downmost
2300 if (this.wrap2.scrollTop < upmost) {
2301 this.wrap2.scrollTop = upmost
2304 if (this.wrap2.scrollTop > downmost) {
2305 this.wrap2.scrollTop = downmost
2309 PeachHTML5Editor.prototype.annotate = function(n) {
2310 var alpha, ann_box, ann_tag, bounds, prev_bounds
2311 while (this.matting.length > 0) {
2312 this.overlay.removeChild(this.matting[0])
2313 this.matting.shift()
2318 prev_bounds = {x: 0, y: 0, w: 0, h: 0}
2320 while (((n != null ? n.el : void 0) != null) && n !== this.tree_parent) {
2321 if (n.type === 'text') {
2325 bounds = get_el_bounds(n.el)
2326 if (bounds == null) {
2329 if (bounds.x === prev_bounds.x && bounds.y === prev_bounds.y && bounds.w === prev_bounds.w && bounds.h === prev_bounds.h) {
2333 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});
2334 this.overlay.appendChild(ann_box)
2335 this.matting.push(ann_box)
2336 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 + " "})]}})
2337 this.overlay.appendChild(ann_tag)
2338 this.matting.push(ann_tag)
2343 PeachHTML5Editor.prototype.pretty_html = function(tree, indent, parent_flags) {
2344 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
2345 if (indent == null) {
2348 if (parent_flags == null) {
2356 want_nl = parent_flags.want_nl
2357 prev_in_flow_is_text = false
2358 prev_in_flow_is_block = false
2359 for (i = 0; i < tree.length; ++i) {
2367 if (n.name === 'br') {
2371 if (n.el.currentStyle != null) {
2372 cs = n.el.currentStyle
2373 whitespace = cs['white-space']
2374 display = cs['display']
2375 position = cs['position']
2377 visibility = cs['visibility']
2379 cs = this.iframe.contentWindow.getComputedStyle(n.el, null)
2380 whitespace = cs.getPropertyValue('white-space')
2381 display = cs.getPropertyValue('display')
2382 position = cs.getPropertyValue('position')
2383 float = cs.getPropertyValue('float')
2384 visibility = cs.getPropertyValue('visibility')
2386 if (n.name === 'textarea') {
2387 inner_flags.pre_ish = true
2389 inner_flags.pre_ish = whitespace.substr(0, 3) === 'pre'
2403 if ('display' === 'none') {
2406 switch (visibility) {
2420 inner_flags.block = false
2421 is_block = in_flow_block = false
2423 case 'inline-black':
2424 inner_flags.block = true
2425 is_block = in_flow_block = false
2428 inner_flags.block = true
2430 in_flow_block = in_flow
2437 in_flow_block = false
2439 default: // 'comment', 'doctype'
2443 in_flow_block = false
2445 // print whitespace if we can
2446 if (!parent_flags.pre_ish) {
2447 if (!(prev_in_flow_is_text && is_br)) {
2448 if ((i === 0 && parent_flags.block) || in_flow_block || prev_in_flow_is_block) {
2460 for (k in n.attrs) {
2461 attr_keys.unshift(k)
2464 for (j = 0; j < attr_keys.length; ++j) {
2467 if (n.attrs[k].length > 0) {
2468 ret += "=\"" + (enc_attr(n.attrs[k])) + "\""
2472 if (void_elements[n.name] == null) {
2473 if (inner_flags.block) {
2474 next_indent = indent + ' '
2476 next_indent = indent
2478 if (n.children.length) {
2479 ret += this.pretty_html(n.children, next_indent, inner_flags)
2481 ret += "</" + n.name + ">"
2485 if (n.parent != null ? plaintext_elements[n.parent.name] : false) {
2487 } else if (n.parent != null ? newline_eating_elements[n.parent.name] && n.text.charAt(0) === "\n" : false) {
2488 ret += enc_text("\n" + n.text)
2490 ret += enc_text(n.text)
2494 ret += "<!--" + n.text + "-->" // TODO encode?
2497 ret += "<!DOCTYPE " + n.name
2498 if ((n.public_identifier != null) && n.public_identifier.length > 0) {
2499 ret += " \"" + n.public_identifier + "\""
2501 if ((n.system_identifier != null) && n.system_identifier.length > 0) {
2502 ret += " \"" + n.system_identifier + "\""
2508 prev_in_flow_is_text = is_text
2509 prev_in_flow_is_block = is_block || (in_flow && is_br)
2513 // output final newline if allowed
2514 if (!parent_flags.pre_ish) {
2515 if (prev_in_flow_is_block || parent_flags.block) {
2516 ret += "\n" + (indent.substr(4))
2522 PeachHTML5Editor.prototype.onblur = function() {
2523 this.editor_is_focused = false
2526 PeachHTML5Editor.prototype.have_focus = function() {
2527 if (!this.editor_is_focused) {
2528 this.input_el.focus()
2529 this.editor_is_focused = true
2533 window.peach_html5_editor = function() {
2534 // coffeescript: return new PeachHTML5Editor args...
2535 // compiles to below... there must be a better way
2537 args = 1 <= arguments.length ? slice.call(arguments, 0) : []
2538 return (function(func, args, ctor) {
2539 ctor.prototype = func.prototype
2540 var child = new ctor, result = func.apply(child, args)
2541 return Object(result) === result ? result : child
2542 })(PeachHTML5Editor, args, function(){})
2547 // test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])