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_text_bounding_rect = (el) ->
31 get_el_bounds = (el) ->
32 if el.getBoundingClientRect?
33 rect = el.getBoundingClientRect()
35 # text nodes don't have getBoundingClientRect(), so use range api
36 range = el.ownerDocument.createRange()
37 range.selectNodeContents el
38 rect = range.getBoundingClientRect()
39 doc = el.ownerDocument.documentElement
40 win = el.ownerDocument.defaultView
41 y_fix = win.pageYOffset - doc.clientTop
42 x_fix = win.pageXOffset - doc.clientLeft
46 w: rect.width ? (rect.right - rect.left)
47 h: rect.height ? (rect.top - rect.bottom)
50 # figure out the x/y coordinates of where the cursor should be if it's at
51 # position ``i`` within text node ``n``
52 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
53 range = document.createRange()
56 range.setStart n.el, i
59 range.setStart n.el, i - 1
63 range.setStart n.el, i
64 range.setEnd n.el, i + 1
65 # chromium returns bogus results with getBoundingClientRect() when zero width and/or height
66 rect = range.getClientRects()
69 # chromium returns multiple rects for the space that is broken
70 # across lines by word-wrap (firefox doesn't)
71 rect = rect[rect.length - 1]
75 return x: 0, y: 0, w: 0, h: 0 # TODO return null, fix callers
79 w: rect.width ? (rect.right - rect.left)
80 h: rect.height ? (rect.top - rect.bottom)
84 debug_dot_at n.el.ownerDocument, ret.x, ret.y
87 # encode text so it can be safely placed inside an html attribute
88 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
90 return txt.replace enc_attr_regex, (match, amp, quote) ->
91 return '&' if (amp)
92 return '"' if (quote)
112 dom_to_html = (dom) ->
124 if el.attrs[k].length > 0
125 ret += "=\"#{enc_attr el.attrs[k]}\""
127 unless void_elements[el.name]
128 if el.children.length
129 ret += dom_to_html el.children
130 ret += "</#{el.name}>"
134 ret += "<!--#{el.text}-->"
136 ret += "<!DOCTYPE #{el.name}"
137 if el.public_identifier? and el.public_identifier.length > 0
138 ret += " \"#{el.public_identifier}\""
139 if el.system_identifier? and el.system_identifier.length > 0
140 ret += " \"#{el.system_identifier}\""
147 return document.createTextNode attrs
148 el = document.createElement tag
158 css += 'div#peach_html5_editor_cursor {'
159 css += 'position: absolute;'
160 css += 'height: 1em;'
162 css += 'margin-left: -1px;'
163 css += 'margin-right: -1px;'
164 css += 'background: #444;'
165 css += '-webkit-animation: blink 1s steps(2, start) infinite;'
166 css += 'animation: blink 1s steps(2, start) infinite;'
168 css += '@-webkit-keyframes blink {'
169 css += 'to { visibility: hidden; }'
171 css += '@keyframes blink {'
172 css += 'to { visibility: hidden; }'
180 KEY_BACKSPACE = 8 # <--
181 KEY_DELETE = 46 # -->
191 instantiate_tree = (tree, parent) ->
195 c.el = parent.ownerDocument.createTextNode c.text
196 parent.appendChild c.el
198 # TODO create in correct namespace
199 c.el = parent.ownerDocument.createElement c.name
201 # FIXME if attr_whitelist[k]?
202 c.el.setAttribute k, v
203 parent.appendChild c.el
205 instantiate_tree c.children, c.el
207 traverse_tree = (tree, state, cb) ->
212 traverse_tree c.children, state, cb
215 # find the next element in tree (and decendants) that is after n and can contain text
216 # TODO make it so cursor can go places that don't have text but could
217 find_next_cursor_position = (tree, n, i) ->
218 if n? and n.type is TYPE_TEXT and n.text.length > i
219 orig_xyh = cursor_to_xyh n, i
220 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
221 next_xyh = cursor_to_xyh n, next_i
222 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
224 found = traverse_tree tree, before: n?, (node, state) ->
225 if node.type is TYPE_TEXT and state.before is false
231 return [found.node, 0]
234 # TODO make it so cursor can go places that don't have text but could
235 find_prev_cursor_position = (tree, n, i) ->
236 if n? and n.type is TYPE_TEXT and i > 0
237 orig_xyh = cursor_to_xyh n, i
238 for prev_i in [i-1 .. 0]
239 prev_xyh = cursor_to_xyh n, prev_i
240 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
243 found = traverse_tree tree, before: n?, (node, state) ->
244 if node.type is TYPE_TEXT
250 state.node = state.prev
255 return [found.node, found.node.text.length]
258 find_loc_cursor_position = (tree, loc) ->
260 if c.type is TYPE_TAG or c.type is TYPE_TEXT
261 bounds = get_el_bounds c.el
262 continue if loc.x < bounds.x
263 continue if loc.x > bounds.x + bounds.w
264 continue if loc.y < bounds.y
265 continue if loc.y > bounds.y + bounds.h
267 ret = find_loc_cursor_position c.children, loc
269 if c.type is TYPE_TEXT
270 # click is within bounding box that contains all text.
271 return [c, 0] if c.text.length is 0
273 before = cursor_to_xyh c, before_i
274 after_i = c.text.length
275 after = cursor_to_xyh c, after_i
276 if loc.y < before.y + before.h and loc.x < before.x
277 # console.log 'before first char on first line'
279 if loc.y > after.y and loc.x > after.x
280 # console.log 'after last char on last line'
283 console.log "Warning: click in bounding box but above first line"
284 continue # above first line (runaround?)
285 if loc.y > after.y + after.h
286 console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
287 continue # below last line (shouldn't happen?)
288 while after_i - before_i > 1
289 cur_i = Math.round((before_i + after_i) / 2)
290 cur = cursor_to_xyh c, cur_i
291 if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
297 # which one is closest?
298 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
304 class PeachHTML5Editor
305 constructor: (in_el, options = {}) ->
308 @iframe = domify iframe: class: 'peach_html5_editor'
311 @cursor_visible = false
312 opt_fragment = options.fragment ? true
315 @parser_opts.fragment = 'body'
318 @idoc = @iframe.contentDocument
322 '20': true # capslock
324 '144': true # numlock
326 '91': true # windows "start" key
327 control_key_codes = # we react to these, but they aren't typing
343 @idoc.body.onclick = (e) =>
344 # idoc.body.offset().left/top
345 new_cursor = find_loc_cursor_position @tree, x: e.pageX, y: e.pageY
347 @move_cursor new_cursor
348 @idoc.body.onkeyup = (e) =>
350 return false if ignore_key_codes[e.keyCode]?
351 #return false if control_key_codes[e.keyCode]?
352 @idoc.body.onkeydown = (e) =>
354 return false if ignore_key_codes[e.keyCode]?
355 #return false if control_key_codes[e.keyCode]?
359 new_cursor = find_prev_cursor_position @tree, @cursor...
361 @move_cursor new_cursor
364 new_cursor = find_next_cursor_position @tree, c, -1
366 @move_cursor new_cursor
373 new_cursor = find_next_cursor_position @tree, @cursor...
375 @move_cursor new_cursor
378 new_cursor = find_prev_cursor_position @tree, c, -1
380 @move_cursor new_cursor
388 return false unless @cursor?
389 return false unless @cursor[1] > 0
390 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
391 @cursor[0].el.nodeValue = @cursor[0].text
392 @move_cursor [@cursor[0], @cursor[1] - 1]
395 return false unless @cursor?
396 return false unless @cursor[1] < @cursor[0].text.length
397 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
398 @cursor[0].el.nodeValue = @cursor[0].text
399 @move_cursor [@cursor[0], @cursor[1]]
415 @idoc.body.onkeypress = (e) =>
417 return false if ignore_key_codes[e.keyCode]?
418 return false if control_key_codes[e.keyCode]? # handled in keydown
419 char = e.charCode ? e.keyCode
421 char = String.fromCharCode char
423 @cursor[0].text = char + @cursor[0].text
424 else if @cursor[1] is @cursor[0].text.length - 1
425 @cursor[0].text += char
428 @cursor[0].text.substr(0, @cursor[1]) +
430 @cursor[0].text.substr(@cursor[1])
431 @cursor[0].el.nodeValue = @cursor[0].text
432 @move_cursor [@cursor[0], @cursor[1] + 1]
434 if options.stylesheet # TODO test this
435 istyle = @idoc.createElement 'style'
436 istyle.setAttribute 'src', options.stylesheet
437 @idoc.head.appendChild istyle
438 icss = @idoc.createElement 'style'
439 icss.appendChild @idoc.createTextNode css
440 @idoc.head.appendChild icss
441 @load_html @in_el.value
443 @in_el.parentNode.appendChild @iframe
445 # FIXME add parent node, so we don't empty body and delete cursor_el
446 while @idoc.body.childNodes.length
447 @idoc.body.removeChild @idoc.body.childNodes[0]
448 @cursor_visible = false
451 @tree = peach_parser.parse html, @parser_opts
452 #as_html = dom_to_html @tree
453 #@iframe.contentDocument.body.innerHTML = as_html
455 instantiate_tree @tree, @idoc.body
456 move_cursor: (cursor) ->
457 loc = cursor_to_xyh cursor[0], cursor[1]
458 return if loc is null
460 # replace cursor, to reset blink animation
462 @cursor_el.parentNode.removeChild @cursor_el
463 @cursor_el = domify div: id: 'peach_html5_editor_cursor'
464 @idoc.body.appendChild @cursor_el
465 @cursor_visible = true
466 # TODO figure out x,y coords for cursor
467 @cursor_el.style.left = "#{loc.x}px"
468 @cursor_el.style.top = "#{loc.y}px"
470 window.peach_html5_editor = (args...) ->
471 return new PeachHTML5Editor args...
473 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])