Subversion-Projekte lars-tiefland.cienc

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
5 lars 1
/**
2
 * Super simple wysiwyg editor v0.8.1
3
 * http://summernote.org/
4
 *
5
 * summernote.js
6
 * Copyright 2013-2015 Alan Hong. and other contributors
7
 * summernote may be freely distributed under the MIT license./
8
 *
9
 * Date: 2016-02-15T18:35Z
10
 */
11
(function (factory) {
12
  /* global define */
13
  if (typeof define === 'function' && define.amd) {
14
    // AMD. Register as an anonymous module.
15
    define(['jquery'], factory);
16
  } else if (typeof module === 'object' && module.exports) {
17
    // Node/CommonJS
18
    module.exports = factory(require('jquery'));
19
  } else {
20
    // Browser globals
21
    factory(window.jQuery);
22
  }
23
}(function ($) {
24
  'use strict';
25
 
26
  /**
27
   * @class core.func
28
   *
29
   * func utils (for high-order func's arg)
30
   *
31
   * @singleton
32
   * @alternateClassName func
33
   */
34
  var func = (function () {
35
    var eq = function (itemA) {
36
      return function (itemB) {
37
        return itemA === itemB;
38
      };
39
    };
40
 
41
    var eq2 = function (itemA, itemB) {
42
      return itemA === itemB;
43
    };
44
 
45
    var peq2 = function (propName) {
46
      return function (itemA, itemB) {
47
        return itemA[propName] === itemB[propName];
48
      };
49
    };
50
 
51
    var ok = function () {
52
      return true;
53
    };
54
 
55
    var fail = function () {
56
      return false;
57
    };
58
 
59
    var not = function (f) {
60
      return function () {
61
        return !f.apply(f, arguments);
62
      };
63
    };
64
 
65
    var and = function (fA, fB) {
66
      return function (item) {
67
        return fA(item) && fB(item);
68
      };
69
    };
70
 
71
    var self = function (a) {
72
      return a;
73
    };
74
 
75
    var invoke = function (obj, method) {
76
      return function () {
77
        return obj[method].apply(obj, arguments);
78
      };
79
    };
80
 
81
    var idCounter = 0;
82
 
83
    /**
84
     * generate a globally-unique id
85
     *
86
     * @param {String} [prefix]
87
     */
88
    var uniqueId = function (prefix) {
89
      var id = ++idCounter + '';
90
      return prefix ? prefix + id : id;
91
    };
92
 
93
    /**
94
     * returns bnd (bounds) from rect
95
     *
96
     * - IE Compatibility Issue: http://goo.gl/sRLOAo
97
     * - Scroll Issue: http://goo.gl/sNjUc
98
     *
99
     * @param {Rect} rect
100
     * @return {Object} bounds
101
     * @return {Number} bounds.top
102
     * @return {Number} bounds.left
103
     * @return {Number} bounds.width
104
     * @return {Number} bounds.height
105
     */
106
    var rect2bnd = function (rect) {
107
      var $document = $(document);
108
      return {
109
        top: rect.top + $document.scrollTop(),
110
        left: rect.left + $document.scrollLeft(),
111
        width: rect.right - rect.left,
112
        height: rect.bottom - rect.top
113
      };
114
    };
115
 
116
    /**
117
     * returns a copy of the object where the keys have become the values and the values the keys.
118
     * @param {Object} obj
119
     * @return {Object}
120
     */
121
    var invertObject = function (obj) {
122
      var inverted = {};
123
      for (var key in obj) {
124
        if (obj.hasOwnProperty(key)) {
125
          inverted[obj[key]] = key;
126
        }
127
      }
128
      return inverted;
129
    };
130
 
131
    /**
132
     * @param {String} namespace
133
     * @param {String} [prefix]
134
     * @return {String}
135
     */
136
    var namespaceToCamel = function (namespace, prefix) {
137
      prefix = prefix || '';
138
      return prefix + namespace.split('.').map(function (name) {
139
        return name.substring(0, 1).toUpperCase() + name.substring(1);
140
      }).join('');
141
    };
142
 
143
    return {
144
      eq: eq,
145
      eq2: eq2,
146
      peq2: peq2,
147
      ok: ok,
148
      fail: fail,
149
      self: self,
150
      not: not,
151
      and: and,
152
      invoke: invoke,
153
      uniqueId: uniqueId,
154
      rect2bnd: rect2bnd,
155
      invertObject: invertObject,
156
      namespaceToCamel: namespaceToCamel
157
    };
158
  })();
159
 
160
  /**
161
   * @class core.list
162
   *
163
   * list utils
164
   *
165
   * @singleton
166
   * @alternateClassName list
167
   */
168
  var list = (function () {
169
    /**
170
     * returns the first item of an array.
171
     *
172
     * @param {Array} array
173
     */
174
    var head = function (array) {
175
      return array[0];
176
    };
177
 
178
    /**
179
     * returns the last item of an array.
180
     *
181
     * @param {Array} array
182
     */
183
    var last = function (array) {
184
      return array[array.length - 1];
185
    };
186
 
187
    /**
188
     * returns everything but the last entry of the array.
189
     *
190
     * @param {Array} array
191
     */
192
    var initial = function (array) {
193
      return array.slice(0, array.length - 1);
194
    };
195
 
196
    /**
197
     * returns the rest of the items in an array.
198
     *
199
     * @param {Array} array
200
     */
201
    var tail = function (array) {
202
      return array.slice(1);
203
    };
204
 
205
    /**
206
     * returns item of array
207
     */
208
    var find = function (array, pred) {
209
      for (var idx = 0, len = array.length; idx < len; idx ++) {
210
        var item = array[idx];
211
        if (pred(item)) {
212
          return item;
213
        }
214
      }
215
    };
216
 
217
    /**
218
     * returns true if all of the values in the array pass the predicate truth test.
219
     */
220
    var all = function (array, pred) {
221
      for (var idx = 0, len = array.length; idx < len; idx ++) {
222
        if (!pred(array[idx])) {
223
          return false;
224
        }
225
      }
226
      return true;
227
    };
228
 
229
    /**
230
     * returns index of item
231
     */
232
    var indexOf = function (array, item) {
233
      return $.inArray(item, array);
234
    };
235
 
236
    /**
237
     * returns true if the value is present in the list.
238
     */
239
    var contains = function (array, item) {
240
      return indexOf(array, item) !== -1;
241
    };
242
 
243
    /**
244
     * get sum from a list
245
     *
246
     * @param {Array} array - array
247
     * @param {Function} fn - iterator
248
     */
249
    var sum = function (array, fn) {
250
      fn = fn || func.self;
251
      return array.reduce(function (memo, v) {
252
        return memo + fn(v);
253
      }, 0);
254
    };
255
 
256
    /**
257
     * returns a copy of the collection with array type.
258
     * @param {Collection} collection - collection eg) node.childNodes, ...
259
     */
260
    var from = function (collection) {
261
      var result = [], idx = -1, length = collection.length;
262
      while (++idx < length) {
263
        result[idx] = collection[idx];
264
      }
265
      return result;
266
    };
267
 
268
    /**
269
     * returns whether list is empty or not
270
     */
271
    var isEmpty = function (array) {
272
      return !array || !array.length;
273
    };
274
 
275
    /**
276
     * cluster elements by predicate function.
277
     *
278
     * @param {Array} array - array
279
     * @param {Function} fn - predicate function for cluster rule
280
     * @param {Array[]}
281
     */
282
    var clusterBy = function (array, fn) {
283
      if (!array.length) { return []; }
284
      var aTail = tail(array);
285
      return aTail.reduce(function (memo, v) {
286
        var aLast = last(memo);
287
        if (fn(last(aLast), v)) {
288
          aLast[aLast.length] = v;
289
        } else {
290
          memo[memo.length] = [v];
291
        }
292
        return memo;
293
      }, [[head(array)]]);
294
    };
295
 
296
    /**
297
     * returns a copy of the array with all falsy values removed
298
     *
299
     * @param {Array} array - array
300
     * @param {Function} fn - predicate function for cluster rule
301
     */
302
    var compact = function (array) {
303
      var aResult = [];
304
      for (var idx = 0, len = array.length; idx < len; idx ++) {
305
        if (array[idx]) { aResult.push(array[idx]); }
306
      }
307
      return aResult;
308
    };
309
 
310
    /**
311
     * produces a duplicate-free version of the array
312
     *
313
     * @param {Array} array
314
     */
315
    var unique = function (array) {
316
      var results = [];
317
 
318
      for (var idx = 0, len = array.length; idx < len; idx ++) {
319
        if (!contains(results, array[idx])) {
320
          results.push(array[idx]);
321
        }
322
      }
323
 
324
      return results;
325
    };
326
 
327
    /**
328
     * returns next item.
329
     * @param {Array} array
330
     */
331
    var next = function (array, item) {
332
      var idx = indexOf(array, item);
333
      if (idx === -1) { return null; }
334
 
335
      return array[idx + 1];
336
    };
337
 
338
    /**
339
     * returns prev item.
340
     * @param {Array} array
341
     */
342
    var prev = function (array, item) {
343
      var idx = indexOf(array, item);
344
      if (idx === -1) { return null; }
345
 
346
      return array[idx - 1];
347
    };
348
 
349
    return { head: head, last: last, initial: initial, tail: tail,
350
             prev: prev, next: next, find: find, contains: contains,
351
             all: all, sum: sum, from: from, isEmpty: isEmpty,
352
             clusterBy: clusterBy, compact: compact, unique: unique };
353
  })();
354
 
355
  var isSupportAmd = typeof define === 'function' && define.amd;
356
 
357
  /**
358
   * returns whether font is installed or not.
359
   *
360
   * @param {String} fontName
361
   * @return {Boolean}
362
   */
363
  var isFontInstalled = function (fontName) {
364
    var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS';
365
    var $tester = $('<div>').css({
366
      position: 'absolute',
367
      left: '-9999px',
368
      top: '-9999px',
369
      fontSize: '200px'
370
    }).text('mmmmmmmmmwwwwwww').appendTo(document.body);
371
 
372
    var originalWidth = $tester.css('fontFamily', testFontName).width();
373
    var width = $tester.css('fontFamily', fontName + ',' + testFontName).width();
374
 
375
    $tester.remove();
376
 
377
    return originalWidth !== width;
378
  };
379
 
380
  var userAgent = navigator.userAgent;
381
  var isMSIE = /MSIE|Trident/i.test(userAgent);
382
  var browserVersion;
383
  if (isMSIE) {
384
    var matches = /MSIE (\d+[.]\d+)/.exec(userAgent);
385
    if (matches) {
386
      browserVersion = parseFloat(matches[1]);
387
    }
388
    matches = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(userAgent);
389
    if (matches) {
390
      browserVersion = parseFloat(matches[1]);
391
    }
392
  }
393
 
394
  var isEdge = /Edge\/\d+/.test(userAgent);
395
 
396
  var hasCodeMirror = !!window.CodeMirror;
397
  if (!hasCodeMirror && isSupportAmd && require) {
398
    if (require.hasOwnProperty('resolve')) {
399
      try {
400
        // If CodeMirror can't be resolved, `require.resolve` will throw an
401
        // exception and `hasCodeMirror` won't be set to `true`.
402
        require.resolve('codemirror');
403
        hasCodeMirror = true;
404
      } catch (e) {
405
        hasCodeMirror = false;
406
      }
407
    } else if (require.hasOwnProperty('specified')) {
408
      hasCodeMirror = require.specified('codemirror');
409
    }
410
  }
411
 
412
  /**
413
   * @class core.agent
414
   *
415
   * Object which check platform and agent
416
   *
417
   * @singleton
418
   * @alternateClassName agent
419
   */
420
  var agent = {
421
    isMac: navigator.appVersion.indexOf('Mac') > -1,
422
    isMSIE: isMSIE,
423
    isEdge: isEdge,
424
    isFF: !isEdge && /firefox/i.test(userAgent),
425
    isPhantom: /PhantomJS/i.test(userAgent),
426
    isWebkit: !isEdge && /webkit/i.test(userAgent),
427
    isChrome: !isEdge && /chrome/i.test(userAgent),
428
    isSafari: !isEdge && /safari/i.test(userAgent),
429
    browserVersion: browserVersion,
430
    jqueryVersion: parseFloat($.fn.jquery),
431
    isSupportAmd: isSupportAmd,
432
    hasCodeMirror: hasCodeMirror,
433
    isFontInstalled: isFontInstalled,
434
    isW3CRangeSupport: !!document.createRange
435
  };
436
 
437
 
438
  var NBSP_CHAR = String.fromCharCode(160);
439
  var ZERO_WIDTH_NBSP_CHAR = '\ufeff';
440
 
441
  /**
442
   * @class core.dom
443
   *
444
   * Dom functions
445
   *
446
   * @singleton
447
   * @alternateClassName dom
448
   */
449
  var dom = (function () {
450
    /**
451
     * @method isEditable
452
     *
453
     * returns whether node is `note-editable` or not.
454
     *
455
     * @param {Node} node
456
     * @return {Boolean}
457
     */
458
    var isEditable = function (node) {
459
      return node && $(node).hasClass('note-editable');
460
    };
461
 
462
    /**
463
     * @method isControlSizing
464
     *
465
     * returns whether node is `note-control-sizing` or not.
466
     *
467
     * @param {Node} node
468
     * @return {Boolean}
469
     */
470
    var isControlSizing = function (node) {
471
      return node && $(node).hasClass('note-control-sizing');
472
    };
473
 
474
    /**
475
     * @method makePredByNodeName
476
     *
477
     * returns predicate which judge whether nodeName is same
478
     *
479
     * @param {String} nodeName
480
     * @return {Function}
481
     */
482
    var makePredByNodeName = function (nodeName) {
483
      nodeName = nodeName.toUpperCase();
484
      return function (node) {
485
        return node && node.nodeName.toUpperCase() === nodeName;
486
      };
487
    };
488
 
489
    /**
490
     * @method isText
491
     *
492
     *
493
     *
494
     * @param {Node} node
495
     * @return {Boolean} true if node's type is text(3)
496
     */
497
    var isText = function (node) {
498
      return node && node.nodeType === 3;
499
    };
500
 
501
    /**
502
     * @method isElement
503
     *
504
     *
505
     *
506
     * @param {Node} node
507
     * @return {Boolean} true if node's type is element(1)
508
     */
509
    var isElement = function (node) {
510
      return node && node.nodeType === 1;
511
    };
512
 
513
    /**
514
     * ex) br, col, embed, hr, img, input, ...
515
     * @see http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements
516
     */
517
    var isVoid = function (node) {
518
      return node && /^BR|^IMG|^HR|^IFRAME|^BUTTON/.test(node.nodeName.toUpperCase());
519
    };
520
 
521
    var isPara = function (node) {
522
      if (isEditable(node)) {
523
        return false;
524
      }
525
 
526
      // Chrome(v31.0), FF(v25.0.1) use DIV for paragraph
527
      return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName.toUpperCase());
528
    };
529
 
530
    var isHeading = function (node) {
531
      return node && /^H[1-7]/.test(node.nodeName.toUpperCase());
532
    };
533
 
534
    var isPre = makePredByNodeName('PRE');
535
 
536
    var isLi = makePredByNodeName('LI');
537
 
538
    var isPurePara = function (node) {
539
      return isPara(node) && !isLi(node);
540
    };
541
 
542
    var isTable = makePredByNodeName('TABLE');
543
 
544
    var isInline = function (node) {
545
      return !isBodyContainer(node) &&
546
             !isList(node) &&
547
             !isHr(node) &&
548
             !isPara(node) &&
549
             !isTable(node) &&
550
             !isBlockquote(node);
551
    };
552
 
553
    var isList = function (node) {
554
      return node && /^UL|^OL/.test(node.nodeName.toUpperCase());
555
    };
556
 
557
    var isHr = makePredByNodeName('HR');
558
 
559
    var isCell = function (node) {
560
      return node && /^TD|^TH/.test(node.nodeName.toUpperCase());
561
    };
562
 
563
    var isBlockquote = makePredByNodeName('BLOCKQUOTE');
564
 
565
    var isBodyContainer = function (node) {
566
      return isCell(node) || isBlockquote(node) || isEditable(node);
567
    };
568
 
569
    var isAnchor = makePredByNodeName('A');
570
 
571
    var isParaInline = function (node) {
572
      return isInline(node) && !!ancestor(node, isPara);
573
    };
574
 
575
    var isBodyInline = function (node) {
576
      return isInline(node) && !ancestor(node, isPara);
577
    };
578
 
579
    var isBody = makePredByNodeName('BODY');
580
 
581
    /**
582
     * returns whether nodeB is closest sibling of nodeA
583
     *
584
     * @param {Node} nodeA
585
     * @param {Node} nodeB
586
     * @return {Boolean}
587
     */
588
    var isClosestSibling = function (nodeA, nodeB) {
589
      return nodeA.nextSibling === nodeB ||
590
             nodeA.previousSibling === nodeB;
591
    };
592
 
593
    /**
594
     * returns array of closest siblings with node
595
     *
596
     * @param {Node} node
597
     * @param {function} [pred] - predicate function
598
     * @return {Node[]}
599
     */
600
    var withClosestSiblings = function (node, pred) {
601
      pred = pred || func.ok;
602
 
603
      var siblings = [];
604
      if (node.previousSibling && pred(node.previousSibling)) {
605
        siblings.push(node.previousSibling);
606
      }
607
      siblings.push(node);
608
      if (node.nextSibling && pred(node.nextSibling)) {
609
        siblings.push(node.nextSibling);
610
      }
611
      return siblings;
612
    };
613
 
614
    /**
615
     * blank HTML for cursor position
616
     * - [workaround] old IE only works with &nbsp;
617
     * - [workaround] IE11 and other browser works with bogus br
618
     */
619
    var blankHTML = agent.isMSIE && agent.browserVersion < 11 ? '&nbsp;' : '<br>';
620
 
621
    /**
622
     * @method nodeLength
623
     *
624
     * returns #text's text size or element's childNodes size
625
     *
626
     * @param {Node} node
627
     */
628
    var nodeLength = function (node) {
629
      if (isText(node)) {
630
        return node.nodeValue.length;
631
      }
632
 
633
      return node.childNodes.length;
634
    };
635
 
636
    /**
637
     * returns whether node is empty or not.
638
     *
639
     * @param {Node} node
640
     * @return {Boolean}
641
     */
642
    var isEmpty = function (node) {
643
      var len = nodeLength(node);
644
 
645
      if (len === 0) {
646
        return true;
647
      } else if (!isText(node) && len === 1 && node.innerHTML === blankHTML) {
648
        // ex) <p><br></p>, <span><br></span>
649
        return true;
650
      } else if (list.all(node.childNodes, isText) && node.innerHTML === '') {
651
        // ex) <p></p>, <span></span>
652
        return true;
653
      }
654
 
655
      return false;
656
    };
657
 
658
    /**
659
     * padding blankHTML if node is empty (for cursor position)
660
     */
661
    var paddingBlankHTML = function (node) {
662
      if (!isVoid(node) && !nodeLength(node)) {
663
        node.innerHTML = blankHTML;
664
      }
665
    };
666
 
667
    /**
668
     * find nearest ancestor predicate hit
669
     *
670
     * @param {Node} node
671
     * @param {Function} pred - predicate function
672
     */
673
    var ancestor = function (node, pred) {
674
      while (node) {
675
        if (pred(node)) { return node; }
676
        if (isEditable(node)) { break; }
677
 
678
        node = node.parentNode;
679
      }
680
      return null;
681
    };
682
 
683
    /**
684
     * find nearest ancestor only single child blood line and predicate hit
685
     *
686
     * @param {Node} node
687
     * @param {Function} pred - predicate function
688
     */
689
    var singleChildAncestor = function (node, pred) {
690
      node = node.parentNode;
691
 
692
      while (node) {
693
        if (nodeLength(node) !== 1) { break; }
694
        if (pred(node)) { return node; }
695
        if (isEditable(node)) { break; }
696
 
697
        node = node.parentNode;
698
      }
699
      return null;
700
    };
701
 
702
    /**
703
     * returns new array of ancestor nodes (until predicate hit).
704
     *
705
     * @param {Node} node
706
     * @param {Function} [optional] pred - predicate function
707
     */
708
    var listAncestor = function (node, pred) {
709
      pred = pred || func.fail;
710
 
711
      var ancestors = [];
712
      ancestor(node, function (el) {
713
        if (!isEditable(el)) {
714
          ancestors.push(el);
715
        }
716
 
717
        return pred(el);
718
      });
719
      return ancestors;
720
    };
721
 
722
    /**
723
     * find farthest ancestor predicate hit
724
     */
725
    var lastAncestor = function (node, pred) {
726
      var ancestors = listAncestor(node);
727
      return list.last(ancestors.filter(pred));
728
    };
729
 
730
    /**
731
     * returns common ancestor node between two nodes.
732
     *
733
     * @param {Node} nodeA
734
     * @param {Node} nodeB
735
     */
736
    var commonAncestor = function (nodeA, nodeB) {
737
      var ancestors = listAncestor(nodeA);
738
      for (var n = nodeB; n; n = n.parentNode) {
739
        if ($.inArray(n, ancestors) > -1) { return n; }
740
      }
741
      return null; // difference document area
742
    };
743
 
744
    /**
745
     * listing all previous siblings (until predicate hit).
746
     *
747
     * @param {Node} node
748
     * @param {Function} [optional] pred - predicate function
749
     */
750
    var listPrev = function (node, pred) {
751
      pred = pred || func.fail;
752
 
753
      var nodes = [];
754
      while (node) {
755
        if (pred(node)) { break; }
756
        nodes.push(node);
757
        node = node.previousSibling;
758
      }
759
      return nodes;
760
    };
761
 
762
    /**
763
     * listing next siblings (until predicate hit).
764
     *
765
     * @param {Node} node
766
     * @param {Function} [pred] - predicate function
767
     */
768
    var listNext = function (node, pred) {
769
      pred = pred || func.fail;
770
 
771
      var nodes = [];
772
      while (node) {
773
        if (pred(node)) { break; }
774
        nodes.push(node);
775
        node = node.nextSibling;
776
      }
777
      return nodes;
778
    };
779
 
780
    /**
781
     * listing descendant nodes
782
     *
783
     * @param {Node} node
784
     * @param {Function} [pred] - predicate function
785
     */
786
    var listDescendant = function (node, pred) {
787
      var descendants = [];
788
      pred = pred || func.ok;
789
 
790
      // start DFS(depth first search) with node
791
      (function fnWalk(current) {
792
        if (node !== current && pred(current)) {
793
          descendants.push(current);
794
        }
795
        for (var idx = 0, len = current.childNodes.length; idx < len; idx++) {
796
          fnWalk(current.childNodes[idx]);
797
        }
798
      })(node);
799
 
800
      return descendants;
801
    };
802
 
803
    /**
804
     * wrap node with new tag.
805
     *
806
     * @param {Node} node
807
     * @param {Node} tagName of wrapper
808
     * @return {Node} - wrapper
809
     */
810
    var wrap = function (node, wrapperName) {
811
      var parent = node.parentNode;
812
      var wrapper = $('<' + wrapperName + '>')[0];
813
 
814
      parent.insertBefore(wrapper, node);
815
      wrapper.appendChild(node);
816
 
817
      return wrapper;
818
    };
819
 
820
    /**
821
     * insert node after preceding
822
     *
823
     * @param {Node} node
824
     * @param {Node} preceding - predicate function
825
     */
826
    var insertAfter = function (node, preceding) {
827
      var next = preceding.nextSibling, parent = preceding.parentNode;
828
      if (next) {
829
        parent.insertBefore(node, next);
830
      } else {
831
        parent.appendChild(node);
832
      }
833
      return node;
834
    };
835
 
836
    /**
837
     * append elements.
838
     *
839
     * @param {Node} node
840
     * @param {Collection} aChild
841
     */
842
    var appendChildNodes = function (node, aChild) {
843
      $.each(aChild, function (idx, child) {
844
        node.appendChild(child);
845
      });
846
      return node;
847
    };
848
 
849
    /**
850
     * returns whether boundaryPoint is left edge or not.
851
     *
852
     * @param {BoundaryPoint} point
853
     * @return {Boolean}
854
     */
855
    var isLeftEdgePoint = function (point) {
856
      return point.offset === 0;
857
    };
858
 
859
    /**
860
     * returns whether boundaryPoint is right edge or not.
861
     *
862
     * @param {BoundaryPoint} point
863
     * @return {Boolean}
864
     */
865
    var isRightEdgePoint = function (point) {
866
      return point.offset === nodeLength(point.node);
867
    };
868
 
869
    /**
870
     * returns whether boundaryPoint is edge or not.
871
     *
872
     * @param {BoundaryPoint} point
873
     * @return {Boolean}
874
     */
875
    var isEdgePoint = function (point) {
876
      return isLeftEdgePoint(point) || isRightEdgePoint(point);
877
    };
878
 
879
    /**
880
     * returns whether node is left edge of ancestor or not.
881
     *
882
     * @param {Node} node
883
     * @param {Node} ancestor
884
     * @return {Boolean}
885
     */
886
    var isLeftEdgeOf = function (node, ancestor) {
887
      while (node && node !== ancestor) {
888
        if (position(node) !== 0) {
889
          return false;
890
        }
891
        node = node.parentNode;
892
      }
893
 
894
      return true;
895
    };
896
 
897
    /**
898
     * returns whether node is right edge of ancestor or not.
899
     *
900
     * @param {Node} node
901
     * @param {Node} ancestor
902
     * @return {Boolean}
903
     */
904
    var isRightEdgeOf = function (node, ancestor) {
905
      while (node && node !== ancestor) {
906
        if (position(node) !== nodeLength(node.parentNode) - 1) {
907
          return false;
908
        }
909
        node = node.parentNode;
910
      }
911
 
912
      return true;
913
    };
914
 
915
    /**
916
     * returns whether point is left edge of ancestor or not.
917
     * @param {BoundaryPoint} point
918
     * @param {Node} ancestor
919
     * @return {Boolean}
920
     */
921
    var isLeftEdgePointOf = function (point, ancestor) {
922
      return isLeftEdgePoint(point) && isLeftEdgeOf(point.node, ancestor);
923
    };
924
 
925
    /**
926
     * returns whether point is right edge of ancestor or not.
927
     * @param {BoundaryPoint} point
928
     * @param {Node} ancestor
929
     * @return {Boolean}
930
     */
931
    var isRightEdgePointOf = function (point, ancestor) {
932
      return isRightEdgePoint(point) && isRightEdgeOf(point.node, ancestor);
933
    };
934
 
935
    /**
936
     * returns offset from parent.
937
     *
938
     * @param {Node} node
939
     */
940
    var position = function (node) {
941
      var offset = 0;
942
      while ((node = node.previousSibling)) {
943
        offset += 1;
944
      }
945
      return offset;
946
    };
947
 
948
    var hasChildren = function (node) {
949
      return !!(node && node.childNodes && node.childNodes.length);
950
    };
951
 
952
    /**
953
     * returns previous boundaryPoint
954
     *
955
     * @param {BoundaryPoint} point
956
     * @param {Boolean} isSkipInnerOffset
957
     * @return {BoundaryPoint}
958
     */
959
    var prevPoint = function (point, isSkipInnerOffset) {
960
      var node, offset;
961
 
962
      if (point.offset === 0) {
963
        if (isEditable(point.node)) {
964
          return null;
965
        }
966
 
967
        node = point.node.parentNode;
968
        offset = position(point.node);
969
      } else if (hasChildren(point.node)) {
970
        node = point.node.childNodes[point.offset - 1];
971
        offset = nodeLength(node);
972
      } else {
973
        node = point.node;
974
        offset = isSkipInnerOffset ? 0 : point.offset - 1;
975
      }
976
 
977
      return {
978
        node: node,
979
        offset: offset
980
      };
981
    };
982
 
983
    /**
984
     * returns next boundaryPoint
985
     *
986
     * @param {BoundaryPoint} point
987
     * @param {Boolean} isSkipInnerOffset
988
     * @return {BoundaryPoint}
989
     */
990
    var nextPoint = function (point, isSkipInnerOffset) {
991
      var node, offset;
992
 
993
      if (nodeLength(point.node) === point.offset) {
994
        if (isEditable(point.node)) {
995
          return null;
996
        }
997
 
998
        node = point.node.parentNode;
999
        offset = position(point.node) + 1;
1000
      } else if (hasChildren(point.node)) {
1001
        node = point.node.childNodes[point.offset];
1002
        offset = 0;
1003
      } else {
1004
        node = point.node;
1005
        offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1;
1006
      }
1007
 
1008
      return {
1009
        node: node,
1010
        offset: offset
1011
      };
1012
    };
1013
 
1014
    /**
1015
     * returns whether pointA and pointB is same or not.
1016
     *
1017
     * @param {BoundaryPoint} pointA
1018
     * @param {BoundaryPoint} pointB
1019
     * @return {Boolean}
1020
     */
1021
    var isSamePoint = function (pointA, pointB) {
1022
      return pointA.node === pointB.node && pointA.offset === pointB.offset;
1023
    };
1024
 
1025
    /**
1026
     * returns whether point is visible (can set cursor) or not.
1027
     *
1028
     * @param {BoundaryPoint} point
1029
     * @return {Boolean}
1030
     */
1031
    var isVisiblePoint = function (point) {
1032
      if (isText(point.node) || !hasChildren(point.node) || isEmpty(point.node)) {
1033
        return true;
1034
      }
1035
 
1036
      var leftNode = point.node.childNodes[point.offset - 1];
1037
      var rightNode = point.node.childNodes[point.offset];
1038
      if ((!leftNode || isVoid(leftNode)) && (!rightNode || isVoid(rightNode))) {
1039
        return true;
1040
      }
1041
 
1042
      return false;
1043
    };
1044
 
1045
    /**
1046
     * @method prevPointUtil
1047
     *
1048
     * @param {BoundaryPoint} point
1049
     * @param {Function} pred
1050
     * @return {BoundaryPoint}
1051
     */
1052
    var prevPointUntil = function (point, pred) {
1053
      while (point) {
1054
        if (pred(point)) {
1055
          return point;
1056
        }
1057
 
1058
        point = prevPoint(point);
1059
      }
1060
 
1061
      return null;
1062
    };
1063
 
1064
    /**
1065
     * @method nextPointUntil
1066
     *
1067
     * @param {BoundaryPoint} point
1068
     * @param {Function} pred
1069
     * @return {BoundaryPoint}
1070
     */
1071
    var nextPointUntil = function (point, pred) {
1072
      while (point) {
1073
        if (pred(point)) {
1074
          return point;
1075
        }
1076
 
1077
        point = nextPoint(point);
1078
      }
1079
 
1080
      return null;
1081
    };
1082
 
1083
    /**
1084
     * returns whether point has character or not.
1085
     *
1086
     * @param {Point} point
1087
     * @return {Boolean}
1088
     */
1089
    var isCharPoint = function (point) {
1090
      if (!isText(point.node)) {
1091
        return false;
1092
      }
1093
 
1094
      var ch = point.node.nodeValue.charAt(point.offset - 1);
1095
      return ch && (ch !== ' ' && ch !== NBSP_CHAR);
1096
    };
1097
 
1098
    /**
1099
     * @method walkPoint
1100
     *
1101
     * @param {BoundaryPoint} startPoint
1102
     * @param {BoundaryPoint} endPoint
1103
     * @param {Function} handler
1104
     * @param {Boolean} isSkipInnerOffset
1105
     */
1106
    var walkPoint = function (startPoint, endPoint, handler, isSkipInnerOffset) {
1107
      var point = startPoint;
1108
 
1109
      while (point) {
1110
        handler(point);
1111
 
1112
        if (isSamePoint(point, endPoint)) {
1113
          break;
1114
        }
1115
 
1116
        var isSkipOffset = isSkipInnerOffset &&
1117
                           startPoint.node !== point.node &&
1118
                           endPoint.node !== point.node;
1119
        point = nextPoint(point, isSkipOffset);
1120
      }
1121
    };
1122
 
1123
    /**
1124
     * @method makeOffsetPath
1125
     *
1126
     * return offsetPath(array of offset) from ancestor
1127
     *
1128
     * @param {Node} ancestor - ancestor node
1129
     * @param {Node} node
1130
     */
1131
    var makeOffsetPath = function (ancestor, node) {
1132
      var ancestors = listAncestor(node, func.eq(ancestor));
1133
      return ancestors.map(position).reverse();
1134
    };
1135
 
1136
    /**
1137
     * @method fromOffsetPath
1138
     *
1139
     * return element from offsetPath(array of offset)
1140
     *
1141
     * @param {Node} ancestor - ancestor node
1142
     * @param {array} offsets - offsetPath
1143
     */
1144
    var fromOffsetPath = function (ancestor, offsets) {
1145
      var current = ancestor;
1146
      for (var i = 0, len = offsets.length; i < len; i++) {
1147
        if (current.childNodes.length <= offsets[i]) {
1148
          current = current.childNodes[current.childNodes.length - 1];
1149
        } else {
1150
          current = current.childNodes[offsets[i]];
1151
        }
1152
      }
1153
      return current;
1154
    };
1155
 
1156
    /**
1157
     * @method splitNode
1158
     *
1159
     * split element or #text
1160
     *
1161
     * @param {BoundaryPoint} point
1162
     * @param {Object} [options]
1163
     * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false
1164
     * @param {Boolean} [options.isNotSplitEdgePoint] - default: false
1165
     * @return {Node} right node of boundaryPoint
1166
     */
1167
    var splitNode = function (point, options) {
1168
      var isSkipPaddingBlankHTML = options && options.isSkipPaddingBlankHTML;
1169
      var isNotSplitEdgePoint = options && options.isNotSplitEdgePoint;
1170
 
1171
      // edge case
1172
      if (isEdgePoint(point) && (isText(point.node) || isNotSplitEdgePoint)) {
1173
        if (isLeftEdgePoint(point)) {
1174
          return point.node;
1175
        } else if (isRightEdgePoint(point)) {
1176
          return point.node.nextSibling;
1177
        }
1178
      }
1179
 
1180
      // split #text
1181
      if (isText(point.node)) {
1182
        return point.node.splitText(point.offset);
1183
      } else {
1184
        var childNode = point.node.childNodes[point.offset];
1185
        var clone = insertAfter(point.node.cloneNode(false), point.node);
1186
        appendChildNodes(clone, listNext(childNode));
1187
 
1188
        if (!isSkipPaddingBlankHTML) {
1189
          paddingBlankHTML(point.node);
1190
          paddingBlankHTML(clone);
1191
        }
1192
 
1193
        return clone;
1194
      }
1195
    };
1196
 
1197
    /**
1198
     * @method splitTree
1199
     *
1200
     * split tree by point
1201
     *
1202
     * @param {Node} root - split root
1203
     * @param {BoundaryPoint} point
1204
     * @param {Object} [options]
1205
     * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false
1206
     * @param {Boolean} [options.isNotSplitEdgePoint] - default: false
1207
     * @return {Node} right node of boundaryPoint
1208
     */
1209
    var splitTree = function (root, point, options) {
1210
      // ex) [#text, <span>, <p>]
1211
      var ancestors = listAncestor(point.node, func.eq(root));
1212
 
1213
      if (!ancestors.length) {
1214
        return null;
1215
      } else if (ancestors.length === 1) {
1216
        return splitNode(point, options);
1217
      }
1218
 
1219
      return ancestors.reduce(function (node, parent) {
1220
        if (node === point.node) {
1221
          node = splitNode(point, options);
1222
        }
1223
 
1224
        return splitNode({
1225
          node: parent,
1226
          offset: node ? dom.position(node) : nodeLength(parent)
1227
        }, options);
1228
      });
1229
    };
1230
 
1231
    /**
1232
     * split point
1233
     *
1234
     * @param {Point} point
1235
     * @param {Boolean} isInline
1236
     * @return {Object}
1237
     */
1238
    var splitPoint = function (point, isInline) {
1239
      // find splitRoot, container
1240
      //  - inline: splitRoot is a child of paragraph
1241
      //  - block: splitRoot is a child of bodyContainer
1242
      var pred = isInline ? isPara : isBodyContainer;
1243
      var ancestors = listAncestor(point.node, pred);
1244
      var topAncestor = list.last(ancestors) || point.node;
1245
 
1246
      var splitRoot, container;
1247
      if (pred(topAncestor)) {
1248
        splitRoot = ancestors[ancestors.length - 2];
1249
        container = topAncestor;
1250
      } else {
1251
        splitRoot = topAncestor;
1252
        container = splitRoot.parentNode;
1253
      }
1254
 
1255
      // if splitRoot is exists, split with splitTree
1256
      var pivot = splitRoot && splitTree(splitRoot, point, {
1257
        isSkipPaddingBlankHTML: isInline,
1258
        isNotSplitEdgePoint: isInline
1259
      });
1260
 
1261
      // if container is point.node, find pivot with point.offset
1262
      if (!pivot && container === point.node) {
1263
        pivot = point.node.childNodes[point.offset];
1264
      }
1265
 
1266
      return {
1267
        rightNode: pivot,
1268
        container: container
1269
      };
1270
    };
1271
 
1272
    var create = function (nodeName) {
1273
      return document.createElement(nodeName);
1274
    };
1275
 
1276
    var createText = function (text) {
1277
      return document.createTextNode(text);
1278
    };
1279
 
1280
    /**
1281
     * @method remove
1282
     *
1283
     * remove node, (isRemoveChild: remove child or not)
1284
     *
1285
     * @param {Node} node
1286
     * @param {Boolean} isRemoveChild
1287
     */
1288
    var remove = function (node, isRemoveChild) {
1289
      if (!node || !node.parentNode) { return; }
1290
      if (node.removeNode) { return node.removeNode(isRemoveChild); }
1291
 
1292
      var parent = node.parentNode;
1293
      if (!isRemoveChild) {
1294
        var nodes = [];
1295
        var i, len;
1296
        for (i = 0, len = node.childNodes.length; i < len; i++) {
1297
          nodes.push(node.childNodes[i]);
1298
        }
1299
 
1300
        for (i = 0, len = nodes.length; i < len; i++) {
1301
          parent.insertBefore(nodes[i], node);
1302
        }
1303
      }
1304
 
1305
      parent.removeChild(node);
1306
    };
1307
 
1308
    /**
1309
     * @method removeWhile
1310
     *
1311
     * @param {Node} node
1312
     * @param {Function} pred
1313
     */
1314
    var removeWhile = function (node, pred) {
1315
      while (node) {
1316
        if (isEditable(node) || !pred(node)) {
1317
          break;
1318
        }
1319
 
1320
        var parent = node.parentNode;
1321
        remove(node);
1322
        node = parent;
1323
      }
1324
    };
1325
 
1326
    /**
1327
     * @method replace
1328
     *
1329
     * replace node with provided nodeName
1330
     *
1331
     * @param {Node} node
1332
     * @param {String} nodeName
1333
     * @return {Node} - new node
1334
     */
1335
    var replace = function (node, nodeName) {
1336
      if (node.nodeName.toUpperCase() === nodeName.toUpperCase()) {
1337
        return node;
1338
      }
1339
 
1340
      var newNode = create(nodeName);
1341
 
1342
      if (node.style.cssText) {
1343
        newNode.style.cssText = node.style.cssText;
1344
      }
1345
 
1346
      appendChildNodes(newNode, list.from(node.childNodes));
1347
      insertAfter(newNode, node);
1348
      remove(node);
1349
 
1350
      return newNode;
1351
    };
1352
 
1353
    var isTextarea = makePredByNodeName('TEXTAREA');
1354
 
1355
    /**
1356
     * @param {jQuery} $node
1357
     * @param {Boolean} [stripLinebreaks] - default: false
1358
     */
1359
    var value = function ($node, stripLinebreaks) {
1360
      var val = isTextarea($node[0]) ? $node.val() : $node.html();
1361
      if (stripLinebreaks) {
1362
        return val.replace(/[\n\r]/g, '');
1363
      }
1364
      return val;
1365
    };
1366
 
1367
    /**
1368
     * @method html
1369
     *
1370
     * get the HTML contents of node
1371
     *
1372
     * @param {jQuery} $node
1373
     * @param {Boolean} [isNewlineOnBlock]
1374
     */
1375
    var html = function ($node, isNewlineOnBlock) {
1376
      var markup = value($node);
1377
 
1378
      if (isNewlineOnBlock) {
1379
        var regexTag = /<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g;
1380
        markup = markup.replace(regexTag, function (match, endSlash, name) {
1381
          name = name.toUpperCase();
1382
          var isEndOfInlineContainer = /^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(name) &&
1383
                                       !!endSlash;
1384
          var isBlockNode = /^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(name);
1385
 
1386
          return match + ((isEndOfInlineContainer || isBlockNode) ? '\n' : '');
1387
        });
1388
        markup = $.trim(markup);
1389
      }
1390
 
1391
      return markup;
1392
    };
1393
 
1394
    var posFromPlaceholder = function (placeholder) {
1395
      var $placeholder = $(placeholder);
1396
      var pos = $placeholder.offset();
1397
      var height = $placeholder.outerHeight(true); // include margin
1398
 
1399
      return {
1400
        left: pos.left,
1401
        top: pos.top + height
1402
      };
1403
    };
1404
 
1405
    var attachEvents = function ($node, events) {
1406
      Object.keys(events).forEach(function (key) {
1407
        $node.on(key, events[key]);
1408
      });
1409
    };
1410
 
1411
    var detachEvents = function ($node, events) {
1412
      Object.keys(events).forEach(function (key) {
1413
        $node.off(key, events[key]);
1414
      });
1415
    };
1416
 
1417
    return {
1418
      /** @property {String} NBSP_CHAR */
1419
      NBSP_CHAR: NBSP_CHAR,
1420
      /** @property {String} ZERO_WIDTH_NBSP_CHAR */
1421
      ZERO_WIDTH_NBSP_CHAR: ZERO_WIDTH_NBSP_CHAR,
1422
      /** @property {String} blank */
1423
      blank: blankHTML,
1424
      /** @property {String} emptyPara */
1425
      emptyPara: '<p>' + blankHTML + '</p>',
1426
      makePredByNodeName: makePredByNodeName,
1427
      isEditable: isEditable,
1428
      isControlSizing: isControlSizing,
1429
      isText: isText,
1430
      isElement: isElement,
1431
      isVoid: isVoid,
1432
      isPara: isPara,
1433
      isPurePara: isPurePara,
1434
      isHeading: isHeading,
1435
      isInline: isInline,
1436
      isBlock: func.not(isInline),
1437
      isBodyInline: isBodyInline,
1438
      isBody: isBody,
1439
      isParaInline: isParaInline,
1440
      isPre: isPre,
1441
      isList: isList,
1442
      isTable: isTable,
1443
      isCell: isCell,
1444
      isBlockquote: isBlockquote,
1445
      isBodyContainer: isBodyContainer,
1446
      isAnchor: isAnchor,
1447
      isDiv: makePredByNodeName('DIV'),
1448
      isLi: isLi,
1449
      isBR: makePredByNodeName('BR'),
1450
      isSpan: makePredByNodeName('SPAN'),
1451
      isB: makePredByNodeName('B'),
1452
      isU: makePredByNodeName('U'),
1453
      isS: makePredByNodeName('S'),
1454
      isI: makePredByNodeName('I'),
1455
      isImg: makePredByNodeName('IMG'),
1456
      isTextarea: isTextarea,
1457
      isEmpty: isEmpty,
1458
      isEmptyAnchor: func.and(isAnchor, isEmpty),
1459
      isClosestSibling: isClosestSibling,
1460
      withClosestSiblings: withClosestSiblings,
1461
      nodeLength: nodeLength,
1462
      isLeftEdgePoint: isLeftEdgePoint,
1463
      isRightEdgePoint: isRightEdgePoint,
1464
      isEdgePoint: isEdgePoint,
1465
      isLeftEdgeOf: isLeftEdgeOf,
1466
      isRightEdgeOf: isRightEdgeOf,
1467
      isLeftEdgePointOf: isLeftEdgePointOf,
1468
      isRightEdgePointOf: isRightEdgePointOf,
1469
      prevPoint: prevPoint,
1470
      nextPoint: nextPoint,
1471
      isSamePoint: isSamePoint,
1472
      isVisiblePoint: isVisiblePoint,
1473
      prevPointUntil: prevPointUntil,
1474
      nextPointUntil: nextPointUntil,
1475
      isCharPoint: isCharPoint,
1476
      walkPoint: walkPoint,
1477
      ancestor: ancestor,
1478
      singleChildAncestor: singleChildAncestor,
1479
      listAncestor: listAncestor,
1480
      lastAncestor: lastAncestor,
1481
      listNext: listNext,
1482
      listPrev: listPrev,
1483
      listDescendant: listDescendant,
1484
      commonAncestor: commonAncestor,
1485
      wrap: wrap,
1486
      insertAfter: insertAfter,
1487
      appendChildNodes: appendChildNodes,
1488
      position: position,
1489
      hasChildren: hasChildren,
1490
      makeOffsetPath: makeOffsetPath,
1491
      fromOffsetPath: fromOffsetPath,
1492
      splitTree: splitTree,
1493
      splitPoint: splitPoint,
1494
      create: create,
1495
      createText: createText,
1496
      remove: remove,
1497
      removeWhile: removeWhile,
1498
      replace: replace,
1499
      html: html,
1500
      value: value,
1501
      posFromPlaceholder: posFromPlaceholder,
1502
      attachEvents: attachEvents,
1503
      detachEvents: detachEvents
1504
    };
1505
  })();
1506
 
1507
  /**
1508
   * @param {jQuery} $note
1509
   * @param {Object} options
1510
   * @return {Context}
1511
   */
1512
  var Context = function ($note, options) {
1513
    var self = this;
1514
 
1515
    var ui = $.summernote.ui;
1516
    this.memos = {};
1517
    this.modules = {};
1518
    this.layoutInfo = {};
1519
    this.options = options;
1520
 
1521
    /**
1522
     * create layout and initialize modules and other resources
1523
     */
1524
    this.initialize = function () {
1525
      this.layoutInfo = ui.createLayout($note, options);
1526
      this._initialize();
1527
      $note.hide();
1528
      return this;
1529
    };
1530
 
1531
    /**
1532
     * destroy modules and other resources and remove layout
1533
     */
1534
    this.destroy = function () {
1535
      this._destroy();
1536
      $note.removeData('summernote');
1537
      ui.removeLayout($note, this.layoutInfo);
1538
    };
1539
 
1540
    /**
1541
     * destory modules and other resources and initialize it again
1542
     */
1543
    this.reset = function () {
1544
      var disabled = self.isDisabled();
1545
      this.code(dom.emptyPara);
1546
      this._destroy();
1547
      this._initialize();
1548
 
1549
      if (disabled) {
1550
        self.disable();
1551
      }
1552
    };
1553
 
1554
    this._initialize = function () {
1555
      // add optional buttons
1556
      var buttons = $.extend({}, this.options.buttons);
1557
      Object.keys(buttons).forEach(function (key) {
1558
        self.memo('button.' + key, buttons[key]);
1559
      });
1560
 
1561
      var modules = $.extend({}, this.options.modules, $.summernote.plugins || {});
1562
 
1563
      // add and initialize modules
1564
      Object.keys(modules).forEach(function (key) {
1565
        self.module(key, modules[key], true);
1566
      });
1567
 
1568
      Object.keys(this.modules).forEach(function (key) {
1569
        self.initializeModule(key);
1570
      });
1571
    };
1572
 
1573
    this._destroy = function () {
1574
      // destroy modules with reversed order
1575
      Object.keys(this.modules).reverse().forEach(function (key) {
1576
        self.removeModule(key);
1577
      });
1578
 
1579
      Object.keys(this.memos).forEach(function (key) {
1580
        self.removeMemo(key);
1581
      });
1582
    };
1583
 
1584
    this.code = function (html) {
1585
      var isActivated = this.invoke('codeview.isActivated');
1586
 
1587
      if (html === undefined) {
1588
        this.invoke('codeview.sync');
1589
        return isActivated ? this.layoutInfo.codable.val() : this.layoutInfo.editable.html();
1590
      } else {
1591
        if (isActivated) {
1592
          this.layoutInfo.codable.val(html);
1593
        } else {
1594
          this.layoutInfo.editable.html(html);
1595
        }
1596
        $note.val(html);
1597
        this.triggerEvent('change', html);
1598
      }
1599
    };
1600
 
1601
    this.isDisabled = function () {
1602
      return this.layoutInfo.editable.attr('contenteditable') === 'false';
1603
    };
1604
 
1605
    this.enable = function () {
1606
      this.layoutInfo.editable.attr('contenteditable', true);
1607
      this.invoke('toolbar.activate', true);
1608
    };
1609
 
1610
    this.disable = function () {
1611
      // close codeview if codeview is opend
1612
      if (this.invoke('codeview.isActivated')) {
1613
        this.invoke('codeview.deactivate');
1614
      }
1615
      this.layoutInfo.editable.attr('contenteditable', false);
1616
      this.invoke('toolbar.deactivate', true);
1617
    };
1618
 
1619
    this.triggerEvent = function () {
1620
      var namespace = list.head(arguments);
1621
      var args = list.tail(list.from(arguments));
1622
 
1623
      var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')];
1624
      if (callback) {
1625
        callback.apply($note[0], args);
1626
      }
1627
      $note.trigger('summernote.' + namespace, args);
1628
    };
1629
 
1630
    this.initializeModule = function (key) {
1631
      var module = this.modules[key];
1632
      module.shouldInitialize = module.shouldInitialize || func.ok;
1633
      if (!module.shouldInitialize()) {
1634
        return;
1635
      }
1636
 
1637
      // initialize module
1638
      if (module.initialize) {
1639
        module.initialize();
1640
      }
1641
 
1642
      // attach events
1643
      if (module.events) {
1644
        dom.attachEvents($note, module.events);
1645
      }
1646
    };
1647
 
1648
    this.module = function (key, ModuleClass, withoutIntialize) {
1649
      if (arguments.length === 1) {
1650
        return this.modules[key];
1651
      }
1652
 
1653
      this.modules[key] = new ModuleClass(this);
1654
 
1655
      if (!withoutIntialize) {
1656
        this.initializeModule(key);
1657
      }
1658
    };
1659
 
1660
    this.removeModule = function (key) {
1661
      var module = this.modules[key];
1662
      if (module.shouldInitialize()) {
1663
        if (module.events) {
1664
          dom.detachEvents($note, module.events);
1665
        }
1666
 
1667
        if (module.destroy) {
1668
          module.destroy();
1669
        }
1670
      }
1671
 
1672
      delete this.modules[key];
1673
    };
1674
 
1675
    this.memo = function (key, obj) {
1676
      if (arguments.length === 1) {
1677
        return this.memos[key];
1678
      }
1679
      this.memos[key] = obj;
1680
    };
1681
 
1682
    this.removeMemo = function (key) {
1683
      if (this.memos[key] && this.memos[key].destroy) {
1684
        this.memos[key].destroy();
1685
      }
1686
 
1687
      delete this.memos[key];
1688
    };
1689
 
1690
    this.createInvokeHandler = function (namespace, value) {
1691
      return function (event) {
1692
        event.preventDefault();
1693
        self.invoke(namespace, value || $(event.target).closest('[data-value]').data('value'));
1694
      };
1695
    };
1696
 
1697
    this.invoke = function () {
1698
      var namespace = list.head(arguments);
1699
      var args = list.tail(list.from(arguments));
1700
 
1701
      var splits = namespace.split('.');
1702
      var hasSeparator = splits.length > 1;
1703
      var moduleName = hasSeparator && list.head(splits);
1704
      var methodName = hasSeparator ? list.last(splits) : list.head(splits);
1705
 
1706
      var module = this.modules[moduleName || 'editor'];
1707
      if (!moduleName && this[methodName]) {
1708
        return this[methodName].apply(this, args);
1709
      } else if (module && module[methodName] && module.shouldInitialize()) {
1710
        return module[methodName].apply(module, args);
1711
      }
1712
    };
1713
 
1714
    return this.initialize();
1715
  };
1716
 
1717
  $.fn.extend({
1718
    /**
1719
     * Summernote API
1720
     *
1721
     * @param {Object|String}
1722
     * @return {this}
1723
     */
1724
    summernote: function () {
1725
      var type = $.type(list.head(arguments));
1726
      var isExternalAPICalled = type === 'string';
1727
      var hasInitOptions = type === 'object';
1728
 
1729
      var options = hasInitOptions ? list.head(arguments) : {};
1730
 
1731
      options = $.extend({}, $.summernote.options, options);
1732
      options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);
1733
 
1734
      this.each(function (idx, note) {
1735
        var $note = $(note);
1736
        if (!$note.data('summernote')) {
1737
          var context = new Context($note, options);
1738
          $note.data('summernote', context);
1739
          $note.data('summernote').triggerEvent('init', context.layoutInfo);
1740
        }
1741
      });
1742
 
1743
      var $note = this.first();
1744
      if ($note.length) {
1745
        var context = $note.data('summernote');
1746
        if (isExternalAPICalled) {
1747
          return context.invoke.apply(context, list.from(arguments));
1748
        } else if (options.focus) {
1749
          context.invoke('editor.focus');
1750
        }
1751
      }
1752
 
1753
      return this;
1754
    }
1755
  });
1756
 
1757
 
1758
  var Renderer = function (markup, children, options, callback) {
1759
    this.render = function ($parent) {
1760
      var $node = $(markup);
1761
 
1762
      if (options && options.contents) {
1763
        $node.html(options.contents);
1764
      }
1765
 
1766
      if (options && options.className) {
1767
        $node.addClass(options.className);
1768
      }
1769
 
1770
      if (options && options.data) {
1771
        $.each(options.data, function (k, v) {
1772
          $node.attr('data-' + k, v);
1773
        });
1774
      }
1775
 
1776
      if (options && options.click) {
1777
        $node.on('click', options.click);
1778
      }
1779
 
1780
      if (children) {
1781
        var $container = $node.find('.note-children-container');
1782
        children.forEach(function (child) {
1783
          child.render($container.length ? $container : $node);
1784
        });
1785
      }
1786
 
1787
      if (callback) {
1788
        callback($node, options);
1789
      }
1790
 
1791
      if (options && options.callback) {
1792
        options.callback($node);
1793
      }
1794
 
1795
      if ($parent) {
1796
        $parent.append($node);
1797
      }
1798
 
1799
      return $node;
1800
    };
1801
  };
1802
 
1803
  var renderer = {
1804
    create: function (markup, callback) {
1805
      return function () {
1806
        var children = $.isArray(arguments[0]) ? arguments[0] : [];
1807
        var options = typeof arguments[1] === 'object' ? arguments[1] : arguments[0];
1808
        if (options && options.children) {
1809
          children = options.children;
1810
        }
1811
        return new Renderer(markup, children, options, callback);
1812
      };
1813
    }
1814
  };
1815
 
1816
  var editor = renderer.create('<div class="note-editor note-frame panel panel-default"/>');
1817
  var toolbar = renderer.create('<div class="note-toolbar panel-heading"/>');
1818
  var editingArea = renderer.create('<div class="note-editing-area"/>');
1819
  var codable = renderer.create('<textarea class="note-codable"/>');
1820
  var editable = renderer.create('<div class="note-editable panel-body" contentEditable="true"/>');
1821
  var statusbar = renderer.create([
1822
    '<div class="note-statusbar">',
1823
    '  <div class="note-resizebar">',
1824
    '    <div class="note-icon-bar"/>',
1825
    '    <div class="note-icon-bar"/>',
1826
    '    <div class="note-icon-bar"/>',
1827
    '  </div>',
1828
    '</div>'
1829
  ].join(''));
1830
 
1831
  var airEditor = renderer.create('<div class="note-editor"/>');
1832
  var airEditable = renderer.create('<div class="note-editable" contentEditable="true"/>');
1833
 
1834
  var buttonGroup = renderer.create('<div class="note-btn-group btn-group">');
1835
  var button = renderer.create('<button type="button" class="note-btn btn btn-default btn-sm">', function ($node, options) {
1836
    if (options && options.tooltip) {
1837
      $node.attr({
1838
        title: options.tooltip
1839
      }).tooltip({
1840
        container: 'body',
1841
        trigger: 'hover',
1842
        placement: 'bottom'
1843
      });
1844
    }
1845
  });
1846
 
1847
  var dropdown = renderer.create('<div class="dropdown-menu">', function ($node, options) {
1848
    var markup = $.isArray(options.items) ? options.items.map(function (item) {
1849
      var value = (typeof item === 'string') ? item : (item.value || '');
1850
      var content = options.template ? options.template(item) : item;
1851
      return '<li><a href="#" data-value="' + value + '">' + content + '</a></li>';
1852
    }).join('') : options.items;
1853
 
1854
    $node.html(markup);
1855
  });
1856
 
1857
  var dropdownCheck = renderer.create('<div class="dropdown-menu note-check">', function ($node, options) {
1858
    var markup = $.isArray(options.items) ? options.items.map(function (item) {
1859
      var value = (typeof item === 'string') ? item : (item.value || '');
1860
      var content = options.template ? options.template(item) : item;
1861
      return '<li><a href="#" data-value="' + value + '">' + icon(options.checkClassName) + ' ' + content + '</a></li>';
1862
    }).join('') : options.items;
1863
    $node.html(markup);
1864
  });
1865
 
1866
  var palette = renderer.create('<div class="note-color-palette"/>', function ($node, options) {
1867
    var contents = [];
1868
    for (var row = 0, rowSize = options.colors.length; row < rowSize; row++) {
1869
      var eventName = options.eventName;
1870
      var colors = options.colors[row];
1871
      var buttons = [];
1872
      for (var col = 0, colSize = colors.length; col < colSize; col++) {
1873
        var color = colors[col];
1874
        buttons.push([
1875
          '<button type="button" class="note-color-btn"',
1876
          'style="background-color:', color, '" ',
1877
          'data-event="', eventName, '" ',
1878
          'data-value="', color, '" ',
1879
          'title="', color, '" ',
1880
          'data-toggle="button" tabindex="-1"></button>'
1881
        ].join(''));
1882
      }
1883
      contents.push('<div class="note-color-row">' + buttons.join('') + '</div>');
1884
    }
1885
    $node.html(contents.join(''));
1886
 
1887
    $node.find('.note-color-btn').tooltip({
1888
      container: 'body',
1889
      trigger: 'hover',
1890
      placement: 'bottom'
1891
    });
1892
  });
1893
 
1894
  var dialog = renderer.create('<div class="modal" aria-hidden="false" tabindex="-1"/>', function ($node, options) {
1895
    if (options.fade) {
1896
      $node.addClass('fade');
1897
    }
1898
    $node.html([
1899
      '<div class="modal-dialog">',
1900
      '  <div class="modal-content">',
1901
      (options.title ?
1902
      '    <div class="modal-header">' +
1903
      '      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
1904
      '      <h4 class="modal-title">' + options.title + '</h4>' +
1905
      '    </div>' : ''
1906
      ),
1907
      '    <div class="modal-body">' + options.body + '</div>',
1908
      (options.footer ?
1909
      '    <div class="modal-footer">' + options.footer + '</div>' : ''
1910
      ),
1911
      '  </div>',
1912
      '</div>'
1913
    ].join(''));
1914
  });
1915
 
1916
  var popover = renderer.create([
1917
    '<div class="note-popover popover in">',
1918
    '  <div class="arrow"/>',
1919
    '  <div class="popover-content note-children-container"/>',
1920
    '</div>'
1921
  ].join(''), function ($node, options) {
1922
    var direction = typeof options.direction !== 'undefined' ? options.direction : 'bottom';
1923
 
1924
    $node.addClass(direction);
1925
 
1926
    if (options.hideArrow) {
1927
      $node.find('.arrow').hide();
1928
    }
1929
  });
1930
 
1931
  var icon = function (iconClassName, tagName) {
1932
    tagName = tagName || 'i';
1933
    return '<' + tagName + ' class="' + iconClassName + '"/>';
1934
  };
1935
 
1936
  var ui = {
1937
    editor: editor,
1938
    toolbar: toolbar,
1939
    editingArea: editingArea,
1940
    codable: codable,
1941
    editable: editable,
1942
    statusbar: statusbar,
1943
    airEditor: airEditor,
1944
    airEditable: airEditable,
1945
    buttonGroup: buttonGroup,
1946
    button: button,
1947
    dropdown: dropdown,
1948
    dropdownCheck: dropdownCheck,
1949
    palette: palette,
1950
    dialog: dialog,
1951
    popover: popover,
1952
    icon: icon,
1953
 
1954
    toggleBtn: function ($btn, isEnable) {
1955
      $btn.toggleClass('disabled', !isEnable);
1956
      $btn.attr('disabled', !isEnable);
1957
    },
1958
 
1959
    toggleBtnActive: function ($btn, isActive) {
1960
      $btn.toggleClass('active', isActive);
1961
    },
1962
 
1963
    onDialogShown: function ($dialog, handler) {
1964
      $dialog.one('shown.bs.modal', handler);
1965
    },
1966
 
1967
    onDialogHidden: function ($dialog, handler) {
1968
      $dialog.one('hidden.bs.modal', handler);
1969
    },
1970
 
1971
    showDialog: function ($dialog) {
1972
      $dialog.modal('show');
1973
    },
1974
 
1975
    hideDialog: function ($dialog) {
1976
      $dialog.modal('hide');
1977
    },
1978
 
1979
    createLayout: function ($note, options) {
1980
      var $editor = (options.airMode ? ui.airEditor([
1981
        ui.editingArea([
1982
          ui.airEditable()
1983
        ])
1984
      ]) : ui.editor([
1985
        ui.toolbar(),
1986
        ui.editingArea([
1987
          ui.codable(),
1988
          ui.editable()
1989
        ]),
1990
        ui.statusbar()
1991
      ])).render();
1992
 
1993
      $editor.insertAfter($note);
1994
 
1995
      return {
1996
        note: $note,
1997
        editor: $editor,
1998
        toolbar: $editor.find('.note-toolbar'),
1999
        editingArea: $editor.find('.note-editing-area'),
2000
        editable: $editor.find('.note-editable'),
2001
        codable: $editor.find('.note-codable'),
2002
        statusbar: $editor.find('.note-statusbar')
2003
      };
2004
    },
2005
 
2006
    removeLayout: function ($note, layoutInfo) {
2007
      $note.html(layoutInfo.editable.html());
2008
      layoutInfo.editor.remove();
2009
      $note.show();
2010
    }
2011
  };
2012
 
2013
  $.summernote = $.summernote || {
2014
    lang: {}
2015
  };
2016
 
2017
  $.extend($.summernote.lang, {
2018
    'en-US': {
2019
      font: {
2020
        bold: 'Bold',
2021
        italic: 'Italic',
2022
        underline: 'Underline',
2023
        clear: 'Remove Font Style',
2024
        height: 'Line Height',
2025
        name: 'Font Family',
2026
        strikethrough: 'Strikethrough',
2027
        subscript: 'Subscript',
2028
        superscript: 'Superscript',
2029
        size: 'Font Size'
2030
      },
2031
      image: {
2032
        image: 'Picture',
2033
        insert: 'Insert Image',
2034
        resizeFull: 'Resize Full',
2035
        resizeHalf: 'Resize Half',
2036
        resizeQuarter: 'Resize Quarter',
2037
        floatLeft: 'Float Left',
2038
        floatRight: 'Float Right',
2039
        floatNone: 'Float None',
2040
        shapeRounded: 'Shape: Rounded',
2041
        shapeCircle: 'Shape: Circle',
2042
        shapeThumbnail: 'Shape: Thumbnail',
2043
        shapeNone: 'Shape: None',
2044
        dragImageHere: 'Drag image or text here',
2045
        dropImage: 'Drop image or Text',
2046
        selectFromFiles: 'Select from files',
2047
        maximumFileSize: 'Maximum file size',
2048
        maximumFileSizeError: 'Maximum file size exceeded.',
2049
        url: 'Image URL',
2050
        remove: 'Remove Image'
2051
      },
2052
      video: {
2053
        video: 'Video',
2054
        videoLink: 'Video Link',
2055
        insert: 'Insert Video',
2056
        url: 'Video URL?',
2057
        providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion or Youku)'
2058
      },
2059
      link: {
2060
        link: 'Link',
2061
        insert: 'Insert Link',
2062
        unlink: 'Unlink',
2063
        edit: 'Edit',
2064
        textToDisplay: 'Text to display',
2065
        url: 'To what URL should this link go?',
2066
        openInNewWindow: 'Open in new window'
2067
      },
2068
      table: {
2069
        table: 'Table'
2070
      },
2071
      hr: {
2072
        insert: 'Insert Horizontal Rule'
2073
      },
2074
      style: {
2075
        style: 'Style',
2076
        normal: 'Normal',
2077
        blockquote: 'Quote',
2078
        pre: 'Code',
2079
        h1: 'Header 1',
2080
        h2: 'Header 2',
2081
        h3: 'Header 3',
2082
        h4: 'Header 4',
2083
        h5: 'Header 5',
2084
        h6: 'Header 6'
2085
      },
2086
      lists: {
2087
        unordered: 'Unordered list',
2088
        ordered: 'Ordered list'
2089
      },
2090
      options: {
2091
        help: 'Help',
2092
        fullscreen: 'Full Screen',
2093
        codeview: 'Code View'
2094
      },
2095
      paragraph: {
2096
        paragraph: 'Paragraph',
2097
        outdent: 'Outdent',
2098
        indent: 'Indent',
2099
        left: 'Align left',
2100
        center: 'Align center',
2101
        right: 'Align right',
2102
        justify: 'Justify full'
2103
      },
2104
      color: {
2105
        recent: 'Recent Color',
2106
        more: 'More Color',
2107
        background: 'Background Color',
2108
        foreground: 'Foreground Color',
2109
        transparent: 'Transparent',
2110
        setTransparent: 'Set transparent',
2111
        reset: 'Reset',
2112
        resetToDefault: 'Reset to default'
2113
      },
2114
      shortcut: {
2115
        shortcuts: 'Keyboard shortcuts',
2116
        close: 'Close',
2117
        textFormatting: 'Text formatting',
2118
        action: 'Action',
2119
        paragraphFormatting: 'Paragraph formatting',
2120
        documentStyle: 'Document Style',
2121
        extraKeys: 'Extra keys'
2122
      },
2123
      help: {
2124
        'insertParagraph': 'Insert Paragraph',
2125
        'undo': 'Undoes the last command',
2126
        'redo': 'Redoes the last command',
2127
        'tab': 'Tab',
2128
        'untab': 'Untab',
2129
        'bold': 'Set a bold style',
2130
        'italic': 'Set a italic style',
2131
        'underline': 'Set a underline style',
2132
        'strikethrough': 'Set a strikethrough style',
2133
        'removeFormat': 'Clean a style',
2134
        'justifyLeft': 'Set left align',
2135
        'justifyCenter': 'Set center align',
2136
        'justifyRight': 'Set right align',
2137
        'justifyFull': 'Set full align',
2138
        'insertUnorderedList': 'Toggle unordered list',
2139
        'insertOrderedList': 'Toggle ordered list',
2140
        'outdent': 'Outdent on current paragraph',
2141
        'indent': 'Indent on current paragraph',
2142
        'formatPara': 'Change current block\'s format as a paragraph(P tag)',
2143
        'formatH1': 'Change current block\'s format as H1',
2144
        'formatH2': 'Change current block\'s format as H2',
2145
        'formatH3': 'Change current block\'s format as H3',
2146
        'formatH4': 'Change current block\'s format as H4',
2147
        'formatH5': 'Change current block\'s format as H5',
2148
        'formatH6': 'Change current block\'s format as H6',
2149
        'insertHorizontalRule': 'Insert horizontal rule',
2150
        'linkDialog.show': 'Show Link Dialog'
2151
      },
2152
      history: {
2153
        undo: 'Undo',
2154
        redo: 'Redo'
2155
      },
2156
      specialChar: {
2157
        specialChar: 'SPECIAL CHARACTERS',
2158
        select: 'Select Special characters'
2159
      }
2160
    }
2161
  });
