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 # Warning: currently assumes you're asking about a single character
60 # Note: chromium returns multiple bounding rects for a space at a line-break
61 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
62 # Note: sometimes returns null (eg for whitespace that is not visible)
63 text_range_bounds = (el, start, end) ->
64 range = document.createRange()
65 range.setStart el, start
67 rects = range.getClientRects()
72 doc = el.ownerDocument.documentElement
73 win = el.ownerDocument.defaultView
74 y_fix = win.pageYOffset - doc.clientTop
75 x_fix = win.pageXOffset - doc.clientLeft
79 w: rect.width ? (rect.right - rect.left)
80 h: rect.height ? (rect.top - rect.bottom)
82 bounding: range.getBoundingClientRect()
85 # figure out the x/y coordinates of where the cursor should be if it's at
86 # position ``i`` within text node ``n``
87 # sometimes returns null (eg for whitespace that is not visible)
88 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
89 range = document.createRange()
91 ret = text_range_bounds n.el, 0, 0
93 ret = text_range_bounds n.el, i - 1, i
97 ret = text_range_bounds n.el, i, i + 1
99 debug_dot_at n.el.ownerDocument, ret.x, ret.y
102 # encode text so it can be safely placed inside an html attribute
103 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
105 return txt.replace enc_attr_regex, (match, amp, quote) ->
106 return '&' if (amp)
107 return '"' if (quote)
109 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
111 return txt.replace enc_text_regex, (match, amp, lt) ->
112 return '&' if (amp)
113 return '<' if (lt)
133 dom_to_html = (dom) ->
145 if el.attrs[k].length > 0
146 ret += "=\"#{enc_attr el.attrs[k]}\""
148 unless void_elements[el.name]
149 if el.children.length
150 ret += dom_to_html el.children
151 ret += "</#{el.name}>"
153 ret += enc_text el.text
155 ret += "<!--#{el.text}-->"
157 ret += "<!DOCTYPE #{el.name}"
158 if el.public_identifier? and el.public_identifier.length > 0
159 ret += " \"#{el.public_identifier}\""
160 if el.system_identifier? and el.system_identifier.length > 0
161 ret += " \"#{el.system_identifier}\""
165 domify = (doc, hash) ->
166 for tag, attrs of hash
168 return document.createTextNode attrs
169 el = document.createElement tag
178 outer_css = (args) ->
181 inner_padding = args.inner_padding ? overlay_padding
182 frame_width = args.frame_width ? inner_padding
183 # TODO editor controls height...
194 ret += "border: #{shrink 1}px solid black;"
195 ret += "padding: #{shrink frame_width}px;"
198 ret += "border: #{shrink 1}px solid black;"
199 ret += "padding: #{shrink inner_padding}px;"
202 ret += 'position: relative;'
205 ret += 'box-sizing: border-box;'
207 ret += 'border: none;'
209 ret += "width: #{w}px;"
210 ret += "height: #{h}px;"
213 ret += 'position: absolute;'
214 ret += "left: -#{inner_padding}px;"
215 ret += "top: -#{inner_padding}px;"
216 ret += "right: -#{inner_padding}px;"
217 ret += "bottom: -#{inner_padding}px;"
218 ret += 'overflow: hidden;'
221 ret += 'position: absolute;'
222 ret += 'background: rgba(100,100,100,0.2);'
225 ret += 'position: absolute;'
226 ret += 'height: 1em;' # FIXME adjust for hight of text
228 ret += 'background: #444;'
229 ret += '-webkit-animation: blink 1s steps(2, start) infinite;'
230 ret += 'animation: blink 1s steps(2, start) infinite;'
232 ret += '@-webkit-keyframes blink {'
233 ret += 'to { visibility: hidden; }'
235 ret += '@keyframes blink {'
236 ret += 'to { visibility: hidden; }'
245 KEY_BACKSPACE = 8 # <--
246 KEY_DELETE = 46 # -->
258 '20': true # capslock
260 '144': true # numlock
262 '91': true # windows "start" key
263 control_key_codes = # we react to these, but they aren't typing
279 instantiate_tree = (tree, parent) ->
283 c.el = parent.ownerDocument.createTextNode c.text
284 parent.appendChild c.el
286 # TODO create in correct namespace
287 c.el = parent.ownerDocument.createElement c.name
289 # FIXME if attr_whitelist[k]?
290 c.el.setAttribute k, v
291 parent.appendChild c.el
293 instantiate_tree c.children, c.el
295 traverse_tree = (tree, state, cb) ->
300 traverse_tree c.children, state, cb
303 # find the next element in tree (and decendants) that is after n and can contain text
304 # TODO make it so cursor can go places that don't have text but could
305 find_next_cursor_position = (tree, n, i) ->
306 if n? and n.type is TYPE_TEXT and n.text.length > i
307 orig_xyh = cursor_to_xyh n, i
309 console.log "ERROR: couldn't find xy for current cursor location"
311 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
312 next_xyh = cursor_to_xyh n, next_i
314 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
316 found = traverse_tree tree, before: n?, (node, state) ->
317 if node.type is TYPE_TEXT and state.before is false
323 return [found.node, 0]
326 # TODO make it so cursor can go places that don't have text but could
327 find_prev_cursor_position = (tree, n, i) ->
328 if n? and n.type is TYPE_TEXT and i > 0
329 orig_xyh = cursor_to_xyh n, i
331 console.log "ERROR: couldn't find xy for current cursor location"
333 for prev_i in [i-1 .. 0]
334 prev_xyh = cursor_to_xyh n, prev_i
336 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
339 found = traverse_tree tree, before: n?, (node, state) ->
340 if node.type is TYPE_TEXT
346 state.node = state.prev
351 return [found.node, found.node.text.length]
354 find_loc_cursor_position = (tree, loc) ->
356 if c.type is TYPE_TAG or c.type is TYPE_TEXT
357 bounds = get_el_bounds c.el
358 continue if loc.x < bounds.x
359 continue if loc.x > bounds.x + bounds.w
360 continue if loc.y < bounds.y
361 continue if loc.y > bounds.y + bounds.h
363 ret = find_loc_cursor_position c.children, loc
365 if c.type is TYPE_TEXT
366 # click is within bounding box that contains all text.
367 return [c, 0] if c.text.length is 0
369 before = cursor_to_xyh c, before_i
371 console.log "error: failed to find cursor pixel location for start of", c
373 after_i = c.text.length
374 after = cursor_to_xyh c, after_i
376 console.log "error: failed to find cursor pixel location for end of", c
378 if loc.y < before.y + before.h and loc.x < before.x
379 # console.log 'before first char on first line'
381 if loc.y > after.y and loc.x > after.x
382 # console.log 'after last char on last line'
385 console.log "Warning: click in bounding box but above first line"
386 continue # above first line (runaround?)
387 if loc.y > after.y + after.h
388 console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
389 continue # below last line (shouldn't happen?)
390 while after_i - before_i > 1
391 cur_i = Math.round((before_i + after_i) / 2)
392 cur = cursor_to_xyh c, cur_i
394 console.log "error: failed to find cursor pixel location for", c, cur_i
396 if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
402 # which one is closest?
403 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
409 # browsers collapse these (html5 spec calls these "space characters")
410 is_space_code = (char_code) ->
412 when 9, 10, 12, 13, 32
416 return is_space_code chr.charCodeAt 0
418 # pass a array of nodes (from parser library, ie it should have .el and .text)
419 tree_dedup_space = (tree) ->
420 prev = cur = next = null
421 prev_i = cur_i = next_i = 0
422 prev_pos = pos = next_pos = null
423 prev_px = cur_px = next_px = null
427 iterate = (tree, cb) ->
429 if n.type is TYPE_TEXT
431 while i < n.text.length # don't foreach, cb might remove chars
435 if n.type is TYPE_TAG
436 block = is_display_block n.el
439 if n.children.length > 0
440 iterate n.children, cb
445 removed_char = cur.text.charAt(cur_i)
446 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
447 if next is cur # in same text node
449 throw "how is this possible?"
454 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
455 if next is cur # in same text node
458 # return true if cur was removed from the dom (ie re-use same prev)
460 # cur definitately set
461 # prev and/or next might be null, indicating the start/end of a display:block
462 return false unless is_space_code cur.text.charCodeAt cur_i
463 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
465 # 1. zero rects returned by getClientRects() means collapsed space
468 # 2. width greater than zero means visible space
471 # now the weird edge cases...
473 # firefox and chromium both report zero width for characters at the end
474 # of a line where the text wraps (automatically, due to word-wrap) to
475 # the next line. These do not appear to be distinguishable from
476 # collapsed spaces via the range/bounds api, so...
478 # remove it from the dom, and if prev or next moves, put it back.
479 if prev? and not prev_px?
480 prev_px = cursor_to_xyh prev, prev_i
481 if next? and not next_px?
482 next_px = cursor_to_xyh next, next_i
483 #if prev is null and next is null
484 # parent_px = cur.parent.el.getBoundingClientRect()
488 new_prev_px = cursor_to_xyh prev, prev_i
489 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
492 console.log "this shouldn't happen, we remove spaces that don't locate"
495 new_next_px = cursor_to_xyh next, next_i
496 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
499 # console.log "removing space becase space after it is collapsed"
500 # if there's no prev or next (single space inside a block-level element?) check
501 # TODO scrapt this, or fix it so it works when there's no parent
502 # if prev is null and next is null
503 # new_parent_px = cur.parent.el.getBoundingClientRect()
504 # 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
505 # console.log "WEIRD: parent moved"
506 # return put_it_back()
507 # we didn't put it back
509 # pass null at start/end of display:block
517 # don't advance (to the next character next time) if we removed a
518 # character from the same text node as ``next``, because doing so
519 # renumbers the indexes in that string
520 if removed and cur is next
536 class PeachHTML5Editor
537 # Options: (all optional)
538 # editor_id: "id" attribute for outer-most element created by/for editor
539 constructor: (in_el, options) ->
540 @options = options ? {}
543 @initialized = false # when iframes have loaded
544 @outer_iframe # iframe to hold editor
545 @outer_idoc # "document" object for @outer_iframe
546 @iframe = null # iframe to hold editable content
547 @idoc = null # "document" object for @iframe
550 @cursor_visible = false
551 opt_fragment = @options.fragment ? true
554 @parser_opts.fragment = 'body'
556 @outer_iframe = domify document, iframe: {}
557 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
558 if @options.editor_id?
559 @outer_iframe.setAttribute 'id', @options.editor_id
560 @outer_iframe.onload = =>
561 @outer_idoc = @outer_iframe.contentDocument
562 icss = domify @outer_idoc, style: children: [
563 domify @outer_idoc, text: css
565 @outer_idoc.head.appendChild icss
566 @iframe = domify @outer_idoc, iframe: {}
569 @outer_idoc.body.appendChild(
570 domify @outer_idoc, div: id: 'wrap1', children: [
571 domify @outer_idoc, div: id: 'wrap2', children: [
572 domify @outer_idoc, div: id: 'wrap3', children: [
574 @overlay = domify @outer_idoc, div: id: 'overlay'
579 outer_wrap = domify document, div: class: 'peach_html5_editor'
580 @in_el.parentNode.appendChild outer_wrap
581 outer_bounds = get_el_bounds outer_wrap
582 if outer_bounds.w < 300
584 if outer_bounds.h < 300
586 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
587 @outer_iframe.setAttribute 'style', outer_iframe_style
588 css = outer_css w: outer_bounds.w, h: outer_bounds.h
589 outer_wrap.appendChild @outer_iframe
590 init: -> # called by @iframe's onload
591 @idoc = @iframe.contentDocument
592 @overlay.onclick = (e) =>
594 @outer_idoc.body.onkeyup = (e) =>
596 @outer_idoc.body.onkeydown = (e) =>
598 @outer_idoc.body.onkeypress = (e) =>
600 if @options.stylesheet
602 @idoc.head.appendChild domify @idoc, style: src: @options.stylesheet
603 @load_html @in_el.value
605 if @options.initialized_cb?
606 @options.initialized_cb()
608 x = (e.offsetX ? e.layerX) - overlay_padding
609 y = (e.offsetY ? e.layerY) - overlay_padding
610 new_cursor = find_loc_cursor_position @tree, x: x, y: y
612 @move_cursor new_cursor
615 return false if ignore_key_codes[e.keyCode]?
616 #return false if control_key_codes[e.keyCode]?
619 return false if ignore_key_codes[e.keyCode]?
620 #return false if control_key_codes[e.keyCode]?
624 new_cursor = find_prev_cursor_position @tree, @cursor...
626 @move_cursor new_cursor
629 new_cursor = find_next_cursor_position @tree, c, -1
631 @move_cursor new_cursor
638 new_cursor = find_next_cursor_position @tree, @cursor...
640 @move_cursor new_cursor
643 new_cursor = find_prev_cursor_position @tree, c, -1
645 @move_cursor new_cursor
653 return false unless @cursor?
654 return false unless @cursor[1] > 0
655 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
656 @cursor[0].el.nodeValue = @cursor[0].text
657 @move_cursor [@cursor[0], @cursor[1] - 1]
660 return false unless @cursor?
661 return false unless @cursor[1] < @cursor[0].text.length
662 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
663 @cursor[0].el.nodeValue = @cursor[0].text
664 @move_cursor [@cursor[0], @cursor[1]]
682 return false if ignore_key_codes[e.keyCode]?
683 return false if control_key_codes[e.keyCode]? # handled in keydown
684 char = e.charCode ? e.keyCode
686 char = String.fromCharCode char
688 @cursor[0].text = char + @cursor[0].text
689 else if @cursor[1] is @cursor[0].text.length - 1
690 @cursor[0].text += char
693 @cursor[0].text.substr(0, @cursor[1]) +
695 @cursor[0].text.substr(@cursor[1])
696 @cursor[0].el.nodeValue = @cursor[0].text
697 @move_cursor [@cursor[0], @cursor[1] + 1]
700 clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
701 while @idoc.body.childNodes.length
702 @idoc.body.removeChild @idoc.body.childNodes[0]
706 @tree = peach_parser.parse html, @parser_opts
708 instantiate_tree @tree, @idoc.body
709 tree_dedup_space @tree
712 # FIXME don't export cursor placeholder (when cursor is between space characters)
713 @in_el.onchange = null
714 @in_el.value = dom_to_html @tree
716 @load_html @in_el.value
717 kill_cursor: -> # remove it, forget where it was
719 @cursor_el.parentNode.removeChild @cursor_el
720 @cursor_visible = false
722 move_cursor: (cursor) ->
723 loc = cursor_to_xyh cursor[0], cursor[1]
725 console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
728 # replace cursor, to reset blink animation
730 @cursor_el.parentNode.removeChild @cursor_el
731 @cursor_el = domify @outer_idoc, div: id: 'cursor'
732 @overlay.appendChild @cursor_el
733 @cursor_visible = true
734 # TODO figure out x,y coords for cursor
735 @cursor_el.style.left = "#{loc.x + overlay_padding - 1}px"
736 @cursor_el.style.top = "#{loc.y + overlay_padding}px"
738 window.peach_html5_editor = (args...) ->
739 return new PeachHTML5Editor args...
741 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])