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