2162
 
2163
 
2164
  /**
2165
   * @class core.key
2166
   *
2167
   * Object for keycodes.
2168
   *
2169
   * @singleton
2170
   * @alternateClassName key
2171
   */
2172
  var key = (function () {
2173
    var keyMap = {
2174
      'BACKSPACE': 8,
2175
      'TAB': 9,
2176
      'ENTER': 13,
2177
      'SPACE': 32,
2178
 
2179
      // Arrow
2180
      'LEFT': 37,
2181
      'UP': 38,
2182
      'RIGHT': 39,
2183
      'DOWN': 40,
2184
 
2185
      // Number: 0-9
2186
      'NUM0': 48,
2187
      'NUM1': 49,
2188
      'NUM2': 50,
2189
      'NUM3': 51,
2190
      'NUM4': 52,
2191
      'NUM5': 53,
2192
      'NUM6': 54,
2193
      'NUM7': 55,
2194
      'NUM8': 56,
2195
 
2196
      // Alphabet: a-z
2197
      'B': 66,
2198
      'E': 69,
2199
      'I': 73,
2200
      'J': 74,
2201
      'K': 75,
2202
      'L': 76,
2203
      'R': 82,
2204
      'S': 83,
2205
      'U': 85,
2206
      'V': 86,
2207
      'Y': 89,
2208
      'Z': 90,
2209
 
2210
      'SLASH': 191,
2211
      'LEFTBRACKET': 219,
2212
      'BACKSLASH': 220,
2213
      'RIGHTBRACKET': 221
2214
    };
2215
 
2216
    return {
2217
      /**
2218
       * @method isEdit
2219
       *
2220
       * @param {Number} keyCode
2221
       * @return {Boolean}
2222
       */
2223
      isEdit: function (keyCode) {
2224
        return list.contains([
2225
          keyMap.BACKSPACE,
2226
          keyMap.TAB,
2227
          keyMap.ENTER,
2228
          keyMap.SPACE
2229
        ], keyCode);
2230
      },
2231
      /**
2232
       * @method isMove
2233
       *
2234
       * @param {Number} keyCode
2235
       * @return {Boolean}
2236
       */
2237
      isMove: function (keyCode) {
2238
        return list.contains([
2239
          keyMap.LEFT,
2240
          keyMap.UP,
2241
          keyMap.RIGHT,
2242
          keyMap.DOWN
2243
        ], keyCode);
2244
      },
2245
      /**
2246
       * @property {Object} nameFromCode
2247
       * @property {String} nameFromCode.8 "BACKSPACE"
2248
       */
2249
      nameFromCode: func.invertObject(keyMap),
2250
      code: keyMap
2251
    };
2252
  })();
