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