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/>.
19 breathing_room = 30 # minimum pixels above/below cursor
21 timeout = (ms, cb) -> return setTimeout cb, ms
23 if (window.requestAnimationFrame?)
24 window.requestAnimationFrame cb
28 this_url_sans_path = ->
29 ret = "#{window.location.href}"
30 clip = ret.lastIndexOf '#'
32 ret = ret.substr 0, clip
33 clip = ret.lastIndexOf '?'
35 ret = ret.substr 0, clip
36 clip = ret.lastIndexOf '/'
38 ret = ret.substr 0, clip + 1
41 # table too look up the properties of various values for css's white-space
44 space: false # spaces are not preserved/rendered
45 newline: false # newlines are not preserved/rendered
46 wrap: true # text is word-wrapped
47 to_preserve: 'pre-wrap' # to preservespaces, change white-space to this
57 to_preserve: 'pre-wrap'
67 # xml 1.0 spec, chromium and firefox accept these, plus lots of unicode chars
68 valid_attr_regex = new RegExp '^[a-zA-Z_:][-a-zA-Z0-9_:.]*$'
69 # html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
70 js_attr_regex = new RegExp '^[oO][nN].'
72 debug_dot_at = (doc, x, y) ->
74 el = doc.createElement 'div'
75 el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
76 doc.body.appendChild el
77 #console.log(new Error().stack)
79 # text nodes don't have getBoundingClientRect(), so use selection api to find
81 get_el_bounds = window.bounds = (el) ->
82 if el.getBoundingClientRect?
83 rect = el.getBoundingClientRect()
85 # text nodes don't have getBoundingClientRect(), so use range api
86 range = el.ownerDocument.createRange()
87 range.selectNodeContents el
88 rect = range.getBoundingClientRect()
89 doc = el.ownerDocument.documentElement
90 win = el.ownerDocument.defaultView
91 y_fix = win.pageYOffset - doc.clientTop
92 x_fix = win.pageXOffset - doc.clientLeft
96 w: rect.width ? (rect.right - rect.left)
97 h: rect.height ? (rect.top - rect.bottom)
100 is_display_block = (el) ->
102 return el.currentStyle.display is 'block'
104 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
106 # Pass return value from dom event handlers to this.
107 # If they return false, this will addinionally stop propagation and default.
108 event_return = (e, bool) ->
110 if e.stopPropagation?
115 # Warning: currently assumes you're asking about a single character
116 # Note: chromium returns multiple bounding rects for a space at a line-break
117 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
118 # Note: sometimes returns null (eg for whitespace that is not visible)
119 text_range_bounds = (el, start, end) ->
120 range = document.createRange()
121 range.setStart el, start
123 rects = range.getClientRects()
126 if rects[1].width > rects[0].width
134 doc = el.ownerDocument.documentElement
135 win = el.ownerDocument.defaultView
136 y_fix = win.pageYOffset - doc.clientTop
137 x_fix = win.pageXOffset - doc.clientLeft
141 w: rect.width ? (rect.right - rect.left)
142 h: rect.height ? (rect.top - rect.bottom)
144 bounding: range.getBoundingClientRect()
148 constructor: (args) ->
159 range = document.createRange()
160 if @n.text.length is 0
161 ret = text_range_bounds @n.el, 0, 0
162 else if @i is @n.text.length
163 ret = text_range_bounds @n.el, @i - 1, @i
167 ret = text_range_bounds @n.el, @i, @i + 1
178 new_cursor_position = (args) ->
179 ret = new CursorPosition args
184 # encode text so it can be safely placed inside an html attribute
185 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
187 return txt.replace enc_attr_regex, (match, amp, quote) ->
188 return '&' if (amp)
189 return '"' if (quote)
191 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
193 return txt.replace enc_text_regex, (match, amp, lt) ->
194 return '&' if (amp)
195 return '<' if (lt)
215 # TODO make these always pretty-print (on the inside) like blocks
216 no_text_elements = { # these elements never contain text
226 domify = (doc, hash) ->
227 for tag, attrs of hash
229 return document.createTextNode attrs
230 el = document.createElement tag
243 '20': true # capslock
245 '144': true # numlock
247 '91': true # windows "start" key
248 # key codes: (valid on keydown, not keypress)
253 KEY_BACKSPACE = 8 # <--
254 KEY_DELETE = 46 # -->
263 control_key_codes = # we react to these, but they aren't typing
279 instantiate_tree = (tree, parent) ->
284 c.el = parent.ownerDocument.createTextNode c.text
285 parent.appendChild c.el
287 if c.name in ['script', 'object', 'iframe', 'link']
288 # TODO put placeholders instead
291 # TODO create in correct namespace
292 c.el = parent.ownerDocument.createElement c.name
294 # FIXME if attr_whitelist[k]?
295 if valid_attr_regex.test k
296 unless js_attr_regex.test k
297 c.el.setAttribute k, v
298 parent.appendChild c.el
300 instantiate_tree c.children, c.el
304 traverse_tree = (tree, cb) ->
310 done = traverse_tree c.children, cb
314 first_cursor_position = (tree) ->
316 traverse_tree tree, (node, state) ->
317 if node.type is 'text'
318 cursor = new_cursor_position n: node, i: 0
323 return found # maybe null
325 # this will fail when text has non-locatable cursor positions
326 find_next_cursor_position = (tree, cursor) ->
327 if cursor.n.type is 'text' and cursor.n.text.length > cursor.i
328 new_cursor = new_cursor_position n: cursor.n, i: cursor.i + 1
333 traverse_tree tree, (node, state) ->
334 if node.type is 'text' and state_before is false
335 new_cursor = new_cursor_position n: node, i: 0
346 last_cursor_position = (tree) ->
348 traverse_tree tree, (node) ->
349 if node.type is 'text'
350 cursor = new_cursor_position n: node, i: node.text.length
354 return found # maybe null
356 # this will fail when text has non-locatable cursor positions
357 find_prev_cursor_position = (tree, cursor) ->
358 if cursor.n.type is 'text' and cursor.i > 0
359 new_cursor = new_cursor_position n: cursor.n, i: cursor.i - 1
364 traverse_tree tree, (node) ->
366 found = found_prev # maybe null
368 if node.type is 'text'
369 new_cursor = new_cursor_position n: node, i: node.text.length
371 found_prev = new_cursor
373 return found # maybe null
375 find_up_cursor_position = (tree, cursor, ideal_x) ->
377 # go prev until we're higher on y axis
378 while new_cursor.y >= cursor.y
379 new_cursor = find_prev_cursor_position tree, new_cursor
380 return null unless new_cursor?
381 # done early if we're already left of old cursor position
382 if new_cursor.x <= ideal_x
384 target_y = new_cursor.y
385 # search leftward, until we find the closest position
386 # new_cursor is the prev-most position we've checked
387 # prev_cursor is the older value, so it's not as prev as new_cursor
388 while new_cursor.x > ideal_x and new_cursor.y is target_y
389 prev_cursor = new_cursor
390 new_cursor = find_prev_cursor_position tree, new_cursor
391 break unless new_cursor?
392 # move cursor to prev_cursor or new_cursor
394 if new_cursor.y is target_y
395 # both valid, and on the same line, use closest
396 if (ideal_x - new_cursor.x) < (prev_cursor.x - ideal_x)
401 # new_cursor on wrong line, use prev_cursor
404 # can't go any further prev, use prev_cursor
407 find_down_cursor_position = (tree, cursor, ideal_x) ->
409 # go next until we move on the y axis
410 while new_cursor.y <= cursor.y
411 new_cursor = find_next_cursor_position tree, new_cursor
412 return null unless new_cursor?
413 # done early if we're already right of old cursor position
414 if new_cursor.x >= ideal_x
415 # this would be strange, but could happen due to runaround
417 target_y = new_cursor.y
418 # search rightward, until we find the closest position
419 # new_cursor is the next-most position we've checked
420 # prev_cursor is the older value, so it's not as next as new_cursor
421 while new_cursor.x < ideal_x and new_cursor.y is target_y
422 prev_cursor = new_cursor
423 new_cursor = find_next_cursor_position tree, new_cursor
424 break unless new_cursor?
425 # move cursor to prev_cursor or new_cursor
427 if new_cursor.y is target_y
428 # both valid, and on the same line, use closest
429 if (new_cursor.x - ideal_x) < (ideal_x - prev_cursor.x)
434 # new_cursor on wrong line, use prev_cursor
437 # can't go any further prev, use prev_cursor
440 xy_to_cursor = (tree, xy) ->
442 if n.type is 'tag' or n.type is 'text'
443 bounds = get_el_bounds n.el
444 continue if xy.x < bounds.x
445 continue if xy.x > bounds.x + bounds.w
446 continue if xy.y < bounds.y
447 continue if xy.y > bounds.y + bounds.h
449 ret = xy_to_cursor n.children, xy
452 # click is within bounding box that contains all text.
453 if n.text.length is 0
454 ret = new_cursor_position n: n, i: 0
457 before = new_cursor_position n: n, i: 0
458 continue unless before?
459 after = new_cursor_position n: n, i: n.text.length
460 continue unless after?
461 if xy.y < before.y + before.h and xy.x < before.x
462 # console.log 'before first char on first line'
464 if xy.y > after.y and xy.x > after.x
465 # console.log 'after last char on last line'
468 console.log "Warning: click in text bounding box but above first line"
469 continue # above first line (runaround?)
470 if xy.y > after.y + after.h
471 console.log "Warning: click in text bounding box but below last line", xy.y, after.y, after.h
472 continue # below last line (shouldn't happen?)
473 while after.i - before.i > 1
474 guess_i = Math.round((before.i + after.i) / 2)
475 cur = new_cursor_position n: n, i: guess_i
477 console.log "error: failed to find cursor pixel location for", n, guess_i
480 if xy.y < cur.y or (xy.y <= cur.y + cur.h and xy.x < cur.x)
484 continue unless before? # signals failure to find a cursor position
485 # which one is closest?
486 if Math.abs(before.x - xy.x) < Math.abs(after.x - xy.x)
492 # browsers collapse these (html5 spec calls these "space characters")
493 is_space_code = (char_code) ->
495 when 9, 10, 12, 13, 32
499 return is_space_code chr.charCodeAt 0
501 tree_remove_empty_text_nodes = (tree) ->
503 traverse_tree tree, (n) ->
505 if n.text.length is 0
509 # don't completely empty the tree
511 if tree[0].type is 'text'
512 console.log "oop, leaving a blank node because it's the only thing"
514 n.el.parentNode.removeChild n.el
515 for c, i in n.parent.children
517 n.parent.children.splice i, 1
520 # pass a array of nodes (from parser library, ie it should have .el and .text)
521 tree_dedup_space = (tree) ->
522 prev = cur = next = null
523 prev_i = cur_i = next_i = 0
524 prev_pos = pos = next_pos = null
525 prev_px = cur_px = next_px = null
529 tree_remove_empty_text_nodes(tree)
531 iterate = (tree, cb) ->
535 while i < n.text.length # don't foreach, cb might remove chars
540 block = is_display_block n.el
543 if n.children.length > 0
544 iterate n.children, cb
550 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
551 if next is cur # in same text node
555 removed_char = cur.text.charAt(cur_i)
556 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
557 if next is cur # in same text node
559 throw "how is this possible?"
562 replace_with_space = (undo) ->
564 cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i + 1)
565 cur.el.textContent = cur.text
567 removed_char = cur.text.charAt(cur_i)
568 if removed_char isnt ' '
569 cur.text = (cur.text.substr 0, cur_i) + ' ' + (cur.text.substr cur_i + 1)
570 cur.el.textContent = cur.text
572 # return true if cur was removed from the dom (ie re-use same prev)
574 # cur definitately set
575 # prev and/or next might be null, indicating the start/end of a display:block
576 return false unless is_space_code cur.text.charCodeAt cur_i
577 fixers = [remove, replace_with_space]
578 # check for common case: single whitespace surrounded by non-whitespace chars
580 unless (is_space_code prev.text.charCodeAt prev_i) or (is_space_code next.text.charCodeAt next_i)
581 dbg = cur.text.charCodeAt cur_i
582 if cur.text.charAt(cur_i) is ' ' # perens required
583 # single space can't collapse, doesn't need fixin'
586 # tab, newline, etc, can't collapse, but maybe should be replaced
587 fixers = [replace_with_space]
588 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
590 # 1. zero rects returned by getClientRects() means collapsed space
593 # 2. width greater than zero means visible space
595 # has bounds, don't try removing
596 fixers = [replace_with_space]
597 # now the weird edge cases...
599 # firefox and chromium both report zero width for characters at the end
600 # of a line where the text wraps (automatically, due to word-wrap) to
601 # the next line. These do not appear to be distinguishable from
602 # collapsed spaces via the range/bounds api, so...
604 # remove it from the dom, and if prev or next moves, put it back.
606 # this block (try changing it, put it back if something moves) is also
607 # used on collapsable whitespace characters besides space. In this case
608 # the character is replaced with a normal space character instead of
610 if prev? and not prev_px?
611 prev_px = new_cursor_position n: prev, i: prev_i
612 if next? and not next_px?
613 next_px = new_cursor_position n: next, i: next_i
614 #if prev is null and next is null
615 # parent_px = cur.parent.el.getBoundingClientRect()
616 undo_arg = true # just for readabality
624 new_prev_px = new_cursor_position n: prev, i: prev_i
626 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
631 console.log "this shouldn't happen, we remove spaces that don't locate"
632 if next? and not need_undo
634 new_next_px = new_cursor_position n: next, i: next_i
636 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
641 # console.log "removing space becase space after it is collapsed"
643 removed += fixer undo_arg
648 # pass null at start/end of display:block
656 # don't advance (to the next character next time) if we removed a
657 # character from the same text node as ``next``, because doing so
658 # renumbers the indexes in that string
659 if removed and cur is next
675 tree_remove_empty_text_nodes(tree)
677 class PeachHTML5Editor
678 # Options: (all optional)
679 # editor_id: "id" attribute for outer-most element created by/for editor
680 # css_file: filename of a css file to style editable content
681 # on_init: callback for when the editable content is in place
682 constructor: (in_el, options) ->
683 @options = options ? {}
685 @tree = null # array of Nodes, all editable content
686 @tree_parent = null # @tree is this.children. .el might === @idoc.body
688 @init_1_called = false # when iframes have loaded
689 @outer_iframe # iframe to hold editor
690 @outer_idoc # "document" object for @outer_iframe
691 @wrap2 = null # scrollbar is on this
693 @wrap2_height = null # including padding
694 @iframe = null # iframe to hold editable content
695 @idoc = null # "document" object for @iframe
698 @cursor_visible = false
699 @cursor_ideal_x = null
700 @poll_for_blur_timeout = null
701 opt_fragment = @options.fragment ? true
704 @parser_opts.fragment = 'body'
706 @outer_iframe = domify document, iframe: {}
707 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
708 if @options.editor_id?
709 @outer_iframe.setAttribute 'id', @options.editor_id
710 @outer_iframe.onload = =>
711 @outer_idoc = @outer_iframe.contentDocument
712 icss = domify @outer_idoc, style: children: [
713 domify @outer_idoc, text: css
715 @outer_idoc.head.appendChild icss
716 @iframe = domify @outer_idoc, iframe: sandbox: 'allow-same-origin allow-scripts'
719 timeout 200, => # firefox never fires this onload
720 @init_1() unless @init_1_called
721 @outer_idoc.body.appendChild(
722 domify @outer_idoc, div: id: 'wrap1', children: [
723 domify @outer_idoc, div: style: "position: absolute; top: 0; left: 1px; font-size: 10px", children: [ domify @outer_idoc, text: "Peach HTML5 Editor" ]
724 @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
725 domify @outer_idoc, div: id: 'wrap3', children: [
727 @overlay = domify @outer_idoc, div: id: 'overlay'
732 outer_wrap = domify document, div: class: 'peach_html5_editor'
733 @in_el.parentNode.appendChild outer_wrap
734 outer_bounds = get_el_bounds outer_wrap
735 if outer_bounds.w < 300
737 if outer_bounds.h < 300
739 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
740 @outer_iframe.setAttribute 'style', outer_iframe_style
741 css = @generate_outer_css w: outer_bounds.w, h: outer_bounds.h
742 outer_wrap.appendChild @outer_iframe
743 init_1: -> # @iframe has loaded (but not it's css)
744 @idoc = @iframe.contentDocument
745 @init_1_called = true
746 # chromium doesn't resolve relative urls as though they were at the same domain
747 # so add a <base> tag
748 @idoc.head.appendChild domify @idoc, base: href: this_url_sans_path()
749 # don't let @iframe have scrollbars
750 @idoc.head.appendChild domify @idoc, style: children: [domify @idoc, text: "body { overflow: hidden; }"]
753 istyle = domify @idoc, link: rel: 'stylesheet', href: @options.css_file
756 @idoc.head.appendChild istyle
759 init_2: -> # @iframe and it's css file(s) are ready
760 @overlay.onclick = (e) =>
762 return event_return e, @onclick e
763 @overlay.ondoubleclick = (e) =>
765 return event_return e, @ondoubleclick e
766 @outer_idoc.body.onkeyup = (e) =>
768 return event_return e, @onkeyup e
769 @outer_idoc.body.onkeydown = (e) =>
771 return event_return e, @onkeydown e
772 @outer_idoc.body.onkeypress = (e) =>
774 return event_return e, @onkeypress e
775 @load_html @in_el.value
778 generate_outer_css: (args) ->
781 inner_padding = args.inner_padding ? overlay_padding
782 frame_width = args.frame_width ? inner_padding
783 occupy = (left, top = left, right = left, bottom = top) ->
786 return Math.max(left, top, right, bottom)
791 ret += 'color: black;'
792 ret += 'background: white;'
795 ret += "border: #{occupy 1}px solid black;"
796 ret += "padding: #{occupy frame_width}px;"
799 ret += "border: #{occupy 1}px solid black;"
800 @wrap2_height = h # including padding because padding scrolls
801 ret += "padding: #{occupy inner_padding}px;"
802 ret += "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
803 ret += "width: #{w}px;"
804 ret += "height: #{h}px;"
805 ret += 'overflow-x: hidden;'
806 ret += 'overflow-y: scroll;'
809 ret += 'position: relative;'
810 ret += "width: #{w}px;"
811 ret += "min-height: #{h}px;"
814 ret += 'box-sizing: border-box;'
816 ret += 'border: none;'
818 ret += "width: #{w}px;"
819 #ret += "height: #{h}px;" # height auto-set when content set/changed
820 ret += '-ms-user-select: none;'
821 ret += '-webkit-user-select: none;'
822 ret += '-moz-user-select: none;'
823 ret += 'user-select: none;'
826 ret += 'position: absolute;'
827 ret += "left: -#{inner_padding}px;"
828 ret += "top: -#{inner_padding}px;"
829 ret += "right: -#{inner_padding}px;"
830 ret += "bottom: -#{inner_padding}px;"
831 ret += 'overflow: hidden;'
834 ret += 'position: absolute;'
835 ret += 'background: rgba(100,100,100,0.2);'
838 ret += 'position: absolute;'
840 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));'
841 ret += 'background-size: 200% 200%;'
842 ret += '-webkit-animation: blink 1s linear normal infinite;'
843 ret += 'animation: blink 1s linear normal infinite;'
845 ret += '@-webkit-keyframes blink {'
846 ret += '0%{background-position:0% 0%}'
847 ret += '100%{background-position:0% -100%}'
849 ret += '@keyframes blink { '
850 ret += '0%{background-position:0% 0%}'
851 ret += '100%{background-position:0% -100%}'
855 ret += 'position: absolute;'
856 ret += 'border: 1px solid rgba(0,0,0,0.1);'
857 ret += 'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
860 ret += 'z-index: 10;'
861 ret += 'position: absolute;'
862 ret += 'font-size: 8px;'
863 ret += 'white-space: pre;'
864 ret += 'background: rgba(255,255,255,0.4);'
865 ret += '-ms-user-select: none;'
866 ret += '-webkit-user-select: none;'
867 ret += '-moz-user-select: none;'
868 ret += 'user-select: none;'
871 overlay_event_to_inner_xy: (e) ->
872 unless @wrap2_offset?
873 @wrap2_offset = get_el_bounds @wrap2
874 x = e.pageX - overlay_padding
875 y = e.pageY - overlay_padding + @wrap2.scrollTop
876 return x: x - @wrap2_offset.x, y: y - @wrap2_offset.y
878 xy = @overlay_event_to_inner_xy e
879 new_cursor = xy_to_cursor @tree, xy
881 @move_cursor new_cursor
885 ondoubleclick: (e) ->
889 return false if ignore_key_codes[e.keyCode]?
890 #return false if control_key_codes[e.keyCode]?
893 return false if ignore_key_codes[e.keyCode]?
894 #return false if control_key_codes[e.keyCode]?
898 new_cursor = find_prev_cursor_position @tree, @cursor
900 new_cursor = first_cursor_position @tree
902 @move_cursor new_cursor
906 new_cursor = find_next_cursor_position @tree, @cursor
908 new_cursor = last_cursor_position @tree
910 @move_cursor new_cursor
914 new_cursor = find_up_cursor_position @tree, @cursor, @cursor_ideal_x
916 saved_ideal_x = @cursor_ideal_x
917 @move_cursor new_cursor
918 @cursor_ideal_x = saved_ideal_x
920 # move cursor to first position in document
921 new_cursor = first_cursor_position @tree
923 @move_cursor new_cursor
927 new_cursor = find_down_cursor_position @tree, @cursor, @cursor_ideal_x
929 saved_ideal_x = @cursor_ideal_x
930 @move_cursor new_cursor
931 @cursor_ideal_x = saved_ideal_x
933 # move cursor to first position in document
934 new_cursor = last_cursor_position @tree
936 @move_cursor new_cursor
939 new_cursor = last_cursor_position @tree
941 @move_cursor new_cursor
947 return false unless @cursor?
948 return false unless @cursor.i < @cursor.n.text.length
949 @remove_character @cursor.n, @cursor.i
950 @adjust_whitespace_style @cursor.n
952 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i
954 @move_cursor new_cursor
965 new_cursor = first_cursor_position @tree
967 @move_cursor new_cursor
981 return false if ignore_key_codes[e.keyCode]?
982 char = e.charCode ? e.keyCode
984 char = String.fromCharCode char
985 @insert_character @cursor.n, @cursor.i, char
986 @adjust_whitespace_style @cursor.n
988 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i + 1
990 @move_cursor new_cursor
992 console.log "ERROR: couldn't find cursor position after insert"
995 on_key_enter: (e) -> # enter key pressed
996 return unless @cursor_visible
997 cur_block = @cursor.n
999 if cur_block.type is 'tag'
1000 if is_display_block cur_block.el
1002 return unless cur_block.parent?
1003 cur_block = cur_block.parent
1004 # find array to insert new element into
1005 if cur_block.parent is @tree_parent # top-level
1006 parent_el = @idoc.body
1009 parent_el = cur_block.parent.el
1010 pc = cur_block.parent.children
1011 # find index of current block in its parent
1013 break if n is cur_block
1014 i += 1 # we want to be after it
1019 # TODO if content after cursor
1020 # TODO new block is empty
1021 new_text = new peach_parser.Node 'text', text: ' '
1022 new_node = new peach_parser.Node 'tag', name: 'p', parent: cur_block.parent, attrs: {style: 'white-space: pre-wrap'}, children: [new_text]
1023 new_text.parent = new_node
1024 new_text.el = domify @idoc, text: ' '
1025 new_node.el = domify @idoc, p: style: 'white-space: pre-wrap', children: [new_text.el]
1026 pc.splice i, 0, new_node
1027 parent_el.insertBefore new_node.el, before
1029 new_cursor = new_cursor_position n: new_text, i: 0
1030 throw 'bork bork' unless new_cursor?
1031 @move_cursor new_cursor
1032 # TODO move content past cursor into this new block
1033 # unlike the global function, this takes a Node, not an element
1034 is_display_block: (n) ->
1035 # TODO stop calling global function, merge it into here, use iframe's window object
1036 return false unless n.type is 'tag'
1037 return is_display_block n.el
1038 find_block_parent: (n) ->
1041 return null unless n?
1042 return n if is_display_block n.el
1043 return n if n is @tree_parent
1045 on_key_backspace: (e) ->
1046 return false unless @cursor?
1047 if @is_lone_space @cursor.n # false if it's not in a tag
1049 # don't delete the space, because then it would collapse
1050 # instead leave a space after the cursor
1051 new_cursor = new_cursor_position n: @cursor.n, i: 0
1053 @move_cursor new_cursor
1057 # cursor at the begining of an element that contains only a space
1058 parent = @cursor.n.parent
1059 new_cursor = find_prev_cursor_position @tree, @cursor
1061 if new_cursor.n is @cursor.n or new_cursor.n is parent
1063 tag = @cursor.n.parent
1064 if tag is @tree_parent
1065 console.log "top-level text not supported" # FIXME
1067 for n, i in tag.parent.children
1069 tag.parent.el.removeChild tag.el
1070 tag.parent.children.splice i, 1
1074 # re-check, in case it moved or is invalid now
1075 new_cursor = new_cursor_position n: new_cursor.n, i: new_cursor.i
1077 @move_cursor new_cursor
1079 new_cursor = first_cursor_position @tree
1081 @move_cursor new_cursor
1085 else if @cursor.i is 0 # start of text chunk
1086 # FIXME clean this up: use new code for text runs
1087 # FIXME handle backspacing a <br> even if it's near a inline tag boundary
1088 # determine if cursor is at start of text run (text formatted inline)
1089 block = @find_block_parent @cursor.n
1091 at_block_start = true
1092 prev_pos = find_prev_cursor_position @tree, @cursor
1094 # if the cursor can't go back, then there's probably nowhere we can merge into
1095 # TODO consider case of nested blocks. should backspace remove one?
1097 prev_pos_block = @find_block_parent prev_pos.n
1098 if prev_pos_block is block
1099 # context: there is text before the cursor within the same block.
1100 # FIXME clean up this hack for looking for <br> (see above)
1101 cursor_text_pi = @cursor.n.parent.children.indexOf @cursor.n
1102 if cursor_text_pi > 0
1103 prev_node = @cursor.n.parent.children[cursor_text_pi - 1]
1104 if prev_node.type is 'tag' and prev_node.name is 'br'
1105 @remove_node prev_node
1106 @text_cleanup @cursor.n.parent
1108 new_cursor = new_cursor_position n: prev_pos.n, i: prev_pos.i
1110 @move_cursor new_cursor
1114 # note: find_prev_cursor_position just crossed a boundary, not a character
1115 # prev_pos is within the same block, try deleting there
1116 @move_cursor prev_pos
1117 # FIXME cleanup: don't call @move_cursor twice if the next line succeeds
1118 return @on_key_backspace()
1119 # context: backspace pressed at start of a display:block
1120 return if block is @tree_parent # top level text
1121 parent = block.parent
1122 parent_i = parent.children.indexOf block
1124 throw "BUG #98270918347"
1127 # no previous sibling to merge into, so instead move contents into parent
1131 # FIXME prev_sib should be the previous in-flow element
1132 # ie it should skip comments, hidden things, floating things, etc.
1133 prev_sib = parent.children[parent_i - 1]
1134 if @is_display_block prev_sib
1136 before = null # null means append
1140 if dest is @tree_parent
1141 # don't remove outer-most blocks
1143 while block.children.length > 0
1144 n = block.children[block.children.length - 1]
1145 @move_node n, dest, before
1146 block.children.pop()
1151 new_cursor = new_cursor_position n: prev_pos.n, i: prev_pos.i
1153 @move_cursor new_cursor
1158 # TODO handle case of removing last char
1160 if @is_only_char_in_tag @cursor.n
1161 if @is_display_block @cursor.n.parent
1162 @cursor.n.el.textContent = @cursor.n.text = ' '
1164 console.log "unimplemented: delete last char in inline" # FIXME
1167 @remove_character @cursor.n, @cursor.i - 1
1168 @adjust_whitespace_style @cursor.n
1170 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i - 1
1172 @move_cursor new_cursor
1176 on_page_up_key: (e) ->
1177 if @wrap2.scrollTop is 0
1178 return unless @cursor?
1179 new_cursor = first_cursor_position @tree
1181 if new_cursor.n isnt @cursor.n or new_cursor.i isnt @cursor.i
1182 @move_cursor new_cursor
1185 screen_y = @cursor.y - @wrap2.scrollTop
1186 scroll_amount = @wrap2_height - breathing_room
1187 @wrap2.scrollTop = Math.max 0, @wrap2.scrollTop - scroll_amount
1189 @move_cursor_into_view screen_y + @wrap2.scrollTop
1190 on_page_down_key: (e) ->
1191 lowest_scrollpos = @wrap2.scrollHeight - @wrap2_height
1192 if @wrap2.scrollTop is lowest_scrollpos
1193 return unless @cursor?
1194 new_cursor = last_cursor_position @tree
1196 if new_cursor.n isnt @cursor.n or new_cursor.i isnt @cursor.i
1197 @move_cursor new_cursor
1200 screen_y = @cursor.y - @wrap2.scrollTop
1201 scroll_amount = @wrap2_height - breathing_room
1202 @wrap2.scrollTop = Math.min lowest_scrollpos, @wrap2.scrollTop + scroll_amount
1204 @move_cursor_into_view screen_y + @wrap2.scrollTop
1206 move_cursor_into_view: (y_target) ->
1207 return if y_target is @cursor.y
1209 y_min = @wrap2.scrollTop
1210 unless @wrap2.scrollTop is 0
1211 y_min += breathing_room
1212 y_max = @wrap2.scrollTop + @wrap2_height
1213 unless @wrap2.scrollTop is @wrap2.scrollHeight - @wrap2_height # downmost
1214 y_max -= breathing_room
1215 y_target = Math.min y_target, y_max
1216 y_target = Math.max y_target, y_min
1217 if y_target < @cursor.y
1218 finder = find_up_cursor_position
1219 far_enough = (cur, target_y) ->
1220 return cur.y + cur.h <= target_y
1222 finder = find_down_cursor_position
1223 far_enough = (cur, y_target) ->
1224 return cur.y >= y_target
1226 cur = finder @tree, was, @cursor_ideal_x
1228 break if far_enough cur, y_target
1233 if was.y + was.h > y_max
1235 else if was.y < y_min
1238 if cur.y + cur.h > y_max
1240 else if cur.y < y_min
1243 # both valid, pick best
1246 else if was.y + was.h > y_max
1248 else if cur.y - y_target < y_target - was.y
1253 new_cursor = was ? cur
1255 saved_ideal_x = @cursor_ideal_x
1256 @move_cursor new_cursor
1257 @cursor_ideal_x = saved_ideal_x
1259 clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
1260 while @idoc.body.childNodes.length
1261 @idoc.body.removeChild @idoc.body.childNodes[0]
1264 load_html: (html) ->
1265 @tree = peach_parser.parse html, @parser_opts
1266 if !@tree[0]?.parent
1267 @tree = peach_parser.parse '<p style="white-space: pre-wrap"> </p>', @parser_opts
1268 @tree_parent = @tree[0]?.parent
1269 @tree_parent.el = @idoc.body
1271 instantiate_tree @tree, @tree_parent.el
1272 tree_dedup_space @tree
1275 @in_el.onchange = null
1276 @in_el.value = @pretty_html @tree
1277 @in_el.onchange = =>
1278 @load_html @in_el.value
1279 @adjust_iframe_height()
1280 adjust_iframe_height: ->
1281 s = @wrap2.scrollTop
1282 # when the content gets shorter, the idoc's body tag will continue to
1283 # report the old (too big) height in Chrome. The workaround is to
1284 # shrink the iframe before the content height:
1285 @iframe.style.height = "10px"
1286 h = parseInt(@idoc.body.scrollHeight, 10)
1287 @iframe.style.height = "#{h}px"
1288 @wrap2.scrollTop = s
1289 # does this node have whitespace that would be collapsed by white-space: normal?
1290 # note: this checks direct text children, and does _not_ recurse into child tags
1291 # tag is a node with type:"tag"
1292 # FIXME use new textrun api
1293 has_collapsable_space: (tag) ->
1294 for n in tag.children
1296 for i in [0...n.text.length]
1297 code = n.text.charCodeAt i
1298 if code isnt 32 and is_space_code code
1301 # check for double spaces that don't surround insert location
1303 if n.text.substr(i - 1, 2) is ' '
1305 if n.text.length > 0
1306 if is_space_code n.text.charCodeAt 0
1308 if is_space_code n.text.charCodeAt n.text.length - 1
1311 # add/remove "white-space: pre[-wrap]" to/from style="" on tags with direct
1312 # child text nodes with multiple spaces in a row, or spaces at the
1315 # text inside child tags are not consulted. Child tags are expected to have
1316 # this function applied to them when their content changes.
1317 adjust_whitespace_style: (n) ->
1319 break if @is_display_block n
1322 return if n is @tree_parent
1323 # which css rule should be used to preserve spaces (should we need to)
1324 style = @iframe.contentWindow.getComputedStyle n.el, null
1325 ws = style.getPropertyValue 'white-space'
1326 if ws_props[ws].space
1329 preserve_rule = ws_props[ws].to_preserve
1330 preserve_rule = "white-space: #{preserve_rule}"
1331 if @has_collapsable_space n
1332 # make sure preserve_rule exists
1333 if n.el.style['white-space']
1334 # FIXME check that it matches
1337 n.attrs.style += "; #{preserve_rule}"
1339 n.attrs.style = preserve_rule
1340 n.el.setAttribute 'style', n.attrs.style
1342 # remove preserve_rule if it exists
1343 return unless n.attrs.style?
1344 # FIXME don't assume whitespace is just so
1345 if n.attrs.style is "white-space: #{ws}"
1346 delete n.attrs.style
1347 n.el.removeAttribute 'style'
1349 # FIXME find it in the middle and at the start
1350 needle = "; white-space: #{ws}"
1351 if needle is n.attrs.style.substr n.attrs.style.length - needle
1352 n.attrs.style = n.attrs.style.substr 0, n.attrs.style.length - needle
1353 n.el.setAttribute n.attrs.style
1354 # true if n is text node with only one caracter, and the only child of a tag
1355 is_only_char_in_tag: (n, i) ->
1356 return false unless n.type is 'text'
1357 return false unless n.text.length is 1
1358 return false if n.parent is @tree_parent
1359 return false unless n.parent.children.length is 1
1361 # true if n is text node with just a space in it, and the only child of a tag
1362 is_lone_space: (n, i) ->
1363 return false unless n.type is 'text'
1364 return false unless n.text is ' '
1365 return false if n.parent is @tree_parent
1366 return false unless n.parent.children.length is 1
1368 # detect special case: typing before a space that's the only thing in a block/doc
1369 # reason: enter key creates blocks with just a space in them
1370 insert_should_replace: (n, i) ->
1371 return false unless i is 0
1372 return false unless n.text is ' '
1373 return true if n.parent is @tree_parent
1374 if n.parent.children.length is 1
1375 if n.parent.children[0] is n
1379 # after calling this, you MUST call changed() and adjust_whitespace_style()
1380 insert_character: (n, i, char) ->
1381 return if @cursor.n.parent is @tree_parent # FIXME implement text nodes at top level
1382 parent = @cursor.n.parent
1383 # insert the character
1384 if @insert_should_replace n, i
1387 n.text = char + n.text
1388 else if i is n.text.length
1393 n.text.substr(0, i) +
1396 n.el.nodeValue = n.text
1397 # WARNING: after calling this, you MUST call changed() and adjust_whitespace_style()
1398 remove_character: (n, i) ->
1399 n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1400 n.el.nodeValue = n.text
1401 # call this after you insert or remove inline nodes. It will:
1402 # merge consecutive text nodes
1403 # remove empty text nodes
1404 # adjust white-space property
1405 text_cleanup: (n) ->
1407 # FIXME implement this
1408 # WARNING: after calling this one or more times, you MUST:
1409 # if it's inline: call @text_cleanup
1412 i = n.parent.children.indexOf n
1414 throw "BUG #9187112313"
1415 n.el.parentNode.removeChild n.el
1416 n.parent.children.splice i, 1
1418 # remove a node from the tree/dom, insert into new_parent before insert_before?end
1419 # WARNING: after calling this one or more times, you MUST:
1420 # if it's inline: call @text_cleanup
1422 move_node: (n, new_parent, insert_before = null) ->
1423 i = n.parent.children.indexOf n
1425 throw "Error: tried to remove node, but it's not in it's parents list of children"
1428 before_i = new_parent.children.indexOf insert_before
1430 throw "Error: tried to move a node to be before a non-existent node"
1431 insert_before = insert_before.el
1434 new_parent.el.insertBefore n.el, insert_before
1435 new_parent.children.splice before_i, 0, n
1437 new_parent.el.appendChild n.el, insert_before
1438 new_parent.children.push n
1439 n.parent = new_parent
1441 kill_cursor: -> # remove it, forget where it was
1443 @cursor_el.parentNode.removeChild @cursor_el
1444 @cursor_visible = false
1448 move_cursor: (cursor) ->
1449 @cursor_ideal_x = cursor.x
1451 unless @cursor_visible
1452 @cursor_el = domify @outer_idoc, div: id: 'cursor'
1453 @overlay.appendChild @cursor_el
1454 @cursor_visible = true
1455 @cursor_el.style.left = "#{cursor.x + overlay_padding - 1}px"
1460 @cursor_el.style.top = "#{cursor.y + overlay_padding + Math.round(height * .07)}px"
1461 @cursor_el.style.height = "#{Math.round height * 0.82}px"
1463 @scroll_into_view cursor.y, height
1465 scroll_into_view: (y, h = 0) ->
1466 y += overlay_padding # convert units from @idoc to @wrap2
1467 # very top of document
1468 if y <= breathing_room
1469 @wrap2.scrollTop = 0
1471 # very bottom of document
1472 if y + h >= @wrap2.scrollHeight - breathing_room
1473 @wrap2.scrollTop = @wrap2.scrollHeight - @wrap2_height
1475 # The most scrolled up (lowest value for scrollTop) that would be OK
1476 upmost = y + h + breathing_room - @wrap2_height
1477 upmost = Math.max(upmost, 0)
1478 # the most scrolled down (highest value for scrollTop) that would be OK
1479 downmost = y - breathing_room
1480 downmost = Math.min(downmost, @wrap2.scrollHeight - @wrap2_height)
1481 if upmost > downmost # means h is too big to fit
1482 # scroll so top is visible
1483 @wrap2.scrollTop = downmost
1485 if @wrap2.scrollTop < upmost
1486 @wrap2.scrollTop = upmost
1488 if @wrap2.scrollTop > downmost
1489 @wrap2.scrollTop = downmost
1493 while @matting.length > 0
1494 @overlay.removeChild @matting[0]
1497 prev_bounds = x: 0, y: 0, w: 0, h: 0
1499 while n?.el? and n isnt @tree_parent
1503 bounds = get_el_bounds n.el
1504 return unless bounds?
1505 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
1508 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});
1509 @overlay.appendChild ann_box
1510 @matting.push ann_box
1511 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} "]
1512 @overlay.appendChild ann_tag
1513 @matting.push ann_tag
1516 pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
1518 want_nl = parent_flags.want_nl
1519 prev_in_flow_is_text = false
1520 prev_in_flow_is_block = false
1523 inner_flags = want_nl: true
1530 if n.el.currentStyle?
1531 cs = n.el.currentStyle
1532 whitespace = cs['white-space']
1533 display = cs['display']
1534 position = cs['position']
1536 visibility = cs['visibility']
1538 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
1539 whitespace = cs.getPropertyValue 'white-space'
1540 display = cs.getPropertyValue 'display'
1541 position = cs.getPropertyValue 'position'
1542 float = cs.getPropertyValue 'float'
1543 visibility = cs.getPropertyValue 'visibility'
1544 if n.name is 'textarea'
1545 inner_flags.pre_ish = true
1547 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
1549 when 'left', 'right'
1553 when 'absolute', 'fixed'
1556 if 'display' is 'none'
1560 when 'hidden', 'collapse'
1565 when 'inline', 'none'
1566 inner_flags.block = false
1567 is_block = in_flow_block = false
1569 inner_flags.block = true
1570 is_block = in_flow_block = false
1571 else # block, table, etc
1572 inner_flags.block = true
1574 in_flow_block = in_flow
1579 in_flow_block = false
1580 else # 'comment', 'doctype'
1584 in_flow_block = false
1585 # print whitespace if we can
1586 unless parent_flags.pre_ish
1587 unless prev_in_flow_is_text and is_br
1588 if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
1601 if n.attrs[k].length > 0
1602 ret += "=\"#{enc_attr n.attrs[k]}\""
1604 unless void_elements[n.name]?
1605 if inner_flags.block
1606 next_indent = indent + ' '
1608 next_indent = indent
1609 if n.children.length
1610 ret += @pretty_html n.children, next_indent, inner_flags
1611 ret += "</#{n.name}>"
1613 ret += enc_text n.text
1615 ret += "<!--#{n.text}-->" # TODO encode?
1617 ret += "<!DOCTYPE #{n.name}"
1618 if n.public_identifier? and n.public_identifier.length > 0
1619 ret += " \"#{n.public_identifier}\""
1620 if n.system_identifier? and n.system_identifier.length > 0
1621 ret += " \"#{n.system_identifier}\""
1625 prev_in_flow_is_text = is_text
1626 prev_in_flow_is_block = is_block or (in_flow and is_br)
1628 # output final newline if allowed
1629 unless parent_flags.pre_ish
1630 if prev_in_flow_is_block or parent_flags.block
1631 ret += "\n#{indent.substr 4}"
1636 @editor_is_focused = true
1639 return if @poll_for_blur_timeout? # already polling
1640 @poll_for_blur_timeout = timeout 150, =>
1641 next_frame => # pause polling when browser knows we're not active/visible/etc.
1642 @poll_for_blur_timeout = null
1643 if document.activeElement is @outer_iframe
1646 @editor_is_focused = false
1649 window.peach_html5_editor = (args...) ->
1650 return new PeachHTML5Editor args...
1652 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])