JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
editor cursor starting (barely) towork
[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"
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 find_next_cursor_position = (n, i) ->
193         if n.type is TYPE_TEXT
194                 if n.text.length > i
195                         return [n, i + 1]
196                 return null
197         if n.type is TYPE_TAG
198                 if n.children.length
199                         for c in n.children
200                                 ret = find_next_cursor_position c, -1
201                                 return ret if ret?
202                         return null
203                 else
204                         # FIXME create an empty text node if needed depending on tag name
205         return null
206
207 class PeachHTML5Editor
208         constructor: (in_el, options = {}) ->
209                 @in_el = in_el
210                 @tree = []
211                 @iframe = document.createElement('iframe')
212                 @cursor = null
213                 @cursor_el = null
214                 @cursor_visible = false
215                 opt_fragment = options.fragment ? true
216                 @parser_opts = {}
217                 if opt_fragment
218                         @parser_opts.fragment = 'body'
219                 @in_el.parentNode.appendChild @iframe
220                 @idoc = @iframe.contentDocument
221
222                 ignore_key_codes =
223                         '18': true # alt
224                         '20': true # capslock
225                         '17': true # ctrl
226                         '144': true # numlock
227                         '16': true # shift
228                         '91': true # windows "start" key
229                 control_key_codes = # we react to these, but they aren't typing
230                         '37': KEY_LEFT
231                         '38': KEY_UP
232                         '39': KEY_RIGHT
233                         '40': KEY_DOWN
234                         '35': KEY_END
235                         '8':  KEY_BACKSPACE
236                         '46': KEY_DELETE
237                         '13': KEY_ENTER
238                         '27': KEY_ESCAPE
239                         '36': KEY_HOME
240                         '45': KEY_INSERT
241                         '33': KEY_PAGE_UP
242                         '34': KEY_PAGE_DOWN
243                         '9':  KEY_TAB
244
245                 @idoc.body.onkeyup = (e) =>
246                         return if e.ctrlKey
247                         return false if ignore_key_codes[e.keyCode]?
248                         #return false if control_key_codes[e.keyCode]?
249                 @idoc.body.onkeydown = (e) =>
250                         return if e.ctrlKey
251                         return false if ignore_key_codes[e.keyCode]?
252                         #return false if control_key_codes[e.keyCode]?
253                         switch e.keyCode
254                                 when KEY_LEFT
255                                         return false
256                                 when KEY_UP
257                                         return false
258                                 when KEY_RIGHT
259                                         window.ce = @cursor_el
260                                         if @cursor?
261                                                 new_cursor = find_next_cursor_position @cursor...
262                                                 if new_cursor?
263                                                         @move_cursor new_cursor
264                                                 else
265                                                         after = false
266                                                         for c in @cursor[0].parent.children
267                                                                 if after
268                                                                         new_cursor = find_next_cursor_position c, -1
269                                                                         if new_cursor?
270                                                                                 @move_cursor new_cursor
271                                                                                 break
272                                                                 if c is @cursor[0]
273                                                                         after = true
274                                         else
275                                                 for c in @tree
276                                                         new_cursor = find_next_cursor_position c, -1
277                                                         if new_cursor?
278                                                                 @move_cursor new_cursor
279                                                                 break
280                                         return false
281                                 when KEY_DOWN
282                                         return false
283                                 when KEY_END
284                                         return false
285                                 when KEY_BACKSPACE
286                                         return false
287                                 when KEY_DELETE
288                                         return false
289                                 when KEY_ENTER
290                                         return false
291                                 when KEY_ESCAPE
292                                         return false
293                                 when KEY_HOME
294                                         return false
295                                 when KEY_INSERT
296                                         return false
297                                 when KEY_PAGE_UP
298                                         return false
299                                 when KEY_PAGE_DOWN
300                                         return false
301                                 when KEY_TAB
302                                         return false
303                 @idoc.body.onkeypress = (e) =>
304                         return if e.ctrlKey
305                         return false if ignore_key_codes[e.keyCode]?
306                         # in firefox, keyCode is only set for non-typing keys
307                         switch e.keyCode
308                                 when KEY_LEFT
309                                         return false
310                                 when KEY_UP
311                                         return false
312                                 when KEY_RIGHT
313                                         console.log "hi"
314                                         console.log @cursor
315                                         if @cursor?
316                                                 new_cursor = find_next_cursor_position @cursor...
317                                                 if new_cursor?
318                                                         @move_cursor new_cursor
319                                                 else
320                                                         after = false
321                                                         for c in @cursor[0].parent.children
322                                                                 if after
323                                                                         new_cursor = find_next_cursor_position c, -1
324                                                                         if new_cursor?
325                                                                                 @move_cursor new_cursor
326                                                                                 break
327                                                                 if c is @cursor[0]
328                                                                         after = true
329                                         else
330                                                 for c in @tree
331                                                         new_cursor = find_next_cursor_position c, -1
332                                                         if new_cursor?
333                                                                 @move_cursor new_cursor
334                                                                 break
335                                         return false
336                                 when KEY_DOWN
337                                         return false
338                                 when KEY_END
339                                         return false
340                                 when KEY_BACKSPACE
341                                         return false
342                                 when KEY_DELETE
343                                         return false
344                                 when KEY_ENTER
345                                         return false
346                                 when KEY_ESCAPE
347                                         return false
348                                 when KEY_HOME
349                                         return false
350                                 when KEY_INSERT
351                                         return false
352                                 when KEY_PAGE_UP
353                                         return false
354                                 when KEY_PAGE_DOWN
355                                         return false
356                                 when KEY_TAB
357                                         return false
358                         char = e.charCode ? e.keyCode
359                         @in_el.value += String.fromCharCode char
360                         @load_html @in_el.value
361                         return false
362                 if options.stylesheet # TODO test this
363                         istyle = @idoc.createElement 'style'
364                         istyle.setAttribute 'src', options.stylesheet
365                         @idoc.head.appendChild istyle
366                 icss = @idoc.createElement 'style'
367                 icss.appendChild @idoc.createTextNode css
368                 @idoc.head.appendChild icss
369                 @load_html @in_el.value
370         clear_dom: ->
371                 # FIXME add parent node, so we don't empty body and delete cursor_el
372                 while @idoc.body.childNodes.length
373                         @idoc.body.removeChild @idoc.body.childNodes[0]
374                 @cursor_visible = false
375                 return
376         load_html: (html) ->
377                 @tree = peach_parser.parse html, @parser_opts
378                 #as_html = dom_to_html @tree
379                 #@iframe.contentDocument.body.innerHTML = as_html
380                 @clear_dom()
381                 instantiate_tree @tree, @idoc.body
382         move_cursor: (cursor) ->
383                 @cursor = cursor
384                 unless @cursor_el?
385                         @cursor_el = domify div: id: 'peach_html5_editor_cursor'
386                 unless @cursor_visible
387                         @idoc.body.appendChild @cursor_el
388                         @cursor_visible = true
389                 # TODO figure out top/left coords for cursor
390                 loc = cursor_to_loc cursor[0], cursor[1]
391                 @cursor_el.style.top = "#{loc.top}px"
392                 @cursor_el.style.left = "#{loc.left}px"
393
394 window.peach_html5_editor = (args...) ->
395         return new PeachHTML5Editor args...
396
397 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])