JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
scroll cursor into view when it moves
[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 this_url_sans_path = ->
28         ret = "#{window.location.href}"
29         clip = ret.lastIndexOf '#'
30         if clip > -1
31                 ret = ret.substr 0, clip
32         clip = ret.lastIndexOf '?'
33         if clip > -1
34                 ret = ret.substr 0, clip
35         clip = ret.lastIndexOf '/'
36         if clip > -1
37                 ret = ret.substr 0, clip + 1
38         return ret
39
40 # table too look up the properties of various values for css's white-space
41 ws_props =
42         normal:
43                 space: false            # spaces are not preserved/rendered
44                 newline: false          # newlines are not preserved/rendered
45                 wrap: true              # text is word-wrapped
46                 to_preserve: 'pre-wrap' # to preservespaces, change white-space to this
47         nowrap:
48                 space: false
49                 newline: false
50                 wrap: false
51                 to_preserve: 'pre'
52         'pre-line':
53                 space: false
54                 newline: true
55                 wrap: true
56                 to_preserve: 'pre-wrap'
57         pre:
58                 space: true
59                 newline: true
60                 wrap: false
61         'pre-wrap':
62                 space: true
63                 newline: true
64                 wrap: true
65
66 # xml 1.0 spec, chromium and firefox accept these, plus lots of unicode chars
67 valid_attr_regex = new RegExp '^[a-zA-Z_:][-a-zA-Z0-9_:.]*$'
68 # html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
69 js_attr_regex = new RegExp '^[oO][nN].'
70
71 debug_dot_at = (doc, x, y) ->
72         return # disabled
73         el = doc.createElement 'div'
74         el.setAttribute 'style', "position: absolute; left: #{x}px; top: #{y}px; width: 1px; height: 3px; background-color: red"
75         doc.body.appendChild el
76         #console.log(new Error().stack)
77
78 # text nodes don't have getBoundingClientRect(), so use selection api to find
79 # it.
80 get_el_bounds = window.bounds = (el) ->
81         if el.getBoundingClientRect?
82                 rect = el.getBoundingClientRect()
83         else
84                 # text nodes don't have getBoundingClientRect(), so use range api
85                 range = el.ownerDocument.createRange()
86                 range.selectNodeContents el
87                 rect = range.getBoundingClientRect()
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         }
98
99 is_display_block = (el) ->
100         if el.currentStyle?
101                 return el.currentStyle.display is 'block'
102         else
103                 return window.getComputedStyle(el, null).getPropertyValue('display') is 'block'
104
105 # Pass return value from dom event handlers to this.
106 # If they return false, this will addinionally stop propagation and default.
107 event_return = (e, bool) ->
108         if bool is false
109                 if e.stopPropagation?
110                         e.stopPropagation()
111                 if e.preventDefault?
112                         e.preventDefault()
113         return bool
114 # Warning: currently assumes you're asking about a single character
115 # Note: chromium returns multiple bounding rects for a space at a line-break
116 # Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
117 # Note: sometimes returns null (eg for whitespace that is not visible)
118 text_range_bounds = (el, start, end) ->
119         range = document.createRange()
120         range.setStart el, start
121         range.setEnd el, end
122         rects = range.getClientRects()
123         if rects.length > 0
124                 if rects.length > 1
125                         if rects[1].width > rects[0].width
126                                 rect = rects[1]
127                         else
128                                 rect = rects[0]
129                 else
130                         rect = rects[0]
131         else
132                 return null
133         doc = el.ownerDocument.documentElement
134         win = el.ownerDocument.defaultView
135         y_fix = win.pageYOffset - doc.clientTop
136         x_fix = win.pageXOffset - doc.clientLeft
137         return {
138                 x: rect.left + x_fix
139                 y: rect.top + y_fix
140                 w: rect.width ? (rect.right - rect.left)
141                 h: rect.height ? (rect.top - rect.bottom)
142                 rects: rects
143                 bounding: range.getBoundingClientRect()
144         }
145
146 class CursorPosition
147         constructor: (args) ->
148                 @n = args.n ? null
149                 @i = args.i ? null
150                 if args.x?
151                         @x = args.x
152                         @y = args.y
153                         @h = args.h
154                 else
155                         @set_xyh()
156                 return
157         set_xyh: ->
158                 range = document.createRange()
159                 if @n.text.length is 0
160                         ret = text_range_bounds @n.el, 0, 0
161                 else if @i is @n.text.length
162                         ret = text_range_bounds @n.el, @i - 1, @i
163                         if ret?
164                                 ret.x += ret.w
165                 else
166                         ret = text_range_bounds @n.el, @i, @i + 1
167                 if ret?
168                         @x = ret.x
169                         @y = ret.y
170                         @h = ret.h
171                 else
172                         @x = null
173                         @y = null
174                         @h = null
175                 return ret
176
177 new_cursor_position = (args) ->
178         ret = new CursorPosition args
179         if ret.x?
180                 return ret
181         return null
182
183 # encode text so it can be safely placed inside an html attribute
184 enc_attr_regex = new RegExp '(&)|(")|(\u00A0)', 'g'
185 enc_attr = (txt) ->
186         return txt.replace enc_attr_regex, (match, amp, quote) ->
187                 return '&amp;' if (amp)
188                 return '&quot;' if (quote)
189                 return '&nbsp;'
190 enc_text_regex = new RegExp '(&)|(<)|(\u00A0)', 'g'
191 enc_text = (txt) ->
192         return txt.replace enc_text_regex, (match, amp, lt) ->
193                 return '&amp;' if (amp)
194                 return '&lt;' if (lt)
195                 return '&nbsp;'
196
197 void_elements = {
198         area: true
199         base: true
200         br: true
201         col: true
202         embed: true
203         hr: true
204         img: true
205         input: true
206         keygen: true
207         link: true
208         meta: true
209         param: true
210         source: true
211         track: true
212         wbr: true
213 }
214 # TODO make these always pretty-print (on the inside) like blocks
215 no_text_elements = { # these elements never contain text
216         select: true
217         table: true
218         tr: true
219         thead: true
220         tbody: true
221         ul: true
222         ol: true
223 }
224
225 domify = (doc, hash) ->
226         for tag, attrs of hash
227                 if tag is 'text'
228                         return document.createTextNode attrs
229                 el = document.createElement tag
230                 for k, v of attrs
231                         if k is 'children'
232                                 for child in v
233                                         el.appendChild child
234                         else
235                                 el.setAttribute k, v
236         return el
237
238
239
240 ignore_key_codes =
241         '18': true # alt
242         '20': true # capslock
243         '17': true # ctrl
244         '144': true # numlock
245         '16': true # shift
246         '91': true # windows "start" key
247 # key codes: (valid on keydown, not keypress)
248 KEY_LEFT = 37
249 KEY_UP = 38
250 KEY_RIGHT = 39
251 KEY_DOWN = 40
252 KEY_BACKSPACE = 8 # <--
253 KEY_DELETE = 46 # -->
254 KEY_END = 35
255 KEY_ENTER = 13
256 KEY_ESCAPE = 27
257 KEY_HOME = 36
258 KEY_INSERT = 45
259 KEY_PAGE_UP = 33
260 KEY_PAGE_DOWN = 34
261 KEY_TAB = 9
262 control_key_codes = # we react to these, but they aren't typing
263         '37': KEY_LEFT
264         '38': KEY_UP
265         '39': KEY_RIGHT
266         '40': KEY_DOWN
267         '35': KEY_END
268         '8':  KEY_BACKSPACE
269         '46': KEY_DELETE
270         '13': KEY_ENTER
271         '27': KEY_ESCAPE
272         '36': KEY_HOME
273         '45': KEY_INSERT
274         '33': KEY_PAGE_UP
275         '34': KEY_PAGE_DOWN
276         '9':  KEY_TAB
277
278 instantiate_tree = (tree, parent) ->
279         remove = []
280         for c, i in tree
281                 switch c.type
282                         when 'text'
283                                 c.el = parent.ownerDocument.createTextNode c.text
284                                 parent.appendChild c.el
285                         when 'tag'
286                                 if c.name in ['script', 'object', 'iframe', 'link']
287                                         # TODO put placeholders instead
288                                         remove.unshift i
289                                         continue
290                                 # TODO create in correct namespace
291                                 c.el = parent.ownerDocument.createElement c.name
292                                 for k, v of c.attrs
293                                         # FIXME if attr_whitelist[k]?
294                                         if valid_attr_regex.test k
295                                                 unless js_attr_regex.test k
296                                                         c.el.setAttribute k, v
297                                 parent.appendChild c.el
298                                 if c.children.length
299                                         instantiate_tree c.children, c.el
300         for i in remove
301                 tree.splice i, 1
302
303 traverse_tree = (tree, cb) ->
304         done = false
305         for c in tree
306                 done = cb c
307                 return done if done
308                 if c.children.length
309                         done = traverse_tree c.children, cb
310                         return done if done
311         return done
312
313 first_cursor_position = (tree) ->
314         found = null
315         traverse_tree tree, (node, state) ->
316                 if node.type is 'text'
317                         cursor = new_cursor_position n: node, i: 0
318                         if cursor?
319                                 found = cursor
320                                 return true
321                 return false
322         return found # maybe null
323
324 # this will fail when text has non-locatable cursor positions
325 find_next_cursor_position = (tree, cursor) ->
326         if cursor.n.type is 'text' and cursor.n.text.length > cursor.i
327                 new_cursor = new_cursor_position n: cursor.n, i: cursor.i + 1
328                 if new_cursor?
329                         return new_cursor
330         state_before = true
331         found = null
332         traverse_tree tree, (node, state) ->
333                 if node.type is 'text' and state_before is false
334                         new_cursor = new_cursor_position n: node, i: 0
335                         if new_cursor?
336                                 found = new_cursor
337                                 return true
338                 if node is cursor.n
339                         state_before = false
340                 return false
341         if found?
342                 return found
343         return null
344
345 last_cursor_position = (tree) ->
346         found = null
347         traverse_tree tree, (node) ->
348                 if node.type is 'text'
349                         cursor = new_cursor_position n: node, i: node.text.length
350                         if cursor?
351                                 found = cursor
352                 return false
353         return found # maybe null
354
355 # this will fail when text has non-locatable cursor positions
356 find_prev_cursor_position = (tree, cursor) ->
357         if cursor.n.type is 'text' and cursor.i > 0
358                 new_cursor = new_cursor_position n: cursor.n, i: cursor.i - 1
359                 if new_cursor?
360                         return new_cursor
361         found_prev = null
362         found = null
363         traverse_tree tree, (node) ->
364                 if node is cursor.n
365                         found = found_prev # maybe null
366                         return true
367                 if node.type is 'text'
368                         new_cursor = new_cursor_position n: node, i: node.text.length
369                         if new_cursor?
370                                 found_prev = new_cursor
371                 return false
372         return found # maybe null
373
374 xy_to_cursor = (tree, xy) ->
375         for n in tree
376                 if n.type is 'tag' or n.type is 'text'
377                         bounds = get_el_bounds n.el
378                         continue if xy.x < bounds.x
379                         continue if xy.x > bounds.x + bounds.w
380                         continue if xy.y < bounds.y
381                         continue if xy.y > bounds.y + bounds.h
382                         if n.children.length
383                                 ret = xy_to_cursor n.children, xy
384                                 return ret if ret?
385                         if n.type is 'text'
386                                 # click is within bounding box that contains all text.
387                                 if n.text.length is 0
388                                         ret = new_cursor_position n: n, i: 0
389                                         return ret if ret?
390                                         continue
391                                 before = new_cursor_position n: n, i: 0
392                                 continue unless before?
393                                 after = new_cursor_position n: n, i: n.text.length
394                                 continue unless after?
395                                 if xy.y < before.y + before.h and xy.x < before.x
396                                         # console.log 'before first char on first line'
397                                         continue
398                                 if xy.y > after.y and xy.x > after.x
399                                         # console.log 'after last char on last line'
400                                         continue
401                                 if xy.y < before.y
402                                         console.log "Warning: click in text bounding box but above first line"
403                                         continue # above first line (runaround?)
404                                 if xy.y > after.y + after.h
405                                         console.log "Warning: click in text bounding box but below last line", xy.y, after.y, after.h
406                                         continue # below last line (shouldn't happen?)
407                                 while after.i - before.i > 1
408                                         guess_i = Math.round((before.i + after.i) / 2)
409                                         cur = new_cursor_position n: n, i: guess_i
410                                         unless cur?
411                                                 console.log "error: failed to find cursor pixel location for", n, guess_i
412                                                 before = null
413                                                 break
414                                         if xy.y < cur.y or (xy.y <= cur.y + cur.h and xy.x < cur.x)
415                                                 after = cur
416                                         else
417                                                 before = cur
418                                 continue unless before? # signals failure to find a cursor position
419                                 # which one is closest?
420                                 if Math.abs(before.x - xy.x) < Math.abs(after.x - xy.x)
421                                         return before
422                                 else
423                                         return after
424         return null
425
426 # browsers collapse these (html5 spec calls these "space characters")
427 is_space_code = (char_code) ->
428         switch char_code
429                 when 9, 10, 12, 13, 32
430                         return true
431         return false
432 is_space = (chr) ->
433         return is_space_code chr.charCodeAt 0
434
435 tree_remove_empty_text_nodes = (tree) ->
436         empties = []
437         traverse_tree tree, (n) ->
438                 if n.type is 'text'
439                         if n.text.length is 0
440                                 empties.unshift n
441                 return false
442         for n in empties
443                 # don't completely empty the tree
444                 if tree.length is 1
445                         if tree[0].type is 'text'
446                                 console.log "oop, leaving a blank node because it's the only thing"
447                                 return
448                 n.el.parentNode.removeChild n.el
449                 for c, i in n.parent.children
450                         if c is n
451                                 n.parent.children.splice i, 1
452                                 break
453
454 # pass a array of nodes (from parser library, ie it should have .el and .text)
455 tree_dedup_space = (tree) ->
456         prev = cur = next = null
457         prev_i = cur_i = next_i = 0
458         prev_pos = pos = next_pos = null
459         prev_px = cur_px = next_px = null
460         first = true
461         removed_char = null
462
463         tree_remove_empty_text_nodes(tree)
464
465         iterate = (tree, cb) ->
466                 for n in tree
467                         if n.type is 'text'
468                                 i = 0
469                                 while i < n.text.length # don't foreach, cb might remove chars
470                                         advance = cb n, i
471                                         if advance
472                                                 i += 1
473                         if n.type is 'tag'
474                                 block = is_display_block n.el
475                                 if block
476                                         cb null
477                                 if n.children.length > 0
478                                         iterate n.children, cb
479                                 if block
480                                         cb null
481         # remove cur char
482         remove = (undo) ->
483                 if undo
484                         cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i)
485                         if next is cur # in same text node
486                                 next_i += 1
487                         return -1
488                 else
489                         removed_char = cur.text.charAt(cur_i)
490                         cur.el.textContent = cur.text = (cur.text.substr 0, cur_i) + (cur.text.substr cur_i + 1)
491                         if next is cur # in same text node
492                                 if next_i is 0
493                                         throw "how is this possible?"
494                                 next_i -= 1
495                         return 1
496         whitespace_to_space = (undo) ->
497                 if undo
498                         cur.text = (cur.text.substr 0, cur_i) + removed_char + (cur.text.substr cur_i + 1)
499                         cur.el.textContent = cur.text
500                 else
501                         removed_char = cur.text.charAt(cur_i)
502                         cur.text = (cur.text.substr 0, cur_i) + ' ' + (cur.text.substr cur_i + 1)
503                         cur.el.textContent = cur.text
504                 return 0
505         # return true if cur was removed from the dom (ie re-use same prev)
506         operate = ->
507                 # cur definitately set
508                 # prev and/or next might be null, indicating the start/end of a display:block
509                 return false unless is_space_code cur.text.charCodeAt cur_i
510                 fixers = [remove, whitespace_to_space]
511                 bounds = text_range_bounds cur.el, cur_i, cur_i + 1
512                 # consistent cases:
513                 # 1. zero rects returned by getClientRects() means collapsed space
514                 if bounds is null
515                         return remove()
516                 # 2. width greater than zero means visible space
517                 if bounds.w > 0
518                         fixers.shift() # don't try removing
519                 # now the weird edge cases...
520                 #
521                 # firefox and chromium both report zero width for characters at the end
522                 # of a line where the text wraps (automatically, due to word-wrap) to
523                 # the next line. These do not appear to be distinguishable from
524                 # collapsed spaces via the range/bounds api, so...
525                 #
526                 # remove it from the dom, and if prev or next moves, put it back.
527                 if prev? and not prev_px?
528                         prev_px = new_cursor_position n: prev, i: prev_i
529                 if next? and not next_px?
530                         next_px = new_cursor_position n: next, i: next_i
531                 #if prev is null and next is null
532                 #       parent_px = cur.parent.el.getBoundingClientRect()
533                 undo_arg = true # just for readabality
534                 removed = 0
535                 for fixer in fixers
536                         break if removed > 0
537                         removed += fixer()
538                         need_undo = false
539                         if prev?
540                                 if prev_px?
541                                         new_prev_px = new_cursor_position n: prev, i: prev_i
542                                         if new_prev_px?
543                                                 if new_prev_px.x isnt prev_px.x or new_prev_px.y isnt prev_px.y
544                                                         need_undo = true
545                                         else
546                                                 need_undo = true
547                                 else
548                                         console.log "this shouldn't happen, we remove spaces that don't locate"
549                         if next? and not need_undo
550                                 if next_px?
551                                         new_next_px = new_cursor_position n: next, i: next_i
552                                         if new_next_px?
553                                                 if new_next_px.x isnt next_px.x or new_next_px.y isnt next_px.y
554                                                         need_undo = true
555                                         else
556                                                 need_undo = true
557                                 #else
558                                 #       console.log "removing space becase space after it is collapsed"
559                         if need_undo
560                                 removed += fixer undo_arg
561                 if removed > 0
562                         return true
563                 else
564                         return false
565         # pass null at start/end of display:block
566         queue = (n, i) ->
567                 next = n
568                 next_i = i
569                 next_px = null
570                 advance = true
571                 if cur?
572                         removed = operate()
573                         # don't advance (to the next character next time) if we removed a
574                         # character from the same text node as ``next``, because doing so
575                         # renumbers the indexes in that string
576                         if removed and cur is next
577                                 advance = false
578                 else
579                         removed = false
580                 unless removed
581                         prev = cur
582                         prev_i = cur_i
583                         prev_px = cur_px
584                 cur = next
585                 cur_i = next_i
586                 cur_px = next_px
587                 return advance
588         queue null
589         iterate tree, queue
590         queue null
591
592         tree_remove_empty_text_nodes(tree)
593
594 class PeachHTML5Editor
595         # Options: (all optional)
596         #   editor_id: "id" attribute for outer-most element created by/for editor
597         #   css_file: filename of a css file to style editable content
598         #   on_init: callback for when the editable content is in place
599         constructor: (in_el, options) ->
600                 @options = options ? {}
601                 @in_el = in_el
602                 @tree = null
603                 @matting = []
604                 @init_1_called = false # when iframes have loaded
605                 @outer_iframe # iframe to hold editor
606                 @outer_idoc # "document" object for @outer_iframe
607                 @wrap2 = null # scrollbar is on this
608                 @wrap2_offset = null
609                 @wrap2_height = null # including padding
610                 @iframe = null # iframe to hold editable content
611                 @idoc = null # "document" object for @iframe
612                 @cursor = null
613                 @cursor_el = null
614                 @cursor_visible = false
615                 @poll_for_blur_timeout = null
616                 opt_fragment = @options.fragment ? true
617                 @parser_opts = {}
618                 if opt_fragment
619                         @parser_opts.fragment = 'body'
620
621                 @outer_iframe = domify document, iframe: {}
622                 outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
623                 if @options.editor_id?
624                         @outer_iframe.setAttribute 'id', @options.editor_id
625                 @outer_iframe.onload = =>
626                         @outer_idoc = @outer_iframe.contentDocument
627                         icss = domify @outer_idoc, style: children: [
628                                 domify @outer_idoc, text: css
629                         ]
630                         @outer_idoc.head.appendChild icss
631                         @iframe = domify @outer_idoc, iframe: sandbox: 'allow-same-origin allow-scripts'
632                         @iframe.onload = =>
633                                 @init_1()
634                         timeout 200, => # firefox never fires this onload
635                                 @init_1() unless @init_1_called
636                         @outer_idoc.body.appendChild(
637                                 domify @outer_idoc, div: id: 'wrap1', children: [
638                                         domify @outer_idoc, div: style: "position: absolute; top: 0; left: 1px; font-size: 10px", children: [ domify @outer_idoc, text: "Peach HTML5 Editor" ]
639                                         @wrap2 = domify @outer_idoc, div: id: 'wrap2', children: [
640                                                 domify @outer_idoc, div: id: 'wrap3', children: [
641                                                         @iframe
642                                                         @overlay = domify @outer_idoc, div: id: 'overlay'
643                                                 ]
644                                         ]
645                                 ]
646                         )
647                 outer_wrap = domify document, div: class: 'peach_html5_editor'
648                 @in_el.parentNode.appendChild outer_wrap
649                 outer_bounds = get_el_bounds outer_wrap
650                 if outer_bounds.w < 300
651                         outer_bounds.w = 300
652                 if outer_bounds.h < 300
653                         outer_bounds.h = 300
654                 outer_iframe_style += "width: #{outer_bounds.w}px; height: #{outer_bounds.h}px;"
655                 @outer_iframe.setAttribute 'style', outer_iframe_style
656                 css = @generate_outer_css w: outer_bounds.w, h: outer_bounds.h
657                 outer_wrap.appendChild @outer_iframe
658         init_1: -> # @iframe has loaded (but not it's css)
659                 @idoc = @iframe.contentDocument
660                 @init_1_called = true
661                 # chromium doesn't resolve relative urls as though they were at the same domain
662                 # so add a <base> tag
663                 @idoc.head.appendChild domify @idoc, base: href: this_url_sans_path()
664                 # don't let @iframe have scrollbars
665                 @idoc.head.appendChild domify @idoc, style: children: [domify @idoc, text: "body { overflow: hidden; }"]
666                 # load css file
667                 if @options.css_file
668                         istyle = domify @idoc, link: rel: 'stylesheet', href: @options.css_file
669                         istyle.onload = =>
670                                 @init_2()
671                         @idoc.head.appendChild istyle
672                 else
673                         @init_2()
674         init_2: -> # @iframe and it's css file(s) are ready
675                 @overlay.onclick = (e) =>
676                         @have_focus()
677                         return event_return e, @onclick e
678                 @overlay.ondoubleclick = (e) =>
679                         @have_focus()
680                         return event_return e, @ondoubleclick e
681                 @outer_idoc.body.onkeyup = (e) =>
682                         @have_focus()
683                         return event_return e, @onkeyup e
684                 @outer_idoc.body.onkeydown = (e) =>
685                         @have_focus()
686                         return event_return e, @onkeydown e
687                 @outer_idoc.body.onkeypress = (e) =>
688                         @have_focus()
689                         return event_return e, @onkeypress e
690                 @load_html @in_el.value
691                 if @options.on_init?
692                         @options.on_init()
693         generate_outer_css: (args) ->
694                 w = args.w ? 300
695                 h = args.h ? 300
696                 inner_padding = args.inner_padding ? overlay_padding
697                 frame_width = args.frame_width ? inner_padding
698                 occupy = (left, top = left, right = left, bottom = top) ->
699                         w -= left + right
700                         h -= top + bottom
701                         return Math.max(left, top, right, bottom)
702                 ret = ''
703                 ret += 'body {'
704                 ret +=     'margin: 0;'
705                 ret +=     'padding: 0;'
706                 ret +=     'color: black;'
707                 ret +=     'background: white;'
708                 ret += '}'
709                 ret += '#wrap1 {'
710                 ret +=     "border: #{occupy 1}px solid black;"
711                 ret +=     "padding: #{occupy frame_width}px;"
712                 ret += '}'
713                 ret += '#wrap2 {'
714                 ret +=     "border: #{occupy 1}px solid black;"
715                 @wrap2_height = h # including padding because padding scrolls
716                 ret +=     "padding: #{occupy inner_padding}px;"
717                 ret +=     "padding-right: #{inner_padding + occupy 0, 0, 15, 0}px;" # for scroll bar
718                 ret +=     "width: #{w}px;"
719                 ret +=     "height: #{h}px;"
720                 ret +=     'overflow-x: hidden;'
721                 ret +=     'overflow-y: scroll;'
722                 ret += '}'
723                 ret += '#wrap3 {'
724                 ret +=     'position: relative;'
725                 ret +=     "width: #{w}px;"
726                 ret +=     "min-height: #{h}px;"
727                 ret += '}'
728                 ret += 'iframe {'
729                 ret +=     'box-sizing: border-box;'
730                 ret +=     'margin: 0;'
731                 ret +=     'border: none;'
732                 ret +=     'padding: 0;'
733                 ret +=     "width: #{w}px;"
734                 #ret +=     "height: #{h}px;" # height auto-set when content set/changed
735                 ret +=     '-ms-user-select: none;'
736                 ret +=     '-webkit-user-select: none;'
737                 ret +=     '-moz-user-select: none;'
738                 ret +=     'user-select: none;'
739                 ret += '}'
740                 ret += '#overlay {'
741                 ret +=     'position: absolute;'
742                 ret +=     "left: -#{inner_padding}px;"
743                 ret +=     "top: -#{inner_padding}px;"
744                 ret +=     "right: -#{inner_padding}px;"
745                 ret +=     "bottom: -#{inner_padding}px;"
746                 ret +=     'overflow: hidden;'
747                 ret += '}'
748                 ret += '.lightbox {'
749                 ret +=     'position: absolute;'
750                 ret +=     'background: rgba(100,100,100,0.2);'
751                 ret += '}'
752                 ret += '#cursor {'
753                 ret +=     'position: absolute;'
754                 ret +=     'width: 2px;'
755                 ret +=     'background: linear-gradient(0deg, rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1));'
756                 ret +=     'background-size: 200% 200%;'
757                 ret +=     '-webkit-animation: blink 1s linear normal infinite;'
758                 ret +=     'animation: blink 1s linear normal infinite;'
759                 ret += '}'
760                 ret += '@-webkit-keyframes blink {'
761                 ret +=     '0%{background-position:0% 0%}'
762                 ret +=     '100%{background-position:0% -100%}'
763                 ret += '}'
764                 ret += '@keyframes blink { '
765                 ret +=     '0%{background-position:0% 0%}'
766                 ret +=     '100%{background-position:0% -100%}'
767                 ret += '}'
768                 ret += '.ann_box {'
769                 ret +=     'z-index: 5;'
770                 ret +=     'position: absolute;'
771                 ret +=     'border: 1px solid rgba(0,0,0,0.1);'
772                 ret +=     'outline: 1px solid rgba(255,255,255,0.1);' # in case there's a black background
773                 ret += '}'
774                 ret += '.ann_tag {'
775                 ret +=     'z-index: 10;'
776                 ret +=     'position: absolute;'
777                 ret +=     'font-size: 8px;'
778                 ret +=     'white-space: pre;'
779                 ret +=     'background: rgba(255,255,255,0.4);'
780                 ret +=     '-ms-user-select: none;'
781                 ret +=     '-webkit-user-select: none;'
782                 ret +=     '-moz-user-select: none;'
783                 ret +=     'user-select: none;'
784                 ret += '}'
785                 return ret
786         overlay_event_to_inner_xy: (e) ->
787                 unless @wrap2_offset?
788                         @wrap2_offset = get_el_bounds @wrap2
789                 x = e.pageX - overlay_padding
790                 y = e.pageY - overlay_padding + @wrap2.scrollTop
791                 return x: x - @wrap2_offset.x, y: y - @wrap2_offset.y
792         onclick: (e) ->
793                 xy = @overlay_event_to_inner_xy e
794                 new_cursor = xy_to_cursor @tree, xy
795                 if new_cursor?
796                         @move_cursor new_cursor
797                 else
798                         @kill_cursor()
799                 return false
800         ondoubleclick: (e) ->
801                 return false
802         onkeyup: (e) ->
803                 return if e.ctrlKey
804                 return false if ignore_key_codes[e.keyCode]?
805                 #return false if control_key_codes[e.keyCode]?
806         onkeydown: (e) ->
807                 return if e.ctrlKey
808                 return false if ignore_key_codes[e.keyCode]?
809                 #return false if control_key_codes[e.keyCode]?
810                 switch e.keyCode
811                         when KEY_LEFT
812                                 if @cursor?
813                                         new_cursor = find_prev_cursor_position @tree, @cursor
814                                 else
815                                         new_cursor = first_cursor_position @tree
816                                 if new_cursor?
817                                         @move_cursor new_cursor
818                                 return false
819                         when KEY_RIGHT
820                                 if @cursor?
821                                         new_cursor = find_next_cursor_position @tree, @cursor
822                                 else
823                                         new_cursor = last_cursor_position @tree
824                                 if new_cursor?
825                                         @move_cursor new_cursor
826                                 return false
827                         when KEY_UP
828                                 if @cursor?
829                                         new_cursor = @cursor
830                                         # go prev until we're higher on y axis
831                                         while new_cursor.y >= @cursor.y
832                                                 new_cursor = find_prev_cursor_position @tree, new_cursor
833                                                 return false unless new_cursor?
834                                         # done early if we're already left of old cursor position
835                                         if new_cursor.x <= @cursor.x
836                                                 @move_cursor new_cursor
837                                                 return false
838                                         target_y = new_cursor.y
839                                         # search leftward, until we find the closest position
840                                         # new_cursor is the prev-most position we've checked
841                                         # prev_cursor is the older value, so it's not as prev as new_cursor
842                                         while new_cursor.x > @cursor.x and new_cursor.y is target_y
843                                                 prev_cursor = new_cursor
844                                                 new_cursor = find_prev_cursor_position @tree, new_cursor
845                                                 break unless new_cursor?
846                                         # move cursor to prev_cursor or new_cursor
847                                         if new_cursor?
848                                                 if new_cursor.y is target_y
849                                                         # both valid, and on the same line, use closest
850                                                         if (@cursor.x - new_cursor.x) < (prev_cursor.x - @cursor.x)
851                                                                 @move_cursor new_cursor
852                                                         else
853                                                                 @move_cursor prev_cursor
854                                                 else
855                                                         # new_cursor on wrong line, use prev_cursor
856                                                         @move_cursor prev_cursor
857                                         else
858                                                 # can't go any further prev, use prev_cursor
859                                                 @move_cursor prev_cursor
860                                 else
861                                         # move cursor to first position in document
862                                         new_cursor = first_cursor_position @tree
863                                         if new_cursor?
864                                                 @move_cursor new_cursor
865                                 return false
866                         when KEY_DOWN
867                                 if @cursor?
868                                         new_cursor = @cursor
869                                         # go next until we move on the y axis
870                                         while new_cursor.y <= @cursor.y
871                                                 new_cursor = find_next_cursor_position @tree, new_cursor
872                                                 return false unless new_cursor?
873                                         # done early if we're already right of old cursor position
874                                         if new_cursor.x >= @cursor.x
875                                                 # this would be strange, but could happen due to runaround
876                                                 @move_cursor new_cursor
877                                                 return false
878                                         target_y = new_cursor.y
879                                         # search rightward, until we find the closest position
880                                         # new_cursor is the next-most position we've checked
881                                         # prev_cursor is the older value, so it's not as next as new_cursor
882                                         while new_cursor.x < @cursor.x and new_cursor.y is target_y
883                                                 prev_cursor = new_cursor
884                                                 new_cursor = find_next_cursor_position @tree, new_cursor
885                                                 break unless new_cursor?
886                                         # move cursor to prev_cursor or new_cursor
887                                         if new_cursor?
888                                                 if new_cursor.y is target_y
889                                                         # both valid, and on the same line, use closest
890                                                         if (new_cursor.x - @cursor.x) < (@cursor.x - prev_cursor.x)
891                                                                 @move_cursor new_cursor
892                                                         else
893                                                                 @move_cursor prev_cursor
894                                                 else
895                                                         # new_cursor on wrong line, use prev_cursor
896                                                         @move_cursor prev_cursor
897                                         else
898                                                 # can't go any further prev, use prev_cursor
899                                                 @move_cursor prev_cursor
900                                 else
901                                         # move cursor to first position in document
902                                         new_cursor = last_cursor_position @tree
903                                         if new_cursor?
904                                                 @move_cursor new_cursor
905                                 return false
906                         when KEY_END
907                                 return false
908                         when KEY_BACKSPACE
909                                 return false unless @cursor?
910                                 return false unless @cursor.i > 0
911                                 @remove_character @cursor.n, @cursor.i - 1
912                                 @adjust_whitespace_style @cursor.n
913                                 @changed()
914                                 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i - 1
915                                 if new_cursor?
916                                         @move_cursor new_cursor
917                                 else
918                                         @kill_cursor()
919                                 return false
920                         when KEY_DELETE
921                                 return false unless @cursor?
922                                 return false unless @cursor.i < @cursor.n.text.length
923                                 @remove_character @cursor.n, @cursor.i
924                                 @adjust_whitespace_style @cursor.n
925                                 @changed()
926                                 new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i
927                                 if new_cursor?
928                                         @move_cursor new_cursor
929                                 else
930                                         @kill_cursor()
931                                 return false
932                         when KEY_ENTER
933                                 return false
934                         when KEY_ESCAPE
935                                 return false
936                         when KEY_HOME
937                                 return false
938                         when KEY_INSERT
939                                 return false
940                         when KEY_PAGE_UP
941                                 return false
942                         when KEY_PAGE_DOWN
943                                 return false
944                         when KEY_TAB
945                                 return false
946         onkeypress: (e) ->
947                 return if e.ctrlKey
948                 return false if ignore_key_codes[e.keyCode]?
949                 char = e.charCode ? e.keyCode
950                 if char and @cursor?
951                         char = String.fromCharCode char
952                         @insert_character @cursor.n, @cursor.i, char
953                         @adjust_whitespace_style @cursor.n
954                         @changed()
955                         new_cursor = new_cursor_position n: @cursor.n, i: @cursor.i + 1
956                         if new_cursor
957                                 @move_cursor new_cursor
958                         else
959                                 console.log "ERROR: couldn't find cursor position after insert"
960                                 @kill_cursor()
961                 return false
962         clear_dom: -> # remove all the editable content (and cursor, overlays, etc)
963                 while @idoc.body.childNodes.length
964                         @idoc.body.removeChild @idoc.body.childNodes[0]
965                 @kill_cursor()
966                 return
967         load_html: (html) ->
968                 @tree = peach_parser.parse html, @parser_opts
969                 @clear_dom()
970                 instantiate_tree @tree, @idoc.body
971                 tree_dedup_space @tree
972                 @changed()
973         changed: ->
974                 @in_el.onchange = null
975                 @in_el.value = @pretty_html @tree
976                 @in_el.onchange = =>
977                         @load_html @in_el.value
978                 @adjust_iframe_height()
979         adjust_iframe_height: ->
980                 s = @wrap2.scrollTop
981                 # when the content gets shorter, the idoc's body tag will continue to
982                 # report the old (too big) height in Chrome. The workaround is to
983                 # shrink the iframe before the content height:
984                 @iframe.style.height = "10px"
985                 h = parseInt(@idoc.body.scrollHeight, 10)
986                 @iframe.style.height = "#{h}px"
987                 @wrap2.scrollTop = s
988         # does this node have whitespace that would be collapsed by white-space: normal?
989         # note: this checks direct text children, and does _not_ recurse into child tags
990         # tag is a node with type:"tag"
991         has_collapsable_space: (tag) ->
992                 for n in tag.children
993                         if n.type is 'text'
994                                 for i in [0...n.text.length]
995                                         code = n.text.charCodeAt i
996                                         if code isnt 32 and is_space_code code
997                                                 # tab, return
998                                                 return true
999                                         # check for double spaces that don't surround insert location
1000                                         continue if i is 0
1001                                         if n.text.substr(i - 1, 2) is '  '
1002                                                 return true
1003                                 if n.text.length > 0
1004                                         if is_space_code n.text.charCodeAt 0
1005                                                 return true
1006                                         if is_space_code n.text.charCodeAt n.text.length - 1
1007                                                 return true
1008         # add/remove "white-space: pre[-wrap]" to/from style="" on tags with direct
1009         # child text nodes with multiple spaces in a row, or spaces at the
1010         # start/end.
1011         #
1012         # text inside child tags are not consulted. Child tags are expected to have
1013         # this function applied to them when their content changes.
1014         adjust_whitespace_style: (n) ->
1015                 if n.type is 'text'
1016                         n = n.parent
1017                         return unless n?.el?
1018                 # which css rule should be used to preserve spaces (should we need to)
1019                 style = @iframe.contentWindow.getComputedStyle n.el, null
1020                 ws = style.getPropertyValue 'white-space'
1021                 if ws_props[ws].space
1022                         preserve_rule = ws
1023                 else
1024                         preserve_rule = ws_props[ws].to_preserve
1025                 preserve_rule = "white-space: #{preserve_rule}"
1026                 if @has_collapsable_space n
1027                         # make sure preserve_rule exists
1028                         if n.el.style['white-space']
1029                                 # FIXME check that it matches
1030                                 return
1031                         if n.attrs[style]?
1032                                 n.attrs.style += "; #{preserve_rule}"
1033                         else
1034                                 n.attrs.style = preserve_rule
1035                         n.el.setAttribute 'style', n.attrs.style
1036                 else
1037                         # remove preserve_rule if it exists
1038                         return unless n.attrs.style?
1039                         # FIXME don't assume whitespace is just so
1040                         if n.attrs.style is "white-space: #{ws}"
1041                                 delete n.attrs.style
1042                                 n.el.removeAttribute 'style'
1043                         else
1044                                 # FIXME find it in the middle and at the start
1045                                 needle = "; white-space: #{ws}"
1046                                 if needle is n.attrs.style.substr n.attrs.style.length - needle
1047                                         n.attrs.style = n.attrs.style.substr 0, n.attrs.style.length - needle
1048                                         n.el.setAttribute n.attrs.style
1049         # after calling this, you MUST call changed() and adjust_whitespace_style()
1050         insert_character: (n, i, char) ->
1051                 parent = @cursor.n.parent
1052                 return unless parent
1053                 return unless parent.el?
1054                 # insert the character
1055                 if i is 0
1056                         n.text = char + n.text
1057                 else if i is n.text.length
1058                         n.text += char
1059                 else
1060                         n.text =
1061                                 n.text.substr(0, i) +
1062                                 char +
1063                                 n.text.substr(i)
1064                 n.el.nodeValue = n.text
1065         # after calling this, you MUST call changed() and adjust_whitespace_style()
1066         remove_character: (n, i) ->
1067                 n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1068                 n.el.nodeValue = n.text
1069         kill_cursor: -> # remove it, forget where it was
1070                 if @cursor_visible
1071                         @cursor_el.parentNode.removeChild @cursor_el
1072                         @cursor_visible = false
1073                 @cursor = null
1074                 @annotate null
1075         move_cursor: (cursor) ->
1076                 @cursor = cursor
1077                 unless @cursor_visible
1078                         @cursor_el = domify @outer_idoc, div: id: 'cursor'
1079                         @overlay.appendChild @cursor_el
1080                         @cursor_visible = true
1081                 @cursor_el.style.left = "#{cursor.x + overlay_padding - 1}px"
1082                 if cursor.h < 5
1083                         height = 12
1084                 else
1085                         height = cursor.h
1086                 @cursor_el.style.top = "#{cursor.y + overlay_padding + Math.round(height * .07)}px"
1087                 @cursor_el.style.height = "#{Math.round height * 0.82}px"
1088                 @annotate cursor.n
1089                 @scroll_into_view cursor.y, height
1090         scroll_into_view: (y, h = 0) ->
1091                 closest = 30 # setting: smallest pixels from top/bottom of screet that's OK
1092                 y += overlay_padding # convert units from @idoc to @wrap2
1093                 # very top of document
1094                 if y <= closest
1095                         @wrap2.scrollTop = 0
1096                         return
1097                 # very bottom of document
1098                 if y + h >= @wrap2.scrollHeight - closest
1099                         @wrap2.scrollTop = @wrap2.scrollHeight - @wrap2_height
1100                         return
1101                 # The most scrolled up (lowest value for scrollTop) that would be OK
1102                 upmost = y + h + closest - @wrap2_height
1103                 upmost = Math.max(upmost, 0)
1104                 # the most scrolled down (highest value for scrollTop) that would be OK
1105                 downmost = y - closest
1106                 downmost = Math.min(downmost, @wrap2.scrollHeight - @wrap2_height)
1107                 if upmost > downmost # means h is too big to fit
1108                         # scroll so top is visible
1109                         @wrap2.scrollTop = downmost
1110                         return
1111                 if @wrap2.scrollTop < upmost
1112                         @wrap2.scrollTop = upmost
1113                         return
1114                 if @wrap2.scrollTop > downmost
1115                         @wrap2.scrollTop = downmost
1116                         return
1117                 return
1118         annotate: (n) ->
1119                 while @matting.length > 0
1120                         @overlay.removeChild @matting[0]
1121                         @matting.shift()
1122                 return unless n?
1123                 prev_bounds = x: 0, y: 0, w: 0, h: 0
1124                 alpha = 0.1
1125                 while n?.el?
1126                         if n.type is 'text'
1127                                 n = n.parent
1128                                 continue
1129                         bounds = get_el_bounds n.el
1130                         return unless bounds?
1131                         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
1132                                 n = n.parent
1133                                 continue
1134                         ann_box = 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});
1135                         @overlay.appendChild ann_box
1136                         @matting.push ann_box
1137                         ann_tag = 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} "]
1138                         @overlay.appendChild ann_tag
1139                         @matting.push ann_tag
1140                         n = n.parent
1141                         alpha *= 1.5
1142         pretty_html: (tree, indent = '', parent_flags = pre_ish: false, block: true, want_nl: false) ->
1143                 ret = ''
1144                 want_nl = parent_flags.want_nl
1145                 prev_in_flow_is_text = false
1146                 prev_in_flow_is_block = false
1147                 for n, i in tree
1148                         # figure out flags
1149                         inner_flags = want_nl: true
1150                         is_br = false
1151                         switch n.type
1152                                 when 'tag'
1153                                         if n.name is 'br'
1154                                                 is_br = true
1155                                         is_text = false
1156                                         if n.el.currentStyle?
1157                                                 cs = n.el.currentStyle
1158                                                 whitespace = cs['white-space']
1159                                                 display = cs['display']
1160                                                 position = cs['position']
1161                                                 float = cs['float']
1162                                                 visibility = cs['visibility']
1163                                         else
1164                                                 cs = @iframe.contentWindow.getComputedStyle(n.el, null)
1165                                                 whitespace = cs.getPropertyValue 'white-space'
1166                                                 display = cs.getPropertyValue 'display'
1167                                                 position = cs.getPropertyValue 'position'
1168                                                 float = cs.getPropertyValue 'float'
1169                                                 visibility = cs.getPropertyValue 'visibility'
1170                                         if n.name is 'textarea'
1171                                                 inner_flags.pre_ish = true
1172                                         else
1173                                                 inner_flags.pre_ish = whitespace.substr(0, 3) is 'pre'
1174                                         switch float
1175                                                 when 'left', 'right'
1176                                                         in_flow = false
1177                                                 else
1178                                                         switch position
1179                                                                 when 'absolute', 'fixed'
1180                                                                         in_flow = false
1181                                                                 else
1182                                                                         if 'display' is 'none'
1183                                                                                 in_flow = false
1184                                                                         else
1185                                                                                 switch visibility
1186                                                                                         when 'hidden', 'collapse'
1187                                                                                                 in_flow = false
1188                                                                                         else # visible
1189                                                                                                 in_flow = true
1190                                         switch display
1191                                                 when 'inline', 'none'
1192                                                         inner_flags.block = false
1193                                                         is_block = in_flow_block = false
1194                                                 when 'inline-black'
1195                                                         inner_flags.block = true
1196                                                         is_block = in_flow_block = false
1197                                                 else # block, table, etc
1198                                                         inner_flags.block = true
1199                                                         is_block = true
1200                                                         in_flow_block = in_flow
1201                                 when 'text'
1202                                         is_text = true
1203                                         is_block = false
1204                                         in_flow = true
1205                                         in_flow_block = false
1206                                 else # 'comment', 'doctype'
1207                                         is_text = false
1208                                         is_block = false
1209                                         in_flow = false
1210                                         in_flow_block = false
1211                         # print whitespace if we can
1212                         unless parent_flags.pre_ish
1213                                 unless prev_in_flow_is_text and is_br
1214                                         if (i is 0 and parent_flags.block) or in_flow_block or prev_in_flow_is_block
1215                                                 if want_nl
1216                                                         ret += "\n"
1217                                                 ret += indent
1218                         switch n.type
1219                                 when 'tag'
1220                                         ret += '<' + n.name
1221                                         attr_keys = []
1222                                         for k of n.attrs
1223                                                 attr_keys.unshift k
1224                                         #attr_keys.sort()
1225                                         for k in attr_keys
1226                                                 ret += " #{k}"
1227                                                 if n.attrs[k].length > 0
1228                                                         ret += "=\"#{enc_attr n.attrs[k]}\""
1229                                         ret += '>'
1230                                         unless void_elements[n.name]?
1231                                                 if inner_flags.block
1232                                                         next_indent = indent + '    '
1233                                                 else
1234                                                         next_indent = indent
1235                                                 if n.children.length
1236                                                         ret += @pretty_html n.children, next_indent, inner_flags
1237                                                 ret += "</#{n.name}>"
1238                                 when 'text'
1239                                         ret += enc_text n.text
1240                                 when 'comment'
1241                                         ret += "<!--#{n.text}-->" # TODO encode?
1242                                 when 'doctype'
1243                                         ret += "<!DOCTYPE #{n.name}"
1244                                         if n.public_identifier? and n.public_identifier.length > 0
1245                                                 ret += " \"#{n.public_identifier}\""
1246                                         if n.system_identifier? and n.system_identifier.length > 0
1247                                                 ret += " \"#{n.system_identifier}\""
1248                                         ret += ">"
1249                         want_nl = true
1250                         if in_flow
1251                                 prev_in_flow_is_text = is_text
1252                                 prev_in_flow_is_block = is_block or (in_flow and is_br)
1253                 if tree.length
1254                         # output final newline if allowed
1255                         unless parent_flags.pre_ish
1256                                 if prev_in_flow_is_block or parent_flags.block
1257                                         ret += "\n#{indent.substr 4}"
1258                 return ret
1259         onblur: ->
1260                 @kill_cursor()
1261         have_focus: ->
1262                 @editor_is_focused = true
1263                 @poll_for_blur()
1264         poll_for_blur: ->
1265                 return if @poll_for_blur_timeout? # already polling
1266                 @poll_for_blur_timeout = timeout 150, =>
1267                         next_frame => # pause polling when browser knows we're not active/visible/etc.
1268                                 @poll_for_blur_timeout = null
1269                                 if document.activeElement is @outer_iframe
1270                                         @poll_for_blur()
1271                                 else
1272                                         @editor_is_focused = false
1273                                         @onblur()
1274
1275 window.peach_html5_editor = (args...) ->
1276         return new PeachHTML5Editor args...
1277
1278 # test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])