Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

7070 linhas
200 KiB

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