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)
123 dom_to_html = (dom) ->
135 if el.attrs[k].length > 0
136 ret += "=\"#{enc_attr el.attrs[k]}\""
138 unless void_elements[el.name]
139 if el.children.length
140 ret += dom_to_html el.children
141 ret += "</#{el.name}>"
145 ret += "<!--#{el.text}-->"
147 ret += "<!DOCTYPE #{el.name}"
148 if el.public_identifier? and el.public_identifier.length > 0
149 ret += " \"#{el.public_identifier}\""
150 if el.system_identifier? and el.system_identifier.length > 0
151 ret += " \"#{el.system_identifier}\""
158 return document.createTextNode attrs
159 el = document.createElement tag
169 css += 'div#peach_html5_editor_cursor {'
170 css += 'position: absolute;'
171 css += 'height: 1em;'
173 css += 'margin-left: -1px;'
174 css += 'margin-right: -1px;'
175 css += 'background: #444;'
176 css += '-webkit-animation: blink 1s steps(2, start) infinite;'
177 css += 'animation: blink 1s steps(2, start) infinite;'
179 css += '@-webkit-keyframes blink {'
180 css += 'to { visibility: hidden; }'
182 css += '@keyframes blink {'
183 css += 'to { visibility: hidden; }'
191 KEY_BACKSPACE = 8 # <--
192 KEY_DELETE = 46 # -->
202 instantiate_tree = (tree, parent) ->
206 c.el = parent.ownerDocument.createTextNode c.text
207 parent.appendChild c.el
209 # TODO create in correct namespace
210 c.el = parent.ownerDocument.createElement c.name
212 # FIXME if attr_whitelist[k]?
213 c.el.setAttribute k, v
214 parent.appendChild c.el
216 instantiate_tree c.children, c.el
218 traverse_tree = (tree, state, cb) ->
223 traverse_tree c.children, state, cb
226 # find the next element in tree (and decendants) that is after n and can contain text
227 # TODO make it so cursor can go places that don't have text but could
228 find_next_cursor_position = (tree, n, i) ->
229 if n? and n.type is TYPE_TEXT and n.text.length > i
230 orig_xyh = cursor_to_xyh n, i
232 console.log "ERROR: couldn't find xy for current cursor location"
234 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
235 next_xyh = cursor_to_xyh n, next_i
237 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
239 found = traverse_tree tree, before: n?, (node, state) ->
240 if node.type is TYPE_TEXT and state.before is false
246 return [found.node, 0]
249 # TODO make it so cursor can go places that don't have text but could
250 find_prev_cursor_position = (tree, n, i) ->
251 if n? and n.type is TYPE_TEXT and i > 0
252 orig_xyh = cursor_to_xyh n, i
254 console.log "ERROR: couldn't find xy for current cursor location"
256 for prev_i in [i-1 .. 0]
257 prev_xyh = cursor_to_xyh n, prev_i
259 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
262 found = traverse_tree tree, before: n?, (node, state) ->
263 if node.type is TYPE_TEXT
269 state.node = state.prev
274 return [found.node, found.node.text.length]
277 find_loc_cursor_position = (tree, loc) ->
279 if c.type is TYPE_TAG or c.type is TYPE_TEXT
280 bounds = get_el_bounds c.el
281 continue if loc.x < bounds.x
282 continue if loc.x > bounds.x + bounds.w
283 continue if loc.y < bounds.y
284 continue if loc.y > bounds.y + bounds.h
286 ret = find_loc_cursor_position c.children, loc
288 if c.type is TYPE_TEXT
289 # click is within bounding box that contains all text.
290 return [c, 0] if c.text.length is 0
292 before = cursor_to_xyh c, before_i
294 console.log "error: failed to find cursor pixel location for start of", c
296 after_i = c.text.length
297 after = cursor_to_xyh c, after_i
299 console.log "error: failed to find cursor pixel location for end of", c
301 if loc.y < before.y + before.h and loc.x < before.x
302 # console.log 'before first char on first line'
304 if loc.y > after.y and loc.x > after.x
305 # console.log 'after last char on last line'
308 console.log "Warning: click in bounding box but above first line"
309 continue # above first line (runaround?)
310 if loc.y > after.y + after.h
311 console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
312 continue # below last line (shouldn't happen?)
313 while after_i - before_i > 1
314 cur_i = Math.round((before_i + after_i) / 2)
315 cur = cursor_to_xyh c, cur_i
317 console.log "error: failed to find cursor pixel location for", c, cur_i
319 if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
325 # which one is closest?
326 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
332 # browsers collapse these (html5 spec calls these "space characters")
333 is_space_code = (char_code) ->
335 when 9, 10, 12, 13, 32
339 return is_space_code chr.charCodeAt 0
341 # pass a array of nodes (from parser library, ie it should have .el and .text)
342 tree_dedup_space = (tree) ->
343 prev = cur = next = null
344 prev_i = cur_i = next_i = 0
345 prev_pos = pos = next_pos = null
346 prev_px = cur_px = next_px = null
350 iterate = (tree, cb) ->
352 if n.type is TYPE_TEXT
354 while i < n.text.length # don't foreach, cb might remove chars
358 if n.type is TYPE_TAG
359 block = is_display_block n.el
362 if n.children.length > 0
363 iterate n.children, cb
368 removed_char = cur.text.charAt(cur_i)
369 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
370 if next is cur # in same text node
372 throw "how is this possible?"
377 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
378 if next is cur # in same text node
381 # return true if cur was removed from the dom (ie re-use same prev)
383 # cur definitately set
384 # prev and/or next might be null, indicating the start/end of a display:block
385 return false unless is_space_code cur.text.charCodeAt cur_i
386 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
388 # 1. zero rects returned by getClientRects() means collapsed space
391 # 2. width greater than zero means visible space
394 # now the weird edge cases...
396 # firefox and chromium both report zero width for characters at the end
397 # of a line where the text wraps (automatically, due to word-wrap) to
398 # the next line. These do not appear to be distinguishable from
399 # collapsed spaces via the range/bounds api, so...
401 # remove it from the dom, and if prev or next moves, put it back.
402 if prev? and not prev_px?
403 prev_px = cursor_to_xyh prev, prev_i
404 if next? and not next_px?
405 next_px = cursor_to_xyh next, next_i
406 #if prev is null and next is null
407 # parent_px = cur.parent.el.getBoundingClientRect()
411 new_prev_px = cursor_to_xyh prev, prev_i
412 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
415 console.log "this shouldn't happen, we remove spaces that don't locate"
418 new_next_px = cursor_to_xyh next, next_i
419 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
422 # console.log "removing space becase space after it is collapsed"
423 # if there's no prev or next (single space inside a block-level element?) check
424 # TODO scrapt this, or fix it so it works when there's no parent
425 # if prev is null and next is null
426 # new_parent_px = cur.parent.el.getBoundingClientRect()
427 # 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
428 # console.log "WEIRD: parent moved"
429 # return put_it_back()
430 # we didn't put it back
432 # pass null at start/end of display:block
453 class PeachHTML5Editor
454 constructor: (in_el, options = {}) ->
457 @iframe = domify iframe: class: 'peach_html5_editor'
460 @cursor_visible = false
461 opt_fragment = options.fragment ? true
464 @parser_opts.fragment = 'body'
467 @idoc = @iframe.contentDocument
471 '20': true # capslock
473 '144': true # numlock
475 '91': true # windows "start" key
476 control_key_codes = # we react to these, but they aren't typing
492 @idoc.body.onclick = (e) =>
493 # idoc.body.offset().left/top
494 new_cursor = find_loc_cursor_position @tree, x: e.pageX, y: e.pageY
496 @move_cursor new_cursor
497 @idoc.body.onkeyup = (e) =>
499 return false if ignore_key_codes[e.keyCode]?
500 #return false if control_key_codes[e.keyCode]?
501 @idoc.body.onkeydown = (e) =>
503 return false if ignore_key_codes[e.keyCode]?
504 #return false if control_key_codes[e.keyCode]?
508 new_cursor = find_prev_cursor_position @tree, @cursor...
510 @move_cursor new_cursor
513 new_cursor = find_next_cursor_position @tree, c, -1
515 @move_cursor new_cursor
522 new_cursor = find_next_cursor_position @tree, @cursor...
524 @move_cursor new_cursor
527 new_cursor = find_prev_cursor_position @tree, c, -1
529 @move_cursor new_cursor
537 return false unless @cursor?
538 return false unless @cursor[1] > 0
539 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
540 @cursor[0].el.nodeValue = @cursor[0].text
541 @move_cursor [@cursor[0], @cursor[1] - 1]
544 return false unless @cursor?
545 return false unless @cursor[1] < @cursor[0].text.length
546 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
547 @cursor[0].el.nodeValue = @cursor[0].text
548 @move_cursor [@cursor[0], @cursor[1]]
564 @idoc.body.onkeypress = (e) =>
566 return false if ignore_key_codes[e.keyCode]?
567 return false if control_key_codes[e.keyCode]? # handled in keydown
568 char = e.charCode ? e.keyCode
570 char = String.fromCharCode char
572 @cursor[0].text = char + @cursor[0].text
573 else if @cursor[1] is @cursor[0].text.length - 1
574 @cursor[0].text += char
577 @cursor[0].text.substr(0, @cursor[1]) +
579 @cursor[0].text.substr(@cursor[1])
580 @cursor[0].el.nodeValue = @cursor[0].text
581 @move_cursor [@cursor[0], @cursor[1] + 1]
584 if options.stylesheet # TODO test this
585 istyle = @idoc.createElement 'style'
586 istyle.setAttribute 'src', options.stylesheet
587 @idoc.head.appendChild istyle
588 icss = @idoc.createElement 'style'
589 icss.appendChild @idoc.createTextNode css
590 @idoc.head.appendChild icss
591 @load_html @in_el.value
593 @in_el.parentNode.appendChild @iframe
595 # FIXME add parent node, so we don't empty body and delete cursor_el
596 while @idoc.body.childNodes.length
597 @idoc.body.removeChild @idoc.body.childNodes[0]
598 @cursor_visible = false
601 @tree = peach_parser.parse html, @parser_opts
603 instantiate_tree @tree, @idoc.body
604 tree_dedup_space @tree
607 # FIXME don't export cursor placeholder (when cursor is between space characters)
608 @in_el.onchange = null
609 @in_el.value = dom_to_html @tree
611 @load_html @in_el.value
612 move_cursor: (cursor) ->
613 loc = cursor_to_xyh cursor[0], cursor[1]
615 console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
618 # replace cursor, to reset blink animation
620 @cursor_el.parentNode.removeChild @cursor_el
621 @cursor_el = domify div: id: 'peach_html5_editor_cursor'
622 @idoc.body.appendChild @cursor_el
623 @cursor_visible = true
624 # TODO figure out x,y coords for cursor
625 @cursor_el.style.left = "#{loc.x}px"
626 @cursor_el.style.top = "#{loc.y}px"
628 window.peach_html5_editor = (args...) ->
629 return new PeachHTML5Editor args...
631 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])