2253
 
2254
  var range = (function () {
2255
 
2256
    /**
2257
     * return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js
2258
     *
2259
     * @param {TextRange} textRange
2260
     * @param {Boolean} isStart
2261
     * @return {BoundaryPoint}
2262
     *
2263
     * @see http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx
2264
     */
2265
    var textRangeToPoint = function (textRange, isStart) {
2266
      var container = textRange.parentElement(), offset;
2267
 
2268
      var tester = document.body.createTextRange(), prevContainer;
2269
      var childNodes = list.from(container.childNodes);
2270
      for (offset = 0; offset < childNodes.length; offset++) {
2271
        if (dom.isText(childNodes[offset])) {
2272
          continue;
2273
        }
2274
        tester.moveToElementText(childNodes[offset]);
2275
        if (tester.compareEndPoints('StartToStart', textRange) >= 0) {
2276
          break;
2277
        }
2278
        prevContainer = childNodes[offset];
2279
      }
2280
 
2281
      if (offset !== 0 && dom.isText(childNodes[offset - 1])) {
2282
        var textRangeStart = document.body.createTextRange(), curTextNode = null;
2283
        textRangeStart.moveToElementText(prevContainer || container);
2284
        textRangeStart.collapse(!prevContainer);
2285
        curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild;
2286
 
2287
        var pointTester = textRange.duplicate();
2288
        pointTester.setEndPoint('StartToStart', textRangeStart);
2289
        var textCount = pointTester.text.replace(/[\r\n]/g, '').length;
2290
 
2291
        while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) {
2292
          textCount -= curTextNode.nodeValue.length;
2293
          curTextNode = curTextNode.nextSibling;
2294
        }
2295
 
2296
        /* jshint ignore:start */
2297
        var dummy = curTextNode.nodeValue; // enforce IE to re-reference curTextNode, hack
2298
        /* jshint ignore:end */
2299
 
2300
        if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) &&
2301
            textCount === curTextNode.nodeValue.length) {
2302
          textCount -= curTextNode.nodeValue.length;
2303
          curTextNode = curTextNode.nextSibling;
2304
        }
2305
 
2306
        container = curTextNode;
2307
        offset = textCount;
2308
      }
2309
 
2310
      return {
2311
        cont: container,
2312
        offset: offset
2313
      };
2314
    };
2315
 
2316
    /**
2317
     * return TextRange from boundary point (inspired by google closure-library)
2318
     * @param {BoundaryPoint} point
2319
     * @return {TextRange}
2320
     */
2321
    var pointToTextRange = function (point) {
2322
      var textRangeInfo = function (container, offset) {
2323
        var node, isCollapseToStart;
2324
 
2325
        if (dom.isText(container)) {
2326
          var prevTextNodes = dom.listPrev(container, func.not(dom.isText));
2327
          var prevContainer = list.last(prevTextNodes).previousSibling;
2328
          node =  prevContainer || container.parentNode;
2329
          offset += list.sum(list.tail(prevTextNodes), dom.nodeLength);
2330
          isCollapseToStart = !prevContainer;
2331
        } else {
2332
          node = container.childNodes[offset] || container;
2333
          if (dom.isText(node)) {
2334
            return textRangeInfo(node, 0);
2335
          }
2336
 
2337
          offset = 0;
2338
          isCollapseToStart = false;
2339
        }
2340
 
2341
        return {
2342
          node: node,
2343
          collapseToStart: isCollapseToStart,
2344
          offset: offset
2345
        };
2346
      };
2347
 
2348
      var textRange = document.body.createTextRange();
2349
      var info = textRangeInfo(point.node, point.offset);
2350
 
2351
      textRange.moveToElementText(info.node);
2352
      textRange.collapse(info.collapseToStart);
2353
      textRange.moveStart('character', info.offset);
2354
      return textRange;
2355
    };
2356
 
2357
    /**
2358
     * Wrapped Range
2359
     *
2360
     * @constructor
2361
     * @param {Node} sc - start container
2362
     * @param {Number} so - start offset
2363
     * @param {Node} ec - end container
2364
     * @param {Number} eo - end offset
2365
     */
2366
    var WrappedRange = function (sc, so, ec, eo) {
2367
      this.sc = sc;
2368
      this.so = so;
2369
      this.ec = ec;
2370
      this.eo = eo;
2371
 
2372
      // nativeRange: get nativeRange from sc, so, ec, eo
2373
      var nativeRange = function () {
2374
        if (agent.isW3CRangeSupport) {
2375
          var w3cRange = document.createRange();
2376
          w3cRange.setStart(sc, so);
2377
          w3cRange.setEnd(ec, eo);
2378
 
2379
          return w3cRange;
2380
        } else {
2381
          var textRange = pointToTextRange({
2382
            node: sc,
2383
            offset: so
2384
          });
2385
 
2386
          textRange.setEndPoint('EndToEnd', pointToTextRange({
2387
            node: ec,
2388
            offset: eo
2389
          }));
2390
 
2391
          return textRange;
2392
        }
2393
      };
2394
 
2395
      this.getPoints = function () {
2396
        return {
2397
          sc: sc,
2398
          so: so,
2399
          ec: ec,
2400
          eo: eo
2401
        };
2402
      };
2403
 
2404
      this.getStartPoint = function () {
2405
        return {
2406
          node: sc,
2407
          offset: so
2408
        };
2409
      };
2410
 
2411
      this.getEndPoint = function () {
2412
        return {
2413
          node: ec,
2414
          offset: eo
2415
        };
2416
      };
2417
 
2418
      /**
2419
       * select update visible range
2420
       */
2421
      this.select = function () {
2422
        var nativeRng = nativeRange();
2423
        if (agent.isW3CRangeSupport) {
2424
          var selection = document.getSelection();
2425
          if (selection.rangeCount > 0) {
2426
            selection.removeAllRanges();
2427
          }
2428
          selection.addRange(nativeRng);
2429
        } else {
2430
          nativeRng.select();
2431
        }
2432
 
2433
        return this;
2434
      };
2435
 
2436
      /**
2437
       * Moves the scrollbar to start container(sc) of current range
2438
       *
2439
       * @return {WrappedRange}
2440
       */
2441
      this.scrollIntoView = function (container) {
2442
        var height = $(container).height();
2443
        if (container.scrollTop + height < this.sc.offsetTop) {
2444
          container.scrollTop += Math.abs(container.scrollTop + height - this.sc.offsetTop);
2445
        }
2446
 
2447
        return this;
2448
      };
2449
 
2450
      /**
2451
       * @return {WrappedRange}
2452
       */
2453
      this.normalize = function () {
2454
 
2455
        /**
2456
         * @param {BoundaryPoint} point
2457
         * @param {Boolean} isLeftToRight
2458
         * @return {BoundaryPoint}
2459
         */
2460
        var getVisiblePoint = function (point, isLeftToRight) {
2461
          if ((dom.isVisiblePoint(point) && !dom.isEdgePoint(point)) ||
2462
              (dom.isVisiblePoint(point) && dom.isRightEdgePoint(point) && !isLeftToRight) ||
2463
              (dom.isVisiblePoint(point) && dom.isLeftEdgePoint(point) && isLeftToRight) ||
2464
              (dom.isVisiblePoint(point) && dom.isBlock(point.node) && dom.isEmpty(point.node))) {
2465
            return point;
2466
          }
2467
 
2468
          // point on block's edge
2469
          var block = dom.ancestor(point.node, dom.isBlock);
2470
          if (((dom.isLeftEdgePointOf(point, block) || dom.isVoid(dom.prevPoint(point).node)) && !isLeftToRight) ||
2471
              ((dom.isRightEdgePointOf(point, block) || dom.isVoid(dom.nextPoint(point).node)) && isLeftToRight)) {
2472
 
2473
            // returns point already on visible point
2474
            if (dom.isVisiblePoint(point)) {
2475
              return point;
2476
            }
2477
            // reverse direction
2478
            isLeftToRight = !isLeftToRight;
2479
          }
2480
 
2481
          var nextPoint = isLeftToRight ? dom.nextPointUntil(dom.nextPoint(point), dom.isVisiblePoint) :
2482
                                          dom.prevPointUntil(dom.prevPoint(point), dom.isVisiblePoint);
2483
          return nextPoint || point;
2484
        };
2485
 
2486
        var endPoint = getVisiblePoint(this.getEndPoint(), false);
2487
        var startPoint = this.isCollapsed() ? endPoint : getVisiblePoint(this.getStartPoint(), true);
2488
 
2489
        return new WrappedRange(
2490
          startPoint.node,
2491
          startPoint.offset,
2492
          endPoint.node,
2493
          endPoint.offset
2494
        );
2495
      };
2496
 
2497
      /**
2498
       * returns matched nodes on range
2499
       *
2500
       * @param {Function} [pred] - predicate function
2501
       * @param {Object} [options]
2502
       * @param {Boolean} [options.includeAncestor]
2503
       * @param {Boolean} [options.fullyContains]
2504
       * @return {Node[]}
2505
       */
2506
      this.nodes = function (pred, options) {
2507
        pred = pred || func.ok;
2508
 
2509
        var includeAncestor = options && options.includeAncestor;
2510
        var fullyContains = options && options.fullyContains;
2511
 
2512
        // TODO compare points and sort
2513
        var startPoint = this.getStartPoint();
2514
        var endPoint = this.getEndPoint();
2515
 
2516
        var nodes = [];
2517
        var leftEdgeNodes = [];
2518
 
2519
        dom.walkPoint(startPoint, endPoint, function (point) {
2520
          if (dom.isEditable(point.node)) {
2521
            return;
2522
          }
2523
 
2524
          var node;
2525
          if (fullyContains) {
2526
            if (dom.isLeftEdgePoint(point)) {
2527
              leftEdgeNodes.push(point.node);
2528
            }
2529
            if (dom.isRightEdgePoint(point) && list.contains(leftEdgeNodes, point.node)) {
2530
              node = point.node;
2531
            }
2532
          } else if (includeAncestor) {
2533
            node = dom.ancestor(point.node, pred);
2534
          } else {
2535
            node = point.node;
2536
          }
2537
 
2538
          if (node && pred(node)) {
2539
            nodes.push(node);
2540
          }
2541
        }, true);
2542
 
2543
        return list.unique(nodes);
2544
      };
2545
 
2546
      /**
2547
       * returns commonAncestor of range
2548
       * @return {Element} - commonAncestor
2549
       */
2550
      this.commonAncestor = function () {
2551
        return dom.commonAncestor(sc, ec);
2552
      };
2553
 
2554
      /**
2555
       * returns expanded range by pred
2556
       *
2557
       * @param {Function} pred - predicate function
2558
       * @return {WrappedRange}
2559
       */
2560
      this.expand = function (pred) {
2561
        var startAncestor = dom.ancestor(sc, pred);
2562
        var endAncestor = dom.ancestor(ec, pred);
2563
 
2564
        if (!startAncestor && !endAncestor) {
2565
          return new WrappedRange(sc, so, ec, eo);
2566
        }
2567
 
2568
        var boundaryPoints = this.getPoints();
2569
 
2570
        if (startAncestor) {
2571
          boundaryPoints.sc = startAncestor;
2572
          boundaryPoints.so = 0;
2573
        }
2574
 
2575
        if (endAncestor) {
2576
          boundaryPoints.ec = endAncestor;
2577
          boundaryPoints.eo = dom.nodeLength(endAncestor);
2578
        }
2579
 
2580
        return new WrappedRange(
2581
          boundaryPoints.sc,
2582
          boundaryPoints.so,
2583
          boundaryPoints.ec,
2584
          boundaryPoints.eo
2585
        );
2586
      };
2587
 
2588
      /**
2589
       * @param {Boolean} isCollapseToStart
2590
       * @return {WrappedRange}
2591
       */
2592
      this.collapse = function (isCollapseToStart) {
2593
        if (isCollapseToStart) {
2594
          return new WrappedRange(sc, so, sc, so);
2595
        } else {
2596
          return new WrappedRange(ec, eo, ec, eo);
2597
        }
2598
      };
2599
 
2600
      /**
2601
       * splitText on range
2602
       */
2603
      this.splitText = function () {
2604
        var isSameContainer = sc === ec;
2605
        var boundaryPoints = this.getPoints();
2606
 
2607
        if (dom.isText(ec) && !dom.isEdgePoint(this.getEndPoint())) {
2608
          ec.splitText(eo);
2609
        }
2610
 
2611
        if (dom.isText(sc) && !dom.isEdgePoint(this.getStartPoint())) {
2612
          boundaryPoints.sc = sc.splitText(so);
2613
          boundaryPoints.so = 0;
2614
 
2615
          if (isSameContainer) {
2616
            boundaryPoints.ec = boundaryPoints.sc;
2617
            boundaryPoints.eo = eo - so;
2618
          }
2619
        }
2620
 
2621
        return new WrappedRange(
2622
          boundaryPoints.sc,
2623
          boundaryPoints.so,
2624
          boundaryPoints.ec,
2625
          boundaryPoints.eo
2626
        );
2627
      };
2628
 
2629
      /**
2630
       * delete contents on range
2631
       * @return {WrappedRange}
2632
       */
2633
      this.deleteContents = function () {
2634
        if (this.isCollapsed()) {
2635
          return this;
2636
        }
2637
 
2638
        var rng = this.splitText();
2639
        var nodes = rng.nodes(null, {
2640
          fullyContains: true
2641
        });
2642
 
2643
        // find new cursor point
2644
        var point = dom.prevPointUntil(rng.getStartPoint(), function (point) {
2645
          return !list.contains(nodes, point.node);
2646
        });
2647
 
2648
        var emptyParents = [];
2649
        $.each(nodes, function (idx, node) {
2650
          // find empty parents
2651
          var parent = node.parentNode;
2652
          if (point.node !== parent && dom.nodeLength(parent) === 1) {
2653
            emptyParents.push(parent);
2654
          }
2655
          dom.remove(node, false);
2656
        });
2657
 
2658
        // remove empty parents
2659
        $.each(emptyParents, function (idx, node) {
2660
          dom.remove(node, false);
2661
        });
2662
 
2663
        return new WrappedRange(
2664
          point.node,
2665
          point.offset,
2666
          point.node,
2667
          point.offset
2668
        ).normalize();
2669
      };
2670
 
2671
      /**
2672
       * makeIsOn: return isOn(pred) function
2673
       */
2674
      var makeIsOn = function (pred) {
2675
        return function () {
2676
          var ancestor = dom.ancestor(sc, pred);
2677
          return !!ancestor && (ancestor === dom.ancestor(ec, pred));
2678
        };
2679
      };
2680
 
2681
      // isOnEditable: judge whether range is on editable or not
2682
      this.isOnEditable = makeIsOn(dom.isEditable);
2683
      // isOnList: judge whether range is on list node or not
2684
      this.isOnList = makeIsOn(dom.isList);
2685
      // isOnAnchor: judge whether range is on anchor node or not
2686
      this.isOnAnchor = makeIsOn(dom.isAnchor);
2687
      // isOnAnchor: judge whether range is on cell node or not
2688
      this.isOnCell = makeIsOn(dom.isCell);
2689
 
2690
      /**
2691
       * @param {Function} pred
2692
       * @return {Boolean}
2693
       */
2694
      this.isLeftEdgeOf = function (pred) {
2695
        if (!dom.isLeftEdgePoint(this.getStartPoint())) {
2696
          return false;
2697
        }
2698
 
2699
        var node = dom.ancestor(this.sc, pred);
2700
        return node && dom.isLeftEdgeOf(this.sc, node);
2701
      };
2702
 
2703
      /**
2704
       * returns whether range was collapsed or not
2705
       */
2706
      this.isCollapsed = function () {
2707
        return sc === ec && so === eo;
2708
      };
2709
 
2710
      /**
2711
       * wrap inline nodes which children of body with paragraph
2712
       *
2713
       * @return {WrappedRange}
2714
       */
2715
      this.wrapBodyInlineWithPara = function () {
2716
        if (dom.isBodyContainer(sc) && dom.isEmpty(sc)) {
2717
          sc.innerHTML = dom.emptyPara;
2718
          return new WrappedRange(sc.firstChild, 0, sc.firstChild, 0);
2719
        }
2720
 
2721
        /**
2722
         * [workaround] firefox often create range on not visible point. so normalize here.
2723
         *  - firefox: |<p>text</p>|
2724
         *  - chrome: <p>|text|</p>
2725
         */
2726
        var rng = this.normalize();
2727
        if (dom.isParaInline(sc) || dom.isPara(sc)) {
2728
          return rng;
2729
        }
2730
 
2731
        // find inline top ancestor
2732
        var topAncestor;
2733
        if (dom.isInline(rng.sc)) {
2734
          var ancestors = dom.listAncestor(rng.sc, func.not(dom.isInline));
2735
          topAncestor = list.last(ancestors);
2736
          if (!dom.isInline(topAncestor)) {
2737
            topAncestor = ancestors[ancestors.length - 2] || rng.sc.childNodes[rng.so];
2738
          }
2739
        } else {
2740
          topAncestor = rng.sc.childNodes[rng.so > 0 ? rng.so - 1 : 0];
2741
        }
2742
 
2743
        // siblings not in paragraph
2744
        var inlineSiblings = dom.listPrev(topAncestor, dom.isParaInline).reverse();
2745
        inlineSiblings = inlineSiblings.concat(dom.listNext(topAncestor.nextSibling, dom.isParaInline));
2746
 
2747
        // wrap with paragraph
2748
        if (inlineSiblings.length) {
2749
          var para = dom.wrap(list.head(inlineSiblings), 'p');
2750
          dom.appendChildNodes(para, list.tail(inlineSiblings));
2751
        }
2752
 
2753
        return this.normalize();
2754
      };
2755
 
2756
      /**
2757
       * insert node at current cursor
2758
       *
2759
       * @param {Node} node
2760
       * @return {Node}
2761
       */
2762
      this.insertNode = function (node) {
2763
        var rng = this.wrapBodyInlineWithPara().deleteContents();
2764
        var info = dom.splitPoint(rng.getStartPoint(), dom.isInline(node));
2765
 
2766
        if (info.rightNode) {
2767
          info.rightNode.parentNode.insertBefore(node, info.rightNode);
2768
        } else {
2769
          info.container.appendChild(node);
2770
        }
2771
 
2772
        return node;
2773
      };
2774
 
2775
      /**
2776
       * insert html at current cursor
2777
       */
2778
      this.pasteHTML = function (markup) {
2779
        var contentsContainer = $('<div></div>').html(markup)[0];
2780
        var childNodes = list.from(contentsContainer.childNodes);
2781
 
2782
        var rng = this.wrapBodyInlineWithPara().deleteContents();
2783
 
2784
        return childNodes.reverse().map(function (childNode) {
2785
          return rng.insertNode(childNode);
2786
        }).reverse();
2787
      };
2788
 
2789
      /**
2790
       * returns text in range
2791
       *
2792
       * @return {String}
2793
       */
2794
      this.toString = function () {
2795
        var nativeRng = nativeRange();
2796
        return agent.isW3CRangeSupport ? nativeRng.toString() : nativeRng.text;
2797
      };
2798
 
2799
      /**
2800
       * returns range for word before cursor
2801
       *
2802
       * @param {Boolean} [findAfter] - find after cursor, default: false
2803
       * @return {WrappedRange}
2804
       */
2805
      this.getWordRange = function (findAfter) {
2806
        var endPoint = this.getEndPoint();
2807
 
2808
        if (!dom.isCharPoint(endPoint)) {
2809
          return this;
2810
        }
2811
 
2812
        var startPoint = dom.prevPointUntil(endPoint, function (point) {
2813
          return !dom.isCharPoint(point);
2814
        });
2815
 
2816
        if (findAfter) {
2817
          endPoint = dom.nextPointUntil(endPoint, function (point) {
2818
            return !dom.isCharPoint(point);
2819
          });
2820
        }
2821
 
2822
        return new WrappedRange(
2823
          startPoint.node,
2824
          startPoint.offset,
2825
          endPoint.node,
2826
          endPoint.offset
2827
        );
2828
      };
2829
 
2830
      /**
2831
       * create offsetPath bookmark
2832
       *
2833
       * @param {Node} editable
2834
       */
2835
      this.bookmark = function (editable) {
2836
        return {
2837
          s: {
2838
            path: dom.makeOffsetPath(editable, sc),
2839
            offset: so
2840
          },
2841
          e: {
2842
            path: dom.makeOffsetPath(editable, ec),
2843
            offset: eo
2844
          }
2845
        };
2846
      };
2847
 
2848
      /**
2849
       * create offsetPath bookmark base on paragraph
2850
       *
2851
       * @param {Node[]} paras
2852
       */
2853
      this.paraBookmark = function (paras) {
2854
        return {
2855
          s: {
2856
            path: list.tail(dom.makeOffsetPath(list.head(paras), sc)),
2857
            offset: so
2858
          },
2859
          e: {
2860
            path: list.tail(dom.makeOffsetPath(list.last(paras), ec)),
2861
            offset: eo
2862
          }
2863
        };
2864
      };
2865
 
2866
      /**
2867
       * getClientRects
2868
       * @return {Rect[]}
2869
       */
2870
      this.getClientRects = function () {
2871
        var nativeRng = nativeRange();
2872
        return nativeRng.getClientRects();
2873
      };
2874
    };
