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