JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
check for visibility:hidden/collapsed too
[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 # SETTINGS
18 overlay_padding = 10
19
20 timeout = (ms, cb) -> return setTimeout cb, ms
21 next_frame = (cb) ->
22         if (window.requestAnimationFrame?)
23                 window.requestAnimationFrame cb
24         else
25                 timeout 16, cb
26
27 # xml 1.0 spec, chromium and firefox accept these, plus lots of unicode chars
28 valid_attr_regex = new RegExp '^[a-zA-Z_:][-a-zA-Z0-9_:.]*$'
29 # html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
30 js_attr_regex = new RegExp '^[oO][nN].'
31
32 debug_dot_at = (doc, x, y) ->
33         return # disabled
34         el = doc.createElement 'div'
35         el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
36         doc.body.appendChild el
37         #console.log(new Error().stack)
38
39 # text nodes don't have getBoundingClientRect(), so use selection api to find
40 # it.
41 get_el_bounds = (el) ->
42         if el.getBoundingClientRect?
43                 rect = el.getBoundingClientRect()
44         else
45                 # text nodes don't have getBoundingClientRect(), so use range api
46                 range = el.ownerDocument.createRange()
47                 range.selectNodeContents el
48                 rect = range.getBoundingClientRect()
49         doc = el.ownerDocument.documentElement
50         win = el.ownerDocument.defaultView
51         y_fix = win.pageYOffset - doc.clientTop
52         x_fix = win.pageXOffset - doc.clientLeft
53         return {
54                 x: rect.left + x_fix
55                 y: rect.top + y_fix
56                 w: rect.width ? (rect.right - rect.left)
57                 h: rect.height ? (rect.top - rect.bottom)
58         }
59
60 is_display_block = (el) ->
61         if el.currentStyle?
62                 return el.currentStyle.display is 'block'
63         else
64                 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
65
66 # Pass return value from dom event handlers to this.
67 # If they return false, this will addinionally stop propagation and default.
68 event_return = (e, bool) ->
69         if bool is false
70                 if e.stopPropagation?
71                         e.stopPropagation()
72                 if e.preventDefault?
73                         e.preventDefault()
74         return bool
75 # Warning: currently assumes you're asking about a single character
76 # Note: chromium returns multiple bounding rects for a space at a line-break
77 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
78 # Note: sometimes returns null (eg for whitespace that is not visible)
79 text_range_bounds = (el, start, end) ->
80         range = document.createRange()
81         range.setStart el, start
82         range.setEnd el, end
83         rects = range.getClientRects()
84         if rects.length > 0
85                 rect = rects[0]
86         else
87                 return null
88         doc = el.ownerDocument.documentElement
89         win = el.ownerDocument.defaultView
90         y_fix = win.pageYOffset - doc.clientTop
91         x_fix = win.pageXOffset - doc.clientLeft
92         return {
93                 x: rect.left + x_fix
94                 y: rect.top + y_fix
95                 w: rect.width ? (rect.right - rect.left)
96                 h: rect.height ? (rect.top - rect.bottom)
97                 rects: rects
98                 bounding: range.getBoundingClientRect()
99         }
100
101 # figure out the x/y coordinates of where the cursor should be if it's at
102 # position ``i`` within text node ``n``
103 # sometimes returns null (eg for whitespace that is not visible)
104 window.cursor_to_xyh = cursor_to_xyh = (n, i) ->
105         range = document.createRange()
106         if n.text.length is 0
107                 ret = text_range_bounds n.el, 0, 0
108         else if i is n.text.length
109                 ret = text_range_bounds n.el, i - 1, i
110                 if ret?
111                         ret.x += ret.w
112         else
113                 ret = text_range_bounds n.el, i, i + 1
114         if ret?
115                 debug_dot_at n.el.ownerDocument, ret.x, ret.y
116         return ret
117
118 # encode text so it can be safely placed inside an html attribute
119 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
120 enc_attr = (txt) ->
121         return txt.replace enc_attr_regex, (match, amp, quote) ->
122                 return '&amp;' if (amp)
123                 return '&quot;' if (quote)
124                 return '&nbsp;'
125 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
126 enc_text = (txt) ->
127         return txt.replace enc_text_regex, (match, amp, lt) ->
128                 return '&amp;' if (amp)
129                 return '&lt;' if (lt)
130                 return '&nbsp;'
131
132 void_elements = {
133         area: true
134         base: true
135         br: true
136         col: true
137         embed: true
138         hr: true
139         img: true
140         input: true
141         keygen: true
142         link: true
143         meta: true
144         param: true
145         source: true
146         track: true
147         wbr: true
148 }
149 # TODO make these always pretty-print (on the inside) like blocks
150 no_text_elements = { # these elements never contain text
151         select: true
152         table: true
153         tr: true
154         thead: true
155         tbody: true
156         ul: true
157         ol: true
158 }
159
160 domify = (doc, hash) ->
161         for tag, attrs of hash
162                 if tag is 'text'
163                         return document.createTextNode attrs
164                 el = document.createElement tag
165                 for k, v of attrs
166                         if k is 'children'
167                                 for child in v
168                                         el.appendChild child
169                         else
170                                 el.setAttribute k, v
171         return el
172
173 outer_css = (args) ->
174         w = args.w ? 300
175         h = args.h ? 300
176         inner_padding = args.inner_padding ? overlay_padding
177         frame_width = args.frame_width ? inner_padding
178         # TODO editor controls height...
179         occupy = (left, top = left, right = left, bottom = top) ->
180                 w -= left + right
181                 h -= top + bottom
182                 return Math.max(left, top, right, bottom)
183         ret = ''
184         ret += 'body {'
185         ret +=     'margin: 0;'
186         ret +=     'padding: 0;'
187         ret += '}'
188         ret += '#wrap1 {'
189         ret +=     "border: #{occupy 1}px solid black;"
190         ret +=     "padding: #{occupy frame_width}px;"
191         ret += '}'
192         ret += '#wrap2 {'
193         ret +=     "border: #{occupy 1}px solid black;"
194         ret +=     "padding: #{occupy inner_padding}px;"
195         ret +=     "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
196         ret +=     "width: #{w}px;"
197         ret +=     "height: #{h}px;"
198         ret +=     'overflow-x: hidden;'
199         ret +=     'overflow-y: scroll;'
200         ret += '}'
201         ret += '#wrap3 {'
202         ret +=     'position: relative;'
203         ret +=     "width: #{w}px;"
204         ret +=     "min-height: #{h}px;"
205         ret += '}'
206         ret += 'iframe {'
207         ret +=     'box-sizing: border-box;'
208         ret +=     'margin: 0;'
209         ret +=     'border: none;'
210         ret +=     'padding: 0;'
211         ret +=     "width: #{w}px;"
212         #ret +=     "height: #{h}px;" # height auto-set when content set/changed
213         ret +=     '-ms-user-select: none;'
214         ret +=     '-webkit-user-select: none;'
215         ret +=     '-moz-user-select: none;'
216         ret +=     'user-select: none;'
217         ret += '}'
218         ret += '#overlay {'
219         ret +=     'position: absolute;'
220         ret +=     "left: -#{inner_padding}px;"
221         ret +=     "top: -#{inner_padding}px;"
222         ret +=     "right: -#{inner_padding}px;"
223         ret +=     "bottom: -#{inner_padding}px;"
224         ret +=     'overflow: hidden;'
225         ret += '}'
226         ret += '.lightbox {'
227         ret +=     'position: absolute;'
228         ret +=     'background: rgba(100,100,100,0.2);'
229         ret += '}'
230         ret += '#cursor {'
231         ret +=     'position: absolute;'
232         ret +=     'height: 1em;' # FIXME adjust for hight of text
233         ret +=     'width: 2px;'
234         ret +=     'background: #444;'
235         ret +=     '-webkit-animation: blink 1s steps(2, start) infinite;'
236         ret +=     'animation: blink 1s steps(2, start) infinite;'
237         ret += '}'
238         ret += '@-webkit-keyframes blink {'
239         ret +=     'to { visibility: hidden; }'
240         ret += '}'
241         ret += '@keyframes blink {'
242         ret +=     'to { visibility: hidden; }'
243         ret += '}'
244         ret += '.ann_box {'
245         ret +=     'z-index: 5;'
246         ret +=     'position: absolute;'
247         ret +=     'border: 1px solid rgba(0,0,0,0.1);'
248         ret +=     'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
249         ret += '}'
250         ret += '.ann_tag {'
251         ret +=     'z-index: 10;'
252         ret +=     'position: absolute;'
253         ret +=     'font-size: 8px;'
254         ret +=     'white-space: pre;'
255         ret +=     'background: rgba(255,255,255,0.4);'
256         ret +=     '-ms-user-select: none;'
257         ret +=     '-webkit-user-select: none;'
258         ret +=     '-moz-user-select: none;'
259         ret +=     'user-select: none;'
260         ret += '}'
261         return ret
262
263
264 ignore_key_codes =
265         '18': true # alt
266         '20': true # capslock
267         '17': true # ctrl
268         '144': true # numlock
269         '16': true # shift
270         '91': true # windows "start" key
271 # key codes: (valid on keydown, not keypress)
272 KEY_LEFT = 37
273 KEY_UP = 38
274 KEY_RIGHT = 39
275 KEY_DOWN = 40
276 KEY_BACKSPACE = 8 # <--
277 KEY_DELETE = 46 # -->
278 KEY_END = 35
279 KEY_ENTER = 13
280 KEY_ESCAPE = 27
281 KEY_HOME = 36
282 KEY_INSERT = 45
283 KEY_PAGE_UP = 33
284 KEY_PAGE_DOWN = 34
285 KEY_TAB = 9
286 control_key_codes = # we react to these, but they aren't typing
287         '37': KEY_LEFT
288         '38': KEY_UP
289         '39': KEY_RIGHT
290         '40': KEY_DOWN
291         '35': KEY_END
292         '8':  KEY_BACKSPACE
293         '46': KEY_DELETE
294         '13': KEY_ENTER
295         '27': KEY_ESCAPE
296         '36': KEY_HOME
297         '45': KEY_INSERT
298         '33': KEY_PAGE_UP
299         '34': KEY_PAGE_DOWN
300         '9':  KEY_TAB
301
302 instantiate_tree = (tree, parent) ->
303         remove = []
304         for c, i in tree
305                 switch c.type
306                         when 'text'
307                                 c.el = parent.ownerDocument.createTextNode c.text
308                                 parent.appendChild c.el
309                         when 'tag'
310                                 if c.name in ['script', 'object', 'iframe', 'link']
311                                         # TODO put placeholders instead
312                                         remove.unshift i
313                                         continue
314                                 # TODO create in correct namespace
315                                 c.el = parent.ownerDocument.createElement c.name
316                                 for k, v of c.attrs
317                                         # FIXME if attr_whitelist[k]?
318                                         if valid_attr_regex.test k
319                                                 unless js_attr_regex.test k
320                                                         c.el.setAttribute k, v
321                                 parent.appendChild c.el
322                                 if c.children.length
323                                         instantiate_tree c.children, c.el
324         for i in remove
325                 tree.splice i, 1
326
327 traverse_tree = (tree, cb) ->
328         done = false
329         for c in tree
330                 done = cb c
331                 return done if done
332                 if c.children.length
333                         done = traverse_tree c.children, cb
334                         return done if done
335         return done
336
337 find_next_cursor_position = (tree, n, i) ->
338         if n.type is 'text' and n.text.length > i
339                 orig_xyh = cursor_to_xyh n, i
340                 unless orig_xyh?
341                         console.log "ERROR: couldn't find xy for current cursor location"
342                         return
343                 for next_i in [i+1 .. n.text.length] # inclusive is valid (after last char)
344                         next_xyh = cursor_to_xyh n, next_i
345                         if next_xyh?
346                                 if next_xyh.x > orig_xyh.x or next_xyh.y > orig_xyh.y
347                                         return [n, next_i]
348         state_before = true
349         found = null
350         traverse_tree tree, (node, state) ->
351                 if node.type is 'text' and state_before is false
352                         if cursor_to_xyh(node, 0)?
353                                 found = node
354                                 return true
355                 if node is n
356                         state_before = false
357                 return false
358         if found?
359                 return [found, 0]
360         return null
361
362 find_prev_cursor_position = (tree, n, i) ->
363         if n? and n.type is 'text' and i > 0
364                 orig_xyh = cursor_to_xyh n, i
365                 unless orig_xyh?
366                         console.log "ERROR: couldn't find xy for current cursor location"
367                         return
368                 for prev_i in [i-1 .. 0]
369                         prev_xyh = cursor_to_xyh n, prev_i
370                         if prev_xyh?
371                                 if prev_xyh.x < orig_xyh.x or prev_xyh.y < orig_xyh.y
372                                         return [n, prev_i]
373                 return [n, i - 1]
374         found_prev = n?
375         found = null
376         traverse_tree tree, (node) ->
377                 if node.type is 'text'
378                         if node is n
379                                 if found_prev?
380                                         found = found_prev
381                                 return true
382                         found_prev = node
383                 return false
384         if found?
385                 if cursor_to_xyh found, found.text.length # text visible?
386                         return [found, found.text.length]
387                 return find_prev_cursor_position tree, found, 0
388         return null
389
390 find_loc_cursor_position = (tree, loc) ->
391         for c in tree
392                 if c.type is 'tag' or c.type is 'text'
393                         bounds = get_el_bounds c.el
394                         continue if loc.x < bounds.x
395                         continue if loc.x > bounds.x + bounds.w
396                         continue if loc.y < bounds.y
397                         continue if loc.y > bounds.y + bounds.h
398                         if c.children.length
399                                 ret = find_loc_cursor_position c.children, loc
400                                 return ret if ret?
401                         if c.type is 'text'
402                                 # click is within bounding box that contains all text.
403                                 return [c, 0] if c.text.length is 0
404                                 before_i = 0
405                                 before = cursor_to_xyh c, before_i
406                                 unless before?
407                                         console.log "error: failed to find cursor pixel location for start of", c
408                                         return
409                                 after_i = c.text.length
410                                 after = cursor_to_xyh c, after_i
411                                 unless after?
412                                         console.log "error: failed to find cursor pixel location for end of", c
413                                         return
414                                 if loc.y < before.y + before.h and loc.x < before.x
415                                         # console.log 'before first char on first line'
416                                         continue
417                                 if loc.y > after.y and loc.x > after.x
418                                         # console.log 'after last char on last line'
419                                         continue
420                                 if loc.y < before.y
421                                         console.log "Warning: click in bounding box but above first line"
422                                         continue # above first line (runaround?)
423                                 if loc.y > after.y + after.h
424                                         console.log "Warning: click in bounding box but below last line", loc.y, after.y, after.h
425                                         continue # below last line (shouldn't happen?)
426                                 while after_i - before_i > 1
427                                         cur_i = Math.round((before_i + after_i) / 2)
428                                         cur = cursor_to_xyh c, cur_i
429                                         unless loc?
430                                                 console.log "error: failed to find cursor pixel location for", c, cur_i
431                                                 return
432                                         if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
433                                                 after_i = cur_i
434                                                 after = cur
435                                         else
436                                                 before_i = cur_i
437                                                 before = cur
438                                 # which one is closest?
439                                 if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
440                                         return [c, before_i]
441                                 else
442                                         return [c, after_i]
443         return null
444
445 # browsers collapse these (html5 spec calls these "space characters")
446 is_space_code = (char_code) ->
447         switch char_code
448                 when 9, 10, 12, 13, 32
449                         return true
450         return false
451 is_space = (chr) ->
452         return is_space_code chr.charCodeAt 0
453
454 tree_remove_empty_text_nodes = (tree) ->
455         empties = []
456         traverse_tree tree, (n) ->
457                 if n.type is 'text'
458                         if n.text.length is 0
459                                 empties.unshift n
460                 return false
461         for n in empties
462                 # don't completely empty the tree
463                 if tree.length is 1
464                         if tree[0].type is 'text'
465                                 console.log "oop, leaving a blank node because it's the only thing"
466                                 return
467                 n.el.parentNode.removeChild n.el
468                 for c, i in n.parent.children
469                         if c is n
470                                 n.parent.children.splice i, 1
471                                 break
472
473 # pass a array of nodes (from parser library, ie it should have .el and .text)
474 tree_dedup_space = (tree) ->
475         prev = cur = next = null
476         prev_i = cur_i = next_i = 0
477         prev_pos = pos = next_pos = null
478         prev_px = cur_px = next_px = null
479         first = true
480         removed_char = null
481
482         tree_remove_empty_text_nodes(tree)
483
484         iterate = (tree, cb) ->
485                 for n in tree
486                         if n.type is 'text'
487                                 i = 0
488                                 while i < n.text.length # don't foreach, cb might remove chars
489                                         advance = cb n, i
490                                         if advance
491                                                 i += 1
492                         if n.type is 'tag'
493                                 block = is_display_block n.el
494                                 if block
495                                         cb null
496                                 if n.children.length > 0
497                                         iterate n.children, cb
498                                 if block
499                                         cb null
500         # remove cur char
501         remove = ->
502                 removed_char = cur.text.charAt(cur_i)
503                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
504                 if next is cur # in same text node
505                         if next_i is 0
506                                 throw "how is this possible?"
507                         next_i -= 1
508                 return true
509         # undo remove()
510         put_it_back = ->
511                 cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
512                 if next is cur # in same text node
513                         next_i += 1
514                 return false
515         # return true if cur was removed from the dom (ie re-use same prev)
516         operate = ->
517                 # cur definitately set
518                 # prev and/or next might be null, indicating the start/end of a display:block
519                 return false unless is_space_code cur.text.charCodeAt cur_i
520                 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
521                 # consistent cases:
522                 # 1. zero rects returned by getClientRects() means collapsed space
523                 if bounds is null
524                         return remove()
525                 # 2. width greater than zero means visible space
526                 if bounds.w > 0
527                         return false
528                 # now the weird edge cases...
529                 #
530                 # firefox and chromium both report zero width for characters at the end
531                 # of a line where the text wraps (automatically, due to word-wrap) to
532                 # the next line. These do not appear to be distinguishable from
533                 # collapsed spaces via the range/bounds api, so...
534                 #
535                 # remove it from the dom, and if prev or next moves, put it back.
536                 if prev? and not prev_px?
537                         prev_px = cursor_to_xyh prev, prev_i
538                 if next? and not next_px?
539                         next_px = cursor_to_xyh next, next_i
540                 #if prev is null and next is null
541                 #       parent_px = cur.parent.el.getBoundingClientRect()
542                 remove()
543                 if prev?
544                         if prev_px?
545                                 new_prev_px = cursor_to_xyh prev, prev_i
546                                 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
547                                         return put_it_back()
548                         else
549                                 console.log "this shouldn't happen, we remove spaces that don't locate"
550                 if next?
551                         if next_px?
552                                 new_next_px = cursor_to_xyh next, next_i
553                                 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
554                                         return put_it_back()
555                         #else
556                         #       console.log "removing space becase space after it is collapsed"
557                 return true
558         # pass null at start/end of display:block
559         queue = (n, i) ->
560                 next = n
561                 next_i = i
562                 next_px = null
563                 advance = true
564                 if cur?
565                         removed = operate()
566                         # don't advance (to the next character next time) if we removed a
567                         # character from the same text node as ``next``, because doing so
568                         # renumbers the indexes in that string
569                         if removed and cur is next
570                                 advance = false
571                 else
572                         removed = false
573                 unless removed
574                         prev = cur
575                         prev_i = cur_i
576                         prev_px = cur_px
577                 cur = next
578                 cur_i = next_i
579                 cur_px = next_px
580                 return advance
581         queue null
582         iterate tree, queue
583         queue null
584
585         tree_remove_empty_text_nodes(tree)
586
587 class PeachHTML5Editor
588         # Options: (all optional)
589         #   editor_id: "id" attribute for outer-most element created by/for editor
590         #   on_init: callback for when the editable content is in place
591         constructor: (in_el, options) ->
592                 @options = options ? {}
593                 @in_el = in_el
594                 @tree = []
595                 @matting = []
596                 @inited = false # when iframes have loaded
597                 @outer_iframe # iframe to hold editor
598                 @outer_idoc # "document" object for @outer_iframe
599                 @wrap2 = null # scrollbar is on this
600                 @iframe = null # iframe to hold editable content
601                 @idoc = null # "document" object for @iframe
602                 @cursor = null
603                 @cursor_el = null
604                 @cursor_visible = false
605                 @poll_for_blur_timeout = null
606                 @iframe_offset = null
607                 opt_fragment = @options.fragment ? true
608                 @parser_opts = {}
609                 if opt_fragment
610                         @parser_opts.fragment = 'body'
611
612                 @outer_iframe = domify document, iframe: {}
613                 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
614                 if @options.editor_id?
615                         @outer_iframe.setAttribute 'id', @options.editor_id
616                 @outer_iframe.onload = =>
617                         @outer_idoc = @outer_iframe.contentDocument
618                         icss = domify @outer_idoc, style: children: [
619                                 domify @outer_idoc, text: css
620                         ]
621                         @outer_idoc.head.appendChild icss
622                         @iframe = domify @outer_idoc, iframe: {}
623                         @iframe.onload = =>
624                                 @init()
625                         setTimeout (=> @init() unless @inited), 200 # firefox never fires this onload
626                         @outer_idoc.body.appendChild(
627                                 domify @outer_idoc, div: id: 'wrap1', children: [
628                                         @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
629                                                 domify @outer_idoc, div: id: 'wrap3', children: [
630                                                         @iframe
631                                                         @overlay = domify @outer_idoc, div: id: 'overlay'
632                                                 ]
633                                         ]
634                                 ]
635                         )
636                 outer_wrap = domify document, div: class: 'peach_html5_editor'
637                 @in_el.parentNode.appendChild outer_wrap
638                 outer_bounds = get_el_bounds outer_wrap
639                 if outer_bounds.w < 300
640                         outer_bounds.w = 300
641                 if outer_bounds.h < 300
642                         outer_bounds.h = 300
643                 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
644                 @outer_iframe.setAttribute 'style', outer_iframe_style
645                 css = outer_css w: outer_bounds.w, h: outer_bounds.h
646                 outer_wrap.appendChild @outer_iframe
647         init: -> # called by @iframe's onload (or timeout on firefox)
648                 @idoc = @iframe.contentDocument
649                 @overlay.onclick = (e) =>
650                         @have_focus()
651                         return event_return e, @onclick e
652                 @overlay.ondoubleclick = (e) =>
653                         @have_focus()
654                         return event_return e, @ondoubleclick e
655                 @outer_idoc.body.onkeyup = (e) =>
656                         @have_focus()
657                         return event_return e, @onkeyup e
658                 @outer_idoc.body.onkeydown = (e) =>
659                         @have_focus()
660                         return event_return e, @onkeydown e
661                 @outer_idoc.body.onkeypress = (e) =>
662                         @have_focus()
663                         return event_return e, @onkeypress e
664                 if @options.stylesheet
665                         # TODO test this
666                         @idoc.head.appendChild domify @idoc, style: src: @options.stylesheet
667                 @load_html @in_el.value
668                 @inited = true
669                 if @options.on_init?
670                         @options.on_init()
671         overlay_event_to_inner_xy: (e) ->
672                 unless @iframe_offset?
673                         @iframe_offset = get_el_bounds @iframe
674                 x = e.pageX # TODO ?cross-browserify
675                 y = e.pageY + @wrap2.scrollTop # TODO ?cross-browserify
676                 # TODO adjust for scrolling
677                 return x: x - @iframe_offset.x, y: y - @iframe_offset.y
678         onclick: (e) ->
679                 xy = @overlay_event_to_inner_xy e
680                 new_cursor = find_loc_cursor_position @tree, xy
681                 if new_cursor?
682                         @move_cursor new_cursor
683                 else
684                         @kill_cursor()
685                 return false
686         ondoubleclick: (e) ->
687                 return false
688         onkeyup: (e) ->
689                 return if e.ctrlKey
690                 return false if ignore_key_codes[e.keyCode]?
691                 #return false if control_key_codes[e.keyCode]?
692         onkeydown: (e) ->
693                 return if e.ctrlKey
694                 return false if ignore_key_codes[e.keyCode]?
695                 #return false if control_key_codes[e.keyCode]?
696                 switch e.keyCode
697                         when KEY_LEFT
698                                 if @cursor?
699                                         new_cursor = find_prev_cursor_position @tree, @cursor...
700                                         if new_cursor?
701                                                 @move_cursor new_cursor
702                                 else
703                                         for c in @tree
704                                                 new_cursor = find_next_cursor_position @tree, c, -1
705                                                 if new_cursor?
706                                                         @move_cursor new_cursor
707                                                         break
708                                 return false
709                         when KEY_UP
710                                 return false
711                         when KEY_RIGHT
712                                 if @cursor?
713                                         new_cursor = find_next_cursor_position @tree, @cursor...
714                                         if new_cursor?
715                                                 @move_cursor new_cursor
716                                 else
717                                         for c in @tree
718                                                 new_cursor = find_prev_cursor_position @tree, c, -1
719                                                 if new_cursor?
720                                                         @move_cursor new_cursor
721                                                         break
722                                 return false
723                         when KEY_DOWN
724                                 return false
725                         when KEY_END
726                                 return false
727                         when KEY_BACKSPACE
728                                 return false unless @cursor?
729                                 return false unless @cursor[1] > 0
730                                 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1] - 1) + @cursor[0].text.substr(@cursor[1])
731                                 @cursor[0].el.nodeValue = @cursor[0].text
732                                 @move_cursor [@cursor[0], @cursor[1] - 1]
733                                 @changed()
734                                 return false
735                         when KEY_DELETE
736                                 return false unless @cursor?
737                                 return false unless @cursor[1] < @cursor[0].text.length
738                                 @cursor[0].text = @cursor[0].text.substr(0, @cursor[1]) + @cursor[0].text.substr(@cursor[1] + 1)
739                                 @cursor[0].el.nodeValue = @cursor[0].text
740                                 @move_cursor [@cursor[0], @cursor[1]]
741                                 @changed()
742                                 return false
743                         when KEY_ENTER
744                                 return false
745                         when KEY_ESCAPE
746                                 return false
747                         when KEY_HOME
748                                 return false
749                         when KEY_INSERT
750                                 return false
751                         when KEY_PAGE_UP
752                                 return false
753                         when KEY_PAGE_DOWN
754                                 return false
755                         when KEY_TAB
756                                 return false
757         onkeypress: (e) ->
758                 return if e.ctrlKey
759                 return false if ignore_key_codes[e.keyCode]?
760                 # return false if control_key_codes[e.keyCode]? # handled in keydown
761                 char = e.charCode ? e.keyCode
762                 if char and @cursor?
763                         char = String.fromCharCode char
764                         if @cursor[1] is 0
765                                 @cursor[0].text = char + @cursor[0].text
766                         else if @cursor[1] is @cursor[0].text.length - 1
767                                 @cursor[0].text += char
768                         else
769                                 @cursor[0].text =
770                                         @cursor[0].text.substr(0, @cursor[1]) +
771                                         char +
772                                         @cursor[0].text.substr(@cursor[1])
773                         @cursor[0].el.nodeValue = @cursor[0].text
774                         @move_cursor [@cursor[0], @cursor[1] + 1]
775                         @changed()
776                 return false
777         clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
778                 while @idoc.body.childNodes.length
779                         @idoc.body.removeChild @idoc.body.childNodes[0]
780                 @kill_cursor()
781                 return
782         load_html: (html) ->
783                 @tree = peach_parser.parse html, @parser_opts
784                 @clear_dom()
785                 instantiate_tree @tree, @idoc.body
786                 tree_dedup_space @tree
787                 @changed()
788         changed: ->
789                 @in_el.onchange = null
790                 @in_el.value = @pretty_html @tree
791                 @in_el.onchange = =>
792                         @load_html @in_el.value
793                 @iframe.style.height = "0"
794                 @iframe.style.height = "#{@idoc.body.scrollHeight}px"
795         kill_cursor: -> # remove it, forget where it was
796                 if @cursor_visible
797                         @cursor_el.parentNode.removeChild @cursor_el
798                         @cursor_visible = false
799                 @cursor = null
800                 @matt null
801         move_cursor: (cursor) ->
802                 loc = cursor_to_xyh cursor[0], cursor[1]
803                 unless loc?
804                         console.log "error: tried to move cursor to position that has no pixel location", cursor[0], cursor[1]
805                         return
806                 @cursor = cursor
807                 # replace cursor element, to reset blink animation
808                 if @cursor_visible
809                         @cursor_el.parentNode.removeChild @cursor_el
810                 @cursor_el = domify @outer_idoc, div: id: 'cursor'
811                 @overlay.appendChild @cursor_el
812                 @cursor_visible = true
813                 @cursor_el.style.left = "#{loc.x + overlay_padding - 1}px"
814                 if loc.h < 5
815                         height = 12
816                 else
817                         height = loc.h
818                 @cursor_el.style.top = "#{loc.y + overlay_padding + Math.round(height * .07)}px"
819                 @cursor_el.style.height = "#{Math.round height * 0.82}px"
820                 @matt cursor[0]
821         matt: (n) ->
822                 while @matting.length > 0
823                         @overlay.removeChild @matting[0]
824                         @matting.shift()
825                 return unless n?
826                 prev_bounds = x: 0, y: 0, w: 0, h: 0
827                 alpha = 0.1
828                 while n?.el?
829                         if n.type is 'text'
830                                 n = n.parent
831                                 continue
832                         bounds = get_el_bounds n.el
833                         return unless bounds?
834                         if bounds.x is prev_bounds.x and bounds.y is prev_bounds.y and bounds.w is prev_bounds.w and bounds.h is prev_bounds.h
835                                 n = n.parent
836                                 continue
837                         matt = domify @outer_idoc, div: class: 'ann_box', style: "left: #{bounds.x - 1 + overlay_padding}px; top: #{bounds.y - 2 + overlay_padding}px; width: #{bounds.w}px; height: #{bounds.h}px" # outline: 1000px solid rgba(0,153,255,#{alpha});
838                         @overlay.appendChild matt
839                         @matting.push matt
840                         ann = domify @outer_idoc, div: class: 'ann_tag', style: "left: #{bounds.x + 1 + overlay_padding}px; top: #{bounds.y - 7 + overlay_padding}px", children: [domify @outer_idoc, text: " #{n.name} "]
841                         @overlay.appendChild ann
842                         @matting.push ann
843                         n = n.parent
844                         alpha *= 1.5
845         pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
846                 ret = ''
847                 want_nl = parent_flags.want_nl
848                 prev_in_flow_is_text = false
849                 prev_in_flow_is_block = false
850                 for n, i in tree
851                         # figure out flags
852                         inner_flags = want_nl: true
853                         is_br = false
854                         switch n.type
855                                 when 'tag'
856                                         if n.name is 'br'
857                                                 is_br = true
858                                         is_text = false
859                                         if n.el.currentStyle?
860                                                 cs = n.el.currentStyle
861                                                 whitespace = cs['white-space']
862                                                 display = cs['display']
863                                                 position = cs['position']
864                                                 float = cs['float']
865                                                 visibility = cs['visibility']
866                                         else
867                                                 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
868                                                 whitespace = cs.getPropertyValue 'white-space'
869                                                 display = cs.getPropertyValue 'display'
870                                                 position = cs.getPropertyValue 'position'
871                                                 float = cs.getPropertyValue 'float'
872                                                 visibility = cs.getPropertyValue 'visibility'
873                                         if n.name is 'textarea'
874                                                 inner_flags.pre_ish = true
875                                         else
876                                                 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
877                                         switch float
878                                                 when 'left', 'right'
879                                                         in_flow = false
880                                                 else
881                                                         switch position
882                                                                 when 'absolute', 'fixed'
883                                                                         in_flow = false
884                                                                 else
885                                                                         if 'display' is 'none'
886                                                                                 in_flow = false
887                                                                         else
888                                                                                 switch visibility
889                                                                                         when 'hidden', 'collapse'
890                                                                                                 in_flow = false
891                                                                                         else # visible
892                                                                                                 in_flow = true
893                                         switch display
894                                                 when 'inline', 'none'
895                                                         inner_flags.block = false
896                                                         is_block = in_flow_block = false
897                                                 when 'inline-black'
898                                                         inner_flags.block = true
899                                                         is_block = in_flow_block = false
900                                                 else # block, table, etc
901                                                         inner_flags.block = true
902                                                         is_block = true
903                                                         in_flow_block = in_flow
904                                 when 'text'
905                                         is_text = true
906                                         is_block = false
907                                         in_flow = true
908                                         in_flow_block = false
909                                 else # 'comment', 'doctype'
910                                         is_text = false
911                                         is_block = false
912                                         in_flow = false
913                                         in_flow_block = false
914                         # print whitespace if we can
915                         unless parent_flags.pre_ish
916                                 unless prev_in_flow_is_text and is_br
917                                         if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
918                                                 if want_nl
919                                                         ret += "\n"
920                                                 ret += indent
921                         switch n.type
922                                 when 'tag'
923                                         ret += '<' + n.name
924                                         attr_keys = []
925                                         for k of n.attrs
926                                                 attr_keys.unshift k
927                                         #attr_keys.sort()
928                                         for k in attr_keys
929                                                 ret += " #{k}"
930                                                 if n.attrs[k].length > 0
931                                                         ret += "=\"#{enc_attr n.attrs[k]}\""
932                                         ret += '>'
933                                         unless void_elements[n.name]?
934                                                 if inner_flags.block
935                                                         next_indent = indent + '    '
936                                                 else
937                                                         next_indent = indent
938                                                 if n.children.length
939                                                         ret += @pretty_html n.children, next_indent, inner_flags
940                                                 ret += "</#{n.name}>"
941                                 when 'text'
942                                         ret += enc_text n.text
943                                 when 'comment'
944                                         ret += "<!--#{n.text}-->" # TODO encode?
945                                 when 'doctype'
946                                         ret += "<!DOCTYPE #{n.name}"
947                                         if n.public_identifier? and n.public_identifier.length > 0
948                                                 ret += " \"#{n.public_identifier}\""
949                                         if n.system_identifier? and n.system_identifier.length > 0
950                                                 ret += " \"#{n.system_identifier}\""
951                                         ret += ">"
952                         want_nl = true
953                         if in_flow
954                                 prev_in_flow_is_text = is_text
955                                 prev_in_flow_is_block = is_block or (in_flow and is_br)
956                 if tree.length
957                         # output final newline if allowed
958                         unless parent_flags.pre_ish
959                                 if prev_in_flow_is_block or parent_flags.block
960                                         ret += "\n#{indent.substr 4}"
961                 return ret
962         onblur: ->
963                 @kill_cursor()
964         have_focus: ->
965                 @editor_is_focused = true
966                 @poll_for_blur()
967         poll_for_blur: ->
968                 return if @poll_for_blur_timeout? # already polling
969                 @poll_for_blur_timeout = timeout 150, =>
970                         next_frame => # pause polling when browser knows we're not active/visible/etc.
971                                 @poll_for_blur_timeout = null
972                                 if document.activeElement is @outer_iframe
973                                         @poll_for_blur()
974                                 else
975                                         @editor_is_focused = false
976                                         @onblur()
977
978 window.peach_html5_editor = (args...) ->
979         return new PeachHTML5Editor args...
980
981 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])