2875
 
2876
  /**
2877
   * @class core.range
2878
   *
2879
   * Data structure
2880
   *  * BoundaryPoint: a point of dom tree
2881
   *  * BoundaryPoints: two boundaryPoints corresponding to the start and the end of the Range
2882
   *
2883
   * See to http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Position
2884
   *
2885
   * @singleton
2886
   * @alternateClassName range
2887
   */
2888
    return {
2889
      /**
2890
       * create Range Object From arguments or Browser Selection
2891
       *
2892
       * @param {Node} sc - start container
2893
       * @param {Number} so - start offset
2894
       * @param {Node} ec - end container
2895
       * @param {Number} eo - end offset
2896
       * @return {WrappedRange}
2897
       */
2898
      create: function (sc, so, ec, eo) {
2899
        if (arguments.length === 4) {
2900
          return new WrappedRange(sc, so, ec, eo);
2901
        } else if (arguments.length === 2) { //collapsed
2902
          ec = sc;
2903
          eo = so;
2904
          return new WrappedRange(sc, so, ec, eo);
2905
        } else {
2906
          var wrappedRange = this.createFromSelection();
2907
          if (!wrappedRange && arguments.length === 1) {
2908
            wrappedRange = this.createFromNode(arguments[0]);
2909
            return wrappedRange.collapse(dom.emptyPara === arguments[0].innerHTML);
2910
          }
2911
          return wrappedRange;
2912
        }
2913
      },
2914
 
2915
      createFromSelection: function () {
2916
        var sc, so, ec, eo;
2917
        if (agent.isW3CRangeSupport) {
2918
          var selection = document.getSelection();
2919
          if (!selection || selection.rangeCount === 0) {
2920
            return null;
2921
          } else if (dom.isBody(selection.anchorNode)) {
2922
            // Firefox: returns entire body as range on initialization.
2923
            // We won't never need it.
2924
            return null;
2925
          }
2926
 
2927
          var nativeRng = selection.getRangeAt(0);
2928
          sc = nativeRng.startContainer;
2929
          so = nativeRng.startOffset;
2930
          ec = nativeRng.endContainer;
2931
          eo = nativeRng.endOffset;
2932
        } else { // IE8: TextRange
2933
          var textRange = document.selection.createRange();
2934
          var textRangeEnd = textRange.duplicate();
2935
          textRangeEnd.collapse(false);
2936
          var textRangeStart = textRange;
2937
          textRangeStart.collapse(true);
2938
 
2939
          var startPoint = textRangeToPoint(textRangeStart, true),
2940
          endPoint = textRangeToPoint(textRangeEnd, false);
2941
 
2942
          // same visible point case: range was collapsed.
2943
          if (dom.isText(startPoint.node) && dom.isLeftEdgePoint(startPoint) &&
2944
              dom.isTextNode(endPoint.node) && dom.isRightEdgePoint(endPoint) &&
2945
              endPoint.node.nextSibling === startPoint.node) {
2946
            startPoint = endPoint;
2947
          }
2948
 
2949
          sc = startPoint.cont;
2950
          so = startPoint.offset;
2951
          ec = endPoint.cont;
2952
          eo = endPoint.offset;
2953
        }
2954
 
2955
        return new WrappedRange(sc, so, ec, eo);
2956
      },
2957
 
2958
      /**
2959
       * @method
2960
       *
2961
       * create WrappedRange from node
2962
       *
2963
       * @param {Node} node
2964
       * @return {WrappedRange}
2965
       */
2966
      createFromNode: function (node) {
2967
        var sc = node;
2968
        var so = 0;
2969
        var ec = node;
2970
        var eo = dom.nodeLength(ec);
2971
 
2972
        // browsers can't target a picture or void node
2973
        if (dom.isVoid(sc)) {
2974
          so = dom.listPrev(sc).length - 1;
2975
          sc = sc.parentNode;
2976
        }
2977
        if (dom.isBR(ec)) {
2978
          eo = dom.listPrev(ec).length - 1;
2979
          ec = ec.parentNode;
2980
        } else if (dom.isVoid(ec)) {
2981
          eo = dom.listPrev(ec).length;
2982
          ec = ec.parentNode;
2983
        }
2984
 
2985
        return this.create(sc, so, ec, eo);
2986
      },
2987
 
2988
      /**
2989
       * create WrappedRange from node after position
2990
       *
2991
       * @param {Node} node
2992
       * @return {WrappedRange}
2993
       */
2994
      createFromNodeBefore: function (node) {
2995
        return this.createFromNode(node).collapse(true);
2996
      },
2997
 
2998
      /**
2999
       * create WrappedRange from node after position
3000
       *
3001
       * @param {Node} node
3002
       * @return {WrappedRange}
3003
       */
3004
      createFromNodeAfter: function (node) {
3005
        return this.createFromNode(node).collapse();
3006
      },
3007
 
3008
      /**
3009
       * @method
3010
       *
3011
       * create WrappedRange from bookmark
3012
       *
3013
       * @param {Node} editable
3014
       * @param {Object} bookmark
3015
       * @return {WrappedRange}
3016
       */
3017
      createFromBookmark: function (editable, bookmark) {
3018
        var sc = dom.fromOffsetPath(editable, bookmark.s.path);
3019
        var so = bookmark.s.offset;
3020
        var ec = dom.fromOffsetPath(editable, bookmark.e.path);
3021
        var eo = bookmark.e.offset;
3022
        return new WrappedRange(sc, so, ec, eo);
3023
      },
3024
 
3025
      /**
3026
       * @method
3027
       *
3028
       * create WrappedRange from paraBookmark
3029
       *
3030
       * @param {Object} bookmark
3031
       * @param {Node[]} paras
3032
       * @return {WrappedRange}
3033
       */
3034
      createFromParaBookmark: function (bookmark, paras) {
3035
        var so = bookmark.s.offset;
3036
        var eo = bookmark.e.offset;
3037
        var sc = dom.fromOffsetPath(list.head(paras), bookmark.s.path);
3038
        var ec = dom.fromOffsetPath(list.last(paras), bookmark.e.path);
3039
 
3040
        return new WrappedRange(sc, so, ec, eo);
3041
      }
3042
    };
3043
  })();
3044
 
3045
  /**
3046
   * @class core.async
3047
   *
3048
   * Async functions which returns `Promise`
3049
   *
3050
   * @singleton
3051
   * @alternateClassName async
3052
   */
3053
  var async = (function () {
3054
    /**
3055
     * @method readFileAsDataURL
3056
     *
3057
     * read contents of file as representing URL
3058
     *
3059
     * @param {File} file
3060
     * @return {Promise} - then: dataUrl
3061
     */
3062
    var readFileAsDataURL = function (file) {
3063
      return $.Deferred(function (deferred) {
3064
        $.extend(new FileReader(), {
3065
          onload: function (e) {
3066
            var dataURL = e.target.result;
3067
            deferred.resolve(dataURL);
3068
          },
3069
          onerror: function () {
3070
            deferred.reject(this);
3071
          }
3072
        }).readAsDataURL(file);
3073
      }).promise();
3074
    };
3075
 
3076
    /**
3077
     * @method createImage
3078
     *
3079
     * create `<image>` from url string
3080
     *
3081
     * @param {String} url
3082
     * @return {Promise} - then: $image
3083
     */
3084
    var createImage = function (url) {
3085
      return $.Deferred(function (deferred) {
3086
        var $img = $('<img>');
3087
 
3088
        $img.one('load', function () {
3089
          $img.off('error abort');
3090
          deferred.resolve($img);
3091
        }).one('error abort', function () {
3092
          $img.off('load').detach();
3093
          deferred.reject($img);
3094
        }).css({
3095
          display: 'none'
3096
        }).appendTo(document.body).attr('src', url);
3097
      }).promise();
3098
    };
3099
 
3100
    return {
3101
      readFileAsDataURL: readFileAsDataURL,
3102
      createImage: createImage
3103
    };
3104
  })();
3105
 
3106
  /**
3107
   * @class editing.History
3108
   *
3109
   * Editor History
3110
   *
3111
   */
3112
  var History = function ($editable) {
3113
    var stack = [], stackOffset = -1;
3114
    var editable = $editable[0];
3115
 
3116
    var makeSnapshot = function () {
3117
      var rng = range.create(editable);
3118
      var emptyBookmark = {s: {path: [], offset: 0}, e: {path: [], offset: 0}};
3119
 
3120
      return {
3121
        contents: $editable.html(),
3122
        bookmark: (rng ? rng.bookmark(editable) : emptyBookmark)
3123
      };
3124
    };
3125
 
3126
    var applySnapshot = function (snapshot) {
3127
      if (snapshot.contents !== null) {
3128
        $editable.html(snapshot.contents);
3129
      }
3130
      if (snapshot.bookmark !== null) {
3131
        range.createFromBookmark(editable, snapshot.bookmark).select();
3132
      }
3133
    };
3134
 
3135
    /**
3136
    * @method rewind
3137
    * Rewinds the history stack back to the first snapshot taken.
3138
    * Leaves the stack intact, so that "Redo" can still be used.
3139
    */
3140
    this.rewind = function () {
3141
      // Create snap shot if not yet recorded
3142
      if ($editable.html() !== stack[stackOffset].contents) {
3143
        this.recordUndo();
3144
      }
3145
 
3146
      // Return to the first available snapshot.
3147
      stackOffset = 0;
3148
 
3149
      // Apply that snapshot.
3150
      applySnapshot(stack[stackOffset]);
3151
    };
3152
 
3153
    /**
3154
    * @method reset
3155
    * Resets the history stack completely; reverting to an empty editor.
3156
    */
3157
    this.reset = function () {
3158
      // Clear the stack.
3159
      stack = [];
3160
 
3161
      // Restore stackOffset to its original value.
3162
      stackOffset = -1;
3163
 
3164
      // Clear the editable area.
3165
      $editable.html('');
3166
 
3167
      // Record our first snapshot (of nothing).
3168
      this.recordUndo();
3169
    };
3170
 
3171
    /**
3172
     * undo
3173
     */
3174
    this.undo = function () {
3175
      // Create snap shot if not yet recorded
3176
      if ($editable.html() !== stack[stackOffset].contents) {
3177
        this.recordUndo();
3178
      }
3179
 
3180
      if (0 < stackOffset) {
3181
        stackOffset--;
3182
        applySnapshot(stack[stackOffset]);
3183
      }
3184
    };
3185
 
3186
    /**
3187
     * redo
3188
     */
3189
    this.redo = function () {
3190
      if (stack.length - 1 > stackOffset) {
3191
        stackOffset++;
3192
        applySnapshot(stack[stackOffset]);
3193
      }
3194
    };
3195
 
3196
    /**
3197
     * recorded undo
3198
     */
3199
    this.recordUndo = function () {
3200
      stackOffset++;
3201
 
3202
      // Wash out stack after stackOffset
3203
      if (stack.length > stackOffset) {
3204
        stack = stack.slice(0, stackOffset);
3205
      }
3206
 
3207
      // Create new snapshot and push it to the end
3208
      stack.push(makeSnapshot());
3209
    };
3210
  };
3211
 
3212
  /**
3213
   * @class editing.Style
3214
   *
3215
   * Style
3216
   *
3217
   */
3218
  var Style = function () {
3219
    /**
3220
     * @method jQueryCSS
3221
     *
3222
     * [workaround] for old jQuery
3223
     * passing an array of style properties to .css()
3224
     * will result in an object of property-value pairs.
3225
     * (compability with version < 1.9)
3226
     *
3227
     * @private
3228
     * @param  {jQuery} $obj
3229
     * @param  {Array} propertyNames - An array of one or more CSS properties.
3230
     * @return {Object}
3231
     */
3232
    var jQueryCSS = function ($obj, propertyNames) {
3233
      if (agent.jqueryVersion < 1.9) {
3234
        var result = {};
3235
        $.each(propertyNames, function (idx, propertyName) {
3236
          result[propertyName] = $obj.css(propertyName);
3237
        });
3238
        return result;
3239
      }
3240
      return $obj.css.call($obj, propertyNames);
3241
    };
3242
 
3243
    /**
3244
     * returns style object from node
3245
     *
3246
     * @param {jQuery} $node
3247
     * @return {Object}
3248
     */
3249
    this.fromNode = function ($node) {
3250
      var properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height'];
3251
      var styleInfo = jQueryCSS($node, properties) || {};
3252
      styleInfo['font-size'] = parseInt(styleInfo['font-size'], 10);
3253
      return styleInfo;
3254
    };
3255
 
3256
    /**
3257
     * paragraph level style
3258
     *
3259
     * @param {WrappedRange} rng
3260
     * @param {Object} styleInfo
3261
     */
3262
    this.stylePara = function (rng, styleInfo) {
3263
      $.each(rng.nodes(dom.isPara, {
3264
        includeAncestor: true
3265
      }), function (idx, para) {
3266
        $(para).css(styleInfo);
3267
      });
3268
    };
3269
 
3270
    /**
3271
     * insert and returns styleNodes on range.
3272
     *
3273
     * @param {WrappedRange} rng
3274
     * @param {Object} [options] - options for styleNodes
3275
     * @param {String} [options.nodeName] - default: `SPAN`
3276
     * @param {Boolean} [options.expandClosestSibling] - default: `false`
3277
     * @param {Boolean} [options.onlyPartialContains] - default: `false`
3278
     * @return {Node[]}
3279
     */
3280
    this.styleNodes = function (rng, options) {
3281
      rng = rng.splitText();
3282
 
3283
      var nodeName = options && options.nodeName || 'SPAN';
3284
      var expandClosestSibling = !!(options && options.expandClosestSibling);
3285
      var onlyPartialContains = !!(options && options.onlyPartialContains);
3286
 
3287
      if (rng.isCollapsed()) {
3288
        return [rng.insertNode(dom.create(nodeName))];
3289
      }
3290
 
3291
      var pred = dom.makePredByNodeName(nodeName);
3292
      var nodes = rng.nodes(dom.isText, {
3293
        fullyContains: true
3294
      }).map(function (text) {
3295
        return dom.singleChildAncestor(text, pred) || dom.wrap(text, nodeName);
3296
      });
3297
 
3298
      if (expandClosestSibling) {
3299
        if (onlyPartialContains) {
3300
          var nodesInRange = rng.nodes();
3301
          // compose with partial contains predication
3302
          pred = func.and(pred, function (node) {
3303
            return list.contains(nodesInRange, node);
3304
          });
3305
        }
3306
 
3307
        return nodes.map(function (node) {
3308
          var siblings = dom.withClosestSiblings(node, pred);
3309
          var head = list.head(siblings);
3310
          var tails = list.tail(siblings);
3311
          $.each(tails, function (idx, elem) {
3312
            dom.appendChildNodes(head, elem.childNodes);
3313
            dom.remove(elem);
3314
          });
3315
          return list.head(siblings);
3316
        });
3317
      } else {
3318
        return nodes;
3319
      }
3320
    };
3321
 
3322
    /**
3323
     * get current style on cursor
3324
     *
3325
     * @param {WrappedRange} rng
3326
     * @return {Object} - object contains style properties.
3327
     */
3328
    this.current = function (rng) {
3329
      var $cont = $(!dom.isElement(rng.sc) ? rng.sc.parentNode : rng.sc);
3330
      var styleInfo = this.fromNode($cont);
3331
 
3332
      // document.queryCommandState for toggle state
3333
      // [workaround] prevent Firefox nsresult: "0x80004005 (NS_ERROR_FAILURE)"
3334
      try {
3335
        styleInfo = $.extend(styleInfo, {
3336
          'font-bold': document.queryCommandState('bold') ? 'bold' : 'normal',
3337
          'font-italic': document.queryCommandState('italic') ? 'italic' : 'normal',
3338
          'font-underline': document.queryCommandState('underline') ? 'underline' : 'normal',
3339
          'font-subscript': document.queryCommandState('subscript') ? 'subscript' : 'normal',
3340
          'font-superscript': document.queryCommandState('superscript') ? 'superscript' : 'normal',
3341
          'font-strikethrough': document.queryCommandState('strikethrough') ? 'strikethrough' : 'normal'
3342
        });
3343
      } catch (e) {}
3344
 
3345
      // list-style-type to list-style(unordered, ordered)
3346
      if (!rng.isOnList()) {
3347
        styleInfo['list-style'] = 'none';
3348
      } else {
3349
        var orderedTypes = ['circle', 'disc', 'disc-leading-zero', 'square'];
3350
        var isUnordered = $.inArray(styleInfo['list-style-type'], orderedTypes) > -1;
3351
        styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered';
3352
      }
3353
 
3354
      var para = dom.ancestor(rng.sc, dom.isPara);
3355
      if (para && para.style['line-height']) {
3356
        styleInfo['line-height'] = para.style.lineHeight;
3357
      } else {
3358
        var lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10);
3359
        styleInfo['line-height'] = lineHeight.toFixed(1);
3360
      }
3361
 
3362
      styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor);
3363
      styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable);
3364
      styleInfo.range = rng;
3365
 
3366
      return styleInfo;
3367
    };
3368
  };
3369
 
3370
 
3371
  /**
3372
   * @class editing.Bullet
3373
   *
3374
   * @alternateClassName Bullet
3375
   */
3376
  var Bullet = function () {
3377
    var self = this;
3378
 
3379
    /**
3380
     * toggle ordered list
3381
     */
3382
    this.insertOrderedList = function (editable) {
3383
      this.toggleList('OL', editable);
3384
    };
3385
 
3386
    /**
3387
     * toggle unordered list
3388
     */
3389
    this.insertUnorderedList = function (editable) {
3390
      this.toggleList('UL', editable);
3391
    };
3392
 
3393
    /**
3394
     * indent
3395
     */
3396
    this.indent = function (editable) {
3397
      var self = this;
3398
      var rng = range.create(editable).wrapBodyInlineWithPara();
3399
 
3400
      var paras = rng.nodes(dom.isPara, { includeAncestor: true });
3401
      var clustereds = list.clusterBy(paras, func.peq2('parentNode'));
3402
 
3403
      $.each(clustereds, function (idx, paras) {
3404
        var head = list.head(paras);
3405
        if (dom.isLi(head)) {
3406
          self.wrapList(paras, head.parentNode.nodeName);
3407
        } else {
3408
          $.each(paras, function (idx, para) {
3409
            $(para).css('marginLeft', function (idx, val) {
3410
              return (parseInt(val, 10) || 0) + 25;
3411
            });
3412
          });
3413
        }
3414
      });
3415
 
3416
      rng.select();
3417
    };
3418
 
3419
    /**
3420
     * outdent
3421
     */
3422
    this.outdent = function (editable) {
3423
      var self = this;
3424
      var rng = range.create(editable).wrapBodyInlineWithPara();
3425
 
3426
      var paras = rng.nodes(dom.isPara, { includeAncestor: true });
3427
      var clustereds = list.clusterBy(paras, func.peq2('parentNode'));
3428
 
3429
      $.each(clustereds, function (idx, paras) {
3430
        var head = list.head(paras);
3431
        if (dom.isLi(head)) {
3432
          self.releaseList([paras]);
3433
        } else {
3434
          $.each(paras, function (idx, para) {
3435
            $(para).css('marginLeft', function (idx, val) {
3436
              val = (parseInt(val, 10) || 0);
3437
              return val > 25 ? val - 25 : '';
3438
            });
3439
          });
3440
        }
3441
      });
3442
 
3443
      rng.select();
3444
    };
3445
 
3446
    /**
3447
     * toggle list
3448
     *
3449
     * @param {String} listName - OL or UL
3450
     */
3451
    this.toggleList = function (listName, editable) {
3452
      var rng = range.create(editable).wrapBodyInlineWithPara();
3453
 
3454
      var paras = rng.nodes(dom.isPara, { includeAncestor: true });
3455
      var bookmark = rng.paraBookmark(paras);
3456
      var clustereds = list.clusterBy(paras, func.peq2('parentNode'));
3457
 
3458
      // paragraph to list
3459
      if (list.find(paras, dom.isPurePara)) {
3460
        var wrappedParas = [];
3461
        $.each(clustereds, function (idx, paras) {
3462
          wrappedParas = wrappedParas.concat(self.wrapList(paras, listName));
3463
        });
3464
        paras = wrappedParas;
3465
      // list to paragraph or change list style
3466
      } else {
3467
        var diffLists = rng.nodes(dom.isList, {
3468
          includeAncestor: true
3469
        }).filter(function (listNode) {
3470
          return !$.nodeName(listNode, listName);
3471
        });
3472
 
3473
        if (diffLists.length) {
3474
          $.each(diffLists, function (idx, listNode) {
3475
            dom.replace(listNode, listName);
3476
          });
3477
        } else {
3478
          paras = this.releaseList(clustereds, true);
3479
        }
3480
      }
3481
 
3482
      range.createFromParaBookmark(bookmark, paras).select();
3483
    };
3484
 
3485
    /**
3486
     * @param {Node[]} paras
3487
     * @param {String} listName
3488
     * @return {Node[]}
3489
     */
3490
    this.wrapList = function (paras, listName) {
3491
      var head = list.head(paras);
3492
      var last = list.last(paras);
3493
 
3494
      var prevList = dom.isList(head.previousSibling) && head.previousSibling;
3495
      var nextList = dom.isList(last.nextSibling) && last.nextSibling;
3496
 
3497
      var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last);
3498
 
3499
      // P to LI
3500
      paras = paras.map(function (para) {
3501
        return dom.isPurePara(para) ? dom.replace(para, 'LI') : para;
3502
      });
3503
 
3504
      // append to list(<ul>, <ol>)
3505
      dom.appendChildNodes(listNode, paras);
3506
 
3507
      if (nextList) {
3508
        dom.appendChildNodes(listNode, list.from(nextList.childNodes));
3509
        dom.remove(nextList);
3510
      }
3511
 
3512
      return paras;
3513
    };
3514
 
3515
    /**
3516
     * @method releaseList
3517
     *
3518
     * @param {Array[]} clustereds
3519
     * @param {Boolean} isEscapseToBody
3520
     * @return {Node[]}
3521
     */
3522
    this.releaseList = function (clustereds, isEscapseToBody) {
3523
      var releasedParas = [];
3524
 
3525
      $.each(clustereds, function (idx, paras) {
3526
        var head = list.head(paras);
3527
        var last = list.last(paras);
3528
 
3529
        var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) :
3530
                                         head.parentNode;
3531
        var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, {
3532
          node: last.parentNode,
3533
          offset: dom.position(last) + 1
3534
        }, {
3535
          isSkipPaddingBlankHTML: true
3536
        }) : null;
3537
 
3538
        var middleList = dom.splitTree(headList, {
3539
          node: head.parentNode,
3540
          offset: dom.position(head)
3541
        }, {
3542
          isSkipPaddingBlankHTML: true
3543
        });
3544
 
3545
        paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) :
3546
                                  list.from(middleList.childNodes).filter(dom.isLi);
3547
 
3548
        // LI to P
3549
        if (isEscapseToBody || !dom.isList(headList.parentNode)) {
3550
          paras = paras.map(function (para) {
3551
            return dom.replace(para, 'P');
3552
          });
3553
        }
3554
 
3555
        $.each(list.from(paras).reverse(), function (idx, para) {
3556
          dom.insertAfter(para, headList);
3557
        });
3558
 
3559
        // remove empty lists
3560
        var rootLists = list.compact([headList, middleList, lastList]);
3561
        $.each(rootLists, function (idx, rootList) {
3562
          var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList));
3563
          $.each(listNodes.reverse(), function (idx, listNode) {
3564
            if (!dom.nodeLength(listNode)) {
3565
              dom.remove(listNode, true);
3566
            }
3567
          });
3568
        });
3569
 
3570
        releasedParas = releasedParas.concat(paras);
3571
      });
3572
 
3573
      return releasedParas;
3574
    };
3575
  };
3576
 
3577
 
3578
  /**
3579
   * @class editing.Typing
3580
   *
3581
   * Typing
3582
   *
3583
   */
3584
  var Typing = function () {
3585
 
3586
    // a Bullet instance to toggle lists off
3587
    var bullet = new Bullet();
3588
 
3589
    /**
3590
     * insert tab
3591
     *
3592
     * @param {WrappedRange} rng
3593
     * @param {Number} tabsize
3594
     */
3595
    this.insertTab = function (rng, tabsize) {
3596
      var tab = dom.createText(new Array(tabsize + 1).join(dom.NBSP_CHAR));
3597
      rng = rng.deleteContents();
3598
      rng.insertNode(tab, true);
3599
 
3600
      rng = range.create(tab, tabsize);
3601
      rng.select();
3602
    };
3603
 
3604
    /**
3605
     * insert paragraph
3606
     */
3607
    this.insertParagraph = function (editable) {
3608
      var rng = range.create(editable);
3609
 
3610
      // deleteContents on range.
3611
      rng = rng.deleteContents();
3612
 
3613
      // Wrap range if it needs to be wrapped by paragraph
3614
      rng = rng.wrapBodyInlineWithPara();
3615
 
3616
      // finding paragraph
3617
      var splitRoot = dom.ancestor(rng.sc, dom.isPara);
3618
 
3619
      var nextPara;
3620
      // on paragraph: split paragraph
3621
      if (splitRoot) {
3622
        // if it is an empty line with li
3623
        if (dom.isEmpty(splitRoot) && dom.isLi(splitRoot)) {
3624
          // toogle UL/OL and escape
3625
          bullet.toggleList(splitRoot.parentNode.nodeName);
3626
          return;
3627
        // if it is an empty line with para on blockquote
3628
        } else if (dom.isEmpty(splitRoot) && dom.isPara(splitRoot) && dom.isBlockquote(splitRoot.parentNode)) {
3629
          // escape blockquote
3630
          dom.insertAfter(splitRoot, splitRoot.parentNode);
3631
          nextPara = splitRoot;
3632
        // if new line has content (not a line break)
3633
        } else {
3634
          nextPara = dom.splitTree(splitRoot, rng.getStartPoint());
3635
 
3636
          var emptyAnchors = dom.listDescendant(splitRoot, dom.isEmptyAnchor);
3637
          emptyAnchors = emptyAnchors.concat(dom.listDescendant(nextPara, dom.isEmptyAnchor));
3638
 
3639
          $.each(emptyAnchors, function (idx, anchor) {
3640
            dom.remove(anchor);
3641
          });
3642
 
3643
          // replace empty heading or pre with P tag
3644
          if ((dom.isHeading(nextPara) || dom.isPre(nextPara)) && dom.isEmpty(nextPara)) {
3645
            nextPara = dom.replace(nextPara, 'p');
3646
          }
3647
        }
3648
      // no paragraph: insert empty paragraph
3649
      } else {
3650
        var next = rng.sc.childNodes[rng.so];
3651
        nextPara = $(dom.emptyPara)[0];
3652
        if (next) {
3653
          rng.sc.insertBefore(nextPara, next);
3654
        } else {
3655
          rng.sc.appendChild(nextPara);
3656
        }
3657
      }
3658
 
3659
      range.create(nextPara, 0).normalize().select().scrollIntoView(editable);
3660
    };
3661
  };
