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