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 top/left 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 cursor_to_loc = (n, i) ->
53 span = domify span: style: "height: 1em; border-left: 1px solid black; margin-left: -1px"
54 parent = n.el.parentNode
59 bounds = get_el_offset n.el
63 if i is 0 # cursor at start of text
65 txts.push n.text.substr 0, 1
66 txts.push n.text.substr 1
67 else if i is n.text.length # cursor at end of text
70 txts.push n.text.substr 0, n.text.length - 1
71 txts.push n.text.substr n.text.length - 1
74 txts.push n.text.substr 0, i
75 txts.push n.text.substr i, 1
76 txts.push n.text.substr i + 1
77 for txt, txt_i in txts
78 el = n.el.ownerDocument.createTextNode txt
80 span = n.el.ownerDocument.createElement 'span'
84 parent.insertBefore el, n.el
85 parent.removeChild n.el
86 bounds = get_el_bounds els[check_i]
87 parent.insertBefore n.el, els[0]
90 ret = top: bounds.y, left: bounds.x
93 # fudge case where bounds are BS because we're on non-significant whitespace
95 first = cursor_to_loc n, 0
96 if ret.left <= first.left
97 # no need for a loop here, because recursion
98 ret = cursor_to_loc n, i - 1
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)
126 dom_to_html = (dom) ->
138 if el.attrs[k].length > 0
139 ret += "=\"#{enc_attr el.attrs[k]}\""
141 unless void_elements[el.name]
142 if el.children.length
143 ret += dom_to_html el.children
144 ret += "</#{el.name}>"
148 ret += "<!--#{el.text}-->"
150 ret += "<!DOCTYPE #{el.name}"
151 if el.public_identifier? and el.public_identifier.length > 0
152 ret += " \"#{el.public_identifier}\""
153 if el.system_identifier? and el.system_identifier.length > 0
154 ret += " \"#{el.system_identifier}\""
161 return document.createTextNode attrs
162 el = document.createElement tag
172 css += 'div#peach_html5_editor_cursor {'
173 css += 'position: absolute;'
174 css += 'height: 1em;'
176 css += 'margin-left: -1px;'
177 css += 'margin-right: -1px;'
178 css += 'background: #000;'
179 css += '-webkit-animation: 1s blink step-end infinite;'
180 css += 'animation: 1s blink step-end infinite;'
182 css += '@-webkit-keyframes "blink" {'
183 css += 'from, to { background: #000; }'
184 css += '50% { background: transparent; }'
186 css += '@keyframes "blink" {'
187 css += 'from, to { background: #000; }'
188 css += '50% { background: transparent; }'
196 KEY_BACKSPACE = 8 # <--
197 KEY_DELETE = 46 # -->
207 instantiate_tree = (tree, parent) ->
211 c.el = parent.ownerDocument.createTextNode c.text
212 parent.appendChild c.el
214 # TODO create in correct namespace
215 c.el = parent.ownerDocument.createElement c.name
217 # FIXME if attr_whitelist[k]?
218 c.el.setAttribute k, v
219 parent.appendChild c.el
221 instantiate_tree c.children, c.el
223 traverse_tree = (tree, state, cb) ->
228 traverse_tree c.children, state, cb
231 # find the next element in top (and decendants) that is after n and can contain text
232 # TODO make it so cursor can go places that don't have text but could
233 find_next_cursor_position = (tree, n, i) ->
234 if n? and n.type is TYPE_TEXT and n.text.length > i
236 found = traverse_tree tree, before: n?, (node, state) ->
237 if node.type is TYPE_TEXT and state.before is false
243 return [found.node, 0]
246 # TODO make it so cursor can go places that don't have text but could
247 find_prev_cursor_position = (tree, n, i) ->
248 if n? and n.type is TYPE_TEXT and i > 0
250 found = traverse_tree tree, before: n?, (node, state) ->
251 if node.type is TYPE_TEXT
257 state.node = state.prev
262 return [found.node, found.node.text.length]
265 find_loc_cursor_position = (tree, loc) ->
266 console.log tree, loc
268 if c.type is TYPE_TAG or c.type is TYPE_TEXT
269 bounds = get_el_bounds c.el
271 continue if loc.left < bounds.x
272 continue if loc.left > bounds.x + bounds.w
273 continue if loc.top < bounds.y
274 continue if loc.top > bounds.y + bounds.h
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
278 #if c.text.length is 1
279 # definitely no linebreak in it
282 # for inline elements, this can include text in other tags on
283 # the first or last lines.
285 # they clicked on text. now determine where in the text
287 cur = Math.floor(c.text.length / 2)
289 # xy = tries[cur] = cursor_to_loc c, cur
293 ret = find_loc_cursor_position c.children, loc
294 console.log 'found', ret if ret?
298 class PeachHTML5Editor
299 constructor: (in_el, options = {}) ->
302 @iframe = domify iframe: class: 'peach_html5_editor'
305 @cursor_visible = false
306 opt_fragment = options.fragment ? true
309 @parser_opts.fragment = 'body'
312 @idoc = @iframe.contentDocument
316 '20': true # capslock
318 '144': true # numlock
320 '91': true # windows "start" key
321 control_key_codes = # we react to these, but they aren't typing
337 @idoc.body.onclick = (e) =>
338 # idoc.body.offset().left/top
339 new_cursor = find_loc_cursor_position @tree, left: e.pageX, top: e.pageY
341 @move_cursor new_cursor
342 @idoc.body.onkeyup = (e) =>
344 return false if ignore_key_codes[e.keyCode]?
345 #return false if control_key_codes[e.keyCode]?
346 @idoc.body.onkeydown = (e) =>
348 return false if ignore_key_codes[e.keyCode]?
349 #return false if control_key_codes[e.keyCode]?
353 new_cursor = find_prev_cursor_position @tree, @cursor...
355 @move_cursor new_cursor
358 new_cursor = find_next_cursor_position @tree, c, -1
360 @move_cursor new_cursor
367 new_cursor = find_next_cursor_position @tree, @cursor...
369 @move_cursor new_cursor
372 new_cursor = find_prev_cursor_position @tree, c, -1
374 @move_cursor new_cursor
399 @idoc.body.onkeypress = (e) =>
401 return false if ignore_key_codes[e.keyCode]?
402 return false if control_key_codes[e.keyCode]? # handled in keydown
403 char = e.charCode ? e.keyCode
405 char = String.fromCharCode char
407 @cursor[0].text = char + @cursor[0].text
408 else if @cursor[1] is @cursor[0].text.length - 1
409 @cursor[0].text += char
412 @cursor[0].text.substr(0, @cursor[1]) +
414 @cursor[0].text.substr(@cursor[1])
415 @cursor[0].el.nodeValue = @cursor[0].text
416 @move_cursor [@cursor[0], @cursor[1] + 1]
418 if options.stylesheet # TODO test this
419 istyle = @idoc.createElement 'style'
420 istyle.setAttribute 'src', options.stylesheet
421 @idoc.head.appendChild istyle
422 icss = @idoc.createElement 'style'
423 icss.appendChild @idoc.createTextNode css
424 @idoc.head.appendChild icss
425 @load_html @in_el.value
427 @in_el.parentNode.appendChild @iframe
429 # FIXME add parent node, so we don't empty body and delete cursor_el
430 while @idoc.body.childNodes.length
431 @idoc.body.removeChild @idoc.body.childNodes[0]
432 @cursor_visible = false
435 @tree = peach_parser.parse html, @parser_opts
436 #as_html = dom_to_html @tree
437 #@iframe.contentDocument.body.innerHTML = as_html
439 instantiate_tree @tree, @idoc.body
440 move_cursor: (cursor) ->
441 return if @cursor? and cursor? and @cursor[0] is cursor[0] and @cursor[1] is cursor[1]
443 # replace cursor, to reset blink animation
445 @cursor_el.parentNode.removeChild @cursor_el
446 @cursor_el = domify div: id: 'peach_html5_editor_cursor'
447 @idoc.body.appendChild @cursor_el
448 @cursor_visible = true
449 # TODO figure out top/left coords for cursor
450 loc = cursor_to_loc cursor[0], cursor[1]
451 @cursor_el.style.top = "#{loc.top}px"
452 @cursor_el.style.left = "#{loc.left}px"
454 window.peach_html5_editor = (args...) ->
455 return new PeachHTML5Editor args...
457 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])