3662
 
3663
  /**
3664
   * @class editing.Table
3665
   *
3666
   * Table
3667
   *
3668
   */
3669
  var Table = function () {
3670
    /**
3671
     * handle tab key
3672
     *
3673
     * @param {WrappedRange} rng
3674
     * @param {Boolean} isShift
3675
     */
3676
    this.tab = function (rng, isShift) {
3677
      var cell = dom.ancestor(rng.commonAncestor(), dom.isCell);
3678
      var table = dom.ancestor(cell, dom.isTable);
3679
      var cells = dom.listDescendant(table, dom.isCell);
3680
 
3681
      var nextCell = list[isShift ? 'prev' : 'next'](cells, cell);
3682
      if (nextCell) {
3683
        range.create(nextCell, 0).select();
3684
      }
3685
    };
3686
 
3687
    /**
3688
     * create empty table element
3689
     *
3690
     * @param {Number} rowCount
3691
     * @param {Number} colCount
3692
     * @return {Node}
3693
     */
3694
    this.createTable = function (colCount, rowCount, options) {
3695
      var tds = [], tdHTML;
3696
      for (var idxCol = 0; idxCol < colCount; idxCol++) {
3697
        tds.push('<td>' + dom.blank + '</td>');
3698
      }
3699
      tdHTML = tds.join('');
3700
 
3701
      var trs = [], trHTML;
3702
      for (var idxRow = 0; idxRow < rowCount; idxRow++) {
3703
        trs.push('<tr>' + tdHTML + '</tr>');
3704
      }
3705
      trHTML = trs.join('');
3706
      var $table = $('<table>' + trHTML + '</table>');
3707
      if (options && options.tableClassName) {
3708
        $table.addClass(options.tableClassName);
3709
      }
3710
 
3711
      return $table[0];
3712
    };
3713
  };
3714
 
3715
 
3716
  var KEY_BOGUS = 'bogus';
3717
 
3718
  /**
3719
   * @class Editor
3720
   */
3721
  var Editor = function (context) {
3722
    var self = this;
3723
 
3724
    var $note = context.layoutInfo.note;
3725
    var $editor = context.layoutInfo.editor;
3726
    var $editable = context.layoutInfo.editable;
3727
    var options = context.options;
3728
    var lang = options.langInfo;
3729
 
3730
    var editable = $editable[0];
3731
    var lastRange = null;
3732
 
3733
    var style = new Style();
3734
    var table = new Table();
3735
    var typing = new Typing();
3736
    var bullet = new Bullet();
3737
    var history = new History($editable);
3738
 
3739
    this.initialize = function () {
3740
      // bind custom events
3741
      $editable.on('keydown', function (event) {
3742
        if (event.keyCode === key.code.ENTER) {
3743
          context.triggerEvent('enter', event);
3744
        }
3745
        context.triggerEvent('keydown', event);
3746
 
3747
        if (options.shortcuts && !event.isDefaultPrevented()) {
3748
          self.handleKeyMap(event);
3749
        }
3750
      }).on('keyup', function (event) {
3751
        context.triggerEvent('keyup', event);
3752
      }).on('focus', function (event) {
3753
        context.triggerEvent('focus', event);
3754
      }).on('blur', function (event) {
3755
        context.triggerEvent('blur', event);
3756
      }).on('mousedown', function (event) {
3757
        context.triggerEvent('mousedown', event);
3758
      }).on('mouseup', function (event) {
3759
        context.triggerEvent('mouseup', event);
3760
      }).on('scroll', function (event) {
3761
        context.triggerEvent('scroll', event);
3762
      }).on('paste', function (event) {
3763
        context.triggerEvent('paste', event);
3764
      });
3765
 
3766
      // init content before set event
3767
      $editable.html(dom.html($note) || dom.emptyPara);
3768
 
3769
      // [workaround] IE doesn't have input events for contentEditable
3770
      // - see: https://goo.gl/4bfIvA
3771
      var changeEventName = agent.isMSIE ? 'DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted' : 'input';
3772
      $editable.on(changeEventName, function () {
3773
        context.triggerEvent('change', $editable.html());
3774
      });
3775
 
3776
      $editor.on('focusin', function (event) {
3777
        context.triggerEvent('focusin', event);
3778
      }).on('focusout', function (event) {
3779
        context.triggerEvent('focusout', event);
3780
      });
3781
 
3782
      if (!options.airMode && options.height) {
3783
        this.setHeight(options.height);
3784
      }
3785
      if (!options.airMode && options.maxHeight) {
3786
        $editable.css('max-height', options.maxHeight);
3787
      }
3788
      if (!options.airMode && options.minHeight) {
3789
        $editable.css('min-height', options.minHeight);
3790
      }
3791
 
3792
      history.recordUndo();
3793
    };
3794
 
3795
    this.destroy = function () {
3796
      $editable.off();
3797
    };
3798
 
3799
    this.handleKeyMap = function (event) {
3800
      var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc'];
3801
      var keys = [];
3802
 
3803
      if (event.metaKey) { keys.push('CMD'); }
3804
      if (event.ctrlKey && !event.altKey) { keys.push('CTRL'); }
3805
      if (event.shiftKey) { keys.push('SHIFT'); }
3806
 
3807
      var keyName = key.nameFromCode[event.keyCode];
3808
      if (keyName) {
3809
        keys.push(keyName);
3810
      }
3811
 
3812
      var eventName = keyMap[keys.join('+')];
3813
      if (eventName) {
3814
        event.preventDefault();
3815
        context.invoke(eventName);
3816
      } else if (key.isEdit(event.keyCode)) {
3817
        this.afterCommand();
3818
      }
3819
    };
3820
 
3821
    /**
3822
     * create range
3823
     * @return {WrappedRange}
3824
     */
3825
    this.createRange = function () {
3826
      this.focus();
3827
      return range.create(editable);
3828
    };
3829
 
3830
    /**
3831
     * saveRange
3832
     *
3833
     * save current range
3834
     *
3835
     * @param {Boolean} [thenCollapse=false]
3836
     */
3837
    this.saveRange = function (thenCollapse) {
3838
      lastRange = this.createRange();
3839
      if (thenCollapse) {
3840
        lastRange.collapse().select();
3841
      }
3842
    };
3843
 
3844
    /**
3845
     * restoreRange
3846
     *
3847
     * restore lately range
3848
     */
3849
    this.restoreRange = function () {
3850
      if (lastRange) {
3851
        lastRange.select();
3852
        this.focus();
3853
      }
3854
    };
3855
 
3856
    this.saveTarget = function (node) {
3857
      $editable.data('target', node);
3858
    };
3859
 
3860
    this.clearTarget = function () {
3861
      $editable.removeData('target');
3862
    };
3863
 
3864
    this.restoreTarget = function () {
3865
      return $editable.data('target');
3866
    };
3867
 
3868
    /**
3869
     * currentStyle
3870
     *
3871
     * current style
3872
     * @return {Object|Boolean} unfocus
3873
     */
3874
    this.currentStyle = function () {
3875
      var rng = range.create();
3876
      if (rng) {
3877
        rng = rng.normalize();
3878
      }
3879
      return rng ? style.current(rng) : style.fromNode($editable);
3880
    };
3881
 
3882
    /**
3883
     * style from node
3884
     *
3885
     * @param {jQuery} $node
3886
     * @return {Object}
3887
     */
3888
    this.styleFromNode = function ($node) {
3889
      return style.fromNode($node);
3890
    };
3891
 
3892
    /**
3893
     * undo
3894
     */
3895
    this.undo = function () {
3896
      context.triggerEvent('before.command', $editable.html());
3897
      history.undo();
3898
      context.triggerEvent('change', $editable.html());
3899
    };
3900
    context.memo('help.undo', lang.help.undo);
3901
 
3902
    /**
3903
     * redo
3904
     */
3905
    this.redo = function () {
3906
      context.triggerEvent('before.command', $editable.html());
3907
      history.redo();
3908
      context.triggerEvent('change', $editable.html());
3909
    };
3910
    context.memo('help.redo', lang.help.redo);
3911
 
3912
    /**
3913
     * before command
3914
     */
3915
    var beforeCommand = this.beforeCommand = function () {
3916
      context.triggerEvent('before.command', $editable.html());
3917
      // keep focus on editable before command execution
3918
      self.focus();
3919
    };
3920
 
3921
    /**
3922
     * after command
3923
     * @param {Boolean} isPreventTrigger
3924
     */
3925
    var afterCommand = this.afterCommand = function (isPreventTrigger) {
3926
      history.recordUndo();
3927
      if (!isPreventTrigger) {
3928
        context.triggerEvent('change', $editable.html());
3929
      }
3930
    };
3931
 
3932
    /* jshint ignore:start */
3933
    // native commands(with execCommand), generate function for execCommand
3934
    var commands = ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript',
3935
                    'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull',
3936
                    'formatBlock', 'removeFormat',
3937
                    'backColor', 'foreColor', 'fontName'];
3938
 
3939
    for (var idx = 0, len = commands.length; idx < len; idx ++) {
3940
      this[commands[idx]] = (function (sCmd) {
3941
        return function (value) {
3942
          beforeCommand();
3943
          document.execCommand(sCmd, false, value);
3944
          afterCommand(true);
3945
        };
3946
      })(commands[idx]);
3947
      context.memo('help.' + commands[idx], lang.help[commands[idx]]);
3948
    }
3949
    /* jshint ignore:end */
3950
 
3951
    /**
3952
     * handle tab key
3953
     */
3954
    this.tab = function () {
3955
      var rng = this.createRange();
3956
      if (rng.isCollapsed() && rng.isOnCell()) {
3957
        table.tab(rng);
3958
      } else {
3959
        beforeCommand();
3960
        typing.insertTab(rng, options.tabSize);
3961
        afterCommand();
3962
      }
3963
    };
3964
    context.memo('help.tab', lang.help.tab);
3965
 
3966
    /**
3967
     * handle shift+tab key
3968
     */
3969
    this.untab = function () {
3970
      var rng = this.createRange();
3971
      if (rng.isCollapsed() && rng.isOnCell()) {
3972
        table.tab(rng, true);
3973
      }
3974
    };
3975
    context.memo('help.untab', lang.help.untab);
3976
 
3977
    /**
3978
     * run given function between beforeCommand and afterCommand
3979
     */
3980
    this.wrapCommand = function (fn) {
3981
      return function () {
3982
        beforeCommand();
3983
        fn.apply(self, arguments);
3984
        afterCommand();
3985
      };
3986
    };
3987
 
3988
    /**
3989
     * insert paragraph
3990
     */
3991
    this.insertParagraph = this.wrapCommand(function () {
3992
      typing.insertParagraph(editable);
3993
    });
3994
    context.memo('help.insertParagraph', lang.help.insertParagraph);
3995
 
3996
    this.insertOrderedList = this.wrapCommand(function () {
3997
      bullet.insertOrderedList(editable);
3998
    });
3999
    context.memo('help.insertOrderedList', lang.help.insertOrderedList);
4000
 
4001
    this.insertUnorderedList = this.wrapCommand(function () {
4002
      bullet.insertUnorderedList(editable);
4003
    });
4004
    context.memo('help.insertUnorderedList', lang.help.insertUnorderedList);
4005
 
4006
    this.indent = this.wrapCommand(function () {
4007
      bullet.indent(editable);
4008
    });
4009
    context.memo('help.indent', lang.help.indent);
4010
 
4011
    this.outdent = this.wrapCommand(function () {
4012
      bullet.outdent(editable);
4013
    });
4014
    context.memo('help.outdent', lang.help.outdent);
4015
 
4016
    /**
4017
     * insert image
4018
     *
4019
     * @param {String} src
4020
     * @param {String|Function} param
4021
     * @return {Promise}
4022
     */
4023
    this.insertImage = function (src, param) {
4024
      return async.createImage(src, param).then(function ($image) {
4025
        beforeCommand();
4026
 
4027
        if (typeof param === 'function') {
4028
          param($image);
4029
        } else {
4030
          if (typeof param === 'string') {
4031
            $image.attr('data-filename', param);
4032
          }
4033
          $image.css('width', Math.min($editable.width(), $image.width()));
4034
        }
4035
 
4036
        $image.show();
4037
        range.create(editable).insertNode($image[0]);
4038
        range.createFromNodeAfter($image[0]).select();
4039
        afterCommand();
4040
      }).fail(function (e) {
4041
        context.triggerEvent('image.upload.error', e);
4042
      });
4043
    };
4044
 
4045
    /**
4046
     * insertImages
4047
     * @param {File[]} files
4048
     */
4049
    this.insertImages = function (files) {
4050
      $.each(files, function (idx, file) {
4051
        var filename = file.name;
4052
        if (options.maximumImageFileSize && options.maximumImageFileSize < file.size) {
4053
          context.triggerEvent('image.upload.error', lang.image.maximumFileSizeError);
4054
        } else {
4055
          async.readFileAsDataURL(file).then(function (dataURL) {
4056
            return self.insertImage(dataURL, filename);
4057
          }).fail(function () {
4058
            context.triggerEvent('image.upload.error');
4059
          });
4060
        }
4061
      });
4062
    };
4063
 
4064
    /**
4065
     * insertImagesOrCallback
4066
     * @param {File[]} files
4067
     */
4068
    this.insertImagesOrCallback = function (files) {
4069
      var callbacks = options.callbacks;
4070
 
4071
      // If onImageUpload options setted
4072
      if (callbacks.onImageUpload) {
4073
        context.triggerEvent('image.upload', files);
4074
      // else insert Image as dataURL
4075
      } else {
4076
        this.insertImages(files);
4077
      }
4078
    };
4079
 
4080
    /**
4081
     * insertNode
4082
     * insert node
4083
     * @param {Node} node
4084
     */
4085
    this.insertNode = this.wrapCommand(function (node) {
4086
      var rng = this.createRange();
4087
      rng.insertNode(node);
4088
      range.createFromNodeAfter(node).select();
4089
    });
4090
 
4091
    /**
4092
     * insert text
4093
     * @param {String} text
4094
     */
4095
    this.insertText = this.wrapCommand(function (text) {
4096
      var rng = this.createRange();
4097
      var textNode = rng.insertNode(dom.createText(text));
4098
      range.create(textNode, dom.nodeLength(textNode)).select();
4099
    });
4100
 
4101
    /**
4102
     * return selected plain text
4103
     * @return {String} text
4104
     */
4105
    this.getSelectedText = function () {
4106
      var rng = this.createRange();
4107
 
4108
      // if range on anchor, expand range with anchor
4109
      if (rng.isOnAnchor()) {
4110
        rng = range.createFromNode(dom.ancestor(rng.sc, dom.isAnchor));
4111
      }
4112
 
4113
      return rng.toString();
4114
    };
4115
 
4116
    /**
4117
     * paste HTML
4118
     * @param {String} markup
4119
     */
4120
    this.pasteHTML = this.wrapCommand(function (markup) {
4121
      var contents = this.createRange().pasteHTML(markup);
4122
      range.createFromNodeAfter(list.last(contents)).select();
4123
    });
4124
 
4125
    /**
4126
     * formatBlock
4127
     *
4128
     * @param {String} tagName
4129
     */
4130
    this.formatBlock = this.wrapCommand(function (tagName) {
4131
      // [workaround] for MSIE, IE need `<`
4132
      tagName = agent.isMSIE ? '<' + tagName + '>' : tagName;
4133
      document.execCommand('FormatBlock', false, tagName);
4134
    });
4135
 
4136
    this.formatPara = function () {
4137
      this.formatBlock('P');
4138
    };
4139
    context.memo('help.formatPara', lang.help.formatPara);
4140
 
4141
    /* jshint ignore:start */
4142
    for (var idx = 1; idx <= 6; idx ++) {
4143
      this['formatH' + idx] = function (idx) {
4144
        return function () {
4145
          this.formatBlock('H' + idx);
4146
        };
4147
      }(idx);
4148
      context.memo('help.formatH'+idx, lang.help['formatH' + idx]);
4149
    };
4150
    /* jshint ignore:end */
4151
 
4152
    /**
4153
     * fontSize
4154
     *
4155
     * @param {String} value - px
4156
     */
4157
    this.fontSize = function (value) {
4158
      var rng = this.createRange();
4159
 
4160
      if (rng && rng.isCollapsed()) {
4161
        var spans = style.styleNodes(rng);
4162
        var firstSpan = list.head(spans);
4163
 
4164
        $(spans).css({
4165
          'font-size': value + 'px'
4166
        });
4167
 
4168
        // [workaround] added styled bogus span for style
4169
        //  - also bogus character needed for cursor position
4170
        if (firstSpan && !dom.nodeLength(firstSpan)) {
4171
          firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR;
4172
          range.createFromNodeAfter(firstSpan.firstChild).select();
4173
          $editable.data(KEY_BOGUS, firstSpan);
4174
        }
4175
      } else {
4176
        beforeCommand();
4177
        $(style.styleNodes(rng)).css({
4178
          'font-size': value + 'px'
4179
        });
4180
        afterCommand();
4181
      }
4182
    };
4183
 
4184
    /**
4185
     * insert horizontal rule
4186
     */
4187
    this.insertHorizontalRule = this.wrapCommand(function () {
4188
      var hrNode = this.createRange().insertNode(dom.create('HR'));
4189
      if (hrNode.nextSibling) {
4190
        range.create(hrNode.nextSibling, 0).normalize().select();
4191
      }
4192
    });
4193
    context.memo('help.insertHorizontalRule', lang.help.insertHorizontalRule);
4194
 
4195
    /**
4196
     * remove bogus node and character
4197
     */
4198
    this.removeBogus = function () {
4199
      var bogusNode = $editable.data(KEY_BOGUS);
4200
      if (!bogusNode) {
4201
        return;
4202
      }
4203
 
4204
      var textNode = list.find(list.from(bogusNode.childNodes), dom.isText);
4205
 
4206
      var bogusCharIdx = textNode.nodeValue.indexOf(dom.ZERO_WIDTH_NBSP_CHAR);
4207
      if (bogusCharIdx !== -1) {
4208
        textNode.deleteData(bogusCharIdx, 1);
4209
      }
4210
 
4211
      if (dom.isEmpty(bogusNode)) {
4212
        dom.remove(bogusNode);
4213
      }
4214
 
4215
      $editable.removeData(KEY_BOGUS);
4216
    };
4217
 
4218
    /**
4219
     * lineHeight
4220
     * @param {String} value
4221
     */
4222
    this.lineHeight = this.wrapCommand(function (value) {
4223
      style.stylePara(this.createRange(), {
4224
        lineHeight: value
4225
      });
4226
    });
4227
 
4228
    /**
4229
     * unlink
4230
     *
4231
     * @type command
4232
     */
4233
    this.unlink = function () {
4234
      var rng = this.createRange();
4235
      if (rng.isOnAnchor()) {
4236
        var anchor = dom.ancestor(rng.sc, dom.isAnchor);
4237
        rng = range.createFromNode(anchor);
4238
        rng.select();
4239
 
4240
        beforeCommand();
4241
        document.execCommand('unlink');
4242
        afterCommand();
4243
      }
4244
    };
4245
 
4246
    /**
4247
     * create link (command)
4248
     *
4249
     * @param {Object} linkInfo
4250
     */
4251
    this.createLink = this.wrapCommand(function (linkInfo) {
4252
      var linkUrl = linkInfo.url;
4253
      var linkText = linkInfo.text;
4254
      var isNewWindow = linkInfo.isNewWindow;
4255
      var rng = linkInfo.range || this.createRange();
4256
      var isTextChanged = rng.toString() !== linkText;
4257
 
4258
      if (options.onCreateLink) {
4259
        linkUrl = options.onCreateLink(linkUrl);
4260
      }
4261
 
4262
      var anchors = [];
4263
      if (isTextChanged) {
4264
        rng = rng.deleteContents();
4265
        var anchor = rng.insertNode($('<A>' + linkText + '</A>')[0]);
4266
        anchors.push(anchor);
4267
      } else {
4268
        anchors = style.styleNodes(rng, {
4269
          nodeName: 'A',
4270
          expandClosestSibling: true,
4271
          onlyPartialContains: true
4272
        });
4273
      }
4274
 
4275
      $.each(anchors, function (idx, anchor) {
4276
        $(anchor).attr('href', linkUrl);
4277
        if (isNewWindow) {
4278
          $(anchor).attr('target', '_blank');
4279
        } else {
4280
          $(anchor).removeAttr('target');
4281
        }
4282
      });
4283
 
4284
      var startRange = range.createFromNodeBefore(list.head(anchors));
4285
      var startPoint = startRange.getStartPoint();
4286
      var endRange = range.createFromNodeAfter(list.last(anchors));
4287
      var endPoint = endRange.getEndPoint();
4288
 
4289
      range.create(
4290
        startPoint.node,
4291
        startPoint.offset,
4292
        endPoint.node,
4293
        endPoint.offset
4294
      ).select();
4295
    });
4296
 
4297
    /**
4298
     * returns link info
4299
     *
4300
     * @return {Object}
4301
     * @return {WrappedRange} return.range
4302
     * @return {String} return.text
4303
     * @return {Boolean} [return.isNewWindow=true]
4304
     * @return {String} [return.url=""]
4305
     */
4306
    this.getLinkInfo = function () {
4307
      var rng = this.createRange().expand(dom.isAnchor);
4308
 
4309
      // Get the first anchor on range(for edit).
4310
      var $anchor = $(list.head(rng.nodes(dom.isAnchor)));
4311
 
4312
      return {
4313
        range: rng,
4314
        text: rng.toString(),
4315
        isNewWindow: $anchor.length ? $anchor.attr('target') === '_blank' : false,
4316
        url: $anchor.length ? $anchor.attr('href') : ''
4317
      };
4318
    };
4319
 
4320
    /**
4321
     * setting color
4322
     *
4323
     * @param {Object} sObjColor  color code
4324
     * @param {String} sObjColor.foreColor foreground color
4325
     * @param {String} sObjColor.backColor background color
4326
     */
4327
    this.color = this.wrapCommand(function (colorInfo) {
4328
      var foreColor = colorInfo.foreColor;
4329
      var backColor = colorInfo.backColor;
4330
 
4331
      if (foreColor) { document.execCommand('foreColor', false, foreColor); }
4332
      if (backColor) { document.execCommand('backColor', false, backColor); }
4333
    });
4334
 
4335
    /**
4336
     * insert Table
4337
     *
4338
     * @param {String} dimension of table (ex : "5x5")
4339
     */
4340
    this.insertTable = this.wrapCommand(function (dim) {
4341
      var dimension = dim.split('x');
4342
 
4343
      var rng = this.createRange().deleteContents();
4344
      rng.insertNode(table.createTable(dimension[0], dimension[1], options));
4345
    });
4346
 
4347
    /**
4348
     * float me
4349
     *
4350
     * @param {String} value
4351
     */
4352
    this.floatMe = this.wrapCommand(function (value) {
4353
      var $target = $(this.restoreTarget());
4354
      $target.css('float', value);
4355
    });
4356
 
4357
    /**
4358
     * resize overlay element
4359
     * @param {String} value
4360
     */
4361
    this.resize = this.wrapCommand(function (value) {
4362
      var $target = $(this.restoreTarget());
4363
      $target.css({
4364
        width: value * 100 + '%',
4365
        height: ''
4366
      });
4367
    });
4368
 
4369
    /**
4370
     * @param {Position} pos
4371
     * @param {jQuery} $target - target element
4372
     * @param {Boolean} [bKeepRatio] - keep ratio
4373
     */
4374
    this.resizeTo = function (pos, $target, bKeepRatio) {
4375
      var imageSize;
4376
      if (bKeepRatio) {
4377
        var newRatio = pos.y / pos.x;
4378
        var ratio = $target.data('ratio');
4379
        imageSize = {
4380
          width: ratio > newRatio ? pos.x : pos.y / ratio,
4381
          height: ratio > newRatio ? pos.x * ratio : pos.y
4382
        };
4383
      } else {
4384
        imageSize = {
4385
          width: pos.x,
4386
          height: pos.y
4387
        };
4388
      }
4389
 
4390
      $target.css(imageSize);
4391
    };
4392
 
4393
    /**
4394
     * remove media object
4395
     */
4396
    this.removeMedia = this.wrapCommand(function () {
4397
      var $target = $(this.restoreTarget()).detach();
4398
      context.triggerEvent('media.delete', $target, $editable);
4399
    });
4400
 
4401
    /**
4402
     * returns whether editable area has focus or not.
4403
     */
4404
    this.hasFocus = function () {
4405
      return $editable.is(':focus');
4406
    };
4407
 
4408
    /**
4409
     * set focus
4410
     */
4411
    this.focus = function () {
4412
      // [workaround] Screen will move when page is scolled in IE.
4413
      //  - do focus when not focused
4414
      if (!this.hasFocus()) {
4415
        $editable.focus();
4416
      }
4417
    };
4418
 
4419
    /**
4420
     * returns whether contents is empty or not.
4421
     * @return {Boolean}
4422
     */
4423
    this.isEmpty = function () {
4424
      return dom.isEmpty($editable[0]) || dom.emptyPara === $editable.html();
4425
    };
4426
 
4427
    /**
4428
     * Removes all contents and restores the editable instance to an _emptyPara_.
4429
     */
4430
    this.empty = function () {
4431
      context.invoke('code', dom.emptyPara);
4432
    };
4433
 
4434
    /**
4435
     * set height for editable
4436
     */
4437
    this.setHeight = function (height) {
4438
      $editable.outerHeight(height);
4439
    };
4440
  };
4441
 
4442
  var Clipboard = function (context) {
4443
    var self = this;
4444
 
4445
    var $editable = context.layoutInfo.editable;
4446
 
4447
    this.events = {
4448
      'summernote.keydown': function (we, e) {
4449
        if (self.needKeydownHook()) {
4450
          if ((e.ctrlKey || e.metaKey) && e.keyCode === key.code.V) {
4451
            context.invoke('editor.saveRange');
4452
            self.$paste.focus();
4453
 
4454
            setTimeout(function () {
4455
              self.pasteByHook();
4456
            }, 0);
4457
          }
4458
        }
4459
      }
4460
    };
4461
 
4462
    this.needKeydownHook = function () {
4463
      return (agent.isMSIE && agent.browserVersion > 10) || agent.isFF;
4464
    };
4465
 
4466
    this.initialize = function () {
4467
      // [workaround] getting image from clipboard
4468
      //  - IE11 and Firefox: CTRL+v hook
4469
      //  - Webkit: event.clipboardData
4470
      if (this.needKeydownHook()) {
4471
        this.$paste = $('<div />').attr('contenteditable', true).css({
4472
          position: 'absolute',
4473
          left: -100000,
4474
          opacity: 0
4475
        });
4476
        $editable.before(this.$paste);
4477
 
4478
        this.$paste.on('paste', function (event) {
4479
          context.triggerEvent('paste', event);
4480
        });
4481
      } else {
4482
        $editable.on('paste', this.pasteByEvent);
4483
      }
4484
    };
4485
 
4486
    this.destroy = function () {
4487
      if (this.needKeydownHook()) {
4488
        this.$paste.remove();
4489
        this.$paste = null;
4490
      }
4491
    };
4492
 
4493
    this.pasteByHook = function () {
4494
      var node = this.$paste[0].firstChild;
4495
 
4496
      if (dom.isImg(node)) {
4497
        var dataURI = node.src;
4498
        var decodedData = atob(dataURI.split(',')[1]);
4499
        var array = new Uint8Array(decodedData.length);
4500
        for (var i = 0; i < decodedData.length; i++) {
4501
          array[i] = decodedData.charCodeAt(i);
4502
        }
4503
 
4504
        var blob = new Blob([array], { type: 'image/png' });
4505
        blob.name = 'clipboard.png';
4506
 
4507
        context.invoke('editor.restoreRange');
4508
        context.invoke('editor.focus');
4509
        context.invoke('editor.insertImagesOrCallback', [blob]);
4510
      } else {
4511
        var pasteContent = $('<div />').html(this.$paste.html()).html();
4512
        context.invoke('editor.restoreRange');
4513
        context.invoke('editor.focus');
4514
 
4515
        if (pasteContent) {
4516
          context.invoke('editor.pasteHTML', pasteContent);
4517
        }
4518
      }
4519
 
4520
      this.$paste.empty();
4521
    };
4522
 
4523
    /**
4524
     * paste by clipboard event
4525
     *
4526
     * @param {Event} event
4527
     */
4528
    this.pasteByEvent = function (event) {
4529
      var clipboardData = event.originalEvent.clipboardData;
4530
      if (clipboardData && clipboardData.items && clipboardData.items.length) {
4531
        var item = list.head(clipboardData.items);
4532
        if (item.kind === 'file' && item.type.indexOf('image/') !== -1) {
4533
          context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]);
4534
        }
4535
        context.invoke('editor.afterCommand');
4536
      }
