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 TYPE_TAG = peach_parser.TYPE_TAG
21 TYPE_TEXT = peach_parser.TYPE_TEXT
22 TYPE_COMMENT = peach_parser.TYPE_COMMENT
23 TYPE_DOCTYPE = peach_parser.TYPE_DOCTYPE
25 timeout = (ms, cb) -> return setTimeout cb, ms
27 debug_dot_at = (doc, x, y) ->
29 el = doc.createElement 'div'
30 el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
31 doc.body.appendChild el
32 #console.log(new Error().stack)
34 # text nodes don't have getBoundingClientRect(), so use selection api to find
36 get_el_bounds = (el) ->
37 if el.getBoundingClientRect?
38 rect = el.getBoundingClientRect()
40 # text nodes don't have getBoundingClientRect(), so use range api
41 range = el.ownerDocument.createRange()
42 range.selectNodeContents el
43 rect = range.getBoundingClientRect()
44 doc = el.ownerDocument.documentElement
45 win = el.ownerDocument.defaultView
46 y_fix = win.pageYOffset - doc.clientTop
47 x_fix = win.pageXOffset - doc.clientLeft
51 w: rect.width ? (rect.right - rect.left)
52 h: rect.height ? (rect.top - rect.bottom)
55 is_display_block = (el) ->
57 return el.currentStyle.display is 'block'
59 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
61 # pass a node (not an element) for a tag
62 # returns if this is the sort of tag that cares about leading/trailing whitespace
63 # FIXME this probably doesn't work all the time
64 is_whitespace_significant = (n) ->
65 if n.name is 'textarea'
70 return n.el.currentStyle['white-space'].substr(0, 3) is 'pre'
72 return window.getComputedStyle(n.el, null).getPropertyValue('white-space').substr(0, 3) is 'pre'
74 # Pass return value from dom event handlers to this.
75 # If they return false, this will addinionally stop propagation and default.
76 event_return = (e, bool) ->
83 # Warning: currently assumes you're asking about a single character
84 # Note: chromium returns multiple bounding rects for a space at a line-break
85 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
86 # Note: sometimes returns null (eg for whitespace that is not visible)
87 text_range_bounds = (el, start, end) ->
88 range = document.createRange()
89 range.setStart el, start
91 rects = range.getClientRects()
96 doc = el.ownerDocument.documentElement
97 win = el.ownerDocument.defaultView
98 y_fix = win.pageYOffset - doc.clientTop
99 x_fix = win.pageXOffset - doc.clientLeft
103 w: rect.width ? (rect.right - rect.left)
104 h: rect.height ? (rect.top - rect.bottom)
106 bounding: range.getBoundingClientRect()
109 # figure out the x/y coordinates of where the cursor should be if it's at
110 # position ``i`` within text node ``n``
111 # sometimes returns null (eg for whitespace that is not visible)
112 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
113 range = document.createRange()
114 if n.text.length is 0
115 ret = text_range_bounds n.el, 0, 0
116 else if i is n.text.length
117 ret = text_range_bounds n.el, i - 1, i
121 ret = text_range_bounds n.el, i, i + 1
123 debug_dot_at n.el.ownerDocument, ret.x, ret.y
126 # encode text so it can be safely placed inside an html attribute
127 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
129 return txt.replace enc_attr_regex, (match, amp, quote) ->
130 return '&' if (amp)
131 return '"' if (quote)
133 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
135 return txt.replace enc_text_regex, (match, amp, lt) ->
136 return '&' if (amp)
137 return '<' if (lt)
157 # TODO make these always pretty-print (on the inside) like blocks
158 no_text_elements = { # these elements never contain text
165 # FIXME terminology: s/dom/tree/; s/el/n/
166 tree_to_html = (tree, indent = '', parent_is_block = false) ->
171 is_block = is_display_block n.el
173 is_tiny_block = false
174 if is_whitespace_significant n
177 if n.children.length is 1
178 if n.children[0].type is TYPE_TEXT
179 if n.children[0].text.length < 35
181 if is_block or (parent_is_block and i is 0)
190 if n.attrs[k].length > 0
191 ret += "=\"#{enc_attr n.attrs[k]}\""
193 unless void_elements[n.name]?
195 next_indent = indent + ' '
199 if is_block and not is_tiny_block
201 ret += tree_to_html n.children, next_indent, is_block and not is_tiny_block
202 if is_block and not is_tiny_block
204 ret += "</#{n.name}>"
205 if is_block or (parent_is_block and i is tree.length - 1)
208 if parent_is_block and i is 0
210 ret += enc_text n.text
211 if parent_is_block and i is tree.length - 1
214 ret += "<!--#{n.text}-->"
216 ret += "<!DOCTYPE #{n.name}"
217 if n.public_identifier? and n.public_identifier.length > 0
218 ret += " \"#{n.public_identifier}\""
219 if n.system_identifier? and n.system_identifier.length > 0
220 ret += " \"#{n.system_identifier}\""
224 domify = (doc, hash) ->
225 for tag, attrs of hash
227 return document.createTextNode attrs
228 el = document.createElement tag
237 outer_css = (args) ->
240 inner_padding = args.inner_padding ? overlay_padding
241 frame_width = args.frame_width ? inner_padding
242 # TODO editor controls height...
243 occupy = (left, top = left, right = left, bottom = top) ->
246 return Math.max(left, top, right, bottom)
253 ret += "border: #{occupy 1}px solid black;"
254 ret += "padding: #{occupy frame_width}px;"
257 ret += "border: #{occupy 1}px solid black;"
258 ret += "padding: #{occupy inner_padding}px;"
259 ret += "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
260 ret += "width: #{w}px;"
261 ret += "height: #{h}px;"
262 ret += 'overflow-x: hidden;'
263 ret += 'overflow-y: scroll;'
266 ret += 'position: relative;'
267 ret += "width: #{w}px;"
268 ret += "min-height: #{h}px;"
271 ret += 'box-sizing: border-box;'
273 ret += 'border: none;'
275 ret += "width: #{w}px;"
276 #ret += "height: #{h}px;" # height auto-set when content set/changed
277 ret += '-ms-user-select: none;'
278 ret += '-webkit-user-select: none;'
279 ret += '-moz-user-select: none;'
280 ret += 'user-select: none;'
283 ret += 'position: absolute;'
284 ret += "left: -#{inner_padding}px;"
285 ret += "top: -#{inner_padding}px;"
286 ret += "right: -#{inner_padding}px;"
287 ret += "bottom: -#{inner_padding}px;"
288 ret += 'overflow: hidden;'
291 ret += 'position: absolute;'
292 ret += 'background: rgba(100,100,100,0.2);'
295 ret += 'position: absolute;'
296 ret += 'height: 1em;' # FIXME adjust for hight of text
298 ret += 'background: #444;'
299 ret += '-webkit-animation: blink 1s steps(2, start) infinite;'
300 ret += 'animation: blink 1s steps(2, start) infinite;'
302 ret += '@-webkit-keyframes blink {'
303 ret += 'to { visibility: hidden; }'
305 ret += '@keyframes blink {'
306 ret += 'to { visibility: hidden; }'
315 KEY_BACKSPACE = 8 # <--
316 KEY_DELETE = 46 # -->
328 '20': true # capslock
330 '144': true # numlock
332 '91': true # windows "start" key
333 control_key_codes = # we react to these, but they aren't typing
349 instantiate_tree = (tree, parent) ->
354 c.el = parent.ownerDocument.createTextNode c.text
355 parent.appendChild c.el
357 if c.name in ['script', 'object', 'iframe', 'link']
358 # TODO put placeholders instead
360 # TODO create in correct namespace
361 c.el = parent.ownerDocument.createElement c.name
363 # FIXME if attr_whitelist[k]?
364 c.el.setAttribute k, v
365 parent.appendChild c.el
367 instantiate_tree c.children, c.el
371 traverse_tree = (tree, cb) ->
377 done = traverse_tree c.children, cb
381 find_next_cursor_position = (tree, n, i) ->
382 if n.type is TYPE_TEXT and n.text.length > i
383 orig_xyh = cursor_to_xyh n, i
385 console.log "ERROR: couldn't find xy for current cursor location"
387 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
388 next_xyh = cursor_to_xyh n, next_i
390 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
394 traverse_tree tree, (node, state) ->
395 if node.type is TYPE_TEXT and state_before is false
396 if cursor_to_xyh(node, 0)?
406 find_prev_cursor_position = (tree, n, i) ->
407 if n? and n.type is TYPE_TEXT and i > 0
408 orig_xyh = cursor_to_xyh n, i
410 console.log "ERROR: couldn't find xy for current cursor location"
412 for prev_i in [i-1 .. 0]
413 prev_xyh = cursor_to_xyh n, prev_i
415 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
420 traverse_tree tree, (node) ->
421 if node.type is TYPE_TEXT
429 if cursor_to_xyh found, found.text.length # text visible?
430 return [found, found.text.length]
431 return find_prev_cursor_position tree, ret[0], 0
434 find_loc_cursor_position = (tree, loc) ->
436 if c.type is TYPE_TAG or c.type is TYPE_TEXT
437 bounds = get_el_bounds c.el
438 continue if loc.x < bounds.x
439 continue if loc.x > bounds.x + bounds.w
440 continue if loc.y < bounds.y
441 continue if loc.y > bounds.y + bounds.h
443 ret = find_loc_cursor_position c.children, loc
445 if c.type is TYPE_TEXT
446 # click is within bounding box that contains all text.
447 return [c, 0] if c.text.length is 0
449 before = cursor_to_xyh c, before_i
451 console.log "error: failed to find cursor pixel location for start of", c
453 after_i = c.text.length
454 after = cursor_to_xyh c, after_i
456 console.log "error: failed to find cursor pixel location for end of", c
458 if loc.y < before.y + before.h and loc.x < before.x
459 # console.log 'before first char on first line'
461 if loc.y > after.y and loc.x > after.x
462 # console.log 'after last char on last line'
465 console.log "Warning: click in bounding box but above first line"
466 continue # above first line (runaround?)
467 if loc.y > after.y + after.h
468 console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
469 continue # below last line (shouldn't happen?)
470 while after_i - before_i > 1
471 cur_i = Math.round((before_i + after_i) / 2)
472 cur = cursor_to_xyh c, cur_i
474 console.log "error: failed to find cursor pixel location for", c, cur_i
476 if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
482 # which one is closest?
483 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
489 # browsers collapse these (html5 spec calls these "space characters")
490 is_space_code = (char_code) ->
492 when 9, 10, 12, 13, 32
496 return is_space_code chr.charCodeAt 0
498 tree_remove_empty_text_nodes = (tree) ->
500 traverse_tree tree, (n) ->
501 if n.type is TYPE_TEXT
502 if n.text.length is 0
506 # don't completely empty the tree
508 if tree[0].type is TYPE_TEXT
509 console.log "oop, leaving a blank node because it's the only thing"
511 n.el.parentNode.removeChild n.el
512 for c, i in n.parent.children
514 n.parent.children.splice i, 1
517 # pass a array of nodes (from parser library, ie it should have .el and .text)
518 tree_dedup_space = (tree) ->
519 prev = cur = next = null
520 prev_i = cur_i = next_i = 0
521 prev_pos = pos = next_pos = null
522 prev_px = cur_px = next_px = null
526 tree_remove_empty_text_nodes(tree)
528 iterate = (tree, cb) ->
530 if n.type is TYPE_TEXT
532 while i < n.text.length # don't foreach, cb might remove chars
536 if n.type is TYPE_TAG
537 block = is_display_block n.el
540 if n.children.length > 0
541 iterate n.children, cb
546 removed_char = cur.text.charAt(cur_i)
547 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
548 if next is cur # in same text node
550 throw "how is this possible?"
555 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
556 if next is cur # in same text node
559 # return true if cur was removed from the dom (ie re-use same prev)
561 # cur definitately set
562 # prev and/or next might be null, indicating the start/end of a display:block
563 return false unless is_space_code cur.text.charCodeAt cur_i
564 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
566 # 1. zero rects returned by getClientRects() means collapsed space
569 # 2. width greater than zero means visible space
572 # now the weird edge cases...
574 # firefox and chromium both report zero width for characters at the end
575 # of a line where the text wraps (automatically, due to word-wrap) to
576 # the next line. These do not appear to be distinguishable from
577 # collapsed spaces via the range/bounds api, so...
579 # remove it from the dom, and if prev or next moves, put it back.
580 if prev? and not prev_px?
581 prev_px = cursor_to_xyh prev, prev_i
582 if next? and not next_px?
583 next_px = cursor_to_xyh next, next_i
584 #if prev is null and next is null
585 # parent_px = cur.parent.el.getBoundingClientRect()
589 new_prev_px = cursor_to_xyh prev, prev_i
590 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
593 console.log "this shouldn't happen, we remove spaces that don't locate"
596 new_next_px = cursor_to_xyh next, next_i
597 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
600 # console.log "removing space becase space after it is collapsed"
602 # pass null at start/end of display:block
610 # don't advance (to the next character next time) if we removed a
611 # character from the same text node as ``next``, because doing so
612 # renumbers the indexes in that string
613 if removed and cur is next
629 tree_remove_empty_text_nodes(tree)
631 class PeachHTML5Editor
632 # Options: (all optional)
633 # editor_id: "id" attribute for outer-most element created by/for editor
634 # on_init: callback for when the editable content is in place
635 constructor: (in_el, options) ->
636 @options = options ? {}
639 @inited = false # when iframes have loaded
640 @outer_iframe # iframe to hold editor
641 @outer_idoc # "document" object for @outer_iframe
642 @iframe = null # iframe to hold editable content
643 @idoc = null # "document" object for @iframe
646 @cursor_visible = false
647 opt_fragment = @options.fragment ? true
650 @parser_opts.fragment = 'body'
652 @outer_iframe = domify document, iframe: {}
653 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
654 if @options.editor_id?
655 @outer_iframe.setAttribute 'id', @options.editor_id
656 @outer_iframe.onload = =>
657 @outer_idoc = @outer_iframe.contentDocument
658 icss = domify @outer_idoc, style: children: [
659 domify @outer_idoc, text: css
661 @outer_idoc.head.appendChild icss
662 @iframe = domify @outer_idoc, iframe: {}
665 setTimeout (=> @init() unless @inited), 200 # firefox never fires this onload
666 @outer_idoc.body.appendChild(
667 domify @outer_idoc, div: id: 'wrap1', children: [
668 domify @outer_idoc, div: id: 'wrap2', children: [
669 domify @outer_idoc, div: id: 'wrap3', children: [
671 @overlay = domify @outer_idoc, div: id: 'overlay'
676 outer_wrap = domify document, div: class: 'peach_html5_editor'
677 @in_el.parentNode.appendChild outer_wrap
678 outer_bounds = get_el_bounds outer_wrap
679 if outer_bounds.w < 300
681 if outer_bounds.h < 300
683 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
684 @outer_iframe.setAttribute 'style', outer_iframe_style
685 css = outer_css w: outer_bounds.w, h: outer_bounds.h
686 outer_wrap.appendChild @outer_iframe
687 init: -> # called by @iframe's onload (or timeout on firefox)
688 @idoc = @iframe.contentDocument
689 @overlay.onclick = (e) =>
690 return event_return e, @onclick e
691 @overlay.ondoubleclick = (e) =>
692 return event_return e, @ondoubleclick e
693 @outer_idoc.body.onkeyup = (e) =>
694 return event_return e, @onkeyup e
695 @outer_idoc.body.onkeydown = (e) =>
696 return event_return e, @onkeydown e
697 @outer_idoc.body.onkeypress = (e) =>
698 return event_return e, @onkeypress e
699 if @options.stylesheet
701 @idoc.head.appendChild domify @idoc, style: src: @options.stylesheet
702 @load_html @in_el.value
707 x = (e.offsetX ? e.layerX) - overlay_padding
708 y = (e.offsetY ? e.layerY) - overlay_padding
709 new_cursor = find_loc_cursor_position @tree, x: x, y: y
711 @move_cursor new_cursor
713 ondoubleclick: (e) ->
717 return false if ignore_key_codes[e.keyCode]?
718 #return false if control_key_codes[e.keyCode]?
721 return false if ignore_key_codes[e.keyCode]?
722 #return false if control_key_codes[e.keyCode]?
726 new_cursor = find_prev_cursor_position @tree, @cursor...
728 @move_cursor new_cursor
731 new_cursor = find_next_cursor_position @tree, c, -1
733 @move_cursor new_cursor
740 new_cursor = find_next_cursor_position @tree, @cursor...
742 @move_cursor new_cursor
745 new_cursor = find_prev_cursor_position @tree, c, -1
747 @move_cursor new_cursor
755 return false unless @cursor?
756 return false unless @cursor[1] > 0
757 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
758 @cursor[0].el.nodeValue = @cursor[0].text
759 @move_cursor [@cursor[0], @cursor[1] - 1]
762 return false unless @cursor?
763 return false unless @cursor[1] < @cursor[0].text.length
764 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
765 @cursor[0].el.nodeValue = @cursor[0].text
766 @move_cursor [@cursor[0], @cursor[1]]
784 return false if ignore_key_codes[e.keyCode]?
785 return false if control_key_codes[e.keyCode]? # handled in keydown
786 char = e.charCode ? e.keyCode
788 char = String.fromCharCode char
790 @cursor[0].text = char + @cursor[0].text
791 else if @cursor[1] is @cursor[0].text.length - 1
792 @cursor[0].text += char
795 @cursor[0].text.substr(0, @cursor[1]) +
797 @cursor[0].text.substr(@cursor[1])
798 @cursor[0].el.nodeValue = @cursor[0].text
799 @move_cursor [@cursor[0], @cursor[1] + 1]
802 clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
803 while @idoc.body.childNodes.length
804 @idoc.body.removeChild @idoc.body.childNodes[0]
808 @tree = peach_parser.parse html, @parser_opts
810 instantiate_tree @tree, @idoc.body
811 tree_dedup_space @tree
814 @in_el.onchange = null
815 @in_el.value = tree_to_html @tree
817 @load_html @in_el.value
818 @iframe.style.height = "0"
819 @iframe.style.height = "#{@idoc.body.scrollHeight}px"
820 kill_cursor: -> # remove it, forget where it was
822 @cursor_el.parentNode.removeChild @cursor_el
823 @cursor_visible = false
825 move_cursor: (cursor) ->
826 loc = cursor_to_xyh cursor[0], cursor[1]
828 console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
831 # replace cursor element, to reset blink animation
833 @cursor_el.parentNode.removeChild @cursor_el
834 @cursor_el = domify @outer_idoc, div: id: 'cursor'
835 @overlay.appendChild @cursor_el
836 @cursor_visible = true
837 @cursor_el.style.left = "#{loc.x + overlay_padding - 1}px"
838 @cursor_el.style.top = "#{loc.y + overlay_padding}px"
840 window.peach_html5_editor = (args...) ->
841 return new PeachHTML5Editor args...
843 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])