JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
use {x,y} instead of {left,top}
[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_loc = (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
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_loc n, 0
96                 if ret.x <= first.x
97                         # no need for a loop here, because recursion
98                         ret = cursor_to_loc 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         console.log tree, loc
267         for c in tree
268                 if c.type is TYPE_TAG or c.type is TYPE_TEXT
269                         bounds = get_el_bounds c.el
270                         console.log bounds
271                         continue if loc.x < bounds.x
272                         continue if loc.x > bounds.x + bounds.w
273                         continue if loc.y < bounds.y
274                         continue if loc.y > bounds.y + bounds.h
275                         if c.type is TYPE_TEXT
276                                 # click is within bounding box that contains all text.
277                                 return [c, 0] if c.text.length is 0
278                                 #if c.text.length is 1
279                                         # definitely no linebreak in it
280                                         #if loc
281                                 #
282                                 # for inline elements, this can include text in other tags on
283                                 # the first or last lines.
284                                 #
285                                 # they clicked on text. now determine where in the text
286                                 tries = {}
287                                 cur = Math.floor(c.text.length / 2)
288                                 #loop
289                                 #       xy = tries[cur] = cursor_to_loc c, cur
290                                 return [c, cur]
291                         if c.children.length
292                                 console.log "in"
293                                 ret = find_loc_cursor_position c.children, loc
294                                 console.log 'found', ret if ret?
295                                 return ret if ret?
296         return null
297
298 class PeachHTML5Editor
299         constructor: (in_el, options = {}) ->
300                 @in_el = in_el
301                 @tree = []
302                 @iframe = domify iframe: class: 'peach_html5_editor'
303                 @cursor = null
304                 @cursor_el = null
305                 @cursor_visible = false
306                 opt_fragment = options.fragment ? true
307                 @parser_opts = {}
308                 if opt_fragment
309                         @parser_opts.fragment = 'body'
310
311                 @iframe.onload = =>
312                         @idoc = @iframe.contentDocument
313
314                         ignore_key_codes =
315                                 '18': true # alt
316                                 '20': true # capslock
317                                 '17': true # ctrl
318                                 '144': true # numlock
319                                 '16': true # shift
320                                 '91': true # windows "start" key
321                         control_key_codes = # we react to these, but they aren't typing
322                                 '37': KEY_LEFT
323                                 '38': KEY_UP
324                                 '39': KEY_RIGHT
325                                 '40': KEY_DOWN
326                                 '35': KEY_END
327                                 '8':  KEY_BACKSPACE
328                                 '46': KEY_DELETE
329                                 '13': KEY_ENTER
330                                 '27': KEY_ESCAPE
331                                 '36': KEY_HOME
332                                 '45': KEY_INSERT
333                                 '33': KEY_PAGE_UP
334                                 '34': KEY_PAGE_DOWN
335                                 '9':  KEY_TAB
336
337                         @idoc.body.onclick = (e) =>
338                                 # idoc.body.offset().left/top
339                                 new_cursor = find_loc_cursor_position @tree, x: e.pageX, y: e.pageY
340                                 if new_cursor?
341                                         @move_cursor new_cursor
342                         @idoc.body.onkeyup = (e) =>
343                                 return if e.ctrlKey
344                                 return false if ignore_key_codes[e.keyCode]?
345                                 #return false if control_key_codes[e.keyCode]?
346                         @idoc.body.onkeydown = (e) =>
347                                 return if e.ctrlKey
348                                 return false if ignore_key_codes[e.keyCode]?
349                                 #return false if control_key_codes[e.keyCode]?
350                                 switch e.keyCode
351                                         when KEY_LEFT
352                                                 if @cursor?
353                                                         new_cursor = find_prev_cursor_position @tree, @cursor...
354                                                         if new_cursor?
355                                                                 @move_cursor new_cursor
356                                                 else
357                                                         for c in @tree
358                                                                 new_cursor = find_next_cursor_position @tree, c, -1
359                                                                 if new_cursor?
360                                                                         @move_cursor new_cursor
361                                                                         break
362                                                 return false
363                                         when KEY_UP
364                                                 return false
365                                         when KEY_RIGHT
366                                                 if @cursor?
367                                                         new_cursor = find_next_cursor_position @tree, @cursor...
368                                                         if new_cursor?
369                                                                 @move_cursor new_cursor
370                                                 else
371                                                         for c in @tree
372                                                                 new_cursor = find_prev_cursor_position @tree, c, -1
373                                                                 if new_cursor?
374                                                                         @move_cursor new_cursor
375                                                                         break
376                                                 return false
377                                         when KEY_DOWN
378                                                 return false
379                                         when KEY_END
380                                                 return false
381                                         when KEY_BACKSPACE
382                                                 return false
383                                         when KEY_DELETE
384                                                 return false
385                                         when KEY_ENTER
386                                                 return false
387                                         when KEY_ESCAPE
388                                                 return false
389                                         when KEY_HOME
390                                                 return false
391                                         when KEY_INSERT
392                                                 return false
393                                         when KEY_PAGE_UP
394                                                 return false
395                                         when KEY_PAGE_DOWN
396                                                 return false
397                                         when KEY_TAB
398                                                 return false
399                         @idoc.body.onkeypress = (e) =>
400                                 return if e.ctrlKey
401                                 return false if ignore_key_codes[e.keyCode]?
402                                 return false if control_key_codes[e.keyCode]? # handled in keydown
403                                 char = e.charCode ? e.keyCode
404                                 if char and @cursor?
405                                         char = String.fromCharCode char
406                                         if @cursor[1] is 0
407                                                 @cursor[0].text = char + @cursor[0].text
408                                         else if @cursor[1] is @cursor[0].text.length - 1
409                                                 @cursor[0].text += char
410                                         else
411                                                 @cursor[0].text =
412                                                         @cursor[0].text.substr(0, @cursor[1]) +
413                                                         char +
414                                                         @cursor[0].text.substr(@cursor[1])
415                                         @cursor[0].el.nodeValue = @cursor[0].text
416                                         @move_cursor [@cursor[0], @cursor[1] + 1]
417                                 return false
418                         if options.stylesheet # TODO test this
419                                 istyle = @idoc.createElement 'style'
420                                 istyle.setAttribute 'src', options.stylesheet
421                                 @idoc.head.appendChild istyle
422                         icss = @idoc.createElement 'style'
423                         icss.appendChild @idoc.createTextNode css
424                         @idoc.head.appendChild icss
425                         @load_html @in_el.value
426
427                 @in_el.parentNode.appendChild @iframe
428         clear_dom: ->
429                 # FIXME add parent node, so we don't empty body and delete cursor_el
430                 while @idoc.body.childNodes.length
431                         @idoc.body.removeChild @idoc.body.childNodes[0]
432                 @cursor_visible = false
433                 return
434         load_html: (html) ->
435                 @tree = peach_parser.parse html, @parser_opts
436                 #as_html = dom_to_html @tree
437                 #@iframe.contentDocument.body.innerHTML = as_html
438                 @clear_dom()
439                 instantiate_tree @tree, @idoc.body
440         move_cursor: (cursor) ->
441                 return if @cursor? and cursor? and @cursor[0] is cursor[0] and @cursor[1] is cursor[1]
442                 @cursor = cursor
443                 # replace cursor, to reset blink animation
444                 if @cursor_visible
445                         @cursor_el.parentNode.removeChild @cursor_el
446                 @cursor_el = domify div: id: 'peach_html5_editor_cursor'
447                 @idoc.body.appendChild @cursor_el
448                 @cursor_visible = true
449                 # TODO figure out x,y coords for cursor
450                 loc = cursor_to_loc cursor[0], cursor[1]
451                 @cursor_el.style.left = "#{loc.x}px"
452                 @cursor_el.style.top = "#{loc.y}px"
453
454 window.peach_html5_editor = (args...) ->
455         return new PeachHTML5Editor args...
456
457 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])