4537
    };
4538
  };
4539
 
4540
  var Dropzone = function (context) {
4541
    var $document = $(document);
4542
    var $editor = context.layoutInfo.editor;
4543
    var $editable = context.layoutInfo.editable;
4544
    var options = context.options;
4545
    var lang = options.langInfo;
4546
 
4547
    var $dropzone = $([
4548
      '<div class="note-dropzone">',
4549
      '  <div class="note-dropzone-message"/>',
4550
      '</div>'
4551
    ].join('')).prependTo($editor);
4552
 
4553
    /**
4554
     * attach Drag and Drop Events
4555
     */
4556
    this.initialize = function () {
4557
      if (options.disableDragAndDrop) {
4558
        // prevent default drop event
4559
        $document.on('drop', function (e) {
4560
          e.preventDefault();
4561
        });
4562
      } else {
4563
        this.attachDragAndDropEvent();
4564
      }
4565
    };
4566
 
4567
    /**
4568
     * attach Drag and Drop Events
4569
     */
4570
    this.attachDragAndDropEvent = function () {
4571
      var collection = $(),
4572
          $dropzoneMessage = $dropzone.find('.note-dropzone-message');
4573
 
4574
      // show dropzone on dragenter when dragging a object to document
4575
      // -but only if the editor is visible, i.e. has a positive width and height
4576
      $document.on('dragenter', function (e) {
4577
        var isCodeview = context.invoke('codeview.isActivated');
4578
        var hasEditorSize = $editor.width() > 0 && $editor.height() > 0;
4579
        if (!isCodeview && !collection.length && hasEditorSize) {
4580
          $editor.addClass('dragover');
4581
          $dropzone.width($editor.width());
4582
          $dropzone.height($editor.height());
4583
          $dropzoneMessage.text(lang.image.dragImageHere);
4584
        }
4585
        collection = collection.add(e.target);
4586
      }).on('dragleave', function (e) {
4587
        collection = collection.not(e.target);
4588
        if (!collection.length) {
4589
          $editor.removeClass('dragover');
4590
        }
4591
      }).on('drop', function () {
4592
        collection = $();
4593
        $editor.removeClass('dragover');
4594
      });
4595
 
4596
      // change dropzone's message on hover.
4597
      $dropzone.on('dragenter', function () {
4598
        $dropzone.addClass('hover');
4599
        $dropzoneMessage.text(lang.image.dropImage);
4600
      }).on('dragleave', function () {
4601
        $dropzone.removeClass('hover');
4602
        $dropzoneMessage.text(lang.image.dragImageHere);
4603
      });
4604
 
4605
      // attach dropImage
4606
      $dropzone.on('drop', function (event) {
4607
        var dataTransfer = event.originalEvent.dataTransfer;
4608
 
4609
        if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
4610
          event.preventDefault();
4611
          $editable.focus();
4612
          context.invoke('editor.insertImagesOrCallback', dataTransfer.files);
4613
        } else {
4614
          $.each(dataTransfer.types, function (idx, type) {
4615
            var content = dataTransfer.getData(type);
4616
 
4617
            if (type.toLowerCase().indexOf('text') > -1) {
4618
              context.invoke('editor.pasteHTML', content);
4619
            } else {
4620
              $(content).each(function () {
4621
                context.invoke('editor.insertNode', this);
4622
              });
4623
            }
4624
          });
4625
        }
4626
      }).on('dragover', false); // prevent default dragover event
4627
    };
4628
  };
4629
 
4630
 
4631
  var CodeMirror;
4632
  if (agent.hasCodeMirror) {
4633
    if (agent.isSupportAmd) {
4634
      require(['codemirror'], function (cm) {
4635
        CodeMirror = cm;
4636
      });
4637
    } else {
4638
      CodeMirror = window.CodeMirror;
4639
    }
4640
  }
4641
 
4642
  /**
4643
   * @class Codeview
4644
   */
4645
  var Codeview = function (context) {
4646
    var $editor = context.layoutInfo.editor;
4647
    var $editable = context.layoutInfo.editable;
4648
    var $codable = context.layoutInfo.codable;
4649
    var options = context.options;
4650
 
4651
    this.sync = function () {
4652
      var isCodeview = this.isActivated();
4653
      if (isCodeview && agent.hasCodeMirror) {
4654
        $codable.data('cmEditor').save();
4655
      }
4656
    };
4657
 
4658
    /**
4659
     * @return {Boolean}
4660
     */
4661
    this.isActivated = function () {
4662
      return $editor.hasClass('codeview');
4663
    };
4664
 
4665
    /**
4666
     * toggle codeview
4667
     */
4668
    this.toggle = function () {
4669
      if (this.isActivated()) {
4670
        this.deactivate();
4671
      } else {
4672
        this.activate();
4673
      }
4674
      context.triggerEvent('codeview.toggled');
4675
    };
4676
 
4677
    /**
4678
     * activate code view
4679
     */
4680
    this.activate = function () {
4681
      $codable.val(dom.html($editable, options.prettifyHtml));
4682
      $codable.height($editable.height());
4683
 
4684
      context.invoke('toolbar.updateCodeview', true);
4685
      $editor.addClass('codeview');
4686
      $codable.focus();
4687
 
4688
      // activate CodeMirror as codable
4689
      if (agent.hasCodeMirror) {
4690
        var cmEditor = CodeMirror.fromTextArea($codable[0], options.codemirror);
4691
 
4692
        // CodeMirror TernServer
4693
        if (options.codemirror.tern) {
4694
          var server = new CodeMirror.TernServer(options.codemirror.tern);
4695
          cmEditor.ternServer = server;
4696
          cmEditor.on('cursorActivity', function (cm) {
4697
            server.updateArgHints(cm);
4698
          });
4699
        }
4700
 
4701
        // CodeMirror hasn't Padding.
4702
        cmEditor.setSize(null, $editable.outerHeight());
4703
        $codable.data('cmEditor', cmEditor);
4704
      }
4705
    };
4706
 
4707
    /**
4708
     * deactivate code view
4709
     */
4710
    this.deactivate = function () {
4711
      // deactivate CodeMirror as codable
4712
      if (agent.hasCodeMirror) {
4713
        var cmEditor = $codable.data('cmEditor');
4714
        $codable.val(cmEditor.getValue());
4715
        cmEditor.toTextArea();
4716
      }
4717
 
4718
      var value = dom.value($codable, options.prettifyHtml) || dom.emptyPara;
4719
      var isChange = $editable.html() !== value;
4720
 
4721
      $editable.html(value);
4722
      $editable.height(options.height ? $codable.height() : 'auto');
4723
      $editor.removeClass('codeview');
4724
 
4725
      if (isChange) {
4726
        context.triggerEvent('change', $editable.html(), $editable);
4727
      }
4728
 
4729
      $editable.focus();
4730
 
4731
      context.invoke('toolbar.updateCodeview', false);
4732
    };
4733
 
4734
    this.destroy = function () {
4735
      if (this.isActivated()) {
4736
        this.deactivate();
4737
      }
4738
    };
4739
  };
4740
 
4741
  var EDITABLE_PADDING = 24;
4742
 
4743
  var Statusbar = function (context) {
4744
    var $document = $(document);
4745
    var $statusbar = context.layoutInfo.statusbar;
4746
    var $editable = context.layoutInfo.editable;
4747
    var options = context.options;
4748
 
4749
    this.initialize = function () {
4750
      if (options.airMode || options.disableResizeEditor) {
4751
        return;
4752
      }
4753
 
4754
      $statusbar.on('mousedown', function (event) {
4755
        event.preventDefault();
4756
        event.stopPropagation();
4757
 
4758
        var editableTop = $editable.offset().top - $document.scrollTop();
4759
 
4760
        $document.on('mousemove', function (event) {
4761
          var height = event.clientY - (editableTop + EDITABLE_PADDING);
4762
 
4763
          height = (options.minheight > 0) ? Math.max(height, options.minheight) : height;
4764
          height = (options.maxHeight > 0) ? Math.min(height, options.maxHeight) : height;
4765
 
4766
          $editable.height(height);
4767
        }).one('mouseup', function () {
4768
          $document.off('mousemove');
4769
        });
4770
      });
4771
    };
4772
 
4773
    this.destroy = function () {
4774
      $statusbar.off();
4775
    };
4776
  };
4777
 
4778
  var Fullscreen = function (context) {
4779
    var $editor = context.layoutInfo.editor;
4780
    var $toolbar = context.layoutInfo.toolbar;
4781
    var $editable = context.layoutInfo.editable;
4782
    var $codable = context.layoutInfo.codable;
4783
 
4784
    var $window = $(window);
4785
    var $scrollbar = $('html, body');
4786
 
4787
    /**
4788
     * toggle fullscreen
4789
     */
4790
    this.toggle = function () {
4791
      var resize = function (size) {
4792
        $editable.css('height', size.h);
4793
        $codable.css('height', size.h);
4794
        if ($codable.data('cmeditor')) {
4795
          $codable.data('cmeditor').setsize(null, size.h);
4796
        }
4797
      };
4798
 
4799
      $editor.toggleClass('fullscreen');
4800
      if (this.isFullscreen()) {
4801
        $editable.data('orgHeight', $editable.css('height'));
4802
 
4803
        $window.on('resize', function () {
4804
          resize({
4805
            h: $window.height() - $toolbar.outerHeight()
4806
          });
4807
        }).trigger('resize');
4808
 
4809
        $scrollbar.css('overflow', 'hidden');
4810
      } else {
4811
        $window.off('resize');
4812
        resize({
4813
          h: $editable.data('orgHeight')
4814
        });
4815
        $scrollbar.css('overflow', 'visible');
4816
      }
4817
 
4818
      context.invoke('toolbar.updateFullscreen', this.isFullscreen());
4819
    };
4820
 
4821
    this.isFullscreen = function () {
4822
      return $editor.hasClass('fullscreen');
4823
    };
4824
  };
4825
 
4826
  var Handle = function (context) {
4827
    var self = this;
4828
 
4829
    var $document = $(document);
4830
    var $editingArea = context.layoutInfo.editingArea;
4831
    var options = context.options;
4832
 
4833
    this.events = {
4834
      'summernote.mousedown': function (we, e) {
4835
        if (self.update(e.target)) {
4836
          e.preventDefault();
4837
        }
4838
      },
4839
      'summernote.keyup summernote.scroll summernote.change summernote.dialog.shown': function () {
4840
        self.update();
4841
      }
4842
    };
4843
 
4844
    this.initialize = function () {
4845
      this.$handle = $([
4846
        '<div class="note-handle">',
4847
        '<div class="note-control-selection">',
4848
        '<div class="note-control-selection-bg"></div>',
4849
        '<div class="note-control-holder note-control-nw"></div>',
4850
        '<div class="note-control-holder note-control-ne"></div>',
4851
        '<div class="note-control-holder note-control-sw"></div>',
4852
        '<div class="',
4853
        (options.disableResizeImage ? 'note-control-holder' : 'note-control-sizing'),
4854
        ' note-control-se"></div>',
4855
        (options.disableResizeImage ? '' : '<div class="note-control-selection-info"></div>'),
4856
        '</div>',
4857
        '</div>'
4858
      ].join('')).prependTo($editingArea);
4859
 
4860
      this.$handle.on('mousedown', function (event) {
4861
        if (dom.isControlSizing(event.target)) {
4862
          event.preventDefault();
4863
          event.stopPropagation();
4864
 
4865
          var $target = self.$handle.find('.note-control-selection').data('target'),
4866
              posStart = $target.offset(),
4867
              scrollTop = $document.scrollTop();
4868
 
4869
          $document.on('mousemove', function (event) {
4870
            context.invoke('editor.resizeTo', {
4871
              x: event.clientX - posStart.left,
4872
              y: event.clientY - (posStart.top - scrollTop)
4873
            }, $target, !event.shiftKey);
4874
 
4875
            self.update($target[0]);
4876
          }).one('mouseup', function (e) {
4877
            e.preventDefault();
4878
            $document.off('mousemove');
4879
            context.invoke('editor.afterCommand');
4880
          });
4881
 
4882
          if (!$target.data('ratio')) { // original ratio.
4883
            $target.data('ratio', $target.height() / $target.width());
4884
          }
4885
        }
4886
      });
4887
    };
4888
 
4889
    this.destroy = function () {
4890
      this.$handle.remove();
4891
    };
4892
 
4893
    this.update = function (target) {
4894
      var isImage = dom.isImg(target);
4895
      var $selection = this.$handle.find('.note-control-selection');
4896
 
4897
      context.invoke('imagePopover.update', target);
4898
 
4899
      if (isImage) {
4900
        var $image = $(target);
4901
        var pos = $image.position();
4902
 
4903
        // include margin
4904
        var imageSize = {
4905
          w: $image.outerWidth(true),
4906
          h: $image.outerHeight(true)
4907
        };
4908
 
4909
        $selection.css({
4910
          display: 'block',
4911
          left: pos.left,
4912
          top: pos.top,
4913
          width: imageSize.w,
4914
          height: imageSize.h
4915
        }).data('target', $image); // save current image element.
4916
 
4917
        var sizingText = imageSize.w + 'x' + imageSize.h;
4918
        $selection.find('.note-control-selection-info').text(sizingText);
4919
        context.invoke('editor.saveTarget', target);
4920
      } else {
4921
        this.hide();
4922
      }
4923
 
4924
      return isImage;
4925
    };
4926
 
4927
    /**
4928
     * hide
4929
     *
4930
     * @param {jQuery} $handle
4931
     */
4932
    this.hide = function () {
4933
      context.invoke('editor.clearTarget');
4934
      this.$handle.children().hide();
4935
    };
4936
  };
4937
 
4938
  var AutoLink = function (context) {
4939
    var self = this;
4940
    var defaultScheme = 'http://';
4941
    var linkPattern = /^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|mailto:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i;
4942
 
4943
    this.events = {
4944
      'summernote.keyup': function (we, e) {
4945
        if (!e.isDefaultPrevented()) {
4946
          self.handleKeyup(e);
4947
        }
4948
      },
4949
      'summernote.keydown': function (we, e) {
4950
        self.handleKeydown(e);
4951
      }
4952
    };
4953
 
4954
    this.initialize = function () {
4955
      this.lastWordRange = null;
4956
    };
4957
 
4958
    this.destroy = function () {
4959
      this.lastWordRange = null;
4960
    };
4961
 
4962
    this.replace = function () {
4963
      if (!this.lastWordRange) {
4964
        return;
4965
      }
4966
 
4967
      var keyword = this.lastWordRange.toString();
4968
      var match = keyword.match(linkPattern);
4969
 
4970
      if (match && (match[1] || match[2])) {
4971
        var link = match[1] ? keyword : defaultScheme + keyword;
4972
        var node = $('<a />').html(keyword).attr('href', link)[0];
4973
 
4974
        this.lastWordRange.insertNode(node);
4975
        this.lastWordRange = null;
4976
        context.invoke('editor.focus');
4977
      }
4978
 
4979
    };
4980
 
4981
    this.handleKeydown = function (e) {
4982
      if (list.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) {
4983
        var wordRange = context.invoke('editor.createRange').getWordRange();
4984
        this.lastWordRange = wordRange;
4985
      }
4986
    };
4987
 
4988
    this.handleKeyup = function (e) {
4989
      if (list.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) {
4990
        this.replace();
4991
      }
4992
    };
4993
  };
4994
 
4995
  /**
4996
   * textarea auto sync.
4997
   */
4998
  var AutoSync = function (context) {
4999
    var $note = context.layoutInfo.note;
5000
 
5001
    this.events = {
5002
      'summernote.change': function () {
5003
        $note.val(context.invoke('code'));
5004
      }
5005
    };
5006
 
5007
    this.shouldInitialize = function () {
5008
      return dom.isTextarea($note[0]);
5009
    };
5010
  };
5011
 
5012
  var Placeholder = function (context) {
5013
    var self = this;
5014
    var $editingArea = context.layoutInfo.editingArea;
5015
    var options = context.options;
5016
 
5017
    this.events = {
5018
      'summernote.init summernote.change': function () {
5019
        self.update();
5020
      },
5021
      'summernote.codeview.toggled': function () {
5022
        self.update();
5023
      }
5024
    };
5025
 
5026
    this.shouldInitialize = function () {
5027
      return !!options.placeholder;
5028
    };
5029
 
5030
    this.initialize = function () {
5031
      this.$placeholder = $('<div class="note-placeholder">');
5032
      this.$placeholder.on('click', function () {
5033
        context.invoke('focus');
5034
      }).text(options.placeholder).prependTo($editingArea);
5035
    };
5036
 
5037
    this.destroy = function () {
5038
      this.$placeholder.remove();
5039
    };
5040
 
5041
    this.update = function () {
5042
      var isShow = !context.invoke('codeview.isActivated') && context.invoke('editor.isEmpty');
5043
      this.$placeholder.toggle(isShow);
5044
    };
5045
  };
5046
 
