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 whitespace_to_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 cur.text = (cur.text.substr 0, cur_i) + ' ' + (cur.text.substr cur_i + 1)
569 cur.el.textContent = cur.text
571 # return true if cur was removed from the dom (ie re-use same prev)
573 # cur definitately set
574 # prev and/or next might be null, indicating the start/end of a display:block
575 return false unless is_space_code cur.text.charCodeAt cur_i
576 fixers = [remove, whitespace_to_space]
577 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
579 # 1. zero rects returned by getClientRects() means collapsed space
582 # 2. width greater than zero means visible space
584 fixers.shift() # don't try removing
585 # now the weird edge cases...
587 # firefox and chromium both report zero width for characters at the end
588 # of a line where the text wraps (automatically, due to word-wrap) to
589 # the next line. These do not appear to be distinguishable from
590 # collapsed spaces via the range/bounds api, so...
592 # remove it from the dom, and if prev or next moves, put it back.
593 if prev? and not prev_px?
594 prev_px = new_cursor_position n: prev, i: prev_i
595 if next? and not next_px?
596 next_px = new_cursor_position n: next, i: next_i
597 #if prev is null and next is null
598 # parent_px = cur.parent.el.getBoundingClientRect()
599 undo_arg = true # just for readabality
607 new_prev_px = new_cursor_position n: prev, i: prev_i
609 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
614 console.log "this shouldn't happen, we remove spaces that don't locate"
615 if next? and not need_undo
617 new_next_px = new_cursor_position n: next, i: next_i
619 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
624 # console.log "removing space becase space after it is collapsed"
626 removed += fixer undo_arg
631 # pass null at start/end of display:block
639 # don't advance (to the next character next time) if we removed a
640 # character from the same text node as ``next``, because doing so
641 # renumbers the indexes in that string
642 if removed and cur is next
658 tree_remove_empty_text_nodes(tree)
660 class PeachHTML5Editor
661 # Options: (all optional)
662 # editor_id: "id" attribute for outer-most element created by/for editor
663 # css_file: filename of a css file to style editable content
664 # on_init: callback for when the editable content is in place
665 constructor: (in_el, options) ->
666 @options = options ? {}
668 @tree = null # array of Nodes, all editable content
669 @tree_parent = null # @tree is this.children. .el might === @idoc.body
671 @init_1_called = false # when iframes have loaded
672 @outer_iframe # iframe to hold editor
673 @outer_idoc # "document" object for @outer_iframe
674 @wrap2 = null # scrollbar is on this
676 @wrap2_height = null # including padding
677 @iframe = null # iframe to hold editable content
678 @idoc = null # "document" object for @iframe
681 @cursor_visible = false
682 @cursor_ideal_x = null
683 @poll_for_blur_timeout = null
684 opt_fragment = @options.fragment ? true
687 @parser_opts.fragment = 'body'
689 @outer_iframe = domify document, iframe: {}
690 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
691 if @options.editor_id?
692 @outer_iframe.setAttribute 'id', @options.editor_id
693 @outer_iframe.onload = =>
694 @outer_idoc = @outer_iframe.contentDocument
695 icss = domify @outer_idoc, style: children: [
696 domify @outer_idoc, text: css
698 @outer_idoc.head.appendChild icss
699 @iframe = domify @outer_idoc, iframe: sandbox: 'allow-same-origin allow-scripts'
702 timeout 200, => # firefox never fires this onload
703 @init_1() unless @init_1_called
704 @outer_idoc.body.appendChild(
705 domify @outer_idoc, div: id: 'wrap1', children: [
706 domify @outer_idoc, div: style: "position: absolute; top: 0; left: 1px; font-size: 10px", children: [ domify @outer_idoc, text: "Peach HTML5 Editor" ]
707 @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
708 domify @outer_idoc, div: id: 'wrap3', children: [
710 @overlay = domify @outer_idoc, div: id: 'overlay'
715 outer_wrap = domify document, div: class: 'peach_html5_editor'
716 @in_el.parentNode.appendChild outer_wrap
717 outer_bounds = get_el_bounds outer_wrap
718 if outer_bounds.w < 300
720 if outer_bounds.h < 300
722 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
723 @outer_iframe.setAttribute 'style', outer_iframe_style
724 css = @generate_outer_css w: outer_bounds.w, h: outer_bounds.h
725 outer_wrap.appendChild @outer_iframe
726 init_1: -> # @iframe has loaded (but not it's css)
727 @idoc = @iframe.contentDocument
728 @init_1_called = true
729 # chromium doesn't resolve relative urls as though they were at the same domain
730 # so add a <base> tag
731 @idoc.head.appendChild domify @idoc, base: href: this_url_sans_path()
732 # don't let @iframe have scrollbars
733 @idoc.head.appendChild domify @idoc, style: children: [domify @idoc, text: "body { overflow: hidden; }"]
736 istyle = domify @idoc, link: rel: 'stylesheet', href: @options.css_file
739 @idoc.head.appendChild istyle
742 init_2: -> # @iframe and it's css file(s) are ready
743 @overlay.onclick = (e) =>
745 return event_return e, @onclick e
746 @overlay.ondoubleclick = (e) =>
748 return event_return e, @ondoubleclick e
749 @outer_idoc.body.onkeyup = (e) =>
751 return event_return e, @onkeyup e
752 @outer_idoc.body.onkeydown = (e) =>
754 return event_return e, @onkeydown e
755 @outer_idoc.body.onkeypress = (e) =>
757 return event_return e, @onkeypress e
758 @load_html @in_el.value
761 generate_outer_css: (args) ->
764 inner_padding = args.inner_padding ? overlay_padding
765 frame_width = args.frame_width ? inner_padding
766 occupy = (left, top = left, right = left, bottom = top) ->
769 return Math.max(left, top, right, bottom)
774 ret += 'color: black;'
775 ret += 'background: white;'
778 ret += "border: #{occupy 1}px solid black;"
779 ret += "padding: #{occupy frame_width}px;"
782 ret += "border: #{occupy 1}px solid black;"
783 @wrap2_height = h # including padding because padding scrolls
784 ret += "padding: #{occupy inner_padding}px;"
785 ret += "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
786 ret += "width: #{w}px;"
787 ret += "height: #{h}px;"
788 ret += 'overflow-x: hidden;'
789 ret += 'overflow-y: scroll;'
792 ret += 'position: relative;'
793 ret += "width: #{w}px;"
794 ret += "min-height: #{h}px;"
797 ret += 'box-sizing: border-box;'
799 ret += 'border: none;'
801 ret += "width: #{w}px;"
802 #ret += "height: #{h}px;" # height auto-set when content set/changed
803 ret += '-ms-user-select: none;'
804 ret += '-webkit-user-select: none;'
805 ret += '-moz-user-select: none;'
806 ret += 'user-select: none;'
809 ret += 'position: absolute;'
810 ret += "left: -#{inner_padding}px;"
811 ret += "top: -#{inner_padding}px;"
812 ret += "right: -#{inner_padding}px;"
813 ret += "bottom: -#{inner_padding}px;"
814 ret += 'overflow: hidden;'
817 ret += 'position: absolute;'
818 ret += 'background: rgba(100,100,100,0.2);'
821 ret += 'position: absolute;'
823 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));'
824 ret += 'background-size: 200% 200%;'
825 ret += '-webkit-animation: blink 1s linear normal infinite;'
826 ret += 'animation: blink 1s linear normal infinite;'
828 ret += '@-webkit-keyframes blink {'
829 ret += '0%{background-position:0% 0%}'
830 ret += '100%{background-position:0% -100%}'
832 ret += '@keyframes blink { '
833 ret += '0%{background-position:0% 0%}'
834 ret += '100%{background-position:0% -100%}'
838 ret += 'position: absolute;'
839 ret += 'border: 1px solid rgba(0,0,0,0.1);'
840 ret += 'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
843 ret += 'z-index: 10;'
844 ret += 'position: absolute;'
845 ret += 'font-size: 8px;'
846 ret += 'white-space: pre;'
847 ret += 'background: rgba(255,255,255,0.4);'
848 ret += '-ms-user-select: none;'
849 ret += '-webkit-user-select: none;'
850 ret += '-moz-user-select: none;'
851 ret += 'user-select: none;'
854 overlay_event_to_inner_xy: (e) ->
855 unless @wrap2_offset?
856 @wrap2_offset = get_el_bounds @wrap2
857 x = e.pageX - overlay_padding
858 y = e.pageY - overlay_padding + @wrap2.scrollTop
859 return x: x - @wrap2_offset.x, y: y - @wrap2_offset.y
861 xy = @overlay_event_to_inner_xy e
862 new_cursor = xy_to_cursor @tree, xy
864 @move_cursor new_cursor
868 ondoubleclick: (e) ->
872 return false if ignore_key_codes[e.keyCode]?
873 #return false if control_key_codes[e.keyCode]?
876 return false if ignore_key_codes[e.keyCode]?
877 #return false if control_key_codes[e.keyCode]?
881 new_cursor = find_prev_cursor_position @tree, @cursor
883 new_cursor = first_cursor_position @tree
885 @move_cursor new_cursor
889 new_cursor = find_next_cursor_position @tree, @cursor
891 new_cursor = last_cursor_position @tree
893 @move_cursor new_cursor
897 new_cursor = find_up_cursor_position @tree, @cursor, @cursor_ideal_x
899 saved_ideal_x = @cursor_ideal_x
900 @move_cursor new_cursor
901 @cursor_ideal_x = saved_ideal_x
903 # move cursor to first position in document
904 new_cursor = first_cursor_position @tree
906 @move_cursor new_cursor
910 new_cursor = find_down_cursor_position @tree, @cursor, @cursor_ideal_x
912 saved_ideal_x = @cursor_ideal_x
913 @move_cursor new_cursor
914 @cursor_ideal_x = saved_ideal_x
916 # move cursor to first position in document
917 new_cursor = last_cursor_position @tree
919 @move_cursor new_cursor
922 new_cursor = last_cursor_position @tree
924 @move_cursor new_cursor
930 return false unless @cursor?
931 return false unless @cursor.i < @cursor.n.text.length
932 @remove_character @cursor.n, @cursor.i
933 @adjust_whitespace_style @cursor.n
935 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i
937 @move_cursor new_cursor
948 new_cursor = first_cursor_position @tree
950 @move_cursor new_cursor
964 return false if ignore_key_codes[e.keyCode]?
965 char = e.charCode ? e.keyCode
967 char = String.fromCharCode char
968 @insert_character @cursor.n, @cursor.i, char
969 @adjust_whitespace_style @cursor.n
971 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i + 1
973 @move_cursor new_cursor
975 console.log "ERROR: couldn't find cursor position after insert"
978 on_key_enter: (e) -> # enter key pressed
979 return unless @cursor_visible
980 cur_block = @cursor.n
982 if cur_block.type is 'tag'
983 if is_display_block cur_block.el
985 return unless cur_block.parent?
986 cur_block = cur_block.parent
987 # find array to insert new element into
988 if cur_block.parent is @tree_parent # top-level
989 parent_el = @idoc.body
992 parent_el = cur_block.parent.el
993 pc = cur_block.parent.children
994 # find index of current block in its parent
996 break if n is cur_block
997 i += 1 # we want to be after it
1002 # TODO if content after cursor
1003 # TODO new block is empty
1004 new_text = new peach_parser.Node 'text', text: ' '
1005 new_node = new peach_parser.Node 'tag', name: 'p', parent: cur_block.parent, attrs: {style: 'white-space: pre-wrap'}, children: [new_text]
1006 new_text.parent = new_node
1007 new_text.el = domify @idoc, text: ' '
1008 new_node.el = domify @idoc, p: style: 'white-space: pre-wrap', children: [new_text.el]
1009 pc.splice i, 0, new_node
1010 parent_el.insertBefore new_node.el, before
1012 new_cursor = new_cursor_position n: new_text, i: 0
1013 throw 'bork bork' unless new_cursor?
1014 @move_cursor new_cursor
1015 # TODO move content past cursor into this new block
1016 on_key_backspace: (e) ->
1017 return false unless @cursor?
1018 if @is_lone_space @cursor.n # false if it's not in a tag
1020 # don't delete the space, because then it would collapse
1021 # instead leave a space after the cursor
1022 new_cursor = new_cursor_position n: @cursor.n, i: 0
1024 @move_cursor new_cursor
1028 parent = @cursor.n.parent
1029 new_cursor = find_prev_cursor_position @tree, @cursor
1031 if new_cursor.n is @cursor.n or new_cursor.n is parent
1033 tag = @cursor.n.parent
1034 if tag is @tree_parent
1035 console.log "top-level text not supported" # FIXME
1037 for n, i in tag.parent.children
1039 tag.parent.el.removeChild tag.el
1040 tag.parent.children.splice i, 1
1044 # re-check, in case it moved or is invalid now
1045 new_cursor = new_cursor_position n: new_cursor.n, i: new_cursor.i
1047 @move_cursor new_cursor
1049 new_cursor = first_cursor_position @tree
1051 @move_cursor new_cursor
1055 else if @cursor.i is 0
1056 console.log 'unimplemented: backspace at start of non-empty tag'
1057 # TODO if block, merge parent into prev
1058 # TODO if inline, delete char from prev text node
1061 # TODO handle case of removing last char
1063 if @is_only_char_in_tag @cursor.n
1064 if is_display_block @cursor.n.parent.el
1065 @cursor.n.el.textContent = @cursor.n.text = ' '
1067 console.log "unimplemented: delete last char in inline" # FIXME
1070 @remove_character @cursor.n, @cursor.i - 1
1071 @adjust_whitespace_style @cursor.n
1073 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i - 1
1075 @move_cursor new_cursor
1079 on_page_up_key: (e) ->
1081 screen_y = @cursor.y - @wrap2.scrollTop
1082 scroll_amount = @wrap2_height - breathing_room
1083 @wrap2.scrollTop = Math.max 0, @wrap2.scrollTop - scroll_amount
1085 @move_cursor_into_view screen_y + @wrap2.scrollTop
1086 on_page_down_key: (e) ->
1088 screen_y = @cursor.y - @wrap2.scrollTop
1089 scroll_amount = @wrap2_height - breathing_room
1090 lowest_scrollpos = @wrap2.scrollHeight - @wrap2_height
1091 if @wrap2.scrollTop is lowest_scrollpos # already at bottom
1092 return unless @cursor?
1093 # move cursor to bottom
1094 new_cursor = last_cursor_position @tree
1096 if new_cursor.n isnt @cursor.n or new_cursor.i isnt @cursor.i
1097 @move_cursor new_cursor
1099 @wrap2.scrollTop = Math.min lowest_scrollpos, @wrap2.scrollTop + scroll_amount
1101 @move_cursor_into_view screen_y + @wrap2.scrollTop
1103 move_cursor_into_view: (y_target) ->
1104 return if y_target is @cursor.y
1106 y_min = @wrap2.scrollTop
1107 unless @wrap2.scrollTop is 0
1108 y_min += breathing_room
1109 y_max = @wrap2.scrollTop + @wrap2_height
1110 unless @wrap2.scrollTop is @wrap2.scrollHeight - @wrap2_height # downmost
1111 y_max -= breathing_room
1112 y_target = Math.min y_target, y_max
1113 y_target = Math.max y_target, y_min
1114 if y_target < @cursor.y
1115 finder = find_up_cursor_position
1116 far_enough = (cur, target_y) ->
1117 return cur.y + cur.h <= target_y
1119 finder = find_down_cursor_position
1120 far_enough = (cur, y_target) ->
1121 return cur.y >= y_target
1123 cur = finder @tree, was, @cursor_ideal_x
1125 break if far_enough cur, y_target
1130 if was.y + was.h > y_max
1132 else if was.y < y_min
1135 if cur.y + cur.h > y_max
1137 else if cur.y < y_min
1140 # both valid, pick best
1143 else if was.y + was.h > y_max
1145 else if cur.y - y_target < y_target - was.y
1150 new_cursor = was ? cur
1152 saved_ideal_x = @cursor_ideal_x
1153 @move_cursor new_cursor
1154 @cursor_ideal_x = saved_ideal_x
1156 clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
1157 while @idoc.body.childNodes.length
1158 @idoc.body.removeChild @idoc.body.childNodes[0]
1161 load_html: (html) ->
1162 @tree = peach_parser.parse html, @parser_opts
1163 if !@tree[0]?.parent
1164 @tree = peach_parser.parse '<p style="white-space: pre-wrap"> </p>', @parser_opts
1165 @tree_parent = @tree[0]?.parent
1166 @tree_parent.el = @idoc.body
1168 instantiate_tree @tree, @tree_parent.el
1169 tree_dedup_space @tree
1172 @in_el.onchange = null
1173 @in_el.value = @pretty_html @tree
1174 @in_el.onchange = =>
1175 @load_html @in_el.value
1176 @adjust_iframe_height()
1177 adjust_iframe_height: ->
1178 s = @wrap2.scrollTop
1179 # when the content gets shorter, the idoc's body tag will continue to
1180 # report the old (too big) height in Chrome. The workaround is to
1181 # shrink the iframe before the content height:
1182 @iframe.style.height = "10px"
1183 h = parseInt(@idoc.body.scrollHeight, 10)
1184 @iframe.style.height = "#{h}px"
1185 @wrap2.scrollTop = s
1186 # does this node have whitespace that would be collapsed by white-space: normal?
1187 # note: this checks direct text children, and does _not_ recurse into child tags
1188 # tag is a node with type:"tag"
1189 has_collapsable_space: (tag) ->
1190 for n in tag.children
1192 for i in [0...n.text.length]
1193 code = n.text.charCodeAt i
1194 if code isnt 32 and is_space_code code
1197 # check for double spaces that don't surround insert location
1199 if n.text.substr(i - 1, 2) is ' '
1201 if n.text.length > 0
1202 if is_space_code n.text.charCodeAt 0
1204 if is_space_code n.text.charCodeAt n.text.length - 1
1206 # add/remove "white-space: pre[-wrap]" to/from style="" on tags with direct
1207 # child text nodes with multiple spaces in a row, or spaces at the
1210 # text inside child tags are not consulted. Child tags are expected to have
1211 # this function applied to them when their content changes.
1212 adjust_whitespace_style: (n) ->
1215 return unless n?.el?
1216 # which css rule should be used to preserve spaces (should we need to)
1217 style = @iframe.contentWindow.getComputedStyle n.el, null
1218 ws = style.getPropertyValue 'white-space'
1219 if ws_props[ws].space
1222 preserve_rule = ws_props[ws].to_preserve
1223 preserve_rule = "white-space: #{preserve_rule}"
1224 if @has_collapsable_space n
1225 # make sure preserve_rule exists
1226 if n.el.style['white-space']
1227 # FIXME check that it matches
1230 n.attrs.style += "; #{preserve_rule}"
1232 n.attrs.style = preserve_rule
1233 n.el.setAttribute 'style', n.attrs.style
1235 # remove preserve_rule if it exists
1236 return unless n.attrs.style?
1237 # FIXME don't assume whitespace is just so
1238 if n.attrs.style is "white-space: #{ws}"
1239 delete n.attrs.style
1240 n.el.removeAttribute 'style'
1242 # FIXME find it in the middle and at the start
1243 needle = "; white-space: #{ws}"
1244 if needle is n.attrs.style.substr n.attrs.style.length - needle
1245 n.attrs.style = n.attrs.style.substr 0, n.attrs.style.length - needle
1246 n.el.setAttribute n.attrs.style
1247 # true if n is text node with only one caracter, and the only child of a tag
1248 is_only_char_in_tag: (n, i) ->
1249 return false unless n.type is 'text'
1250 return false unless n.text.length is 1
1251 return false if n.parent is @tree_parent
1252 return false unless n.parent.children.length is 1
1254 # true if n is text node with just a space in it, and the only child of a tag
1255 is_lone_space: (n, i) ->
1256 return false unless n.type is 'text'
1257 return false unless n.text is ' '
1258 return false if n.parent is @tree_parent
1259 return false unless n.parent.children.length is 1
1261 # detect special case: typing before a space that's the only thing in a block/doc
1262 # reason: enter key creates blocks with just a space in them
1263 insert_should_replace: (n, i) ->
1264 return false unless i is 0
1265 return false unless n.text is ' '
1266 return true if n.parent is @tree_parent
1267 if n.parent.children.length is 1
1268 if n.parent.children[0] is n
1272 # after calling this, you MUST call changed() and adjust_whitespace_style()
1273 insert_character: (n, i, char) ->
1274 return if @cursor.n.parent is @tree_parent # FIXME implement text nodes at top level
1275 parent = @cursor.n.parent
1276 # insert the character
1277 if @insert_should_replace n, i
1280 n.text = char + n.text
1281 else if i is n.text.length
1286 n.text.substr(0, i) +
1289 n.el.nodeValue = n.text
1290 # after calling this, you MUST call changed() and adjust_whitespace_style()
1291 remove_character: (n, i) ->
1292 n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1293 n.el.nodeValue = n.text
1294 kill_cursor: -> # remove it, forget where it was
1296 @cursor_el.parentNode.removeChild @cursor_el
1297 @cursor_visible = false
1300 move_cursor: (cursor) ->
1301 @cursor_ideal_x = cursor.x
1303 unless @cursor_visible
1304 @cursor_el = domify @outer_idoc, div: id: 'cursor'
1305 @overlay.appendChild @cursor_el
1306 @cursor_visible = true
1307 @cursor_el.style.left = "#{cursor.x + overlay_padding - 1}px"
1312 @cursor_el.style.top = "#{cursor.y + overlay_padding + Math.round(height * .07)}px"
1313 @cursor_el.style.height = "#{Math.round height * 0.82}px"
1315 @scroll_into_view cursor.y, height
1316 scroll_into_view: (y, h = 0) ->
1317 y += overlay_padding # convert units from @idoc to @wrap2
1318 # very top of document
1319 if y <= breathing_room
1320 @wrap2.scrollTop = 0
1322 # very bottom of document
1323 if y + h >= @wrap2.scrollHeight - breathing_room
1324 @wrap2.scrollTop = @wrap2.scrollHeight - @wrap2_height
1326 # The most scrolled up (lowest value for scrollTop) that would be OK
1327 upmost = y + h + breathing_room - @wrap2_height
1328 upmost = Math.max(upmost, 0)
1329 # the most scrolled down (highest value for scrollTop) that would be OK
1330 downmost = y - breathing_room
1331 downmost = Math.min(downmost, @wrap2.scrollHeight - @wrap2_height)
1332 if upmost > downmost # means h is too big to fit
1333 # scroll so top is visible
1334 @wrap2.scrollTop = downmost
1336 if @wrap2.scrollTop < upmost
1337 @wrap2.scrollTop = upmost
1339 if @wrap2.scrollTop > downmost
1340 @wrap2.scrollTop = downmost
1344 while @matting.length > 0
1345 @overlay.removeChild @matting[0]
1348 prev_bounds = x: 0, y: 0, w: 0, h: 0
1350 while n?.el? and n isnt @tree_parent
1354 bounds = get_el_bounds n.el
1355 return unless bounds?
1356 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
1359 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});
1360 @overlay.appendChild ann_box
1361 @matting.push ann_box
1362 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} "]
1363 @overlay.appendChild ann_tag
1364 @matting.push ann_tag
1367 pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
1369 want_nl = parent_flags.want_nl
1370 prev_in_flow_is_text = false
1371 prev_in_flow_is_block = false
1374 inner_flags = want_nl: true
1381 if n.el.currentStyle?
1382 cs = n.el.currentStyle
1383 whitespace = cs['white-space']
1384 display = cs['display']
1385 position = cs['position']
1387 visibility = cs['visibility']
1389 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
1390 whitespace = cs.getPropertyValue 'white-space'
1391 display = cs.getPropertyValue 'display'
1392 position = cs.getPropertyValue 'position'
1393 float = cs.getPropertyValue 'float'
1394 visibility = cs.getPropertyValue 'visibility'
1395 if n.name is 'textarea'
1396 inner_flags.pre_ish = true
1398 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
1400 when 'left', 'right'
1404 when 'absolute', 'fixed'
1407 if 'display' is 'none'
1411 when 'hidden', 'collapse'
1416 when 'inline', 'none'
1417 inner_flags.block = false
1418 is_block = in_flow_block = false
1420 inner_flags.block = true
1421 is_block = in_flow_block = false
1422 else # block, table, etc
1423 inner_flags.block = true
1425 in_flow_block = in_flow
1430 in_flow_block = false
1431 else # 'comment', 'doctype'
1435 in_flow_block = false
1436 # print whitespace if we can
1437 unless parent_flags.pre_ish
1438 unless prev_in_flow_is_text and is_br
1439 if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
1452 if n.attrs[k].length > 0
1453 ret += "=\"#{enc_attr n.attrs[k]}\""
1455 unless void_elements[n.name]?
1456 if inner_flags.block
1457 next_indent = indent + ' '
1459 next_indent = indent
1460 if n.children.length
1461 ret += @pretty_html n.children, next_indent, inner_flags
1462 ret += "</#{n.name}>"
1464 ret += enc_text n.text
1466 ret += "<!--#{n.text}-->" # TODO encode?
1468 ret += "<!DOCTYPE #{n.name}"
1469 if n.public_identifier? and n.public_identifier.length > 0
1470 ret += " \"#{n.public_identifier}\""
1471 if n.system_identifier? and n.system_identifier.length > 0
1472 ret += " \"#{n.system_identifier}\""
1476 prev_in_flow_is_text = is_text
1477 prev_in_flow_is_block = is_block or (in_flow and is_br)
1479 # output final newline if allowed
1480 unless parent_flags.pre_ish
1481 if prev_in_flow_is_block or parent_flags.block
1482 ret += "\n#{indent.substr 4}"
1487 @editor_is_focused = true
1490 return if @poll_for_blur_timeout? # already polling
1491 @poll_for_blur_timeout = timeout 150, =>
1492 next_frame => # pause polling when browser knows we're not active/visible/etc.
1493 @poll_for_blur_timeout = null
1494 if document.activeElement is @outer_iframe
1497 @editor_is_focused = false
1500 window.peach_html5_editor = (args...) ->
1501 return new PeachHTML5Editor args...
1503 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])