@toast-ui/editor 3.0.1 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +4 -4
  2. package/dist/esm/i18n/ar.js +63 -0
  3. package/dist/esm/i18n/cs-cz.js +63 -0
  4. package/dist/esm/i18n/de-de.js +63 -0
  5. package/dist/esm/i18n/en-us.js +63 -0
  6. package/dist/esm/i18n/es-es.js +63 -0
  7. package/dist/esm/i18n/fi-fi.js +63 -0
  8. package/dist/esm/i18n/fr-fr.js +63 -0
  9. package/dist/esm/i18n/gl-es.js +63 -0
  10. package/dist/esm/i18n/hr-hr.js +63 -0
  11. package/dist/esm/i18n/i18n.js +223 -0
  12. package/dist/esm/i18n/it-it.js +63 -0
  13. package/dist/esm/i18n/ja-jp.js +63 -0
  14. package/dist/esm/i18n/ko-kr.js +63 -0
  15. package/dist/esm/i18n/nb-no.js +63 -0
  16. package/dist/esm/i18n/nl-nl.js +63 -0
  17. package/dist/esm/i18n/pl-pl.js +63 -0
  18. package/dist/esm/i18n/pt-br.js +63 -0
  19. package/dist/esm/i18n/ru-ru.js +64 -0
  20. package/dist/esm/i18n/sv-se.js +63 -0
  21. package/dist/esm/i18n/tr-tr.js +63 -0
  22. package/dist/esm/i18n/uk-ua.js +63 -0
  23. package/dist/esm/i18n/zh-cn.js +63 -0
  24. package/dist/esm/i18n/zh-tw.js +63 -0
  25. package/dist/esm/index.js +2887 -441
  26. package/dist/esm/indexViewer.js +1659 -293
  27. package/dist/i18n/ar.js +1 -1
  28. package/dist/i18n/cs-cz.js +1 -1
  29. package/dist/i18n/de-de.js +1 -1
  30. package/dist/i18n/es-es.js +1 -1
  31. package/dist/i18n/fi-fi.js +1 -1
  32. package/dist/i18n/fr-fr.js +1 -1
  33. package/dist/i18n/gl-es.js +1 -1
  34. package/dist/i18n/hr-hr.js +1 -1
  35. package/dist/i18n/it-it.js +1 -1
  36. package/dist/i18n/ja-jp.js +1 -1
  37. package/dist/i18n/ko-kr.js +1 -1
  38. package/dist/i18n/nb-no.js +1 -1
  39. package/dist/i18n/nl-nl.js +1 -1
  40. package/dist/i18n/pl-pl.js +1 -1
  41. package/dist/i18n/pt-br.js +1 -1
  42. package/dist/i18n/ru-ru.js +15 -14
  43. package/dist/i18n/sv-se.js +1 -1
  44. package/dist/i18n/tr-tr.js +1 -1
  45. package/dist/i18n/uk-ua.js +1 -1
  46. package/dist/i18n/zh-cn.js +1 -1
  47. package/dist/i18n/zh-tw.js +1 -1
  48. package/dist/toastui-editor-only.css +27 -19
  49. package/dist/toastui-editor-viewer.css +10 -2
  50. package/dist/toastui-editor-viewer.js +1849 -386
  51. package/dist/toastui-editor.css +36 -20
  52. package/dist/toastui-editor.js +2841 -318
  53. package/package.json +10 -1
  54. package/types/editor.d.ts +6 -4
  55. package/types/index.d.ts +4 -3
  56. package/types/toastui-editor-viewer.d.ts +39 -0
package/dist/esm/index.js CHANGED
@@ -1,3 +1,10 @@
1
+ /**
2
+ * @toast-ui/editor
3
+ * @version 3.1.1 | Wed Oct 27 2021
4
+ * @author NHN FE Development Lab <dl_javascript@nhn.com>
5
+ * @license MIT
6
+ */
7
+
1
8
  import { Fragment, Schema, Slice, NodeRange, Mark as Mark$1, DOMParser, Node as Node$3 } from 'prosemirror-model';
2
9
  import { DecorationSet, Decoration, EditorView } from 'prosemirror-view';
3
10
  import { ReplaceAroundStep, liftTarget, canSplit, StepMap } from 'prosemirror-transform';
@@ -49,10 +56,14 @@ var __assign$1 = function() {
49
56
  return __assign$1.apply(this, arguments);
50
57
  };
51
58
 
52
- function __spreadArray$1(to, from) {
53
- for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
54
- to[j] = from[i];
55
- return to;
59
+ function __spreadArray$1(to, from, pack) {
60
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
61
+ if (ar || !(i in from)) {
62
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
63
+ ar[i] = from[i];
64
+ }
65
+ }
66
+ return to.concat(ar || Array.prototype.slice.call(from));
56
67
  }
57
68
 
