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/>.
17 TYPE_TAG = peach_parser.TYPE_TAG
18 TYPE_TEXT = peach_parser.TYPE_TEXT
19 TYPE_COMMENT = peach_parser.TYPE_COMMENT
20 TYPE_DOCTYPE = peach_parser.TYPE_DOCTYPE
22 debug_dot_at = (doc, x, y) ->
23 el = doc.createElement 'div'
24 el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
25 doc.body.appendChild el
26 #console.log(new Error().stack)
28 # text nodes don't have getBoundingClientRect(), so use selection api to find
30 get_el_bounds = (el) ->
31 if el.getBoundingClientRect?
32 rect = el.getBoundingClientRect()
34 # text nodes don't have getBoundingClientRect(), so use range api
35 range = el.ownerDocument.createRange()
36 range.selectNodeContents el
37 rect = range.getBoundingClientRect()
38 doc = el.ownerDocument.documentElement
39 win = el.ownerDocument.defaultView
40 y_fix = win.pageYOffset - doc.clientTop
41 x_fix = win.pageXOffset - doc.clientLeft
45 w: rect.width ? (rect.right - rect.left)
46 h: rect.height ? (rect.top - rect.bottom)
49 is_display_block = (el) ->
51 return el.currentStyle.display is 'block'
53 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
55 # Warning: currently assumes you're asking about a single character
56 # Note: chromium returns multiple bounding rects for a space at a line-break
57 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
58 # Note: sometimes returns null (eg for whitespace that is not visible)
59 text_range_bounds = (el, start, end) ->
60 range = document.createRange()
61 range.setStart el, start
63 rects = range.getClientRects()
68 doc = el.ownerDocument.documentElement
69 win = el.ownerDocument.defaultView
70 y_fix = win.pageYOffset - doc.clientTop
71 x_fix = win.pageXOffset - doc.clientLeft
75 w: rect.width ? (rect.right - rect.left)
76 h: rect.height ? (rect.top - rect.bottom)
78 bounding: range.getBoundingClientRect()
81 # figure out the x/y coordinates of where the cursor should be if it's at
82 # position ``i`` within text node ``n``
83 # sometimes returns null (eg for whitespace that is not visible)
84 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
85 range = document.createRange()
87 ret = text_range_bounds n.el, 0, 0
89 ret = text_range_bounds n.el, i - 1, i
93 ret = text_range_bounds n.el, i, i + 1
95 debug_dot_at n.el.ownerDocument, ret.x, ret.y
98 # encode text so it can be safely placed inside an html attribute
99 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
101 return txt.replace enc_attr_regex, (match, amp, quote) ->
102 return '&' if (amp)
103 return '"' if (quote)
105 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
107 return txt.replace enc_text_regex, (match, amp, lt) ->
108 return '&' if (amp)
109 return '<' if (lt)
129 dom_to_html = (dom) ->
141 if el.attrs[k].length > 0
142 ret += "=\"#{enc_attr el.attrs[k]}\""
144 unless void_elements[el.name]
145 if el.children.length
146 ret += dom_to_html el.children
147 ret += "</#{el.name}>"
149 ret += enc_text el.text
151 ret += "<!--#{el.text}-->"
153 ret += "<!DOCTYPE #{el.name}"
154 if el.public_identifier? and el.public_identifier.length > 0
155 ret += " \"#{el.public_identifier}\""
156 if el.system_identifier? and el.system_identifier.length > 0
157 ret += " \"#{el.system_identifier}\""
164 return document.createTextNode attrs
165 el = document.createElement tag
175 css += 'div#peach_html5_editor_cursor {'
176 css += 'position: absolute;'
177 css += 'height: 1em;'
179 css += 'margin-left: -1px;'
180 css += 'margin-right: -1px;'
181 css += 'background: #444;'
182 css += '-webkit-animation: blink 1s steps(2, start) infinite;'
183 css += 'animation: blink 1s steps(2, start) infinite;'
185 css += '@-webkit-keyframes blink {'
186 css += 'to { visibility: hidden; }'
188 css += '@keyframes blink {'
189 css += 'to { visibility: hidden; }'
197 KEY_BACKSPACE = 8 # <--
198 KEY_DELETE = 46 # -->
208 instantiate_tree = (tree, parent) ->
212 c.el = parent.ownerDocument.createTextNode c.text
213 parent.appendChild c.el
215 # TODO create in correct namespace
216 c.el = parent.ownerDocument.createElement c.name
218 # FIXME if attr_whitelist[k]?
219 c.el.setAttribute k, v
220 parent.appendChild c.el
222 instantiate_tree c.children, c.el
224 traverse_tree = (tree, state, cb) ->
229 traverse_tree c.children, state, cb
232 # find the next element in tree (and decendants) that is after n and can contain text
233 # TODO make it so cursor can go places that don't have text but could
234 find_next_cursor_position = (tree, n, i) ->
235 if n? and n.type is TYPE_TEXT and n.text.length > i
236 orig_xyh = cursor_to_xyh n, i
238 console.log "ERROR: couldn't find xy for current cursor location"
240 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
241 next_xyh = cursor_to_xyh n, next_i
243 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
245 found = traverse_tree tree, before: n?, (node, state) ->
246 if node.type is TYPE_TEXT and state.before is false
252 return [found.node, 0]
255 # TODO make it so cursor can go places that don't have text but could
256 find_prev_cursor_position = (tree, n, i) ->
257 if n? and n.type is TYPE_TEXT and i > 0
258 orig_xyh = cursor_to_xyh n, i
260 console.log "ERROR: couldn't find xy for current cursor location"
262 for prev_i in [i-1 .. 0]
263 prev_xyh = cursor_to_xyh n, prev_i
265 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
268 found = traverse_tree tree, before: n?, (node, state) ->
269 if node.type is TYPE_TEXT
275 state.node = state.prev
280 return [found.node, found.node.text.length]
283 find_loc_cursor_position = (tree, loc) ->
285 if c.type is TYPE_TAG or c.type is TYPE_TEXT
286 bounds = get_el_bounds c.el
287 continue if loc.x < bounds.x
288 continue if loc.x > bounds.x + bounds.w
289 continue if loc.y < bounds.y
290 continue if loc.y > bounds.y + bounds.h
292 ret = find_loc_cursor_position c.children, loc
294 if c.type is TYPE_TEXT
295 # click is within bounding box that contains all text.
296 return [c, 0] if c.text.length is 0
298 before = cursor_to_xyh c, before_i
300 console.log "error: failed to find cursor pixel location for start of", c
302 after_i = c.text.length
303 after = cursor_to_xyh c, after_i
305 console.log "error: failed to find cursor pixel location for end of", c
307 if loc.y < before.y + before.h and loc.x < before.x
308 # console.log 'before first char on first line'
310 if loc.y > after.y and loc.x > after.x
311 # console.log 'after last char on last line'
314 console.log "Warning: click in bounding box but above first line"
315 continue # above first line (runaround?)
316 if loc.y > after.y + after.h
317 console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
318 continue # below last line (shouldn't happen?)
319 while after_i - before_i > 1
320 cur_i = Math.round((before_i + after_i) / 2)
321 cur = cursor_to_xyh c, cur_i
323 console.log "error: failed to find cursor pixel location for", c, cur_i
325 if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
331 # which one is closest?
332 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
338 # browsers collapse these (html5 spec calls these "space characters")
339 is_space_code = (char_code) ->
341 when 9, 10, 12, 13, 32
345 return is_space_code chr.charCodeAt 0
347 # pass a array of nodes (from parser library, ie it should have .el and .text)
348 tree_dedup_space = (tree) ->
349 prev = cur = next = null
350 prev_i = cur_i = next_i = 0
351 prev_pos = pos = next_pos = null
352 prev_px = cur_px = next_px = null
356 iterate = (tree, cb) ->
358 if n.type is TYPE_TEXT
360 while i < n.text.length # don't foreach, cb might remove chars
364 if n.type is TYPE_TAG
365 block = is_display_block n.el
368 if n.children.length > 0
369 iterate n.children, cb
374 removed_char = cur.text.charAt(cur_i)
375 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
376 if next is cur # in same text node
378 throw "how is this possible?"
383 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
384 if next is cur # in same text node
387 # return true if cur was removed from the dom (ie re-use same prev)
389 # cur definitately set
390 # prev and/or next might be null, indicating the start/end of a display:block
391 return false unless is_space_code cur.text.charCodeAt cur_i
392 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
394 # 1. zero rects returned by getClientRects() means collapsed space
397 # 2. width greater than zero means visible space
400 # now the weird edge cases...
402 # firefox and chromium both report zero width for characters at the end
403 # of a line where the text wraps (automatically, due to word-wrap) to
404 # the next line. These do not appear to be distinguishable from
405 # collapsed spaces via the range/bounds api, so...
407 # remove it from the dom, and if prev or next moves, put it back.
408 if prev? and not prev_px?
409 prev_px = cursor_to_xyh prev, prev_i
410 if next? and not next_px?
411 next_px = cursor_to_xyh next, next_i
412 #if prev is null and next is null
413 # parent_px = cur.parent.el.getBoundingClientRect()
417 new_prev_px = cursor_to_xyh prev, prev_i
418 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
421 console.log "this shouldn't happen, we remove spaces that don't locate"
424 new_next_px = cursor_to_xyh next, next_i
425 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
428 # console.log "removing space becase space after it is collapsed"
429 # if there's no prev or next (single space inside a block-level element?) check
430 # TODO scrapt this, or fix it so it works when there's no parent
431 # if prev is null and next is null
432 # new_parent_px = cur.parent.el.getBoundingClientRect()
433 # 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
434 # console.log "WEIRD: parent moved"
435 # return put_it_back()
436 # we didn't put it back
438 # pass null at start/end of display:block
446 # don't advance (to the next character next time) if we removed a
447 # character from the same text node as ``next``, because doing so
448 # renumbers the indexes in that string
449 if removed and cur is next
465 class PeachHTML5Editor
466 constructor: (in_el, options = {}) ->
469 @iframe = domify iframe: class: 'peach_html5_editor'
472 @cursor_visible = false
473 opt_fragment = options.fragment ? true
476 @parser_opts.fragment = 'body'
479 @idoc = @iframe.contentDocument
483 '20': true # capslock
485 '144': true # numlock
487 '91': true # windows "start" key
488 control_key_codes = # we react to these, but they aren't typing
504 @idoc.body.onclick = (e) =>
505 # idoc.body.offset().left/top
506 new_cursor = find_loc_cursor_position @tree, x: e.pageX, y: e.pageY
508 @move_cursor new_cursor
509 @idoc.body.onkeyup = (e) =>
511 return false if ignore_key_codes[e.keyCode]?
512 #return false if control_key_codes[e.keyCode]?
513 @idoc.body.onkeydown = (e) =>
515 return false if ignore_key_codes[e.keyCode]?
516 #return false if control_key_codes[e.keyCode]?
520 new_cursor = find_prev_cursor_position @tree, @cursor...
522 @move_cursor new_cursor
525 new_cursor = find_next_cursor_position @tree, c, -1
527 @move_cursor new_cursor
534 new_cursor = find_next_cursor_position @tree, @cursor...
536 @move_cursor new_cursor
539 new_cursor = find_prev_cursor_position @tree, c, -1
541 @move_cursor new_cursor
549 return false unless @cursor?
550 return false unless @cursor[1] > 0
551 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
552 @cursor[0].el.nodeValue = @cursor[0].text
553 @move_cursor [@cursor[0], @cursor[1] - 1]
556 return false unless @cursor?
557 return false unless @cursor[1] < @cursor[0].text.length
558 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
559 @cursor[0].el.nodeValue = @cursor[0].text
560 @move_cursor [@cursor[0], @cursor[1]]
576 @idoc.body.onkeypress = (e) =>
578 return false if ignore_key_codes[e.keyCode]?
579 return false if control_key_codes[e.keyCode]? # handled in keydown
580 char = e.charCode ? e.keyCode
582 char = String.fromCharCode char
584 @cursor[0].text = char + @cursor[0].text
585 else if @cursor[1] is @cursor[0].text.length - 1
586 @cursor[0].text += char
589 @cursor[0].text.substr(0, @cursor[1]) +
591 @cursor[0].text.substr(@cursor[1])
592 @cursor[0].el.nodeValue = @cursor[0].text
593 @move_cursor [@cursor[0], @cursor[1] + 1]
596 if options.stylesheet # TODO test this
597 istyle = @idoc.createElement 'style'
598 istyle.setAttribute 'src', options.stylesheet
599 @idoc.head.appendChild istyle
600 icss = @idoc.createElement 'style'
601 icss.appendChild @idoc.createTextNode css
602 @idoc.head.appendChild icss
603 @load_html @in_el.value
605 @in_el.parentNode.appendChild @iframe
607 # FIXME add parent node, so we don't empty body and delete cursor_el
608 while @idoc.body.childNodes.length
609 @idoc.body.removeChild @idoc.body.childNodes[0]
610 @cursor_visible = false
613 @tree = peach_parser.parse html, @parser_opts
615 instantiate_tree @tree, @idoc.body
616 tree_dedup_space @tree
619 # FIXME don't export cursor placeholder (when cursor is between space characters)
620 @in_el.onchange = null
621 @in_el.value = dom_to_html @tree
623 @load_html @in_el.value
624 move_cursor: (cursor) ->
625 loc = cursor_to_xyh cursor[0], cursor[1]
627 console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
630 # replace cursor, to reset blink animation
632 @cursor_el.parentNode.removeChild @cursor_el
633 @cursor_el = domify div: id: 'peach_html5_editor_cursor'
634 @idoc.body.appendChild @cursor_el
635 @cursor_visible = true
636 # TODO figure out x,y coords for cursor
637 @cursor_el.style.left = "#{loc.x}px"
638 @cursor_el.style.top = "#{loc.y}px"
640 window.peach_html5_editor = (args...) ->
641 return new PeachHTML5Editor args...
643 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])