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