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 # text nodes don't have getBoundingClientRect(), so wrap it in a span, measure
23 # and then put it back
24 get_text_bounding_rect = (el) ->
25 span = el.ownerDocument.createElement 'span'
26 el.parentNode.replaceChild span, el
28 ret = span.getBoundingClientRect()
29 span.parentNode.replaceChild el, span
31 get_el_bounds = (el) ->
32 if el.getBoundingClientRect
33 rect = el.getBoundingClientRect()
35 rect = get_text_bounding_rect el
36 doc = el.ownerDocument.documentElement
37 win = el.ownerDocument.defaultView
38 y_fix = win.pageYOffset - doc.clientTop
39 x_fix = win.pageXOffset - doc.clientLeft
43 w: rect.width ? (rect.right - rect.left)
44 h: rect.height ? (rect.top - rect.bottom)
47 # figure out the x/y coordinates of where the cursor should be if it's at
48 # position ``i`` within text node ``n``
50 # implementation: insert a span tag where we want the cursor, and ask the
51 # browser where it put that span
52 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
53 parent = n.el.parentNode
58 bounds = get_el_offset n.el
62 if i is 0 # cursor at start of text
64 txts.push n.text.substr 0, 1
65 txts.push n.text.substr 1
66 else if i is n.text.length # cursor at end of text
69 txts.push n.text.substr 0, n.text.length - 1
70 txts.push n.text.substr n.text.length - 1
73 txts.push n.text.substr 0, i
74 txts.push n.text.substr i, 1
75 txts.push n.text.substr i + 1
76 for txt, txt_i in txts
77 el = n.el.ownerDocument.createTextNode txt
79 span = n.el.ownerDocument.createElement 'span'
83 parent.insertBefore el, n.el
84 parent.removeChild n.el
85 bounds = get_el_bounds els[check_i]
86 parent.insertBefore n.el, els[0]
89 ret = x: bounds.x, y: bounds.y, h: bounds.h
92 # fudge case where bounds are BS because we're on non-significant whitespace
94 first = cursor_to_xyh n, 0
95 if ret.x <= first.x and ret.y is first.y
96 # no need for a loop here, because recursion
97 ret = cursor_to_xyh n, i - 1
100 # encode text so it can be safely placed inside an html attribute
101 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
103 return txt.replace enc_attr_regex, (match, amp, quote) ->
104 return '&' if (amp)
105 return '"' if (quote)
125 dom_to_html = (dom) ->
137 if el.attrs[k].length > 0
138 ret += "=\"#{enc_attr el.attrs[k]}\""
140 unless void_elements[el.name]
141 if el.children.length
142 ret += dom_to_html el.children
143 ret += "</#{el.name}>"
147 ret += "<!--#{el.text}-->"
149 ret += "<!DOCTYPE #{el.name}"
150 if el.public_identifier? and el.public_identifier.length > 0
151 ret += " \"#{el.public_identifier}\""
152 if el.system_identifier? and el.system_identifier.length > 0
153 ret += " \"#{el.system_identifier}\""
160 return document.createTextNode attrs
161 el = document.createElement tag
171 css += 'div#peach_html5_editor_cursor {'
172 css += 'position: absolute;'
173 css += 'height: 1em;'
175 css += 'margin-left: -1px;'
176 css += 'margin-right: -1px;'
177 css += 'background: #000;'
178 css += '-webkit-animation: 1s blink step-end infinite;'
179 css += 'animation: 1s blink step-end infinite;'
181 css += '@-webkit-keyframes "blink" {'
182 css += 'from, to { background: #000; }'
183 css += '50% { background: transparent; }'
185 css += '@keyframes "blink" {'
186 css += 'from, to { background: #000; }'
187 css += '50% { background: transparent; }'
195 KEY_BACKSPACE = 8 # <--
196 KEY_DELETE = 46 # -->
206 instantiate_tree = (tree, parent) ->
210 c.el = parent.ownerDocument.createTextNode c.text
211 parent.appendChild c.el
213 # TODO create in correct namespace
214 c.el = parent.ownerDocument.createElement c.name
216 # FIXME if attr_whitelist[k]?
217 c.el.setAttribute k, v
218 parent.appendChild c.el
220 instantiate_tree c.children, c.el
222 traverse_tree = (tree, state, cb) ->
227 traverse_tree c.children, state, cb
230 # find the next element in tree (and decendants) that is after n and can contain text
231 # TODO make it so cursor can go places that don't have text but could
232 find_next_cursor_position = (tree, n, i) ->
233 if n? and n.type is TYPE_TEXT and n.text.length > i
235 found = traverse_tree tree, before: n?, (node, state) ->
236 if node.type is TYPE_TEXT and state.before is false
242 return [found.node, 0]
245 # TODO make it so cursor can go places that don't have text but could
246 find_prev_cursor_position = (tree, n, i) ->
247 if n? and n.type is TYPE_TEXT and i > 0
249 found = traverse_tree tree, before: n?, (node, state) ->
250 if node.type is TYPE_TEXT
256 state.node = state.prev
261 return [found.node, found.node.text.length]
264 find_loc_cursor_position = (tree, loc) ->
266 if c.type is TYPE_TAG or c.type is TYPE_TEXT
267 bounds = get_el_bounds c.el
268 continue if loc.x < bounds.x
269 continue if loc.x > bounds.x + bounds.w
270 continue if loc.y < bounds.y
271 continue if loc.y > bounds.y + bounds.h
273 ret = find_loc_cursor_position c.children, loc
275 if c.type is TYPE_TEXT
276 # click is within bounding box that contains all text.
277 return [c, 0] if c.text.length is 0
279 before = cursor_to_xyh c, before_i
280 after_i = c.text.length
281 after = cursor_to_xyh c, after_i
282 if loc.y < before.y + before.h and loc.x < before.x
283 continue # before first char on first line
284 if loc.y > after.y and loc.x > after.x
285 continue # after last char on last line
287 console.log "Warning: click in bounding box but above first line"
288 continue # above first line (runaround?)
289 if loc.y > after.y + after.h
290 console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
291 continue # below last line (shouldn't happen?)
292 while after_i - before_i > 1
293 cur_i = Math.round((before_i + after_i) / 2)
294 cur = cursor_to_xyh c, cur_i
295 if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
301 # which one is closest?
302 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
308 class PeachHTML5Editor
309 constructor: (in_el, options = {}) ->
312 @iframe = domify iframe: class: 'peach_html5_editor'
315 @cursor_visible = false
316 opt_fragment = options.fragment ? true
319 @parser_opts.fragment = 'body'
322 @idoc = @iframe.contentDocument
326 '20': true # capslock
328 '144': true # numlock
330 '91': true # windows "start" key
331 control_key_codes = # we react to these, but they aren't typing
347 @idoc.body.onclick = (e) =>
348 # idoc.body.offset().left/top
349 new_cursor = find_loc_cursor_position @tree, x: e.pageX, y: e.pageY
351 @move_cursor new_cursor
352 @idoc.body.onkeyup = (e) =>
354 return false if ignore_key_codes[e.keyCode]?
355 #return false if control_key_codes[e.keyCode]?
356 @idoc.body.onkeydown = (e) =>
358 return false if ignore_key_codes[e.keyCode]?
359 #return false if control_key_codes[e.keyCode]?
363 new_cursor = find_prev_cursor_position @tree, @cursor...
365 @move_cursor new_cursor
368 new_cursor = find_next_cursor_position @tree, c, -1
370 @move_cursor new_cursor
377 new_cursor = find_next_cursor_position @tree, @cursor...
379 @move_cursor new_cursor
382 new_cursor = find_prev_cursor_position @tree, c, -1
384 @move_cursor new_cursor
409 @idoc.body.onkeypress = (e) =>
411 return false if ignore_key_codes[e.keyCode]?
412 return false if control_key_codes[e.keyCode]? # handled in keydown
413 char = e.charCode ? e.keyCode
415 char = String.fromCharCode char
417 @cursor[0].text = char + @cursor[0].text
418 else if @cursor[1] is @cursor[0].text.length - 1
419 @cursor[0].text += char
422 @cursor[0].text.substr(0, @cursor[1]) +
424 @cursor[0].text.substr(@cursor[1])
425 @cursor[0].el.nodeValue = @cursor[0].text
426 @move_cursor [@cursor[0], @cursor[1] + 1]
428 if options.stylesheet # TODO test this
429 istyle = @idoc.createElement 'style'
430 istyle.setAttribute 'src', options.stylesheet
431 @idoc.head.appendChild istyle
432 icss = @idoc.createElement 'style'
433 icss.appendChild @idoc.createTextNode css
434 @idoc.head.appendChild icss
435 @load_html @in_el.value
437 @in_el.parentNode.appendChild @iframe
439 # FIXME add parent node, so we don't empty body and delete cursor_el
440 while @idoc.body.childNodes.length
441 @idoc.body.removeChild @idoc.body.childNodes[0]
442 @cursor_visible = false
445 @tree = peach_parser.parse html, @parser_opts
446 #as_html = dom_to_html @tree
447 #@iframe.contentDocument.body.innerHTML = as_html
449 instantiate_tree @tree, @idoc.body
450 move_cursor: (cursor) ->
451 return if @cursor? and cursor? and @cursor[0] is cursor[0] and @cursor[1] is cursor[1]
453 # replace cursor, to reset blink animation
455 @cursor_el.parentNode.removeChild @cursor_el
456 @cursor_el = domify div: id: 'peach_html5_editor_cursor'
457 @idoc.body.appendChild @cursor_el
458 @cursor_visible = true
459 # TODO figure out x,y coords for cursor
460 loc = cursor_to_xyh cursor[0], cursor[1]
461 @cursor_el.style.left = "#{loc.x}px"
462 @cursor_el.style.top = "#{loc.y}px"
464 window.peach_html5_editor = (args...) ->
465 return new PeachHTML5Editor args...
467 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])