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