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
242 '20': true # capslock
244 '144': true # numlock
246 '91': true # windows "start" key
247 # key codes: (valid on keydown, not keypress)
252 KEY_BACKSPACE = 8 # <--
253 KEY_DELETE = 46 # -->
262 control_key_codes = # we react to these, but they aren't typing
278 instantiate_tree = (tree, parent) ->
283 c.el = parent.ownerDocument.createTextNode c.text
284 parent.appendChild c.el
286 if c.name in ['script', 'object', 'iframe', 'link']
287 # TODO put placeholders instead
290 # TODO create in correct namespace
291 c.el = parent.ownerDocument.createElement c.name
293 # FIXME if attr_whitelist[k]?
294 if valid_attr_regex.test k
295 unless js_attr_regex.test k
296 c.el.setAttribute k, v
297 parent.appendChild c.el
299 instantiate_tree c.children, c.el
303 traverse_tree = (tree, cb) ->
309 done = traverse_tree c.children, cb
313 first_cursor_position = (tree) ->
315 traverse_tree tree, (node, state) ->
316 if node.type is 'text'
317 cursor = new_cursor_position n: node, i: 0
322 return found # maybe null
324 # this will fail when text has non-locatable cursor positions
325 find_next_cursor_position = (tree, cursor) ->
326 if cursor.n.type is 'text' and cursor.n.text.length > cursor.i
327 new_cursor = new_cursor_position n: cursor.n, i: cursor.i + 1
332 traverse_tree tree, (node, state) ->
333 if node.type is 'text' and state_before is false
334 new_cursor = new_cursor_position n: node, i: 0
345 last_cursor_position = (tree) ->
347 traverse_tree tree, (node) ->
348 if node.type is 'text'
349 cursor = new_cursor_position n: node, i: node.text.length
353 return found # maybe null
355 # this will fail when text has non-locatable cursor positions
356 find_prev_cursor_position = (tree, cursor) ->
357 if cursor.n.type is 'text' and cursor.i > 0
358 new_cursor = new_cursor_position n: cursor.n, i: cursor.i - 1
363 traverse_tree tree, (node) ->
365 found = found_prev # maybe null
367 if node.type is 'text'
368 new_cursor = new_cursor_position n: node, i: node.text.length
370 found_prev = new_cursor
372 return found # maybe null
374 find_up_cursor_position = (tree, cursor, ideal_x) ->
376 # go prev until we're higher on y axis
377 while new_cursor.y >= cursor.y
378 new_cursor = find_prev_cursor_position tree, new_cursor
379 return null unless new_cursor?
380 # done early if we're already left of old cursor position
381 if new_cursor.x <= ideal_x
383 target_y = new_cursor.y
384 # search leftward, until we find the closest position
385 # new_cursor is the prev-most position we've checked
386 # prev_cursor is the older value, so it's not as prev as new_cursor
387 while new_cursor.x > ideal_x and new_cursor.y is target_y
388 prev_cursor = new_cursor
389 new_cursor = find_prev_cursor_position tree, new_cursor
390 break unless new_cursor?
391 # move cursor to prev_cursor or new_cursor
393 if new_cursor.y is target_y
394 # both valid, and on the same line, use closest
395 if (ideal_x - new_cursor.x) < (prev_cursor.x - ideal_x)
400 # new_cursor on wrong line, use prev_cursor
403 # can't go any further prev, use prev_cursor
406 find_down_cursor_position = (tree, cursor, ideal_x) ->
408 # go next until we move on the y axis
409 while new_cursor.y <= cursor.y
410 new_cursor = find_next_cursor_position tree, new_cursor
411 return null unless new_cursor?
412 # done early if we're already right of old cursor position
413 if new_cursor.x >= ideal_x
414 # this would be strange, but could happen due to runaround
416 target_y = new_cursor.y
417 # search rightward, until we find the closest position
418 # new_cursor is the next-most position we've checked
419 # prev_cursor is the older value, so it's not as next as new_cursor
420 while new_cursor.x < ideal_x and new_cursor.y is target_y
421 prev_cursor = new_cursor
422 new_cursor = find_next_cursor_position tree, new_cursor
423 break unless new_cursor?
424 # move cursor to prev_cursor or new_cursor
426 if new_cursor.y is target_y
427 # both valid, and on the same line, use closest
428 if (new_cursor.x - ideal_x) < (ideal_x - prev_cursor.x)
433 # new_cursor on wrong line, use prev_cursor
436 # can't go any further prev, use prev_cursor
439 xy_to_cursor = (tree, xy) ->
441 if n.type is 'tag' or n.type is 'text'
442 bounds = get_el_bounds n.el
443 continue if xy.x < bounds.x
444 continue if xy.x > bounds.x + bounds.w
445 continue if xy.y < bounds.y
446 continue if xy.y > bounds.y + bounds.h
448 ret = xy_to_cursor n.children, xy
451 # click is within bounding box that contains all text.
452 if n.text.length is 0
453 ret = new_cursor_position n: n, i: 0
456 before = new_cursor_position n: n, i: 0
457 continue unless before?
458 after = new_cursor_position n: n, i: n.text.length
459 continue unless after?
460 if xy.y < before.y + before.h and xy.x < before.x
461 # console.log 'before first char on first line'
463 if xy.y > after.y and xy.x > after.x
464 # console.log 'after last char on last line'
467 console.log "Warning: click in text bounding box but above first line"
468 continue # above first line (runaround?)
469 if xy.y > after.y + after.h
470 console.log "Warning: click in text bounding box but below last line", xy.y, after.y, after.h
471 continue # below last line (shouldn't happen?)
472 while after.i - before.i > 1
473 guess_i = Math.round((before.i + after.i) / 2)
474 cur = new_cursor_position n: n, i: guess_i
476 console.log "error: failed to find cursor pixel location for", n, guess_i
479 if xy.y < cur.y or (xy.y <= cur.y + cur.h and xy.x < cur.x)
483 continue unless before? # signals failure to find a cursor position
484 # which one is closest?
485 if Math.abs(before.x - xy.x) < Math.abs(after.x - xy.x)
491 # browsers collapse these (html5 spec calls these "space characters")
492 is_space_code = (char_code) ->
494 when 9, 10, 12, 13, 32
498 return is_space_code chr.charCodeAt 0
500 tree_remove_empty_text_nodes = (tree) ->
502 traverse_tree tree, (n) ->
504 if n.text.length is 0
508 # don't completely empty the tree
510 if tree[0].type is 'text'
511 console.log "oop, leaving a blank node because it's the only thing"
513 n.el.parentNode.removeChild n.el
514 for c, i in n.parent.children
516 n.parent.children.splice i, 1
519 # pass a array of nodes (from parser library, ie it should have .el and .text)
520 tree_dedup_space = (tree) ->
521 prev = cur = next = null
522 prev_i = cur_i = next_i = 0
523 prev_pos = pos = next_pos = null
524 prev_px = cur_px = next_px = null
528 tree_remove_empty_text_nodes(tree)
530 iterate = (tree, cb) ->
534 while i < n.text.length # don't foreach, cb might remove chars
539 block = is_display_block n.el
542 if n.children.length > 0
543 iterate n.children, cb
549 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
550 if next is cur # in same text node
554 removed_char = cur.text.charAt(cur_i)
555 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
556 if next is cur # in same text node
558 throw "how is this possible?"
561 whitespace_to_space = (undo) ->
563 cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i + 1)
564 cur.el.textContent = cur.text
566 removed_char = cur.text.charAt(cur_i)
567 cur.text = (cur.text.substr 0, cur_i) + ' ' + (cur.text.substr cur_i + 1)
568 cur.el.textContent = cur.text
570 # return true if cur was removed from the dom (ie re-use same prev)
572 # cur definitately set
573 # prev and/or next might be null, indicating the start/end of a display:block
574 return false unless is_space_code cur.text.charCodeAt cur_i
575 fixers = [remove, whitespace_to_space]
576 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
578 # 1. zero rects returned by getClientRects() means collapsed space
581 # 2. width greater than zero means visible space
583 fixers.shift() # don't try removing
584 # now the weird edge cases...
586 # firefox and chromium both report zero width for characters at the end
587 # of a line where the text wraps (automatically, due to word-wrap) to
588 # the next line. These do not appear to be distinguishable from
589 # collapsed spaces via the range/bounds api, so...
591 # remove it from the dom, and if prev or next moves, put it back.
592 if prev? and not prev_px?
593 prev_px = new_cursor_position n: prev, i: prev_i
594 if next? and not next_px?
595 next_px = new_cursor_position n: next, i: next_i
596 #if prev is null and next is null
597 # parent_px = cur.parent.el.getBoundingClientRect()
598 undo_arg = true # just for readabality
606 new_prev_px = new_cursor_position n: prev, i: prev_i
608 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
613 console.log "this shouldn't happen, we remove spaces that don't locate"
614 if next? and not need_undo
616 new_next_px = new_cursor_position n: next, i: next_i
618 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
623 # console.log "removing space becase space after it is collapsed"
625 removed += fixer undo_arg
630 # pass null at start/end of display:block
638 # don't advance (to the next character next time) if we removed a
639 # character from the same text node as ``next``, because doing so
640 # renumbers the indexes in that string
641 if removed and cur is next
657 tree_remove_empty_text_nodes(tree)
659 class PeachHTML5Editor
660 # Options: (all optional)
661 # editor_id: "id" attribute for outer-most element created by/for editor
662 # css_file: filename of a css file to style editable content
663 # on_init: callback for when the editable content is in place
664 constructor: (in_el, options) ->
665 @options = options ? {}
669 @init_1_called = false # when iframes have loaded
670 @outer_iframe # iframe to hold editor
671 @outer_idoc # "document" object for @outer_iframe
672 @wrap2 = null # scrollbar is on this
674 @wrap2_height = null # including padding
675 @iframe = null # iframe to hold editable content
676 @idoc = null # "document" object for @iframe
679 @cursor_visible = false
680 @cursor_ideal_x = null
681 @poll_for_blur_timeout = null
682 opt_fragment = @options.fragment ? true
685 @parser_opts.fragment = 'body'
687 @outer_iframe = domify document, iframe: {}
688 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
689 if @options.editor_id?
690 @outer_iframe.setAttribute 'id', @options.editor_id
691 @outer_iframe.onload = =>
692 @outer_idoc = @outer_iframe.contentDocument
693 icss = domify @outer_idoc, style: children: [
694 domify @outer_idoc, text: css
696 @outer_idoc.head.appendChild icss
697 @iframe = domify @outer_idoc, iframe: sandbox: 'allow-same-origin allow-scripts'
700 timeout 200, => # firefox never fires this onload
701 @init_1() unless @init_1_called
702 @outer_idoc.body.appendChild(
703 domify @outer_idoc, div: id: 'wrap1', children: [
704 domify @outer_idoc, div: style: "position: absolute; top: 0; left: 1px; font-size: 10px", children: [ domify @outer_idoc, text: "Peach HTML5 Editor" ]
705 @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
706 domify @outer_idoc, div: id: 'wrap3', children: [
708 @overlay = domify @outer_idoc, div: id: 'overlay'
713 outer_wrap = domify document, div: class: 'peach_html5_editor'
714 @in_el.parentNode.appendChild outer_wrap
715 outer_bounds = get_el_bounds outer_wrap
716 if outer_bounds.w < 300
718 if outer_bounds.h < 300
720 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
721 @outer_iframe.setAttribute 'style', outer_iframe_style
722 css = @generate_outer_css w: outer_bounds.w, h: outer_bounds.h
723 outer_wrap.appendChild @outer_iframe
724 init_1: -> # @iframe has loaded (but not it's css)
725 @idoc = @iframe.contentDocument
726 @init_1_called = true
727 # chromium doesn't resolve relative urls as though they were at the same domain
728 # so add a <base> tag
729 @idoc.head.appendChild domify @idoc, base: href: this_url_sans_path()
730 # don't let @iframe have scrollbars
731 @idoc.head.appendChild domify @idoc, style: children: [domify @idoc, text: "body { overflow: hidden; }"]
734 istyle = domify @idoc, link: rel: 'stylesheet', href: @options.css_file
737 @idoc.head.appendChild istyle
740 init_2: -> # @iframe and it's css file(s) are ready
741 @overlay.onclick = (e) =>
743 return event_return e, @onclick e
744 @overlay.ondoubleclick = (e) =>
746 return event_return e, @ondoubleclick e
747 @outer_idoc.body.onkeyup = (e) =>
749 return event_return e, @onkeyup e
750 @outer_idoc.body.onkeydown = (e) =>
752 return event_return e, @onkeydown e
753 @outer_idoc.body.onkeypress = (e) =>
755 return event_return e, @onkeypress e
756 @load_html @in_el.value
759 generate_outer_css: (args) ->
762 inner_padding = args.inner_padding ? overlay_padding
763 frame_width = args.frame_width ? inner_padding
764 occupy = (left, top = left, right = left, bottom = top) ->
767 return Math.max(left, top, right, bottom)
772 ret += 'color: black;'
773 ret += 'background: white;'
776 ret += "border: #{occupy 1}px solid black;"
777 ret += "padding: #{occupy frame_width}px;"
780 ret += "border: #{occupy 1}px solid black;"
781 @wrap2_height = h # including padding because padding scrolls
782 ret += "padding: #{occupy inner_padding}px;"
783 ret += "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
784 ret += "width: #{w}px;"
785 ret += "height: #{h}px;"
786 ret += 'overflow-x: hidden;'
787 ret += 'overflow-y: scroll;'
790 ret += 'position: relative;'
791 ret += "width: #{w}px;"
792 ret += "min-height: #{h}px;"
795 ret += 'box-sizing: border-box;'
797 ret += 'border: none;'
799 ret += "width: #{w}px;"
800 #ret += "height: #{h}px;" # height auto-set when content set/changed
801 ret += '-ms-user-select: none;'
802 ret += '-webkit-user-select: none;'
803 ret += '-moz-user-select: none;'
804 ret += 'user-select: none;'
807 ret += 'position: absolute;'
808 ret += "left: -#{inner_padding}px;"
809 ret += "top: -#{inner_padding}px;"
810 ret += "right: -#{inner_padding}px;"
811 ret += "bottom: -#{inner_padding}px;"
812 ret += 'overflow: hidden;'
815 ret += 'position: absolute;'
816 ret += 'background: rgba(100,100,100,0.2);'
819 ret += 'position: absolute;'
821 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));'
822 ret += 'background-size: 200% 200%;'
823 ret += '-webkit-animation: blink 1s linear normal infinite;'
824 ret += 'animation: blink 1s linear normal infinite;'
826 ret += '@-webkit-keyframes blink {'
827 ret += '0%{background-position:0% 0%}'
828 ret += '100%{background-position:0% -100%}'
830 ret += '@keyframes blink { '
831 ret += '0%{background-position:0% 0%}'
832 ret += '100%{background-position:0% -100%}'
836 ret += 'position: absolute;'
837 ret += 'border: 1px solid rgba(0,0,0,0.1);'
838 ret += 'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
841 ret += 'z-index: 10;'
842 ret += 'position: absolute;'
843 ret += 'font-size: 8px;'
844 ret += 'white-space: pre;'
845 ret += 'background: rgba(255,255,255,0.4);'
846 ret += '-ms-user-select: none;'
847 ret += '-webkit-user-select: none;'
848 ret += '-moz-user-select: none;'
849 ret += 'user-select: none;'
852 overlay_event_to_inner_xy: (e) ->
853 unless @wrap2_offset?
854 @wrap2_offset = get_el_bounds @wrap2
855 x = e.pageX - overlay_padding
856 y = e.pageY - overlay_padding + @wrap2.scrollTop
857 return x: x - @wrap2_offset.x, y: y - @wrap2_offset.y
859 xy = @overlay_event_to_inner_xy e
860 new_cursor = xy_to_cursor @tree, xy
862 @move_cursor new_cursor
866 ondoubleclick: (e) ->
870 return false if ignore_key_codes[e.keyCode]?
871 #return false if control_key_codes[e.keyCode]?
874 return false if ignore_key_codes[e.keyCode]?
875 #return false if control_key_codes[e.keyCode]?
879 new_cursor = find_prev_cursor_position @tree, @cursor
881 new_cursor = first_cursor_position @tree
883 @move_cursor new_cursor
887 new_cursor = find_next_cursor_position @tree, @cursor
889 new_cursor = last_cursor_position @tree
891 @move_cursor new_cursor
895 new_cursor = find_up_cursor_position @tree, @cursor, @cursor_ideal_x
897 saved_ideal_x = @cursor_ideal_x
898 @move_cursor new_cursor
899 @cursor_ideal_x = saved_ideal_x
901 # move cursor to first position in document
902 new_cursor = first_cursor_position @tree
904 @move_cursor new_cursor
908 new_cursor = find_down_cursor_position @tree, @cursor, @cursor_ideal_x
910 saved_ideal_x = @cursor_ideal_x
911 @move_cursor new_cursor
912 @cursor_ideal_x = saved_ideal_x
914 # move cursor to first position in document
915 new_cursor = last_cursor_position @tree
917 @move_cursor new_cursor
922 return false unless @cursor?
923 return false unless @cursor.i > 0
924 @remove_character @cursor.n, @cursor.i - 1
925 @adjust_whitespace_style @cursor.n
927 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i - 1
929 @move_cursor new_cursor
934 return false unless @cursor?
935 return false unless @cursor.i < @cursor.n.text.length
936 @remove_character @cursor.n, @cursor.i
937 @adjust_whitespace_style @cursor.n
939 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i
941 @move_cursor new_cursor
961 return false if ignore_key_codes[e.keyCode]?
962 char = e.charCode ? e.keyCode
964 char = String.fromCharCode char
965 @insert_character @cursor.n, @cursor.i, char
966 @adjust_whitespace_style @cursor.n
968 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i + 1
970 @move_cursor new_cursor
972 console.log "ERROR: couldn't find cursor position after insert"
975 clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
976 while @idoc.body.childNodes.length
977 @idoc.body.removeChild @idoc.body.childNodes[0]
981 @tree = peach_parser.parse html, @parser_opts
983 instantiate_tree @tree, @idoc.body
984 tree_dedup_space @tree
987 @in_el.onchange = null
988 @in_el.value = @pretty_html @tree
990 @load_html @in_el.value
991 @adjust_iframe_height()
992 adjust_iframe_height: ->
994 # when the content gets shorter, the idoc's body tag will continue to
995 # report the old (too big) height in Chrome. The workaround is to
996 # shrink the iframe before the content height:
997 @iframe.style.height = "10px"
998 h = parseInt(@idoc.body.scrollHeight, 10)
999 @iframe.style.height = "#{h}px"
1000 @wrap2.scrollTop = s
1001 # does this node have whitespace that would be collapsed by white-space: normal?
1002 # note: this checks direct text children, and does _not_ recurse into child tags
1003 # tag is a node with type:"tag"
1004 has_collapsable_space: (tag) ->
1005 for n in tag.children
1007 for i in [0...n.text.length]
1008 code = n.text.charCodeAt i
1009 if code isnt 32 and is_space_code code
1012 # check for double spaces that don't surround insert location
1014 if n.text.substr(i - 1, 2) is ' '
1016 if n.text.length > 0
1017 if is_space_code n.text.charCodeAt 0
1019 if is_space_code n.text.charCodeAt n.text.length - 1
1021 # add/remove "white-space: pre[-wrap]" to/from style="" on tags with direct
1022 # child text nodes with multiple spaces in a row, or spaces at the
1025 # text inside child tags are not consulted. Child tags are expected to have
1026 # this function applied to them when their content changes.
1027 adjust_whitespace_style: (n) ->
1030 return unless n?.el?
1031 # which css rule should be used to preserve spaces (should we need to)
1032 style = @iframe.contentWindow.getComputedStyle n.el, null
1033 ws = style.getPropertyValue 'white-space'
1034 if ws_props[ws].space
1037 preserve_rule = ws_props[ws].to_preserve
1038 preserve_rule = "white-space: #{preserve_rule}"
1039 if @has_collapsable_space n
1040 # make sure preserve_rule exists
1041 if n.el.style['white-space']
1042 # FIXME check that it matches
1045 n.attrs.style += "; #{preserve_rule}"
1047 n.attrs.style = preserve_rule
1048 n.el.setAttribute 'style', n.attrs.style
1050 # remove preserve_rule if it exists
1051 return unless n.attrs.style?
1052 # FIXME don't assume whitespace is just so
1053 if n.attrs.style is "white-space: #{ws}"
1054 delete n.attrs.style
1055 n.el.removeAttribute 'style'
1057 # FIXME find it in the middle and at the start
1058 needle = "; white-space: #{ws}"
1059 if needle is n.attrs.style.substr n.attrs.style.length - needle
1060 n.attrs.style = n.attrs.style.substr 0, n.attrs.style.length - needle
1061 n.el.setAttribute n.attrs.style
1062 # after calling this, you MUST call changed() and adjust_whitespace_style()
1063 insert_character: (n, i, char) ->
1064 parent = @cursor.n.parent
1065 return unless parent
1066 return unless parent.el?
1067 # insert the character
1069 n.text = char + n.text
1070 else if i is n.text.length
1074 n.text.substr(0, i) +
1077 n.el.nodeValue = n.text
1078 # after calling this, you MUST call changed() and adjust_whitespace_style()
1079 remove_character: (n, i) ->
1080 n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1081 n.el.nodeValue = n.text
1082 kill_cursor: -> # remove it, forget where it was
1084 @cursor_el.parentNode.removeChild @cursor_el
1085 @cursor_visible = false
1088 move_cursor: (cursor) ->
1089 @cursor_ideal_x = cursor.x
1091 unless @cursor_visible
1092 @cursor_el = domify @outer_idoc, div: id: 'cursor'
1093 @overlay.appendChild @cursor_el
1094 @cursor_visible = true
1095 @cursor_el.style.left = "#{cursor.x + overlay_padding - 1}px"
1100 @cursor_el.style.top = "#{cursor.y + overlay_padding + Math.round(height * .07)}px"
1101 @cursor_el.style.height = "#{Math.round height * 0.82}px"
1103 @scroll_into_view cursor.y, height
1104 scroll_into_view: (y, h = 0) ->
1105 closest = 30 # setting: smallest pixels from top/bottom of screet that's OK
1106 y += overlay_padding # convert units from @idoc to @wrap2
1107 # very top of document
1109 @wrap2.scrollTop = 0
1111 # very bottom of document
1112 if y + h >= @wrap2.scrollHeight - closest
1113 @wrap2.scrollTop = @wrap2.scrollHeight - @wrap2_height
1115 # The most scrolled up (lowest value for scrollTop) that would be OK
1116 upmost = y + h + closest - @wrap2_height
1117 upmost = Math.max(upmost, 0)
1118 # the most scrolled down (highest value for scrollTop) that would be OK
1119 downmost = y - closest
1120 downmost = Math.min(downmost, @wrap2.scrollHeight - @wrap2_height)
1121 if upmost > downmost # means h is too big to fit
1122 # scroll so top is visible
1123 @wrap2.scrollTop = downmost
1125 if @wrap2.scrollTop < upmost
1126 @wrap2.scrollTop = upmost
1128 if @wrap2.scrollTop > downmost
1129 @wrap2.scrollTop = downmost
1133 while @matting.length > 0
1134 @overlay.removeChild @matting[0]
1137 prev_bounds = x: 0, y: 0, w: 0, h: 0
1143 bounds = get_el_bounds n.el
1144 return unless bounds?
1145 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
1148 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});
1149 @overlay.appendChild ann_box
1150 @matting.push ann_box
1151 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} "]
1152 @overlay.appendChild ann_tag
1153 @matting.push ann_tag
1156 pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
1158 want_nl = parent_flags.want_nl
1159 prev_in_flow_is_text = false
1160 prev_in_flow_is_block = false
1163 inner_flags = want_nl: true
1170 if n.el.currentStyle?
1171 cs = n.el.currentStyle
1172 whitespace = cs['white-space']
1173 display = cs['display']
1174 position = cs['position']
1176 visibility = cs['visibility']
1178 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
1179 whitespace = cs.getPropertyValue 'white-space'
1180 display = cs.getPropertyValue 'display'
1181 position = cs.getPropertyValue 'position'
1182 float = cs.getPropertyValue 'float'
1183 visibility = cs.getPropertyValue 'visibility'
1184 if n.name is 'textarea'
1185 inner_flags.pre_ish = true
1187 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
1189 when 'left', 'right'
1193 when 'absolute', 'fixed'
1196 if 'display' is 'none'
1200 when 'hidden', 'collapse'
1205 when 'inline', 'none'
1206 inner_flags.block = false
1207 is_block = in_flow_block = false
1209 inner_flags.block = true
1210 is_block = in_flow_block = false
1211 else # block, table, etc
1212 inner_flags.block = true
1214 in_flow_block = in_flow
1219 in_flow_block = false
1220 else # 'comment', 'doctype'
1224 in_flow_block = false
1225 # print whitespace if we can
1226 unless parent_flags.pre_ish
1227 unless prev_in_flow_is_text and is_br
1228 if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
1241 if n.attrs[k].length > 0
1242 ret += "=\"#{enc_attr n.attrs[k]}\""
1244 unless void_elements[n.name]?
1245 if inner_flags.block
1246 next_indent = indent + ' '
1248 next_indent = indent
1249 if n.children.length
1250 ret += @pretty_html n.children, next_indent, inner_flags
1251 ret += "</#{n.name}>"
1253 ret += enc_text n.text
1255 ret += "<!--#{n.text}-->" # TODO encode?
1257 ret += "<!DOCTYPE #{n.name}"
1258 if n.public_identifier? and n.public_identifier.length > 0
1259 ret += " \"#{n.public_identifier}\""
1260 if n.system_identifier? and n.system_identifier.length > 0
1261 ret += " \"#{n.system_identifier}\""
1265 prev_in_flow_is_text = is_text
1266 prev_in_flow_is_block = is_block or (in_flow and is_br)
1268 # output final newline if allowed
1269 unless parent_flags.pre_ish
1270 if prev_in_flow_is_block or parent_flags.block
1271 ret += "\n#{indent.substr 4}"
1276 @editor_is_focused = true
1279 return if @poll_for_blur_timeout? # already polling
1280 @poll_for_blur_timeout = timeout 150, =>
1281 next_frame => # pause polling when browser knows we're not active/visible/etc.
1282 @poll_for_blur_timeout = null
1283 if document.activeElement is @outer_iframe
1286 @editor_is_focused = false
1289 window.peach_html5_editor = (args...) ->
1290 return new PeachHTML5Editor args...
1292 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])