JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
click to cursor position works
[peach-html5-editor.git] / editor.coffee
1 # Copyright 2015 Jason Woofenden
2 # This file implements an WYSIWYG editor in the browser (no contenteditable)
3 #
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
7 # later version.
8 #
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
12 # details.
13 #
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/>.
16
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
21
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
27         span.appendChild el
28         ret = span.getBoundingClientRect()
29         span.parentNode.replaceChild el, span
30         return ret
31 get_el_bounds = (el) ->
32         if el.getBoundingClientRect
33                 rect = el.getBoundingClientRect()
34         else
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
40         return {
41                 x: rect.left + x_fix
42                 y: rect.top + y_fix
43                 w: rect.width ? (rect.right - rect.left)
44                 h: rect.height ? (rect.top - rect.bottom)
45         }
46
47 # figure out the x/y coordinates of where the cursor should be if it's at
48 # position ``i`` within text node ``n``
49 #
50 # implementation: insert a span tag where we want the cursor, and ask the
51 # browser where it put that span
52 cursor_to_xyh = (n, i) ->
53         span = domify span: style: "height: 1em; border-left: 1px solid black; margin-left: -1px"
54         parent = n.el.parentNode
55         els = []
56         txts = []
57         plus_width = false
58         if n.text.length < 2
59                 bounds = get_el_offset n.el
60                 if i is 1
61                         plus_width = true
62         else
63                 if i is 0 # cursor at start of text
64                         check_i = 0
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
68                         check_i = 1
69                         plus_width = true
70                         txts.push n.text.substr 0, n.text.length - 1
71                         txts.push n.text.substr n.text.length - 1
72                 else
73                         check_i = 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
79                         if txt_i is check_i
80                                 span = n.el.ownerDocument.createElement 'span'
81                                 span.appendChild el
82                                 el = span
83                         els.push el
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]
88                 for el in els
89                         parent.removeChild el
90         ret = x: bounds.x, y: bounds.y, h: bounds.h
91         if plus_width
92                 ret.x += bounds.w
93         # fudge case where bounds are BS because we're on non-significant whitespace
94         if i > 0
95                 first = cursor_to_xyh n, 0
96                 if ret.x <= first.x
97                         # no need for a loop here, because recursion
98                         ret = cursor_to_xyh n, i - 1
99         return ret
100
101 # encode text so it can be safely placed inside an html attribute
102 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
103 enc_attr = (txt) ->
104         return txt.replace enc_attr_regex, (match, amp, quote) ->
105                 return '&amp;' if (amp)
106                 return '&quot;' if (quote)
107                 return '&nbsp;'
108
109 void_elements = {
110         area: true
111         base: true
112         br: true
113         col: true
114         embed: true
115         hr: true
116         img: true
117         input: true
118         keygen: true
119         link: true
120         meta: true
121         param: true
122         source: true
123         track: true
124         wbr: true
125 }
126 dom_to_html = (dom) ->
127         ret = ''
128         for el in dom
129                 switch el.type
130                         when TYPE_TAG
131                                 ret += '<' + el.name
132                                 attr_keys = []
133                                 for k of el.attrs
134                                         attr_keys.unshift k
135                                 #attr_keys.sort()
136                                 for k in attr_keys
137                                         ret += " #{k}"
138                                         if el.attrs[k].length > 0
139                                                 ret += "=\"#{enc_attr el.attrs[k]}\""
140                                 ret += '>'
141                                 unless void_elements[el.name]
142                                         if el.children.length
143                                                 ret += dom_to_html el.children
144                                         ret += "</#{el.name}>"
145                         when TYPE_TEXT
146                                 ret += el.text
147                         when TYPE_COMMENT
148                                 ret += "<!--#{el.text}-->"
149                         when TYPE_DOCTYPE
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}\""
155                                 ret += ">\n"
156         return ret
157
158 domify = (h) ->
159         for tag, attrs of h
160                 if tag is 'text'
161                         return document.createTextNode attrs
162                 el = document.createElement tag
163                 for k, v of attrs
164                         if k is 'children'
165                                 for child in v
166                                         el.appendChild child
167                         else
168                                 el.setAttribute k, v
169         return el
170
171 css = ''
172 css += 'div#peach_html5_editor_cursor {'
173 css +=     'position: absolute;'
174 css +=     'height: 1em;'
175 css +=     'width: 2px;'
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;'
181 css += '}'
182 css += '@-webkit-keyframes "blink" {'
183 css +=     'from, to { background: #000; }'
184 css +=     '50% { background: transparent; }'
185 css += '}'
186 css += '@keyframes "blink" {'
187 css +=     'from, to { background: #000; }'
188 css +=     '50% { background: transparent; }'
189 css += '}'
190
191 # key codes:
192 KEY_LEFT = 37
193 KEY_UP = 38
194 KEY_RIGHT = 39
195 KEY_DOWN = 40
196 KEY_BACKSPACE = 8 # <--
197 KEY_DELETE = 46 # -->
198 KEY_END = 35
199 KEY_ENTER = 13
200 KEY_ESCAPE = 27
201 KEY_HOME = 36
202 KEY_INSERT = 45
203 KEY_PAGE_UP = 33
204 KEY_PAGE_DOWN = 34
205 KEY_TAB = 9
206
207 instantiate_tree = (tree, parent) ->
208         for c in tree
209                 switch c.type
210                         when TYPE_TEXT
211                                 c.el = parent.ownerDocument.createTextNode c.text
212                                 parent.appendChild c.el
213                         when TYPE_TAG
214                                 # TODO create in correct namespace
215                                 c.el = parent.ownerDocument.createElement c.name
216                                 for k, v of c.attrs
217                                         # FIXME if attr_whitelist[k]?
218                                         c.el.setAttribute k, v
219                                 parent.appendChild c.el
220                                 if c.children.length
221                                         instantiate_tree c.children, c.el
222
223 traverse_tree = (tree, state, cb) ->
224         for c in tree
225                 cb c, state
226                 break if state.done?
227                 if c.children.length
228                         traverse_tree c.children, state, cb
229                         break if state.done?
230         return state
231 # find the next element in tree (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
235                 return [n, i + 1]
236         found = traverse_tree tree, before: n?, (node, state) ->
237                 if node.type is TYPE_TEXT and state.before is false
238                         state.node = node
239                         state.done = true
240                 if node is n
241                         state.before = false
242         if found.node?
243                 return [found.node, 0]
244         return null
245
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
249                 return [n, i - 1]
250         found = traverse_tree tree, before: n?, (node, state) ->
251                 if node.type is TYPE_TEXT
252                         unless n?
253                                 state.node = node
254                                 state.done = true
255                         if node is n
256                                 if state.prev?
257                                         state.node = state.prev
258                                 state.done = true
259                         if node
260                                 state.prev = node
261         if found.node?
262                 return [found.node, found.node.text.length]
263         return null
264
265 find_loc_cursor_position = (tree, loc) ->
266         for c in tree
267                 if c.type is TYPE_TAG or c.type is TYPE_TEXT
268                         bounds = get_el_bounds c.el
269                         continue if loc.x < bounds.x
270                         continue if loc.x > bounds.x + bounds.w
271                         continue if loc.y < bounds.y
272                         continue if loc.y > bounds.y + bounds.h
273                         if c.type is TYPE_TEXT
274                                 # click is within bounding box that contains all text.
275                                 return [c, 0] if c.text.length is 0
276                                 before_i = 0
277                                 before = cursor_to_xyh c, before_i
278                                 after_i = c.text.length
279                                 after = cursor_to_xyh c, after_i
280                                 if loc.y < before.y + before.h and loc.x < before.x
281                                         continue # before first char on first line
282                                 if loc.y > after.y and loc.x > after.x
283                                         continue # after last char on last line
284                                 while after_i - before_i > 1
285                                         cur_i = Math.round((before_i + after_i) / 2)
286                                         cur = cursor_to_xyh c, cur_i
287                                         if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
288                                                 after_i = cur_i
289                                                 after = cur
290                                         else
291                                                 before_i = cur_i
292                                                 before = cur
293                                 # which one is closest?
294                                 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
295                                         return [c, before_i]
296                                 else
297                                         return [c, after_i]
298                         if c.children.length
299                                 ret = find_loc_cursor_position c.children, loc
300                                 return ret if ret?
301         return null
302
303 class PeachHTML5Editor
304         constructor: (in_el, options = {}) ->
305                 @in_el = in_el
306                 @tree = []
307                 @iframe = domify iframe: class: 'peach_html5_editor'
308                 @cursor = null
309                 @cursor_el = null
310                 @cursor_visible = false
311                 opt_fragment = options.fragment ? true
312                 @parser_opts = {}
313                 if opt_fragment
314                         @parser_opts.fragment = 'body'
315
316                 @iframe.onload = =>
317                         @idoc = @iframe.contentDocument
318
319                         ignore_key_codes =
320                                 '18': true # alt
321                                 '20': true # capslock
322                                 '17': true # ctrl
323                                 '144': true # numlock
324                                 '16': true # shift
325                                 '91': true # windows "start" key
326                         control_key_codes = # we react to these, but they aren't typing
327                                 '37': KEY_LEFT
328                                 '38': KEY_UP
329                                 '39': KEY_RIGHT
330                                 '40': KEY_DOWN
331                                 '35': KEY_END
332                                 '8':  KEY_BACKSPACE
333                                 '46': KEY_DELETE
334                                 '13': KEY_ENTER
335                                 '27': KEY_ESCAPE
336                                 '36': KEY_HOME
337                                 '45': KEY_INSERT
338                                 '33': KEY_PAGE_UP
339                                 '34': KEY_PAGE_DOWN
340                                 '9':  KEY_TAB
341
342                         @idoc.body.onclick = (e) =>
343                                 # idoc.body.offset().left/top
344                                 new_cursor = find_loc_cursor_position @tree, x: e.pageX, y: e.pageY
345                                 if new_cursor?
346                                         @move_cursor new_cursor
347                         @idoc.body.onkeyup = (e) =>
348                                 return if e.ctrlKey
349                                 return false if ignore_key_codes[e.keyCode]?
350                                 #return false if control_key_codes[e.keyCode]?
351                         @idoc.body.onkeydown = (e) =>
352                                 return if e.ctrlKey
353                                 return false if ignore_key_codes[e.keyCode]?
354                                 #return false if control_key_codes[e.keyCode]?
355                                 switch e.keyCode
356                                         when KEY_LEFT
357                                                 if @cursor?
358                                                         new_cursor = find_prev_cursor_position @tree, @cursor...
359                                                         if new_cursor?
360                                                                 @move_cursor new_cursor
361                                                 else
362                                                         for c in @tree
363                                                                 new_cursor = find_next_cursor_position @tree, c, -1
364                                                                 if new_cursor?
365                                                                         @move_cursor new_cursor
366                                                                         break
367                                                 return false
368                                         when KEY_UP
369                                                 return false
370                                         when KEY_RIGHT
371                                                 if @cursor?
372                                                         new_cursor = find_next_cursor_position @tree, @cursor...
373                                                         if new_cursor?
374                                                                 @move_cursor new_cursor
375                                                 else
376                                                         for c in @tree
377                                                                 new_cursor = find_prev_cursor_position @tree, c, -1
378                                                                 if new_cursor?
379                                                                         @move_cursor new_cursor
380                                                                         break
381                                                 return false
382                                         when KEY_DOWN
383                                                 return false
384                                         when KEY_END
385                                                 return false
386                                         when KEY_BACKSPACE
387                                                 return false
388                                         when KEY_DELETE
389                                                 return false
390                                         when KEY_ENTER
391                                                 return false
392                                         when KEY_ESCAPE
393                                                 return false
394                                         when KEY_HOME
395                                                 return false
396                                         when KEY_INSERT
397                                                 return false
398                                         when KEY_PAGE_UP
399                                                 return false
400                                         when KEY_PAGE_DOWN
401                                                 return false
402                                         when KEY_TAB
403                                                 return false
404                         @idoc.body.onkeypress = (e) =>
405                                 return if e.ctrlKey
406                                 return false if ignore_key_codes[e.keyCode]?
407                                 return false if control_key_codes[e.keyCode]? # handled in keydown
408                                 char = e.charCode ? e.keyCode
409                                 if char and @cursor?
410                                         char = String.fromCharCode char
411                                         if @cursor[1] is 0
412                                                 @cursor[0].text = char + @cursor[0].text
413                                         else if @cursor[1] is @cursor[0].text.length - 1
414                                                 @cursor[0].text += char
415                                         else
416                                                 @cursor[0].text =
417                                                         @cursor[0].text.substr(0, @cursor[1]) +
418                                                         char +
419                                                         @cursor[0].text.substr(@cursor[1])
420                                         @cursor[0].el.nodeValue = @cursor[0].text
421                                         @move_cursor [@cursor[0], @cursor[1] + 1]
422                                 return false
423                         if options.stylesheet # TODO test this
424                                 istyle = @idoc.createElement 'style'
425                                 istyle.setAttribute 'src', options.stylesheet
426                                 @idoc.head.appendChild istyle
427                         icss = @idoc.createElement 'style'
428                         icss.appendChild @idoc.createTextNode css
429                         @idoc.head.appendChild icss
430                         @load_html @in_el.value
431
432                 @in_el.parentNode.appendChild @iframe
433         clear_dom: ->
434                 # FIXME add parent node, so we don't empty body and delete cursor_el
435                 while @idoc.body.childNodes.length
436                         @idoc.body.removeChild @idoc.body.childNodes[0]
437                 @cursor_visible = false
438                 return
439         load_html: (html) ->
440                 @tree = peach_parser.parse html, @parser_opts
441                 #as_html = dom_to_html @tree
442                 #@iframe.contentDocument.body.innerHTML = as_html
443                 @clear_dom()
444                 instantiate_tree @tree, @idoc.body
445         move_cursor: (cursor) ->
446                 return if @cursor? and cursor? and @cursor[0] is cursor[0] and @cursor[1] is cursor[1]
447                 @cursor = cursor
448                 # replace cursor, to reset blink animation
449                 if @cursor_visible
450                         @cursor_el.parentNode.removeChild @cursor_el
451                 @cursor_el = domify div: id: 'peach_html5_editor_cursor'
452                 @idoc.body.appendChild @cursor_el
453                 @cursor_visible = true
454                 # TODO figure out x,y coords for cursor
455                 loc = cursor_to_xyh cursor[0], cursor[1]
456                 @cursor_el.style.left = "#{loc.x}px"
457                 @cursor_el.style.top = "#{loc.y}px"
458
459 window.peach_html5_editor = (args...) ->
460         return new PeachHTML5Editor args...
461
462 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])