5047
  var Buttons = function (context) {
5048
    var self = this;
5049
    var ui = $.summernote.ui;
5050
 
5051
    var $toolbar = context.layoutInfo.toolbar;
5052
    var options = context.options;
5053
    var lang = options.langInfo;
5054
 
5055
    var invertedKeyMap = func.invertObject(options.keyMap[agent.isMac ? 'mac' : 'pc']);
5056
 
5057
    var representShortcut = this.representShortcut = function (editorMethod) {
5058
      var shortcut = invertedKeyMap[editorMethod];
5059
      if (agent.isMac) {
5060
        shortcut = shortcut.replace('CMD', '⌘').replace('SHIFT', '⇧');
5061
      }
5062
 
5063
      shortcut = shortcut.replace('BACKSLASH', '\\')
5064
                         .replace('SLASH', '/')
5065
                         .replace('LEFTBRACKET', '[')
5066
                         .replace('RIGHTBRACKET', ']');
5067
 
5068
      return ' (' + shortcut + ')';
5069
    };
5070
 
5071
    this.initialize = function () {
5072
      this.addToolbarButtons();
5073
      this.addImagePopoverButtons();
5074
      this.addLinkPopoverButtons();
5075
      this.fontInstalledMap = {};
5076
    };
5077
 
5078
    this.destroy = function () {
5079
      delete this.fontInstalledMap;
5080
    };
5081
 
5082
    this.isFontInstalled = function (name) {
5083
      if (!self.fontInstalledMap.hasOwnProperty(name)) {
5084
        self.fontInstalledMap[name] = agent.isFontInstalled(name) ||
5085
          list.contains(options.fontNamesIgnoreCheck, name);
5086
      }
5087
 
5088
      return self.fontInstalledMap[name];
5089
    };
5090
 
5091
    this.addToolbarButtons = function () {
5092
      context.memo('button.style', function () {
5093
        return ui.buttonGroup([
5094
          ui.button({
5095
            className: 'dropdown-toggle',
5096
            contents: ui.icon(options.icons.magic) + ' ' + ui.icon(options.icons.caret, 'span'),
5097
            tooltip: lang.style.style,
5098
            data: {
5099
              toggle: 'dropdown'
5100
            }
5101
          }),
5102
          ui.dropdown({
5103
            className: 'dropdown-style',
5104
            items: context.options.styleTags,
5105
            template: function (item) {
5106
 
5107
              if (typeof item === 'string') {
5108
                item = { tag: item, title: item };
5109
              }
5110
 
5111
              var tag = item.tag;
5112
              var title = item.title;
5113
              var style = item.style ? ' style="' + item.style + '" ' : '';
5114
              var className = item.className ? ' className="' + item.className + '"' : '';
5115
 
5116
              return '<' + tag + style + className + '>' + title + '</' + tag +  '>';
5117
            },
5118
            click: context.createInvokeHandler('editor.formatBlock')
5119
          })
5120
        ]).render();
5121
      });
5122
 
5123
      context.memo('button.bold', function () {
5124
        return ui.button({
5125
          className: 'note-btn-bold',
5126
          contents: ui.icon(options.icons.bold),
5127
          tooltip: lang.font.bold + representShortcut('bold'),
5128
          click: context.createInvokeHandler('editor.bold')
5129
        }).render();
5130
      });
5131
 
5132
      context.memo('button.italic', function () {
5133
        return ui.button({
5134
          className: 'note-btn-italic',
5135
          contents: ui.icon(options.icons.italic),
5136
          tooltip: lang.font.italic + representShortcut('italic'),
5137
          click: context.createInvokeHandler('editor.italic')
5138
        }).render();
5139
      });
5140
 
5141
      context.memo('button.underline', function () {
5142
        return ui.button({
5143
          className: 'note-btn-underline',
5144
          contents: ui.icon(options.icons.underline),
5145
          tooltip: lang.font.underline + representShortcut('underline'),
5146
          click: context.createInvokeHandler('editor.underline')
5147
        }).render();
5148
      });
5149
 
5150
      context.memo('button.clear', function () {
5151
        return ui.button({
5152
          contents: ui.icon(options.icons.eraser),
5153
          tooltip: lang.font.clear + representShortcut('removeFormat'),
5154
          click: context.createInvokeHandler('editor.removeFormat')
5155
        }).render();
5156
      });
5157
 
5158
      context.memo('button.strikethrough', function () {
5159
        return ui.button({
5160
          className: 'note-btn-strikethrough',
5161
          contents: ui.icon(options.icons.strikethrough),
5162
          tooltip: lang.font.strikethrough + representShortcut('strikethrough'),
5163
          click: context.createInvokeHandler('editor.strikethrough')
5164
        }).render();
5165
      });
5166
 
5167
      context.memo('button.superscript', function () {
5168
        return ui.button({
5169
          className: 'note-btn-superscript',
5170
          contents: ui.icon(options.icons.superscript),
5171
          tooltip: lang.font.superscript,
5172
          click: context.createInvokeHandler('editor.superscript')
5173
        }).render();
5174
      });
5175
 
5176
      context.memo('button.subscript', function () {
5177
        return ui.button({
5178
          className: 'note-btn-subscript',
5179
          contents: ui.icon(options.icons.subscript),
5180
          tooltip: lang.font.subscript,
5181
          click: context.createInvokeHandler('editor.subscript')
5182
        }).render();
5183
      });
5184
 
5185
      context.memo('button.fontname', function () {
5186
        return ui.buttonGroup([
5187
          ui.button({
5188
            className: 'dropdown-toggle',
5189
            contents: '<span class="note-current-fontname"/> ' + ui.icon(options.icons.caret, 'span'),
5190
            tooltip: lang.font.name,
5191
            data: {
5192
              toggle: 'dropdown'
5193
            }
5194
          }),
5195
          ui.dropdownCheck({
5196
            className: 'dropdown-fontname',
5197
            checkClassName: options.icons.menuCheck,
5198
            items: options.fontNames.filter(self.isFontInstalled),
5199
            template: function (item) {
5200
              return '<span style="font-family:' + item + '">' + item + '</span>';
5201
            },
5202
            click: context.createInvokeHandler('editor.fontName')
5203
          })
5204
        ]).render();
5205
      });
5206
 
5207
      context.memo('button.fontsize', function () {
5208
        return ui.buttonGroup([
5209
          ui.button({
5210
            className: 'dropdown-toggle',
5211
            contents: '<span class="note-current-fontsize"/>' + ui.icon(options.icons.caret, 'span'),
5212
            tooltip: lang.font.size,
5213
            data: {
5214
              toggle: 'dropdown'
5215
            }
5216
          }),
5217
          ui.dropdownCheck({
5218
            className: 'dropdown-fontsize',
5219
            checkClassName: options.icons.menuCheck,
5220
            items: options.fontSizes,
5221
            click: context.createInvokeHandler('editor.fontSize')
5222
          })
5223
        ]).render();
5224
      });
5225
 
5226
      context.memo('button.color', function () {
5227
        return ui.buttonGroup({
5228
          className: 'note-color',
5229
          children: [
5230
            ui.button({
5231
              className: 'note-current-color-button',
5232
              contents: ui.icon(options.icons.font + ' note-recent-color'),
5233
              tooltip: lang.color.recent,
5234
              click: function (e) {
5235
                var $button = $(e.currentTarget);
5236
                context.invoke('editor.color', {
5237
                  backColor: $button.attr('data-backColor'),
5238
                  foreColor: $button.attr('data-foreColor')
5239
                });
5240
              },
5241
              callback: function ($button) {
5242
                var $recentColor = $button.find('.note-recent-color');
5243
                $recentColor.css('background-color', '#FFFF00');
5244
                $button.attr('data-backColor', '#FFFF00');
5245
              }
5246
            }),
5247
            ui.button({
5248
              className: 'dropdown-toggle',
5249
              contents: ui.icon(options.icons.caret, 'span'),
5250
              tooltip: lang.color.more,
5251
              data: {
5252
                toggle: 'dropdown'
5253
              }
5254
            }),
5255
            ui.dropdown({
5256
              items: [
5257
                '<li>',
5258
                '<div class="btn-group">',
5259
                '  <div class="note-palette-title">' + lang.color.background + '</div>',
5260
                '  <div>',
5261
                '    <button type="button" class="note-color-reset btn btn-default" data-event="backColor" data-value="inherit">',
5262
                lang.color.transparent,
5263
                '    </button>',
5264
                '  </div>',
5265
                '  <div class="note-holder" data-event="backColor"/>',
5266
                '</div>',
5267
                '<div class="btn-group">',
5268
                '  <div class="note-palette-title">' + lang.color.foreground + '</div>',
5269
                '  <div>',
5270
                '    <button type="button" class="note-color-reset btn btn-default" data-event="removeFormat" data-value="foreColor">',
5271
                lang.color.resetToDefault,
5272
                '    </button>',
5273
                '  </div>',
5274
                '  <div class="note-holder" data-event="foreColor"/>',
5275
                '</div>',
5276
                '</li>'
5277
              ].join(''),
5278
              callback: function ($dropdown) {
5279
                $dropdown.find('.note-holder').each(function () {
5280
                  var $holder = $(this);
5281
                  $holder.append(ui.palette({
5282
                    colors: options.colors,
5283
                    eventName: $holder.data('event')
5284
                  }).render());
5285
                });
5286
              },
5287
              click: function (event) {
5288
                var $button = $(event.target);
5289
                var eventName = $button.data('event');
5290
                var value = $button.data('value');
5291
 
5292
                if (eventName && value) {
5293
                  var key = eventName === 'backColor' ? 'background-color' : 'color';
5294
                  var $color = $button.closest('.note-color').find('.note-recent-color');
5295
                  var $currentButton = $button.closest('.note-color').find('.note-current-color-button');
5296
 
5297
                  $color.css(key, value);
5298
                  $currentButton.attr('data-' + eventName, value);
5299
                  context.invoke('editor.' + eventName, value);
5300
                }
5301
              }
5302
            })
5303
          ]
5304
        }).render();
5305
      });
5306
 
5307
      context.memo('button.ul',  function () {
5308
        return ui.button({
5309
          contents: ui.icon(options.icons.unorderedlist),
5310
          tooltip: lang.lists.unordered + representShortcut('insertUnorderedList'),
5311
          click: context.createInvokeHandler('editor.insertUnorderedList')
5312
        }).render();
5313
      });
5314
 
5315
      context.memo('button.ol', function () {
5316
        return ui.button({
5317
          contents: ui.icon(options.icons.orderedlist),
5318
          tooltip: lang.lists.ordered + representShortcut('insertOrderedList'),
5319
          click:  context.createInvokeHandler('editor.insertOrderedList')
5320
        }).render();
5321
      });
5322
 
5323
      var justifyLeft = ui.button({
5324
        contents: ui.icon(options.icons.alignLeft),
5325
        tooltip: lang.paragraph.left + representShortcut('justifyLeft'),
5326
        click: context.createInvokeHandler('editor.justifyLeft')
5327
      });
5328
 
5329
      var justifyCenter = ui.button({
5330
        contents: ui.icon(options.icons.alignCenter),
5331
        tooltip: lang.paragraph.center + representShortcut('justifyCenter'),
5332
        click: context.createInvokeHandler('editor.justifyCenter')
5333
      });
5334
 
5335
      var justifyRight = ui.button({
5336
        contents: ui.icon(options.icons.alignRight),
5337
        tooltip: lang.paragraph.right + representShortcut('justifyRight'),
5338
        click: context.createInvokeHandler('editor.justifyRight')
5339
      });
5340
 
5341
      var justifyFull = ui.button({
5342
        contents: ui.icon(options.icons.alignJustify),
5343
        tooltip: lang.paragraph.justify + representShortcut('justifyFull'),
5344
        click: context.createInvokeHandler('editor.justifyFull')
5345
      });
5346
 
5347
      var outdent = ui.button({
5348
        contents: ui.icon(options.icons.outdent),
5349
        tooltip: lang.paragraph.outdent + representShortcut('outdent'),
5350
        click: context.createInvokeHandler('editor.outdent')
5351
      });
5352
 
5353
      var indent = ui.button({
5354
        contents: ui.icon(options.icons.indent),
5355
        tooltip: lang.paragraph.indent + representShortcut('indent'),
5356
        click: context.createInvokeHandler('editor.indent')
5357
      });
5358
 
5359
      context.memo('button.justifyLeft', func.invoke(justifyLeft, 'render'));
5360
      context.memo('button.justifyCenter', func.invoke(justifyCenter, 'render'));
5361
      context.memo('button.justifyRight', func.invoke(justifyRight, 'render'));
5362
      context.memo('button.justifyFull', func.invoke(justifyFull, 'render'));
5363
      context.memo('button.outdent', func.invoke(outdent, 'render'));
5364
      context.memo('button.indent', func.invoke(indent, 'render'));
5365
 
5366
      context.memo('button.paragraph', function () {
5367
        return ui.buttonGroup([
5368
          ui.button({
5369
            className: 'dropdown-toggle',
5370
            contents: ui.icon(options.icons.alignLeft) + ' ' + ui.icon(options.icons.caret, 'span'),
5371
            tooltip: lang.paragraph.paragraph,
5372
            data: {
5373
              toggle: 'dropdown'
5374
            }
5375
          }),
5376
          ui.dropdown([
5377
            ui.buttonGroup({
5378
              className: 'note-align',
5379
              children: [justifyLeft, justifyCenter, justifyRight, justifyFull]
5380
            }),
5381
            ui.buttonGroup({
5382
              className: 'note-list',
5383
              children: [outdent, indent]
5384
            })
5385
          ])
5386
        ]).render();
5387
      });
5388
 
5389
      context.memo('button.height', function () {
5390
        return ui.buttonGroup([
5391
          ui.button({
5392
            className: 'dropdown-toggle',
5393
            contents: ui.icon(options.icons.textHeight) + ' ' + ui.icon(options.icons.caret, 'span'),
5394
            tooltip: lang.font.height,
5395
            data: {
5396
              toggle: 'dropdown'
5397
            }
5398
          }),
5399
          ui.dropdownCheck({
5400
            items: options.lineHeights,
5401
            checkClassName: options.icons.menuCheck,
5402
            className: 'dropdown-line-height',
5403
            click: context.createInvokeHandler('editor.lineHeight')
5404
          })
5405
        ]).render();
5406
      });
5407
 
5408
      context.memo('button.table', function () {
5409
        return ui.buttonGroup([
5410
          ui.button({
5411
            className: 'dropdown-toggle',
5412
            contents: ui.icon(options.icons.table) + ' ' + ui.icon(options.icons.caret, 'span'),
5413
            tooltip: lang.table.table,
5414
            data: {
5415
              toggle: 'dropdown'
5416
            }
5417
          }),
5418
          ui.dropdown({
5419
            className: 'note-table',
5420
            items: [
5421
              '<div class="note-dimension-picker">',
5422
              '  <div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"/>',
5423
              '  <div class="note-dimension-picker-highlighted"/>',
5424
              '  <div class="note-dimension-picker-unhighlighted"/>',
5425
              '</div>',
5426
              '<div class="note-dimension-display">1 x 1</div>'
5427
            ].join('')
5428
          })
5429
        ], {
5430
          callback: function ($node) {
5431
            var $catcher = $node.find('.note-dimension-picker-mousecatcher');
5432
            $catcher.css({
5433
              width: options.insertTableMaxSize.col + 'em',
5434
              height: options.insertTableMaxSize.row + 'em'
5435
            }).mousedown(context.createInvokeHandler('editor.insertTable'))
5436
              .on('mousemove', self.tableMoveHandler);
5437
          }
5438
        }).render();
5439
      });
5440
 
5441
      context.memo('button.link', function () {
5442
        return ui.button({
5443
          contents: ui.icon(options.icons.link),
5444
          tooltip: lang.link.link,
5445
          click: context.createInvokeHandler('linkDialog.show')
5446
        }).render();
5447
      });
5448
 
5449
      context.memo('button.picture', function () {
5450
        return ui.button({
5451
          contents: ui.icon(options.icons.picture),
5452
          tooltip: lang.image.image,
5453
          click: context.createInvokeHandler('imageDialog.show')
5454
        }).render();
5455
      });
5456
 
5457
      context.memo('button.video', function () {
5458
        return ui.button({
5459
          contents: ui.icon(options.icons.video),
5460
          tooltip: lang.video.video,
5461
          click: context.createInvokeHandler('videoDialog.show')
5462
        }).render();
5463
      });
5464
 
5465
      context.memo('button.hr', function () {
5466
        return ui.button({
5467
          contents: ui.icon(options.icons.minus),
5468
          tooltip: lang.hr.insert + representShortcut('insertHorizontalRule'),
5469
          click: context.createInvokeHandler('editor.insertHorizontalRule')
5470
        }).render();
5471
      });
5472
 
5473
      context.memo('button.fullscreen', function () {
5474
        return ui.button({
5475
          className: 'btn-fullscreen',
5476
          contents: ui.icon(options.icons.arrowsAlt),
5477
          tooltip: lang.options.fullscreen,
5478
          click: context.createInvokeHandler('fullscreen.toggle')
5479
        }).render();
5480
      });
5481
 
5482
      context.memo('button.codeview', function () {
5483
        return ui.button({
5484
          className: 'btn-codeview',
5485
          contents: ui.icon(options.icons.code),
5486
          tooltip: lang.options.codeview,
5487
          click: context.createInvokeHandler('codeview.toggle')
5488
        }).render();
5489
      });
5490
 
5491
      context.memo('button.redo', function () {
5492
        return ui.button({
5493
          contents: ui.icon(options.icons.redo),
5494
          tooltip: lang.history.redo + representShortcut('redo'),
5495
          click: context.createInvokeHandler('editor.redo')
5496
        }).render();
5497
      });
5498
 
5499
      context.memo('button.undo', function () {
5500
        return ui.button({
5501
          contents: ui.icon(options.icons.undo),
5502
          tooltip: lang.history.undo + representShortcut('undo'),
5503
          click: context.createInvokeHandler('editor.undo')
5504
        }).render();
5505
      });
5506
 
5507
      context.memo('button.help', function () {
5508
        return ui.button({
5509
          contents: ui.icon(options.icons.question),
5510
          tooltip: lang.options.help,
5511
          click: context.createInvokeHandler('helpDialog.show')
5512
        }).render();
5513
      });
5514
    };
5515
 
5516
    /**
5517
     * image : [
5518
     *   ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
5519
     *   ['float', ['floatLeft', 'floatRight', 'floatNone' ]],
5520
     *   ['remove', ['removeMedia']]
5521
     * ],
5522
     */
5523
    this.addImagePopoverButtons = function () {
5524
      // Image Size Buttons
5525
      context.memo('button.imageSize100', function () {
5526
        return ui.button({
5527
          contents: '<span class="note-fontsize-10">100%</span>',
5528
          tooltip: lang.image.resizeFull,
5529
          click: context.createInvokeHandler('editor.resize', '1')
5530
        }).render();
5531
      });
5532
      context.memo('button.imageSize50', function () {
5533
        return  ui.button({
5534
          contents: '<span class="note-fontsize-10">50%</span>',
5535
          tooltip: lang.image.resizeHalf,
5536
          click: context.createInvokeHandler('editor.resize', '0.5')
5537
        }).render();
5538
      });
5539
      context.memo('button.imageSize25', function () {
5540
        return ui.button({
5541
          contents: '<span class="note-fontsize-10">25%</span>',
5542
          tooltip: lang.image.resizeQuarter,
5543
          click: context.createInvokeHandler('editor.resize', '0.25')
5544
        }).render();
5545
      });
5546
 
5547
      // Float Buttons
5548
      context.memo('button.floatLeft', function () {
5549
        return ui.button({
5550
          contents: ui.icon(options.icons.alignLeft),
5551
          tooltip: lang.image.floatLeft,
5552
          click: context.createInvokeHandler('editor.floatMe', 'left')
5553
        }).render();
5554
      });
5555
 
5556
      context.memo('button.floatRight', function () {
5557
        return ui.button({
5558
          contents: ui.icon(options.icons.alignRight),
5559
          tooltip: lang.image.floatRight,
5560
          click: context.createInvokeHandler('editor.floatMe', 'right')
5561
        }).render();
5562
      });
5563
 
5564
      context.memo('button.floatNone', function () {
5565
        return ui.button({
5566
          contents: ui.icon(options.icons.alignJustify),
5567
          tooltip: lang.image.floatNone,
5568
          click: context.createInvokeHandler('editor.floatMe', 'none')
5569
        }).render();
5570
      });
5571
 
5572
      // Remove Buttons
5573
      context.memo('button.removeMedia', function () {
5574
        return ui.button({
5575
          contents: ui.icon(options.icons.trash),
5576
          tooltip: lang.image.remove,
5577
          click: context.createInvokeHandler('editor.removeMedia')
5578
        }).render();
5579
      });
5580
    };
5581
 
5582
    this.addLinkPopoverButtons = function () {
5583
      context.memo('button.linkDialogShow', function () {
5584
        return ui.button({
5585
          contents: ui.icon(options.icons.link),
5586
          tooltip: lang.link.edit,
5587
          click: context.createInvokeHandler('linkDialog.show')
5588
        }).render();
5589
      });
5590
 
5591
      context.memo('button.unlink', function () {
5592
        return ui.button({
5593
          contents: ui.icon(options.icons.unlink),
5594
          tooltip: lang.link.unlink,
5595
          click: context.createInvokeHandler('editor.unlink')
5596
        }).render();
5597
      });
5598
    };
5599
 
5600
    this.build = function ($container, groups) {
5601
      for (var groupIdx = 0, groupLen = groups.length; groupIdx < groupLen; groupIdx++) {
5602
        var group = groups[groupIdx];
5603
        var groupName = group[0];
5604
        var buttons = group[1];
5605
 
5606
        var $group = ui.buttonGroup({
5607
          className: 'note-' + groupName
5608
        }).render();
5609
 
5610
        for (var idx = 0, len = buttons.length; idx < len; idx++) {
5611
          var button = context.memo('button.' + buttons[idx]);
5612
          if (button) {
5613
            $group.append(typeof button === 'function' ? button(context) : button);
5614
          }
5615
        }
5616
        $group.appendTo($container);
5617
      }
5618
    };
5619
 
5620
    this.updateCurrentStyle = function () {
5621
      var styleInfo = context.invoke('editor.currentStyle');
5622
      this.updateBtnStates({
5623
        '.note-btn-bold': function () {
5624
          return styleInfo['font-bold'] === 'bold';
5625
        },
5626
        '.note-btn-italic': function () {
5627
          return styleInfo['font-italic'] === 'italic';
5628
        },
5629
        '.note-btn-underline': function () {
5630
          return styleInfo['font-underline'] === 'underline';
5631
        },
5632
        '.note-btn-subscript': function () {
5633
          return styleInfo['font-subscript'] === 'subscript';
5634
        },
5635
        '.note-btn-superscript': function () {
5636
          return styleInfo['font-superscript'] === 'superscript';
5637
        },
5638
        '.note-btn-strikethrough': function () {
5639
          return styleInfo['font-strikethrough'] === 'strikethrough';
5640
        }
5641
      });
5642
 
5643
      if (styleInfo['font-family']) {
5644
        var fontNames = styleInfo['font-family'].split(',').map(function (name) {
5645
          return name.replace(/[\'\"]/g, '')
5646
            .replace(/\s+$/, '')
5647
            .replace(/^\s+/, '');
5648
        });
5649
        var fontName = list.find(fontNames, self.isFontInstalled);
5650
 
5651
        $toolbar.find('.dropdown-fontname li a').each(function () {
5652
          // always compare string to avoid creating another func.
5653
          var isChecked = ($(this).data('value') + '') === (fontName + '');
5654
          this.className = isChecked ? 'checked' : '';
5655
        });
5656
        $toolbar.find('.note-current-fontname').text(fontName);
5657
      }
5658
 
5659
      if (styleInfo['font-size']) {
5660
        var fontSize = styleInfo['font-size'];
5661
        $toolbar.find('.dropdown-fontsize li a').each(function () {
5662
          // always compare with string to avoid creating another func.
5663
          var isChecked = ($(this).data('value') + '') === (fontSize + '');
5664
          this.className = isChecked ? 'checked' : '';
5665
        });
5666
        $toolbar.find('.note-current-fontsize').text(fontSize);
5667
      }
5668
 
5669
      if (styleInfo['line-height']) {
5670
        var lineHeight = styleInfo['line-height'];
5671
        $toolbar.find('.dropdown-line-height li a').each(function () {
5672
          // always compare with string to avoid creating another func.
5673
          var isChecked = ($(this).data('value') + '') === (lineHeight + '');
5674
          this.className = isChecked ? 'checked' : '';
5675
        });
5676
      }
5677
    };
5678
 
5679
    this.updateBtnStates = function (infos) {
5680
      $.each(infos, function (selector, pred) {
5681
        ui.toggleBtnActive($toolbar.find(selector), pred());
5682
      });
5683
    };
5684
 
5685
    this.tableMoveHandler = function (event) {
5686
      var PX_PER_EM = 18;
5687
      var $picker = $(event.target.parentNode); // target is mousecatcher
5688
      var $dimensionDisplay = $picker.next();
5689
      var $catcher = $picker.find('.note-dimension-picker-mousecatcher');
5690
      var $highlighted = $picker.find('.note-dimension-picker-highlighted');
5691
      var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted');
5692
 
5693
      var posOffset;
5694
      // HTML5 with jQuery - e.offsetX is undefined in Firefox
5695
      if (event.offsetX === undefined) {
5696
        var posCatcher = $(event.target).offset();
5697
        posOffset = {
5698
          x: event.pageX - posCatcher.left,
5699
          y: event.pageY - posCatcher.top
5700
        };
5701
      } else {
5702
        posOffset = {
5703
          x: event.offsetX,
5704
          y: event.offsetY
5705
        };
5706
      }
5707
 
5708
      var dim = {
5709
        c: Math.ceil(posOffset.x / PX_PER_EM) || 1,
5710
        r: Math.ceil(posOffset.y / PX_PER_EM) || 1
5711
      };
5712
 
5713
      $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' });
5714
      $catcher.data('value', dim.c + 'x' + dim.r);
5715
 
5716
      if (3 < dim.c && dim.c < options.insertTableMaxSize.col) {
5717
        $unhighlighted.css({ width: dim.c + 1 + 'em'});
5718
      }
5719
 
5720
      if (3 < dim.r && dim.r < options.insertTableMaxSize.row) {
5721
        $unhighlighted.css({ height: dim.r + 1 + 'em'});
5722
      }
5723
 
5724
      $dimensionDisplay.html(dim.c + ' x ' + dim.r);
5725
    };
5726
  };
5727
 
5728
  var Toolbar = function (context) {
5729
    var ui = $.summernote.ui;
5730
 
5731
    var $note = context.layoutInfo.note;
5732
    var $toolbar = context.layoutInfo.toolbar;
5733
    var options = context.options;
5734
 
5735
    this.shouldInitialize = function () {
5736
      return !options.airMode;
5737
    };
5738
 
5739
    this.initialize = function () {
5740
      options.toolbar = options.toolbar || [];
5741
 
5742
      if (!options.toolbar.length) {
5743
        $toolbar.hide();
5744
      } else {
5745
        context.invoke('buttons.build', $toolbar, options.toolbar);
5746
      }
5747
 
5748
      if (options.toolbarContainer) {
5749
        $toolbar.appendTo(options.toolbarContainer);
5750
      }
5751
 
5752
      $note.on('summernote.keyup summernote.mouseup summernote.change', function () {
5753
        context.invoke('buttons.updateCurrentStyle');
5754
      });
5755
 
5756
      context.invoke('buttons.updateCurrentStyle');
5757
    };
5758
 
5759
    this.destroy = function () {
5760
      $toolbar.children().remove();
5761
    };
5762
 
5763
    this.updateFullscreen = function (isFullscreen) {
5764
      ui.toggleBtnActive($toolbar.find('.btn-fullscreen'), isFullscreen);
5765
    };
5766
 
5767
    this.updateCodeview = function (isCodeview) {
5768
      ui.toggleBtnActive($toolbar.find('.btn-codeview'), isCodeview);
5769
      if (isCodeview) {
5770
        this.deactivate();
5771
      } else {
5772
        this.activate();
5773
      }
5774
    };
5775
 
5776
    this.activate = function (isIncludeCodeview) {
5777
      var $btn = $toolbar.find('button');
5778
      if (!isIncludeCodeview) {
5779
        $btn = $btn.not('.btn-codeview');
5780
      }
5781
      ui.toggleBtn($btn, true);
5782
    };
5783
 
5784
    this.deactivate = function (isIncludeCodeview) {
5785
      var $btn = $toolbar.find('button');
5786
      if (!isIncludeCodeview) {
5787
        $btn = $btn.not('.btn-codeview');
5788
      }
5789
      ui.toggleBtn($btn, false);
5790
    };
5791
  };
5792
 
5793
  var LinkDialog = function (context) {
5794
    var self = this;
5795
    var ui = $.summernote.ui;
5796
 
5797
    var $editor = context.layoutInfo.editor;
5798
    var options = context.options;
5799
    var lang = options.langInfo;
5800
 
5801
    this.initialize = function () {
5802
      var $container = options.dialogsInBody ? $(document.body) : $editor;
5803
 
5804
      var body = '<div class="form-group">' +
5805
                   '<label>' + lang.link.textToDisplay + '</label>' +
5806
                   '<input class="note-link-text form-control" type="text" />' +
5807
                 '</div>' +
5808
                 '<div class="form-group">' +
5809
                   '<label>' + lang.link.url + '</label>' +
5810
                   '<input class="note-link-url form-control" type="text" value="http://" />' +
5811
                 '</div>' +
5812
                 (!options.disableLinkTarget ?
5813
                   '<div class="checkbox">' +
5814
                     '<label>' + '<input type="checkbox" checked> ' + lang.link.openInNewWindow + '</label>' +
5815
                   '</div>' : ''
5816
                 );
5817
      var footer = '<button href="#" class="btn btn-primary note-link-btn disabled" disabled>' + lang.link.insert + '</button>';
5818
 
5819
      this.$dialog = ui.dialog({
5820
        className: 'link-dialog',
5821
        title: lang.link.insert,
5822
        fade: options.dialogsFade,
5823
        body: body,
5824
        footer: footer
5825
      }).render().appendTo($container);
5826
    };
5827
 
5828
    this.destroy = function () {
5829
      ui.hideDialog(this.$dialog);
5830
      this.$dialog.remove();
5831
    };
5832
 
5833
    this.bindEnterKey = function ($input, $btn) {
5834
      $input.on('keypress', function (event) {
5835
        if (event.keyCode === key.code.ENTER) {
5836
          $btn.trigger('click');
5837
        }
5838
      });
5839
    };
5840
 
5841
    /**
5842
     * Show link dialog and set event handlers on dialog controls.
5843
     *
5844
     * @param {Object} linkInfo
5845
     * @return {Promise}
5846
     */
5847
    this.showLinkDialog = function (linkInfo) {
5848
      return $.Deferred(function (deferred) {
5849
        var $linkText = self.$dialog.find('.note-link-text'),
5850
        $linkUrl = self.$dialog.find('.note-link-url'),
5851
        $linkBtn = self.$dialog.find('.note-link-btn'),
5852
        $openInNewWindow = self.$dialog.find('input[type=checkbox]');
5853
 
5854
        ui.onDialogShown(self.$dialog, function () {
5855
          context.triggerEvent('dialog.shown');
5856
 
5857
          $linkText.val(linkInfo.text);
5858
 
5859
          $linkText.on('input', function () {
5860
            ui.toggleBtn($linkBtn, $linkText.val() && $linkUrl.val());
5861
            // if linktext was modified by keyup,
5862
            // stop cloning text from linkUrl
5863
            linkInfo.text = $linkText.val();
5864
          });
5865
 
5866
          // if no url was given, copy text to url
5867
          if (!linkInfo.url) {
5868
            linkInfo.url = linkInfo.text || 'http://';
5869
            ui.toggleBtn($linkBtn, linkInfo.text);
5870
          }
5871
 
5872
          $linkUrl.on('input', function () {
5873
            ui.toggleBtn($linkBtn, $linkText.val() && $linkUrl.val());
5874
            // display same link on `Text to display` input
5875
            // when create a new link
5876
            if (!linkInfo.text) {
5877
              $linkText.val($linkUrl.val());
5878
            }
5879
          }).val(linkInfo.url).trigger('focus');
5880
 
5881
          self.bindEnterKey($linkUrl, $linkBtn);
5882
          self.bindEnterKey($linkText, $linkBtn);
5883
 
5884
          $openInNewWindow.prop('checked', linkInfo.isNewWindow);
5885
 
5886
          $linkBtn.one('click', function (event) {
5887
            event.preventDefault();
5888
 
5889
            deferred.resolve({
5890
              range: linkInfo.range,
5891
              url: $linkUrl.val(),
5892
              text: $linkText.val(),
5893
              isNewWindow: $openInNewWindow.is(':checked')
5894
            });
5895
            self.$dialog.modal('hide');
5896
          });
5897
        });
5898
 
5899
        ui.onDialogHidden(self.$dialog, function () {
5900
          // detach events
5901
          $linkText.off('input keypress');
5902
          $linkUrl.off('input keypress');
5903
          $linkBtn.off('click');
5904
 
5905
          if (deferred.state() === 'pending') {
5906
            deferred.reject();
5907
          }
5908
        });
5909
 
5910
        ui.showDialog(self.$dialog);
5911
      }).promise();
5912
    };
5913
 
5914
    /**
5915
     * @param {Object} layoutInfo
5916
     */
5917
    this.show = function () {
5918
      var linkInfo = context.invoke('editor.getLinkInfo');
5919
 
5920
      context.invoke('editor.saveRange');
5921
      this.showLinkDialog(linkInfo).then(function (linkInfo) {
5922
        context.invoke('editor.restoreRange');
5923
        context.invoke('editor.createLink', linkInfo);
5924
      }).fail(function () {
5925
        context.invoke('editor.restoreRange');
5926
      });
5927
    };
5928
    context.memo('help.linkDialog.show', options.langInfo.help['linkDialog.show']);
5929
  };
5930
 
5931
  var LinkPopover = function (context) {
5932
    var self = this;
5933
    var ui = $.summernote.ui;
5934
 
5935
    var options = context.options;
5936
 
5937
    this.events = {
5938
      'summernote.keyup summernote.mouseup summernote.change summernote.scroll': function () {
5939
        self.update();
5940
      },
5941
      'summernote.dialog.shown': function () {
5942
        self.hide();
5943
      }
5944
    };
5945
 
5946
    this.shouldInitialize = function () {
5947
      return !list.isEmpty(options.popover.link);
5948
    };
5949
 
5950
    this.initialize = function () {
5951
      this.$popover = ui.popover({
5952
        className: 'note-link-popover',
5953
        callback: function ($node) {
5954
          var $content = $node.find('.popover-content');
5955
          $content.prepend('<span><a target="_blank"></a>&nbsp;</span>');
5956
        }
5957
      }).render().appendTo('body');
5958
      var $content = this.$popover.find('.popover-content');
5959
 
5960
      context.invoke('buttons.build', $content, options.popover.link);
5961
    };
5962
 
5963
    this.destroy = function () {
5964
      this.$popover.remove();
5965
    };
5966
 
5967
    this.update = function () {
5968
      // Prevent focusing on editable when invoke('code') is executed
5969
      if (!context.invoke('editor.hasFocus')) {
5970
        this.hide();
5971
        return;
5972
      }
5973
 
5974
      var rng = context.invoke('editor.createRange');
5975
      if (rng.isCollapsed() && rng.isOnAnchor()) {
5976
        var anchor = dom.ancestor(rng.sc, dom.isAnchor);
5977
        var href = $(anchor).attr('href');
5978
        this.$popover.find('a').attr('href', href).html(href);
5979
 
5980
        var pos = dom.posFromPlaceholder(anchor);
5981
        this.$popover.css({
5982
          display: 'block',
5983
          left: pos.left,
5984
          top: pos.top
5985
        });
5986
      } else {
5987
        this.hide();
5988
      }
5989
    };
5990
 
5991
    this.hide = function () {
5992
      this.$popover.hide();
5993
    };
5994
  };
5995
 
5996
  var ImageDialog = function (context) {
5997
    var self = this;
5998
    var ui = $.summernote.ui;
5999
 
6000
    var $editor = context.layoutInfo.editor;
6001
    var options = context.options;
6002
    var lang = options.langInfo;
6003
 
6004
    this.initialize = function () {
6005
      var $container = options.dialogsInBody ? $(document.body) : $editor;
6006
 
6007
      var imageLimitation = '';
6008
      if (options.maximumImageFileSize) {
6009
        var unit = Math.floor(Math.log(options.maximumImageFileSize) / Math.log(1024));
6010
        var readableSize = (options.maximumImageFileSize / Math.pow(1024, unit)).toFixed(2) * 1 +
6011
                           ' ' + ' KMGTP'[unit] + 'B';
6012
        imageLimitation = '<small>' + lang.image.maximumFileSize + ' : ' + readableSize + '</small>';
6013
      }
6014
 
6015
      var body = '<div class="form-group note-group-select-from-files">' +
6016
                   '<label>' + lang.image.selectFromFiles + '</label>' +
6017
                   '<input class="note-image-input form-control" type="file" name="files" accept="image/*" multiple="multiple" />' +
6018
                   imageLimitation +
6019
                 '</div>' +
6020
                 '<div class="form-group" style="overflow:auto;">' +
6021
                   '<label>' + lang.image.url + '</label>' +
6022
                   '<input class="note-image-url form-control col-md-12" type="text" />' +
6023
                 '</div>';
6024
      var footer = '<button href="#" class="btn btn-primary note-image-btn disabled" disabled>' + lang.image.insert + '</button>';
6025
 
6026
      this.$dialog = ui.dialog({
6027
        title: lang.image.insert,
6028
        fade: options.dialogsFade,
6029
        body: body,
6030
        footer: footer
6031
      }).render().appendTo($container);
6032
    };
6033
 
6034
    this.destroy = function () {
6035
      ui.hideDialog(this.$dialog);
6036
      this.$dialog.remove();
6037
    };
6038
 
6039
    this.bindEnterKey = function ($input, $btn) {
6040
      $input.on('keypress', function (event) {
6041
        if (event.keyCode === key.code.ENTER) {
6042
          $btn.trigger('click');
6043
        }
6044
      });
6045
    };
6046
 
6047
    this.show = function () {
6048
      context.invoke('editor.saveRange');
6049
      this.showImageDialog().then(function (data) {
6050
        // [workaround] hide dialog before restore range for IE range focus
6051
        ui.hideDialog(self.$dialog);
6052
        context.invoke('editor.restoreRange');
6053
 
6054
        if (typeof data === 'string') { // image url
6055
          context.invoke('editor.insertImage', data);
6056
        } else { // array of files
6057
          context.invoke('editor.insertImagesOrCallback', data);
6058
        }
6059
      }).fail(function () {
6060
        context.invoke('editor.restoreRange');
6061
      });
6062
    };
6063
 
6064
    /**
6065
     * show image dialog
6066
     *
6067
     * @param {jQuery} $dialog
6068
     * @return {Promise}
6069
     */
6070
    this.showImageDialog = function () {
6071
      return $.Deferred(function (deferred) {
6072
        var $imageInput = self.$dialog.find('.note-image-input'),
6073
            $imageUrl = self.$dialog.find('.note-image-url'),
6074
            $imageBtn = self.$dialog.find('.note-image-btn');
6075
 
6076
        ui.onDialogShown(self.$dialog, function () {
6077
          context.triggerEvent('dialog.shown');
6078
 
6079
          // Cloning imageInput to clear element.
6080
          $imageInput.replaceWith($imageInput.clone()
6081
            .on('change', function () {
6082
              deferred.resolve(this.files || this.value);
6083
            })
6084
            .val('')
6085
          );
6086
 
6087
          $imageBtn.click(function (event) {
6088
            event.preventDefault();
6089
 
6090
            deferred.resolve($imageUrl.val());
6091
          });
6092
 
6093
          $imageUrl.on('keyup paste', function () {
6094
            var url = $imageUrl.val();
6095
            ui.toggleBtn($imageBtn, url);
6096
          }).val('').trigger('focus');
6097
          self.bindEnterKey($imageUrl, $imageBtn);
6098
        });
6099
 
6100
        ui.onDialogHidden(self.$dialog, function () {
6101
          $imageInput.off('change');
6102
          $imageUrl.off('keyup paste keypress');
6103
          $imageBtn.off('click');
6104
 
6105
          if (deferred.state() === 'pending') {
6106
            deferred.reject();
6107
          }
6108
        });
6109
 
6110
        ui.showDialog(self.$dialog);
6111
      });
6112
    };
6113
  };
6114
 
6115
  var ImagePopover = function (context) {
6116
    var ui = $.summernote.ui;
6117
 
6118
    var options = context.options;
6119
 
6120
    this.shouldInitialize = function () {
6121
      return !list.isEmpty(options.popover.image);
6122
    };
6123
 
6124
    this.initialize = function () {
6125
      this.$popover = ui.popover({
6126
        className: 'note-image-popover'
6127
      }).render().appendTo('body');
6128
      var $content = this.$popover.find('.popover-content');
6129
 
6130
      context.invoke('buttons.build', $content, options.popover.image);
6131
    };
6132
 
6133
    this.destroy = function () {
6134
      this.$popover.remove();
6135
    };
6136
 
6137
    this.update = function (target) {
6138
      if (dom.isImg(target)) {
6139
        var pos = dom.posFromPlaceholder(target);
6140
        this.$popover.css({
6141
          display: 'block',
6142
          left: pos.left,
6143
          top: pos.top
6144
        });
6145
      } else {
6146
        this.hide();
6147
      }
6148
    };
6149
 
6150
    this.hide = function () {
6151
      this.$popover.hide();
6152
    };
6153
  };
6154
 
6155
  var VideoDialog = function (context) {
6156
    var self = this;
6157
    var ui = $.summernote.ui;
6158
 
6159
    var $editor = context.layoutInfo.editor;
6160
    var options = context.options;
6161
    var lang = options.langInfo;
6162
 
6163
    this.initialize = function () {
6164
      var $container = options.dialogsInBody ? $(document.body) : $editor;
6165
 
6166
      var body = '<div class="form-group row-fluid">' +
6167
          '<label>' + lang.video.url + ' <small class="text-muted">' + lang.video.providers + '</small></label>' +
6168
          '<input class="note-video-url form-control span12" type="text" />' +
6169
          '</div>';
6170
      var footer = '<button href="#" class="btn btn-primary note-video-btn disabled" disabled>' + lang.video.insert + '</button>';
6171
 
6172
      this.$dialog = ui.dialog({
6173
        title: lang.video.insert,
6174
        fade: options.dialogsFade,
6175
        body: body,
6176
        footer: footer
6177
      }).render().appendTo($container);
6178
    };
6179
 
6180
    this.destroy = function () {
6181
      ui.hideDialog(this.$dialog);
6182
      this.$dialog.remove();
6183
    };
6184
 
6185
    this.bindEnterKey = function ($input, $btn) {
6186
      $input.on('keypress', function (event) {
6187
        if (event.keyCode === key.code.ENTER) {
6188
          $btn.trigger('click');
6189
        }
6190
      });
6191
    };
6192
 
6193
    this.createVideoNode = function (url) {
6194
      // video url patterns(youtube, instagram, vimeo, dailymotion, youku, mp4, ogg, webm)
6195
      var ytRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
6196
      var ytMatch = url.match(ytRegExp);
6197
 
6198
      var igRegExp = /\/\/instagram.com\/p\/(.[a-zA-Z0-9_-]*)/;
6199
      var igMatch = url.match(igRegExp);
6200
 
6201
      var vRegExp = /\/\/vine.co\/v\/(.[a-zA-Z0-9]*)/;
6202
      var vMatch = url.match(vRegExp);
6203
 
6204
      var vimRegExp = /\/\/(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/;
6205
      var vimMatch = url.match(vimRegExp);
6206
 
6207
      var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/;
6208
      var dmMatch = url.match(dmRegExp);
6209
 
6210
      var youkuRegExp = /\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/;
6211
      var youkuMatch = url.match(youkuRegExp);
6212
 
6213
      var mp4RegExp = /^.+.(mp4|m4v)$/;
6214
      var mp4Match = url.match(mp4RegExp);
6215
 
6216
      var oggRegExp = /^.+.(ogg|ogv)$/;
6217
      var oggMatch = url.match(oggRegExp);
6218
 
6219
      var webmRegExp = /^.+.(webm)$/;
6220
      var webmMatch = url.match(webmRegExp);
6221
 
6222
      var $video;
6223
      if (ytMatch && ytMatch[1].length === 11) {
6224
        var youtubeId = ytMatch[1];
6225
        $video = $('<iframe>')
6226
            .attr('frameborder', 0)
6227
            .attr('src', '//www.youtube.com/embed/' + youtubeId)
6228
            .attr('width', '640').attr('height', '360');
6229
      } else if (igMatch && igMatch[0].length) {
6230
        $video = $('<iframe>')
6231
            .attr('frameborder', 0)
6232
            .attr('src', igMatch[0] + '/embed/')
6233
            .attr('width', '612').attr('height', '710')
6234
            .attr('scrolling', 'no')
6235
            .attr('allowtransparency', 'true');
6236
      } else if (vMatch && vMatch[0].length) {
6237
        $video = $('<iframe>')
6238
            .attr('frameborder', 0)
6239
            .attr('src', vMatch[0] + '/embed/simple')
6240
            .attr('width', '600').attr('height', '600')
6241
            .attr('class', 'vine-embed');
6242
      } else if (vimMatch && vimMatch[3].length) {
6243
        $video = $('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>')
6244
            .attr('frameborder', 0)
6245
            .attr('src', '//player.vimeo.com/video/' + vimMatch[3])
6246
            .attr('width', '640').attr('height', '360');
6247
      } else if (dmMatch && dmMatch[2].length) {
6248
        $video = $('<iframe>')
6249
            .attr('frameborder', 0)
6250
            .attr('src', '//www.dailymotion.com/embed/video/' + dmMatch[2])
6251
            .attr('width', '640').attr('height', '360');
6252
      } else if (youkuMatch && youkuMatch[1].length) {
6253
        $video = $('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>')
6254
            .attr('frameborder', 0)
6255
            .attr('height', '498')
6256
            .attr('width', '510')
6257
            .attr('src', '//player.youku.com/embed/' + youkuMatch[1]);
6258
      } else if (mp4Match || oggMatch || webmMatch) {
6259
        $video = $('<video controls>')
6260
            .attr('src', url)
6261
            .attr('width', '640').attr('height', '360');
6262
      } else {
6263
        // this is not a known video link. Now what, Cat? Now what?
6264
        return false;
6265
      }
6266
 
6267
      $video.addClass('note-video-clip');
6268
 
6269
      return $video[0];
6270
    };
6271
 
6272
    this.show = function () {
6273
      var text = context.invoke('editor.getSelectedText');
6274
      context.invoke('editor.saveRange');
6275
      this.showVideoDialog(text).then(function (url) {
6276
        // [workaround] hide dialog before restore range for IE range focus
6277
        ui.hideDialog(self.$dialog);
6278
        context.invoke('editor.restoreRange');
6279
 
6280
        // build node
6281
        var $node = self.createVideoNode(url);
6282
 
6283
        if ($node) {
6284
          // insert video node
6285
          context.invoke('editor.insertNode', $node);
6286
        }
6287
      }).fail(function () {
6288
        context.invoke('editor.restoreRange');
6289
      });
6290
    };
6291
 
6292
    /**
6293
     * show image dialog
6294
     *
6295
     * @param {jQuery} $dialog
6296
     * @return {Promise}
6297
     */
6298
    this.showVideoDialog = function (text) {
6299
      return $.Deferred(function (deferred) {
6300
        var $videoUrl = self.$dialog.find('.note-video-url'),
6301
            $videoBtn = self.$dialog.find('.note-video-btn');
6302
 
6303
        ui.onDialogShown(self.$dialog, function () {
6304
          context.triggerEvent('dialog.shown');
6305
 
6306
          $videoUrl.val(text).on('input', function () {
6307
            ui.toggleBtn($videoBtn, $videoUrl.val());
6308
          }).trigger('focus');
6309
 
6310
          $videoBtn.click(function (event) {
6311
            event.preventDefault();
6312
 
6313
            deferred.resolve($videoUrl.val());
6314
          });
6315
 
6316
          self.bindEnterKey($videoUrl, $videoBtn);
6317
        });
6318
 
6319
        ui.onDialogHidden(self.$dialog, function () {
6320
          $videoUrl.off('input');
6321
          $videoBtn.off('click');
6322
 
6323
          if (deferred.state() === 'pending') {
6324
            deferred.reject();
6325
          }
6326
        });
6327
 
6328
        ui.showDialog(self.$dialog);
6329
      });
6330
    };
6331
  };
6332
 
6333
  var HelpDialog = function (context) {
6334
    var self = this;
6335
    var ui = $.summernote.ui;
6336
 
6337
    var $editor = context.layoutInfo.editor;
6338
    var options = context.options;
6339
    var lang = options.langInfo;
6340
 
6341
    this.createShortCutList = function () {
6342
      var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc'];
6343
      return Object.keys(keyMap).map(function (key) {
6344
        var command = keyMap[key];
6345
        var $row = $('<div><div class="help-list-item"/></div>');
6346
        $row.append($('<label><kbd>' + key + '</kdb></label>').css({
6347
          'width': 180,
6348
          'margin-right': 10
6349
        })).append($('<span/>').html(context.memo('help.' + command) || command));
6350
        return $row.html();
6351
      }).join('');
6352
    };
6353
 
6354
    this.initialize = function () {
6355
      var $container = options.dialogsInBody ? $(document.body) : $editor;
6356
 
6357
      var body = [
6358
        '<p class="text-center">',
6359
        '<a href="//summernote.org/" target="_blank">Summernote 0.8.1</a> · ',
6360
        '<a href="//github.com/summernote/summernote" target="_blank">Project</a> · ',
6361
        '<a href="//github.com/summernote/summernote/issues" target="_blank">Issues</a>',
6362
        '</p>'
6363
      ].join('');
6364
 
6365
      this.$dialog = ui.dialog({
6366
        title: lang.options.help,
6367
        fade: options.dialogsFade,
6368
        body: this.createShortCutList(),
6369
        footer: body,
6370
        callback: function ($node) {
6371
          $node.find('.modal-body').css({
6372
            'max-height': 300,
6373
            'overflow': 'scroll'
6374
          });
6375
        }
6376
      }).render().appendTo($container);
6377
    };
6378
 
6379
    this.destroy = function () {
6380
      ui.hideDialog(this.$dialog);
6381
      this.$dialog.remove();
6382
    };
6383
 
6384
    /**
6385
     * show help dialog
6386
     *
6387
     * @return {Promise}
6388
     */
6389
    this.showHelpDialog = function () {
6390
      return $.Deferred(function (deferred) {
6391
        ui.onDialogShown(self.$dialog, function () {
6392
          context.triggerEvent('dialog.shown');
6393
          deferred.resolve();
6394
        });
6395
        ui.showDialog(self.$dialog);
6396
      }).promise();
6397
    };
6398
 
6399
    this.show = function () {
6400
      context.invoke('editor.saveRange');
6401
      this.showHelpDialog().then(function () {
6402
        context.invoke('editor.restoreRange');
6403
      });
6404
    };
6405
  };
6406
 
6407
  var AirPopover = function (context) {
6408
    var self = this;
6409
    var ui = $.summernote.ui;
6410
 
6411
    var options = context.options;
6412
 
6413
    var AIR_MODE_POPOVER_X_OFFSET = 20;
6414
 
6415
    this.events = {
6416
      'summernote.keyup summernote.mouseup summernote.scroll': function () {
6417
        self.update();
6418
      },
6419
      'summernote.change summernote.dialog.shown': function () {
6420
        self.hide();
6421
      },
6422
      'summernote.focusout': function (we, e) {
6423
        // [workaround] Firefox doesn't support relatedTarget on focusout
6424
        //  - Ignore hide action on focus out in FF.
6425
        if (agent.isFF) {
6426
          return;
6427
        }
6428
 
6429
        if (!e.relatedTarget || !dom.ancestor(e.relatedTarget, func.eq(self.$popover[0]))) {
6430
          self.hide();
6431
        }
6432
      }
6433
    };
6434
 
6435
    this.shouldInitialize = function () {
6436
      return options.airMode && !list.isEmpty(options.popover.air);
6437
    };
6438
 
6439
    this.initialize = function () {
6440
      this.$popover = ui.popover({
6441
        className: 'note-air-popover'
6442
      }).render().appendTo('body');
6443
      var $content = this.$popover.find('.popover-content');
6444
 
6445
      context.invoke('buttons.build', $content, options.popover.air);
6446
    };
6447
 
6448
    this.destroy = function () {
6449
      this.$popover.remove();
6450
    };
6451
 
6452
    this.update = function () {
6453
      var styleInfo = context.invoke('editor.currentStyle');
6454
      if (styleInfo.range && !styleInfo.range.isCollapsed()) {
6455
        var rect = list.last(styleInfo.range.getClientRects());
6456
        if (rect) {
6457
          var bnd = func.rect2bnd(rect);
6458
          this.$popover.css({
6459
            display: 'block',
6460
            left: Math.max(bnd.left + bnd.width / 2, 0) - AIR_MODE_POPOVER_X_OFFSET,
6461
            top: bnd.top + bnd.height
6462
          });
6463
        }
6464
      } else {
6465
        this.hide();
6466
      }
6467
    };
6468
 
6469
    this.hide = function () {
6470
      this.$popover.hide();
6471
    };
6472
  };
6473
 
6474
  var HintPopover = function (context) {
6475
    var self = this;
6476
    var ui = $.summernote.ui;
6477
 
6478
    var POPOVER_DIST = 5;
6479
    var hint = context.options.hint || [];
6480
    var direction = context.options.hintDirection || 'bottom';
6481
    var hints = $.isArray(hint) ? hint : [hint];
6482
 
6483
    this.events = {
6484
      'summernote.keyup': function (we, e) {
6485
        if (!e.isDefaultPrevented()) {
6486
          self.handleKeyup(e);
6487
        }
6488
      },
6489
      'summernote.keydown': function (we, e) {
6490
        self.handleKeydown(e);
6491
      },
6492
      'summernote.dialog.shown': function () {
6493
        self.hide();
6494
      }
6495
    };
6496
 
6497
    this.shouldInitialize = function () {
6498
      return hints.length > 0;
6499
    };
6500
 
6501
    this.initialize = function () {
6502
      this.lastWordRange = null;
6503
      this.$popover = ui.popover({
6504
        className: 'note-hint-popover',
6505
        hideArrow: true,
6506
        direction: ''
6507
      }).render().appendTo('body');
6508
 
6509
      this.$popover.hide();
6510
 
6511
      this.$content = this.$popover.find('.popover-content');
6512
 
6513
      this.$content.on('click', '.note-hint-item', function () {
6514
        self.$content.find('.active').removeClass('active');
6515
        $(this).addClass('active');
6516
        self.replace();
6517
      });
6518
    };
6519
 
6520
    this.destroy = function () {
6521
      this.$popover.remove();
6522
    };
6523
 
6524
    this.selectItem = function ($item) {
6525
      this.$content.find('.active').removeClass('active');
6526
      $item.addClass('active');
6527
 
6528
      this.$content[0].scrollTop = $item[0].offsetTop - (this.$content.innerHeight() / 2);
6529
    };
6530
 
6531
    this.moveDown = function () {
6532
      var $current = this.$content.find('.note-hint-item.active');
6533
      var $next = $current.next();
6534
 
6535
      if ($next.length) {
6536
        this.selectItem($next);
6537
      } else {
6538
        var $nextGroup = $current.parent().next();
6539
 
6540
        if (!$nextGroup.length) {
6541
          $nextGroup = this.$content.find('.note-hint-group').first();
6542
        }
6543
 
6544
        this.selectItem($nextGroup.find('.note-hint-item').first());
6545
      }
6546
    };
6547
 
6548
    this.moveUp = function () {
6549
      var $current = this.$content.find('.note-hint-item.active');
6550
      var $prev = $current.prev();
6551
 
6552
      if ($prev.length) {
6553
        this.selectItem($prev);
6554
      } else {
6555
        var $prevGroup = $current.parent().prev();
6556
 
6557
        if (!$prevGroup.length) {
6558
          $prevGroup = this.$content.find('.note-hint-group').last();
6559
        }
6560
 
6561
        this.selectItem($prevGroup.find('.note-hint-item').last());
6562
      }
6563
    };
6564
 
6565
    this.replace = function () {
6566
      var $item = this.$content.find('.note-hint-item.active');
6567
 
6568
      if ($item.length) {
6569
        var node = this.nodeFromItem($item);
6570
        this.lastWordRange.insertNode(node);
6571
        range.createFromNode(node).collapse().select();
6572
 
6573
        this.lastWordRange = null;
6574
        this.hide();
6575
        context.invoke('editor.focus');
6576
      }
6577
 
6578
    };
6579
 
6580
    this.nodeFromItem = function ($item) {
6581
      var hint = hints[$item.data('index')];
6582
      var item = $item.data('item');
6583
      var node = hint.content ? hint.content(item) : item;
6584
      if (typeof node === 'string') {
6585
        node = dom.createText(node);
6586
      }
6587
      return node;
6588
    };
6589
 
6590
    this.createItemTemplates = function (hintIdx, items) {
6591
      var hint = hints[hintIdx];
6592
      return items.map(function (item, idx) {
6593
        var $item = $('<div class="note-hint-item"/>');
6594
        $item.append(hint.template ? hint.template(item) : item + '');
6595
        $item.data({
6596
          'index': hintIdx,
6597
          'item': item
6598
        });
6599
 
6600
        if (hintIdx === 0 && idx === 0) {
6601
          $item.addClass('active');
6602
        }
6603
        return $item;
6604
      });
6605
    };
6606
 
6607
    this.handleKeydown = function (e) {
6608
      if (!this.$popover.is(':visible')) {
6609
        return;
6610
      }
6611
 
6612
      if (e.keyCode === key.code.ENTER) {
6613
        e.preventDefault();
6614
        this.replace();
6615
      } else if (e.keyCode === key.code.UP) {
6616
        e.preventDefault();
6617
        this.moveUp();
6618
      } else if (e.keyCode === key.code.DOWN) {
6619
        e.preventDefault();
6620
        this.moveDown();
6621
      }
6622
    };
6623
 
6624
    this.searchKeyword = function (index, keyword, callback) {
6625
      var hint = hints[index];
6626
      if (hint && hint.match.test(keyword) && hint.search) {
6627
        var matches = hint.match.exec(keyword);
6628
        hint.search(matches[1], callback);
6629
      } else {
6630
        callback();
6631
      }
6632
    };
6633
 
6634
    this.createGroup = function (idx, keyword) {
6635
      var $group = $('<div class="note-hint-group note-hint-group-' + idx + '"/>');
6636
      this.searchKeyword(idx, keyword, function (items) {
6637
        items = items || [];
6638
        if (items.length) {
6639
          $group.html(self.createItemTemplates(idx, items));
6640
          self.show();
6641
        }
6642
      });
6643
 
6644
      return $group;
6645
    };
6646
 
6647
    this.handleKeyup = function (e) {
6648
      if (list.contains([key.code.ENTER, key.code.UP, key.code.DOWN], e.keyCode)) {
6649
        if (e.keyCode === key.code.ENTER) {
6650
          if (this.$popover.is(':visible')) {
6651
            return;
6652
          }
6653
        }
6654
      } else {
6655
        var wordRange = context.invoke('editor.createRange').getWordRange();
6656
        var keyword = wordRange.toString();
6657
        if (hints.length && keyword) {
6658
          this.$content.empty();
6659
 
6660
          var bnd = func.rect2bnd(list.last(wordRange.getClientRects()));
6661
          if (bnd) {
6662
 
6663
            this.$popover.hide();
6664
 
6665
            this.lastWordRange = wordRange;
6666
 
6667
            hints.forEach(function (hint, idx) {
6668
              if (hint.match.test(keyword)) {
6669
                self.createGroup(idx, keyword).appendTo(self.$content);
6670
              }
6671
            });
6672
 
6673
            // set position for popover after group is created
6674
            if (direction === 'top') {
6675
              this.$popover.css({
6676
                left: bnd.left,
6677
                top: bnd.top - this.$popover.outerHeight() - POPOVER_DIST
6678
              });
6679
            } else {
6680
              this.$popover.css({
6681
                left: bnd.left,
6682
                top: bnd.top + bnd.height + POPOVER_DIST
6683
              });
6684
            }
6685
 
6686
          }
6687
        } else {
6688
          this.hide();
6689
        }
6690
      }
6691
    };
6692
 
6693
    this.show = function () {
6694
      this.$popover.show();
6695
    };
6696
 
6697
    this.hide = function () {
6698
      this.$popover.hide();
6699
    };
6700
  };
6701
 
6702
 
6703
  $.summernote = $.extend($.summernote, {
6704
    version: '0.8.1',
6705
    ui: ui,
6706
 
6707
    plugins: {},
6708
 
6709
    options: {
6710
      modules: {
6711
        'editor': Editor,
6712
        'clipboard': Clipboard,
6713
        'dropzone': Dropzone,
6714
        'codeview': Codeview,
6715
        'statusbar': Statusbar,
6716
        'fullscreen': Fullscreen,
6717
        'handle': Handle,
6718
        // FIXME: HintPopover must be front of autolink
6719
        //  - Script error about range when Enter key is pressed on hint popover
6720
        'hintPopover': HintPopover,
6721
        'autoLink': AutoLink,
6722
        'autoSync': AutoSync,
6723
        'placeholder': Placeholder,
6724
        'buttons': Buttons,
6725
        'toolbar': Toolbar,
6726
        'linkDialog': LinkDialog,
6727
        'linkPopover': LinkPopover,
6728
        'imageDialog': ImageDialog,
6729
        'imagePopover': ImagePopover,
6730
        'videoDialog': VideoDialog,
6731
        'helpDialog': HelpDialog,
6732
        'airPopover': AirPopover
6733
      },
6734
 
6735
      buttons: {},
6736
 
6737
      lang: 'en-US',
6738
 
6739
      // toolbar
6740
      toolbar: [
6741
        ['style', ['style']],
6742
        ['font', ['bold', 'underline', 'clear']],
6743
        ['fontname', ['fontname']],
6744
        ['color', ['color']],
6745
        ['para', ['ul', 'ol', 'paragraph']],
6746
        ['table', ['table']],
6747
        ['insert', ['link', 'picture', 'video']],
6748
        ['view', ['fullscreen', 'codeview', 'help']]
6749
      ],
6750
 
6751
      // popover
6752
      popover: {
6753
        image: [
6754
          ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
6755
          ['float', ['floatLeft', 'floatRight', 'floatNone']],
6756
          ['remove', ['removeMedia']]
6757
        ],
6758
        link: [
6759
          ['link', ['linkDialogShow', 'unlink']]
6760
        ],
6761
        air: [
6762
          ['color', ['color']],
6763
          ['font', ['bold', 'underline', 'clear']],
6764
          ['para', ['ul', 'paragraph']],
6765
          ['table', ['table']],
6766
          ['insert', ['link', 'picture']]
6767
        ]
6768
      },
6769
 
6770
      // air mode: inline editor
6771
      airMode: false,
6772
 
6773
      width: null,
6774
      height: null,
6775
 
6776
      focus: false,
6777
      tabSize: 4,
6778
      styleWithSpan: true,
6779
      shortcuts: true,
6780
      textareaAutoSync: true,
6781
      direction: null,
6782
 
6783
      styleTags: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
6784
 
6785
      fontNames: [
6786
        'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New',
6787
        'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande',
6788
        'Tahoma', 'Times New Roman', 'Verdana'
6789
      ],
6790
 
6791
      fontSizes: ['8', '9', '10', '11', '12', '14', '18', '24', '36'],
6792
 
6793
      // pallete colors(n x n)
6794
      colors: [
6795
        ['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF'],
6796
        ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'],
6797
        ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'],
6798
        ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'],
6799
        ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'],
6800
        ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'],
6801
        ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'],
6802
        ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031']
6803
      ],
6804
 
6805
      lineHeights: ['1.0', '1.2', '1.4', '1.5', '1.6', '1.8', '2.0', '3.0'],
6806
 
6807
      tableClassName: 'table table-bordered',
6808
 
6809
      insertTableMaxSize: {
6810
        col: 10,
6811
        row: 10
6812
      },
6813
 
6814
      dialogsInBody: false,
6815
      dialogsFade: false,
6816
 
6817
      maximumImageFileSize: null,
6818
 
6819
      callbacks: {
6820
        onInit: null,
6821
        onFocus: null,
6822
        onBlur: null,
6823
        onEnter: null,
6824
        onKeyup: null,
6825
        onKeydown: null,
6826
        onSubmit: null,
6827
        onImageUpload: null,
6828
        onImageUploadError: null
6829
      },
6830
 
6831
      codemirror: {
6832
        mode: 'text/html',
6833
        htmlMode: true,
6834
        lineNumbers: true
6835
      },
6836
 
6837
      keyMap: {
6838
        pc: {
6839
          'ENTER': 'insertParagraph',
6840
          'CTRL+Z': 'undo',
6841
          'CTRL+Y': 'redo',
6842
          'TAB': 'tab',
6843
          'SHIFT+TAB': 'untab',
6844
          'CTRL+B': 'bold',
6845
          'CTRL+I': 'italic',
6846
          'CTRL+U': 'underline',
6847
          'CTRL+SHIFT+S': 'strikethrough',
6848
          'CTRL+BACKSLASH': 'removeFormat',
6849
          'CTRL+SHIFT+L': 'justifyLeft',
6850
          'CTRL+SHIFT+E': 'justifyCenter',
6851
          'CTRL+SHIFT+R': 'justifyRight',
6852
          'CTRL+SHIFT+J': 'justifyFull',
6853
          'CTRL+SHIFT+NUM7': 'insertUnorderedList',
6854
          'CTRL+SHIFT+NUM8': 'insertOrderedList',
6855
          'CTRL+LEFTBRACKET': 'outdent',
6856
          'CTRL+RIGHTBRACKET': 'indent',
6857
          'CTRL+NUM0': 'formatPara',
6858
          'CTRL+NUM1': 'formatH1',
6859
          'CTRL+NUM2': 'formatH2',
6860
          'CTRL+NUM3': 'formatH3',
6861
          'CTRL+NUM4': 'formatH4',
6862
          'CTRL+NUM5': 'formatH5',
6863
          'CTRL+NUM6': 'formatH6',
6864
          'CTRL+ENTER': 'insertHorizontalRule',
6865
          'CTRL+K': 'linkDialog.show'
6866
        },
6867
 
6868
        mac: {
6869
          'ENTER': 'insertParagraph',
6870
          'CMD+Z': 'undo',
6871
          'CMD+SHIFT+Z': 'redo',
6872
          'TAB': 'tab',
6873
          'SHIFT+TAB': 'untab',
6874
          'CMD+B': 'bold',
6875
          'CMD+I': 'italic',
6876
          'CMD+U': 'underline',
6877
          'CMD+SHIFT+S': 'strikethrough',
6878
          'CMD+BACKSLASH': 'removeFormat',
6879
          'CMD+SHIFT+L': 'justifyLeft',
6880
          'CMD+SHIFT+E': 'justifyCenter',
6881
          'CMD+SHIFT+R': 'justifyRight',
6882
          'CMD+SHIFT+J': 'justifyFull',
6883
          'CMD+SHIFT+NUM7': 'insertUnorderedList',
6884
          'CMD+SHIFT+NUM8': 'insertOrderedList',
6885
          'CMD+LEFTBRACKET': 'outdent',
6886
          'CMD+RIGHTBRACKET': 'indent',
6887
          'CMD+NUM0': 'formatPara',
6888
          'CMD+NUM1': 'formatH1',
6889
          'CMD+NUM2': 'formatH2',
6890
          'CMD+NUM3': 'formatH3',
6891
          'CMD+NUM4': 'formatH4',
6892
          'CMD+NUM5': 'formatH5',
6893
          'CMD+NUM6': 'formatH6',
6894
          'CMD+ENTER': 'insertHorizontalRule',
6895
          'CMD+K': 'linkDialog.show'
6896
        }
6897
      },
6898
      icons: {
6899
        'align': 'note-icon-align',
6900
        'alignCenter': 'note-icon-align-center',
6901
        'alignJustify': 'note-icon-align-justify',
6902
        'alignLeft': 'note-icon-align-left',
6903
        'alignRight': 'note-icon-align-right',
6904
        'indent': 'note-icon-align-indent',
6905
        'outdent': 'note-icon-align-outdent',
6906
        'arrowsAlt': 'note-icon-arrows-alt',
6907
        'bold': 'note-icon-bold',
6908
        'caret': 'note-icon-caret',
6909
        'circle': 'note-icon-circle',
6910
        'close': 'note-icon-close',
6911
        'code': 'note-icon-code',
6912
        'eraser': 'note-icon-eraser',
6913
        'font': 'note-icon-font',
6914
        'frame': 'note-icon-frame',
6915
        'italic': 'note-icon-italic',
6916
        'link': 'note-icon-link',
6917
        'unlink': 'note-icon-chain-broken',
6918
        'magic': 'note-icon-magic',
6919
        'menuCheck': 'note-icon-check',
6920
        'minus': 'note-icon-minus',
6921
        'orderedlist': 'note-icon-orderedlist',
6922
        'pencil': 'note-icon-pencil',
6923
        'picture': 'note-icon-picture',
6924
        'question': 'note-icon-question',
6925
        'redo': 'note-icon-redo',
6926
        'square': 'note-icon-square',
6927
        'strikethrough': 'note-icon-strikethrough',
6928
        'subscript': 'note-icon-subscript',
6929
        'superscript': 'note-icon-superscript',
6930
        'table': 'note-icon-table',
6931
        'textHeight': 'note-icon-text-height',
6932
        'trash': 'note-icon-trash',
6933
        'underline': 'note-icon-underline',
6934
        'undo': 'note-icon-undo',
6935
        'unorderedlist': 'note-icon-unorderedlist',
6936
        'video': 'note-icon-video'
6937
      }
6938
    }
6939
  });
6940
 
6941
}));