JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
determine text/character position with range api
[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 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)
27
28 # text nodes don't have getBoundingClientRect(), so use selection api to find
29 # it.
30 get_text_bounding_rect = (el) ->
31 get_el_bounds = (el) ->
32         if el.getBoundingClientRect?
33                 rect = el.getBoundingClientRect()
34         else
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
43         return {
44                 x: rect.left + x_fix
45                 y: rect.top + y_fix
46                 w: rect.width ? (rect.right - rect.left)
47                 h: rect.height ? (rect.top - rect.bottom)
48         }
49
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()
54         plus_width = false
55         if n.text.length is 0
56                 range.setStart n.el, i
57                 range.setEnd n.el, i
58         if i is n.text.length
59                 range.setStart n.el, i - 1
60                 range.setEnd n.el, i
61                 plus_width = true
62         else
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()
67         if rect.length > 0
68                 if plus_width
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]
72                 else
73                         rect = rect[0]
74         else
75                 return x: 0, y: 0, w: 0, h: 0 # TODO return null, fix callers
76         ret = {
77                 x: rect.left
78                 y: rect.top
79                 w: rect.width ? (rect.right - rect.left)
80                 h: rect.height ? (rect.top - rect.bottom)
81         }
82         if plus_width
83                 ret.x += ret.w
84         debug_dot_at n.el.ownerDocument, ret.x, ret.y
85         return ret
86
87 # encode text so it can be safely placed inside an html attribute
88 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
89 enc_attr = (txt) ->
90         return txt.replace enc_attr_regex, (match, amp, quote) ->
91                 return '&amp;' if (amp)
92                 return '&quot;' if (quote)
93                 return '&nbsp;'
94
95 void_elements = {
96         area: true
97         base: true
98         br: true
99         col: true
100         embed: true
101         hr: true
102         img: true
103         input: true
104         keygen: true
105         link: true
106         meta: true
107         param: true
108         source: true
109         track: true
110         wbr: true
111 }
112 dom_to_html = (dom) ->
113         ret = ''
114         for el in dom
115                 switch el.type
116                         when TYPE_TAG
117                                 ret += '<' + el.name
118                                 attr_keys = []
119                                 for k of el.attrs
120                                         attr_keys.unshift k
121                                 #attr_keys.sort()
122                                 for k in attr_keys
123                                         ret += " #{k}"
124                                         if el.attrs[k].length > 0
125                                                 ret += "=\"#{enc_attr el.attrs[k]}\""
126                                 ret += '>'
127                                 unless void_elements[el.name]
128                                         if el.children.length
129                                                 ret += dom_to_html el.children
130                                         ret += "</#{el.name}>"
131                         when TYPE_TEXT
132                                 ret += el.text
133                         when TYPE_COMMENT
134                                 ret += "<!--#{el.text}-->"
135                         when TYPE_DOCTYPE
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}\""
141                                 ret += ">\n"
142         return ret
143
144 domify = (h) ->
145         for tag, attrs of h
146                 if tag is 'text'
147                         return document.createTextNode attrs
148                 el = document.createElement tag
149                 for k, v of attrs
150                         if k is 'children'
151                                 for child in v
152                                         el.appendChild child
153                         else
154                                 el.setAttribute k, v
155         return el
156
157 css = ''
158 css += 'div#peach_html5_editor_cursor {'
159 css +=     'position: absolute;'
160 css +=     'height: 1em;'
161 css +=     'width: 2px;'
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;'
167 css += '}'
168 css += '@-webkit-keyframes blink {'
169 css +=     'to { visibility: hidden; }'
170 css += '}'
171 css += '@keyframes blink {'
172 css +=     'to { visibility: hidden; }'
173 css += '}'
174
175 # key codes:
176 KEY_LEFT = 37
177 KEY_UP = 38
178 KEY_RIGHT = 39
179 KEY_DOWN = 40
180 KEY_BACKSPACE = 8 # <--
181 KEY_DELETE = 46 # -->
182 KEY_END = 35
183 KEY_ENTER = 13
184 KEY_ESCAPE = 27
185 KEY_HOME = 36
186 KEY_INSERT = 45
187 KEY_PAGE_UP = 33
188 KEY_PAGE_DOWN = 34
189 KEY_TAB = 9
190
191 instantiate_tree = (tree, parent) ->
192         for c in tree
193                 switch c.type
194                         when TYPE_TEXT
195                                 c.el = parent.ownerDocument.createTextNode c.text
196                                 parent.appendChild c.el
197                         when TYPE_TAG
198                                 # TODO create in correct namespace
199                                 c.el = parent.ownerDocument.createElement c.name
200                                 for k, v of c.attrs
201                                         # FIXME if attr_whitelist[k]?
202                                         c.el.setAttribute k, v
203                                 parent.appendChild c.el
204                                 if c.children.length
205                                         instantiate_tree c.children, c.el
206
207 traverse_tree = (tree, state, cb) ->
208         for c in tree
209                 cb c, state
210                 break if state.done?
211                 if c.children.length
212                         traverse_tree c.children, state, cb
213                         break if state.done?
214         return state
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
223                                 return [n, next_i]
224         found = traverse_tree tree, before: n?, (node, state) ->
225                 if node.type is TYPE_TEXT and state.before is false
226                         state.node = node
227                         state.done = true
228                 if node is n
229                         state.before = false
230         if found.node?
231                 return [found.node, 0]
232         return null
233
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
241                                 return [n, prev_i]
242                 return [n, i - 1]
243         found = traverse_tree tree, before: n?, (node, state) ->
244                 if node.type is TYPE_TEXT
245                         unless n?
246                                 state.node = node
247                                 state.done = true
248                         if node is n
249                                 if state.prev?
250                                         state.node = state.prev
251                                 state.done = true
252                         if node
253                                 state.prev = node
254         if found.node?
255                 return [found.node, found.node.text.length]
256         return null
257
258 find_loc_cursor_position = (tree, loc) ->
259         for c in tree
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
266                         if c.children.length
267                                 ret = find_loc_cursor_position c.children, loc
268                                 return ret if ret?
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
272                                 before_i = 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'
278                                         continue
279                                 if loc.y > after.y and loc.x > after.x
280                                         # console.log 'after last char on last line'
281                                         continue
282                                 if loc.y < before.y
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)
292                                                 after_i = cur_i
293                                                 after = cur
294                                         else
295                                                 before_i = cur_i
296                                                 before = cur
297                                 # which one is closest?
298                                 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
299                                         return [c, before_i]
300                                 else
301                                         return [c, after_i]
302         return null
303
304 class PeachHTML5Editor
305         constructor: (in_el, options = {}) ->
306                 @in_el = in_el
307                 @tree = []
308                 @iframe = domify iframe: class: 'peach_html5_editor'
309                 @cursor = null
310                 @cursor_el = null
311                 @cursor_visible = false
312                 opt_fragment = options.fragment ? true
313                 @parser_opts = {}
314                 if opt_fragment
315                         @parser_opts.fragment = 'body'
316
317                 @iframe.onload = =>
318                         @idoc = @iframe.contentDocument
319
320                         ignore_key_codes =
321                                 '18': true # alt
322                                 '20': true # capslock
323                                 '17': true # ctrl
324                                 '144': true # numlock
325                                 '16': true # shift
326                                 '91': true # windows "start" key
327                         control_key_codes = # we react to these, but they aren't typing
328                                 '37': KEY_LEFT
329                                 '38': KEY_UP
330                                 '39': KEY_RIGHT
331                                 '40': KEY_DOWN
332                                 '35': KEY_END
333                                 '8':  KEY_BACKSPACE
334                                 '46': KEY_DELETE
335                                 '13': KEY_ENTER
336                                 '27': KEY_ESCAPE
337                                 '36': KEY_HOME
338                                 '45': KEY_INSERT
339                                 '33': KEY_PAGE_UP
340                                 '34': KEY_PAGE_DOWN
341                                 '9':  KEY_TAB
342
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
346                                 if new_cursor?
347                                         @move_cursor new_cursor
348                         @idoc.body.onkeyup = (e) =>
349                                 return if e.ctrlKey
350                                 return false if ignore_key_codes[e.keyCode]?
351                                 #return false if control_key_codes[e.keyCode]?
352                         @idoc.body.onkeydown = (e) =>
353                                 return if e.ctrlKey
354                                 return false if ignore_key_codes[e.keyCode]?
355                                 #return false if control_key_codes[e.keyCode]?
356                                 switch e.keyCode
357                                         when KEY_LEFT
358                                                 if @cursor?
359                                                         new_cursor = find_prev_cursor_position @tree, @cursor...
360                                                         if new_cursor?
361                                                                 @move_cursor new_cursor
362                                                 else
363                                                         for c in @tree
364                                                                 new_cursor = find_next_cursor_position @tree, c, -1
365                                                                 if new_cursor?
366                                                                         @move_cursor new_cursor
367                                                                         break
368                                                 return false
369                                         when KEY_UP
370                                                 return false
371                                         when KEY_RIGHT
372                                                 if @cursor?
373                                                         new_cursor = find_next_cursor_position @tree, @cursor...
374                                                         if new_cursor?
375                                                                 @move_cursor new_cursor
376                                                 else
377                                                         for c in @tree
378                                                                 new_cursor = find_prev_cursor_position @tree, c, -1
379                                                                 if new_cursor?
380                                                                         @move_cursor new_cursor
381                                                                         break
382                                                 return false
383                                         when KEY_DOWN
384                                                 return false
385                                         when KEY_END
386                                                 return false
387                                         when KEY_BACKSPACE
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]
393                                                 return false
394                                         when KEY_DELETE
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]]
400                                                 return false
401                                         when KEY_ENTER
402                                                 return false
403                                         when KEY_ESCAPE
404                                                 return false
405                                         when KEY_HOME
406                                                 return false
407                                         when KEY_INSERT
408                                                 return false
409                                         when KEY_PAGE_UP
410                                                 return false
411                                         when KEY_PAGE_DOWN
412                                                 return false
413                                         when KEY_TAB
414                                                 return false
415                         @idoc.body.onkeypress = (e) =>
416                                 return if e.ctrlKey
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
420                                 if char and @cursor?
421                                         char = String.fromCharCode char
422                                         if @cursor[1] is 0
423                                                 @cursor[0].text = char + @cursor[0].text
424                                         else if @cursor[1] is @cursor[0].text.length - 1
425                                                 @cursor[0].text += char
426                                         else
427                                                 @cursor[0].text =
428                                                         @cursor[0].text.substr(0, @cursor[1]) +
429                                                         char +
430                                                         @cursor[0].text.substr(@cursor[1])
431                                         @cursor[0].el.nodeValue = @cursor[0].text
432                                         @move_cursor [@cursor[0], @cursor[1] + 1]
433                                 return false
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
442
443                 @in_el.parentNode.appendChild @iframe
444         clear_dom: ->
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
449                 return
450         load_html: (html) ->
451                 @tree = peach_parser.parse html, @parser_opts
452                 #as_html = dom_to_html @tree
453                 #@iframe.contentDocument.body.innerHTML = as_html
454                 @clear_dom()
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
459                 @cursor = cursor
460                 # replace cursor, to reset blink animation
461                 if @cursor_visible
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"
469
470 window.peach_html5_editor = (args...) ->
471         return new PeachHTML5Editor args...
472
473 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])