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/>.
18 overlay_padding = 6 # TODO generate css from this
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) ->
26 el = doc.createElement 'div'
27 el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
28 doc.body.appendChild el
29 #console.log(new Error().stack)
31 # text nodes don't have getBoundingClientRect(), so use selection api to find
33 get_el_bounds = (el) ->
34 if el.getBoundingClientRect?
35 rect = el.getBoundingClientRect()
37 # text nodes don't have getBoundingClientRect(), so use range api
38 range = el.ownerDocument.createRange()
39 range.selectNodeContents el
40 rect = range.getBoundingClientRect()
41 doc = el.ownerDocument.documentElement
42 win = el.ownerDocument.defaultView
43 y_fix = win.pageYOffset - doc.clientTop
44 x_fix = win.pageXOffset - doc.clientLeft
48 w: rect.width ? (rect.right - rect.left)
49 h: rect.height ? (rect.top - rect.bottom)
52 is_display_block = (el) ->
54 return el.currentStyle.display is 'block'
56 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
58 # Warning: currently assumes you're asking about a single character
59 # Note: chromium returns multiple bounding rects for a space at a line-break
60 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
61 # Note: sometimes returns null (eg for whitespace that is not visible)
62 text_range_bounds = (el, start, end) ->
63 range = document.createRange()
64 range.setStart el, start
66 rects = range.getClientRects()
71 doc = el.ownerDocument.documentElement
72 win = el.ownerDocument.defaultView
73 y_fix = win.pageYOffset - doc.clientTop
74 x_fix = win.pageXOffset - doc.clientLeft
78 w: rect.width ? (rect.right - rect.left)
79 h: rect.height ? (rect.top - rect.bottom)
81 bounding: range.getBoundingClientRect()
84 # figure out the x/y coordinates of where the cursor should be if it's at
85 # position ``i`` within text node ``n``
86 # sometimes returns null (eg for whitespace that is not visible)
87 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
88 range = document.createRange()
90 ret = text_range_bounds n.el, 0, 0
92 ret = text_range_bounds n.el, i - 1, i
96 ret = text_range_bounds n.el, i, i + 1
98 debug_dot_at n.el.ownerDocument, ret.x, ret.y
101 # encode text so it can be safely placed inside an html attribute
102 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
104 return txt.replace enc_attr_regex, (match, amp, quote) ->
105 return '&' if (amp)
106 return '"' if (quote)
108 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
110 return txt.replace enc_text_regex, (match, amp, lt) ->
111 return '&' if (amp)
112 return '<' if (lt)
132 dom_to_html = (dom) ->
144 if el.attrs[k].length > 0
145 ret += "=\"#{enc_attr el.attrs[k]}\""
147 unless void_elements[el.name]
148 if el.children.length
149 ret += dom_to_html el.children
150 ret += "</#{el.name}>"
152 ret += enc_text el.text
154 ret += "<!--#{el.text}-->"
156 ret += "<!DOCTYPE #{el.name}"
157 if el.public_identifier? and el.public_identifier.length > 0
158 ret += " \"#{el.public_identifier}\""
159 if el.system_identifier? and el.system_identifier.length > 0
160 ret += " \"#{el.system_identifier}\""
167 return document.createTextNode attrs
168 el = document.createElement tag
178 css += 'div#peach_html5_editor_cursor {'
179 css += 'position: absolute;'
180 css += 'height: 1em;'
182 css += 'margin-left: -1px;'
183 css += 'margin-right: -1px;'
184 css += 'background: #444;'
185 css += '-webkit-animation: blink 1s steps(2, start) infinite;'
186 css += 'animation: blink 1s steps(2, start) infinite;'
188 css += '@-webkit-keyframes blink {'
189 css += 'to { visibility: hidden; }'
191 css += '@keyframes blink {'
192 css += 'to { visibility: hidden; }'
200 KEY_BACKSPACE = 8 # <--
201 KEY_DELETE = 46 # -->
211 instantiate_tree = (tree, parent) ->
215 c.el = parent.ownerDocument.createTextNode c.text
216 parent.appendChild c.el
218 # TODO create in correct namespace
219 c.el = parent.ownerDocument.createElement c.name
221 # FIXME if attr_whitelist[k]?
222 c.el.setAttribute k, v
223 parent.appendChild c.el
225 instantiate_tree c.children, c.el
227 traverse_tree = (tree, state, cb) ->
232 traverse_tree c.children, state, cb
235 # find the next element in tree (and decendants) that is after n and can contain text
236 # TODO make it so cursor can go places that don't have text but could
237 find_next_cursor_position = (tree, n, i) ->
238 if n? and n.type is TYPE_TEXT and n.text.length > i
239 orig_xyh = cursor_to_xyh n, i
241 console.log "ERROR: couldn't find xy for current cursor location"
243 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
244 next_xyh = cursor_to_xyh n, next_i
246 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
248 found = traverse_tree tree, before: n?, (node, state) ->
249 if node.type is TYPE_TEXT and state.before is false
255 return [found.node, 0]
258 # TODO make it so cursor can go places that don't have text but could
259 find_prev_cursor_position = (tree, n, i) ->
260 if n? and n.type is TYPE_TEXT and i > 0
261 orig_xyh = cursor_to_xyh n, i
263 console.log "ERROR: couldn't find xy for current cursor location"
265 for prev_i in [i-1 .. 0]
266 prev_xyh = cursor_to_xyh n, prev_i
268 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
271 found = traverse_tree tree, before: n?, (node, state) ->
272 if node.type is TYPE_TEXT
278 state.node = state.prev
283 return [found.node, found.node.text.length]
286 find_loc_cursor_position = (tree, loc) ->
288 if c.type is TYPE_TAG or c.type is TYPE_TEXT
289 bounds = get_el_bounds c.el
290 continue if loc.x < bounds.x
291 continue if loc.x > bounds.x + bounds.w
292 continue if loc.y < bounds.y
293 continue if loc.y > bounds.y + bounds.h
295 ret = find_loc_cursor_position c.children, loc
297 if c.type is TYPE_TEXT
298 # click is within bounding box that contains all text.
299 return [c, 0] if c.text.length is 0
301 before = cursor_to_xyh c, before_i
303 console.log "error: failed to find cursor pixel location for start of", c
305 after_i = c.text.length
306 after = cursor_to_xyh c, after_i
308 console.log "error: failed to find cursor pixel location for end of", c
310 if loc.y < before.y + before.h and loc.x < before.x
311 # console.log 'before first char on first line'
313 if loc.y > after.y and loc.x > after.x
314 # console.log 'after last char on last line'
317 console.log "Warning: click in bounding box but above first line"
318 continue # above first line (runaround?)
319 if loc.y > after.y + after.h
320 console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
321 continue # below last line (shouldn't happen?)
322 while after_i - before_i > 1
323 cur_i = Math.round((before_i + after_i) / 2)
324 cur = cursor_to_xyh c, cur_i
326 console.log "error: failed to find cursor pixel location for", c, cur_i
328 if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
334 # which one is closest?
335 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
341 # browsers collapse these (html5 spec calls these "space characters")
342 is_space_code = (char_code) ->
344 when 9, 10, 12, 13, 32
348 return is_space_code chr.charCodeAt 0
350 # pass a array of nodes (from parser library, ie it should have .el and .text)
351 tree_dedup_space = (tree) ->
352 prev = cur = next = null
353 prev_i = cur_i = next_i = 0
354 prev_pos = pos = next_pos = null
355 prev_px = cur_px = next_px = null
359 iterate = (tree, cb) ->
361 if n.type is TYPE_TEXT
363 while i < n.text.length # don't foreach, cb might remove chars
367 if n.type is TYPE_TAG
368 block = is_display_block n.el
371 if n.children.length > 0
372 iterate n.children, cb
377 removed_char = cur.text.charAt(cur_i)
378 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
379 if next is cur # in same text node
381 throw "how is this possible?"
386 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
387 if next is cur # in same text node
390 # return true if cur was removed from the dom (ie re-use same prev)
392 # cur definitately set
393 # prev and/or next might be null, indicating the start/end of a display:block
394 return false unless is_space_code cur.text.charCodeAt cur_i
395 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
397 # 1. zero rects returned by getClientRects() means collapsed space
400 # 2. width greater than zero means visible space
403 # now the weird edge cases...
405 # firefox and chromium both report zero width for characters at the end
406 # of a line where the text wraps (automatically, due to word-wrap) to
407 # the next line. These do not appear to be distinguishable from
408 # collapsed spaces via the range/bounds api, so...
410 # remove it from the dom, and if prev or next moves, put it back.
411 if prev? and not prev_px?
412 prev_px = cursor_to_xyh prev, prev_i
413 if next? and not next_px?
414 next_px = cursor_to_xyh next, next_i
415 #if prev is null and next is null
416 # parent_px = cur.parent.el.getBoundingClientRect()
420 new_prev_px = cursor_to_xyh prev, prev_i
421 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
424 console.log "this shouldn't happen, we remove spaces that don't locate"
427 new_next_px = cursor_to_xyh next, next_i
428 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
431 # console.log "removing space becase space after it is collapsed"
432 # if there's no prev or next (single space inside a block-level element?) check
433 # TODO scrapt this, or fix it so it works when there's no parent
434 # if prev is null and next is null
435 # new_parent_px = cur.parent.el.getBoundingClientRect()
436 # 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
437 # console.log "WEIRD: parent moved"
438 # return put_it_back()
439 # we didn't put it back
441 # pass null at start/end of display:block
449 # don't advance (to the next character next time) if we removed a
450 # character from the same text node as ``next``, because doing so
451 # renumbers the indexes in that string
452 if removed and cur is next
468 class PeachHTML5Editor
469 constructor: (in_el, options = {}) ->
472 @outer_el = domify div: class: 'peach_html5_editor', children: [
473 @iframe = domify iframe: class: 'peach_html5_editor_iframe'
474 @overlay = domify div: class: 'peach_html5_editor_overlay'
478 @cursor_visible = false
479 opt_fragment = options.fragment ? true
482 @parser_opts.fragment = 'body'
485 @idoc = @iframe.contentDocument
489 '20': true # capslock
491 '144': true # numlock
493 '91': true # windows "start" key
494 control_key_codes = # we react to these, but they aren't typing
510 @overlay.onclick = (e) =>
511 x = (e.offsetX ? e.layerX) - overlay_padding
512 y = (e.offsetY ? e.layerY) - overlay_padding
513 new_cursor = find_loc_cursor_position @tree, x: x, y: y
515 @move_cursor new_cursor
516 @idoc.body.onkeyup = (e) =>
518 return false if ignore_key_codes[e.keyCode]?
519 #return false if control_key_codes[e.keyCode]?
520 @idoc.body.onkeydown = (e) =>
522 return false if ignore_key_codes[e.keyCode]?
523 #return false if control_key_codes[e.keyCode]?
527 new_cursor = find_prev_cursor_position @tree, @cursor...
529 @move_cursor new_cursor
532 new_cursor = find_next_cursor_position @tree, c, -1
534 @move_cursor new_cursor
541 new_cursor = find_next_cursor_position @tree, @cursor...
543 @move_cursor new_cursor
546 new_cursor = find_prev_cursor_position @tree, c, -1
548 @move_cursor new_cursor
556 return false unless @cursor?
557 return false unless @cursor[1] > 0
558 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
559 @cursor[0].el.nodeValue = @cursor[0].text
560 @move_cursor [@cursor[0], @cursor[1] - 1]
563 return false unless @cursor?
564 return false unless @cursor[1] < @cursor[0].text.length
565 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
566 @cursor[0].el.nodeValue = @cursor[0].text
567 @move_cursor [@cursor[0], @cursor[1]]
583 @idoc.body.onkeypress = (e) =>
585 return false if ignore_key_codes[e.keyCode]?
586 return false if control_key_codes[e.keyCode]? # handled in keydown
587 char = e.charCode ? e.keyCode
589 char = String.fromCharCode char
591 @cursor[0].text = char + @cursor[0].text
592 else if @cursor[1] is @cursor[0].text.length - 1
593 @cursor[0].text += char
596 @cursor[0].text.substr(0, @cursor[1]) +
598 @cursor[0].text.substr(@cursor[1])
599 @cursor[0].el.nodeValue = @cursor[0].text
600 @move_cursor [@cursor[0], @cursor[1] + 1]
603 if options.stylesheet # TODO test this
604 istyle = @idoc.createElement 'style'
605 istyle.setAttribute 'src', options.stylesheet
606 @idoc.head.appendChild istyle
607 icss = @idoc.createElement 'style'
608 icss.appendChild @idoc.createTextNode css
609 document.head.appendChild icss
610 @load_html @in_el.value
612 @in_el.parentNode.appendChild @outer_el
614 # FIXME add parent node, so we don't empty body and delete cursor_el
615 while @idoc.body.childNodes.length
616 @idoc.body.removeChild @idoc.body.childNodes[0]
618 @cursor_visible = false
621 @tree = peach_parser.parse html, @parser_opts
623 instantiate_tree @tree, @idoc.body
624 tree_dedup_space @tree
627 # FIXME don't export cursor placeholder (when cursor is between space characters)
628 @in_el.onchange = null
629 @in_el.value = dom_to_html @tree
631 @load_html @in_el.value
632 kill_cursor: -> # remove it, forget where it was
634 @cursor_el.parentNode.removeChild @cursor_el
635 @cursor_visible = false
637 move_cursor: (cursor) ->
638 loc = cursor_to_xyh cursor[0], cursor[1]
640 console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
643 # replace cursor, to reset blink animation
645 @cursor_el.parentNode.removeChild @cursor_el
646 @cursor_el = domify div: id: 'peach_html5_editor_cursor'
647 @overlay.appendChild @cursor_el
648 @cursor_visible = true
649 # TODO figure out x,y coords for cursor
650 @cursor_el.style.left = "#{loc.x + overlay_padding}px"
651 @cursor_el.style.top = "#{loc.y + overlay_padding}px"
653 window.peach_html5_editor = (args...) ->
654 return new PeachHTML5Editor args...
656 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])