vendor: 6,750 bytes, lines 1-231
1/* 2Trix 2.1.12 3Copyright © 2024 37signals, LLC 4 */ 5(function (global, factory) { 6 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 7 typeof define === 'function' && define.amd ? define(factory) : 8 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Trix = factory()); 9})(this, (function () { 'use strict'; 10 11 var name = "trix"; 12 var version = "2.1.12"; 13 var description = "A rich text editor for everyday writing"; 14 var main = "dist/trix.umd.min.js"; 15 var module = "dist/trix.esm.min.js"; 16 var style = "dist/trix.css"; 17 var files = [ 18 "dist/*.css", 19 "dist/*.js", 20 "dist/*.map", 21 "src/{inspector,trix}/*.js" 22 ]; 23 var repository = { 24 type: "git", 25 url: "git+https://github.com/basecamp/trix.git" 26 }; 27 var keywords = [ 28 "rich text", 29 "wysiwyg", 30 "editor" 31 ]; 32 var author = "37signals, LLC"; 33 var license = "MIT"; 34 var bugs = { 35 url: "https://github.com/basecamp/trix/issues" 36 }; 37 var homepage = "https://trix-editor.org/"; 38 var devDependencies = { 39 "@babel/core": "^7.16.0", 40 "@babel/preset-env": "^7.16.4", 41 "@rollup/plugin-babel": "^5.3.0", 42 "@rollup/plugin-commonjs": "^22.0.2", 43 "@rollup/plugin-json": "^4.1.0", 44 "@rollup/plugin-node-resolve": "^13.3.0", 45 "@web/dev-server": "^0.1.34", 46 "babel-eslint": "^10.1.0", 47 chokidar: "^4.0.2", 48 concurrently: "^7.4.0", 49 eslint: "^7.32.0", 50 esm: "^3.2.25", 51 karma: "6.4.1", 52 "karma-chrome-launcher": "3.2.0", 53 "karma-qunit": "^4.1.2", 54 "karma-sauce-launcher": "^4.3.6", 55 qunit: "2.19.1", 56 rangy: "^1.3.0", 57 rollup: "^2.56.3", 58 "rollup-plugin-includepaths": "^0.2.4", 59 "rollup-plugin-terser": "^7.0.2", 60 sass: "^1.83.0", 61 svgo: "^2.8.0", 62 webdriverio: "^7.19.5" 63 }; 64 var resolutions = { 65 webdriverio: "^7.19.5" 66 }; 67 var scripts = { 68 "build-css": "bin/sass-build assets/trix.scss dist/trix.css", 69 "build-js": "rollup -c", 70 "build-assets": "cp -f assets/*.html dist/", 71 build: "yarn run build-js && yarn run build-css && yarn run build-assets", 72 watch: "rollup -c -w", 73 lint: "eslint .", 74 pretest: "yarn run lint && yarn run build", 75 test: "karma start", 76 prerelease: "yarn version && yarn test", 77 release: "npm adduser && npm publish", 78 postrelease: "git push && git push --tags", 79 dev: "web-dev-server --app-index index.html --root-dir dist --node-resolve --open", 80 start: "yarn build-assets && concurrently --kill-others --names js,css,dev-server 'yarn watch' 'yarn build-css --watch' 'yarn dev'" 81 }; 82 var dependencies = { 83 dompurify: "^3.2.3" 84 }; 85 var _package = { 86 name: name, 87 version: version, 88 description: description, 89 main: main, 90 module: module, 91 style: style, 92 files: files, 93 repository: repository, 94 keywords: keywords, 95 author: author, 96 license: license, 97 bugs: bugs, 98 homepage: homepage, 99 devDependencies: devDependencies, 100 resolutions: resolutions, 101 scripts: scripts, 102 dependencies: dependencies 103 }; 104 105 const attachmentSelector = "[data-trix-attachment]"; 106 const attachments = { 107 preview: { 108 presentation: "gallery", 109 caption: { 110 name: true, 111 size: true 112 } 113 }, 114 file: { 115 caption: { 116 size: true 117 } 118 } 119 }; 120 121 const attributes = { 122 default: { 123 tagName: "div", 124 parse: false 125 }, 126 quote: { 127 tagName: "blockquote", 128 nestable: true 129 }, 130 heading1: { 131 tagName: "h1", 132 terminal: true, 133 breakOnReturn: true, 134 group: false 135 }, 136 code: { 137 tagName: "pre", 138 terminal: true, 139 htmlAttributes: ["language"], 140 text: { 141 plaintext: true 142 } 143 }, 144 bulletList: { 145 tagName: "ul", 146 parse: false 147 }, 148 bullet: { 149 tagName: "li", 150 listAttribute: "bulletList", 151 group: false, 152 nestable: true, 153 test(element) { 154 return tagName$1(element.parentNode) === attributes[this.listAttribute].tagName; 155 } 156 }, 157 numberList: { 158 tagName: "ol", 159 parse: false 160 }, 161 number: { 162 tagName: "li", 163 listAttribute: "numberList", 164 group: false, 165 nestable: true, 166 test(element) { 167 return tagName$1(element.parentNode) === attributes[this.listAttribute].tagName; 168 } 169 }, 170 attachmentGallery: { 171 tagName: "div", 172 exclusive: true, 173 terminal: true, 174 parse: false, 175 group: false 176 } 177 }; 178 const tagName$1 = element => { 179 var _element$tagName; 180 return element === null || element === void 0 || (_element$tagName = element.tagName) === null || _element$tagName === void 0 ? void 0 : _element$tagName.toLowerCase(); 181 }; 182 183 const androidVersionMatch = navigator.userAgent.match(/android\s([0-9]+.*Chrome)/i); 184 const androidVersion = androidVersionMatch && parseInt(androidVersionMatch[1]); 185 var browser$1 = { 186 // Android emits composition events when moving the cursor through existing text 187 // Introduced in Chrome 65: https://bugs.chromium.org/p/chromium/issues/detail?id=764439#c9 188 composesExistingText: /Android.*Chrome/.test(navigator.userAgent), 189 // Android 13, especially on Samsung keyboards, emits extra compositionend and beforeinput events 190 // that can make the input handler lose the current selection or enter an infinite input -> render -> input 191 // loop. 192 recentAndroid: androidVersion && androidVersion > 12, 193 samsungAndroid: androidVersion && navigator.userAgent.match(/Android.*SM-/), 194 // IE 11 activates resizing handles on editable elements that have "layout" 195 forcesObjectResizing: /Trident.*rv:11/.test(navigator.userAgent), 196 // https://www.w3.org/TR/input-events-1/ + https://www.w3.org/TR/input-events-2/ 197 supportsInputEvents: typeof InputEvent !== "undefined" && ["data", "getTargetRanges", "inputType"].every(prop => prop in InputEvent.prototype) 198 }; 199 200 var css$3 = { 201 attachment: "attachment", 202 attachmentCaption: "attachment__caption", 203 attachmentCaptionEditor: "attachment__caption-editor", 204 attachmentMetadata: "attachment__metadata", 205 attachmentMetadataContainer: "attachment__metadata-container", 206 attachmentName: "attachment__name", 207 attachmentProgress: "attachment__progress", 208 attachmentSize: "attachment__size", 209 attachmentToolbar: "attachment__toolbar", 210 attachmentGallery: "attachment-gallery" 211 }; 212 213 var dompurify = { 214 ADD_ATTR: ["language"], 215 SAFE_FOR_XML: false, 216 RETURN_DOM: true 217 }; 218 219 var lang$1 = { 220 attachFiles: "Attach Files", 221 bold: "Bold", 222 bullets: "Bullets", 223 byte: "Byte", 224 bytes: "Bytes", 225 captionPlaceholder: "Add a captionâ¦", 226 code: "Code", 227 heading1: "Heading", 228 indent: "Increase Level", 229 italic: "Italic", 230 link: "Link", 231 numbers: "Numbers",
vendor: 3,320 bytes, lines 232-340
232 outdent: "Decrease Level", 233 quote: "Quote", 234 redo: "Redo", 235 remove: "Remove", 236 strike: "Strikethrough", 237 undo: "Undo", 238 unlink: "Unlink", 239 url: "URL", 240 urlPlaceholder: "Enter a URLâ¦", 241 GB: "GB", 242 KB: "KB", 243 MB: "MB", 244 PB: "PB", 245 TB: "TB" 246 }; 247 248 /* eslint-disable 249 no-case-declarations, 250 */ 251 const sizes = [lang$1.bytes, lang$1.KB, lang$1.MB, lang$1.GB, lang$1.TB, lang$1.PB]; 252 var file_size_formatting = { 253 prefix: "IEC", 254 precision: 2, 255 formatter(number) { 256 switch (number) { 257 case 0: 258 return "0 ".concat(lang$1.bytes); 259 case 1: 260 return "1 ".concat(lang$1.byte); 261 default: 262 let base; 263 if (this.prefix === "SI") { 264 base = 1000; 265 } else if (this.prefix === "IEC") { 266 base = 1024; 267 } 268 const exp = Math.floor(Math.log(number) / Math.log(base)); 269 const humanSize = number / Math.pow(base, exp); 270 const string = humanSize.toFixed(this.precision); 271 const withoutInsignificantZeros = string.replace(/0*$/, "").replace(/\.$/, ""); 272 return "".concat(withoutInsignificantZeros, " ").concat(sizes[exp]); 273 } 274 } 275 }; 276 277 const ZERO_WIDTH_SPACE = "\uFEFF"; 278 const NON_BREAKING_SPACE = "\u00A0"; 279 const OBJECT_REPLACEMENT_CHARACTER = "\uFFFC"; 280 281 const extend = function (properties) { 282 for (const key in properties) { 283 const value = properties[key]; 284 this[key] = value; 285 } 286 return this; 287 }; 288 289 const html$2 = document.documentElement; 290 const match = html$2.matches; 291 const handleEvent = function (eventName) { 292 let { 293 onElement, 294 matchingSelector, 295 withCallback, 296 inPhase, 297 preventDefault, 298 times 299 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 300 const element = onElement ? onElement : html$2; 301 const selector = matchingSelector; 302 const useCapture = inPhase === "capturing"; 303 const handler = function (event) { 304 if (times != null && --times === 0) { 305 handler.destroy(); 306 } 307 const target = findClosestElementFromNode(event.target, { 308 matchingSelector: selector 309 }); 310 if (target != null) { 311 withCallback === null || withCallback === void 0 || withCallback.call(target, event, target); 312 if (preventDefault) { 313 event.preventDefault(); 314 } 315 } 316 }; 317 handler.destroy = () => element.removeEventListener(eventName, handler, useCapture); 318 element.addEventListener(eventName, handler, useCapture); 319 return handler; 320 }; 321 const handleEventOnce = function (eventName) { 322 let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 323 options.times = 1; 324 return handleEvent(eventName, options); 325 }; 326 const triggerEvent = function (eventName) { 327 let { 328 onElement, 329 bubbles, 330 cancelable, 331 attributes 332 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 333 const element = onElement != null ? onElement : html$2; 334 bubbles = bubbles !== false; 335 cancelable = cancelable !== false; 336 const event = document.createEvent("Events"); 337 event.initEvent(eventName, bubbles, cancelable); 338 if (attributes != null) { 339 extend.call(event, attributes); 340 }
vendor: 47,974 bytes, lines 340-1745
340 341 return element.dispatchEvent(event); 342 }; 343 const elementMatchesSelector = function (element, selector) { 344 if ((element === null || element === void 0 ? void 0 : element.nodeType) === 1) { 345 return match.call(element, selector); 346 } 347 }; 348 const findClosestElementFromNode = function (node) { 349 let { 350 matchingSelector, 351 untilNode 352 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 353 while (node && node.nodeType !== Node.ELEMENT_NODE) { 354 node = node.parentNode; 355 } 356 if (node == null) { 357 return; 358 } 359 if (matchingSelector != null) { 360 if (node.closest && untilNode == null) { 361 return node.closest(matchingSelector); 362 } else { 363 while (node && node !== untilNode) { 364 if (elementMatchesSelector(node, matchingSelector)) { 365 return node; 366 } 367 node = node.parentNode; 368 } 369 } 370 } else { 371 return node; 372 } 373 }; 374 const findInnerElement = function (element) { 375 while ((_element = element) !== null && _element !== void 0 && _element.firstElementChild) { 376 var _element; 377 element = element.firstElementChild; 378 } 379 return element; 380 }; 381 const innerElementIsActive = element => document.activeElement !== element && elementContainsNode(element, document.activeElement); 382 const elementContainsNode = function (element, node) { 383 if (!element || !node) { 384 return; 385 } 386 while (node) { 387 if (node === element) { 388 return true; 389 } 390 node = node.parentNode; 391 } 392 }; 393 const findNodeFromContainerAndOffset = function (container, offset) { 394 if (!container) { 395 return; 396 } 397 if (container.nodeType === Node.TEXT_NODE) { 398 return container; 399 } else if (offset === 0) { 400 return container.firstChild != null ? container.firstChild : container; 401 } else { 402 return container.childNodes.item(offset - 1); 403 } 404 }; 405 const findElementFromContainerAndOffset = function (container, offset) { 406 const node = findNodeFromContainerAndOffset(container, offset); 407 return findClosestElementFromNode(node); 408 }; 409 const findChildIndexOfNode = function (node) { 410 var _node; 411 if (!((_node = node) !== null && _node !== void 0 && _node.parentNode)) { 412 return; 413 } 414 let childIndex = 0; 415 node = node.previousSibling; 416 while (node) { 417 childIndex++; 418 node = node.previousSibling; 419 } 420 return childIndex; 421 }; 422 const removeNode = node => { 423 var _node$parentNode; 424 return node === null || node === void 0 || (_node$parentNode = node.parentNode) === null || _node$parentNode === void 0 ? void 0 : _node$parentNode.removeChild(node); 425 }; 426 const walkTree = function (tree) { 427 let { 428 onlyNodesOfType, 429 usingFilter, 430 expandEntityReferences 431 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 432 const whatToShow = (() => { 433 switch (onlyNodesOfType) { 434 case "element": 435 return NodeFilter.SHOW_ELEMENT; 436 case "text": 437 return NodeFilter.SHOW_TEXT; 438 case "comment": 439 return NodeFilter.SHOW_COMMENT; 440 default: 441 return NodeFilter.SHOW_ALL; 442 } 443 })(); 444 return document.createTreeWalker(tree, whatToShow, usingFilter != null ? usingFilter : null, expandEntityReferences === true); 445 }; 446 const tagName = element => { 447 var _element$tagName; 448 return element === null || element === void 0 || (_element$tagName = element.tagName) === null || _element$tagName === void 0 ? void 0 : _element$tagName.toLowerCase(); 449 }; 450 const makeElement = function (tag) { 451 let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 452 let key, value; 453 if (typeof tag === "object") { 454 options = tag; 455 tag = options.tagName; 456 } else { 457 options = { 458 attributes: options 459 }; 460 } 461 const element = document.createElement(tag); 462 if (options.editable != null) { 463 if (options.attributes == null) { 464 options.attributes = {}; 465 } 466 options.attributes.contenteditable = options.editable; 467 } 468 if (options.attributes) { 469 for (key in options.attributes) { 470 value = options.attributes[key]; 471 element.setAttribute(key, value); 472 } 473 } 474 if (options.style) { 475 for (key in options.style) { 476 value = options.style[key]; 477 element.style[key] = value; 478 } 479 } 480 if (options.data) { 481 for (key in options.data) { 482 value = options.data[key]; 483 element.dataset[key] = value; 484 } 485 } 486 if (options.className) { 487 options.className.split(" ").forEach(className => { 488 element.classList.add(className); 489 }); 490 } 491 if (options.textContent) { 492 element.textContent = options.textContent; 493 } 494 if (options.childNodes) { 495 [].concat(options.childNodes).forEach(childNode => { 496 element.appendChild(childNode); 497 }); 498 } 499 return element; 500 }; 501 let blockTagNames = undefined; 502 const getBlockTagNames = function () { 503 if (blockTagNames != null) { 504 return blockTagNames; 505 } 506 blockTagNames = []; 507 for (const key in attributes) { 508 const attributes$1 = attributes[key]; 509 if (attributes$1.tagName) { 510 blockTagNames.push(attributes$1.tagName); 511 } 512 } 513 return blockTagNames; 514 }; 515 const nodeIsBlockContainer = node => nodeIsBlockStartComment(node === null || node === void 0 ? void 0 : node.firstChild); 516 const nodeProbablyIsBlockContainer = function (node) { 517 return getBlockTagNames().includes(tagName(node)) && !getBlockTagNames().includes(tagName(node.firstChild)); 518 }; 519 const nodeIsBlockStart = function (node) { 520 let { 521 strict 522 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { 523 strict: true 524 }; 525 if (strict) { 526 return nodeIsBlockStartComment(node); 527 } else { 528 return nodeIsBlockStartComment(node) || !nodeIsBlockStartComment(node.firstChild) && nodeProbablyIsBlockContainer(node); 529 } 530 }; 531 const nodeIsBlockStartComment = node => nodeIsCommentNode(node) && (node === null || node === void 0 ? void 0 : node.data) === "block"; 532 const nodeIsCommentNode = node => (node === null || node === void 0 ? void 0 : node.nodeType) === Node.COMMENT_NODE; 533 const nodeIsCursorTarget = function (node) { 534 let { 535 name 536 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 537 if (!node) { 538 return; 539 } 540 if (nodeIsTextNode(node)) { 541 if (node.data === ZERO_WIDTH_SPACE) { 542 if (name) { 543 return node.parentNode.dataset.trixCursorTarget === name; 544 } else { 545 return true; 546 } 547 } 548 } else { 549 return nodeIsCursorTarget(node.firstChild); 550 } 551 }; 552 const nodeIsAttachmentElement = node => elementMatchesSelector(node, attachmentSelector); 553 const nodeIsEmptyTextNode = node => nodeIsTextNode(node) && (node === null || node === void 0 ? void 0 : node.data) === ""; 554 const nodeIsTextNode = node => (node === null || node === void 0 ? void 0 : node.nodeType) === Node.TEXT_NODE; 555 556 const input = { 557 level2Enabled: true, 558 getLevel() { 559 if (this.level2Enabled && browser$1.supportsInputEvents) { 560 return 2; 561 } else { 562 return 0; 563 } 564 }, 565 pickFiles(callback) { 566 const input = makeElement("input", { 567 type: "file", 568 multiple: true, 569 hidden: true, 570 id: this.fileInputId 571 }); 572 input.addEventListener("change", () => { 573 callback(input.files); 574 removeNode(input); 575 }); 576 removeNode(document.getElementById(this.fileInputId)); 577 document.body.appendChild(input); 578 input.click(); 579 } 580 }; 581 582 var key_names = { 583 8: "backspace", 584 9: "tab", 585 13: "return", 586 27: "escape", 587 37: "left", 588 39: "right", 589 46: "delete", 590 68: "d", 591 72: "h", 592 79: "o" 593 }; 594 595 var parser = { 596 removeBlankTableCells: false, 597 tableCellSeparator: " | ", 598 tableRowSeparator: "\n" 599 }; 600 601 var text_attributes = { 602 bold: { 603 tagName: "strong", 604 inheritable: true, 605 parser(element) { 606 const style = window.getComputedStyle(element); 607 return style.fontWeight === "bold" || style.fontWeight >= 600; 608 } 609 }, 610 italic: { 611 tagName: "em", 612 inheritable: true, 613 parser(element) { 614 const style = window.getComputedStyle(element); 615 return style.fontStyle === "italic"; 616 } 617 }, 618 href: { 619 groupTagName: "a", 620 parser(element) { 621 const matchingSelector = "a:not(".concat(attachmentSelector, ")"); 622 const link = element.closest(matchingSelector); 623 if (link) { 624 return link.getAttribute("href"); 625 } 626 } 627 }, 628 strike: { 629 tagName: "del", 630 inheritable: true 631 }, 632 frozen: { 633 style: { 634 backgroundColor: "highlight" 635 } 636 } 637 }; 638 639 var toolbar = { 640 getDefaultHTML() { 641 return "<div class=\"trix-button-row\">\n <span class=\"trix-button-group trix-button-group--text-tools\" data-trix-button-group=\"text-tools\">\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-bold\" data-trix-attribute=\"bold\" data-trix-key=\"b\" title=\"".concat(lang$1.bold, "\" tabindex=\"-1\">").concat(lang$1.bold, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-italic\" data-trix-attribute=\"italic\" data-trix-key=\"i\" title=\"").concat(lang$1.italic, "\" tabindex=\"-1\">").concat(lang$1.italic, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-strike\" data-trix-attribute=\"strike\" title=\"").concat(lang$1.strike, "\" tabindex=\"-1\">").concat(lang$1.strike, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-link\" data-trix-attribute=\"href\" data-trix-action=\"link\" data-trix-key=\"k\" title=\"").concat(lang$1.link, "\" tabindex=\"-1\">").concat(lang$1.link, "</button>\n </span>\n\n <span class=\"trix-button-group trix-button-group--block-tools\" data-trix-button-group=\"block-tools\">\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-heading-1\" data-trix-attribute=\"heading1\" title=\"").concat(lang$1.heading1, "\" tabindex=\"-1\">").concat(lang$1.heading1, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-quote\" data-trix-attribute=\"quote\" title=\"").concat(lang$1.quote, "\" tabindex=\"-1\">").concat(lang$1.quote, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-code\" data-trix-attribute=\"code\" title=\"").concat(lang$1.code, "\" tabindex=\"-1\">").concat(lang$1.code, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-bullet-list\" data-trix-attribute=\"bullet\" title=\"").concat(lang$1.bullets, "\" tabindex=\"-1\">").concat(lang$1.bullets, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-number-list\" data-trix-attribute=\"number\" title=\"").concat(lang$1.numbers, "\" tabindex=\"-1\">").concat(lang$1.numbers, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-decrease-nesting-level\" data-trix-action=\"decreaseNestingLevel\" title=\"").concat(lang$1.outdent, "\" tabindex=\"-1\">").concat(lang$1.outdent, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-increase-nesting-level\" data-trix-action=\"increaseNestingLevel\" title=\"").concat(lang$1.indent, "\" tabindex=\"-1\">").concat(lang$1.indent, "</button>\n </span>\n\n <span class=\"trix-button-group trix-button-group--file-tools\" data-trix-button-group=\"file-tools\">\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-attach\" data-trix-action=\"attachFiles\" title=\"").concat(lang$1.attachFiles, "\" tabindex=\"-1\">").concat(lang$1.attachFiles, "</button>\n </span>\n\n <span class=\"trix-button-group-spacer\"></span>\n\n <span class=\"trix-button-group trix-button-group--history-tools\" data-trix-button-group=\"history-tools\">\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-undo\" data-trix-action=\"undo\" data-trix-key=\"z\" title=\"").concat(lang$1.undo, "\" tabindex=\"-1\">").concat(lang$1.undo, "</button>\n <button type=\"button\" class=\"trix-button trix-button--icon trix-button--icon-redo\" data-trix-action=\"redo\" data-trix-key=\"shift+z\" title=\"").concat(lang$1.redo, "\" tabindex=\"-1\">").concat(lang$1.redo, "</button>\n </span>\n </div>\n\n <div class=\"trix-dialogs\" data-trix-dialogs>\n <div class=\"trix-dialog trix-dialog--link\" data-trix-dialog=\"href\" data-trix-dialog-attribute=\"href\">\n <div class=\"trix-dialog__link-fields\">\n <input type=\"url\" name=\"href\" class=\"trix-input trix-input--dialog\" placeholder=\"").concat(lang$1.urlPlaceholder, "\" aria-label=\"").concat(lang$1.url, "\" data-trix-validate-href required data-trix-input>\n <div class=\"trix-button-group\">\n <input type=\"button\" class=\"trix-button trix-button--dialog\" value=\"").concat(lang$1.link, "\" data-trix-method=\"setAttribute\">\n <input type=\"button\" class=\"trix-button trix-button--dialog\" value=\"").concat(lang$1.unlink, "\" data-trix-method=\"removeAttribute\">\n </div>\n </div>\n </div>\n </div>"); 642 } 643 }; 644 645 const undo = { 646 interval: 5000 647 }; 648 649 var config = /*#__PURE__*/Object.freeze({ 650 __proto__: null, 651 attachments: attachments, 652 blockAttributes: attributes, 653 browser: browser$1, 654 css: css$3, 655 dompurify: dompurify, 656 fileSize: file_size_formatting, 657 input: input, 658 keyNames: key_names, 659 lang: lang$1, 660 parser: parser, 661 textAttributes: text_attributes, 662 toolbar: toolbar, 663 undo: undo 664 }); 665 666 class BasicObject { 667 static proxyMethod(expression) { 668 const { 669 name, 670 toMethod, 671 toProperty, 672 optional 673 } = parseProxyMethodExpression(expression); 674 this.prototype[name] = function () { 675 let subject; 676 let object; 677 if (toMethod) { 678 if (optional) { 679 var _this$toMethod; 680 object = (_this$toMethod = this[toMethod]) === null || _this$toMethod === void 0 ? void 0 : _this$toMethod.call(this); 681 } else { 682 object = this[toMethod](); 683 } 684 } else if (toProperty) { 685 object = this[toProperty]; 686 } 687 if (optional) { 688 var _object; 689 subject = (_object = object) === null || _object === void 0 ? void 0 : _object[name]; 690 if (subject) { 691 return apply$1.call(subject, object, arguments); 692 } 693 } else { 694 subject = object[name]; 695 return apply$1.call(subject, object, arguments); 696 } 697 }; 698 } 699 } 700 const parseProxyMethodExpression = function (expression) { 701 const match = expression.match(proxyMethodExpressionPattern); 702 if (!match) { 703 throw new Error("can't parse @proxyMethod expression: ".concat(expression)); 704 } 705 const args = { 706 name: match[4] 707 }; 708 if (match[2] != null) { 709 args.toMethod = match[1]; 710 } else { 711 args.toProperty = match[1]; 712 } 713 if (match[3] != null) { 714 args.optional = true; 715 } 716 return args; 717 }; 718 const { 719 apply: apply$1 720 } = Function.prototype; 721 const proxyMethodExpressionPattern = new RegExp("\ 722^\ 723(.+?)\ 724(\\(\\))?\ 725(\\?)?\ 726\\.\ 727(.+?)\ 728$\ 729"); 730 731 var _Array$from, _$codePointAt$1, _$1, _String$fromCodePoint; 732 class UTF16String extends BasicObject { 733 static box() { 734 let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; 735 if (value instanceof this) { 736 return value; 737 } else { 738 return this.fromUCS2String(value === null || value === void 0 ? void 0 : value.toString()); 739 } 740 } 741 static fromUCS2String(ucs2String) { 742 return new this(ucs2String, ucs2decode(ucs2String)); 743 } 744 static fromCodepoints(codepoints) { 745 return new this(ucs2encode(codepoints), codepoints); 746 } 747 constructor(ucs2String, codepoints) { 748 super(...arguments); 749 this.ucs2String = ucs2String; 750 this.codepoints = codepoints; 751 this.length = this.codepoints.length; 752 this.ucs2Length = this.ucs2String.length; 753 } 754 offsetToUCS2Offset(offset) { 755 return ucs2encode(this.codepoints.slice(0, Math.max(0, offset))).length; 756 } 757 offsetFromUCS2Offset(ucs2Offset) { 758 return ucs2decode(this.ucs2String.slice(0, Math.max(0, ucs2Offset))).length; 759 } 760 slice() { 761 return this.constructor.fromCodepoints(this.codepoints.slice(...arguments)); 762 } 763 charAt(offset) { 764 return this.slice(offset, offset + 1); 765 } 766 isEqualTo(value) { 767 return this.constructor.box(value).ucs2String === this.ucs2String; 768 } 769 toJSON() { 770 return this.ucs2String; 771 } 772 getCacheKey() { 773 return this.ucs2String; 774 } 775 toString() { 776 return this.ucs2String; 777 } 778 } 779 const hasArrayFrom = ((_Array$from = Array.from) === null || _Array$from === void 0 ? void 0 : _Array$from.call(Array, "\ud83d\udc7c").length) === 1; 780 const hasStringCodePointAt$1 = ((_$codePointAt$1 = (_$1 = " ").codePointAt) === null || _$codePointAt$1 === void 0 ? void 0 : _$codePointAt$1.call(_$1, 0)) != null; 781 const hasStringFromCodePoint = ((_String$fromCodePoint = String.fromCodePoint) === null || _String$fromCodePoint === void 0 ? void 0 : _String$fromCodePoint.call(String, 32, 128124)) === " \ud83d\udc7c"; 782 783 // UCS-2 conversion helpers ported from Mathias Bynens' Punycode.js: 784 // https://github.com/bestiejs/punycode.js#punycodeucs2 785 786 let ucs2decode, ucs2encode; 787 788 // Creates an array containing the numeric code points of each Unicode 789 // character in the string. While JavaScript uses UCS-2 internally, 790 // this function will convert a pair of surrogate halves (each of which 791 // UCS-2 exposes as separate characters) into a single code point, 792 // matching UTF-16. 793 if (hasArrayFrom && hasStringCodePointAt$1) { 794 ucs2decode = string => Array.from(string).map(char => char.codePointAt(0)); 795 } else { 796 ucs2decode = function (string) { 797 const output = []; 798 let counter = 0; 799 const { 800 length 801 } = string; 802 while (counter < length) { 803 let value = string.charCodeAt(counter++); 804 if (0xd800 <= value && value <= 0xdbff && counter < length) { 805 // high surrogate, and there is a next character 806 const extra = string.charCodeAt(counter++); 807 if ((extra & 0xfc00) === 0xdc00) { 808 // low surrogate 809 value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000; 810 } else { 811 // unmatched surrogate; only append this code unit, in case the 812 // next code unit is the high surrogate of a surrogate pair 813 counter--; 814 } 815 } 816 output.push(value); 817 } 818 return output; 819 }; 820 } 821 822 // Creates a string based on an array of numeric code points. 823 if (hasStringFromCodePoint) { 824 ucs2encode = array => String.fromCodePoint(...Array.from(array || [])); 825 } else { 826 ucs2encode = function (array) { 827 const characters = (() => { 828 const result = []; 829 Array.from(array).forEach(value => { 830 let output = ""; 831 if (value > 0xffff) { 832 value -= 0x10000; 833 output += String.fromCharCode(value >>> 10 & 0x3ff | 0xd800); 834 value = 0xdc00 | value & 0x3ff; 835 } 836 result.push(output + String.fromCharCode(value)); 837 }); 838 return result; 839 })(); 840 return characters.join(""); 841 }; 842 } 843 844 let id$2 = 0; 845 class TrixObject extends BasicObject { 846 static fromJSONString(jsonString) { 847 return this.fromJSON(JSON.parse(jsonString)); 848 } 849 constructor() { 850 super(...arguments); 851 this.id = ++id$2; 852 } 853 hasSameConstructorAs(object) { 854 return this.constructor === (object === null || object === void 0 ? void 0 : object.constructor); 855 } 856 isEqualTo(object) { 857 return this === object; 858 } 859 inspect() { 860 const parts = []; 861 const contents = this.contentsForInspection() || {}; 862 for (const key in contents) { 863 const value = contents[key]; 864 parts.push("".concat(key, "=").concat(value)); 865 } 866 return "#<".concat(this.constructor.name, ":").concat(this.id).concat(parts.length ? " ".concat(parts.join(", ")) : "", ">"); 867 } 868 contentsForInspection() {} 869 toJSONString() { 870 return JSON.stringify(this); 871 } 872 toUTF16String() { 873 return UTF16String.box(this); 874 } 875 getCacheKey() { 876 return this.id.toString(); 877 } 878 } 879 880 /* eslint-disable 881 id-length, 882 */ 883 const arraysAreEqual = function () { 884 let a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 885 let b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; 886 if (a.length !== b.length) { 887 return false; 888 } 889 for (let index = 0; index < a.length; index++) { 890 const value = a[index]; 891 if (value !== b[index]) { 892 return false; 893 } 894 } 895 return true; 896 }; 897 const arrayStartsWith = function () { 898 let a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 899 let b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; 900 return arraysAreEqual(a.slice(0, b.length), b); 901 }; 902 const spliceArray = function (array) { 903 const result = array.slice(0); 904 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { 905 args[_key - 1] = arguments[_key]; 906 } 907 result.splice(...args); 908 return result; 909 }; 910 const summarizeArrayChange = function () { 911 let oldArray = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 912 let newArray = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; 913 const added = []; 914 const removed = []; 915 const existingValues = new Set(); 916 oldArray.forEach(value => { 917 existingValues.add(value); 918 }); 919 const currentValues = new Set(); 920 newArray.forEach(value => { 921 currentValues.add(value); 922 if (!existingValues.has(value)) { 923 added.push(value); 924 } 925 }); 926 oldArray.forEach(value => { 927 if (!currentValues.has(value)) { 928 removed.push(value); 929 } 930 }); 931 return { 932 added, 933 removed 934 }; 935 }; 936 937 // https://github.com/mathiasbynens/unicode-2.1.8/blob/master/Bidi_Class/Right_To_Left/regex.js 938 const RTL_PATTERN = /[\u05BE\u05C0\u05C3\u05D0-\u05EA\u05F0-\u05F4\u061B\u061F\u0621-\u063A\u0640-\u064A\u066D\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D5\u06E5\u06E6\u200F\u202B\u202E\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE72\uFE74\uFE76-\uFEFC]/; 939 const getDirection = function () { 940 const input = makeElement("input", { 941 dir: "auto", 942 name: "x", 943 dirName: "x.dir" 944 }); 945 const textArea = makeElement("textarea", { 946 dir: "auto", 947 name: "y", 948 dirName: "y.dir" 949 }); 950 const form = makeElement("form"); 951 form.appendChild(input); 952 form.appendChild(textArea); 953 const supportsDirName = function () { 954 try { 955 return new FormData(form).has(textArea.dirName); 956 } catch (error) { 957 return false; 958 } 959 }(); 960 const supportsDirSelector = function () { 961 try { 962 return input.matches(":dir(ltr),:dir(rtl)"); 963 } catch (error) { 964 return false; 965 } 966 }(); 967 if (supportsDirName) { 968 return function (string) { 969 textArea.value = string; 970 return new FormData(form).get(textArea.dirName); 971 }; 972 } else if (supportsDirSelector) { 973 return function (string) { 974 input.value = string; 975 if (input.matches(":dir(rtl)")) { 976 return "rtl"; 977 } else { 978 return "ltr"; 979 } 980 }; 981 } else { 982 return function (string) { 983 const char = string.trim().charAt(0); 984 if (RTL_PATTERN.test(char)) { 985 return "rtl"; 986 } else { 987 return "ltr"; 988 } 989 }; 990 } 991 }(); 992 993 let allAttributeNames = null; 994 let blockAttributeNames = null; 995 let textAttributeNames = null; 996 let listAttributeNames = null; 997 const getAllAttributeNames = () => { 998 if (!allAttributeNames) { 999 allAttributeNames = getTextAttributeNames().concat(getBlockAttributeNames()); 1000 } 1001 return allAttributeNames; 1002 }; 1003 const getBlockConfig = attributeName => attributes[attributeName]; 1004 const getBlockAttributeNames = () => { 1005 if (!blockAttributeNames) { 1006 blockAttributeNames = Object.keys(attributes); 1007 } 1008 return blockAttributeNames; 1009 }; 1010 const getTextConfig = attributeName => text_attributes[attributeName]; 1011 const getTextAttributeNames = () => { 1012 if (!textAttributeNames) { 1013 textAttributeNames = Object.keys(text_attributes); 1014 } 1015 return textAttributeNames; 1016 }; 1017 const getListAttributeNames = () => { 1018 if (!listAttributeNames) { 1019 listAttributeNames = []; 1020 for (const key in attributes) { 1021 const { 1022 listAttribute 1023 } = attributes[key]; 1024 if (listAttribute != null) { 1025 listAttributeNames.push(listAttribute); 1026 } 1027 } 1028 } 1029 return listAttributeNames; 1030 }; 1031 1032 /* eslint-disable 1033 */ 1034 const installDefaultCSSForTagName = function (tagName, defaultCSS) { 1035 const styleElement = insertStyleElementForTagName(tagName); 1036 styleElement.textContent = defaultCSS.replace(/%t/g, tagName); 1037 }; 1038 const insertStyleElementForTagName = function (tagName) { 1039 const element = document.createElement("style"); 1040 element.setAttribute("type", "text/css"); 1041 element.setAttribute("data-tag-name", tagName.toLowerCase()); 1042 const nonce = getCSPNonce(); 1043 if (nonce) { 1044 element.setAttribute("nonce", nonce); 1045 } 1046 document.head.insertBefore(element, document.head.firstChild); 1047 return element; 1048 }; 1049 const getCSPNonce = function () { 1050 const element = getMetaElement("trix-csp-nonce") || getMetaElement("csp-nonce"); 1051 if (element) { 1052 const { 1053 nonce, 1054 content 1055 } = element; 1056 return nonce == "" ? content : nonce; 1057 } 1058 }; 1059 const getMetaElement = name => document.head.querySelector("meta[name=".concat(name, "]")); 1060 1061 const testTransferData = { 1062 "application/x-trix-feature-detection": "test" 1063 }; 1064 const dataTransferIsPlainText = function (dataTransfer) { 1065 const text = dataTransfer.getData("text/plain"); 1066 const html = dataTransfer.getData("text/html"); 1067 if (text && html) { 1068 const { 1069 body 1070 } = new DOMParser().parseFromString(html, "text/html"); 1071 if (body.textContent === text) { 1072 return !body.querySelector("*"); 1073 } 1074 } else { 1075 return text === null || text === void 0 ? void 0 : text.length; 1076 } 1077 }; 1078 const dataTransferIsMsOfficePaste = _ref => { 1079 let { 1080 dataTransfer 1081 } = _ref; 1082 return dataTransfer.types.includes("Files") && dataTransfer.types.includes("text/html") && dataTransfer.getData("text/html").includes("urn:schemas-microsoft-com:office:office"); 1083 }; 1084 const dataTransferIsWritable = function (dataTransfer) { 1085 if (!(dataTransfer !== null && dataTransfer !== void 0 && dataTransfer.setData)) return false; 1086 for (const key in testTransferData) { 1087 const value = testTransferData[key]; 1088 try { 1089 dataTransfer.setData(key, value); 1090 if (!dataTransfer.getData(key) === value) return false; 1091 } catch (error) { 1092 return false; 1093 } 1094 } 1095 return true; 1096 }; 1097 const keyEventIsKeyboardCommand = function () { 1098 if (/Mac|^iP/.test(navigator.platform)) { 1099 return event => event.metaKey; 1100 } else { 1101 return event => event.ctrlKey; 1102 } 1103 }(); 1104 function shouldRenderInmmediatelyToDealWithIOSDictation(inputEvent) { 1105 if (/iPhone|iPad/.test(navigator.userAgent)) { 1106 // Handle garbled content and duplicated newlines when using dictation on iOS 18+. Upon dictation completion, iOS sends 1107 // the list of insertText / insertParagraph events in a quick sequence. If we don't render 1108 // the editor synchronously, the internal range fails to update and results in garbled content or duplicated newlines. 1109 // 1110 // This workaround is necessary because iOS doesn't send composing events as expected while dictating: 1111 // https://bugs.webkit.org/show_bug.cgi?id=261764 1112 return !inputEvent.inputType || inputEvent.inputType === "insertParagraph"; 1113 } else { 1114 return false; 1115 } 1116 } 1117 1118 const defer = fn => setTimeout(fn, 1); 1119 1120 /* eslint-disable 1121 id-length, 1122 */ 1123 const copyObject = function () { 1124 let object = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 1125 const result = {}; 1126 for (const key in object) { 1127 const value = object[key]; 1128 result[key] = value; 1129 } 1130 return result; 1131 }; 1132 const objectsAreEqual = function () { 1133 let a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 1134 let b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 1135 if (Object.keys(a).length !== Object.keys(b).length) { 1136 return false; 1137 } 1138 for (const key in a) { 1139 const value = a[key]; 1140 if (value !== b[key]) { 1141 return false; 1142 } 1143 } 1144 return true; 1145 }; 1146 1147 const normalizeRange = function (range) { 1148 if (range == null) return; 1149 if (!Array.isArray(range)) { 1150 range = [range, range]; 1151 } 1152 return [copyValue(range[0]), copyValue(range[1] != null ? range[1] : range[0])]; 1153 }; 1154 const rangeIsCollapsed = function (range) { 1155 if (range == null) return; 1156 const [start, end] = normalizeRange(range); 1157 return rangeValuesAreEqual(start, end); 1158 }; 1159 const rangesAreEqual = function (leftRange, rightRange) { 1160 if (leftRange == null || rightRange == null) return; 1161 const [leftStart, leftEnd] = normalizeRange(leftRange); 1162 const [rightStart, rightEnd] = normalizeRange(rightRange); 1163 return rangeValuesAreEqual(leftStart, rightStart) && rangeValuesAreEqual(leftEnd, rightEnd); 1164 }; 1165 const copyValue = function (value) { 1166 if (typeof value === "number") { 1167 return value; 1168 } else { 1169 return copyObject(value); 1170 } 1171 }; 1172 const rangeValuesAreEqual = function (left, right) { 1173 if (typeof left === "number") { 1174 return left === right; 1175 } else { 1176 return objectsAreEqual(left, right); 1177 } 1178 }; 1179 1180 class SelectionChangeObserver extends BasicObject { 1181 constructor() { 1182 super(...arguments); 1183 this.update = this.update.bind(this); 1184 this.selectionManagers = []; 1185 } 1186 start() { 1187 if (!this.started) { 1188 this.started = true; 1189 document.addEventListener("selectionchange", this.update, true); 1190 } 1191 } 1192 stop() { 1193 if (this.started) { 1194 this.started = false; 1195 return document.removeEventListener("selectionchange", this.update, true); 1196 } 1197 } 1198 registerSelectionManager(selectionManager) { 1199 if (!this.selectionManagers.includes(selectionManager)) { 1200 this.selectionManagers.push(selectionManager); 1201 return this.start(); 1202 } 1203 } 1204 unregisterSelectionManager(selectionManager) { 1205 this.selectionManagers = this.selectionManagers.filter(sm => sm !== selectionManager); 1206 if (this.selectionManagers.length === 0) { 1207 return this.stop(); 1208 } 1209 } 1210 notifySelectionManagersOfSelectionChange() { 1211 return this.selectionManagers.map(selectionManager => selectionManager.selectionDidChange()); 1212 } 1213 update() { 1214 this.notifySelectionManagersOfSelectionChange(); 1215 } 1216 reset() { 1217 this.update(); 1218 } 1219 } 1220 const selectionChangeObserver = new SelectionChangeObserver(); 1221 const getDOMSelection = function () { 1222 const selection = window.getSelection(); 1223 if (selection.rangeCount > 0) { 1224 return selection; 1225 } 1226 }; 1227 const getDOMRange = function () { 1228 var _getDOMSelection; 1229 const domRange = (_getDOMSelection = getDOMSelection()) === null || _getDOMSelection === void 0 ? void 0 : _getDOMSelection.getRangeAt(0); 1230 if (domRange) { 1231 if (!domRangeIsPrivate(domRange)) { 1232 return domRange; 1233 } 1234 } 1235 }; 1236 const setDOMRange = function (domRange) { 1237 const selection = window.getSelection(); 1238 selection.removeAllRanges(); 1239 selection.addRange(domRange); 1240 return selectionChangeObserver.update(); 1241 }; 1242 1243 // In Firefox, clicking certain <input> elements changes the selection to a 1244 // private element used to draw its UI. Attempting to access properties of those 1245 // elements throws an error. 1246 // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 1247 const domRangeIsPrivate = domRange => nodeIsPrivate(domRange.startContainer) || nodeIsPrivate(domRange.endContainer); 1248 const nodeIsPrivate = node => !Object.getPrototypeOf(node); 1249 1250 /* eslint-disable 1251 id-length, 1252 no-useless-escape, 1253 */ 1254 const normalizeSpaces = string => string.replace(new RegExp("".concat(ZERO_WIDTH_SPACE), "g"), "").replace(new RegExp("".concat(NON_BREAKING_SPACE), "g"), " "); 1255 const normalizeNewlines = string => string.replace(/\r\n?/g, "\n"); 1256 const breakableWhitespacePattern = new RegExp("[^\\S".concat(NON_BREAKING_SPACE, "]")); 1257 const squishBreakableWhitespace = string => string 1258 // Replace all breakable whitespace characters with a space 1259 .replace(new RegExp("".concat(breakableWhitespacePattern.source), "g"), " ") 1260 // Replace two or more spaces with a single space 1261 .replace(/\ {2,}/g, " "); 1262 const summarizeStringChange = function (oldString, newString) { 1263 let added, removed; 1264 oldString = UTF16String.box(oldString); 1265 newString = UTF16String.box(newString); 1266 if (newString.length < oldString.length) { 1267 [removed, added] = utf16StringDifferences(oldString, newString); 1268 } else { 1269 [added, removed] = utf16StringDifferences(newString, oldString); 1270 } 1271 return { 1272 added, 1273 removed 1274 }; 1275 }; 1276 const utf16StringDifferences = function (a, b) { 1277 if (a.isEqualTo(b)) { 1278 return ["", ""]; 1279 } 1280 const diffA = utf16StringDifference(a, b); 1281 const { 1282 length 1283 } = diffA.utf16String; 1284 let diffB; 1285 if (length) { 1286 const { 1287 offset 1288 } = diffA; 1289 const codepoints = a.codepoints.slice(0, offset).concat(a.codepoints.slice(offset + length)); 1290 diffB = utf16StringDifference(b, UTF16String.fromCodepoints(codepoints)); 1291 } else { 1292 diffB = utf16StringDifference(b, a); 1293 } 1294 return [diffA.utf16String.toString(), diffB.utf16String.toString()]; 1295 }; 1296 const utf16StringDifference = function (a, b) { 1297 let leftIndex = 0; 1298 let rightIndexA = a.length; 1299 let rightIndexB = b.length; 1300 while (leftIndex < rightIndexA && a.charAt(leftIndex).isEqualTo(b.charAt(leftIndex))) { 1301 leftIndex++; 1302 } 1303 while (rightIndexA > leftIndex + 1 && a.charAt(rightIndexA - 1).isEqualTo(b.charAt(rightIndexB - 1))) { 1304 rightIndexA--; 1305 rightIndexB--; 1306 } 1307 return { 1308 utf16String: a.slice(leftIndex, rightIndexA), 1309 offset: leftIndex 1310 }; 1311 }; 1312 1313 class Hash extends TrixObject { 1314 static fromCommonAttributesOfObjects() { 1315 let objects = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 1316 if (!objects.length) { 1317 return new this(); 1318 } 1319 let hash = box(objects[0]); 1320 let keys = hash.getKeys(); 1321 objects.slice(1).forEach(object => { 1322 keys = hash.getKeysCommonToHash(box(object)); 1323 hash = hash.slice(keys); 1324 }); 1325 return hash; 1326 } 1327 static box(values) { 1328 return box(values); 1329 } 1330 constructor() { 1331 let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 1332 super(...arguments); 1333 this.values = copy(values); 1334 } 1335 add(key, value) { 1336 return this.merge(object(key, value)); 1337 } 1338 remove(key) { 1339 return new Hash(copy(this.values, key)); 1340 } 1341 get(key) { 1342 return this.values[key]; 1343 } 1344 has(key) { 1345 return key in this.values; 1346 } 1347 merge(values) { 1348 return new Hash(merge(this.values, unbox(values))); 1349 } 1350 slice(keys) { 1351 const values = {}; 1352 Array.from(keys).forEach(key => { 1353 if (this.has(key)) { 1354 values[key] = this.values[key]; 1355 } 1356 }); 1357 return new Hash(values); 1358 } 1359 getKeys() { 1360 return Object.keys(this.values); 1361 } 1362 getKeysCommonToHash(hash) { 1363 hash = box(hash); 1364 return this.getKeys().filter(key => this.values[key] === hash.values[key]); 1365 } 1366 isEqualTo(values) { 1367 return arraysAreEqual(this.toArray(), box(values).toArray()); 1368 } 1369 isEmpty() { 1370 return this.getKeys().length === 0; 1371 } 1372 toArray() { 1373 if (!this.array) { 1374 const result = []; 1375 for (const key in this.values) { 1376 const value = this.values[key]; 1377 result.push(result.push(key, value)); 1378 } 1379 this.array = result.slice(0); 1380 } 1381 return this.array; 1382 } 1383 toObject() { 1384 return copy(this.values); 1385 } 1386 toJSON() { 1387 return this.toObject(); 1388 } 1389 contentsForInspection() { 1390 return { 1391 values: JSON.stringify(this.values) 1392 }; 1393 } 1394 } 1395 const object = function (key, value) { 1396 const result = {}; 1397 result[key] = value; 1398 return result; 1399 }; 1400 const merge = function (object, values) { 1401 const result = copy(object); 1402 for (const key in values) { 1403 const value = values[key]; 1404 result[key] = value; 1405 } 1406 return result; 1407 }; 1408 const copy = function (object, keyToRemove) { 1409 const result = {}; 1410 const sortedKeys = Object.keys(object).sort(); 1411 sortedKeys.forEach(key => { 1412 if (key !== keyToRemove) { 1413 result[key] = object[key]; 1414 } 1415 }); 1416 return result; 1417 }; 1418 const box = function (object) { 1419 if (object instanceof Hash) { 1420 return object; 1421 } else { 1422 return new Hash(object); 1423 } 1424 }; 1425 const unbox = function (object) { 1426 if (object instanceof Hash) { 1427 return object.values; 1428 } else { 1429 return object; 1430 } 1431 }; 1432 1433 class ObjectGroup { 1434 static groupObjects() { 1435 let ungroupedObjects = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 1436 let { 1437 depth, 1438 asTree 1439 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 1440 let group; 1441 if (asTree) { 1442 if (depth == null) { 1443 depth = 0; 1444 } 1445 } 1446 const objects = []; 1447 Array.from(ungroupedObjects).forEach(object => { 1448 var _object$canBeGrouped2; 1449 if (group) { 1450 var _object$canBeGrouped, _group$canBeGroupedWi, _group; 1451 if ((_object$canBeGrouped = object.canBeGrouped) !== null && _object$canBeGrouped !== void 0 && _object$canBeGrouped.call(object, depth) && (_group$canBeGroupedWi = (_group = group[group.length - 1]).canBeGroupedWith) !== null && _group$canBeGroupedWi !== void 0 && _group$canBeGroupedWi.call(_group, object, depth)) { 1452 group.push(object); 1453 return; 1454 } else { 1455 objects.push(new this(group, { 1456 depth, 1457 asTree 1458 })); 1459 group = null; 1460 } 1461 } 1462 if ((_object$canBeGrouped2 = object.canBeGrouped) !== null && _object$canBeGrouped2 !== void 0 && _object$canBeGrouped2.call(object, depth)) { 1463 group = [object]; 1464 } else { 1465 objects.push(object); 1466 } 1467 }); 1468 if (group) { 1469 objects.push(new this(group, { 1470 depth, 1471 asTree 1472 })); 1473 } 1474 return objects; 1475 } 1476 constructor() { 1477 let objects = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 1478 let { 1479 depth, 1480 asTree 1481 } = arguments.length > 1 ? arguments[1] : undefined; 1482 this.objects = objects; 1483 if (asTree) { 1484 this.depth = depth; 1485 this.objects = this.constructor.groupObjects(this.objects, { 1486 asTree, 1487 depth: this.depth + 1 1488 }); 1489 } 1490 } 1491 getObjects() { 1492 return this.objects; 1493 } 1494 getDepth() { 1495 return this.depth; 1496 } 1497 getCacheKey() { 1498 const keys = ["objectGroup"]; 1499 Array.from(this.getObjects()).forEach(object => { 1500 keys.push(object.getCacheKey()); 1501 }); 1502 return keys.join("/"); 1503 } 1504 } 1505 1506 class ObjectMap extends BasicObject { 1507 constructor() { 1508 let objects = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 1509 super(...arguments); 1510 this.objects = {}; 1511 Array.from(objects).forEach(object => { 1512 const hash = JSON.stringify(object); 1513 if (this.objects[hash] == null) { 1514 this.objects[hash] = object; 1515 } 1516 }); 1517 } 1518 find(object) { 1519 const hash = JSON.stringify(object); 1520 return this.objects[hash]; 1521 } 1522 } 1523 1524 class ElementStore { 1525 constructor(elements) { 1526 this.reset(elements); 1527 } 1528 add(element) { 1529 const key = getKey(element); 1530 this.elements[key] = element; 1531 } 1532 remove(element) { 1533 const key = getKey(element); 1534 const value = this.elements[key]; 1535 if (value) { 1536 delete this.elements[key]; 1537 return value; 1538 } 1539 } 1540 reset() { 1541 let elements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 1542 this.elements = {}; 1543 Array.from(elements).forEach(element => { 1544 this.add(element); 1545 }); 1546 return elements; 1547 } 1548 } 1549 const getKey = element => element.dataset.trixStoreKey; 1550 1551 class Operation extends BasicObject { 1552 isPerforming() { 1553 return this.performing === true; 1554 } 1555 hasPerformed() { 1556 return this.performed === true; 1557 } 1558 hasSucceeded() { 1559 return this.performed && this.succeeded; 1560 } 1561 hasFailed() { 1562 return this.performed && !this.succeeded; 1563 } 1564 getPromise() { 1565 if (!this.promise) { 1566 this.promise = new Promise((resolve, reject) => { 1567 this.performing = true; 1568 return this.perform((succeeded, result) => { 1569 this.succeeded = succeeded; 1570 this.performing = false; 1571 this.performed = true; 1572 if (this.succeeded) { 1573 resolve(result); 1574 } else { 1575 reject(result); 1576 } 1577 }); 1578 }); 1579 } 1580 return this.promise; 1581 } 1582 perform(callback) { 1583 return callback(false); 1584 } 1585 release() { 1586 var _this$promise, _this$promise$cancel; 1587 (_this$promise = this.promise) === null || _this$promise === void 0 || (_this$promise$cancel = _this$promise.cancel) === null || _this$promise$cancel === void 0 || _this$promise$cancel.call(_this$promise); 1588 this.promise = null; 1589 this.performing = null; 1590 this.performed = null; 1591 this.succeeded = null; 1592 } 1593 } 1594 Operation.proxyMethod("getPromise().then"); 1595 Operation.proxyMethod("getPromise().catch"); 1596 1597 class ObjectView extends BasicObject { 1598 constructor(object) { 1599 let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 1600 super(...arguments); 1601 this.object = object; 1602 this.options = options; 1603 this.childViews = []; 1604 this.rootView = this; 1605 } 1606 getNodes() { 1607 if (!this.nodes) { 1608 this.nodes = this.createNodes(); 1609 } 1610 return this.nodes.map(node => node.cloneNode(true)); 1611 } 1612 invalidate() { 1613 var _this$parentView; 1614 this.nodes = null; 1615 this.childViews = []; 1616 return (_this$parentView = this.parentView) === null || _this$parentView === void 0 ? void 0 : _this$parentView.invalidate(); 1617 } 1618 invalidateViewForObject(object) { 1619 var _this$findViewForObje; 1620 return (_this$findViewForObje = this.findViewForObject(object)) === null || _this$findViewForObje === void 0 ? void 0 : _this$findViewForObje.invalidate(); 1621 } 1622 findOrCreateCachedChildView(viewClass, object, options) { 1623 let view = this.getCachedViewForObject(object); 1624 if (view) { 1625 this.recordChildView(view); 1626 } else { 1627 view = this.createChildView(...arguments); 1628 this.cacheViewForObject(view, object); 1629 } 1630 return view; 1631 } 1632 createChildView(viewClass, object) { 1633 let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; 1634 if (object instanceof ObjectGroup) { 1635 options.viewClass = viewClass; 1636 viewClass = ObjectGroupView; 1637 } 1638 const view = new viewClass(object, options); 1639 return this.recordChildView(view); 1640 } 1641 recordChildView(view) { 1642 view.parentView = this; 1643 view.rootView = this.rootView; 1644 this.childViews.push(view); 1645 return view; 1646 } 1647 getAllChildViews() { 1648 let views = []; 1649 this.childViews.forEach(childView => { 1650 views.push(childView); 1651 views = views.concat(childView.getAllChildViews()); 1652 }); 1653 return views; 1654 } 1655 findElement() { 1656 return this.findElementForObject(this.object); 1657 } 1658 findElementForObject(object) { 1659 const id = object === null || object === void 0 ? void 0 : object.id; 1660 if (id) { 1661 return this.rootView.element.querySelector("[data-trix-id='".concat(id, "']")); 1662 } 1663 } 1664 findViewForObject(object) { 1665 for (const view of this.getAllChildViews()) { 1666 if (view.object === object) { 1667 return view; 1668 } 1669 } 1670 } 1671 getViewCache() { 1672 if (this.rootView === this) { 1673 if (this.isViewCachingEnabled()) { 1674 if (!this.viewCache) { 1675 this.viewCache = {}; 1676 } 1677 return this.viewCache; 1678 } 1679 } else { 1680 return this.rootView.getViewCache(); 1681 } 1682 } 1683 isViewCachingEnabled() { 1684 return this.shouldCacheViews !== false; 1685 } 1686 enableViewCaching() { 1687 this.shouldCacheViews = true; 1688 } 1689 disableViewCaching() { 1690 this.shouldCacheViews = false; 1691 } 1692 getCachedViewForObject(object) { 1693 var _this$getViewCache; 1694 return (_this$getViewCache = this.getViewCache()) === null || _this$getViewCache === void 0 ? void 0 : _this$getViewCache[object.getCacheKey()]; 1695 } 1696 cacheViewForObject(view, object) { 1697 const cache = this.getViewCache(); 1698 if (cache) { 1699 cache[object.getCacheKey()] = view; 1700 } 1701 } 1702 garbageCollectCachedViews() { 1703 const cache = this.getViewCache(); 1704 if (cache) { 1705 const views = this.getAllChildViews().concat(this); 1706 const objectKeys = views.map(view => view.object.getCacheKey()); 1707 for (const key in cache) { 1708 if (!objectKeys.includes(key)) { 1709 delete cache[key]; 1710 } 1711 } 1712 } 1713 } 1714 } 1715 class ObjectGroupView extends ObjectView { 1716 constructor() { 1717 super(...arguments); 1718 this.objectGroup = this.object; 1719 this.viewClass = this.options.viewClass; 1720 delete this.options.viewClass; 1721 } 1722 getChildViews() { 1723 if (!this.childViews.length) { 1724 Array.from(this.objectGroup.getObjects()).forEach(object => { 1725 this.findOrCreateCachedChildView(this.viewClass, object, this.options); 1726 }); 1727 } 1728 return this.childViews; 1729 } 1730 createNodes() { 1731 const element = this.createContainerElement(); 1732 this.getChildViews().forEach(view => { 1733 Array.from(view.getNodes()).forEach(node => { 1734 element.appendChild(node); 1735 }); 1736 }); 1737 return [element]; 1738 } 1739 createContainerElement() { 1740 let depth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.objectGroup.getDepth(); 1741 return this.getChildViews()[0].createContainerElement(depth); 1742 } 1743 } 1744 1745 /*! @license DOMPurify 3.
vendor: 4,515 bytes, lines 1745-1878
17452.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.3/LICENSE */ 1746 1747 const { 1748 entries, 1749 setPrototypeOf, 1750 isFrozen, 1751 getPrototypeOf, 1752 getOwnPropertyDescriptor 1753 } = Object; 1754 let { 1755 freeze, 1756 seal, 1757 create 1758 } = Object; // eslint-disable-line import/no-mutable-exports 1759 let { 1760 apply, 1761 construct 1762 } = typeof Reflect !== 'undefined' && Reflect; 1763 if (!freeze) { 1764 freeze = function freeze(x) { 1765 return x; 1766 }; 1767 } 1768 if (!seal) { 1769 seal = function seal(x) { 1770 return x; 1771 }; 1772 } 1773 if (!apply) { 1774 apply = function apply(fun, thisValue, args) { 1775 return fun.apply(thisValue, args); 1776 }; 1777 } 1778 if (!construct) { 1779 construct = function construct(Func, args) { 1780 return new Func(...args); 1781 }; 1782 } 1783 const arrayForEach = unapply(Array.prototype.forEach); 1784 const arrayPop = unapply(Array.prototype.pop); 1785 const arrayPush = unapply(Array.prototype.push); 1786 const stringToLowerCase = unapply(String.prototype.toLowerCase); 1787 const stringToString = unapply(String.prototype.toString); 1788 const stringMatch = unapply(String.prototype.match); 1789 const stringReplace = unapply(String.prototype.replace); 1790 const stringIndexOf = unapply(String.prototype.indexOf); 1791 const stringTrim = unapply(String.prototype.trim); 1792 const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty); 1793 const regExpTest = unapply(RegExp.prototype.test); 1794 const typeErrorCreate = unconstruct(TypeError); 1795 /** 1796 * Creates a new function that calls the given function with a specified thisArg and arguments. 1797 * 1798 * @param func - The function to be wrapped and called. 1799 * @returns A new function that calls the given function with a specified thisArg and arguments. 1800 */ 1801 function unapply(func) { 1802 return function (thisArg) { 1803 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { 1804 args[_key - 1] = arguments[_key]; 1805 } 1806 return apply(func, thisArg, args); 1807 }; 1808 } 1809 /** 1810 * Creates a new function that constructs an instance of the given constructor function with the provided arguments. 1811 * 1812 * @param func - The constructor function to be wrapped and called. 1813 * @returns A new function that constructs an instance of the given constructor function with the provided arguments. 1814 */ 1815 function unconstruct(func) { 1816 return function () { 1817 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { 1818 args[_key2] = arguments[_key2]; 1819 } 1820 return construct(func, args); 1821 }; 1822 } 1823 /** 1824 * Add properties to a lookup table 1825 * 1826 * @param set - The set to which elements will be added. 1827 * @param array - The array containing elements to be added to the set. 1828 * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set. 1829 * @returns The modified set with added elements. 1830 */ 1831 function addToSet(set, array) { 1832 let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase; 1833 if (setPrototypeOf) { 1834 // Make 'in' and truthy checks like Boolean(set.constructor) 1835 // independent of any properties defined on Object.prototype. 1836 // Prevent prototype setters from intercepting set as a this value. 1837 setPrototypeOf(set, null); 1838 } 1839 let l = array.length; 1840 while (l--) { 1841 let element = array[l]; 1842 if (typeof element === 'string') { 1843 const lcElement = transformCaseFunc(element); 1844 if (lcElement !== element) { 1845 // Config presets (e.g. tags.js, attrs.js) are immutable. 1846 if (!isFrozen(array)) { 1847 array[l] = lcElement; 1848 } 1849 element = lcElement; 1850 } 1851 } 1852 set[element] = true; 1853 } 1854 return set; 1855 } 1856 /** 1857 * Clean up an array to harden against CSPP 1858 * 1859 * @param array - The array to be cleaned. 1860 * @returns The cleaned version of the array 1861 */ 1862 function cleanArray(array) { 1863 for (let index = 0; index < array.length; index++) { 1864 const isPropertyExist = objectHasOwnProperty(array, index); 1865 if (!isPropertyExist) { 1866 array[index] = null; 1867 } 1868 } 1869 return array; 1870 } 1871 /** 1872 * Shallow clone an object 1873 * 1874 * @param object - The object to be cloned. 1875 * @returns A new object that copies the original. 1876 */ 1877 function clone(object) { 1878 const newObject = create(null);
vendor: 4,347 bytes, lines 1879-1929
1879 for (const [property, value] of entries(object)) { 1880 const isPropertyExist = objectHasOwnProperty(object, property); 1881 if (isPropertyExist) { 1882 if (Array.isArray(value)) { 1883 newObject[property] = cleanArray(value); 1884 } else if (value && typeof value === 'object' && value.constructor === Object) { 1885 newObject[property] = clone(value); 1886 } else { 1887 newObject[property] = value; 1888 } 1889 } 1890 } 1891 return newObject; 1892 } 1893 /** 1894 * This method automatically checks if the prop is function or getter and behaves accordingly. 1895 * 1896 * @param object - The object to look up the getter function in its prototype chain. 1897 * @param prop - The property name for which to find the getter function. 1898 * @returns The getter function found in the prototype chain or a fallback function. 1899 */ 1900 function lookupGetter(object, prop) { 1901 while (object !== null) { 1902 const desc = getOwnPropertyDescriptor(object, prop); 1903 if (desc) { 1904 if (desc.get) { 1905 return unapply(desc.get); 1906 } 1907 if (typeof desc.value === 'function') { 1908 return unapply(desc.value); 1909 } 1910 } 1911 object = getPrototypeOf(object); 1912 } 1913 function fallbackValue() { 1914 return null; 1915 } 1916 return fallbackValue; 1917 } 1918 const html$1 = 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']); 1919 const svg$1 = 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']); 1920 const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); 1921 // List of SVG elements that are disallowed by default. 1922 // We still need to know them so that we can do namespace 1923 // checks properly in case one wants to add them to 1924 // allow-list. 1925 const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', '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']); 1926 const mathMl$1 = 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', 'mprescripts']); 1927 // Similarly to SVG, we want to know all MathML elements, 1928 // even those that we disallow by default. 1929 const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'n
1929one']); 1930 const text = freeze(['#text']); 1931 const html = 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', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', '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', 'wrap', 'xmlns', 'slot']); 1932 const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', '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', 'exponent', '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', 'intercept', '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', 'slope', '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', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', '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']); 1933 const mathMl = 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']); 1934 const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); 1935 1936 // eslint-disable-next-line unicorn/better-regex 1937 const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode 1938 const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); 1939 const TMPLIT_EXPR = seal(/\$\{[\w\W]*}/gm); // eslint-disable-line unicorn/better-regex 1940 const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape 1941 const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
vendor: 7,904 bytes, lines 1942-2151
1942 const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape 1943 ); 1944 1945 const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); 1946 const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex 1947 ); 1948 1949 const DOCTYPE_NAME = seal(/^html$/i); 1950 const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); 1951 var EXPRESSIONS = /*#__PURE__*/Object.freeze({ 1952 __proto__: null, 1953 ARIA_ATTR: ARIA_ATTR, 1954 ATTR_WHITESPACE: ATTR_WHITESPACE, 1955 CUSTOM_ELEMENT: CUSTOM_ELEMENT, 1956 DATA_ATTR: DATA_ATTR, 1957 DOCTYPE_NAME: DOCTYPE_NAME, 1958 ERB_EXPR: ERB_EXPR, 1959 IS_ALLOWED_URI: IS_ALLOWED_URI, 1960 IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA, 1961 MUSTACHE_EXPR: MUSTACHE_EXPR, 1962 TMPLIT_EXPR: TMPLIT_EXPR 1963 }); 1964 1965 /* eslint-disable @typescript-eslint/indent */ 1966 // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType 1967 const NODE_TYPE = { 1968 element: 1, 1969 attribute: 2, 1970 text: 3, 1971 cdataSection: 4, 1972 entityReference: 5, 1973 // Deprecated 1974 entityNode: 6, 1975 // Deprecated 1976 progressingInstruction: 7, 1977 comment: 8, 1978 document: 9, 1979 documentType: 10, 1980 documentFragment: 11, 1981 notation: 12 // Deprecated 1982 }; 1983 1984 const getGlobal = function getGlobal() { 1985 return typeof window === 'undefined' ? null : window; 1986 }; 1987 /** 1988 * Creates a no-op policy for internal use only. 1989 * Don't export this function outside this module! 1990 * @param trustedTypes The policy factory. 1991 * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix). 1992 * @return The policy created (or null, if Trusted Types 1993 * are not supported or creating the policy failed). 1994 */ 1995 const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) { 1996 if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') { 1997 return null; 1998 } 1999 // Allow the callers to control the unique policy name 2000 // by adding a data-tt-policy-suffix to the script element with the DOMPurify. 2001 // Policy creation with duplicate names throws in Trusted Types. 2002 let suffix = null; 2003 const ATTR_NAME = 'data-tt-policy-suffix'; 2004 if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { 2005 suffix = purifyHostElement.getAttribute(ATTR_NAME); 2006 } 2007 const policyName = 'dompurify' + (suffix ? '#' + suffix : ''); 2008 try { 2009 return trustedTypes.createPolicy(policyName, { 2010 createHTML(html) { 2011 return html; 2012 }, 2013 createScriptURL(scriptUrl) { 2014 return scriptUrl; 2015 } 2016 }); 2017 } catch (_) { 2018 // Policy creation failed (most likely another DOMPurify script has 2019 // already run). Skip creating the policy, as this will only cause errors 2020 // if TT are enforced. 2021 console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); 2022 return null; 2023 } 2024 }; 2025 const _createHooksMap = function _createHooksMap() { 2026 return { 2027 afterSanitizeAttributes: [], 2028 afterSanitizeElements: [], 2029 afterSanitizeShadowDOM: [], 2030 beforeSanitizeAttributes: [], 2031 beforeSanitizeElements: [], 2032 beforeSanitizeShadowDOM: [], 2033 uponSanitizeAttribute: [], 2034 uponSanitizeElement: [], 2035 uponSanitizeShadowNode: [] 2036 }; 2037 }; 2038 function createDOMPurify() { 2039 let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); 2040 const DOMPurify = root => createDOMPurify(root); 2041 DOMPurify.version = '3.2.3'; 2042 DOMPurify.removed = []; 2043 if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document) { 2044 // Not running in a browser, provide a factory function 2045 // so that you can pass your own Window 2046 DOMPurify.isSupported = false; 2047 return DOMPurify; 2048 } 2049 let { 2050 document 2051 } = window; 2052 const originalDocument = document; 2053 const currentScript = originalDocument.currentScript; 2054 const { 2055 DocumentFragment, 2056 HTMLTemplateElement, 2057 Node, 2058 Element, 2059 NodeFilter, 2060 NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap, 2061 HTMLFormElement, 2062 DOMParser, 2063 trustedTypes 2064 } = window; 2065 const ElementPrototype = Element.prototype; 2066 const cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); 2067 const remove = lookupGetter(ElementPrototype, 'remove'); 2068 const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); 2069 const getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); 2070 const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); 2071 // As per issue #47, the web-components registry is inherited by a 2072 // new document created via createHTMLDocument. As per the spec 2073 // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) 2074 // a new empty registry is used when creating a template contents owner 2075 // document, so we use that as our parent document to ensure nothing 2076 // is inherited. 2077 if (typeof HTMLTemplateElement === 'function') { 2078 const template = document.createElement('template'); 2079 if (template.content && template.content.ownerDocument) { 2080 document = template.content.ownerDocument; 2081 } 2082 } 2083 let trustedTypesPolicy; 2084 let emptyHTML = ''; 2085 const { 2086 implementation, 2087 createNodeIterator, 2088 createDocumentFragment, 2089 getElementsByTagName 2090 } = document; 2091 const { 2092 importNode 2093 } = originalDocument; 2094 let hooks = _createHooksMap(); 2095 /** 2096 * Expose whether this browser supports running the full DOMPurify. 2097 */ 2098 DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined; 2099 const { 2100 MUSTACHE_EXPR, 2101 ERB_EXPR, 2102 TMPLIT_EXPR, 2103 DATA_ATTR, 2104 ARIA_ATTR, 2105 IS_SCRIPT_OR_DATA, 2106 ATTR_WHITESPACE, 2107 CUSTOM_ELEMENT 2108 } = EXPRESSIONS; 2109 let { 2110 IS_ALLOWED_URI: IS_ALLOWED_URI$1 2111 } = EXPRESSIONS; 2112 /** 2113 * We consider the elements and attributes below to be safe. Ideally 2114 * don't add any new ones but feel free to remove unwanted ones. 2115 */ 2116 /* allowed element names */ 2117 let ALLOWED_TAGS = null; 2118 const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); 2119 /* Allowed attribute names */ 2120 let ALLOWED_ATTR = null; 2121 const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); 2122 /* 2123 * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements. 2124 * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) 2125 * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list) 2126 * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`. 2127 */ 2128 let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { 2129 tagNameCheck: { 2130 writable: true, 2131 configurable: false, 2132 enumerable: true, 2133 value: null 2134 }, 2135 attributeNameCheck: { 2136 writable: true, 2137 configurable: false, 2138 enumerable: true, 2139 value: null 2140 }, 2141 allowCustomizedBuiltInElements: { 2142 writable: true, 2143 configurable: false, 2144 enumerable: true, 2145 value: false 2146 } 2147 })); 2148 /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ 2149 let FORBID_TAGS = null; 2150 /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ 2151 let FORBID_ATTR = null
vendor: 7,523 bytes, lines 2151-2280
2151; 2152 /* Decide if ARIA attributes are okay */ 2153 let ALLOW_ARIA_ATTR = true; 2154 /* Decide if custom data attributes are okay */ 2155 let ALLOW_DATA_ATTR = true; 2156 /* Decide if unknown protocols are okay */ 2157 let ALLOW_UNKNOWN_PROTOCOLS = false; 2158 /* Decide if self-closing tags in attributes are allowed. 2159 * Usually removed due to a mXSS issue in jQuery 3.0 */ 2160 let ALLOW_SELF_CLOSE_IN_ATTR = true; 2161 /* Output should be safe for common template engines. 2162 * This means, DOMPurify removes data attributes, mustaches and ERB 2163 */ 2164 let SAFE_FOR_TEMPLATES = false; 2165 /* Output should be safe even for XML used within HTML and alike. 2166 * This means, DOMPurify removes comments when containing risky content. 2167 */ 2168 let SAFE_FOR_XML = true; 2169 /* Decide if document with <html>... should be returned */ 2170 let WHOLE_DOCUMENT = false; 2171 /* Track whether config is already set on this instance of DOMPurify. */ 2172 let SET_CONFIG = false; 2173 /* Decide if all elements (e.g. style, script) must be children of 2174 * document.body. By default, browsers might move them to document.head */ 2175 let FORCE_BODY = false; 2176 /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html 2177 * string (or a TrustedHTML object if Trusted Types are supported). 2178 * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead 2179 */ 2180 let RETURN_DOM = false; 2181 /* Decide if a DOM `DocumentFragment` should be returned, instead of a html 2182 * string (or a TrustedHTML object if Trusted Types are supported) */ 2183 let RETURN_DOM_FRAGMENT = false; 2184 /* Try to return a Trusted Type object instead of a string, return a string in 2185 * case Trusted Types are not supported */ 2186 let RETURN_TRUSTED_TYPE = false; 2187 /* Output should be free from DOM clobbering attacks? 2188 * This sanitizes markups named with colliding, clobberable built-in DOM APIs. 2189 */ 2190 let SANITIZE_DOM = true; 2191 /* Achieve full DOM Clobbering protection by isolating the namespace of named 2192 * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules. 2193 * 2194 * HTML/DOM spec rules that enable DOM Clobbering: 2195 * - Named Access on Window (§7.3.3) 2196 * - DOM Tree Accessors (§3.1.5) 2197 * - Form Element Parent-Child Relations (§4.10.3) 2198 * - Iframe srcdoc / Nested WindowProxies (§4.8.5) 2199 * - HTMLCollection (§4.2.10.2) 2200 * 2201 * Namespace isolation is implemented by prefixing `id` and `name` attributes 2202 * with a constant string, i.e., `user-content-` 2203 */ 2204 let SANITIZE_NAMED_PROPS = false; 2205 const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; 2206 /* Keep element content when removing element? */ 2207 let KEEP_CONTENT = true; 2208 /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead 2209 * of importing it into a new Document and returning a sanitized copy */ 2210 let IN_PLACE = false; 2211 /* Allow usage of profiles like html, svg and mathMl */ 2212 let USE_PROFILES = {}; 2213 /* Tags to ignore content of when KEEP_CONTENT is true */ 2214 let FORBID_CONTENTS = null; 2215 const 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']); 2216 /* Tags that are safe for data: URIs */ 2217 let DATA_URI_TAGS = null; 2218 const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); 2219 /* Attributes safe for values like "javascript:" */ 2220 let URI_SAFE_ATTRIBUTES = null; 2221 const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); 2222 const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; 2223 const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; 2224 const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; 2225 /* Document namespace */ 2226 let NAMESPACE = HTML_NAMESPACE; 2227 let IS_EMPTY_INPUT = false; 2228 /* Allowed XHTML+XML namespaces */ 2229 let ALLOWED_NAMESPACES = null; 2230 const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); 2231 let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); 2232 let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']); 2233 // Certain elements are allowed in both SVG and HTML 2234 // namespace. We need to specify them explicitly 2235 // so that they don't get erroneously deleted from 2236 // HTML namespace. 2237 const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']); 2238 /* Parsing of strict XHTML documents */ 2239 let PARSER_MEDIA_TYPE = null; 2240 const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; 2241 const DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; 2242 let transformCaseFunc = null; 2243 /* Keep a reference to config to pass to hooks */ 2244 let CONFIG = null; 2245 /* Ideally, do not touch anything below this line */ 2246 /* ______________________________________________ */ 2247 const formElement = document.createElement('form'); 2248 const isRegexOrFunction = function isRegexOrFunction(testValue) { 2249 return testValue instanceof RegExp || testValue instanceof Function; 2250 }; 2251 /** 2252 * _parseConfig 2253 * 2254 * @param cfg optional config literal 2255 */ 2256 // eslint-disable-next-line complexity 2257 const _parseConfig = function _parseConfig() { 2258 let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 2259 if (CONFIG && CONFIG === cfg) { 2260 return; 2261 } 2262 /* Shield configuration object from tampering */ 2263 if (!cfg || typeof cfg !== 'object') { 2264 cfg = {}; 2265 } 2266 /* Shield configuration object from prototype pollution */ 2267 cfg = clone(cfg); 2268 PARSER_MEDIA_TYPE = 2269 // eslint-disable-next-line unicorn/prefer-includes 2270 SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; 2271 // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is. 2272 transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase; 2273 /* Set configuration parameters */ 2274 ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; 2275 ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; 2276 ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; 2277 URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; 2278 DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; 2279 FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; 2280 FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) :
vendor: 3,290 bytes, lines 2280-2341
2280{}; 2281 FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {}; 2282 USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false; 2283 ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true 2284 ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true 2285 ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false 2286 ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true 2287 SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false 2288 SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true 2289 WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false 2290 RETURN_DOM = cfg.RETURN_DOM || false; // Default false 2291 RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false 2292 RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false 2293 FORCE_BODY = cfg.FORCE_BODY || false; // Default false 2294 SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true 2295 SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false 2296 KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true 2297 IN_PLACE = cfg.IN_PLACE || false; // Default false 2298 IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; 2299 NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; 2300 MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; 2301 HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; 2302 CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; 2303 if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { 2304 CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; 2305 } 2306 if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { 2307 CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; 2308 } 2309 if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') { 2310 CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; 2311 } 2312 if (SAFE_FOR_TEMPLATES) { 2313 ALLOW_DATA_ATTR = false; 2314 } 2315 if (RETURN_DOM_FRAGMENT) { 2316 RETURN_DOM = true; 2317 } 2318 /* Parse profile info */ 2319 if (USE_PROFILES) { 2320 ALLOWED_TAGS = addToSet({}, text); 2321 ALLOWED_ATTR = []; 2322 if (USE_PROFILES.html === true) { 2323 addToSet(ALLOWED_TAGS, html$1); 2324 addToSet(ALLOWED_ATTR, html); 2325 } 2326 if (USE_PROFILES.svg === true) { 2327 addToSet(ALLOWED_TAGS, svg$1); 2328 addToSet(ALLOWED_ATTR, svg); 2329 addToSet(ALLOWED_ATTR, xml); 2330 } 2331 if (USE_PROFILES.svgFilters === true) { 2332 addToSet(ALLOWED_TAGS, svgFilters); 2333 addToSet(ALLOWED_ATTR, svg); 2334 addToSet(ALLOWED_ATTR, xml); 2335 } 2336 if (USE_PROFILES.mathMl === true) { 2337 addToSet(ALLOWED_TAGS, mathMl$1); 2338 addToSet(ALLOWED_ATTR, mathMl); 2339 addToSet(ALLOWED_ATTR, xml); 2340 } 2341 }
vendor: 5,664 bytes, lines 2342-2469
2342 /* Merge configuration parameters */ 2343 if (cfg.ADD_TAGS) { 2344 if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { 2345 ALLOWED_TAGS = clone(ALLOWED_TAGS); 2346 } 2347 addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); 2348 } 2349 if (cfg.ADD_ATTR) { 2350 if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { 2351 ALLOWED_ATTR = clone(ALLOWED_ATTR); 2352 } 2353 addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); 2354 } 2355 if (cfg.ADD_URI_SAFE_ATTR) { 2356 addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); 2357 } 2358 if (cfg.FORBID_CONTENTS) { 2359 if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { 2360 FORBID_CONTENTS = clone(FORBID_CONTENTS); 2361 } 2362 addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); 2363 } 2364 /* Add #text in case KEEP_CONTENT is set to true */ 2365 if (KEEP_CONTENT) { 2366 ALLOWED_TAGS['#text'] = true; 2367 } 2368 /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ 2369 if (WHOLE_DOCUMENT) { 2370 addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); 2371 } 2372 /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ 2373 if (ALLOWED_TAGS.table) { 2374 addToSet(ALLOWED_TAGS, ['tbody']); 2375 delete FORBID_TAGS.tbody; 2376 } 2377 if (cfg.TRUSTED_TYPES_POLICY) { 2378 if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') { 2379 throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); 2380 } 2381 if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') { 2382 throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); 2383 } 2384 // Overwrite existing TrustedTypes policy. 2385 trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; 2386 // Sign local variables required by `sanitize`. 2387 emptyHTML = trustedTypesPolicy.createHTML(''); 2388 } else { 2389 // Uninitialized policy, attempt to initialize the internal dompurify policy. 2390 if (trustedTypesPolicy === undefined) { 2391 trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); 2392 } 2393 // If creating the internal policy succeeded sign internal variables. 2394 if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') { 2395 emptyHTML = trustedTypesPolicy.createHTML(''); 2396 } 2397 } 2398 // Prevent further manipulation of configuration. 2399 // Not available in IE8, Safari 5, etc. 2400 if (freeze) { 2401 freeze(cfg); 2402 } 2403 CONFIG = cfg; 2404 }; 2405 /* Keep track of all possible SVG and MathML tags 2406 * so that we can perform the namespace checks 2407 * correctly. */ 2408 const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); 2409 const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); 2410 /** 2411 * @param element a DOM element whose namespace is being checked 2412 * @returns Return false if the element has a 2413 * namespace that a spec-compliant parser would never 2414 * return. Return true otherwise. 2415 */ 2416 const _checkValidNamespace = function _checkValidNamespace(element) { 2417 let parent = getParentNode(element); 2418 // In JSDOM, if we're inside shadow DOM, then parentNode 2419 // can be null. We just simulate parent in this case. 2420 if (!parent || !parent.tagName) { 2421 parent = { 2422 namespaceURI: NAMESPACE, 2423 tagName: 'template' 2424 }; 2425 } 2426 const tagName = stringToLowerCase(element.tagName); 2427 const parentTagName = stringToLowerCase(parent.tagName); 2428 if (!ALLOWED_NAMESPACES[element.namespaceURI]) { 2429 return false; 2430 } 2431 if (element.namespaceURI === SVG_NAMESPACE) { 2432 // The only way to switch from HTML namespace to SVG 2433 // is via <svg>. If it happens via any other tag, then 2434 // it should be killed. 2435 if (parent.namespaceURI === HTML_NAMESPACE) { 2436 return tagName === 'svg'; 2437 } 2438 // The only way to switch from MathML to SVG is via` 2439 // svg if parent is either <annotation-xml> or MathML 2440 // text integration points. 2441 if (parent.namespaceURI === MATHML_NAMESPACE) { 2442 return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); 2443 } 2444 // We only allow elements that are defined in SVG 2445 // spec. All others are disallowed in SVG namespace. 2446 return Boolean(ALL_SVG_TAGS[tagName]); 2447 } 2448 if (element.namespaceURI === MATHML_NAMESPACE) { 2449 // The only way to switch from HTML namespace to MathML 2450 // is via <math>. If it happens via any other tag, then 2451 // it should be killed. 2452 if (parent.namespaceURI === HTML_NAMESPACE) { 2453 return tagName === 'math'; 2454 } 2455 // The only way to switch from SVG to MathML is via 2456 // <math> and HTML integration points 2457 if (parent.namespaceURI === SVG_NAMESPACE) { 2458 return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; 2459 } 2460 // We only allow elements that are defined in MathML 2461 // spec. All others are disallowed in MathML namespace. 2462 return Boolean(ALL_MATHML_TAGS[tagName]); 2463 } 2464 if (element.namespaceURI === HTML_NAMESPACE) { 2465 // The only way to switch from SVG to HTML is via 2466 // HTML integration points, and from MathML to HTML 2467 // is via MathML text integration points 2468 if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { 2469 return false;
2470 } 2471 if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { 2472 return false; 2473 } 2474 // We disallow tags that are specific for MathML 2475 // or SVG and should never appear in HTML namespace 2476 return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); 2477 } 2478 // For XHTML and XML documents that support custom namespaces 2479 if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) { 2480 return true; 2481 } 2482 // The code should never reach this place (this means 2483 // that the element somehow got namespace that is not 2484 // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES). 2485 // Return false just in case. 2486 return false; 2487 }; 2488 /** 2489 * _forceRemove 2490 * 2491 * @param node a DOM node 2492 */ 2493 const _forceRemove = function _forceRemove(node) { 2494 arrayPush(DOMPurify.removed, { 2495 element: node 2496 }); 2497 try {
vendor: 19,679 bytes, lines 2498-2943
2498 // eslint-disable-next-line unicorn/prefer-dom-node-remove 2499 getParentNode(node).removeChild(node); 2500 } catch (_) { 2501 remove(node); 2502 } 2503 }; 2504 /** 2505 * _removeAttribute 2506 * 2507 * @param name an Attribute name 2508 * @param element a DOM node 2509 */ 2510 const _removeAttribute = function _removeAttribute(name, element) { 2511 try { 2512 arrayPush(DOMPurify.removed, { 2513 attribute: element.getAttributeNode(name), 2514 from: element 2515 }); 2516 } catch (_) { 2517 arrayPush(DOMPurify.removed, { 2518 attribute: null, 2519 from: element 2520 }); 2521 } 2522 element.removeAttribute(name); 2523 // We void attribute values for unremovable "is" attributes 2524 if (name === 'is') { 2525 if (RETURN_DOM || RETURN_DOM_FRAGMENT) { 2526 try { 2527 _forceRemove(element); 2528 } catch (_) {} 2529 } else { 2530 try { 2531 element.setAttribute(name, ''); 2532 } catch (_) {} 2533 } 2534 } 2535 }; 2536 /** 2537 * _initDocument 2538 * 2539 * @param dirty - a string of dirty markup 2540 * @return a DOM, filled with the dirty markup 2541 */ 2542 const _initDocument = function _initDocument(dirty) { 2543 /* Create a HTML document */ 2544 let doc = null; 2545 let leadingWhitespace = null; 2546 if (FORCE_BODY) { 2547 dirty = '<remove></remove>' + dirty; 2548 } else { 2549 /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ 2550 const matches = stringMatch(dirty, /^[\r\n\t ]+/); 2551 leadingWhitespace = matches && matches[0]; 2552 } 2553 if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) { 2554 // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict) 2555 dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>'; 2556 } 2557 const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; 2558 /* 2559 * Use the DOMParser API by default, fallback later if needs be 2560 * DOMParser not work for svg when has multiple root element. 2561 */ 2562 if (NAMESPACE === HTML_NAMESPACE) { 2563 try { 2564 doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); 2565 } catch (_) {} 2566 } 2567 /* Use createHTMLDocument in case DOMParser is not available */ 2568 if (!doc || !doc.documentElement) { 2569 doc = implementation.createDocument(NAMESPACE, 'template', null); 2570 try { 2571 doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; 2572 } catch (_) { 2573 // Syntax error if dirtyPayload is invalid xml 2574 } 2575 } 2576 const body = doc.body || doc.documentElement; 2577 if (dirty && leadingWhitespace) { 2578 body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); 2579 } 2580 /* Work on whole document or just its body */ 2581 if (NAMESPACE === HTML_NAMESPACE) { 2582 return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; 2583 } 2584 return WHOLE_DOCUMENT ? doc.documentElement : body; 2585 }; 2586 /** 2587 * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. 2588 * 2589 * @param root The root element or node to start traversing on. 2590 * @return The created NodeIterator 2591 */ 2592 const _createNodeIterator = function _createNodeIterator(root) { 2593 return createNodeIterator.call(root.ownerDocument || root, root, 2594 // eslint-disable-next-line no-bitwise 2595 NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null); 2596 }; 2597 /** 2598 * _isClobbered 2599 * 2600 * @param element element to check for clobbering attacks 2601 * @return true if clobbered, false if safe 2602 */ 2603 const _isClobbered = function _isClobbered(element) { 2604 return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function'); 2605 }; 2606 /** 2607 * Checks whether the given object is a DOM node. 2608 * 2609 * @param value object to check whether it's a DOM node 2610 * @return true is object is a DOM node 2611 */ 2612 const _isNode = function _isNode(value) { 2613 return typeof Node === 'function' && value instanceof Node; 2614 }; 2615 function _executeHooks(hooks, currentNode, data) { 2616 arrayForEach(hooks, hook => { 2617 hook.call(DOMPurify, currentNode, data, CONFIG); 2618 }); 2619 } 2620 /** 2621 * _sanitizeElements 2622 * 2623 * @protect nodeName 2624 * @protect textContent 2625 * @protect removeChild 2626 * @param currentNode to check for permission to exist 2627 * @return true if node was killed, false if left alive 2628 */ 2629 const _sanitizeElements = function _sanitizeElements(currentNode) { 2630 let content = null; 2631 /* Execute a hook if present */ 2632 _executeHooks(hooks.beforeSanitizeElements, currentNode, null); 2633 /* Check if element is clobbered or can clobber */ 2634 if (_isClobbered(currentNode)) { 2635 _forceRemove(currentNode); 2636 return true; 2637 } 2638 /* Now let's check the element's type and name */ 2639 const tagName = transformCaseFunc(currentNode.nodeName); 2640 /* Execute a hook if present */ 2641 _executeHooks(hooks.uponSanitizeElement, currentNode, { 2642 tagName, 2643 allowedTags: ALLOWED_TAGS 2644 }); 2645 /* Detect mXSS attempts abusing namespace confusion */ 2646 if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { 2647 _forceRemove(currentNode); 2648 return true; 2649 } 2650 /* Remove any occurrence of processing instructions */ 2651 if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { 2652 _forceRemove(currentNode); 2653 return true; 2654 } 2655 /* Remove any kind of possibly harmful comments */ 2656 if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { 2657 _forceRemove(currentNode); 2658 return true; 2659 } 2660 /* Remove element if anything forbids its presence */ 2661 if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { 2662 /* Check if we have a custom element to handle */ 2663 if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { 2664 if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { 2665 return false; 2666 } 2667 if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { 2668 return false; 2669 } 2670 } 2671 /* Keep content except for bad-listed elements */ 2672 if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { 2673 const parentNode = getParentNode(currentNode) || currentNode.parentNode; 2674 const childNodes = getChildNodes(currentNode) || currentNode.childNodes; 2675 if (childNodes && parentNode) { 2676 const childCount = childNodes.length; 2677 for (let i = childCount - 1; i >= 0; --i) { 2678 const childClone = cloneNode(childNodes[i], true); 2679 childClone.__removalCount = (currentNode.__removalCount || 0) + 1; 2680 parentNode.insertBefore(childClone, getNextSibling(currentNode)); 2681 } 2682 } 2683 } 2684 _forceRemove(currentNode); 2685 return true; 2686 } 2687 /* Check whether element has a valid namespace */ 2688 if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { 2689 _forceRemove(currentNode); 2690 return true; 2691 } 2692 /* Make sure that older browsers don't get fallback-tag mXSS */ 2693 if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { 2694 _forceRemove(currentNode); 2695 return true; 2696 } 2697 /* Sanitize element content to be template-safe */ 2698 if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { 2699 /* Get the element's text content */ 2700 content = currentNode.textContent; 2701 arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { 2702 content = stringReplace(content, expr, ' '); 2703 }); 2704 if (currentNode.textContent !== content) { 2705 arrayPush(DOMPurify.removed, { 2706 element: currentNode.cloneNode() 2707 }); 2708 currentNode.textContent = content; 2709 } 2710 } 2711 /* Execute a hook if present */ 2712 _executeHooks(hooks.afterSanitizeElements, currentNode, null); 2713 return false; 2714 }; 2715 /** 2716 * _isValidAttribute 2717 * 2718 * @param lcTag Lowercase tag name of containing element. 2719 * @param lcName Lowercase attribute name. 2720 * @param value Attribute value. 2721 * @return Returns true if `value` is valid, otherwise false. 2722 */ 2723 // eslint-disable-next-line complexity 2724 const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) { 2725 /* Make sure attribute cannot clobber */ 2726 if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) { 2727 return false; 2728 } 2729 /* Allow valid data-* attributes: At least one character after "-" 2730 (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) 2731 XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) 2732 We don't need to check the value; it's always URI safe. */ 2733 if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ;else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ;else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { 2734 if ( 2735 // First condition does a very basic check if a) it's basically a valid custom element tagname AND 2736 // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck 2737 // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck 2738 _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || 2739 // Alternative, second condition checks if it's an `is`-attribute, AND 2740 // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck 2741 lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ;else { 2742 return false; 2743 } 2744 /* Check value is safe. First, is attr inert? If so, is safe */ 2745 } else if (URI_SAFE_ATTRIBUTES[lcName]) ;else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ;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, stringReplace(value, ATTR_WHITESPACE, ''))) ;else if (value) { 2746 return false; 2747 } else ; 2748 return true; 2749 }; 2750 /** 2751 * _isBasicCustomElement 2752 * checks if at least one dash is included in tagName, and it's not the first char 2753 * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name 2754 * 2755 * @param tagName name of the tag of the node to sanitize 2756 * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false. 2757 */ 2758 const _isBasicCustomElement = function _isBasicCustomElement(tagName) { 2759 return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT); 2760 }; 2761 /** 2762 * _sanitizeAttributes 2763 * 2764 * @protect attributes 2765 * @protect nodeName 2766 * @protect removeAttribute 2767 * @protect setAttribute 2768 * 2769 * @param currentNode to sanitize 2770 */ 2771 const _sanitizeAttributes = function _sanitizeAttributes(currentNode) { 2772 /* Execute a hook if present */ 2773 _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); 2774 const { 2775 attributes 2776 } = currentNode; 2777 /* Check if we have attributes; if not we might have a text node */ 2778 if (!attributes || _isClobbered(currentNode)) { 2779 return; 2780 } 2781 const hookEvent = { 2782 attrName: '', 2783 attrValue: '', 2784 keepAttr: true, 2785 allowedAttributes: ALLOWED_ATTR, 2786 forceKeepAttr: undefined 2787 }; 2788 let l = attributes.length; 2789 /* Go backwards over all attributes; safely remove bad ones */ 2790 while (l--) { 2791 const attr = attributes[l]; 2792 const { 2793 name, 2794 namespaceURI, 2795 value: attrValue 2796 } = attr; 2797 const lcName = transformCaseFunc(name); 2798 let value = name === 'value' ? attrValue : stringTrim(attrValue); 2799 /* Execute a hook if present */ 2800 hookEvent.attrName = lcName; 2801 hookEvent.attrValue = value; 2802 hookEvent.keepAttr = true; 2803 hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set 2804 _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); 2805 value = hookEvent.attrValue; 2806 /* Full DOM Clobbering protection via namespace isolation, 2807 * Prefix id and name attributes with `user-content-` 2808 */ 2809 if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) { 2810 // Remove the attribute with this value 2811 _removeAttribute(name, currentNode); 2812 // Prefix the value and later re-create the attribute with the sanitized value 2813 value = SANITIZE_NAMED_PROPS_PREFIX + value; 2814 } 2815 /* Work around a security issue with comments inside attributes */ 2816 if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) { 2817 _removeAttribute(name, currentNode); 2818 continue; 2819 } 2820 /* Did the hooks approve of the attribute? */ 2821 if (hookEvent.forceKeepAttr) { 2822 continue; 2823 } 2824 /* Remove attribute */ 2825 _removeAttribute(name, currentNode); 2826 /* Did the hooks approve of the attribute? */ 2827 if (!hookEvent.keepAttr) { 2828 continue; 2829 } 2830 /* Work around a security issue in jQuery 3.0 */ 2831 if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { 2832 _removeAttribute(name, currentNode); 2833 continue; 2834 } 2835 /* Sanitize attribute content to be template-safe */ 2836 if (SAFE_FOR_TEMPLATES) { 2837 arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { 2838 value = stringReplace(value, expr, ' '); 2839 }); 2840 } 2841 /* Is `value` valid for this attribute? */ 2842 const lcTag = transformCaseFunc(currentNode.nodeName); 2843 if (!_isValidAttribute(lcTag, lcName, value)) { 2844 continue; 2845 } 2846 /* Handle attributes that require Trusted Types */ 2847 if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') { 2848 if (namespaceURI) ;else { 2849 switch (trustedTypes.getAttributeType(lcTag, lcName)) { 2850 case 'TrustedHTML': 2851 { 2852 value = trustedTypesPolicy.createHTML(value); 2853 break; 2854 } 2855 case 'TrustedScriptURL': 2856 { 2857 value = trustedTypesPolicy.createScriptURL(value); 2858 break; 2859 } 2860 } 2861 } 2862 } 2863 /* Handle invalid data-* attribute set by try-catching it */ 2864 try { 2865 if (namespaceURI) { 2866 currentNode.setAttributeNS(namespaceURI, name, value); 2867 } else { 2868 /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */ 2869 currentNode.setAttribute(name, value); 2870 } 2871 if (_isClobbered(currentNode)) { 2872 _forceRemove(currentNode); 2873 } else { 2874 arrayPop(DOMPurify.removed); 2875 } 2876 } catch (_) {} 2877 } 2878 /* Execute a hook if present */ 2879 _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); 2880 }; 2881 /** 2882 * _sanitizeShadowDOM 2883 * 2884 * @param fragment to iterate over recursively 2885 */ 2886 const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) { 2887 let shadowNode = null; 2888 const shadowIterator = _createNodeIterator(fragment); 2889 /* Execute a hook if present */ 2890 _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); 2891 while (shadowNode = shadowIterator.nextNode()) { 2892 /* Execute a hook if present */ 2893 _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); 2894 /* Sanitize tags and elements */ 2895 _sanitizeElements(shadowNode); 2896 /* Check attributes next */ 2897 _sanitizeAttributes(shadowNode); 2898 /* Deep shadow DOM detected */ 2899 if (shadowNode.content instanceof DocumentFragment) { 2900 _sanitizeShadowDOM(shadowNode.content); 2901 } 2902 } 2903 /* Execute a hook if present */ 2904 _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); 2905 }; 2906 // eslint-disable-next-line complexity 2907 DOMPurify.sanitize = function (dirty) { 2908 let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 2909 let body = null; 2910 let importedNode = null; 2911 let currentNode = null; 2912 let returnNode = null; 2913 /* Make sure we have a string to sanitize. 2914 DO NOT return early, as this will return the wrong type if 2915 the user has requested a DOM object rather than a string */ 2916 IS_EMPTY_INPUT = !dirty; 2917 if (IS_EMPTY_INPUT) { 2918 dirty = '<!-->'; 2919 } 2920 /* Stringify, in case dirty is an object */ 2921 if (typeof dirty !== 'string' && !_isNode(dirty)) { 2922 if (typeof dirty.toString === 'function') { 2923 dirty = dirty.toString(); 2924 if (typeof dirty !== 'string') { 2925 throw typeErrorCreate('dirty is not a string, aborting'); 2926 } 2927 } else { 2928 throw typeErrorCreate('toString is not a function'); 2929 } 2930 } 2931 /* Return dirty HTML if DOMPurify cannot run */ 2932 if (!DOMPurify.isSupported) { 2933 return dirty; 2934 } 2935 /* Assign config vars */ 2936 if (!SET_CONFIG) { 2937 _parseConfig(cfg); 2938 } 2939 /* Clean up removed elements */ 2940 DOMPurify.removed = []; 2941 /* Check if dirty is correctly typed for IN_PLACE */ 2942 if (typeof dirty === 'string') { 2943 IN_PLACE = false;
vendor: 2,671 bytes, lines 2944-3006
2944 } 2945 if (IN_PLACE) { 2946 /* Do some early pre-sanitization to avoid unsafe root nodes */ 2947 if (dirty.nodeName) { 2948 const tagName = transformCaseFunc(dirty.nodeName); 2949 if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { 2950 throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place'); 2951 } 2952 } 2953 } else if (dirty instanceof Node) { 2954 /* If dirty is a DOM element, append to an empty document to avoid 2955 elements being stripped by the parser */ 2956 body = _initDocument('<!---->'); 2957 importedNode = body.ownerDocument.importNode(dirty, true); 2958 if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') { 2959 /* Node is already a body, use as is */ 2960 body = importedNode; 2961 } else if (importedNode.nodeName === 'HTML') { 2962 body = importedNode; 2963 } else { 2964 // eslint-disable-next-line unicorn/prefer-dom-node-append 2965 body.appendChild(importedNode); 2966 } 2967 } else { 2968 /* Exit directly if we have nothing to do */ 2969 if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && 2970 // eslint-disable-next-line unicorn/prefer-includes 2971 dirty.indexOf('<') === -1) { 2972 return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; 2973 } 2974 /* Initialize the document to work on */ 2975 body = _initDocument(dirty); 2976 /* Check we have a DOM node from the data */ 2977 if (!body) { 2978 return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ''; 2979 } 2980 } 2981 /* Remove first element node (ours) if FORCE_BODY is set */ 2982 if (body && FORCE_BODY) { 2983 _forceRemove(body.firstChild); 2984 } 2985 /* Get node iterator */ 2986 const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); 2987 /* Now start iterating over the created document */ 2988 while (currentNode = nodeIterator.nextNode()) { 2989 /* Sanitize tags and elements */ 2990 _sanitizeElements(currentNode); 2991 /* Check attributes next */ 2992 _sanitizeAttributes(currentNode); 2993 /* Shadow DOM detected, sanitize it */ 2994 if (currentNode.content instanceof DocumentFragment) { 2995 _sanitizeShadowDOM(currentNode.content); 2996 } 2997 } 2998 /* If we sanitized `dirty` in-place, return it. */ 2999 if (IN_PLACE) { 3000 return dirty; 3001 } 3002 /* Return sanitized string or DOM */ 3003 if (RETURN_DOM) { 3004 if (RETURN_DOM_FRAGMENT) { 3005 returnNode = createDocumentFragment.call(body.ownerDocument); 3006 while (body.firstChild) {
vendor: 4,199 bytes, lines 3007-3110
3007 // eslint-disable-next-line unicorn/prefer-dom-node-append 3008 returnNode.appendChild(body.firstChild); 3009 } 3010 } else { 3011 returnNode = body; 3012 } 3013 if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { 3014 /* 3015 AdoptNode() is not used because internal state is not reset 3016 (e.g. the past names map of a HTMLFormElement), this is safe 3017 in theory but we would rather not risk another attack vector. 3018 The state that is cloned by importNode() is explicitly defined 3019 by the specs. 3020 */ 3021 returnNode = importNode.call(originalDocument, returnNode, true); 3022 } 3023 return returnNode; 3024 } 3025 let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; 3026 /* Serialize doctype if allowed */ 3027 if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { 3028 serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML; 3029 } 3030 /* Sanitize final string template-safe */ 3031 if (SAFE_FOR_TEMPLATES) { 3032 arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => { 3033 serializedHTML = stringReplace(serializedHTML, expr, ' '); 3034 }); 3035 } 3036 return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; 3037 }; 3038 DOMPurify.setConfig = function () { 3039 let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 3040 _parseConfig(cfg); 3041 SET_CONFIG = true; 3042 }; 3043 DOMPurify.clearConfig = function () { 3044 CONFIG = null; 3045 SET_CONFIG = false; 3046 }; 3047 DOMPurify.isValidAttribute = function (tag, attr, value) { 3048 /* Initialize shared config vars if necessary. */ 3049 if (!CONFIG) { 3050 _parseConfig({}); 3051 } 3052 const lcTag = transformCaseFunc(tag); 3053 const lcName = transformCaseFunc(attr); 3054 return _isValidAttribute(lcTag, lcName, value); 3055 }; 3056 DOMPurify.addHook = function (entryPoint, hookFunction) { 3057 if (typeof hookFunction !== 'function') { 3058 return; 3059 } 3060 arrayPush(hooks[entryPoint], hookFunction); 3061 }; 3062 DOMPurify.removeHook = function (entryPoint) { 3063 return arrayPop(hooks[entryPoint]); 3064 }; 3065 DOMPurify.removeHooks = function (entryPoint) { 3066 hooks[entryPoint] = []; 3067 }; 3068 DOMPurify.removeAllHooks = function () { 3069 hooks = _createHooksMap(); 3070 }; 3071 return DOMPurify; 3072 } 3073 var purify = createDOMPurify(); 3074 3075 purify.addHook("uponSanitizeAttribute", function (node, data) { 3076 const allowedAttributePattern = /^data-trix-/; 3077 if (allowedAttributePattern.test(data.attrName)) { 3078 data.forceKeepAttr = true; 3079 } 3080 }); 3081 const DEFAULT_ALLOWED_ATTRIBUTES = "style href src width height language class".split(" "); 3082 const DEFAULT_FORBIDDEN_PROTOCOLS = "javascript:".split(" "); 3083 const DEFAULT_FORBIDDEN_ELEMENTS = "script iframe form noscript".split(" "); 3084 class HTMLSanitizer extends BasicObject { 3085 static setHTML(element, html) { 3086 const sanitizedElement = new this(html).sanitize(); 3087 const sanitizedHtml = sanitizedElement.getHTML ? sanitizedElement.getHTML() : sanitizedElement.outerHTML; 3088 element.innerHTML = sanitizedHtml; 3089 } 3090 static sanitize(html, options) { 3091 const sanitizer = new this(html, options); 3092 sanitizer.sanitize(); 3093 return sanitizer; 3094 } 3095 constructor(html) { 3096 let { 3097 allowedAttributes, 3098 forbiddenProtocols, 3099 forbiddenElements 3100 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 3101 super(...arguments); 3102 this.allowedAttributes = allowedAttributes || DEFAULT_ALLOWED_ATTRIBUTES; 3103 this.forbiddenProtocols = forbiddenProtocols || DEFAULT_FORBIDDEN_PROTOCOLS; 3104 this.forbiddenElements = forbiddenElements || DEFAULT_FORBIDDEN_ELEMENTS; 3105 this.body = createBodyElementForHTML(html); 3106 } 3107 sanitize() { 3108 this.sanitizeElements(); 3109 this.normalizeListElementNesting(); 3110 purify.setConfig(dompurify
vendor: 6,519 bytes, lines 3110-3319
3110); 3111 this.body = purify.sanitize(this.body); 3112 return this.body; 3113 } 3114 getHTML() { 3115 return this.body.innerHTML; 3116 } 3117 getBody() { 3118 return this.body; 3119 } 3120 3121 // Private 3122 3123 sanitizeElements() { 3124 const walker = walkTree(this.body); 3125 const nodesToRemove = []; 3126 while (walker.nextNode()) { 3127 const node = walker.currentNode; 3128 switch (node.nodeType) { 3129 case Node.ELEMENT_NODE: 3130 if (this.elementIsRemovable(node)) { 3131 nodesToRemove.push(node); 3132 } else { 3133 this.sanitizeElement(node); 3134 } 3135 break; 3136 case Node.COMMENT_NODE: 3137 nodesToRemove.push(node); 3138 break; 3139 } 3140 } 3141 nodesToRemove.forEach(node => removeNode(node)); 3142 return this.body; 3143 } 3144 sanitizeElement(element) { 3145 if (element.hasAttribute("href")) { 3146 if (this.forbiddenProtocols.includes(element.protocol)) { 3147 element.removeAttribute("href"); 3148 } 3149 } 3150 Array.from(element.attributes).forEach(_ref => { 3151 let { 3152 name 3153 } = _ref; 3154 if (!this.allowedAttributes.includes(name) && name.indexOf("data-trix") !== 0) { 3155 element.removeAttribute(name); 3156 } 3157 }); 3158 return element; 3159 } 3160 normalizeListElementNesting() { 3161 Array.from(this.body.querySelectorAll("ul,ol")).forEach(listElement => { 3162 const previousElement = listElement.previousElementSibling; 3163 if (previousElement) { 3164 if (tagName(previousElement) === "li") { 3165 previousElement.appendChild(listElement); 3166 } 3167 } 3168 }); 3169 return this.body; 3170 } 3171 elementIsRemovable(element) { 3172 if ((element === null || element === void 0 ? void 0 : element.nodeType) !== Node.ELEMENT_NODE) return; 3173 return this.elementIsForbidden(element) || this.elementIsntSerializable(element); 3174 } 3175 elementIsForbidden(element) { 3176 return this.forbiddenElements.includes(tagName(element)); 3177 } 3178 elementIsntSerializable(element) { 3179 return element.getAttribute("data-trix-serialize") === "false" && !nodeIsAttachmentElement(element); 3180 } 3181 } 3182 const createBodyElementForHTML = function () { 3183 let html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; 3184 // Remove everything after </html> 3185 html = html.replace(/<\/html[^>]*>[^]*$/i, "</html>"); 3186 const doc = document.implementation.createHTMLDocument(""); 3187 doc.documentElement.innerHTML = html; 3188 Array.from(doc.head.querySelectorAll("style")).forEach(element => { 3189 doc.body.appendChild(element); 3190 }); 3191 return doc.body; 3192 }; 3193 3194 const { 3195 css: css$2 3196 } = config; 3197 class AttachmentView extends ObjectView { 3198 constructor() { 3199 super(...arguments); 3200 this.attachment = this.object; 3201 this.attachment.uploadProgressDelegate = this; 3202 this.attachmentPiece = this.options.piece; 3203 } 3204 createContentNodes() { 3205 return []; 3206 } 3207 createNodes() { 3208 let innerElement; 3209 const figure = innerElement = makeElement({ 3210 tagName: "figure", 3211 className: this.getClassName(), 3212 data: this.getData(), 3213 editable: false 3214 }); 3215 const href = this.getHref(); 3216 if (href) { 3217 innerElement = makeElement({ 3218 tagName: "a", 3219 editable: false, 3220 attributes: { 3221 href, 3222 tabindex: -1 3223 } 3224 }); 3225 figure.appendChild(innerElement); 3226 } 3227 if (this.attachment.hasContent()) { 3228 HTMLSanitizer.setHTML(innerElement, this.attachment.getContent()); 3229 } else { 3230 this.createContentNodes().forEach(node => { 3231 innerElement.appendChild(node); 3232 }); 3233 } 3234 innerElement.appendChild(this.createCaptionElement()); 3235 if (this.attachment.isPending()) { 3236 this.progressElement = makeElement({ 3237 tagName: "progress", 3238 attributes: { 3239 class: css$2.attachmentProgress, 3240 value: this.attachment.getUploadProgress(), 3241 max: 100 3242 }, 3243 data: { 3244 trixMutable: true, 3245 trixStoreKey: ["progressElement", this.attachment.id].join("/") 3246 } 3247 }); 3248 figure.appendChild(this.progressElement); 3249 } 3250 return [createCursorTarget("left"), figure, createCursorTarget("right")]; 3251 } 3252 createCaptionElement() { 3253 const figcaption = makeElement({ 3254 tagName: "figcaption", 3255 className: css$2.attachmentCaption 3256 }); 3257 const caption = this.attachmentPiece.getCaption(); 3258 if (caption) { 3259 figcaption.classList.add("".concat(css$2.attachmentCaption, "--edited")); 3260 figcaption.textContent = caption; 3261 } else { 3262 let name, size; 3263 const captionConfig = this.getCaptionConfig(); 3264 if (captionConfig.name) { 3265 name = this.attachment.getFilename(); 3266 } 3267 if (captionConfig.size) { 3268 size = this.attachment.getFormattedFilesize(); 3269 } 3270 if (name) { 3271 const nameElement = makeElement({ 3272 tagName: "span", 3273 className: css$2.attachmentName, 3274 textContent: name 3275 }); 3276 figcaption.appendChild(nameElement); 3277 } 3278 if (size) { 3279 if (name) { 3280 figcaption.appendChild(document.createTextNode(" ")); 3281 } 3282 const sizeElement = makeElement({ 3283 tagName: "span", 3284 className: css$2.attachmentSize, 3285 textContent: size 3286 }); 3287 figcaption.appendChild(sizeElement); 3288 } 3289 } 3290 return figcaption; 3291 } 3292 getClassName() { 3293 const names = [css$2.attachment, "".concat(css$2.attachment, "--").concat(this.attachment.getType())]; 3294 const extension = this.attachment.getExtension(); 3295 if (extension) { 3296 names.push("".concat(css$2.attachment, "--").concat(extension)); 3297 } 3298 return names.join(" "); 3299 } 3300 getData() { 3301 const data = { 3302 trixAttachment: JSON.stringify(this.attachment), 3303 trixContentType: this.attachment.getContentType(), 3304 trixId: this.attachment.id 3305 }; 3306 const { 3307 attributes 3308 } = this.attachmentPiece; 3309 if (!attributes.isEmpty()) { 3310 data.trixAttributes = JSON.stringify(attributes); 3311 } 3312 if (this.attachment.isPending()) { 3313 data.trixSerialize = false; 3314 } 3315 return data; 3316 } 3317 getHref() { 3318 if (!htmlContainsTagName(this.attachment.getContent(), "a")) { 3319
vendor: 2,965 bytes, lines 3319-3412
3319return this.attachment.getHref(); 3320 } 3321 } 3322 getCaptionConfig() { 3323 var _config$attachments$t; 3324 const type = this.attachment.getType(); 3325 const captionConfig = copyObject((_config$attachments$t = attachments[type]) === null || _config$attachments$t === void 0 ? void 0 : _config$attachments$t.caption); 3326 if (type === "file") { 3327 captionConfig.name = true; 3328 } 3329 return captionConfig; 3330 } 3331 findProgressElement() { 3332 var _this$findElement; 3333 return (_this$findElement = this.findElement()) === null || _this$findElement === void 0 ? void 0 : _this$findElement.querySelector("progress"); 3334 } 3335 3336 // Attachment delegate 3337 3338 attachmentDidChangeUploadProgress() { 3339 const value = this.attachment.getUploadProgress(); 3340 const progressElement = this.findProgressElement(); 3341 if (progressElement) { 3342 progressElement.value = value; 3343 } 3344 } 3345 } 3346 const createCursorTarget = name => makeElement({ 3347 tagName: "span", 3348 textContent: ZERO_WIDTH_SPACE, 3349 data: { 3350 trixCursorTarget: name, 3351 trixSerialize: false 3352 } 3353 }); 3354 const htmlContainsTagName = function (html, tagName) { 3355 const div = makeElement("div"); 3356 HTMLSanitizer.setHTML(div, html || ""); 3357 return div.querySelector(tagName); 3358 }; 3359 3360 class PreviewableAttachmentView extends AttachmentView { 3361 constructor() { 3362 super(...arguments); 3363 this.attachment.previewDelegate = this; 3364 } 3365 createContentNodes() { 3366 this.image = makeElement({ 3367 tagName: "img", 3368 attributes: { 3369 src: "" 3370 }, 3371 data: { 3372 trixMutable: true 3373 } 3374 }); 3375 this.refresh(this.image); 3376 return [this.image]; 3377 } 3378 createCaptionElement() { 3379 const figcaption = super.createCaptionElement(...arguments); 3380 if (!figcaption.textContent) { 3381 figcaption.setAttribute("data-trix-placeholder", lang$1.captionPlaceholder); 3382 } 3383 return figcaption; 3384 } 3385 refresh(image) { 3386 if (!image) { 3387 var _this$findElement; 3388 image = (_this$findElement = this.findElement()) === null || _this$findElement === void 0 ? void 0 : _this$findElement.querySelector("img"); 3389 } 3390 if (image) { 3391 return this.updateAttributesForImage(image); 3392 } 3393 } 3394 updateAttributesForImage(image) { 3395 const url = this.attachment.getURL(); 3396 const previewURL = this.attachment.getPreviewURL(); 3397 image.src = previewURL || url; 3398 if (previewURL === url) { 3399 image.removeAttribute("data-trix-serialized-attributes"); 3400 } else { 3401 const serializedAttributes = JSON.stringify({ 3402 src: url 3403 }); 3404 image.setAttribute("data-trix-serialized-attributes", serializedAttributes); 3405 } 3406 const width = this.attachment.getWidth(); 3407 const height = this.attachment.getHeight(); 3408 if (width != null) { 3409 image.width = width; 3410 } 3411 if (height != null) { 3412 image.height = heigh
vendor: 9,116 bytes, lines 3412-3707
3412t; 3413 } 3414 const storeKey = ["imageElement", this.attachment.id, image.src, image.width, image.height].join("/"); 3415 image.dataset.trixStoreKey = storeKey; 3416 } 3417 3418 // Attachment delegate 3419 3420 attachmentDidChangeAttributes() { 3421 this.refresh(this.image); 3422 return this.refresh(); 3423 } 3424 } 3425 3426 /* eslint-disable 3427 no-useless-escape, 3428 no-var, 3429 */ 3430 class PieceView extends ObjectView { 3431 constructor() { 3432 super(...arguments); 3433 this.piece = this.object; 3434 this.attributes = this.piece.getAttributes(); 3435 this.textConfig = this.options.textConfig; 3436 this.context = this.options.context; 3437 if (this.piece.attachment) { 3438 this.attachment = this.piece.attachment; 3439 } else { 3440 this.string = this.piece.toString(); 3441 } 3442 } 3443 createNodes() { 3444 let nodes = this.attachment ? this.createAttachmentNodes() : this.createStringNodes(); 3445 const element = this.createElement(); 3446 if (element) { 3447 const innerElement = findInnerElement(element); 3448 Array.from(nodes).forEach(node => { 3449 innerElement.appendChild(node); 3450 }); 3451 nodes = [element]; 3452 } 3453 return nodes; 3454 } 3455 createAttachmentNodes() { 3456 const constructor = this.attachment.isPreviewable() ? PreviewableAttachmentView : AttachmentView; 3457 const view = this.createChildView(constructor, this.piece.attachment, { 3458 piece: this.piece 3459 }); 3460 return view.getNodes(); 3461 } 3462 createStringNodes() { 3463 var _this$textConfig; 3464 if ((_this$textConfig = this.textConfig) !== null && _this$textConfig !== void 0 && _this$textConfig.plaintext) { 3465 return [document.createTextNode(this.string)]; 3466 } else { 3467 const nodes = []; 3468 const iterable = this.string.split("\n"); 3469 for (let index = 0; index < iterable.length; index++) { 3470 const substring = iterable[index]; 3471 if (index > 0) { 3472 const element = makeElement("br"); 3473 nodes.push(element); 3474 } 3475 if (substring.length) { 3476 const node = document.createTextNode(this.preserveSpaces(substring)); 3477 nodes.push(node); 3478 } 3479 } 3480 return nodes; 3481 } 3482 } 3483 createElement() { 3484 let element, key, value; 3485 const styles = {}; 3486 for (key in this.attributes) { 3487 value = this.attributes[key]; 3488 const config = getTextConfig(key); 3489 if (config) { 3490 if (config.tagName) { 3491 var innerElement; 3492 const pendingElement = makeElement(config.tagName); 3493 if (innerElement) { 3494 innerElement.appendChild(pendingElement); 3495 innerElement = pendingElement; 3496 } else { 3497 element = innerElement = pendingElement; 3498 } 3499 } 3500 if (config.styleProperty) { 3501 styles[config.styleProperty] = value; 3502 } 3503 if (config.style) { 3504 for (key in config.style) { 3505 value = config.style[key]; 3506 styles[key] = value; 3507 } 3508 } 3509 } 3510 } 3511 if (Object.keys(styles).length) { 3512 if (!element) { 3513 element = makeElement("span"); 3514 } 3515 for (key in styles) { 3516 value = styles[key]; 3517 element.style[key] = value; 3518 } 3519 } 3520 return element; 3521 } 3522 createContainerElement() { 3523 for (const key in this.attributes) { 3524 const value = this.attributes[key]; 3525 const config = getTextConfig(key); 3526 if (config) { 3527 if (config.groupTagName) { 3528 const attributes = {}; 3529 attributes[key] = value; 3530 return makeElement(config.groupTagName, attributes); 3531 } 3532 } 3533 } 3534 } 3535 preserveSpaces(string) { 3536 if (this.context.isLast) { 3537 string = string.replace(/\ $/, NON_BREAKING_SPACE); 3538 } 3539 string = string.replace(/(\S)\ {3}(\S)/g, "$1 ".concat(NON_BREAKING_SPACE, " $2")).replace(/\ {2}/g, "".concat(NON_BREAKING_SPACE, " ")).replace(/\ {2}/g, " ".concat(NON_BREAKING_SPACE)); 3540 if (this.context.isFirst || this.context.followsWhitespace) { 3541 string = string.replace(/^\ /, NON_BREAKING_SPACE); 3542 } 3543 return string; 3544 } 3545 } 3546 3547 /* eslint-disable 3548 no-var, 3549 */ 3550 class TextView extends ObjectView { 3551 constructor() { 3552 super(...arguments); 3553 this.text = this.object; 3554 this.textConfig = this.options.textConfig; 3555 } 3556 createNodes() { 3557 const nodes = []; 3558 const pieces = ObjectGroup.groupObjects(this.getPieces()); 3559 const lastIndex = pieces.length - 1; 3560 for (let index = 0; index < pieces.length; index++) { 3561 const piece = pieces[index]; 3562 const context = {}; 3563 if (index === 0) { 3564 context.isFirst = true; 3565 } 3566 if (index === lastIndex) { 3567 context.isLast = true; 3568 } 3569 if (endsWithWhitespace(previousPiece)) { 3570 context.followsWhitespace = true; 3571 } 3572 const view = this.findOrCreateCachedChildView(PieceView, piece, { 3573 textConfig: this.textConfig, 3574 context 3575 }); 3576 nodes.push(...Array.from(view.getNodes() || [])); 3577 var previousPiece = piece; 3578 } 3579 return nodes; 3580 } 3581 getPieces() { 3582 return Array.from(this.text.getPieces()).filter(piece => !piece.hasAttribute("blockBreak")); 3583 } 3584 } 3585 const endsWithWhitespace = piece => /\s$/.test(piece === null || piece === void 0 ? void 0 : piece.toString()); 3586 3587 const { 3588 css: css$1 3589 } = config; 3590 class BlockView extends ObjectView { 3591 constructor() { 3592 super(...arguments); 3593 this.block = this.object; 3594 this.attributes = this.block.getAttributes(); 3595 } 3596 createNodes() { 3597 const comment = document.createComment("block"); 3598 const nodes = [comment]; 3599 if (this.block.isEmpty()) { 3600 nodes.push(makeElement("br")); 3601 } else { 3602 var _getBlockConfig; 3603 const textConfig = (_getBlockConfig = getBlockConfig(this.block.getLastAttribute())) === null || _getBlockConfig === void 0 ? void 0 : _getBlockConfig.text; 3604 const textView = this.findOrCreateCachedChildView(TextView, this.block.text, { 3605 textConfig 3606 }); 3607 nodes.push(...Array.from(textView.getNodes() || [])); 3608 if (this.shouldAddExtraNewlineElement()) { 3609 nodes.push(makeElement("br")); 3610 } 3611 } 3612 if (this.attributes.length) { 3613 return nodes; 3614 } else { 3615 let attributes$1; 3616 const { 3617 tagName 3618 } = attributes.default; 3619 if (this.block.isRTL()) { 3620 attributes$1 = { 3621 dir: "rtl" 3622 }; 3623 } 3624 const element = makeElement({ 3625 tagName, 3626 attributes: attributes$1 3627 }); 3628 nodes.forEach(node => element.appendChild(node)); 3629 return [element]; 3630 } 3631 } 3632 createContainerElement(depth) { 3633 const attributes = {}; 3634 let className; 3635 const attributeName = this.attributes[depth]; 3636 const { 3637 tagName, 3638 htmlAttributes = [] 3639 } = getBlockConfig(attributeName); 3640 if (depth === 0 && this.block.isRTL()) { 3641 Object.assign(attributes, { 3642 dir: "rtl" 3643 }); 3644 } 3645 if (attributeName === "attachmentGallery") { 3646 const size = this.block.getBlockBreakPosition(); 3647 className = "".concat(css$1.attachmentGallery, " ").concat(css$1.attachmentGallery, "--").concat(size); 3648 } 3649 Object.entries(this.block.htmlAttributes).forEach(_ref => { 3650 let [name, value] = _ref; 3651 if (htmlAttributes.includes(name)) { 3652 attributes[name] = value; 3653 } 3654 }); 3655 return makeElement({ 3656 tagName, 3657 className, 3658 attributes 3659 }); 3660 } 3661 3662 // A single <br> at the end of a block element has no visual representation 3663 // so add an extra one. 3664 shouldAddExtraNewlineElement() { 3665 return /\n\n$/.test(this.block.toString()); 3666 } 3667 } 3668 3669 class DocumentView extends ObjectView { 3670 static render(document) { 3671 const element = makeElement("div"); 3672 const view = new this(document, { 3673 element 3674 }); 3675 view.render(); 3676 view.sync(); 3677 return element; 3678 } 3679 constructor() { 3680 super(...arguments); 3681 this.element = this.options.element; 3682 this.elementStore = new ElementStore(); 3683 this.setDocument(this.object); 3684 } 3685 setDocument(document) { 3686 if (!document.isEqualTo(this.document)) { 3687 this.document = this.object = document; 3688 } 3689 } 3690 render() { 3691 this.childViews = []; 3692 this.shadowElement = makeElement("div"); 3693 if (!this.document.isEmpty()) { 3694 const objects = ObjectGroup.groupObjects(this.document.getBlocks(), { 3695 asTree: true 3696 }); 3697 Array.from(objects).forEach(object => { 3698 const view = this.findOrCreateCachedChildView(BlockView, object); 3699 Array.from(view.getNodes()).map(node => this.shadowElement.appendChild(node)); 3700 }); 3701 } 3702 } 3703 isSynced() { 3704 return elementsHaveEqualHTML(this.shadowElement, this.element); 3705 } 3706 sync() { 3707 const
3707fragment = this.createDocumentFragmentForSync(); 3708 while (this.element.lastChild) { 3709 this.element.removeChild(this.element.lastChild); 3710 } 3711 this.element.appendChild(fragment); 3712 return this.didSync(); 3713 } 3714 3715 // Private 3716 3717 didSync() { 3718 this.elementStore.reset(findStoredElements(this.element)); 3719 return defer(() => this.garbageCollectCachedViews()); 3720 } 3721 createDocumentFragmentForSync() { 3722 const fragment = document.createDocumentFragment();
vendor: 7,482 bytes, lines 3723-3946
3723 Array.from(this.shadowElement.childNodes).forEach(node => { 3724 fragment.appendChild(node.cloneNode(true)); 3725 }); 3726 Array.from(findStoredElements(fragment)).forEach(element => { 3727 const storedElement = this.elementStore.remove(element); 3728 if (storedElement) { 3729 element.parentNode.replaceChild(storedElement, element); 3730 } 3731 }); 3732 return fragment; 3733 } 3734 } 3735 const findStoredElements = element => element.querySelectorAll("[data-trix-store-key]"); 3736 const elementsHaveEqualHTML = (element, otherElement) => ignoreSpaces(element.innerHTML) === ignoreSpaces(otherElement.innerHTML); 3737 const ignoreSpaces = html => html.replace(/ /g, " "); 3738 3739 function _AsyncGenerator(e) { 3740 var r, t; 3741 function resume(r, t) { 3742 try { 3743 var n = e[r](t), 3744 o = n.value, 3745 u = o instanceof _OverloadYield; 3746 Promise.resolve(u ? o.v : o).then(function (t) { 3747 if (u) { 3748 var i = "return" === r ? "return" : "next"; 3749 if (!o.k || t.done) return resume(i, t); 3750 t = e[i](t).value; 3751 } 3752 settle(n.done ? "return" : "normal", t); 3753 }, function (e) { 3754 resume("throw", e); 3755 }); 3756 } catch (e) { 3757 settle("throw", e); 3758 } 3759 } 3760 function settle(e, n) { 3761 switch (e) { 3762 case "return": 3763 r.resolve({ 3764 value: n, 3765 done: !0 3766 }); 3767 break; 3768 case "throw": 3769 r.reject(n); 3770 break; 3771 default: 3772 r.resolve({ 3773 value: n, 3774 done: !1 3775 }); 3776 } 3777 (r = r.next) ? resume(r.key, r.arg) : t = null; 3778 } 3779 this._invoke = function (e, n) { 3780 return new Promise(function (o, u) { 3781 var i = { 3782 key: e, 3783 arg: n, 3784 resolve: o, 3785 reject: u, 3786 next: null 3787 }; 3788 t ? t = t.next = i : (r = t = i, resume(e, n)); 3789 }); 3790 }, "function" != typeof e.return && (this.return = void 0); 3791 } 3792 _AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { 3793 return this; 3794 }, _AsyncGenerator.prototype.next = function (e) { 3795 return this._invoke("next", e); 3796 }, _AsyncGenerator.prototype.throw = function (e) { 3797 return this._invoke("throw", e); 3798 }, _AsyncGenerator.prototype.return = function (e) { 3799 return this._invoke("return", e); 3800 }; 3801 function _OverloadYield(t, e) { 3802 this.v = t, this.k = e; 3803 } 3804 function old_createMetadataMethodsForProperty(e, t, a, r) { 3805 return { 3806 getMetadata: function (o) { 3807 old_assertNotFinished(r, "getMetadata"), old_assertMetadataKey(o); 3808 var i = e[o]; 3809 if (void 0 !== i) if (1 === t) { 3810 var n = i.public; 3811 if (void 0 !== n) return n[a]; 3812 } else if (2 === t) { 3813 var l = i.private; 3814 if (void 0 !== l) return l.get(a); 3815 } else if (Object.hasOwnProperty.call(i, "constructor")) return i.constructor; 3816 }, 3817 setMetadata: function (o, i) { 3818 old_assertNotFinished(r, "setMetadata"), old_assertMetadataKey(o); 3819 var n = e[o]; 3820 if (void 0 === n && (n = e[o] = {}), 1 === t) { 3821 var l = n.public; 3822 void 0 === l && (l = n.public = {}), l[a] = i; 3823 } else if (2 === t) { 3824 var s = n.priv; 3825 void 0 === s && (s = n.private = new Map()), s.set(a, i); 3826 } else n.constructor = i; 3827 } 3828 }; 3829 } 3830 function old_convertMetadataMapToFinal(e, t) { 3831 var a = e[Symbol.metadata || Symbol.for("Symbol.metadata")], 3832 r = Object.getOwnPropertySymbols(t); 3833 if (0 !== r.length) { 3834 for (var o = 0; o < r.length; o++) { 3835 var i = r[o], 3836 n = t[i], 3837 l = a ? a[i] : null, 3838 s = n.public, 3839 c = l ? l.public : null; 3840 s && c && Object.setPrototypeOf(s, c); 3841 var d = n.private; 3842 if (d) { 3843 var u = Array.from(d.values()), 3844 f = l ? l.private : null; 3845 f && (u = u.concat(f)), n.private = u; 3846 } 3847 l && Object.setPrototypeOf(n, l); 3848 } 3849 a && Object.setPrototypeOf(t, a), e[Symbol.metadata || Symbol.for("Symbol.metadata")] = t; 3850 } 3851 } 3852 function old_createAddInitializerMethod(e, t) { 3853 return function (a) { 3854 old_assertNotFinished(t, "addInitializer"), old_assertCallable(a, "An initializer"), e.push(a); 3855 }; 3856 } 3857 function old_memberDec(e, t, a, r, o, i, n, l, s) { 3858 var c; 3859 switch (i) { 3860 case 1: 3861 c = "accessor"; 3862 break; 3863 case 2: 3864 c = "method"; 3865 break; 3866 case 3: 3867 c = "getter"; 3868 break; 3869 case 4: 3870 c = "setter"; 3871 break; 3872 default: 3873 c = "field"; 3874 } 3875 var d, 3876 u, 3877 f = { 3878 kind: c, 3879 name: l ? "#" + t : t, 3880 isStatic: n, 3881 isPrivate: l 3882 }, 3883 p = { 3884 v: !1 3885 }; 3886 if (0 !== i && (f.addInitializer = old_createAddInitializerMethod(o, p)), l) { 3887 d = 2, u = Symbol(t); 3888 var v = {}; 3889 0 === i ? (v.get = a.get, v.set = a.set) : 2 === i ? v.get = function () { 3890 return a.value; 3891 } : (1 !== i && 3 !== i || (v.get = function () { 3892 return a.get.call(this); 3893 }), 1 !== i && 4 !== i || (v.set = function (e) { 3894 a.set.call(this, e); 3895 })), f.access = v; 3896 } else d = 1, u = t; 3897 try { 3898 return e(s, Object.assign(f, old_createMetadataMethodsForProperty(r, d, u, p))); 3899 } finally { 3900 p.v = !0; 3901 } 3902 } 3903 function old_assertNotFinished(e, t) { 3904 if (e.v) throw new Error("attempted to call " + t + " after decoration was finished"); 3905 } 3906 function old_assertMetadataKey(e) { 3907 if ("symbol" != typeof e) throw new TypeError("Metadata keys must be symbols, received: " + e); 3908 } 3909 function old_assertCallable(e, t) { 3910 if ("function" != typeof e) throw new TypeError(t + " must be a function"); 3911 } 3912 function old_assertValidReturnValue(e, t) { 3913 var a = typeof t; 3914 if (1 === e) { 3915 if ("object" !== a || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); 3916 void 0 !== t.get && old_assertCallable(t.get, "accessor.get"), void 0 !== t.set && old_assertCallable(t.set, "accessor.set"), void 0 !== t.init && old_assertCallable(t.init, "accessor.init"), void 0 !== t.initializer && old_assertCallable(t.initializer, "accessor.initializer"); 3917 } else if ("function" !== a) { 3918 var r; 3919 throw r = 0 === e ? "field" : 10 === e ? "class" : "method", new TypeError(r + " decorators must return a function or void 0"); 3920 } 3921 } 3922 function old_getInit(e) { 3923 var t; 3924 return null == (t = e.init) && (t = e.initializer) && "undefined" != typeof console && console.warn(".initializer has been renamed to .init as of March 2022"), t; 3925 } 3926 function old_applyMemberDec(e, t, a, r, o, i, n, l, s) { 3927 var c, 3928 d, 3929 u, 3930 f, 3931 p, 3932 v, 3933 h = a[0]; 3934 if (n ? c = 0 === o || 1 === o ? { 3935 get: a[3], 3936 set: a[4] 3937 } : 3 === o ? { 3938 get: a[3] 3939 } : 4 === o ? { 3940 set: a[3] 3941 } : { 3942 value: a[3] 3943 } : 0 !== o && (c = Object.getOwnPropertyDescriptor(t, r)), 1 === o ? u = { 3944 get: c.get, 3945 set: c.set 3946 } : 2 === o ? u = c.value : 3 === o ? u = c.get : 4 === o && (u = c.set), "function" == typeof h) void 0 !== (f = old_memberDec(h, r, c, l, s, o, i, n, u)) && (old_assertValidReturnValue(o, f), 0 === o ? d = f : 1 === o ? (d = old_getInit(f), p
vendor: 22,399 bytes, lines 3946-4589
3946= f.get || u.get, v = f.set || u.set, u = { 3947 get: p, 3948 set: v 3949 }) : u = f);else for (var y = h.length - 1; y >= 0; y--) { 3950 var b; 3951 if (void 0 !== (f = old_memberDec(h[y], r, c, l, s, o, i, n, u))) old_assertValidReturnValue(o, f), 0 === o ? b = f : 1 === o ? (b = old_getInit(f), p = f.get || u.get, v = f.set || u.set, u = { 3952 get: p, 3953 set: v 3954 }) : u = f, void 0 !== b && (void 0 === d ? d = b : "function" == typeof d ? d = [d, b] : d.push(b)); 3955 } 3956 if (0 === o || 1 === o) { 3957 if (void 0 === d) d = function (e, t) { 3958 return t; 3959 };else if ("function" != typeof d) { 3960 var g = d; 3961 d = function (e, t) { 3962 for (var a = t, r = 0; r < g.length; r++) a = g[r].call(e, a); 3963 return a; 3964 }; 3965 } else { 3966 var m = d; 3967 d = function (e, t) { 3968 return m.call(e, t); 3969 }; 3970 } 3971 e.push(d); 3972 } 3973 0 !== o && (1 === o ? (c.get = u.get, c.set = u.set) : 2 === o ? c.value = u : 3 === o ? c.get = u : 4 === o && (c.set = u), n ? 1 === o ? (e.push(function (e, t) { 3974 return u.get.call(e, t); 3975 }), e.push(function (e, t) { 3976 return u.set.call(e, t); 3977 })) : 2 === o ? e.push(u) : e.push(function (e, t) { 3978 return u.call(e, t); 3979 }) : Object.defineProperty(t, r, c)); 3980 } 3981 function old_applyMemberDecs(e, t, a, r, o) { 3982 for (var i, n, l = new Map(), s = new Map(), c = 0; c < o.length; c++) { 3983 var d = o[c]; 3984 if (Array.isArray(d)) { 3985 var u, 3986 f, 3987 p, 3988 v = d[1], 3989 h = d[2], 3990 y = d.length > 3, 3991 b = v >= 5; 3992 if (b ? (u = t, f = r, 0 !== (v -= 5) && (p = n = n || [])) : (u = t.prototype, f = a, 0 !== v && (p = i = i || [])), 0 !== v && !y) { 3993 var g = b ? s : l, 3994 m = g.get(h) || 0; 3995 if (!0 === m || 3 === m && 4 !== v || 4 === m && 3 !== v) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + h); 3996 !m && v > 2 ? g.set(h, v) : g.set(h, !0); 3997 } 3998 old_applyMemberDec(e, u, d, h, v, b, y, f, p); 3999 } 4000 } 4001 old_pushInitializers(e, i), old_pushInitializers(e, n); 4002 } 4003 function old_pushInitializers(e, t) { 4004 t && e.push(function (e) { 4005 for (var a = 0; a < t.length; a++) t[a].call(e); 4006 return e; 4007 }); 4008 } 4009 function old_applyClassDecs(e, t, a, r) { 4010 if (r.length > 0) { 4011 for (var o = [], i = t, n = t.name, l = r.length - 1; l >= 0; l--) { 4012 var s = { 4013 v: !1 4014 }; 4015 try { 4016 var c = Object.assign({ 4017 kind: "class", 4018 name: n, 4019 addInitializer: old_createAddInitializerMethod(o, s) 4020 }, old_createMetadataMethodsForProperty(a, 0, n, s)), 4021 d = r[l](i, c); 4022 } finally { 4023 s.v = !0; 4024 } 4025 void 0 !== d && (old_assertValidReturnValue(10, d), i = d); 4026 } 4027 e.push(i, function () { 4028 for (var e = 0; e < o.length; e++) o[e].call(i); 4029 }); 4030 } 4031 } 4032 function _applyDecs(e, t, a) { 4033 var r = [], 4034 o = {}, 4035 i = {}; 4036 return old_applyMemberDecs(r, e, i, o, t), old_convertMetadataMapToFinal(e.prototype, i), old_applyClassDecs(r, e, o, a), old_convertMetadataMapToFinal(e, o), r; 4037 } 4038 function applyDecs2203Factory() { 4039 function createAddInitializerMethod(e, t) { 4040 return function (r) { 4041 !function (e, t) { 4042 if (e.v) throw new Error("attempted to call " + t + " after decoration was finished"); 4043 }(t, "addInitializer"), assertCallable(r, "An initializer"), e.push(r); 4044 }; 4045 } 4046 function memberDec(e, t, r, a, n, i, s, o) { 4047 var c; 4048 switch (n) { 4049 case 1: 4050 c = "accessor"; 4051 break; 4052 case 2: 4053 c = "method"; 4054 break; 4055 case 3: 4056 c = "getter"; 4057 break; 4058 case 4: 4059 c = "setter"; 4060 break; 4061 default: 4062 c = "field"; 4063 } 4064 var l, 4065 u, 4066 f = { 4067 kind: c, 4068 name: s ? "#" + t : t, 4069 static: i, 4070 private: s 4071 }, 4072 p = { 4073 v: !1 4074 }; 4075 0 !== n && (f.addInitializer = createAddInitializerMethod(a, p)), 0 === n ? s ? (l = r.get, u = r.set) : (l = function () { 4076 return this[t]; 4077 }, u = function (e) { 4078 this[t] = e; 4079 }) : 2 === n ? l = function () { 4080 return r.value; 4081 } : (1 !== n && 3 !== n || (l = function () { 4082 return r.get.call(this); 4083 }), 1 !== n && 4 !== n || (u = function (e) { 4084 r.set.call(this, e); 4085 })), f.access = l && u ? { 4086 get: l, 4087 set: u 4088 } : l ? { 4089 get: l 4090 } : { 4091 set: u 4092 }; 4093 try { 4094 return e(o, f); 4095 } finally { 4096 p.v = !0; 4097 } 4098 } 4099 function assertCallable(e, t) { 4100 if ("function" != typeof e) throw new TypeError(t + " must be a function"); 4101 } 4102 function assertValidReturnValue(e, t) { 4103 var r = typeof t; 4104 if (1 === e) { 4105 if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); 4106 void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init"); 4107 } else if ("function" !== r) { 4108 var a; 4109 throw a = 0 === e ? "field" : 10 === e ? "class" : "method", new TypeError(a + " decorators must return a function or void 0"); 4110 } 4111 } 4112 function applyMemberDec(e, t, r, a, n, i, s, o) { 4113 var c, 4114 l, 4115 u, 4116 f, 4117 p, 4118 d, 4119 h = r[0]; 4120 if (s ? c = 0 === n || 1 === n ? { 4121 get: r[3], 4122 set: r[4] 4123 } : 3 === n ? { 4124 get: r[3] 4125 } : 4 === n ? { 4126 set: r[3] 4127 } : { 4128 value: r[3] 4129 } : 0 !== n && (c = Object.getOwnPropertyDescriptor(t, a)), 1 === n ? u = { 4130 get: c.get, 4131 set: c.set 4132 } : 2 === n ? u = c.value : 3 === n ? u = c.get : 4 === n && (u = c.set), "function" == typeof h) void 0 !== (f = memberDec(h, a, c, o, n, i, s, u)) && (assertValidReturnValue(n, f), 0 === n ? l = f : 1 === n ? (l = f.init, p = f.get || u.get, d = f.set || u.set, u = { 4133 get: p, 4134 set: d 4135 }) : u = f);else for (var v = h.length - 1; v >= 0; v--) { 4136 var g; 4137 if (void 0 !== (f = memberDec(h[v], a, c, o, n, i, s, u))) assertValidReturnValue(n, f), 0 === n ? g = f : 1 === n ? (g = f.init, p = f.get || u.get, d = f.set || u.set, u = { 4138 get: p, 4139 set: d 4140 }) : u = f, void 0 !== g && (void 0 === l ? l = g : "function" == typeof l ? l = [l, g] : l.push(g)); 4141 } 4142 if (0 === n || 1 === n) { 4143 if (void 0 === l) l = function (e, t) { 4144 return t; 4145 };else if ("function" != typeof l) { 4146 var y = l; 4147 l = function (e, t) { 4148 for (var r = t, a = 0; a < y.length; a++) r = y[a].call(e, r); 4149 return r; 4150 }; 4151 } else { 4152 var m = l; 4153 l = function (e, t) { 4154 return m.call(e, t); 4155 }; 4156 } 4157 e.push(l); 4158 } 4159 0 !== n && (1 === n ? (c.get = u.get, c.set = u.set) : 2 === n ? c.value = u : 3 === n ? c.get = u : 4 === n && (c.set = u), s ? 1 === n ? (e.push(function (e, t) { 4160 return u.get.call(e, t); 4161 }), e.push(function (e, t) { 4162 return u.set.call(e, t); 4163 })) : 2 === n ? e.push(u) : e.push(function (e, t) { 4164 return u.call(e, t); 4165 }) : Object.defineProperty(t, a, c)); 4166 } 4167 function pushInitializers(e, t) { 4168 t && e.push(function (e) { 4169 for (var r = 0; r < t.length; r++) t[r].call(e); 4170 return e; 4171 }); 4172 } 4173 return function (e, t, r) { 4174 var a = []; 4175 return function (e, t, r) { 4176 for (var a, n, i = new Map(), s = new Map(), o = 0; o < r.length; o++) { 4177 var c = r[o]; 4178 if (Array.isArray(c)) { 4179 var l, 4180 u, 4181 f = c[1], 4182 p = c[2], 4183 d = c.length > 3, 4184 h = f >= 5; 4185 if (h ? (l = t, 0 != (f -= 5) && (u = n = n || [])) : (l = t.prototype, 0 !== f && (u = a = a || [])), 0 !== f && !d) { 4186 var v = h ? s : i, 4187 g = v.get(p) || 0; 4188 if (!0 === g || 3 === g && 4 !== f || 4 === g && 3 !== f) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + p); 4189 !g && f > 2 ? v.set(p, f) : v.set(p, !0); 4190 } 4191 applyMemberDec(e, l, c, p, f, h, d, u); 4192 } 4193 } 4194 pushInitializers(e, a), pushInitializers(e, n); 4195 }(a, e, t), function (e, t, r) { 4196 if (r.length > 0) { 4197 for (var a = [], n = t, i = t.name, s = r.length - 1; s >= 0; s--) { 4198 var o = { 4199 v: !1 4200 }; 4201 try { 4202 var c = r[s](n, { 4203 kind: "class", 4204 name: i, 4205 addInitializer: createAddInitializerMethod(a, o) 4206 }); 4207 } finally { 4208 o.v = !0; 4209 } 4210 void 0 !== c && (assertValidReturnValue(10, c), n = c); 4211 } 4212 e.push(n, function () { 4213 for (var e = 0; e < a.length; e++) a[e].call(n); 4214 }); 4215 } 4216 }(a, e, r), a; 4217 }; 4218 } 4219 var applyDecs2203Impl; 4220 function _applyDecs2203(e, t, r) { 4221 return (applyDecs2203Impl = applyDecs2203Impl || applyDecs2203Factory())(e, t, r); 4222 } 4223 function applyDecs2203RFactory() { 4224 function createAddInitializerMethod(e, t) { 4225 return function (r) { 4226 !function (e, t) { 4227 if (e.v) throw new Error("attempted to call " + t + " after decoration was finished"); 4228 }(t, "addInitializer"), assertCallable(r, "An initializer"), e.push(r); 4229 }; 4230 } 4231 function memberDec(e, t, r, n, a, i, s, o) { 4232 var c; 4233 switch (a) { 4234 case 1: 4235 c = "accessor"; 4236 break; 4237 case 2: 4238 c = "method"; 4239 break; 4240 case 3: 4241 c = "getter"; 4242 break; 4243 case 4: 4244 c = "setter"; 4245 break; 4246 default: 4247 c = "field"; 4248 } 4249 var l, 4250 u, 4251 f = { 4252 kind: c, 4253 name: s ? "#" + t : t, 4254 static: i, 4255 private: s 4256 }, 4257 p = { 4258 v: !1 4259 }; 4260 0 !== a && (f.addInitializer = createAddInitializerMethod(n, p)), 0 === a ? s ? (l = r.get, u = r.set) : (l = function () { 4261 return this[t]; 4262 }, u = function (e) { 4263 this[t] = e; 4264 }) : 2 === a ? l = function () { 4265 return r.value; 4266 } : (1 !== a && 3 !== a || (l = function () { 4267 return r.get.call(this); 4268 }), 1 !== a && 4 !== a || (u = function (e) { 4269 r.set.call(this, e); 4270 })), f.access = l && u ? { 4271 get: l, 4272 set: u 4273 } : l ? { 4274 get: l 4275 } : { 4276 set: u 4277 }; 4278 try { 4279 return e(o, f); 4280 } finally { 4281 p.v = !0; 4282 } 4283 } 4284 function assertCallable(e, t) { 4285 if ("function" != typeof e) throw new TypeError(t + " must be a function"); 4286 } 4287 function assertValidReturnValue(e, t) { 4288 var r = typeof t; 4289 if (1 === e) { 4290 if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); 4291 void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init"); 4292 } else if ("function" !== r) { 4293 var n; 4294 throw n = 0 === e ? "field" : 10 === e ? "class" : "method", new TypeError(n + " decorators must return a function or void 0"); 4295 } 4296 } 4297 function applyMemberDec(e, t, r, n, a, i, s, o) { 4298 var c, 4299 l, 4300 u, 4301 f, 4302 p, 4303 d, 4304 h = r[0]; 4305 if (s ? c = 0 === a || 1 === a ? { 4306 get: r[3], 4307 set: r[4] 4308 } : 3 === a ? { 4309 get: r[3] 4310 } : 4 === a ? { 4311 set: r[3] 4312 } : { 4313 value: r[3] 4314 } : 0 !== a && (c = Object.getOwnPropertyDescriptor(t, n)), 1 === a ? u = { 4315 get: c.get, 4316 set: c.set 4317 } : 2 === a ? u = c.value : 3 === a ? u = c.get : 4 === a && (u = c.set), "function" == typeof h) void 0 !== (f = memberDec(h, n, c, o, a, i, s, u)) && (assertValidReturnValue(a, f), 0 === a ? l = f : 1 === a ? (l = f.init, p = f.get || u.get, d = f.set || u.set, u = { 4318 get: p, 4319 set: d 4320 }) : u = f);else for (var v = h.length - 1; v >= 0; v--) { 4321 var g; 4322 if (void 0 !== (f = memberDec(h[v], n, c, o, a, i, s, u))) assertValidReturnValue(a, f), 0 === a ? g = f : 1 === a ? (g = f.init, p = f.get || u.get, d = f.set || u.set, u = { 4323 get: p, 4324 set: d 4325 }) : u = f, void 0 !== g && (void 0 === l ? l = g : "function" == typeof l ? l = [l, g] : l.push(g)); 4326 } 4327 if (0 === a || 1 === a) { 4328 if (void 0 === l) l = function (e, t) { 4329 return t; 4330 };else if ("function" != typeof l) { 4331 var y = l; 4332 l = function (e, t) { 4333 for (var r = t, n = 0; n < y.length; n++) r = y[n].call(e, r); 4334 return r; 4335 }; 4336 } else { 4337 var m = l; 4338 l = function (e, t) { 4339 return m.call(e, t); 4340 }; 4341 } 4342 e.push(l); 4343 } 4344 0 !== a && (1 === a ? (c.get = u.get, c.set = u.set) : 2 === a ? c.value = u : 3 === a ? c.get = u : 4 === a && (c.set = u), s ? 1 === a ? (e.push(function (e, t) { 4345 return u.get.call(e, t); 4346 }), e.push(function (e, t) { 4347 return u.set.call(e, t); 4348 })) : 2 === a ? e.push(u) : e.push(function (e, t) { 4349 return u.call(e, t); 4350 }) : Object.defineProperty(t, n, c)); 4351 } 4352 function applyMemberDecs(e, t) { 4353 for (var r, n, a = [], i = new Map(), s = new Map(), o = 0; o < t.length; o++) { 4354 var c = t[o]; 4355 if (Array.isArray(c)) { 4356 var l, 4357 u, 4358 f = c[1], 4359 p = c[2], 4360 d = c.length > 3, 4361 h = f >= 5; 4362 if (h ? (l = e, 0 !== (f -= 5) && (u = n = n || [])) : (l = e.prototype, 0 !== f && (u = r = r || [])), 0 !== f && !d) { 4363 var v = h ? s : i, 4364 g = v.get(p) || 0; 4365 if (!0 === g || 3 === g && 4 !== f || 4 === g && 3 !== f) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + p); 4366 !g && f > 2 ? v.set(p, f) : v.set(p, !0); 4367 } 4368 applyMemberDec(a, l, c, p, f, h, d, u); 4369 } 4370 } 4371 return pushInitializers(a, r), pushInitializers(a, n), a; 4372 } 4373 function pushInitializers(e, t) { 4374 t && e.push(function (e) { 4375 for (var r = 0; r < t.length; r++) t[r].call(e); 4376 return e; 4377 }); 4378 } 4379 return function (e, t, r) { 4380 return { 4381 e: applyMemberDecs(e, t), 4382 get c() { 4383 return function (e, t) { 4384 if (t.length > 0) { 4385 for (var r = [], n = e, a = e.name, i = t.length - 1; i >= 0; i--) { 4386 var s = { 4387 v: !1 4388 }; 4389 try { 4390 var o = t[i](n, { 4391 kind: "class", 4392 name: a, 4393 addInitializer: createAddInitializerMethod(r, s) 4394 }); 4395 } finally { 4396 s.v = !0; 4397 } 4398 void 0 !== o && (assertValidReturnValue(10, o), n = o); 4399 } 4400 return [n, function () { 4401 for (var e = 0; e < r.length; e++) r[e].call(n); 4402 }]; 4403 } 4404 }(e, r); 4405 } 4406 }; 4407 }; 4408 } 4409 function _applyDecs2203R(e, t, r) { 4410 return (_applyDecs2203R = applyDecs2203RFactory())(e, t, r); 4411 } 4412 function applyDecs2301Factory() { 4413 function createAddInitializerMethod(e, t) { 4414 return function (r) { 4415 !function (e, t) { 4416 if (e.v) throw new Error("attempted to call " + t + " after decoration was finished"); 4417 }(t, "addInitializer"), assertCallable(r, "An initializer"), e.push(r); 4418 }; 4419 } 4420 function assertInstanceIfPrivate(e, t) { 4421 if (!e(t)) throw new TypeError("Attempted to access private element on non-instance"); 4422 } 4423 function memberDec(e, t, r, n, a, i, s, o, c) { 4424 var u; 4425 switch (a) { 4426 case 1: 4427 u = "accessor"; 4428 break; 4429 case 2: 4430 u = "method"; 4431 break; 4432 case 3: 4433 u = "getter"; 4434 break; 4435 case 4: 4436 u = "setter"; 4437 break; 4438 default: 4439 u = "field"; 4440 } 4441 var l, 4442 f, 4443 p = { 4444 kind: u, 4445 name: s ? "#" + t : t, 4446 static: i, 4447 private: s 4448 }, 4449 d = { 4450 v: !1 4451 }; 4452 if (0 !== a && (p.addInitializer = createAddInitializerMethod(n, d)), s || 0 !== a && 2 !== a) { 4453 if (2 === a) l = function (e) { 4454 return assertInstanceIfPrivate(c, e), r.value; 4455 };else { 4456 var h = 0 === a || 1 === a; 4457 (h || 3 === a) && (l = s ? function (e) { 4458 return assertInstanceIfPrivate(c, e), r.get.call(e); 4459 } : function (e) { 4460 return r.get.call(e); 4461 }), (h || 4 === a) && (f = s ? function (e, t) { 4462 assertInstanceIfPrivate(c, e), r.set.call(e, t); 4463 } : function (e, t) { 4464 r.set.call(e, t); 4465 }); 4466 } 4467 } else l = function (e) { 4468 return e[t]; 4469 }, 0 === a && (f = function (e, r) { 4470 e[t] = r; 4471 }); 4472 var v = s ? c.bind() : function (e) { 4473 return t in e; 4474 }; 4475 p.access = l && f ? { 4476 get: l, 4477 set: f, 4478 has: v 4479 } : l ? { 4480 get: l, 4481 has: v 4482 } : { 4483 set: f, 4484 has: v 4485 }; 4486 try { 4487 return e(o, p); 4488 } finally { 4489 d.v = !0; 4490 } 4491 } 4492 function assertCallable(e, t) { 4493 if ("function" != typeof e) throw new TypeError(t + " must be a function"); 4494 } 4495 function assertValidReturnValue(e, t) { 4496 var r = typeof t; 4497 if (1 === e) { 4498 if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); 4499 void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init"); 4500 } else if ("function" !== r) { 4501 var n; 4502 throw n = 0 === e ? "field" : 10 === e ? "class" : "method", new TypeError(n + " decorators must return a function or void 0"); 4503 } 4504 } 4505 function curryThis2(e) { 4506 return function (t) { 4507 e(this, t); 4508 }; 4509 } 4510 function applyMemberDec(e, t, r, n, a, i, s, o, c) { 4511 var u, 4512 l, 4513 f, 4514 p, 4515 d, 4516 h, 4517 v, 4518 g = r[0]; 4519 if (s ? u = 0 === a || 1 === a ? { 4520 get: (p = r[3], function () { 4521 return p(this); 4522 }), 4523 set: curryThis2(r[4]) 4524 } : 3 === a ? { 4525 get: r[3] 4526 } : 4 === a ? { 4527 set: r[3] 4528 } : { 4529 value: r[3] 4530 } : 0 !== a && (u = Object.getOwnPropertyDescriptor(t, n)), 1 === a ? f = { 4531 get: u.get, 4532 set: u.set 4533 } : 2 === a ? f = u.value : 3 === a ? f = u.get : 4 === a && (f = u.set), "function" == typeof g) void 0 !== (d = memberDec(g, n, u, o, a, i, s, f, c)) && (assertValidReturnValue(a, d), 0 === a ? l = d : 1 === a ? (l = d.init, h = d.get || f.get, v = d.set || f.set, f = { 4534 get: h, 4535 set: v 4536 }) : f = d);else for (var y = g.length - 1; y >= 0; y--) { 4537 var m; 4538 if (void 0 !== (d = memberDec(g[y], n, u, o, a, i, s, f, c))) assertValidReturnValue(a, d), 0 === a ? m = d : 1 === a ? (m = d.init, h = d.get || f.get, v = d.set || f.set, f = { 4539 get: h, 4540 set: v 4541 }) : f = d, void 0 !== m && (void 0 === l ? l = m : "function" == typeof l ? l = [l, m] : l.push(m)); 4542 } 4543 if (0 === a || 1 === a) { 4544 if (void 0 === l) l = function (e, t) { 4545 return t; 4546 };else if ("function" != typeof l) { 4547 var b = l; 4548 l = function (e, t) { 4549 for (var r = t, n = 0; n < b.length; n++) r = b[n].call(e, r); 4550 return r; 4551 }; 4552 } else { 4553 var I = l; 4554 l = function (e, t) { 4555 return I.call(e, t); 4556 }; 4557 } 4558 e.push(l); 4559 } 4560 0 !== a && (1 === a ? (u.get = f.get, u.set = f.set) : 2 === a ? u.value = f : 3 === a ? u.get = f : 4 === a && (u.set = f), s ? 1 === a ? (e.push(function (e, t) { 4561 return f.get.call(e, t); 4562 }), e.push(function (e, t) { 4563 return f.set.call(e, t); 4564 })) : 2 === a ? e.push(f) : e.push(function (e, t) { 4565 return f.call(e, t); 4566 }) : Object.defineProperty(t, n, u)); 4567 } 4568 function applyMemberDecs(e, t, r) { 4569 for (var n, a, i, s = [], o = new Map(), c = new Map(), u = 0; u < t.length; u++) { 4570 var l = t[u]; 4571 if (Array.isArray(l)) { 4572 var f, 4573 p, 4574 d = l[1], 4575 h = l[2], 4576 v = l.length > 3, 4577 g = d >= 5, 4578 y = r; 4579 if (g ? (f = e, 0 !== (d -= 5) && (p = a = a || []), v && !i && (i = function (t) { 4580 return _checkInRHS(t) === e; 4581 }), y = i) : (f = e.prototype, 0 !== d && (p = n = n || [])), 0 !== d && !v) { 4582 var m = g ? c : o, 4583 b = m.get(h) || 0; 4584 if (!0 === b || 3 === b && 4 !== d || 4 === b && 3 !== d) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + h); 4585 !b && d > 2 ? m.set(h, d) : m.set(h, !0); 4586 } 4587 applyMemberDec(s, f, l, h, d, g, v, p, y); 4588 } 4589 }
vendor: 6,955 bytes, lines 4590-4810
4590 return pushInitializers(s, n), pushInitializers(s, a), s; 4591 } 4592 function pushInitializers(e, t) { 4593 t && e.push(function (e) { 4594 for (var r = 0; r < t.length; r++) t[r].call(e); 4595 return e; 4596 }); 4597 } 4598 return function (e, t, r, n) { 4599 return { 4600 e: applyMemberDecs(e, t, n), 4601 get c() { 4602 return function (e, t) { 4603 if (t.length > 0) { 4604 for (var r = [], n = e, a = e.name, i = t.length - 1; i >= 0; i--) { 4605 var s = { 4606 v: !1 4607 }; 4608 try { 4609 var o = t[i](n, { 4610 kind: "class", 4611 name: a, 4612 addInitializer: createAddInitializerMethod(r, s) 4613 }); 4614 } finally { 4615 s.v = !0; 4616 } 4617 void 0 !== o && (assertValidReturnValue(10, o), n = o); 4618 } 4619 return [n, function () { 4620 for (var e = 0; e < r.length; e++) r[e].call(n); 4621 }]; 4622 } 4623 }(e, r); 4624 } 4625 }; 4626 }; 4627 } 4628 function _applyDecs2301(e, t, r, n) { 4629 return (_applyDecs2301 = applyDecs2301Factory())(e, t, r, n); 4630 } 4631 function createAddInitializerMethod(e, t) { 4632 return function (r) { 4633 assertNotFinished(t, "addInitializer"), assertCallable(r, "An initializer"), e.push(r); 4634 }; 4635 } 4636 function assertInstanceIfPrivate(e, t) { 4637 if (!e(t)) throw new TypeError("Attempted to access private element on non-instance"); 4638 } 4639 function memberDec(e, t, r, a, n, i, s, o, c, l, u) { 4640 var f; 4641 switch (i) { 4642 case 1: 4643 f = "accessor"; 4644 break; 4645 case 2: 4646 f = "method"; 4647 break; 4648 case 3: 4649 f = "getter"; 4650 break; 4651 case 4: 4652 f = "setter"; 4653 break; 4654 default: 4655 f = "field"; 4656 } 4657 var d, 4658 p, 4659 h = { 4660 kind: f, 4661 name: o ? "#" + r : r, 4662 static: s, 4663 private: o, 4664 metadata: u 4665 }, 4666 v = { 4667 v: !1 4668 }; 4669 if (0 !== i && (h.addInitializer = createAddInitializerMethod(n, v)), o || 0 !== i && 2 !== i) { 4670 if (2 === i) d = function (e) { 4671 return assertInstanceIfPrivate(l, e), a.value; 4672 };else { 4673 var y = 0 === i || 1 === i; 4674 (y || 3 === i) && (d = o ? function (e) { 4675 return assertInstanceIfPrivate(l, e), a.get.call(e); 4676 } : function (e) { 4677 return a.get.call(e); 4678 }), (y || 4 === i) && (p = o ? function (e, t) { 4679 assertInstanceIfPrivate(l, e), a.set.call(e, t); 4680 } : function (e, t) { 4681 a.set.call(e, t); 4682 }); 4683 } 4684 } else d = function (e) { 4685 return e[r]; 4686 }, 0 === i && (p = function (e, t) { 4687 e[r] = t; 4688 }); 4689 var m = o ? l.bind() : function (e) { 4690 return r in e; 4691 }; 4692 h.access = d && p ? { 4693 get: d, 4694 set: p, 4695 has: m 4696 } : d ? { 4697 get: d, 4698 has: m 4699 } : { 4700 set: p, 4701 has: m 4702 }; 4703 try { 4704 return e.call(t, c, h); 4705 } finally { 4706 v.v = !0; 4707 } 4708 } 4709 function assertNotFinished(e, t) { 4710 if (e.v) throw new Error("attempted to call " + t + " after decoration was finished"); 4711 } 4712 function assertCallable(e, t) { 4713 if ("function" != typeof e) throw new TypeError(t + " must be a function"); 4714 } 4715 function assertValidReturnValue(e, t) { 4716 var r = typeof t; 4717 if (1 === e) { 4718 if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); 4719 void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init"); 4720 } else if ("function" !== r) { 4721 var a; 4722 throw a = 0 === e ? "field" : 5 === e ? "class" : "method", new TypeError(a + " decorators must return a function or void 0"); 4723 } 4724 } 4725 function curryThis1(e) { 4726 return function () { 4727 return e(this); 4728 }; 4729 } 4730 function curryThis2(e) { 4731 return function (t) { 4732 e(this, t); 4733 }; 4734 } 4735 function applyMemberDec(e, t, r, a, n, i, s, o, c, l, u) { 4736 var f, 4737 d, 4738 p, 4739 h, 4740 v, 4741 y, 4742 m = r[0]; 4743 a || Array.isArray(m) || (m = [m]), o ? f = 0 === i || 1 === i ? { 4744 get: curryThis1(r[3]), 4745 set: curryThis2(r[4]) 4746 } : 3 === i ? { 4747 get: r[3] 4748 } : 4 === i ? { 4749 set: r[3] 4750 } : { 4751 value: r[3] 4752 } : 0 !== i && (f = Object.getOwnPropertyDescriptor(t, n)), 1 === i ? p = { 4753 get: f.get, 4754 set: f.set 4755 } : 2 === i ? p = f.value : 3 === i ? p = f.get : 4 === i && (p = f.set); 4756 for (var g = a ? 2 : 1, b = m.length - 1; b >= 0; b -= g) { 4757 var I; 4758 if (void 0 !== (h = memberDec(m[b], a ? m[b - 1] : void 0, n, f, c, i, s, o, p, l, u))) assertValidReturnValue(i, h), 0 === i ? I = h : 1 === i ? (I = h.init, v = h.get || p.get, y = h.set || p.set, p = { 4759 get: v, 4760 set: y 4761 }) : p = h, void 0 !== I && (void 0 === d ? d = I : "function" == typeof d ? d = [d, I] : d.push(I)); 4762 } 4763 if (0 === i || 1 === i) { 4764 if (void 0 === d) d = function (e, t) { 4765 return t; 4766 };else if ("function" != typeof d) { 4767 var w = d; 4768 d = function (e, t) { 4769 for (var r = t, a = w.length - 1; a >= 0; a--) r = w[a].call(e, r); 4770 return r; 4771 }; 4772 } else { 4773 var M = d; 4774 d = function (e, t) { 4775 return M.call(e, t); 4776 }; 4777 } 4778 e.push(d); 4779 } 4780 0 !== i && (1 === i ? (f.get = p.get, f.set = p.set) : 2 === i ? f.value = p : 3 === i ? f.get = p : 4 === i && (f.set = p), o ? 1 === i ? (e.push(function (e, t) { 4781 return p.get.call(e, t); 4782 }), e.push(function (e, t) { 4783 return p.set.call(e, t); 4784 })) : 2 === i ? e.push(p) : e.push(function (e, t) { 4785 return p.call(e, t); 4786 }) : Object.defineProperty(t, n, f)); 4787 } 4788 function applyMemberDecs(e, t, r, a) { 4789 for (var n, i, s, o = [], c = new Map(), l = new Map(), u = 0; u < t.length; u++) { 4790 var f = t[u]; 4791 if (Array.isArray(f)) { 4792 var d, 4793 p, 4794 h = f[1], 4795 v = f[2], 4796 y = f.length > 3, 4797 m = 16 & h, 4798 g = !!(8 & h), 4799 b = r; 4800 if (h &= 7, g ? (d = e, 0 !== h && (p = i = i || []), y && !s && (s = function (t) { 4801 return _checkInRHS(t) === e; 4802 }), b = s) : (d = e.prototype, 0 !== h && (p = n = n || [])), 0 !== h && !y) { 4803 var I = g ? l : c, 4804 w = I.get(v) || 0; 4805 if (!0 === w || 3 === w && 4 !== h || 4 === w && 3 !== h) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + v); 4806 I.set(v, !(!w && h > 2) || h); 4807 } 4808 applyMemberDec(o, d, f, m, v, h, g, y, p, b, a); 4809 } 4810 }
vendor: 23,828 bytes, lines 4811-5494
4811 return pushInitializers(o, n), pushInitializers(o, i), o; 4812 } 4813 function pushInitializers(e, t) { 4814 t && e.push(function (e) { 4815 for (var r = 0; r < t.length; r++) t[r].call(e); 4816 return e; 4817 }); 4818 } 4819 function applyClassDecs(e, t, r, a) { 4820 if (t.length) { 4821 for (var n = [], i = e, s = e.name, o = r ? 2 : 1, c = t.length - 1; c >= 0; c -= o) { 4822 var l = { 4823 v: !1 4824 }; 4825 try { 4826 var u = t[c].call(r ? t[c - 1] : void 0, i, { 4827 kind: "class", 4828 name: s, 4829 addInitializer: createAddInitializerMethod(n, l), 4830 metadata: a 4831 }); 4832 } finally { 4833 l.v = !0; 4834 } 4835 void 0 !== u && (assertValidReturnValue(5, u), i = u); 4836 } 4837 return [defineMetadata(i, a), function () { 4838 for (var e = 0; e < n.length; e++) n[e].call(i); 4839 }]; 4840 } 4841 } 4842 function defineMetadata(e, t) { 4843 return Object.defineProperty(e, Symbol.metadata || Symbol.for("Symbol.metadata"), { 4844 configurable: !0, 4845 enumerable: !0, 4846 value: t 4847 }); 4848 } 4849 function _applyDecs2305(e, t, r, a, n, i) { 4850 if (arguments.length >= 6) var s = i[Symbol.metadata || Symbol.for("Symbol.metadata")]; 4851 var o = Object.create(void 0 === s ? null : s), 4852 c = applyMemberDecs(e, t, n, o); 4853 return r.length || defineMetadata(e, o), { 4854 e: c, 4855 get c() { 4856 return applyClassDecs(e, r, a, o); 4857 } 4858 }; 4859 } 4860 function _asyncGeneratorDelegate(t) { 4861 var e = {}, 4862 n = !1; 4863 function pump(e, r) { 4864 return n = !0, r = new Promise(function (n) { 4865 n(t[e](r)); 4866 }), { 4867 done: !1, 4868 value: new _OverloadYield(r, 1) 4869 }; 4870 } 4871 return e["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function () { 4872 return this; 4873 }, e.next = function (t) { 4874 return n ? (n = !1, t) : pump("next", t); 4875 }, "function" == typeof t.throw && (e.throw = function (t) { 4876 if (n) throw n = !1, t; 4877 return pump("throw", t); 4878 }), "function" == typeof t.return && (e.return = function (t) { 4879 return n ? (n = !1, t) : pump("return", t); 4880 }), e; 4881 } 4882 function _asyncIterator(r) { 4883 var n, 4884 t, 4885 o, 4886 e = 2; 4887 for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) { 4888 if (t && null != (n = r[t])) return n.call(r); 4889 if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r)); 4890 t = "@@asyncIterator", o = "@@iterator"; 4891 } 4892 throw new TypeError("Object is not async iterable"); 4893 } 4894 function AsyncFromSyncIterator(r) { 4895 function AsyncFromSyncIteratorContinuation(r) { 4896 if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); 4897 var n = r.done; 4898 return Promise.resolve(r.value).then(function (r) { 4899 return { 4900 value: r, 4901 done: n 4902 }; 4903 }); 4904 } 4905 return AsyncFromSyncIterator = function (r) { 4906 this.s = r, this.n = r.next; 4907 }, AsyncFromSyncIterator.prototype = { 4908 s: null, 4909 n: null, 4910 next: function () { 4911 return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); 4912 }, 4913 return: function (r) { 4914 var n = this.s.return; 4915 return void 0 === n ? Promise.resolve({ 4916 value: r, 4917 done: !0 4918 }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); 4919 }, 4920 throw: function (r) { 4921 var n = this.s.return; 4922 return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); 4923 } 4924 }, new AsyncFromSyncIterator(r); 4925 } 4926 function _awaitAsyncGenerator(e) { 4927 return new _OverloadYield(e, 0); 4928 } 4929 function _checkInRHS(e) { 4930 if (Object(e) !== e) throw TypeError("right-hand side of 'in' should be an object, got " + (null !== e ? typeof e : "null")); 4931 return e; 4932 } 4933 function _defineAccessor(e, r, n, t) { 4934 var c = { 4935 configurable: !0, 4936 enumerable: !0 4937 }; 4938 return c[e] = t, Object.defineProperty(r, n, c); 4939 } 4940 function dispose_SuppressedError(r, e) { 4941 return "undefined" != typeof SuppressedError ? dispose_SuppressedError = SuppressedError : (dispose_SuppressedError = function (r, e) { 4942 this.suppressed = r, this.error = e, this.stack = new Error().stack; 4943 }, dispose_SuppressedError.prototype = Object.create(Error.prototype, { 4944 constructor: { 4945 value: dispose_SuppressedError, 4946 writable: !0, 4947 configurable: !0 4948 } 4949 })), new dispose_SuppressedError(r, e); 4950 } 4951 function _dispose(r, e, s) { 4952 function next() { 4953 for (; r.length > 0;) try { 4954 var o = r.pop(), 4955 p = o.d.call(o.v); 4956 if (o.a) return Promise.resolve(p).then(next, err); 4957 } catch (r) { 4958 return err(r); 4959 } 4960 if (s) throw e; 4961 } 4962 function err(r) { 4963 return e = s ? new dispose_SuppressedError(r, e) : r, s = !0, next(); 4964 } 4965 return next(); 4966 } 4967 function _importDeferProxy(e) { 4968 var t = null, 4969 constValue = function (e) { 4970 return function () { 4971 return e; 4972 }; 4973 }, 4974 proxy = function (r) { 4975 return function (n, o, f) { 4976 return null === t && (t = e()), r(t, o, f); 4977 }; 4978 }; 4979 return new Proxy({}, { 4980 defineProperty: constValue(!1), 4981 deleteProperty: constValue(!1), 4982 get: proxy(Reflect.get), 4983 getOwnPropertyDescriptor: proxy(Reflect.getOwnPropertyDescriptor), 4984 getPrototypeOf: constValue(null), 4985 isExtensible: constValue(!1), 4986 has: proxy(Reflect.has), 4987 ownKeys: proxy(Reflect.ownKeys), 4988 preventExtensions: constValue(!0), 4989 set: constValue(!1), 4990 setPrototypeOf: constValue(!1) 4991 }); 4992 } 4993 function _iterableToArrayLimit(r, l) { 4994 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; 4995 if (null != t) { 4996 var e, 4997 n, 4998 i, 4999 u, 5000 a = [], 5001 f = !0, 5002 o = !1; 5003 try { 5004 if (i = (t = t.call(r)).next, 0 === l) { 5005 if (Object(t) !== t) return; 5006 f = !1; 5007 } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); 5008 } catch (r) { 5009 o = !0, n = r; 5010 } finally { 5011 try { 5012 if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; 5013 } finally { 5014 if (o) throw n; 5015 } 5016 } 5017 return a; 5018 } 5019 } 5020 function _iterableToArrayLimitLoose(e, r) { 5021 var t = e && ("undefined" != typeof Symbol && e[Symbol.iterator] || e["@@iterator"]); 5022 if (null != t) { 5023 var o, 5024 l = []; 5025 for (t = t.call(e); e.length < r && !(o = t.next()).done;) l.push(o.value); 5026 return l; 5027 } 5028 } 5029 var REACT_ELEMENT_TYPE; 5030 function _jsx(e, r, E, l) { 5031 REACT_ELEMENT_TYPE || (REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103); 5032 var o = e && e.defaultProps, 5033 n = arguments.length - 3; 5034 if (r || 0 === n || (r = { 5035 children: void 0 5036 }), 1 === n) r.children = l;else if (n > 1) { 5037 for (var t = new Array(n), f = 0; f < n; f++) t[f] = arguments[f + 3]; 5038 r.children = t; 5039 } 5040 if (r && o) for (var i in o) void 0 === r[i] && (r[i] = o[i]);else r || (r = o || {}); 5041 return { 5042 $$typeof: REACT_ELEMENT_TYPE, 5043 type: e, 5044 key: void 0 === E ? null : "" + E, 5045 ref: null, 5046 props: r, 5047 _owner: null 5048 }; 5049 } 5050 function ownKeys(e, r) { 5051 var t = Object.keys(e); 5052 if (Object.getOwnPropertySymbols) { 5053 var o = Object.getOwnPropertySymbols(e); 5054 r && (o = o.filter(function (r) { 5055 return Object.getOwnPropertyDescriptor(e, r).enumerable; 5056 })), t.push.apply(t, o); 5057 } 5058 return t; 5059 } 5060 function _objectSpread2(e) { 5061 for (var r = 1; r < arguments.length; r++) { 5062 var t = null != arguments[r] ? arguments[r] : {}; 5063 r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { 5064 _defineProperty(e, r, t[r]); 5065 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { 5066 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); 5067 }); 5068 } 5069 return e; 5070 } 5071 function _regeneratorRuntime() { 5072 "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ 5073 _regeneratorRuntime = function () { 5074 return e; 5075 }; 5076 var t, 5077 e = {}, 5078 r = Object.prototype, 5079 n = r.hasOwnProperty, 5080 o = Object.defineProperty || function (t, e, r) { 5081 t[e] = r.value; 5082 }, 5083 i = "function" == typeof Symbol ? Symbol : {}, 5084 a = i.iterator || "@@iterator", 5085 c = i.asyncIterator || "@@asyncIterator", 5086 u = i.toStringTag || "@@toStringTag"; 5087 function define(t, e, r) { 5088 return Object.defineProperty(t, e, { 5089 value: r, 5090 enumerable: !0, 5091 configurable: !0, 5092 writable: !0 5093 }), t[e]; 5094 } 5095 try { 5096 define({}, ""); 5097 } catch (t) { 5098 define = function (t, e, r) { 5099 return t[e] = r; 5100 }; 5101 } 5102 function wrap(t, e, r, n) { 5103 var i = e && e.prototype instanceof Generator ? e : Generator, 5104 a = Object.create(i.prototype), 5105 c = new Context(n || []); 5106 return o(a, "_invoke", { 5107 value: makeInvokeMethod(t, r, c) 5108 }), a; 5109 } 5110 function tryCatch(t, e, r) { 5111 try { 5112 return { 5113 type: "normal", 5114 arg: t.call(e, r) 5115 }; 5116 } catch (t) { 5117 return { 5118 type: "throw", 5119 arg: t 5120 }; 5121 } 5122 } 5123 e.wrap = wrap; 5124 var h = "suspendedStart", 5125 l = "suspendedYield", 5126 f = "executing", 5127 s = "completed", 5128 y = {}; 5129 function Generator() {} 5130 function GeneratorFunction() {} 5131 function GeneratorFunctionPrototype() {} 5132 var p = {}; 5133 define(p, a, function () { 5134 return this; 5135 }); 5136 var d = Object.getPrototypeOf, 5137 v = d && d(d(values([]))); 5138 v && v !== r && n.call(v, a) && (p = v); 5139 var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); 5140 function defineIteratorMethods(t) { 5141 ["next", "throw", "return"].forEach(function (e) { 5142 define(t, e, function (t) { 5143 return this._invoke(e, t); 5144 }); 5145 }); 5146 } 5147 function AsyncIterator(t, e) { 5148 function invoke(r, o, i, a) { 5149 var c = tryCatch(t[r], t, o); 5150 if ("throw" !== c.type) { 5151 var u = c.arg, 5152 h = u.value; 5153 return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { 5154 invoke("next", t, i, a); 5155 }, function (t) { 5156 invoke("throw", t, i, a); 5157 }) : e.resolve(h).then(function (t) { 5158 u.value = t, i(u); 5159 }, function (t) { 5160 return invoke("throw", t, i, a); 5161 }); 5162 } 5163 a(c.arg); 5164 } 5165 var r; 5166 o(this, "_invoke", { 5167 value: function (t, n) { 5168 function callInvokeWithMethodAndArg() { 5169 return new e(function (e, r) { 5170 invoke(t, n, e, r); 5171 }); 5172 } 5173 return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); 5174 } 5175 }); 5176 } 5177 function makeInvokeMethod(e, r, n) { 5178 var o = h; 5179 return function (i, a) { 5180 if (o === f) throw new Error("Generator is already running"); 5181 if (o === s) { 5182 if ("throw" === i) throw a; 5183 return { 5184 value: t, 5185 done: !0 5186 }; 5187 } 5188 for (n.method = i, n.arg = a;;) { 5189 var c = n.delegate; 5190 if (c) { 5191 var u = maybeInvokeDelegate(c, n); 5192 if (u) { 5193 if (u === y) continue; 5194 return u; 5195 } 5196 } 5197 if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { 5198 if (o === h) throw o = s, n.arg; 5199 n.dispatchException(n.arg); 5200 } else "return" === n.method && n.abrupt("return", n.arg); 5201 o = f; 5202 var p = tryCatch(e, r, n); 5203 if ("normal" === p.type) { 5204 if (o = n.done ? s : l, p.arg === y) continue; 5205 return { 5206 value: p.arg, 5207 done: n.done 5208 }; 5209 } 5210 "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); 5211 } 5212 }; 5213 } 5214 function maybeInvokeDelegate(e, r) { 5215 var n = r.method, 5216 o = e.iterator[n]; 5217 if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; 5218 var i = tryCatch(o, e.iterator, r.arg); 5219 if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; 5220 var a = i.arg; 5221 return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); 5222 } 5223 function pushTryEntry(t) { 5224 var e = { 5225 tryLoc: t[0] 5226 }; 5227 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); 5228 } 5229 function resetTryEntry(t) { 5230 var e = t.completion || {}; 5231 e.type = "normal", delete e.arg, t.completion = e; 5232 } 5233 function Context(t) { 5234 this.tryEntries = [{ 5235 tryLoc: "root" 5236 }], t.forEach(pushTryEntry, this), this.reset(!0); 5237 } 5238 function values(e) { 5239 if (e || "" === e) { 5240 var r = e[a]; 5241 if (r) return r.call(e); 5242 if ("function" == typeof e.next) return e; 5243 if (!isNaN(e.length)) { 5244 var o = -1, 5245 i = function next() { 5246 for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; 5247 return next.value = t, next.done = !0, next; 5248 }; 5249 return i.next = i; 5250 } 5251 } 5252 throw new TypeError(typeof e + " is not iterable"); 5253 } 5254 return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { 5255 value: GeneratorFunctionPrototype, 5256 configurable: !0 5257 }), o(GeneratorFunctionPrototype, "constructor", { 5258 value: GeneratorFunction, 5259 configurable: !0 5260 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { 5261 var e = "function" == typeof t && t.constructor; 5262 return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); 5263 }, e.mark = function (t) { 5264 return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; 5265 }, e.awrap = function (t) { 5266 return { 5267 __await: t 5268 }; 5269 }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { 5270 return this; 5271 }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { 5272 void 0 === i && (i = Promise); 5273 var a = new AsyncIterator(wrap(t, r, n, o), i); 5274 return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { 5275 return t.done ? t.value : a.next(); 5276 }); 5277 }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { 5278 return this; 5279 }), define(g, "toString", function () { 5280 return "[object Generator]"; 5281 }), e.keys = function (t) { 5282 var e = Object(t), 5283 r = []; 5284 for (var n in e) r.push(n); 5285 return r.reverse(), function next() { 5286 for (; r.length;) { 5287 var t = r.pop(); 5288 if (t in e) return next.value = t, next.done = !1, next; 5289 } 5290 return next.done = !0, next; 5291 }; 5292 }, e.values = values, Context.prototype = { 5293 constructor: Context, 5294 reset: function (e) { 5295 if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); 5296 }, 5297 stop: function () { 5298 this.done = !0; 5299 var t = this.tryEntries[0].completion; 5300 if ("throw" === t.type) throw t.arg; 5301 return this.rval; 5302 }, 5303 dispatchException: function (e) { 5304 if (this.done) throw e; 5305 var r = this; 5306 function handle(n, o) { 5307 return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; 5308 } 5309 for (var o = this.tryEntries.length - 1; o >= 0; --o) { 5310 var i = this.tryEntries[o], 5311 a = i.completion; 5312 if ("root" === i.tryLoc) return handle("end"); 5313 if (i.tryLoc <= this.prev) { 5314 var c = n.call(i, "catchLoc"), 5315 u = n.call(i, "finallyLoc"); 5316 if (c && u) { 5317 if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); 5318 if (this.prev < i.finallyLoc) return handle(i.finallyLoc); 5319 } else if (c) { 5320 if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); 5321 } else { 5322 if (!u) throw new Error("try statement without catch or finally"); 5323 if (this.prev < i.finallyLoc) return handle(i.finallyLoc); 5324 } 5325 } 5326 } 5327 }, 5328 abrupt: function (t, e) { 5329 for (var r = this.tryEntries.length - 1; r >= 0; --r) { 5330 var o = this.tryEntries[r]; 5331 if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { 5332 var i = o; 5333 break; 5334 } 5335 } 5336 i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); 5337 var a = i ? i.completion : {}; 5338 return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); 5339 }, 5340 complete: function (t, e) { 5341 if ("throw" === t.type) throw t.arg; 5342 return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; 5343 }, 5344 finish: function (t) { 5345 for (var e = this.tryEntries.length - 1; e >= 0; --e) { 5346 var r = this.tryEntries[e]; 5347 if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; 5348 } 5349 }, 5350 catch: function (t) { 5351 for (var e = this.tryEntries.length - 1; e >= 0; --e) { 5352 var r = this.tryEntries[e]; 5353 if (r.tryLoc === t) { 5354 var n = r.completion; 5355 if ("throw" === n.type) { 5356 var o = n.arg; 5357 resetTryEntry(r); 5358 } 5359 return o; 5360 } 5361 } 5362 throw new Error("illegal catch attempt"); 5363 }, 5364 delegateYield: function (e, r, n) { 5365 return this.delegate = { 5366 iterator: values(e), 5367 resultName: r, 5368 nextLoc: n 5369 }, "next" === this.method && (this.arg = t), y; 5370 } 5371 }, e; 5372 } 5373 function _typeof(o) { 5374 "@babel/helpers - typeof"; 5375 5376 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { 5377 return typeof o; 5378 } : function (o) { 5379 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; 5380 }, _typeof(o); 5381 } 5382 function _using(o, e, n) { 5383 if (null == e) return e; 5384 if ("object" != typeof e) throw new TypeError("using declarations can only be used with objects, null, or undefined."); 5385 if (n) var r = e[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")]; 5386 if (null == r && (r = e[Symbol.dispose || Symbol.for("Symbol.dispose")]), "function" != typeof r) throw new TypeError("Property [Symbol.dispose] is not a function."); 5387 return o.push({ 5388 v: e, 5389 d: r, 5390 a: n 5391 }), e; 5392 } 5393 function _wrapRegExp() { 5394 _wrapRegExp = function (e, r) { 5395 return new BabelRegExp(e, void 0, r); 5396 }; 5397 var e = RegExp.prototype, 5398 r = new WeakMap(); 5399 function BabelRegExp(e, t, p) { 5400 var o = new RegExp(e, t); 5401 return r.set(o, p || r.get(e)), _setPrototypeOf(o, BabelRegExp.prototype); 5402 } 5403 function buildGroups(e, t) { 5404 var p = r.get(t); 5405 return Object.keys(p).reduce(function (r, t) { 5406 var o = p[t]; 5407 if ("number" == typeof o) r[t] = e[o];else { 5408 for (var i = 0; void 0 === e[o[i]] && i + 1 < o.length;) i++; 5409 r[t] = e[o[i]]; 5410 } 5411 return r; 5412 }, Object.create(null)); 5413 } 5414 return _inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (r) { 5415 var t = e.exec.call(this, r); 5416 if (t) { 5417 t.groups = buildGroups(t, this); 5418 var p = t.indices; 5419 p && (p.groups = buildGroups(p, this)); 5420 } 5421 return t; 5422 }, BabelRegExp.prototype[Symbol.replace] = function (t, p) { 5423 if ("string" == typeof p) { 5424 var o = r.get(this); 5425 return e[Symbol.replace].call(this, t, p.replace(/\$<([^>]+)>/g, function (e, r) { 5426 var t = o[r]; 5427 return "$" + (Array.isArray(t) ? t.join("$") : t); 5428 })); 5429 } 5430 if ("function" == typeof p) { 5431 var i = this; 5432 return e[Symbol.replace].call(this, t, function () { 5433 var e = arguments; 5434 return "object" != typeof e[e.length - 1] && (e = [].slice.call(e)).push(buildGroups(e, i)), p.apply(this, e); 5435 }); 5436 } 5437 return e[Symbol.replace].call(this, t, p); 5438 }, _wrapRegExp.apply(this, arguments); 5439 } 5440 function _AwaitValue(value) { 5441 this.wrapped = value; 5442 } 5443 function _wrapAsyncGenerator(fn) { 5444 return function () { 5445 return new _AsyncGenerator(fn.apply(this, arguments)); 5446 }; 5447 } 5448 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { 5449 try { 5450 var info = gen[key](arg); 5451 var value = info.value; 5452 } catch (error) { 5453 reject(error); 5454 return; 5455 } 5456 if (info.done) { 5457 resolve(value); 5458 } else { 5459 Promise.resolve(value).then(_next, _throw); 5460 } 5461 } 5462 function _asyncToGenerator(fn) { 5463 return function () { 5464 var self = this, 5465 args = arguments; 5466 return new Promise(function (resolve, reject) { 5467 var gen = fn.apply(self, args); 5468 function _next(value) { 5469 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); 5470 } 5471 function _throw(err) { 5472 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); 5473 } 5474 _next(undefined); 5475 }); 5476 }; 5477 } 5478 function _classCallCheck(instance, Constructor) { 5479 if (!(instance instanceof Constructor)) { 5480 throw new TypeError("Cannot call a class as a function"); 5481 } 5482 } 5483 function _defineProperties(target, props) { 5484 for (var i = 0; i < props.length; i++) { 5485 var descriptor = props[i]; 5486 descriptor.enumerable = descriptor.enumerable || false; 5487 descriptor.configurable = true; 5488 if ("value" in descriptor) descriptor.writable = true; 5489 Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); 5490 } 5491 } 5492 function _createClass(Constructor, protoProps, staticProps) { 5493 if (protoProps) _defineProperties(Constructor.prototype, protoProps); 5494 if (staticProps) _defineProperties(Constructor, staticProps);
5495 Object.defineProperty(Constructor, "prototype", { 5496 writable: false 5497 }); 5498 return Constructor; 5499 } 5500 function _defineEnumerableProperties(obj, descs) { 5501 for (var key in descs) { 5502 var desc = descs[key]; 5503 desc.configurable = desc.enumerable = true; 5504 if ("value" in desc) desc.writable = true; 5505 Object.defineProperty(obj, key, desc); 5506 } 5507 if (Object.getOwnPropertySymbols) { 5508 var objectSymbols = Object.getOwnPropertySymbols(descs); 5509 for (var i = 0; i < objectSymbols.length; i++) { 5510 var sym = objectSymbols[i]; 5511 var desc = descs[sym]; 5512 desc.configurable = desc.enumerable = true; 5513 if ("value" in desc) desc.writable = true; 5514 Object.defineProperty(obj, sym, desc); 5515 } 5516 } 5517 return obj; 5518 } 5519 function _defaults(obj, defaults) { 5520 var keys = Object.getOwnPropertyNames(defaults); 5521 for (var i = 0; i < keys.length; i++) { 5522 var key = keys[i]; 5523 var value = Object.getOwnPropertyDescriptor(defaults, key); 5524 if (value && value.configurable && obj[key] === undefined) { 5525 Object.defineProperty(obj, key, value); 5526 } 5527 } 5528 return obj; 5529 } 5530 function _defineProperty(obj, key, value) { 5531 key = _toPropertyKey(key); 5532 if (key in obj) { 5533 Object.defineProperty(obj, key, { 5534 value: value, 5535 enumerable: true, 5536 configurable: true, 5537 writable: true 5538 }); 5539 } else { 5540 obj[key] = value; 5541 } 5542 return obj; 5543 } 5544 function _extends() { 5545 _extends = Object.assign ? Object.assign.bind() : function (target) { 5546 for (var i = 1; i < arguments.length; i++) { 5547 var source = arguments[i]; 5548 for (var key in source) { 5549 if (Object.prototype.hasOwnProperty.call(source, key)) { 5550 target[key] = source[key]; 5551 } 5552 } 5553 } 5554 return target; 5555 }; 5556 return _extends.apply(this, arguments); 5557 } 5558 function _objectSpread(target) { 5559 for (var i = 1; i < arguments.length; i++) { 5560 var source = arguments[i] != null ? Object(arguments[i]) : {}; 5561 var ownKeys = Object.keys(source); 5562 if (typeof Object.getOwnPropertySymbols === 'function') { 5563 ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function (sym) { 5564 return Object.getOwnPropertyDescriptor(source, sym).enumerable; 5565 })); 5566 } 5567 ownKeys.forEach(function (key) { 5568 _defineProperty(target, key, source[key]); 5569 }); 5570 } 5571 return target; 5572 } 5573 function _inherits(subClass, superClass) { 5574 if (typeof superClass !== "function" && superClass !== null) { 5575 throw new TypeError("Super expression must either be null or a function"); 5576 } 5577 subClass.prototype = Object.create(superClass && superClass.prototype, { 5578 constructor: { 5579 value: subClass, 5580 writable: true, 5581 configurable: true 5582 } 5583 }); 5584 Object.defineProperty(subClass, "prototype", { 5585 writable: false 5586 }); 5587 if (superClass) _setPrototypeOf(subClass, superClass); 5588 } 5589 function _inheritsLoose(subClass, superClass) { 5590 subClass.prototype = Object.create(superClass.prototype); 5591 subClass.prototype.constructor = subClass; 5592 _setPrototypeOf(subClass, superClass); 5593 } 5594 function _getPrototypeOf(o) { 5595 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { 5596 return o.__proto__ || Object.getPrototypeOf(o); 5597 }; 5598 return _getPrototypeOf(o); 5599 } 5600 function _setPrototypeOf(o, p) { 5601 _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { 5602 o.__proto__ = p; 5603 return o; 5604 }; 5605 return _setPrototypeOf(o, p); 5606 } 5607 function _isNativeReflectConstruct() { 5608 if (typeof Reflect === "undefined" || !Reflect.construct) return false; 5609 if (Reflect.construct.sham) return false; 5610 if (typeof Proxy === "function") return true; 5611 try { 5612 Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); 5613 return true; 5614 } catch (e) { 5615 return false; 5616 } 5617 } 5618 function _construct(Parent, args, Class) { 5619 if (_isNativeReflectConstruct()) { 5620 _construct = Reflect.construct.bind(); 5621 } else { 5622 _construct = function _construct(Parent, args, Class) { 5623 var a = [null]; 5624 a.push.apply(a, args); 5625 var Constructor = Function.bind.apply(Parent, a); 5626 var instance = new Constructor(); 5627 if (Class) _setPrototypeOf(instance, Class.prototype); 5628 return instance; 5629 }; 5630 } 5631 return _construct.apply(null, arguments); 5632 } 5633 function _isNativeFunction(fn) { 5634 return Function.toString.call(fn).indexOf("[native code]") !== -1; 5635 } 5636 function _wrapNativeSuper(Class) { 5637 var _cache = typeof Map === "function" ? new Map() : undefined; 5638 _wrapNativeSuper = function _wrapNativeSuper(Class) { 5639 if (Class === null || !_isNativeFunction(Class)) return Class; 5640 if (typeof Class !== "function") { 5641 throw new TypeError("Super expression must either be null or a function"); 5642 }
5643 if (typeof _cache !== "undefined") { 5644 if (_cache.has(Class)) return _cache.get(Class); 5645 _cache.set(Class, Wrapper); 5646 } 5647 function Wrapper() { 5648 return _construct(Class, arguments, _getPrototypeOf(this).constructor); 5649 } 5650 Wrapper.prototype = Object.create(Class.prototype, { 5651 constructor: { 5652 value: Wrapper, 5653 enumerable: false, 5654 writable: true, 5655 configurable: true 5656 } 5657 }); 5658 return _setPrototypeOf(Wrapper, Class); 5659 }; 5660 return _wrapNativeSuper(Class); 5661 } 5662 function _instanceof(left, right) { 5663 if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { 5664 return !!right[Symbol.hasInstance](left); 5665 } else { 5666 return left instanceof right; 5667 } 5668 } 5669 function _interopRequireDefault(obj) { 5670 return obj && obj.__esModule ? obj : { 5671 default: obj 5672 }; 5673 } 5674 function _getRequireWildcardCache(nodeInterop) { 5675 if (typeof WeakMap !== "function") return null; 5676 var cacheBabelInterop = new WeakMap(); 5677 var cacheNodeInterop = new WeakMap(); 5678 return (_getRequireWildcardCache = function (nodeInterop) { 5679 return nodeInterop ? cacheNodeInterop : cacheBabelInterop; 5680 })(nodeInterop); 5681 } 5682 function _interopRequireWildcard(obj, nodeInterop) { 5683 if (!nodeInterop && obj && obj.__esModule) { 5684 return obj; 5685 } 5686 if (obj === null || typeof obj !== "object" && typeof obj !== "function") { 5687 return { 5688 default: obj 5689 }; 5690 } 5691 var cache = _getRequireWildcardCache(nodeInterop); 5692 if (cache && cache.has(obj)) { 5693 return cache.get(obj); 5694 } 5695 var newObj = {}; 5696 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; 5697 for (var key in obj) { 5698 if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { 5699 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; 5700 if (desc && (desc.get || desc.set)) { 5701 Object.defineProperty(newObj, key, desc); 5702 } else { 5703 newObj[key] = obj[key]; 5704 } 5705 } 5706 } 5707 newObj.default = obj; 5708 if (cache) { 5709 cache.set(obj, newObj); 5710 } 5711 return newObj; 5712 } 5713 function _newArrowCheck(innerThis, boundThis) { 5714 if (innerThis !== boundThis) { 5715 throw new TypeError("Cannot instantiate an arrow function"); 5716 } 5717 } 5718 function _objectDestructuringEmpty(obj) { 5719 if (obj == null) throw new TypeError("Cannot destructure " + obj); 5720 } 5721 function _objectWithoutPropertiesLoose(source, excluded) { 5722 if (source == null) return {}; 5723 var target = {}; 5724 var sourceKeys = Object.keys(source); 5725 var key, i; 5726 for (i = 0; i < sourceKeys.length; i++) { 5727 key = sourceKeys[i]; 5728 if (excluded.indexOf(key) >= 0) continue; 5729 target[key] = source[key]; 5730 } 5731 return target; 5732 } 5733 function _objectWithoutProperties(source, excluded) { 5734 if (source == null) return {}; 5735 var target = _objectWithoutPropertiesLoose(source, excluded); 5736 var key, i; 5737 if (Object.getOwnPropertySymbols) { 5738 var sourceSymbolKeys = Object.getOwnPropertySymbols(source); 5739 for (i = 0; i < sourceSymbolKeys.length; i++) { 5740 key = sourceSymbolKeys[i]; 5741 if (excluded.indexOf(key) >= 0) continue; 5742 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; 5743 target[key] = source[key]; 5744 } 5745 } 5746 return target; 5747 } 5748 function _assertThisInitialized(self) { 5749 if (self === void 0) { 5750 throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); 5751 } 5752 return self; 5753 } 5754 function _possibleConstructorReturn(self, call) { 5755 if (call && (typeof call === "object" || typeof call === "function")) { 5756 return call; 5757 } else if (call !== void 0) { 5758 throw new TypeError("Derived constructors may only return object or undefined"); 5759 } 5760 return _assertThisInitialized(self); 5761 } 5762 function _createSuper(Derived) { 5763 var hasNativeReflectConstruct = _isNativeReflectConstruct(); 5764 return function _createSuperInternal() { 5765 var Super = _getPrototypeOf(Derived), 5766 result; 5767 if (hasNativeReflectConstruct) { 5768 var NewTarget = _getPrototypeOf(this).constructor; 5769 result = Reflect.construct(Super, arguments, NewTarget); 5770 } else { 5771 result = Super.apply(this, arguments); 5772 } 5773 return _possibleConstructorReturn(this, result); 5774 }; 5775 } 5776 function _superPropBase(object, property) { 5777 while (!Object.prototype.hasOwnProperty.call(object, property)) { 5778 object = _getPrototypeOf(object); 5779 if (object === null) break; 5780 } 5781 return object; 5782 } 5783 function _get() { 5784 if (typeof Reflect !== "undefined" && Reflect.get) { 5785 _get = Reflect.get.bind(); 5786 } else { 5787 _get = function _get(target, property, receiver) { 5788 var base = _superPropBase(target, property); 5789 if (!base) return; 5790 var desc = Object.getOwnPropertyDescriptor(base, property); 5791 if (desc.get) { 5792 return desc.get.call(arguments.length < 3 ? target : receiver); 5793 } 5794 return desc.value; 5795 }; 5796 } 5797 return _get.apply(this, arguments); 5798 } 5799 function set(target, property, value, receiver) { 5800 if (typeof Reflect !== "undefined" && Reflect.set) { 5801 set = Reflect.set; 5802 } else { 5803 set = function set(target, property, value, receiver) { 5804 var base = _superPropBase(target, property); 5805 var desc; 5806 if (base) { 5807 desc = Object.getOwnPropertyDescriptor(base, property); 5808 if (desc.set) { 5809 desc.set.call(receiver, value); 5810 return true; 5811 } else if (!desc.writable) { 5812 return false;
vendor: 6,730 bytes, lines 5813-6005
5813 } 5814 } 5815 desc = Object.getOwnPropertyDescriptor(receiver, property); 5816 if (desc) { 5817 if (!desc.writable) { 5818 return false; 5819 } 5820 desc.value = value; 5821 Object.defineProperty(receiver, property, desc); 5822 } else { 5823 _defineProperty(receiver, property, value); 5824 } 5825 return true; 5826 }; 5827 } 5828 return set(target, property, value, receiver); 5829 } 5830 function _set(target, property, value, receiver, isStrict) { 5831 var s = set(target, property, value, receiver || target); 5832 if (!s && isStrict) { 5833 throw new TypeError('failed to set property'); 5834 } 5835 return value; 5836 } 5837 function _taggedTemplateLiteral(strings, raw) { 5838 if (!raw) { 5839 raw = strings.slice(0); 5840 } 5841 return Object.freeze(Object.defineProperties(strings, { 5842 raw: { 5843 value: Object.freeze(raw) 5844 } 5845 })); 5846 } 5847 function _taggedTemplateLiteralLoose(strings, raw) { 5848 if (!raw) { 5849 raw = strings.slice(0); 5850 } 5851 strings.raw = raw; 5852 return strings; 5853 } 5854 function _readOnlyError(name) { 5855 throw new TypeError("\"" + name + "\" is read-only"); 5856 } 5857 function _writeOnlyError(name) { 5858 throw new TypeError("\"" + name + "\" is write-only"); 5859 } 5860 function _classNameTDZError(name) { 5861 throw new ReferenceError("Class \"" + name + "\" cannot be referenced in computed property keys."); 5862 } 5863 function _temporalUndefined() {} 5864 function _tdz(name) { 5865 throw new ReferenceError(name + " is not defined - temporal dead zone"); 5866 } 5867 function _temporalRef(val, name) { 5868 return val === _temporalUndefined ? _tdz(name) : val; 5869 } 5870 function _slicedToArray(arr, i) { 5871 return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); 5872 } 5873 function _slicedToArrayLoose(arr, i) { 5874 return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); 5875 } 5876 function _toArray(arr) { 5877 return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); 5878 } 5879 function _toConsumableArray(arr) { 5880 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); 5881 } 5882 function _arrayWithoutHoles(arr) { 5883 if (Array.isArray(arr)) return _arrayLikeToArray(arr); 5884 } 5885 function _arrayWithHoles(arr) { 5886 if (Array.isArray(arr)) return arr; 5887 } 5888 function _maybeArrayLike(next, arr, i) { 5889 if (arr && !Array.isArray(arr) && typeof arr.length === "number") { 5890 var len = arr.length; 5891 return _arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); 5892 } 5893 return next(arr, i); 5894 } 5895 function _iterableToArray(iter) { 5896 if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); 5897 } 5898 function _unsupportedIterableToArray(o, minLen) { 5899 if (!o) return; 5900 if (typeof o === "string") return _arrayLikeToArray(o, minLen); 5901 var n = Object.prototype.toString.call(o).slice(8, -1); 5902 if (n === "Object" && o.constructor) n = o.constructor.name; 5903 if (n === "Map" || n === "Set") return Array.from(o); 5904 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); 5905 } 5906 function _arrayLikeToArray(arr, len) { 5907 if (len == null || len > arr.length) len = arr.length; 5908 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; 5909 return arr2; 5910 } 5911 function _nonIterableSpread() { 5912 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 5913 } 5914 function _nonIterableRest() { 5915 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 5916 } 5917 function _createForOfIteratorHelper(o, allowArrayLike) { 5918 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; 5919 if (!it) { 5920 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { 5921 if (it) o = it; 5922 var i = 0; 5923 var F = function () {}; 5924 return { 5925 s: F, 5926 n: function () { 5927 if (i >= o.length) return { 5928 done: true 5929 }; 5930 return { 5931 done: false, 5932 value: o[i++] 5933 }; 5934 }, 5935 e: function (e) { 5936 throw e; 5937 }, 5938 f: F 5939 }; 5940 } 5941 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 5942 } 5943 var normalCompletion = true, 5944 didErr = false, 5945 err; 5946 return { 5947 s: function () { 5948 it = it.call(o); 5949 }, 5950 n: function () { 5951 var step = it.next(); 5952 normalCompletion = step.done; 5953 return step; 5954 }, 5955 e: function (e) { 5956 didErr = true; 5957 err = e; 5958 }, 5959 f: function () { 5960 try { 5961 if (!normalCompletion && it.return != null) it.return(); 5962 } finally { 5963 if (didErr) throw err; 5964 } 5965 } 5966 }; 5967 } 5968 function _createForOfIteratorHelperLoose(o, allowArrayLike) { 5969 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; 5970 if (it) return (it = it.call(o)).next.bind(it); 5971 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { 5972 if (it) o = it; 5973 var i = 0; 5974 return function () { 5975 if (i >= o.length) return { 5976 done: true 5977 }; 5978 return { 5979 done: false, 5980 value: o[i++] 5981 }; 5982 }; 5983 } 5984 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 5985 } 5986 function _skipFirstGeneratorNext(fn) { 5987 return function () { 5988 var it = fn.apply(this, arguments); 5989 it.next(); 5990 return it; 5991 }; 5992 } 5993 function _toPrimitive(input, hint) { 5994 if (typeof input !== "object" || input === null) return input; 5995 var prim = input[Symbol.toPrimitive]; 5996 if (prim !== undefined) { 5997 var res = prim.call(input, hint || "default"); 5998 if (typeof res !== "object") return res; 5999 throw new TypeError("@@toPrimitive must return a primitive value."); 6000 } 6001 return (hint === "string" ? String : Number)(input); 6002 } 6003 function _toPropertyKey(arg) { 6004 var key = _toPrimitive(arg, "string"); 6005 return typeof key === "symbol" ? key : String(key)
vendor: 23,419 bytes, lines 6005-6638
6005; 6006 } 6007 function _initializerWarningHelper(descriptor, context) { 6008 throw new Error('Decorating class property failed. Please ensure that ' + 'transform-class-properties is enabled and runs after the decorators transform.'); 6009 } 6010 function _initializerDefineProperty(target, property, descriptor, context) { 6011 if (!descriptor) return; 6012 Object.defineProperty(target, property, { 6013 enumerable: descriptor.enumerable, 6014 configurable: descriptor.configurable, 6015 writable: descriptor.writable, 6016 value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 6017 }); 6018 } 6019 function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { 6020 var desc = {}; 6021 Object.keys(descriptor).forEach(function (key) { 6022 desc[key] = descriptor[key]; 6023 }); 6024 desc.enumerable = !!desc.enumerable; 6025 desc.configurable = !!desc.configurable; 6026 if ('value' in desc || desc.initializer) { 6027 desc.writable = true; 6028 } 6029 desc = decorators.slice().reverse().reduce(function (desc, decorator) { 6030 return decorator(target, property, desc) || desc; 6031 }, desc); 6032 if (context && desc.initializer !== void 0) { 6033 desc.value = desc.initializer ? desc.initializer.call(context) : void 0; 6034 desc.initializer = undefined; 6035 } 6036 if (desc.initializer === void 0) { 6037 Object.defineProperty(target, property, desc); 6038 desc = null; 6039 } 6040 return desc; 6041 } 6042 var id$1 = 0; 6043 function _classPrivateFieldLooseKey(name) { 6044 return "__private_" + id$1++ + "_" + name; 6045 } 6046 function _classPrivateFieldLooseBase(receiver, privateKey) { 6047 if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { 6048 throw new TypeError("attempted to use private field on non-instance"); 6049 } 6050 return receiver; 6051 } 6052 function _classPrivateFieldGet(receiver, privateMap) { 6053 var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get"); 6054 return _classApplyDescriptorGet(receiver, descriptor); 6055 } 6056 function _classPrivateFieldSet(receiver, privateMap, value) { 6057 var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set"); 6058 _classApplyDescriptorSet(receiver, descriptor, value); 6059 return value; 6060 } 6061 function _classPrivateFieldDestructureSet(receiver, privateMap) { 6062 var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set"); 6063 return _classApplyDescriptorDestructureSet(receiver, descriptor); 6064 } 6065 function _classExtractFieldDescriptor(receiver, privateMap, action) { 6066 if (!privateMap.has(receiver)) { 6067 throw new TypeError("attempted to " + action + " private field on non-instance"); 6068 } 6069 return privateMap.get(receiver); 6070 } 6071 function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { 6072 _classCheckPrivateStaticAccess(receiver, classConstructor); 6073 _classCheckPrivateStaticFieldDescriptor(descriptor, "get"); 6074 return _classApplyDescriptorGet(receiver, descriptor); 6075 } 6076 function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { 6077 _classCheckPrivateStaticAccess(receiver, classConstructor); 6078 _classCheckPrivateStaticFieldDescriptor(descriptor, "set"); 6079 _classApplyDescriptorSet(receiver, descriptor, value); 6080 return value; 6081 } 6082 function _classStaticPrivateMethodGet(receiver, classConstructor, method) { 6083 _classCheckPrivateStaticAccess(receiver, classConstructor); 6084 return method; 6085 } 6086 function _classStaticPrivateMethodSet() { 6087 throw new TypeError("attempted to set read only static private field"); 6088 } 6089 function _classApplyDescriptorGet(receiver, descriptor) { 6090 if (descriptor.get) { 6091 return descriptor.get.call(receiver); 6092 } 6093 return descriptor.value; 6094 } 6095 function _classApplyDescriptorSet(receiver, descriptor, value) { 6096 if (descriptor.set) { 6097 descriptor.set.call(receiver, value); 6098 } else { 6099 if (!descriptor.writable) { 6100 throw new TypeError("attempted to set read only private field"); 6101 } 6102 descriptor.value = value; 6103 } 6104 } 6105 function _classApplyDescriptorDestructureSet(receiver, descriptor) { 6106 if (descriptor.set) { 6107 if (!("__destrObj" in descriptor)) { 6108 descriptor.__destrObj = { 6109 set value(v) { 6110 descriptor.set.call(receiver, v); 6111 } 6112 }; 6113 } 6114 return descriptor.__destrObj; 6115 } else { 6116 if (!descriptor.writable) { 6117 throw new TypeError("attempted to set read only private field"); 6118 } 6119 return descriptor; 6120 } 6121 } 6122 function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) { 6123 _classCheckPrivateStaticAccess(receiver, classConstructor); 6124 _classCheckPrivateStaticFieldDescriptor(descriptor, "set"); 6125 return _classApplyDescriptorDestructureSet(receiver, descriptor); 6126 } 6127 function _classCheckPrivateStaticAccess(receiver, classConstructor) { 6128 if (receiver !== classConstructor) { 6129 throw new TypeError("Private static access of wrong provenance"); 6130 } 6131 } 6132 function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { 6133 if (descriptor === undefined) { 6134 throw new TypeError("attempted to " + action + " private static field before its declaration"); 6135 } 6136 } 6137 function _decorate(decorators, factory, superClass, mixins) { 6138 var api = _getDecoratorsApi(); 6139 if (mixins) { 6140 for (var i = 0; i < mixins.length; i++) { 6141 api = mixins[i](api); 6142 } 6143 } 6144 var r = factory(function initialize(O) { 6145 api.initializeInstanceElements(O, decorated.elements); 6146 }, superClass); 6147 var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); 6148 api.initializeClassElements(r.F, decorated.elements); 6149 return api.runClassFinishers(r.F, decorated.finishers); 6150 } 6151 function _getDecoratorsApi() { 6152 _getDecoratorsApi = function () { 6153 return api; 6154 }; 6155 var api = { 6156 elementsDefinitionOrder: [["method"], ["field"]], 6157 initializeInstanceElements: function (O, elements) { 6158 ["method", "field"].forEach(function (kind) { 6159 elements.forEach(function (element) { 6160 if (element.kind === kind && element.placement === "own") { 6161 this.defineClassElement(O, element); 6162 } 6163 }, this); 6164 }, this); 6165 }, 6166 initializeClassElements: function (F, elements) { 6167 var proto = F.prototype; 6168 ["method", "field"].forEach(function (kind) { 6169 elements.forEach(function (element) { 6170 var placement = element.placement; 6171 if (element.kind === kind && (placement === "static" || placement === "prototype")) { 6172 var receiver = placement === "static" ? F : proto; 6173 this.defineClassElement(receiver, element); 6174 } 6175 }, this); 6176 }, this); 6177 }, 6178 defineClassElement: function (receiver, element) { 6179 var descriptor = element.descriptor; 6180 if (element.kind === "field") { 6181 var initializer = element.initializer; 6182 descriptor = { 6183 enumerable: descriptor.enumerable, 6184 writable: descriptor.writable, 6185 configurable: descriptor.configurable, 6186 value: initializer === void 0 ? void 0 : initializer.call(receiver) 6187 }; 6188 } 6189 Object.defineProperty(receiver, element.key, descriptor); 6190 }, 6191 decorateClass: function (elements, decorators) { 6192 var newElements = []; 6193 var finishers = []; 6194 var placements = { 6195 static: [], 6196 prototype: [], 6197 own: [] 6198 }; 6199 elements.forEach(function (element) { 6200 this.addElementPlacement(element, placements); 6201 }, this); 6202 elements.forEach(function (element) { 6203 if (!_hasDecorators(element)) return newElements.push(element); 6204 var elementFinishersExtras = this.decorateElement(element, placements); 6205 newElements.push(elementFinishersExtras.element); 6206 newElements.push.apply(newElements, elementFinishersExtras.extras); 6207 finishers.push.apply(finishers, elementFinishersExtras.finishers); 6208 }, this); 6209 if (!decorators) { 6210 return { 6211 elements: newElements, 6212 finishers: finishers 6213 }; 6214 } 6215 var result = this.decorateConstructor(newElements, decorators); 6216 finishers.push.apply(finishers, result.finishers); 6217 result.finishers = finishers; 6218 return result; 6219 }, 6220 addElementPlacement: function (element, placements, silent) { 6221 var keys = placements[element.placement]; 6222 if (!silent && keys.indexOf(element.key) !== -1) { 6223 throw new TypeError("Duplicated element (" + element.key + ")"); 6224 } 6225 keys.push(element.key); 6226 }, 6227 decorateElement: function (element, placements) { 6228 var extras = []; 6229 var finishers = []; 6230 for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { 6231 var keys = placements[element.placement]; 6232 keys.splice(keys.indexOf(element.key), 1); 6233 var elementObject = this.fromElementDescriptor(element); 6234 var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); 6235 element = elementFinisherExtras.element; 6236 this.addElementPlacement(element, placements); 6237 if (elementFinisherExtras.finisher) { 6238 finishers.push(elementFinisherExtras.finisher); 6239 } 6240 var newExtras = elementFinisherExtras.extras; 6241 if (newExtras) { 6242 for (var j = 0; j < newExtras.length; j++) { 6243 this.addElementPlacement(newExtras[j], placements); 6244 } 6245 extras.push.apply(extras, newExtras); 6246 } 6247 } 6248 return { 6249 element: element, 6250 finishers: finishers, 6251 extras: extras 6252 }; 6253 }, 6254 decorateConstructor: function (elements, decorators) { 6255 var finishers = []; 6256 for (var i = decorators.length - 1; i >= 0; i--) { 6257 var obj = this.fromClassDescriptor(elements); 6258 var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); 6259 if (elementsAndFinisher.finisher !== undefined) { 6260 finishers.push(elementsAndFinisher.finisher); 6261 } 6262 if (elementsAndFinisher.elements !== undefined) { 6263 elements = elementsAndFinisher.elements; 6264 for (var j = 0; j < elements.length - 1; j++) { 6265 for (var k = j + 1; k < elements.length; k++) { 6266 if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { 6267 throw new TypeError("Duplicated element (" + elements[j].key + ")"); 6268 } 6269 } 6270 } 6271 } 6272 } 6273 return { 6274 elements: elements, 6275 finishers: finishers 6276 }; 6277 }, 6278 fromElementDescriptor: function (element) { 6279 var obj = { 6280 kind: element.kind, 6281 key: element.key, 6282 placement: element.placement, 6283 descriptor: element.descriptor 6284 }; 6285 var desc = { 6286 value: "Descriptor", 6287 configurable: true 6288 }; 6289 Object.defineProperty(obj, Symbol.toStringTag, desc); 6290 if (element.kind === "field") obj.initializer = element.initializer; 6291 return obj; 6292 }, 6293 toElementDescriptors: function (elementObjects) { 6294 if (elementObjects === undefined) return; 6295 return _toArray(elementObjects).map(function (elementObject) { 6296 var element = this.toElementDescriptor(elementObject); 6297 this.disallowProperty(elementObject, "finisher", "An element descriptor"); 6298 this.disallowProperty(elementObject, "extras", "An element descriptor"); 6299 return element; 6300 }, this); 6301 }, 6302 toElementDescriptor: function (elementObject) { 6303 var kind = String(elementObject.kind); 6304 if (kind !== "method" && kind !== "field") { 6305 throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); 6306 } 6307 var key = _toPropertyKey(elementObject.key); 6308 var placement = String(elementObject.placement); 6309 if (placement !== "static" && placement !== "prototype" && placement !== "own") { 6310 throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); 6311 } 6312 var descriptor = elementObject.descriptor; 6313 this.disallowProperty(elementObject, "elements", "An element descriptor"); 6314 var element = { 6315 kind: kind, 6316 key: key, 6317 placement: placement, 6318 descriptor: Object.assign({}, descriptor) 6319 }; 6320 if (kind !== "field") { 6321 this.disallowProperty(elementObject, "initializer", "A method descriptor"); 6322 } else { 6323 this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); 6324 this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); 6325 this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); 6326 element.initializer = elementObject.initializer; 6327 } 6328 return element; 6329 }, 6330 toElementFinisherExtras: function (elementObject) { 6331 var element = this.toElementDescriptor(elementObject); 6332 var finisher = _optionalCallableProperty(elementObject, "finisher"); 6333 var extras = this.toElementDescriptors(elementObject.extras); 6334 return { 6335 element: element, 6336 finisher: finisher, 6337 extras: extras 6338 }; 6339 }, 6340 fromClassDescriptor: function (elements) { 6341 var obj = { 6342 kind: "class", 6343 elements: elements.map(this.fromElementDescriptor, this) 6344 }; 6345 var desc = { 6346 value: "Descriptor", 6347 configurable: true 6348 }; 6349 Object.defineProperty(obj, Symbol.toStringTag, desc); 6350 return obj; 6351 }, 6352 toClassDescriptor: function (obj) { 6353 var kind = String(obj.kind); 6354 if (kind !== "class") { 6355 throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); 6356 } 6357 this.disallowProperty(obj, "key", "A class descriptor"); 6358 this.disallowProperty(obj, "placement", "A class descriptor"); 6359 this.disallowProperty(obj, "descriptor", "A class descriptor"); 6360 this.disallowProperty(obj, "initializer", "A class descriptor"); 6361 this.disallowProperty(obj, "extras", "A class descriptor"); 6362 var finisher = _optionalCallableProperty(obj, "finisher"); 6363 var elements = this.toElementDescriptors(obj.elements); 6364 return { 6365 elements: elements, 6366 finisher: finisher 6367 }; 6368 }, 6369 runClassFinishers: function (constructor, finishers) { 6370 for (var i = 0; i < finishers.length; i++) { 6371 var newConstructor = (0, finishers[i])(constructor); 6372 if (newConstructor !== undefined) { 6373 if (typeof newConstructor !== "function") { 6374 throw new TypeError("Finishers must return a constructor."); 6375 } 6376 constructor = newConstructor; 6377 } 6378 } 6379 return constructor; 6380 }, 6381 disallowProperty: function (obj, name, objectType) { 6382 if (obj[name] !== undefined) { 6383 throw new TypeError(objectType + " can't have a ." + name + " property."); 6384 } 6385 } 6386 }; 6387 return api; 6388 } 6389 function _createElementDescriptor(def) { 6390 var key = _toPropertyKey(def.key); 6391 var descriptor; 6392 if (def.kind === "method") { 6393 descriptor = { 6394 value: def.value, 6395 writable: true, 6396 configurable: true, 6397 enumerable: false 6398 }; 6399 } else if (def.kind === "get") { 6400 descriptor = { 6401 get: def.value, 6402 configurable: true, 6403 enumerable: false 6404 }; 6405 } else if (def.kind === "set") { 6406 descriptor = { 6407 set: def.value, 6408 configurable: true, 6409 enumerable: false 6410 }; 6411 } else if (def.kind === "field") { 6412 descriptor = { 6413 configurable: true, 6414 writable: true, 6415 enumerable: true 6416 }; 6417 } 6418 var element = { 6419 kind: def.kind === "field" ? "field" : "method", 6420 key: key, 6421 placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", 6422 descriptor: descriptor 6423 }; 6424 if (def.decorators) element.decorators = def.decorators; 6425 if (def.kind === "field") element.initializer = def.value; 6426 return element; 6427 } 6428 function _coalesceGetterSetter(element, other) { 6429 if (element.descriptor.get !== undefined) { 6430 other.descriptor.get = element.descriptor.get; 6431 } else { 6432 other.descriptor.set = element.descriptor.set; 6433 } 6434 } 6435 function _coalesceClassElements(elements) { 6436 var newElements = []; 6437 var isSameElement = function (other) { 6438 return other.kind === "method" && other.key === element.key && other.placement === element.placement; 6439 }; 6440 for (var i = 0; i < elements.length; i++) { 6441 var element = elements[i]; 6442 var other; 6443 if (element.kind === "method" && (other = newElements.find(isSameElement))) { 6444 if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { 6445 if (_hasDecorators(element) || _hasDecorators(other)) { 6446 throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); 6447 } 6448 other.descriptor = element.descriptor; 6449 } else { 6450 if (_hasDecorators(element)) { 6451 if (_hasDecorators(other)) { 6452 throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); 6453 } 6454 other.decorators = element.decorators; 6455 } 6456 _coalesceGetterSetter(element, other); 6457 } 6458 } else { 6459 newElements.push(element); 6460 } 6461 } 6462 return newElements; 6463 } 6464 function _hasDecorators(element) { 6465 return element.decorators && element.decorators.length; 6466 } 6467 function _isDataDescriptor(desc) { 6468 return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); 6469 } 6470 function _optionalCallableProperty(obj, name) { 6471 var value = obj[name]; 6472 if (value !== undefined && typeof value !== "function") { 6473 throw new TypeError("Expected '" + name + "' to be a function"); 6474 } 6475 return value; 6476 } 6477 function _classPrivateMethodGet(receiver, privateSet, fn) { 6478 if (!privateSet.has(receiver)) { 6479 throw new TypeError("attempted to get private field on non-instance"); 6480 } 6481 return fn; 6482 } 6483 function _checkPrivateRedeclaration(obj, privateCollection) { 6484 if (privateCollection.has(obj)) { 6485 throw new TypeError("Cannot initialize the same private elements twice on an object"); 6486 } 6487 } 6488 function _classPrivateFieldInitSpec(obj, privateMap, value) { 6489 _checkPrivateRedeclaration(obj, privateMap); 6490 privateMap.set(obj, value); 6491 } 6492 function _classPrivateMethodInitSpec(obj, privateSet) { 6493 _checkPrivateRedeclaration(obj, privateSet); 6494 privateSet.add(obj); 6495 } 6496 function _classPrivateMethodSet() { 6497 throw new TypeError("attempted to reassign private method"); 6498 } 6499 function _identity(x) { 6500 return x; 6501 } 6502 function _nullishReceiverError(r) { 6503 throw new TypeError("Cannot set property of null or undefined."); 6504 } 6505 6506 class Piece extends TrixObject { 6507 static registerType(type, constructor) { 6508 constructor.type = type; 6509 this.types[type] = constructor; 6510 } 6511 static fromJSON(pieceJSON) { 6512 const constructor = this.types[pieceJSON.type]; 6513 if (constructor) { 6514 return constructor.fromJSON(pieceJSON); 6515 } 6516 } 6517 constructor(value) { 6518 let attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 6519 super(...arguments); 6520 this.attributes = Hash.box(attributes); 6521 } 6522 copyWithAttributes(attributes) { 6523 return new this.constructor(this.getValue(), attributes); 6524 } 6525 copyWithAdditionalAttributes(attributes) { 6526 return this.copyWithAttributes(this.attributes.merge(attributes)); 6527 } 6528 copyWithoutAttribute(attribute) { 6529 return this.copyWithAttributes(this.attributes.remove(attribute)); 6530 } 6531 copy() { 6532 return this.copyWithAttributes(this.attributes); 6533 } 6534 getAttribute(attribute) { 6535 return this.attributes.get(attribute); 6536 } 6537 getAttributesHash() { 6538 return this.attributes; 6539 } 6540 getAttributes() { 6541 return this.attributes.toObject(); 6542 } 6543 hasAttribute(attribute) { 6544 return this.attributes.has(attribute); 6545 } 6546 hasSameStringValueAsPiece(piece) { 6547 return piece && this.toString() === piece.toString(); 6548 } 6549 hasSameAttributesAsPiece(piece) { 6550 return piece && (this.attributes === piece.attributes || this.attributes.isEqualTo(piece.attributes)); 6551 } 6552 isBlockBreak() { 6553 return false; 6554 } 6555 isEqualTo(piece) { 6556 return super.isEqualTo(...arguments) || this.hasSameConstructorAs(piece) && this.hasSameStringValueAsPiece(piece) && this.hasSameAttributesAsPiece(piece); 6557 } 6558 isEmpty() { 6559 return this.length === 0; 6560 } 6561 isSerializable() { 6562 return true; 6563 } 6564 toJSON() { 6565 return { 6566 type: this.constructor.type, 6567 attributes: this.getAttributes() 6568 }; 6569 } 6570 contentsForInspection() { 6571 return { 6572 type: this.constructor.type, 6573 attributes: this.attributes.inspect() 6574 }; 6575 } 6576 6577 // Grouping 6578 6579 canBeGrouped() { 6580 return this.hasAttribute("href"); 6581 } 6582 canBeGroupedWith(piece) { 6583 return this.getAttribute("href") === piece.getAttribute("href"); 6584 } 6585 6586 // Splittable 6587 6588 getLength() { 6589 return this.length; 6590 } 6591 canBeConsolidatedWith(piece) { 6592 return false; 6593 } 6594 } 6595 _defineProperty(Piece, "types", {}); 6596 6597 class ImagePreloadOperation extends Operation { 6598 constructor(url) { 6599 super(...arguments); 6600 this.url = url; 6601 } 6602 perform(callback) { 6603 const image = new Image(); 6604 image.onload = () => { 6605 image.width = this.width = image.naturalWidth; 6606 image.height = this.height = image.naturalHeight; 6607 return callback(true, image); 6608 }; 6609 image.onerror = () => callback(false); 6610 image.src = this.url; 6611 } 6612 } 6613 6614 class Attachment extends TrixObject { 6615 static attachmentForFile(file) { 6616 const attributes = this.attributesForFile(file); 6617 const attachment = new this(attributes); 6618 attachment.setFile(file); 6619 return attachment; 6620 } 6621 static attributesForFile(file) { 6622 return new Hash({ 6623 filename: file.name, 6624 filesize: file.size, 6625 contentType: file.type 6626 }); 6627 } 6628 static fromJSON(attachmentJSON) { 6629 return new this(attachmentJSON); 6630 } 6631 constructor() { 6632 let attributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 6633 super(attributes); 6634 this.releaseFile = this.releaseFile.bind(this); 6635 this.attributes = Hash.box(attributes); 6636 this.didChangeAttributes(); 6637 } 6638
vendor: 8,215 bytes, lines 6638-6866
6638getAttribute(attribute) { 6639 return this.attributes.get(attribute); 6640 } 6641 hasAttribute(attribute) { 6642 return this.attributes.has(attribute); 6643 } 6644 getAttributes() { 6645 return this.attributes.toObject(); 6646 } 6647 setAttributes() { 6648 let attributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 6649 const newAttributes = this.attributes.merge(attributes); 6650 if (!this.attributes.isEqualTo(newAttributes)) { 6651 var _this$previewDelegate, _this$previewDelegate2, _this$delegate, _this$delegate$attach; 6652 this.attributes = newAttributes; 6653 this.didChangeAttributes(); 6654 (_this$previewDelegate = this.previewDelegate) === null || _this$previewDelegate === void 0 || (_this$previewDelegate2 = _this$previewDelegate.attachmentDidChangeAttributes) === null || _this$previewDelegate2 === void 0 || _this$previewDelegate2.call(_this$previewDelegate, this); 6655 return (_this$delegate = this.delegate) === null || _this$delegate === void 0 || (_this$delegate$attach = _this$delegate.attachmentDidChangeAttributes) === null || _this$delegate$attach === void 0 ? void 0 : _this$delegate$attach.call(_this$delegate, this); 6656 } 6657 } 6658 didChangeAttributes() { 6659 if (this.isPreviewable()) { 6660 return this.preloadURL(); 6661 } 6662 } 6663 isPending() { 6664 return this.file != null && !(this.getURL() || this.getHref()); 6665 } 6666 isPreviewable() { 6667 if (this.attributes.has("previewable")) { 6668 return this.attributes.get("previewable"); 6669 } else { 6670 return Attachment.previewablePattern.test(this.getContentType()); 6671 } 6672 } 6673 getType() { 6674 if (this.hasContent()) { 6675 return "content"; 6676 } else if (this.isPreviewable()) { 6677 return "preview"; 6678 } else { 6679 return "file"; 6680 } 6681 } 6682 getURL() { 6683 return this.attributes.get("url"); 6684 } 6685 getHref() { 6686 return this.attributes.get("href"); 6687 } 6688 getFilename() { 6689 return this.attributes.get("filename") || ""; 6690 } 6691 getFilesize() { 6692 return this.attributes.get("filesize"); 6693 } 6694 getFormattedFilesize() { 6695 const filesize = this.attributes.get("filesize"); 6696 if (typeof filesize === "number") { 6697 return file_size_formatting.formatter(filesize); 6698 } else { 6699 return ""; 6700 } 6701 } 6702 getExtension() { 6703 var _this$getFilename$mat; 6704 return (_this$getFilename$mat = this.getFilename().match(/\.(\w+)$/)) === null || _this$getFilename$mat === void 0 ? void 0 : _this$getFilename$mat[1].toLowerCase(); 6705 } 6706 getContentType() { 6707 return this.attributes.get("contentType"); 6708 } 6709 hasContent() { 6710 return this.attributes.has("content"); 6711 } 6712 getContent() { 6713 return this.attributes.get("content"); 6714 } 6715 getWidth() { 6716 return this.attributes.get("width"); 6717 } 6718 getHeight() { 6719 return this.attributes.get("height"); 6720 } 6721 getFile() { 6722 return this.file; 6723 } 6724 setFile(file) { 6725 this.file = file; 6726 if (this.isPreviewable()) { 6727 return this.preloadFile(); 6728 } 6729 } 6730 releaseFile() { 6731 this.releasePreloadedFile(); 6732 this.file = null; 6733 } 6734 getUploadProgress() { 6735 return this.uploadProgress != null ? this.uploadProgress : 0; 6736 } 6737 setUploadProgress(value) { 6738 if (this.uploadProgress !== value) { 6739 var _this$uploadProgressD, _this$uploadProgressD2; 6740 this.uploadProgress = value; 6741 return (_this$uploadProgressD = this.uploadProgressDelegate) === null || _this$uploadProgressD === void 0 || (_this$uploadProgressD2 = _this$uploadProgressD.attachmentDidChangeUploadProgress) === null || _this$uploadProgressD2 === void 0 ? void 0 : _this$uploadProgressD2.call(_this$uploadProgressD, this); 6742 } 6743 } 6744 toJSON() { 6745 return this.getAttributes(); 6746 } 6747 getCacheKey() { 6748 return [super.getCacheKey(...arguments), this.attributes.getCacheKey(), this.getPreviewURL()].join("/"); 6749 } 6750 6751 // Previewable 6752 6753 getPreviewURL() { 6754 return this.previewURL || this.preloadingURL; 6755 } 6756 setPreviewURL(url) { 6757 if (url !== this.getPreviewURL()) { 6758 var _this$previewDelegate3, _this$previewDelegate4, _this$delegate2, _this$delegate2$attac; 6759 this.previewURL = url; 6760 (_this$previewDelegate3 = this.previewDelegate) === null || _this$previewDelegate3 === void 0 || (_this$previewDelegate4 = _this$previewDelegate3.attachmentDidChangeAttributes) === null || _this$previewDelegate4 === void 0 || _this$previewDelegate4.call(_this$previewDelegate3, this); 6761 return (_this$delegate2 = this.delegate) === null || _this$delegate2 === void 0 || (_this$delegate2$attac = _this$delegate2.attachmentDidChangePreviewURL) === null || _this$delegate2$attac === void 0 ? void 0 : _this$delegate2$attac.call(_this$delegate2, this); 6762 } 6763 } 6764 preloadURL() { 6765 return this.preload(this.getURL(), this.releaseFile); 6766 } 6767 preloadFile() { 6768 if (this.file) { 6769 this.fileObjectURL = URL.createObjectURL(this.file); 6770 return this.preload(this.fileObjectURL); 6771 } 6772 } 6773 releasePreloadedFile() { 6774 if (this.fileObjectURL) { 6775 URL.revokeObjectURL(this.fileObjectURL); 6776 this.fileObjectURL = null; 6777 } 6778 } 6779 preload(url, callback) { 6780 if (url && url !== this.getPreviewURL()) { 6781 this.preloadingURL = url; 6782 const operation = new ImagePreloadOperation(url); 6783 return operation.then(_ref => { 6784 let { 6785 width, 6786 height 6787 } = _ref; 6788 if (!this.getWidth() || !this.getHeight()) { 6789 this.setAttributes({ 6790 width, 6791 height 6792 }); 6793 } 6794 this.preloadingURL = null; 6795 this.setPreviewURL(url); 6796 return callback === null || callback === void 0 ? void 0 : callback(); 6797 }).catch(() => { 6798 this.preloadingURL = null; 6799 return callback === null || callback === void 0 ? void 0 : callback(); 6800 }); 6801 } 6802 } 6803 } 6804 _defineProperty(Attachment, "previewablePattern", /^image(\/(gif|png|webp|jpe?g)|$)/); 6805 6806 class AttachmentPiece extends Piece { 6807 static fromJSON(pieceJSON) { 6808 return new this(Attachment.fromJSON(pieceJSON.attachment), pieceJSON.attributes); 6809 } 6810 constructor(attachment) { 6811 super(...arguments); 6812 this.attachment = attachment; 6813 this.length = 1; 6814 this.ensureAttachmentExclusivelyHasAttribute("href"); 6815 if (!this.attachment.hasContent()) { 6816 this.removeProhibitedAttributes(); 6817 } 6818 } 6819 ensureAttachmentExclusivelyHasAttribute(attribute) { 6820 if (this.hasAttribute(attribute)) { 6821 if (!this.attachment.hasAttribute(attribute)) { 6822 this.attachment.setAttributes(this.attributes.slice([attribute])); 6823 } 6824 this.attributes = this.attributes.remove(attribute); 6825 } 6826 } 6827 removeProhibitedAttributes() { 6828 const attributes = this.attributes.slice(AttachmentPiece.permittedAttributes); 6829 if (!attributes.isEqualTo(this.attributes)) { 6830 this.attributes = attributes; 6831 } 6832 } 6833 getValue() { 6834 return this.attachment; 6835 } 6836 isSerializable() { 6837 return !this.attachment.isPending(); 6838 } 6839 getCaption() { 6840 return this.attributes.get("caption") || ""; 6841 } 6842 isEqualTo(piece) { 6843 var _piece$attachment; 6844 return super.isEqualTo(piece) && this.attachment.id === (piece === null || piece === void 0 || (_piece$attachment = piece.attachment) === null || _piece$attachment === void 0 ? void 0 : _piece$attachment.id); 6845 } 6846 toString() { 6847 return OBJECT_REPLACEMENT_CHARACTER; 6848 } 6849 toJSON() { 6850 const json = super.toJSON(...arguments); 6851 json.attachment = this.attachment; 6852 return json; 6853 } 6854 getCacheKey() { 6855 return [super.getCacheKey(...arguments), this.attachment.getCacheKey()].join("/"); 6856 } 6857 toConsole() { 6858 return JSON.stringify(this.toString()); 6859 } 6860 } 6861 _defineProperty(AttachmentPiece, "permittedAttributes", ["caption", "presentation"]); 6862 Piece.registerType("attachment", AttachmentPiece); 6863 6864 class StringPiece extends Piece { 6865 static fromJSON(pieceJSON) { 6866 return new this(pieceJSON.string, pieceJSON.
vendor: 53,370 bytes, lines 6866-8363
6866attributes); 6867 } 6868 constructor(string) { 6869 super(...arguments); 6870 this.string = normalizeNewlines(string); 6871 this.length = this.string.length; 6872 } 6873 getValue() { 6874 return this.string; 6875 } 6876 toString() { 6877 return this.string.toString(); 6878 } 6879 isBlockBreak() { 6880 return this.toString() === "\n" && this.getAttribute("blockBreak") === true; 6881 } 6882 toJSON() { 6883 const result = super.toJSON(...arguments); 6884 result.string = this.string; 6885 return result; 6886 } 6887 6888 // Splittable 6889 6890 canBeConsolidatedWith(piece) { 6891 return piece && this.hasSameConstructorAs(piece) && this.hasSameAttributesAsPiece(piece); 6892 } 6893 consolidateWith(piece) { 6894 return new this.constructor(this.toString() + piece.toString(), this.attributes); 6895 } 6896 splitAtOffset(offset) { 6897 let left, right; 6898 if (offset === 0) { 6899 left = null; 6900 right = this; 6901 } else if (offset === this.length) { 6902 left = this; 6903 right = null; 6904 } else { 6905 left = new this.constructor(this.string.slice(0, offset), this.attributes); 6906 right = new this.constructor(this.string.slice(offset), this.attributes); 6907 } 6908 return [left, right]; 6909 } 6910 toConsole() { 6911 let { 6912 string 6913 } = this; 6914 if (string.length > 15) { 6915 string = string.slice(0, 14) + "â¦"; 6916 } 6917 return JSON.stringify(string.toString()); 6918 } 6919 } 6920 Piece.registerType("string", StringPiece); 6921 6922 /* eslint-disable 6923 prefer-const, 6924 */ 6925 class SplittableList extends TrixObject { 6926 static box(objects) { 6927 if (objects instanceof this) { 6928 return objects; 6929 } else { 6930 return new this(objects); 6931 } 6932 } 6933 constructor() { 6934 let objects = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 6935 super(...arguments); 6936 this.objects = objects.slice(0); 6937 this.length = this.objects.length; 6938 } 6939 indexOf(object) { 6940 return this.objects.indexOf(object); 6941 } 6942 splice() { 6943 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 6944 args[_key] = arguments[_key]; 6945 } 6946 return new this.constructor(spliceArray(this.objects, ...args)); 6947 } 6948 eachObject(callback) { 6949 return this.objects.map((object, index) => callback(object, index)); 6950 } 6951 insertObjectAtIndex(object, index) { 6952 return this.splice(index, 0, object); 6953 } 6954 insertSplittableListAtIndex(splittableList, index) { 6955 return this.splice(index, 0, ...splittableList.objects); 6956 } 6957 insertSplittableListAtPosition(splittableList, position) { 6958 const [objects, index] = this.splitObjectAtPosition(position); 6959 return new this.constructor(objects).insertSplittableListAtIndex(splittableList, index); 6960 } 6961 editObjectAtIndex(index, callback) { 6962 return this.replaceObjectAtIndex(callback(this.objects[index]), index); 6963 } 6964 replaceObjectAtIndex(object, index) { 6965 return this.splice(index, 1, object); 6966 } 6967 removeObjectAtIndex(index) { 6968 return this.splice(index, 1); 6969 } 6970 getObjectAtIndex(index) { 6971 return this.objects[index]; 6972 } 6973 getSplittableListInRange(range) { 6974 const [objects, leftIndex, rightIndex] = this.splitObjectsAtRange(range); 6975 return new this.constructor(objects.slice(leftIndex, rightIndex + 1)); 6976 } 6977 selectSplittableList(test) { 6978 const objects = this.objects.filter(object => test(object)); 6979 return new this.constructor(objects); 6980 } 6981 removeObjectsInRange(range) { 6982 const [objects, leftIndex, rightIndex] = this.splitObjectsAtRange(range); 6983 return new this.constructor(objects).splice(leftIndex, rightIndex - leftIndex + 1); 6984 } 6985 transformObjectsInRange(range, transform) { 6986 const [objects, leftIndex, rightIndex] = this.splitObjectsAtRange(range); 6987 const transformedObjects = objects.map((object, index) => leftIndex <= index && index <= rightIndex ? transform(object) : object); 6988 return new this.constructor(transformedObjects); 6989 } 6990 splitObjectsAtRange(range) { 6991 let rightOuterIndex; 6992 let [objects, leftInnerIndex, offset] = this.splitObjectAtPosition(startOfRange(range)); 6993 [objects, rightOuterIndex] = new this.constructor(objects).splitObjectAtPosition(endOfRange(range) + offset); 6994 return [objects, leftInnerIndex, rightOuterIndex - 1]; 6995 } 6996 getObjectAtPosition(position) { 6997 const { 6998 index 6999 } = this.findIndexAndOffsetAtPosition(position); 7000 return this.objects[index]; 7001 } 7002 splitObjectAtPosition(position) { 7003 let splitIndex, splitOffset; 7004 const { 7005 index, 7006 offset 7007 } = this.findIndexAndOffsetAtPosition(position); 7008 const objects = this.objects.slice(0); 7009 if (index != null) { 7010 if (offset === 0) { 7011 splitIndex = index; 7012 splitOffset = 0; 7013 } else { 7014 const object = this.getObjectAtIndex(index); 7015 const [leftObject, rightObject] = object.splitAtOffset(offset); 7016 objects.splice(index, 1, leftObject, rightObject); 7017 splitIndex = index + 1; 7018 splitOffset = leftObject.getLength() - offset; 7019 } 7020 } else { 7021 splitIndex = objects.length; 7022 splitOffset = 0; 7023 } 7024 return [objects, splitIndex, splitOffset]; 7025 } 7026 consolidate() { 7027 const objects = []; 7028 let pendingObject = this.objects[0]; 7029 this.objects.slice(1).forEach(object => { 7030 var _pendingObject$canBeC, _pendingObject; 7031 if ((_pendingObject$canBeC = (_pendingObject = pendingObject).canBeConsolidatedWith) !== null && _pendingObject$canBeC !== void 0 && _pendingObject$canBeC.call(_pendingObject, object)) { 7032 pendingObject = pendingObject.consolidateWith(object); 7033 } else { 7034 objects.push(pendingObject); 7035 pendingObject = object; 7036 } 7037 }); 7038 if (pendingObject) { 7039 objects.push(pendingObject); 7040 } 7041 return new this.constructor(objects); 7042 } 7043 consolidateFromIndexToIndex(startIndex, endIndex) { 7044 const objects = this.objects.slice(0); 7045 const objectsInRange = objects.slice(startIndex, endIndex + 1); 7046 const consolidatedInRange = new this.constructor(objectsInRange).consolidate().toArray(); 7047 return this.splice(startIndex, objectsInRange.length, ...consolidatedInRange); 7048 } 7049 findIndexAndOffsetAtPosition(position) { 7050 let index; 7051 let currentPosition = 0; 7052 for (index = 0; index < this.objects.length; index++) { 7053 const object = this.objects[index]; 7054 const nextPosition = currentPosition + object.getLength(); 7055 if (currentPosition <= position && position < nextPosition) { 7056 return { 7057 index, 7058 offset: position - currentPosition 7059 }; 7060 } 7061 currentPosition = nextPosition; 7062 } 7063 return { 7064 index: null, 7065 offset: null 7066 }; 7067 } 7068 findPositionAtIndexAndOffset(index, offset) { 7069 let position = 0; 7070 for (let currentIndex = 0; currentIndex < this.objects.length; currentIndex++) { 7071 const object = this.objects[currentIndex]; 7072 if (currentIndex < index) { 7073 position += object.getLength(); 7074 } else if (currentIndex === index) { 7075 position += offset; 7076 break; 7077 } 7078 } 7079 return position; 7080 } 7081 getEndPosition() { 7082 if (this.endPosition == null) { 7083 this.endPosition = 0; 7084 this.objects.forEach(object => this.endPosition += object.getLength()); 7085 } 7086 return this.endPosition; 7087 } 7088 toString() { 7089 return this.objects.join(""); 7090 } 7091 toArray() { 7092 return this.objects.slice(0); 7093 } 7094 toJSON() { 7095 return this.toArray(); 7096 } 7097 isEqualTo(splittableList) { 7098 return super.isEqualTo(...arguments) || objectArraysAreEqual(this.objects, splittableList === null || splittableList === void 0 ? void 0 : splittableList.objects); 7099 } 7100 contentsForInspection() { 7101 return { 7102 objects: "[".concat(this.objects.map(object => object.inspect()).join(", "), "]") 7103 }; 7104 } 7105 } 7106 const objectArraysAreEqual = function (left) { 7107 let right = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; 7108 if (left.length !== right.length) { 7109 return false; 7110 } 7111 let result = true; 7112 for (let index = 0; index < left.length; index++) { 7113 const object = left[index]; 7114 if (result && !object.isEqualTo(right[index])) { 7115 result = false; 7116 } 7117 } 7118 return result; 7119 }; 7120 const startOfRange = range => range[0]; 7121 const endOfRange = range => range[1]; 7122 7123 class Text extends TrixObject { 7124 static textForAttachmentWithAttributes(attachment, attributes) { 7125 const piece = new AttachmentPiece(attachment, attributes); 7126 return new this([piece]); 7127 } 7128 static textForStringWithAttributes(string, attributes) { 7129 const piece = new StringPiece(string, attributes); 7130 return new this([piece]); 7131 } 7132 static fromJSON(textJSON) { 7133 const pieces = Array.from(textJSON).map(pieceJSON => Piece.fromJSON(pieceJSON)); 7134 return new this(pieces); 7135 } 7136 constructor() { 7137 let pieces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 7138 super(...arguments); 7139 const notEmpty = pieces.filter(piece => !piece.isEmpty()); 7140 this.pieceList = new SplittableList(notEmpty); 7141 } 7142 copy() { 7143 return this.copyWithPieceList(this.pieceList); 7144 } 7145 copyWithPieceList(pieceList) { 7146 return new this.constructor(pieceList.consolidate().toArray()); 7147 } 7148 copyUsingObjectMap(objectMap) { 7149 const pieces = this.getPieces().map(piece => objectMap.find(piece) || piece); 7150 return new this.constructor(pieces); 7151 } 7152 appendText(text) { 7153 return this.insertTextAtPosition(text, this.getLength()); 7154 } 7155 insertTextAtPosition(text, position) { 7156 return this.copyWithPieceList(this.pieceList.insertSplittableListAtPosition(text.pieceList, position)); 7157 } 7158 removeTextAtRange(range) { 7159 return this.copyWithPieceList(this.pieceList.removeObjectsInRange(range)); 7160 } 7161 replaceTextAtRange(text, range) { 7162 return this.removeTextAtRange(range).insertTextAtPosition(text, range[0]); 7163 } 7164 moveTextFromRangeToPosition(range, position) { 7165 if (range[0] <= position && position <= range[1]) return; 7166 const text = this.getTextAtRange(range); 7167 const length = text.getLength(); 7168 if (range[0] < position) { 7169 position -= length; 7170 } 7171 return this.removeTextAtRange(range).insertTextAtPosition(text, position); 7172 } 7173 addAttributeAtRange(attribute, value, range) { 7174 const attributes = {}; 7175 attributes[attribute] = value; 7176 return this.addAttributesAtRange(attributes, range); 7177 } 7178 addAttributesAtRange(attributes, range) { 7179 return this.copyWithPieceList(this.pieceList.transformObjectsInRange(range, piece => piece.copyWithAdditionalAttributes(attributes))); 7180 } 7181 removeAttributeAtRange(attribute, range) { 7182 return this.copyWithPieceList(this.pieceList.transformObjectsInRange(range, piece => piece.copyWithoutAttribute(attribute))); 7183 } 7184 setAttributesAtRange(attributes, range) { 7185 return this.copyWithPieceList(this.pieceList.transformObjectsInRange(range, piece => piece.copyWithAttributes(attributes))); 7186 } 7187 getAttributesAtPosition(position) { 7188 var _this$pieceList$getOb; 7189 return ((_this$pieceList$getOb = this.pieceList.getObjectAtPosition(position)) === null || _this$pieceList$getOb === void 0 ? void 0 : _this$pieceList$getOb.getAttributes()) || {}; 7190 } 7191 getCommonAttributes() { 7192 const objects = Array.from(this.pieceList.toArray()).map(piece => piece.getAttributes()); 7193 return Hash.fromCommonAttributesOfObjects(objects).toObject(); 7194 } 7195 getCommonAttributesAtRange(range) { 7196 return this.getTextAtRange(range).getCommonAttributes() || {}; 7197 } 7198 getExpandedRangeForAttributeAtOffset(attributeName, offset) { 7199 let right; 7200 let left = right = offset; 7201 const length = this.getLength(); 7202 while (left > 0 && this.getCommonAttributesAtRange([left - 1, right])[attributeName]) { 7203 left--; 7204 } 7205 while (right < length && this.getCommonAttributesAtRange([offset, right + 1])[attributeName]) { 7206 right++; 7207 } 7208 return [left, right]; 7209 } 7210 getTextAtRange(range) { 7211 return this.copyWithPieceList(this.pieceList.getSplittableListInRange(range)); 7212 } 7213 getStringAtRange(range) { 7214 return this.pieceList.getSplittableListInRange(range).toString(); 7215 } 7216 getStringAtPosition(position) { 7217 return this.getStringAtRange([position, position + 1]); 7218 } 7219 startsWithString(string) { 7220 return this.getStringAtRange([0, string.length]) === string; 7221 } 7222 endsWithString(string) { 7223 const length = this.getLength(); 7224 return this.getStringAtRange([length - string.length, length]) === string; 7225 } 7226 getAttachmentPieces() { 7227 return this.pieceList.toArray().filter(piece => !!piece.attachment); 7228 } 7229 getAttachments() { 7230 return this.getAttachmentPieces().map(piece => piece.attachment); 7231 } 7232 getAttachmentAndPositionById(attachmentId) { 7233 let position = 0; 7234 for (const piece of this.pieceList.toArray()) { 7235 var _piece$attachment; 7236 if (((_piece$attachment = piece.attachment) === null || _piece$attachment === void 0 ? void 0 : _piece$attachment.id) === attachmentId) { 7237 return { 7238 attachment: piece.attachment, 7239 position 7240 }; 7241 } 7242 position += piece.length; 7243 } 7244 return { 7245 attachment: null, 7246 position: null 7247 }; 7248 } 7249 getAttachmentById(attachmentId) { 7250 const { 7251 attachment 7252 } = this.getAttachmentAndPositionById(attachmentId); 7253 return attachment; 7254 } 7255 getRangeOfAttachment(attachment) { 7256 const attachmentAndPosition = this.getAttachmentAndPositionById(attachment.id); 7257 const position = attachmentAndPosition.position; 7258 attachment = attachmentAndPosition.attachment; 7259 if (attachment) { 7260 return [position, position + 1]; 7261 } 7262 } 7263 updateAttributesForAttachment(attributes, attachment) { 7264 const range = this.getRangeOfAttachment(attachment); 7265 if (range) { 7266 return this.addAttributesAtRange(attributes, range); 7267 } else { 7268 return this; 7269 } 7270 } 7271 getLength() { 7272 return this.pieceList.getEndPosition(); 7273 } 7274 isEmpty() { 7275 return this.getLength() === 0; 7276 } 7277 isEqualTo(text) { 7278 var _text$pieceList; 7279 return super.isEqualTo(text) || (text === null || text === void 0 || (_text$pieceList = text.pieceList) === null || _text$pieceList === void 0 ? void 0 : _text$pieceList.isEqualTo(this.pieceList)); 7280 } 7281 isBlockBreak() { 7282 return this.getLength() === 1 && this.pieceList.getObjectAtIndex(0).isBlockBreak(); 7283 } 7284 eachPiece(callback) { 7285 return this.pieceList.eachObject(callback); 7286 } 7287 getPieces() { 7288 return this.pieceList.toArray(); 7289 } 7290 getPieceAtPosition(position) { 7291 return this.pieceList.getObjectAtPosition(position); 7292 } 7293 contentsForInspection() { 7294 return { 7295 pieceList: this.pieceList.inspect() 7296 }; 7297 } 7298 toSerializableText() { 7299 const pieceList = this.pieceList.selectSplittableList(piece => piece.isSerializable()); 7300 return this.copyWithPieceList(pieceList); 7301 } 7302 toString() { 7303 return this.pieceList.toString(); 7304 } 7305 toJSON() { 7306 return this.pieceList.toJSON(); 7307 } 7308 toConsole() { 7309 return JSON.stringify(this.pieceList.toArray().map(piece => JSON.parse(piece.toConsole()))); 7310 } 7311 7312 // BIDI 7313 7314 getDirection() { 7315 return getDirection(this.toString()); 7316 } 7317 isRTL() { 7318 return this.getDirection() === "rtl"; 7319 } 7320 } 7321 7322 class Block extends TrixObject { 7323 static fromJSON(blockJSON) { 7324 const text = Text.fromJSON(blockJSON.text); 7325 return new this(text, blockJSON.attributes, blockJSON.htmlAttributes); 7326 } 7327 constructor(text, attributes, htmlAttributes) { 7328 super(...arguments); 7329 this.text = applyBlockBreakToText(text || new Text()); 7330 this.attributes = attributes || []; 7331 this.htmlAttributes = htmlAttributes || {}; 7332 } 7333 isEmpty() { 7334 return this.text.isBlockBreak(); 7335 } 7336 isEqualTo(block) { 7337 if (super.isEqualTo(block)) return true; 7338 return this.text.isEqualTo(block === null || block === void 0 ? void 0 : block.text) && arraysAreEqual(this.attributes, block === null || block === void 0 ? void 0 : block.attributes) && objectsAreEqual(this.htmlAttributes, block === null || block === void 0 ? void 0 : block.htmlAttributes); 7339 } 7340 copyWithText(text) { 7341 return new Block(text, this.attributes, this.htmlAttributes); 7342 } 7343 copyWithoutText() { 7344 return this.copyWithText(null); 7345 } 7346 copyWithAttributes(attributes) { 7347 return new Block(this.text, attributes, this.htmlAttributes); 7348 } 7349 copyWithoutAttributes() { 7350 return this.copyWithAttributes(null); 7351 } 7352 copyUsingObjectMap(objectMap) { 7353 const mappedText = objectMap.find(this.text); 7354 if (mappedText) { 7355 return this.copyWithText(mappedText); 7356 } else { 7357 return this.copyWithText(this.text.copyUsingObjectMap(objectMap)); 7358 } 7359 } 7360 addAttribute(attribute) { 7361 const attributes = this.attributes.concat(expandAttribute(attribute)); 7362 return this.copyWithAttributes(attributes); 7363 } 7364 addHTMLAttribute(attribute, value) { 7365 const htmlAttributes = Object.assign({}, this.htmlAttributes, { 7366 [attribute]: value 7367 }); 7368 return new Block(this.text, this.attributes, htmlAttributes); 7369 } 7370 removeAttribute(attribute) { 7371 const { 7372 listAttribute 7373 } = getBlockConfig(attribute); 7374 const attributes = removeLastValue(removeLastValue(this.attributes, attribute), listAttribute); 7375 return this.copyWithAttributes(attributes); 7376 } 7377 removeLastAttribute() { 7378 return this.removeAttribute(this.getLastAttribute()); 7379 } 7380 getLastAttribute() { 7381 return getLastElement(this.attributes); 7382 } 7383 getAttributes() { 7384 return this.attributes.slice(0); 7385 } 7386 getAttributeLevel() { 7387 return this.attributes.length; 7388 } 7389 getAttributeAtLevel(level) { 7390 return this.attributes[level - 1]; 7391 } 7392 hasAttribute(attributeName) { 7393 return this.attributes.includes(attributeName); 7394 } 7395 hasAttributes() { 7396 return this.getAttributeLevel() > 0; 7397 } 7398 getLastNestableAttribute() { 7399 return getLastElement(this.getNestableAttributes()); 7400 } 7401 getNestableAttributes() { 7402 return this.attributes.filter(attribute => getBlockConfig(attribute).nestable); 7403 } 7404 getNestingLevel() { 7405 return this.getNestableAttributes().length; 7406 } 7407 decreaseNestingLevel() { 7408 const attribute = this.getLastNestableAttribute(); 7409 if (attribute) { 7410 return this.removeAttribute(attribute); 7411 } else { 7412 return this; 7413 } 7414 } 7415 increaseNestingLevel() { 7416 const attribute = this.getLastNestableAttribute(); 7417 if (attribute) { 7418 const index = this.attributes.lastIndexOf(attribute); 7419 const attributes = spliceArray(this.attributes, index + 1, 0, ...expandAttribute(attribute)); 7420 return this.copyWithAttributes(attributes); 7421 } else { 7422 return this; 7423 } 7424 } 7425 getListItemAttributes() { 7426 return this.attributes.filter(attribute => getBlockConfig(attribute).listAttribute); 7427 } 7428 isListItem() { 7429 var _getBlockConfig; 7430 return (_getBlockConfig = getBlockConfig(this.getLastAttribute())) === null || _getBlockConfig === void 0 ? void 0 : _getBlockConfig.listAttribute; 7431 } 7432 isTerminalBlock() { 7433 var _getBlockConfig2; 7434 return (_getBlockConfig2 = getBlockConfig(this.getLastAttribute())) === null || _getBlockConfig2 === void 0 ? void 0 : _getBlockConfig2.terminal; 7435 } 7436 breaksOnReturn() { 7437 var _getBlockConfig3; 7438 return (_getBlockConfig3 = getBlockConfig(this.getLastAttribute())) === null || _getBlockConfig3 === void 0 ? void 0 : _getBlockConfig3.breakOnReturn; 7439 } 7440 findLineBreakInDirectionFromPosition(direction, position) { 7441 const string = this.toString(); 7442 let result; 7443 switch (direction) { 7444 case "forward": 7445 result = string.indexOf("\n", position); 7446 break; 7447 case "backward": 7448 result = string.slice(0, position).lastIndexOf("\n"); 7449 } 7450 if (result !== -1) { 7451 return result; 7452 } 7453 } 7454 contentsForInspection() { 7455 return { 7456 text: this.text.inspect(), 7457 attributes: this.attributes 7458 }; 7459 } 7460 toString() { 7461 return this.text.toString(); 7462 } 7463 toJSON() { 7464 return { 7465 text: this.text, 7466 attributes: this.attributes, 7467 htmlAttributes: this.htmlAttributes 7468 }; 7469 } 7470 7471 // BIDI 7472 7473 getDirection() { 7474 return this.text.getDirection(); 7475 } 7476 isRTL() { 7477 return this.text.isRTL(); 7478 } 7479 7480 // Splittable 7481 7482 getLength() { 7483 return this.text.getLength(); 7484 } 7485 canBeConsolidatedWith(block) { 7486 return !this.hasAttributes() && !block.hasAttributes() && this.getDirection() === block.getDirection(); 7487 } 7488 consolidateWith(block) { 7489 const newlineText = Text.textForStringWithAttributes("\n"); 7490 const text = this.getTextWithoutBlockBreak().appendText(newlineText); 7491 return this.copyWithText(text.appendText(block.text)); 7492 } 7493 splitAtOffset(offset) { 7494 let left, right; 7495 if (offset === 0) { 7496 left = null; 7497 right = this; 7498 } else if (offset === this.getLength()) { 7499 left = this; 7500 right = null; 7501 } else { 7502 left = this.copyWithText(this.text.getTextAtRange([0, offset])); 7503 right = this.copyWithText(this.text.getTextAtRange([offset, this.getLength()])); 7504 } 7505 return [left, right]; 7506 } 7507 getBlockBreakPosition() { 7508 return this.text.getLength() - 1; 7509 } 7510 getTextWithoutBlockBreak() { 7511 if (textEndsInBlockBreak(this.text)) { 7512 return this.text.getTextAtRange([0, this.getBlockBreakPosition()]); 7513 } else { 7514 return this.text.copy(); 7515 } 7516 } 7517 7518 // Grouping 7519 7520 canBeGrouped(depth) { 7521 return this.attributes[depth]; 7522 } 7523 canBeGroupedWith(otherBlock, depth) { 7524 const otherAttributes = otherBlock.getAttributes(); 7525 const otherAttribute = otherAttributes[depth]; 7526 const attribute = this.attributes[depth]; 7527 return attribute === otherAttribute && !(getBlockConfig(attribute).group === false && !getListAttributeNames().includes(otherAttributes[depth + 1])) && (this.getDirection() === otherBlock.getDirection() || otherBlock.isEmpty()); 7528 } 7529 } 7530 7531 // Block breaks 7532 7533 const applyBlockBreakToText = function (text) { 7534 text = unmarkExistingInnerBlockBreaksInText(text); 7535 text = addBlockBreakToText(text); 7536 return text; 7537 }; 7538 const unmarkExistingInnerBlockBreaksInText = function (text) { 7539 let modified = false; 7540 const pieces = text.getPieces(); 7541 let innerPieces = pieces.slice(0, pieces.length - 1); 7542 const lastPiece = pieces[pieces.length - 1]; 7543 if (!lastPiece) return text; 7544 innerPieces = innerPieces.map(piece => { 7545 if (piece.isBlockBreak()) { 7546 modified = true; 7547 return unmarkBlockBreakPiece(piece); 7548 } else { 7549 return piece; 7550 } 7551 }); 7552 if (modified) { 7553 return new Text([...innerPieces, lastPiece]); 7554 } else { 7555 return text; 7556 } 7557 }; 7558 const blockBreakText = Text.textForStringWithAttributes("\n", { 7559 blockBreak: true 7560 }); 7561 const addBlockBreakToText = function (text) { 7562 if (textEndsInBlockBreak(text)) { 7563 return text; 7564 } else { 7565 return text.appendText(blockBreakText); 7566 } 7567 }; 7568 const textEndsInBlockBreak = function (text) { 7569 const length = text.getLength(); 7570 if (length === 0) { 7571 return false; 7572 } 7573 const endText = text.getTextAtRange([length - 1, length]); 7574 return endText.isBlockBreak(); 7575 }; 7576 const unmarkBlockBreakPiece = piece => piece.copyWithoutAttribute("blockBreak"); 7577 7578 // Attributes 7579 7580 const expandAttribute = function (attribute) { 7581 const { 7582 listAttribute 7583 } = getBlockConfig(attribute); 7584 if (listAttribute) { 7585 return [listAttribute, attribute]; 7586 } else { 7587 return [attribute]; 7588 } 7589 }; 7590 7591 // Array helpers 7592 7593 const getLastElement = array => array.slice(-1)[0]; 7594 const removeLastValue = function (array, value) { 7595 const index = array.lastIndexOf(value); 7596 if (index === -1) { 7597 return array; 7598 } else { 7599 return spliceArray(array, index, 1); 7600 } 7601 }; 7602 7603 class Document extends TrixObject { 7604 static fromJSON(documentJSON) { 7605 const blocks = Array.from(documentJSON).map(blockJSON => Block.fromJSON(blockJSON)); 7606 return new this(blocks); 7607 } 7608 static fromString(string, textAttributes) { 7609 const text = Text.textForStringWithAttributes(string, textAttributes); 7610 return new this([new Block(text)]); 7611 } 7612 constructor() { 7613 let blocks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 7614 super(...arguments); 7615 if (blocks.length === 0) { 7616 blocks = [new Block()]; 7617 } 7618 this.blockList = SplittableList.box(blocks); 7619 } 7620 isEmpty() { 7621 const block = this.getBlockAtIndex(0); 7622 return this.blockList.length === 1 && block.isEmpty() && !block.hasAttributes(); 7623 } 7624 copy() { 7625 let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 7626 const blocks = options.consolidateBlocks ? this.blockList.consolidate().toArray() : this.blockList.toArray(); 7627 return new this.constructor(blocks); 7628 } 7629 copyUsingObjectsFromDocument(sourceDocument) { 7630 const objectMap = new ObjectMap(sourceDocument.getObjects()); 7631 return this.copyUsingObjectMap(objectMap); 7632 } 7633 copyUsingObjectMap(objectMap) { 7634 const blocks = this.getBlocks().map(block => { 7635 const mappedBlock = objectMap.find(block); 7636 return mappedBlock || block.copyUsingObjectMap(objectMap); 7637 }); 7638 return new this.constructor(blocks); 7639 } 7640 copyWithBaseBlockAttributes() { 7641 let blockAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 7642 const blocks = this.getBlocks().map(block => { 7643 const attributes = blockAttributes.concat(block.getAttributes()); 7644 return block.copyWithAttributes(attributes); 7645 }); 7646 return new this.constructor(blocks); 7647 } 7648 replaceBlock(oldBlock, newBlock) { 7649 const index = this.blockList.indexOf(oldBlock); 7650 if (index === -1) { 7651 return this; 7652 } 7653 return new this.constructor(this.blockList.replaceObjectAtIndex(newBlock, index)); 7654 } 7655 insertDocumentAtRange(document, range) { 7656 const { 7657 blockList 7658 } = document; 7659 range = normalizeRange(range); 7660 let [position] = range; 7661 const { 7662 index, 7663 offset 7664 } = this.locationFromPosition(position); 7665 let result = this; 7666 const block = this.getBlockAtPosition(position); 7667 if (rangeIsCollapsed(range) && block.isEmpty() && !block.hasAttributes()) { 7668 result = new this.constructor(result.blockList.removeObjectAtIndex(index)); 7669 } else if (block.getBlockBreakPosition() === offset) { 7670 position++; 7671 } 7672 result = result.removeTextAtRange(range); 7673 return new this.constructor(result.blockList.insertSplittableListAtPosition(blockList, position)); 7674 } 7675 mergeDocumentAtRange(document, range) { 7676 let formattedDocument, result; 7677 range = normalizeRange(range); 7678 const [startPosition] = range; 7679 const startLocation = this.locationFromPosition(startPosition); 7680 const blockAttributes = this.getBlockAtIndex(startLocation.index).getAttributes(); 7681 const baseBlockAttributes = document.getBaseBlockAttributes(); 7682 const trailingBlockAttributes = blockAttributes.slice(-baseBlockAttributes.length); 7683 if (arraysAreEqual(baseBlockAttributes, trailingBlockAttributes)) { 7684 const leadingBlockAttributes = blockAttributes.slice(0, -baseBlockAttributes.length); 7685 formattedDocument = document.copyWithBaseBlockAttributes(leadingBlockAttributes); 7686 } else { 7687 formattedDocument = document.copy({ 7688 consolidateBlocks: true 7689 }).copyWithBaseBlockAttributes(blockAttributes); 7690 } 7691 const blockCount = formattedDocument.getBlockCount(); 7692 const firstBlock = formattedDocument.getBlockAtIndex(0); 7693 if (arraysAreEqual(blockAttributes, firstBlock.getAttributes())) { 7694 const firstText = firstBlock.getTextWithoutBlockBreak(); 7695 result = this.insertTextAtRange(firstText, range); 7696 if (blockCount > 1) { 7697 formattedDocument = new this.constructor(formattedDocument.getBlocks().slice(1)); 7698 const position = startPosition + firstText.getLength(); 7699 result = result.insertDocumentAtRange(formattedDocument, position); 7700 } 7701 } else { 7702 result = this.insertDocumentAtRange(formattedDocument, range); 7703 } 7704 return result; 7705 } 7706 insertTextAtRange(text, range) { 7707 range = normalizeRange(range); 7708 const [startPosition] = range; 7709 const { 7710 index, 7711 offset 7712 } = this.locationFromPosition(startPosition); 7713 const document = this.removeTextAtRange(range); 7714 return new this.constructor(document.blockList.editObjectAtIndex(index, block => block.copyWithText(block.text.insertTextAtPosition(text, offset)))); 7715 } 7716 removeTextAtRange(range) { 7717 let blocks; 7718 range = normalizeRange(range); 7719 const [leftPosition, rightPosition] = range; 7720 if (rangeIsCollapsed(range)) { 7721 return this; 7722 } 7723 const [leftLocation, rightLocation] = Array.from(this.locationRangeFromRange(range)); 7724 const leftIndex = leftLocation.index; 7725 const leftOffset = leftLocation.offset; 7726 const leftBlock = this.getBlockAtIndex(leftIndex); 7727 const rightIndex = rightLocation.index; 7728 const rightOffset = rightLocation.offset; 7729 const rightBlock = this.getBlockAtIndex(rightIndex); 7730 const removeRightNewline = rightPosition - leftPosition === 1 && leftBlock.getBlockBreakPosition() === leftOffset && rightBlock.getBlockBreakPosition() !== rightOffset && rightBlock.text.getStringAtPosition(rightOffset) === "\n"; 7731 if (removeRightNewline) { 7732 blocks = this.blockList.editObjectAtIndex(rightIndex, block => block.copyWithText(block.text.removeTextAtRange([rightOffset, rightOffset + 1]))); 7733 } else { 7734 let block; 7735 const leftText = leftBlock.text.getTextAtRange([0, leftOffset]); 7736 const rightText = rightBlock.text.getTextAtRange([rightOffset, rightBlock.getLength()]); 7737 const text = leftText.appendText(rightText); 7738 const removingLeftBlock = leftIndex !== rightIndex && leftOffset === 0; 7739 const useRightBlock = removingLeftBlock && leftBlock.getAttributeLevel() >= rightBlock.getAttributeLevel(); 7740 if (useRightBlock) { 7741 block = rightBlock.copyWithText(text); 7742 } else { 7743 block = leftBlock.copyWithText(text); 7744 } 7745 const affectedBlockCount = rightIndex + 1 - leftIndex; 7746 blocks = this.blockList.splice(leftIndex, affectedBlockCount, block); 7747 } 7748 return new this.constructor(blocks); 7749 } 7750 moveTextFromRangeToPosition(range, position) { 7751 let text; 7752 range = normalizeRange(range); 7753 const [startPosition, endPosition] = range; 7754 if (startPosition <= position && position <= endPosition) { 7755 return this; 7756 } 7757 let document = this.getDocumentAtRange(range); 7758 let result = this.removeTextAtRange(range); 7759 const movingRightward = startPosition < position; 7760 if (movingRightward) { 7761 position -= document.getLength(); 7762 } 7763 const [firstBlock, ...blocks] = document.getBlocks(); 7764 if (blocks.length === 0) { 7765 text = firstBlock.getTextWithoutBlockBreak(); 7766 if (movingRightward) { 7767 position += 1; 7768 } 7769 } else { 7770 text = firstBlock.text; 7771 } 7772 result = result.insertTextAtRange(text, position); 7773 if (blocks.length === 0) { 7774 return result; 7775 } 7776 document = new this.constructor(blocks); 7777 position += text.getLength(); 7778 return result.insertDocumentAtRange(document, position); 7779 } 7780 addAttributeAtRange(attribute, value, range) { 7781 let { 7782 blockList 7783 } = this; 7784 this.eachBlockAtRange(range, (block, textRange, index) => blockList = blockList.editObjectAtIndex(index, function () { 7785 if (getBlockConfig(attribute)) { 7786 return block.addAttribute(attribute, value); 7787 } else { 7788 if (textRange[0] === textRange[1]) { 7789 return block; 7790 } else { 7791 return block.copyWithText(block.text.addAttributeAtRange(attribute, value, textRange)); 7792 } 7793 } 7794 })); 7795 return new this.constructor(blockList); 7796 } 7797 addAttribute(attribute, value) { 7798 let { 7799 blockList 7800 } = this; 7801 this.eachBlock((block, index) => blockList = blockList.editObjectAtIndex(index, () => block.addAttribute(attribute, value))); 7802 return new this.constructor(blockList); 7803 } 7804 removeAttributeAtRange(attribute, range) { 7805 let { 7806 blockList 7807 } = this; 7808 this.eachBlockAtRange(range, function (block, textRange, index) { 7809 if (getBlockConfig(attribute)) { 7810 blockList = blockList.editObjectAtIndex(index, () => block.removeAttribute(attribute)); 7811 } else if (textRange[0] !== textRange[1]) { 7812 blockList = blockList.editObjectAtIndex(index, () => block.copyWithText(block.text.removeAttributeAtRange(attribute, textRange))); 7813 } 7814 }); 7815 return new this.constructor(blockList); 7816 } 7817 updateAttributesForAttachment(attributes, attachment) { 7818 const range = this.getRangeOfAttachment(attachment); 7819 const [startPosition] = Array.from(range); 7820 const { 7821 index 7822 } = this.locationFromPosition(startPosition); 7823 const text = this.getTextAtIndex(index); 7824 return new this.constructor(this.blockList.editObjectAtIndex(index, block => block.copyWithText(text.updateAttributesForAttachment(attributes, attachment)))); 7825 } 7826 removeAttributeForAttachment(attribute, attachment) { 7827 const range = this.getRangeOfAttachment(attachment); 7828 return this.removeAttributeAtRange(attribute, range); 7829 } 7830 setHTMLAttributeAtPosition(position, name, value) { 7831 const block = this.getBlockAtPosition(position); 7832 const updatedBlock = block.addHTMLAttribute(name, value); 7833 return this.replaceBlock(block, updatedBlock); 7834 } 7835 insertBlockBreakAtRange(range) { 7836 let blocks; 7837 range = normalizeRange(range); 7838 const [startPosition] = range; 7839 const { 7840 offset 7841 } = this.locationFromPosition(startPosition); 7842 const document = this.removeTextAtRange(range); 7843 if (offset === 0) { 7844 blocks = [new Block()]; 7845 } 7846 return new this.constructor(document.blockList.insertSplittableListAtPosition(new SplittableList(blocks), startPosition)); 7847 } 7848 applyBlockAttributeAtRange(attributeName, value, range) { 7849 const expanded = this.expandRangeToLineBreaksAndSplitBlocks(range); 7850 let document = expanded.document; 7851 range = expanded.range; 7852 const blockConfig = getBlockConfig(attributeName); 7853 if (blockConfig.listAttribute) { 7854 document = document.removeLastListAttributeAtRange(range, { 7855 exceptAttributeName: attributeName 7856 }); 7857 const converted = document.convertLineBreaksToBlockBreaksInRange(range); 7858 document = converted.document; 7859 range = converted.range; 7860 } else if (blockConfig.exclusive) { 7861 document = document.removeBlockAttributesAtRange(range); 7862 } else if (blockConfig.terminal) { 7863 document = document.removeLastTerminalAttributeAtRange(range); 7864 } else { 7865 document = document.consolidateBlocksAtRange(range); 7866 } 7867 return document.addAttributeAtRange(attributeName, value, range); 7868 } 7869 removeLastListAttributeAtRange(range) { 7870 let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 7871 let { 7872 blockList 7873 } = this; 7874 this.eachBlockAtRange(range, function (block, textRange, index) { 7875 const lastAttributeName = block.getLastAttribute(); 7876 if (!lastAttributeName) { 7877 return; 7878 } 7879 if (!getBlockConfig(lastAttributeName).listAttribute) { 7880 return; 7881 } 7882 if (lastAttributeName === options.exceptAttributeName) { 7883 return; 7884 } 7885 blockList = blockList.editObjectAtIndex(index, () => block.removeAttribute(lastAttributeName)); 7886 }); 7887 return new this.constructor(blockList); 7888 } 7889 removeLastTerminalAttributeAtRange(range) { 7890 let { 7891 blockList 7892 } = this; 7893 this.eachBlockAtRange(range, function (block, textRange, index) { 7894 const lastAttributeName = block.getLastAttribute(); 7895 if (!lastAttributeName) { 7896 return; 7897 } 7898 if (!getBlockConfig(lastAttributeName).terminal) { 7899 return; 7900 } 7901 blockList = blockList.editObjectAtIndex(index, () => block.removeAttribute(lastAttributeName)); 7902 }); 7903 return new this.constructor(blockList); 7904 } 7905 removeBlockAttributesAtRange(range) { 7906 let { 7907 blockList 7908 } = this; 7909 this.eachBlockAtRange(range, function (block, textRange, index) { 7910 if (block.hasAttributes()) { 7911 blockList = blockList.editObjectAtIndex(index, () => block.copyWithoutAttributes()); 7912 } 7913 }); 7914 return new this.constructor(blockList); 7915 } 7916 expandRangeToLineBreaksAndSplitBlocks(range) { 7917 let position; 7918 range = normalizeRange(range); 7919 let [startPosition, endPosition] = range; 7920 const startLocation = this.locationFromPosition(startPosition); 7921 const endLocation = this.locationFromPosition(endPosition); 7922 let document = this; 7923 const startBlock = document.getBlockAtIndex(startLocation.index); 7924 startLocation.offset = startBlock.findLineBreakInDirectionFromPosition("backward", startLocation.offset); 7925 if (startLocation.offset != null) { 7926 position = document.positionFromLocation(startLocation); 7927 document = document.insertBlockBreakAtRange([position, position + 1]); 7928 endLocation.index += 1; 7929 endLocation.offset -= document.getBlockAtIndex(startLocation.index).getLength(); 7930 startLocation.index += 1; 7931 } 7932 startLocation.offset = 0; 7933 if (endLocation.offset === 0 && endLocation.index > startLocation.index) { 7934 endLocation.index -= 1; 7935 endLocation.offset = document.getBlockAtIndex(endLocation.index).getBlockBreakPosition(); 7936 } else { 7937 const endBlock = document.getBlockAtIndex(endLocation.index); 7938 if (endBlock.text.getStringAtRange([endLocation.offset - 1, endLocation.offset]) === "\n") { 7939 endLocation.offset -= 1; 7940 } else { 7941 endLocation.offset = endBlock.findLineBreakInDirectionFromPosition("forward", endLocation.offset); 7942 } 7943 if (endLocation.offset !== endBlock.getBlockBreakPosition()) { 7944 position = document.positionFromLocation(endLocation); 7945 document = document.insertBlockBreakAtRange([position, position + 1]); 7946 } 7947 } 7948 startPosition = document.positionFromLocation(startLocation); 7949 endPosition = document.positionFromLocation(endLocation); 7950 range = normalizeRange([startPosition, endPosition]); 7951 return { 7952 document, 7953 range 7954 }; 7955 } 7956 convertLineBreaksToBlockBreaksInRange(range) { 7957 range = normalizeRange(range); 7958 let [position] = range; 7959 const string = this.getStringAtRange(range).slice(0, -1); 7960 let document = this; 7961 string.replace(/.*?\n/g, function (match) { 7962 position += match.length; 7963 document = document.insertBlockBreakAtRange([position - 1, position]); 7964 }); 7965 return { 7966 document, 7967 range 7968 }; 7969 } 7970 consolidateBlocksAtRange(range) { 7971 range = normalizeRange(range); 7972 const [startPosition, endPosition] = range; 7973 const startIndex = this.locationFromPosition(startPosition).index; 7974 const endIndex = this.locationFromPosition(endPosition).index; 7975 return new this.constructor(this.blockList.consolidateFromIndexToIndex(startIndex, endIndex)); 7976 } 7977 getDocumentAtRange(range) { 7978 range = normalizeRange(range); 7979 const blocks = this.blockList.getSplittableListInRange(range).toArray(); 7980 return new this.constructor(blocks); 7981 } 7982 getStringAtRange(range) { 7983 let endIndex; 7984 const array = range = normalizeRange(range), 7985 endPosition = array[array.length - 1]; 7986 if (endPosition !== this.getLength()) { 7987 endIndex = -1; 7988 } 7989 return this.getDocumentAtRange(range).toString().slice(0, endIndex); 7990 } 7991 getBlockAtIndex(index) { 7992 return this.blockList.getObjectAtIndex(index); 7993 } 7994 getBlockAtPosition(position) { 7995 const { 7996 index 7997 } = this.locationFromPosition(position); 7998 return this.getBlockAtIndex(index); 7999 } 8000 getTextAtIndex(index) { 8001 var _this$getBlockAtIndex; 8002 return (_this$getBlockAtIndex = this.getBlockAtIndex(index)) === null || _this$getBlockAtIndex === void 0 ? void 0 : _this$getBlockAtIndex.text; 8003 } 8004 getTextAtPosition(position) { 8005 const { 8006 index 8007 } = this.locationFromPosition(position); 8008 return this.getTextAtIndex(index); 8009 } 8010 getPieceAtPosition(position) { 8011 const { 8012 index, 8013 offset 8014 } = this.locationFromPosition(position); 8015 return this.getTextAtIndex(index).getPieceAtPosition(offset); 8016 } 8017 getCharacterAtPosition(position) { 8018 const { 8019 index, 8020 offset 8021 } = this.locationFromPosition(position); 8022 return this.getTextAtIndex(index).getStringAtRange([offset, offset + 1]); 8023 } 8024 getLength() { 8025 return this.blockList.getEndPosition(); 8026 } 8027 getBlocks() { 8028 return this.blockList.toArray(); 8029 } 8030 getBlockCount() { 8031 return this.blockList.length; 8032 } 8033 getEditCount() { 8034 return this.editCount; 8035 } 8036 eachBlock(callback) { 8037 return this.blockList.eachObject(callback); 8038 } 8039 eachBlockAtRange(range, callback) { 8040 let block, textRange; 8041 range = normalizeRange(range); 8042 const [startPosition, endPosition] = range; 8043 const startLocation = this.locationFromPosition(startPosition); 8044 const endLocation = this.locationFromPosition(endPosition); 8045 if (startLocation.index === endLocation.index) { 8046 block = this.getBlockAtIndex(startLocation.index); 8047 textRange = [startLocation.offset, endLocation.offset]; 8048 return callback(block, textRange, startLocation.index); 8049 } else { 8050 for (let index = startLocation.index; index <= endLocation.index; index++) { 8051 block = this.getBlockAtIndex(index); 8052 if (block) { 8053 switch (index) { 8054 case startLocation.index: 8055 textRange = [startLocation.offset, block.text.getLength()]; 8056 break; 8057 case endLocation.index: 8058 textRange = [0, endLocation.offset]; 8059 break; 8060 default: 8061 textRange = [0, block.text.getLength()]; 8062 } 8063 callback(block, textRange, index); 8064 } 8065 } 8066 } 8067 } 8068 getCommonAttributesAtRange(range) { 8069 range = normalizeRange(range); 8070 const [startPosition] = range; 8071 if (rangeIsCollapsed(range)) { 8072 return this.getCommonAttributesAtPosition(startPosition); 8073 } else { 8074 const textAttributes = []; 8075 const blockAttributes = []; 8076 this.eachBlockAtRange(range, function (block, textRange) { 8077 if (textRange[0] !== textRange[1]) { 8078 textAttributes.push(block.text.getCommonAttributesAtRange(textRange)); 8079 return blockAttributes.push(attributesForBlock(block)); 8080 } 8081 }); 8082 return Hash.fromCommonAttributesOfObjects(textAttributes).merge(Hash.fromCommonAttributesOfObjects(blockAttributes)).toObject(); 8083 } 8084 } 8085 getCommonAttributesAtPosition(position) { 8086 let key, value; 8087 const { 8088 index, 8089 offset 8090 } = this.locationFromPosition(position); 8091 const block = this.getBlockAtIndex(index); 8092 if (!block) { 8093 return {}; 8094 } 8095 const commonAttributes = attributesForBlock(block); 8096 const attributes = block.text.getAttributesAtPosition(offset); 8097 const attributesLeft = block.text.getAttributesAtPosition(offset - 1); 8098 const inheritableAttributes = Object.keys(text_attributes).filter(key => { 8099 return text_attributes[key].inheritable; 8100 }); 8101 for (key in attributesLeft) { 8102 value = attributesLeft[key]; 8103 if (value === attributes[key] || inheritableAttributes.includes(key)) { 8104 commonAttributes[key] = value; 8105 } 8106 } 8107 return commonAttributes; 8108 } 8109 getRangeOfCommonAttributeAtPosition(attributeName, position) { 8110 const { 8111 index, 8112 offset 8113 } = this.locationFromPosition(position); 8114 const text = this.getTextAtIndex(index); 8115 const [startOffset, endOffset] = Array.from(text.getExpandedRangeForAttributeAtOffset(attributeName, offset)); 8116 const start = this.positionFromLocation({ 8117 index, 8118 offset: startOffset 8119 }); 8120 const end = this.positionFromLocation({ 8121 index, 8122 offset: endOffset 8123 }); 8124 return normalizeRange([start, end]); 8125 } 8126 getBaseBlockAttributes() { 8127 let baseBlockAttributes = this.getBlockAtIndex(0).getAttributes(); 8128 for (let blockIndex = 1; blockIndex < this.getBlockCount(); blockIndex++) { 8129 const blockAttributes = this.getBlockAtIndex(blockIndex).getAttributes(); 8130 const lastAttributeIndex = Math.min(baseBlockAttributes.length, blockAttributes.length); 8131 baseBlockAttributes = (() => { 8132 const result = []; 8133 for (let index = 0; index < lastAttributeIndex; index++) { 8134 if (blockAttributes[index] !== baseBlockAttributes[index]) { 8135 break; 8136 } 8137 result.push(blockAttributes[index]); 8138 } 8139 return result; 8140 })(); 8141 } 8142 return baseBlockAttributes; 8143 } 8144 getAttachmentById(attachmentId) { 8145 for (const attachment of this.getAttachments()) { 8146 if (attachment.id === attachmentId) { 8147 return attachment; 8148 } 8149 } 8150 } 8151 getAttachmentPieces() { 8152 let attachmentPieces = []; 8153 this.blockList.eachObject(_ref => { 8154 let { 8155 text 8156 } = _ref; 8157 return attachmentPieces = attachmentPieces.concat(text.getAttachmentPieces()); 8158 }); 8159 return attachmentPieces; 8160 } 8161 getAttachments() { 8162 return this.getAttachmentPieces().map(piece => piece.attachment); 8163 } 8164 getRangeOfAttachment(attachment) { 8165 let position = 0; 8166 const iterable = this.blockList.toArray(); 8167 for (let index = 0; index < iterable.length; index++) { 8168 const { 8169 text 8170 } = iterable[index]; 8171 const textRange = text.getRangeOfAttachment(attachment); 8172 if (textRange) { 8173 return normalizeRange([position + textRange[0], position + textRange[1]]); 8174 } 8175 position += text.getLength(); 8176 } 8177 } 8178 getLocationRangeOfAttachment(attachment) { 8179 const range = this.getRangeOfAttachment(attachment); 8180 return this.locationRangeFromRange(range); 8181 } 8182 getAttachmentPieceForAttachment(attachment) { 8183 for (const piece of this.getAttachmentPieces()) { 8184 if (piece.attachment === attachment) { 8185 return piece; 8186 } 8187 } 8188 } 8189 findRangesForBlockAttribute(attributeName) { 8190 let position = 0; 8191 const ranges = []; 8192 this.getBlocks().forEach(block => { 8193 const length = block.getLength(); 8194 if (block.hasAttribute(attributeName)) { 8195 ranges.push([position, position + length]); 8196 } 8197 position += length; 8198 }); 8199 return ranges; 8200 } 8201 findRangesForTextAttribute(attributeName) { 8202 let { 8203 withValue 8204 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 8205 let position = 0; 8206 let range = []; 8207 const ranges = []; 8208 const match = function (piece) { 8209 if (withValue) { 8210 return piece.getAttribute(attributeName) === withValue; 8211 } else { 8212 return piece.hasAttribute(attributeName); 8213 } 8214 }; 8215 this.getPieces().forEach(piece => { 8216 const length = piece.getLength(); 8217 if (match(piece)) { 8218 if (range[1] === position) { 8219 range[1] = position + length; 8220 } else { 8221 ranges.push(range = [position, position + length]); 8222 } 8223 } 8224 position += length; 8225 }); 8226 return ranges; 8227 } 8228 locationFromPosition(position) { 8229 const location = this.blockList.findIndexAndOffsetAtPosition(Math.max(0, position)); 8230 if (location.index != null) { 8231 return location; 8232 } else { 8233 const blocks = this.getBlocks(); 8234 return { 8235 index: blocks.length - 1, 8236 offset: blocks[blocks.length - 1].getLength() 8237 }; 8238 } 8239 } 8240 positionFromLocation(location) { 8241 return this.blockList.findPositionAtIndexAndOffset(location.index, location.offset); 8242 } 8243 locationRangeFromPosition(position) { 8244 return normalizeRange(this.locationFromPosition(position)); 8245 } 8246 locationRangeFromRange(range) { 8247 range = normalizeRange(range); 8248 if (!range) return; 8249 const [startPosition, endPosition] = Array.from(range); 8250 const startLocation = this.locationFromPosition(startPosition); 8251 const endLocation = this.locationFromPosition(endPosition); 8252 return normalizeRange([startLocation, endLocation]); 8253 } 8254 rangeFromLocationRange(locationRange) { 8255 let rightPosition; 8256 locationRange = normalizeRange(locationRange); 8257 const leftPosition = this.positionFromLocation(locationRange[0]); 8258 if (!rangeIsCollapsed(locationRange)) { 8259 rightPosition = this.positionFromLocation(locationRange[1]); 8260 } 8261 return normalizeRange([leftPosition, rightPosition]); 8262 } 8263 isEqualTo(document) { 8264 return this.blockList.isEqualTo(document === null || document === void 0 ? void 0 : document.blockList); 8265 } 8266 getTexts() { 8267 return this.getBlocks().map(block => block.text); 8268 } 8269 getPieces() { 8270 const pieces = []; 8271 Array.from(this.getTexts()).forEach(text => { 8272 pieces.push(...Array.from(text.getPieces() || [])); 8273 }); 8274 return pieces; 8275 } 8276 getObjects() { 8277 return this.getBlocks().concat(this.getTexts()).concat(this.getPieces()); 8278 } 8279 toSerializableDocument() { 8280 const blocks = []; 8281 this.blockList.eachObject(block => blocks.push(block.copyWithText(block.text.toSerializableText()))); 8282 return new this.constructor(blocks); 8283 } 8284 toString() { 8285 return this.blockList.toString(); 8286 } 8287 toJSON() { 8288 return this.blockList.toJSON(); 8289 } 8290 toConsole() { 8291 return JSON.stringify(this.blockList.toArray().map(block => JSON.parse(block.text.toConsole()))); 8292 } 8293 } 8294 const attributesForBlock = function (block) { 8295 const attributes = {}; 8296 const attributeName = block.getLastAttribute(); 8297 if (attributeName) { 8298 attributes[attributeName] = true; 8299 } 8300 return attributes; 8301 }; 8302 8303 /* eslint-disable 8304 no-case-declarations, 8305 no-irregular-whitespace, 8306 */ 8307 const pieceForString = function (string) { 8308 let attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 8309 const type = "string"; 8310 string = normalizeSpaces(string); 8311 return { 8312 string, 8313 attributes, 8314 type 8315 }; 8316 }; 8317 const pieceForAttachment = function (attachment) { 8318 let attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 8319 const type = "attachment"; 8320 return { 8321 attachment, 8322 attributes, 8323 type 8324 }; 8325 }; 8326 const blockForAttributes = function () { 8327 let attributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 8328 let htmlAttributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 8329 const text = []; 8330 return { 8331 text, 8332 attributes, 8333 htmlAttributes 8334 }; 8335 }; 8336 const parseTrixDataAttribute = (element, name) => { 8337 try { 8338 return JSON.parse(element.getAttribute("data-trix-".concat(name))); 8339 } catch (error) { 8340 return {}; 8341 } 8342 }; 8343 const getImageDimensions = element => { 8344 const width = element.getAttribute("width"); 8345 const height = element.getAttribute("height"); 8346 const dimensions = {}; 8347 if (width) { 8348 dimensions.width = parseInt(width, 10); 8349 } 8350 if (height) { 8351 dimensions.height = parseInt(height, 10); 8352 } 8353 return dimensions; 8354 }; 8355 class HTMLParser extends BasicObject { 8356 static parse(html, options) { 8357 const parser = new this(html, options); 8358 parser.parse(); 8359 return parser; 8360 } 8361 constructor(html) { 8362 let { 8363 referenceElement
8363 8364 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 8365 super(...arguments); 8366 this.html = html; 8367 this.referenceElement = referenceElement; 8368 this.blocks = []; 8369 this.blockElements = []; 8370 this.processedElements = []; 8371 } 8372 getDocument() { 8373 return Document.fromJSON(this.blocks); 8374 } 8375 8376 // HTML parsing 8377 8378 parse() { 8379 try { 8380 this.createHiddenContainer(); 8381 HTMLSanitizer.setHTML(this.containerElement, this.html
vendor: 189,867 bytes, lines 8381-13261
8381); 8382 const walker = walkTree(this.containerElement, { 8383 usingFilter: nodeFilter 8384 }); 8385 while (walker.nextNode()) { 8386 this.processNode(walker.currentNode); 8387 } 8388 return this.translateBlockElementMarginsToNewlines(); 8389 } finally { 8390 this.removeHiddenContainer(); 8391 } 8392 } 8393 createHiddenContainer() { 8394 if (this.referenceElement) { 8395 this.containerElement = this.referenceElement.cloneNode(false); 8396 this.containerElement.removeAttribute("id"); 8397 this.containerElement.setAttribute("data-trix-internal", ""); 8398 this.containerElement.style.display = "none"; 8399 return this.referenceElement.parentNode.insertBefore(this.containerElement, this.referenceElement.nextSibling); 8400 } else { 8401 this.containerElement = makeElement({ 8402 tagName: "div", 8403 style: { 8404 display: "none" 8405 } 8406 }); 8407 return document.body.appendChild(this.containerElement); 8408 } 8409 } 8410 removeHiddenContainer() { 8411 return removeNode(this.containerElement); 8412 } 8413 processNode(node) { 8414 switch (node.nodeType) { 8415 case Node.TEXT_NODE: 8416 if (!this.isInsignificantTextNode(node)) { 8417 this.appendBlockForTextNode(node); 8418 return this.processTextNode(node); 8419 } 8420 break; 8421 case Node.ELEMENT_NODE: 8422 this.appendBlockForElement(node); 8423 return this.processElement(node); 8424 } 8425 } 8426 appendBlockForTextNode(node) { 8427 const element = node.parentNode; 8428 if (element === this.currentBlockElement && this.isBlockElement(node.previousSibling)) { 8429 return this.appendStringWithAttributes("\n"); 8430 } else if (element === this.containerElement || this.isBlockElement(element)) { 8431 var _this$currentBlock; 8432 const attributes = this.getBlockAttributes(element); 8433 const htmlAttributes = this.getBlockHTMLAttributes(element); 8434 if (!arraysAreEqual(attributes, (_this$currentBlock = this.currentBlock) === null || _this$currentBlock === void 0 ? void 0 : _this$currentBlock.attributes)) { 8435 this.currentBlock = this.appendBlockForAttributesWithElement(attributes, element, htmlAttributes); 8436 this.currentBlockElement = element; 8437 } 8438 } 8439 } 8440 appendBlockForElement(element) { 8441 const elementIsBlockElement = this.isBlockElement(element); 8442 const currentBlockContainsElement = elementContainsNode(this.currentBlockElement, element); 8443 if (elementIsBlockElement && !this.isBlockElement(element.firstChild)) { 8444 if (!this.isInsignificantTextNode(element.firstChild) || !this.isBlockElement(element.firstElementChild)) { 8445 const attributes = this.getBlockAttributes(element); 8446 const htmlAttributes = this.getBlockHTMLAttributes(element); 8447 if (element.firstChild) { 8448 if (!(currentBlockContainsElement && arraysAreEqual(attributes, this.currentBlock.attributes))) { 8449 this.currentBlock = this.appendBlockForAttributesWithElement(attributes, element, htmlAttributes); 8450 this.currentBlockElement = element; 8451 } else { 8452 return this.appendStringWithAttributes("\n"); 8453 } 8454 } 8455 } 8456 } else if (this.currentBlockElement && !currentBlockContainsElement && !elementIsBlockElement) { 8457 const parentBlockElement = this.findParentBlockElement(element); 8458 if (parentBlockElement) { 8459 return this.appendBlockForElement(parentBlockElement); 8460 } else { 8461 this.currentBlock = this.appendEmptyBlock(); 8462 this.currentBlockElement = null; 8463 } 8464 } 8465 } 8466 findParentBlockElement(element) { 8467 let { 8468 parentElement 8469 } = element; 8470 while (parentElement && parentElement !== this.containerElement) { 8471 if (this.isBlockElement(parentElement) && this.blockElements.includes(parentElement)) { 8472 return parentElement; 8473 } else { 8474 parentElement = parentElement.parentElement; 8475 } 8476 } 8477 return null; 8478 } 8479 processTextNode(node) { 8480 let string = node.data; 8481 if (!elementCanDisplayPreformattedText(node.parentNode)) { 8482 var _node$previousSibling; 8483 string = squishBreakableWhitespace(string); 8484 if (stringEndsWithWhitespace((_node$previousSibling = node.previousSibling) === null || _node$previousSibling === void 0 ? void 0 : _node$previousSibling.textContent)) { 8485 string = leftTrimBreakableWhitespace(string); 8486 } 8487 } 8488 return this.appendStringWithAttributes(string, this.getTextAttributes(node.parentNode)); 8489 } 8490 processElement(element) { 8491 let attributes; 8492 if (nodeIsAttachmentElement(element)) { 8493 attributes = parseTrixDataAttribute(element, "attachment"); 8494 if (Object.keys(attributes).length) { 8495 const textAttributes = this.getTextAttributes(element); 8496 this.appendAttachmentWithAttributes(attributes, textAttributes); 8497 // We have everything we need so avoid processing inner nodes 8498 element.innerHTML = ""; 8499 } 8500 return this.processedElements.push(element); 8501 } else { 8502 switch (tagName(element)) { 8503 case "br": 8504 if (!this.isExtraBR(element) && !this.isBlockElement(element.nextSibling)) { 8505 this.appendStringWithAttributes("\n", this.getTextAttributes(element)); 8506 } 8507 return this.processedElements.push(element); 8508 case "img": 8509 attributes = { 8510 url: element.getAttribute("src"), 8511 contentType: "image" 8512 }; 8513 const object = getImageDimensions(element); 8514 for (const key in object) { 8515 const value = object[key]; 8516 attributes[key] = value; 8517 } 8518 this.appendAttachmentWithAttributes(attributes, this.getTextAttributes(element)); 8519 return this.processedElements.push(element); 8520 case "tr": 8521 if (this.needsTableSeparator(element)) { 8522 return this.appendStringWithAttributes(parser.tableRowSeparator); 8523 } 8524 break; 8525 case "td": 8526 if (this.needsTableSeparator(element)) { 8527 return this.appendStringWithAttributes(parser.tableCellSeparator); 8528 } 8529 break; 8530 } 8531 } 8532 } 8533 8534 // Document construction 8535 8536 appendBlockForAttributesWithElement(attributes, element) { 8537 let htmlAttributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; 8538 this.blockElements.push(element); 8539 const block = blockForAttributes(attributes, htmlAttributes); 8540 this.blocks.push(block); 8541 return block; 8542 } 8543 appendEmptyBlock() { 8544 return this.appendBlockForAttributesWithElement([], null); 8545 } 8546 appendStringWithAttributes(string, attributes) { 8547 return this.appendPiece(pieceForString(string, attributes)); 8548 } 8549 appendAttachmentWithAttributes(attachment, attributes) { 8550 return this.appendPiece(pieceForAttachment(attachment, attributes)); 8551 } 8552 appendPiece(piece) { 8553 if (this.blocks.length === 0) { 8554 this.appendEmptyBlock(); 8555 } 8556 return this.blocks[this.blocks.length - 1].text.push(piece); 8557 } 8558 appendStringToTextAtIndex(string, index) { 8559 const { 8560 text 8561 } = this.blocks[index]; 8562 const piece = text[text.length - 1]; 8563 if ((piece === null || piece === void 0 ? void 0 : piece.type) === "string") { 8564 piece.string += string; 8565 } else { 8566 return text.push(pieceForString(string)); 8567 } 8568 } 8569 prependStringToTextAtIndex(string, index) { 8570 const { 8571 text 8572 } = this.blocks[index]; 8573 const piece = text[0]; 8574 if ((piece === null || piece === void 0 ? void 0 : piece.type) === "string") { 8575 piece.string = string + piece.string; 8576 } else { 8577 return text.unshift(pieceForString(string)); 8578 } 8579 } 8580 8581 // Attribute parsing 8582 8583 getTextAttributes(element) { 8584 let value; 8585 const attributes = {}; 8586 for (const attribute in text_attributes) { 8587 const configAttr = text_attributes[attribute]; 8588 if (configAttr.tagName && findClosestElementFromNode(element, { 8589 matchingSelector: configAttr.tagName, 8590 untilNode: this.containerElement 8591 })) { 8592 attributes[attribute] = true; 8593 } else if (configAttr.parser) { 8594 value = configAttr.parser(element); 8595 if (value) { 8596 let attributeInheritedFromBlock = false; 8597 for (const blockElement of this.findBlockElementAncestors(element)) { 8598 if (configAttr.parser(blockElement) === value) { 8599 attributeInheritedFromBlock = true; 8600 break; 8601 } 8602 } 8603 if (!attributeInheritedFromBlock) { 8604 attributes[attribute] = value; 8605 } 8606 } 8607 } else if (configAttr.styleProperty) { 8608 value = element.style[configAttr.styleProperty]; 8609 if (value) { 8610 attributes[attribute] = value; 8611 } 8612 } 8613 } 8614 if (nodeIsAttachmentElement(element)) { 8615 const object = parseTrixDataAttribute(element, "attributes"); 8616 for (const key in object) { 8617 value = object[key]; 8618 attributes[key] = value; 8619 } 8620 } 8621 return attributes; 8622 } 8623 getBlockAttributes(element) { 8624 const attributes$1 = []; 8625 while (element && element !== this.containerElement) { 8626 for (const attribute in attributes) { 8627 const attrConfig = attributes[attribute]; 8628 if (attrConfig.parse !== false) { 8629 if (tagName(element) === attrConfig.tagName) { 8630 var _attrConfig$test; 8631 if ((_attrConfig$test = attrConfig.test) !== null && _attrConfig$test !== void 0 && _attrConfig$test.call(attrConfig, element) || !attrConfig.test) { 8632 attributes$1.push(attribute); 8633 if (attrConfig.listAttribute) { 8634 attributes$1.push(attrConfig.listAttribute); 8635 } 8636 } 8637 } 8638 } 8639 } 8640 element = element.parentNode; 8641 } 8642 return attributes$1.reverse(); 8643 } 8644 getBlockHTMLAttributes(element) { 8645 const attributes$1 = {}; 8646 const blockConfig = Object.values(attributes).find(settings => settings.tagName === tagName(element)); 8647 const allowedAttributes = (blockConfig === null || blockConfig === void 0 ? void 0 : blockConfig.htmlAttributes) || []; 8648 allowedAttributes.forEach(attribute => { 8649 if (element.hasAttribute(attribute)) { 8650 attributes$1[attribute] = element.getAttribute(attribute); 8651 } 8652 }); 8653 return attributes$1; 8654 } 8655 findBlockElementAncestors(element) { 8656 const ancestors = []; 8657 while (element && element !== this.containerElement) { 8658 const tag = tagName(element); 8659 if (getBlockTagNames().includes(tag)) { 8660 ancestors.push(element); 8661 } 8662 element = element.parentNode; 8663 } 8664 return ancestors; 8665 } 8666 8667 // Element inspection 8668 8669 isBlockElement(element) { 8670 if ((element === null || element === void 0 ? void 0 : element.nodeType) !== Node.ELEMENT_NODE) return; 8671 if (nodeIsAttachmentElement(element)) return; 8672 if (findClosestElementFromNode(element, { 8673 matchingSelector: "td", 8674 untilNode: this.containerElement 8675 })) return; 8676 return getBlockTagNames().includes(tagName(element)) || window.getComputedStyle(element).display === "block"; 8677 } 8678 isInsignificantTextNode(node) { 8679 if ((node === null || node === void 0 ? void 0 : node.nodeType) !== Node.TEXT_NODE) return; 8680 if (!stringIsAllBreakableWhitespace(node.data)) return; 8681 const { 8682 parentNode, 8683 previousSibling, 8684 nextSibling 8685 } = node; 8686 if (nodeEndsWithNonWhitespace(parentNode.previousSibling) && !this.isBlockElement(parentNode.previousSibling)) return; 8687 if (elementCanDisplayPreformattedText(parentNode)) return; 8688 return !previousSibling || this.isBlockElement(previousSibling) || !nextSibling || this.isBlockElement(nextSibling); 8689 } 8690 isExtraBR(element) { 8691 return tagName(element) === "br" && this.isBlockElement(element.parentNode) && element.parentNode.lastChild === element; 8692 } 8693 needsTableSeparator(element) { 8694 if (parser.removeBlankTableCells) { 8695 var _element$previousSibl; 8696 const content = (_element$previousSibl = element.previousSibling) === null || _element$previousSibl === void 0 ? void 0 : _element$previousSibl.textContent; 8697 return content && /\S/.test(content); 8698 } else { 8699 return element.previousSibling; 8700 } 8701 } 8702 8703 // Margin translation 8704 8705 translateBlockElementMarginsToNewlines() { 8706 const defaultMargin = this.getMarginOfDefaultBlockElement(); 8707 for (let index = 0; index < this.blocks.length; index++) { 8708 const margin = this.getMarginOfBlockElementAtIndex(index); 8709 if (margin) { 8710 if (margin.top > defaultMargin.top * 2) { 8711 this.prependStringToTextAtIndex("\n", index); 8712 } 8713 if (margin.bottom > defaultMargin.bottom * 2) { 8714 this.appendStringToTextAtIndex("\n", index); 8715 } 8716 } 8717 } 8718 } 8719 getMarginOfBlockElementAtIndex(index) { 8720 const element = this.blockElements[index]; 8721 if (element) { 8722 if (element.textContent) { 8723 if (!getBlockTagNames().includes(tagName(element)) && !this.processedElements.includes(element)) { 8724 return getBlockElementMargin(element); 8725 } 8726 } 8727 } 8728 } 8729 getMarginOfDefaultBlockElement() { 8730 const element = makeElement(attributes.default.tagName); 8731 this.containerElement.appendChild(element); 8732 return getBlockElementMargin(element); 8733 } 8734 } 8735 8736 //Â Helpers 8737 8738 const elementCanDisplayPreformattedText = function (element) { 8739 const { 8740 whiteSpace 8741 } = window.getComputedStyle(element); 8742 return ["pre", "pre-wrap", "pre-line"].includes(whiteSpace); 8743 }; 8744 const nodeEndsWithNonWhitespace = node => node && !stringEndsWithWhitespace(node.textContent); 8745 const getBlockElementMargin = function (element) { 8746 const style = window.getComputedStyle(element); 8747 if (style.display === "block") { 8748 return { 8749 top: parseInt(style.marginTop), 8750 bottom: parseInt(style.marginBottom) 8751 }; 8752 } 8753 }; 8754 const nodeFilter = function (node) { 8755 if (tagName(node) === "style") { 8756 return NodeFilter.FILTER_REJECT; 8757 } else { 8758 return NodeFilter.FILTER_ACCEPT; 8759 } 8760 }; 8761 8762 // Whitespace 8763 8764 const leftTrimBreakableWhitespace = string => string.replace(new RegExp("^".concat(breakableWhitespacePattern.source, "+")), ""); 8765 const stringIsAllBreakableWhitespace = string => new RegExp("^".concat(breakableWhitespacePattern.source, "*$")).test(string); 8766 const stringEndsWithWhitespace = string => /\s$/.test(string); 8767 8768 /* eslint-disable 8769 no-empty, 8770 */ 8771 const unserializableElementSelector = "[data-trix-serialize=false]"; 8772 const unserializableAttributeNames = ["contenteditable", "data-trix-id", "data-trix-store-key", "data-trix-mutable", "data-trix-placeholder", "tabindex"]; 8773 const serializedAttributesAttribute = "data-trix-serialized-attributes"; 8774 const serializedAttributesSelector = "[".concat(serializedAttributesAttribute, "]"); 8775 const blockCommentPattern = new RegExp("<!--block-->", "g"); 8776 const serializers = { 8777 "application/json": function (serializable) { 8778 let document; 8779 if (serializable instanceof Document) { 8780 document = serializable; 8781 } else if (serializable instanceof HTMLElement) { 8782 document = HTMLParser.parse(serializable.innerHTML).getDocument(); 8783 } else { 8784 throw new Error("unserializable object"); 8785 } 8786 return document.toSerializableDocument().toJSONString(); 8787 }, 8788 "text/html": function (serializable) { 8789 let element; 8790 if (serializable instanceof Document) { 8791 element = DocumentView.render(serializable); 8792 } else if (serializable instanceof HTMLElement) { 8793 element = serializable.cloneNode(true); 8794 } else { 8795 throw new Error("unserializable object"); 8796 } 8797 8798 // Remove unserializable elements 8799 Array.from(element.querySelectorAll(unserializableElementSelector)).forEach(el => { 8800 removeNode(el); 8801 }); 8802 8803 // Remove unserializable attributes 8804 unserializableAttributeNames.forEach(attribute => { 8805 Array.from(element.querySelectorAll("[".concat(attribute, "]"))).forEach(el => { 8806 el.removeAttribute(attribute); 8807 }); 8808 }); 8809 8810 // Rewrite elements with serialized attribute overrides 8811 Array.from(element.querySelectorAll(serializedAttributesSelector)).forEach(el => { 8812 try { 8813 const attributes = JSON.parse(el.getAttribute(serializedAttributesAttribute)); 8814 el.removeAttribute(serializedAttributesAttribute); 8815 for (const name in attributes) { 8816 const value = attributes[name]; 8817 el.setAttribute(name, value); 8818 } 8819 } catch (error) {} 8820 }); 8821 return element.innerHTML.replace(blockCommentPattern, ""); 8822 } 8823 }; 8824 const deserializers = { 8825 "application/json": function (string) { 8826 return Document.fromJSONString(string); 8827 }, 8828 "text/html": function (string) { 8829 return HTMLParser.parse(string).getDocument(); 8830 } 8831 }; 8832 const serializeToContentType = function (serializable, contentType) { 8833 const serializer = serializers[contentType]; 8834 if (serializer) { 8835 return serializer(serializable); 8836 } else { 8837 throw new Error("unknown content type: ".concat(contentType)); 8838 } 8839 }; 8840 const deserializeFromContentType = function (string, contentType) { 8841 const deserializer = deserializers[contentType]; 8842 if (deserializer) { 8843 return deserializer(string); 8844 } else { 8845 throw new Error("unknown content type: ".concat(contentType)); 8846 } 8847 }; 8848 8849 var core = /*#__PURE__*/Object.freeze({ 8850 __proto__: null 8851 }); 8852 8853 class ManagedAttachment extends BasicObject { 8854 constructor(attachmentManager, attachment) { 8855 super(...arguments); 8856 this.attachmentManager = attachmentManager; 8857 this.attachment = attachment; 8858 this.id = this.attachment.id; 8859 this.file = this.attachment.file; 8860 } 8861 remove() { 8862 return this.attachmentManager.requestRemovalOfAttachment(this.attachment); 8863 } 8864 } 8865 ManagedAttachment.proxyMethod("attachment.getAttribute"); 8866 ManagedAttachment.proxyMethod("attachment.hasAttribute"); 8867 ManagedAttachment.proxyMethod("attachment.setAttribute"); 8868 ManagedAttachment.proxyMethod("attachment.getAttributes"); 8869 ManagedAttachment.proxyMethod("attachment.setAttributes"); 8870 ManagedAttachment.proxyMethod("attachment.isPending"); 8871 ManagedAttachment.proxyMethod("attachment.isPreviewable"); 8872 ManagedAttachment.proxyMethod("attachment.getURL"); 8873 ManagedAttachment.proxyMethod("attachment.getHref"); 8874 ManagedAttachment.proxyMethod("attachment.getFilename"); 8875 ManagedAttachment.proxyMethod("attachment.getFilesize"); 8876 ManagedAttachment.proxyMethod("attachment.getFormattedFilesize"); 8877 ManagedAttachment.proxyMethod("attachment.getExtension"); 8878 ManagedAttachment.proxyMethod("attachment.getContentType"); 8879 ManagedAttachment.proxyMethod("attachment.getFile"); 8880 ManagedAttachment.proxyMethod("attachment.setFile"); 8881 ManagedAttachment.proxyMethod("attachment.releaseFile"); 8882 ManagedAttachment.proxyMethod("attachment.getUploadProgress"); 8883 ManagedAttachment.proxyMethod("attachment.setUploadProgress"); 8884 8885 class AttachmentManager extends BasicObject { 8886 constructor() { 8887 let attachments = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 8888 super(...arguments); 8889 this.managedAttachments = {}; 8890 Array.from(attachments).forEach(attachment => { 8891 this.manageAttachment(attachment); 8892 }); 8893 } 8894 getAttachments() { 8895 const result = []; 8896 for (const id in this.managedAttachments) { 8897 const attachment = this.managedAttachments[id]; 8898 result.push(attachment); 8899 } 8900 return result; 8901 } 8902 manageAttachment(attachment) { 8903 if (!this.managedAttachments[attachment.id]) { 8904 this.managedAttachments[attachment.id] = new ManagedAttachment(this, attachment); 8905 } 8906 return this.managedAttachments[attachment.id]; 8907 } 8908 attachmentIsManaged(attachment) { 8909 return attachment.id in this.managedAttachments; 8910 } 8911 requestRemovalOfAttachment(attachment) { 8912 if (this.attachmentIsManaged(attachment)) { 8913 var _this$delegate, _this$delegate$attach; 8914 return (_this$delegate = this.delegate) === null || _this$delegate === void 0 || (_this$delegate$attach = _this$delegate.attachmentManagerDidRequestRemovalOfAttachment) === null || _this$delegate$attach === void 0 ? void 0 : _this$delegate$attach.call(_this$delegate, attachment); 8915 } 8916 } 8917 unmanageAttachment(attachment) { 8918 const managedAttachment = this.managedAttachments[attachment.id]; 8919 delete this.managedAttachments[attachment.id]; 8920 return managedAttachment; 8921 } 8922 } 8923 8924 class LineBreakInsertion { 8925 constructor(composition) { 8926 this.composition = composition; 8927 this.document = this.composition.document; 8928 const selectedRange = this.composition.getSelectedRange(); 8929 this.startPosition = selectedRange[0]; 8930 this.endPosition = selectedRange[1]; 8931 this.startLocation = this.document.locationFromPosition(this.startPosition); 8932 this.endLocation = this.document.locationFromPosition(this.endPosition); 8933 this.block = this.document.getBlockAtIndex(this.endLocation.index); 8934 this.breaksOnReturn = this.block.breaksOnReturn(); 8935 this.previousCharacter = this.block.text.getStringAtPosition(this.endLocation.offset - 1); 8936 this.nextCharacter = this.block.text.getStringAtPosition(this.endLocation.offset); 8937 } 8938 shouldInsertBlockBreak() { 8939 if (this.block.hasAttributes() && this.block.isListItem() && !this.block.isEmpty()) { 8940 return this.startLocation.offset !== 0; 8941 } else { 8942 return this.breaksOnReturn && this.nextCharacter !== "\n"; 8943 } 8944 } 8945 shouldBreakFormattedBlock() { 8946 return this.block.hasAttributes() && !this.block.isListItem() && (this.breaksOnReturn && this.nextCharacter === "\n" || this.previousCharacter === "\n"); 8947 } 8948 shouldDecreaseListLevel() { 8949 return this.block.hasAttributes() && this.block.isListItem() && this.block.isEmpty(); 8950 } 8951 shouldPrependListItem() { 8952 return this.block.isListItem() && this.startLocation.offset === 0 && !this.block.isEmpty(); 8953 } 8954 shouldRemoveLastBlockAttribute() { 8955 return this.block.hasAttributes() && !this.block.isListItem() && this.block.isEmpty(); 8956 } 8957 } 8958 8959 const PLACEHOLDER = " "; 8960 class Composition extends BasicObject { 8961 constructor() { 8962 super(...arguments); 8963 this.document = new Document(); 8964 this.attachments = []; 8965 this.currentAttributes = {}; 8966 this.revision = 0; 8967 } 8968 setDocument(document) { 8969 if (!document.isEqualTo(this.document)) { 8970 var _this$delegate, _this$delegate$compos; 8971 this.document = document; 8972 this.refreshAttachments(); 8973 this.revision++; 8974 return (_this$delegate = this.delegate) === null || _this$delegate === void 0 || (_this$delegate$compos = _this$delegate.compositionDidChangeDocument) === null || _this$delegate$compos === void 0 ? void 0 : _this$delegate$compos.call(_this$delegate, document); 8975 } 8976 } 8977 8978 // Snapshots 8979 8980 getSnapshot() { 8981 return { 8982 document: this.document, 8983 selectedRange: this.getSelectedRange() 8984 }; 8985 } 8986 loadSnapshot(_ref) { 8987 var _this$delegate2, _this$delegate2$compo, _this$delegate3, _this$delegate3$compo; 8988 let { 8989 document, 8990 selectedRange 8991 } = _ref; 8992 (_this$delegate2 = this.delegate) === null || _this$delegate2 === void 0 || (_this$delegate2$compo = _this$delegate2.compositionWillLoadSnapshot) === null || _this$delegate2$compo === void 0 || _this$delegate2$compo.call(_this$delegate2); 8993 this.setDocument(document != null ? document : new Document()); 8994 this.setSelection(selectedRange != null ? selectedRange : [0, 0]); 8995 return (_this$delegate3 = this.delegate) === null || _this$delegate3 === void 0 || (_this$delegate3$compo = _this$delegate3.compositionDidLoadSnapshot) === null || _this$delegate3$compo === void 0 ? void 0 : _this$delegate3$compo.call(_this$delegate3); 8996 } 8997 8998 // Responder protocol 8999 9000 insertText(text) { 9001 let { 9002 updatePosition 9003 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { 9004 updatePosition: true 9005 }; 9006 const selectedRange = this.getSelectedRange(); 9007 this.setDocument(this.document.insertTextAtRange(text, selectedRange)); 9008 const startPosition = selectedRange[0]; 9009 const endPosition = startPosition + text.getLength(); 9010 if (updatePosition) { 9011 this.setSelection(endPosition); 9012 } 9013 return this.notifyDelegateOfInsertionAtRange([startPosition, endPosition]); 9014 } 9015 insertBlock() { 9016 let block = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Block(); 9017 const document = new Document([block]); 9018 return this.insertDocument(document); 9019 } 9020 insertDocument() { 9021 let document = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Document(); 9022 const selectedRange = this.getSelectedRange(); 9023 this.setDocument(this.document.insertDocumentAtRange(document, selectedRange)); 9024 const startPosition = selectedRange[0]; 9025 const endPosition = startPosition + document.getLength(); 9026 this.setSelection(endPosition); 9027 return this.notifyDelegateOfInsertionAtRange([startPosition, endPosition]); 9028 } 9029 insertString(string, options) { 9030 const attributes = this.getCurrentTextAttributes(); 9031 const text = Text.textForStringWithAttributes(string, attributes); 9032 return this.insertText(text, options); 9033 } 9034 insertBlockBreak() { 9035 const selectedRange = this.getSelectedRange(); 9036 this.setDocument(this.document.insertBlockBreakAtRange(selectedRange)); 9037 const startPosition = selectedRange[0]; 9038 const endPosition = startPosition + 1; 9039 this.setSelection(endPosition); 9040 return this.notifyDelegateOfInsertionAtRange([startPosition, endPosition]); 9041 } 9042 insertLineBreak() { 9043 const insertion = new LineBreakInsertion(this); 9044 if (insertion.shouldDecreaseListLevel()) { 9045 this.decreaseListLevel(); 9046 return this.setSelection(insertion.startPosition); 9047 } else if (insertion.shouldPrependListItem()) { 9048 const document = new Document([insertion.block.copyWithoutText()]); 9049 return this.insertDocument(document); 9050 } else if (insertion.shouldInsertBlockBreak()) { 9051 return this.insertBlockBreak(); 9052 } else if (insertion.shouldRemoveLastBlockAttribute()) { 9053 return this.removeLastBlockAttribute(); 9054 } else if (insertion.shouldBreakFormattedBlock()) { 9055 return this.breakFormattedBlock(insertion); 9056 } else { 9057 return this.insertString("\n"); 9058 } 9059 } 9060 insertHTML(html) { 9061 const document = HTMLParser.parse(html).getDocument(); 9062 const selectedRange = this.getSelectedRange(); 9063 this.setDocument(this.document.mergeDocumentAtRange(document, selectedRange)); 9064 const startPosition = selectedRange[0]; 9065 const endPosition = startPosition + document.getLength() - 1; 9066 this.setSelection(endPosition); 9067 return this.notifyDelegateOfInsertionAtRange([startPosition, endPosition]); 9068 } 9069 replaceHTML(html) { 9070 const document = HTMLParser.parse(html).getDocument().copyUsingObjectsFromDocument(this.document); 9071 const locationRange = this.getLocationRange({ 9072 strict: false 9073 }); 9074 const selectedRange = this.document.rangeFromLocationRange(locationRange); 9075 this.setDocument(document); 9076 return this.setSelection(selectedRange); 9077 } 9078 insertFile(file) { 9079 return this.insertFiles([file]); 9080 } 9081 insertFiles(files) { 9082 const attachments = []; 9083 Array.from(files).forEach(file => { 9084 var _this$delegate4; 9085 if ((_this$delegate4 = this.delegate) !== null && _this$delegate4 !== void 0 && _this$delegate4.compositionShouldAcceptFile(file)) { 9086 const attachment = Attachment.attachmentForFile(file); 9087 attachments.push(attachment); 9088 } 9089 }); 9090 return this.insertAttachments(attachments); 9091 } 9092 insertAttachment(attachment) { 9093 return this.insertAttachments([attachment]); 9094 } 9095 insertAttachments(attachments$1) { 9096 let text = new Text(); 9097 Array.from(attachments$1).forEach(attachment => { 9098 var _config$attachments$t; 9099 const type = attachment.getType(); 9100 const presentation = (_config$attachments$t = attachments[type]) === null || _config$attachments$t === void 0 ? void 0 : _config$attachments$t.presentation; 9101 const attributes = this.getCurrentTextAttributes(); 9102 if (presentation) { 9103 attributes.presentation = presentation; 9104 } 9105 const attachmentText = Text.textForAttachmentWithAttributes(attachment, attributes); 9106 text = text.appendText(attachmentText); 9107 }); 9108 return this.insertText(text); 9109 } 9110 shouldManageDeletingInDirection(direction) { 9111 const locationRange = this.getLocationRange(); 9112 if (rangeIsCollapsed(locationRange)) { 9113 if (direction === "backward" && locationRange[0].offset === 0) { 9114 return true; 9115 } 9116 if (this.shouldManageMovingCursorInDirection(direction)) { 9117 return true; 9118 } 9119 } else { 9120 if (locationRange[0].index !== locationRange[1].index) { 9121 return true; 9122 } 9123 } 9124 return false; 9125 } 9126 deleteInDirection(direction) { 9127 let { 9128 length 9129 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 9130 let attachment, deletingIntoPreviousBlock, selectionSpansBlocks; 9131 const locationRange = this.getLocationRange(); 9132 let range = this.getSelectedRange(); 9133 const selectionIsCollapsed = rangeIsCollapsed(range); 9134 if (selectionIsCollapsed) { 9135 deletingIntoPreviousBlock = direction === "backward" && locationRange[0].offset === 0; 9136 } else { 9137 selectionSpansBlocks = locationRange[0].index !== locationRange[1].index; 9138 } 9139 if (deletingIntoPreviousBlock) { 9140 if (this.canDecreaseBlockAttributeLevel()) { 9141 const block = this.getBlock(); 9142 if (block.isListItem()) { 9143 this.decreaseListLevel(); 9144 } else { 9145 this.decreaseBlockAttributeLevel(); 9146 } 9147 this.setSelection(range[0]); 9148 if (block.isEmpty()) { 9149 return false; 9150 } 9151 } 9152 } 9153 if (selectionIsCollapsed) { 9154 range = this.getExpandedRangeInDirection(direction, { 9155 length 9156 }); 9157 if (direction === "backward") { 9158 attachment = this.getAttachmentAtRange(range); 9159 } 9160 } 9161 if (attachment) { 9162 this.editAttachment(attachment); 9163 return false; 9164 } else { 9165 this.setDocument(this.document.removeTextAtRange(range)); 9166 this.setSelection(range[0]); 9167 if (deletingIntoPreviousBlock || selectionSpansBlocks) { 9168 return false; 9169 } 9170 } 9171 } 9172 moveTextFromRange(range) { 9173 const [position] = Array.from(this.getSelectedRange()); 9174 this.setDocument(this.document.moveTextFromRangeToPosition(range, position)); 9175 return this.setSelection(position); 9176 } 9177 removeAttachment(attachment) { 9178 const range = this.document.getRangeOfAttachment(attachment); 9179 if (range) { 9180 this.stopEditingAttachment(); 9181 this.setDocument(this.document.removeTextAtRange(range)); 9182 return this.setSelection(range[0]); 9183 } 9184 } 9185 removeLastBlockAttribute() { 9186 const [startPosition, endPosition] = Array.from(this.getSelectedRange()); 9187 const block = this.document.getBlockAtPosition(endPosition); 9188 this.removeCurrentAttribute(block.getLastAttribute()); 9189 return this.setSelection(startPosition); 9190 } 9191 insertPlaceholder() { 9192 this.placeholderPosition = this.getPosition(); 9193 return this.insertString(PLACEHOLDER); 9194 } 9195 selectPlaceholder() { 9196 if (this.placeholderPosition != null) { 9197 this.setSelectedRange([this.placeholderPosition, this.placeholderPosition + PLACEHOLDER.length]); 9198 return this.getSelectedRange(); 9199 } 9200 } 9201 forgetPlaceholder() { 9202 this.placeholderPosition = null; 9203 } 9204 9205 // Current attributes 9206 9207 hasCurrentAttribute(attributeName) { 9208 const value = this.currentAttributes[attributeName]; 9209 return value != null && value !== false; 9210 } 9211 toggleCurrentAttribute(attributeName) { 9212 const value = !this.currentAttributes[attributeName]; 9213 if (value) { 9214 return this.setCurrentAttribute(attributeName, value); 9215 } else { 9216 return this.removeCurrentAttribute(attributeName); 9217 } 9218 } 9219 canSetCurrentAttribute(attributeName) { 9220 if (getBlockConfig(attributeName)) { 9221 return this.canSetCurrentBlockAttribute(attributeName); 9222 } else { 9223 return this.canSetCurrentTextAttribute(attributeName); 9224 } 9225 } 9226 canSetCurrentTextAttribute(attributeName) { 9227 const document = this.getSelectedDocument(); 9228 if (!document) return; 9229 for (const attachment of Array.from(document.getAttachments())) { 9230 if (!attachment.hasContent()) { 9231 return false; 9232 } 9233 } 9234 return true; 9235 } 9236 canSetCurrentBlockAttribute(attributeName) { 9237 const block = this.getBlock(); 9238 if (!block) return; 9239 return !block.isTerminalBlock(); 9240 } 9241 setCurrentAttribute(attributeName, value) { 9242 if (getBlockConfig(attributeName)) { 9243 return this.setBlockAttribute(attributeName, value); 9244 } else { 9245 this.setTextAttribute(attributeName, value); 9246 this.currentAttributes[attributeName] = value; 9247 return this.notifyDelegateOfCurrentAttributesChange(); 9248 } 9249 } 9250 setHTMLAtributeAtPosition(position, attributeName, value) { 9251 var _getBlockConfig; 9252 const block = this.document.getBlockAtPosition(position); 9253 const allowedHTMLAttributes = (_getBlockConfig = getBlockConfig(block.getLastAttribute())) === null || _getBlockConfig === void 0 ? void 0 : _getBlockConfig.htmlAttributes; 9254 if (block && allowedHTMLAttributes !== null && allowedHTMLAttributes !== void 0 && allowedHTMLAttributes.includes(attributeName)) { 9255 const newDocument = this.document.setHTMLAttributeAtPosition(position, attributeName, value); 9256 this.setDocument(newDocument); 9257 } 9258 } 9259 setTextAttribute(attributeName, value) { 9260 const selectedRange = this.getSelectedRange(); 9261 if (!selectedRange) return; 9262 const [startPosition, endPosition] = Array.from(selectedRange); 9263 if (startPosition === endPosition) { 9264 if (attributeName === "href") { 9265 const text = Text.textForStringWithAttributes(value, { 9266 href: value 9267 }); 9268 return this.insertText(text); 9269 } 9270 } else { 9271 return this.setDocument(this.document.addAttributeAtRange(attributeName, value, selectedRange)); 9272 } 9273 } 9274 setBlockAttribute(attributeName, value) { 9275 const selectedRange = this.getSelectedRange(); 9276 if (this.canSetCurrentAttribute(attributeName)) { 9277 this.setDocument(this.document.applyBlockAttributeAtRange(attributeName, value, selectedRange)); 9278 return this.setSelection(selectedRange); 9279 } 9280 } 9281 removeCurrentAttribute(attributeName) { 9282 if (getBlockConfig(attributeName)) { 9283 this.removeBlockAttribute(attributeName); 9284 return this.updateCurrentAttributes(); 9285 } else { 9286 this.removeTextAttribute(attributeName); 9287 delete this.currentAttributes[attributeName]; 9288 return this.notifyDelegateOfCurrentAttributesChange(); 9289 } 9290 } 9291 removeTextAttribute(attributeName) { 9292 const selectedRange = this.getSelectedRange(); 9293 if (!selectedRange) return; 9294 return this.setDocument(this.document.removeAttributeAtRange(attributeName, selectedRange)); 9295 } 9296 removeBlockAttribute(attributeName) { 9297 const selectedRange = this.getSelectedRange(); 9298 if (!selectedRange) return; 9299 return this.setDocument(this.document.removeAttributeAtRange(attributeName, selectedRange)); 9300 } 9301 canDecreaseNestingLevel() { 9302 var _this$getBlock; 9303 return ((_this$getBlock = this.getBlock()) === null || _this$getBlock === void 0 ? void 0 : _this$getBlock.getNestingLevel()) > 0; 9304 } 9305 canIncreaseNestingLevel() { 9306 var _getBlockConfig2; 9307 const block = this.getBlock(); 9308 if (!block) return; 9309 if ((_getBlockConfig2 = getBlockConfig(block.getLastNestableAttribute())) !== null && _getBlockConfig2 !== void 0 && _getBlockConfig2.listAttribute) { 9310 const previousBlock = this.getPreviousBlock(); 9311 if (previousBlock) { 9312 return arrayStartsWith(previousBlock.getListItemAttributes(), block.getListItemAttributes()); 9313 } 9314 } else { 9315 return block.getNestingLevel() > 0; 9316 } 9317 } 9318 decreaseNestingLevel() { 9319 const block = this.getBlock(); 9320 if (!block) return; 9321 return this.setDocument(this.document.replaceBlock(block, block.decreaseNestingLevel())); 9322 } 9323 increaseNestingLevel() { 9324 const block = this.getBlock(); 9325 if (!block) return; 9326 return this.setDocument(this.document.replaceBlock(block, block.increaseNestingLevel())); 9327 } 9328 canDecreaseBlockAttributeLevel() { 9329 var _this$getBlock2; 9330 return ((_this$getBlock2 = this.getBlock()) === null || _this$getBlock2 === void 0 ? void 0 : _this$getBlock2.getAttributeLevel()) > 0; 9331 } 9332 decreaseBlockAttributeLevel() { 9333 var _this$getBlock3; 9334 const attribute = (_this$getBlock3 = this.getBlock()) === null || _this$getBlock3 === void 0 ? void 0 : _this$getBlock3.getLastAttribute(); 9335 if (attribute) { 9336 return this.removeCurrentAttribute(attribute); 9337 } 9338 } 9339 decreaseListLevel() { 9340 let [startPosition] = Array.from(this.getSelectedRange()); 9341 const { 9342 index 9343 } = this.document.locationFromPosition(startPosition); 9344 let endIndex = index; 9345 const attributeLevel = this.getBlock().getAttributeLevel(); 9346 let block = this.document.getBlockAtIndex(endIndex + 1); 9347 while (block) { 9348 if (!block.isListItem() || block.getAttributeLevel() <= attributeLevel) { 9349 break; 9350 } 9351 endIndex++; 9352 block = this.document.getBlockAtIndex(endIndex + 1); 9353 } 9354 startPosition = this.document.positionFromLocation({ 9355 index, 9356 offset: 0 9357 }); 9358 const endPosition = this.document.positionFromLocation({ 9359 index: endIndex, 9360 offset: 0 9361 }); 9362 return this.setDocument(this.document.removeLastListAttributeAtRange([startPosition, endPosition])); 9363 } 9364 updateCurrentAttributes() { 9365 const selectedRange = this.getSelectedRange({ 9366 ignoreLock: true 9367 }); 9368 if (selectedRange) { 9369 const currentAttributes = this.document.getCommonAttributesAtRange(selectedRange); 9370 Array.from(getAllAttributeNames()).forEach(attributeName => { 9371 if (!currentAttributes[attributeName]) { 9372 if (!this.canSetCurrentAttribute(attributeName)) { 9373 currentAttributes[attributeName] = false; 9374 } 9375 } 9376 }); 9377 if (!objectsAreEqual(currentAttributes, this.currentAttributes)) { 9378 this.currentAttributes = currentAttributes; 9379 return this.notifyDelegateOfCurrentAttributesChange(); 9380 } 9381 } 9382 } 9383 getCurrentAttributes() { 9384 return extend.call({}, this.currentAttributes); 9385 } 9386 getCurrentTextAttributes() { 9387 const attributes = {}; 9388 for (const key in this.currentAttributes) { 9389 const value = this.currentAttributes[key]; 9390 if (value !== false) { 9391 if (getTextConfig(key)) { 9392 attributes[key] = value; 9393 } 9394 } 9395 } 9396 return attributes; 9397 } 9398 9399 // Selection freezing 9400 9401 freezeSelection() { 9402 return this.setCurrentAttribute("frozen", true); 9403 } 9404 thawSelection() { 9405 return this.removeCurrentAttribute("frozen"); 9406 } 9407 hasFrozenSelection() { 9408 return this.hasCurrentAttribute("frozen"); 9409 } 9410 setSelection(selectedRange) { 9411 var _this$delegate5; 9412 const locationRange = this.document.locationRangeFromRange(selectedRange); 9413 return (_this$delegate5 = this.delegate) === null || _this$delegate5 === void 0 ? void 0 : _this$delegate5.compositionDidRequestChangingSelectionToLocationRange(locationRange); 9414 } 9415 getSelectedRange() { 9416 const locationRange = this.getLocationRange(); 9417 if (locationRange) { 9418 return this.document.rangeFromLocationRange(locationRange); 9419 } 9420 } 9421 setSelectedRange(selectedRange) { 9422 const locationRange = this.document.locationRangeFromRange(selectedRange); 9423 return this.getSelectionManager().setLocationRange(locationRange); 9424 } 9425 getPosition() { 9426 const locationRange = this.getLocationRange(); 9427 if (locationRange) { 9428 return this.document.positionFromLocation(locationRange[0]); 9429 } 9430 } 9431 getLocationRange(options) { 9432 if (this.targetLocationRange) { 9433 return this.targetLocationRange; 9434 } else { 9435 return this.getSelectionManager().getLocationRange(options) || normalizeRange({ 9436 index: 0, 9437 offset: 0 9438 }); 9439 } 9440 } 9441 withTargetLocationRange(locationRange, fn) { 9442 let result; 9443 this.targetLocationRange = locationRange; 9444 try { 9445 result = fn(); 9446 } finally { 9447 this.targetLocationRange = null; 9448 } 9449 return result; 9450 } 9451 withTargetRange(range, fn) { 9452 const locationRange = this.document.locationRangeFromRange(range); 9453 return this.withTargetLocationRange(locationRange, fn); 9454 } 9455 withTargetDOMRange(domRange, fn) { 9456 const locationRange = this.createLocationRangeFromDOMRange(domRange, { 9457 strict: false 9458 }); 9459 return this.withTargetLocationRange(locationRange, fn); 9460 } 9461 getExpandedRangeInDirection(direction) { 9462 let { 9463 length 9464 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 9465 let [startPosition, endPosition] = Array.from(this.getSelectedRange()); 9466 if (direction === "backward") { 9467 if (length) { 9468 startPosition -= length; 9469 } else { 9470 startPosition = this.translateUTF16PositionFromOffset(startPosition, -1); 9471 } 9472 } else { 9473 if (length) { 9474 endPosition += length; 9475 } else { 9476 endPosition = this.translateUTF16PositionFromOffset(endPosition, 1); 9477 } 9478 } 9479 return normalizeRange([startPosition, endPosition]); 9480 } 9481 shouldManageMovingCursorInDirection(direction) { 9482 if (this.editingAttachment) { 9483 return true; 9484 } 9485 const range = this.getExpandedRangeInDirection(direction); 9486 return this.getAttachmentAtRange(range) != null; 9487 } 9488 moveCursorInDirection(direction) { 9489 let canEditAttachment, range; 9490 if (this.editingAttachment) { 9491 range = this.document.getRangeOfAttachment(this.editingAttachment); 9492 } else { 9493 const selectedRange = this.getSelectedRange(); 9494 range = this.getExpandedRangeInDirection(direction); 9495 canEditAttachment = !rangesAreEqual(selectedRange, range); 9496 } 9497 if (direction === "backward") { 9498 this.setSelectedRange(range[0]); 9499 } else { 9500 this.setSelectedRange(range[1]); 9501 } 9502 if (canEditAttachment) { 9503 const attachment = this.getAttachmentAtRange(range); 9504 if (attachment) { 9505 return this.editAttachment(attachment); 9506 } 9507 } 9508 } 9509 expandSelectionInDirection(direction) { 9510 let { 9511 length 9512 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 9513 const range = this.getExpandedRangeInDirection(direction, { 9514 length 9515 }); 9516 return this.setSelectedRange(range); 9517 } 9518 expandSelectionForEditing() { 9519 if (this.hasCurrentAttribute("href")) { 9520 return this.expandSelectionAroundCommonAttribute("href"); 9521 } 9522 } 9523 expandSelectionAroundCommonAttribute(attributeName) { 9524 const position = this.getPosition(); 9525 const range = this.document.getRangeOfCommonAttributeAtPosition(attributeName, position); 9526 return this.setSelectedRange(range); 9527 } 9528 selectionContainsAttachments() { 9529 var _this$getSelectedAtta; 9530 return ((_this$getSelectedAtta = this.getSelectedAttachments()) === null || _this$getSelectedAtta === void 0 ? void 0 : _this$getSelectedAtta.length) > 0; 9531 } 9532 selectionIsInCursorTarget() { 9533 return this.editingAttachment || this.positionIsCursorTarget(this.getPosition()); 9534 } 9535 positionIsCursorTarget(position) { 9536 const location = this.document.locationFromPosition(position); 9537 if (location) { 9538 return this.locationIsCursorTarget(location); 9539 } 9540 } 9541 positionIsBlockBreak(position) { 9542 var _this$document$getPie; 9543 return (_this$document$getPie = this.document.getPieceAtPosition(position)) === null || _this$document$getPie === void 0 ? void 0 : _this$document$getPie.isBlockBreak(); 9544 } 9545 getSelectedDocument() { 9546 const selectedRange = this.getSelectedRange(); 9547 if (selectedRange) { 9548 return this.document.getDocumentAtRange(selectedRange); 9549 } 9550 } 9551 getSelectedAttachments() { 9552 var _this$getSelectedDocu; 9553 return (_this$getSelectedDocu = this.getSelectedDocument()) === null || _this$getSelectedDocu === void 0 ? void 0 : _this$getSelectedDocu.getAttachments(); 9554 } 9555 9556 // Attachments 9557 9558 getAttachments() { 9559 return this.attachments.slice(0); 9560 } 9561 refreshAttachments() { 9562 const attachments = this.document.getAttachments(); 9563 const { 9564 added, 9565 removed 9566 } = summarizeArrayChange(this.attachments, attachments); 9567 this.attachments = attachments; 9568 Array.from(removed).forEach(attachment => { 9569 var _this$delegate6, _this$delegate6$compo; 9570 attachment.delegate = null; 9571 (_this$delegate6 = this.delegate) === null || _this$delegate6 === void 0 || (_this$delegate6$compo = _this$delegate6.compositionDidRemoveAttachment) === null || _this$delegate6$compo === void 0 || _this$delegate6$compo.call(_this$delegate6, attachment); 9572 }); 9573 return (() => { 9574 const result = []; 9575 Array.from(added).forEach(attachment => { 9576 var _this$delegate7, _this$delegate7$compo; 9577 attachment.delegate = this; 9578 result.push((_this$delegate7 = this.delegate) === null || _this$delegate7 === void 0 || (_this$delegate7$compo = _this$delegate7.compositionDidAddAttachment) === null || _this$delegate7$compo === void 0 ? void 0 : _this$delegate7$compo.call(_this$delegate7, attachment)); 9579 }); 9580 return result; 9581 })(); 9582 } 9583 9584 // Attachment delegate 9585 9586 attachmentDidChangeAttributes(attachment) { 9587 var _this$delegate8, _this$delegate8$compo; 9588 this.revision++; 9589 return (_this$delegate8 = this.delegate) === null || _this$delegate8 === void 0 || (_this$delegate8$compo = _this$delegate8.compositionDidEditAttachment) === null || _this$delegate8$compo === void 0 ? void 0 : _this$delegate8$compo.call(_this$delegate8, attachment); 9590 } 9591 attachmentDidChangePreviewURL(attachment) { 9592 var _this$delegate9, _this$delegate9$compo; 9593 this.revision++; 9594 return (_this$delegate9 = this.delegate) === null || _this$delegate9 === void 0 || (_this$delegate9$compo = _this$delegate9.compositionDidChangeAttachmentPreviewURL) === null || _this$delegate9$compo === void 0 ? void 0 : _this$delegate9$compo.call(_this$delegate9, attachment); 9595 } 9596 9597 // Attachment editing 9598 9599 editAttachment(attachment, options) { 9600 var _this$delegate10, _this$delegate10$comp; 9601 if (attachment === this.editingAttachment) return; 9602 this.stopEditingAttachment(); 9603 this.editingAttachment = attachment; 9604 return (_this$delegate10 = this.delegate) === null || _this$delegate10 === void 0 || (_this$delegate10$comp = _this$delegate10.compositionDidStartEditingAttachment) === null || _this$delegate10$comp === void 0 ? void 0 : _this$delegate10$comp.call(_this$delegate10, this.editingAttachment, options); 9605 } 9606 stopEditingAttachment() { 9607 var _this$delegate11, _this$delegate11$comp; 9608 if (!this.editingAttachment) return; 9609 (_this$delegate11 = this.delegate) === null || _this$delegate11 === void 0 || (_this$delegate11$comp = _this$delegate11.compositionDidStopEditingAttachment) === null || _this$delegate11$comp === void 0 || _this$delegate11$comp.call(_this$delegate11, this.editingAttachment); 9610 this.editingAttachment = null; 9611 } 9612 updateAttributesForAttachment(attributes, attachment) { 9613 return this.setDocument(this.document.updateAttributesForAttachment(attributes, attachment)); 9614 } 9615 removeAttributeForAttachment(attribute, attachment) { 9616 return this.setDocument(this.document.removeAttributeForAttachment(attribute, attachment)); 9617 } 9618 9619 // Private 9620 9621 breakFormattedBlock(insertion) { 9622 let { 9623 document 9624 } = insertion; 9625 const { 9626 block 9627 } = insertion; 9628 let position = insertion.startPosition; 9629 let range = [position - 1, position]; 9630 if (block.getBlockBreakPosition() === insertion.startLocation.offset) { 9631 if (block.breaksOnReturn() && insertion.nextCharacter === "\n") { 9632 position += 1; 9633 } else { 9634 document = document.removeTextAtRange(range); 9635 } 9636 range = [position, position]; 9637 } else if (insertion.nextCharacter === "\n") { 9638 if (insertion.previousCharacter === "\n") { 9639 range = [position - 1, position + 1]; 9640 } else { 9641 range = [position, position + 1]; 9642 position += 1; 9643 } 9644 } else if (insertion.startLocation.offset - 1 !== 0) { 9645 position += 1; 9646 } 9647 const newDocument = new Document([block.removeLastAttribute().copyWithoutText()]); 9648 this.setDocument(document.insertDocumentAtRange(newDocument, range)); 9649 return this.setSelection(position); 9650 } 9651 getPreviousBlock() { 9652 const locationRange = this.getLocationRange(); 9653 if (locationRange) { 9654 const { 9655 index 9656 } = locationRange[0]; 9657 if (index > 0) { 9658 return this.document.getBlockAtIndex(index - 1); 9659 } 9660 } 9661 } 9662 getBlock() { 9663 const locationRange = this.getLocationRange(); 9664 if (locationRange) { 9665 return this.document.getBlockAtIndex(locationRange[0].index); 9666 } 9667 } 9668 getAttachmentAtRange(range) { 9669 const document = this.document.getDocumentAtRange(range); 9670 if (document.toString() === "".concat(OBJECT_REPLACEMENT_CHARACTER, "\n")) { 9671 return document.getAttachments()[0]; 9672 } 9673 } 9674 notifyDelegateOfCurrentAttributesChange() { 9675 var _this$delegate12, _this$delegate12$comp; 9676 return (_this$delegate12 = this.delegate) === null || _this$delegate12 === void 0 || (_this$delegate12$comp = _this$delegate12.compositionDidChangeCurrentAttributes) === null || _this$delegate12$comp === void 0 ? void 0 : _this$delegate12$comp.call(_this$delegate12, this.currentAttributes); 9677 } 9678 notifyDelegateOfInsertionAtRange(range) { 9679 var _this$delegate13, _this$delegate13$comp; 9680 return (_this$delegate13 = this.delegate) === null || _this$delegate13 === void 0 || (_this$delegate13$comp = _this$delegate13.compositionDidPerformInsertionAtRange) === null || _this$delegate13$comp === void 0 ? void 0 : _this$delegate13$comp.call(_this$delegate13, range); 9681 } 9682 translateUTF16PositionFromOffset(position, offset) { 9683 const utf16string = this.document.toUTF16String(); 9684 const utf16position = utf16string.offsetFromUCS2Offset(position); 9685 return utf16string.offsetToUCS2Offset(utf16position + offset); 9686 } 9687 } 9688 Composition.proxyMethod("getSelectionManager().getPointRange"); 9689 Composition.proxyMethod("getSelectionManager().setLocationRangeFromPointRange"); 9690 Composition.proxyMethod("getSelectionManager().createLocationRangeFromDOMRange"); 9691 Composition.proxyMethod("getSelectionManager().locationIsCursorTarget"); 9692 Composition.proxyMethod("getSelectionManager().selectionIsExpanded"); 9693 Composition.proxyMethod("delegate?.getSelectionManager"); 9694 9695 class UndoManager extends BasicObject { 9696 constructor(composition) { 9697 super(...arguments); 9698 this.composition = composition; 9699 this.undoEntries = []; 9700 this.redoEntries = []; 9701 } 9702 recordUndoEntry(description) { 9703 let { 9704 context, 9705 consolidatable 9706 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 9707 const previousEntry = this.undoEntries.slice(-1)[0]; 9708 if (!consolidatable || !entryHasDescriptionAndContext(previousEntry, description, context)) { 9709 const undoEntry = this.createEntry({ 9710 description, 9711 context 9712 }); 9713 this.undoEntries.push(undoEntry); 9714 this.redoEntries = []; 9715 } 9716 } 9717 undo() { 9718 const undoEntry = this.undoEntries.pop(); 9719 if (undoEntry) { 9720 const redoEntry = this.createEntry(undoEntry); 9721 this.redoEntries.push(redoEntry); 9722 return this.composition.loadSnapshot(undoEntry.snapshot); 9723 } 9724 } 9725 redo() { 9726 const redoEntry = this.redoEntries.pop(); 9727 if (redoEntry) { 9728 const undoEntry = this.createEntry(redoEntry); 9729 this.undoEntries.push(undoEntry); 9730 return this.composition.loadSnapshot(redoEntry.snapshot); 9731 } 9732 } 9733 canUndo() { 9734 return this.undoEntries.length > 0; 9735 } 9736 canRedo() { 9737 return this.redoEntries.length > 0; 9738 } 9739 9740 // Private 9741 9742 createEntry() { 9743 let { 9744 description, 9745 context 9746 } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 9747 return { 9748 description: description === null || description === void 0 ? void 0 : description.toString(), 9749 context: JSON.stringify(context), 9750 snapshot: this.composition.getSnapshot() 9751 }; 9752 } 9753 } 9754 const entryHasDescriptionAndContext = (entry, description, context) => (entry === null || entry === void 0 ? void 0 : entry.description) === (description === null || description === void 0 ? void 0 : description.toString()) && (entry === null || entry === void 0 ? void 0 : entry.context) === JSON.stringify(context); 9755 9756 const BLOCK_ATTRIBUTE_NAME = "attachmentGallery"; 9757 const TEXT_ATTRIBUTE_NAME = "presentation"; 9758 const TEXT_ATTRIBUTE_VALUE = "gallery"; 9759 class Filter { 9760 constructor(snapshot) { 9761 this.document = snapshot.document; 9762 this.selectedRange = snapshot.selectedRange; 9763 } 9764 perform() { 9765 this.removeBlockAttribute(); 9766 return this.applyBlockAttribute(); 9767 } 9768 getSnapshot() { 9769 return { 9770 document: this.document, 9771 selectedRange: this.selectedRange 9772 }; 9773 } 9774 9775 // Private 9776 9777 removeBlockAttribute() { 9778 return this.findRangesOfBlocks().map(range => this.document = this.document.removeAttributeAtRange(BLOCK_ATTRIBUTE_NAME, range)); 9779 } 9780 applyBlockAttribute() { 9781 let offset = 0; 9782 this.findRangesOfPieces().forEach(range => { 9783 if (range[1] - range[0] > 1) { 9784 range[0] += offset; 9785 range[1] += offset; 9786 if (this.document.getCharacterAtPosition(range[1]) !== "\n") { 9787 this.document = this.document.insertBlockBreakAtRange(range[1]); 9788 if (range[1] < this.selectedRange[1]) { 9789 this.moveSelectedRangeForward(); 9790 } 9791 range[1]++; 9792 offset++; 9793 } 9794 if (range[0] !== 0) { 9795 if (this.document.getCharacterAtPosition(range[0] - 1) !== "\n") { 9796 this.document = this.document.insertBlockBreakAtRange(range[0]); 9797 if (range[0] < this.selectedRange[0]) { 9798 this.moveSelectedRangeForward(); 9799 } 9800 range[0]++; 9801 offset++; 9802 } 9803 } 9804 this.document = this.document.applyBlockAttributeAtRange(BLOCK_ATTRIBUTE_NAME, true, range); 9805 } 9806 }); 9807 } 9808 findRangesOfBlocks() { 9809 return this.document.findRangesForBlockAttribute(BLOCK_ATTRIBUTE_NAME); 9810 } 9811 findRangesOfPieces() { 9812 return this.document.findRangesForTextAttribute(TEXT_ATTRIBUTE_NAME, { 9813 withValue: TEXT_ATTRIBUTE_VALUE 9814 }); 9815 } 9816 moveSelectedRangeForward() { 9817 this.selectedRange[0] += 1; 9818 this.selectedRange[1] += 1; 9819 } 9820 } 9821 9822 const attachmentGalleryFilter = function (snapshot) { 9823 const filter = new Filter(snapshot); 9824 filter.perform(); 9825 return filter.getSnapshot(); 9826 }; 9827 9828 const DEFAULT_FILTERS = [attachmentGalleryFilter]; 9829 class Editor { 9830 constructor(composition, selectionManager, element) { 9831 this.insertFiles = this.insertFiles.bind(this); 9832 this.composition = composition; 9833 this.selectionManager = selectionManager; 9834 this.element = element; 9835 this.undoManager = new UndoManager(this.composition); 9836 this.filters = DEFAULT_FILTERS.slice(0); 9837 } 9838 loadDocument(document) { 9839 return this.loadSnapshot({ 9840 document, 9841 selectedRange: [0, 0] 9842 }); 9843 } 9844 loadHTML() { 9845 let html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; 9846 const document = HTMLParser.parse(html, { 9847 referenceElement: this.element 9848 }).getDocument(); 9849 return this.loadDocument(document); 9850 } 9851 loadJSON(_ref) { 9852 let { 9853 document, 9854 selectedRange 9855 } = _ref; 9856 document = Document.fromJSON(document); 9857 return this.loadSnapshot({ 9858 document, 9859 selectedRange 9860 }); 9861 } 9862 loadSnapshot(snapshot) { 9863 this.undoManager = new UndoManager(this.composition); 9864 return this.composition.loadSnapshot(snapshot); 9865 } 9866 getDocument() { 9867 return this.composition.document; 9868 } 9869 getSelectedDocument() { 9870 return this.composition.getSelectedDocument(); 9871 } 9872 getSnapshot() { 9873 return this.composition.getSnapshot(); 9874 } 9875 toJSON() { 9876 return this.getSnapshot(); 9877 } 9878 9879 // Document manipulation 9880 9881 deleteInDirection(direction) { 9882 return this.composition.deleteInDirection(direction); 9883 } 9884 insertAttachment(attachment) { 9885 return this.composition.insertAttachment(attachment); 9886 } 9887 insertAttachments(attachments) { 9888 return this.composition.insertAttachments(attachments); 9889 } 9890 insertDocument(document) { 9891 return this.composition.insertDocument(document); 9892 } 9893 insertFile(file) { 9894 return this.composition.insertFile(file); 9895 } 9896 insertFiles(files) { 9897 return this.composition.insertFiles(files); 9898 } 9899 insertHTML(html) { 9900 return this.composition.insertHTML(html); 9901 } 9902 insertString(string) { 9903 return this.composition.insertString(string); 9904 } 9905 insertText(text) { 9906 return this.composition.insertText(text); 9907 } 9908 insertLineBreak() { 9909 return this.composition.insertLineBreak(); 9910 } 9911 9912 // Selection 9913 9914 getSelectedRange() { 9915 return this.composition.getSelectedRange(); 9916 } 9917 getPosition() { 9918 return this.composition.getPosition(); 9919 } 9920 getClientRectAtPosition(position) { 9921 const locationRange = this.getDocument().locationRangeFromRange([position, position + 1]); 9922 return this.selectionManager.getClientRectAtLocationRange(locationRange); 9923 } 9924 expandSelectionInDirection(direction) { 9925 return this.composition.expandSelectionInDirection(direction); 9926 } 9927 moveCursorInDirection(direction) { 9928 return this.composition.moveCursorInDirection(direction); 9929 } 9930 setSelectedRange(selectedRange) { 9931 return this.composition.setSelectedRange(selectedRange); 9932 } 9933 9934 // Attributes 9935 9936 activateAttribute(name) { 9937 let value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; 9938 return this.composition.setCurrentAttribute(name, value); 9939 } 9940 attributeIsActive(name) { 9941 return this.composition.hasCurrentAttribute(name); 9942 } 9943 canActivateAttribute(name) { 9944 return this.composition.canSetCurrentAttribute(name); 9945 } 9946 deactivateAttribute(name) { 9947 return this.composition.removeCurrentAttribute(name); 9948 } 9949 9950 // HTML attributes 9951 setHTMLAtributeAtPosition(position, name, value) { 9952 this.composition.setHTMLAtributeAtPosition(position, name, value); 9953 } 9954 9955 // Nesting level 9956 9957 canDecreaseNestingLevel() { 9958 return this.composition.canDecreaseNestingLevel(); 9959 } 9960 canIncreaseNestingLevel() { 9961 return this.composition.canIncreaseNestingLevel(); 9962 } 9963 decreaseNestingLevel() { 9964 if (this.canDecreaseNestingLevel()) { 9965 return this.composition.decreaseNestingLevel(); 9966 } 9967 } 9968 increaseNestingLevel() { 9969 if (this.canIncreaseNestingLevel()) { 9970 return this.composition.increaseNestingLevel(); 9971 } 9972 } 9973 9974 // Undo/redo 9975 9976 canRedo() { 9977 return this.undoManager.canRedo(); 9978 } 9979 canUndo() { 9980 return this.undoManager.canUndo(); 9981 } 9982 recordUndoEntry(description) { 9983 let { 9984 context, 9985 consolidatable 9986 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 9987 return this.undoManager.recordUndoEntry(description, { 9988 context, 9989 consolidatable 9990 }); 9991 } 9992 redo() { 9993 if (this.canRedo()) { 9994 return this.undoManager.redo(); 9995 } 9996 } 9997 undo() { 9998 if (this.canUndo()) { 9999 return this.undoManager.undo(); 10000 } 10001 } 10002 } 10003 10004 /* eslint-disable 10005 no-var, 10006 prefer-const, 10007 */ 10008 class LocationMapper { 10009 constructor(element) { 10010 this.element = element; 10011 } 10012 findLocationFromContainerAndOffset(container, offset) { 10013 let { 10014 strict 10015 } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { 10016 strict: true 10017 }; 10018 let childIndex = 0; 10019 let foundBlock = false; 10020 const location = { 10021 index: 0, 10022 offset: 0 10023 }; 10024 const attachmentElement = this.findAttachmentElementParentForNode(container); 10025 if (attachmentElement) { 10026 container = attachmentElement.parentNode; 10027 offset = findChildIndexOfNode(attachmentElement); 10028 } 10029 const walker = walkTree(this.element, { 10030 usingFilter: rejectAttachmentContents 10031 }); 10032 while (walker.nextNode()) { 10033 const node = walker.currentNode; 10034 if (node === container && nodeIsTextNode(container)) { 10035 if (!nodeIsCursorTarget(node)) { 10036 location.offset += offset; 10037 } 10038 break; 10039 } else { 10040 if (node.parentNode === container) { 10041 if (childIndex++ === offset) { 10042 break; 10043 } 10044 } else if (!elementContainsNode(container, node)) { 10045 if (childIndex > 0) { 10046 break; 10047 } 10048 } 10049 if (nodeIsBlockStart(node, { 10050 strict 10051 })) { 10052 if (foundBlock) { 10053 location.index++; 10054 } 10055 location.offset = 0; 10056 foundBlock = true; 10057 } else { 10058 location.offset += nodeLength(node); 10059 } 10060 } 10061 } 10062 return location; 10063 } 10064 findContainerAndOffsetFromLocation(location) { 10065 let container, offset; 10066 if (location.index === 0 && location.offset === 0) { 10067 container = this.element; 10068 offset = 0; 10069 while (container.firstChild) { 10070 container = container.firstChild; 10071 if (nodeIsBlockContainer(container)) { 10072 offset = 1; 10073 break; 10074 } 10075 } 10076 return [container, offset]; 10077 } 10078 let [node, nodeOffset] = this.findNodeAndOffsetFromLocation(location); 10079 if (!node) return; 10080 if (nodeIsTextNode(node)) { 10081 if (nodeLength(node) === 0) { 10082 container = node.parentNode.parentNode; 10083 offset = findChildIndexOfNode(node.parentNode); 10084 if (nodeIsCursorTarget(node, { 10085 name: "right" 10086 })) { 10087 offset++; 10088 } 10089 } else { 10090 container = node; 10091 offset = location.offset - nodeOffset; 10092 } 10093 } else { 10094 container = node.parentNode; 10095 if (!nodeIsBlockStart(node.previousSibling)) { 10096 if (!nodeIsBlockContainer(container)) { 10097 while (node === container.lastChild) { 10098 node = container; 10099 container = container.parentNode; 10100 if (nodeIsBlockContainer(container)) { 10101 break; 10102 } 10103 } 10104 } 10105 } 10106 offset = findChildIndexOfNode(node); 10107 if (location.offset !== 0) { 10108 offset++; 10109 } 10110 } 10111 return [container, offset]; 10112 } 10113 findNodeAndOffsetFromLocation(location) { 10114 let node, nodeOffset; 10115 let offset = 0; 10116 for (const currentNode of this.getSignificantNodesForIndex(location.index)) { 10117 const length = nodeLength(currentNode); 10118 if (location.offset <= offset + length) { 10119 if (nodeIsTextNode(currentNode)) { 10120 node = currentNode; 10121 nodeOffset = offset; 10122 if (location.offset === nodeOffset && nodeIsCursorTarget(node)) { 10123 break; 10124 } 10125 } else if (!node) { 10126 node = currentNode; 10127 nodeOffset = offset; 10128 } 10129 } 10130 offset += length; 10131 if (offset > location.offset) { 10132 break; 10133 } 10134 } 10135 return [node, nodeOffset]; 10136 } 10137 10138 // Private 10139 10140 findAttachmentElementParentForNode(node) { 10141 while (node && node !== this.element) { 10142 if (nodeIsAttachmentElement(node)) { 10143 return node; 10144 } 10145 node = node.parentNode; 10146 } 10147 } 10148 getSignificantNodesForIndex(index) { 10149 const nodes = []; 10150 const walker = walkTree(this.element, { 10151 usingFilter: acceptSignificantNodes 10152 }); 10153 let recordingNodes = false; 10154 while (walker.nextNode()) { 10155 const node = walker.currentNode; 10156 if (nodeIsBlockStartComment(node)) { 10157 var blockIndex; 10158 if (blockIndex != null) { 10159 blockIndex++; 10160 } else { 10161 blockIndex = 0; 10162 } 10163 if (blockIndex === index) { 10164 recordingNodes = true; 10165 } else if (recordingNodes) { 10166 break; 10167 } 10168 } else if (recordingNodes) { 10169 nodes.push(node); 10170 } 10171 } 10172 return nodes; 10173 } 10174 } 10175 const nodeLength = function (node) { 10176 if (node.nodeType === Node.TEXT_NODE) { 10177 if (nodeIsCursorTarget(node)) { 10178 return 0; 10179 } else { 10180 const string = node.textContent; 10181 return string.length; 10182 } 10183 } else if (tagName(node) === "br" || nodeIsAttachmentElement(node)) { 10184 return 1; 10185 } else { 10186 return 0; 10187 } 10188 }; 10189 const acceptSignificantNodes = function (node) { 10190 if (rejectEmptyTextNodes(node) === NodeFilter.FILTER_ACCEPT) { 10191 return rejectAttachmentContents(node); 10192 } else { 10193 return NodeFilter.FILTER_REJECT; 10194 } 10195 }; 10196 const rejectEmptyTextNodes = function (node) { 10197 if (nodeIsEmptyTextNode(node)) { 10198 return NodeFilter.FILTER_REJECT; 10199 } else { 10200 return NodeFilter.FILTER_ACCEPT; 10201 } 10202 }; 10203 const rejectAttachmentContents = function (node) { 10204 if (nodeIsAttachmentElement(node.parentNode)) { 10205 return NodeFilter.FILTER_REJECT; 10206 } else { 10207 return NodeFilter.FILTER_ACCEPT; 10208 } 10209 }; 10210 10211 /* eslint-disable 10212 id-length, 10213 no-empty, 10214 */ 10215 class PointMapper { 10216 createDOMRangeFromPoint(_ref) { 10217 let { 10218 x, 10219 y 10220 } = _ref; 10221 let domRange; 10222 if (document.caretPositionFromPoint) { 10223 const { 10224 offsetNode, 10225 offset 10226 } = document.caretPositionFromPoint(x, y); 10227 domRange = document.createRange(); 10228 domRange.setStart(offsetNode, offset); 10229 return domRange; 10230 } else if (document.caretRangeFromPoint) { 10231 return document.caretRangeFromPoint(x, y); 10232 } else if (document.body.createTextRange) { 10233 const originalDOMRange = getDOMRange(); 10234 try { 10235 // IE 11 throws "Unspecified error" when using moveToPoint 10236 // during a drag-and-drop operation. 10237 const textRange = document.body.createTextRange(); 10238 textRange.moveToPoint(x, y); 10239 textRange.select(); 10240 } catch (error) {} 10241 domRange = getDOMRange(); 10242 setDOMRange(originalDOMRange); 10243 return domRange; 10244 } 10245 } 10246 getClientRectsForDOMRange(domRange) { 10247 const array = Array.from(domRange.getClientRects()); 10248 const start = array[0]; 10249 const end = array[array.length - 1]; 10250 return [start, end]; 10251 } 10252 } 10253 10254 /* eslint-disable 10255 */ 10256 class SelectionManager extends BasicObject { 10257 constructor(element) { 10258 super(...arguments); 10259 this.didMouseDown = this.didMouseDown.bind(this); 10260 this.selectionDidChange = this.selectionDidChange.bind(this); 10261 this.element = element; 10262 this.locationMapper = new LocationMapper(this.element); 10263 this.pointMapper = new PointMapper(); 10264 this.lockCount = 0; 10265 handleEvent("mousedown", { 10266 onElement: this.element, 10267 withCallback: this.didMouseDown 10268 }); 10269 } 10270 getLocationRange() { 10271 let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 10272 if (options.strict === false) { 10273 return this.createLocationRangeFromDOMRange(getDOMRange()); 10274 } else if (options.ignoreLock) { 10275 return this.currentLocationRange; 10276 } else if (this.lockedLocationRange) { 10277 return this.lockedLocationRange; 10278 } else { 10279 return this.currentLocationRange; 10280 } 10281 } 10282 setLocationRange(locationRange) { 10283 if (this.lockedLocationRange) return; 10284 locationRange = normalizeRange(locationRange); 10285 const domRange = this.createDOMRangeFromLocationRange(locationRange); 10286 if (domRange) { 10287 setDOMRange(domRange); 10288 this.updateCurrentLocationRange(locationRange); 10289 } 10290 } 10291 setLocationRangeFromPointRange(pointRange) { 10292 pointRange = normalizeRange(pointRange); 10293 const startLocation = this.getLocationAtPoint(pointRange[0]); 10294 const endLocation = this.getLocationAtPoint(pointRange[1]); 10295 this.setLocationRange([startLocation, endLocation]); 10296 } 10297 getClientRectAtLocationRange(locationRange) { 10298 const domRange = this.createDOMRangeFromLocationRange(locationRange); 10299 if (domRange) { 10300 return this.getClientRectsForDOMRange(domRange)[1]; 10301 } 10302 } 10303 locationIsCursorTarget(location) { 10304 const node = Array.from(this.findNodeAndOffsetFromLocation(location))[0]; 10305 return nodeIsCursorTarget(node); 10306 } 10307 lock() { 10308 if (this.lockCount++ === 0) { 10309 this.updateCurrentLocationRange(); 10310 this.lockedLocationRange = this.getLocationRange(); 10311 } 10312 } 10313 unlock() { 10314 if (--this.lockCount === 0) { 10315 const { 10316 lockedLocationRange 10317 } = this; 10318 this.lockedLocationRange = null; 10319 if (lockedLocationRange != null) { 10320 return this.setLocationRange(lockedLocationRange); 10321 } 10322 } 10323 } 10324 clearSelection() { 10325 var _getDOMSelection; 10326 return (_getDOMSelection = getDOMSelection()) === null || _getDOMSelection === void 0 ? void 0 : _getDOMSelection.removeAllRanges(); 10327 } 10328 selectionIsCollapsed() { 10329 var _getDOMRange; 10330 return ((_getDOMRange = getDOMRange()) === null || _getDOMRange === void 0 ? void 0 : _getDOMRange.collapsed) === true; 10331 } 10332 selectionIsExpanded() { 10333 return !this.selectionIsCollapsed(); 10334 } 10335 createLocationRangeFromDOMRange(domRange, options) { 10336 if (domRange == null || !this.domRangeWithinElement(domRange)) return; 10337 const start = this.findLocationFromContainerAndOffset(domRange.startContainer, domRange.startOffset, options); 10338 if (!start) return; 10339 const end = domRange.collapsed ? undefined : this.findLocationFromContainerAndOffset(domRange.endContainer, domRange.endOffset, options); 10340 return normalizeRange([start, end]); 10341 } 10342 didMouseDown() { 10343 return this.pauseTemporarily(); 10344 } 10345 pauseTemporarily() { 10346 let resumeHandlers; 10347 this.paused = true; 10348 const resume = () => { 10349 this.paused = false; 10350 clearTimeout(resumeTimeout); 10351 Array.from(resumeHandlers).forEach(handler => { 10352 handler.destroy(); 10353 }); 10354 if (elementContainsNode(document, this.element)) { 10355 return this.selectionDidChange(); 10356 } 10357 }; 10358 const resumeTimeout = setTimeout(resume, 200); 10359 resumeHandlers = ["mousemove", "keydown"].map(eventName => handleEvent(eventName, { 10360 onElement: document, 10361 withCallback: resume 10362 })); 10363 } 10364 selectionDidChange() { 10365 if (!this.paused && !innerElementIsActive(this.element)) { 10366 return this.updateCurrentLocationRange(); 10367 } 10368 } 10369 updateCurrentLocationRange(locationRange) { 10370 if (locationRange != null ? locationRange : locationRange = this.createLocationRangeFromDOMRange(getDOMRange())) { 10371 if (!rangesAreEqual(locationRange, this.currentLocationRange)) { 10372 var _this$delegate, _this$delegate$locati; 10373 this.currentLocationRange = locationRange; 10374 return (_this$delegate = this.delegate) === null || _this$delegate === void 0 || (_this$delegate$locati = _this$delegate.locationRangeDidChange) === null || _this$delegate$locati === void 0 ? void 0 : _this$delegate$locati.call(_this$delegate, this.currentLocationRange.slice(0)); 10375 } 10376 } 10377 } 10378 createDOMRangeFromLocationRange(locationRange) { 10379 const rangeStart = this.findContainerAndOffsetFromLocation(locationRange[0]); 10380 const rangeEnd = rangeIsCollapsed(locationRange) ? rangeStart : this.findContainerAndOffsetFromLocation(locationRange[1]) || rangeStart; 10381 if (rangeStart != null && rangeEnd != null) { 10382 const domRange = document.createRange(); 10383 domRange.setStart(...Array.from(rangeStart || [])); 10384 domRange.setEnd(...Array.from(rangeEnd || [])); 10385 return domRange; 10386 } 10387 } 10388 getLocationAtPoint(point) { 10389 const domRange = this.createDOMRangeFromPoint(point); 10390 if (domRange) { 10391 var _this$createLocationR; 10392 return (_this$createLocationR = this.createLocationRangeFromDOMRange(domRange)) === null || _this$createLocationR === void 0 ? void 0 : _this$createLocationR[0]; 10393 } 10394 } 10395 domRangeWithinElement(domRange) { 10396 if (domRange.collapsed) { 10397 return elementContainsNode(this.element, domRange.startContainer); 10398 } else { 10399 return elementContainsNode(this.element, domRange.startContainer) && elementContainsNode(this.element, domRange.endContainer); 10400 } 10401 } 10402 } 10403 SelectionManager.proxyMethod("locationMapper.findLocationFromContainerAndOffset"); 10404 SelectionManager.proxyMethod("locationMapper.findContainerAndOffsetFromLocation"); 10405 SelectionManager.proxyMethod("locationMapper.findNodeAndOffsetFromLocation"); 10406 SelectionManager.proxyMethod("pointMapper.createDOMRangeFromPoint"); 10407 SelectionManager.proxyMethod("pointMapper.getClientRectsForDOMRange"); 10408 10409 var models = /*#__PURE__*/Object.freeze({ 10410 __proto__: null, 10411 Attachment: Attachment, 10412 AttachmentManager: AttachmentManager, 10413 AttachmentPiece: AttachmentPiece, 10414 Block: Block, 10415 Composition: Composition, 10416 Document: Document, 10417 Editor: Editor, 10418 HTMLParser: HTMLParser, 10419 HTMLSanitizer: HTMLSanitizer, 10420 LineBreakInsertion: LineBreakInsertion, 10421 LocationMapper: LocationMapper, 10422 ManagedAttachment: ManagedAttachment, 10423 Piece: Piece, 10424 PointMapper: PointMapper, 10425 SelectionManager: SelectionManager, 10426 SplittableList: SplittableList, 10427 StringPiece: StringPiece, 10428 Text: Text, 10429 UndoManager: UndoManager 10430 }); 10431 10432 var views = /*#__PURE__*/Object.freeze({ 10433 __proto__: null, 10434 ObjectView: ObjectView, 10435 AttachmentView: AttachmentView, 10436 BlockView: BlockView, 10437 DocumentView: DocumentView, 10438 PieceView: PieceView, 10439 PreviewableAttachmentView: PreviewableAttachmentView, 10440 TextView: TextView 10441 }); 10442 10443 const { 10444 lang, 10445 css, 10446 keyNames: keyNames$1 10447 } = config; 10448 const undoable = function (fn) { 10449 return function () { 10450 const commands = fn.apply(this, arguments); 10451 commands.do(); 10452 if (!this.undos) { 10453 this.undos = []; 10454 } 10455 this.undos.push(commands.undo); 10456 }; 10457 }; 10458 class AttachmentEditorController extends BasicObject { 10459 constructor(attachmentPiece, _element, container) { 10460 let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; 10461 super(...arguments); 10462 // Installing and uninstalling 10463 _defineProperty(this, "makeElementMutable", undoable(() => { 10464 return { 10465 do: () => { 10466 this.element.dataset.trixMutable = true; 10467 }, 10468 undo: () => delete this.element.dataset.trixMutable 10469 }; 10470 })); 10471 _defineProperty(this, "addToolbar", undoable(() => { 10472 // <div class="#{css.attachmentMetadataContainer}" data-trix-mutable="true"> 10473 // <div class="trix-button-row"> 10474 // <span class="trix-button-group trix-button-group--actions"> 10475 // <button type="button" class="trix-button trix-button--remove" title="#{lang.remove}" data-trix-action="remove">#{lang.remove}</button> 10476 // </span> 10477 // </div> 10478 // </div> 10479 const element = makeElement({ 10480 tagName: "div", 10481 className: css.attachmentToolbar, 10482 data: { 10483 trixMutable: true 10484 }, 10485 childNodes: makeElement({ 10486 tagName: "div", 10487 className: "trix-button-row", 10488 childNodes: makeElement({ 10489 tagName: "span", 10490 className: "trix-button-group trix-button-group--actions", 10491 childNodes: makeElement({ 10492 tagName: "button", 10493 className: "trix-button trix-button--remove", 10494 textContent: lang.remove, 10495 attributes: { 10496 title: lang.remove 10497 }, 10498 data: { 10499 trixAction: "remove" 10500 } 10501 }) 10502 }) 10503 }) 10504 }); 10505 if (this.attachment.isPreviewable()) { 10506 // <div class="#{css.attachmentMetadataContainer}"> 10507 // <span class="#{css.attachmentMetadata}"> 10508 // <span class="#{css.attachmentName}" title="#{name}">#{name}</span> 10509 // <span class="#{css.attachmentSize}">#{size}</span> 10510 // </span> 10511 // </div> 10512 element.appendChild(makeElement({ 10513 tagName: "div", 10514 className: css.attachmentMetadataContainer, 10515 childNodes: makeElement({ 10516 tagName: "span", 10517 className: css.attachmentMetadata, 10518 childNodes: [makeElement({ 10519 tagName: "span", 10520 className: css.attachmentName, 10521 textContent: this.attachment.getFilename(), 10522 attributes: { 10523 title: this.attachment.getFilename() 10524 } 10525 }), makeElement({ 10526 tagName: "span", 10527 className: css.attachmentSize, 10528 textContent: this.attachment.getFormattedFilesize() 10529 })] 10530 }) 10531 })); 10532 } 10533 handleEvent("click", { 10534 onElement: element, 10535 withCallback: this.didClickToolbar 10536 }); 10537 handleEvent("click", { 10538 onElement: element, 10539 matchingSelector: "[data-trix-action]", 10540 withCallback: this.didClickActionButton 10541 }); 10542 triggerEvent("trix-attachment-before-toolbar", { 10543 onElement: this.element, 10544 attributes: { 10545 toolbar: element, 10546 attachment: this.attachment 10547 } 10548 }); 10549 return { 10550 do: () => this.element.appendChild(element), 10551 undo: () => removeNode(element) 10552 }; 10553 })); 10554 _defineProperty(this, "installCaptionEditor", undoable(() => { 10555 const textarea = makeElement({ 10556 tagName: "textarea", 10557 className: css.attachmentCaptionEditor, 10558 attributes: { 10559 placeholder: lang.captionPlaceholder 10560 }, 10561 data: { 10562 trixMutable: true 10563 } 10564 }); 10565 textarea.value = this.attachmentPiece.getCaption(); 10566 const textareaClone = textarea.cloneNode(); 10567 textareaClone.classList.add("trix-autoresize-clone"); 10568 textareaClone.tabIndex = -1; 10569 const autoresize = function () { 10570 textareaClone.value = textarea.value; 10571 textarea.style.height = textareaClone.scrollHeight + "px"; 10572 }; 10573 handleEvent("input", { 10574 onElement: textarea, 10575 withCallback: autoresize 10576 }); 10577 handleEvent("input", { 10578 onElement: textarea, 10579 withCallback: this.didInputCaption 10580 }); 10581 handleEvent("keydown", { 10582 onElement: textarea, 10583 withCallback: this.didKeyDownCaption 10584 }); 10585 handleEvent("change", { 10586 onElement: textarea, 10587 withCallback: this.didChangeCaption 10588 }); 10589 handleEvent("blur", { 10590 onElement: textarea, 10591 withCallback: this.didBlurCaption 10592 }); 10593 const figcaption = this.element.querySelector("figcaption"); 10594 const editingFigcaption = figcaption.cloneNode(); 10595 return { 10596 do: () => { 10597 figcaption.style.display = "none"; 10598 editingFigcaption.appendChild(textarea); 10599 editingFigcaption.appendChild(textareaClone); 10600 editingFigcaption.classList.add("".concat(css.attachmentCaption, "--editing")); 10601 figcaption.parentElement.insertBefore(editingFigcaption, figcaption); 10602 autoresize(); 10603 if (this.options.editCaption) { 10604 return defer(() => textarea.focus()); 10605 } 10606 }, 10607 undo() { 10608 removeNode(editingFigcaption); 10609 figcaption.style.display = null; 10610 } 10611 }; 10612 })); 10613 this.didClickToolbar = this.didClickToolbar.bind(this); 10614 this.didClickActionButton = this.didClickActionButton.bind(this); 10615 this.didKeyDownCaption = this.didKeyDownCaption.bind(this); 10616 this.didInputCaption = this.didInputCaption.bind(this); 10617 this.didChangeCaption = this.didChangeCaption.bind(this); 10618 this.didBlurCaption = this.didBlurCaption.bind(this); 10619 this.attachmentPiece = attachmentPiece; 10620 this.element = _element; 10621 this.container = container; 10622 this.options = options; 10623 this.attachment = this.attachmentPiece.attachment; 10624 if (tagName(this.element) === "a") { 10625 this.element = this.element.firstChild; 10626 } 10627 this.install(); 10628 } 10629 install() { 10630 this.makeElementMutable(); 10631 this.addToolbar(); 10632 if (this.attachment.isPreviewable()) { 10633 this.installCaptionEditor(); 10634 } 10635 } 10636 uninstall() { 10637 var _this$delegate; 10638 let undo = this.undos.pop(); 10639 this.savePendingCaption(); 10640 while (undo) { 10641 undo(); 10642 undo = this.undos.pop(); 10643 } 10644 (_this$delegate = this.delegate) === null || _this$delegate === void 0 || _this$delegate.didUninstallAttachmentEditor(this); 10645 } 10646 10647 // Private 10648 10649 savePendingCaption() { 10650 if (this.pendingCaption != null) { 10651 const caption = this.pendingCaption; 10652 this.pendingCaption = null; 10653 if (caption) { 10654 var _this$delegate2, _this$delegate2$attac; 10655 (_this$delegate2 = this.delegate) === null || _this$delegate2 === void 0 || (_this$delegate2$attac = _this$delegate2.attachmentEditorDidRequestUpdatingAttributesForAttachment) === null || _this$delegate2$attac === void 0 || _this$delegate2$attac.call(_this$delegate2, { 10656 caption 10657 }, this.attachment); 10658 } else { 10659 var _this$delegate3, _this$delegate3$attac; 10660 (_this$delegate3 = this.delegate) === null || _this$delegate3 === void 0 || (_this$delegate3$attac = _this$delegate3.attachmentEditorDidRequestRemovingAttributeForAttachment) === null || _this$delegate3$attac === void 0 || _this$delegate3$attac.call(_this$delegate3, "caption", this.attachment); 10661 } 10662 } 10663 } 10664 // Event handlers 10665 10666 didClickToolbar(event) { 10667 event.preventDefault(); 10668 return event.stopPropagation(); 10669 } 10670 didClickActionButton(event) { 10671 var _this$delegate4; 10672 const action = event.target.getAttribute("data-trix-action"); 10673 switch (action) { 10674 case "remove": 10675 return (_this$delegate4 = this.delegate) === null || _this$delegate4 === void 0 ? void 0 : _this$delegate4.attachmentEditorDidRequestRemovalOfAttachment(this.attachment); 10676 } 10677 } 10678 didKeyDownCaption(event) { 10679 if (keyNames$1[event.keyCode] === "return") { 10680 var _this$delegate5, _this$delegate5$attac; 10681 event.preventDefault(); 10682 this.savePendingCaption(); 10683 return (_this$delegate5 = this.delegate) === null || _this$delegate5 === void 0 || (_this$delegate5$attac = _this$delegate5.attachmentEditorDidRequestDeselectingAttachment) === null || _this$delegate5$attac === void 0 ? void 0 : _this$delegate5$attac.call(_this$delegate5, this.attachment); 10684 } 10685 } 10686 didInputCaption(event) { 10687 this.pendingCaption = event.target.value.replace(/\s/g, " ").trim(); 10688 } 10689 didChangeCaption(event) { 10690 return this.savePendingCaption(); 10691 } 10692 didBlurCaption(event) { 10693 return this.savePendingCaption(); 10694 } 10695 } 10696 10697 class CompositionController extends BasicObject { 10698 constructor(element, composition) { 10699 super(...arguments); 10700 this.didFocus = this.didFocus.bind(this); 10701 this.didBlur = this.didBlur.bind(this); 10702 this.didClickAttachment = this.didClickAttachment.bind(this); 10703 this.element = element; 10704 this.composition = composition; 10705 this.documentView = new DocumentView(this.composition.document, { 10706 element: this.element 10707 }); 10708 handleEvent("focus", { 10709 onElement: this.element, 10710 withCallback: this.didFocus 10711 }); 10712 handleEvent("blur", { 10713 onElement: this.element, 10714 withCallback: this.didBlur 10715 }); 10716 handleEvent("click", { 10717 onElement: this.element, 10718 matchingSelector: "a[contenteditable=false]", 10719 preventDefault: true 10720 }); 10721 handleEvent("mousedown", { 10722 onElement: this.element, 10723 matchingSelector: attachmentSelector, 10724 withCallback: this.didClickAttachment 10725 }); 10726 handleEvent("click", { 10727 onElement: this.element, 10728 matchingSelector: "a".concat(attachmentSelector), 10729 preventDefault: true 10730 }); 10731 } 10732 didFocus(event) { 10733 var _this$blurPromise; 10734 const perform = () => { 10735 if (!this.focused) { 10736 var _this$delegate, _this$delegate$compos; 10737 this.focused = true; 10738 return (_this$delegate = this.delegate) === null || _this$delegate === void 0 || (_this$delegate$compos = _this$delegate.compositionControllerDidFocus) === null || _this$delegate$compos === void 0 ? void 0 : _this$delegate$compos.call(_this$delegate); 10739 } 10740 }; 10741 return ((_this$blurPromise = this.blurPromise) === null || _this$blurPromise === void 0 ? void 0 : _this$blurPromise.then(perform)) || perform(); 10742 } 10743 didBlur(event) { 10744 this.blurPromise = new Promise(resolve => { 10745 return defer(() => { 10746 if (!innerElementIsActive(this.element)) { 10747 var _this$delegate2, _this$delegate2$compo; 10748 this.focused = null; 10749 (_this$delegate2 = this.delegate) === null || _this$delegate2 === void 0 || (_this$delegate2$compo = _this$delegate2.compositionControllerDidBlur) === null || _this$delegate2$compo === void 0 || _this$delegate2$compo.call(_this$delegate2); 10750 } 10751 this.blurPromise = null; 10752 return resolve(); 10753 }); 10754 }); 10755 } 10756 didClickAttachment(event, target) { 10757 var _this$delegate3, _this$delegate3$compo; 10758 const attachment = this.findAttachmentForElement(target); 10759 const editCaption = !!findClosestElementFromNode(event.target, { 10760 matchingSelector: "figcaption" 10761 }); 10762 return (_this$delegate3 = this.delegate) === null || _this$delegate3 === void 0 || (_this$delegate3$compo = _this$delegate3.compositionControllerDidSelectAttachment) === null || _this$delegate3$compo === void 0 ? void 0 : _this$delegate3$compo.call(_this$delegate3, attachment, { 10763 editCaption 10764 }); 10765 } 10766 getSerializableElement() { 10767 if (this.isEditingAttachment()) { 10768 return this.documentView.shadowElement; 10769 } else { 10770 return this.element; 10771 } 10772 } 10773 render() { 10774 var _this$delegate6, _this$delegate6$compo; 10775 if (this.revision !== this.composition.revision) { 10776 this.documentView.setDocument(this.composition.document); 10777 this.documentView.render(); 10778 this.revision = this.composition.revision; 10779 } 10780 if (this.canSyncDocumentView() && !this.documentView.isSynced()) { 10781 var _this$delegate4, _this$delegate4$compo, _this$delegate5, _this$delegate5$compo; 10782 (_this$delegate4 = this.delegate) === null || _this$delegate4 === void 0 || (_this$delegate4$compo = _this$delegate4.compositionControllerWillSyncDocumentView) === null || _this$delegate4$compo === void 0 || _this$delegate4$compo.call(_this$delegate4); 10783 this.documentView.sync(); 10784 (_this$delegate5 = this.delegate) === null || _this$delegate5 === void 0 || (_this$delegate5$compo = _this$delegate5.compositionControllerDidSyncDocumentView) === null || _this$delegate5$compo === void 0 || _this$delegate5$compo.call(_this$delegate5); 10785 } 10786 return (_this$delegate6 = this.delegate) === null || _this$delegate6 === void 0 || (_this$delegate6$compo = _this$delegate6.compositionControllerDidRender) === null || _this$delegate6$compo === void 0 ? void 0 : _this$delegate6$compo.call(_this$delegate6); 10787 } 10788 rerenderViewForObject(object) { 10789 this.invalidateViewForObject(object); 10790 return this.render(); 10791 } 10792 invalidateViewForObject(object) { 10793 return this.documentView.invalidateViewForObject(object); 10794 } 10795 isViewCachingEnabled() { 10796 return this.documentView.isViewCachingEnabled(); 10797 } 10798 enableViewCaching() { 10799 return this.documentView.enableViewCaching(); 10800 } 10801 disableViewCaching() { 10802 return this.documentView.disableViewCaching(); 10803 } 10804 refreshViewCache() { 10805 return this.documentView.garbageCollectCachedViews(); 10806 } 10807 10808 // Attachment editor management 10809 10810 isEditingAttachment() { 10811 return !!this.attachmentEditor; 10812 } 10813 installAttachmentEditorForAttachment(attachment, options) { 10814 var _this$attachmentEdito; 10815 if (((_this$attachmentEdito = this.attachmentEditor) === null || _this$attachmentEdito === void 0 ? void 0 : _this$attachmentEdito.attachment) === attachment) return; 10816 const element = this.documentView.findElementForObject(attachment); 10817 if (!element) return; 10818 this.uninstallAttachmentEditor(); 10819 const attachmentPiece = this.composition.document.getAttachmentPieceForAttachment(attachment); 10820 this.attachmentEditor = new AttachmentEditorController(attachmentPiece, element, this.element, options); 10821 this.attachmentEditor.delegate = this; 10822 } 10823 uninstallAttachmentEditor() { 10824 var _this$attachmentEdito2; 10825 return (_this$attachmentEdito2 = this.attachmentEditor) === null || _this$attachmentEdito2 === void 0 ? void 0 : _this$attachmentEdito2.uninstall(); 10826 } 10827 10828 // Attachment controller delegate 10829 10830 didUninstallAttachmentEditor() { 10831 this.attachmentEditor = null; 10832 return this.render(); 10833 } 10834 attachmentEditorDidRequestUpdatingAttributesForAttachment(attributes, attachment) { 10835 var _this$delegate7, _this$delegate7$compo; 10836 (_this$delegate7 = this.delegate) === null || _this$delegate7 === void 0 || (_this$delegate7$compo = _this$delegate7.compositionControllerWillUpdateAttachment) === null || _this$delegate7$compo === void 0 || _this$delegate7$compo.call(_this$delegate7, attachment); 10837 return this.composition.updateAttributesForAttachment(attributes, attachment); 10838 } 10839 attachmentEditorDidRequestRemovingAttributeForAttachment(attribute, attachment) { 10840 var _this$delegate8, _this$delegate8$compo; 10841 (_this$delegate8 = this.delegate) === null || _this$delegate8 === void 0 || (_this$delegate8$compo = _this$delegate8.compositionControllerWillUpdateAttachment) === null || _this$delegate8$compo === void 0 || _this$delegate8$compo.call(_this$delegate8, attachment); 10842 return this.composition.removeAttributeForAttachment(attribute, attachment); 10843 } 10844 attachmentEditorDidRequestRemovalOfAttachment(attachment) { 10845 var _this$delegate9, _this$delegate9$compo; 10846 return (_this$delegate9 = this.delegate) === null || _this$delegate9 === void 0 || (_this$delegate9$compo = _this$delegate9.compositionControllerDidRequestRemovalOfAttachment) === null || _this$delegate9$compo === void 0 ? void 0 : _this$delegate9$compo.call(_this$delegate9, attachment); 10847 } 10848 attachmentEditorDidRequestDeselectingAttachment(attachment) { 10849 var _this$delegate10, _this$delegate10$comp; 10850 return (_this$delegate10 = this.delegate) === null || _this$delegate10 === void 0 || (_this$delegate10$comp = _this$delegate10.compositionControllerDidRequestDeselectingAttachment) === null || _this$delegate10$comp === void 0 ? void 0 : _this$delegate10$comp.call(_this$delegate10, attachment); 10851 } 10852 10853 // Private 10854 10855 canSyncDocumentView() { 10856 return !this.isEditingAttachment(); 10857 } 10858 findAttachmentForElement(element) { 10859 return this.composition.document.getAttachmentById(parseInt(element.dataset.trixId, 10)); 10860 } 10861 } 10862 10863 class Controller extends BasicObject {} 10864 10865 const mutableAttributeName = "data-trix-mutable"; 10866 const mutableSelector = "[".concat(mutableAttributeName, "]"); 10867 const options = { 10868 attributes: true, 10869 childList: true, 10870 characterData: true, 10871 characterDataOldValue: true, 10872 subtree: true 10873 }; 10874 class MutationObserver extends BasicObject { 10875 constructor(element) { 10876 super(element); 10877 this.didMutate = this.didMutate.bind(this); 10878 this.element = element; 10879 this.observer = new window.MutationObserver(this.didMutate); 10880 this.start(); 10881 } 10882 start() { 10883 this.reset(); 10884 return this.observer.observe(this.element, options); 10885 } 10886 stop() { 10887 return this.observer.disconnect(); 10888 } 10889 didMutate(mutations) { 10890 this.mutations.push(...Array.from(this.findSignificantMutations(mutations) || [])); 10891 if (this.mutations.length) { 10892 var _this$delegate, _this$delegate$elemen; 10893 (_this$delegate = this.delegate) === null || _this$delegate === void 0 || (_this$delegate$elemen = _this$delegate.elementDidMutate) === null || _this$delegate$elemen === void 0 || _this$delegate$elemen.call(_this$delegate, this.getMutationSummary()); 10894 return this.reset(); 10895 } 10896 } 10897 10898 // Private 10899 10900 reset() { 10901 this.mutations = []; 10902 } 10903 findSignificantMutations(mutations) { 10904 return mutations.filter(mutation => { 10905 return this.mutationIsSignificant(mutation); 10906 }); 10907 } 10908 mutationIsSignificant(mutation) { 10909 if (this.nodeIsMutable(mutation.target)) { 10910 return false; 10911 } 10912 for (const node of Array.from(this.nodesModifiedByMutation(mutation))) { 10913 if (this.nodeIsSignificant(node)) return true; 10914 } 10915 return false; 10916 } 10917 nodeIsSignificant(node) { 10918 return node !== this.element && !this.nodeIsMutable(node) && !nodeIsEmptyTextNode(node); 10919 } 10920 nodeIsMutable(node) { 10921 return findClosestElementFromNode(node, { 10922 matchingSelector: mutableSelector 10923 }); 10924 } 10925 nodesModifiedByMutation(mutation) { 10926 const nodes = []; 10927 switch (mutation.type) { 10928 case "attributes": 10929 if (mutation.attributeName !== mutableAttributeName) { 10930 nodes.push(mutation.target); 10931 } 10932 break; 10933 case "characterData": 10934 // Changes to text nodes should consider the parent element 10935 nodes.push(mutation.target.parentNode); 10936 nodes.push(mutation.target); 10937 break; 10938 case "childList": 10939 // Consider each added or removed node 10940 nodes.push(...Array.from(mutation.addedNodes || [])); 10941 nodes.push(...Array.from(mutation.removedNodes || [])); 10942 break; 10943 } 10944 return nodes; 10945 } 10946 getMutationSummary() { 10947 return this.getTextMutationSummary(); 10948 } 10949 getTextMutationSummary() { 10950 const { 10951 additions, 10952 deletions 10953 } = this.getTextChangesFromCharacterData(); 10954 const textChanges = this.getTextChangesFromChildList(); 10955 Array.from(textChanges.additions).forEach(addition => { 10956 if (!Array.from(additions).includes(addition)) { 10957 additions.push(addition); 10958 } 10959 }); 10960 deletions.push(...Array.from(textChanges.deletions || [])); 10961 const summary = {}; 10962 const added = additions.join(""); 10963 if (added) { 10964 summary.textAdded = added; 10965 } 10966 const deleted = deletions.join(""); 10967 if (deleted) { 10968 summary.textDeleted = deleted; 10969 } 10970 return summary; 10971 } 10972 getMutationsByType(type) { 10973 return Array.from(this.mutations).filter(mutation => mutation.type === type); 10974 } 10975 getTextChangesFromChildList() { 10976 let textAdded, textRemoved; 10977 const addedNodes = []; 10978 const removedNodes = []; 10979 Array.from(this.getMutationsByType("childList")).forEach(mutation => { 10980 addedNodes.push(...Array.from(mutation.addedNodes || [])); 10981 removedNodes.push(...Array.from(mutation.removedNodes || [])); 10982 }); 10983 const singleBlockCommentRemoved = addedNodes.length === 0 && removedNodes.length === 1 && nodeIsBlockStartComment(removedNodes[0]); 10984 if (singleBlockCommentRemoved) { 10985 textAdded = []; 10986 textRemoved = ["\n"]; 10987 } else { 10988 textAdded = getTextForNodes(addedNodes); 10989 textRemoved = getTextForNodes(removedNodes); 10990 } 10991 const additions = textAdded.filter((text, index) => text !== textRemoved[index]).map(normalizeSpaces); 10992 const deletions = textRemoved.filter((text, index) => text !== textAdded[index]).map(normalizeSpaces); 10993 return { 10994 additions, 10995 deletions 10996 }; 10997 } 10998 getTextChangesFromCharacterData() { 10999 let added, removed; 11000 const characterMutations = this.getMutationsByType("characterData"); 11001 if (characterMutations.length) { 11002 const startMutation = characterMutations[0], 11003 endMutation = characterMutations[characterMutations.length - 1]; 11004 const oldString = normalizeSpaces(startMutation.oldValue); 11005 const newString = normalizeSpaces(endMutation.target.data); 11006 const summarized = summarizeStringChange(oldString, newString); 11007 added = summarized.added; 11008 removed = summarized.removed; 11009 } 11010 return { 11011 additions: added ? [added] : [], 11012 deletions: removed ? [removed] : [] 11013 }; 11014 } 11015 } 11016 const getTextForNodes = function () { 11017 let nodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 11018 const text = []; 11019 for (const node of Array.from(nodes)) { 11020 switch (node.nodeType) { 11021 case Node.TEXT_NODE: 11022 text.push(node.data); 11023 break; 11024 case Node.ELEMENT_NODE: 11025 if (tagName(node) === "br") { 11026 text.push("\n"); 11027 } else { 11028 text.push(...Array.from(getTextForNodes(node.childNodes) || [])); 11029 } 11030 break; 11031 } 11032 } 11033 return text; 11034 }; 11035 11036 /* eslint-disable 11037 no-empty, 11038 */ 11039 class FileVerificationOperation extends Operation { 11040 constructor(file) { 11041 super(...arguments); 11042 this.file = file; 11043 } 11044 perform(callback) { 11045 const reader = new FileReader(); 11046 reader.onerror = () => callback(false); 11047 reader.onload = () => { 11048 reader.onerror = null; 11049 try { 11050 reader.abort(); 11051 } catch (error) {} 11052 return callback(true, this.file); 11053 }; 11054 return reader.readAsArrayBuffer(this.file); 11055 } 11056 } 11057 11058 // Each software keyboard on Android emits its own set of events and some of them can be buggy. 11059 // This class detects when some buggy events are being emitted and lets know the input controller 11060 // that they should be ignored. 11061 class FlakyAndroidKeyboardDetector { 11062 constructor(element) { 11063 this.element = element; 11064 } 11065 shouldIgnore(event) { 11066 if (!browser$1.samsungAndroid) return false; 11067 this.previousEvent = this.event; 11068 this.event = event; 11069 this.checkSamsungKeyboardBuggyModeStart(); 11070 this.checkSamsungKeyboardBuggyModeEnd(); 11071 return this.buggyMode; 11072 } 11073 11074 // private 11075 11076 // The Samsung keyboard on Android can enter a buggy state in which it emits a flurry of confused events that, 11077 // if processed, corrupts the editor. The buggy mode always starts with an insertText event, right after a 11078 // keydown event with for an "Unidentified" key, with the same text as the editor element, except for a few 11079 // extra whitespace, or exotic utf8, characters. 11080 checkSamsungKeyboardBuggyModeStart() { 11081 if (this.insertingLongTextAfterUnidentifiedChar() && differsInWhitespace(this.element.innerText, this.event.data)) { 11082 this.buggyMode = true; 11083 this.event.preventDefault(); 11084 } 11085 } 11086 11087 // The flurry of buggy events are always insertText. If we see any other type, it means it's over. 11088 checkSamsungKeyboardBuggyModeEnd() { 11089 if (this.buggyMode && this.event.inputType !== "insertText") { 11090 this.buggyMode = false; 11091 } 11092 } 11093 insertingLongTextAfterUnidentifiedChar() { 11094 var _this$event$data; 11095 return this.isBeforeInputInsertText() && this.previousEventWasUnidentifiedKeydown() && ((_this$event$data = this.event.data) === null || _this$event$data === void 0 ? void 0 : _this$event$data.length) > 50; 11096 } 11097 isBeforeInputInsertText() { 11098 return this.event.type === "beforeinput" && this.event.inputType === "insertText"; 11099 } 11100 previousEventWasUnidentifiedKeydown() { 11101 var _this$previousEvent, _this$previousEvent2; 11102 return ((_this$previousEvent = this.previousEvent) === null || _this$previousEvent === void 0 ? void 0 : _this$previousEvent.type) === "keydown" && ((_this$previousEvent2 = this.previousEvent) === null || _this$previousEvent2 === void 0 ? void 0 : _this$previousEvent2.key) === "Unidentified"; 11103 } 11104 } 11105 const differsInWhitespace = (text1, text2) => { 11106 return normalize(text1) === normalize(text2); 11107 }; 11108 const whiteSpaceNormalizerRegexp = new RegExp("(".concat(OBJECT_REPLACEMENT_CHARACTER, "|").concat(ZERO_WIDTH_SPACE, "|").concat(NON_BREAKING_SPACE, "|\\s)+"), "g"); 11109 const normalize = text => text.replace(whiteSpaceNormalizerRegexp, " ").trim(); 11110 11111 class InputController extends BasicObject { 11112 constructor(element) { 11113 super(...arguments); 11114 this.element = element; 11115 this.mutationObserver = new MutationObserver(this.element); 11116 this.mutationObserver.delegate = this; 11117 this.flakyKeyboardDetector = new FlakyAndroidKeyboardDetector(this.element); 11118 for (const eventName in this.constructor.events) { 11119 handleEvent(eventName, { 11120 onElement: this.element, 11121 withCallback: this.handlerFor(eventName) 11122 }); 11123 } 11124 } 11125 elementDidMutate(mutationSummary) {} 11126 editorWillSyncDocumentView() { 11127 return this.mutationObserver.stop(); 11128 } 11129 editorDidSyncDocumentView() { 11130 return this.mutationObserver.start(); 11131 } 11132 requestRender() { 11133 var _this$delegate, _this$delegate$inputC; 11134 return (_this$delegate = this.delegate) === null || _this$delegate === void 0 || (_this$delegate$inputC = _this$delegate.inputControllerDidRequestRender) === null || _this$delegate$inputC === void 0 ? void 0 : _this$delegate$inputC.call(_this$delegate); 11135 } 11136 requestReparse() { 11137 var _this$delegate2, _this$delegate2$input; 11138 (_this$delegate2 = this.delegate) === null || _this$delegate2 === void 0 || (_this$delegate2$input = _this$delegate2.inputControllerDidRequestReparse) === null || _this$delegate2$input === void 0 || _this$delegate2$input.call(_this$delegate2); 11139 return this.requestRender(); 11140 } 11141 attachFiles(files) { 11142 const operations = Array.from(files).map(file => new FileVerificationOperation(file)); 11143 return Promise.all(operations).then(files => { 11144 this.handleInput(function () { 11145 var _this$delegate3, _this$responder; 11146 (_this$delegate3 = this.delegate) === null || _this$delegate3 === void 0 || _this$delegate3.inputControllerWillAttachFiles(); 11147 (_this$responder = this.responder) === null || _this$responder === void 0 || _this$responder.insertFiles(files); 11148 return this.requestRender(); 11149 }); 11150 }); 11151 } 11152 11153 // Private 11154 11155 handlerFor(eventName) { 11156 return event => { 11157 if (!event.defaultPrevented) { 11158 this.handleInput(() => { 11159 if (!innerElementIsActive(this.element)) { 11160 if (this.flakyKeyboardDetector.shouldIgnore(event)) return; 11161 this.eventName = eventName; 11162 this.constructor.events[eventName].call(this, event); 11163 } 11164 }); 11165 } 11166 }; 11167 } 11168 handleInput(callback) { 11169 try { 11170 var _this$delegate4; 11171 (_this$delegate4 = this.delegate) === null || _this$delegate4 === void 0 || _this$delegate4.inputControllerWillHandleInput(); 11172 callback.call(this); 11173 } finally { 11174 var _this$delegate5; 11175 (_this$delegate5 = this.delegate) === null || _this$delegate5 === void 0 || _this$delegate5.inputControllerDidHandleInput(); 11176 } 11177 } 11178 createLinkHTML(href, text) { 11179 const link = document.createElement("a"); 11180 link.href = href; 11181 link.textContent = text ? text : href; 11182 return link.outerHTML; 11183 } 11184 } 11185 _defineProperty(InputController, "events", {}); 11186 11187 var _$codePointAt, _; 11188 const { 11189 browser, 11190 keyNames 11191 } = config; 11192 let pastedFileCount = 0; 11193 class Level0InputController extends InputController { 11194 constructor() { 11195 super(...arguments); 11196 this.resetInputSummary(); 11197 } 11198 setInputSummary() { 11199 let summary = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 11200 this.inputSummary.eventName = this.eventName; 11201 for (const key in summary) { 11202 const value = summary[key]; 11203 this.inputSummary[key] = value; 11204 } 11205 return this.inputSummary; 11206 } 11207 resetInputSummary() { 11208 this.inputSummary = {}; 11209 } 11210 reset() { 11211 this.resetInputSummary(); 11212 return selectionChangeObserver.reset(); 11213 } 11214 11215 // Mutation observer delegate 11216 11217 elementDidMutate(mutationSummary) { 11218 if (this.isComposing()) { 11219 var _this$delegate, _this$delegate$inputC; 11220 return (_this$delegate = this.delegate) === null || _this$delegate === void 0 || (_this$delegate$inputC = _this$delegate.inputControllerDidAllowUnhandledInput) === null || _this$delegate$inputC === void 0 ? void 0 : _this$delegate$inputC.call(_this$delegate); 11221 } else { 11222 return this.handleInput(function () { 11223 if (this.mutationIsSignificant(mutationSummary)) { 11224 if (this.mutationIsExpected(mutationSummary)) { 11225 this.requestRender(); 11226 } else { 11227 this.requestReparse(); 11228 } 11229 } 11230 return this.reset(); 11231 }); 11232 } 11233 } 11234 mutationIsExpected(_ref) { 11235 let { 11236 textAdded, 11237 textDeleted 11238 } = _ref; 11239 if (this.inputSummary.preferDocument) { 11240 return true; 11241 } 11242 const mutationAdditionMatchesSummary = textAdded != null ? textAdded === this.inputSummary.textAdded : !this.inputSummary.textAdded; 11243 const mutationDeletionMatchesSummary = textDeleted != null ? this.inputSummary.didDelete : !this.inputSummary.didDelete; 11244 const unexpectedNewlineAddition = ["\n", " \n"].includes(textAdded) && !mutationAdditionMatchesSummary; 11245 const unexpectedNewlineDeletion = textDeleted === "\n" && !mutationDeletionMatchesSummary; 11246 const singleUnexpectedNewline = unexpectedNewlineAddition && !unexpectedNewlineDeletion || unexpectedNewlineDeletion && !unexpectedNewlineAddition; 11247 if (singleUnexpectedNewline) { 11248 const range = this.getSelectedRange(); 11249 if (range) { 11250 var _this$responder; 11251 const offset = unexpectedNewlineAddition ? textAdded.replace(/\n$/, "").length || -1 : (textAdded === null || textAdded === void 0 ? void 0 : textAdded.length) || 1; 11252 if ((_this$responder = this.responder) !== null && _this$responder !== void 0 && _this$responder.positionIsBlockBreak(range[1] + offset)) { 11253 return true; 11254 } 11255 } 11256 } 11257 return mutationAdditionMatchesSummary && mutationDeletionMatchesSummary; 11258 } 11259 mutationIsSignificant(mutationSummary) { 11260 var _this$compositionInpu; 11261 const textChanged = Object.keys(mutationSummary).length > 0; 11262 const composedEmptyString = ((_this$compositionInpu = this.compositionInput) === null || _this$compositionInpu === void 0 ? void 0 : _this$compositionInpu.getEndData()) === ""; 11263 return textChanged || !composedEmptyString; 11264 } 11265 11266 // Private 11267 11268 getCompositionInput() { 11269 if (this.isComposing()) { 11270 return this.compositionInput; 11271 } else { 11272 this.compositionInput = new CompositionInput(this); 11273 } 11274 } 11275 isComposing() { 11276 return this.compositionInput && !this.compositionInput.isEnded(); 11277 } 11278 deleteInDirection(direction, event) { 11279 var _this$responder2; 11280 if (((_this$responder2 = this.responder) === null || _this$responder2 === void 0 ? void 0 : _this$responder2.deleteInDirection(direction)) === false) { 11281 if (event) { 11282 event.preventDefault(); 11283 return this.requestRender(); 11284 } 11285 } else { 11286 return this.setInputSummary({ 11287 didDelete: true 11288 }); 11289 } 11290 } 11291 serializeSelectionToDataTransfer(dataTransfer) { 11292 var _this$responder3; 11293 if (!dataTransferIsWritable(dataTransfer)) return; 11294 const document = (_this$responder3 = this.responder) === null || _this$responder3 === void 0 ? void 0 : _this$responder3.getSelectedDocument().toSerializableDocument(); 11295 dataTransfer.setData("application/x-trix-document", JSON.stringify(document)); 11296 dataTransfer.setData("text/html", DocumentView.render(document).innerHTML); 11297 dataTransfer.setData("text/plain", document.toString().replace(/\n$/, "")); 11298 return true; 11299 } 11300 canAcceptDataTransfer(dataTransfer) { 11301 const types = {}; 11302 Array.from((dataTransfer === null || dataTransfer === void 0 ? void 0 : dataTransfer.types) || []).forEach(type => { 11303 types[type] = true; 11304 }); 11305 return types.Files || types["application/x-trix-document"] || types["text/html"] || types["text/plain"]; 11306 } 11307 getPastedHTMLUsingHiddenElement(callback) { 11308 const selectedRange = this.getSelectedRange(); 11309 const style = { 11310 position: "absolute", 11311 left: "".concat(window.pageXOffset, "px"), 11312 top: "".concat(window.pageYOffset, "px"), 11313 opacity: 0 11314 }; 11315 const element = makeElement({ 11316 style, 11317 tagName: "div", 11318 editable: true 11319 }); 11320 document.body.appendChild(element); 11321 element.focus(); 11322 return requestAnimationFrame(() => { 11323 const html = element.innerHTML; 11324 removeNode(element); 11325 this.setSelectedRange(selectedRange); 11326 return callback(html); 11327 }); 11328 } 11329 } 11330 _defineProperty(Level0InputController, "events", { 11331 keydown(event) { 11332 if (!this.isComposing()) { 11333 this.resetInputSummary(); 11334 } 11335 this.inputSummary.didInput = true; 11336 const keyName = keyNames[event.keyCode]; 11337 if (keyName) { 11338 var _context2; 11339 let context = this.keys; 11340 ["ctrl", "alt", "shift", "meta"].forEach(modifier => { 11341 if (event["".concat(modifier, "Key")]) { 11342 var _context; 11343 if (modifier === "ctrl") { 11344 modifier = "control"; 11345 } 11346 context = (_context = context) === null || _context === void 0 ? void 0 : _context[modifier]; 11347 } 11348 }); 11349 if (((_context2 = context) === null || _context2 === void 0 ? void 0 : _context2[keyName]) != null) { 11350 this.setInputSummary({ 11351 keyName 11352 }); 11353 selectionChangeObserver.reset(); 11354 context[keyName].call(this, event); 11355 } 11356 } 11357 if (keyEventIsKeyboardCommand(event)) { 11358 const character = String.fromCharCode(event.keyCode).toLowerCase(); 11359 if (character) { 11360 var _this$delegate3; 11361 const keys = ["alt", "shift"].map(modifier => { 11362 if (event["".concat(modifier, "Key")]) { 11363 return modifier; 11364 } 11365 }).filter(key => key); 11366 keys.push(character); 11367 if ((_this$delegate3 = this.delegate) !== null && _this$delegate3 !== void 0 && _this$delegate3.inputControllerDidReceiveKeyboardCommand(keys)) { 11368 event.preventDefault(); 11369 } 11370 } 11371 } 11372 }, 11373 keypress(event) { 11374 if (this.inputSummary.eventName != null) return; 11375 if (event.metaKey) return; 11376 if (event.ctrlKey && !event.altKey) return; 11377 const string = stringFromKeyEvent(event); 11378 if (string) { 11379 var _this$delegate4, _this$responder9; 11380 (_this$delegate4 = this.delegate) === null || _this$delegate4 === void 0 || _this$delegate4.inputControllerWillPerformTyping(); 11381 (_this$responder9 = this.responder) === null || _this$responder9 === void 0 || _this$responder9.insertString(string); 11382 return this.setInputSummary({ 11383 textAdded: string, 11384 didDelete: this.selectionIsExpanded() 11385 }); 11386 } 11387 }, 11388 textInput(event) { 11389 // Handle autocapitalization 11390 const { 11391 data 11392 } = event; 11393 const { 11394 textAdded 11395 } = this.inputSummary; 11396 if (textAdded && textAdded !== data && textAdded.toUpperCase() === data) { 11397 var _this$responder10; 11398 const range = this.getSelectedRange(); 11399 this.setSelectedRange([range[0], range[1] + textAdded.length]); 11400 (_this$responder10 = this.responder) === null || _this$responder10 === void 0 || _this$responder10.insertString(data); 11401 this.setInputSummary({ 11402 textAdded: data 11403 }); 11404 return this.setSelectedRange(range); 11405 } 11406 }, 11407 dragenter(event) { 11408 event.preventDefault(); 11409 }, 11410 dragstart(event) { 11411 var _this$delegate5, _this$delegate5$input; 11412 this.serializeSelectionToDataTransfer(event.dataTransfer); 11413 this.draggedRange = this.getSelectedRange(); 11414 return (_this$delegate5 = this.delegate) === null || _this$delegate5 === void 0 || (_this$delegate5$input = _this$delegate5.inputControllerDidStartDrag) === null || _this$delegate5$input === void 0 ? void 0 : _this$delegate5$input.call(_this$delegate5); 11415 }, 11416 dragover(event) { 11417 if (this.draggedRange || this.canAcceptDataTransfer(event.dataTransfer)) { 11418 event.preventDefault(); 11419 const draggingPoint = { 11420 x: event.clientX, 11421 y: event.clientY 11422 }; 11423 if (!objectsAreEqual(draggingPoint, this.draggingPoint)) { 11424 var _this$delegate6, _this$delegate6$input; 11425 this.draggingPoint = draggingPoint; 11426 return (_this$delegate6 = this.delegate) === null || _this$delegate6 === void 0 || (_this$delegate6$input = _this$delegate6.inputControllerDidReceiveDragOverPoint) === null || _this$delegate6$input === void 0 ? void 0 : _this$delegate6$input.call(_this$delegate6, this.draggingPoint); 11427 } 11428 } 11429 }, 11430 dragend(event) { 11431 var _this$delegate7, _this$delegate7$input; 11432 (_this$delegate7 = this.delegate) === null || _this$delegate7 === void 0 || (_this$delegate7$input = _this$delegate7.inputControllerDidCancelDrag) === null || _this$delegate7$input === void 0 || _this$delegate7$input.call(_this$delegate7); 11433 this.draggedRange = null; 11434 this.draggingPoint = null; 11435 }, 11436 drop(event) { 11437 var _event$dataTransfer, _this$responder11; 11438 event.preventDefault(); 11439 const files = (_event$dataTransfer = event.dataTransfer) === null || _event$dataTransfer === void 0 ? void 0 : _event$dataTransfer.files; 11440 const documentJSON = event.dataTransfer.getData("application/x-trix-document"); 11441 const point = { 11442 x: event.clientX, 11443 y: event.clientY 11444 }; 11445 (_this$responder11 = this.responder) === null || _this$responder11 === void 0 || _this$responder11.setLocationRangeFromPointRange(point); 11446 if (files !== null && files !== void 0 && files.length) { 11447 this.attachFiles(files); 11448 } else if (this.draggedRange) { 11449 var _this$delegate8, _this$responder12; 11450 (_this$delegate8 = this.delegate) === null || _this$delegate8 === void 0 || _this$delegate8.inputControllerWillMoveText(); 11451 (_this$responder12 = this.responder) === null || _this$responder12 === void 0 || _this$responder12.moveTextFromRange(this.draggedRange); 11452 this.draggedRange = null; 11453 this.requestRender(); 11454 } else if (documentJSON) { 11455 var _this$responder13; 11456 const document = Document.fromJSONString(documentJSON); 11457 (_this$responder13 = this.responder) === null || _this$responder13 === void 0 || _this$responder13.insertDocument(document); 11458 this.requestRender(); 11459 } 11460 this.draggedRange = null; 11461 this.draggingPoint = null; 11462 }, 11463 cut(event) { 11464 var _this$responder14; 11465 if ((_this$responder14 = this.responder) !== null && _this$responder14 !== void 0 && _this$responder14.selectionIsExpanded()) { 11466 var _this$delegate9; 11467 if (this.serializeSelectionToDataTransfer(event.clipboardData)) { 11468 event.preventDefault(); 11469 } 11470 (_this$delegate9 = this.delegate) === null || _this$delegate9 === void 0 || _this$delegate9.inputControllerWillCutText(); 11471 this.deleteInDirection("backward"); 11472 if (event.defaultPrevented) { 11473 return this.requestRender(); 11474 } 11475 } 11476 }, 11477 copy(event) { 11478 var _this$responder15; 11479 if ((_this$responder15 = this.responder) !== null && _this$responder15 !== void 0 && _this$responder15.selectionIsExpanded()) { 11480 if (this.serializeSelectionToDataTransfer(event.clipboardData)) { 11481 event.preventDefault(); 11482 } 11483 } 11484 }, 11485 paste(event) { 11486 const clipboard = event.clipboardData || event.testClipboardData; 11487 const paste = { 11488 clipboard 11489 }; 11490 if (!clipboard || pasteEventIsCrippledSafariHTMLPaste(event)) { 11491 this.getPastedHTMLUsingHiddenElement(html => { 11492 var _this$delegate10, _this$responder16, _this$delegate11; 11493 paste.type = "text/html"; 11494 paste.html = html; 11495 (_this$delegate10 = this.delegate) === null || _this$delegate10 === void 0 || _this$delegate10.inputControllerWillPaste(paste); 11496 (_this$responder16 = this.responder) === null || _this$responder16 === void 0 || _this$responder16.insertHTML(paste.html); 11497 this.requestRender(); 11498 return (_this$delegate11 = this.delegate) === null || _this$delegate11 === void 0 ? void 0 : _this$delegate11.inputControllerDidPaste(paste); 11499 }); 11500 return; 11501 } 11502 const href = clipboard.getData("URL"); 11503 const html = clipboard.getData("text/html"); 11504 const name = clipboard.getData("public.url-name"); 11505 if (href) { 11506 var _this$delegate12, _this$responder17, _this$delegate13; 11507 let string; 11508 paste.type = "text/html"; 11509 if (name) { 11510 string = squishBreakableWhitespace(name).trim(); 11511 } else { 11512 string = href; 11513 } 11514 paste.html = this.createLinkHTML(href, string); 11515 (_this$delegate12 = this.delegate) === null || _this$delegate12 === void 0 || _this$delegate12.inputControllerWillPaste(paste); 11516 this.setInputSummary({ 11517 textAdded: string, 11518 didDelete: this.selectionIsExpanded() 11519 }); 11520 (_this$responder17 = this.responder) === null || _this$responder17 === void 0 || _this$responder17.insertHTML(paste.html); 11521 this.requestRender(); 11522 (_this$delegate13 = this.delegate) === null || _this$delegate13 === void 0 || _this$delegate13.inputControllerDidPaste(paste); 11523 } else if (dataTransferIsPlainText(clipboard)) { 11524 var _this$delegate14, _this$responder18, _this$delegate15; 11525 paste.type = "text/plain"; 11526 paste.string = clipboard.getData("text/plain"); 11527 (_this$delegate14 = this.delegate) === null || _this$delegate14 === void 0 || _this$delegate14.inputControllerWillPaste(paste); 11528 this.setInputSummary({ 11529 textAdded: paste.string, 11530 didDelete: this.selectionIsExpanded() 11531 }); 11532 (_this$responder18 = this.responder) === null || _this$responder18 === void 0 || _this$responder18.insertString(paste.string); 11533 this.requestRender(); 11534 (_this$delegate15 = this.delegate) === null || _this$delegate15 === void 0 || _this$delegate15.inputControllerDidPaste(paste); 11535 } else if (html) { 11536 var _this$delegate16, _this$responder19, _this$delegate17; 11537 paste.type = "text/html"; 11538 paste.html = html; 11539 (_this$delegate16 = this.delegate) === null || _this$delegate16 === void 0 || _this$delegate16.inputControllerWillPaste(paste); 11540 (_this$responder19 = this.responder) === null || _this$responder19 === void 0 || _this$responder19.insertHTML(paste.html); 11541 this.requestRender(); 11542 (_this$delegate17 = this.delegate) === null || _this$delegate17 === void 0 || _this$delegate17.inputControllerDidPaste(paste); 11543 } else if (Array.from(clipboard.types).includes("Files")) { 11544 var _clipboard$items, _clipboard$items$getA; 11545 const file = (_clipboard$items = clipboard.items) === null || _clipboard$items === void 0 || (_clipboard$items = _clipboard$items[0]) === null || _clipboard$items === void 0 || (_clipboard$items$getA = _clipboard$items.getAsFile) === null || _clipboard$items$getA === void 0 ? void 0 : _clipboard$items$getA.call(_clipboard$items); 11546 if (file) { 11547 var _this$delegate18, _this$responder20, _this$delegate19; 11548 const extension = extensionForFile(file); 11549 if (!file.name && extension) { 11550 file.name = "pasted-file-".concat(++pastedFileCount, ".").concat(extension); 11551 } 11552 paste.type = "File"; 11553 paste.file = file; 11554 (_this$delegate18 = this.delegate) === null || _this$delegate18 === void 0 || _this$delegate18.inputControllerWillAttachFiles(); 11555 (_this$responder20 = this.responder) === null || _this$responder20 === void 0 || _this$responder20.insertFile(paste.file); 11556 this.requestRender(); 11557 (_this$delegate19 = this.delegate) === null || _this$delegate19 === void 0 || _this$delegate19.inputControllerDidPaste(paste); 11558 } 11559 } 11560 event.preventDefault(); 11561 }, 11562 compositionstart(event) { 11563 return this.getCompositionInput().start(event.data); 11564 }, 11565 compositionupdate(event) { 11566 return this.getCompositionInput().update(event.data); 11567 }, 11568 compositionend(event) { 11569 return this.getCompositionInput().end(event.data); 11570 }, 11571 beforeinput(event) { 11572 this.inputSummary.didInput = true; 11573 }, 11574 input(event) { 11575 this.inputSummary.didInput = true; 11576 return event.stopPropagation(); 11577 } 11578 }); 11579 _defineProperty(Level0InputController, "keys", { 11580 backspace(event) { 11581 var _this$delegate20; 11582 (_this$delegate20 = this.delegate) === null || _this$delegate20 === void 0 || _this$delegate20.inputControllerWillPerformTyping(); 11583 return this.deleteInDirection("backward", event); 11584 }, 11585 delete(event) { 11586 var _this$delegate21; 11587 (_this$delegate21 = this.delegate) === null || _this$delegate21 === void 0 || _this$delegate21.inputControllerWillPerformTyping(); 11588 return this.deleteInDirection("forward", event); 11589 }, 11590 return(event) { 11591 var _this$delegate22, _this$responder21; 11592 this.setInputSummary({ 11593 preferDocument: true 11594 }); 11595 (_this$delegate22 = this.delegate) === null || _this$delegate22 === void 0 || _this$delegate22.inputControllerWillPerformTyping(); 11596 return (_this$responder21 = this.responder) === null || _this$responder21 === void 0 ? void 0 : _this$responder21.insertLineBreak(); 11597 }, 11598 tab(event) { 11599 var _this$responder22; 11600 if ((_this$responder22 = this.responder) !== null && _this$responder22 !== void 0 && _this$responder22.canIncreaseNestingLevel()) { 11601 var _this$responder23; 11602 (_this$responder23 = this.responder) === null || _this$responder23 === void 0 || _this$responder23.increaseNestingLevel(); 11603 this.requestRender(); 11604 event.preventDefault(); 11605 } 11606 }, 11607 left(event) { 11608 if (this.selectionIsInCursorTarget()) { 11609 var _this$responder24; 11610 event.preventDefault(); 11611 return (_this$responder24 = this.responder) === null || _this$responder24 === void 0 ? void 0 : _this$responder24.moveCursorInDirection("backward"); 11612 } 11613 }, 11614 right(event) { 11615 if (this.selectionIsInCursorTarget()) { 11616 var _this$responder25; 11617 event.preventDefault(); 11618 return (_this$responder25 = this.responder) === null || _this$responder25 === void 0 ? void 0 : _this$responder25.moveCursorInDirection("forward"); 11619 } 11620 }, 11621 control: { 11622 d(event) { 11623 var _this$delegate23; 11624 (_this$delegate23 = this.delegate) === null || _this$delegate23 === void 0 || _this$delegate23.inputControllerWillPerformTyping(); 11625 return this.deleteInDirection("forward", event); 11626 }, 11627 h(event) { 11628 var _this$delegate24; 11629 (_this$delegate24 = this.delegate) === null || _this$delegate24 === void 0 || _this$delegate24.inputControllerWillPerformTyping(); 11630 return this.deleteInDirection("backward", event); 11631 }, 11632 o(event) { 11633 var _this$delegate25, _this$responder26; 11634 event.preventDefault(); 11635 (_this$delegate25 = this.delegate) === null || _this$delegate25 === void 0 || _this$delegate25.inputControllerWillPerformTyping(); 11636 (_this$responder26 = this.responder) === null || _this$responder26 === void 0 || _this$responder26.insertString("\n", { 11637 updatePosition: false 11638 }); 11639 return this.requestRender(); 11640 } 11641 }, 11642 shift: { 11643 return(event) { 11644 var _this$delegate26, _this$responder27; 11645 (_this$delegate26 = this.delegate) === null || _this$delegate26 === void 0 || _this$delegate26.inputControllerWillPerformTyping(); 11646 (_this$responder27 = this.responder) === null || _this$responder27 === void 0 || _this$responder27.insertString("\n"); 11647 this.requestRender(); 11648 event.preventDefault(); 11649 }, 11650 tab(event) { 11651 var _this$responder28; 11652 if ((_this$responder28 = this.responder) !== null && _this$responder28 !== void 0 && _this$responder28.canDecreaseNestingLevel()) { 11653 var _this$responder29; 11654 (_this$responder29 = this.responder) === null || _this$responder29 === void 0 || _this$responder29.decreaseNestingLevel(); 11655 this.requestRender(); 11656 event.preventDefault(); 11657 } 11658 }, 11659 left(event) { 11660 if (this.selectionIsInCursorTarget()) { 11661 event.preventDefault(); 11662 return this.expandSelectionInDirection("backward"); 11663 } 11664 }, 11665 right(event) { 11666 if (this.selectionIsInCursorTarget()) { 11667 event.preventDefault(); 11668 return this.expandSelectionInDirection("forward"); 11669 } 11670 } 11671 }, 11672 alt: { 11673 backspace(event) { 11674 var _this$delegate27; 11675 this.setInputSummary({ 11676 preferDocument: false 11677 }); 11678 return (_this$delegate27 = this.delegate) === null || _this$delegate27 === void 0 ? void 0 : _this$delegate27.inputControllerWillPerformTyping(); 11679 } 11680 }, 11681 meta: { 11682 backspace(event) { 11683 var _this$delegate28; 11684 this.setInputSummary({ 11685 preferDocument: false 11686 }); 11687 return (_this$delegate28 = this.delegate) === null || _this$delegate28 === void 0 ? void 0 : _this$delegate28.inputControllerWillPerformTyping(); 11688 } 11689 } 11690 }); 11691 Level0InputController.proxyMethod("responder?.getSelectedRange"); 11692 Level0InputController.proxyMethod("responder?.setSelectedRange"); 11693 Level0InputController.proxyMethod("responder?.expandSelectionInDirection"); 11694 Level0InputController.proxyMethod("responder?.selectionIsInCursorTarget"); 11695 Level0InputController.proxyMethod("responder?.selectionIsExpanded"); 11696 const extensionForFile = file => { 11697 var _file$type; 11698 return (_file$type = file.type) === null || _file$type === void 0 || (_file$type = _file$type.match(/\/(\w+)$/)) === null || _file$type === void 0 ? void 0 : _file$type[1]; 11699 }; 11700 const hasStringCodePointAt = !!((_$codePointAt = (_ = " ").codePointAt) !== null && _$codePointAt !== void 0 && _$codePointAt.call(_, 0)); 11701 const stringFromKeyEvent = function (event) { 11702 if (event.key && hasStringCodePointAt && event.key.codePointAt(0) === event.keyCode) { 11703 return event.key; 11704 } else { 11705 let code; 11706 if (event.which === null) { 11707 code = event.keyCode; 11708 } else if (event.which !== 0 && event.charCode !== 0) { 11709 code = event.charCode; 11710 } 11711 if (code != null && keyNames[code] !== "escape") { 11712 return UTF16String.fromCodepoints([code]).toString(); 11713 } 11714 } 11715 }; 11716 const pasteEventIsCrippledSafariHTMLPaste = function (event) { 11717 const paste = event.clipboardData; 11718 if (paste) { 11719 if (paste.types.includes("text/html")) { 11720 // Answer is yes if there's any possibility of Paste and Match Style in Safari, 11721 // which is nearly impossible to detect confidently: https://bugs.webkit.org/show_bug.cgi?id=174165 11722 for (const type of paste.types) { 11723 const hasPasteboardFlavor = /^CorePasteboardFlavorType/.test(type); 11724 const hasReadableDynamicData = /^dyn\./.test(type) && paste.getData(type); 11725 const mightBePasteAndMatchStyle = hasPasteboardFlavor || hasReadableDynamicData; 11726 if (mightBePasteAndMatchStyle) { 11727 return true; 11728 } 11729 } 11730 return false; 11731 } else { 11732 const isExternalHTMLPaste = paste.types.includes("com.apple.webarchive"); 11733 const isExternalRichTextPaste = paste.types.includes("com.apple.flat-rtfd"); 11734 return isExternalHTMLPaste || isExternalRichTextPaste; 11735 } 11736 } 11737 }; 11738 class CompositionInput extends BasicObject { 11739 constructor(inputController) { 11740 super(...arguments); 11741 this.inputController = inputController; 11742 this.responder = this.inputController.responder; 11743 this.delegate = this.inputController.delegate; 11744 this.inputSummary = this.inputController.inputSummary; 11745 this.data = {}; 11746 } 11747 start(data) { 11748 this.data.start = data; 11749 if (this.isSignificant()) { 11750 var _this$responder5; 11751 if (this.inputSummary.eventName === "keypress" && this.inputSummary.textAdded) { 11752 var _this$responder4; 11753 (_this$responder4 = this.responder) === null || _this$responder4 === void 0 || _this$responder4.deleteInDirection("left"); 11754 } 11755 if (!this.selectionIsExpanded()) { 11756 this.insertPlaceholder(); 11757 this.requestRender(); 11758 } 11759 this.range = (_this$responder5 = this.responder) === null || _this$responder5 === void 0 ? void 0 : _this$responder5.getSelectedRange(); 11760 } 11761 } 11762 update(data) { 11763 this.data.update = data; 11764 if (this.isSignificant()) { 11765 const range = this.selectPlaceholder(); 11766 if (range) { 11767 this.forgetPlaceholder(); 11768 this.range = range; 11769 } 11770 } 11771 } 11772 end(data) { 11773 this.data.end = data; 11774 if (this.isSignificant()) { 11775 this.forgetPlaceholder(); 11776 if (this.canApplyToDocument()) { 11777 var _this$delegate2, _this$responder6, _this$responder7, _this$responder8; 11778 this.setInputSummary({ 11779 preferDocument: true, 11780 didInput: false 11781 }); 11782 (_this$delegate2 = this.delegate) === null || _this$delegate2 === void 0 || _this$delegate2.inputControllerWillPerformTyping(); 11783 (_this$responder6 = this.responder) === null || _this$responder6 === void 0 || _this$responder6.setSelectedRange(this.range); 11784 (_this$responder7 = this.responder) === null || _this$responder7 === void 0 || _this$responder7.insertString(this.data.end); 11785 return (_this$responder8 = this.responder) === null || _this$responder8 === void 0 ? void 0 : _this$responder8.setSelectedRange(this.range[0] + this.data.end.length); 11786 } else if (this.data.start != null || this.data.update != null) { 11787 this.requestReparse(); 11788 return this.inputController.reset(); 11789 } 11790 } else { 11791 return this.inputController.reset(); 11792 } 11793 } 11794 getEndData() { 11795 return this.data.end; 11796 } 11797 isEnded() { 11798 return this.getEndData() != null; 11799 } 11800 isSignificant() { 11801 if (browser.composesExistingText) { 11802 return this.inputSummary.didInput; 11803 } else { 11804 return true; 11805 } 11806 } 11807 11808 // Private 11809 11810 canApplyToDocument() { 11811 var _this$data$start, _this$data$end; 11812 return ((_this$data$start = this.data.start) === null || _this$data$start === void 0 ? void 0 : _this$data$start.length) === 0 && ((_this$data$end = this.data.end) === null || _this$data$end === void 0 ? void 0 : _this$data$end.length) > 0 && this.range; 11813 } 11814 } 11815 CompositionInput.proxyMethod("inputController.setInputSummary"); 11816 CompositionInput.proxyMethod("inputController.requestRender"); 11817 CompositionInput.proxyMethod("inputController.requestReparse"); 11818 CompositionInput.proxyMethod("responder?.selectionIsExpanded"); 11819 CompositionInput.proxyMethod("responder?.insertPlaceholder"); 11820 CompositionInput.proxyMethod("responder?.selectPlaceholder"); 11821 CompositionInput.proxyMethod("responder?.forgetPlaceholder"); 11822 11823 class Level2InputController extends InputController { 11824 constructor() { 11825 super(...arguments); 11826 this.render = this.render.bind(this); 11827 } 11828 elementDidMutate() { 11829 if (this.scheduledRender) { 11830 if (this.composing) { 11831 var _this$delegate, _this$delegate$inputC; 11832 return (_this$delegate = this.delegate) === null || _this$delegate === void 0 || (_this$delegate$inputC = _this$delegate.inputControllerDidAllowUnhandledInput) === null || _this$delegate$inputC === void 0 ? void 0 : _this$delegate$inputC.call(_this$delegate); 11833 } 11834 } else { 11835 return this.reparse(); 11836 } 11837 } 11838 scheduleRender() { 11839 return this.scheduledRender ? this.scheduledRender : this.scheduledRender = requestAnimationFrame(this.render); 11840 } 11841 render() { 11842 var _this$afterRender; 11843 cancelAnimationFrame(this.scheduledRender); 11844 this.scheduledRender = null; 11845 if (!this.composing) { 11846 var _this$delegate2; 11847 (_this$delegate2 = this.delegate) === null || _this$delegate2 === void 0 || _this$delegate2.render(); 11848 } 11849 (_this$afterRender = this.afterRender) === null || _this$afterRender === void 0 || _this$afterRender.call(this); 11850 this.afterRender = null; 11851 } 11852 reparse() { 11853 var _this$delegate3; 11854 return (_this$delegate3 = this.delegate) === null || _this$delegate3 === void 0 ? void 0 : _this$delegate3.reparse(); 11855 } 11856 11857 // Responder helpers 11858 11859 insertString() { 11860 var _this$delegate4; 11861 let string = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; 11862 let options = arguments.length > 1 ? arguments[1] : undefined; 11863 (_this$delegate4 = this.delegate) === null || _this$delegate4 === void 0 || _this$delegate4.inputControllerWillPerformTyping(); 11864 return this.withTargetDOMRange(function () { 11865 var _this$responder; 11866 return (_this$responder = this.responder) === null || _this$responder === void 0 ? void 0 : _this$responder.insertString(string, options); 11867 }); 11868 } 11869 toggleAttributeIfSupported(attributeName) { 11870 if (getAllAttributeNames().includes(attributeName)) { 11871 var _this$delegate5; 11872 (_this$delegate5 = this.delegate) === null || _this$delegate5 === void 0 || _this$delegate5.inputControllerWillPerformFormatting(attributeName); 11873 return this.withTargetDOMRange(function () { 11874 var _this$responder2; 11875 return (_this$responder2 = this.responder) === null || _this$responder2 === void 0 ? void 0 : _this$responder2.toggleCurrentAttribute(attributeName); 11876 }); 11877 } 11878 } 11879 activateAttributeIfSupported(attributeName, value) { 11880 if (getAllAttributeNames().includes(attributeName)) { 11881 var _this$delegate6; 11882 (_this$delegate6 = this.delegate) === null || _this$delegate6 === void 0 || _this$delegate6.inputControllerWillPerformFormatting(attributeName); 11883 return this.withTargetDOMRange(function () { 11884 var _this$responder3; 11885 return (_this$responder3 = this.responder) === null || _this$responder3 === void 0 ? void 0 : _this$responder3.setCurrentAttribute(attributeName, value); 11886 }); 11887 } 11888 } 11889 deleteInDirection(direction) { 11890 let { 11891 recordUndoEntry 11892 } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { 11893 recordUndoEntry: true 11894 }; 11895 if (recordUndoEntry) { 11896 var _this$delegate7; 11897 (_this$delegate7 = this.delegate) === null || _this$delegate7 === void 0 || _this$delegate7.inputControllerWillPerformTyping(); 11898 } 11899 const perform = () => { 11900 var _this$responder4; 11901 return (_this$responder4 = this.responder) === null || _this$responder4 === void 0 ? void 0 : _this$responder4.deleteInDirection(direction); 11902 }; 11903 const domRange = this.getTargetDOMRange({ 11904 minLength: this.composing ? 1 : 2 11905 }); 11906 if (domRange) { 11907 return this.withTargetDOMRange(domRange, perform); 11908 } else { 11909 return perform(); 11910 } 11911 } 11912 11913 // Selection helpers 11914 11915 withTargetDOMRange(domRange, fn) { 11916 if (typeof domRange === "function") { 11917 fn = domRange; 11918 domRange = this.getTargetDOMRange(); 11919 } 11920 if (domRange) { 11921 var _this$responder5; 11922 return (_this$responder5 = this.responder) === null || _this$responder5 === void 0 ? void 0 : _this$responder5.withTargetDOMRange(domRange, fn.bind(this)); 11923 } else { 11924 selectionChangeObserver.reset(); 11925 return fn.call(this); 11926 } 11927 } 11928 getTargetDOMRange() { 11929 var _this$event$getTarget, _this$event; 11930 let { 11931 minLength 11932 } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { 11933 minLength: 0 11934 }; 11935 const targetRanges = (_this$event$getTarget = (_this$event = this.event).getTargetRanges) === null || _this$event$getTarget === void 0 ? void 0 : _this$event$getTarget.call(_this$event); 11936 if (targetRanges) { 11937 if (targetRanges.length) { 11938 const domRange = staticRangeToRange(targetRanges[0]); 11939 if (minLength === 0 || domRange.toString().length >= minLength) { 11940 return domRange; 11941 } 11942 } 11943 } 11944 } 11945 withEvent(event, fn) { 11946 let result; 11947 this.event = event; 11948 try { 11949 result = fn.call(this); 11950 } finally { 11951 this.event = null; 11952 } 11953 return result; 11954 } 11955 } 11956 _defineProperty(Level2InputController, "events", { 11957 keydown(event) { 11958 if (keyEventIsKeyboardCommand(event)) { 11959 var _this$delegate8; 11960 const command = keyboardCommandFromKeyEvent(event); 11961 if ((_this$delegate8 = this.delegate) !== null && _this$delegate8 !== void 0 && _this$delegate8.inputControllerDidReceiveKeyboardCommand(command)) { 11962 event.preventDefault(); 11963 } 11964 } else { 11965 let name = event.key; 11966 if (event.altKey) { 11967 name += "+Alt"; 11968 } 11969 if (event.shiftKey) { 11970 name += "+Shift"; 11971 } 11972 const handler = this.constructor.keys[name]; 11973 if (handler) { 11974 return this.withEvent(event, handler); 11975 } 11976 } 11977 }, 11978 // Handle paste event to work around beforeinput.insertFromPaste browser bugs. 11979 // Safe to remove each condition once fixed upstream. 11980 paste(event) { 11981 var _event$clipboardData; 11982 // https://bugs.webkit.org/show_bug.cgi?id=194921 11983 let paste; 11984 const href = (_event$clipboardData = event.clipboardData) === null || _event$clipboardData === void 0 ? void 0 : _event$clipboardData.getData("URL"); 11985 if (pasteEventHasFilesOnly(event)) { 11986 event.preventDefault(); 11987 return this.attachFiles(event.clipboardData.files); 11988 11989 // https://bugs.chromium.org/p/chromium/issues/detail?id=934448 11990 } else if (pasteEventHasPlainTextOnly(event)) { 11991 var _this$delegate9, _this$responder6, _this$delegate10; 11992 event.preventDefault(); 11993 paste = { 11994 type: "text/plain", 11995 string: event.clipboardData.getData("text/plain") 11996 }; 11997 (_this$delegate9 = this.delegate) === null || _this$delegate9 === void 0 || _this$delegate9.inputControllerWillPaste(paste); 11998 (_this$responder6 = this.responder) === null || _this$responder6 === void 0 || _this$responder6.insertString(paste.string); 11999 this.render(); 12000 return (_this$delegate10 = this.delegate) === null || _this$delegate10 === void 0 ? void 0 : _this$delegate10.inputControllerDidPaste(paste); 12001 12002 // https://bugs.webkit.org/show_bug.cgi?id=196702 12003 } else if (href) { 12004 var _this$delegate11, _this$responder7, _this$delegate12; 12005 event.preventDefault(); 12006 paste = { 12007 type: "text/html", 12008 html: this.createLinkHTML(href) 12009 }; 12010 (_this$delegate11 = this.delegate) === null || _this$delegate11 === void 0 || _this$delegate11.inputControllerWillPaste(paste); 12011 (_this$responder7 = this.responder) === null || _this$responder7 === void 0 || _this$responder7.insertHTML(paste.html); 12012 this.render(); 12013 return (_this$delegate12 = this.delegate) === null || _this$delegate12 === void 0 ? void 0 : _this$delegate12.inputControllerDidPaste(paste); 12014 } 12015 }, 12016 beforeinput(event) { 12017 const handler = this.constructor.inputTypes[event.inputType]; 12018 const immmediateRender = shouldRenderInmmediatelyToDealWithIOSDictation(event); 12019 if (handler) { 12020 this.withEvent(event, handler); 12021 if (!immmediateRender) { 12022 this.scheduleRender(); 12023 } 12024 } 12025 if (immmediateRender) { 12026 this.render(); 12027 } 12028 }, 12029 input(event) { 12030 selectionChangeObserver.reset(); 12031 }, 12032 dragstart(event) { 12033 var _this$responder8; 12034 if ((_this$responder8 = this.responder) !== null && _this$responder8 !== void 0 && _this$responder8.selectionContainsAttachments()) { 12035 var _this$responder9; 12036 event.dataTransfer.setData("application/x-trix-dragging", true); 12037 this.dragging = { 12038 range: (_this$responder9 = this.responder) === null || _this$responder9 === void 0 ? void 0 : _this$responder9.getSelectedRange(), 12039 point: pointFromEvent(event) 12040 }; 12041 } 12042 }, 12043 dragenter(event) { 12044 if (dragEventHasFiles(event)) { 12045 event.preventDefault(); 12046 } 12047 }, 12048 dragover(event) { 12049 if (this.dragging) { 12050 event.preventDefault(); 12051 const point = pointFromEvent(event); 12052 if (!objectsAreEqual(point, this.dragging.point)) { 12053 var _this$responder10; 12054 this.dragging.point = point; 12055 return (_this$responder10 = this.responder) === null || _this$responder10 === void 0 ? void 0 : _this$responder10.setLocationRangeFromPointRange(point); 12056 } 12057 } else if (dragEventHasFiles(event)) { 12058 event.preventDefault(); 12059 } 12060 }, 12061 drop(event) { 12062 if (this.dragging) { 12063 var _this$delegate13, _this$responder11; 12064 event.preventDefault(); 12065 (_this$delegate13 = this.delegate) === null || _this$delegate13 === void 0 || _this$delegate13.inputControllerWillMoveText(); 12066 (_this$responder11 = this.responder) === null || _this$responder11 === void 0 || _this$responder11.moveTextFromRange(this.dragging.range); 12067 this.dragging = null; 12068 return this.scheduleRender(); 12069 } else if (dragEventHasFiles(event)) { 12070 var _this$responder12; 12071 event.preventDefault(); 12072 const point = pointFromEvent(event); 12073 (_this$responder12 = this.responder) === null || _this$responder12 === void 0 || _this$responder12.setLocationRangeFromPointRange(point); 12074 return this.attachFiles(event.dataTransfer.files); 12075 } 12076 }, 12077 dragend() { 12078 if (this.dragging) { 12079 var _this$responder13; 12080 (_this$responder13 = this.responder) === null || _this$responder13 === void 0 || _this$responder13.setSelectedRange(this.dragging.range); 12081 this.dragging = null; 12082 } 12083 }, 12084 compositionend(event) { 12085 if (this.composing) { 12086 this.composing = false; 12087 if (!browser$1.recentAndroid) this.scheduleRender(); 12088 } 12089 } 12090 }); 12091 _defineProperty(Level2InputController, "keys", { 12092 ArrowLeft() { 12093 var _this$responder14; 12094 if ((_this$responder14 = this.responder) !== null && _this$responder14 !== void 0 && _this$responder14.shouldManageMovingCursorInDirection("backward")) { 12095 var _this$responder15; 12096 this.event.preventDefault(); 12097 return (_this$responder15 = this.responder) === null || _this$responder15 === void 0 ? void 0 : _this$responder15.moveCursorInDirection("backward"); 12098 } 12099 }, 12100 ArrowRight() { 12101 var _this$responder16; 12102 if ((_this$responder16 = this.responder) !== null && _this$responder16 !== void 0 && _this$responder16.shouldManageMovingCursorInDirection("forward")) { 12103 var _this$responder17; 12104 this.event.preventDefault(); 12105 return (_this$responder17 = this.responder) === null || _this$responder17 === void 0 ? void 0 : _this$responder17.moveCursorInDirection("forward"); 12106 } 12107 }, 12108 Backspace() { 12109 var _this$responder18; 12110 if ((_this$responder18 = this.responder) !== null && _this$responder18 !== void 0 && _this$responder18.shouldManageDeletingInDirection("backward")) { 12111 var _this$delegate14, _this$responder19; 12112 this.event.preventDefault(); 12113 (_this$delegate14 = this.delegate) === null || _this$delegate14 === void 0 || _this$delegate14.inputControllerWillPerformTyping(); 12114 (_this$responder19 = this.responder) === null || _this$responder19 === void 0 || _this$responder19.deleteInDirection("backward"); 12115 return this.render(); 12116 } 12117 }, 12118 Tab() { 12119 var _this$responder20; 12120 if ((_this$responder20 = this.responder) !== null && _this$responder20 !== void 0 && _this$responder20.canIncreaseNestingLevel()) { 12121 var _this$responder21; 12122 this.event.preventDefault(); 12123 (_this$responder21 = this.responder) === null || _this$responder21 === void 0 || _this$responder21.increaseNestingLevel(); 12124 return this.render(); 12125 } 12126 }, 12127 "Tab+Shift"() { 12128 var _this$responder22; 12129 if ((_this$responder22 = this.responder) !== null && _this$responder22 !== void 0 && _this$responder22.canDecreaseNestingLevel()) { 12130 var _this$responder23; 12131 this.event.preventDefault(); 12132 (_this$responder23 = this.responder) === null || _this$responder23 === void 0 || _this$responder23.decreaseNestingLevel(); 12133 return this.render(); 12134 } 12135 } 12136 }); 12137 _defineProperty(Level2InputController, "inputTypes", { 12138 deleteByComposition() { 12139 return this.deleteInDirection("backward", { 12140 recordUndoEntry: false 12141 }); 12142 }, 12143 deleteByCut() { 12144 return this.deleteInDirection("backward"); 12145 }, 12146 deleteByDrag() { 12147 this.event.preventDefault(); 12148 return this.withTargetDOMRange(function () { 12149 var _this$responder24; 12150 this.deleteByDragRange = (_this$responder24 = this.responder) === null || _this$responder24 === void 0 ? void 0 : _this$responder24.getSelectedRange(); 12151 }); 12152 }, 12153 deleteCompositionText() { 12154 return this.deleteInDirection("backward", { 12155 recordUndoEntry: false 12156 }); 12157 }, 12158 deleteContent() { 12159 return this.deleteInDirection("backward"); 12160 }, 12161 deleteContentBackward() { 12162 return this.deleteInDirection("backward"); 12163 }, 12164 deleteContentForward() { 12165 return this.deleteInDirection("forward"); 12166 }, 12167 deleteEntireSoftLine() { 12168 return this.deleteInDirection("forward"); 12169 }, 12170 deleteHardLineBackward() { 12171 return this.deleteInDirection("backward"); 12172 }, 12173 deleteHardLineForward() { 12174 return this.deleteInDirection("forward"); 12175 }, 12176 deleteSoftLineBackward() { 12177 return this.deleteInDirection("backward"); 12178 }, 12179 deleteSoftLineForward() { 12180 return this.deleteInDirection("forward"); 12181 }, 12182 deleteWordBackward() { 12183 return this.deleteInDirection("backward"); 12184 }, 12185 deleteWordForward() { 12186 return this.deleteInDirection("forward"); 12187 }, 12188 formatBackColor() { 12189 return this.activateAttributeIfSupported("backgroundColor", this.event.data); 12190 }, 12191 formatBold() { 12192 return this.toggleAttributeIfSupported("bold"); 12193 }, 12194 formatFontColor() { 12195 return this.activateAttributeIfSupported("color", this.event.data); 12196 }, 12197 formatFontName() { 12198 return this.activateAttributeIfSupported("font", this.event.data); 12199 }, 12200 formatIndent() { 12201 var _this$responder25; 12202 if ((_this$responder25 = this.responder) !== null && _this$responder25 !== void 0 && _this$responder25.canIncreaseNestingLevel()) { 12203 return this.withTargetDOMRange(function () { 12204 var _this$responder26; 12205 return (_this$responder26 = this.responder) === null || _this$responder26 === void 0 ? void 0 : _this$responder26.increaseNestingLevel(); 12206 }); 12207 } 12208 }, 12209 formatItalic() { 12210 return this.toggleAttributeIfSupported("italic"); 12211 }, 12212 formatJustifyCenter() { 12213 return this.toggleAttributeIfSupported("justifyCenter"); 12214 }, 12215 formatJustifyFull() { 12216 return this.toggleAttributeIfSupported("justifyFull"); 12217 }, 12218 formatJustifyLeft() { 12219 return this.toggleAttributeIfSupported("justifyLeft"); 12220 }, 12221 formatJustifyRight() { 12222 return this.toggleAttributeIfSupported("justifyRight"); 12223 }, 12224 formatOutdent() { 12225 var _this$responder27; 12226 if ((_this$responder27 = this.responder) !== null && _this$responder27 !== void 0 && _this$responder27.canDecreaseNestingLevel()) { 12227 return this.withTargetDOMRange(function () { 12228 var _this$responder28; 12229 return (_this$responder28 = this.responder) === null || _this$responder28 === void 0 ? void 0 : _this$responder28.decreaseNestingLevel(); 12230 }); 12231 } 12232 }, 12233 formatRemove() { 12234 this.withTargetDOMRange(function () { 12235 for (const attributeName in (_this$responder29 = this.responder) === null || _this$responder29 === void 0 ? void 0 : _this$responder29.getCurrentAttributes()) { 12236 var _this$responder29, _this$responder30; 12237 (_this$responder30 = this.responder) === null || _this$responder30 === void 0 || _this$responder30.removeCurrentAttribute(attributeName); 12238 } 12239 }); 12240 }, 12241 formatSetBlockTextDirection() { 12242 return this.activateAttributeIfSupported("blockDir", this.event.data); 12243 }, 12244 formatSetInlineTextDirection() { 12245 return this.activateAttributeIfSupported("textDir", this.event.data); 12246 }, 12247 formatStrikeThrough() { 12248 return this.toggleAttributeIfSupported("strike"); 12249 }, 12250 formatSubscript() { 12251 return this.toggleAttributeIfSupported("sub"); 12252 }, 12253 formatSuperscript() { 12254 return this.toggleAttributeIfSupported("sup"); 12255 }, 12256 formatUnderline() { 12257 return this.toggleAttributeIfSupported("underline"); 12258 }, 12259 historyRedo() { 12260 var _this$delegate15; 12261 return (_this$delegate15 = this.delegate) === null || _this$delegate15 === void 0 ? void 0 : _this$delegate15.inputControllerWillPerformRedo(); 12262 }, 12263 historyUndo() { 12264 var _this$delegate16; 12265 return (_this$delegate16 = this.delegate) === null || _this$delegate16 === void 0 ? void 0 : _this$delegate16.inputControllerWillPerformUndo(); 12266 }, 12267 insertCompositionText() { 12268 this.composing = true; 12269 return this.insertString(this.event.data); 12270 }, 12271 insertFromComposition() { 12272 this.composing = false; 12273 return this.insertString(this.event.data); 12274 }, 12275 insertFromDrop() { 12276 const range = this.deleteByDragRange; 12277 if (range) { 12278 var _this$delegate17; 12279 this.deleteByDragRange = null; 12280 (_this$delegate17 = this.delegate) === null || _this$delegate17 === void 0 || _this$delegate17.inputControllerWillMoveText(); 12281 return this.withTargetDOMRange(function () { 12282 var _this$responder31; 12283 return (_this$responder31 = this.responder) === null || _this$responder31 === void 0 ? void 0 : _this$responder31.moveTextFromRange(range); 12284 }); 12285 } 12286 }, 12287 insertFromPaste() { 12288 const { 12289 dataTransfer 12290 } = this.event; 12291 const paste = { 12292 dataTransfer 12293 }; 12294 const href = dataTransfer.getData("URL"); 12295 const html = dataTransfer.getData("text/html"); 12296 if (href) { 12297 var _this$delegate18; 12298 let string; 12299 this.event.preventDefault(); 12300 paste.type = "text/html"; 12301 const name = dataTransfer.getData("public.url-name"); 12302 if (name) { 12303 string = squishBreakableWhitespace(name).trim(); 12304 } else { 12305 string = href; 12306 } 12307 paste.html = this.createLinkHTML(href, string); 12308 (_this$delegate18 = this.delegate) === null || _this$delegate18 === void 0 || _this$delegate18.inputControllerWillPaste(paste); 12309 this.withTargetDOMRange(function () { 12310 var _this$responder32; 12311 return (_this$responder32 = this.responder) === null || _this$responder32 === void 0 ? void 0 : _this$responder32.insertHTML(paste.html); 12312 }); 12313 this.afterRender = () => { 12314 var _this$delegate19; 12315 return (_this$delegate19 = this.delegate) === null || _this$delegate19 === void 0 ? void 0 : _this$delegate19.inputControllerDidPaste(paste); 12316 }; 12317 } else if (dataTransferIsPlainText(dataTransfer)) { 12318 var _this$delegate20; 12319 paste.type = "text/plain"; 12320 paste.string = dataTransfer.getData("text/plain"); 12321 (_this$delegate20 = this.delegate) === null || _this$delegate20 === void 0 || _this$delegate20.inputControllerWillPaste(paste); 12322 this.withTargetDOMRange(function () { 12323 var _this$responder33; 12324 return (_this$responder33 = this.responder) === null || _this$responder33 === void 0 ? void 0 : _this$responder33.insertString(paste.string); 12325 }); 12326 this.afterRender = () => { 12327 var _this$delegate21; 12328 return (_this$delegate21 = this.delegate) === null || _this$delegate21 === void 0 ? void 0 : _this$delegate21.inputControllerDidPaste(paste); 12329 }; 12330 } else if (processableFilePaste(this.event)) { 12331 var _this$delegate22; 12332 paste.type = "File"; 12333 paste.file = dataTransfer.files[0]; 12334 (_this$delegate22 = this.delegate) === null || _this$delegate22 === void 0 || _this$delegate22.inputControllerWillPaste(paste); 12335 this.withTargetDOMRange(function () { 12336 var _this$responder34; 12337 return (_this$responder34 = this.responder) === null || _this$responder34 === void 0 ? void 0 : _this$responder34.insertFile(paste.file); 12338 }); 12339 this.afterRender = () => { 12340 var _this$delegate23; 12341 return (_this$delegate23 = this.delegate) === null || _this$delegate23 === void 0 ? void 0 : _this$delegate23.inputControllerDidPaste(paste); 12342 }; 12343 } else if (html) { 12344 var _this$delegate24; 12345 this.event.preventDefault(); 12346 paste.type = "text/html"; 12347 paste.html = html; 12348 (_this$delegate24 = this.delegate) === null || _this$delegate24 === void 0 || _this$delegate24.inputControllerWillPaste(paste); 12349 this.withTargetDOMRange(function () { 12350 var _this$responder35; 12351 return (_this$responder35 = this.responder) === null || _this$responder35 === void 0 ? void 0 : _this$responder35.insertHTML(paste.html); 12352 }); 12353 this.afterRender = () => { 12354 var _this$delegate25; 12355 return (_this$delegate25 = this.delegate) === null || _this$delegate25 === void 0 ? void 0 : _this$delegate25.inputControllerDidPaste(paste); 12356 }; 12357 } 12358 }, 12359 insertFromYank() { 12360 return this.insertString(this.event.data); 12361 }, 12362 insertLineBreak() { 12363 return this.insertString("\n"); 12364 }, 12365 insertLink() { 12366 return this.activateAttributeIfSupported("href", this.event.data); 12367 }, 12368 insertOrderedList() { 12369 return this.toggleAttributeIfSupported("number"); 12370 }, 12371 insertParagraph() { 12372 var _this$delegate26; 12373 (_this$delegate26 = this.delegate) === null || _this$delegate26 === void 0 || _this$delegate26.inputControllerWillPerformTyping(); 12374 return this.withTargetDOMRange(function () { 12375 var _this$responder36; 12376 return (_this$responder36 = this.responder) === null || _this$responder36 === void 0 ? void 0 : _this$responder36.insertLineBreak(); 12377 }); 12378 }, 12379 insertReplacementText() { 12380 const replacement = this.event.dataTransfer.getData("text/plain"); 12381 const domRange = this.event.getTargetRanges()[0]; 12382 this.withTargetDOMRange(domRange, () => { 12383 this.insertString(replacement, { 12384 updatePosition: false 12385 }); 12386 }); 12387 }, 12388 insertText() { 12389 var _this$event$dataTrans; 12390 return this.insertString(this.event.data || ((_this$event$dataTrans = this.event.dataTransfer) === null || _this$event$dataTrans === void 0 ? void 0 : _this$event$dataTrans.getData("text/plain"))); 12391 }, 12392 insertTranspose() { 12393 return this.insertString(this.event.data); 12394 }, 12395 insertUnorderedList() { 12396 return this.toggleAttributeIfSupported("bullet"); 12397 } 12398 }); 12399 const staticRangeToRange = function (staticRange) { 12400 const range = document.createRange(); 12401 range.setStart(staticRange.startContainer, staticRange.startOffset); 12402 range.setEnd(staticRange.endContainer, staticRange.endOffset); 12403 return range; 12404 }; 12405 12406 // Event helpers 12407 12408 const dragEventHasFiles = event => { 12409 var _event$dataTransfer; 12410 return Array.from(((_event$dataTransfer = event.dataTransfer) === null || _event$dataTransfer === void 0 ? void 0 : _event$dataTransfer.types) || []).includes("Files"); 12411 }; 12412 const processableFilePaste = event => { 12413 var _event$dataTransfer$f; 12414 // Paste events that only have files are handled by the paste event handler, 12415 // to work around Safari not supporting beforeinput.insertFromPaste for files. 12416 12417 // MS Office text pastes include a file with a screenshot of the text, but we should 12418 // handle them as text pastes. 12419 return ((_event$dataTransfer$f = event.dataTransfer.files) === null || _event$dataTransfer$f === void 0 ? void 0 : _event$dataTransfer$f[0]) && !pasteEventHasFilesOnly(event) && !dataTransferIsMsOfficePaste(event); 12420 }; 12421 const pasteEventHasFilesOnly = function (event) { 12422 const clipboard = event.clipboardData; 12423 if (clipboard) { 12424 const fileTypes = Array.from(clipboard.types).filter(type => type.match(/file/i)); // "Files", "application/x-moz-file" 12425 return fileTypes.length === clipboard.types.length && clipboard.files.length >= 1; 12426 } 12427 }; 12428 const pasteEventHasPlainTextOnly = function (event) { 12429 const clipboard = event.clipboardData; 12430 if (clipboard) { 12431 return clipboard.types.includes("text/plain") && clipboard.types.length === 1; 12432 } 12433 }; 12434 const keyboardCommandFromKeyEvent = function (event) { 12435 const command = []; 12436 if (event.altKey) { 12437 command.push("alt"); 12438 } 12439 if (event.shiftKey) { 12440 command.push("shift"); 12441 } 12442 command.push(event.key); 12443 return command; 12444 }; 12445 const pointFromEvent = event => ({ 12446 x: event.clientX, 12447 y: event.clientY 12448 }); 12449 12450 const attributeButtonSelector = "[data-trix-attribute]"; 12451 const actionButtonSelector = "[data-trix-action]"; 12452 const toolbarButtonSelector = "".concat(attributeButtonSelector, ", ").concat(actionButtonSelector); 12453 const dialogSelector = "[data-trix-dialog]"; 12454 const activeDialogSelector = "".concat(dialogSelector, "[data-trix-active]"); 12455 const dialogButtonSelector = "".concat(dialogSelector, " [data-trix-method]"); 12456 const dialogInputSelector = "".concat(dialogSelector, " [data-trix-input]"); 12457 const getInputForDialog = (element, attributeName) => { 12458 if (!attributeName) { 12459 attributeName = getAttributeName(element); 12460 } 12461 return element.querySelector("[data-trix-input][name='".concat(attributeName, "']")); 12462 }; 12463 const getActionName = element => element.getAttribute("data-trix-action"); 12464 const getAttributeName = element => { 12465 return element.getAttribute("data-trix-attribute") || element.getAttribute("data-trix-dialog-attribute"); 12466 }; 12467 const getDialogName = element => element.getAttribute("data-trix-dialog"); 12468 class ToolbarController extends BasicObject { 12469 constructor(element) { 12470 super(element); 12471 this.didClickActionButton = this.didClickActionButton.bind(this); 12472 this.didClickAttributeButton = this.didClickAttributeButton.bind(this); 12473 this.didClickDialogButton = this.didClickDialogButton.bind(this); 12474 this.didKeyDownDialogInput = this.didKeyDownDialogInput.bind(this); 12475 this.element = element; 12476 this.attributes = {}; 12477 this.actions = {}; 12478 this.resetDialogInputs(); 12479 handleEvent("mousedown", { 12480 onElement: this.element, 12481 matchingSelector: actionButtonSelector, 12482 withCallback: this.didClickActionButton 12483 }); 12484 handleEvent("mousedown", { 12485 onElement: this.element, 12486 matchingSelector: attributeButtonSelector, 12487 withCallback: this.didClickAttributeButton 12488 }); 12489 handleEvent("click", { 12490 onElement: this.element, 12491 matchingSelector: toolbarButtonSelector, 12492 preventDefault: true 12493 }); 12494 handleEvent("click", { 12495 onElement: this.element, 12496 matchingSelector: dialogButtonSelector, 12497 withCallback: this.didClickDialogButton 12498 }); 12499 handleEvent("keydown", { 12500 onElement: this.element, 12501 matchingSelector: dialogInputSelector, 12502 withCallback: this.didKeyDownDialogInput 12503 }); 12504 } 12505 12506 // Event handlers 12507 12508 didClickActionButton(event, element) { 12509 var _this$delegate; 12510 (_this$delegate = this.delegate) === null || _this$delegate === void 0 || _this$delegate.toolbarDidClickButton(); 12511 event.preventDefault(); 12512 const actionName = getActionName(element); 12513 if (this.getDialog(actionName)) { 12514 return this.toggleDialog(actionName); 12515 } else { 12516 var _this$delegate2; 12517 return (_this$delegate2 = this.delegate) === null || _this$delegate2 === void 0 ? void 0 : _this$delegate2.toolbarDidInvokeAction(actionName, element); 12518 } 12519 } 12520 didClickAttributeButton(event, element) { 12521 var _this$delegate3; 12522 (_this$delegate3 = this.delegate) === null || _this$delegate3 === void 0 || _this$delegate3.toolbarDidClickButton(); 12523 event.preventDefault(); 12524 const attributeName = getAttributeName(element); 12525 if (this.getDialog(attributeName)) { 12526 this.toggleDialog(attributeName); 12527 } else { 12528 var _this$delegate4; 12529 (_this$delegate4 = this.delegate) === null || _this$delegate4 === void 0 || _this$delegate4.toolbarDidToggleAttribute(attributeName); 12530 } 12531 return this.refreshAttributeButtons(); 12532 } 12533 didClickDialogButton(event, element) { 12534 const dialogElement = findClosestElementFromNode(element, { 12535 matchingSelector: dialogSelector 12536 }); 12537 const method = element.getAttribute("data-trix-method"); 12538 return this[method].call(this, dialogElement); 12539 } 12540 didKeyDownDialogInput(event, element) { 12541 if (event.keyCode === 13) { 12542 // Enter key 12543 event.preventDefault(); 12544 const attribute = element.getAttribute("name"); 12545 const dialog = this.getDialog(attribute); 12546 this.setAttribute(dialog); 12547 } 12548 if (event.keyCode === 27) { 12549 // Escape key 12550 event.preventDefault(); 12551 return this.hideDialog(); 12552 } 12553 } 12554 12555 // Action buttons 12556 12557 updateActions(actions) { 12558 this.actions = actions; 12559 return this.refreshActionButtons(); 12560 } 12561 refreshActionButtons() { 12562 return this.eachActionButton((element, actionName) => { 12563 element.disabled = this.actions[actionName] === false; 12564 }); 12565 } 12566 eachActionButton(callback) { 12567 return Array.from(this.element.querySelectorAll(actionButtonSelector)).map(element => callback(element, getActionName(element))); 12568 } 12569 12570 // Attribute buttons 12571 12572 updateAttributes(attributes) { 12573 this.attributes = attributes; 12574 return this.refreshAttributeButtons(); 12575 } 12576 refreshAttributeButtons() { 12577 return this.eachAttributeButton((element, attributeName) => { 12578 element.disabled = this.attributes[attributeName] === false; 12579 if (this.attributes[attributeName] || this.dialogIsVisible(attributeName)) { 12580 element.setAttribute("data-trix-active", ""); 12581 return element.classList.add("trix-active"); 12582 } else { 12583 element.removeAttribute("data-trix-active"); 12584 return element.classList.remove("trix-active"); 12585 } 12586 }); 12587 } 12588 eachAttributeButton(callback) { 12589 return Array.from(this.element.querySelectorAll(attributeButtonSelector)).map(element => callback(element, getAttributeName(element))); 12590 } 12591 applyKeyboardCommand(keys) { 12592 const keyString = JSON.stringify(keys.sort()); 12593 for (const button of Array.from(this.element.querySelectorAll("[data-trix-key]"))) { 12594 const buttonKeys = button.getAttribute("data-trix-key").split("+"); 12595 const buttonKeyString = JSON.stringify(buttonKeys.sort()); 12596 if (buttonKeyString === keyString) { 12597 triggerEvent("mousedown", { 12598 onElement: button 12599 }); 12600 return true; 12601 } 12602 } 12603 return false; 12604 } 12605 12606 // Dialogs 12607 12608 dialogIsVisible(dialogName) { 12609 const element = this.getDialog(dialogName); 12610 if (element) { 12611 return element.hasAttribute("data-trix-active"); 12612 } 12613 } 12614 toggleDialog(dialogName) { 12615 if (this.dialogIsVisible(dialogName)) { 12616 return this.hideDialog(); 12617 } else { 12618 return this.showDialog(dialogName); 12619 } 12620 } 12621 showDialog(dialogName) { 12622 var _this$delegate5, _this$delegate6; 12623 this.hideDialog(); 12624 (_this$delegate5 = this.delegate) === null || _this$delegate5 === void 0 || _this$delegate5.toolbarWillShowDialog(); 12625 const element = this.getDialog(dialogName); 12626 element.setAttribute("data-trix-active", ""); 12627 element.classList.add("trix-active"); 12628 Array.from(element.querySelectorAll("input[disabled]")).forEach(disabledInput => { 12629 disabledInput.removeAttribute("disabled"); 12630 }); 12631 const attributeName = getAttributeName(element); 12632 if (attributeName) { 12633 const input = getInputForDialog(element, dialogName); 12634 if (input) { 12635 input.value = this.attributes[attributeName] || ""; 12636 input.select(); 12637 } 12638 } 12639 return (_this$delegate6 = this.delegate) === null || _this$delegate6 === void 0 ? void 0 : _this$delegate6.toolbarDidShowDialog(dialogName); 12640 } 12641 setAttribute(dialogElement) { 12642 var _this$delegate7; 12643 const attributeName = getAttributeName(dialogElement); 12644 const input = getInputForDialog(dialogElement, attributeName); 12645 if (input.willValidate) { 12646 input.setCustomValidity(""); 12647 if (!input.checkValidity() || !this.isSafeAttribute(input)) { 12648 input.setCustomValidity("Invalid value"); 12649 input.setAttribute("data-trix-validate", ""); 12650 input.classList.add("trix-validate"); 12651 return input.focus(); 12652 } 12653 } 12654 (_this$delegate7 = this.delegate) === null || _this$delegate7 === void 0 || _this$delegate7.toolbarDidUpdateAttribute(attributeName, input.value); 12655 return this.hideDialog(); 12656 } 12657 isSafeAttribute(input) { 12658 if (input.hasAttribute("data-trix-validate-href")) { 12659 return purify.isValidAttribute("a", "href", input.value); 12660 } else { 12661 return true; 12662 } 12663 } 12664 removeAttribute(dialogElement) { 12665 var _this$delegate8; 12666 const attributeName = getAttributeName(dialogElement); 12667 (_this$delegate8 = this.delegate) === null || _this$delegate8 === void 0 || _this$delegate8.toolbarDidRemoveAttribute(attributeName); 12668 return this.hideDialog(); 12669 } 12670 hideDialog() { 12671 const element = this.element.querySelector(activeDialogSelector); 12672 if (element) { 12673 var _this$delegate9; 12674 element.removeAttribute("data-trix-active"); 12675 element.classList.remove("trix-active"); 12676 this.resetDialogInputs(); 12677 return (_this$delegate9 = this.delegate) === null || _this$delegate9 === void 0 ? void 0 : _this$delegate9.toolbarDidHideDialog(getDialogName(element)); 12678 } 12679 } 12680 resetDialogInputs() { 12681 Array.from(this.element.querySelectorAll(dialogInputSelector)).forEach(input => { 12682 input.setAttribute("disabled", "disabled"); 12683 input.removeAttribute("data-trix-validate"); 12684 input.classList.remove("trix-validate"); 12685 }); 12686 } 12687 getDialog(dialogName) { 12688 return this.element.querySelector("[data-trix-dialog=".concat(dialogName, "]")); 12689 } 12690 } 12691 12692 const snapshotsAreEqual = (a, b) => rangesAreEqual(a.selectedRange, b.selectedRange) && a.document.isEqualTo(b.document); 12693 class EditorController extends Controller { 12694 constructor(_ref) { 12695 let { 12696 editorElement, 12697 document, 12698 html 12699 } = _ref; 12700 super(...arguments); 12701 this.editorElement = editorElement; 12702 this.selectionManager = new SelectionManager(this.editorElement); 12703 this.selectionManager.delegate = this; 12704 this.composition = new Composition(); 12705 this.composition.delegate = this; 12706 this.attachmentManager = new AttachmentManager(this.composition.getAttachments()); 12707 this.attachmentManager.delegate = this; 12708 this.inputController = input.getLevel() === 2 ? new Level2InputController(this.editorElement) : new Level0InputController(this.editorElement); 12709 this.inputController.delegate = this; 12710 this.inputController.responder = this.composition; 12711 this.compositionController = new CompositionController(this.editorElement, this.composition); 12712 this.compositionController.delegate = this; 12713 this.toolbarController = new ToolbarController(this.editorElement.toolbarElement); 12714 this.toolbarController.delegate = this; 12715 this.editor = new Editor(this.composition, this.selectionManager, this.editorElement); 12716 if (document) { 12717 this.editor.loadDocument(document); 12718 } else { 12719 this.editor.loadHTML(html); 12720 } 12721 } 12722 registerSelectionManager() { 12723 return selectionChangeObserver.registerSelectionManager(this.selectionManager); 12724 } 12725 unregisterSelectionManager() { 12726 return selectionChangeObserver.unregisterSelectionManager(this.selectionManager); 12727 } 12728 render() { 12729 return this.compositionController.render(); 12730 } 12731 reparse() { 12732 return this.composition.replaceHTML(this.editorElement.innerHTML); 12733 } 12734 12735 // Composition delegate 12736 12737 compositionDidChangeDocument(document) { 12738 this.notifyEditorElement("document-change"); 12739 if (!this.handlingInput) { 12740 return this.render(); 12741 } 12742 } 12743 compositionDidChangeCurrentAttributes(currentAttributes) { 12744 this.currentAttributes = currentAttributes; 12745 this.toolbarController.updateAttributes(this.currentAttributes); 12746 this.updateCurrentActions(); 12747 return this.notifyEditorElement("attributes-change", { 12748 attributes: this.currentAttributes 12749 }); 12750 } 12751 compositionDidPerformInsertionAtRange(range) { 12752 if (this.pasting) { 12753 this.pastedRange = range; 12754 } 12755 } 12756 compositionShouldAcceptFile(file) { 12757 return this.notifyEditorElement("file-accept", { 12758 file 12759 }); 12760 } 12761 compositionDidAddAttachment(attachment) { 12762 const managedAttachment = this.attachmentManager.manageAttachment(attachment); 12763 return this.notifyEditorElement("attachment-add", { 12764 attachment: managedAttachment 12765 }); 12766 } 12767 compositionDidEditAttachment(attachment) { 12768 this.compositionController.rerenderViewForObject(attachment); 12769 const managedAttachment = this.attachmentManager.manageAttachment(attachment); 12770 this.notifyEditorElement("attachment-edit", { 12771 attachment: managedAttachment 12772 }); 12773 return this.notifyEditorElement("change"); 12774 } 12775 compositionDidChangeAttachmentPreviewURL(attachment) { 12776 this.compositionController.invalidateViewForObject(attachment); 12777 return this.notifyEditorElement("change"); 12778 } 12779 compositionDidRemoveAttachment(attachment) { 12780 const managedAttachment = this.attachmentManager.unmanageAttachment(attachment); 12781 return this.notifyEditorElement("attachment-remove", { 12782 attachment: managedAttachment 12783 }); 12784 } 12785 compositionDidStartEditingAttachment(attachment, options) { 12786 this.attachmentLocationRange = this.composition.document.getLocationRangeOfAttachment(attachment); 12787 this.compositionController.installAttachmentEditorForAttachment(attachment, options); 12788 return this.selectionManager.setLocationRange(this.attachmentLocationRange); 12789 } 12790 compositionDidStopEditingAttachment(attachment) { 12791 this.compositionController.uninstallAttachmentEditor(); 12792 this.attachmentLocationRange = null; 12793 } 12794 compositionDidRequestChangingSelectionToLocationRange(locationRange) { 12795 if (this.loadingSnapshot && !this.isFocused()) return; 12796 this.requestedLocationRange = locationRange; 12797 this.compositionRevisionWhenLocationRangeRequested = this.composition.revision; 12798 if (!this.handlingInput) { 12799 return this.render(); 12800 } 12801 } 12802 compositionWillLoadSnapshot() { 12803 this.loadingSnapshot = true; 12804 } 12805 compositionDidLoadSnapshot() { 12806 this.compositionController.refreshViewCache(); 12807 this.render(); 12808 this.loadingSnapshot = false; 12809 } 12810 getSelectionManager() { 12811 return this.selectionManager; 12812 } 12813 12814 // Attachment manager delegate 12815 12816 attachmentManagerDidRequestRemovalOfAttachment(attachment) { 12817 return this.removeAttachment(attachment); 12818 } 12819 12820 // Document controller delegate 12821 12822 compositionControllerWillSyncDocumentView() { 12823 this.inputController.editorWillSyncDocumentView(); 12824 this.selectionManager.lock(); 12825 return this.selectionManager.clearSelection(); 12826 } 12827 compositionControllerDidSyncDocumentView() { 12828 this.inputController.editorDidSyncDocumentView(); 12829 this.selectionManager.unlock(); 12830 this.updateCurrentActions(); 12831 return this.notifyEditorElement("sync"); 12832 } 12833 compositionControllerDidRender() { 12834 if (this.requestedLocationRange) { 12835 if (this.compositionRevisionWhenLocationRangeRequested === this.composition.revision) { 12836 this.selectionManager.setLocationRange(this.requestedLocationRange); 12837 } 12838 this.requestedLocationRange = null; 12839 this.compositionRevisionWhenLocationRangeRequested = null; 12840 } 12841 if (this.renderedCompositionRevision !== this.composition.revision) { 12842 this.runEditorFilters(); 12843 this.composition.updateCurrentAttributes(); 12844 this.notifyEditorElement("render"); 12845 } 12846 this.renderedCompositionRevision = this.composition.revision; 12847 } 12848 compositionControllerDidFocus() { 12849 if (this.isFocusedInvisibly()) { 12850 this.setLocationRange({ 12851 index: 0, 12852 offset: 0 12853 }); 12854 } 12855 this.toolbarController.hideDialog(); 12856 return this.notifyEditorElement("focus"); 12857 } 12858 compositionControllerDidBlur() { 12859 return this.notifyEditorElement("blur"); 12860 } 12861 compositionControllerDidSelectAttachment(attachment, options) { 12862 this.toolbarController.hideDialog(); 12863 return this.composition.editAttachment(attachment, options); 12864 } 12865 compositionControllerDidRequestDeselectingAttachment(attachment) { 12866 const locationRange = this.attachmentLocationRange || this.composition.document.getLocationRangeOfAttachment(attachment); 12867 return this.selectionManager.setLocationRange(locationRange[1]); 12868 } 12869 compositionControllerWillUpdateAttachment(attachment) { 12870 return this.editor.recordUndoEntry("Edit Attachment", { 12871 context: attachment.id, 12872 consolidatable: true 12873 }); 12874 } 12875 compositionControllerDidRequestRemovalOfAttachment(attachment) { 12876 return this.removeAttachment(attachment); 12877 } 12878 12879 // Input controller delegate 12880 12881 inputControllerWillHandleInput() { 12882 this.handlingInput = true; 12883 this.requestedRender = false; 12884 } 12885 inputControllerDidRequestRender() { 12886 this.requestedRender = true; 12887 } 12888 inputControllerDidHandleInput() { 12889 this.handlingInput = false; 12890 if (this.requestedRender) { 12891 this.requestedRender = false; 12892 return this.render(); 12893 } 12894 } 12895 inputControllerDidAllowUnhandledInput() { 12896 return this.notifyEditorElement("change"); 12897 } 12898 inputControllerDidRequestReparse() { 12899 return this.reparse(); 12900 } 12901 inputControllerWillPerformTyping() { 12902 return this.recordTypingUndoEntry(); 12903 } 12904 inputControllerWillPerformFormatting(attributeName) { 12905 return this.recordFormattingUndoEntry(attributeName); 12906 } 12907 inputControllerWillCutText() { 12908 return this.editor.recordUndoEntry("Cut"); 12909 } 12910 inputControllerWillPaste(paste) { 12911 this.editor.recordUndoEntry("Paste"); 12912 this.pasting = true; 12913 return this.notifyEditorElement("before-paste", { 12914 paste 12915 }); 12916 } 12917 inputControllerDidPaste(paste) { 12918 paste.range = this.pastedRange; 12919 this.pastedRange = null; 12920 this.pasting = null; 12921 return this.notifyEditorElement("paste", { 12922 paste 12923 }); 12924 } 12925 inputControllerWillMoveText() { 12926 return this.editor.recordUndoEntry("Move"); 12927 } 12928 inputControllerWillAttachFiles() { 12929 return this.editor.recordUndoEntry("Drop Files"); 12930 } 12931 inputControllerWillPerformUndo() { 12932 return this.editor.undo(); 12933 } 12934 inputControllerWillPerformRedo() { 12935 return this.editor.redo(); 12936 } 12937 inputControllerDidReceiveKeyboardCommand(keys) { 12938 return this.toolbarController.applyKeyboardCommand(keys); 12939 } 12940 inputControllerDidStartDrag() { 12941 this.locationRangeBeforeDrag = this.selectionManager.getLocationRange(); 12942 } 12943 inputControllerDidReceiveDragOverPoint(point) { 12944 return this.selectionManager.setLocationRangeFromPointRange(point); 12945 } 12946 inputControllerDidCancelDrag() { 12947 this.selectionManager.setLocationRange(this.locationRangeBeforeDrag); 12948 this.locationRangeBeforeDrag = null; 12949 } 12950 12951 // Selection manager delegate 12952 12953 locationRangeDidChange(locationRange) { 12954 this.composition.updateCurrentAttributes(); 12955 this.updateCurrentActions(); 12956 if (this.attachmentLocationRange && !rangesAreEqual(this.attachmentLocationRange, locationRange)) { 12957 this.composition.stopEditingAttachment(); 12958 } 12959 return this.notifyEditorElement("selection-change"); 12960 } 12961 12962 // Toolbar controller delegate 12963 12964 toolbarDidClickButton() { 12965 if (!this.getLocationRange()) { 12966 return this.setLocationRange({ 12967 index: 0, 12968 offset: 0 12969 }); 12970 } 12971 } 12972 toolbarDidInvokeAction(actionName, invokingElement) { 12973 return this.invokeAction(actionName, invokingElement); 12974 } 12975 toolbarDidToggleAttribute(attributeName) { 12976 this.recordFormattingUndoEntry(attributeName); 12977 this.composition.toggleCurrentAttribute(attributeName); 12978 this.render(); 12979 if (!this.selectionFrozen) { 12980 return this.editorElement.focus(); 12981 } 12982 } 12983 toolbarDidUpdateAttribute(attributeName, value) { 12984 this.recordFormattingUndoEntry(attributeName); 12985 this.composition.setCurrentAttribute(attributeName, value); 12986 this.render(); 12987 if (!this.selectionFrozen) { 12988 return this.editorElement.focus(); 12989 } 12990 } 12991 toolbarDidRemoveAttribute(attributeName) { 12992 this.recordFormattingUndoEntry(attributeName); 12993 this.composition.removeCurrentAttribute(attributeName); 12994 this.render(); 12995 if (!this.selectionFrozen) { 12996 return this.editorElement.focus(); 12997 } 12998 } 12999 toolbarWillShowDialog(dialogElement) { 13000 this.composition.expandSelectionForEditing(); 13001 return this.freezeSelection(); 13002 } 13003 toolbarDidShowDialog(dialogName) { 13004 return this.notifyEditorElement("toolbar-dialog-show", { 13005 dialogName 13006 }); 13007 } 13008 toolbarDidHideDialog(dialogName) { 13009 this.thawSelection(); 13010 this.editorElement.focus(); 13011 return this.notifyEditorElement("toolbar-dialog-hide", { 13012 dialogName 13013 }); 13014 } 13015 13016 // Selection 13017 13018 freezeSelection() { 13019 if (!this.selectionFrozen) { 13020 this.selectionManager.lock(); 13021 this.composition.freezeSelection(); 13022 this.selectionFrozen = true; 13023 return this.render(); 13024 } 13025 } 13026 thawSelection() { 13027 if (this.selectionFrozen) { 13028 this.composition.thawSelection(); 13029 this.selectionManager.unlock(); 13030 this.selectionFrozen = false; 13031 return this.render(); 13032 } 13033 } 13034 canInvokeAction(actionName) { 13035 if (this.actionIsExternal(actionName)) { 13036 return true; 13037 } else { 13038 var _this$actions$actionN; 13039 return !!((_this$actions$actionN = this.actions[actionName]) !== null && _this$actions$actionN !== void 0 && (_this$actions$actionN = _this$actions$actionN.test) !== null && _this$actions$actionN !== void 0 && _this$actions$actionN.call(this)); 13040 } 13041 } 13042 invokeAction(actionName, invokingElement) { 13043 if (this.actionIsExternal(actionName)) { 13044 return this.notifyEditorElement("action-invoke", { 13045 actionName, 13046 invokingElement 13047 }); 13048 } else { 13049 var _this$actions$actionN2; 13050 return (_this$actions$actionN2 = this.actions[actionName]) === null || _this$actions$actionN2 === void 0 || (_this$actions$actionN2 = _this$actions$actionN2.perform) === null || _this$actions$actionN2 === void 0 ? void 0 : _this$actions$actionN2.call(this); 13051 } 13052 } 13053 actionIsExternal(actionName) { 13054 return /^x-./.test(actionName); 13055 } 13056 getCurrentActions() { 13057 const result = {}; 13058 for (const actionName in this.actions) { 13059 result[actionName] = this.canInvokeAction(actionName); 13060 } 13061 return result; 13062 } 13063 updateCurrentActions() { 13064 const currentActions = this.getCurrentActions(); 13065 if (!objectsAreEqual(currentActions, this.currentActions)) { 13066 this.currentActions = currentActions; 13067 this.toolbarController.updateActions(this.currentActions); 13068 return this.notifyEditorElement("actions-change", { 13069 actions: this.currentActions 13070 }); 13071 } 13072 } 13073 13074 // Editor filters 13075 13076 runEditorFilters() { 13077 let snapshot = this.composition.getSnapshot(); 13078 Array.from(this.editor.filters).forEach(filter => { 13079 const { 13080 document, 13081 selectedRange 13082 } = snapshot; 13083 snapshot = filter.call(this.editor, snapshot) || {}; 13084 if (!snapshot.document) { 13085 snapshot.document = document; 13086 } 13087 if (!snapshot.selectedRange) { 13088 snapshot.selectedRange = selectedRange; 13089 } 13090 }); 13091 if (!snapshotsAreEqual(snapshot, this.composition.getSnapshot())) { 13092 return this.composition.loadSnapshot(snapshot); 13093 } 13094 } 13095 13096 // Private 13097 13098 updateInputElement() { 13099 const element = this.compositionController.getSerializableElement(); 13100 const value = serializeToContentType(element, "text/html"); 13101 return this.editorElement.setFormValue(value); 13102 } 13103 notifyEditorElement(message, data) { 13104 switch (message) { 13105 case "document-change": 13106 this.documentChangedSinceLastRender = true; 13107 break; 13108 case "render": 13109 if (this.documentChangedSinceLastRender) { 13110 this.documentChangedSinceLastRender = false; 13111 this.notifyEditorElement("change"); 13112 } 13113 break; 13114 case "change": 13115 case "attachment-add": 13116 case "attachment-edit": 13117 case "attachment-remove": 13118 this.updateInputElement(); 13119 break; 13120 } 13121 return this.editorElement.notify(message, data); 13122 } 13123 removeAttachment(attachment) { 13124 this.editor.recordUndoEntry("Delete Attachment"); 13125 this.composition.removeAttachment(attachment); 13126 return this.render(); 13127 } 13128 recordFormattingUndoEntry(attributeName) { 13129 const blockConfig = getBlockConfig(attributeName); 13130 const locationRange = this.selectionManager.getLocationRange(); 13131 if (blockConfig || !rangeIsCollapsed(locationRange)) { 13132 return this.editor.recordUndoEntry("Formatting", { 13133 context: this.getUndoContext(), 13134 consolidatable: true 13135 }); 13136 } 13137 } 13138 recordTypingUndoEntry() { 13139 return this.editor.recordUndoEntry("Typing", { 13140 context: this.getUndoContext(this.currentAttributes), 13141 consolidatable: true 13142 }); 13143 } 13144 getUndoContext() { 13145 for (var _len = arguments.length, context = new Array(_len), _key = 0; _key < _len; _key++) { 13146 context[_key] = arguments[_key]; 13147 } 13148 return [this.getLocationContext(), this.getTimeContext(), ...Array.from(context)]; 13149 } 13150 getLocationContext() { 13151 const locationRange = this.selectionManager.getLocationRange(); 13152 if (rangeIsCollapsed(locationRange)) { 13153 return locationRange[0].index; 13154 } else { 13155 return locationRange; 13156 } 13157 } 13158 getTimeContext() { 13159 if (undo.interval > 0) { 13160 return Math.floor(new Date().getTime() / undo.interval); 13161 } else { 13162 return 0; 13163 } 13164 } 13165 isFocused() { 13166 var _this$editorElement$o; 13167 return this.editorElement === ((_this$editorElement$o = this.editorElement.ownerDocument) === null || _this$editorElement$o === void 0 ? void 0 : _this$editorElement$o.activeElement); 13168 } 13169 13170 // Detect "Cursor disappears sporadically" Firefox bug. 13171 // - https://bugzilla.mozilla.org/show_bug.cgi?id=226301 13172 isFocusedInvisibly() { 13173 return this.isFocused() && !this.getLocationRange(); 13174 } 13175 get actions() { 13176 return this.constructor.actions; 13177 } 13178 } 13179 _defineProperty(EditorController, "actions", { 13180 undo: { 13181 test() { 13182 return this.editor.canUndo(); 13183 }, 13184 perform() { 13185 return this.editor.undo(); 13186 } 13187 }, 13188 redo: { 13189 test() { 13190 return this.editor.canRedo(); 13191 }, 13192 perform() { 13193 return this.editor.redo(); 13194 } 13195 }, 13196 link: { 13197 test() { 13198 return this.editor.canActivateAttribute("href"); 13199 } 13200 }, 13201 increaseNestingLevel: { 13202 test() { 13203 return this.editor.canIncreaseNestingLevel(); 13204 }, 13205 perform() { 13206 return this.editor.increaseNestingLevel() && this.render(); 13207 } 13208 }, 13209 decreaseNestingLevel: { 13210 test() { 13211 return this.editor.canDecreaseNestingLevel(); 13212 }, 13213 perform() { 13214 return this.editor.decreaseNestingLevel() && this.render(); 13215 } 13216 }, 13217 attachFiles: { 13218 test() { 13219 return true; 13220 }, 13221 perform() { 13222 return input.pickFiles(this.editor.insertFiles); 13223 } 13224 } 13225 }); 13226 EditorController.proxyMethod("getSelectionManager().setLocationRange"); 13227 EditorController.proxyMethod("getSelectionManager().getLocationRange"); 13228 13229 var controllers = /*#__PURE__*/Object.freeze({ 13230 __proto__: null, 13231 AttachmentEditorController: AttachmentEditorController, 13232 CompositionController: CompositionController, 13233 Controller: Controller, 13234 EditorController: EditorController, 13235 InputController: InputController, 13236 Level0InputController: Level0InputController, 13237 Level2InputController: Level2InputController, 13238 ToolbarController: ToolbarController 13239 }); 13240 13241 var observers = /*#__PURE__*/Object.freeze({ 13242 __proto__: null, 13243 MutationObserver: MutationObserver, 13244 SelectionChangeObserver: SelectionChangeObserver 13245 }); 13246 13247 var operations = /*#__PURE__*/Object.freeze({ 13248 __proto__: null, 13249 FileVerificationOperation: FileVerificationOperation, 13250 ImagePreloadOperation: ImagePreloadOperation 13251 }); 13252 13253 installDefaultCSSForTagName("trix-toolbar", "%t {\n display: block;\n}\n\n%t {\n white-space: nowrap;\n}\n\n%t [data-trix-dialog] {\n display: none;\n}\n\n%t [data-trix-dialog][data-trix-active] {\n display: block;\n}\n\n%t [data-trix-dialog] [data-trix-validate]:invalid {\n background-color: #ffdddd;\n}"); 13254 class TrixToolbarElement extends HTMLElement { 13255 // Element lifecycle 13256 13257 connectedCallback() { 13258 if (this.innerHTML === "") { 13259 this.innerHTML = toolbar.getDefaultHTML(); 13260 } 13261 }
vendor: 11,761 bytes, lines 13262-13572
13262 } 13263 13264 let id = 0; 13265 13266 // Contenteditable support helpers 13267 13268 const autofocus = function (element) { 13269 if (!document.querySelector(":focus")) { 13270 if (element.hasAttribute("autofocus") && document.querySelector("[autofocus]") === element) { 13271 return element.focus(); 13272 } 13273 } 13274 }; 13275 const makeEditable = function (element) { 13276 if (element.hasAttribute("contenteditable")) { 13277 return; 13278 } 13279 element.setAttribute("contenteditable", ""); 13280 return handleEventOnce("focus", { 13281 onElement: element, 13282 withCallback() { 13283 return configureContentEditable(element); 13284 } 13285 }); 13286 }; 13287 const configureContentEditable = function (element) { 13288 disableObjectResizing(element); 13289 return setDefaultParagraphSeparator(element); 13290 }; 13291 const disableObjectResizing = function (element) { 13292 var _document$queryComman, _document; 13293 if ((_document$queryComman = (_document = document).queryCommandSupported) !== null && _document$queryComman !== void 0 && _document$queryComman.call(_document, "enableObjectResizing")) { 13294 document.execCommand("enableObjectResizing", false, false); 13295 return handleEvent("mscontrolselect", { 13296 onElement: element, 13297 preventDefault: true 13298 }); 13299 } 13300 }; 13301 const setDefaultParagraphSeparator = function (element) { 13302 var _document$queryComman2, _document2; 13303 if ((_document$queryComman2 = (_document2 = document).queryCommandSupported) !== null && _document$queryComman2 !== void 0 && _document$queryComman2.call(_document2, "DefaultParagraphSeparator")) { 13304 const { 13305 tagName 13306 } = attributes.default; 13307 if (["div", "p"].includes(tagName)) { 13308 return document.execCommand("DefaultParagraphSeparator", false, tagName); 13309 } 13310 } 13311 }; 13312 13313 // Accessibility helpers 13314 13315 const addAccessibilityRole = function (element) { 13316 if (element.hasAttribute("role")) { 13317 return; 13318 } 13319 return element.setAttribute("role", "textbox"); 13320 }; 13321 const ensureAriaLabel = function (element) { 13322 if (element.hasAttribute("aria-label") || element.hasAttribute("aria-labelledby")) { 13323 return; 13324 } 13325 const update = function () { 13326 const texts = Array.from(element.labels).map(label => { 13327 if (!label.contains(element)) return label.textContent; 13328 }).filter(text => text); 13329 const text = texts.join(" "); 13330 if (text) { 13331 return element.setAttribute("aria-label", text); 13332 } else { 13333 return element.removeAttribute("aria-label"); 13334 } 13335 }; 13336 update(); 13337 return handleEvent("focus", { 13338 onElement: element, 13339 withCallback: update 13340 }); 13341 }; 13342 13343 // Style 13344 13345 const cursorTargetStyles = function () { 13346 if (browser$1.forcesObjectResizing) { 13347 return { 13348 display: "inline", 13349 width: "auto" 13350 }; 13351 } else { 13352 return { 13353 display: "inline-block", 13354 width: "1px" 13355 }; 13356 } 13357 }(); 13358 installDefaultCSSForTagName("trix-editor", "%t {\n display: block;\n}\n\n%t:empty::before {\n content: attr(placeholder);\n color: graytext;\n cursor: text;\n pointer-events: none;\n white-space: pre-line;\n}\n\n%t a[contenteditable=false] {\n cursor: text;\n}\n\n%t img {\n max-width: 100%;\n height: auto;\n}\n\n%t ".concat(attachmentSelector, " figcaption textarea {\n resize: none;\n}\n\n%t ").concat(attachmentSelector, " figcaption textarea.trix-autoresize-clone {\n position: absolute;\n left: -9999px;\n max-height: 0px;\n}\n\n%t ").concat(attachmentSelector, " figcaption[data-trix-placeholder]:empty::before {\n content: attr(data-trix-placeholder);\n color: graytext;\n}\n\n%t [data-trix-cursor-target] {\n display: ").concat(cursorTargetStyles.display, " !important;\n width: ").concat(cursorTargetStyles.width, " !important;\n padding: 0 !important;\n margin: 0 !important;\n border: none !important;\n}\n\n%t [data-trix-cursor-target=left] {\n vertical-align: top !important;\n margin-left: -1px !important;\n}\n\n%t [data-trix-cursor-target=right] {\n vertical-align: bottom !important;\n margin-right: -1px !important;\n}")); 13359 var _internals = /*#__PURE__*/new WeakMap(); 13360 var _validate = /*#__PURE__*/new WeakSet(); 13361 class ElementInternalsDelegate { 13362 constructor(element) { 13363 _classPrivateMethodInitSpec(this, _validate); 13364 _classPrivateFieldInitSpec(this, _internals, { 13365 writable: true, 13366 value: void 0 13367 }); 13368 this.element = element; 13369 _classPrivateFieldSet(this, _internals, element.attachInternals()); 13370 } 13371 connectedCallback() { 13372 _classPrivateMethodGet(this, _validate, _validate2).call(this); 13373 } 13374 disconnectedCallback() {} 13375 get labels() { 13376 return _classPrivateFieldGet(this, _internals).labels; 13377 } 13378 get disabled() { 13379 var _this$element$inputEl; 13380 return (_this$element$inputEl = this.element.inputElement) === null || _this$element$inputEl === void 0 ? void 0 : _this$element$inputEl.disabled; 13381 } 13382 set disabled(value) { 13383 this.element.toggleAttribute("disabled", value); 13384 } 13385 get required() { 13386 return this.element.hasAttribute("required"); 13387 } 13388 set required(value) { 13389 this.element.toggleAttribute("required", value); 13390 _classPrivateMethodGet(this, _validate, _validate2).call(this); 13391 } 13392 get validity() { 13393 return _classPrivateFieldGet(this, _internals).validity; 13394 } 13395 get validationMessage() { 13396 return _classPrivateFieldGet(this, _internals).validationMessage; 13397 } 13398 get willValidate() { 13399 return _classPrivateFieldGet(this, _internals).willValidate; 13400 } 13401 setFormValue(value) { 13402 _classPrivateMethodGet(this, _validate, _validate2).call(this); 13403 } 13404 checkValidity() { 13405 return _classPrivateFieldGet(this, _internals).checkValidity(); 13406 } 13407 reportValidity() { 13408 return _classPrivateFieldGet(this, _internals).reportValidity(); 13409 } 13410 setCustomValidity(validationMessage) { 13411 _classPrivateMethodGet(this, _validate, _validate2).call(this, validationMessage); 13412 } 13413 } 13414 function _validate2() { 13415 let customValidationMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; 13416 const { 13417 required, 13418 value 13419 } = this.element; 13420 const valueMissing = required && !value; 13421 const customError = !!customValidationMessage; 13422 const input = makeElement("input", { 13423 required 13424 }); 13425 const validationMessage = customValidationMessage || input.validationMessage; 13426 _classPrivateFieldGet(this, _internals).setValidity({ 13427 valueMissing, 13428 customError 13429 }, validationMessage); 13430 } 13431 var _focusHandler = /*#__PURE__*/new WeakMap(); 13432 var _resetBubbled = /*#__PURE__*/new WeakMap(); 13433 var _clickBubbled = /*#__PURE__*/new WeakMap(); 13434 class LegacyDelegate { 13435 constructor(element) { 13436 _classPrivateFieldInitSpec(this, _focusHandler, { 13437 writable: true, 13438 value: void 0 13439 }); 13440 _classPrivateFieldInitSpec(this, _resetBubbled, { 13441 writable: true, 13442 value: event => { 13443 if (event.defaultPrevented) return; 13444 if (event.target !== this.element.form) return; 13445 this.element.reset(); 13446 } 13447 }); 13448 _classPrivateFieldInitSpec(this, _clickBubbled, { 13449 writable: true, 13450 value: event => { 13451 if (event.defaultPrevented) return; 13452 if (this.element.contains(event.target)) return; 13453 const label = findClosestElementFromNode(event.target, { 13454 matchingSelector: "label" 13455 }); 13456 if (!label) return; 13457 if (!Array.from(this.labels).includes(label)) return; 13458 this.element.focus(); 13459 } 13460 }); 13461 this.element = element; 13462 } 13463 connectedCallback() { 13464 _classPrivateFieldSet(this, _focusHandler, ensureAriaLabel(this.element)); 13465 window.addEventListener("reset", _classPrivateFieldGet(this, _resetBubbled), false); 13466 window.addEventListener("click", _classPrivateFieldGet(this, _clickBubbled), false); 13467 } 13468 disconnectedCallback() { 13469 var _classPrivateFieldGet2; 13470 (_classPrivateFieldGet2 = _classPrivateFieldGet(this, _focusHandler)) === null || _classPrivateFieldGet2 === void 0 || _classPrivateFieldGet2.destroy(); 13471 window.removeEventListener("reset", _classPrivateFieldGet(this, _resetBubbled), false); 13472 window.removeEventListener("click", _classPrivateFieldGet(this, _clickBubbled), false); 13473 } 13474 get labels() { 13475 const labels = []; 13476 if (this.element.id && this.element.ownerDocument) { 13477 labels.push(...Array.from(this.element.ownerDocument.querySelectorAll("label[for='".concat(this.element.id, "']")) || [])); 13478 } 13479 const label = findClosestElementFromNode(this.element, { 13480 matchingSelector: "label" 13481 }); 13482 if (label) { 13483 if ([this.element, null].includes(label.control)) { 13484 labels.push(label); 13485 } 13486 } 13487 return labels; 13488 } 13489 get disabled() { 13490 console.warn("This browser does not support the [disabled] attribute for trix-editor elements."); 13491 return false; 13492 } 13493 set disabled(value) { 13494 console.warn("This browser does not support the [disabled] attribute for trix-editor elements."); 13495 } 13496 get required() { 13497 console.warn("This browser does not support the [required] attribute for trix-editor elements."); 13498 return false; 13499 } 13500 set required(value) { 13501 console.warn("This browser does not support the [required] attribute for trix-editor elements."); 13502 } 13503 get validity() { 13504 console.warn("This browser does not support the validity property for trix-editor elements."); 13505 return null; 13506 } 13507 get validationMessage() { 13508 console.warn("This browser does not support the validationMessage property for trix-editor elements."); 13509 return ""; 13510 } 13511 get willValidate() { 13512 console.warn("This browser does not support the willValidate property for trix-editor elements."); 13513 return false; 13514 } 13515 setFormValue(value) {} 13516 checkValidity() { 13517 console.warn("This browser does not support checkValidity() for trix-editor elements."); 13518 return true; 13519 } 13520 reportValidity() { 13521 console.warn("This browser does not support reportValidity() for trix-editor elements."); 13522 return true; 13523 } 13524 setCustomValidity(validationMessage) { 13525 console.warn("This browser does not support setCustomValidity(validationMessage) for trix-editor elements."); 13526 } 13527 } 13528 var _delegate = /*#__PURE__*/new WeakMap(); 13529 class TrixEditorElement extends HTMLElement { 13530 constructor() { 13531 super(); 13532 _classPrivateFieldInitSpec(this, _delegate, { 13533 writable: true, 13534 value: void 0 13535 }); 13536 _classPrivateFieldSet(this, _delegate, this.constructor.formAssociated ? new ElementInternalsDelegate(this) : new LegacyDelegate(this)); 13537 } 13538 13539 // Properties 13540 13541 get trixId() { 13542 if (this.hasAttribute("trix-id")) { 13543 return this.getAttribute("trix-id"); 13544 } else { 13545 this.setAttribute("trix-id", ++id); 13546 return this.trixId; 13547 } 13548 } 13549 get labels() { 13550 return _classPrivateFieldGet(this, _delegate).labels; 13551 } 13552 get disabled() { 13553 return _classPrivateFieldGet(this, _delegate).disabled; 13554 } 13555 set disabled(value) { 13556 _classPrivateFieldGet(this, _delegate).disabled = value; 13557 } 13558 get required() { 13559 return _classPrivateFieldGet(this, _delegate).required; 13560 } 13561 set required(value) { 13562 _classPrivateFieldGet(this, _delegate).required = value; 13563 } 13564 get validity() { 13565 return _classPrivateFieldGet(this, _delegate).validity; 13566 } 13567 get validationMessage() { 13568 return _classPrivateFieldGet(this, _delegate).validationMessage; 13569 } 13570 get willValidate() { 13571 return _classPrivateFieldGet(this, _delegate).willValidate; 13572 }
13573 get type() { 13574 return this.localName; 13575 } 13576 get toolbarElement() { 13577 if (this.hasAttribute("toolbar")) { 13578 var _this$ownerDocument; 13579 return (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.getElementById(this.getAttribute("toolbar")); 13580 } else if (this.parentNode) { 13581 const toolbarId = "trix-toolbar-".concat(this.trixId); 13582 this.setAttribute("toolbar", toolbarId); 13583 const element = makeElement("trix-toolbar", { 13584 id: toolbarId 13585 }); 13586 this.parentNode.insertBefore(element, this); 13587 return element; 13588 } else { 13589 return undefined; 13590 } 13591 } 13592 get form() { 13593 var _this$inputElement; 13594 return (_this$inputElement = this.inputElement) === null || _this$inputElement === void 0 ? void 0 : _this$inputElement.form; 13595 } 13596 get inputElement() { 13597 if (this.hasAttribute("input")) { 13598 var _this$ownerDocument2; 13599 return (_this$ownerDocument2 = this.ownerDocument) === null || _this$ownerDocument2 === void 0 ? void 0 : _this$ownerDocument2.getElementById(this.getAttribute("input")); 13600 } else if (this.parentNode) { 13601 const inputId = "trix-input-".concat(this.trixId); 13602 this.setAttribute("input", inputId); 13603 const element = makeElement("input", { 13604 type: "hidden", 13605 id: inputId 13606 }); 13607 this.parentNode.insertBefore(element, this.nextElementSibling); 13608 return element; 13609 } else { 13610 return undefined; 13611 } 13612 } 13613 get editor() { 13614 var _this$editorControlle; 13615 return (_this$editorControlle = this.editorController) === null || _this$editorControlle === void 0 ? void 0 : _this$editorControlle.editor; 13616 } 13617 get name() { 13618 var _this$inputElement2; 13619 return (_this$inputElement2 = this.inputElement) === null || _this$inputElement2 === void 0 ? void 0 : _this$inputElement2.name; 13620 } 13621 get value() { 13622 var _this$inputElement3; 13623 return (_this$inputElement3 = this.inputElement) === null || _this$inputElement3 === void 0 ? void 0 : _this$inputElement3.value; 13624 } 13625 set value(defaultValue) { 13626 var _this$editor; 13627 this.defaultValue = defaultValue; 13628 (_this$editor = this.editor) === null || _this$editor === void 0 || _this$editor.loadHTML(this.defaultValue); 13629 } 13630 13631 // Controller delegate methods 13632 13633 notify(message, data) { 13634 if (this.editorController) { 13635 return triggerEvent("trix-".concat(message), { 13636 onElement: this, 13637 attributes: data 13638 }); 13639 } 13640 } 13641 setFormValue(value) { 13642 if (this.inputElement) { 13643 this.inputElement.value = value; 13644 _classPrivateFieldGet(this, _delegate).setFormValue(value); 13645 } 13646 } 13647 13648 // Element lifecycle 13649 13650 connectedCallback() { 13651 if (!this.hasAttribute("data-trix-internal")) { 13652 makeEditable(this); 13653 addAccessibilityRole(this); 13654 if (!this.editorController) { 13655 triggerEvent("trix-before-initialize", { 13656 onElement: this 13657 }); 13658 this.editorController = new EditorController({ 13659 editorElement: this, 13660 html: this.defaultValue = this.value 13661 }); 13662 requestAnimationFrame(() => triggerEvent("trix-initialize", { 13663 onElement: this 13664 })); 13665 } 13666 this.editorController.registerSelectionManager(); 13667 _classPrivateFieldGet(this, _delegate).connectedCallback(); 13668 autofocus(this); 13669 } 13670 } 13671 disconnectedCallback() { 13672 var _this$editorControlle2; 13673 (_this$editorControlle2 = this.editorController) === null || _this$editorControlle2 === void 0 || _this$editorControlle2.unregisterSelectionManager(); 13674 _classPrivateFieldGet(this, _delegate).disconnectedCallback(); 13675 } 13676 13677 // Form support 13678 13679 checkValidity() { 13680 return _classPrivateFieldGet(this, _delegate).checkValidity(); 13681 } 13682 reportValidity() { 13683 return _classPrivateFieldGet(this, _delegate).reportValidity(); 13684 } 13685 setCustomValidity(validationMessage) { 13686 _classPrivateFieldGet(this, _delegate).setCustomValidity(validationMessage); 13687 } 13688 formDisabledCallback(disabled) { 13689 if (this.inputElement) { 13690 this.inputElement.disabled = disabled; 13691 } 13692 this.toggleAttribute("contenteditable", !disabled); 13693 } 13694 formResetCallback() { 13695 this.reset(); 13696 } 13697 reset() { 13698 this.value = this.defaultValue; 13699 } 13700 } 13701 _defineProperty(TrixEditorElement, "formAssociated", "ElementInternals" in window); 13702 13703 var elements = /*#__PURE__*/Object.freeze({ 13704 __proto__: null, 13705 TrixEditorElement: TrixEditorElement, 13706 TrixToolbarElement: TrixToolbarElement 13707 }); 13708 13709 var filters = /*#__PURE__*/Object.freeze({ 13710 __proto__: null, 13711 Filter: Filter, 13712 attachmentGalleryFilter: attachmentGalleryFilter 13713 }); 13714 13715 const Trix = { 13716 VERSION: version, 13717 config, 13718 core, 13719 models, 13720 views, 13721 controllers, 13722 observers, 13723 operations, 13724 elements, 13725 filters 13726 }; 13727 13728 // Expose models under the Trix constant for compatibility with v1 13729 Object.assign(Trix, models); 13730 function start() { 13731 if (!customElements.get("trix-toolbar")) { 13732 customElements.define("trix-toolbar", TrixToolbarElement); 13733 } 13734 if (!customElements.get("trix-editor")) { 13735 customElements.define("trix-editor", TrixEditorElement); 13736 } 13737 } 13738 window.Trix = Trix; 13739 setTimeout(start, 0); 13740 13741 return Trix; 13742 13743}));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.