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 debug_dot_at = (doc, x, y) ->
24 el = doc.createElement 'div'
25 el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
26 doc.body.appendChild el
27 #console.log(new Error().stack)
29 # text nodes don't have getBoundingClientRect(), so use selection api to find
31 get_el_bounds = (el) ->
32 if el.getBoundingClientRect?
33 rect = el.getBoundingClientRect()
35 # text nodes don't have getBoundingClientRect(), so use range api
36 range = el.ownerDocument.createRange()
37 range.selectNodeContents el
38 rect = range.getBoundingClientRect()
39 doc = el.ownerDocument.documentElement
40 win = el.ownerDocument.defaultView
41 y_fix = win.pageYOffset - doc.clientTop
42 x_fix = win.pageXOffset - doc.clientLeft
46 w: rect.width ? (rect.right - rect.left)
47 h: rect.height ? (rect.top - rect.bottom)
50 is_display_block = (el) ->
52 return el.currentStyle.display is 'block'
54 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
56 # Pass return value from dom event handlers to this.
57 # If they return false, this will addinionally stop propagation and default.
58 event_return = (e, bool) ->
65 # Warning: currently assumes you're asking about a single character
66 # Note: chromium returns multiple bounding rects for a space at a line-break
67 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
68 # Note: sometimes returns null (eg for whitespace that is not visible)
69 text_range_bounds = (el, start, end) ->
70 range = document.createRange()
71 range.setStart el, start
73 rects = range.getClientRects()
78 doc = el.ownerDocument.documentElement
79 win = el.ownerDocument.defaultView
80 y_fix = win.pageYOffset - doc.clientTop
81 x_fix = win.pageXOffset - doc.clientLeft
85 w: rect.width ? (rect.right - rect.left)
86 h: rect.height ? (rect.top - rect.bottom)
88 bounding: range.getBoundingClientRect()
91 # figure out the x/y coordinates of where the cursor should be if it's at
92 # position ``i`` within text node ``n``
93 # sometimes returns null (eg for whitespace that is not visible)
94 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
95 range = document.createRange()
97 ret = text_range_bounds n.el, 0, 0
98 else if i is n.text.length
99 ret = text_range_bounds n.el, i - 1, i
103 ret = text_range_bounds n.el, i, i + 1
105 debug_dot_at n.el.ownerDocument, ret.x, ret.y
108 # encode text so it can be safely placed inside an html attribute
109 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
111 return txt.replace enc_attr_regex, (match, amp, quote) ->
112 return '&' if (amp)
113 return '"' if (quote)
115 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
117 return txt.replace enc_text_regex, (match, amp, lt) ->
118 return '&' if (amp)
119 return '<' if (lt)
139 # TODO make these always pretty-print (on the inside) like blocks
140 no_text_elements = { # these elements never contain text
150 domify = (doc, hash) ->
151 for tag, attrs of hash
153 return document.createTextNode attrs
154 el = document.createElement tag
163 outer_css = (args) ->
166 inner_padding = args.inner_padding ? overlay_padding
167 frame_width = args.frame_width ? inner_padding
168 # TODO editor controls height...
169 occupy = (left, top = left, right = left, bottom = top) ->
172 return Math.max(left, top, right, bottom)
179 ret += "border: #{occupy 1}px solid black;"
180 ret += "padding: #{occupy frame_width}px;"
183 ret += "border: #{occupy 1}px solid black;"
184 ret += "padding: #{occupy inner_padding}px;"
185 ret += "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
186 ret += "width: #{w}px;"
187 ret += "height: #{h}px;"
188 ret += 'overflow-x: hidden;'
189 ret += 'overflow-y: scroll;'
192 ret += 'position: relative;'
193 ret += "width: #{w}px;"
194 ret += "min-height: #{h}px;"
197 ret += 'box-sizing: border-box;'
199 ret += 'border: none;'
201 ret += "width: #{w}px;"
202 #ret += "height: #{h}px;" # height auto-set when content set/changed
203 ret += '-ms-user-select: none;'
204 ret += '-webkit-user-select: none;'
205 ret += '-moz-user-select: none;'
206 ret += 'user-select: none;'
209 ret += 'position: absolute;'
210 ret += "left: -#{inner_padding}px;"
211 ret += "top: -#{inner_padding}px;"
212 ret += "right: -#{inner_padding}px;"
213 ret += "bottom: -#{inner_padding}px;"
214 ret += 'overflow: hidden;'
217 ret += 'position: absolute;'
218 ret += 'background: rgba(100,100,100,0.2);'
221 ret += 'position: absolute;'
222 ret += 'height: 1em;' # FIXME adjust for hight of text
224 ret += 'background: #444;'
225 ret += '-webkit-animation: blink 1s steps(2, start) infinite;'
226 ret += 'animation: blink 1s steps(2, start) infinite;'
228 ret += '@-webkit-keyframes blink {'
229 ret += 'to { visibility: hidden; }'
231 ret += '@keyframes blink {'
232 ret += 'to { visibility: hidden; }'
236 ret += 'position: absolute;'
237 ret += 'border: 1px solid rgba(0,0,0,0.1);'
238 ret += 'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
241 ret += 'z-index: 10;'
242 ret += 'position: absolute;'
243 ret += 'font-size: 8px;'
244 ret += 'white-space: pre;'
245 ret += 'background: rgba(255,255,255,0.4);'
254 KEY_BACKSPACE = 8 # <--
255 KEY_DELETE = 46 # -->
267 '20': true # capslock
269 '144': true # numlock
271 '91': true # windows "start" key
272 control_key_codes = # we react to these, but they aren't typing
288 instantiate_tree = (tree, parent) ->
293 c.el = parent.ownerDocument.createTextNode c.text
294 parent.appendChild c.el
296 if c.name in ['script', 'object', 'iframe', 'link']
297 # TODO put placeholders instead
299 # TODO create in correct namespace
300 c.el = parent.ownerDocument.createElement c.name
302 # FIXME if attr_whitelist[k]?
303 c.el.setAttribute k, v
304 parent.appendChild c.el
306 instantiate_tree c.children, c.el
310 traverse_tree = (tree, cb) ->
316 done = traverse_tree c.children, cb
320 find_next_cursor_position = (tree, n, i) ->
321 if n.type is 'text' and n.text.length > i
322 orig_xyh = cursor_to_xyh n, i
324 console.log "ERROR: couldn't find xy for current cursor location"
326 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
327 next_xyh = cursor_to_xyh n, next_i
329 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
333 traverse_tree tree, (node, state) ->
334 if node.type is 'text' and state_before is false
335 if cursor_to_xyh(node, 0)?
345 find_prev_cursor_position = (tree, n, i) ->
346 if n? and n.type is 'text' and i > 0
347 orig_xyh = cursor_to_xyh n, i
349 console.log "ERROR: couldn't find xy for current cursor location"
351 for prev_i in [i-1 .. 0]
352 prev_xyh = cursor_to_xyh n, prev_i
354 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
359 traverse_tree tree, (node) ->
360 if node.type is 'text'
368 if cursor_to_xyh found, found.text.length # text visible?
369 return [found, found.text.length]
370 return find_prev_cursor_position tree, found, 0
373 find_loc_cursor_position = (tree, loc) ->
375 if c.type is 'tag' or c.type is 'text'
376 bounds = get_el_bounds c.el
377 continue if loc.x < bounds.x
378 continue if loc.x > bounds.x + bounds.w
379 continue if loc.y < bounds.y
380 continue if loc.y > bounds.y + bounds.h
382 ret = find_loc_cursor_position c.children, loc
385 # click is within bounding box that contains all text.
386 return [c, 0] if c.text.length is 0
388 before = cursor_to_xyh c, before_i
390 console.log "error: failed to find cursor pixel location for start of", c
392 after_i = c.text.length
393 after = cursor_to_xyh c, after_i
395 console.log "error: failed to find cursor pixel location for end of", c
397 if loc.y < before.y + before.h and loc.x < before.x
398 # console.log 'before first char on first line'
400 if loc.y > after.y and loc.x > after.x
401 # console.log 'after last char on last line'
404 console.log "Warning: click in bounding box but above first line"
405 continue # above first line (runaround?)
406 if loc.y > after.y + after.h
407 console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
408 continue # below last line (shouldn't happen?)
409 while after_i - before_i > 1
410 cur_i = Math.round((before_i + after_i) / 2)
411 cur = cursor_to_xyh c, cur_i
413 console.log "error: failed to find cursor pixel location for", c, cur_i
415 if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
421 # which one is closest?
422 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
428 # browsers collapse these (html5 spec calls these "space characters")
429 is_space_code = (char_code) ->
431 when 9, 10, 12, 13, 32
435 return is_space_code chr.charCodeAt 0
437 tree_remove_empty_text_nodes = (tree) ->
439 traverse_tree tree, (n) ->
441 if n.text.length is 0
445 # don't completely empty the tree
447 if tree[0].type is 'text'
448 console.log "oop, leaving a blank node because it's the only thing"
450 n.el.parentNode.removeChild n.el
451 for c, i in n.parent.children
453 n.parent.children.splice i, 1
456 # pass a array of nodes (from parser library, ie it should have .el and .text)
457 tree_dedup_space = (tree) ->
458 prev = cur = next = null
459 prev_i = cur_i = next_i = 0
460 prev_pos = pos = next_pos = null
461 prev_px = cur_px = next_px = null
465 tree_remove_empty_text_nodes(tree)
467 iterate = (tree, cb) ->
471 while i < n.text.length # don't foreach, cb might remove chars
476 block = is_display_block n.el
479 if n.children.length > 0
480 iterate n.children, cb
485 removed_char = cur.text.charAt(cur_i)
486 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
487 if next is cur # in same text node
489 throw "how is this possible?"
494 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
495 if next is cur # in same text node
498 # return true if cur was removed from the dom (ie re-use same prev)
500 # cur definitately set
501 # prev and/or next might be null, indicating the start/end of a display:block
502 return false unless is_space_code cur.text.charCodeAt cur_i
503 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
505 # 1. zero rects returned by getClientRects() means collapsed space
508 # 2. width greater than zero means visible space
511 # now the weird edge cases...
513 # firefox and chromium both report zero width for characters at the end
514 # of a line where the text wraps (automatically, due to word-wrap) to
515 # the next line. These do not appear to be distinguishable from
516 # collapsed spaces via the range/bounds api, so...
518 # remove it from the dom, and if prev or next moves, put it back.
519 if prev? and not prev_px?
520 prev_px = cursor_to_xyh prev, prev_i
521 if next? and not next_px?
522 next_px = cursor_to_xyh next, next_i
523 #if prev is null and next is null
524 # parent_px = cur.parent.el.getBoundingClientRect()
528 new_prev_px = cursor_to_xyh prev, prev_i
529 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
532 console.log "this shouldn't happen, we remove spaces that don't locate"
535 new_next_px = cursor_to_xyh next, next_i
536 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
539 # console.log "removing space becase space after it is collapsed"
541 # pass null at start/end of display:block
549 # don't advance (to the next character next time) if we removed a
550 # character from the same text node as ``next``, because doing so
551 # renumbers the indexes in that string
552 if removed and cur is next
568 tree_remove_empty_text_nodes(tree)
570 class PeachHTML5Editor
571 # Options: (all optional)
572 # editor_id: "id" attribute for outer-most element created by/for editor
573 # on_init: callback for when the editable content is in place
574 constructor: (in_el, options) ->
575 @options = options ? {}
579 @inited = false # when iframes have loaded
580 @outer_iframe # iframe to hold editor
581 @outer_idoc # "document" object for @outer_iframe
582 @wrap2 = null # scrollbar is on this
583 @iframe = null # iframe to hold editable content
584 @idoc = null # "document" object for @iframe
587 @cursor_visible = false
588 @iframe_offset = null
589 opt_fragment = @options.fragment ? true
592 @parser_opts.fragment = 'body'
594 @outer_iframe = domify document, iframe: {}
595 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
596 if @options.editor_id?
597 @outer_iframe.setAttribute 'id', @options.editor_id
598 @outer_iframe.onload = =>
599 @outer_idoc = @outer_iframe.contentDocument
600 icss = domify @outer_idoc, style: children: [
601 domify @outer_idoc, text: css
603 @outer_idoc.head.appendChild icss
604 @iframe = domify @outer_idoc, iframe: {}
607 setTimeout (=> @init() unless @inited), 200 # firefox never fires this onload
608 @outer_idoc.body.appendChild(
609 domify @outer_idoc, div: id: 'wrap1', children: [
610 @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
611 domify @outer_idoc, div: id: 'wrap3', children: [
613 @overlay = domify @outer_idoc, div: id: 'overlay'
618 outer_wrap = domify document, div: class: 'peach_html5_editor'
619 @in_el.parentNode.appendChild outer_wrap
620 outer_bounds = get_el_bounds outer_wrap
621 if outer_bounds.w < 300
623 if outer_bounds.h < 300
625 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
626 @outer_iframe.setAttribute 'style', outer_iframe_style
627 css = outer_css w: outer_bounds.w, h: outer_bounds.h
628 outer_wrap.appendChild @outer_iframe
629 init: -> # called by @iframe's onload (or timeout on firefox)
630 @idoc = @iframe.contentDocument
631 @overlay.onclick = (e) =>
632 return event_return e, @onclick e
633 @overlay.ondoubleclick = (e) =>
634 return event_return e, @ondoubleclick e
635 @outer_idoc.body.onkeyup = (e) =>
636 return event_return e, @onkeyup e
637 @outer_idoc.body.onkeydown = (e) =>
638 return event_return e, @onkeydown e
639 @outer_idoc.body.onkeypress = (e) =>
640 return event_return e, @onkeypress e
641 if @options.stylesheet
643 @idoc.head.appendChild domify @idoc, style: src: @options.stylesheet
644 @load_html @in_el.value
648 overlay_event_to_inner_xy: (e) ->
649 unless @iframe_offset?
650 @iframe_offset = get_el_bounds @iframe
651 x = e.pageX # TODO ?cross-browserify
652 y = e.pageY + @wrap2.scrollTop # TODO ?cross-browserify
653 # TODO adjust for scrolling
654 return x: x - @iframe_offset.x, y: y - @iframe_offset.y
656 xy = @overlay_event_to_inner_xy e
657 new_cursor = find_loc_cursor_position @tree, xy
659 @move_cursor new_cursor
661 ondoubleclick: (e) ->
665 return false if ignore_key_codes[e.keyCode]?
666 #return false if control_key_codes[e.keyCode]?
669 return false if ignore_key_codes[e.keyCode]?
670 #return false if control_key_codes[e.keyCode]?
674 new_cursor = find_prev_cursor_position @tree, @cursor...
676 @move_cursor new_cursor
679 new_cursor = find_next_cursor_position @tree, c, -1
681 @move_cursor new_cursor
688 new_cursor = find_next_cursor_position @tree, @cursor...
690 @move_cursor new_cursor
693 new_cursor = find_prev_cursor_position @tree, c, -1
695 @move_cursor new_cursor
703 return false unless @cursor?
704 return false unless @cursor[1] > 0
705 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
706 @cursor[0].el.nodeValue = @cursor[0].text
707 @move_cursor [@cursor[0], @cursor[1] - 1]
711 return false unless @cursor?
712 return false unless @cursor[1] < @cursor[0].text.length
713 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
714 @cursor[0].el.nodeValue = @cursor[0].text
715 @move_cursor [@cursor[0], @cursor[1]]
734 return false if ignore_key_codes[e.keyCode]?
735 return false if control_key_codes[e.keyCode]? # handled in keydown
736 char = e.charCode ? e.keyCode
738 char = String.fromCharCode char
740 @cursor[0].text = char + @cursor[0].text
741 else if @cursor[1] is @cursor[0].text.length - 1
742 @cursor[0].text += char
745 @cursor[0].text.substr(0, @cursor[1]) +
747 @cursor[0].text.substr(@cursor[1])
748 @cursor[0].el.nodeValue = @cursor[0].text
749 @move_cursor [@cursor[0], @cursor[1] + 1]
752 clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
753 while @idoc.body.childNodes.length
754 @idoc.body.removeChild @idoc.body.childNodes[0]
758 @tree = peach_parser.parse html, @parser_opts
760 instantiate_tree @tree, @idoc.body
761 tree_dedup_space @tree
764 @in_el.onchange = null
765 @in_el.value = @pretty_html @tree
767 @load_html @in_el.value
768 @iframe.style.height = "0"
769 @iframe.style.height = "#{@idoc.body.scrollHeight}px"
770 kill_cursor: -> # remove it, forget where it was
772 @cursor_el.parentNode.removeChild @cursor_el
773 @cursor_visible = false
776 move_cursor: (cursor) ->
777 loc = cursor_to_xyh cursor[0], cursor[1]
779 console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
782 # replace cursor element, to reset blink animation
784 @cursor_el.parentNode.removeChild @cursor_el
785 @cursor_el = domify @outer_idoc, div: id: 'cursor'
786 @overlay.appendChild @cursor_el
787 @cursor_visible = true
788 @cursor_el.style.left = "#{loc.x + overlay_padding - 1}px"
789 @cursor_el.style.top = "#{loc.y + overlay_padding}px"
792 while @matting.length > 0
793 @overlay.removeChild @matting[0]
796 prev_bounds = x: 0, y: 0, w: 0, h: 0
802 bounds = get_el_bounds n.el
803 return unless bounds?
804 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
807 matt = 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});
808 @overlay.appendChild matt
810 ann = 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} "]
811 @overlay.appendChild ann
815 pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
817 want_nl = parent_flags.want_nl
818 prev_in_flow_is_text = false
819 prev_in_flow_is_block = false
822 inner_flags = want_nl: true
829 if n.el.currentStyle?
830 cs = n.el.currentStyle
831 whitespace = cs['white-space']
832 display = cs['display']
833 position = cs['position']
836 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
837 whitespace = cs.getPropertyValue 'white-space'
838 display = cs.getPropertyValue 'display'
839 position = cs.getPropertyValue 'position'
840 float = cs.getPropertyValue 'float'
841 if n.name is 'textarea'
842 inner_flags.pre_ish = true
844 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
850 when 'absolute', 'fixed'
853 if 'display' is 'none'
858 when 'inline', 'none'
859 inner_flags.block = false
860 is_block = in_flow_block = false
862 inner_flags.block = true
863 is_block = in_flow_block = false
864 else # block, table, etc
865 inner_flags.block = true
867 in_flow_block = in_flow
872 in_flow_block = false
873 else # 'comment', 'doctype'
877 in_flow_block = false
878 # print whitespace if we can
879 unless parent_flags.pre_ish
880 unless prev_in_flow_is_text and is_br
881 if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
894 if n.attrs[k].length > 0
895 ret += "=\"#{enc_attr n.attrs[k]}\""
897 unless void_elements[n.name]?
899 next_indent = indent + ' '
903 ret += @pretty_html n.children, next_indent, inner_flags
904 ret += "</#{n.name}>"
906 ret += enc_text n.text
908 ret += "<!--#{n.text}-->" # TODO encode?
910 ret += "<!DOCTYPE #{n.name}"
911 if n.public_identifier? and n.public_identifier.length > 0
912 ret += " \"#{n.public_identifier}\""
913 if n.system_identifier? and n.system_identifier.length > 0
914 ret += " \"#{n.system_identifier}\""
918 prev_in_flow_is_text = is_text
919 prev_in_flow_is_block = is_block or (in_flow and is_br)
921 # output final newline if allowed
922 unless parent_flags.pre_ish
923 if prev_in_flow_is_block or parent_flags.block
924 ret += "\n#{indent.substr 4}"
927 window.peach_html5_editor = (args...) ->
928 return new PeachHTML5Editor args...
930 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])