58
69
  function __makeTemplateObject(cooked, raw) {
@@ -77,12 +88,16 @@ function __makeTemplateObject(cooked, raw) {
77
88
  * @param {Object} [context] Context(this) of callback function
78
89
  * @memberof module:collection
79
90
  * @example
80
- * var forEachOwnProperties = require('tui-code-snippet/collection/forEachOwnProperties'); // node, commonjs
91
+ * // ES6
92
+ * import forEachOwnProperties from 'tui-code-snippet/collection/forEachOwnProperties';
93
+ *
94
+ * // CommonJS
95
+ * const forEachOwnProperties = require('tui-code-snippet/collection/forEachOwnProperties');
81
96
  *
82
- * var sum = 0;
97
+ * let sum = 0;
83
98
  *
84
99
  * forEachOwnProperties({a:1,b:2,c:3}, function(value){
85
- * sum += value;
100
+ * sum += value;
86
101
  * });
87
102
  * alert(sum); // 6
88
103
  */
@@ -190,12 +205,16 @@ var isArray_1 = isArray$3;
190
205
  * @param {Object} [context] Context(this) of callback function
191
206
  * @memberof module:collection
192
207
  * @example
193
- * var forEachArray = require('tui-code-snippet/collection/forEachArray'); // node, commonjs
208
+ * // ES6
209
+ * import forEachArray from 'tui-code-snippet/collection/forEachArray';
210
+ *
211
+ * // CommonJS
212
+ * const forEachArray = require('tui-code-snippet/collection/forEachArray');
194
213
  *
195
- * var sum = 0;
214
+ * let sum = 0;
196
215
  *
197
216
  * forEachArray([1,2,3], function(value){
198
- * sum += value;
217
+ * sum += value;
199
218
  * });
200
219
  * alert(sum); // 6
201
220
  */
@@ -240,19 +259,23 @@ var forEachOwnProperties$1 = forEachOwnProperties_1;
240
259
  * @param {Object} [context] Context(this) of callback function
241
260
  * @memberof module:collection
242
261
  * @example
243
- * var forEach = require('tui-code-snippet/collection/forEach'); // node, commonjs
262
+ * // ES6
263
+ * import forEach from 'tui-code-snippet/collection/forEach';
264
+ *
265
+ * // CommonJS
266
+ * const forEach = require('tui-code-snippet/collection/forEach');
244
267
  *
245
- * var sum = 0;
268
+ * let sum = 0;
246
269
  *
247
270
  * forEach([1,2,3], function(value){
248
- * sum += value;
271
+ * sum += value;
249
272
  * });
250
273
  * alert(sum); // 6
251
274
  *
252
275
  * // In case of Array-like object
253
- * var array = Array.prototype.slice.call(arrayLike); // change to array
276
+ * const array = Array.prototype.slice.call(arrayLike); // change to array
254
277
  * forEach(array, function(value){
255
- * sum += value;
278
+ * sum += value;
256
279
  * });
257
280
  */
258
281
  function forEach$4(obj, iteratee, context) {
@@ -315,11 +338,15 @@ var isArray$1 = isArray_1;
315
338
  * @returns {number} the First index at which a given element, or -1 if it is not present
316
339
  * @memberof module:array
317
340
  * @example
318
- * var inArray = require('tui-code-snippet/array/inArray'); // node, commonjs
341
+ * // ES6
342
+ * import inArray from 'tui-code-snippet/array/inArray';
343
+ *
344
+ * // CommonJS
345
+ * const inArray = require('tui-code-snippet/array/inArray');
319
346
  *
320
- * var arr = ['one', 'two', 'three', 'four'];
321
- * var idx1 = inArray('one', arr, 3); // -1
322
- * var idx2 = inArray('one', arr); // 0
347
+ * const arr = ['one', 'two', 'three', 'four'];
348
+ * const idx1 = inArray('one', arr, 3); // -1
349
+ * const idx2 = inArray('one', arr); // 0
323
350
  */
324
351
  function inArray$4(searchElement, array, startIndex) {
325
352
  var i;
@@ -569,15 +596,19 @@ var forEachOwnProperties = forEachOwnProperties_1;
569
596
  * @returns {HTMLElement}
570
597
  * @memberof module:request
571
598
  * @example
572
- * var imagePing = require('tui-code-snippet/request/imagePing'); // node, commonjs
599
+ * // ES6
600
+ * import imagePing from 'tui-code-snippet/request/imagePing';
601
+ *
602
+ * // CommonJS
603
+ * const imagePing = require('tui-code-snippet/request/imagePing');
573
604
  *
574
605
  * imagePing('https://www.google-analytics.com/collect', {
575
- * v: 1,
576
- * t: 'event',
577
- * tid: 'trackingid',
578
- * cid: 'cid',
579
- * dp: 'dp',
580
- * dh: 'dh'
606
+ * v: 1,
607
+ * t: 'event',
608
+ * tid: 'trackingid',
609
+ * cid: 'cid',
610
+ * dp: 'dp',
611
+ * dh: 'dh'
581
612
  * });
582
613
  */
583
614
  function imagePing$1(url, trackingInfo) {
@@ -667,6 +698,11 @@ function sendHostname(appName, trackingId) {
667
698
  var sendHostname_1 = sendHostname;
668
699
 
669
700
  /Mac/.test(navigator.platform);
701
+ var reSpaceMoreThanOne = /[\u0020]+/g;
702
+ var reEscapeChars$1 = /[>(){}[\]+-.!#|]/g;
703
+ var reEscapeHTML = /<([a-zA-Z_][a-zA-Z0-9\-._]*)(\s|[^\\/>])*\/?>|<(\/)([a-zA-Z_][a-zA-Z0-9\-._]*)\s*\/?>|<!--[^-]+-->|<([a-zA-Z_][a-zA-Z0-9\-.:/]*)>/g;
704
+ var reEscapeBackSlash = /\\[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~\\]/g;
705
+ var reEscapePairedChars = /[*_~`]/g;
670
706
  function sendHostName() {
671
707
  sendHostname_1('editor', 'UA-129966929-1');
672
708
  }
@@ -674,6 +710,19 @@ function includes(arr, targetItem) {
674
710
  return arr.indexOf(targetItem) !== -1;
675
711
  }
676
712
  var availableLinkAttributes = ['rel', 'target', 'hreflang', 'type'];
713
+ var reMarkdownTextToEscapeMap = {
714
+ codeblock: /(^ {4}[^\n]+\n*)+/,
715
+ thematicBreak: /^ *((\* *){3,}|(- *){3,} *|(_ *){3,}) */,
716
+ atxHeading: /^(#{1,6}) +[\s\S]+/,
717
+ seTextheading: /^([^\n]+)\n *(=|-){2,} */,
718
+ blockquote: /^( *>[^\n]+.*)+/,
719
+ list: /^ *(\*+|-+|\d+\.) [\s\S]+/,
720
+ def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? */,
721
+ link: /!?\[.*\]\(.*\)/,
722
+ reflink: /!?\[.*\]\s*\[([^\]]*)\]/,
723
+ verticalBar: /\u007C/,
724
+ fencedCodeblock: /^((`|~){3,})/,
725
+ };
677
726
  function sanitizeLinkAttribute(attribute) {
678
727
  if (!attribute) {
679
728
  return null;
@@ -693,12 +742,30 @@ function repeat$1(text, count) {
693
742
  }
694
743
  return result;
695
744
  }
696
- function escape$1(text, startOfLine) {
697
- var result = text.replace(/[`*\\~[\]]/g, '\\$&');
698
- if (startOfLine) {
699
- return result.replace(/^[:#\-*+]/, '\\$&').replace(/^(\d+)\./, '$1\\.');
745
+ function isNeedEscapeText(text) {
746
+ var needEscape = false;
747
+ forEachOwnProperties_1(reMarkdownTextToEscapeMap, function (reMarkdownTextToEscape) {
748
+ if (reMarkdownTextToEscape.test(text)) {
749
+ needEscape = true;
750
+ }
751
+ return !needEscape;
752
+ });
753
+ return needEscape;
754
+ }
755
+ function escape$1(text) {
756
+ var replacer = function (matched) { return "\\" + matched; };
757
+ var escapedText = text.replace(reSpaceMoreThanOne, ' ');
758
+ if (reEscapeBackSlash.test(escapedText)) {
759
+ escapedText = escapedText.replace(reEscapeBackSlash, replacer);
700
760
  }
701
- return result;
761
+ escapedText = escapedText.replace(reEscapePairedChars, replacer);
762
+ if (reEscapeHTML.test(escapedText)) {
763
+ escapedText = escapedText.replace(reEscapeHTML, replacer);
764
+ }
765
+ if (isNeedEscapeText(escapedText)) {
766
+ escapedText = escapedText.replace(reEscapeChars$1, replacer);
767
+ }
768
+ return escapedText;
702
769
  }
703
770
  function quote(text) {
704
771
  var result;
@@ -1198,16 +1265,20 @@ var forEachArray = forEachArray_1;
1198
1265
  * @returns {Array} Array
1199
1266
  * @memberof module:collection
1200
1267
  * @example
1201
- * var toArray = require('tui-code-snippet/collection/toArray'); // node, commonjs
1268
+ * // ES6
1269
+ * import toArray from 'tui-code-snippet/collection/toArray';
1270
+ *
1271
+ * // CommonJS
1272
+ * const toArray = require('tui-code-snippet/collection/toArray');
1202
1273
  *
1203
- * var arrayLike = {
1204
- * 0: 'one',
1205
- * 1: 'two',
1206
- * 2: 'three',
1207
- * 3: 'four',
1208
- * length: 4
1274
+ * const arrayLike = {
1275
+ * 0: 'one',
1276
+ * 1: 'two',
1277
+ * 2: 'three',
1278
+ * 3: 'four',
1279
+ * length: 4
1209
1280
  * };
1210
- * var result = toArray(arrayLike);
1281
+ * const result = toArray(arrayLike);
1211
1282
  *
1212
1283
  * alert(result instanceof Array); // true
1213
1284
  * alert(result); // one,two,three,four
@@ -1386,7 +1457,7 @@ var EditorBase = /** @class */ (function () {
1386
1457
  var _a = getDefaultCommands(), undo = _a.undo, redo = _a.redo;
1387
1458
  var rules = this.createInputRules();
1388
1459
  var plugins = __spreadArray$1(__spreadArray$1([], this.keymaps), [
1389
- keymap(__assign$1({ 'Mod-z': undo(), 'Shift-Mod-z': redo() }, baseKeymap)),
1460
+ keymap(__assign$1({ 'Mod-z': undo(), 'Shift-Mod-z': redo(), 'Shift-Enter': baseKeymap.Enter }, baseKeymap)),
1390
1461
  history(),
1391
1462
  placeholder(this.placeholder),
1392
1463
  addWidget(this.eventEmitter),
@@ -1457,15 +1528,19 @@ var EditorBase = /** @class */ (function () {
1457
1528
  delete _this[prop];
1458
1529
  });
1459
1530
  };
1460
- EditorBase.prototype.moveCursorToStart = function () {
1531
+ EditorBase.prototype.moveCursorToStart = function (focus) {
1461
1532
  var tr = this.view.state.tr;
1462
1533
  this.view.dispatch(tr.setSelection(createTextSelection(tr, 1)).scrollIntoView());
1463
- this.focus();
1534
+ if (focus) {
1535
+ this.focus();
1536
+ }
1464
1537
  };
1465
- EditorBase.prototype.moveCursorToEnd = function () {
1538
+ EditorBase.prototype.moveCursorToEnd = function (focus) {
1466
1539
  var tr = this.view.state.tr;
1467
1540
  this.view.dispatch(tr.setSelection(createTextSelection(tr, tr.doc.content.size - 1)).scrollIntoView());
1468
- this.focus();
1541
+ if (focus) {
1542
+ this.focus();
1543
+ }
1469
1544
  };
1470
1545
  EditorBase.prototype.setScrollTop = function (top) {
1471
1546
  this.view.dom.scrollTop = top;
@@ -1656,6 +1731,8 @@ var OPEN_TAG = "<(" + TAG_NAME + ")(" + ATTRIBUTE$1 + ")*\\s*/?>";
1656
1731
  var CLOSE_TAG = "</(" + TAG_NAME + ")\\s*[>]";
1657
1732
  var HTML_TAG = "(?:" + OPEN_TAG + "|" + CLOSE_TAG + ")";
1658
1733
  var reHTMLTag = new RegExp("^" + HTML_TAG, 'i');
1734
+ var reBR = /<br\s*\/*>/i;
1735
+ var ALTERNATIVE_TAG_FOR_BR = '</p><p>';
1659
1736
 
1660
1737
  function isPositionInBox(style, offsetX, offsetY) {
1661
1738
  var left = parseInt(style.left, 10);
@@ -1788,51 +1865,36 @@ function getTotalOffset(el, root) {
1788
1865
  }
1789
1866
  return { offsetTop: offsetTop, offsetLeft: offsetLeft };
1790
1867
  }
1791
- function finalizeHtml(html, needHtmlText) {
1792
- var result;
1793
- if (needHtmlText) {
1794
- result = html.innerHTML;
1795
- }
1796
- else {
1797
- var frag = document.createDocumentFragment();
1798
- var childNodes = toArray_1(html.childNodes);
1799
- var length_1 = childNodes.length;
1800
- for (var i = 0; i < length_1; i += 1) {
1801
- frag.appendChild(childNodes[i]);
1802
- }
1803
- result = frag;
1804
- }
1805
- return result;
1806
- }
1807
1868
  function setAttributes(attributes, element) {
1808
1869
  Object.keys(attributes).forEach(function (attrName) {
1809
- if (attributes[attrName]) {
1810
- element.setAttribute(attrName, attributes[attrName]);
1870
+ if (isNil(attributes[attrName])) {
1871
+ element.removeAttribute(attrName);
1811
1872
  }
1812
1873
  else {
1813
- element.removeAttribute(attrName);
1874
+ element.setAttribute(attrName, attributes[attrName]);
1814
1875
  }
1815
1876
  });
1816
1877
  }
1817
1878
  function replaceBRWithEmptyBlock(html) {
1818
- var reBr = /<br\s*\/*>/i;
1879
+ // remove br in paragraph to compatible with markdown
1880
+ var replacedHTML = html.replace(/<p><br\s*\/*><\/p>/gi, '<p></p>');
1819
1881
  var reHTMLTag = new RegExp(HTML_TAG, 'ig');
1820
- var htmlTagMatched = html.match(reHTMLTag);
1882
+ var htmlTagMatched = replacedHTML.match(reHTMLTag);
1821
1883
  htmlTagMatched === null || htmlTagMatched === void 0 ? void 0 : htmlTagMatched.forEach(function (htmlTag, index) {
1822
- if (reBr.test(htmlTag)) {
1823
- var alternativeTag = '';
1884
+ if (reBR.test(htmlTag)) {
1885
+ var alternativeTag = ALTERNATIVE_TAG_FOR_BR;
1824
1886
  if (index) {
1825
1887
  var prevTag = htmlTagMatched[index - 1];
1826
1888
  var openTagMatched = prevTag.match(OPEN_TAG);
1827
- if (openTagMatched) {
1889
+ if (openTagMatched && !/br/i.test(openTagMatched[1])) {
1828
1890
  var tagName = openTagMatched[1];
1829
1891
  alternativeTag = "</" + tagName + "><" + tagName + ">";
1830
1892
  }
1831
1893
  }
1832
- html = html.replace(reBr, alternativeTag);
1894
+ replacedHTML = replacedHTML.replace(reBR, alternativeTag);
1833
1895
  }
1834
1896
  });
1835
- return html;
1897
+ return replacedHTML;
1836
1898
  }
1837
1899
 
1838
1900
  function resolveSelectionPos(selection) {
@@ -1842,12 +1904,8 @@ function resolveSelectionPos(selection) {
1842
1904
  }
1843
1905
  return [from, to];
1844
1906
  }
1845
- function getEditorToMdLine(from, to, doc) {
1846
- var fragment = doc.content;
1847
- var childCount = fragment.childCount;
1848
- var startLine = Math.min(fragment.findIndex(from).index + 1, childCount);
1849
- var endLine = from === to ? startLine : Math.min(fragment.findIndex(to).index + 1, childCount);
1850
- return [startLine, endLine];
1907
+ function getMdLine(resolvedPos) {
1908
+ return resolvedPos.index(0) + 1;
1851
1909
  }
1852
1910
  function getWidgetNodePos(node, chPos, direction) {
1853
1911
  if (direction === void 0) { direction = 1; }
@@ -1864,13 +1922,15 @@ function getEditorToMdPos(doc, from, to) {
1864
1922
  if (to === void 0) { to = from; }
1865
1923
  var collapsed = from === to;
1866
1924
  var startResolvedPos = doc.resolve(from);
1867
- var lineRange = getEditorToMdLine(from, to, doc);
1925
+ var startLine = getMdLine(startResolvedPos);
1926
+ var endLine = startLine;
1868
1927
  var startOffset = startResolvedPos.start(1);
1869
1928
  var endOffset = startOffset;
1870
1929
  if (!collapsed) {
1871
1930
  // prevent the end offset from pointing to the root document position
1872
1931
  var endResolvedPos = doc.resolve(to === doc.content.size ? to - 1 : to);
1873
- endOffset = endResolvedPos.start();
1932
+ endOffset = endResolvedPos.start(1);
1933
+ endLine = getMdLine(endResolvedPos);
1874
1934
  // To resolve the end offset excluding document tag size
1875
1935
  if (endResolvedPos.pos === doc.content.size) {
1876
1936
  to = doc.content.size - 2;
@@ -1879,8 +1939,8 @@ function getEditorToMdPos(doc, from, to) {
1879
1939
  var startCh = Math.max(from - startOffset + 1, 1);
1880
1940
  var endCh = Math.max(to - endOffset + 1, 1);
1881
1941
  return [
1882
- [lineRange[0], startCh + getWidgetNodePos(doc.child(lineRange[0] - 1), startCh, -1)],
1883
- [lineRange[1], endCh + getWidgetNodePos(doc.child(lineRange[1] - 1), endCh, -1)],
1942
+ [startLine, startCh + getWidgetNodePos(doc.child(startLine - 1), startCh, -1)],
1943
+ [endLine, endCh + getWidgetNodePos(doc.child(endLine - 1), endCh, -1)],
1884
1944
  ];
1885
1945
  }
1886
1946
  function getStartPosListPerLine(doc, endIndex) {
@@ -2062,7 +2122,7 @@ function customBlock$2(node, start, end) {
2062
2122
  var marks = [markInfo(setOffsetPos(start, 1), end, CUSTOM_BLOCK)];
2063
2123
  marks.push(markInfo(start, addOffsetPos(start, syntaxEnd), DELIM));
2064
2124
  if (info) {
2065
- marks.push(markInfo(addOffsetPos(start, 2), addOffsetPos(start, syntaxLength + info.length), META));
2125
+ marks.push(markInfo(addOffsetPos(start, syntaxEnd), addOffsetPos(start, syntaxLength + info.length), META));
2066
2126
  }
2067
2127
  marks.push(markInfo(setOffsetPos(end, 1), end, DELIM));
2068
2128
  var lineBackgroundMarkInfo = lineBackground(parent, start, end, 'custom-block');
@@ -3983,15 +4043,16 @@ function smartTask(_a) {
3983
4043
  props: {
3984
4044
  handleDOMEvents: {
3985
4045
  keyup: function (view, ev) {
3986
- var _a = view.state, doc = _a.doc, tr = _a.tr, selection = _a.selection;
4046
+ var _a;
4047
+ var _b = view.state, doc = _b.doc, tr = _b.tr, selection = _b.selection;
3987
4048
  if (selection.empty && reTaskMarkerKey.test(ev.key)) {
3988
- var _b = getRangeInfo(selection), startIndex = _b.startIndex, startFromOffset = _b.startFromOffset, from = _b.from;
4049
+ var _c = getRangeInfo(selection), startIndex = _c.startIndex, startFromOffset = _c.startFromOffset, from = _c.from;
3989
4050
  // should add `1` to line for the markdown parser
3990
4051
  // because markdown parser has `1`(not zero) as the start number
3991
4052
  var mdPos = [startIndex + 1, from - startFromOffset + 1];
3992
4053
  var mdNode = toastMark.findNodeAtPosition(mdPos);
3993
4054
  var paraNode = findClosestNode(mdNode, function (node) { var _a; return node.type === 'paragraph' && ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.type) === 'item'; });
3994
- if (paraNode && paraNode.firstChild) {
4055
+ if ((_a = paraNode === null || paraNode === void 0 ? void 0 : paraNode.firstChild) === null || _a === void 0 ? void 0 : _a.literal) {
3995
4056
  var firstChild = paraNode.firstChild;
3996
4057
  var matched = firstChild.literal.match(reTaskMarker);
3997
4058
  if (matched) {
@@ -4020,6 +4081,7 @@ function smartTask(_a) {
4020
4081
  }
4021
4082
 
4022
4083
  var EVENT_TYPE = 'cut';
4084
+ var reLineEnding$2 = /\r\n|\n|\r/;
4023
4085
  var MdEditor = /** @class */ (function (_super) {
4024
4086
  __extends$1(MdEditor, _super);
4025
4087
  function MdEditor(eventEmitter, options) {
@@ -4212,7 +4274,7 @@ var MdEditor = /** @class */ (function (_super) {
4212
4274
  MdEditor.prototype.replaceSelection = function (text, start, end) {
4213
4275
  var newTr;
4214
4276
  var _a = this.view.state, tr = _a.tr, schema = _a.schema, doc = _a.doc;
4215
- var lineTexts = text.split('\n');
4277
+ var lineTexts = text.split(reLineEnding$2);
4216
4278
  var nodes = lineTexts.map(function (lineText) {
4217
4279
  return createParagraph(schema, createNodesWithWidget(lineText, schema));
4218
4280
  });
@@ -4255,14 +4317,14 @@ var MdEditor = /** @class */ (function (_super) {
4255
4317
  };
4256
4318
  MdEditor.prototype.setMarkdown = function (markdown, cursorToEnd) {
4257
4319
  if (cursorToEnd === void 0) { cursorToEnd = true; }
4258
- var lineTexts = markdown.split('\n');
4320
+ var lineTexts = markdown.split(reLineEnding$2);
4259
4321
  var _a = this.view.state, tr = _a.tr, doc = _a.doc, schema = _a.schema;
4260
4322
  var nodes = lineTexts.map(function (lineText) {
4261
4323
  return createParagraph(schema, createNodesWithWidget(lineText, schema));
4262
4324
  });
4263
4325
  this.view.dispatch(tr.replaceWith(0, doc.content.size, nodes));
4264
4326
  if (cursorToEnd) {
4265
- this.moveCursorToEnd();
4327
+ this.moveCursorToEnd(true);
4266
4328
  }
4267
4329
  };
4268
4330
  MdEditor.prototype.addWidget = function (node, style, mdPos) {
@@ -4449,7 +4511,7 @@ var safeEvent = _safeEvent;
4449
4511
  * @param {object} [context] context - context for handler method.
4450
4512
  * @memberof module:domEvent
4451
4513
  * @example
4452
- * var div = document.querySelector('div');
4514
+ * const div = document.querySelector('div');
4453
4515
  *
4454
4516
  * // Bind one event to an element.
4455
4517
  * on(div, 'click', toggle);
@@ -4466,10 +4528,10 @@ var safeEvent = _safeEvent;
4466
4528
  * });
4467
4529
  *
4468
4530
  * // Set a context for handler method.
4469
- * var name = 'global';
4470
- * var repository = {name: 'CodeSnippet'};
4531
+ * const name = 'global';
4532
+ * const repository = {name: 'CodeSnippet'};
4471
4533
  * on(div, 'drag', function() {
4472
- * console.log(this.name);
4534
+ * console.log(this.name);
4473
4535
  * }, repository);
4474
4536
  * // Result when you drag a div: "CodeSnippet"
4475
4537
  */
@@ -4586,10 +4648,14 @@ var __assign = function() {
4586
4648
  return __assign.apply(this, arguments);
4587
4649
  };
4588
4650
 
4589
- function __spreadArray(to, from) {
4590
- for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
4591
- to[j] = from[i];
4592
- return to;
4651
+ function __spreadArray(to, from, pack) {
4652
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
4653
+ if (ar || !(i in from)) {
4654
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
4655
+ ar[i] = from[i];
4656
+ }
4657
+ }
4658
+ return to.concat(ar || Array.prototype.slice.call(from));
4593
4659
  }
4594
4660
 
4595
4661
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
@@ -9922,7 +9988,7 @@ function isCustomBlock(node) {
9922
9988
  function isCustomInline(node) {
9923
9989
  return node.type === 'customInline';
9924
9990
  }
9925
- function text(s, sourcepos) {
9991
+ function text$1(s, sourcepos) {
9926
9992
  var node = createNode$1('text', sourcepos);
9927
9993
  node.literal = s;
9928
9994
  return node;
@@ -10098,17 +10164,17 @@ function convertExtAutoLinks(walker, autolinkParser) {
10098
10164
  for (var _i = 0, linkInfos_1 = linkInfos; _i < linkInfos_1.length; _i++) {
10099
10165
  var _b = linkInfos_1[_i], range = _b.range, url = _b.url, linkText = _b.text;
10100
10166
  if (range[0] > lastIdx) {
10101
- newNodes.push(text(literal.substring(lastIdx, range[0]), sourcepos(lastIdx, range[0] - 1)));
10167
+ newNodes.push(text$1(literal.substring(lastIdx, range[0]), sourcepos(lastIdx, range[0] - 1)));
10102
10168
  }
10103
10169
  var linkNode = createNode$1('link', sourcepos.apply(void 0, range));
10104
- linkNode.appendChild(text(linkText, sourcepos.apply(void 0, range)));
10170
+ linkNode.appendChild(text$1(linkText, sourcepos.apply(void 0, range)));
10105
10171
  linkNode.destination = url;
10106
10172
  linkNode.extendedAutolink = true;
10107
10173
  newNodes.push(linkNode);
10108
10174
  lastIdx = range[1] + 1;
10109
10175
  }
10110
10176
  if (lastIdx < literal.length) {
10111
- newNodes.push(text(literal.substring(lastIdx), sourcepos(lastIdx, literal.length - 1)));
10177
+ newNodes.push(text$1(literal.substring(lastIdx), sourcepos(lastIdx, literal.length - 1)));
10112
10178
  }
10113
10179
  for (var _c = 0, newNodes_1 = newNodes; _c < newNodes_1.length; _c++) {
10114
10180
  var newNode = newNodes_1[_c];
@@ -10299,7 +10365,7 @@ var InlineParser = /** @class */ (function () {
10299
10365
  }
10300
10366
  // If we got here, we didn't match a closing backtick sequence.
10301
10367
  this.pos = afterOpenTicks;
10302
- block.appendChild(text(ticks, this.sourcepos(startpos, this.pos - 1)));
10368
+ block.appendChild(text$1(ticks, this.sourcepos(startpos, this.pos - 1)));
10303
10369
  return true;
10304
10370
  };
10305
10371
  // Parse a backslash-escaped special character, adding either the escaped
@@ -10318,11 +10384,11 @@ var InlineParser = /** @class */ (function () {
10318
10384
  this.nextLine();
10319
10385
  }
10320
10386
  else if (reEscapable.test(subj.charAt(this.pos))) {
10321
- block.appendChild(text(subj.charAt(this.pos), this.sourcepos(startpos, this.pos)));
10387
+ block.appendChild(text$1(subj.charAt(this.pos), this.sourcepos(startpos, this.pos)));
10322
10388
  this.pos += 1;
10323
10389
  }
10324
10390
  else {
10325
- block.appendChild(text('\\', this.sourcepos(startpos, startpos)));
10391
+ block.appendChild(text$1('\\', this.sourcepos(startpos, startpos)));
10326
10392
  }
10327
10393
  return true;
10328
10394
  };
@@ -10337,7 +10403,7 @@ var InlineParser = /** @class */ (function () {
10337
10403
  node = createNode$1('link', this.sourcepos(startpos, this.pos));
10338
10404
  node.destination = normalizeURI("mailto:" + dest);
10339
10405
  node.title = '';
10340
- node.appendChild(text(dest, this.sourcepos(startpos + 1, this.pos - 1)));
10406
+ node.appendChild(text$1(dest, this.sourcepos(startpos + 1, this.pos - 1)));
10341
10407
  block.appendChild(node);
10342
10408
  return true;
10343
10409
  }
@@ -10346,7 +10412,7 @@ var InlineParser = /** @class */ (function () {
10346
10412
  node = createNode$1('link', this.sourcepos(startpos, this.pos));
10347
10413
  node.destination = normalizeURI(dest);
10348
10414
  node.title = '';
10349
- node.appendChild(text(dest, this.sourcepos(startpos + 1, this.pos - 1)));
10415
+ node.appendChild(text$1(dest, this.sourcepos(startpos + 1, this.pos - 1)));
10350
10416
  block.appendChild(node);
10351
10417
  return true;
10352
10418
  }
@@ -10440,7 +10506,7 @@ var InlineParser = /** @class */ (function () {
10440
10506
  else {
10441
10507
  contents = this.subject.slice(startpos - 1, this.pos);
10442
10508
  }
10443
- var node = text(contents, this.sourcepos(startpos, this.pos));
10509
+ var node = text$1(contents, this.sourcepos(startpos, this.pos));
10444
10510
  block.appendChild(node);
10445
10511
  // Add entry to stack for this opener
10446
10512
  if ((res.canOpen || res.canClose) &&
@@ -10711,7 +10777,7 @@ var InlineParser = /** @class */ (function () {
10711
10777
  InlineParser.prototype.parseOpenBracket = function (block) {
10712
10778
  var startpos = this.pos;
10713
10779
  this.pos += 1;
10714
- var node = text('[', this.sourcepos(this.pos, this.pos));
10780
+ var node = text$1('[', this.sourcepos(this.pos, this.pos));
10715
10781
  block.appendChild(node);
10716
10782
  // Add entry to stack for this opener
10717
10783
  this.addBracket(node, startpos, false);
@@ -10724,13 +10790,13 @@ var InlineParser = /** @class */ (function () {
10724
10790
  this.pos += 1;
10725
10791
  if (this.peek() === C_OPEN_BRACKET$1) {
10726
10792
  this.pos += 1;
10727
- var node = text('![', this.sourcepos(this.pos - 1, this.pos));
10793
+ var node = text$1('![', this.sourcepos(this.pos - 1, this.pos));
10728
10794
  block.appendChild(node);
10729
10795
  // Add entry to stack for this opener
10730
10796
  this.addBracket(node, startpos + 1, true);
10731
10797
  }
10732
10798
  else {
10733
- var node = text('!', this.sourcepos(this.pos, this.pos));
10799
+ var node = text$1('!', this.sourcepos(this.pos, this.pos));
10734
10800
  block.appendChild(node);
10735
10801
  }
10736
10802
  return true;
@@ -10749,12 +10815,12 @@ var InlineParser = /** @class */ (function () {
10749
10815
  var opener = this.brackets;
10750
10816
  if (opener === null) {
10751
10817
  // no matched opener, just return a literal
10752
- block.appendChild(text(']', this.sourcepos(startpos, startpos)));
10818
+ block.appendChild(text$1(']', this.sourcepos(startpos, startpos)));
10753
10819
  return true;
10754
10820
  }
10755
10821
  if (!opener.active) {
10756
10822
  // no matched opener, just return a literal
10757
- block.appendChild(text(']', this.sourcepos(startpos, startpos)));
10823
+ block.appendChild(text$1(']', this.sourcepos(startpos, startpos)));
10758
10824
  // take opener off brackets stack
10759
10825
  this.removeBracket();
10760
10826
  return true;
@@ -10846,7 +10912,7 @@ var InlineParser = /** @class */ (function () {
10846
10912
  } // no match
10847
10913
  this.removeBracket(); // remove this opener from stack
10848
10914
  this.pos = startpos;
10849
- block.appendChild(text(']', this.sourcepos(startpos, startpos)));
10915
+ block.appendChild(text$1(']', this.sourcepos(startpos, startpos)));
10850
10916
  if (this.options.referenceDefinition) {
10851
10917
  this.refLinkCandidateMap[block.id] = { node: block, refLabel: refLabel };
10852
10918
  }
@@ -10876,7 +10942,7 @@ var InlineParser = /** @class */ (function () {
10876
10942
  var m;
10877
10943
  var startpos = this.pos + 1;
10878
10944
  if ((m = this.match(reEntityHere))) {
10879
- block.appendChild(text(lib.decodeHTML(m), this.sourcepos(startpos, this.pos)));
10945
+ block.appendChild(text$1(lib.decodeHTML(m), this.sourcepos(startpos, this.pos)));
10880
10946
  return true;
10881
10947
  }
10882
10948
  return false;
@@ -10911,10 +10977,10 @@ var InlineParser = /** @class */ (function () {
10911
10977
  }
10912
10978
  return repeat('\u2014', emCount) + repeat('\u2013', enCount);
10913
10979
  });
10914
- block.appendChild(text(lit, this.sourcepos(startpos, this.pos)));
10980
+ block.appendChild(text$1(lit, this.sourcepos(startpos, this.pos)));
10915
10981
  }
10916
10982
  else {
10917
- var node = text(m, this.sourcepos(startpos, this.pos));
10983
+ var node = text$1(m, this.sourcepos(startpos, this.pos));
10918
10984
  block.appendChild(node);
10919
10985
  }
10920
10986
  return true;
@@ -11137,7 +11203,7 @@ var InlineParser = /** @class */ (function () {
11137
11203
  }
11138
11204
  if (!res) {
11139
11205
  this.pos += 1;
11140
- block.appendChild(text(fromCodePoint$1(c), this.sourcepos(this.pos, this.pos + 1)));
11206
+ block.appendChild(text$1(fromCodePoint$1(c), this.sourcepos(this.pos, this.pos + 1)));
11141
11207
  }
11142
11208
  return true;
11143
11209
  };
@@ -13023,6 +13089,7 @@ function filterDisallowedTags(str) {
13023
13089
  return str;
13024
13090
  }
13025
13091
 
13092
+ var CUSTOM_SYNTAX_LENGTH = 4;
13026
13093
  var baseConvertors$1 = {
13027
13094
  heading: function (node, _a) {
13028
13095
  var entering = _a.entering;
@@ -13190,7 +13257,7 @@ var baseConvertors$1 = {
13190
13257
  return customConvertor(node, context);
13191
13258
  }
13192
13259
  catch (e) {
13193
- console.warn(e);
13260
+ console.warn("[@toast-ui/editor] - The error occurred when " + info + " block node was parsed in markdown renderer: " + e);
13194
13261
  }
13195
13262
  }
13196
13263
  return [
@@ -13213,15 +13280,30 @@ var baseConvertors$1 = {
13213
13280
  ];
13214
13281
  },
13215
13282
  customInline: function (node, context, convertors) {
13216
- var info = node.info.trim().toLowerCase();
13217
- var customConvertor = convertors[info];
13283
+ var _a = node, sourcepos = _a.sourcepos, info = _a.info;
13284
+ var nomalizedInfo = info.trim().toLowerCase();
13285
+ var customConvertor = convertors[nomalizedInfo];
13286
+ var entering = context.entering;
13218
13287
  if (customConvertor) {
13219
- return customConvertor(node, context);
13220
- }
13221
- return {
13222
- type: context.entering ? 'openTag' : 'closeTag',
13223
- tagName: 'span',
13224
- };
13288
+ try {
13289
+ return customConvertor(node, context);
13290
+ }
13291
+ catch (e) {
13292
+ console.warn("[@toast-ui/editor] - The error occurred when " + nomalizedInfo + " inline node was parsed in markdown renderer: " + e);
13293
+ }
13294
+ }
13295
+ var text = sourcepos[1][1] - sourcepos[0][1] + 1 === info.length + CUSTOM_SYNTAX_LENGTH
13296
+ ? ''
13297
+ : info + " ";
13298
+ return entering
13299
+ ? [
13300
+ { type: 'openTag', tagName: 'span' },
13301
+ { type: 'text', content: "$$" + text },
13302
+ ]
13303
+ : [
13304
+ { type: 'text', content: '$$' },
13305
+ { type: 'closeTag', tagName: 'span' },
13306
+ ];
13225
13307
  },
13226
13308
  };
13227
13309
 
@@ -13386,8 +13468,8 @@ var Renderer = /** @class */ (function () {
13386
13468
  ? nodeType.toLowerCase()
13387
13469
  : nodeType;
13388
13470
  if (orgConvertor) {
13389
- convertors[convertorType] = function (node, context) {
13390
- context.origin = function () { return orgConvertor(node, context); };
13471
+ convertors[convertorType] = function (node, context, convertors) {
13472
+ context.origin = function () { return orgConvertor(node, context, convertors); };
13391
13473
  return convertor(node, context);
13392
13474
  };
13393
13475
  }
@@ -13532,222 +13614,1537 @@ var Renderer = /** @class */ (function () {
13532
13614
  return Renderer;
13533
13615
  }());
13534
13616
 
13535
- var reXSSHtmlAttr = new RegExp('^(abbr|align|alt|axis|bgcolor|border|cellpadding|cellspacing|class|clear|' +
13536
- 'color|cols|compact|coords|dir|face|headers|height|hreflang|hspace|' +
13537
- 'ismap|lang|language|nohref|nowrap|rel|rev|rows|rules|' +
13538
- 'scope|scrolling|shape|size|span|start|summary|tabindex|target|title|type|' +
13539
- 'valign|value|vspace|width|checked|mathvariant|encoding|id|name|' +
13540
- 'background|cite|href|longdesc|src|usemap|xlink:href|data-+|checked|style)', 'g');
13541
- var reXSSSvgAttr = new RegExp('^(accent-height|accumulate|additive|alphabetic|arabic-form|ascent|' +
13542
- 'baseProfile|bbox|begin|by|calcMode|cap-height|class|color|color-rendering|content|' +
13543
- 'cx|cy|d|dx|dy|descent|display|dur|end|fill|fill-rule|font-family|font-size|font-stretch|' +
13544
- 'font-style|font-variant|font-weight|from|fx|fy|g1|g2|glyph-name|gradientUnits|hanging|' +
13545
- 'height|horiz-adv-x|horiz-origin-x|ideographic|k|keyPoints|keySplines|keyTimes|lang|' +
13546
- 'marker-end|marker-mid|marker-start|markerHeight|markerUnits|markerWidth|mathematical|' +
13547
- 'max|min|offset|opacity|orient|origin|overline-position|overline-thickness|panose-1|' +
13548
- 'path|pathLength|points|preserveAspectRatio|r|refX|refY|repeatCount|repeatDur|' +
13549
- 'requiredExtensions|requiredFeatures|restart|rotate|rx|ry|slope|stemh|stemv|stop-color|' +
13550
- 'stop-opacity|strikethrough-position|strikethrough-thickness|stroke|stroke-dasharray|' +
13551
- 'stroke-dashoffset|stroke-linecap|stroke-linejoin|stroke-miterlimit|stroke-opacity|' +
13552
- 'stroke-width|systemLanguage|target|text-anchor|to|transform|type|u1|u2|underline-position|' +
13553
- 'underline-thickness|unicode|unicode-range|units-per-em|values|version|viewBox|visibility|' +
13554
- 'width|widths|x|x-height|x1|x2|xlink:actuate|xlink:arcrole|xlink:role|xlink:show|xlink:title|' +
13555
- 'xlink:type|xml:base|xml:lang|xml:space|xmlns|xmlns:xlink|y|y1|y2|zoomAndPan)', 'g');
13556
- var reXSSAttr = /href|src|background/i;
13557
- var reXSSAttrValue = /((java|vb|live)script|x):/i;
13558
- var reOnEvent = /^on\S+/i;
13559
- var reComment = /<!--[\s\S]*?-->/g;
13560
- var DEFAULT_TAG_BLACK_LIST = [
13561
- 'script',
13562
- 'iframe',
13563
- 'textarea',
13564
- 'form',
13565
- 'button',
13566
- 'select',
13567
- 'input',
13568
- 'meta',
13569
- 'style',
13570
- 'link',
13571
- 'title',
13572
- 'embed',
13573
- 'object',
13574
- 'details',
13575
- 'summary',
13576
- ];
13577
- var CAN_BE_TAG_WHITE_LIST = ['iframe', 'embed', 'details', 'summary'];
13578
- var tagBlacklist = __spreadArray$1([], DEFAULT_TAG_BLACK_LIST);
13579
- function registerTagWhitelistIfPossible(tagName) {
13580
- if (includes(CAN_BE_TAG_WHITE_LIST, tagName)) {
13581
- tagBlacklist.splice(tagBlacklist.indexOf(tagName), 1);
13582
- }
13583
- }
13584
- function sanitizeHTML(html) {
13585
- var root = document.createElement('div');
13586
- if (isString_1(html)) {
13587
- html = html.replace(reComment, '');
13588
- root.innerHTML = html;
13589
- }
13590
- removeUnnecessaryTags(root);
13591
- leaveOnlyWhitelistAttribute(root);
13592
- return finalizeHtml(root, true);
13593
- }
13594
- function removeUnnecessaryTags(html) {
13595
- var removedTags = findNodes(html, tagBlacklist.join(','));
13596
- removedTags.forEach(function (node) {
13597
- removeNode$1(node);
13598
- });
13617
+ /*! @license DOMPurify 2.3.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.3/LICENSE */
13618
+
13619
+ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
13620
+
13621
+ var hasOwnProperty = Object.hasOwnProperty,
13622
+ setPrototypeOf = Object.setPrototypeOf,
13623
+ isFrozen = Object.isFrozen,
13624
+ getPrototypeOf = Object.getPrototypeOf,
13625
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
13626
+ var freeze = Object.freeze,
13627
+ seal = Object.seal,
13628
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
13629
+
13630
+ var _ref = typeof Reflect !== 'undefined' && Reflect,
13631
+ apply = _ref.apply,
13632
+ construct = _ref.construct;
13633
+
13634
+ if (!apply) {
13635
+ apply = function apply(fun, thisValue, args) {
13636
+ return fun.apply(thisValue, args);
13637
+ };
13599
13638
  }
13600
- function isXSSAttribute(attrName, attrValue) {
13601
- return attrName.match(reXSSAttr) && attrValue.match(reXSSAttrValue);
13639
+
13640
+ if (!freeze) {
13641
+ freeze = function freeze(x) {
13642
+ return x;
13643
+ };
13602
13644
  }
13603
- function removeBlacklistAttributes(node, blacklistAttrs) {
13604
- blacklistAttrs.forEach(function (_a) {
13605
- var name = _a.name;
13606
- if (reOnEvent.test(name)) {
13607
- node[name] = null;
13608
- }
13609
- if (node.getAttribute(name)) {
13610
- node.removeAttribute(name);
13611
- }
13612
- });
13645
+
13646
+ if (!seal) {
13647
+ seal = function seal(x) {
13648
+ return x;
13649
+ };
13613
13650
  }
13614
- function leaveOnlyWhitelistAttribute(html) {
13615
- findNodes(html, '*').forEach(function (node) {
13616
- var attributes = node.attributes;
13617
- var blacklist = toArray_1(attributes).filter(function (attr) {
13618
- var name = attr.name, value = attr.value;
13619
- var htmlAttr = name.match(reXSSHtmlAttr);
13620
- var svgAttr = name.match(reXSSSvgAttr);
13621
- var xssAttr = htmlAttr && isXSSAttribute(name, value);
13622
- return (!htmlAttr && !svgAttr) || xssAttr;
13623
- });
13624
- removeBlacklistAttributes(node, blacklist);
13625
- });
13651
+
13652
+ if (!construct) {
13653
+ construct = function construct(Func, args) {
13654
+ return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
13655
+ };
13626
13656
  }
13627
- function sanitizeXSSAttributeValue(attrValue) {
13628
- attrValue = attrValue.replace(reComment, '');
13629
- return reXSSAttrValue.test(attrValue) ? '' : attrValue;
13657
+
13658
+ var arrayForEach = unapply(Array.prototype.forEach);
13659
+ var arrayPop = unapply(Array.prototype.pop);
13660
+ var arrayPush = unapply(Array.prototype.push);
13661
+
13662
+ var stringToLowerCase = unapply(String.prototype.toLowerCase);
13663
+ var stringMatch = unapply(String.prototype.match);
13664
+ var stringReplace = unapply(String.prototype.replace);
13665
+ var stringIndexOf = unapply(String.prototype.indexOf);
13666
+ var stringTrim = unapply(String.prototype.trim);
13667
+
13668
+ var regExpTest = unapply(RegExp.prototype.test);
13669
+
13670
+ var typeErrorCreate = unconstruct(TypeError);
13671
+
13672
+ function unapply(func) {
13673
+ return function (thisArg) {
13674
+ for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
13675
+ args[_key - 1] = arguments[_key];
13676
+ }
13677
+
13678
+ return apply(func, thisArg, args);
13679
+ };
13630
13680
  }
13631
13681
 
13632
- function getChildrenHTML(node, typeName) {
13633
- return node
13634
- .literal.replace(new RegExp("(<\\s*" + typeName + "[^>]+?>)|(</" + typeName + "\\s*[>])", 'ig'), '')
13635
- .trim();
13682
+ function unconstruct(func) {
13683
+ return function () {
13684
+ for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
13685
+ args[_key2] = arguments[_key2];
13686
+ }
13687
+
13688
+ return construct(func, args);
13689
+ };
13636
13690
  }
13637
- function getHTMLAttrsByHTMLString(html) {
13638
- html = html.match(reHTMLTag)[0];
13639
- var attrs = html.match(new RegExp(ATTRIBUTE$1, 'g'));
13640
- return attrs
13641
- ? attrs.reduce(function (acc, attr) {
13642
- var _a = attr.trim().split('='), name = _a[0], values = _a.slice(1);
13643
- if (values.length) {
13644
- acc[name] = values.join('=').replace(/'|"/g, '').trim();
13645
- }
13646
- return acc;
13647
- }, {})
13648
- : {};
13691
+
13692
+ /* Add properties to a lookup table */
13693
+ function addToSet(set, array) {
13694
+ if (setPrototypeOf) {
13695
+ // Make 'in' and truthy checks like Boolean(set.constructor)
13696
+ // independent of any properties defined on Object.prototype.
13697
+ // Prevent prototype setters from intercepting set as a this value.
13698
+ setPrototypeOf(set, null);
13699
+ }
13700
+
13701
+ var l = array.length;
13702
+ while (l--) {
13703
+ var element = array[l];
13704
+ if (typeof element === 'string') {
13705
+ var lcElement = stringToLowerCase(element);
13706
+ if (lcElement !== element) {
13707
+ // Config presets (e.g. tags.js, attrs.js) are immutable.
13708
+ if (!isFrozen(array)) {
13709
+ array[l] = lcElement;
13710
+ }
13711
+
13712
+ element = lcElement;
13713
+ }
13714
+ }
13715
+
13716
+ set[element] = true;
13717
+ }
13718
+
13719
+ return set;
13649
13720
  }
13650
- function getHTMLAttrs(dom) {
13651
- return toArray_1(dom.attributes).reduce(function (acc, attr) {
13652
- acc[attr.nodeName] = attr.nodeValue;
13653
- return acc;
13654
- }, {});
13721
+
13722
+ /* Shallow clone an object */
13723
+ function clone(object) {
13724
+ var newObject = create(null);
13725
+
13726
+ var property = void 0;
13727
+ for (property in object) {
13728
+ if (apply(hasOwnProperty, object, [property])) {
13729
+ newObject[property] = object[property];
13730
+ }
13731
+ }
13732
+
13733
+ return newObject;
13655
13734
  }
13656
- function sanitizeDOM(node, typeName, sanitizer, wwToDOMAdaptor) {
13657
- var dom = wwToDOMAdaptor.getToDOMNode(typeName)(node);
13658
- var html = sanitizer(dom.outerHTML);
13659
- var container = document.createElement('div');
13660
- container.innerHTML = html;
13661
- dom = container.firstChild;
13662
- var htmlAttrs = getHTMLAttrs(dom);
13663
- return { dom: dom, htmlAttrs: htmlAttrs };
13735
+
13736
+ /* IE10 doesn't support __lookupGetter__ so lets'
13737
+ * simulate it. It also automatically checks
13738
+ * if the prop is function or getter and behaves
13739
+ * accordingly. */
13740
+ function lookupGetter(object, prop) {
13741
+ while (object !== null) {
13742
+ var desc = getOwnPropertyDescriptor(object, prop);
13743
+ if (desc) {
13744
+ if (desc.get) {
13745
+ return unapply(desc.get);
13746
+ }
13747
+
13748
+ if (typeof desc.value === 'function') {
13749
+ return unapply(desc.value);
13750
+ }
13751
+ }
13752
+
13753
+ object = getPrototypeOf(object);
13754
+ }
13755
+
13756
+ function fallbackValue(element) {
13757
+ console.warn('fallback value for', element);
13758
+ return null;
13759
+ }
13760
+
13761
+ return fallbackValue;
13664
13762
  }
13665
- var schemaFactory = {
13666
- htmlBlock: function (typeName, sanitizeHTML, wwToDOMAdaptor) {
13667
- return {
13668
- atom: true,
13669
- content: 'block+',
13670
- group: 'block',
13671
- attrs: {
13672
- htmlAttrs: { default: {} },
13673
- childrenHTML: { default: '' },
13674
- htmlBlock: { default: true },
13675
- },
13676
- parseDOM: [
13677
- {
13678
- tag: typeName,
13679
- getAttrs: function (dom) {
13680
- return {
13681
- htmlAttrs: getHTMLAttrs(dom),
13682
- childrenHTML: dom.innerHTML,
13683
- };
13684
- },
13685
- },
13686
- ],
13687
- toDOM: function (node) {
13688
- var _a = sanitizeDOM(node, typeName, sanitizeHTML, wwToDOMAdaptor), dom = _a.dom, htmlAttrs = _a.htmlAttrs;
13689
- htmlAttrs.class = htmlAttrs.class ? htmlAttrs.class + " html-block" : 'html-block';
13690
- return __spreadArray$1([typeName, htmlAttrs], toArray_1(dom.childNodes));
13691
- },
13692
- };
13693
- },
13694
- htmlInline: function (typeName, sanitizeHTML, wwToDOMAdaptor) {
13695
- return {
13696
- attrs: {
13697
- htmlAttrs: { default: {} },
13698
- htmlInline: { default: true },
13699
- },
13700
- parseDOM: [
13701
- {
13702
- tag: typeName,
13703
- getAttrs: function (dom) {
13704
- return {
13705
- htmlAttrs: getHTMLAttrs(dom),
13706
- };
13707
- },
13708
- },
13709
- ],
13710
- toDOM: function (node) {
13711
- var htmlAttrs = sanitizeDOM(node, typeName, sanitizeHTML, wwToDOMAdaptor).htmlAttrs;
13712
- return [typeName, htmlAttrs, 0];
13713
- },
13714
- };
13715
- },
13763
+
13764
+ var html$2 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
13765
+
13766
+ // SVG
13767
+ var svg = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
13768
+
13769
+ var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
13770
+
13771
+ // List of SVG elements that are disallowed by default.
13772
+ // We still need to know them so that we can do namespace
13773
+ // checks properly in case one wants to add them to
13774
+ // allow-list.
13775
+ var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'feimage', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
13776
+
13777
+ var mathMl = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']);
13778
+
13779
+ // Similarly to SVG, we want to know all MathML elements,
13780
+ // even those that we disallow by default.
13781
+ var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
13782
+
13783
+ var text = freeze(['#text']);
13784
+
13785
+ var html$1$1 = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
13786
+
13787
+ var svg$1 = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
13788
+
13789
+ var mathMl$1 = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
13790
+
13791
+ var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
13792
+
13793
+ // eslint-disable-next-line unicorn/better-regex
13794
+ var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
13795
+ var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm);
13796
+ var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
13797
+ var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
13798
+ var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
13799
+ );
13800
+ var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
13801
+ var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
13802
+ );
13803
+
13804
+ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
13805
+
13806
+ function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
13807
+
13808
+ var getGlobal = function getGlobal() {
13809
+ return typeof window === 'undefined' ? null : window;
13716
13810
  };
13717
- function createHTMLSchemaMap(convertorMap, sanitizeHTML, wwToDOMAdaptor) {
13718
- var htmlSchemaMap = { nodes: {}, marks: {} };
13719
- ['htmlBlock', 'htmlInline'].forEach(function (htmlType) {
13720
- if (convertorMap[htmlType]) {
13721
- Object.keys(convertorMap[htmlType]).forEach(function (type) {
13722
- var targetType = htmlType === 'htmlBlock' ? 'nodes' : 'marks';
13723
- // register tag white list for preventing to remove the html in sanitizer
13724
- registerTagWhitelistIfPossible(type);
13725
- htmlSchemaMap[targetType][type] = schemaFactory[htmlType](type, sanitizeHTML, wwToDOMAdaptor);
13726
- });
13727
- }
13811
+
13812
+ /**
13813
+ * Creates a no-op policy for internal use only.
13814
+ * Don't export this function outside this module!
13815
+ * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
13816
+ * @param {Document} document The document object (to determine policy name suffix)
13817
+ * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
13818
+ * are not supported).
13819
+ */
13820
+ var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
13821
+ if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
13822
+ return null;
13823
+ }
13824
+
13825
+ // Allow the callers to control the unique policy name
13826
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
13827
+ // Policy creation with duplicate names throws in Trusted Types.
13828
+ var suffix = null;
13829
+ var ATTR_NAME = 'data-tt-policy-suffix';
13830
+ if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
13831
+ suffix = document.currentScript.getAttribute(ATTR_NAME);
13832
+ }
13833
+
13834
+ var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
13835
+
13836
+ try {
13837
+ return trustedTypes.createPolicy(policyName, {
13838
+ createHTML: function createHTML(html$$1) {
13839
+ return html$$1;
13840
+ }
13728
13841
  });
13729
- return htmlSchemaMap;
13730
- }
13842
+ } catch (_) {
13843
+ // Policy creation failed (most likely another DOMPurify script has
13844
+ // already run). Skip creating the policy, as this will only cause errors
13845
+ // if TT are enforced.
13846
+ console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
13847
+ return null;
13848
+ }
13849
+ };
13731
13850
 
13732
- var reCloseTag = /^\s*<\s*\//;
13733
- var baseConvertors = {
13734
- paragraph: function (_, _a) {
13735
- var entering = _a.entering, origin = _a.origin, options = _a.options;
13736
- if (options.nodeId) {
13737
- return {
13738
- type: entering ? 'openTag' : 'closeTag',
13739
- outerNewLine: true,
13740
- tagName: 'p',
13741
- };
13742
- }
13743
- return origin();
13744
- },
13745
- softbreak: function (node) {
13746
- var isPrevNodeHTML = node.prev && node.prev.type === 'htmlInline';
13747
- var isPrevBR = isPrevNodeHTML && /<br ?\/?>/.test(node.prev.literal);
13748
- var content = isPrevBR ? '\n' : '<br>\n';
13749
- return { type: 'html', content: content };
13750
- },
13851
+ function createDOMPurify() {
13852
+ var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
13853
+
13854
+ var DOMPurify = function DOMPurify(root) {
13855
+ return createDOMPurify(root);
13856
+ };
13857
+
13858
+ /**
13859
+ * Version label, exposed for easier checks
13860
+ * if DOMPurify is up to date or not
13861
+ */
13862
+ DOMPurify.version = '2.3.3';
13863
+
13864
+ /**
13865
+ * Array of elements that DOMPurify removed during sanitation.
13866
+ * Empty if nothing was removed.
13867
+ */
13868
+ DOMPurify.removed = [];
13869
+
13870
+ if (!window || !window.document || window.document.nodeType !== 9) {
13871
+ // Not running in a browser, provide a factory function
13872
+ // so that you can pass your own Window
13873
+ DOMPurify.isSupported = false;
13874
+
13875
+ return DOMPurify;
13876
+ }
13877
+
13878
+ var originalDocument = window.document;
13879
+
13880
+ var document = window.document;
13881
+ var DocumentFragment = window.DocumentFragment,
13882
+ HTMLTemplateElement = window.HTMLTemplateElement,
13883
+ Node = window.Node,
13884
+ Element = window.Element,
13885
+ NodeFilter = window.NodeFilter,
13886
+ _window$NamedNodeMap = window.NamedNodeMap,
13887
+ NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
13888
+ Text = window.Text,
13889
+ Comment = window.Comment,
13890
+ DOMParser = window.DOMParser,
13891
+ trustedTypes = window.trustedTypes;
13892
+
13893
+
13894
+ var ElementPrototype = Element.prototype;
13895
+
13896
+ var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
13897
+ var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
13898
+ var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
13899
+ var getParentNode = lookupGetter(ElementPrototype, 'parentNode');
13900
+
13901
+ // As per issue #47, the web-components registry is inherited by a
13902
+ // new document created via createHTMLDocument. As per the spec
13903
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
13904
+ // a new empty registry is used when creating a template contents owner
13905
+ // document, so we use that as our parent document to ensure nothing
13906
+ // is inherited.
13907
+ if (typeof HTMLTemplateElement === 'function') {
13908
+ var template = document.createElement('template');
13909
+ if (template.content && template.content.ownerDocument) {
13910
+ document = template.content.ownerDocument;
13911
+ }
13912
+ }
13913
+
13914
+ var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
13915
+ var emptyHTML = trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML('') : '';
13916
+
13917
+ var _document = document,
13918
+ implementation = _document.implementation,
13919
+ createNodeIterator = _document.createNodeIterator,
13920
+ createDocumentFragment = _document.createDocumentFragment,
13921
+ getElementsByTagName = _document.getElementsByTagName;
13922
+ var importNode = originalDocument.importNode;
13923
+
13924
+
13925
+ var documentMode = {};
13926
+ try {
13927
+ documentMode = clone(document).documentMode ? document.documentMode : {};
13928
+ } catch (_) {}
13929
+
13930
+ var hooks = {};
13931
+
13932
+ /**
13933
+ * Expose whether this browser supports running the full DOMPurify.
13934
+ */
13935
+ DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
13936
+
13937
+ var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR,
13938
+ ERB_EXPR$$1 = ERB_EXPR,
13939
+ DATA_ATTR$$1 = DATA_ATTR,
13940
+ ARIA_ATTR$$1 = ARIA_ATTR,
13941
+ IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA,
13942
+ ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;
13943
+ var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;
13944
+
13945
+ /**
13946
+ * We consider the elements and attributes below to be safe. Ideally
13947
+ * don't add any new ones but feel free to remove unwanted ones.
13948
+ */
13949
+
13950
+ /* allowed element names */
13951
+
13952
+ var ALLOWED_TAGS = null;
13953
+ var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html$2), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text)));
13954
+
13955
+ /* Allowed attribute names */
13956
+ var ALLOWED_ATTR = null;
13957
+ var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml)));
13958
+
13959
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
13960
+ var FORBID_TAGS = null;
13961
+
13962
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
13963
+ var FORBID_ATTR = null;
13964
+
13965
+ /* Decide if ARIA attributes are okay */
13966
+ var ALLOW_ARIA_ATTR = true;
13967
+
13968
+ /* Decide if custom data attributes are okay */
13969
+ var ALLOW_DATA_ATTR = true;
13970
+
13971
+ /* Decide if unknown protocols are okay */
13972
+ var ALLOW_UNKNOWN_PROTOCOLS = false;
13973
+
13974
+ /* Output should be safe for common template engines.
13975
+ * This means, DOMPurify removes data attributes, mustaches and ERB
13976
+ */
13977
+ var SAFE_FOR_TEMPLATES = false;
13978
+
13979
+ /* Decide if document with <html>... should be returned */
13980
+ var WHOLE_DOCUMENT = false;
13981
+
13982
+ /* Track whether config is already set on this instance of DOMPurify. */
13983
+ var SET_CONFIG = false;
13984
+
13985
+ /* Decide if all elements (e.g. style, script) must be children of
13986
+ * document.body. By default, browsers might move them to document.head */
13987
+ var FORCE_BODY = false;
13988
+
13989
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
13990
+ * string (or a TrustedHTML object if Trusted Types are supported).
13991
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
13992
+ */
13993
+ var RETURN_DOM = false;
13994
+
13995
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
13996
+ * string (or a TrustedHTML object if Trusted Types are supported) */
13997
+ var RETURN_DOM_FRAGMENT = false;
13998
+
13999
+ /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM
14000
+ * `Node` is imported into the current `Document`. If this flag is not enabled the
14001
+ * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by
14002
+ * DOMPurify.
14003
+ *
14004
+ * This defaults to `true` starting DOMPurify 2.2.0. Note that setting it to `false`
14005
+ * might cause XSS from attacks hidden in closed shadowroots in case the browser
14006
+ * supports Declarative Shadow: DOM https://web.dev/declarative-shadow-dom/
14007
+ */
14008
+ var RETURN_DOM_IMPORT = true;
14009
+
14010
+ /* Try to return a Trusted Type object instead of a string, return a string in
14011
+ * case Trusted Types are not supported */
14012
+ var RETURN_TRUSTED_TYPE = false;
14013
+
14014
+ /* Output should be free from DOM clobbering attacks? */
14015
+ var SANITIZE_DOM = true;
14016
+
14017
+ /* Keep element content when removing element? */
14018
+ var KEEP_CONTENT = true;
14019
+
14020
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
14021
+ * of importing it into a new Document and returning a sanitized copy */
14022
+ var IN_PLACE = false;
14023
+
14024
+ /* Allow usage of profiles like html, svg and mathMl */
14025
+ var USE_PROFILES = {};
14026
+
14027
+ /* Tags to ignore content of when KEEP_CONTENT is true */
14028
+ var FORBID_CONTENTS = null;
14029
+ var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
14030
+
14031
+ /* Tags that are safe for data: URIs */
14032
+ var DATA_URI_TAGS = null;
14033
+ var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
14034
+
14035
+ /* Attributes safe for values like "javascript:" */
14036
+ var URI_SAFE_ATTRIBUTES = null;
14037
+ var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
14038
+
14039
+ var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
14040
+ var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
14041
+ var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
14042
+ /* Document namespace */
14043
+ var NAMESPACE = HTML_NAMESPACE;
14044
+ var IS_EMPTY_INPUT = false;
14045
+
14046
+ /* Parsing of strict XHTML documents */
14047
+ var PARSER_MEDIA_TYPE = void 0;
14048
+ var SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
14049
+ var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
14050
+ var transformCaseFunc = void 0;
14051
+
14052
+ /* Keep a reference to config to pass to hooks */
14053
+ var CONFIG = null;
14054
+
14055
+ /* Ideally, do not touch anything below this line */
14056
+ /* ______________________________________________ */
14057
+
14058
+ var formElement = document.createElement('form');
14059
+
14060
+ /**
14061
+ * _parseConfig
14062
+ *
14063
+ * @param {Object} cfg optional config literal
14064
+ */
14065
+ // eslint-disable-next-line complexity
14066
+ var _parseConfig = function _parseConfig(cfg) {
14067
+ if (CONFIG && CONFIG === cfg) {
14068
+ return;
14069
+ }
14070
+
14071
+ /* Shield configuration object from tampering */
14072
+ if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') {
14073
+ cfg = {};
14074
+ }
14075
+
14076
+ /* Shield configuration object from prototype pollution */
14077
+ cfg = clone(cfg);
14078
+
14079
+ /* Set configuration parameters */
14080
+ ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
14081
+ ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
14082
+ URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
14083
+ DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
14084
+ FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
14085
+ FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
14086
+ FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
14087
+ USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
14088
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
14089
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
14090
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
14091
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
14092
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
14093
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
14094
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
14095
+ RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT !== false; // Default true
14096
+ RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
14097
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
14098
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
14099
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
14100
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
14101
+ IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;
14102
+ NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
14103
+
14104
+ PARSER_MEDIA_TYPE =
14105
+ // eslint-disable-next-line unicorn/prefer-includes
14106
+ SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE;
14107
+
14108
+ // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
14109
+ transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? function (x) {
14110
+ return x;
14111
+ } : stringToLowerCase;
14112
+
14113
+ if (SAFE_FOR_TEMPLATES) {
14114
+ ALLOW_DATA_ATTR = false;
14115
+ }
14116
+
14117
+ if (RETURN_DOM_FRAGMENT) {
14118
+ RETURN_DOM = true;
14119
+ }
14120
+
14121
+ /* Parse profile info */
14122
+ if (USE_PROFILES) {
14123
+ ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text)));
14124
+ ALLOWED_ATTR = [];
14125
+ if (USE_PROFILES.html === true) {
14126
+ addToSet(ALLOWED_TAGS, html$2);
14127
+ addToSet(ALLOWED_ATTR, html$1$1);
14128
+ }
14129
+
14130
+ if (USE_PROFILES.svg === true) {
14131
+ addToSet(ALLOWED_TAGS, svg);
14132
+ addToSet(ALLOWED_ATTR, svg$1);
14133
+ addToSet(ALLOWED_ATTR, xml);
14134
+ }
14135
+
14136
+ if (USE_PROFILES.svgFilters === true) {
14137
+ addToSet(ALLOWED_TAGS, svgFilters);
14138
+ addToSet(ALLOWED_ATTR, svg$1);
14139
+ addToSet(ALLOWED_ATTR, xml);
14140
+ }
14141
+
14142
+ if (USE_PROFILES.mathMl === true) {
14143
+ addToSet(ALLOWED_TAGS, mathMl);
14144
+ addToSet(ALLOWED_ATTR, mathMl$1);
14145
+ addToSet(ALLOWED_ATTR, xml);
14146
+ }
14147
+ }
14148
+
14149
+ /* Merge configuration parameters */
14150
+ if (cfg.ADD_TAGS) {
14151
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
14152
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
14153
+ }
14154
+
14155
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
14156
+ }
14157
+
14158
+ if (cfg.ADD_ATTR) {
14159
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
14160
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
14161
+ }
14162
+
14163
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
14164
+ }
14165
+
14166
+ if (cfg.ADD_URI_SAFE_ATTR) {
14167
+ addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
14168
+ }
14169
+
14170
+ if (cfg.FORBID_CONTENTS) {
14171
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
14172
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
14173
+ }
14174
+
14175
+ addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
14176
+ }
14177
+
14178
+ /* Add #text in case KEEP_CONTENT is set to true */
14179
+ if (KEEP_CONTENT) {
14180
+ ALLOWED_TAGS['#text'] = true;
14181
+ }
14182
+
14183
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
14184
+ if (WHOLE_DOCUMENT) {
14185
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
14186
+ }
14187
+
14188
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
14189
+ if (ALLOWED_TAGS.table) {
14190
+ addToSet(ALLOWED_TAGS, ['tbody']);
14191
+ delete FORBID_TAGS.tbody;
14192
+ }
14193
+
14194
+ // Prevent further manipulation of configuration.
14195
+ // Not available in IE8, Safari 5, etc.
14196
+ if (freeze) {
14197
+ freeze(cfg);
14198
+ }
14199
+
14200
+ CONFIG = cfg;
14201
+ };
14202
+
14203
+ var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
14204
+
14205
+ var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']);
14206
+
14207
+ /* Keep track of all possible SVG and MathML tags
14208
+ * so that we can perform the namespace checks
14209
+ * correctly. */
14210
+ var ALL_SVG_TAGS = addToSet({}, svg);
14211
+ addToSet(ALL_SVG_TAGS, svgFilters);
14212
+ addToSet(ALL_SVG_TAGS, svgDisallowed);
14213
+
14214
+ var ALL_MATHML_TAGS = addToSet({}, mathMl);
14215
+ addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
14216
+
14217
+ /**
14218
+ *
14219
+ *
14220
+ * @param {Element} element a DOM element whose namespace is being checked
14221
+ * @returns {boolean} Return false if the element has a
14222
+ * namespace that a spec-compliant parser would never
14223
+ * return. Return true otherwise.
14224
+ */
14225
+ var _checkValidNamespace = function _checkValidNamespace(element) {
14226
+ var parent = getParentNode(element);
14227
+
14228
+ // In JSDOM, if we're inside shadow DOM, then parentNode
14229
+ // can be null. We just simulate parent in this case.
14230
+ if (!parent || !parent.tagName) {
14231
+ parent = {
14232
+ namespaceURI: HTML_NAMESPACE,
14233
+ tagName: 'template'
14234
+ };
14235
+ }
14236
+
14237
+ var tagName = stringToLowerCase(element.tagName);
14238
+ var parentTagName = stringToLowerCase(parent.tagName);
14239
+
14240
+ if (element.namespaceURI === SVG_NAMESPACE) {
14241
+ // The only way to switch from HTML namespace to SVG
14242
+ // is via <svg>. If it happens via any other tag, then
14243
+ // it should be killed.
14244
+ if (parent.namespaceURI === HTML_NAMESPACE) {
14245
+ return tagName === 'svg';
14246
+ }
14247
+
14248
+ // The only way to switch from MathML to SVG is via
14249
+ // svg if parent is either <annotation-xml> or MathML
14250
+ // text integration points.
14251
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
14252
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
14253
+ }
14254
+
14255
+ // We only allow elements that are defined in SVG
14256
+ // spec. All others are disallowed in SVG namespace.
14257
+ return Boolean(ALL_SVG_TAGS[tagName]);
14258
+ }
14259
+
14260
+ if (element.namespaceURI === MATHML_NAMESPACE) {
14261
+ // The only way to switch from HTML namespace to MathML
14262
+ // is via <math>. If it happens via any other tag, then
14263
+ // it should be killed.
14264
+ if (parent.namespaceURI === HTML_NAMESPACE) {
14265
+ return tagName === 'math';
14266
+ }
14267
+
14268
+ // The only way to switch from SVG to MathML is via
14269
+ // <math> and HTML integration points
14270
+ if (parent.namespaceURI === SVG_NAMESPACE) {
14271
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
14272
+ }
14273
+
14274
+ // We only allow elements that are defined in MathML
14275
+ // spec. All others are disallowed in MathML namespace.
14276
+ return Boolean(ALL_MATHML_TAGS[tagName]);
14277
+ }
14278
+
14279
+ if (element.namespaceURI === HTML_NAMESPACE) {
14280
+ // The only way to switch from SVG to HTML is via
14281
+ // HTML integration points, and from MathML to HTML
14282
+ // is via MathML text integration points
14283
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
14284
+ return false;
14285
+ }
14286
+
14287
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
14288
+ return false;
14289
+ }
14290
+
14291
+ // Certain elements are allowed in both SVG and HTML
14292
+ // namespace. We need to specify them explicitly
14293
+ // so that they don't get erronously deleted from
14294
+ // HTML namespace.
14295
+ var commonSvgAndHTMLElements = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
14296
+
14297
+ // We disallow tags that are specific for MathML
14298
+ // or SVG and should never appear in HTML namespace
14299
+ return !ALL_MATHML_TAGS[tagName] && (commonSvgAndHTMLElements[tagName] || !ALL_SVG_TAGS[tagName]);
14300
+ }
14301
+
14302
+ // The code should never reach this place (this means
14303
+ // that the element somehow got namespace that is not
14304
+ // HTML, SVG or MathML). Return false just in case.
14305
+ return false;
14306
+ };
14307
+
14308
+ /**
14309
+ * _forceRemove
14310
+ *
14311
+ * @param {Node} node a DOM node
14312
+ */
14313
+ var _forceRemove = function _forceRemove(node) {
14314
+ arrayPush(DOMPurify.removed, { element: node });
14315
+ try {
14316
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
14317
+ node.parentNode.removeChild(node);
14318
+ } catch (_) {
14319
+ try {
14320
+ node.outerHTML = emptyHTML;
14321
+ } catch (_) {
14322
+ node.remove();
14323
+ }
14324
+ }
14325
+ };
14326
+
14327
+ /**
14328
+ * _removeAttribute
14329
+ *
14330
+ * @param {String} name an Attribute name
14331
+ * @param {Node} node a DOM node
14332
+ */
14333
+ var _removeAttribute = function _removeAttribute(name, node) {
14334
+ try {
14335
+ arrayPush(DOMPurify.removed, {
14336
+ attribute: node.getAttributeNode(name),
14337
+ from: node
14338
+ });
14339
+ } catch (_) {
14340
+ arrayPush(DOMPurify.removed, {
14341
+ attribute: null,
14342
+ from: node
14343
+ });
14344
+ }
14345
+
14346
+ node.removeAttribute(name);
14347
+
14348
+ // We void attribute values for unremovable "is"" attributes
14349
+ if (name === 'is' && !ALLOWED_ATTR[name]) {
14350
+ if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
14351
+ try {
14352
+ _forceRemove(node);
14353
+ } catch (_) {}
14354
+ } else {
14355
+ try {
14356
+ node.setAttribute(name, '');
14357
+ } catch (_) {}
14358
+ }
14359
+ }
14360
+ };
14361
+
14362
+ /**
14363
+ * _initDocument
14364
+ *
14365
+ * @param {String} dirty a string of dirty markup
14366
+ * @return {Document} a DOM, filled with the dirty markup
14367
+ */
14368
+ var _initDocument = function _initDocument(dirty) {
14369
+ /* Create a HTML document */
14370
+ var doc = void 0;
14371
+ var leadingWhitespace = void 0;
14372
+
14373
+ if (FORCE_BODY) {
14374
+ dirty = '<remove></remove>' + dirty;
14375
+ } else {
14376
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
14377
+ var matches = stringMatch(dirty, /^[\r\n\t ]+/);
14378
+ leadingWhitespace = matches && matches[0];
14379
+ }
14380
+
14381
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml') {
14382
+ // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
14383
+ dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
14384
+ }
14385
+
14386
+ var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
14387
+ /*
14388
+ * Use the DOMParser API by default, fallback later if needs be
14389
+ * DOMParser not work for svg when has multiple root element.
14390
+ */
14391
+ if (NAMESPACE === HTML_NAMESPACE) {
14392
+ try {
14393
+ doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
14394
+ } catch (_) {}
14395
+ }
14396
+
14397
+ /* Use createHTMLDocument in case DOMParser is not available */
14398
+ if (!doc || !doc.documentElement) {
14399
+ doc = implementation.createDocument(NAMESPACE, 'template', null);
14400
+ try {
14401
+ doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
14402
+ } catch (_) {
14403
+ // Syntax error if dirtyPayload is invalid xml
14404
+ }
14405
+ }
14406
+
14407
+ var body = doc.body || doc.documentElement;
14408
+
14409
+ if (dirty && leadingWhitespace) {
14410
+ body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
14411
+ }
14412
+
14413
+ /* Work on whole document or just its body */
14414
+ if (NAMESPACE === HTML_NAMESPACE) {
14415
+ return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
14416
+ }
14417
+
14418
+ return WHOLE_DOCUMENT ? doc.documentElement : body;
14419
+ };
14420
+
14421
+ /**
14422
+ * _createIterator
14423
+ *
14424
+ * @param {Document} root document/fragment to create iterator for
14425
+ * @return {Iterator} iterator instance
14426
+ */
14427
+ var _createIterator = function _createIterator(root) {
14428
+ return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
14429
+ };
14430
+
14431
+ /**
14432
+ * _isClobbered
14433
+ *
14434
+ * @param {Node} elm element to check for clobbering attacks
14435
+ * @return {Boolean} true if clobbered, false if safe
14436
+ */
14437
+ var _isClobbered = function _isClobbered(elm) {
14438
+ if (elm instanceof Text || elm instanceof Comment) {
14439
+ return false;
14440
+ }
14441
+
14442
+ if (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function') {
14443
+ return true;
14444
+ }
14445
+
14446
+ return false;
14447
+ };
14448
+
14449
+ /**
14450
+ * _isNode
14451
+ *
14452
+ * @param {Node} obj object to check whether it's a DOM node
14453
+ * @return {Boolean} true is object is a DOM node
14454
+ */
14455
+ var _isNode = function _isNode(object) {
14456
+ return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? object instanceof Node : object && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
14457
+ };
14458
+
14459
+ /**
14460
+ * _executeHook
14461
+ * Execute user configurable hooks
14462
+ *
14463
+ * @param {String} entryPoint Name of the hook's entry point
14464
+ * @param {Node} currentNode node to work on with the hook
14465
+ * @param {Object} data additional hook parameters
14466
+ */
14467
+ var _executeHook = function _executeHook(entryPoint, currentNode, data) {
14468
+ if (!hooks[entryPoint]) {
14469
+ return;
14470
+ }
14471
+
14472
+ arrayForEach(hooks[entryPoint], function (hook) {
14473
+ hook.call(DOMPurify, currentNode, data, CONFIG);
14474
+ });
14475
+ };
14476
+
14477
+ /**
14478
+ * _sanitizeElements
14479
+ *
14480
+ * @protect nodeName
14481
+ * @protect textContent
14482
+ * @protect removeChild
14483
+ *
14484
+ * @param {Node} currentNode to check for permission to exist
14485
+ * @return {Boolean} true if node was killed, false if left alive
14486
+ */
14487
+ var _sanitizeElements = function _sanitizeElements(currentNode) {
14488
+ var content = void 0;
14489
+
14490
+ /* Execute a hook if present */
14491
+ _executeHook('beforeSanitizeElements', currentNode, null);
14492
+
14493
+ /* Check if element is clobbered or can clobber */
14494
+ if (_isClobbered(currentNode)) {
14495
+ _forceRemove(currentNode);
14496
+ return true;
14497
+ }
14498
+
14499
+ /* Check if tagname contains Unicode */
14500
+ if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) {
14501
+ _forceRemove(currentNode);
14502
+ return true;
14503
+ }
14504
+
14505
+ /* Now let's check the element's type and name */
14506
+ var tagName = transformCaseFunc(currentNode.nodeName);
14507
+
14508
+ /* Execute a hook if present */
14509
+ _executeHook('uponSanitizeElement', currentNode, {
14510
+ tagName: tagName,
14511
+ allowedTags: ALLOWED_TAGS
14512
+ });
14513
+
14514
+ /* Detect mXSS attempts abusing namespace confusion */
14515
+ if (!_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
14516
+ _forceRemove(currentNode);
14517
+ return true;
14518
+ }
14519
+
14520
+ /* Mitigate a problem with templates inside select */
14521
+ if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
14522
+ _forceRemove(currentNode);
14523
+ return true;
14524
+ }
14525
+
14526
+ /* Remove element if anything forbids its presence */
14527
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
14528
+ /* Keep content except for bad-listed elements */
14529
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
14530
+ var parentNode = getParentNode(currentNode) || currentNode.parentNode;
14531
+ var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
14532
+
14533
+ if (childNodes && parentNode) {
14534
+ var childCount = childNodes.length;
14535
+
14536
+ for (var i = childCount - 1; i >= 0; --i) {
14537
+ parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
14538
+ }
14539
+ }
14540
+ }
14541
+
14542
+ _forceRemove(currentNode);
14543
+ return true;
14544
+ }
14545
+
14546
+ /* Check whether element has a valid namespace */
14547
+ if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
14548
+ _forceRemove(currentNode);
14549
+ return true;
14550
+ }
14551
+
14552
+ if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
14553
+ _forceRemove(currentNode);
14554
+ return true;
14555
+ }
14556
+
14557
+ /* Sanitize element content to be template-safe */
14558
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
14559
+ /* Get the element's text content */
14560
+ content = currentNode.textContent;
14561
+ content = stringReplace(content, MUSTACHE_EXPR$$1, ' ');
14562
+ content = stringReplace(content, ERB_EXPR$$1, ' ');
14563
+ if (currentNode.textContent !== content) {
14564
+ arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
14565
+ currentNode.textContent = content;
14566
+ }
14567
+ }
14568
+
14569
+ /* Execute a hook if present */
14570
+ _executeHook('afterSanitizeElements', currentNode, null);
14571
+
14572
+ return false;
14573
+ };
14574
+
14575
+ /**
14576
+ * _isValidAttribute
14577
+ *
14578
+ * @param {string} lcTag Lowercase tag name of containing element.
14579
+ * @param {string} lcName Lowercase attribute name.
14580
+ * @param {string} value Attribute value.
14581
+ * @return {Boolean} Returns true if `value` is valid, otherwise false.
14582
+ */
14583
+ // eslint-disable-next-line complexity
14584
+ var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
14585
+ /* Make sure attribute cannot clobber */
14586
+ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
14587
+ return false;
14588
+ }
14589
+
14590
+ /* Allow valid data-* attributes: At least one character after "-"
14591
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
14592
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
14593
+ We don't need to check the value; it's always URI safe. */
14594
+ if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$$1, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
14595
+ return false;
14596
+
14597
+ /* Check value is safe. First, is attr inert? If so, is safe */
14598
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; else if (!value) ; else {
14599
+ return false;
14600
+ }
14601
+
14602
+ return true;
14603
+ };
14604
+
14605
+ /**
14606
+ * _sanitizeAttributes
14607
+ *
14608
+ * @protect attributes
14609
+ * @protect nodeName
14610
+ * @protect removeAttribute
14611
+ * @protect setAttribute
14612
+ *
14613
+ * @param {Node} currentNode to sanitize
14614
+ */
14615
+ var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
14616
+ var attr = void 0;
14617
+ var value = void 0;
14618
+ var lcName = void 0;
14619
+ var l = void 0;
14620
+ /* Execute a hook if present */
14621
+ _executeHook('beforeSanitizeAttributes', currentNode, null);
14622
+
14623
+ var attributes = currentNode.attributes;
14624
+
14625
+ /* Check if we have attributes; if not we might have a text node */
14626
+
14627
+ if (!attributes) {
14628
+ return;
14629
+ }
14630
+
14631
+ var hookEvent = {
14632
+ attrName: '',
14633
+ attrValue: '',
14634
+ keepAttr: true,
14635
+ allowedAttributes: ALLOWED_ATTR
14636
+ };
14637
+ l = attributes.length;
14638
+
14639
+ /* Go backwards over all attributes; safely remove bad ones */
14640
+ while (l--) {
14641
+ attr = attributes[l];
14642
+ var _attr = attr,
14643
+ name = _attr.name,
14644
+ namespaceURI = _attr.namespaceURI;
14645
+
14646
+ value = stringTrim(attr.value);
14647
+ lcName = transformCaseFunc(name);
14648
+
14649
+ /* Execute a hook if present */
14650
+ hookEvent.attrName = lcName;
14651
+ hookEvent.attrValue = value;
14652
+ hookEvent.keepAttr = true;
14653
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
14654
+ _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
14655
+ value = hookEvent.attrValue;
14656
+ /* Did the hooks approve of the attribute? */
14657
+ if (hookEvent.forceKeepAttr) {
14658
+ continue;
14659
+ }
14660
+
14661
+ /* Remove attribute */
14662
+ _removeAttribute(name, currentNode);
14663
+
14664
+ /* Did the hooks approve of the attribute? */
14665
+ if (!hookEvent.keepAttr) {
14666
+ continue;
14667
+ }
14668
+
14669
+ /* Work around a security issue in jQuery 3.0 */
14670
+ if (regExpTest(/\/>/i, value)) {
14671
+ _removeAttribute(name, currentNode);
14672
+ continue;
14673
+ }
14674
+
14675
+ /* Sanitize attribute content to be template-safe */
14676
+ if (SAFE_FOR_TEMPLATES) {
14677
+ value = stringReplace(value, MUSTACHE_EXPR$$1, ' ');
14678
+ value = stringReplace(value, ERB_EXPR$$1, ' ');
14679
+ }
14680
+
14681
+ /* Is `value` valid for this attribute? */
14682
+ var lcTag = transformCaseFunc(currentNode.nodeName);
14683
+ if (!_isValidAttribute(lcTag, lcName, value)) {
14684
+ continue;
14685
+ }
14686
+
14687
+ /* Handle invalid data-* attribute set by try-catching it */
14688
+ try {
14689
+ if (namespaceURI) {
14690
+ currentNode.setAttributeNS(namespaceURI, name, value);
14691
+ } else {
14692
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
14693
+ currentNode.setAttribute(name, value);
14694
+ }
14695
+
14696
+ arrayPop(DOMPurify.removed);
14697
+ } catch (_) {}
14698
+ }
14699
+
14700
+ /* Execute a hook if present */
14701
+ _executeHook('afterSanitizeAttributes', currentNode, null);
14702
+ };
14703
+
14704
+ /**
14705
+ * _sanitizeShadowDOM
14706
+ *
14707
+ * @param {DocumentFragment} fragment to iterate over recursively
14708
+ */
14709
+ var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
14710
+ var shadowNode = void 0;
14711
+ var shadowIterator = _createIterator(fragment);
14712
+
14713
+ /* Execute a hook if present */
14714
+ _executeHook('beforeSanitizeShadowDOM', fragment, null);
14715
+
14716
+ while (shadowNode = shadowIterator.nextNode()) {
14717
+ /* Execute a hook if present */
14718
+ _executeHook('uponSanitizeShadowNode', shadowNode, null);
14719
+
14720
+ /* Sanitize tags and elements */
14721
+ if (_sanitizeElements(shadowNode)) {
14722
+ continue;
14723
+ }
14724
+
14725
+ /* Deep shadow DOM detected */
14726
+ if (shadowNode.content instanceof DocumentFragment) {
14727
+ _sanitizeShadowDOM(shadowNode.content);
14728
+ }
14729
+
14730
+ /* Check attributes, sanitize if necessary */
14731
+ _sanitizeAttributes(shadowNode);
14732
+ }
14733
+
14734
+ /* Execute a hook if present */
14735
+ _executeHook('afterSanitizeShadowDOM', fragment, null);
14736
+ };
14737
+
14738
+ /**
14739
+ * Sanitize
14740
+ * Public method providing core sanitation functionality
14741
+ *
14742
+ * @param {String|Node} dirty string or DOM node
14743
+ * @param {Object} configuration object
14744
+ */
14745
+ // eslint-disable-next-line complexity
14746
+ DOMPurify.sanitize = function (dirty, cfg) {
14747
+ var body = void 0;
14748
+ var importedNode = void 0;
14749
+ var currentNode = void 0;
14750
+ var oldNode = void 0;
14751
+ var returnNode = void 0;
14752
+ /* Make sure we have a string to sanitize.
14753
+ DO NOT return early, as this will return the wrong type if
14754
+ the user has requested a DOM object rather than a string */
14755
+ IS_EMPTY_INPUT = !dirty;
14756
+ if (IS_EMPTY_INPUT) {
14757
+ dirty = '<!-->';
14758
+ }
14759
+
14760
+ /* Stringify, in case dirty is an object */
14761
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
14762
+ // eslint-disable-next-line no-negated-condition
14763
+ if (typeof dirty.toString !== 'function') {
14764
+ throw typeErrorCreate('toString is not a function');
14765
+ } else {
14766
+ dirty = dirty.toString();
14767
+ if (typeof dirty !== 'string') {
14768
+ throw typeErrorCreate('dirty is not a string, aborting');
14769
+ }
14770
+ }
14771
+ }
14772
+
14773
+ /* Check we can run. Otherwise fall back or ignore */
14774
+ if (!DOMPurify.isSupported) {
14775
+ if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
14776
+ if (typeof dirty === 'string') {
14777
+ return window.toStaticHTML(dirty);
14778
+ }
14779
+
14780
+ if (_isNode(dirty)) {
14781
+ return window.toStaticHTML(dirty.outerHTML);
14782
+ }
14783
+ }
14784
+
14785
+ return dirty;
14786
+ }
14787
+
14788
+ /* Assign config vars */
14789
+ if (!SET_CONFIG) {
14790
+ _parseConfig(cfg);
14791
+ }
14792
+
14793
+ /* Clean up removed elements */
14794
+ DOMPurify.removed = [];
14795
+
14796
+ /* Check if dirty is correctly typed for IN_PLACE */
14797
+ if (typeof dirty === 'string') {
14798
+ IN_PLACE = false;
14799
+ }
14800
+
14801
+ if (IN_PLACE) ; else if (dirty instanceof Node) {
14802
+ /* If dirty is a DOM element, append to an empty document to avoid
14803
+ elements being stripped by the parser */
14804
+ body = _initDocument('<!---->');
14805
+ importedNode = body.ownerDocument.importNode(dirty, true);
14806
+ if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
14807
+ /* Node is already a body, use as is */
14808
+ body = importedNode;
14809
+ } else if (importedNode.nodeName === 'HTML') {
14810
+ body = importedNode;
14811
+ } else {
14812
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
14813
+ body.appendChild(importedNode);
14814
+ }
14815
+ } else {
14816
+ /* Exit directly if we have nothing to do */
14817
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
14818
+ // eslint-disable-next-line unicorn/prefer-includes
14819
+ dirty.indexOf('<') === -1) {
14820
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
14821
+ }
14822
+
14823
+ /* Initialize the document to work on */
14824
+ body = _initDocument(dirty);
14825
+
14826
+ /* Check we have a DOM node from the data */
14827
+ if (!body) {
14828
+ return RETURN_DOM ? null : emptyHTML;
14829
+ }
14830
+ }
14831
+
14832
+ /* Remove first element node (ours) if FORCE_BODY is set */
14833
+ if (body && FORCE_BODY) {
14834
+ _forceRemove(body.firstChild);
14835
+ }
14836
+
14837
+ /* Get node iterator */
14838
+ var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
14839
+
14840
+ /* Now start iterating over the created document */
14841
+ while (currentNode = nodeIterator.nextNode()) {
14842
+ /* Fix IE's strange behavior with manipulated textNodes #89 */
14843
+ if (currentNode.nodeType === 3 && currentNode === oldNode) {
14844
+ continue;
14845
+ }
14846
+
14847
+ /* Sanitize tags and elements */
14848
+ if (_sanitizeElements(currentNode)) {
14849
+ continue;
14850
+ }
14851
+
14852
+ /* Shadow DOM detected, sanitize it */
14853
+ if (currentNode.content instanceof DocumentFragment) {
14854
+ _sanitizeShadowDOM(currentNode.content);
14855
+ }
14856
+
14857
+ /* Check attributes, sanitize if necessary */
14858
+ _sanitizeAttributes(currentNode);
14859
+
14860
+ oldNode = currentNode;
14861
+ }
14862
+
14863
+ oldNode = null;
14864
+
14865
+ /* If we sanitized `dirty` in-place, return it. */
14866
+ if (IN_PLACE) {
14867
+ return dirty;
14868
+ }
14869
+
14870
+ /* Return sanitized string or DOM */
14871
+ if (RETURN_DOM) {
14872
+ if (RETURN_DOM_FRAGMENT) {
14873
+ returnNode = createDocumentFragment.call(body.ownerDocument);
14874
+
14875
+ while (body.firstChild) {
14876
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
14877
+ returnNode.appendChild(body.firstChild);
14878
+ }
14879
+ } else {
14880
+ returnNode = body;
14881
+ }
14882
+
14883
+ if (RETURN_DOM_IMPORT) {
14884
+ /*
14885
+ AdoptNode() is not used because internal state is not reset
14886
+ (e.g. the past names map of a HTMLFormElement), this is safe
14887
+ in theory but we would rather not risk another attack vector.
14888
+ The state that is cloned by importNode() is explicitly defined
14889
+ by the specs.
14890
+ */
14891
+ returnNode = importNode.call(originalDocument, returnNode, true);
14892
+ }
14893
+
14894
+ return returnNode;
14895
+ }
14896
+
14897
+ var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
14898
+
14899
+ /* Sanitize final string template-safe */
14900
+ if (SAFE_FOR_TEMPLATES) {
14901
+ serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$$1, ' ');
14902
+ serializedHTML = stringReplace(serializedHTML, ERB_EXPR$$1, ' ');
14903
+ }
14904
+
14905
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
14906
+ };
14907
+
14908
+ /**
14909
+ * Public method to set the configuration once
14910
+ * setConfig
14911
+ *
14912
+ * @param {Object} cfg configuration object
14913
+ */
14914
+ DOMPurify.setConfig = function (cfg) {
14915
+ _parseConfig(cfg);
14916
+ SET_CONFIG = true;
14917
+ };
14918
+
14919
+ /**
14920
+ * Public method to remove the configuration
14921
+ * clearConfig
14922
+ *
14923
+ */
14924
+ DOMPurify.clearConfig = function () {
14925
+ CONFIG = null;
14926
+ SET_CONFIG = false;
14927
+ };
14928
+
14929
+ /**
14930
+ * Public method to check if an attribute value is valid.
14931
+ * Uses last set config, if any. Otherwise, uses config defaults.
14932
+ * isValidAttribute
14933
+ *
14934
+ * @param {string} tag Tag name of containing element.
14935
+ * @param {string} attr Attribute name.
14936
+ * @param {string} value Attribute value.
14937
+ * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
14938
+ */
14939
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
14940
+ /* Initialize shared config vars if necessary. */
14941
+ if (!CONFIG) {
14942
+ _parseConfig({});
14943
+ }
14944
+
14945
+ var lcTag = transformCaseFunc(tag);
14946
+ var lcName = transformCaseFunc(attr);
14947
+ return _isValidAttribute(lcTag, lcName, value);
14948
+ };
14949
+
14950
+ /**
14951
+ * AddHook
14952
+ * Public method to add DOMPurify hooks
14953
+ *
14954
+ * @param {String} entryPoint entry point for the hook to add
14955
+ * @param {Function} hookFunction function to execute
14956
+ */
14957
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
14958
+ if (typeof hookFunction !== 'function') {
14959
+ return;
14960
+ }
14961
+
14962
+ hooks[entryPoint] = hooks[entryPoint] || [];
14963
+ arrayPush(hooks[entryPoint], hookFunction);
14964
+ };
14965
+
14966
+ /**
14967
+ * RemoveHook
14968
+ * Public method to remove a DOMPurify hook at a given entryPoint
14969
+ * (pops it from the stack of hooks if more are present)
14970
+ *
14971
+ * @param {String} entryPoint entry point for the hook to remove
14972
+ */
14973
+ DOMPurify.removeHook = function (entryPoint) {
14974
+ if (hooks[entryPoint]) {
14975
+ arrayPop(hooks[entryPoint]);
14976
+ }
14977
+ };
14978
+
14979
+ /**
14980
+ * RemoveHooks
14981
+ * Public method to remove all DOMPurify hooks at a given entryPoint
14982
+ *
14983
+ * @param {String} entryPoint entry point for the hooks to remove
14984
+ */
14985
+ DOMPurify.removeHooks = function (entryPoint) {
14986
+ if (hooks[entryPoint]) {
14987
+ hooks[entryPoint] = [];
14988
+ }
14989
+ };
14990
+
14991
+ /**
14992
+ * RemoveAllHooks
14993
+ * Public method to remove all DOMPurify hooks
14994
+ *
14995
+ */
14996
+ DOMPurify.removeAllHooks = function () {
14997
+ hooks = {};
14998
+ };
14999
+
15000
+ return DOMPurify;
15001
+ }
15002
+
15003
+ var purify = createDOMPurify();
15004
+
15005
+ var CAN_BE_WHITE_TAG_LIST = ['iframe', 'embed'];
15006
+ var whiteTagList = [];
15007
+ function registerTagWhitelistIfPossible(tagName) {
15008
+ if (includes(CAN_BE_WHITE_TAG_LIST, tagName)) {
15009
+ whiteTagList.push(tagName.toLowerCase());
15010
+ }
15011
+ }
15012
+ function sanitizeHTML(html, options) {
15013
+ return purify.sanitize(html, __assign$1({ ADD_TAGS: whiteTagList, ADD_ATTR: ['rel', 'target', 'hreflang', 'type'], FORBID_TAGS: [
15014
+ 'input',
15015
+ 'script',
15016
+ 'textarea',
15017
+ 'form',
15018
+ 'button',
15019
+ 'select',
15020
+ 'meta',
15021
+ 'style',
15022
+ 'link',
15023
+ 'title',
15024
+ 'object',
15025
+ 'base',
15026
+ ] }, options));
15027
+ }
15028
+
15029
+ function getChildrenHTML(node, typeName) {
15030
+ return node
15031
+ .literal.replace(new RegExp("(<\\s*" + typeName + "[^>]+?>)|(</" + typeName + "\\s*[>])", 'ig'), '')
15032
+ .trim();
15033
+ }
15034
+ function getHTMLAttrsByHTMLString(html) {
15035
+ html = html.match(reHTMLTag)[0];
15036
+ var attrs = html.match(new RegExp(ATTRIBUTE$1, 'g'));
15037
+ return attrs
15038
+ ? attrs.reduce(function (acc, attr) {
15039
+ var _a = attr.trim().split('='), name = _a[0], values = _a.slice(1);
15040
+ if (values.length) {
15041
+ acc[name] = values.join('=').replace(/'|"/g, '').trim();
15042
+ }
15043
+ return acc;
15044
+ }, {})
15045
+ : {};
15046
+ }
15047
+ function getHTMLAttrs(dom) {
15048
+ return toArray_1(dom.attributes).reduce(function (acc, attr) {
15049
+ acc[attr.nodeName] = attr.nodeValue;
15050
+ return acc;
15051
+ }, {});
15052
+ }
15053
+ function sanitizeDOM(node, typeName, sanitizer, wwToDOMAdaptor) {
15054
+ var dom = wwToDOMAdaptor.getToDOMNode(typeName)(node);
15055
+ var html = sanitizer(dom.outerHTML);
15056
+ var container = document.createElement('div');
15057
+ container.innerHTML = html;
15058
+ dom = container.firstChild;
15059
+ var htmlAttrs = getHTMLAttrs(dom);
15060
+ return { dom: dom, htmlAttrs: htmlAttrs };
15061
+ }
15062
+ var schemaFactory = {
15063
+ htmlBlock: function (typeName, sanitizeHTML, wwToDOMAdaptor) {
15064
+ return {
15065
+ atom: true,
15066
+ content: 'block+',
15067
+ group: 'block',
15068
+ attrs: {
15069
+ htmlAttrs: { default: {} },
15070
+ childrenHTML: { default: '' },
15071
+ htmlBlock: { default: true },
15072
+ },
15073
+ parseDOM: [
15074
+ {
15075
+ tag: typeName,
15076
+ getAttrs: function (dom) {
15077
+ return {
15078
+ htmlAttrs: getHTMLAttrs(dom),
15079
+ childrenHTML: dom.innerHTML,
15080
+ };
15081
+ },
15082
+ },
15083
+ ],
15084
+ toDOM: function (node) {
15085
+ var _a = sanitizeDOM(node, typeName, sanitizeHTML, wwToDOMAdaptor), dom = _a.dom, htmlAttrs = _a.htmlAttrs;
15086
+ htmlAttrs.class = htmlAttrs.class ? htmlAttrs.class + " html-block" : 'html-block';
15087
+ return __spreadArray$1([typeName, htmlAttrs], toArray_1(dom.childNodes));
15088
+ },
15089
+ };
15090
+ },
15091
+ htmlInline: function (typeName, sanitizeHTML, wwToDOMAdaptor) {
15092
+ return {
15093
+ attrs: {
15094
+ htmlAttrs: { default: {} },
15095
+ htmlInline: { default: true },
15096
+ },
15097
+ parseDOM: [
15098
+ {
15099
+ tag: typeName,
15100
+ getAttrs: function (dom) {
15101
+ return {
15102
+ htmlAttrs: getHTMLAttrs(dom),
15103
+ };
15104
+ },
15105
+ },
15106
+ ],
15107
+ toDOM: function (node) {
15108
+ var htmlAttrs = sanitizeDOM(node, typeName, sanitizeHTML, wwToDOMAdaptor).htmlAttrs;
15109
+ return [typeName, htmlAttrs, 0];
15110
+ },
15111
+ };
15112
+ },
15113
+ };
15114
+ function createHTMLSchemaMap(convertorMap, sanitizeHTML, wwToDOMAdaptor) {
15115
+ var htmlSchemaMap = { nodes: {}, marks: {} };
15116
+ ['htmlBlock', 'htmlInline'].forEach(function (htmlType) {
15117
+ if (convertorMap[htmlType]) {
15118
+ Object.keys(convertorMap[htmlType]).forEach(function (type) {
15119
+ var targetType = htmlType === 'htmlBlock' ? 'nodes' : 'marks';
15120
+ // register tag white list for preventing to remove the html in sanitizer
15121
+ registerTagWhitelistIfPossible(type);
15122
+ htmlSchemaMap[targetType][type] = schemaFactory[htmlType](type, sanitizeHTML, wwToDOMAdaptor);
15123
+ });
15124
+ }
15125
+ });
15126
+ return htmlSchemaMap;
15127
+ }
15128
+
15129
+ var reCloseTag = /^\s*<\s*\//;
15130
+ var baseConvertors = {
15131
+ paragraph: function (_, _a) {
15132
+ var entering = _a.entering, origin = _a.origin, options = _a.options;
15133
+ if (options.nodeId) {
15134
+ return {
15135
+ type: entering ? 'openTag' : 'closeTag',
15136
+ outerNewLine: true,
15137
+ tagName: 'p',
15138
+ };
15139
+ }
15140
+ return origin();
15141
+ },
15142
+ softbreak: function (node) {
15143
+ var isPrevNodeHTML = node.prev && node.prev.type === 'htmlInline';
15144
+ var isPrevBR = isPrevNodeHTML && /<br ?\/?>/.test(node.prev.literal);
15145
+ var content = isPrevBR ? '\n' : '<br>\n';
15146
+ return { type: 'html', content: content };
15147
+ },
13751
15148
  item: function (node, _a) {
13752
15149
  var entering = _a.entering;
13753
15150
  if (entering) {
@@ -15878,7 +17275,7 @@ function getContentBetweenFragmentComments(html) {
15878
17275
  if (startFragmentIndex > -1 && endFragmentIndex > -1) {
15879
17276
  html = html.slice(startFragmentIndex + START_FRAGMENT_COMMENT.length, endFragmentIndex);
15880
17277
  }
15881
- return html;
17278
+ return html.replace(/<br[^>]*>/g, ALTERNATIVE_TAG_FOR_BR);
15882
17279
  }
15883
17280
  function convertMsoTableToCompletedTable(html) {
15884
17281
  // wrap with <tr> if html contains dangling <td> tags
@@ -15966,9 +17363,9 @@ function createTableBody(tableBodyRows, maxColumnCount, schema) {
15966
17363
  }
15967
17364
  return schema.nodes.tableBody.create(null, copiedRows);
15968
17365
  }
15969
- function createTableFromPastingTable(rows, schema, startFromBody) {
17366
+ function createTableFromPastingTable(rows, schema, startFromBody, isInTable) {
15970
17367
  var columnCount = getMaxColumnCount(rows);
15971
- if (startFromBody) {
17368
+ if (startFromBody && isInTable) {
15972
17369
  return schema.nodes.table.create(null, [createTableBody(rows, columnCount, schema)]);
15973
17370
  }
15974
17371
  var tableHeadRow = rows[0];
@@ -15979,15 +17376,16 @@ function createTableFromPastingTable(rows, schema, startFromBody) {
15979
17376
  }
15980
17377
  return schema.nodes.table.create(null, nodes);
15981
17378
  }
15982
- function changePastedSlice(slice, schema) {
17379
+ function changePastedSlice(slice, schema, isInTable) {
15983
17380
  var nodes = [];
15984
- slice.content.forEach(function (node) {
17381
+ var content = slice.content, openStart = slice.openStart, openEnd = slice.openEnd;
17382
+ content.forEach(function (node) {
15985
17383
  if (node.type.name === 'table') {
15986
17384
  var tableContent = getTableContentFromSlice(new Slice(Fragment.from(node), 0, 0));
15987
17385
  if (tableContent) {
15988
17386
  var rows = createRowsFromPastingTable(tableContent);
15989
17387
  var startFromBody = tableContent.firstChild.type.name === 'tableBody';
15990
- var table = createTableFromPastingTable(rows, schema, startFromBody);
17388
+ var table = createTableFromPastingTable(rows, schema, startFromBody, isInTable);
15991
17389
  nodes.push(table);
15992
17390
  }
15993
17391
  }
@@ -15995,7 +17393,7 @@ function changePastedSlice(slice, schema) {
15995
17393
  nodes.push(node);
15996
17394
  }
15997
17395
  });
15998
- return new Slice(Fragment.from(nodes), 0, 0);
17396
+ return new Slice(Fragment.from(nodes), openStart, openEnd);
15999
17397
  }
16000
17398
 
16001
17399
  var DUMMY_CELL_SIZE = 4;
@@ -16208,7 +17606,7 @@ var Paragraph = /** @class */ (function (_super) {
16208
17606
  get: function () {
16209
17607
  return {
16210
17608
  content: 'inline*',
16211
- group: 'block listGroup',
17609
+ group: 'block',
16212
17610
  attrs: __assign$1({}, getDefaultCustomAttrs()),
16213
17611
  parseDOM: [{ tag: 'p' }],
16214
17612
  toDOM: function (_a) {
@@ -16437,7 +17835,7 @@ var BulletList = /** @class */ (function (_super) {
16437
17835
  get: function () {
16438
17836
  return {
16439
17837
  content: 'listItem+',
16440
- group: 'block listGroup',
17838
+ group: 'block',
16441
17839
  attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
16442
17840
  parseDOM: [createDOMInfoParsedRawHTML('ul')],
16443
17841
  toDOM: function (_a) {
@@ -16487,7 +17885,7 @@ var OrderedList = /** @class */ (function (_super) {
16487
17885
  get: function () {
16488
17886
  return {
16489
17887
  content: 'listItem+',
16490
- group: 'block listGroup',
17888
+ group: 'block',
16491
17889
  attrs: __assign$1({ order: { default: 1 }, rawHTML: { default: null } }, getDefaultCustomAttrs()),
16492
17890
  parseDOM: [
16493
17891
  {
@@ -16543,7 +17941,8 @@ var ListItem = /** @class */ (function (_super) {
16543
17941
  Object.defineProperty(ListItem.prototype, "schema", {
16544
17942
  get: function () {
16545
17943
  return {
16546
- content: 'paragraph listGroup*',
17944
+ content: 'paragraph block*',
17945
+ selectable: false,
16547
17946
  attrs: {
16548
17947
  task: { default: false },
16549
17948
  checked: { default: false },
@@ -17391,9 +18790,13 @@ var Image = /** @class */ (function (_super) {
17391
18790
  {
17392
18791
  tag: 'img[src]',
17393
18792
  getAttrs: function (dom) {
17394
- var imageUrl = dom.getAttribute('src') || '';
17395
- var rawHTML = dom.getAttribute('data-raw-html');
17396
- return __assign$1({ imageUrl: sanitizeXSSAttributeValue(imageUrl), altText: dom.getAttribute('alt') }, (rawHTML && { rawHTML: rawHTML }));
18793
+ var sanitizedDOM = sanitizeHTML(dom, { RETURN_DOM_FRAGMENT: true })
18794
+ .firstChild;
18795
+ var imageUrl = sanitizedDOM.getAttribute('src') || '';
18796
+ var rawHTML = sanitizedDOM.getAttribute('data-raw-html');
18797
+ var altText = sanitizedDOM.getAttribute('alt');
18798
+ return __assign$1({ imageUrl: imageUrl,
18799
+ altText: altText }, (rawHTML && { rawHTML: rawHTML }));
17397
18800
  },
17398
18801
  },
17399
18802
  ],
@@ -17667,9 +19070,11 @@ var Link = /** @class */ (function (_super) {
17667
19070
  {
17668
19071
  tag: 'a[href]',
17669
19072
  getAttrs: function (dom) {
17670
- var href = dom.getAttribute('href') || '';
17671
- var rawHTML = dom.getAttribute('data-raw-html');
17672
- return __assign$1({ linkUrl: sanitizeXSSAttributeValue(href), linkText: dom.textContent }, (rawHTML && { rawHTML: rawHTML }));
19073
+ var sanitizedDOM = sanitizeHTML(dom, { RETURN_DOM_FRAGMENT: true })
19074
+ .firstChild;
19075
+ var href = sanitizedDOM.getAttribute('href') || '';
19076
+ var rawHTML = sanitizedDOM.getAttribute('data-raw-html');
19077
+ return __assign$1({ linkUrl: href, linkText: sanitizedDOM.textContent }, (rawHTML && { rawHTML: rawHTML }));
17673
19078
  },
17674
19079
  },
17675
19080
  ],
@@ -17973,7 +19378,9 @@ var WysiwygEditor = /** @class */ (function (_super) {
17973
19378
  _this.eventEmitter.emit('setFocusedNode', state.selection.$from.node(1));
17974
19379
  },
17975
19380
  transformPastedHTML: changePastedHTML,
17976
- transformPasted: function (slice) { return changePastedSlice(slice, _this.schema); },
19381
+ transformPasted: function (slice) {
19382
+ return changePastedSlice(slice, _this.schema, isInTableNode(_this.view.state.selection.$from));
19383
+ },
17977
19384
  handlePaste: function (view, _, slice) { return pasteToTable(view, slice); },
17978
19385
  handleKeyDown: function (_, ev) {
17979
19386
  _this.eventEmitter.emit('keydown', _this.editorType, ev);
@@ -17982,8 +19389,8 @@ var WysiwygEditor = /** @class */ (function (_super) {
17982
19389
  handleDOMEvents: {
17983
19390
  paste: function (_, ev) {
17984
19391
  var clipboardData = ev.clipboardData || window.clipboardData;
17985
- var items = clipboardData && clipboardData.items;
17986
- if (items) {
19392
+ var items = clipboardData === null || clipboardData === void 0 ? void 0 : clipboardData.items;
19393
+ if ((items === null || items === void 0 ? void 0 : items.length) === 1) {
17987
19394
  var imageBlob = pasteImageOnly(items);
17988
19395
  if (imageBlob) {
17989
19396
  ev.preventDefault();
@@ -18051,7 +19458,7 @@ var WysiwygEditor = /** @class */ (function (_super) {
18051
19458
  var _a = this.view.state, tr = _a.tr, doc = _a.doc;
18052
19459
  this.view.dispatch(tr.replaceWith(0, doc.content.size, newDoc));
18053
19460
  if (cursorToEnd) {
18054
- this.moveCursorToEnd();
19461
+ this.moveCursorToEnd(true);
18055
19462
  }
18056
19463
  };
18057
19464
  WysiwygEditor.prototype.setSelection = function (start, end) {
@@ -18115,7 +19522,11 @@ var isNull = isNull_1;
18115
19522
  * @returns {boolean} Is existy?
18116
19523
  * @memberof module:type
18117
19524
  * @example
18118
- * var isExisty = require('tui-code-snippet/type/isExisty'); // node, commonjs
19525
+ * // ES6
19526
+ * import isExisty from 'tui-code-snippet/type/isExisty');
19527
+ *
19528
+ * // CommonJS
19529
+ * const isExisty = require('tui-code-snippet/type/isExisty');
18119
19530
  *
18120
19531
  * isExisty(''); //true
18121
19532
  * isExisty(0); //true
@@ -18444,6 +19855,9 @@ function isInlineNode(_a) {
18444
19855
  var type = _a.type;
18445
19856
  return includes(['text', 'strong', 'emph', 'strike', 'image', 'link', 'code'], type);
18446
19857
  }
19858
+ function isSoftbreak(mdNode) {
19859
+ return (mdNode === null || mdNode === void 0 ? void 0 : mdNode.type) === 'softbreak';
19860
+ }
18447
19861
  function isListNode(_a) {
18448
19862
  var type = _a.type, literal = _a.literal;
18449
19863
  var matched = type === 'htmlInline' && literal.match(reHTMLTag);
@@ -18462,11 +19876,15 @@ function getListItemAttrs(_a) {
18462
19876
  var checked = /data-task-checked/.test(literal);
18463
19877
  return { task: task, checked: checked };
18464
19878
  }
18465
- function getMatchedAttributeValue(rawHTML, attrName) {
19879
+ function getMatchedAttributeValue(rawHTML) {
19880
+ var attrNames = [];
19881
+ for (var _i = 1; _i < arguments.length; _i++) {
19882
+ attrNames[_i - 1] = arguments[_i];
19883
+ }
18466
19884
  var wrapper = document.createElement('div');
18467
- wrapper.innerHTML = rawHTML;
19885
+ wrapper.innerHTML = sanitizeHTML(rawHTML);
18468
19886
  var el = wrapper.firstChild;
18469
- return el.getAttribute(attrName) || '';
19887
+ return attrNames.map(function (attrName) { return el.getAttribute(attrName) || ''; });
18470
19888
  }
18471
19889
  function createConvertors(convertors) {
18472
19890
  var convertorMap = {};
@@ -18520,9 +19938,9 @@ var convertors = {
18520
19938
  var tag = node.literal;
18521
19939
  var link = state.schema.marks.link;
18522
19940
  if (openTagName) {
18523
- var linkUrl = getMatchedAttributeValue(tag, 'href');
19941
+ var linkUrl = getMatchedAttributeValue(tag, 'href')[0];
18524
19942
  state.openMark(link.create({
18525
- linkUrl: sanitizeXSSAttributeValue(linkUrl),
19943
+ linkUrl: linkUrl,
18526
19944
  rawHTML: openTagName,
18527
19945
  }));
18528
19946
  }
@@ -18532,32 +19950,42 @@ var convertors = {
18532
19950
  },
18533
19951
  img: function (state, node, openTagName) {
18534
19952
  var tag = node.literal;
18535
- var imageUrl = getMatchedAttributeValue(tag, 'src');
18536
- if (imageUrl) {
18537
- var altText = getMatchedAttributeValue(tag, 'alt');
19953
+ if (openTagName) {
19954
+ var _a = getMatchedAttributeValue(tag, 'src', 'alt'), imageUrl = _a[0], altText = _a[1];
18538
19955
  var image = state.schema.nodes.image;
18539
- state.addNode(image, __assign$1({ rawHTML: openTagName, imageUrl: sanitizeXSSAttributeValue(imageUrl) }, (altText && { altText: altText })));
19956
+ state.addNode(image, __assign$1({ rawHTML: openTagName, imageUrl: imageUrl }, (altText && { altText: altText })));
18540
19957
  }
18541
19958
  },
18542
19959
  hr: function (state, _, openTagName) {
18543
19960
  state.addNode(state.schema.nodes.thematicBreak, { rawHTML: openTagName });
18544
19961
  },
18545
19962
  br: function (state, node) {
18546
- var _a, _b;
18547
19963
  var paragraph = state.schema.nodes.paragraph;
18548
- if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.type) === 'paragraph') {
18549
- if (node.prev) {
19964
+ var parent = node.parent, prev = node.prev, next = node.next;
19965
+ if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'paragraph') {
19966
+ // should open a paragraph node when line text has only <br> tag
19967
+ // ex) first line\n\n<br>\nfourth line
19968
+ if (isSoftbreak(prev)) {
18550
19969
  state.openNode(paragraph);
18551
19970
  }
18552
- if (node.next) {
19971
+ // should close a paragraph node when line text has only <br> tag
19972
+ // ex) first line\n\n<br>\nfourth line
19973
+ if (isSoftbreak(next)) {
19974
+ state.closeNode();
19975
+ // should close a paragraph node and open a paragraph node to separate between blocks
19976
+ // when <br> tag is in the middle of the paragraph
19977
+ // ex) first <br>line\nthird line
19978
+ }
19979
+ else if (next) {
18553
19980
  state.closeNode();
19981
+ state.openNode(paragraph);
18554
19982
  }
18555
19983
  }
18556
- else if (((_b = node.parent) === null || _b === void 0 ? void 0 : _b.type) === 'tableCell') {
18557
- if (node.prev && (isInlineNode(node.prev) || isCustomHTMLInlineNode(state, node.prev))) {
19984
+ else if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'tableCell') {
19985
+ if (prev && (isInlineNode(prev) || isCustomHTMLInlineNode(state, prev))) {
18558
19986
  state.closeNode();
18559
19987
  }
18560
- if (node.next && (isInlineNode(node.next) || isCustomHTMLInlineNode(state, node.next))) {
19988
+ if (next && (isInlineNode(next) || isCustomHTMLInlineNode(state, next))) {
18561
19989
  state.openNode(paragraph);
18562
19990
  }
18563
19991
  }
@@ -18617,7 +20045,7 @@ var convertors = {
18617
20045
  var htmlToWwConvertors = createConvertors(convertors);
18618
20046
 
18619
20047
  function isBRTag(node) {
18620
- return node.type === 'htmlInline' && /<br ?\/?>/.test(node.literal);
20048
+ return node.type === 'htmlInline' && reBR.test(node.literal);
18621
20049
  }
18622
20050
  function addRawHTMLAttributeToDOM(parent) {
18623
20051
  toArray_1(parent.childNodes).forEach(function (child) {
@@ -18865,10 +20293,11 @@ var toWwConvertors = {
18865
20293
  var openTagName = matched[1], closeTagName = matched[3];
18866
20294
  var typeName = (openTagName || closeTagName).toLowerCase();
18867
20295
  var markType = state.schema.marks[typeName];
20296
+ var sanitizedHTML = sanitizeHTML(html);
18868
20297
  // for user defined html schema
18869
20298
  if (markType === null || markType === void 0 ? void 0 : markType.spec.attrs.htmlInline) {
18870
20299
  if (openTagName) {
18871
- var htmlAttrs = getHTMLAttrsByHTMLString(html);
20300
+ var htmlAttrs = getHTMLAttrsByHTMLString(sanitizedHTML);
18872
20301
  state.openMark(markType.create({ htmlAttrs: htmlAttrs }));
18873
20302
  }
18874
20303
  else {
@@ -18889,14 +20318,15 @@ var toWwConvertors = {
18889
20318
  var openTagName = matched[1], closeTagName = matched[3];
18890
20319
  var typeName = (openTagName || closeTagName).toLowerCase();
18891
20320
  var nodeType = state.schema.nodes[typeName];
20321
+ var sanitizedHTML = sanitizeHTML(html);
18892
20322
  // for user defined html schema
18893
20323
  if (nodeType === null || nodeType === void 0 ? void 0 : nodeType.spec.attrs.htmlBlock) {
18894
- var htmlAttrs = getHTMLAttrsByHTMLString(html);
20324
+ var htmlAttrs = getHTMLAttrsByHTMLString(sanitizedHTML);
18895
20325
  var childrenHTML = getChildrenHTML(node, typeName);
18896
20326
  state.addNode(nodeType, { htmlAttrs: htmlAttrs, childrenHTML: childrenHTML });
18897
20327
  }
18898
20328
  else {
18899
- container.innerHTML = html;
20329
+ container.innerHTML = sanitizedHTML;
18900
20330
  addRawHTMLAttributeToDOM(container);
18901
20331
  state.convertByDOMParser(container);
18902
20332
  }
@@ -19007,6 +20437,27 @@ var ToWwConvertorState = /** @class */ (function () {
19007
20437
  var doc = DOMParser.fromSchema(this.schema).parse(root);
19008
20438
  doc.content.forEach(function (node) { return _this.push(node); });
19009
20439
  };
20440
+ ToWwConvertorState.prototype.closeUnmatchedHTMLInline = function (node, entering) {
20441
+ var _a;
20442
+ if (!entering && node.type !== 'htmlInline') {
20443
+ var length_1 = this.stack.length - 1;
20444
+ for (var i = length_1; i >= 0; i -= 1) {
20445
+ var nodeInfo = this.stack[i];
20446
+ if ((_a = nodeInfo.attrs) === null || _a === void 0 ? void 0 : _a.rawHTML) {
20447
+ if (nodeInfo.content.length) {
20448
+ this.closeNode();
20449
+ }
20450
+ else {
20451
+ // just pop useless unmatched html inline node
20452
+ this.stack.pop();
20453
+ }
20454
+ }
20455
+ else {
20456
+ break;
20457
+ }
20458
+ }
20459
+ }
20460
+ };
19010
20461
  ToWwConvertorState.prototype.convert = function (mdNode, infoForPosSync) {
19011
20462
  var walker = mdNode.walker();
19012
20463
  var event = walker.next();
@@ -19024,6 +20475,7 @@ var ToWwConvertorState = /** @class */ (function () {
19024
20475
  skipped = true;
19025
20476
  },
19026
20477
  };
20478
+ this_1.closeUnmatchedHTMLInline(node, entering);
19027
20479
  convertor(this_1, node, context);
19028
20480
  if ((infoForPosSync === null || infoForPosSync === void 0 ? void 0 : infoForPosSync.node) === node) {
19029
20481
  var pos = this_1.stack.reduce(function (nodeSize, stackItem) {
@@ -19705,11 +21157,11 @@ var ToMdConvertorState = /** @class */ (function () {
19705
21157
  this.closed = node;
19706
21158
  };
19707
21159
  ToMdConvertorState.prototype.text = function (text, escaped) {
21160
+ if (escaped === void 0) { escaped = true; }
19708
21161
  var lines = text.split('\n');
19709
21162
  for (var i = 0; i < lines.length; i += 1) {
19710
- var startOfLine = this.isInBlank() || !!this.closed;
19711
21163
  this.write();
19712
- this.result += escaped !== false ? escape$1(lines[i], startOfLine) : lines[i];
21164
+ this.result += escaped ? escape$1(lines[i]) : lines[i];
19713
21165
  if (i !== lines.length - 1) {
19714
21166
  this.result += '\n';
19715
21167
  }
@@ -19989,6 +21441,14 @@ function getPluginInfo(plugins, eventEmitter, usageStatistics) {
19989
21441
  var TASK_ATTR_NAME = 'data-task';
19990
21442
  var DISABLED_TASK_ATTR_NAME = 'data-task-disabled';
19991
21443
  var TASK_CHECKED_CLASS_NAME = 'checked';
21444
+ function registerHTMLTagToWhitelist(convertorMap) {
21445
+ ['htmlBlock', 'htmlInline'].forEach(function (htmlType) {
21446
+ if (convertorMap[htmlType]) {
21447
+ // register tag white list for preventing to remove the html in sanitizer
21448
+ Object.keys(convertorMap[htmlType]).forEach(function (type) { return registerTagWhitelistIfPossible(type); });
21449
+ }
21450
+ });
21451
+ }
19992
21452
  /**
19993
21453
  * Class ToastUIEditorViewer
19994
21454
  * @param {object} options Option object
@@ -20034,6 +21494,7 @@ var ToastUIEditorViewer = /** @class */ (function () {
20034
21494
  frontMatter: frontMatter,
20035
21495
  sanitizer: customHTMLSanitizer || sanitizeHTML,
20036
21496
  };
21497
+ registerHTMLTagToWhitelist(rendererOptions.customHTMLRenderer);
20037
21498
  if (this.options.events) {
20038
21499
  forEachOwnProperties_1(this.options.events, function (fn, key) {
20039
21500
  _this.on(key, fn);
@@ -20507,11 +21968,12 @@ var ScrollSync = /** @class */ (function () {
20507
21968
  * @param {boolean} [options.frontMatter=false] - whether use the front matter
20508
21969
  * @param {Array.<object>} [options.widgetRules=[]] - The rules for replacing the text with widget node
20509
21970
  * @param {string} [options.theme] - The theme to style the editor with. The default is included in toastui-editor.css.
21971
+ * @param {autofocus} [options.autofocus=true] - automatically focus the editor on creation.
20510
21972
  */
20511
21973
  var ToastUIEditorCore = /** @class */ (function () {
20512
21974
  function ToastUIEditorCore(options) {
20513
21975
  var _this = this;
20514
- this.initialHtml = options.el.innerHTML;
21976
+ this.initialHTML = options.el.innerHTML;
20515
21977
  options.el.innerHTML = '';
20516
21978
  this.options = extend_1({
20517
21979
  previewStyle: 'tab',
@@ -20540,10 +22002,13 @@ var ToastUIEditorCore = /** @class */ (function () {
20540
22002
  frontMatter: false,
20541
22003
  widgetRules: [],
20542
22004
  theme: 'light',
22005
+ autofocus: true,
20543
22006
  }, options);
20544
22007
  var _a = this.options, customHTMLRenderer = _a.customHTMLRenderer, extendedAutolinks = _a.extendedAutolinks, referenceDefinition = _a.referenceDefinition, frontMatter = _a.frontMatter, customMarkdownRenderer = _a.customMarkdownRenderer, useCommandShortcut = _a.useCommandShortcut, initialEditType = _a.initialEditType, widgetRules = _a.widgetRules, customHTMLSanitizer = _a.customHTMLSanitizer;
20545
22008
  this.mode = initialEditType || 'markdown';
20546
22009
  this.mdPreviewStyle = this.options.previewStyle;
22010
+ this.i18n = i18n;
22011
+ this.i18n.setCode(this.options.language);
20547
22012
  this.eventEmitter = new EventEmitter();
20548
22013
  setWidgetRules(widgetRules);
20549
22014
  var linkAttributes = sanitizeLinkAttribute(this.options.linkAttributes);
@@ -20559,8 +22024,6 @@ var ToastUIEditorCore = /** @class */ (function () {
20559
22024
  };
20560
22025
  var wwToDOMAdaptor = new WwToDOMAdaptor(linkAttributes, rendererOptions.customHTMLRenderer);
20561
22026
  var htmlSchemaMap = createHTMLSchemaMap(rendererOptions.customHTMLRenderer, rendererOptions.sanitizer, wwToDOMAdaptor);
20562
- this.i18n = i18n;
20563
- this.i18n.setCode(this.options.language);
20564
22027
  this.toastMark = new ToastMark('', {
20565
22028
  disallowedHtmlBlockTags: ['br', 'img'],
20566
22029
  extendedAutolinks: extendedAutolinks,
@@ -20591,7 +22054,7 @@ var ToastUIEditorCore = /** @class */ (function () {
20591
22054
  this.setPlaceholder(this.options.placeholder);
20592
22055
  }
20593
22056
  if (!this.options.initialValue) {
20594
- this.setHTML(this.initialHtml, false);
22057
+ this.setHTML(this.initialHTML, false);
20595
22058
  }
20596
22059
  this.commandManager = new CommandManager(this.eventEmitter, this.mdEditor.commands, this.wwEditor.commands, function () { return _this.mode; });
20597
22060
  if (this.options.usageStatistics) {
@@ -20607,7 +22070,7 @@ var ToastUIEditorCore = /** @class */ (function () {
20607
22070
  forEachOwnProperties_1(this.options.events, function (fn, key) { return _this.on(key, fn); });
20608
22071
  }
20609
22072
  this.eventEmitter.emit('load', this);
20610
- this.moveCursorToStart();
22073
+ this.moveCursorToStart(this.options.autofocus);
20611
22074
  }
20612
22075
  ToastUIEditorCore.prototype.addInitEvent = function () {
20613
22076
  this.on('needChangeMode', this.changeMode.bind(this));
@@ -20723,15 +22186,19 @@ var ToastUIEditorCore = /** @class */ (function () {
20723
22186
  };
20724
22187
  /**
20725
22188
  * Set cursor position to end
22189
+ * @param {boolean} [focus] - automatically focus the editor
20726
22190
  */
20727
- ToastUIEditorCore.prototype.moveCursorToEnd = function () {
20728
- this.getCurrentModeEditor().moveCursorToEnd();
22191
+ ToastUIEditorCore.prototype.moveCursorToEnd = function (focus) {
22192
+ if (focus === void 0) { focus = true; }
22193
+ this.getCurrentModeEditor().moveCursorToEnd(focus);
20729
22194
  };
20730
22195
  /**
20731
22196
  * Set cursor position to start
22197
+ * @param {boolean} [focus] - automatically focus the editor
20732
22198
  */
20733
- ToastUIEditorCore.prototype.moveCursorToStart = function () {
20734
- this.getCurrentModeEditor().moveCursorToStart();
22199
+ ToastUIEditorCore.prototype.moveCursorToStart = function (focus) {
22200
+ if (focus === void 0) { focus = true; }
22201
+ this.getCurrentModeEditor().moveCursorToStart(focus);
20735
22202
  };
20736
22203
  /**
20737
22204
  * Set markdown syntax text.
@@ -20784,16 +22251,13 @@ var ToastUIEditorCore = /** @class */ (function () {
20784
22251
  ToastUIEditorCore.prototype.getHTML = function () {
20785
22252
  var _this = this;
20786
22253
  this.eventEmitter.holdEventInvoke(function () {
20787
- if (_this.isWysiwygMode()) {
20788
- _this.mdEditor.setMarkdown(_this.convertor.toMarkdownText(_this.wwEditor.getModel()));
22254
+ if (_this.isMarkdownMode()) {
22255
+ var mdNode = _this.toastMark.getRootNode();
22256
+ var wwNode = _this.convertor.toWysiwygModel(mdNode);
22257
+ _this.wwEditor.setModel(wwNode);
20789
22258
  }
20790
22259
  });
20791
- var mdNode = this.toastMark.getRootNode();
20792
- var mdRenderer = this.preview.getRenderer();
20793
- return mdRenderer
20794
- .render(mdNode)
20795
- .replace(/\sdata-nodeid="\d{1,}"/g, '')
20796
- .trim();
22260
+ return this.wwEditor.view.dom.innerHTML;
20797
22261
  };
20798
22262
  /**
20799
22263
  * Insert text
@@ -21600,11 +23064,15 @@ var templateObject_1$h;
21600
23064
  * @returns {function} debounced function.
21601
23065
  * @memberof module:tricks
21602
23066
  * @example
21603
- * var debounce = require('tui-code-snippet/tricks/debounce'); // node, commonjs
23067
+ * // ES6
23068
+ * import debounce from 'tui-code-snippet/tricks/debounce';
23069
+ *
23070
+ * // CommonJS
23071
+ * const debounce = require('tui-code-snippet/tricks/debounce');
21604
23072
  *
21605
23073
  * function someMethodToInvokeDebounced() {}
21606
23074
  *
21607
- * var debounced = debounce(someMethodToInvokeDebounced, 300);
23075
+ * const debounced = debounce(someMethodToInvokeDebounced, 300);
21608
23076
  *
21609
23077
  * // invoke repeatedly
21610
23078
  * debounced();
@@ -21652,11 +23120,15 @@ var debounce = debounce_1;
21652
23120
  * @returns {function} throttled function
21653
23121
  * @memberof module:tricks
21654
23122
  * @example
21655
- * var throttle = require('tui-code-snippet/tricks/throttle'); // node, commonjs
23123
+ * // ES6
23124
+ * import throttle from 'tui-code-snippet/tricks/throttle';
23125
+ *
23126
+ * // CommonJS
23127
+ * const throttle = require('tui-code-snippet/tricks/throttle');
21656
23128
  *
21657
23129
  * function someMethodToInvokeThrottled() {}
21658
23130
  *
21659
- * var throttled = throttle(someMethodToInvokeThrottled, 300);
23131
+ * const throttled = throttle(someMethodToInvokeThrottled, 300);
21660
23132
  *
21661
23133
  * // invoke repeatedly
21662
23134
  * throttled(); // invoke (leading)
@@ -21671,7 +23143,7 @@ var debounce = debounce_1;
21671
23143
  * // if you need reuse throttled method. then invoke reset()
21672
23144
  * throttled.reset();
21673
23145
  */
21674
- function throttle(fn, interval) {
23146
+ function throttle$1(fn, interval) {
21675
23147
  var base;
21676
23148
  var isLeading = true;
21677
23149
  var tick = function(_args) {
@@ -21721,7 +23193,934 @@ function throttle(fn, interval) {
21721
23193
  return throttled;
21722
23194
  }
21723
23195
 
21724
- var throttle_1 = throttle;
23196
+ var throttle_1 = throttle$1;
23197
+
23198
+ /**
23199
+ * A collection of shims that provide minimal functionality of the ES6 collections.
23200
+ *
23201
+ * These implementations are not meant to be used outside of the ResizeObserver
23202
+ * modules as they cover only a limited range of use cases.
23203
+ */
23204
+ /* eslint-disable require-jsdoc, valid-jsdoc */
23205
+ var MapShim = (function () {
23206
+ if (typeof Map !== 'undefined') {
23207
+ return Map;
23208
+ }
23209
+ /**
23210
+ * Returns index in provided array that matches the specified key.
23211
+ *
23212
+ * @param {Array<Array>} arr
23213
+ * @param {*} key
23214
+ * @returns {number}
23215
+ */
23216
+ function getIndex(arr, key) {
23217
+ var result = -1;
23218
+ arr.some(function (entry, index) {
23219
+ if (entry[0] === key) {
23220
+ result = index;
23221
+ return true;
23222
+ }
23223
+ return false;
23224
+ });
23225
+ return result;
23226
+ }
23227
+ return /** @class */ (function () {
23228
+ function class_1() {
23229
+ this.__entries__ = [];
23230
+ }
23231
+ Object.defineProperty(class_1.prototype, "size", {
23232
+ /**
23233
+ * @returns {boolean}
23234
+ */
23235
+ get: function () {
23236
+ return this.__entries__.length;
23237
+ },
23238
+ enumerable: true,
23239
+ configurable: true
23240
+ });
23241
+ /**
23242
+ * @param {*} key
23243
+ * @returns {*}
23244
+ */
23245
+ class_1.prototype.get = function (key) {
23246
+ var index = getIndex(this.__entries__, key);
23247
+ var entry = this.__entries__[index];
23248
+ return entry && entry[1];
23249
+ };
23250
+ /**
23251
+ * @param {*} key
23252
+ * @param {*} value
23253
+ * @returns {void}
23254
+ */
23255
+ class_1.prototype.set = function (key, value) {
23256
+ var index = getIndex(this.__entries__, key);
23257
+ if (~index) {
23258
+ this.__entries__[index][1] = value;
23259
+ }
23260
+ else {
23261
+ this.__entries__.push([key, value]);
23262
+ }
23263
+ };
23264
+ /**
23265
+ * @param {*} key
23266
+ * @returns {void}
23267
+ */
23268
+ class_1.prototype.delete = function (key) {
23269
+ var entries = this.__entries__;
23270
+ var index = getIndex(entries, key);
23271
+ if (~index) {
23272
+ entries.splice(index, 1);
23273
+ }
23274
+ };
23275
+ /**
23276
+ * @param {*} key
23277
+ * @returns {void}
23278
+ */
23279
+ class_1.prototype.has = function (key) {
23280
+ return !!~getIndex(this.__entries__, key);
23281
+ };
23282
+ /**
23283
+ * @returns {void}
23284
+ */
23285
+ class_1.prototype.clear = function () {
23286
+ this.__entries__.splice(0);
23287
+ };
23288
+ /**
23289
+ * @param {Function} callback
23290
+ * @param {*} [ctx=null]
23291
+ * @returns {void}
23292
+ */
23293
+ class_1.prototype.forEach = function (callback, ctx) {
23294
+ if (ctx === void 0) { ctx = null; }
23295
+ for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {
23296
+ var entry = _a[_i];
23297
+ callback.call(ctx, entry[1], entry[0]);
23298
+ }
23299
+ };
23300
+ return class_1;
23301
+ }());
23302
+ })();
23303
+
23304
+ /**
23305
+ * Detects whether window and document objects are available in current environment.
23306
+ */
23307
+ var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;
23308
+
23309
+ // Returns global object of a current environment.
23310
+ var global$1 = (function () {
23311
+ if (typeof global !== 'undefined' && global.Math === Math) {
23312
+ return global;
23313
+ }
23314
+ if (typeof self !== 'undefined' && self.Math === Math) {
23315
+ return self;
23316
+ }
23317
+ if (typeof window !== 'undefined' && window.Math === Math) {
23318
+ return window;
23319
+ }
23320
+ // eslint-disable-next-line no-new-func
23321
+ return Function('return this')();
23322
+ })();
23323
+
23324
+ /**
23325
+ * A shim for the requestAnimationFrame which falls back to the setTimeout if
23326
+ * first one is not supported.
23327
+ *
23328
+ * @returns {number} Requests' identifier.
23329
+ */
23330
+ var requestAnimationFrame$1 = (function () {
23331
+ if (typeof requestAnimationFrame === 'function') {
23332
+ // It's required to use a bounded function because IE sometimes throws
23333
+ // an "Invalid calling object" error if rAF is invoked without the global
23334
+ // object on the left hand side.
23335
+ return requestAnimationFrame.bind(global$1);
23336
+ }
23337
+ return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };
23338
+ })();
23339
+
23340
+ // Defines minimum timeout before adding a trailing call.
23341
+ var trailingTimeout = 2;
23342
+ /**
23343
+ * Creates a wrapper function which ensures that provided callback will be
23344
+ * invoked only once during the specified delay period.
23345
+ *
23346
+ * @param {Function} callback - Function to be invoked after the delay period.
23347
+ * @param {number} delay - Delay after which to invoke callback.
23348
+ * @returns {Function}
23349
+ */
23350
+ function throttle (callback, delay) {
23351
+ var leadingCall = false, trailingCall = false, lastCallTime = 0;
23352
+ /**
23353
+ * Invokes the original callback function and schedules new invocation if
23354
+ * the "proxy" was called during current request.
23355
+ *
23356
+ * @returns {void}
23357
+ */
23358
+ function resolvePending() {
23359
+ if (leadingCall) {
23360
+ leadingCall = false;
23361
+ callback();
23362
+ }
23363
+ if (trailingCall) {
23364
+ proxy();
23365
+ }
23366
+ }
23367
+ /**
23368
+ * Callback invoked after the specified delay. It will further postpone
23369
+ * invocation of the original function delegating it to the
23370
+ * requestAnimationFrame.
23371
+ *
23372
+ * @returns {void}
23373
+ */
23374
+ function timeoutCallback() {
23375
+ requestAnimationFrame$1(resolvePending);
23376
+ }
23377
+ /**
23378
+ * Schedules invocation of the original function.
23379
+ *
23380
+ * @returns {void}
23381
+ */
23382
+ function proxy() {
23383
+ var timeStamp = Date.now();
23384
+ if (leadingCall) {
23385
+ // Reject immediately following calls.
23386
+ if (timeStamp - lastCallTime < trailingTimeout) {
23387
+ return;
23388
+ }
23389
+ // Schedule new call to be in invoked when the pending one is resolved.
23390
+ // This is important for "transitions" which never actually start
23391
+ // immediately so there is a chance that we might miss one if change
23392
+ // happens amids the pending invocation.
23393
+ trailingCall = true;
23394
+ }
23395
+ else {
23396
+ leadingCall = true;
23397
+ trailingCall = false;
23398
+ setTimeout(timeoutCallback, delay);
23399
+ }
23400
+ lastCallTime = timeStamp;
23401
+ }
23402
+ return proxy;
23403
+ }
23404
+
23405
+ // Minimum delay before invoking the update of observers.
23406
+ var REFRESH_DELAY = 20;
23407
+ // A list of substrings of CSS properties used to find transition events that
23408
+ // might affect dimensions of observed elements.
23409
+ var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];
23410
+ // Check if MutationObserver is available.
23411
+ var mutationObserverSupported = typeof MutationObserver !== 'undefined';
23412
+ /**
23413
+ * Singleton controller class which handles updates of ResizeObserver instances.
23414
+ */
23415
+ var ResizeObserverController = /** @class */ (function () {
23416
+ /**
23417
+ * Creates a new instance of ResizeObserverController.
23418
+ *
23419
+ * @private
23420
+ */
23421
+ function ResizeObserverController() {
23422
+ /**
23423
+ * Indicates whether DOM listeners have been added.
23424
+ *
23425
+ * @private {boolean}
23426
+ */
23427
+ this.connected_ = false;
23428
+ /**
23429
+ * Tells that controller has subscribed for Mutation Events.
23430
+ *
23431
+ * @private {boolean}
23432
+ */
23433
+ this.mutationEventsAdded_ = false;
23434
+ /**
23435
+ * Keeps reference to the instance of MutationObserver.
23436
+ *
23437
+ * @private {MutationObserver}
23438
+ */
23439
+ this.mutationsObserver_ = null;
23440
+ /**
23441
+ * A list of connected observers.
23442
+ *
23443
+ * @private {Array<ResizeObserverSPI>}
23444
+ */
23445
+ this.observers_ = [];
23446
+ this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);
23447
+ this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);
23448
+ }
23449
+ /**
23450
+ * Adds observer to observers list.
23451
+ *
23452
+ * @param {ResizeObserverSPI} observer - Observer to be added.
23453
+ * @returns {void}
23454
+ */
23455
+ ResizeObserverController.prototype.addObserver = function (observer) {
23456
+ if (!~this.observers_.indexOf(observer)) {
23457
+ this.observers_.push(observer);
23458
+ }
23459
+ // Add listeners if they haven't been added yet.
23460
+ if (!this.connected_) {
23461
+ this.connect_();
23462
+ }
23463
+ };
23464
+ /**
23465
+ * Removes observer from observers list.
23466
+ *
23467
+ * @param {ResizeObserverSPI} observer - Observer to be removed.
23468
+ * @returns {void}
23469
+ */
23470
+ ResizeObserverController.prototype.removeObserver = function (observer) {
23471
+ var observers = this.observers_;
23472
+ var index = observers.indexOf(observer);
23473
+ // Remove observer if it's present in registry.
23474
+ if (~index) {
23475
+ observers.splice(index, 1);
23476
+ }
23477
+ // Remove listeners if controller has no connected observers.
23478
+ if (!observers.length && this.connected_) {
23479
+ this.disconnect_();
23480
+ }
23481
+ };
23482
+ /**
23483
+ * Invokes the update of observers. It will continue running updates insofar
23484
+ * it detects changes.
23485
+ *
23486
+ * @returns {void}
23487
+ */
23488
+ ResizeObserverController.prototype.refresh = function () {
23489
+ var changesDetected = this.updateObservers_();
23490
+ // Continue running updates if changes have been detected as there might
23491
+ // be future ones caused by CSS transitions.
23492
+ if (changesDetected) {
23493
+ this.refresh();
23494
+ }
23495
+ };
23496
+ /**
23497
+ * Updates every observer from observers list and notifies them of queued
23498
+ * entries.
23499
+ *
23500
+ * @private
23501
+ * @returns {boolean} Returns "true" if any observer has detected changes in
23502
+ * dimensions of it's elements.
23503
+ */
23504
+ ResizeObserverController.prototype.updateObservers_ = function () {
23505
+ // Collect observers that have active observations.
23506
+ var activeObservers = this.observers_.filter(function (observer) {
23507
+ return observer.gatherActive(), observer.hasActive();
23508
+ });
23509
+ // Deliver notifications in a separate cycle in order to avoid any
23510
+ // collisions between observers, e.g. when multiple instances of
23511
+ // ResizeObserver are tracking the same element and the callback of one
23512
+ // of them changes content dimensions of the observed target. Sometimes
23513
+ // this may result in notifications being blocked for the rest of observers.
23514
+ activeObservers.forEach(function (observer) { return observer.broadcastActive(); });
23515
+ return activeObservers.length > 0;
23516
+ };
23517
+ /**
23518
+ * Initializes DOM listeners.
23519
+ *
23520
+ * @private
23521
+ * @returns {void}
23522
+ */
23523
+ ResizeObserverController.prototype.connect_ = function () {
23524
+ // Do nothing if running in a non-browser environment or if listeners
23525
+ // have been already added.
23526
+ if (!isBrowser || this.connected_) {
23527
+ return;
23528
+ }
23529
+ // Subscription to the "Transitionend" event is used as a workaround for
23530
+ // delayed transitions. This way it's possible to capture at least the
23531
+ // final state of an element.
23532
+ document.addEventListener('transitionend', this.onTransitionEnd_);
23533
+ window.addEventListener('resize', this.refresh);
23534
+ if (mutationObserverSupported) {
23535
+ this.mutationsObserver_ = new MutationObserver(this.refresh);
23536
+ this.mutationsObserver_.observe(document, {
23537
+ attributes: true,
23538
+ childList: true,
23539
+ characterData: true,
23540
+ subtree: true
23541
+ });
23542
+ }
23543
+ else {
23544
+ document.addEventListener('DOMSubtreeModified', this.refresh);
23545
+ this.mutationEventsAdded_ = true;
23546
+ }
23547
+ this.connected_ = true;
23548
+ };
23549
+ /**
23550
+ * Removes DOM listeners.
23551
+ *
23552
+ * @private
23553
+ * @returns {void}
23554
+ */
23555
+ ResizeObserverController.prototype.disconnect_ = function () {
23556
+ // Do nothing if running in a non-browser environment or if listeners
23557
+ // have been already removed.
23558
+ if (!isBrowser || !this.connected_) {
23559
+ return;
23560
+ }
23561
+ document.removeEventListener('transitionend', this.onTransitionEnd_);
23562
+ window.removeEventListener('resize', this.refresh);
23563
+ if (this.mutationsObserver_) {
23564
+ this.mutationsObserver_.disconnect();
23565
+ }
23566
+ if (this.mutationEventsAdded_) {
23567
+ document.removeEventListener('DOMSubtreeModified', this.refresh);
23568
+ }
23569
+ this.mutationsObserver_ = null;
23570
+ this.mutationEventsAdded_ = false;
23571
+ this.connected_ = false;
23572
+ };
23573
+ /**
23574
+ * "Transitionend" event handler.
23575
+ *
23576
+ * @private
23577
+ * @param {TransitionEvent} event
23578
+ * @returns {void}
23579
+ */
23580
+ ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {
23581
+ var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;
23582
+ // Detect whether transition may affect dimensions of an element.
23583
+ var isReflowProperty = transitionKeys.some(function (key) {
23584
+ return !!~propertyName.indexOf(key);
23585
+ });
23586
+ if (isReflowProperty) {
23587
+ this.refresh();
23588
+ }
23589
+ };
23590
+ /**
23591
+ * Returns instance of the ResizeObserverController.
23592
+ *
23593
+ * @returns {ResizeObserverController}
23594
+ */
23595
+ ResizeObserverController.getInstance = function () {
23596
+ if (!this.instance_) {
23597
+ this.instance_ = new ResizeObserverController();
23598
+ }
23599
+ return this.instance_;
23600
+ };
23601
+ /**
23602
+ * Holds reference to the controller's instance.
23603
+ *
23604
+ * @private {ResizeObserverController}
23605
+ */
23606
+ ResizeObserverController.instance_ = null;
23607
+ return ResizeObserverController;
23608
+ }());
23609
+
23610
+ /**
23611
+ * Defines non-writable/enumerable properties of the provided target object.
23612
+ *
23613
+ * @param {Object} target - Object for which to define properties.
23614
+ * @param {Object} props - Properties to be defined.
23615
+ * @returns {Object} Target object.
23616
+ */
23617
+ var defineConfigurable = (function (target, props) {
23618
+ for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
23619
+ var key = _a[_i];
23620
+ Object.defineProperty(target, key, {
23621
+ value: props[key],
23622
+ enumerable: false,
23623
+ writable: false,
23624
+ configurable: true
23625
+ });
23626
+ }
23627
+ return target;
23628
+ });
23629
+
23630
+ /**
23631
+ * Returns the global object associated with provided element.
23632
+ *
23633
+ * @param {Object} target
23634
+ * @returns {Object}
23635
+ */
23636
+ var getWindowOf = (function (target) {
23637
+ // Assume that the element is an instance of Node, which means that it
23638
+ // has the "ownerDocument" property from which we can retrieve a
23639
+ // corresponding global object.
23640
+ var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;
23641
+ // Return the local global object if it's not possible extract one from
23642
+ // provided element.
23643
+ return ownerGlobal || global$1;
23644
+ });
23645
+
23646
+ // Placeholder of an empty content rectangle.
23647
+ var emptyRect = createRectInit(0, 0, 0, 0);
23648
+ /**
23649
+ * Converts provided string to a number.
23650
+ *
23651
+ * @param {number|string} value
23652
+ * @returns {number}
23653
+ */
23654
+ function toFloat(value) {
23655
+ return parseFloat(value) || 0;
23656
+ }
23657
+ /**
23658
+ * Extracts borders size from provided styles.
23659
+ *
23660
+ * @param {CSSStyleDeclaration} styles
23661
+ * @param {...string} positions - Borders positions (top, right, ...)
23662
+ * @returns {number}
23663
+ */
23664
+ function getBordersSize(styles) {
23665
+ var positions = [];
23666
+ for (var _i = 1; _i < arguments.length; _i++) {
23667
+ positions[_i - 1] = arguments[_i];
23668
+ }
23669
+ return positions.reduce(function (size, position) {
23670
+ var value = styles['border-' + position + '-width'];
23671
+ return size + toFloat(value);
23672
+ }, 0);
23673
+ }
23674
+ /**
23675
+ * Extracts paddings sizes from provided styles.
23676
+ *
23677
+ * @param {CSSStyleDeclaration} styles
23678
+ * @returns {Object} Paddings box.
23679
+ */
23680
+ function getPaddings(styles) {
23681
+ var positions = ['top', 'right', 'bottom', 'left'];
23682
+ var paddings = {};
23683
+ for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
23684
+ var position = positions_1[_i];
23685
+ var value = styles['padding-' + position];
23686
+ paddings[position] = toFloat(value);
23687
+ }
23688
+ return paddings;
23689
+ }
23690
+ /**
23691
+ * Calculates content rectangle of provided SVG element.
23692
+ *
23693
+ * @param {SVGGraphicsElement} target - Element content rectangle of which needs
23694
+ * to be calculated.
23695
+ * @returns {DOMRectInit}
23696
+ */
23697
+ function getSVGContentRect(target) {
23698
+ var bbox = target.getBBox();
23699
+ return createRectInit(0, 0, bbox.width, bbox.height);
23700
+ }
23701
+ /**
23702
+ * Calculates content rectangle of provided HTMLElement.
23703
+ *
23704
+ * @param {HTMLElement} target - Element for which to calculate the content rectangle.
23705
+ * @returns {DOMRectInit}
23706
+ */
23707
+ function getHTMLElementContentRect(target) {
23708
+ // Client width & height properties can't be
23709
+ // used exclusively as they provide rounded values.
23710
+ var clientWidth = target.clientWidth, clientHeight = target.clientHeight;
23711
+ // By this condition we can catch all non-replaced inline, hidden and
23712
+ // detached elements. Though elements with width & height properties less
23713
+ // than 0.5 will be discarded as well.
23714
+ //
23715
+ // Without it we would need to implement separate methods for each of
23716
+ // those cases and it's not possible to perform a precise and performance
23717
+ // effective test for hidden elements. E.g. even jQuery's ':visible' filter
23718
+ // gives wrong results for elements with width & height less than 0.5.
23719
+ if (!clientWidth && !clientHeight) {
23720
+ return emptyRect;
23721
+ }
23722
+ var styles = getWindowOf(target).getComputedStyle(target);
23723
+ var paddings = getPaddings(styles);
23724
+ var horizPad = paddings.left + paddings.right;
23725
+ var vertPad = paddings.top + paddings.bottom;
23726
+ // Computed styles of width & height are being used because they are the
23727
+ // only dimensions available to JS that contain non-rounded values. It could
23728
+ // be possible to utilize the getBoundingClientRect if only it's data wasn't
23729
+ // affected by CSS transformations let alone paddings, borders and scroll bars.
23730
+ var width = toFloat(styles.width), height = toFloat(styles.height);
23731
+ // Width & height include paddings and borders when the 'border-box' box
23732
+ // model is applied (except for IE).
23733
+ if (styles.boxSizing === 'border-box') {
23734
+ // Following conditions are required to handle Internet Explorer which
23735
+ // doesn't include paddings and borders to computed CSS dimensions.
23736
+ //
23737
+ // We can say that if CSS dimensions + paddings are equal to the "client"
23738
+ // properties then it's either IE, and thus we don't need to subtract
23739
+ // anything, or an element merely doesn't have paddings/borders styles.
23740
+ if (Math.round(width + horizPad) !== clientWidth) {
23741
+ width -= getBordersSize(styles, 'left', 'right') + horizPad;
23742
+ }
23743
+ if (Math.round(height + vertPad) !== clientHeight) {
23744
+ height -= getBordersSize(styles, 'top', 'bottom') + vertPad;
23745
+ }
23746
+ }
23747
+ // Following steps can't be applied to the document's root element as its
23748
+ // client[Width/Height] properties represent viewport area of the window.
23749
+ // Besides, it's as well not necessary as the <html> itself neither has
23750
+ // rendered scroll bars nor it can be clipped.
23751
+ if (!isDocumentElement(target)) {
23752
+ // In some browsers (only in Firefox, actually) CSS width & height
23753
+ // include scroll bars size which can be removed at this step as scroll
23754
+ // bars are the only difference between rounded dimensions + paddings
23755
+ // and "client" properties, though that is not always true in Chrome.
23756
+ var vertScrollbar = Math.round(width + horizPad) - clientWidth;
23757
+ var horizScrollbar = Math.round(height + vertPad) - clientHeight;
23758
+ // Chrome has a rather weird rounding of "client" properties.
23759
+ // E.g. for an element with content width of 314.2px it sometimes gives
23760
+ // the client width of 315px and for the width of 314.7px it may give
23761
+ // 314px. And it doesn't happen all the time. So just ignore this delta
23762
+ // as a non-relevant.
23763
+ if (Math.abs(vertScrollbar) !== 1) {
23764
+ width -= vertScrollbar;
23765
+ }
23766
+ if (Math.abs(horizScrollbar) !== 1) {
23767
+ height -= horizScrollbar;
23768
+ }
23769
+ }
23770
+ return createRectInit(paddings.left, paddings.top, width, height);
23771
+ }
23772
+ /**
23773
+ * Checks whether provided element is an instance of the SVGGraphicsElement.
23774
+ *
23775
+ * @param {Element} target - Element to be checked.
23776
+ * @returns {boolean}
23777
+ */
23778
+ var isSVGGraphicsElement = (function () {
23779
+ // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement
23780
+ // interface.
23781
+ if (typeof SVGGraphicsElement !== 'undefined') {
23782
+ return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };
23783
+ }
23784
+ // If it's so, then check that element is at least an instance of the
23785
+ // SVGElement and that it has the "getBBox" method.
23786
+ // eslint-disable-next-line no-extra-parens
23787
+ return function (target) { return (target instanceof getWindowOf(target).SVGElement &&
23788
+ typeof target.getBBox === 'function'); };
23789
+ })();
23790
+ /**
23791
+ * Checks whether provided element is a document element (<html>).
23792
+ *
23793
+ * @param {Element} target - Element to be checked.
23794
+ * @returns {boolean}
23795
+ */
23796
+ function isDocumentElement(target) {
23797
+ return target === getWindowOf(target).document.documentElement;
23798
+ }
23799
+ /**
23800
+ * Calculates an appropriate content rectangle for provided html or svg element.
23801
+ *
23802
+ * @param {Element} target - Element content rectangle of which needs to be calculated.
23803
+ * @returns {DOMRectInit}
23804
+ */
23805
+ function getContentRect(target) {
23806
+ if (!isBrowser) {
23807
+ return emptyRect;
23808
+ }
23809
+ if (isSVGGraphicsElement(target)) {
23810
+ return getSVGContentRect(target);
23811
+ }
23812
+ return getHTMLElementContentRect(target);
23813
+ }
23814
+ /**
23815
+ * Creates rectangle with an interface of the DOMRectReadOnly.
23816
+ * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly
23817
+ *
23818
+ * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.
23819
+ * @returns {DOMRectReadOnly}
23820
+ */
23821
+ function createReadOnlyRect(_a) {
23822
+ var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
23823
+ // If DOMRectReadOnly is available use it as a prototype for the rectangle.
23824
+ var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;
23825
+ var rect = Object.create(Constr.prototype);
23826
+ // Rectangle's properties are not writable and non-enumerable.
23827
+ defineConfigurable(rect, {
23828
+ x: x, y: y, width: width, height: height,
23829
+ top: y,
23830
+ right: x + width,
23831
+ bottom: height + y,
23832
+ left: x
23833
+ });
23834
+ return rect;
23835
+ }
23836
+ /**
23837
+ * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.
23838
+ * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit
23839
+ *
23840
+ * @param {number} x - X coordinate.
23841
+ * @param {number} y - Y coordinate.
23842
+ * @param {number} width - Rectangle's width.
23843
+ * @param {number} height - Rectangle's height.
23844
+ * @returns {DOMRectInit}
23845
+ */
23846
+ function createRectInit(x, y, width, height) {
23847
+ return { x: x, y: y, width: width, height: height };
23848
+ }
23849
+
23850
+ /**
23851
+ * Class that is responsible for computations of the content rectangle of
23852
+ * provided DOM element and for keeping track of it's changes.
23853
+ */
23854
+ var ResizeObservation = /** @class */ (function () {
23855
+ /**
23856
+ * Creates an instance of ResizeObservation.
23857
+ *
23858
+ * @param {Element} target - Element to be observed.
23859
+ */
23860
+ function ResizeObservation(target) {
23861
+ /**
23862
+ * Broadcasted width of content rectangle.
23863
+ *
23864
+ * @type {number}
23865
+ */
23866
+ this.broadcastWidth = 0;
23867
+ /**
23868
+ * Broadcasted height of content rectangle.
23869
+ *
23870
+ * @type {number}
23871
+ */
23872
+ this.broadcastHeight = 0;
23873
+ /**
23874
+ * Reference to the last observed content rectangle.
23875
+ *
23876
+ * @private {DOMRectInit}
23877
+ */
23878
+ this.contentRect_ = createRectInit(0, 0, 0, 0);
23879
+ this.target = target;
23880
+ }
23881
+ /**
23882
+ * Updates content rectangle and tells whether it's width or height properties
23883
+ * have changed since the last broadcast.
23884
+ *
23885
+ * @returns {boolean}
23886
+ */
23887
+ ResizeObservation.prototype.isActive = function () {
23888
+ var rect = getContentRect(this.target);
23889
+ this.contentRect_ = rect;
23890
+ return (rect.width !== this.broadcastWidth ||
23891
+ rect.height !== this.broadcastHeight);
23892
+ };
23893
+ /**
23894
+ * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data
23895
+ * from the corresponding properties of the last observed content rectangle.
23896
+ *
23897
+ * @returns {DOMRectInit} Last observed content rectangle.
23898
+ */
23899
+ ResizeObservation.prototype.broadcastRect = function () {
23900
+ var rect = this.contentRect_;
23901
+ this.broadcastWidth = rect.width;
23902
+ this.broadcastHeight = rect.height;
23903
+ return rect;
23904
+ };
23905
+ return ResizeObservation;
23906
+ }());
23907
+
23908
+ var ResizeObserverEntry = /** @class */ (function () {
23909
+ /**
23910
+ * Creates an instance of ResizeObserverEntry.
23911
+ *
23912
+ * @param {Element} target - Element that is being observed.
23913
+ * @param {DOMRectInit} rectInit - Data of the element's content rectangle.
23914
+ */
23915
+ function ResizeObserverEntry(target, rectInit) {
23916
+ var contentRect = createReadOnlyRect(rectInit);
23917
+ // According to the specification following properties are not writable
23918
+ // and are also not enumerable in the native implementation.
23919
+ //
23920
+ // Property accessors are not being used as they'd require to define a
23921
+ // private WeakMap storage which may cause memory leaks in browsers that
23922
+ // don't support this type of collections.
23923
+ defineConfigurable(this, { target: target, contentRect: contentRect });
23924
+ }
23925
+ return ResizeObserverEntry;
23926
+ }());
23927
+
23928
+ var ResizeObserverSPI = /** @class */ (function () {
23929
+ /**
23930
+ * Creates a new instance of ResizeObserver.
23931
+ *
23932
+ * @param {ResizeObserverCallback} callback - Callback function that is invoked
23933
+ * when one of the observed elements changes it's content dimensions.
23934
+ * @param {ResizeObserverController} controller - Controller instance which
23935
+ * is responsible for the updates of observer.
23936
+ * @param {ResizeObserver} callbackCtx - Reference to the public
23937
+ * ResizeObserver instance which will be passed to callback function.
23938
+ */
23939
+ function ResizeObserverSPI(callback, controller, callbackCtx) {
23940
+ /**
23941
+ * Collection of resize observations that have detected changes in dimensions
23942
+ * of elements.
23943
+ *
23944
+ * @private {Array<ResizeObservation>}
23945
+ */
23946
+ this.activeObservations_ = [];
23947
+ /**
23948
+ * Registry of the ResizeObservation instances.
23949
+ *
23950
+ * @private {Map<Element, ResizeObservation>}
23951
+ */
23952
+ this.observations_ = new MapShim();
23953
+ if (typeof callback !== 'function') {
23954
+ throw new TypeError('The callback provided as parameter 1 is not a function.');
23955
+ }
23956
+ this.callback_ = callback;
23957
+ this.controller_ = controller;
23958
+ this.callbackCtx_ = callbackCtx;
23959
+ }
23960
+ /**
23961
+ * Starts observing provided element.
23962
+ *
23963
+ * @param {Element} target - Element to be observed.
23964
+ * @returns {void}
23965
+ */
23966
+ ResizeObserverSPI.prototype.observe = function (target) {
23967
+ if (!arguments.length) {
23968
+ throw new TypeError('1 argument required, but only 0 present.');
23969
+ }
23970
+ // Do nothing if current environment doesn't have the Element interface.
23971
+ if (typeof Element === 'undefined' || !(Element instanceof Object)) {
23972
+ return;
23973
+ }
23974
+ if (!(target instanceof getWindowOf(target).Element)) {
23975
+ throw new TypeError('parameter 1 is not of type "Element".');
23976
+ }
23977
+ var observations = this.observations_;
23978
+ // Do nothing if element is already being observed.
23979
+ if (observations.has(target)) {
23980
+ return;
23981
+ }
23982
+ observations.set(target, new ResizeObservation(target));
23983
+ this.controller_.addObserver(this);
23984
+ // Force the update of observations.
23985
+ this.controller_.refresh();
23986
+ };
23987
+ /**
23988
+ * Stops observing provided element.
23989
+ *
23990
+ * @param {Element} target - Element to stop observing.
23991
+ * @returns {void}
23992
+ */
23993
+ ResizeObserverSPI.prototype.unobserve = function (target) {
23994
+ if (!arguments.length) {
23995
+ throw new TypeError('1 argument required, but only 0 present.');
23996
+ }
23997
+ // Do nothing if current environment doesn't have the Element interface.
23998
+ if (typeof Element === 'undefined' || !(Element instanceof Object)) {
23999
+ return;
24000
+ }
24001
+ if (!(target instanceof getWindowOf(target).Element)) {
24002
+ throw new TypeError('parameter 1 is not of type "Element".');
24003
+ }
24004
+ var observations = this.observations_;
24005
+ // Do nothing if element is not being observed.
24006
+ if (!observations.has(target)) {
24007
+ return;
24008
+ }
24009
+ observations.delete(target);
24010
+ if (!observations.size) {
24011
+ this.controller_.removeObserver(this);
24012
+ }
24013
+ };
24014
+ /**
24015
+ * Stops observing all elements.
24016
+ *
24017
+ * @returns {void}
24018
+ */
24019
+ ResizeObserverSPI.prototype.disconnect = function () {
24020
+ this.clearActive();
24021
+ this.observations_.clear();
24022
+ this.controller_.removeObserver(this);
24023
+ };
24024
+ /**
24025
+ * Collects observation instances the associated element of which has changed
24026
+ * it's content rectangle.
24027
+ *
24028
+ * @returns {void}
24029
+ */
24030
+ ResizeObserverSPI.prototype.gatherActive = function () {
24031
+ var _this = this;
24032
+ this.clearActive();
24033
+ this.observations_.forEach(function (observation) {
24034
+ if (observation.isActive()) {
24035
+ _this.activeObservations_.push(observation);
24036
+ }
24037
+ });
24038
+ };
24039
+ /**
24040
+ * Invokes initial callback function with a list of ResizeObserverEntry
24041
+ * instances collected from active resize observations.
24042
+ *
24043
+ * @returns {void}
24044
+ */
24045
+ ResizeObserverSPI.prototype.broadcastActive = function () {
24046
+ // Do nothing if observer doesn't have active observations.
24047
+ if (!this.hasActive()) {
24048
+ return;
24049
+ }
24050
+ var ctx = this.callbackCtx_;
24051
+ // Create ResizeObserverEntry instance for every active observation.
24052
+ var entries = this.activeObservations_.map(function (observation) {
24053
+ return new ResizeObserverEntry(observation.target, observation.broadcastRect());
24054
+ });
24055
+ this.callback_.call(ctx, entries, ctx);
24056
+ this.clearActive();
24057
+ };
24058
+ /**
24059
+ * Clears the collection of active observations.
24060
+ *
24061
+ * @returns {void}
24062
+ */
24063
+ ResizeObserverSPI.prototype.clearActive = function () {
24064
+ this.activeObservations_.splice(0);
24065
+ };
24066
+ /**
24067
+ * Tells whether observer has active observations.
24068
+ *
24069
+ * @returns {boolean}
24070
+ */
24071
+ ResizeObserverSPI.prototype.hasActive = function () {
24072
+ return this.activeObservations_.length > 0;
24073
+ };
24074
+ return ResizeObserverSPI;
24075
+ }());
24076
+
24077
+ // Registry of internal observers. If WeakMap is not available use current shim
24078
+ // for the Map collection as it has all required methods and because WeakMap
24079
+ // can't be fully polyfilled anyway.
24080
+ var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();
24081
+ /**
24082
+ * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
24083
+ * exposing only those methods and properties that are defined in the spec.
24084
+ */
24085
+ var ResizeObserver = /** @class */ (function () {
24086
+ /**
24087
+ * Creates a new instance of ResizeObserver.
24088
+ *
24089
+ * @param {ResizeObserverCallback} callback - Callback that is invoked when
24090
+ * dimensions of the observed elements change.
24091
+ */
24092
+ function ResizeObserver(callback) {
24093
+ if (!(this instanceof ResizeObserver)) {
24094
+ throw new TypeError('Cannot call a class as a function.');
24095
+ }
24096
+ if (!arguments.length) {
24097
+ throw new TypeError('1 argument required, but only 0 present.');
24098
+ }
24099
+ var controller = ResizeObserverController.getInstance();
24100
+ var observer = new ResizeObserverSPI(callback, controller, this);
24101
+ observers.set(this, observer);
24102
+ }
24103
+ return ResizeObserver;
24104
+ }());
24105
+ // Expose public methods of ResizeObserver.
24106
+ [
24107
+ 'observe',
24108
+ 'unobserve',
24109
+ 'disconnect'
24110
+ ].forEach(function (method) {
24111
+ ResizeObserver.prototype[method] = function () {
24112
+ var _a;
24113
+ return (_a = observers.get(this))[method].apply(_a, arguments);
24114
+ };
24115
+ });
24116
+
24117
+ var index = (function () {
24118
+ // Export existing implementation if available.
24119
+ if (typeof global$1.ResizeObserver !== 'undefined') {
24120
+ return global$1.ResizeObserver;
24121
+ }
24122
+ return ResizeObserver;
24123
+ })();
21725
24124
 
21726
24125
  var HeadingPopupBody = /** @class */ (function (_super) {
21727
24126
  __extends$1(HeadingPopupBody, _super);
@@ -21736,9 +24135,9 @@ var HeadingPopupBody = /** @class */ (function (_super) {
21736
24135
  };
21737
24136
  HeadingPopupBody.prototype.render = function () {
21738
24137
  var _this = this;
21739
- return html(templateObject_2$8 || (templateObject_2$8 = __makeTemplateObject(["\n <ul onClick=", ">\n ", "\n <li data-type=\"Paragraph\"><div>", "</div></li>\n </ul>\n "], ["\n <ul onClick=", ">\n ",
21740
- "\n <li data-type=\"Paragraph\"><div>", "</div></li>\n </ul>\n "])), function (ev) { return _this.execCommand(ev); }, [1, 2, 3, 4, 5, 6].map(function (level) {
21741
- return html(templateObject_1$g || (templateObject_1$g = __makeTemplateObject(["\n <li data-level=\"", "\" data-type=\"Heading\">\n <", ">", " ", "</$>\n </li>\n "], ["\n <li data-level=\"", "\" data-type=\"Heading\">\n <", ">", " ", "</$>\n </li>\n "])), level, "h" + level, i18n.get('Heading'), level);
24138
+ return html(templateObject_2$8 || (templateObject_2$8 = __makeTemplateObject(["\n <ul\n onClick=", "\n aria-role=\"menu\"\n aria-label=\"", "\"\n >\n ", "\n <li data-type=\"Paragraph\" aria-role=\"menuitem\">\n <div>", "</div>\n </li>\n </ul>\n "], ["\n <ul\n onClick=", "\n aria-role=\"menu\"\n aria-label=\"", "\"\n >\n ",
24139
+ "\n <li data-type=\"Paragraph\" aria-role=\"menuitem\">\n <div>", "</div>\n </li>\n </ul>\n "])), function (ev) { return _this.execCommand(ev); }, i18n.get('Headings'), [1, 2, 3, 4, 5, 6].map(function (level) {
24140
+ return html(templateObject_1$g || (templateObject_1$g = __makeTemplateObject(["\n <li data-level=\"", "\" data-type=\"Heading\" aria-role=\"menuitem\">\n <", ">", " ", "</$>\n </li>\n "], ["\n <li data-level=\"", "\" data-type=\"Heading\" aria-role=\"menuitem\">\n <", ">", " ", "</$>\n </li>\n "])), level, "h" + level, i18n.get('Heading'), level);
21742
24141
  }), i18n.get('Paragraph'));
21743
24142
  };
21744
24143
  return HeadingPopupBody;
@@ -21755,10 +24154,11 @@ var Tabs = /** @class */ (function (_super) {
21755
24154
  };
21756
24155
  Tabs.prototype.render = function () {
21757
24156
  var _this = this;
21758
- return html(templateObject_2$7 || (templateObject_2$7 = __makeTemplateObject(["\n <div class=\"", "\">\n ", "\n </div>\n "], ["\n <div class=\"", "\">\n ",
24157
+ return html(templateObject_2$7 || (templateObject_2$7 = __makeTemplateObject(["\n <div class=\"", "\" aria-role=\"tabpanel\">\n ", "\n </div>\n "], ["\n <div class=\"", "\" aria-role=\"tabpanel\">\n ",
21759
24158
  "\n </div>\n "])), cls('tabs'), this.props.tabs.map(function (_a) {
21760
24159
  var name = _a.name, text = _a.text;
21761
- return html(templateObject_1$f || (templateObject_1$f = __makeTemplateObject(["\n <div\n class=\"tab-item", "\"\n onClick=", "\n >\n ", "\n </div>\n "], ["\n <div\n class=\"tab-item", "\"\n onClick=", "\n >\n ", "\n </div>\n "])), _this.props.activeTab === name ? ' active' : '', function (ev) { return _this.toggleTab(ev, name); }, i18n.get(text));
24160
+ var isActive = _this.props.activeTab === name;
24161
+ return html(templateObject_1$f || (templateObject_1$f = __makeTemplateObject(["\n <div\n class=\"tab-item", "\"\n onClick=", "\n aria-role=\"tab\"\n aria-label=\"", "\"\n aria-selected=\"", "\"\n tabindex=\"", "\"\n >\n ", "\n </div>\n "], ["\n <div\n class=\"tab-item", "\"\n onClick=", "\n aria-role=\"tab\"\n aria-label=\"", "\"\n aria-selected=\"", "\"\n tabindex=\"", "\"\n >\n ", "\n </div>\n "])), isActive ? ' active' : '', function (ev) { return _this.toggleTab(ev, name); }, i18n.get(text), isActive ? 'true' : 'false', isActive ? '0' : '-1', i18n.get(text));
21762
24162
  }));
21763
24163
  };
21764
24164
  return Tabs;
@@ -21848,7 +24248,7 @@ var ImagePopupBody = /** @class */ (function (_super) {
21848
24248
  ImagePopupBody.prototype.render = function () {
21849
24249
  var _this = this;
21850
24250
  var _a = this.state, activeTab = _a.activeTab, file = _a.file, fileNameElClassName = _a.fileNameElClassName;
21851
- return html(templateObject_1$e || (templateObject_1$e = __makeTemplateObject(["\n <div>\n <", " tabs=", " activeTab=", " onClick=", " />\n <div style=\"display:", "\">\n <label for=\"toastuiImageUrlInput\">", "</label>\n <input\n id=\"toastuiImageUrlInput\"\n type=\"text\"\n ref=", "\n />\n </div>\n <div style=\"display:", ";position: relative;\">\n <label for=\"toastuiImageFileInput\">", "</label>\n <span\n class=\"", "", "\"\n onClick=", "\n onSelectstart=", "\n >\n ", "\n </span>\n <button\n type=\"button\"\n class=\"", "\"\n onClick=", "\n >\n ", "\n </button>\n <input\n id=\"toastuiImageFileInput\"\n type=\"file\"\n accept=\"image/*\"\n onChange=", "\n ref=", "\n />\n </div>\n <label for=\"toastuiAltTextInput\">", "</label>\n <input\n id=\"toastuiAltTextInput\"\n type=\"text\"\n ref=", "\n />\n <div class=\"", "\">\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n </div>\n </div>\n "], ["\n <div>\n <", " tabs=", " activeTab=", " onClick=", " />\n <div style=\"display:", "\">\n <label for=\"toastuiImageUrlInput\">", "</label>\n <input\n id=\"toastuiImageUrlInput\"\n type=\"text\"\n ref=", "\n />\n </div>\n <div style=\"display:", ";position: relative;\">\n <label for=\"toastuiImageFileInput\">", "</label>\n <span\n class=\"", "", "\"\n onClick=", "\n onSelectstart=", "\n >\n ", "\n </span>\n <button\n type=\"button\"\n class=\"", "\"\n onClick=", "\n >\n ", "\n </button>\n <input\n id=\"toastuiImageFileInput\"\n type=\"file\"\n accept=\"image/*\"\n onChange=", "\n ref=", "\n />\n </div>\n <label for=\"toastuiAltTextInput\">", "</label>\n <input\n id=\"toastuiAltTextInput\"\n type=\"text\"\n ref=", "\n />\n <div class=\"", "\">\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n </div>\n </div>\n "])), Tabs, this.tabs, activeTab, this.toggleTab, activeTab === 'url' ? 'block' : 'none', i18n.get('Image URL'), function (el) { return (_this.refs.url = el); }, activeTab === 'file' ? 'block' : 'none', i18n.get('Select image file'), cls('file-name'), file ? ' has-file' : fileNameElClassName, this.showFileSelectBox, this.preventSelectStart, file ? file.name : i18n.get('No file'), cls('file-select-button'), this.showFileSelectBox, i18n.get('Choose a file'), this.changeFile, function (el) { return (_this.refs.file = el); }, i18n.get('Description'), function (el) { return (_this.refs.altText = el); }, cls('button-container'), cls('close-button'), this.props.hidePopup, i18n.get('Cancel'), cls('ok-button'), this.execCommand, i18n.get('OK'));
24251
+ return html(templateObject_1$e || (templateObject_1$e = __makeTemplateObject(["\n <div aria-label=\"", "\">\n <", " tabs=", " activeTab=", " onClick=", " />\n <div style=\"display:", "\">\n <label for=\"toastuiImageUrlInput\">", "</label>\n <input\n id=\"toastuiImageUrlInput\"\n type=\"text\"\n ref=", "\n />\n </div>\n <div style=\"display:", ";position: relative;\">\n <label for=\"toastuiImageFileInput\">", "</label>\n <span\n class=\"", "", "\"\n onClick=", "\n onSelectstart=", "\n >\n ", "\n </span>\n <button\n type=\"button\"\n class=\"", "\"\n onClick=", "\n >\n ", "\n </button>\n <input\n id=\"toastuiImageFileInput\"\n type=\"file\"\n accept=\"image/*\"\n onChange=", "\n ref=", "\n />\n </div>\n <label for=\"toastuiAltTextInput\">", "</label>\n <input\n id=\"toastuiAltTextInput\"\n type=\"text\"\n ref=", "\n />\n <div class=\"", "\">\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n </div>\n </div>\n "], ["\n <div aria-label=\"", "\">\n <", " tabs=", " activeTab=", " onClick=", " />\n <div style=\"display:", "\">\n <label for=\"toastuiImageUrlInput\">", "</label>\n <input\n id=\"toastuiImageUrlInput\"\n type=\"text\"\n ref=", "\n />\n </div>\n <div style=\"display:", ";position: relative;\">\n <label for=\"toastuiImageFileInput\">", "</label>\n <span\n class=\"", "", "\"\n onClick=", "\n onSelectstart=", "\n >\n ", "\n </span>\n <button\n type=\"button\"\n class=\"", "\"\n onClick=", "\n >\n ", "\n </button>\n <input\n id=\"toastuiImageFileInput\"\n type=\"file\"\n accept=\"image/*\"\n onChange=", "\n ref=", "\n />\n </div>\n <label for=\"toastuiAltTextInput\">", "</label>\n <input\n id=\"toastuiAltTextInput\"\n type=\"text\"\n ref=", "\n />\n <div class=\"", "\">\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n </div>\n </div>\n "])), i18n.get('Insert image'), Tabs, this.tabs, activeTab, this.toggleTab, activeTab === 'url' ? 'block' : 'none', i18n.get('Image URL'), function (el) { return (_this.refs.url = el); }, activeTab === 'file' ? 'block' : 'none', i18n.get('Select image file'), cls('file-name'), file ? ' has-file' : fileNameElClassName, this.showFileSelectBox, this.preventSelectStart, file ? file.name : i18n.get('No file'), cls('file-select-button'), this.showFileSelectBox, i18n.get('Choose a file'), this.changeFile, function (el) { return (_this.refs.file = el); }, i18n.get('Description'), function (el) { return (_this.refs.altText = el); }, cls('button-container'), cls('close-button'), this.props.hidePopup, i18n.get('Cancel'), cls('ok-button'), this.execCommand, i18n.get('OK'));
21852
24252
  };
21853
24253
  return ImagePopupBody;
21854
24254
  }(Component));
@@ -21903,7 +24303,7 @@ var LinkPopupBody = /** @class */ (function (_super) {
21903
24303
  };
21904
24304
  LinkPopupBody.prototype.render = function () {
21905
24305
  var _this = this;
21906
- return html(templateObject_1$d || (templateObject_1$d = __makeTemplateObject(["\n <div>\n <label for=\"toastuiLinkUrlInput\">", "</label>\n <input\n id=\"toastuiLinkUrlInput\"\n type=\"text\"\n ref=", "\n />\n <label for=\"toastuiLinkTextInput\">", "</label>\n <input\n id=\"toastuiLinkTextInput\"\n type=\"text\"\n ref=", "\n />\n <div class=\"", "\">\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n </div>\n </div>\n "], ["\n <div>\n <label for=\"toastuiLinkUrlInput\">", "</label>\n <input\n id=\"toastuiLinkUrlInput\"\n type=\"text\"\n ref=", "\n />\n <label for=\"toastuiLinkTextInput\">", "</label>\n <input\n id=\"toastuiLinkTextInput\"\n type=\"text\"\n ref=", "\n />\n <div class=\"", "\">\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n </div>\n </div>\n "])), i18n.get('URL'), function (el) { return (_this.refs.url = el); }, i18n.get('Link text'), function (el) { return (_this.refs.text = el); }, cls('button-container'), cls('close-button'), this.props.hidePopup, i18n.get('Cancel'), cls('ok-button'), this.execCommand, i18n.get('OK'));
24306
+ return html(templateObject_1$d || (templateObject_1$d = __makeTemplateObject(["\n <div aria-label=\"", "\">\n <label for=\"toastuiLinkUrlInput\">", "</label>\n <input\n id=\"toastuiLinkUrlInput\"\n type=\"text\"\n ref=", "\n />\n <label for=\"toastuiLinkTextInput\">", "</label>\n <input\n id=\"toastuiLinkTextInput\"\n type=\"text\"\n ref=", "\n />\n <div class=\"", "\">\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n </div>\n </div>\n "], ["\n <div aria-label=\"", "\">\n <label for=\"toastuiLinkUrlInput\">", "</label>\n <input\n id=\"toastuiLinkUrlInput\"\n type=\"text\"\n ref=", "\n />\n <label for=\"toastuiLinkTextInput\">", "</label>\n <input\n id=\"toastuiLinkTextInput\"\n type=\"text\"\n ref=", "\n />\n <div class=\"", "\">\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n <button type=\"button\" class=\"", "\" onClick=", ">\n ", "\n </button>\n </div>\n </div>\n "])), i18n.get('Insert link'), i18n.get('URL'), function (el) { return (_this.refs.url = el); }, i18n.get('Link text'), function (el) { return (_this.refs.text = el); }, cls('button-container'), cls('close-button'), this.props.hidePopup, i18n.get('Cancel'), cls('ok-button'), this.execCommand, i18n.get('OK'));
21907
24307
  };
21908
24308
  return LinkPopupBody;
21909
24309
  }(Component));
@@ -21981,17 +24381,17 @@ var TablePopupBody = /** @class */ (function (_super) {
21981
24381
  range.colIdx = Math.min(Math.max(range.colIdx, MIN_COL_SELECTION_INDEX), MAX_COL_INDEX);
21982
24382
  return range;
21983
24383
  };
21984
- TablePopupBody.prototype.mounted = function () {
21985
- var _a = this.refs.tableEl.getBoundingClientRect(), left = _a.left, top = _a.top;
21986
- this.offsetRect = {
21987
- left: window.pageXOffset + left,
21988
- top: window.pageYOffset + top,
21989
- };
21990
- };
21991
24384
  TablePopupBody.prototype.updated = function () {
21992
24385
  if (!this.props.show) {
21993
24386
  this.setState({ colIdx: -1, rowIdx: -1 });
21994
24387
  }
24388
+ else if (this.state.colIdx === -1 && this.state.rowIdx === -1) {
24389
+ var _a = this.refs.tableEl.getBoundingClientRect(), left = _a.left, top_1 = _a.top;
24390
+ this.offsetRect = {
24391
+ left: window.pageXOffset + left,
24392
+ top: window.pageYOffset + top_1,
24393
+ };
24394
+ }
21995
24395
  };
21996
24396
  TablePopupBody.prototype.createTableArea = function (tableRange) {
21997
24397
  var colIdx = tableRange.colIdx, rowIdx = tableRange.rowIdx;
@@ -22010,7 +24410,7 @@ var TablePopupBody = /** @class */ (function (_super) {
22010
24410
  var _this = this;
22011
24411
  var tableRange = this.getTableRange();
22012
24412
  var selectionAreaBound = this.getSelectionAreaBound();
22013
- return html(templateObject_4$1 || (templateObject_4$1 = __makeTemplateObject(["\n <div>\n <div\n class=\"", "\"\n ref=", "\n onMousemove=", "\n onClick=", "\n >\n ", "\n <div class=\"", "\" style=", "></div>\n </div>\n <p class=\"", "\">", "</p>\n </div>\n "], ["\n <div>\n <div\n class=\"", "\"\n ref=", "\n onMousemove=", "\n onClick=", "\n >\n ", "\n <div class=\"", "\" style=", "></div>\n </div>\n <p class=\"", "\">", "</p>\n </div>\n "])), cls('table-selection'), function (el) { return (_this.refs.tableEl = el); }, this.extendSelectionRange, this.execCommand, this.createTableArea(tableRange), cls('table-selection-layer'), selectionAreaBound, cls('table-description'), this.getDescription());
24413
+ return html(templateObject_4$1 || (templateObject_4$1 = __makeTemplateObject(["\n <div aria-label=\"", "\">\n <div\n class=\"", "\"\n ref=", "\n onMousemove=", "\n onClick=", "\n >\n ", "\n <div class=\"", "\" style=", "></div>\n </div>\n <p class=\"", "\">", "</p>\n </div>\n "], ["\n <div aria-label=\"", "\">\n <div\n class=\"", "\"\n ref=", "\n onMousemove=", "\n onClick=", "\n >\n ", "\n <div class=\"", "\" style=", "></div>\n </div>\n <p class=\"", "\">", "</p>\n </div>\n "])), i18n.get('Insert table'), cls('table-selection'), function (el) { return (_this.refs.tableEl = el); }, this.extendSelectionRange, this.execCommand, this.createTableArea(tableRange), cls('table-selection-layer'), selectionAreaBound, cls('table-description'), this.getDescription());
22014
24414
  };
22015
24415
  return TablePopupBody;
22016
24416
  }(Component));
@@ -22018,10 +24418,8 @@ var templateObject_1$c, templateObject_2$6, templateObject_3$2, templateObject_4
22018
24418
 
22019
24419
  var CustomPopupBody = /** @class */ (function (_super) {
22020
24420
  __extends$1(CustomPopupBody, _super);
22021
- function CustomPopupBody(props) {
22022
- var _this = _super.call(this, props) || this;
22023
- props.eventEmitter.listen('closePopup', _this.props.hidePopup);
22024
- return _this;
24421
+ function CustomPopupBody() {
24422
+ return _super !== null && _super.apply(this, arguments) || this;
22025
24423
  }
22026
24424
  CustomPopupBody.prototype.mounted = function () {
22027
24425
  // append the custom popup body element
@@ -22222,7 +24620,6 @@ function createDefaultToolbarItemInfo(type) {
22222
24620
  }
22223
24621
  return info;
22224
24622
  }
22225
- // eslint-disable-next-line consistent-return
22226
24623
  function createPopupInfo(type, payload) {
22227
24624
  var el = payload.el, pos = payload.pos, popup = payload.popup, initialValues = payload.initialValues;
22228
24625
  switch (type) {
@@ -22289,6 +24686,7 @@ function toggleScrollSync(toolbarItems, hiddenScrollSync) {
22289
24686
  }
22290
24687
  var templateObject_1$a, templateObject_2$5, templateObject_3$1, templateObject_4, templateObject_5;
22291
24688
 
24689
+ var MARGIN_FROM_RIGHT_SIDE = 20;
22292
24690
  var Popup = /** @class */ (function (_super) {
22293
24691
  __extends$1(Popup, _super);
22294
24692
  function Popup() {
@@ -22303,19 +24701,32 @@ var Popup = /** @class */ (function (_super) {
22303
24701
  }
22304
24702
  Popup.prototype.mounted = function () {
22305
24703
  document.addEventListener('mousedown', this.handleMousedown);
24704
+ this.props.eventEmitter.listen('closePopup', this.props.hidePopup);
22306
24705
  };
22307
24706
  Popup.prototype.beforeDestroy = function () {
22308
24707
  document.removeEventListener('mousedown', this.handleMousedown);
22309
24708
  };
24709
+ Popup.prototype.updated = function (prevProps) {
24710
+ var _a = this.props, show = _a.show, info = _a.info;
24711
+ if (show && info.pos && prevProps.show !== show) {
24712
+ var popupPos = __assign$1({}, info.pos);
24713
+ var offsetWidth = this.refs.el.offsetWidth;
24714
+ var toolbarEl = closest(this.refs.el, "." + cls('toolbar'));
24715
+ var toolbarOffsetWidth = toolbarEl.offsetWidth;
24716
+ if (popupPos.left + offsetWidth >= toolbarOffsetWidth) {
24717
+ popupPos.left = toolbarOffsetWidth - offsetWidth - MARGIN_FROM_RIGHT_SIDE;
24718
+ }
24719
+ if (!shallowEqual(this.state.popupPos, popupPos)) {
24720
+ this.setState({ popupPos: popupPos });
24721
+ }
24722
+ }
24723
+ };
22310
24724
  Popup.prototype.render = function () {
24725
+ var _this = this;
22311
24726
  var _a = this.props, info = _a.info, show = _a.show, hidePopup = _a.hidePopup, eventEmitter = _a.eventEmitter, execCommand = _a.execCommand;
22312
- var _b = info || {}, _c = _b.className, className = _c === void 0 ? '' : _c, style = _b.style, render = _b.render, pos = _b.pos, _d = _b.initialValues, initialValues = _d === void 0 ? {} : _d;
22313
- var popupStyle = __assign$1({ display: show ? 'block' : 'none' }, style);
22314
- if (pos) {
22315
- popupStyle.left = pos.left;
22316
- popupStyle.top = pos.top;
22317
- }
22318
- return html(templateObject_1$9 || (templateObject_1$9 = __makeTemplateObject(["\n <div class=\"", " ", "\" style=", ">\n <div class=\"", "\">\n ", "\n </div>\n </div>\n "], ["\n <div class=\"", " ", "\" style=", ">\n <div class=\"", "\">\n ", "\n </div>\n </div>\n "])), cls('popup'), className, popupStyle, cls('popup-body'), render && render({ eventEmitter: eventEmitter, show: show, hidePopup: hidePopup, execCommand: execCommand, initialValues: initialValues }));
24727
+ var _b = info || {}, _c = _b.className, className = _c === void 0 ? '' : _c, style = _b.style, render = _b.render, _d = _b.initialValues, initialValues = _d === void 0 ? {} : _d;
24728
+ var popupStyle = __assign$1(__assign$1({ display: show ? 'block' : 'none' }, style), this.state.popupPos);
24729
+ return html(templateObject_1$9 || (templateObject_1$9 = __makeTemplateObject(["\n <div\n class=\"", " ", "\"\n style=", "\n ref=", "\n aria-role=\"dialog\"\n >\n <div class=\"", "\">\n ", "\n </div>\n </div>\n "], ["\n <div\n class=\"", " ", "\"\n style=", "\n ref=", "\n aria-role=\"dialog\"\n >\n <div class=\"", "\">\n ", "\n </div>\n </div>\n "])), cls('popup'), className, popupStyle, function (el) { return (_this.refs.el = el); }, cls('popup-body'), render && render({ eventEmitter: eventEmitter, show: show, hidePopup: hidePopup, execCommand: execCommand, initialValues: initialValues }));
22319
24730
  };
22320
24731
  return Popup;
22321
24732
  }(Component));
@@ -22367,7 +24778,7 @@ function connectHOC(WrappedComponent) {
22367
24778
  }
22368
24779
  var templateObject_1$8;
22369
24780
 
22370
- var DEFAULT_WIDTH$1 = 80;
24781
+ var DEFAULT_WIDTH = 80;
22371
24782
  var ToolbarButtonComp = /** @class */ (function (_super) {
22372
24783
  __extends$1(ToolbarButtonComp, _super);
22373
24784
  function ToolbarButtonComp() {
@@ -22407,7 +24818,7 @@ var ToolbarButtonComp = /** @class */ (function (_super) {
22407
24818
  var _a = this.props, setItemWidth = _a.setItemWidth, item = _a.item;
22408
24819
  // set width only if it is not a dropdown toolbar
22409
24820
  if (setItemWidth) {
22410
- setItemWidth(item.name, getOuterWidth(this.refs.el) + (item.hidden ? DEFAULT_WIDTH$1 : 0));
24821
+ setItemWidth(item.name, getOuterWidth(this.refs.el) + (item.hidden ? DEFAULT_WIDTH : 0));
22411
24822
  }
22412
24823
  };
22413
24824
  ToolbarButtonComp.prototype.render = function () {
@@ -22415,7 +24826,7 @@ var ToolbarButtonComp = /** @class */ (function (_super) {
22415
24826
  var _a = this.props, hideTooltip = _a.hideTooltip, disabled = _a.disabled, item = _a.item, active = _a.active;
22416
24827
  var style = __assign$1({ display: item.hidden ? 'none' : null }, item.style);
22417
24828
  var classNames = "" + (item.className || '') + (active ? ' active' : '');
22418
- return html(templateObject_1$7 || (templateObject_1$7 = __makeTemplateObject(["\n <button\n ref=", "\n type=\"button\"\n style=", "\n class=", "\n onClick=", "\n onMouseover=", "\n onMouseout=", "\n disabled=", "\n >\n ", "\n </button>\n "], ["\n <button\n ref=", "\n type=\"button\"\n style=", "\n class=", "\n onClick=", "\n onMouseover=", "\n onMouseout=", "\n disabled=", "\n >\n ", "\n </button>\n "])), function (el) { return (_this.refs.el = el); }, style, classNames, this.execCommand, this.showTooltip, hideTooltip, !!disabled, item.text || '');
24829
+ return html(templateObject_1$7 || (templateObject_1$7 = __makeTemplateObject(["\n <button\n ref=", "\n type=\"button\"\n style=", "\n class=", "\n onClick=", "\n onMouseover=", "\n onMouseout=", "\n disabled=", "\n aria-label=", "\n >\n ", "\n </button>\n "], ["\n <button\n ref=", "\n type=\"button\"\n style=", "\n class=", "\n onClick=", "\n onMouseover=", "\n onMouseout=", "\n disabled=", "\n aria-label=", "\n >\n ", "\n </button>\n "])), function (el) { return (_this.refs.el = el); }, style, classNames, this.execCommand, this.showTooltip, hideTooltip, !!disabled, item.text || item.tooltip || '', item.text || '');
22419
24830
  };
22420
24831
  return ToolbarButtonComp;
22421
24832
  }(Component));
@@ -22548,8 +24959,7 @@ var DropdownToolbarButtonComp = /** @class */ (function (_super) {
22548
24959
  var DropdownToolbarButton = connectHOC(DropdownToolbarButtonComp);
22549
24960
  var templateObject_1$4, templateObject_2$3;
22550
24961
 
22551
- var DROPDOWN_WIDTH = 120;
22552
- var DEFAULT_WIDTH = 80;
24962
+ var INLINE_PADDING = 50;
22553
24963
  var Toolbar = /** @class */ (function (_super) {
22554
24964
  __extends$1(Toolbar, _super);
22555
24965
  function Toolbar(props) {
@@ -22607,6 +25017,7 @@ var Toolbar = /** @class */ (function (_super) {
22607
25017
  activeTab: 'write',
22608
25018
  };
22609
25019
  _this.tooltipRef = { current: null };
25020
+ _this.resizeObserver = new index(function () { return _this.handleResize(); });
22610
25021
  _this.addEvent();
22611
25022
  return _this;
22612
25023
  }
@@ -22640,9 +25051,13 @@ var Toolbar = /** @class */ (function (_super) {
22640
25051
  };
22641
25052
  Toolbar.prototype.addEvent = function () {
22642
25053
  var _this = this;
22643
- this.props.eventEmitter.listen('openPopup', this.openPopup);
22644
- this.handleResize = throttle_1(function () { return _this.setState(_this.classifyToolbarItems()); }, 200);
22645
- window.addEventListener('resize', this.handleResize);
25054
+ var eventEmitter = this.props.eventEmitter;
25055
+ this.handleResize = throttle_1(function () {
25056
+ // reset toolbar items to re-layout toolbar items with each clientWidth
25057
+ _this.setState({ items: _this.initialItems, dropdownItems: [] });
25058
+ _this.setState(_this.classifyToolbarItems());
25059
+ }, 200);
25060
+ eventEmitter.listen('openPopup', this.openPopup);
22646
25061
  };
22647
25062
  Toolbar.prototype.appendTooltipToRoot = function () {
22648
25063
  var tooltip = "<div class=\"" + cls('tooltip') + "\" style=\"display:none\">\n <div class=\"arrow\"></div>\n <span class=\"text\"></span>\n </div>";
@@ -22651,6 +25066,23 @@ var Toolbar = /** @class */ (function (_super) {
22651
25066
  Toolbar.prototype.hiddenScrollSync = function () {
22652
25067
  return this.props.editorType === 'wysiwyg' || this.props.previewStyle === 'tab';
22653
25068
  };
25069
+ Toolbar.prototype.movePrevItemToDropdownToolbar = function (itemIndex, items, group, dropdownGroup) {
25070
+ var moveItem = function (targetGroup) {
25071
+ var item = targetGroup.pop();
25072
+ if (item) {
25073
+ dropdownGroup.push(item);
25074
+ }
25075
+ };
25076
+ if (itemIndex > 1) {
25077
+ moveItem(group);
25078
+ }
25079
+ else {
25080
+ var prevGroup = last$1(items);
25081
+ if (prevGroup) {
25082
+ moveItem(prevGroup);
25083
+ }
25084
+ }
25085
+ };
22654
25086
  Toolbar.prototype.classifyToolbarItems = function () {
22655
25087
  var _this = this;
22656
25088
  var totalWidth = 0;
@@ -22659,13 +25091,25 @@ var Toolbar = /** @class */ (function (_super) {
22659
25091
  var dividerWidth = divider ? getOuterWidth(divider) : 0;
22660
25092
  var items = [];
22661
25093
  var dropdownItems = [];
22662
- this.initialItems.forEach(function (initialGroup, index) {
25094
+ var moved = false;
25095
+ this.initialItems.forEach(function (initialGroup, groupIndex) {
22663
25096
  var group = [];
22664
25097
  var dropdownGroup = [];
22665
- initialGroup.forEach(function (item) {
22666
- totalWidth += _this.itemWidthMap[item.name] || DEFAULT_WIDTH;
22667
- var target = totalWidth >= clientWidth - DROPDOWN_WIDTH ? dropdownGroup : group;
22668
- target.push(item);
25098
+ initialGroup.forEach(function (item, itemIndex) {
25099
+ if (!item.hidden) {
25100
+ totalWidth += _this.itemWidthMap[item.name];
25101
+ if (totalWidth > clientWidth - INLINE_PADDING) {
25102
+ // should move the prev item to dropdown toolbar for placing the more button
25103
+ if (!moved) {
25104
+ _this.movePrevItemToDropdownToolbar(itemIndex, items, group, dropdownGroup);
25105
+ moved = true;
25106
+ }
25107
+ dropdownGroup.push(item);
25108
+ }
25109
+ else {
25110
+ group.push(item);
25111
+ }
25112
+ }
22669
25113
  });
22670
25114
  if (group.length) {
22671
25115
  setGroupState(group);
@@ -22676,7 +25120,7 @@ var Toolbar = /** @class */ (function (_super) {
22676
25120
  dropdownItems.push(dropdownGroup);
22677
25121
  }
22678
25122
  // add divider width
22679
- if (index < _this.state.items.length - 1) {
25123
+ if (groupIndex < _this.state.items.length - 1) {
22680
25124
  totalWidth += dividerWidth;
22681
25125
  }
22682
25126
  });
@@ -22689,6 +25133,7 @@ var Toolbar = /** @class */ (function (_super) {
22689
25133
  // classify toolbar and dropdown toolbar after DOM has been rendered
22690
25134
  this.setState(this.classifyToolbarItems());
22691
25135
  this.appendTooltipToRoot();
25136
+ this.resizeObserver.observe(this.refs.el);
22692
25137
  };
22693
25138
  Toolbar.prototype.updated = function (prevProps) {
22694
25139
  var _a = this.props, editorType = _a.editorType, previewStyle = _a.previewStyle, eventEmitter = _a.eventEmitter;
@@ -22707,6 +25152,7 @@ var Toolbar = /** @class */ (function (_super) {
22707
25152
  };
22708
25153
  Toolbar.prototype.beforeDestroy = function () {
22709
25154
  window.removeEventListener('resize', this.handleResize);
25155
+ this.resizeObserver.disconnect();
22710
25156
  removeNode$1(this.tooltipRef.current);
22711
25157
  };
22712
25158
  Toolbar.prototype.render = function () {
@@ -22777,7 +25223,7 @@ var ContextMenu = /** @class */ (function (_super) {
22777
25223
  _this.setState({ pos: null });
22778
25224
  }
22779
25225
  };
22780
- menuItem.push(html(templateObject_1$2 || (templateObject_1$2 = __makeTemplateObject(["\n <li onClick=", " class=\"menu-item", "\">\n <span class=\"", "\">", "</span>\n </li>\n "], ["\n <li onClick=", " class=\"menu-item", "\">\n <span class=\"", "\">", "</span>\n </li>\n "])), handleClick, disabled ? ' disabled' : '', className, label));
25226
+ menuItem.push(html(templateObject_1$2 || (templateObject_1$2 = __makeTemplateObject(["\n <li\n onClick=", "\n class=\"menu-item", "\"\n aria-role=\"menuitem\"\n >\n <span class=\"", "\">", "</span>\n </li>\n "], ["\n <li\n onClick=", "\n class=\"menu-item", "\"\n aria-role=\"menuitem\"\n >\n <span class=\"", "\">", "</span>\n </li>\n "])), handleClick, disabled ? ' disabled' : '', className, label));
22781
25227
  });
22782
25228
  acc.push(html(templateObject_2$1 || (templateObject_2$1 = __makeTemplateObject(["<ul class=\"menu-group\">\n ", "\n </ul>"], ["<ul class=\"menu-group\">\n ", "\n </ul>"])), menuItem));
22783
25229
  return acc;
@@ -22786,7 +25232,7 @@ var ContextMenu = /** @class */ (function (_super) {
22786
25232
  };
22787
25233
  ContextMenu.prototype.render = function () {
22788
25234
  var style = __assign$1({ display: this.state.pos ? 'block' : 'none' }, this.state.pos);
22789
- return html(templateObject_3 || (templateObject_3 = __makeTemplateObject(["<div class=\"", "\" style=", ">\n ", "\n </div>"], ["<div class=\"", "\" style=", ">\n ", "\n </div>"])), cls('context-menu'), style, this.getMenuGroupElements());
25235
+ return html(templateObject_3 || (templateObject_3 = __makeTemplateObject(["<div class=\"", "\" style=", " aria-role=\"menu\">\n ", "\n </div>"], ["<div class=\"", "\" style=", " aria-role=\"menu\">\n ", "\n </div>"])), cls('context-menu'), style, this.getMenuGroupElements());
22790
25236
  };
22791
25237
  return ContextMenu;
22792
25238
  }(Component));
@@ -22841,8 +25287,8 @@ var Layout = /** @class */ (function (_super) {
22841
25287
  var editorTypeClassName = cls(editorType === 'markdown' ? 'md-mode' : 'ww-mode');
22842
25288
  var previewClassName = cls('md') + "-" + previewStyle + "-style";
22843
25289
  var themeClassName = cls([theme !== 'light', theme + " "]);
22844
- return html(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n <div\n class=\"", "", "", "\"\n ref=", "\n >\n <", "\n ref=", "\n eventEmitter=", "\n previewStyle=", "\n toolbarItems=", "\n editorType=", "\n />\n <div\n class=\"", " ", "\"\n ref=", "\n >\n <div\n class=\"", " ", "\"\n ref=", "\n >\n <div class=\"", "\"></div>\n </div>\n <div\n class=\"", "\"\n ref=", "\n />\n </div>\n ", "\n <", " eventEmitter=", " />\n </div>\n "], ["\n <div\n class=\"", "", "", "\"\n ref=", "\n >\n <", "\n ref=", "\n eventEmitter=", "\n previewStyle=", "\n toolbarItems=", "\n editorType=", "\n />\n <div\n class=\"", " ", "\"\n ref=", "\n >\n <div\n class=\"", " ", "\"\n ref=", "\n >\n <div class=\"", "\"></div>\n </div>\n <div\n class=\"", "\"\n ref=", "\n />\n </div>\n ",
22845
- "\n <", " eventEmitter=", " />\n </div>\n "])), themeClassName, cls('defaultUI'), displayClassName, function (el) { return (_this.refs.el = el); }, Toolbar, function (toolbar) { return (_this.toolbar = toolbar); }, eventEmitter, previewStyle, toolbarItems, editorType, cls('main'), editorTypeClassName, function (el) { return (_this.refs.editorSection = el); }, cls('md-container'), previewClassName, function (el) { return (_this.refs.mdContainer = el); }, cls('md-splitter'), cls('ww-container'), function (el) { return (_this.refs.wwContainer = el); }, !hideModeSwitch && html(templateObject_1$1 || (templateObject_1$1 = __makeTemplateObject(["<", " eventEmitter=", " editorType=", " />"], ["<", " eventEmitter=", " editorType=", " />"])), Switch, eventEmitter, editorType), ContextMenu, eventEmitter);
25290
+ return html(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n <div\n class=\"", "", "", "\"\n ref=", "\n >\n <", "\n ref=", "\n eventEmitter=", "\n previewStyle=", "\n toolbarItems=", "\n editorType=", "\n />\n <div\n class=\"", " ", "\"\n ref=", "\n >\n <div class=\"", "\">\n <div\n class=\"", " ", "\"\n ref=", "\n >\n <div class=\"", "\"></div>\n </div>\n <div\n class=\"", "\"\n ref=", "\n />\n </div>\n </div>\n ", "\n <", " eventEmitter=", " />\n </div>\n "], ["\n <div\n class=\"", "", "", "\"\n ref=", "\n >\n <", "\n ref=", "\n eventEmitter=", "\n previewStyle=", "\n toolbarItems=", "\n editorType=", "\n />\n <div\n class=\"", " ", "\"\n ref=", "\n >\n <div class=\"", "\">\n <div\n class=\"", " ", "\"\n ref=", "\n >\n <div class=\"", "\"></div>\n </div>\n <div\n class=\"", "\"\n ref=", "\n />\n </div>\n </div>\n ",
25291
+ "\n <", " eventEmitter=", " />\n </div>\n "])), themeClassName, cls('defaultUI'), displayClassName, function (el) { return (_this.refs.el = el); }, Toolbar, function (toolbar) { return (_this.toolbar = toolbar); }, eventEmitter, previewStyle, toolbarItems, editorType, cls('main'), editorTypeClassName, function (el) { return (_this.refs.editorSection = el); }, cls('main-container'), cls('md-container'), previewClassName, function (el) { return (_this.refs.mdContainer = el); }, cls('md-splitter'), cls('ww-container'), function (el) { return (_this.refs.wwContainer = el); }, !hideModeSwitch && html(templateObject_1$1 || (templateObject_1$1 = __makeTemplateObject(["<", " eventEmitter=", " editorType=", " />"], ["<", " eventEmitter=", " editorType=", " />"])), Switch, eventEmitter, editorType), ContextMenu, eventEmitter);
22846
25292
  };
22847
25293
  Layout.prototype.addEvent = function () {
22848
25294
  var eventEmitter = this.props.eventEmitter;