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/>.
20 timeout = (ms, cb) -> return setTimeout cb, ms
22 if (window.requestAnimationFrame?)
23 window.requestAnimationFrame cb
27 this_url_sans_path = ->
28 ret = "#{window.location.href}"
29 clip = ret.lastIndexOf '#'
31 ret = ret.substr 0, clip
32 clip = ret.lastIndexOf '?'
34 ret = ret.substr 0, clip
35 clip = ret.lastIndexOf '/'
37 ret = ret.substr 0, clip + 1
40 # table too look up the properties of various values for css's white-space
43 space: false # spaces are not preserved/rendered
44 newline: false # newlines are not preserved/rendered
45 wrap: true # text is word-wrapped
46 to_preserve: 'pre-wrap' # to preservespaces, change white-space to this
56 to_preserve: 'pre-wrap'
66 # xml 1.0 spec, chromium and firefox accept these, plus lots of unicode chars
67 valid_attr_regex = new RegExp '^[a-zA-Z_:][-a-zA-Z0-9_:.]*$'
68 # html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
69 js_attr_regex = new RegExp '^[oO][nN].'
71 debug_dot_at = (doc, x, y) ->
73 el = doc.createElement 'div'
74 el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
75 doc.body.appendChild el
76 #console.log(new Error().stack)
78 # text nodes don't have getBoundingClientRect(), so use selection api to find
80 get_el_bounds = window.bounds = (el) ->
81 if el.getBoundingClientRect?
82 rect = el.getBoundingClientRect()
84 # text nodes don't have getBoundingClientRect(), so use range api
85 range = el.ownerDocument.createRange()
86 range.selectNodeContents el
87 rect = range.getBoundingClientRect()
88 doc = el.ownerDocument.documentElement
89 win = el.ownerDocument.defaultView
90 y_fix = win.pageYOffset - doc.clientTop
91 x_fix = win.pageXOffset - doc.clientLeft
95 w: rect.width ? (rect.right - rect.left)
96 h: rect.height ? (rect.top - rect.bottom)
99 is_display_block = (el) ->
101 return el.currentStyle.display is 'block'
103 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
105 # Pass return value from dom event handlers to this.
106 # If they return false, this will addinionally stop propagation and default.
107 event_return = (e, bool) ->
109 if e.stopPropagation?
114 # Warning: currently assumes you're asking about a single character
115 # Note: chromium returns multiple bounding rects for a space at a line-break
116 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
117 # Note: sometimes returns null (eg for whitespace that is not visible)
118 text_range_bounds = (el, start, end) ->
119 range = document.createRange()
120 range.setStart el, start
122 rects = range.getClientRects()
125 if rects[1].width > rects[0].width
133 doc = el.ownerDocument.documentElement
134 win = el.ownerDocument.defaultView
135 y_fix = win.pageYOffset - doc.clientTop
136 x_fix = win.pageXOffset - doc.clientLeft
140 w: rect.width ? (rect.right - rect.left)
141 h: rect.height ? (rect.top - rect.bottom)
143 bounding: range.getBoundingClientRect()
147 constructor: (args) ->
158 range = document.createRange()
159 if @n.text.length is 0
160 ret = text_range_bounds @n.el, 0, 0
161 else if @i is @n.text.length
162 ret = text_range_bounds @n.el, @i - 1, @i
166 ret = text_range_bounds @n.el, @i, @i + 1
177 new_cursor_position = (args) ->
178 ret = new CursorPosition args
183 # encode text so it can be safely placed inside an html attribute
184 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
186 return txt.replace enc_attr_regex, (match, amp, quote) ->
187 return '&' if (amp)
188 return '"' if (quote)
190 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
192 return txt.replace enc_text_regex, (match, amp, lt) ->
193 return '&' if (amp)
194 return '<' if (lt)
214 # TODO make these always pretty-print (on the inside) like blocks
215 no_text_elements = { # these elements never contain text
225 domify = (doc, hash) ->
226 for tag, attrs of hash
228 return document.createTextNode attrs
229 el = document.createElement tag
238 outer_css = (args) ->
241 inner_padding = args.inner_padding ? overlay_padding
242 frame_width = args.frame_width ? inner_padding
243 # TODO editor controls height...
244 occupy = (left, top = left, right = left, bottom = top) ->
247 return Math.max(left, top, right, bottom)
252 ret += 'color: black;'
253 ret += 'background: white;'
256 ret += "border: #{occupy 1}px solid black;"
257 ret += "padding: #{occupy frame_width}px;"
260 ret += "border: #{occupy 1}px solid black;"
261 ret += "padding: #{occupy inner_padding}px;"
262 ret += "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
263 ret += "width: #{w}px;"
264 ret += "height: #{h}px;"
265 ret += 'overflow-x: hidden;'
266 ret += 'overflow-y: scroll;'
269 ret += 'position: relative;'
270 ret += "width: #{w}px;"
271 ret += "min-height: #{h}px;"
274 ret += 'box-sizing: border-box;'
276 ret += 'border: none;'
278 ret += "width: #{w}px;"
279 #ret += "height: #{h}px;" # height auto-set when content set/changed
280 ret += '-ms-user-select: none;'
281 ret += '-webkit-user-select: none;'
282 ret += '-moz-user-select: none;'
283 ret += 'user-select: none;'
286 ret += 'position: absolute;'
287 ret += "left: -#{inner_padding}px;"
288 ret += "top: -#{inner_padding}px;"
289 ret += "right: -#{inner_padding}px;"
290 ret += "bottom: -#{inner_padding}px;"
291 ret += 'overflow: hidden;'
294 ret += 'position: absolute;'
295 ret += 'background: rgba(100,100,100,0.2);'
298 ret += 'position: absolute;'
300 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));'
301 ret += 'background-size: 200% 200%;'
302 ret += '-webkit-animation: blink 1s linear normal infinite;'
303 ret += 'animation: blink 1s linear normal infinite;'
305 ret += '@-webkit-keyframes blink {'
306 ret += '0%{background-position:0% 0%}'
307 ret += '100%{background-position:0% -100%}'
309 ret += '@keyframes blink { '
310 ret += '0%{background-position:0% 0%}'
311 ret += '100%{background-position:0% -100%}'
315 ret += 'position: absolute;'
316 ret += 'border: 1px solid rgba(0,0,0,0.1);'
317 ret += 'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
320 ret += 'z-index: 10;'
321 ret += 'position: absolute;'
322 ret += 'font-size: 8px;'
323 ret += 'white-space: pre;'
324 ret += 'background: rgba(255,255,255,0.4);'
325 ret += '-ms-user-select: none;'
326 ret += '-webkit-user-select: none;'
327 ret += '-moz-user-select: none;'
328 ret += 'user-select: none;'
335 '20': true # capslock
337 '144': true # numlock
339 '91': true # windows "start" key
340 # key codes: (valid on keydown, not keypress)
345 KEY_BACKSPACE = 8 # <--
346 KEY_DELETE = 46 # -->
355 control_key_codes = # we react to these, but they aren't typing
371 instantiate_tree = (tree, parent) ->
376 c.el = parent.ownerDocument.createTextNode c.text
377 parent.appendChild c.el
379 if c.name in ['script', 'object', 'iframe', 'link']
380 # TODO put placeholders instead
383 # TODO create in correct namespace
384 c.el = parent.ownerDocument.createElement c.name
386 # FIXME if attr_whitelist[k]?
387 if valid_attr_regex.test k
388 unless js_attr_regex.test k
389 c.el.setAttribute k, v
390 parent.appendChild c.el
392 instantiate_tree c.children, c.el
396 traverse_tree = (tree, cb) ->
402 done = traverse_tree c.children, cb
406 first_cursor_position = (tree) ->
408 traverse_tree tree, (node, state) ->
409 if node.type is 'text'
410 cursor = new_cursor_position n: node, i: 0
415 return found # maybe null
417 # this will fail when text has non-locatable cursor positions
418 find_next_cursor_position = (tree, cursor) ->
419 if cursor.n.type is 'text' and cursor.n.text.length > cursor.i
420 new_cursor = new_cursor_position n: cursor.n, i: cursor.i + 1
425 traverse_tree tree, (node, state) ->
426 if node.type is 'text' and state_before is false
427 new_cursor = new_cursor_position n: node, i: 0
438 last_cursor_position = (tree) ->
440 traverse_tree tree, (node) ->
441 if node.type is 'text'
442 cursor = new_cursor_position n: node, i: node.text.length
446 return found # maybe null
448 # this will fail when text has non-locatable cursor positions
449 find_prev_cursor_position = (tree, cursor) ->
450 if cursor.n.type is 'text' and cursor.i > 0
451 new_cursor = new_cursor_position n: cursor.n, i: cursor.i - 1
456 traverse_tree tree, (node) ->
458 found = found_prev # maybe null
460 if node.type is 'text'
461 new_cursor = new_cursor_position n: node, i: node.text.length
463 found_prev = new_cursor
465 return found # maybe null
467 xy_to_cursor = (tree, xy) ->
469 if n.type is 'tag' or n.type is 'text'
470 bounds = get_el_bounds n.el
471 continue if xy.x < bounds.x
472 continue if xy.x > bounds.x + bounds.w
473 continue if xy.y < bounds.y
474 continue if xy.y > bounds.y + bounds.h
476 ret = xy_to_cursor n.children, xy
479 # click is within bounding box that contains all text.
480 if n.text.length is 0
481 ret = new_cursor_position n: n, i: 0
484 before = new_cursor_position n: n, i: 0
485 continue unless before?
486 after = new_cursor_position n: n, i: n.text.length
487 continue unless after?
488 if xy.y < before.y + before.h and xy.x < before.x
489 # console.log 'before first char on first line'
491 if xy.y > after.y and xy.x > after.x
492 # console.log 'after last char on last line'
495 console.log "Warning: click in text bounding box but above first line"
496 continue # above first line (runaround?)
497 if xy.y > after.y + after.h
498 console.log "Warning: click in text bounding box but below last line", xy.y, after.y, after.h
499 continue # below last line (shouldn't happen?)
500 while after.i - before.i > 1
501 guess_i = Math.round((before.i + after.i) / 2)
502 cur = new_cursor_position n: n, i: guess_i
504 console.log "error: failed to find cursor pixel location for", n, guess_i
507 if xy.y < cur.y or (xy.y <= cur.y + cur.h and xy.x < cur.x)
511 continue unless before? # signals failure to find a cursor position
512 # which one is closest?
513 if Math.abs(before.x - xy.x) < Math.abs(after.x - xy.x)
519 # browsers collapse these (html5 spec calls these "space characters")
520 is_space_code = (char_code) ->
522 when 9, 10, 12, 13, 32
526 return is_space_code chr.charCodeAt 0
528 tree_remove_empty_text_nodes = (tree) ->
530 traverse_tree tree, (n) ->
532 if n.text.length is 0
536 # don't completely empty the tree
538 if tree[0].type is 'text'
539 console.log "oop, leaving a blank node because it's the only thing"
541 n.el.parentNode.removeChild n.el
542 for c, i in n.parent.children
544 n.parent.children.splice i, 1
547 # pass a array of nodes (from parser library, ie it should have .el and .text)
548 tree_dedup_space = (tree) ->
549 prev = cur = next = null
550 prev_i = cur_i = next_i = 0
551 prev_pos = pos = next_pos = null
552 prev_px = cur_px = next_px = null
556 tree_remove_empty_text_nodes(tree)
558 iterate = (tree, cb) ->
562 while i < n.text.length # don't foreach, cb might remove chars
567 block = is_display_block n.el
570 if n.children.length > 0
571 iterate n.children, cb
577 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
578 if next is cur # in same text node
582 removed_char = cur.text.charAt(cur_i)
583 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
584 if next is cur # in same text node
586 throw "how is this possible?"
589 whitespace_to_space = (undo) ->
591 cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i + 1)
592 cur.el.textContent = cur.text
594 removed_char = cur.text.charAt(cur_i)
595 cur.text = (cur.text.substr 0, cur_i) + ' ' + (cur.text.substr cur_i + 1)
596 cur.el.textContent = cur.text
598 # return true if cur was removed from the dom (ie re-use same prev)
600 # cur definitately set
601 # prev and/or next might be null, indicating the start/end of a display:block
602 return false unless is_space_code cur.text.charCodeAt cur_i
603 fixers = [remove, whitespace_to_space]
604 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
606 # 1. zero rects returned by getClientRects() means collapsed space
609 # 2. width greater than zero means visible space
611 fixers.shift() # don't try removing
612 # now the weird edge cases...
614 # firefox and chromium both report zero width for characters at the end
615 # of a line where the text wraps (automatically, due to word-wrap) to
616 # the next line. These do not appear to be distinguishable from
617 # collapsed spaces via the range/bounds api, so...
619 # remove it from the dom, and if prev or next moves, put it back.
620 if prev? and not prev_px?
621 prev_px = new_cursor_position n: prev, i: prev_i
622 if next? and not next_px?
623 next_px = new_cursor_position n: next, i: next_i
624 #if prev is null and next is null
625 # parent_px = cur.parent.el.getBoundingClientRect()
626 undo_arg = true # just for readabality
634 new_prev_px = new_cursor_position n: prev, i: prev_i
636 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
641 console.log "this shouldn't happen, we remove spaces that don't locate"
642 if next? and not need_undo
644 new_next_px = new_cursor_position n: next, i: next_i
646 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
651 # console.log "removing space becase space after it is collapsed"
653 removed += fixer undo_arg
658 # pass null at start/end of display:block
666 # don't advance (to the next character next time) if we removed a
667 # character from the same text node as ``next``, because doing so
668 # renumbers the indexes in that string
669 if removed and cur is next
685 tree_remove_empty_text_nodes(tree)
687 class PeachHTML5Editor
688 # Options: (all optional)
689 # editor_id: "id" attribute for outer-most element created by/for editor
690 # css_file: filename of a css file to style editable content
691 # on_init: callback for when the editable content is in place
692 constructor: (in_el, options) ->
693 @options = options ? {}
697 @init_1_called = false # when iframes have loaded
698 @outer_iframe # iframe to hold editor
699 @outer_idoc # "document" object for @outer_iframe
700 @wrap2 = null # scrollbar is on this
701 @iframe = null # iframe to hold editable content
702 @idoc = null # "document" object for @iframe
705 @cursor_visible = false
706 @poll_for_blur_timeout = null
708 @iframe_height = null
709 opt_fragment = @options.fragment ? true
712 @parser_opts.fragment = 'body'
714 @outer_iframe = domify document, iframe: {}
715 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
716 if @options.editor_id?
717 @outer_iframe.setAttribute 'id', @options.editor_id
718 @outer_iframe.onload = =>
719 @outer_idoc = @outer_iframe.contentDocument
720 icss = domify @outer_idoc, style: children: [
721 domify @outer_idoc, text: css
723 @outer_idoc.head.appendChild icss
724 @iframe = domify @outer_idoc, iframe: sandbox: 'allow-same-origin allow-scripts'
727 timeout 200, => # firefox never fires this onload
728 @init_1() unless @init_1_called
729 @outer_idoc.body.appendChild(
730 domify @outer_idoc, div: id: 'wrap1', children: [
731 domify @outer_idoc, div: style: "position: absolute; top: 0; left: 1px; font-size: 10px", children: [ domify @outer_idoc, text: "Peach HTML5 Editor" ]
732 @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
733 domify @outer_idoc, div: id: 'wrap3', children: [
735 @overlay = domify @outer_idoc, div: id: 'overlay'
740 outer_wrap = domify document, div: class: 'peach_html5_editor'
741 @in_el.parentNode.appendChild outer_wrap
742 outer_bounds = get_el_bounds outer_wrap
743 if outer_bounds.w < 300
745 if outer_bounds.h < 300
747 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
748 @outer_iframe.setAttribute 'style', outer_iframe_style
749 css = outer_css w: outer_bounds.w, h: outer_bounds.h
750 outer_wrap.appendChild @outer_iframe
751 init_1: -> # @iframe has loaded (but not it's css)
752 @idoc = @iframe.contentDocument
753 @init_1_called = true
754 # chromium doesn't resolve relative urls as though they were at the same domain
755 # so add a <base> tag
756 @idoc.head.appendChild domify @idoc, base: href: this_url_sans_path()
757 # don't let @iframe have scrollbars
758 @idoc.head.appendChild domify @idoc, style: children: [domify @idoc, text: "body { overflow: hidden; }"]
761 istyle = domify @idoc, link: rel: 'stylesheet', href: @options.css_file
764 @idoc.head.appendChild istyle
767 init_2: -> # @iframe and it's css file(s) are ready
768 @overlay.onclick = (e) =>
770 return event_return e, @onclick e
771 @overlay.ondoubleclick = (e) =>
773 return event_return e, @ondoubleclick e
774 @outer_idoc.body.onkeyup = (e) =>
776 return event_return e, @onkeyup e
777 @outer_idoc.body.onkeydown = (e) =>
779 return event_return e, @onkeydown e
780 @outer_idoc.body.onkeypress = (e) =>
782 return event_return e, @onkeypress e
783 @load_html @in_el.value
786 overlay_event_to_inner_xy: (e) ->
787 unless @wrap2_offset?
788 @wrap2_offset = get_el_bounds @wrap2
789 x = e.pageX - overlay_padding
790 y = e.pageY - overlay_padding + @wrap2.scrollTop
791 return x: x - @wrap2_offset.x, y: y - @wrap2_offset.y
793 xy = @overlay_event_to_inner_xy e
794 new_cursor = xy_to_cursor @tree, xy
796 @move_cursor new_cursor
800 ondoubleclick: (e) ->
804 return false if ignore_key_codes[e.keyCode]?
805 #return false if control_key_codes[e.keyCode]?
808 return false if ignore_key_codes[e.keyCode]?
809 #return false if control_key_codes[e.keyCode]?
813 new_cursor = find_prev_cursor_position @tree, @cursor
815 new_cursor = first_cursor_position @tree
817 @move_cursor new_cursor
821 new_cursor = find_next_cursor_position @tree, @cursor
823 new_cursor = last_cursor_position @tree
825 @move_cursor new_cursor
830 # go prev until we're higher on y axis
831 while new_cursor.y >= @cursor.y
832 new_cursor = find_prev_cursor_position @tree, new_cursor
833 return false unless new_cursor?
834 # done early if we're already left of old cursor position
835 if new_cursor.x <= @cursor.x
836 @move_cursor new_cursor
838 target_y = new_cursor.y
839 # search leftward, until we find the closest position
840 # new_cursor is the prev-most position we've checked
841 # prev_cursor is the older value, so it's not as prev as new_cursor
842 while new_cursor.x > @cursor.x and new_cursor.y is target_y
843 prev_cursor = new_cursor
844 new_cursor = find_prev_cursor_position @tree, new_cursor
845 break unless new_cursor?
846 # move cursor to prev_cursor or new_cursor
848 if new_cursor.y is target_y
849 # both valid, and on the same line, use closest
850 if (@cursor.x - new_cursor.x) < (prev_cursor.x - @cursor.x)
851 @move_cursor new_cursor
853 @move_cursor prev_cursor
855 # new_cursor on wrong line, use prev_cursor
856 @move_cursor prev_cursor
858 # can't go any further prev, use prev_cursor
859 @move_cursor prev_cursor
861 # move cursor to first position in document
862 new_cursor = first_cursor_position @tree
864 @move_cursor new_cursor
869 # go next until we move on the y axis
870 while new_cursor.y <= @cursor.y
871 new_cursor = find_next_cursor_position @tree, new_cursor
872 return false unless new_cursor?
873 # done early if we're already right of old cursor position
874 if new_cursor.x >= @cursor.x
875 # this would be strange, but could happen due to runaround
876 @move_cursor new_cursor
878 target_y = new_cursor.y
879 # search rightward, until we find the closest position
880 # new_cursor is the next-most position we've checked
881 # prev_cursor is the older value, so it's not as next as new_cursor
882 while new_cursor.x < @cursor.x and new_cursor.y is target_y
883 prev_cursor = new_cursor
884 new_cursor = find_next_cursor_position @tree, new_cursor
885 break unless new_cursor?
886 # move cursor to prev_cursor or new_cursor
888 if new_cursor.y is target_y
889 # both valid, and on the same line, use closest
890 if (new_cursor.x - @cursor.x) < (@cursor.x - prev_cursor.x)
891 @move_cursor new_cursor
893 @move_cursor prev_cursor
895 # new_cursor on wrong line, use prev_cursor
896 @move_cursor prev_cursor
898 # can't go any further prev, use prev_cursor
899 @move_cursor prev_cursor
901 # move cursor to first position in document
902 new_cursor = last_cursor_position @tree
904 @move_cursor new_cursor
909 return false unless @cursor?
910 return false unless @cursor.i > 0
911 @remove_character @cursor.n, @cursor.i - 1
912 @adjust_whitespace_style @cursor.n
914 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i - 1
916 @move_cursor new_cursor
921 return false unless @cursor?
922 return false unless @cursor.i < @cursor.n.text.length
923 @remove_character @cursor.n, @cursor.i
924 @adjust_whitespace_style @cursor.n
926 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i
928 @move_cursor new_cursor
948 return false if ignore_key_codes[e.keyCode]?
949 char = e.charCode ? e.keyCode
951 char = String.fromCharCode char
952 @insert_character @cursor.n, @cursor.i, char
953 @adjust_whitespace_style @cursor.n
955 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i + 1
957 @move_cursor new_cursor
959 console.log "ERROR: couldn't find cursor position after insert"
962 clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
963 while @idoc.body.childNodes.length
964 @idoc.body.removeChild @idoc.body.childNodes[0]
968 @tree = peach_parser.parse html, @parser_opts
970 instantiate_tree @tree, @idoc.body
971 tree_dedup_space @tree
974 @in_el.onchange = null
975 @in_el.value = @pretty_html @tree
977 @load_html @in_el.value
978 @adjust_iframe_height()
979 adjust_iframe_height: ->
980 h = parseInt(@idoc.body.scrollHeight, 10)
981 if @iframe_height isnt h
984 @iframe.style.height = "0"
985 @iframe.style.height = "#{h}px"
987 # does this node have whitespace that would be collapsed by white-space: normal?
988 # note: this checks direct text children, and does _not_ recurse into child tags
989 # tag is a node with type:"tag"
990 has_collapsable_space: (tag) ->
991 for n in tag.children
993 for i in [0...n.text.length]
994 code = n.text.charCodeAt i
995 if code isnt 32 and is_space_code code
998 # check for double spaces that don't surround insert location
1000 if n.text.substr(i - 1, 2) is ' '
1002 if n.text.length > 0
1003 if is_space_code n.text.charCodeAt 0
1005 if is_space_code n.text.charCodeAt n.text.length - 1
1007 # add/remove "white-space: pre[-wrap]" to/from style="" on tags with direct
1008 # child text nodes with multiple spaces in a row, or spaces at the
1011 # text inside child tags are not consulted. Child tags are expected to have
1012 # this function applied to them when their content changes.
1013 adjust_whitespace_style: (n) ->
1016 return unless n?.el?
1017 # which css rule should be used to preserve spaces (should we need to)
1018 style = @iframe.contentWindow.getComputedStyle n.el, null
1019 ws = style.getPropertyValue 'white-space'
1020 if ws_props[ws].space
1023 preserve_rule = ws_props[ws].to_preserve
1024 preserve_rule = "white-space: #{preserve_rule}"
1025 if @has_collapsable_space n
1026 # make sure preserve_rule exists
1027 if n.el.style['white-space']
1028 # FIXME check that it matches
1031 n.attrs.style += "; #{preserve_rule}"
1033 n.attrs.style = preserve_rule
1034 n.el.setAttribute 'style', n.attrs.style
1036 # remove preserve_rule if it exists
1037 return unless n.attrs.style?
1038 # FIXME don't assume whitespace is just so
1039 if n.attrs.style is "white-space: #{ws}"
1040 delete n.attrs.style
1041 n.el.removeAttribute 'style'
1043 # FIXME find it in the middle and at the start
1044 needle = "; white-space: #{ws}"
1045 if needle is n.attrs.style.substr n.attrs.style.length - needle
1046 n.attrs.style = n.attrs.style.substr 0, n.attrs.style.length - needle
1047 n.el.setAttribute n.attrs.style
1048 # after calling this, you MUST call changed() and adjust_whitespace_style()
1049 insert_character: (n, i, char) ->
1050 parent = @cursor.n.parent
1051 return unless parent
1052 return unless parent.el?
1053 # insert the character
1055 n.text = char + n.text
1056 else if i is n.text.length
1060 n.text.substr(0, i) +
1063 n.el.nodeValue = n.text
1064 # after calling this, you MUST call changed() and adjust_whitespace_style()
1065 remove_character: (n, i) ->
1066 n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1067 n.el.nodeValue = n.text
1068 kill_cursor: -> # remove it, forget where it was
1070 @cursor_el.parentNode.removeChild @cursor_el
1071 @cursor_visible = false
1074 move_cursor: (cursor) ->
1076 unless @cursor_visible
1077 @cursor_el = domify @outer_idoc, div: id: 'cursor'
1078 @overlay.appendChild @cursor_el
1079 @cursor_visible = true
1080 @cursor_el.style.left = "#{cursor.x + overlay_padding - 1}px"
1085 @cursor_el.style.top = "#{cursor.y + overlay_padding + Math.round(height * .07)}px"
1086 @cursor_el.style.height = "#{Math.round height * 0.82}px"
1089 while @matting.length > 0
1090 @overlay.removeChild @matting[0]
1093 prev_bounds = x: 0, y: 0, w: 0, h: 0
1099 bounds = get_el_bounds n.el
1100 return unless bounds?
1101 if bounds.x is prev_bounds.x and bounds.y is prev_bounds.y and bounds.w is prev_bounds.w and bounds.h is prev_bounds.h
1104 ann_box = domify @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});
1105 @overlay.appendChild ann_box
1106 @matting.push ann_box
1107 ann_tag = domify @outer_idoc, div: class: 'ann_tag', style: "left: #{bounds.x + 1 + overlay_padding}px; top: #{bounds.y - 7 + overlay_padding}px", children: [domify @outer_idoc, text: " #{n.name} "]
1108 @overlay.appendChild ann_tag
1109 @matting.push ann_tag
1112 pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
1114 want_nl = parent_flags.want_nl
1115 prev_in_flow_is_text = false
1116 prev_in_flow_is_block = false
1119 inner_flags = want_nl: true
1126 if n.el.currentStyle?
1127 cs = n.el.currentStyle
1128 whitespace = cs['white-space']
1129 display = cs['display']
1130 position = cs['position']
1132 visibility = cs['visibility']
1134 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
1135 whitespace = cs.getPropertyValue 'white-space'
1136 display = cs.getPropertyValue 'display'
1137 position = cs.getPropertyValue 'position'
1138 float = cs.getPropertyValue 'float'
1139 visibility = cs.getPropertyValue 'visibility'
1140 if n.name is 'textarea'
1141 inner_flags.pre_ish = true
1143 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
1145 when 'left', 'right'
1149 when 'absolute', 'fixed'
1152 if 'display' is 'none'
1156 when 'hidden', 'collapse'
1161 when 'inline', 'none'
1162 inner_flags.block = false
1163 is_block = in_flow_block = false
1165 inner_flags.block = true
1166 is_block = in_flow_block = false
1167 else # block, table, etc
1168 inner_flags.block = true
1170 in_flow_block = in_flow
1175 in_flow_block = false
1176 else # 'comment', 'doctype'
1180 in_flow_block = false
1181 # print whitespace if we can
1182 unless parent_flags.pre_ish
1183 unless prev_in_flow_is_text and is_br
1184 if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
1197 if n.attrs[k].length > 0
1198 ret += "=\"#{enc_attr n.attrs[k]}\""
1200 unless void_elements[n.name]?
1201 if inner_flags.block
1202 next_indent = indent + ' '
1204 next_indent = indent
1205 if n.children.length
1206 ret += @pretty_html n.children, next_indent, inner_flags
1207 ret += "</#{n.name}>"
1209 ret += enc_text n.text
1211 ret += "<!--#{n.text}-->" # TODO encode?
1213 ret += "<!DOCTYPE #{n.name}"
1214 if n.public_identifier? and n.public_identifier.length > 0
1215 ret += " \"#{n.public_identifier}\""
1216 if n.system_identifier? and n.system_identifier.length > 0
1217 ret += " \"#{n.system_identifier}\""
1221 prev_in_flow_is_text = is_text
1222 prev_in_flow_is_block = is_block or (in_flow and is_br)
1224 # output final newline if allowed
1225 unless parent_flags.pre_ish
1226 if prev_in_flow_is_block or parent_flags.block
1227 ret += "\n#{indent.substr 4}"
1232 @editor_is_focused = true
1235 return if @poll_for_blur_timeout? # already polling
1236 @poll_for_blur_timeout = timeout 150, =>
1237 next_frame => # pause polling when browser knows we're not active/visible/etc.
1238 @poll_for_blur_timeout = null
1239 if document.activeElement is @outer_iframe
1242 @editor_is_focused = false
1245 window.peach_html5_editor = (args...) ->
1246 return new PeachHTML5Editor args...
1248 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])