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 debug_dot_at = (doc, x, y) ->
27 el = doc.createElement 'div'
28 el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
29 doc.body.appendChild el
30 #console.log(new Error().stack)
32 # text nodes don't have getBoundingClientRect(), so use selection api to find
34 get_el_bounds = (el) ->
35 if el.getBoundingClientRect?
36 rect = el.getBoundingClientRect()
38 # text nodes don't have getBoundingClientRect(), so use range api
39 range = el.ownerDocument.createRange()
40 range.selectNodeContents el
41 rect = range.getBoundingClientRect()
42 doc = el.ownerDocument.documentElement
43 win = el.ownerDocument.defaultView
44 y_fix = win.pageYOffset - doc.clientTop
45 x_fix = win.pageXOffset - doc.clientLeft
49 w: rect.width ? (rect.right - rect.left)
50 h: rect.height ? (rect.top - rect.bottom)
53 is_display_block = (el) ->
55 return el.currentStyle.display is 'block'
57 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
59 # Pass return value from dom event handlers to this.
60 # If they return false, this will addinionally stop propagation and default.
61 event_return = (e, bool) ->
68 # Warning: currently assumes you're asking about a single character
69 # Note: chromium returns multiple bounding rects for a space at a line-break
70 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
71 # Note: sometimes returns null (eg for whitespace that is not visible)
72 text_range_bounds = (el, start, end) ->
73 range = document.createRange()
74 range.setStart el, start
76 rects = range.getClientRects()
81 doc = el.ownerDocument.documentElement
82 win = el.ownerDocument.defaultView
83 y_fix = win.pageYOffset - doc.clientTop
84 x_fix = win.pageXOffset - doc.clientLeft
88 w: rect.width ? (rect.right - rect.left)
89 h: rect.height ? (rect.top - rect.bottom)
91 bounding: range.getBoundingClientRect()
94 # figure out the x/y coordinates of where the cursor should be if it's at
95 # position ``i`` within text node ``n``
96 # sometimes returns null (eg for whitespace that is not visible)
97 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
98 range = document.createRange()
100 ret = text_range_bounds n.el, 0, 0
101 else if i is n.text.length
102 ret = text_range_bounds n.el, i - 1, i
106 ret = text_range_bounds n.el, i, i + 1
108 debug_dot_at n.el.ownerDocument, ret.x, ret.y
111 # encode text so it can be safely placed inside an html attribute
112 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
114 return txt.replace enc_attr_regex, (match, amp, quote) ->
115 return '&' if (amp)
116 return '"' if (quote)
118 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
120 return txt.replace enc_text_regex, (match, amp, lt) ->
121 return '&' if (amp)
122 return '<' if (lt)
142 dom_to_html = (dom) ->
154 if el.attrs[k].length > 0
155 ret += "=\"#{enc_attr el.attrs[k]}\""
157 unless void_elements[el.name]
158 if el.children.length
159 ret += dom_to_html el.children
160 ret += "</#{el.name}>"
162 ret += enc_text el.text
164 ret += "<!--#{el.text}-->"
166 ret += "<!DOCTYPE #{el.name}"
167 if el.public_identifier? and el.public_identifier.length > 0
168 ret += " \"#{el.public_identifier}\""
169 if el.system_identifier? and el.system_identifier.length > 0
170 ret += " \"#{el.system_identifier}\""
174 domify = (doc, hash) ->
175 for tag, attrs of hash
177 return document.createTextNode attrs
178 el = document.createElement tag
187 outer_css = (args) ->
190 inner_padding = args.inner_padding ? overlay_padding
191 frame_width = args.frame_width ? inner_padding
192 # TODO editor controls height...
193 occupy = (left, top = left, right = left, bottom = top) ->
196 return Math.max(left, top, right, bottom)
203 ret += "border: #{occupy 1}px solid black;"
204 ret += "padding: #{occupy frame_width}px;"
207 ret += "border: #{occupy 1}px solid black;"
208 ret += "padding: #{occupy inner_padding}px;"
209 ret += "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
210 ret += "width: #{w}px;"
211 ret += "height: #{h}px;"
212 ret += 'overflow-x: hidden;'
213 ret += 'overflow-y: scroll;'
216 ret += 'position: relative;'
217 ret += "width: #{w}px;"
218 ret += "min-height: #{h}px;"
221 ret += 'box-sizing: border-box;'
223 ret += 'border: none;'
225 ret += "width: #{w}px;"
226 #ret += "height: #{h}px;" # height auto-set when content set/changed
227 ret += '-ms-user-select: none;'
228 ret += '-webkit-user-select: none;'
229 ret += '-moz-user-select: none;'
230 ret += 'user-select: none;'
233 ret += 'position: absolute;'
234 ret += "left: -#{inner_padding}px;"
235 ret += "top: -#{inner_padding}px;"
236 ret += "right: -#{inner_padding}px;"
237 ret += "bottom: -#{inner_padding}px;"
238 ret += 'overflow: hidden;'
241 ret += 'position: absolute;'
242 ret += 'background: rgba(100,100,100,0.2);'
245 ret += 'position: absolute;'
246 ret += 'height: 1em;' # FIXME adjust for hight of text
248 ret += 'background: #444;'
249 ret += '-webkit-animation: blink 1s steps(2, start) infinite;'
250 ret += 'animation: blink 1s steps(2, start) infinite;'
252 ret += '@-webkit-keyframes blink {'
253 ret += 'to { visibility: hidden; }'
255 ret += '@keyframes blink {'
256 ret += 'to { visibility: hidden; }'
265 KEY_BACKSPACE = 8 # <--
266 KEY_DELETE = 46 # -->
278 '20': true # capslock
280 '144': true # numlock
282 '91': true # windows "start" key
283 control_key_codes = # we react to these, but they aren't typing
299 instantiate_tree = (tree, parent) ->
304 c.el = parent.ownerDocument.createTextNode c.text
305 parent.appendChild c.el
307 if c.name in ['script', 'object', 'iframe', 'link']
308 # TODO put placeholders instead
310 # TODO create in correct namespace
311 c.el = parent.ownerDocument.createElement c.name
313 # FIXME if attr_whitelist[k]?
314 c.el.setAttribute k, v
315 parent.appendChild c.el
317 instantiate_tree c.children, c.el
321 traverse_tree = (tree, state, cb) ->
326 traverse_tree c.children, state, cb
330 find_next_cursor_position = (tree, n, i) ->
331 if n? and n.type is TYPE_TEXT and n.text.length > i
332 orig_xyh = cursor_to_xyh n, i
334 console.log "ERROR: couldn't find xy for current cursor location"
336 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
337 next_xyh = cursor_to_xyh n, next_i
339 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
341 found = traverse_tree tree, before: n?, (node, state) ->
342 if node.type is TYPE_TEXT and state.before is false
343 if cursor_to_xyh(node, 0)?
349 return [found.node, 0]
352 find_prev_cursor_position = (tree, n, i) ->
353 if n? and n.type is TYPE_TEXT and i > 0
354 orig_xyh = cursor_to_xyh n, i
356 console.log "ERROR: couldn't find xy for current cursor location"
358 for prev_i in [i-1 .. 0]
359 prev_xyh = cursor_to_xyh n, prev_i
361 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
364 found = traverse_tree tree, before: n?, (node, state) ->
365 if node.type is TYPE_TEXT
371 state.node = state.prev
376 ret = [found.node, found.node.text.length]
377 # check for unusual case: text not visible
378 loc = cursor_to_xyh ret[0], ret[1]
381 return find_prev_cursor_position tree, ret[0], 0
384 find_loc_cursor_position = (tree, loc) ->
386 if c.type is TYPE_TAG or c.type is TYPE_TEXT
387 bounds = get_el_bounds c.el
388 continue if loc.x < bounds.x
389 continue if loc.x > bounds.x + bounds.w
390 continue if loc.y < bounds.y
391 continue if loc.y > bounds.y + bounds.h
393 ret = find_loc_cursor_position c.children, loc
395 if c.type is TYPE_TEXT
396 # click is within bounding box that contains all text.
397 return [c, 0] if c.text.length is 0
399 before = cursor_to_xyh c, before_i
401 console.log "error: failed to find cursor pixel location for start of", c
403 after_i = c.text.length
404 after = cursor_to_xyh c, after_i
406 console.log "error: failed to find cursor pixel location for end of", c
408 if loc.y < before.y + before.h and loc.x < before.x
409 # console.log 'before first char on first line'
411 if loc.y > after.y and loc.x > after.x
412 # console.log 'after last char on last line'
415 console.log "Warning: click in bounding box but above first line"
416 continue # above first line (runaround?)
417 if loc.y > after.y + after.h
418 console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
419 continue # below last line (shouldn't happen?)
420 while after_i - before_i > 1
421 cur_i = Math.round((before_i + after_i) / 2)
422 cur = cursor_to_xyh c, cur_i
424 console.log "error: failed to find cursor pixel location for", c, cur_i
426 if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
432 # which one is closest?
433 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
439 # browsers collapse these (html5 spec calls these "space characters")
440 is_space_code = (char_code) ->
442 when 9, 10, 12, 13, 32
446 return is_space_code chr.charCodeAt 0
448 # pass a array of nodes (from parser library, ie it should have .el and .text)
449 tree_dedup_space = (tree) ->
450 prev = cur = next = null
451 prev_i = cur_i = next_i = 0
452 prev_pos = pos = next_pos = null
453 prev_px = cur_px = next_px = null
457 iterate = (tree, cb) ->
459 if n.type is TYPE_TEXT
461 while i < n.text.length # don't foreach, cb might remove chars
465 if n.type is TYPE_TAG
466 block = is_display_block n.el
469 if n.children.length > 0
470 iterate n.children, cb
475 removed_char = cur.text.charAt(cur_i)
476 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
477 if next is cur # in same text node
479 throw "how is this possible?"
484 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
485 if next is cur # in same text node
488 # return true if cur was removed from the dom (ie re-use same prev)
490 # cur definitately set
491 # prev and/or next might be null, indicating the start/end of a display:block
492 return false unless is_space_code cur.text.charCodeAt cur_i
493 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
495 # 1. zero rects returned by getClientRects() means collapsed space
498 # 2. width greater than zero means visible space
501 # now the weird edge cases...
503 # firefox and chromium both report zero width for characters at the end
504 # of a line where the text wraps (automatically, due to word-wrap) to
505 # the next line. These do not appear to be distinguishable from
506 # collapsed spaces via the range/bounds api, so...
508 # remove it from the dom, and if prev or next moves, put it back.
509 if prev? and not prev_px?
510 prev_px = cursor_to_xyh prev, prev_i
511 if next? and not next_px?
512 next_px = cursor_to_xyh next, next_i
513 #if prev is null and next is null
514 # parent_px = cur.parent.el.getBoundingClientRect()
518 new_prev_px = cursor_to_xyh prev, prev_i
519 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
522 console.log "this shouldn't happen, we remove spaces that don't locate"
525 new_next_px = cursor_to_xyh next, next_i
526 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
529 # console.log "removing space becase space after it is collapsed"
530 # if there's no prev or next (single space inside a block-level element?) check
531 # TODO scrapt this, or fix it so it works when there's no parent
532 # if prev is null and next is null
533 # new_parent_px = cur.parent.el.getBoundingClientRect()
534 # if new_parent_px.left isnt parent_px.left or new_parent_px.top isnt parent_px.top or new_parent_px.right isnt parent_px.right or new_parent_px.bottom isnt parent_px.bottom
535 # console.log "WEIRD: parent moved"
536 # return put_it_back()
537 # we didn't put it back
539 # pass null at start/end of display:block
547 # don't advance (to the next character next time) if we removed a
548 # character from the same text node as ``next``, because doing so
549 # renumbers the indexes in that string
550 if removed and cur is next
566 class PeachHTML5Editor
567 # Options: (all optional)
568 # editor_id: "id" attribute for outer-most element created by/for editor
569 # on_init: callback for when the editable content is in place
570 constructor: (in_el, options) ->
571 @options = options ? {}
574 @inited = false # when iframes have loaded
575 @outer_iframe # iframe to hold editor
576 @outer_idoc # "document" object for @outer_iframe
577 @iframe = null # iframe to hold editable content
578 @idoc = null # "document" object for @iframe
581 @cursor_visible = false
582 opt_fragment = @options.fragment ? true
585 @parser_opts.fragment = 'body'
587 @outer_iframe = domify document, iframe: {}
588 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
589 if @options.editor_id?
590 @outer_iframe.setAttribute 'id', @options.editor_id
591 @outer_iframe.onload = =>
592 @outer_idoc = @outer_iframe.contentDocument
593 icss = domify @outer_idoc, style: children: [
594 domify @outer_idoc, text: css
596 @outer_idoc.head.appendChild icss
597 @iframe = domify @outer_idoc, iframe: {}
600 setTimeout (=> @init() unless @inited), 200 # firefox never fires this onload
601 @outer_idoc.body.appendChild(
602 domify @outer_idoc, div: id: 'wrap1', children: [
603 domify @outer_idoc, div: id: 'wrap2', children: [
604 domify @outer_idoc, div: id: 'wrap3', children: [
606 @overlay = domify @outer_idoc, div: id: 'overlay'
611 outer_wrap = domify document, div: class: 'peach_html5_editor'
612 @in_el.parentNode.appendChild outer_wrap
613 outer_bounds = get_el_bounds outer_wrap
614 if outer_bounds.w < 300
616 if outer_bounds.h < 300
618 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
619 @outer_iframe.setAttribute 'style', outer_iframe_style
620 css = outer_css w: outer_bounds.w, h: outer_bounds.h
621 outer_wrap.appendChild @outer_iframe
622 init: -> # called by @iframe's onload (or timeout on firefox)
623 @idoc = @iframe.contentDocument
624 @overlay.onclick = (e) =>
625 return event_return @onclick e
626 @overlay.ondoubleclick = (e) =>
627 return event_return @ondoubleclick e
628 @outer_idoc.body.onkeyup = (e) =>
629 return event_return @onkeyup e
630 @outer_idoc.body.onkeydown = (e) =>
631 return event_return @onkeydown e
632 @outer_idoc.body.onkeypress = (e) =>
633 return event_return @onkeypress e
634 if @options.stylesheet
636 @idoc.head.appendChild domify @idoc, style: src: @options.stylesheet
637 @load_html @in_el.value
642 x = (e.offsetX ? e.layerX) - overlay_padding
643 y = (e.offsetY ? e.layerY) - overlay_padding
644 new_cursor = find_loc_cursor_position @tree, x: x, y: y
646 @move_cursor new_cursor
648 ondoubleclick: (e) ->
652 return false if ignore_key_codes[e.keyCode]?
653 #return false if control_key_codes[e.keyCode]?
656 return false if ignore_key_codes[e.keyCode]?
657 #return false if control_key_codes[e.keyCode]?
661 new_cursor = find_prev_cursor_position @tree, @cursor...
663 @move_cursor new_cursor
666 new_cursor = find_next_cursor_position @tree, c, -1
668 @move_cursor new_cursor
675 new_cursor = find_next_cursor_position @tree, @cursor...
677 @move_cursor new_cursor
680 new_cursor = find_prev_cursor_position @tree, c, -1
682 @move_cursor new_cursor
690 return false unless @cursor?
691 return false unless @cursor[1] > 0
692 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
693 @cursor[0].el.nodeValue = @cursor[0].text
694 @move_cursor [@cursor[0], @cursor[1] - 1]
697 return false unless @cursor?
698 return false unless @cursor[1] < @cursor[0].text.length
699 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
700 @cursor[0].el.nodeValue = @cursor[0].text
701 @move_cursor [@cursor[0], @cursor[1]]
719 return false if ignore_key_codes[e.keyCode]?
720 return false if control_key_codes[e.keyCode]? # handled in keydown
721 char = e.charCode ? e.keyCode
723 char = String.fromCharCode char
725 @cursor[0].text = char + @cursor[0].text
726 else if @cursor[1] is @cursor[0].text.length - 1
727 @cursor[0].text += char
730 @cursor[0].text.substr(0, @cursor[1]) +
732 @cursor[0].text.substr(@cursor[1])
733 @cursor[0].el.nodeValue = @cursor[0].text
734 @move_cursor [@cursor[0], @cursor[1] + 1]
737 clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
738 while @idoc.body.childNodes.length
739 @idoc.body.removeChild @idoc.body.childNodes[0]
743 @tree = peach_parser.parse html, @parser_opts
745 instantiate_tree @tree, @idoc.body
746 tree_dedup_space @tree
749 # FIXME don't export cursor placeholder (when cursor is between space characters)
750 @in_el.onchange = null
751 @in_el.value = dom_to_html @tree
753 @load_html @in_el.value
754 @iframe.style.height = "0"
755 @iframe.style.height = "#{@idoc.body.scrollHeight}px"
756 kill_cursor: -> # remove it, forget where it was
758 @cursor_el.parentNode.removeChild @cursor_el
759 @cursor_visible = false
761 move_cursor: (cursor) ->
762 loc = cursor_to_xyh cursor[0], cursor[1]
764 console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
767 # replace cursor, to reset blink animation
769 @cursor_el.parentNode.removeChild @cursor_el
770 @cursor_el = domify @outer_idoc, div: id: 'cursor'
771 @overlay.appendChild @cursor_el
772 @cursor_visible = true
773 # TODO figure out x,y coords for cursor
774 @cursor_el.style.left = "#{loc.x + overlay_padding - 1}px"
775 @cursor_el.style.top = "#{loc.y + overlay_padding}px"
777 window.peach_html5_editor = (args...) ->
778 return new PeachHTML5Editor args...
780 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])