1 define([ 2 'aloha/core', 3 'aloha/ecma5shims', 4 'util/maps', 5 'util/html', 6 'util/dom', 7 'jquery', 8 'PubSub' 9 ], function ( 10 Aloha, 11 $_, 12 Maps, 13 Html, 14 Dom, 15 jQuery, 16 PubSub 17 ) { 18 "use strict"; 19 20 /** 21 * 22 * @param obj 23 * @param attr 24 * @returns {Boolean} true 25 */ 26 function hasAttribute(obj, attr) { 27 var native_method = obj.hasAttribute; 28 if (native_method) { 29 return obj.hasAttribute(attr); 30 } 31 return (typeof obj.attributes[attr] !== 'undefined'); 32 } 33 34 /** 35 * Insert the node `node` after `preceding`. 36 * 37 * @param {Element} node 38 * @param {Element} preceding 39 * @return {Element} 40 */ 41 function insertAfter(node, preceding) { 42 var next = preceding.nextSibling, 43 parent = preceding.parentNode; 44 if (next) { 45 parent.insertBefore(node, next); 46 } else { 47 parent.appendChild(node); 48 } 49 return node; 50 } 51 52 /** 53 * Splits text node `node` at the given text index. 54 * 55 * Note that we cannot use splitText() because it is bugridden in IE 9. 56 * 57 * Borrowed from rangy. 58 * 59 * @param {Element} node 60 * @param {number} index 61 * @return {Element} 62 */ 63 function splitText(node, index) { 64 var newNode = node.cloneNode(false); 65 newNode.deleteData(0, index); 66 node.deleteData(index, node.length - index); 67 insertAfter(newNode, node); 68 return newNode; 69 } 70 71 var htmlNamespace = "http://www.w3.org/1999/xhtml"; 72 73 var cssStylingFlag = false; 74 75 // This is bad :( 76 var globalRange = null; 77 78 // Commands are stored in a dictionary where we call their actions and such 79 var commands = {}; 80 81 /////////////////////////////////////////////////////////////////////////////// 82 ////////////////////////////// Utility functions ////////////////////////////// 83 /////////////////////////////////////////////////////////////////////////////// 84 //@{ 85 86 // Opera 11 puts HTML elements in the null namespace, it seems. 87 function isHtmlNamespace(ns) { 88 return ns === null || !ns || ns === htmlNamespace; 89 } 90 91 // "An HTML element is an Element whose namespace is the HTML namespace." 92 // 93 // I allow an extra argument to more easily check whether something is a 94 // particular HTML element, like isNamedHtmlElement(node, 'OL'). It accepts arrays 95 // too, like isHtmlElementInArray(node, ["OL", "UL"]) to check if it's an ol or ul. 96 // TODO This function was prominent during profiling. Remove it 97 // and replace with calls to isAnyHtmlElement, isNamedHtmlElement 98 // and is isMappedHtmlElement. 99 function isHtmlElement_obsolete(node, tags) { 100 if (typeof tags == "string") { 101 tags = [tags]; 102 } 103 if (typeof tags == "object") { 104 tags = $_(tags).map(function (tag) { 105 return tag.toUpperCase(); 106 }); 107 } 108 return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI) && (typeof tags == "undefined" || $_(tags).indexOf(node.tagName) != -1); 109 } 110 111 function isAnyHtmlElement(node) { 112 return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI); 113 } 114 115 // name should be uppercase 116 function isNamedHtmlElement(node, name) { 117 return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI) 118 // This function is passed in a mix of upper and lower case names 119 && name.toUpperCase() === node.nodeName; 120 } 121 122 // TODO remove when isHtmlElementInArray is removed 123 function arrayContainsInsensitive(array, str) { 124 var i, len; 125 str = str.toUpperCase(); 126 127 for (i = 0, len = array.length; i < len; i++) { 128 if (array[i].toUpperCase() === str) { 129 return true; 130 } 131 } 132 return false; 133 } 134 // TODO replace calls to this function with calls to isMappedHtmlElement() 135 function isHtmlElementInArray(node, array) { 136 return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI) 137 // This function is passed in a mix of upper and lower case names 138 && arrayContainsInsensitive(array, node.nodeName); 139 } 140 141 // map must have all-uppercase keys 142 function isMappedHtmlElement(node, map) { 143 return node && node.nodeType == 1 && isHtmlNamespace(node.namespaceURI) && map[node.nodeName]; 144 } 145 146 /** 147 * Method to count the number of styles in the given style 148 */ 149 function getStyleLength(node) { 150 var s; 151 var styleLength = 0; 152 153 if (!node) { 154 return 0; 155 } 156 157 if (!node.style) { 158 return 0; 159 } 160 161 // some browsers support .length on styles 162 if (typeof node.style.length !== 'undefined') { 163 return node.style.length; 164 } 165 166 /*jslint forin: true*/ //not sure whether node.style.hasOwnProperty is valid 167 for (s in node.style) { 168 if (node.style[s] && node.style[s] !== 0 && node.style[s] !== 'false') { 169 styleLength++; 170 } 171 } 172 /*jslint forin: false*/ 173 174 return styleLength; 175 } 176 177 function toArray(obj) { 178 if (!obj) { 179 return null; 180 } 181 var array = [], 182 i, 183 l = obj.length; 184 // iterate backwards ensuring that length is an UInt32 185 i = l >>> 0; 186 while (i--) { 187 array[i] = obj[i]; 188 } 189 return array; 190 } 191 192 function nextNodeDescendants(node) { 193 while (node && !node.nextSibling) { 194 node = node.parentNode; 195 } 196 if (!node) { 197 return null; 198 } 199 return node.nextSibling; 200 } 201 202 function nextNode(node) { 203 if (node.hasChildNodes()) { 204 return node.firstChild; 205 } 206 return nextNodeDescendants(node); 207 } 208 209 function previousNode(node) { 210 if (node.previousSibling) { 211 node = node.previousSibling; 212 while (node.hasChildNodes()) { 213 node = node.lastChild; 214 } 215 return node; 216 } 217 if (node.parentNode && node.parentNode.nodeType == $_.Node.ELEMENT_NODE) { 218 return node.parentNode; 219 } 220 return null; 221 } 222 223 /** 224 * Returns true if ancestor is an ancestor of descendant, false otherwise. 225 */ 226 function isAncestor(ancestor, descendant) { 227 return ancestor && descendant && Boolean($_.compareDocumentPosition(ancestor, descendant) & $_.Node.DOCUMENT_POSITION_CONTAINED_BY); 228 } 229 230 /** 231 * Returns true if ancestor is an ancestor of or equal to descendant, false 232 * otherwise. 233 */ 234 function isAncestorContainer(ancestor, descendant) { 235 return (ancestor || descendant) && (ancestor == descendant || isAncestor(ancestor, descendant)); 236 } 237 238 /** 239 * Returns true if descendant is a descendant of ancestor, false otherwise. 240 */ 241 function isDescendant(descendant, ancestor) { 242 return ancestor && descendant && Boolean($_.compareDocumentPosition(ancestor, descendant) & $_.Node.DOCUMENT_POSITION_CONTAINED_BY); 243 } 244 245 /** 246 * Returns true if node1 is before node2 in tree order, false otherwise. 247 */ 248 function isBefore(node1, node2) { 249 return Boolean($_.compareDocumentPosition(node1, node2) & $_.Node.DOCUMENT_POSITION_FOLLOWING); 250 } 251 252 /** 253 * Returns true if node1 is after node2 in tree order, false otherwise. 254 */ 255 function isAfter(node1, node2) { 256 return Boolean($_.compareDocumentPosition(node1, node2) & $_.Node.DOCUMENT_POSITION_PRECEDING); 257 } 258 259 function getAncestors(node) { 260 var ancestors = []; 261 while (node.parentNode) { 262 ancestors.unshift(node.parentNode); 263 node = node.parentNode; 264 } 265 return ancestors; 266 } 267 268 function getDescendants(node) { 269 var descendants = []; 270 var stop = nextNodeDescendants(node); 271 while (null != (node = nextNode(node)) && node != stop) { 272 descendants.push(node); 273 } 274 return descendants; 275 } 276 277 function convertProperty(property) { 278 // Special-case for now 279 var map = { 280 "fontFamily": "font-family", 281 "fontSize": "font-size", 282 "fontStyle": "font-style", 283 "fontWeight": "font-weight", 284 "textDecoration": "text-decoration" 285 }; 286 if (typeof map[property] != "undefined") { 287 return map[property]; 288 } 289 290 return property; 291 } 292 293 // Return the <font size=X> value for the given CSS size, or undefined if there 294 // is none. 295 function cssSizeToLegacy(cssVal) { 296 return { 297 "xx-small": 1, 298 "small": 2, 299 "medium": 3, 300 "large": 4, 301 "x-large": 5, 302 "xx-large": 6, 303 "xxx-large": 7 304 }[cssVal]; 305 } 306 307 // Return the CSS size given a legacy size. 308 function legacySizeToCss(legacyVal) { 309 return { 310 1: "xx-small", 311 2: "small", 312 3: "medium", 313 4: "large", 314 5: "x-large", 315 6: "xx-large", 316 7: "xxx-large" 317 }[legacyVal]; 318 } 319 320 // "the directionality" from HTML. I don't bother caring about non-HTML 321 // elements. 322 // 323 // "The directionality of an element is either 'ltr' or 'rtl', and is 324 // determined as per the first appropriate set of steps from the following 325 // list:" 326 function getDirectionality(element) { 327 // "If the element's dir attribute is in the ltr state 328 // The directionality of the element is 'ltr'." 329 if (element.dir == "ltr") { 330 return "ltr"; 331 } 332 333 // "If the element's dir attribute is in the rtl state 334 // The directionality of the element is 'rtl'." 335 if (element.dir == "rtl") { 336 return "rtl"; 337 } 338 339 // "If the element's dir attribute is in the auto state 340 // "If the element is a bdi element and the dir attribute is not in a 341 // defined state (i.e. it is not present or has an invalid value) 342 // [lots of complicated stuff] 343 // 344 // Skip this, since no browser implements it anyway. 345 346 // "If the element is a root element and the dir attribute is not in a 347 // defined state (i.e. it is not present or has an invalid value) 348 // The directionality of the element is 'ltr'." 349 if (!isAnyHtmlElement(element.parentNode)) { 350 return "ltr"; 351 } 352 353 // "If the element has a parent element and the dir attribute is not in a 354 // defined state (i.e. it is not present or has an invalid value) 355 // The directionality of the element is the same as the element's 356 // parent element's directionality." 357 return getDirectionality(element.parentNode); 358 } 359 360 //@} 361 362 /////////////////////////////////////////////////////////////////////////////// 363 ///////////////////////////// DOM Range functions ///////////////////////////// 364 /////////////////////////////////////////////////////////////////////////////// 365 //@{ 366 367 // "The length of a Node node is the following, depending on node: 368 // 369 // ProcessingInstruction 370 // DocumentType 371 // Always 0. 372 // Text 373 // Comment 374 // node's length. 375 // Any other node 376 // node's childNodes's length." 377 function getNodeLength(node) { 378 switch (node.nodeType) { 379 case $_.Node.PROCESSING_INSTRUCTION_NODE: 380 case $_.Node.DOCUMENT_TYPE_NODE: 381 return 0; 382 383 case $_.Node.TEXT_NODE: 384 case $_.Node.COMMENT_NODE: 385 return node.length; 386 387 default: 388 return node.childNodes.length; 389 } 390 } 391 392 /** 393 * The position of two boundary points relative to one another, as defined by 394 * DOM Range. 395 */ 396 function getPosition(nodeA, offsetA, nodeB, offsetB) { 397 // "If node A is the same as node B, return equal if offset A equals offset 398 // B, before if offset A is less than offset B, and after if offset A is 399 // greater than offset B." 400 if (nodeA == nodeB) { 401 if (offsetA == offsetB) { 402 return "equal"; 403 } 404 if (offsetA < offsetB) { 405 return "before"; 406 } 407 if (offsetA > offsetB) { 408 return "after"; 409 } 410 } 411 412 var documentPosition = $_.compareDocumentPosition(nodeB, nodeA); 413 // "If node A is after node B in tree order, compute the position of (node 414 // B, offset B) relative to (node A, offset A). If it is before, return 415 // after. If it is after, return before." 416 if (documentPosition & $_.Node.DOCUMENT_POSITION_FOLLOWING) { 417 var pos = getPosition(nodeB, offsetB, nodeA, offsetA); 418 if (pos == "before") { 419 return "after"; 420 } 421 if (pos == "after") { 422 return "before"; 423 } 424 } 425 426 // "If node A is an ancestor of node B:" 427 if (documentPosition & $_.Node.DOCUMENT_POSITION_CONTAINS) { 428 // "Let child equal node B." 429 var child = nodeB; 430 431 // "While child is not a child of node A, set child to its parent." 432 while (child.parentNode != nodeA) { 433 child = child.parentNode; 434 } 435 436 // "If the index of child is less than offset A, return after." 437 if (Dom.getIndexInParent(child) < offsetA) { 438 return "after"; 439 } 440 } 441 442 // "Return before." 443 return "before"; 444 } 445 446 /** 447 * Returns the furthest ancestor of a Node as defined by DOM Range. 448 */ 449 function getFurthestAncestor(node) { 450 var root = node; 451 while (root.parentNode != null) { 452 root = root.parentNode; 453 } 454 return root; 455 } 456 457 /** 458 * "contained" as defined by DOM Range: "A Node node is contained in a range 459 * range if node's furthest ancestor is the same as range's root, and (node, 0) 460 * is after range's start, and (node, length of node) is before range's end." 461 */ 462 function isContained(node, range) { 463 var pos1 = getPosition(node, 0, range.startContainer, range.startOffset); 464 if (pos1 !== "after") { 465 return false; 466 } 467 var pos2 = getPosition(node, getNodeLength(node), range.endContainer, range.endOffset); 468 if (pos2 !== "before") { 469 return false; 470 } 471 return getFurthestAncestor(node) == getFurthestAncestor(range.startContainer); 472 } 473 474 /** 475 * Return all nodes contained in range that the provided function returns true 476 * for, omitting any with an ancestor already being returned. 477 */ 478 function getContainedNodes(range, condition) { 479 if (typeof condition == "undefined") { 480 condition = function () { 481 return true; 482 }; 483 } 484 var node = range.startContainer; 485 if (node.hasChildNodes() && range.startOffset < node.childNodes.length) { 486 // A child is contained 487 node = node.childNodes[range.startOffset]; 488 } else if (range.startOffset == getNodeLength(node)) { 489 // No descendant can be contained 490 node = nextNodeDescendants(node); 491 } else { 492 // No children; this node at least can't be contained 493 node = nextNode(node); 494 } 495 496 var stop = range.endContainer; 497 if (stop.hasChildNodes() && range.endOffset < stop.childNodes.length) { 498 // The node after the last contained node is a child 499 stop = stop.childNodes[range.endOffset]; 500 } else { 501 // This node and/or some of its children might be contained 502 stop = nextNodeDescendants(stop); 503 } 504 505 var nodeList = []; 506 while (isBefore(node, stop)) { 507 if (isContained(node, range) && condition(node)) { 508 nodeList.push(node); 509 node = nextNodeDescendants(node); 510 continue; 511 } 512 node = nextNode(node); 513 } 514 return nodeList; 515 } 516 517 /** 518 * As above, but includes nodes with an ancestor that's already been returned. 519 */ 520 function getAllContainedNodes(range, condition) { 521 if (typeof condition == "undefined") { 522 condition = function () { 523 return true; 524 }; 525 } 526 var node = range.startContainer; 527 if (node.hasChildNodes() && range.startOffset < node.childNodes.length) { 528 // A child is contained 529 node = node.childNodes[range.startOffset]; 530 } else if (range.startOffset == getNodeLength(node)) { 531 // No descendant can be contained 532 node = nextNodeDescendants(node); 533 } else { 534 // No children; this node at least can't be contained 535 node = nextNode(node); 536 } 537 538 var stop = range.endContainer; 539 if (stop.hasChildNodes() && range.endOffset < stop.childNodes.length) { 540 // The node after the last contained node is a child 541 stop = stop.childNodes[range.endOffset]; 542 } else { 543 // This node and/or some of its children might be contained 544 stop = nextNodeDescendants(stop); 545 } 546 547 var nodeList = []; 548 while (isBefore(node, stop)) { 549 if (isContained(node, range) && condition(node)) { 550 nodeList.push(node); 551 } 552 node = nextNode(node); 553 } 554 return nodeList; 555 } 556 557 // Returns either null, or something of the form rgb(x, y, z), or something of 558 // the form rgb(x, y, z, w) with w != 0. 559 function normalizeColor(color) { 560 if (color.toLowerCase() == "currentcolor") { 561 return null; 562 } 563 564 var outerSpan = document.createElement("span"); 565 document.body.appendChild(outerSpan); 566 outerSpan.style.color = "black"; 567 568 var innerSpan = document.createElement("span"); 569 outerSpan.appendChild(innerSpan); 570 innerSpan.style.color = color; 571 color = $_.getComputedStyle(innerSpan).color; 572 573 if (color == "rgb(0, 0, 0)") { 574 // Maybe it's really black, maybe it's invalid. 575 outerSpan.color = "white"; 576 color = $_.getComputedStyle(innerSpan).color; 577 if (color != "rgb(0, 0, 0)") { 578 return null; 579 } 580 } 581 582 document.body.removeChild(outerSpan); 583 584 // I rely on the fact that browsers generally provide consistent syntax for 585 // getComputedStyle(), although it's not standardized. There are only two 586 // exceptions I found: 587 if (/^rgba\([0-9]+, [0-9]+, [0-9]+, 1\)$/.test(color)) { 588 // IE10PP2 seems to do this sometimes. 589 return color.replace("rgba", "rgb").replace(", 1)", ")"); 590 } 591 if (color == "transparent") { 592 // IE10PP2, Firefox 7.0a2, and Opera 11.50 all return "transparent" if 593 // the specified value is "transparent". 594 return "rgba(0, 0, 0, 0)"; 595 } 596 return color; 597 } 598 599 // Returns either null, or something of the form #xxxxxx, or the color itself 600 // if it's a valid keyword. 601 function parseSimpleColor(color) { 602 color = color.toLowerCase(); 603 if ($_(["aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "grey", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen"]).indexOf(color) != -1) { 604 return color; 605 } 606 607 color = normalizeColor(color); 608 var matches = /^rgb\(([0-9]+), ([0-9]+), ([0-9]+)\)$/.exec(color); 609 if (matches) { 610 return "#" + parseInt(matches[1], 10).toString(16).replace(/^.$/, "0$&") + parseInt(matches[2], 10).toString(16).replace(/^.$/, "0$&") + parseInt(matches[3], 10).toString(16).replace(/^.$/, "0$&"); 611 } else if (/^#[abcdef0123456789]+$/i.exec(color)) { 612 // return hexadecimal color values (as returned by IE 7/8) 613 return color; 614 } 615 return null; 616 } 617 618 //@} 619 620 ////////////////////////////////////////////////////////////////////////////// 621 /////////////////////////// Edit command functions /////////////////////////// 622 ////////////////////////////////////////////////////////////////////////////// 623 624 ///////////////////////////////////////////////// 625 ///// Methods of the HTMLDocument interface ///// 626 ///////////////////////////////////////////////// 627 //@{ 628 629 var getStateOverride, 630 setStateOverride, 631 resetOverrides, 632 unsetStateOverride, 633 getValueOverride, 634 setValueOverride, 635 unsetValueOverride; 636 637 var executionStackDepth = 0; 638 639 // Helper function for fontSize's action plus queryOutputHelper. It's just the 640 // middle of fontSize's action, ripped out into its own function. 641 function normalizeFontSize(value) { 642 // "Strip leading and trailing whitespace from value." 643 // 644 // Cheap hack, not following the actual algorithm. 645 value = $_(value).trim(); 646 647 // "If value is a valid floating point number, or would be a valid 648 // floating point number if a single leading "+" character were 649 // stripped:" 650 if (/^[\-+]?[0-9]+(\.[0-9]+)?([eE][\-+]?[0-9]+)?$/.test(value)) { 651 var mode; 652 653 // "If the first character of value is "+", delete the character 654 // and let mode be "relative-plus"." 655 656 if (value[0] == "+") { 657 value = value.slice(1); 658 mode = "relative-plus"; 659 // "Otherwise, if the first character of value is "-", delete the 660 // character and let mode be "relative-minus"." 661 } else if (value[0] == "-") { 662 value = value.slice(1); 663 mode = "relative-minus"; 664 // "Otherwise, let mode be "absolute"." 665 } else { 666 mode = "absolute"; 667 } 668 669 // "Apply the rules for parsing non-negative integers to value, and 670 // let number be the result." 671 // 672 // Another cheap hack. 673 var num = parseInt(value, 10); 674 675 // "If mode is "relative-plus", add three to number." 676 if (mode == "relative-plus") { 677 num += 3; 678 } 679 680 // "If mode is "relative-minus", negate number, then add three to 681 // it." 682 if (mode == "relative-minus") { 683 num = 3 - num; 684 } 685 686 // "If number is less than one, let number equal 1." 687 if (num < 1) { 688 num = 1; 689 } 690 691 // "If number is greater than seven, let number equal 7." 692 if (num > 7) { 693 num = 7; 694 } 695 696 // "Set value to the string here corresponding to number:" [table 697 // omitted] 698 value = { 699 1: "xx-small", 700 2: "small", 701 3: "medium", 702 4: "large", 703 5: "x-large", 704 6: "xx-large", 705 7: "xxx-large" 706 }[num]; 707 } 708 709 return value; 710 } 711 712 function getLegacyFontSize(size) { 713 // For convenience in other places in my code, I handle all sizes, not just 714 // pixel sizes as the spec says. This means pixel sizes have to be passed 715 // in suffixed with "px", not as plain numbers. 716 size = normalizeFontSize(size); 717 718 if (jQuery.inArray(size, ["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"]) == -1 && !/^[0-9]+(\.[0-9]+)?(cm|mm|in|pt|pc|px)$/.test(size)) { 719 // There is no sensible legacy size for things like "2em". 720 return null; 721 } 722 723 var font = document.createElement("font"); 724 document.body.appendChild(font); 725 726 if (size == "xxx-large") { 727 font.size = 7; 728 } else { 729 font.style.fontSize = size; 730 } 731 var pixelSize = parseInt($_.getComputedStyle(font).fontSize, 10); 732 document.body.removeChild(font); 733 734 // "Let returned size be 1." 735 736 var returnedSize = 1; 737 738 // "While returned size is less than 7:" 739 while (returnedSize < 7) { 740 // "Let lower bound be the resolved value of "font-size" in pixels 741 // of a font element whose size attribute is set to returned size." 742 font = document.createElement("font"); 743 font.size = returnedSize; 744 document.body.appendChild(font); 745 var lowerBound = parseInt($_.getComputedStyle(font).fontSize, 10); 746 747 // "Let upper bound be the resolved value of "font-size" in pixels 748 // of a font element whose size attribute is set to one plus 749 // returned size." 750 font.size = 1 + returnedSize; 751 var upperBound = parseInt($_.getComputedStyle(font).fontSize, 10); 752 document.body.removeChild(font); 753 754 // "Let average be the average of upper bound and lower bound." 755 var average = (upperBound + lowerBound) / 2; 756 757 // "If pixel size is less than average, return the one-element 758 // string consisting of the digit returned size." 759 if (pixelSize < average) { 760 return String(returnedSize); 761 } 762 763 // "Add one to returned size." 764 returnedSize++; 765 } 766 767 // "Return "7"." 768 return "7"; 769 } 770 771 // Helper function for common behavior. 772 function editCommandMethod(command, prop, range, callback) { 773 var ret; 774 775 // Set up our global range magic, but only if we're the outermost function 776 if (executionStackDepth === 0) { 777 globalRange = range; 778 } 779 780 executionStackDepth++; 781 try { 782 ret = callback(); 783 } catch (e) { 784 executionStackDepth--; 785 throw e; 786 } 787 executionStackDepth--; 788 return ret; 789 } 790 791 function myQueryCommandEnabled(command, range) { 792 // "All of these methods must treat their command argument ASCII 793 // case-insensitively." 794 command = command.toLowerCase(); 795 796 // "If command is not supported, raise a NOT_SUPPORTED_ERR exception." 797 return editCommandMethod(command, "action", range, (function (command) { 798 return function () { 799 // "Among commands defined in this specification, those listed in 800 // Miscellaneous commands are always enabled. The other commands defined 801 // here are enabled if the active range is not null, and disabled 802 // otherwise." 803 return jQuery.inArray(command, ["copy", "cut", "paste", "selectall", "stylewithcss", "usecss"]) != -1 || range !== null; 804 }; 805 }(command))); 806 } 807 808 function setActiveRange(range) { 809 var rangeObject = new window.GENTICS.Utils.RangeObject(); 810 811 rangeObject.startContainer = range.startContainer; 812 rangeObject.startOffset = range.startOffset; 813 rangeObject.endContainer = range.endContainer; 814 rangeObject.endOffset = range.endOffset; 815 816 rangeObject.select(); 817 } 818 819 function myExecCommand(commandArg, showUiArg, valueArg, range) { 820 // "All of these methods must treat their command argument ASCII 821 // case-insensitively." 822 var command = commandArg.toLowerCase(); 823 var showUi = showUiArg; 824 var value = valueArg; 825 826 // "If only one argument was provided, let show UI be false." 827 // 828 // If range was passed, I can't actually detect how many args were passed 829 // . . . 830 if (arguments.length == 1 || (arguments.length >= 4 && typeof showUi == "undefined")) { 831 showUi = false; 832 } 833 834 // "If only one or two arguments were provided, let value be the empty 835 // string." 836 if (arguments.length <= 2 || (arguments.length >= 4 && typeof value == "undefined")) { 837 value = ""; 838 } 839 840 // "If command is not supported, raise a NOT_SUPPORTED_ERR exception." 841 // 842 // "If command has no action, raise an INVALID_ACCESS_ERR exception." 843 return editCommandMethod(command, "action", range, (function (command, showUi, value) { 844 return function () { 845 // "If command is not enabled, return false." 846 if (!myQueryCommandEnabled(command)) { 847 return false; 848 } 849 850 // "Take the action for command, passing value to the instructions as an 851 // argument." 852 commands[command].action(value, range); 853 854 // always fix the range after the command is complete 855 setActiveRange(range); 856 857 // "Return true." 858 return true; 859 }; 860 }(command, showUi, value))); 861 } 862 863 function myQueryCommandIndeterm(command, range) { 864 // "All of these methods must treat their command argument ASCII 865 // case-insensitively." 866 command = command.toLowerCase(); 867 868 // "If command is not supported, raise a NOT_SUPPORTED_ERR exception." 869 // 870 // "If command has no indeterminacy, raise an INVALID_ACCESS_ERR 871 // exception." 872 return editCommandMethod(command, "indeterm", range, (function (command) { 873 return function () { 874 // "If command is not enabled, return false." 875 if (!myQueryCommandEnabled(command, range)) { 876 return false; 877 } 878 879 // "Return true if command is indeterminate, otherwise false." 880 return commands[command].indeterm(range); 881 }; 882 }(command))); 883 } 884 885 function myQueryCommandState(command, range) { 886 // "All of these methods must treat their command argument ASCII 887 // case-insensitively." 888 command = command.toLowerCase(); 889 890 // "If command is not supported, raise a NOT_SUPPORTED_ERR exception." 891 // 892 // "If command has no state, raise an INVALID_ACCESS_ERR exception." 893 return editCommandMethod(command, "state", range, (function (command) { 894 return function () { 895 // "If command is not enabled, return false." 896 if (!myQueryCommandEnabled(command, range)) { 897 return false; 898 } 899 900 // "If the state override for command is set, return it." 901 if (typeof getStateOverride(command, range) != "undefined") { 902 return getStateOverride(command, range); 903 } 904 905 // "Return true if command's state is true, otherwise false." 906 return commands[command].state(range); 907 }; 908 }(command))); 909 } 910 911 // "When the queryCommandSupported(command) method on the HTMLDocument 912 // interface is invoked, the user agent must return true if command is 913 // supported, and false otherwise." 914 function myQueryCommandSupported(command) { 915 // "All of these methods must treat their command argument ASCII 916 // case-insensitively." 917 command = command.toLowerCase(); 918 919 return commands.hasOwnProperty(command); 920 } 921 922 function myQueryCommandValue(command, range) { 923 // "All of these methods must treat their command argument ASCII 924 // case-insensitively." 925 command = command.toLowerCase(); 926 927 return editCommandMethod(command, "value", range, function () { 928 // "If command is not supported or has no value, return the empty string." 929 if (!commands.hasOwnProperty(command) || !commands[command].hasOwnProperty("value")) { 930 return ""; 931 } 932 933 // "If command is "fontSize" and its value override is set, convert the 934 // value override to an integer number of pixels and return the legacy 935 // font size for the result." 936 if (command == "fontsize" && getValueOverride("fontsize", range) !== undefined) { 937 return getLegacyFontSize(getValueOverride("fontsize", range)); 938 } 939 940 // "If the value override for command is set, return it." 941 if (typeof getValueOverride(command, range) != "undefined") { 942 return getValueOverride(command, range); 943 } 944 945 // "Return command's value." 946 return commands[command].value(range); 947 }); 948 } 949 //@} 950 951 ////////////////////////////// 952 ///// Common definitions ///// 953 ////////////////////////////// 954 //@{ 955 956 // "A prohibited paragraph child name is "address", "article", "aside", 957 // "blockquote", "caption", "center", "col", "colgroup", "dd", "details", 958 // "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", 959 // "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li", 960 // "listing", "menu", "nav", "ol", "p", "plaintext", "pre", "section", 961 // "summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul", or 962 // "xmp"." 963 964 var prohibitedParagraphChildNamesMap = { 965 "ADDRESS": true, 966 "ARTICLE": true, 967 "ASIDE": true, 968 "BLOCKQUOTE": true, 969 "CAPTION": true, 970 "CENTER": true, 971 "COL": true, 972 "COLGROUP": true, 973 "DD": true, 974 "DETAILS": true, 975 "DIR": true, 976 "DIV": true, 977 "DL": true, 978 "DT": true, 979 "FIELDSET": true, 980 "FIGCAPTION": true, 981 "FIGURE": true, 982 "FOOTER": true, 983 "FORM": true, 984 "H1": true, 985 "H2": true, 986 "H3": true, 987 "H4": true, 988 "H5": true, 989 "H6": true, 990 "HEADER": true, 991 "HGROUP": true, 992 "HR": true, 993 "LI": true, 994 "LISTING": true, 995 "MENU": true, 996 "NAV": true, 997 "OL": true, 998 "P": true, 999 "PLAINTEXT": true, 1000 "PRE": true, 1001 "SECTION": true, 1002 "SUMMARY": true, 1003 "TABLE": true, 1004 "TBODY": true, 1005 "TD": true, 1006 "TFOOT": true, 1007 "TH": true, 1008 "THEAD": true, 1009 "TR": true, 1010 "UL": true, 1011 "XMP": true 1012 }; 1013 1014 // "A prohibited paragraph child is an HTML element whose local name is a 1015 // prohibited paragraph child name." 1016 function isProhibitedParagraphChild(node) { 1017 return isMappedHtmlElement(node, prohibitedParagraphChildNamesMap); 1018 } 1019 1020 var nonBlockDisplayValuesMap = { 1021 "inline": true, 1022 "inline-block": true, 1023 "inline-table": true, 1024 "none": true 1025 }; 1026 1027 // "A block node is either an Element whose "display" property does not have 1028 // resolved value "inline" or "inline-block" or "inline-table" or "none", or a 1029 // Document, or a DocumentFragment." 1030 function isBlockNode(node) { 1031 return node && ((node.nodeType == $_.Node.ELEMENT_NODE && !nonBlockDisplayValuesMap[$_.getComputedStyle(node).display]) || node.nodeType == $_.Node.DOCUMENT_NODE || node.nodeType == $_.Node.DOCUMENT_FRAGMENT_NODE); 1032 } 1033 1034 // "An inline node is a node that is not a block node." 1035 function isInlineNode(node) { 1036 return node && !isBlockNode(node); 1037 } 1038 1039 // "An editing host is a node that is either an Element with a contenteditable 1040 // attribute set to the true state, or the Element child of a Document whose 1041 // designMode is enabled." 1042 function isEditingHost(node) { 1043 return node && node.nodeType == $_.Node.ELEMENT_NODE && (node.contentEditable == "true" || (node.parentNode && node.parentNode.nodeType == $_.Node.DOCUMENT_NODE && node.parentNode.designMode == "on")); 1044 } 1045 1046 // "Something is editable if it is a node which is not an editing host, does 1047 // not have a contenteditable attribute set to the false state, and whose 1048 // parent is an editing host or editable." 1049 function isEditable(node) { 1050 // This is slightly a lie, because we're excluding non-HTML elements with 1051 // contentEditable attributes. 1052 return node && !isEditingHost(node) && (node.nodeType != $_.Node.ELEMENT_NODE || node.contentEditable != "false" || jQuery(node).hasClass('aloha-table-wrapper')) && (isEditingHost(node.parentNode) || isEditable(node.parentNode)); 1053 } 1054 1055 // Helper function, not defined in the spec 1056 function hasEditableDescendants(node) { 1057 var i; 1058 for (i = 0; i < node.childNodes.length; i++) { 1059 if (isEditable(node.childNodes[i]) || hasEditableDescendants(node.childNodes[i])) { 1060 return true; 1061 } 1062 } 1063 return false; 1064 } 1065 1066 // "The editing host of node is null if node is neither editable nor an editing 1067 // host; node itself, if node is an editing host; or the nearest ancestor of 1068 // node that is an editing host, if node is editable." 1069 function getEditingHostOf(node) { 1070 if (isEditingHost(node)) { 1071 return node; 1072 } 1073 if (isEditable(node)) { 1074 var ancestor = node.parentNode; 1075 while (!isEditingHost(ancestor)) { 1076 ancestor = ancestor.parentNode; 1077 } 1078 return ancestor; 1079 } 1080 return null; 1081 } 1082 1083 // "Two nodes are in the same editing host if the editing host of the first is 1084 // non-null and the same as the editing host of the second." 1085 function inSameEditingHost(node1, node2) { 1086 return getEditingHostOf(node1) && getEditingHostOf(node1) == getEditingHostOf(node2); 1087 } 1088 1089 // "A collapsed line break is a br that begins a line box which has nothing 1090 // else in it, and therefore has zero height." 1091 function isCollapsedLineBreak(br) { 1092 if (!isNamedHtmlElement(br, 'br')) { 1093 return false; 1094 } 1095 1096 // Add a zwsp after it and see if that changes the height of the nearest 1097 // non-inline parent. Note: this is not actually reliable, because the 1098 // parent might have a fixed height or something. 1099 var ref = br.parentNode; 1100 while ($_.getComputedStyle(ref).display == "inline") { 1101 ref = ref.parentNode; 1102 } 1103 1104 var origStyle = { 1105 height: ref.style.height, 1106 maxHeight: ref.style.maxHeight, 1107 minHeight: ref.style.minHeight 1108 }; 1109 1110 ref.style.height = 'auto'; 1111 ref.style.maxHeight = 'none'; 1112 if (!(Aloha.browser.msie && Aloha.browser.version < 8)) { 1113 ref.style.minHeight = '0'; 1114 } 1115 var space = document.createTextNode('\u200b'); 1116 var origHeight = ref.offsetHeight; 1117 if (origHeight == 0) { 1118 throw 'isCollapsedLineBreak: original height is zero, bug?'; 1119 } 1120 br.parentNode.insertBefore(space, br.nextSibling); 1121 var finalHeight = ref.offsetHeight; 1122 space.parentNode.removeChild(space); 1123 1124 ref.style.height = origStyle.height; 1125 ref.style.maxHeight = origStyle.maxHeight; 1126 if (!(Aloha.browser.msie && Aloha.browser.version < 8)) { 1127 ref.style.minHeight = origStyle.minHeight; 1128 } 1129 1130 // Allow some leeway in case the zwsp didn't create a whole new line, but 1131 // only made an existing line slightly higher. Firefox 6.0a2 shows this 1132 // behavior when the first line is bold. 1133 return origHeight < finalHeight - 5; 1134 } 1135 1136 // "An extraneous line break is a br that has no visual effect, in that 1137 // removing it from the DOM would not change layout, except that a br that is 1138 // the sole child of an li is not extraneous." 1139 function isExtraneousLineBreak(br) { 1140 1141 if (!isNamedHtmlElement(br, 'br')) { 1142 return false; 1143 } 1144 1145 if (isNamedHtmlElement(br.parentNode, "li") && br.parentNode.childNodes.length == 1) { 1146 return false; 1147 } 1148 1149 // Make the line break disappear and see if that changes the block's 1150 // height. Yes, this is an absurd hack. We have to reset height etc. on 1151 // the reference node because otherwise its height won't change if it's not 1152 // auto. 1153 var ref = br.parentNode; 1154 while ($_.getComputedStyle(ref).display == "inline") { 1155 ref = ref.parentNode; 1156 } 1157 1158 var origStyle = { 1159 height: ref.style.height, 1160 maxHeight: ref.style.maxHeight, 1161 minHeight: ref.style.minHeight, 1162 contentEditable: ref.contentEditable 1163 }; 1164 1165 ref.style.height = 'auto'; 1166 ref.style.maxHeight = 'none'; 1167 ref.style.minHeight = '0'; 1168 // IE7 would ignore display:none in contentEditable, so we temporarily set it to false 1169 if (Aloha.browser.msie && Aloha.browser.version <= 7) { 1170 ref.contentEditable = 'false'; 1171 } 1172 1173 var origHeight = ref.offsetHeight; 1174 if (origHeight == 0) { 1175 throw "isExtraneousLineBreak: original height is zero, bug?"; 1176 } 1177 1178 var origBrDisplay = br.style.display; 1179 br.style.display = 'none'; 1180 var finalHeight = ref.offsetHeight; 1181 1182 // Restore original styles to the touched elements. 1183 ref.style.height = origStyle.height; 1184 ref.style.maxHeight = origStyle.maxHeight; 1185 ref.style.minHeight = origStyle.minHeight; 1186 // reset contentEditable for IE7 1187 if (Aloha.browser.msie && Aloha.browser.version <= 7) { 1188 ref.contentEditable = origStyle.contentEditable; 1189 } 1190 br.style.display = origBrDisplay; 1191 1192 // https://github.com/alohaeditor/Aloha-Editor/issues/516 1193 // look like it works in msie > 7 1194 /* if (Aloha.browser.msie && Aloha.browser.version < 8) { 1195 br.removeAttribute("style"); 1196 ref.removeAttribute("style"); 1197 } */ 1198 1199 return origHeight == finalHeight; 1200 } 1201 1202 // "A whitespace node is either a Text node whose data is the empty string; or 1203 // a Text node whose data consists only of one or more tabs (0x0009), line 1204 // feeds (0x000A), carriage returns (0x000D), and/or spaces (0x0020), and whose 1205 // parent is an Element whose resolved value for "white-space" is "normal" or 1206 // "nowrap"; or a Text node whose data consists only of one or more tabs 1207 // (0x0009), carriage returns (0x000D), and/or spaces (0x0020), and whose 1208 // parent is an Element whose resolved value for "white-space" is "pre-line"." 1209 function isWhitespaceNode(node) { 1210 var nodeTypes = $_.Node; 1211 if (node && node.nodeType === nodeTypes.TEXT_NODE) { 1212 var parentNode = node.parentNode; 1213 1214 var nodeData = node.data; 1215 if (jQuery.trim(nodeData).length === 0) { 1216 return true; 1217 } else if (parentNode && /^[\t\n\r ]+$/.test(nodeData)) { 1218 if (parentNode.nodeType === nodeTypes.ELEMENT_NODE) { 1219 if (jQuery.inArray($_.getComputedStyle(parentNode).whiteSpace, ["normal", "nowrap"]) !== -1) { 1220 return true; 1221 } else if ($_.getComputedStyle(parentNode).whiteSpace === "pre-line") { 1222 return true; 1223 } 1224 } else if (parentNode.nodeType === nodeTypes.DOCUMENT_FRAGMENT_NODE) { 1225 return true; 1226 } 1227 } 1228 } 1229 return false; 1230 } 1231 1232 /** 1233 * Collapse sequences of ignorable whitespace (tab (0x0009), line feed (0x000A), carriage return (0x000D), space (0x0020)) to only one space. 1234 * Preserve the given range if necessary. 1235 * @param node text node 1236 * @param range range 1237 */ 1238 function collapseWhitespace(node, range) { 1239 // "If node is neither editable nor an editing host, abort these steps." 1240 if (!isEditable(node) && !isEditingHost(node)) { 1241 return; 1242 } 1243 1244 // if the given node is not a text node, return 1245 if (!node || node.nodeType !== $_.Node.TEXT_NODE) { 1246 return; 1247 } 1248 1249 // if the node is in a pre or pre-wrap node, return 1250 if (jQuery.inArray($_.getComputedStyle(node.parentNode).whiteSpace, ["pre", "pre-wrap"]) != -1) { 1251 1252 return; 1253 } 1254 1255 // if the given node does not contain sequences of at least two consecutive ignorable whitespace characters, return 1256 if (!/[\t\n\r ]{2,}/.test(node.data)) { 1257 return; 1258 } 1259 1260 1261 var newData = ''; 1262 var correctStart = range.startContainer == node; 1263 var correctEnd = range.endContainer == node; 1264 var wsFound = false; 1265 var i; 1266 1267 // iterate through the node data 1268 for (i = 0; i < node.data.length; ++i) { 1269 if (/[\t\n\r ]/.test(node.data.substr(i, 1))) { 1270 // found a whitespace 1271 if (!wsFound) { 1272 // this is the first whitespace in the current sequence 1273 // add a whitespace to the new data sequence 1274 newData += ' '; 1275 // remember that we found a whitespace 1276 wsFound = true; 1277 } else { 1278 // this is not the first whitespace in the sequence, so omit this character 1279 if (correctStart && newData.length < range.startOffset) { 1280 range.startOffset--; 1281 } 1282 if (correctEnd && newData.length < range.endOffset) { 1283 range.endOffset--; 1284 } 1285 } 1286 } else { 1287 newData += node.data.substr(i, 1); 1288 wsFound = false; 1289 } 1290 } 1291 1292 // set the new data 1293 node.data = newData; 1294 } 1295 1296 // "node is a collapsed whitespace node if the following algorithm returns 1297 // true:" 1298 function isCollapsedWhitespaceNode(node) { 1299 // "If node is not a whitespace node, return false." 1300 if (!isWhitespaceNode(node)) { 1301 return false; 1302 } 1303 1304 // "If node's data is the empty string, return true." 1305 if (node.data == "") { 1306 return true; 1307 } 1308 1309 // "Let ancestor be node's parent." 1310 var ancestor = node.parentNode; 1311 1312 // "If ancestor is null, return true." 1313 if (!ancestor) { 1314 return true; 1315 } 1316 1317 // "If the "display" property of some ancestor of node has resolved value 1318 // "none", return true." 1319 if ($_(getAncestors(node)).some(function (ancestor) { return ancestor.nodeType == $_.Node.ELEMENT_NODE && $_.getComputedStyle(ancestor).display == "none"; })) { 1320 return true; 1321 } 1322 1323 // "While ancestor is not a block node and its parent is not null, set 1324 // ancestor to its parent." 1325 while (!isBlockNode(ancestor) && ancestor.parentNode) { 1326 ancestor = ancestor.parentNode; 1327 } 1328 1329 // "Let reference be node." 1330 var reference = node; 1331 1332 // "While reference is a descendant of ancestor:" 1333 while (reference != ancestor) { 1334 // "Let reference be the node before it in tree order." 1335 reference = previousNode(reference); 1336 1337 // "If reference is a block node or a br, return true." 1338 if (isBlockNode(reference) || isNamedHtmlElement(reference, 'br')) { 1339 return true; 1340 } 1341 1342 // "If reference is a Text node that is not a whitespace node, or is an 1343 // img, break from this loop." 1344 if ((reference.nodeType == $_.Node.TEXT_NODE && !isWhitespaceNode(reference)) || isNamedHtmlElement(reference, 'img')) { 1345 break; 1346 } 1347 } 1348 1349 // "Let reference be node." 1350 reference = node; 1351 1352 // "While reference is a descendant of ancestor:" 1353 var stop = nextNodeDescendants(ancestor); 1354 while (reference != stop) { 1355 // "Let reference be the node after it in tree order, or null if there 1356 // is no such node." 1357 reference = nextNode(reference); 1358 1359 // "If reference is a block node or a br, return true." 1360 if (isBlockNode(reference) || isNamedHtmlElement(reference, 'br')) { 1361 return true; 1362 } 1363 1364 // "If reference is a Text node that is not a whitespace node, or is an 1365 // img, break from this loop." 1366 1367 if ((reference && reference.nodeType == $_.Node.TEXT_NODE && !isWhitespaceNode(reference)) || isNamedHtmlElement(reference, 'img')) { 1368 break; 1369 } 1370 } 1371 1372 // "Return false." 1373 return false; 1374 } 1375 1376 // "Something is visible if it is a node that either is a block node, or a Text 1377 // node that is not a collapsed whitespace node, or an img, or a br that is not 1378 // an extraneous line break, or any node with a visible descendant; excluding 1379 // any node with an ancestor container Element whose "display" property has 1380 // resolved value "none"." 1381 function isVisible(node) { 1382 var i; 1383 1384 if (!node) { 1385 return false; 1386 } 1387 1388 if ($_(getAncestors(node).concat(node)) 1389 .filter(function (node) { return node.nodeType == $_.Node.ELEMENT_NODE; }, true) 1390 .some(function (node) { return $_.getComputedStyle(node).display == "none"; })) { 1391 return false; 1392 } 1393 1394 if (isBlockNode(node) || (node.nodeType == $_.Node.TEXT_NODE && !isCollapsedWhitespaceNode(node)) || isNamedHtmlElement(node, 'img') || (isNamedHtmlElement(node, 'br') && !isExtraneousLineBreak(node))) { 1395 return true; 1396 } 1397 1398 for (i = 0; i < node.childNodes.length; i++) { 1399 if (isVisible(node.childNodes[i])) { 1400 return true; 1401 } 1402 } 1403 1404 return false; 1405 } 1406 1407 // "Something is invisible if it is a node that is not visible." 1408 function isInvisible(node) { 1409 return node && !isVisible(node); 1410 } 1411 1412 // "A collapsed block prop is either a collapsed line break that is not an 1413 // extraneous line break, or an Element that is an inline node and whose 1414 // children are all either invisible or collapsed block props and that has at 1415 // least one child that is a collapsed block prop." 1416 function isCollapsedBlockProp(node) { 1417 var i; 1418 1419 if (isCollapsedLineBreak(node) && !isExtraneousLineBreak(node)) { 1420 return true; 1421 } 1422 1423 if (!isInlineNode(node) || node.nodeType != $_.Node.ELEMENT_NODE) { 1424 return false; 1425 } 1426 1427 var hasCollapsedBlockPropChild = false; 1428 for (i = 0; i < node.childNodes.length; i++) { 1429 if (!isInvisible(node.childNodes[i]) && !isCollapsedBlockProp(node.childNodes[i])) { 1430 return false; 1431 } 1432 if (isCollapsedBlockProp(node.childNodes[i])) { 1433 hasCollapsedBlockPropChild = true; 1434 } 1435 } 1436 1437 return hasCollapsedBlockPropChild; 1438 } 1439 1440 /** 1441 * Checks whether the given node is a visible text node. 1442 * 1443 * @param {HTMLElement} node 1444 * @return {Boolean} True if `node` is a visible text node. 1445 */ 1446 function isInvisibleTextNode(node) { 1447 if (node && node.nodeType !== $_.Node.TEXT_NODE) { 1448 return false; 1449 } 1450 var offset = 0; 1451 var data = node.data; 1452 var len = data.length; 1453 while (offset < len && data.charAt(offset) === '\u200b') { 1454 offset++; 1455 } 1456 return offset === len; 1457 } 1458 1459 /** 1460 * Complement of isInvisibleTextNode(). 1461 * 1462 * @param {HTMLElement} node 1463 * @return {Boolean} True if `node` is anything but an invisible text node. 1464 */ 1465 function isNotInvisibleTextNode(node) { 1466 return !isInvisibleTextNode(node); 1467 } 1468 1469 /** 1470 * Checks whether the given node is a otherwise empty block-level element 1471 * containing a propping <br> element. 1472 * 1473 * @param {HTMLElement} node 1474 * @return {Boolean} True if `node` is a propped up block-level element. 1475 */ 1476 function isProppedBlock(node) { 1477 if (!Html.isBlock(node)) { 1478 return false; 1479 } 1480 var child = Html.findNodeRight(node.lastChild, isVisible); 1481 return ( 1482 child 1483 && 'br' === child.nodeName.toLowerCase() 1484 && !Html.findNodeRight(child.previousSibling, isVisible) 1485 ); 1486 } 1487 1488 /** 1489 * Checks whether the given node is a empty element, or an element that 1490 * would otherwise be empty except for a propping <br>, or an element 1491 * containing only invisible text nodes. 1492 * 1493 * @param {HTMLElement} node 1494 * @return {Boolean} True if `node` can be considered empty. 1495 */ 1496 function isEmptyNode(node) { 1497 return ( 1498 !node.hasChildNodes() 1499 || isProppedBlock(node) 1500 || !Html.findNodeRight(node.lastChild, isNotInvisibleTextNode) 1501 ); 1502 } 1503 1504 /** 1505 * Check if the given node is a empty element which is the only 1506 * immediate child of a editing host. 1507 * 1508 * @param {HTMLElement} node 1509 * @return {Boolean} True if `node` can be regarded as empty and the 1510 * only immediate child of its parent editing host. 1511 */ 1512 function isEmptyOnlyChildOfEditingHost(node) { 1513 return ( 1514 node 1515 && isEmptyNode(node) 1516 && isEditingHost(node.parentNode) 1517 && !node.previousSibling 1518 && !node.nextSibling 1519 ); 1520 } 1521 1522 /** 1523 * Remove the given node and return the position from where it was 1524 * removed. 1525 * 1526 * @param {HTMLElement} node Element to remove from DOM 1527 * @return {object} Object containing node and offset index. 1528 */ 1529 function removeNode(node) { 1530 var ancestor = node.parentNode; 1531 var offset = Dom.getIndexInParent(node); 1532 ancestor.removeChild(node); 1533 return { 1534 node: ancestor, 1535 offset: offset 1536 }; 1537 } 1538 1539 // Please note: This method is deprecated and will be removed. 1540 // Every command should use the value and range parameter. 1541 // 1542 // "The active range is the first range in the Selection given by calling 1543 // getSelection() on the context object, or null if there is no such range." 1544 // 1545 // We cheat and return globalRange if that's defined. We also ensure that the 1546 // active range meets the requirements that selection boundary points are 1547 // supposed to meet, i.e., that the nodes are both Text or Element nodes that 1548 // descend from a Document. 1549 function getActiveRange() { 1550 var ret; 1551 if (globalRange) { 1552 ret = globalRange; 1553 } else if (Aloha.getSelection().rangeCount) { 1554 ret = Aloha.getSelection().getRangeAt(0); 1555 } else { 1556 return null; 1557 } 1558 if (jQuery.inArray(ret.startContainer.nodeType, [$_.Node.TEXT_NODE, $_.Node.ELEMENT_NODE]) == -1 || jQuery.inArray(ret.endContainer.nodeType, [$_.Node.TEXT_NODE, $_.Node.ELEMENT_NODE]) == -1 || !ret.startContainer.ownerDocument || !ret.endContainer.ownerDocument || !isDescendant(ret.startContainer, ret.startContainer.ownerDocument) || !isDescendant(ret.endContainer, ret.endContainer.ownerDocument)) { 1559 throw "Invalid active range; test bug?"; 1560 } 1561 return ret; 1562 } 1563 1564 1565 // "For some commands, each HTMLDocument must have a boolean state override 1566 // and/or a string value override. These do not change the command's state or 1567 // value, but change the way some algorithms behave, as specified in those 1568 // algorithms' definitions. Initially, both must be unset for every command. 1569 // Whenever the number of ranges in the Selection changes to something 1570 // different, and whenever a boundary point of the range at a given index in 1571 // the Selection changes to something different, the state override and value 1572 // override must be unset for every command." 1573 // 1574 // We implement this crudely by using setters and getters. To verify that the 1575 // selection hasn't changed, we copy the active range and just check the 1576 // endpoints match. This isn't really correct, but it's good enough for us. 1577 // Unset state/value overrides are undefined. We put everything in a function 1578 // so no one can access anything except via the provided functions, since 1579 // otherwise callers might mistakenly use outdated overrides (if the selection 1580 // has changed). 1581 (function () { 1582 var stateOverrides = {}; 1583 var valueOverrides = {}; 1584 var storedRange = null; 1585 1586 resetOverrides = function (range) { 1587 if (!storedRange 1588 || storedRange.startContainer != range.startContainer 1589 || storedRange.endContainer != range.endContainer 1590 || storedRange.startOffset != range.startOffset 1591 || storedRange.endOffset != range.endOffset) { 1592 storedRange = { 1593 startContainer: range.startContainer, 1594 endContainer: range.endContainer, 1595 startOffset: range.startOffset, 1596 endOffset: range.endOffset 1597 }; 1598 if (!Maps.isEmpty(stateOverrides) || !Maps.isEmpty(valueOverrides)) { 1599 stateOverrides = {}; 1600 valueOverrides = {}; 1601 return true; 1602 } 1603 } 1604 return false; 1605 }; 1606 1607 getStateOverride = function (command, range) { 1608 1609 resetOverrides(range); 1610 return stateOverrides[command]; 1611 }; 1612 1613 setStateOverride = function (command, newState, range) { 1614 resetOverrides(range); 1615 stateOverrides[command] = newState; 1616 }; 1617 1618 unsetStateOverride = function (command, range) { 1619 resetOverrides(range); 1620 delete stateOverrides[command]; 1621 }; 1622 1623 getValueOverride = function (command, range) { 1624 resetOverrides(range); 1625 return valueOverrides[command]; 1626 }; 1627 1628 // "The value override for the backColor command must be the same as the 1629 // value override for the hiliteColor command, such that setting one sets 1630 // the other to the same thing and unsetting one unsets the other." 1631 setValueOverride = function (command, newValue, range) { 1632 resetOverrides(range); 1633 valueOverrides[command] = newValue; 1634 if (command == "backcolor") { 1635 valueOverrides.hilitecolor = newValue; 1636 } else if (command == "hilitecolor") { 1637 valueOverrides.backcolor = newValue; 1638 } 1639 }; 1640 1641 unsetValueOverride = function (command, range) { 1642 resetOverrides(range); 1643 delete valueOverrides[command]; 1644 if (command == "backcolor") { 1645 delete valueOverrides.hilitecolor; 1646 } else if (command == "hilitecolor") { 1647 delete valueOverrides.backcolor; 1648 } 1649 }; 1650 }()); 1651 1652 //@} 1653 1654 ///////////////////////////// 1655 ///// Common algorithms ///// 1656 ///////////////////////////// 1657 1658 ///// Assorted common algorithms ///// 1659 //@{ 1660 1661 function movePreservingRanges(node, newParent, newIndex, range) { 1662 // For convenience, I allow newIndex to be -1 to mean "insert at the end". 1663 if (newIndex == -1) { 1664 newIndex = newParent.childNodes.length; 1665 } 1666 1667 // "When the user agent is to move a Node to a new location, preserving 1668 // ranges, it must remove the Node from its original parent (if any), then 1669 // insert it in the new location. In doing so, however, it must ignore the 1670 // regular range mutation rules, and instead follow these rules:" 1671 1672 // "Let node be the moved Node, old parent and old index be the old parent 1673 // (which may be null) and index, and new parent and new index be the new 1674 // parent and index." 1675 var oldParent = node.parentNode; 1676 var oldIndex = Dom.getIndexInParent(node); 1677 var i; 1678 1679 // We only even attempt to preserve the global range object and the ranges 1680 // in the selection, not every range out there (the latter is probably 1681 // impossible). 1682 var ranges = [range]; 1683 for (i = 0; i < Aloha.getSelection().rangeCount; i++) { 1684 ranges.push(Aloha.getSelection().getRangeAt(i)); 1685 } 1686 var boundaryPoints = []; 1687 $_(ranges).forEach(function (range) { 1688 boundaryPoints.push([range.startContainer, range.startOffset]); 1689 boundaryPoints.push([range.endContainer, range.endOffset]); 1690 }); 1691 1692 $_(boundaryPoints).forEach(function (boundaryPoint) { 1693 // "If a boundary point's node is the same as or a descendant of node, 1694 // leave it unchanged, so it moves to the new location." 1695 // 1696 // No modifications necessary. 1697 1698 // "If a boundary point's node is new parent and its offset is greater 1699 // than new index, add one to its offset." 1700 if (boundaryPoint[0] == newParent && boundaryPoint[1] > newIndex) { 1701 boundaryPoint[1]++; 1702 } 1703 1704 // "If a boundary point's node is old parent and its offset is old index or 1705 // old index + 1, set its node to new parent and add new index − old index 1706 // to its offset." 1707 if (boundaryPoint[0] == oldParent && (boundaryPoint[1] == oldIndex || boundaryPoint[1] == oldIndex + 1)) { 1708 boundaryPoint[0] = newParent; 1709 boundaryPoint[1] += newIndex - oldIndex; 1710 } 1711 1712 // "If a boundary point's node is old parent and its offset is greater than 1713 // old index + 1, subtract one from its offset." 1714 if (boundaryPoint[0] == oldParent && boundaryPoint[1] > oldIndex + 1) { 1715 boundaryPoint[1]--; 1716 } 1717 }); 1718 1719 // Now actually move it and preserve the ranges. 1720 if (newParent.childNodes.length == newIndex) { 1721 newParent.appendChild(node); 1722 } else { 1723 newParent.insertBefore(node, newParent.childNodes[newIndex]); 1724 } 1725 1726 // if we're off actual node boundaries this implies that the move was 1727 // part of a deletion process (backspace). If that's the case we 1728 // attempt to fix this by restoring the range to the first index of 1729 // the node that has been moved 1730 var newRange = null; 1731 if (boundaryPoints[0][1] > boundaryPoints[0][0].childNodes.length && boundaryPoints[1][1] > boundaryPoints[1][0].childNodes.length) { 1732 range.setStart(node, 0); 1733 range.setEnd(node, 0); 1734 } else { 1735 range.setStart(boundaryPoints[0][0], boundaryPoints[0][1]); 1736 range.setEnd(boundaryPoints[1][0], boundaryPoints[1][1]); 1737 1738 Aloha.getSelection().removeAllRanges(); 1739 for (i = 1; i < ranges.length; i++) { 1740 newRange = Aloha.createRange(); 1741 newRange.setStart(boundaryPoints[2 * i][0], boundaryPoints[2 * i][1]); 1742 newRange.setEnd(boundaryPoints[2 * i + 1][0], boundaryPoints[2 * i + 1][1]); 1743 Aloha.getSelection().addRange(newRange); 1744 } 1745 if (newRange) { 1746 range = newRange; 1747 } 1748 } 1749 } 1750 1751 /** 1752 * Copy all non empty attributes from an existing to a new element 1753 * 1754 * @param {dom} element The source DOM element 1755 * @param {dom} newElement The new DOM element which will get the attributes of the source DOM element 1756 * @return void 1757 */ 1758 function copyAttributes(element, newElement) { 1759 1760 // This is an IE7 workaround. We identified three places that were connected 1761 // to the mysterious ie7 crash: 1762 // 1. Add attribute to dom element (Initialization of jquery-ui sortable) 1763 // 2. Access the jquery expando attribute. Just reading the name is 1764 // sufficient to make the browser vulnerable for the crash (Press enter) 1765 // 3. On editable blur the Aloha.editables[0].getContents(); gets invoked. 1766 // This invokation somehow crashes the ie7. We assume that the access of 1767 // shared expando attribute updates internal references which are not 1768 // correclty handled during clone(); 1769 if (Aloha.browser.msie && Aloha.browser.version >= 7 && typeof element.attributes[jQuery.expando] !== 'undefined') { 1770 jQuery(element).removeAttr(jQuery.expando); 1771 } 1772 1773 var attrs = element.attributes; 1774 var i; 1775 for (i = 0; i < attrs.length; i++) { 1776 var attr = attrs[i]; 1777 // attr.specified is an IE specific check to exclude attributes that were never really set. 1778 if (typeof attr.specified === "undefined" || attr.specified) { 1779 if (typeof newElement.setAttributeNS === 'function') { 1780 newElement.setAttributeNS(attr.namespaceURI, attr.name, attr.value); 1781 } else { 1782 // fixes https://github.com/alohaeditor/Aloha-Editor/issues/515 1783 newElement.setAttribute(attr.name, attr.value); 1784 } 1785 } 1786 } 1787 } 1788 1789 function setTagName(element, newName, range) { 1790 // "If element is an HTML element with local name equal to new name, return 1791 // element." 1792 if (isNamedHtmlElement(element, newName)) { 1793 return element; 1794 } 1795 1796 1797 // "If element's parent is null, return element." 1798 if (!element.parentNode) { 1799 return element; 1800 } 1801 1802 // "Let replacement element be the result of calling createElement(new 1803 // name) on the ownerDocument of element." 1804 var replacementElement = element.ownerDocument.createElement(newName); 1805 1806 // "Insert replacement element into element's parent immediately before 1807 // element." 1808 element.parentNode.insertBefore(replacementElement, element); 1809 1810 // "Copy all attributes of element to replacement element, in order." 1811 copyAttributes(element, replacementElement); 1812 1813 // "While element has children, append the first child of element as the 1814 // last child of replacement element, preserving ranges." 1815 while (element.childNodes.length) { 1816 movePreservingRanges(element.firstChild, replacementElement, replacementElement.childNodes.length, range); 1817 } 1818 1819 // "Remove element from its parent." 1820 element.parentNode.removeChild(element); 1821 1822 // if the range still uses the old element, we modify it to the new one 1823 if (range.startContainer === element) { 1824 range.startContainer = replacementElement; 1825 } 1826 if (range.endContainer === element) { 1827 range.endContainer = replacementElement; 1828 } 1829 1830 // "Return replacement element." 1831 return replacementElement; 1832 } 1833 1834 function removeExtraneousLineBreaksBefore(node) { 1835 // "Let ref be the previousSibling of node." 1836 var ref = node.previousSibling; 1837 1838 // "If ref is null, abort these steps." 1839 if (!ref) { 1840 return; 1841 } 1842 1843 // "While ref has children, set ref to its lastChild." 1844 while (ref.hasChildNodes()) { 1845 ref = ref.lastChild; 1846 } 1847 1848 // "While ref is invisible but not an extraneous line break, and ref does 1849 // not equal node's parent, set ref to the node before it in tree order." 1850 while (isInvisible(ref) && !isExtraneousLineBreak(ref) && ref != node.parentNode) { 1851 ref = previousNode(ref); 1852 } 1853 1854 // "If ref is an editable extraneous line break, remove it from its 1855 // parent." 1856 if (isEditable(ref) && isExtraneousLineBreak(ref)) { 1857 ref.parentNode.removeChild(ref); 1858 } 1859 } 1860 1861 function removeExtraneousLineBreaksAtTheEndOf(node) { 1862 // "Let ref be node." 1863 var ref = node; 1864 1865 // "While ref has children, set ref to its lastChild." 1866 while (ref.hasChildNodes()) { 1867 ref = ref.lastChild; 1868 } 1869 1870 // "While ref is invisible but not an extraneous line break, and ref does 1871 // not equal node, set ref to the node before it in tree order." 1872 while (isInvisible(ref) && !isExtraneousLineBreak(ref) && ref != node) { 1873 ref = previousNode(ref); 1874 } 1875 1876 // "If ref is an editable extraneous line break, remove it from its 1877 // parent." 1878 if (isEditable(ref) && isExtraneousLineBreak(ref)) { 1879 ref.parentNode.removeChild(ref); 1880 } 1881 } 1882 1883 // "To remove extraneous line breaks from a node, first remove extraneous line 1884 // breaks before it, then remove extraneous line breaks at the end of it." 1885 function removeExtraneousLineBreaksFrom(node) { 1886 removeExtraneousLineBreaksBefore(node); 1887 removeExtraneousLineBreaksAtTheEndOf(node); 1888 } 1889 1890 //@} 1891 ///// Wrapping a list of nodes ///// 1892 //@{ 1893 1894 function wrap(nodeList, siblingCriteria, newParentInstructions, range) { 1895 var i; 1896 1897 // "If not provided, sibling criteria returns false and new parent 1898 // instructions returns null." 1899 if (typeof siblingCriteria == "undefined") { 1900 siblingCriteria = function () { 1901 return false; 1902 }; 1903 } 1904 if (typeof newParentInstructions == "undefined") { 1905 newParentInstructions = function () { 1906 return null; 1907 }; 1908 } 1909 1910 // "If node list is empty, or the first member of node list is not 1911 // editable, return null and abort these steps." 1912 if (!nodeList.length || !isEditable(nodeList[0])) { 1913 return null; 1914 } 1915 1916 // "If node list's last member is an inline node that's not a br, and node 1917 // list's last member's nextSibling is a br, append that br to node list." 1918 if (isInlineNode(nodeList[nodeList.length - 1]) && !isNamedHtmlElement(nodeList[nodeList.length - 1], "br") && isNamedHtmlElement(nodeList[nodeList.length - 1].nextSibling, "br")) { 1919 nodeList.push(nodeList[nodeList.length - 1].nextSibling); 1920 } 1921 1922 // "If the previousSibling of the first member of node list is editable and 1923 // running sibling criteria on it returns true, let new parent be the 1924 // previousSibling of the first member of node list." 1925 var newParent; 1926 if (isEditable(nodeList[0].previousSibling) && siblingCriteria(nodeList[0].previousSibling)) { 1927 newParent = nodeList[0].previousSibling; 1928 1929 // "Otherwise, if the nextSibling of the last member of node list is 1930 // editable and running sibling criteria on it returns true, let new parent 1931 // be the nextSibling of the last member of node list." 1932 } else if (isEditable(nodeList[nodeList.length - 1].nextSibling) && siblingCriteria(nodeList[nodeList.length - 1].nextSibling)) { 1933 newParent = nodeList[nodeList.length - 1].nextSibling; 1934 1935 // "Otherwise, run new parent instructions, and let new parent be the 1936 // result." 1937 } else { 1938 newParent = newParentInstructions(); 1939 } 1940 1941 // "If new parent is null, abort these steps and return null." 1942 if (!newParent) { 1943 return null; 1944 } 1945 1946 // "If new parent's parent is null:" 1947 if (!newParent.parentNode) { 1948 // "Insert new parent into the parent of the first member of node list 1949 // immediately before the first member of node list." 1950 nodeList[0].parentNode.insertBefore(newParent, nodeList[0]); 1951 1952 // "If any range has a boundary point with node equal to the parent of 1953 // new parent and offset equal to the index of new parent, add one to 1954 // that boundary point's offset." 1955 // 1956 // Try to fix range 1957 var startContainer = range.startContainer, 1958 startOffset = range.startOffset, 1959 endContainer = range.endContainer, 1960 endOffset = range.endOffset, 1961 newParentIndex = Dom.getIndexInParent(newParent); 1962 1963 if (startOffset >= newParentIndex && startContainer == newParent.parentNode) { 1964 range.setStart(startContainer, startOffset + 1); 1965 } 1966 if (endOffset >= newParentIndex && endContainer == newParent.parentNode) { 1967 range.setEnd(endContainer, endOffset + 1); 1968 } 1969 1970 // Only try to fix the global range. TODO remove globalRange here 1971 if (globalRange && globalRange !== range) { 1972 startContainer = globalRange.startContainer; 1973 startOffset = globalRange.startOffset; 1974 endContainer = globalRange.endContainer; 1975 endOffset = globalRange.endOffset; 1976 if (startContainer == newParent.parentNode && startOffset >= newParentIndex) { 1977 globalRange.setStart(startContainer, startOffset + 1); 1978 } 1979 if (endContainer == newParent.parentNode && endOffset >= newParentIndex) { 1980 globalRange.setEnd(endContainer, endOffset + 1); 1981 } 1982 } 1983 } 1984 1985 // "Let original parent be the parent of the first member of node list." 1986 var originalParent = nodeList[0].parentNode; 1987 1988 // "If new parent is before the first member of node list in tree order:" 1989 if (isBefore(newParent, nodeList[0])) { 1990 // "If new parent is not an inline node, but the last child of new 1991 // parent and the first member of node list are both inline nodes, and 1992 // the last child of new parent is not a br, call createElement("br") 1993 // on the ownerDocument of new parent and append the result as the last 1994 // child of new parent." 1995 if (!isInlineNode(newParent) && isInlineNode(newParent.lastChild) && isInlineNode(nodeList[0]) && !isNamedHtmlElement(newParent.lastChild, "BR")) { 1996 newParent.appendChild(newParent.ownerDocument.createElement("br")); 1997 } 1998 1999 // "For each node in node list, append node as the last child of new 2000 // parent, preserving ranges." 2001 for (i = 0; i < nodeList.length; i++) { 2002 movePreservingRanges(nodeList[i], newParent, -1, range); 2003 } 2004 2005 // "Otherwise:" 2006 } else { 2007 // "If new parent is not an inline node, but the first child of new 2008 // parent and the last member of node list are both inline nodes, and 2009 // the last member of node list is not a br, call createElement("br") 2010 // on the ownerDocument of new parent and insert the result as the 2011 // first child of new parent." 2012 if (!isInlineNode(newParent) && isInlineNode(newParent.firstChild) && isInlineNode(nodeList[nodeList.length - 1]) && !isNamedHtmlElement(nodeList[nodeList.length - 1], "BR")) { 2013 newParent.insertBefore(newParent.ownerDocument.createElement("br"), newParent.firstChild); 2014 } 2015 2016 // "For each node in node list, in reverse order, insert node as the 2017 // first child of new parent, preserving ranges." 2018 for (i = nodeList.length - 1; i >= 0; i--) { 2019 movePreservingRanges(nodeList[i], newParent, 0, range); 2020 } 2021 } 2022 2023 // "If original parent is editable and has no children, remove it from its 2024 // parent." 2025 if (isEditable(originalParent) && !originalParent.hasChildNodes()) { 2026 originalParent.parentNode.removeChild(originalParent); 2027 } 2028 2029 // "If new parent's nextSibling is editable and running sibling criteria on 2030 // it returns true:" 2031 if (isEditable(newParent.nextSibling) && siblingCriteria(newParent.nextSibling)) { 2032 // "If new parent is not an inline node, but new parent's last child 2033 // and new parent's nextSibling's first child are both inline nodes, 2034 // and new parent's last child is not a br, call createElement("br") on 2035 // the ownerDocument of new parent and append the result as the last 2036 // child of new parent." 2037 if (!isInlineNode(newParent) && isInlineNode(newParent.lastChild) && isInlineNode(newParent.nextSibling.firstChild) && !isNamedHtmlElement(newParent.lastChild, "BR")) { 2038 newParent.appendChild(newParent.ownerDocument.createElement("br")); 2039 } 2040 2041 // "While new parent's nextSibling has children, append its first child 2042 // as the last child of new parent, preserving ranges." 2043 while (newParent.nextSibling.hasChildNodes()) { 2044 movePreservingRanges(newParent.nextSibling.firstChild, newParent, -1, range); 2045 } 2046 2047 // "Remove new parent's nextSibling from its parent." 2048 newParent.parentNode.removeChild(newParent.nextSibling); 2049 } 2050 2051 // "Remove extraneous line breaks from new parent." 2052 removeExtraneousLineBreaksFrom(newParent); 2053 2054 // "Return new parent." 2055 return newParent; 2056 } 2057 2058 2059 //@} 2060 ///// Allowed children ///// 2061 //@{ 2062 2063 // "A name of an element with inline contents is "a", "abbr", "b", "bdi", 2064 // "bdo", "cite", "code", "dfn", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i", 2065 // "kbd", "mark", "p", "pre", "q", "rp", "rt", "ruby", "s", "samp", "small", 2066 // "span", "strong", "sub", "sup", "u", "var", "acronym", "listing", "strike", 2067 // "xmp", "big", "blink", "font", "marquee", "nobr", or "tt"." 2068 var namesOfElementsWithInlineContentsMap = { 2069 "A": true, 2070 "ABBR": true, 2071 "B": true, 2072 "BDI": true, 2073 "BDO": true, 2074 "CITE": true, 2075 "CODE": true, 2076 "DFN": true, 2077 "EM": true, 2078 "H1": true, 2079 "H2": true, 2080 "H3": true, 2081 "H4": true, 2082 "H5": true, 2083 "H6": true, 2084 "I": true, 2085 "KBD": true, 2086 "MARK": true, 2087 "P": true, 2088 "PRE": true, 2089 "Q": true, 2090 "RP": true, 2091 "RT": true, 2092 "RUBY": true, 2093 "S": true, 2094 "SAMP": true, 2095 "SMALL": true, 2096 "SPAN": true, 2097 "STRONG": true, 2098 "SUB": true, 2099 "SUP": true, 2100 "U": true, 2101 "VAR": true, 2102 "ACRONYM": true, 2103 "LISTING": true, 2104 "STRIKE": true, 2105 "XMP": true, 2106 "BIG": true, 2107 "BLINK": true, 2108 "FONT": true, 2109 "MARQUEE": true, 2110 "NOBR": true, 2111 "TT": true 2112 }; 2113 2114 2115 var tableRelatedElements = { 2116 "colgroup": true, 2117 "table": true, 2118 "tbody": true, 2119 "tfoot": true, 2120 "thead": true, 2121 "tr": true 2122 }; 2123 2124 var scriptRelatedElements = { 2125 "script": true, 2126 "style": true, 2127 "plaintext": true, 2128 "xmp": true 2129 }; 2130 2131 var prohibitedHeadingNestingMap = jQuery.extend({ 2132 "H1": true, 2133 "H2": true, 2134 "H3": true, 2135 "H4": true, 2136 "H5": true, 2137 "H6": true 2138 }, prohibitedParagraphChildNamesMap); 2139 var prohibitedTableNestingMap = { 2140 "CAPTION": true, 2141 "COL": true, 2142 "COLGROUP": true, 2143 "TBODY": true, 2144 "TD": true, 2145 "TFOOT": true, 2146 "TH": true, 2147 "THEAD": true, 2148 "TR": true 2149 }; 2150 var prohibitedDefNestingMap = { 2151 "DD": true, 2152 "DT": true 2153 }; 2154 var prohibitedNestingCombinationsMap = { 2155 "A": jQuery.extend({ 2156 "A": true 2157 }, prohibitedParagraphChildNamesMap), 2158 "DD": prohibitedDefNestingMap, 2159 "DT": prohibitedDefNestingMap, 2160 "LI": { 2161 "LI": true 2162 }, 2163 "NOBR": jQuery.extend({ 2164 "NOBR": true 2165 }, prohibitedParagraphChildNamesMap), 2166 "H1": prohibitedHeadingNestingMap, 2167 "H2": prohibitedHeadingNestingMap, 2168 "H3": prohibitedHeadingNestingMap, 2169 "H4": prohibitedHeadingNestingMap, 2170 "H5": prohibitedHeadingNestingMap, 2171 "H6": prohibitedHeadingNestingMap, 2172 "TD": prohibitedTableNestingMap, 2173 "TH": prohibitedTableNestingMap, 2174 // this is the same as namesOfElementsWithInlineContentsMap excluding a and h1-h6 elements above 2175 "ABBR": prohibitedParagraphChildNamesMap, 2176 "B": prohibitedParagraphChildNamesMap, 2177 "BDI": prohibitedParagraphChildNamesMap, 2178 "BDO": prohibitedParagraphChildNamesMap, 2179 "CITE": prohibitedParagraphChildNamesMap, 2180 "CODE": prohibitedParagraphChildNamesMap, 2181 "DFN": prohibitedParagraphChildNamesMap, 2182 "EM": prohibitedParagraphChildNamesMap, 2183 "I": prohibitedParagraphChildNamesMap, 2184 "KBD": prohibitedParagraphChildNamesMap, 2185 "MARK": prohibitedParagraphChildNamesMap, 2186 "P": prohibitedParagraphChildNamesMap, 2187 "PRE": prohibitedParagraphChildNamesMap, 2188 "Q": prohibitedParagraphChildNamesMap, 2189 "RP": prohibitedParagraphChildNamesMap, 2190 "RT": prohibitedParagraphChildNamesMap, 2191 "RUBY": prohibitedParagraphChildNamesMap, 2192 "S": prohibitedParagraphChildNamesMap, 2193 "SAMP": prohibitedParagraphChildNamesMap, 2194 "SMALL": prohibitedParagraphChildNamesMap, 2195 "SPAN": prohibitedParagraphChildNamesMap, 2196 "STRONG": prohibitedParagraphChildNamesMap, 2197 "SUB": prohibitedParagraphChildNamesMap, 2198 "SUP": prohibitedParagraphChildNamesMap, 2199 "U": prohibitedParagraphChildNamesMap, 2200 "VAR": prohibitedParagraphChildNamesMap, 2201 "ACRONYM": prohibitedParagraphChildNamesMap, 2202 "LISTING": prohibitedParagraphChildNamesMap, 2203 "STRIKE": prohibitedParagraphChildNamesMap, 2204 "XMP": prohibitedParagraphChildNamesMap, 2205 "BIG": prohibitedParagraphChildNamesMap, 2206 "BLINK": prohibitedParagraphChildNamesMap, 2207 "FONT": prohibitedParagraphChildNamesMap, 2208 "MARQUEE": prohibitedParagraphChildNamesMap, 2209 "TT": prohibitedParagraphChildNamesMap 2210 }; 2211 2212 // "An element with inline contents is an HTML element whose local name is a 2213 // name of an element with inline contents." 2214 function isElementWithInlineContents(node) { 2215 return isMappedHtmlElement(node, namesOfElementsWithInlineContentsMap); 2216 } 2217 2218 function isAllowedChild(child, parent_) { 2219 // "If parent is "colgroup", "table", "tbody", "tfoot", "thead", "tr", or 2220 // an HTML element with local name equal to one of those, and child is a 2221 // Text node whose data does not consist solely of space characters, return 2222 // false." 2223 if ((tableRelatedElements[parent_] || isHtmlElementInArray(parent_, ["colgroup", "table", "tbody", "tfoot", "thead", "tr"])) && typeof child == "object" && child.nodeType == $_.Node.TEXT_NODE && !/^[ \t\n\f\r]*$/.test(child.data)) { 2224 return false; 2225 } 2226 2227 // "If parent is "script", "style", "plaintext", or "xmp", or an HTML 2228 // element with local name equal to one of those, and child is not a Text 2229 // node, return false." 2230 if ((scriptRelatedElements[parent_] || isHtmlElementInArray(parent_, ["script", "style", "plaintext", "xmp"])) && (typeof child != "object" || child.nodeType != $_.Node.TEXT_NODE)) { 2231 return false; 2232 } 2233 2234 // "If child is a Document, DocumentFragment, or DocumentType, return 2235 // false." 2236 if (typeof child == "object" && (child.nodeType == $_.Node.DOCUMENT_NODE || child.nodeType == $_.Node.DOCUMENT_FRAGMENT_NODE || child.nodeType == $_.Node.DOCUMENT_TYPE_NODE)) { 2237 return false; 2238 } 2239 2240 // "If child is an HTML element, set child to the local name of child." 2241 if (isAnyHtmlElement(child)) { 2242 child = child.tagName.toLowerCase(); 2243 } 2244 2245 // "If child is not a string, return true." 2246 if (typeof child != "string") { 2247 return true; 2248 } 2249 2250 // "If parent is an HTML element:" 2251 if (isAnyHtmlElement(parent_)) { 2252 // "If child is "a", and parent or some ancestor of parent is an a, 2253 // return false." 2254 // 2255 // "If child is a prohibited paragraph child name and parent or some 2256 // ancestor of parent is an element with inline contents, return 2257 // false." 2258 // 2259 // "If child is "h1", "h2", "h3", "h4", "h5", or "h6", and parent or 2260 // some ancestor of parent is an HTML element with local name "h1", 2261 // "h2", "h3", "h4", "h5", or "h6", return false." 2262 var ancestor = parent_; 2263 while (ancestor) { 2264 if (child == "a" && isNamedHtmlElement(ancestor, 'a')) { 2265 return false; 2266 } 2267 if (prohibitedParagraphChildNamesMap[child.toUpperCase()] && isElementWithInlineContents(ancestor)) { 2268 return false; 2269 } 2270 if (/^h[1-6]$/.test(child) && isAnyHtmlElement(ancestor) && /^H[1-6]$/.test(ancestor.tagName)) { 2271 return false; 2272 } 2273 ancestor = ancestor.parentNode; 2274 } 2275 2276 // "Let parent be the local name of parent." 2277 parent_ = parent_.tagName.toLowerCase(); 2278 } 2279 2280 // "If parent is an Element or DocumentFragment, return true." 2281 if (typeof parent_ == "object" && (parent_.nodeType == $_.Node.ELEMENT_NODE || parent_.nodeType == $_.Node.DOCUMENT_FRAGMENT_NODE)) { 2282 return true; 2283 } 2284 2285 // "If parent is not a string, return false." 2286 if (typeof parent_ != "string") { 2287 return false; 2288 } 2289 2290 // "If parent is on the left-hand side of an entry on the following list, 2291 // then return true if child is listed on the right-hand side of that 2292 // entry, and false otherwise." 2293 switch (parent_) { 2294 case "colgroup": 2295 return child == "col"; 2296 case "table": 2297 return jQuery.inArray(child, ["caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"]) != -1; 2298 case "tbody": 2299 case "thead": 2300 case "tfoot": 2301 return jQuery.inArray(child, ["td", "th", "tr"]) != -1; 2302 case "tr": 2303 return jQuery.inArray(child, ["td", "th"]) != -1; 2304 case "dl": 2305 return jQuery.inArray(child, ["dt", "dd"]) != -1; 2306 case "dir": 2307 case "ol": 2308 case "ul": 2309 return jQuery.inArray(child, ["dir", "li", "ol", "ul"]) != -1; 2310 case "hgroup": 2311 return (/^h[1-6]$/).test(child); 2312 } 2313 2314 // "If child is "body", "caption", "col", "colgroup", "frame", "frameset", 2315 // "head", "html", "tbody", "td", "tfoot", "th", "thead", or "tr", return 2316 // false." 2317 if (jQuery.inArray(child, ["body", "caption", "col", "colgroup", "frame", "frameset", "head", "html", "tbody", "td", "tfoot", "th", "thead", "tr"]) != -1) { 2318 return false; 2319 } 2320 2321 // "If child is "dd" or "dt" and parent is not "dl", return false." 2322 if (jQuery.inArray(child, ["dd", "dt"]) != -1 && parent_ != "dl") { 2323 return false; 2324 } 2325 2326 // "If child is "li" and parent is not "ol" or "ul", return false." 2327 if (child == "li" && parent_ != "ol" && parent_ != "ul") { 2328 return false; 2329 } 2330 2331 // "If parent is on the left-hand side of an entry on the following list 2332 // and child is listed on the right-hand side of that entry, return false." 2333 var leftSide = prohibitedNestingCombinationsMap[parent_.toUpperCase()]; 2334 if (leftSide) { 2335 var rightSide = leftSide[child.toUpperCase()]; 2336 if (rightSide) { 2337 return false; 2338 } 2339 } 2340 2341 // "Return true." 2342 return true; 2343 } 2344 2345 2346 //@} 2347 2348 ////////////////////////////////////// 2349 ///// Inline formatting commands ///// 2350 ////////////////////////////////////// 2351 2352 ///// Inline formatting command definitions ///// 2353 //@{ 2354 2355 // "A node node is effectively contained in a range range if range is not 2356 // collapsed, and at least one of the following holds:" 2357 function isEffectivelyContained(node, range) { 2358 if (range.collapsed) { 2359 return false; 2360 } 2361 2362 // "node is contained in range." 2363 if (isContained(node, range)) { 2364 return true; 2365 } 2366 2367 // "node is range's start node, it is a Text node, and its length is 2368 // different from range's start offset." 2369 if (node == range.startContainer && node.nodeType == $_.Node.TEXT_NODE && getNodeLength(node) != range.startOffset) { 2370 return true; 2371 } 2372 2373 // "node is range's end node, it is a Text node, and range's end offset is 2374 // not 0." 2375 if (node == range.endContainer && node.nodeType == $_.Node.TEXT_NODE && range.endOffset != 0) { 2376 return true; 2377 } 2378 2379 // "node has at least one child; and all its children are effectively 2380 // contained in range; and either range's start node is not a descendant of 2381 // node or is not a Text node or range's start offset is zero; and either 2382 // range's end node is not a descendant of node or is not a Text node or 2383 // range's end offset is its end node's length." 2384 if (node.hasChildNodes() && $_(node.childNodes).every(function (child) { return isEffectivelyContained(child, range); }) 2385 && (!isDescendant(range.startContainer, node) 2386 || range.startContainer.nodeType != $_.Node.TEXT_NODE 2387 || range.startOffset == 0) 2388 && (!isDescendant(range.endContainer, node) 2389 || range.endContainer.nodeType != $_.Node.TEXT_NODE 2390 || range.endOffset == getNodeLength(range.endContainer))) { 2391 return true; 2392 } 2393 2394 return false; 2395 } 2396 2397 // Like get(All)ContainedNodes(), but for effectively contained nodes. 2398 function getEffectivelyContainedNodes(range, condition) { 2399 if (typeof condition == "undefined") { 2400 condition = function () { 2401 return true; 2402 }; 2403 } 2404 var node = range.startContainer; 2405 while (isEffectivelyContained(node.parentNode, range)) { 2406 node = node.parentNode; 2407 } 2408 2409 var stop = nextNodeDescendants(range.endContainer); 2410 2411 var nodeList = []; 2412 while (isBefore(node, stop)) { 2413 if (isEffectivelyContained(node, range) && condition(node)) { 2414 nodeList.push(node); 2415 node = nextNodeDescendants(node); 2416 continue; 2417 } 2418 node = nextNode(node); 2419 } 2420 return nodeList; 2421 } 2422 2423 function getAllEffectivelyContainedNodes(range, condition) { 2424 if (typeof condition == "undefined") { 2425 condition = function () { 2426 return true; 2427 }; 2428 } 2429 var node = range.startContainer; 2430 while (isEffectivelyContained(node.parentNode, range)) { 2431 node = node.parentNode; 2432 } 2433 2434 var stop = nextNodeDescendants(range.endContainer); 2435 2436 var nodeList = []; 2437 while (isBefore(node, stop)) { 2438 if (isEffectivelyContained(node, range) && condition(node)) { 2439 nodeList.push(node); 2440 } 2441 node = nextNode(node); 2442 } 2443 return nodeList; 2444 } 2445 2446 // "A modifiable element is a b, em, i, s, span, strong, sub, sup, or u element 2447 // with no attributes except possibly style; or a font element with no 2448 // attributes except possibly style, color, face, and/or size; or an a element 2449 // with no attributes except possibly style and/or href." 2450 function isModifiableElement(node) { 2451 if (!isAnyHtmlElement(node)) { 2452 return false; 2453 } 2454 2455 if (jQuery.inArray(node.tagName, ["B", "EM", "I", "S", "SPAN", "STRIKE", "STRONG", "SUB", "SUP", "U"]) != -1) { 2456 if (node.attributes.length == 0) { 2457 return true; 2458 } 2459 2460 if (node.attributes.length == 1 && hasAttribute(node, "style")) { 2461 return true; 2462 } 2463 } 2464 2465 if (node.tagName == "FONT" || node.tagName == "A") { 2466 var numAttrs = node.attributes.length; 2467 2468 if (hasAttribute(node, "style")) { 2469 numAttrs--; 2470 } 2471 2472 if (node.tagName == "FONT") { 2473 if (hasAttribute(node, "color")) { 2474 numAttrs--; 2475 } 2476 2477 if (hasAttribute(node, "face")) { 2478 numAttrs--; 2479 } 2480 2481 if (hasAttribute(node, "size")) { 2482 numAttrs--; 2483 } 2484 } 2485 2486 if (node.tagName == "A" && hasAttribute(node, "href")) { 2487 numAttrs--; 2488 } 2489 2490 if (numAttrs == 0) { 2491 return true; 2492 } 2493 } 2494 2495 return false; 2496 } 2497 2498 function isSimpleModifiableElement(node) { 2499 // "A simple modifiable element is an HTML element for which at least one 2500 // of the following holds:" 2501 if (!isAnyHtmlElement(node)) { 2502 return false; 2503 } 2504 2505 // Only these elements can possibly be a simple modifiable element. 2506 if (jQuery.inArray(node.tagName, ["A", "B", "EM", "FONT", "I", "S", "SPAN", "STRIKE", "STRONG", "SUB", "SUP", "U"]) == -1) { 2507 return false; 2508 } 2509 2510 // "It is an a, b, em, font, i, s, span, strike, strong, sub, sup, or u 2511 // element with no attributes." 2512 if (node.attributes.length == 0) { 2513 return true; 2514 } 2515 2516 // If it's got more than one attribute, everything after this fails. 2517 if (node.attributes.length > 1) { 2518 return false; 2519 } 2520 2521 // "It is an a, b, em, font, i, s, span, strike, strong, sub, sup, or u 2522 // element with exactly one attribute, which is style, which sets no CSS 2523 // properties (including invalid or unrecognized properties)." 2524 // 2525 // Not gonna try for invalid or unrecognized. 2526 if (hasAttribute(node, "style") && getStyleLength(node) == 0) { 2527 return true; 2528 } 2529 2530 // "It is an a element with exactly one attribute, which is href." 2531 if (node.tagName == "A" && hasAttribute(node, "href")) { 2532 return true; 2533 } 2534 2535 // "It is a font element with exactly one attribute, which is either color, 2536 // face, or size." 2537 if (node.tagName == "FONT" && (hasAttribute(node, "color") || hasAttribute(node, "face") || hasAttribute(node, "size"))) { 2538 return true; 2539 } 2540 2541 // "It is a b or strong element with exactly one attribute, which is style, 2542 // and the style attribute sets exactly one CSS property (including invalid 2543 // or unrecognized properties), which is "font-weight"." 2544 if ((node.tagName == "B" || node.tagName == "STRONG") && hasAttribute(node, "style") && getStyleLength(node) == 1 && node.style.fontWeight != "") { 2545 return true; 2546 } 2547 2548 // "It is an i or em element with exactly one attribute, which is style, 2549 // and the style attribute sets exactly one CSS property (including invalid 2550 // or unrecognized properties), which is "font-style"." 2551 if ((node.tagName == "I" || node.tagName == "EM") && hasAttribute(node, "style") && getStyleLength(node) == 1 && node.style.fontStyle != "") { 2552 return true; 2553 } 2554 2555 // "It is an a, font, or span element with exactly one attribute, which is 2556 // style, and the style attribute sets exactly one CSS property (including 2557 // invalid or unrecognized properties), and that property is not 2558 // "text-decoration"." 2559 if ((node.tagName == "A" || node.tagName == "FONT" || node.tagName == "SPAN") && hasAttribute(node, "style") && getStyleLength(node) == 1 && node.style.textDecoration == "") { 2560 return true; 2561 } 2562 2563 // "It is an a, font, s, span, strike, or u element with exactly one 2564 // attribute, which is style, and the style attribute sets exactly one CSS 2565 // property (including invalid or unrecognized properties), which is 2566 // "text-decoration", which is set to "line-through" or "underline" or 2567 // "overline" or "none"." 2568 if (jQuery.inArray(node.tagName, ["A", "FONT", "S", "SPAN", "STRIKE", "U"]) != -1 && hasAttribute(node, "style") && getStyleLength(node) == 1 && (node.style.textDecoration == "line-through" || node.style.textDecoration == "underline" || node.style.textDecoration == "overline" || node.style.textDecoration == "none")) { 2569 return true; 2570 } 2571 2572 return false; 2573 } 2574 2575 // "Two quantities are equivalent values for a command if either both are null, 2576 // or both are strings and they're equal and the command does not define any 2577 // equivalent values, or both are strings and the command defines equivalent 2578 // values and they match the definition." 2579 function areEquivalentValues(command, val1, val2) { 2580 if (val1 === null && val2 === null) { 2581 return true; 2582 } 2583 2584 if (typeof val1 == "string" && typeof val2 == "string" && val1 == val2 && !(commands[command].hasOwnProperty("equivalentValues"))) { 2585 return true; 2586 } 2587 2588 if (typeof val1 == "string" && typeof val2 == "string" && commands[command].hasOwnProperty("equivalentValues") && commands[command].equivalentValues(val1, val2)) { 2589 return true; 2590 } 2591 2592 return false; 2593 } 2594 2595 // "Two quantities are loosely equivalent values for a command if either they 2596 // are equivalent values for the command, or if the command is the fontSize 2597 // command; one of the quantities is one of "xx-small", "small", "medium", 2598 // "large", "x-large", "xx-large", or "xxx-large"; and the other quantity is 2599 // the resolved value of "font-size" on a font element whose size attribute has 2600 // the corresponding value set ("1" through "7" respectively)." 2601 function areLooselyEquivalentValues(command, val1, val2) { 2602 if (areEquivalentValues(command, val1, val2)) { 2603 return true; 2604 } 2605 2606 if (command != "fontsize" || typeof val1 != "string" || typeof val2 != "string") { 2607 return false; 2608 } 2609 2610 // Static variables in JavaScript? 2611 var callee = areLooselyEquivalentValues; 2612 if (callee.sizeMap === undefined) { 2613 callee.sizeMap = {}; 2614 var font = document.createElement("font"); 2615 document.body.appendChild(font); 2616 $_(["xx-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"]).forEach(function (keyword) { 2617 font.size = cssSizeToLegacy(keyword); 2618 callee.sizeMap[keyword] = $_.getComputedStyle(font).fontSize; 2619 }); 2620 document.body.removeChild(font); 2621 } 2622 2623 return val1 === callee.sizeMap[val2] || val2 === callee.sizeMap[val1]; 2624 } 2625 2626 //@} 2627 ///// Assorted inline formatting command algorithms ///// 2628 //@{ 2629 2630 function getEffectiveCommandValue(node, command) { 2631 // "If neither node nor its parent is an Element, return null." 2632 if (node.nodeType != $_.Node.ELEMENT_NODE && (!node.parentNode || node.parentNode.nodeType != $_.Node.ELEMENT_NODE)) { 2633 return null; 2634 } 2635 2636 // "If node is not an Element, return the effective command value of its 2637 // parent for command." 2638 if (node.nodeType != $_.Node.ELEMENT_NODE) { 2639 return getEffectiveCommandValue(node.parentNode, command); 2640 } 2641 2642 // "If command is "createLink" or "unlink":" 2643 if (command == "createlink" || command == "unlink") { 2644 // "While node is not null, and is not an a element that has an href 2645 // attribute, set node to its parent." 2646 while (node && (!isAnyHtmlElement(node) || node.tagName != "A" || !hasAttribute(node, "href"))) { 2647 node = node.parentNode; 2648 } 2649 2650 // "If node is null, return null." 2651 if (!node) { 2652 return null; 2653 } 2654 2655 // "Return the value of node's href attribute." 2656 return node.getAttribute("href"); 2657 } 2658 2659 // "If command is "backColor" or "hiliteColor":" 2660 if (command == "backcolor" || command == "hilitecolor") { 2661 // "While the resolved value of "background-color" on node is any 2662 // fully transparent value, and node's parent is an Element, set 2663 // node to its parent." 2664 // 2665 // Another lame hack to avoid flawed APIs. 2666 while (($_.getComputedStyle(node).backgroundColor == "rgba(0, 0, 0, 0)" || $_.getComputedStyle(node).backgroundColor === "" || $_.getComputedStyle(node).backgroundColor == "transparent") && node.parentNode && node.parentNode.nodeType == $_.Node.ELEMENT_NODE) { 2667 node = node.parentNode; 2668 } 2669 2670 // "If the resolved value of "background-color" on node is a fully 2671 // transparent value, return "rgb(255, 255, 255)"." 2672 if ($_.getComputedStyle(node).backgroundColor == "rgba(0, 0, 0, 0)" || $_.getComputedStyle(node).backgroundColor === "" || $_.getComputedStyle(node).backgroundColor == "transparent") { 2673 return "rgb(255, 255, 255)"; 2674 } 2675 2676 // "Otherwise, return the resolved value of "background-color" for 2677 // node." 2678 return $_.getComputedStyle(node).backgroundColor; 2679 } 2680 2681 // "If command is "subscript" or "superscript":" 2682 if (command == "subscript" || command == "superscript") { 2683 // "Let affected by subscript and affected by superscript be two 2684 // boolean variables, both initially false." 2685 var affectedBySubscript = false; 2686 var affectedBySuperscript = false; 2687 2688 // "While node is an inline node:" 2689 while (isInlineNode(node)) { 2690 var verticalAlign = $_.getComputedStyle(node).verticalAlign; 2691 2692 // "If node is a sub, set affected by subscript to true." 2693 if (isNamedHtmlElement(node, 'sub')) { 2694 affectedBySubscript = true; 2695 // "Otherwise, if node is a sup, set affected by superscript to 2696 // true." 2697 } else if (isNamedHtmlElement(node, 'sup')) { 2698 affectedBySuperscript = true; 2699 } 2700 2701 // "Set node to its parent." 2702 node = node.parentNode; 2703 } 2704 2705 // "If affected by subscript and affected by superscript are both true, 2706 // return the string "mixed"." 2707 if (affectedBySubscript && affectedBySuperscript) { 2708 return "mixed"; 2709 } 2710 2711 // "If affected by subscript is true, return "subscript"." 2712 if (affectedBySubscript) { 2713 return "subscript"; 2714 } 2715 2716 // "If affected by superscript is true, return "superscript"." 2717 if (affectedBySuperscript) { 2718 return "superscript"; 2719 } 2720 2721 // "Return null." 2722 return null; 2723 } 2724 2725 // "If command is "strikethrough", and the "text-decoration" property of 2726 // node or any of its ancestors has resolved value containing 2727 // "line-through", return "line-through". Otherwise, return null." 2728 if (command == "strikethrough") { 2729 do { 2730 if ($_.getComputedStyle(node).textDecoration.indexOf("line-through") != -1) { 2731 return "line-through"; 2732 } 2733 node = node.parentNode; 2734 } while (node && node.nodeType == $_.Node.ELEMENT_NODE); 2735 return null; 2736 } 2737 2738 // "If command is "underline", and the "text-decoration" property of node 2739 // or any of its ancestors has resolved value containing "underline", 2740 // return "underline". Otherwise, return null." 2741 if (command == "underline") { 2742 do { 2743 if ($_.getComputedStyle(node).textDecoration.indexOf("underline") != -1) { 2744 return "underline"; 2745 } 2746 node = node.parentNode; 2747 } while (node && node.nodeType == $_.Node.ELEMENT_NODE); 2748 return null; 2749 } 2750 2751 if (!commands[command].hasOwnProperty("relevantCssProperty")) { 2752 throw "Bug: no relevantCssProperty for " + command + " in getEffectiveCommandValue"; 2753 } 2754 2755 // "Return the resolved value for node of the relevant CSS property for 2756 // command." 2757 return $_.getComputedStyle(node)[commands[command].relevantCssProperty].toString(); 2758 } 2759 2760 function getSpecifiedCommandValue(element, command) { 2761 // "If command is "backColor" or "hiliteColor" and element's display 2762 // property does not have resolved value "inline", return null." 2763 if ((command == "backcolor" || command == "hilitecolor") && $_.getComputedStyle(element).display != "inline") { 2764 return null; 2765 } 2766 2767 // "If command is "createLink" or "unlink":" 2768 if (command == "createlink" || command == "unlink") { 2769 // "If element is an a element and has an href attribute, return the 2770 // value of that attribute." 2771 if (isAnyHtmlElement(element) && element.tagName == "A" && hasAttribute(element, "href")) { 2772 return element.getAttribute("href"); 2773 } 2774 2775 // "Return null." 2776 return null; 2777 } 2778 2779 // "If command is "subscript" or "superscript":" 2780 if (command == "subscript" || command == "superscript") { 2781 // "If element is a sup, return "superscript"." 2782 if (isNamedHtmlElement(element, 'sup')) { 2783 return "superscript"; 2784 } 2785 2786 // "If element is a sub, return "subscript"." 2787 if (isNamedHtmlElement(element, 'sub')) { 2788 return "subscript"; 2789 } 2790 2791 // "Return null." 2792 return null; 2793 } 2794 2795 // "If command is "strikethrough", and element has a style attribute set, 2796 // and that attribute sets "text-decoration":" 2797 if (command == "strikethrough" && element.style.textDecoration != "") { 2798 // "If element's style attribute sets "text-decoration" to a value 2799 // containing "line-through", return "line-through"." 2800 if (element.style.textDecoration.indexOf("line-through") != -1) { 2801 return "line-through"; 2802 } 2803 2804 // "Return null." 2805 return null; 2806 2807 } 2808 2809 // "If command is "strikethrough" and element is a s or strike element, 2810 // return "line-through"." 2811 if (command == "strikethrough" && isHtmlElementInArray(element, ["S", "STRIKE"])) { 2812 return "line-through"; 2813 } 2814 2815 // "If command is "underline", and element has a style attribute set, and 2816 // that attribute sets "text-decoration":" 2817 if (command == "underline" && element.style.textDecoration != "") { 2818 // "If element's style attribute sets "text-decoration" to a value 2819 // containing "underline", return "underline"." 2820 if (element.style.textDecoration.indexOf("underline") != -1) { 2821 return "underline"; 2822 } 2823 2824 // "Return null." 2825 return null; 2826 } 2827 2828 // "If command is "underline" and element is a u element, return 2829 // "underline"." 2830 if (command == "underline" && isNamedHtmlElement(element, 'U')) { 2831 return "underline"; 2832 } 2833 2834 // "Let property be the relevant CSS property for command." 2835 var property = commands[command].relevantCssProperty; 2836 2837 // "If property is null, return null." 2838 if (property === null) { 2839 return null; 2840 } 2841 2842 // "If element has a style attribute set, and that attribute has the 2843 // effect of setting property, return the value that it sets property to." 2844 if (element.style[property] != "") { 2845 return element.style[property]; 2846 } 2847 2848 // "If element is a font element that has an attribute whose effect is 2849 // to create a presentational hint for property, return the value that the 2850 // hint sets property to. (For a size of 7, this will be the non-CSS value 2851 // "xxx-large".)" 2852 if (isHtmlNamespace(element.namespaceURI) && element.tagName == "FONT") { 2853 if (property == "color" && hasAttribute(element, "color")) { 2854 return element.color; 2855 } 2856 if (property == "fontFamily" && hasAttribute(element, "face")) { 2857 return element.face; 2858 } 2859 if (property == "fontSize" && hasAttribute(element, "size")) { 2860 // This is not even close to correct in general. 2861 var size = parseInt(element.size, 10); 2862 if (size < 1) { 2863 size = 1; 2864 } 2865 if (size > 7) { 2866 size = 7; 2867 } 2868 return { 2869 1: "xx-small", 2870 2: "small", 2871 3: "medium", 2872 4: "large", 2873 5: "x-large", 2874 6: "xx-large", 2875 7: "xxx-large" 2876 }[size]; 2877 } 2878 } 2879 2880 // "If element is in the following list, and property is equal to the 2881 // CSS property name listed for it, return the string listed for it." 2882 // 2883 // A list follows, whose meaning is copied here. 2884 if (property == "fontWeight" && (element.tagName == "B" || element.tagName == "STRONG")) { 2885 return "bold"; 2886 } 2887 if (property == "fontStyle" && (element.tagName == "I" || element.tagName == "EM")) { 2888 return "italic"; 2889 } 2890 2891 // "Return null." 2892 return null; 2893 } 2894 2895 function reorderModifiableDescendants(node, command, newValue, range) { 2896 // "Let candidate equal node." 2897 var candidate = node; 2898 2899 // "While candidate is a modifiable element, and candidate has exactly one 2900 // child, and that child is also a modifiable element, and candidate is not 2901 // a simple modifiable element or candidate's specified command value for 2902 // command is not equivalent to new value, set candidate to its child." 2903 while (isModifiableElement(candidate) && candidate.childNodes.length == 1 && isModifiableElement(candidate.firstChild) && (!isSimpleModifiableElement(candidate) || !areEquivalentValues(command, getSpecifiedCommandValue(candidate, command), newValue))) { 2904 candidate = candidate.firstChild; 2905 } 2906 2907 // "If candidate is node, or is not a simple modifiable element, or its 2908 // specified command value is not equivalent to new value, or its effective 2909 // command value is not loosely equivalent to new value, abort these 2910 // steps." 2911 if (candidate == node || !isSimpleModifiableElement(candidate) || !areEquivalentValues(command, getSpecifiedCommandValue(candidate, command), newValue) || !areLooselyEquivalentValues(command, getEffectiveCommandValue(candidate, command), newValue)) { 2912 return; 2913 } 2914 2915 // "While candidate has children, insert the first child of candidate into 2916 // candidate's parent immediately before candidate, preserving ranges." 2917 while (candidate.hasChildNodes()) { 2918 movePreservingRanges(candidate.firstChild, candidate.parentNode, Dom.getIndexInParent(candidate), range); 2919 } 2920 2921 // "Insert candidate into node's parent immediately after node." 2922 node.parentNode.insertBefore(candidate, node.nextSibling); 2923 2924 // "Append the node as the last child of candidate, preserving ranges." 2925 movePreservingRanges(node, candidate, -1, range); 2926 } 2927 2928 var recordValuesCommands = ["subscript", "bold", "fontname", "fontsize", "forecolor", "hilitecolor", "italic", "strikethrough", "underline"]; 2929 2930 function recordValues(nodeList) { 2931 // "Let values be a list of (node, command, specified command value) 2932 // triples, initially empty." 2933 var values = []; 2934 2935 // "For each node in node list, for each command in the list "subscript", 2936 // "bold", "fontName", "fontSize", "foreColor", "hiliteColor", "italic", 2937 // "strikethrough", and "underline" in that order:" 2938 2939 // Ensure we have a plain array to avoid the potential performance 2940 // overhead of a NodeList 2941 var nodes = jQuery.makeArray(nodeList); 2942 var i, j; 2943 var node; 2944 var command; 2945 var ancestor; 2946 var specifiedCommandValue; 2947 for (i = 0; i < nodes.length; i++) { 2948 node = nodes[i]; 2949 for (j = 0; j < recordValuesCommands.length; j++) { 2950 command = recordValuesCommands[j]; 2951 2952 // "Let ancestor equal node." 2953 2954 ancestor = node; 2955 2956 // "If ancestor is not an Element, set it to its parent." 2957 if (ancestor.nodeType != 1) { 2958 ancestor = ancestor.parentNode; 2959 } 2960 2961 // "While ancestor is an Element and its specified command value 2962 // for command is null, set it to its parent." 2963 specifiedCommandValue = null; 2964 while (ancestor && ancestor.nodeType == 1 && (specifiedCommandValue = getSpecifiedCommandValue(ancestor, command)) === null) { 2965 ancestor = ancestor.parentNode; 2966 } 2967 2968 // "If ancestor is an Element, add (node, command, ancestor's 2969 // specified command value for command) to values. Otherwise add 2970 // (node, command, null) to values." 2971 values.push([node, command, specifiedCommandValue]); 2972 } 2973 } 2974 2975 // "Return values." 2976 return values; 2977 } 2978 2979 //@} 2980 ///// Clearing an element's value ///// 2981 //@{ 2982 2983 function clearValue(element, command, range) { 2984 // "If element is not editable, return the empty list." 2985 if (!isEditable(element)) { 2986 return []; 2987 } 2988 2989 // "If element's specified command value for command is null, return the 2990 // empty list." 2991 if (getSpecifiedCommandValue(element, command) === null) { 2992 return []; 2993 } 2994 2995 // "If element is a simple modifiable element:" 2996 if (isSimpleModifiableElement(element)) { 2997 // "Let children be the children of element." 2998 var children = Array.prototype.slice.call(toArray(element.childNodes)); 2999 3000 // "For each child in children, insert child into element's parent 3001 // immediately before element, preserving ranges." 3002 var i; 3003 for (i = 0; i < children.length; i++) { 3004 movePreservingRanges(children[i], element.parentNode, Dom.getIndexInParent(element), range); 3005 } 3006 3007 // "Remove element from its parent." 3008 element.parentNode.removeChild(element); 3009 3010 // "Return children." 3011 return children; 3012 } 3013 3014 // "If command is "strikethrough", and element has a style attribute that 3015 // sets "text-decoration" to some value containing "line-through", delete 3016 // "line-through" from the value." 3017 if (command == "strikethrough" && element.style.textDecoration.indexOf("line-through") != -1) { 3018 if (element.style.textDecoration == "line-through") { 3019 element.style.textDecoration = ""; 3020 } else { 3021 element.style.textDecoration = element.style.textDecoration.replace("line-through", ""); 3022 } 3023 if (element.getAttribute("style") == "") { 3024 element.removeAttribute("style"); 3025 } 3026 } 3027 3028 // "If command is "underline", and element has a style attribute that sets 3029 // "text-decoration" to some value containing "underline", delete 3030 // "underline" from the value." 3031 if (command == "underline" && element.style.textDecoration.indexOf("underline") != -1) { 3032 if (element.style.textDecoration == "underline") { 3033 element.style.textDecoration = ""; 3034 } else { 3035 element.style.textDecoration = element.style.textDecoration.replace("underline", ""); 3036 } 3037 if (element.getAttribute("style") == "") { 3038 element.removeAttribute("style"); 3039 } 3040 } 3041 3042 // "If the relevant CSS property for command is not null, unset the CSS 3043 // property property of element." 3044 if (commands[command].relevantCssProperty !== null) { 3045 element.style[commands[command].relevantCssProperty] = ''; 3046 if (element.getAttribute("style") == "") { 3047 element.removeAttribute("style"); 3048 } 3049 } 3050 3051 // "If element is a font element:" 3052 if (isHtmlNamespace(element.namespaceURI) && element.tagName == "FONT") { 3053 // "If command is "foreColor", unset element's color attribute, if set." 3054 if (command == "forecolor") { 3055 element.removeAttribute("color"); 3056 } 3057 3058 // "If command is "fontName", unset element's face attribute, if set." 3059 if (command == "fontname") { 3060 element.removeAttribute("face"); 3061 } 3062 3063 // "If command is "fontSize", unset element's size attribute, if set." 3064 if (command == "fontsize") { 3065 element.removeAttribute("size"); 3066 } 3067 } 3068 3069 // "If element is an a element and command is "createLink" or "unlink", 3070 // unset the href property of element." 3071 if (isNamedHtmlElement(element, 'A') && (command == "createlink" || command == "unlink")) { 3072 element.removeAttribute("href"); 3073 } 3074 3075 // "If element's specified command value for command is null, return the 3076 // empty list." 3077 if (getSpecifiedCommandValue(element, command) === null) { 3078 return []; 3079 } 3080 3081 // "Set the tag name of element to "span", and return the one-node list 3082 // consisting of the result." 3083 return [setTagName(element, "span", range)]; 3084 } 3085 3086 //@} 3087 3088 ///// Forcing the value of a node ///// 3089 //@{ 3090 3091 function forceValue(node, command, newValue, range) { 3092 var children = []; 3093 var i; 3094 var specifiedValue; 3095 3096 // "If node's parent is null, abort this algorithm." 3097 if (!node.parentNode) { 3098 return; 3099 } 3100 3101 // "If new value is null, abort this algorithm." 3102 if (newValue === null) { 3103 return; 3104 } 3105 3106 // "If node is an allowed child of "span":" 3107 if (isAllowedChild(node, "span")) { 3108 // "Reorder modifiable descendants of node's previousSibling." 3109 reorderModifiableDescendants(node.previousSibling, command, newValue, range); 3110 3111 // "Reorder modifiable descendants of node's nextSibling." 3112 reorderModifiableDescendants(node.nextSibling, command, newValue, range); 3113 3114 // "Wrap the one-node list consisting of node, with sibling criteria 3115 // returning true for a simple modifiable element whose specified 3116 // command value is equivalent to new value and whose effective command 3117 // value is loosely equivalent to new value and false otherwise, and 3118 // with new parent instructions returning null." 3119 wrap( 3120 [node], 3121 function (node) { 3122 return isSimpleModifiableElement(node) && areEquivalentValues(command, getSpecifiedCommandValue(node, command), newValue) && areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue); 3123 }, 3124 function () { 3125 return null; 3126 }, 3127 range 3128 ); 3129 } 3130 3131 // "If the effective command value of command is loosely equivalent to new 3132 // value on node, abort this algorithm." 3133 if (areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) { 3134 return; 3135 } 3136 3137 // "If node is not an allowed child of "span":" 3138 if (!isAllowedChild(node, "span")) { 3139 // "Let children be all children of node, omitting any that are 3140 // Elements whose specified command value for command is neither null 3141 // nor equivalent to new value." 3142 for (i = 0; i < node.childNodes.length; i++) { 3143 if (node.childNodes[i].nodeType == $_.Node.ELEMENT_NODE) { 3144 specifiedValue = getSpecifiedCommandValue(node.childNodes[i], command); 3145 3146 if (specifiedValue !== null && !areEquivalentValues(command, newValue, specifiedValue)) { 3147 continue; 3148 } 3149 } 3150 children.push(node.childNodes[i]); 3151 } 3152 3153 // "Force the value of each Node in children, with command and new 3154 // value as in this invocation of the algorithm." 3155 for (i = 0; i < children.length; i++) { 3156 forceValue(children[i], command, newValue, range); 3157 } 3158 3159 // "Abort this algorithm." 3160 return; 3161 } 3162 3163 // "If the effective command value of command is loosely equivalent to new 3164 // value on node, abort this algorithm." 3165 if (areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) { 3166 return; 3167 } 3168 3169 // "Let new parent be null." 3170 var newParent = null; 3171 3172 // "If the CSS styling flag is false:" 3173 if (!cssStylingFlag) { 3174 // "If command is "bold" and new value is "bold", let new parent be the 3175 // result of calling createElement("b") on the ownerDocument of node." 3176 if (command == "bold" && (newValue == "bold" || newValue == "700")) { 3177 newParent = node.ownerDocument.createElement("b"); 3178 } 3179 3180 // "If command is "italic" and new value is "italic", let new parent be 3181 // the result of calling createElement("i") on the ownerDocument of 3182 // node." 3183 if (command == "italic" && newValue == "italic") { 3184 newParent = node.ownerDocument.createElement("i"); 3185 } 3186 3187 // "If command is "strikethrough" and new value is "line-through", let 3188 // new parent be the result of calling createElement("s") on the 3189 // ownerDocument of node." 3190 if (command == "strikethrough" && newValue == "line-through") { 3191 newParent = node.ownerDocument.createElement("s"); 3192 } 3193 3194 // "If command is "underline" and new value is "underline", let new 3195 // parent be the result of calling createElement("u") on the 3196 // ownerDocument of node." 3197 if (command == "underline" && newValue == "underline") { 3198 newParent = node.ownerDocument.createElement("u"); 3199 } 3200 3201 // "If command is "foreColor", and new value is fully opaque with red, 3202 // green, and blue components in the range 0 to 255:" 3203 if (command == "forecolor" && parseSimpleColor(newValue)) { 3204 // "Let new parent be the result of calling createElement("span") 3205 // on the ownerDocument of node." 3206 // NOTE: modified this process to create span elements with style attributes 3207 // instead of oldschool font tags with color attributes 3208 newParent = node.ownerDocument.createElement("span"); 3209 3210 // "If new value is an extended color keyword, set the color 3211 // attribute of new parent to new value." 3212 // 3213 // "Otherwise, set the color attribute of new parent to the result 3214 // of applying the rules for serializing simple color values to new 3215 // value (interpreted as a simple color)." 3216 jQuery(newParent).css('color', parseSimpleColor(newValue)); 3217 } 3218 3219 // "If command is "fontName", let new parent be the result of calling 3220 // createElement("font") on the ownerDocument of node, then set the 3221 // face attribute of new parent to new value." 3222 if (command == "fontname") { 3223 newParent = node.ownerDocument.createElement("font"); 3224 newParent.face = newValue; 3225 } 3226 } 3227 3228 // "If command is "createLink" or "unlink":" 3229 if (command == "createlink" || command == "unlink") { 3230 // "Let new parent be the result of calling createElement("a") on the 3231 // ownerDocument of node." 3232 newParent = node.ownerDocument.createElement("a"); 3233 3234 // "Set the href attribute of new parent to new value." 3235 newParent.setAttribute("href", newValue); 3236 3237 // "Let ancestor be node's parent." 3238 var ancestor = node.parentNode; 3239 3240 // "While ancestor is not null:" 3241 while (ancestor) { 3242 // "If ancestor is an a, set the tag name of ancestor to "span", 3243 // and let ancestor be the result." 3244 if (isNamedHtmlElement(ancestor, 'A')) { 3245 ancestor = setTagName(ancestor, "span", range); 3246 } 3247 3248 // "Set ancestor to its parent." 3249 ancestor = ancestor.parentNode; 3250 } 3251 } 3252 3253 // "If command is "fontSize"; and new value is one of "xx-small", "small", 3254 // "medium", "large", "x-large", "xx-large", or "xxx-large"; and either the 3255 // CSS styling flag is false, or new value is "xxx-large": let new parent 3256 // be the result of calling createElement("font") on the ownerDocument of 3257 // node, then set the size attribute of new parent to the number from the 3258 // following table based on new value: [table omitted]" 3259 if (command == "fontsize" && jQuery.inArray(newValue, ["xx-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"]) != -1 && (!cssStylingFlag || newValue == "xxx-large")) { 3260 newParent = node.ownerDocument.createElement("font"); 3261 newParent.size = cssSizeToLegacy(newValue); 3262 } 3263 3264 // "If command is "subscript" or "superscript" and new value is 3265 // "subscript", let new parent be the result of calling 3266 // createElement("sub") on the ownerDocument of node." 3267 if ((command == "subscript" || command == "superscript") && newValue == "subscript") { 3268 newParent = node.ownerDocument.createElement("sub"); 3269 } 3270 3271 // "If command is "subscript" or "superscript" and new value is 3272 // "superscript", let new parent be the result of calling 3273 // createElement("sup") on the ownerDocument of node." 3274 if ((command == "subscript" || command == "superscript") && newValue == "superscript") { 3275 newParent = node.ownerDocument.createElement("sup"); 3276 } 3277 3278 // "If new parent is null, let new parent be the result of calling 3279 // createElement("span") on the ownerDocument of node." 3280 if (!newParent) { 3281 newParent = node.ownerDocument.createElement("span"); 3282 } 3283 3284 // "Insert new parent in node's parent before node." 3285 node.parentNode.insertBefore(newParent, node); 3286 3287 // "If the effective command value of command for new parent is not loosely 3288 // equivalent to new value, and the relevant CSS property for command is 3289 // not null, set that CSS property of new parent to new value (if the new 3290 // value would be valid)." 3291 var property = commands[command].relevantCssProperty; 3292 if (property !== null && !areLooselyEquivalentValues(command, getEffectiveCommandValue(newParent, command), newValue)) { 3293 newParent.style[property] = newValue; 3294 } 3295 3296 // "If command is "strikethrough", and new value is "line-through", and the 3297 // effective command value of "strikethrough" for new parent is not 3298 // "line-through", set the "text-decoration" property of new parent to 3299 // "line-through"." 3300 if (command == "strikethrough" && newValue == "line-through" && getEffectiveCommandValue(newParent, "strikethrough") != "line-through") { 3301 newParent.style.textDecoration = "line-through"; 3302 } 3303 3304 // "If command is "underline", and new value is "underline", and the 3305 // effective command value of "underline" for new parent is not 3306 // "underline", set the "text-decoration" property of new parent to 3307 // "underline"." 3308 if (command == "underline" && newValue == "underline" && getEffectiveCommandValue(newParent, "underline") != "underline") { 3309 newParent.style.textDecoration = "underline"; 3310 } 3311 3312 // "Append node to new parent as its last child, preserving ranges." 3313 movePreservingRanges(node, newParent, newParent.childNodes.length, range); 3314 3315 // "If node is an Element and the effective command value of command for 3316 // node is not loosely equivalent to new value:" 3317 if (node.nodeType == $_.Node.ELEMENT_NODE && !areEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) { 3318 // "Insert node into the parent of new parent before new parent, 3319 // preserving ranges." 3320 movePreservingRanges(node, newParent.parentNode, Dom.getIndexInParent(newParent), range); 3321 3322 // "Remove new parent from its parent." 3323 newParent.parentNode.removeChild(newParent); 3324 3325 // "Let children be all children of node, omitting any that are 3326 // Elements whose specified command value for command is neither null 3327 // nor equivalent to new value." 3328 children = []; 3329 for (i = 0; i < node.childNodes.length; i++) { 3330 if (node.childNodes[i].nodeType == $_.Node.ELEMENT_NODE) { 3331 specifiedValue = getSpecifiedCommandValue(node.childNodes[i], command); 3332 3333 if (specifiedValue !== null && !areEquivalentValues(command, newValue, specifiedValue)) { 3334 continue; 3335 } 3336 } 3337 children.push(node.childNodes[i]); 3338 } 3339 3340 // "Force the value of each Node in children, with command and new 3341 // value as in this invocation of the algorithm." 3342 for (i = 0; i < children.length; i++) { 3343 forceValue(children[i], command, newValue, range); 3344 } 3345 } 3346 } 3347 3348 //@} 3349 ///// Pushing down values ///// 3350 //@{ 3351 3352 function pushDownValues(node, command, newValue, range) { 3353 // "If node's parent is not an Element, abort this algorithm." 3354 if (!node.parentNode || node.parentNode.nodeType != $_.Node.ELEMENT_NODE) { 3355 return; 3356 } 3357 3358 // "If the effective command value of command is loosely equivalent to new 3359 // value on node, abort this algorithm." 3360 if (areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) { 3361 return; 3362 } 3363 3364 // "Let current ancestor be node's parent." 3365 var currentAncestor = node.parentNode; 3366 3367 // "Let ancestor list be a list of Nodes, initially empty." 3368 var ancestorList = []; 3369 3370 // "While current ancestor is an editable Element and the effective command 3371 // value of command is not loosely equivalent to new value on it, append 3372 // current ancestor to ancestor list, then set current ancestor to its 3373 // parent." 3374 while (isEditable(currentAncestor) && currentAncestor.nodeType == $_.Node.ELEMENT_NODE && !areLooselyEquivalentValues(command, getEffectiveCommandValue(currentAncestor, command), newValue)) { 3375 ancestorList.push(currentAncestor); 3376 currentAncestor = currentAncestor.parentNode; 3377 } 3378 3379 // "If ancestor list is empty, abort this algorithm." 3380 if (!ancestorList.length) { 3381 return; 3382 } 3383 3384 // "Let propagated value be the specified command value of command on the 3385 // last member of ancestor list." 3386 var propagatedValue = getSpecifiedCommandValue(ancestorList[ancestorList.length - 1], command); 3387 3388 // "If propagated value is null and is not equal to new value, abort this 3389 // algorithm." 3390 3391 if (propagatedValue === null && propagatedValue != newValue) { 3392 return; 3393 } 3394 3395 // "If the effective command value for the parent of the last member of 3396 // ancestor list is not loosely equivalent to new value, and new value is 3397 // not null, abort this algorithm." 3398 if (newValue !== null && !areLooselyEquivalentValues(command, getEffectiveCommandValue(ancestorList[ancestorList.length - 1].parentNode, command), newValue)) { 3399 return; 3400 } 3401 3402 // "While ancestor list is not empty:" 3403 while (ancestorList.length) { 3404 // "Let current ancestor be the last member of ancestor list." 3405 // "Remove the last member from ancestor list." 3406 currentAncestor = ancestorList.pop(); 3407 3408 // "If the specified command value of current ancestor for command is 3409 // not null, set propagated value to that value." 3410 if (getSpecifiedCommandValue(currentAncestor, command) !== null) { 3411 propagatedValue = getSpecifiedCommandValue(currentAncestor, command); 3412 } 3413 3414 // "Let children be the children of current ancestor." 3415 var children = Array.prototype.slice.call(toArray(currentAncestor.childNodes)); 3416 3417 // "If the specified command value of current ancestor for command is 3418 // not null, clear the value of current ancestor." 3419 if (getSpecifiedCommandValue(currentAncestor, command) !== null) { 3420 clearValue(currentAncestor, command, range); 3421 } 3422 3423 // "For every child in children:" 3424 var i; 3425 for (i = 0; i < children.length; i++) { 3426 var child = children[i]; 3427 3428 // "If child is node, continue with the next child." 3429 if (child == node) { 3430 continue; 3431 } 3432 3433 // "If child is an Element whose specified command value for 3434 // command is neither null nor equivalent to propagated value, 3435 // continue with the next child." 3436 if (child.nodeType == $_.Node.ELEMENT_NODE && getSpecifiedCommandValue(child, command) !== null && !areEquivalentValues(command, propagatedValue, getSpecifiedCommandValue(child, command))) { 3437 continue; 3438 } 3439 3440 // "If child is the last member of ancestor list, continue with the 3441 // next child." 3442 if (child == ancestorList[ancestorList.length - 1]) { 3443 continue; 3444 } 3445 3446 // "Force the value of child, with command as in this algorithm 3447 // and new value equal to propagated value." 3448 forceValue(child, command, propagatedValue, range); 3449 } 3450 } 3451 } 3452 3453 function restoreValues(values, range) { 3454 // "For each (node, command, value) triple in values:" 3455 $_(values).forEach(function (triple) { 3456 var node = triple[0]; 3457 var command = triple[1]; 3458 var value = triple[2]; 3459 3460 // "Let ancestor equal node." 3461 var ancestor = node; 3462 3463 // "If ancestor is not an Element, set it to its parent." 3464 if (!ancestor || ancestor.nodeType != $_.Node.ELEMENT_NODE) { 3465 ancestor = ancestor.parentNode; 3466 } 3467 3468 // "While ancestor is an Element and its specified command value for 3469 // command is null, set it to its parent." 3470 while (ancestor && ancestor.nodeType == $_.Node.ELEMENT_NODE && getSpecifiedCommandValue(ancestor, command) === null) { 3471 ancestor = ancestor.parentNode; 3472 } 3473 3474 // "If value is null and ancestor is an Element, push down values on 3475 // node for command, with new value null." 3476 if (value === null && ancestor && ancestor.nodeType == $_.Node.ELEMENT_NODE) { 3477 pushDownValues(node, command, null, range); 3478 3479 // "Otherwise, if ancestor is an Element and its specified command 3480 // value for command is not equivalent to value, or if ancestor is not 3481 // an Element and value is not null, force the value of command to 3482 // value on node." 3483 } else if ((ancestor && ancestor.nodeType == $_.Node.ELEMENT_NODE && !areEquivalentValues(command, getSpecifiedCommandValue(ancestor, command), value)) || ((!ancestor || ancestor.nodeType != $_.Node.ELEMENT_NODE) && value !== null)) { 3484 forceValue(node, command, value, range); 3485 } 3486 }); 3487 } 3488 3489 //@} 3490 ///// Setting the selection's value ///// 3491 //@{ 3492 3493 function setSelectionValue(command, newValue, range) { 3494 3495 // Use current selected range if no range passed 3496 range = range || getActiveRange(); 3497 3498 // "If there is no editable text node effectively contained in the active 3499 // range:" 3500 if (!$_(getAllEffectivelyContainedNodes(range)).filter(function (node) { return node.nodeType == $_.Node.TEXT_NODE; }, true).some(isEditable)) { 3501 // "If command has inline command activated values, set the state 3502 // override to true if new value is among them and false if it's not." 3503 if (commands[command].hasOwnProperty("inlineCommandActivatedValues")) { 3504 setStateOverride( 3505 command, 3506 $_(commands[command].inlineCommandActivatedValues).indexOf(newValue) != -1, 3507 range 3508 ); 3509 } 3510 3511 // "If command is "subscript", unset the state override for 3512 // "superscript"." 3513 if (command == "subscript") { 3514 unsetStateOverride("superscript", range); 3515 } 3516 3517 // "If command is "superscript", unset the state override for 3518 // "subscript"." 3519 if (command == "superscript") { 3520 unsetStateOverride("subscript", range); 3521 } 3522 3523 // "If new value is null, unset the value override (if any)." 3524 if (newValue === null) { 3525 3526 unsetValueOverride(command, range); 3527 3528 // "Otherwise, if command has a value specified, set the value override 3529 // to new value." 3530 } else if (commands[command].hasOwnProperty("value")) { 3531 setValueOverride(command, newValue, range); 3532 } 3533 3534 // "Abort these steps." 3535 return; 3536 } 3537 3538 // "If the active range's start node is an editable Text node, and its 3539 // start offset is neither zero nor its start node's length, call 3540 // splitText() on the active range's start node, with argument equal to the 3541 // active range's start offset. Then set the active range's start node to 3542 // the result, and its start offset to zero." 3543 if (isEditable(range.startContainer) && range.startContainer.nodeType == $_.Node.TEXT_NODE && range.startOffset != 0 && range.startOffset != getNodeLength(range.startContainer)) { 3544 // Account for browsers not following range mutation rules 3545 var newNode = splitText(range.startContainer, range.startOffset); 3546 var newActiveRange = Aloha.createRange(); 3547 if (range.startContainer == range.endContainer) { 3548 var newEndOffset = range.endOffset - range.startOffset; 3549 newActiveRange.setEnd(newNode, newEndOffset); 3550 range.setEnd(newNode, newEndOffset); 3551 } 3552 newActiveRange.setStart(newNode, 0); 3553 Aloha.getSelection().removeAllRanges(); 3554 Aloha.getSelection().addRange(newActiveRange); 3555 3556 range.setStart(newNode, 0); 3557 } 3558 3559 // "If the active range's end node is an editable Text node, and its end 3560 // offset is neither zero nor its end node's length, call splitText() on 3561 // the active range's end node, with argument equal to the active range's 3562 // end offset." 3563 if (isEditable(range.endContainer) && range.endContainer.nodeType == $_.Node.TEXT_NODE && range.endOffset != 0 && range.endOffset != getNodeLength(range.endContainer)) { 3564 // IE seems to mutate the range incorrectly here, so we need correction 3565 // here as well. The active range will be temporarily in orphaned 3566 // nodes, so calling getActiveRange() after splitText() but before 3567 // fixing the range will throw an exception. 3568 3569 // TODO: check if this is still neccessary 3570 var activeRange = range; 3571 var newStart = [activeRange.startContainer, activeRange.startOffset]; 3572 var newEnd = [activeRange.endContainer, activeRange.endOffset]; 3573 splitText(activeRange.endContainer, activeRange.endOffset); 3574 activeRange.setStart(newStart[0], newStart[1]); 3575 activeRange.setEnd(newEnd[0], newEnd[1]); 3576 3577 Aloha.getSelection().removeAllRanges(); 3578 Aloha.getSelection().addRange(activeRange); 3579 } 3580 3581 // "Let element list be all editable Elements effectively contained in the 3582 // active range. 3583 // 3584 // "For each element in element list, clear the value of element." 3585 $_(getAllEffectivelyContainedNodes(getActiveRange(), function (node) { 3586 return isEditable(node) && node.nodeType == $_.Node.ELEMENT_NODE; 3587 })).forEach(function (element) { 3588 clearValue(element, command, range); 3589 }); 3590 3591 // "Let node list be all editable nodes effectively contained in the active 3592 // range. 3593 // 3594 // "For each node in node list:" 3595 $_(getAllEffectivelyContainedNodes(range, isEditable)).forEach(function (node) { 3596 // "Push down values on node." 3597 pushDownValues(node, command, newValue, range); 3598 3599 // "Force the value of node." 3600 forceValue(node, command, newValue, range); 3601 }); 3602 } 3603 3604 /** 3605 * attempt to retrieve a block like a table or an Aloha Block 3606 * which is located one step right of the current caret position. 3607 * If an appropriate element is found it will be returned or 3608 * false otherwise 3609 * 3610 * @param {element} node current node we're in 3611 * @param {number} offset current offset within that node 3612 * 3613 * @return the dom node if found or false if no appropriate 3614 * element was found 3615 */ 3616 function getBlockAtNextPosition(node, offset) { 3617 var i; 3618 3619 // if we're inside a text node we first have to check 3620 // if there is nothing but tabs, newlines or the like 3621 // after our current cursor position 3622 if (node.nodeType === $_.Node.TEXT_NODE && offset < node.length) { 3623 for (i = offset; i < node.length; i++) { 3624 if ((node.data.charAt(i) !== '\t' && node.data.charAt(i) !== '\r' && node.data.charAt(i) !== '\n') || node.data.charCodeAt(i) === 160) { // 3625 // this is a character that has to be deleted first 3626 return false; 3627 } 3628 } 3629 } 3630 3631 // try the most simple approach first: the next sibling 3632 // is a table 3633 if (node.nextSibling && node.nextSibling.className && node.nextSibling.className.indexOf("aloha-table-wrapper") >= 0) { 3634 return node.nextSibling; 3635 } 3636 3637 // since we got only ignorable whitespace here determine if 3638 // our nodes parents next sibling is a table 3639 if (node.parentNode && node.parentNode.nextSibling && node.parentNode.nextSibling.className && node.parentNode.nextSibling.className.indexOf("aloha-table-wrapper") >= 0) { 3640 return node.parentNode.nextSibling; 3641 } 3642 3643 // our parents nextsibling is a pure whitespace node such as 3644 // generated by sourcecode indentation so we'll check for 3645 // the next next sibling 3646 if (node.parentNode && node.parentNode.nextSibling && isWhitespaceNode(node.parentNode.nextSibling) && node.parentNode.nextSibling.nextSibling && node.parentNode.nextSibling.nextSibling.className && node.parentNode.nextSibling.nextSibling.className.indexOf("aloha-table-wrapper") >= 0) { 3647 return node.parentNode.nextSibling.nextSibling; 3648 } 3649 3650 // Note: the search above works for tables, since they cannot be 3651 // nested deeply in paragraphs and other formatting tags. If this code 3652 // is extended to work also for other blocks, the search probably needs to be adapted 3653 } 3654 3655 /** 3656 * Attempt to retrieve a block like a table or an Aloha Block 3657 * which is located right before the current position. 3658 * If an appropriate element is found, it will be returned or 3659 * false otherwise 3660 * 3661 * @param {element} node current node 3662 * @param {offset} offset current offset 3663 * 3664 * @return dom node of found or false if no appropriate 3665 * element was found 3666 */ 3667 function getBlockAtPreviousPosition(node, offset) { 3668 var i; 3669 3670 if (node.nodeType === $_.Node.TEXT_NODE && offset > 0) { 3671 for (i = offset - 1; i >= 0; i--) { 3672 if ((node.data.charAt(i) !== '\t' && node.data.charAt(i) !== '\r' && node.data.charAt(i) !== '\n') || node.data.charCodeAt(i) === 160) { // 3673 // this is a character that has to be deleted first 3674 return false; 3675 } 3676 } 3677 } 3678 3679 // try the previous sibling 3680 if (node.previousSibling && node.previousSibling.className && node.previousSibling.className.indexOf("aloha-table-wrapper") >= 0) { 3681 return node.previousSibling; 3682 } 3683 3684 // try the parent's previous sibling 3685 if (node.parentNode && node.parentNode.previousSibling && node.parentNode.previousSibling.className && node.parentNode.previousSibling.className.indexOf("aloha-table-wrapper") >= 0) { 3686 return node.parentNode.previousSibling; 3687 } 3688 3689 // the parent's previous sibling might be a whitespace node 3690 if (node.parentNode && node.parentNode.previousSibling && isWhitespaceNode(node.parentNode.previousSibling) && node.parentNode.previousSibling.previousSibling && node.parentNode.previousSibling.previousSibling.className && node.parentNode.previousSibling.previousSibling.className.indexOf('aloha-table-wrapper') >= 0) { 3691 return node.parentNode.previousSibling.previousSibling; 3692 } 3693 3694 // Note: the search above works for tables, since they cannot be 3695 // nested deeply in paragraphs and other formatting tags. If this code 3696 // is extended to work also for other blocks, the search probably needs to be adapted 3697 3698 return false; 3699 } 3700 3701 // "A boundary point (node, offset) is a block start point if either node's 3702 // parent is null and offset is zero; or node has a child with index offset − 3703 // 1, and that child is either a visible block node or a visible br." 3704 function isBlockStartPoint(node, offset) { 3705 return (!node.parentNode && offset == 0) || (0 <= offset - 1 && offset - 1 < node.childNodes.length && isVisible(node.childNodes[offset - 1]) && (isBlockNode(node.childNodes[offset - 1]) || isNamedHtmlElement(node.childNodes[offset - 1], "br"))); 3706 } 3707 3708 // "A boundary point (node, offset) is a block end point if either node's 3709 // parent is null and offset is node's length; or node has a child with index 3710 // offset, and that child is a visible block node." 3711 function isBlockEndPoint(node, offset) { 3712 return (!node.parentNode && offset == getNodeLength(node)) || (offset < node.childNodes.length && isVisible(node.childNodes[offset]) && isBlockNode(node.childNodes[offset])); 3713 } 3714 3715 // "A boundary point is a block boundary point if it is either a block start 3716 // point or a block end point." 3717 function isBlockBoundaryPoint(node, offset) { 3718 return isBlockStartPoint(node, offset) || isBlockEndPoint(node, offset); 3719 } 3720 3721 function followsLineBreak(node) { 3722 // "Let offset be zero." 3723 var offset = 0; 3724 3725 // "While (node, offset) is not a block boundary point:" 3726 while (!isBlockBoundaryPoint(node, offset)) { 3727 // "If node has a visible child with index offset minus one, return 3728 // false." 3729 if (0 <= offset - 1 && offset - 1 < node.childNodes.length && isVisible(node.childNodes[offset - 1])) { 3730 return false; 3731 } 3732 3733 // "If offset is zero or node has no children, set offset to node's 3734 // index, then set node to its parent." 3735 if (offset == 0 || !node.hasChildNodes()) { 3736 offset = Dom.getIndexInParent(node); 3737 node = node.parentNode; 3738 3739 // "Otherwise, set node to its child with index offset minus one, then 3740 // set offset to node's length." 3741 } else { 3742 node = node.childNodes[offset - 1]; 3743 offset = getNodeLength(node); 3744 } 3745 } 3746 3747 // "Return true." 3748 return true; 3749 } 3750 3751 function precedesLineBreak(node) { 3752 // "Let offset be node's length." 3753 var offset = getNodeLength(node); 3754 3755 // "While (node, offset) is not a block boundary point:" 3756 while (!isBlockBoundaryPoint(node, offset)) { 3757 // "If node has a visible child with index offset, return false." 3758 if (offset < node.childNodes.length && isVisible(node.childNodes[offset])) { 3759 return false; 3760 } 3761 3762 // "If offset is node's length or node has no children, set offset to 3763 // one plus node's index, then set node to its parent." 3764 if (offset == getNodeLength(node) || !node.hasChildNodes()) { 3765 offset = 1 + Dom.getIndexInParent(node); 3766 node = node.parentNode; 3767 3768 // "Otherwise, set node to its child with index offset and set offset 3769 // to zero." 3770 } else { 3771 node = node.childNodes[offset]; 3772 offset = 0; 3773 } 3774 } 3775 3776 // "Return true." 3777 return true; 3778 } 3779 3780 //@} 3781 ///// Splitting a node list's parent ///// 3782 //@{ 3783 3784 function splitParent(nodeList, range) { 3785 var i; 3786 3787 // "Let original parent be the parent of the first member of node list." 3788 var originalParent = nodeList[0].parentNode; 3789 3790 // "If original parent is not editable or its parent is null, do nothing 3791 // and abort these steps." 3792 if (!isEditable(originalParent) || !originalParent.parentNode) { 3793 return; 3794 } 3795 3796 // "If the first child of original parent is in node list, remove 3797 // extraneous line breaks before original parent." 3798 if (jQuery.inArray(originalParent.firstChild, nodeList) != -1) { 3799 removeExtraneousLineBreaksBefore(originalParent); 3800 } 3801 3802 var firstChildInNodeList = jQuery.inArray(originalParent.firstChild, nodeList) != -1; 3803 var lastChildInNodeList = jQuery.inArray(originalParent.lastChild, nodeList) != -1; 3804 3805 // "If the first child of original parent is in node list, and original 3806 // parent follows a line break, set follows line break to true. Otherwise, 3807 // set follows line break to false." 3808 var followsLineBreak_ = firstChildInNodeList && followsLineBreak(originalParent); 3809 3810 // "If the last child of original parent is in node list, and original 3811 // parent precedes a line break, set precedes line break to true. 3812 // Otherwise, set precedes line break to false." 3813 var precedesLineBreak_ = lastChildInNodeList && precedesLineBreak(originalParent); 3814 3815 // "If the first child of original parent is not in node list, but its last 3816 // child is:" 3817 if (!firstChildInNodeList && lastChildInNodeList) { 3818 // "For each node in node list, in reverse order, insert node into the 3819 // parent of original parent immediately after original parent, 3820 // preserving ranges." 3821 for (i = nodeList.length - 1; i >= 0; i--) { 3822 movePreservingRanges(nodeList[i], originalParent.parentNode, 1 + Dom.getIndexInParent(originalParent), range); 3823 } 3824 3825 // "If precedes line break is true, and the last member of node list 3826 // does not precede a line break, call createElement("br") on the 3827 // context object and insert the result immediately after the last 3828 // member of node list." 3829 if (precedesLineBreak_ && !precedesLineBreak(nodeList[nodeList.length - 1])) { 3830 nodeList[nodeList.length - 1].parentNode.insertBefore(document.createElement("br"), nodeList[nodeList.length - 1].nextSibling); 3831 } 3832 3833 // "Remove extraneous line breaks at the end of original parent." 3834 removeExtraneousLineBreaksAtTheEndOf(originalParent); 3835 3836 // "Abort these steps." 3837 return; 3838 } 3839 3840 // "If the first child of original parent is not in node list:" 3841 if (!firstChildInNodeList) { 3842 // "Let cloned parent be the result of calling cloneNode(false) on 3843 // original parent." 3844 var clonedParent = originalParent.cloneNode(false); 3845 3846 // "If original parent has an id attribute, unset it." 3847 originalParent.removeAttribute("id"); 3848 3849 // "Insert cloned parent into the parent of original parent immediately 3850 // before original parent." 3851 originalParent.parentNode.insertBefore(clonedParent, originalParent); 3852 3853 // "While the previousSibling of the first member of node list is not 3854 // null, append the first child of original parent as the last child of 3855 // cloned parent, preserving ranges." 3856 while (nodeList[0].previousSibling) { 3857 movePreservingRanges(originalParent.firstChild, clonedParent, clonedParent.childNodes.length, range); 3858 } 3859 } 3860 3861 // "For each node in node list, insert node into the parent of original 3862 // parent immediately before original parent, preserving ranges." 3863 for (i = 0; i < nodeList.length; i++) { 3864 movePreservingRanges(nodeList[i], originalParent.parentNode, Dom.getIndexInParent(originalParent), range); 3865 } 3866 3867 // "If follows line break is true, and the first member of node list does 3868 // not follow a line break, call createElement("br") on the context object 3869 // and insert the result immediately before the first member of node list." 3870 if (followsLineBreak_ && !followsLineBreak(nodeList[0])) { 3871 nodeList[0].parentNode.insertBefore(document.createElement("br"), nodeList[0]); 3872 } 3873 3874 // "If the last member of node list is an inline node other than a br, and 3875 // the first child of original parent is a br, and original parent is not 3876 // an inline node, remove the first child of original parent from original 3877 // parent." 3878 if (isInlineNode(nodeList[nodeList.length - 1]) && !isNamedHtmlElement(nodeList[nodeList.length - 1], "br") && isNamedHtmlElement(originalParent.firstChild, "br") && !isInlineNode(originalParent)) { 3879 originalParent.removeChild(originalParent.firstChild); 3880 } 3881 3882 // "If original parent has no children:" 3883 if (!originalParent.hasChildNodes()) { 3884 // if the current range is collapsed and at the end of the originalParent.parentNode 3885 // the offset will not be available anymore after the next step (remove child) 3886 // that's why we need to fix the range to prevent a bogus offset 3887 if (originalParent.parentNode === range.startContainer && originalParent.parentNode === range.endContainer && range.startContainer === range.endContainer && range.startOffset === range.endOffset && originalParent.parentNode.childNodes.length === range.startOffset) { 3888 range.startOffset = originalParent.parentNode.childNodes.length - 1; 3889 range.endOffset = range.startOffset; 3890 } 3891 3892 // "Remove original parent from its parent." 3893 originalParent.parentNode.removeChild(originalParent); 3894 3895 // "If precedes line break is true, and the last member of node list 3896 // does not precede a line break, call createElement("br") on the 3897 // context object and insert the result immediately after the last 3898 // member of node list." 3899 if (precedesLineBreak_ && !precedesLineBreak(nodeList[nodeList.length - 1])) { 3900 nodeList[nodeList.length - 1].parentNode.insertBefore(document.createElement("br"), nodeList[nodeList.length - 1].nextSibling); 3901 } 3902 3903 // "Otherwise, remove extraneous line breaks before original parent." 3904 } else { 3905 removeExtraneousLineBreaksBefore(originalParent); 3906 } 3907 3908 // "If node list's last member's nextSibling is null, but its parent is not 3909 // null, remove extraneous line breaks at the end of node list's last 3910 // member's parent." 3911 if (!nodeList[nodeList.length - 1].nextSibling && nodeList[nodeList.length - 1].parentNode) { 3912 removeExtraneousLineBreaksAtTheEndOf(nodeList[nodeList.length - 1].parentNode); 3913 } 3914 } 3915 3916 //@} 3917 ///// The backColor command ///// 3918 //@{ 3919 commands.backcolor = { 3920 // Copy-pasted, same as hiliteColor 3921 action: function (value, range) { 3922 // Action is further copy-pasted, same as foreColor 3923 3924 // "If value is not a valid CSS color, prepend "#" to it." 3925 // 3926 // "If value is still not a valid CSS color, or if it is currentColor, 3927 // abort these steps and do nothing." 3928 // 3929 // Cheap hack for testing, no attempt to be comprehensive. 3930 if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) { 3931 value = "#" + value; 3932 } 3933 if (!/^(rgba?|hsla?)\(.*\)$/.test(value) && !parseSimpleColor(value) && value.toLowerCase() != "transparent") { 3934 return; 3935 } 3936 3937 // "Set the selection's value to value." 3938 setSelectionValue("backcolor", value, range); 3939 }, 3940 standardInlineValueCommand: true, 3941 relevantCssProperty: "backgroundColor", 3942 equivalentValues: function (val1, val2) { 3943 // "Either both strings are valid CSS colors and have the same red, 3944 // green, blue, and alpha components, or neither string is a valid CSS 3945 // color." 3946 return normalizeColor(val1) === normalizeColor(val2); 3947 } 3948 }; 3949 3950 //@} 3951 ///// The bold command ///// 3952 //@{ 3953 commands.bold = { 3954 action: function (value, range) { 3955 // "If queryCommandState("bold") returns true, set the selection's 3956 // value to "normal". Otherwise set the selection's value to "bold"." 3957 if (myQueryCommandState("bold", range)) { 3958 setSelectionValue("bold", "normal", range); 3959 } else { 3960 setSelectionValue("bold", "bold", range); 3961 } 3962 }, 3963 inlineCommandActivatedValues: ["bold", "600", "700", "800", "900"], 3964 relevantCssProperty: "fontWeight", 3965 equivalentValues: function (val1, val2) { 3966 // "Either the two strings are equal, or one is "bold" and the other is 3967 // "700", or one is "normal" and the other is "400"." 3968 return val1 == val2 || (val1 == "bold" && val2 == "700") || (val1 == "700" && val2 == "bold") || (val1 == "normal" && val2 == "400") || (val1 == "400" && val2 == "normal"); 3969 } 3970 }; 3971 3972 //@} 3973 ///// The createLink command ///// 3974 //@{ 3975 commands.createlink = { 3976 action: function (value, range) { 3977 // "If value is the empty string, abort these steps and do nothing." 3978 if (value === "") { 3979 return; 3980 } 3981 3982 // "For each editable a element that has an href attribute and is an 3983 // ancestor of some node effectively contained in the active range, set 3984 // that a element's href attribute to value." 3985 // 3986 // TODO: We don't actually do this in tree order, not that it matters 3987 // unless you're spying with mutation events. 3988 $_(getAllEffectivelyContainedNodes(getActiveRange())).forEach(function (node) { 3989 $_(getAncestors(node)).forEach(function (ancestor) { 3990 if (isEditable(ancestor) && isNamedHtmlElement(ancestor, 'a') && hasAttribute(ancestor, "href")) { 3991 ancestor.setAttribute("href", value); 3992 } 3993 }); 3994 }); 3995 3996 // "Set the selection's value to value." 3997 setSelectionValue("createlink", value, range); 3998 }, 3999 standardInlineValueCommand: true 4000 }; 4001 4002 //@} 4003 ///// The fontName command ///// 4004 //@{ 4005 commands.fontname = { 4006 4007 action: function (value, range) { 4008 // "Set the selection's value to value." 4009 setSelectionValue("fontname", value, range); 4010 }, 4011 standardInlineValueCommand: true, 4012 relevantCssProperty: "fontFamily" 4013 }; 4014 4015 //@} 4016 ///// The fontSize command ///// 4017 //@{ 4018 4019 commands.fontsize = { 4020 4021 action: function (value, range) { 4022 // "If value is the empty string, abort these steps and do nothing." 4023 if (value === "") { 4024 return; 4025 } 4026 4027 value = normalizeFontSize(value); 4028 4029 // "If value is not one of the strings "xx-small", "x-small", "small", 4030 // "medium", "large", "x-large", "xx-large", "xxx-large", and is not a 4031 // valid CSS absolute length, then abort these steps and do nothing." 4032 // 4033 // More cheap hacks to skip valid CSS absolute length checks. 4034 if (jQuery.inArray(value, ["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"]) == -1 && !/^[0-9]+(\.[0-9]+)?(cm|mm|in|pt|pc)$/.test(value)) { 4035 return; 4036 } 4037 4038 // "Set the selection's value to value." 4039 setSelectionValue("fontsize", value, range); 4040 }, 4041 indeterm: function () { 4042 // "True if among editable Text nodes that are effectively contained in 4043 // the active range, there are two that have distinct effective command 4044 // values. Otherwise false." 4045 return $_(getAllEffectivelyContainedNodes(getActiveRange(), function (node) { 4046 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 4047 })).map(function (node) { 4048 return getEffectiveCommandValue(node, "fontsize"); 4049 }, true).filter(function (value, i, arr) { 4050 return $_(arr.slice(0, i)).indexOf(value) == -1; 4051 }).length >= 2; 4052 }, 4053 value: function (range) { 4054 // "Let pixel size be the effective command value of the first editable 4055 // Text node that is effectively contained in the active range, or if 4056 // there is no such node, the effective command value of the active 4057 // range's start node, in either case interpreted as a number of 4058 // pixels." 4059 var node = getAllEffectivelyContainedNodes(range, function (node) { 4060 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 4061 })[0]; 4062 if (node === undefined) { 4063 node = range.startContainer; 4064 } 4065 var pixelSize = getEffectiveCommandValue(node, "fontsize"); 4066 4067 // "Return the legacy font size for pixel size." 4068 return getLegacyFontSize(pixelSize); 4069 }, 4070 relevantCssProperty: "fontSize" 4071 }; 4072 4073 //@} 4074 ///// The foreColor command ///// 4075 //@{ 4076 commands.forecolor = { 4077 action: function (value, range) { 4078 // Copy-pasted, same as backColor and hiliteColor 4079 4080 // "If value is not a valid CSS color, prepend "#" to it." 4081 // 4082 // "If value is still not a valid CSS color, or if it is currentColor, 4083 // abort these steps and do nothing." 4084 // 4085 // Cheap hack for testing, no attempt to be comprehensive. 4086 if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) { 4087 value = "#" + value; 4088 } 4089 if (!/^(rgba?|hsla?)\(.*\)$/.test(value) && !parseSimpleColor(value) && value.toLowerCase() != "transparent") { 4090 return; 4091 } 4092 4093 // "Set the selection's value to value." 4094 setSelectionValue("forecolor", value, range); 4095 }, 4096 standardInlineValueCommand: true, 4097 relevantCssProperty: "color", 4098 equivalentValues: function (val1, val2) { 4099 // "Either both strings are valid CSS colors and have the same red, 4100 // green, blue, and alpha components, or neither string is a valid CSS 4101 // color." 4102 return normalizeColor(val1) === normalizeColor(val2); 4103 } 4104 }; 4105 4106 //@} 4107 ///// The hiliteColor command ///// 4108 //@{ 4109 commands.hilitecolor = { 4110 // Copy-pasted, same as backColor 4111 action: function (value, range) { 4112 // Action is further copy-pasted, same as foreColor 4113 4114 // "If value is not a valid CSS color, prepend "#" to it." 4115 // 4116 // "If value is still not a valid CSS color, or if it is currentColor, 4117 // abort these steps and do nothing." 4118 // 4119 // Cheap hack for testing, no attempt to be comprehensive. 4120 if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) { 4121 value = "#" + value; 4122 } 4123 if (!/^(rgba?|hsla?)\(.*\)$/.test(value) && !parseSimpleColor(value) && value.toLowerCase() != "transparent") { 4124 return; 4125 } 4126 4127 // "Set the selection's value to value." 4128 setSelectionValue("hilitecolor", value, range); 4129 }, 4130 indeterm: function () { 4131 // "True if among editable Text nodes that are effectively contained in 4132 // the active range, there are two that have distinct effective command 4133 // values. Otherwise false." 4134 return $_(getAllEffectivelyContainedNodes(getActiveRange(), function (node) { 4135 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 4136 })).map(function (node) { 4137 return getEffectiveCommandValue(node, "hilitecolor"); 4138 }, true).filter(function (value, i, arr) { 4139 return $_(arr.slice(0, i)).indexOf(value) == -1; 4140 }).length >= 2; 4141 }, 4142 standardInlineValueCommand: true, 4143 relevantCssProperty: "backgroundColor", 4144 equivalentValues: function (val1, val2) { 4145 // "Either both strings are valid CSS colors and have the same red, 4146 // green, blue, and alpha components, or neither string is a valid CSS 4147 // color." 4148 return normalizeColor(val1) === normalizeColor(val2); 4149 } 4150 }; 4151 4152 //@} 4153 ///// The italic command ///// 4154 //@{ 4155 commands.italic = { 4156 action: function (value, range) { 4157 // "If queryCommandState("italic") returns true, set the selection's 4158 // value to "normal". Otherwise set the selection's value to "italic"." 4159 if (myQueryCommandState("italic", range)) { 4160 setSelectionValue("italic", "normal", range); 4161 } else { 4162 setSelectionValue("italic", "italic", range); 4163 } 4164 }, 4165 inlineCommandActivatedValues: ["italic", "oblique"], 4166 relevantCssProperty: "fontStyle" 4167 }; 4168 4169 //@} 4170 ///// The removeFormat command ///// 4171 //@{ 4172 commands.removeformat = { 4173 action: function (value, range) { 4174 var newEnd, newStart, newNode; 4175 4176 // "A removeFormat candidate is an editable HTML element with local 4177 // name "abbr", "acronym", "b", "bdi", "bdo", "big", "blink", "cite", 4178 // "code", "dfn", "em", "font", "i", "ins", "kbd", "mark", "nobr", "q", 4179 // "s", "samp", "small", "span", "strike", "strong", "sub", "sup", 4180 // "tt", "u", or "var"." 4181 function isRemoveFormatCandidate(node) { 4182 return isEditable(node) && isHtmlElementInArray(node, ["abbr", "acronym", "b", "bdi", "bdo", "big", "blink", "cite", "code", "dfn", "em", "font", "i", "ins", "kbd", "mark", "nobr", "q", "s", "samp", "small", "span", "strike", "strong", "sub", "sup", "tt", "u", "var"]); 4183 } 4184 4185 // "Let elements to remove be a list of every removeFormat candidate 4186 // effectively contained in the active range." 4187 var elementsToRemove = getAllEffectivelyContainedNodes(getActiveRange(), isRemoveFormatCandidate); 4188 4189 // "For each element in elements to remove:" 4190 $_(elementsToRemove).forEach(function (element) { 4191 // "While element has children, insert the first child of element 4192 // into the parent of element immediately before element, 4193 // preserving ranges." 4194 while (element.hasChildNodes()) { 4195 movePreservingRanges(element.firstChild, element.parentNode, Dom.getIndexInParent(element), getActiveRange()); 4196 } 4197 4198 // "Remove element from its parent." 4199 element.parentNode.removeChild(element); 4200 }); 4201 4202 // "If the active range's start node is an editable Text node, and its 4203 // start offset is neither zero nor its start node's length, call 4204 // splitText() on the active range's start node, with argument equal to 4205 // the active range's start offset. Then set the active range's start 4206 // node to the result, and its start offset to zero." 4207 if (isEditable(getActiveRange().startContainer) && getActiveRange().startContainer.nodeType == $_.Node.TEXT_NODE && getActiveRange().startOffset != 0 && getActiveRange().startOffset != getNodeLength(getActiveRange().startContainer)) { 4208 // Account for browsers not following range mutation rules 4209 if (getActiveRange().startContainer == getActiveRange().endContainer) { 4210 newEnd = getActiveRange().endOffset - getActiveRange().startOffset; 4211 newNode = splitText(getActiveRange().startContainer, getActiveRange().startOffset); 4212 getActiveRange().setStart(newNode, 0); 4213 getActiveRange().setEnd(newNode, newEnd); 4214 } else { 4215 getActiveRange().setStart(splitText(getActiveRange().startContainer, getActiveRange().startOffset), 0); 4216 } 4217 } 4218 4219 // "If the active range's end node is an editable Text node, and its 4220 // end offset is neither zero nor its end node's length, call 4221 // splitText() on the active range's end node, with argument equal to 4222 // the active range's end offset." 4223 if (isEditable(getActiveRange().endContainer) && getActiveRange().endContainer.nodeType == $_.Node.TEXT_NODE && getActiveRange().endOffset != 0 && getActiveRange().endOffset != getNodeLength(getActiveRange().endContainer)) { 4224 // IE seems to mutate the range incorrectly here, so we need 4225 // correction here as well. Have to be careful to set the range to 4226 // something not including the text node so that getActiveRange() 4227 // doesn't throw an exception due to a temporarily detached 4228 // endpoint. 4229 newStart = [getActiveRange().startContainer, getActiveRange().startOffset]; 4230 newEnd = [getActiveRange().endContainer, getActiveRange().endOffset]; 4231 getActiveRange().setEnd(document.documentElement, 0); 4232 splitText(newEnd[0], newEnd[1]); 4233 getActiveRange().setStart(newStart[0], newStart[1]); 4234 getActiveRange().setEnd(newEnd[0], newEnd[1]); 4235 } 4236 4237 // "Let node list consist of all editable nodes effectively contained 4238 // in the active range." 4239 // 4240 // "For each node in node list, while node's parent is a removeFormat 4241 // candidate in the same editing host as node, split the parent of the 4242 // one-node list consisting of node." 4243 $_(getAllEffectivelyContainedNodes(getActiveRange(), isEditable)).forEach(function (node) { 4244 while (isRemoveFormatCandidate(node.parentNode) && inSameEditingHost(node.parentNode, node)) { 4245 splitParent([node], getActiveRange()); 4246 } 4247 }); 4248 4249 // "For each of the entries in the following list, in the given order, 4250 // set the selection's value to null, with command as given." 4251 $_(["subscript", "bold", "fontname", "fontsize", "forecolor", "hilitecolor", "italic", "strikethrough", "underline"]).forEach(function (command) { 4252 setSelectionValue(command, null, range); 4253 }); 4254 } 4255 }; 4256 4257 //@} 4258 ///// The strikethrough command ///// 4259 //@{ 4260 commands.strikethrough = { 4261 action: function (value, range) { 4262 // "If queryCommandState("strikethrough") returns true, set the 4263 // selection's value to null. Otherwise set the selection's value to 4264 // "line-through"." 4265 if (myQueryCommandState("strikethrough", range)) { 4266 setSelectionValue("strikethrough", null, range); 4267 } else { 4268 setSelectionValue("strikethrough", "line-through", range); 4269 } 4270 }, 4271 inlineCommandActivatedValues: ["line-through"] 4272 }; 4273 4274 //@} 4275 ///// The subscript command ///// 4276 //@{ 4277 commands.subscript = { 4278 action: function (value, range) { 4279 // "Call queryCommandState("subscript"), and let state be the result." 4280 var state = myQueryCommandState("subscript", range); 4281 4282 // "Set the selection's value to null." 4283 setSelectionValue("subscript", null, range); 4284 4285 // "If state is false, set the selection's value to "subscript"." 4286 if (!state) { 4287 setSelectionValue("subscript", "subscript", range); 4288 } 4289 }, 4290 indeterm: function () { 4291 // "True if either among editable Text nodes that are effectively 4292 // contained in the active range, there is at least one with effective 4293 // command value "subscript" and at least one with some other effective 4294 // command value; or if there is some editable Text node effectively 4295 // contained in the active range with effective command value "mixed". 4296 // Otherwise false." 4297 var nodes = getAllEffectivelyContainedNodes(getActiveRange(), function (node) { 4298 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 4299 }); 4300 return (($_(nodes).some(function (node) { return getEffectiveCommandValue(node, "subscript") == "subscript"; }) 4301 && $_(nodes).some(function (node) { return getEffectiveCommandValue(node, "subscript") != "subscript"; })) 4302 || $_(nodes).some(function (node) { return getEffectiveCommandValue(node, "subscript") == "mixed"; })); 4303 }, 4304 inlineCommandActivatedValues: ["subscript"] 4305 }; 4306 4307 //@} 4308 ///// The superscript command ///// 4309 //@{ 4310 commands.superscript = { 4311 action: function (value, range) { 4312 // "Call queryCommandState("superscript"), and let state be the 4313 // result." 4314 var state = myQueryCommandState("superscript", range); 4315 4316 // "Set the selection's value to null." 4317 setSelectionValue("superscript", null, range); 4318 4319 // "If state is false, set the selection's value to "superscript"." 4320 if (!state) { 4321 setSelectionValue("superscript", "superscript", range); 4322 } 4323 }, 4324 indeterm: function () { 4325 // "True if either among editable Text nodes that are effectively 4326 // contained in the active range, there is at least one with effective 4327 // command value "superscript" and at least one with some other 4328 // effective command value; or if there is some editable Text node 4329 // effectively contained in the active range with effective command 4330 // value "mixed". Otherwise false." 4331 var nodes = getAllEffectivelyContainedNodes( 4332 getActiveRange(), 4333 function (node) { 4334 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 4335 } 4336 ); 4337 return (($_(nodes).some(function (node) { return getEffectiveCommandValue(node, "superscript") == "superscript"; }) 4338 && $_(nodes).some(function (node) { return getEffectiveCommandValue(node, "superscript") != "superscript"; })) 4339 || $_(nodes).some(function (node) { return getEffectiveCommandValue(node, "superscript") == "mixed"; })); 4340 }, 4341 inlineCommandActivatedValues: ["superscript"] 4342 }; 4343 4344 //@} 4345 ///// The underline command ///// 4346 //@{ 4347 commands.underline = { 4348 action: function (value, range) { 4349 // "If queryCommandState("underline") returns true, set the selection's 4350 // value to null. Otherwise set the selection's value to "underline"." 4351 if (myQueryCommandState("underline", range)) { 4352 setSelectionValue("underline", null, range); 4353 } else { 4354 setSelectionValue("underline", "underline", range); 4355 } 4356 }, 4357 inlineCommandActivatedValues: ["underline"] 4358 }; 4359 4360 //@} 4361 ///// The unlink command ///// 4362 //@{ 4363 commands.unlink = { 4364 action: function () { 4365 // "Let hyperlinks be a list of every a element that has an href 4366 // attribute and is contained in the active range or is an ancestor of 4367 // one of its boundary points." 4368 // 4369 // As usual, take care to ensure it's tree order. The correctness of 4370 // the following is left as an exercise for the reader. 4371 var range = getActiveRange(); 4372 var hyperlinks = []; 4373 var node; 4374 for (node = range.startContainer; node; node = node.parentNode) { 4375 if (isNamedHtmlElement(node, 'A') && hasAttribute(node, "href")) { 4376 hyperlinks.unshift(node); 4377 } 4378 } 4379 for (node = range.startContainer; node != nextNodeDescendants(range.endContainer); node = nextNode(node)) { 4380 if (isNamedHtmlElement(node, 'A') && hasAttribute(node, "href") && (isContained(node, range) || isAncestor(node, range.endContainer) || node == range.endContainer)) { 4381 hyperlinks.push(node); 4382 } 4383 } 4384 4385 // "Clear the value of each member of hyperlinks." 4386 var i; 4387 for (i = 0; i < hyperlinks.length; i++) { 4388 clearValue(hyperlinks[i], "unlink", range); 4389 } 4390 }, 4391 standardInlineValueCommand: true 4392 }; 4393 4394 //@} 4395 4396 ///////////////////////////////////// 4397 ///// Block formatting commands ///// 4398 ///////////////////////////////////// 4399 4400 ///// Block formatting command definitions ///// 4401 //@{ 4402 4403 // "An indentation element is either a blockquote, or a div that has a style 4404 // attribute that sets "margin" or some subproperty of it." 4405 function isIndentationElement(node) { 4406 // Handling of indentation elements while deleting is somehow broken (pressing backspace 4407 // in blockquotes wraps the blockquote into a div, ...) 4408 // therefore for now, we pretend that indentation elements do not exist at all. 4409 return false; 4410 } 4411 4412 // "A simple indentation element is an indentation element that has no 4413 // attributes other than one or more of 4414 // 4415 // * "a style attribute that sets no properties other than "margin", "border", 4416 // "padding", or subproperties of those; 4417 // * "a class attribute; 4418 // * "a dir attribute." 4419 function isSimpleIndentationElement(node) { 4420 if (!isIndentationElement(node)) { 4421 return false; 4422 } 4423 4424 if (node.tagName != "BLOCKQUOTE" && node.tagName != "DIV") { 4425 return false; 4426 } 4427 4428 var i; 4429 for (i = 0; i < node.attributes.length; i++) { 4430 if (!isHtmlNamespace(node.attributes[i].namespaceURI) || jQuery.inArray(node.attributes[i].name, ["style", "class", "dir"]) == -1) { 4431 return false; 4432 } 4433 } 4434 4435 if (typeof node.style.length !== 'undefined') { 4436 for (i = 0; i < node.style.length; i++) { 4437 // This is approximate, but it works well enough for my purposes. 4438 if (!/^(-[a-z]+-)?(margin|border|padding)/.test(node.style[i])) { 4439 return false; 4440 } 4441 } 4442 } else { 4443 var s; 4444 /*jslint forin: true*/ //not sure whether node.style.hasOwnProperty is valid 4445 for (s in node.style) { 4446 // This is approximate, but it works well enough for my purposes. 4447 if (!/^(-[a-z]+-)?(margin|border|padding)/.test(s) && node.style[s] && node.style[s] !== 0 && node.style[s] !== 'false') { 4448 return false; 4449 } 4450 } 4451 /*jslint forin: false*/ 4452 } 4453 4454 return true; 4455 } 4456 4457 // "A non-list single-line container is an HTML element with local name 4458 // "address", "div", "h1", "h2", "h3", "h4", "h5", "h6", "listing", "p", "pre", 4459 // or "xmp"." 4460 function isNonListSingleLineContainer(node) { 4461 return isHtmlElementInArray(node, ["address", "div", "h1", "h2", "h3", "h4", "h5", "h6", "listing", "p", "pre", "xmp"]); 4462 } 4463 4464 // "A single-line container is either a non-list single-line container, or an 4465 // HTML element with local name "li", "dt", or "dd"." 4466 function isSingleLineContainer(node) { 4467 return isNonListSingleLineContainer(node) || isHtmlElementInArray(node, ["li", "dt", "dd"]); 4468 } 4469 4470 // "The default single-line container name is "p"." 4471 var defaultSingleLineContainerName = "p"; 4472 4473 //@} 4474 ///// Check whether the given element is an end break ///// 4475 //@{ 4476 function isEndBreak(element) { 4477 return (isNamedHtmlElement(element, 'br') && element.parentNode.lastChild === element); 4478 } 4479 4480 //@} 4481 ///// Create an end break ///// 4482 //@{ 4483 function createEndBreak() { 4484 return document.createElement("br"); 4485 } 4486 4487 /** 4488 * Ensure the container is editable 4489 * E.g. when called for an empty paragraph or header, and the browser is not IE, 4490 * we need to append a br (marked with class aloha-end-br) 4491 * For IE7, there is a special behaviour that will append zero-width whitespace 4492 * @param {DOMNode} container 4493 */ 4494 function ensureContainerEditable(container) { 4495 if (!container) { 4496 return; 4497 } 4498 4499 // Because it is useful to be able to completely empty the contents of 4500 // an editing host during editing. So long as the container's 4501 // contenteditable attribute is "true" (as is the case during editing), 4502 // the element will be rendered visibly in all browsers. This fact 4503 // allows us to not have to prop up the container with a <br> in order 4504 // to keep it accessible to the editor. 4505 if (isEditingHost(container)) { 4506 return; 4507 } 4508 4509 if (isNamedHtmlElement(container.lastChild, "br")) { 4510 return; 4511 } 4512 4513 if ($_(container.childNodes).some(isVisible)) { 4514 return; 4515 } 4516 4517 if (!Aloha.browser.msie) { 4518 // for normal browsers, the end-br will do 4519 container.appendChild(createEndBreak()); 4520 } else if (Aloha.browser.msie && Aloha.browser.version <= 7 && isHtmlElementInArray(container, ["p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "blockquote"])) { 4521 4522 // for IE7, we need to insert a text node containing a single zero-width whitespace character 4523 if (!container.firstChild) { 4524 container.appendChild(document.createTextNode('\u200b')); 4525 } 4526 } 4527 } 4528 4529 /** 4530 * Node names that can not be unwrapped. 4531 * 4532 * @const 4533 * @type {string[]} 4534 */ 4535 var NOT_UNWRAPPABLE_NODES = ['TABLE', 'OL', 'UL', 'DL']; 4536 4537 /** 4538 * Checks if `node` can be unwrapped. 4539 * 4540 * @param {Element} node 4541 * @return {boolean} 4542 */ 4543 function isUnwrappable(node) { 4544 return jQuery.inArray(node.nodeName, NOT_UNWRAPPABLE_NODES) === -1; 4545 } 4546 //@} 4547 ///// Assorted block formatting command algorithms ///// 4548 //@{ 4549 4550 function fixDisallowedAncestors(node, range) { 4551 var i; 4552 4553 // "If node is not editable, abort these steps." 4554 if (!isEditable(node)) { 4555 return; 4556 } 4557 4558 // "If node is not an allowed child of any of its ancestors in the same 4559 // editing host, and is not an HTML element with local name equal to the 4560 // default single-line container name:" 4561 if ($_(getAncestors(node)).every(function (ancestor) { return !inSameEditingHost(node, ancestor) || !isAllowedChild(node, ancestor); }) 4562 && !isHtmlElement_obsolete(node, defaultSingleLineContainerName)) { 4563 // "If node is a dd or dt, wrap the one-node list consisting of node, 4564 // with sibling criteria returning true for any dl with no attributes 4565 // and false otherwise, and new parent instructions returning the 4566 // result of calling createElement("dl") on the context object. Then 4567 // abort these steps." 4568 if (isHtmlElementInArray(node, ["dd", "dt"])) { 4569 wrap( 4570 [node], 4571 function (sibling) { 4572 return isNamedHtmlElement(sibling, 'dl') && !sibling.attributes.length; 4573 }, 4574 function () { 4575 return document.createElement("dl"); 4576 }, 4577 range 4578 ); 4579 return; 4580 } 4581 4582 // "If node is not a prohibited paragraph child, abort these steps." 4583 if (!isProhibitedParagraphChild(node)) { 4584 return; 4585 } 4586 4587 // "Set the tag name of node to the default single-line container name, 4588 // and let node be the result." 4589 node = setTagName(node, defaultSingleLineContainerName, range); 4590 4591 ensureContainerEditable(node); 4592 4593 // "Fix disallowed ancestors of node." 4594 fixDisallowedAncestors(node, range); 4595 4596 // "Let descendants be all descendants of node." 4597 var descendants = getDescendants(node); 4598 4599 // "Fix disallowed ancestors of each member of descendants." 4600 for (i = 0; i < descendants.length; i++) { 4601 fixDisallowedAncestors(descendants[i], range); 4602 } 4603 4604 // "Abort these steps." 4605 return; 4606 } 4607 4608 // "Record the values of the one-node list consisting of node, and let 4609 // values be the result." 4610 var values = recordValues([node]); 4611 var newStartOffset, newEndOffset; 4612 4613 // "While node is not an allowed child of its parent, split the parent of 4614 // the one-node list consisting of node." 4615 while (!isAllowedChild(node, node.parentNode)) { 4616 // If the parent contains only this node and possibly empty text nodes, we rather want to unwrap the node, instead of splitting. 4617 // With splitting, we would get empty nodes, like: 4618 // split: <p><p>foo</p></p> -> <p></p><p>foo</p> (bad) 4619 // unwrap: <p><p>foo</p></p> -> <p>foo</p> (good) 4620 4621 // First remove empty text nodes that are children of the parent and correct the range if necessary 4622 // we do this to have the node being the only child of its parent, so that we can replace the parent with the node 4623 for (i = node.parentNode.childNodes.length - 1; i >= 0; --i) { 4624 if (node.parentNode.childNodes[i].nodeType == 3 && node.parentNode.childNodes[i].data.length == 0) { 4625 // we remove the empty text node 4626 node.parentNode.removeChild(node.parentNode.childNodes[i]); 4627 4628 // if the range points to somewhere behind the removed text node, we reduce the offset 4629 if (range.startContainer == node.parentNode && range.startOffset > i) { 4630 range.startOffset--; 4631 } 4632 if (range.endContainer == node.parentNode && range.endOffset > i) { 4633 range.endOffset--; 4634 } 4635 } 4636 } 4637 4638 // now that the parent has only the node as child (because we 4639 // removed any existing empty text nodes), we can safely unwrap the 4640 // node's contents, and correct the range if necessary 4641 // if the node is unwrappable (table, lists) the node is not unwrapped 4642 // but splitted. 4643 if (node.parentNode.childNodes.length == 1 && isUnwrappable(node)) { 4644 newStartOffset = range.startOffset; 4645 newEndOffset = range.endOffset; 4646 4647 if (range.startContainer === node.parentNode && range.startOffset > Dom.getIndexInParent(node)) { 4648 // the node (1 element) will be replaced by its contents (contents().length elements) 4649 newStartOffset = range.startOffset + (jQuery(node).contents().length - 1); 4650 } 4651 if (range.endContainer === node.parentNode && range.endOffset > Dom.getIndexInParent(node)) { 4652 // the node (1 element) will be replaced by its contents (contents().length elements) 4653 newEndOffset = range.endOffset + (jQuery(node).contents().length - 1); 4654 } 4655 4656 jQuery(node).contents().unwrap(); 4657 range.startOffset = newStartOffset; 4658 range.endOffset = newEndOffset; 4659 // after unwrapping, we are done 4660 break; 4661 } else { 4662 // store the original parent 4663 var originalParent = node.parentNode; 4664 splitParent([node], range); 4665 // check whether the parent did not change, so the split did not work, e.g. 4666 // because we already reached the editing host itself. 4667 // this situation can occur, e.g. when we insert a paragraph into an contenteditable span 4668 // in such cases, we just unwrap the contents of the paragraph 4669 if (originalParent === node.parentNode) { 4670 // so we unwrap now 4671 newStartOffset = range.startOffset; 4672 newEndOffset = range.endOffset; 4673 4674 if (range.startContainer === node.parentNode && range.startOffset > Dom.getIndexInParent(node)) { 4675 // the node (1 element) will be replaced by its contents (contents().length elements) 4676 newStartOffset = range.startOffset + (jQuery(node).contents().length - 1); 4677 } 4678 if (range.endContainer === node.parentNode && range.endOffset > Dom.getIndexInParent(node)) { 4679 // the node (1 element) will be replaced by its contents (contents().length elements) 4680 newEndOffset = range.endOffset + (jQuery(node).contents().length - 1); 4681 } 4682 jQuery(node).contents().unwrap(); 4683 range.startOffset = newStartOffset; 4684 range.endOffset = newEndOffset; 4685 // after unwrapping, we are done 4686 break; 4687 } 4688 } 4689 } 4690 4691 // "Restore the values from values." 4692 restoreValues(values, range); 4693 } 4694 4695 /** 4696 * This method "normalizes" sublists of the given item (which is supposed to be a LI): 4697 * If sublists are found in the LI element, they are moved directly into the outer list. 4698 * @param item item 4699 * @param range range, which will be modified if necessary 4700 */ 4701 function normalizeSublists(item, range) { 4702 // "If item is not an li or it is not editable or its parent is not 4703 // editable, abort these steps." 4704 if (!isNamedHtmlElement(item, 'LI') || !isEditable(item) || !isEditable(item.parentNode)) { 4705 return; 4706 } 4707 4708 // "Let new item be null." 4709 var newItem = null; 4710 4711 function isOlUl(node) { 4712 return isHtmlElementInArray(node, ["OL", "UL"]); 4713 } 4714 4715 // "While item has an ol or ul child:" 4716 while ($_(item.childNodes).some(isOlUl)) { 4717 // "Let child be the last child of item." 4718 var child = item.lastChild; 4719 4720 // "If child is an ol or ul, or new item is null and child is a Text 4721 // node whose data consists of zero of more space characters:" 4722 if (isHtmlElementInArray(child, ["OL", "UL"]) || (!newItem && child.nodeType == $_.Node.TEXT_NODE && /^[ \t\n\f\r]*$/.test(child.data))) { 4723 // "Set new item to null." 4724 newItem = null; 4725 4726 // "Insert child into the parent of item immediately following 4727 // item, preserving ranges." 4728 movePreservingRanges(child, item.parentNode, 1 + Dom.getIndexInParent(item), range); 4729 4730 // "Otherwise:" 4731 } else { 4732 // "If new item is null, let new item be the result of calling 4733 // createElement("li") on the ownerDocument of item, then insert 4734 // new item into the parent of item immediately after item." 4735 if (!newItem) { 4736 newItem = item.ownerDocument.createElement("li"); 4737 item.parentNode.insertBefore(newItem, item.nextSibling); 4738 } 4739 4740 // "Insert child into new item as its first child, preserving 4741 // ranges." 4742 movePreservingRanges(child, newItem, 0, range); 4743 } 4744 } 4745 } 4746 4747 /** 4748 * This method is the exact opposite of normalizeSublists. 4749 * List nodes directly nested into each other are corrected to be nested in li elements (so that the resulting lists conform the html5 specification) 4750 * @param item list node 4751 * @param range range, which is preserved when modifying the list 4752 */ 4753 function unNormalizeSublists(item, range) { 4754 // "If item is not an ol or ol or it is not editable or its parent is not 4755 // editable, abort these steps." 4756 if (!isHtmlElementInArray(item, ["OL", "UL"]) || !isEditable(item)) { 4757 return; 4758 } 4759 4760 var $list = jQuery(item); 4761 $list.children("ol,ul").each(function (index, sublist) { 4762 if (isNamedHtmlElement(sublist.previousSibling, "LI")) { 4763 // move the sublist into the LI 4764 movePreservingRanges(sublist, sublist.previousSibling, sublist.previousSibling.childNodes.length, range); 4765 } 4766 }); 4767 } 4768 4769 //@} 4770 ///// Block-extending a range ///// 4771 //@{ 4772 4773 function blockExtend(range) { 4774 // "Let start node, start offset, end node, and end offset be the start 4775 // and end nodes and offsets of the range." 4776 var startNode = range.startContainer; 4777 var startOffset = range.startOffset; 4778 var endNode = range.endContainer; 4779 var endOffset = range.endOffset; 4780 4781 // "If some ancestor container of start node is an li, set start offset to 4782 // the index of the last such li in tree order, and set start node to that 4783 // li's parent." 4784 var liAncestors = $_(getAncestors(startNode).concat(startNode)).filter(function (ancestor) { return isNamedHtmlElement(ancestor, 'li'); }).slice(-1); 4785 if (liAncestors.length) { 4786 startOffset = Dom.getIndexInParent(liAncestors[0]); 4787 startNode = liAncestors[0].parentNode; 4788 } 4789 4790 // "If (start node, start offset) is not a block start point, repeat the 4791 // following steps:" 4792 if (!isBlockStartPoint(startNode, startOffset)) { 4793 do { 4794 // "If start offset is zero, set it to start node's index, then set 4795 // start node to its parent." 4796 if (startOffset == 0) { 4797 startOffset = Dom.getIndexInParent(startNode); 4798 startNode = startNode.parentNode; 4799 4800 // "Otherwise, subtract one from start offset." 4801 } else { 4802 startOffset--; 4803 } 4804 4805 // "If (start node, start offset) is a block boundary point, break from 4806 // this loop." 4807 } while (!isBlockBoundaryPoint(startNode, startOffset)); 4808 } 4809 4810 // "While start offset is zero and start node's parent is not null, set 4811 // start offset to start node's index, then set start node to its parent." 4812 while (startOffset == 0 && startNode.parentNode) { 4813 startOffset = Dom.getIndexInParent(startNode); 4814 startNode = startNode.parentNode; 4815 } 4816 4817 // "If some ancestor container of end node is an li, set end offset to one 4818 // plus the index of the last such li in tree order, and set end node to 4819 // that li's parent." 4820 liAncestors = $_(getAncestors(endNode).concat(endNode)).filter(function (ancestor) { return isNamedHtmlElement(ancestor, 'li'); }).slice(-1); 4821 if (liAncestors.length) { 4822 endOffset = 1 + Dom.getIndexInParent(liAncestors[0]); 4823 endNode = liAncestors[0].parentNode; 4824 } 4825 4826 // "If (end node, end offset) is not a block end point, repeat the 4827 // following steps:" 4828 if (!isBlockEndPoint(endNode, endOffset)) { 4829 do { 4830 // "If end offset is end node's length, set it to one plus end node's 4831 // index, then set end node to its parent." 4832 if (endOffset == getNodeLength(endNode)) { 4833 endOffset = 1 + Dom.getIndexInParent(endNode); 4834 endNode = endNode.parentNode; 4835 4836 // "Otherwise, add one to end offset. 4837 } else { 4838 endOffset++; 4839 } 4840 4841 // "If (end node, end offset) is a block boundary point, break from 4842 // this loop." 4843 } while (!isBlockBoundaryPoint(endNode, endOffset)); 4844 } 4845 4846 // "While end offset is end node's length and end node's parent is not 4847 // null, set end offset to one plus end node's index, then set end node to 4848 // its parent." 4849 while (endOffset == getNodeLength(endNode) && endNode.parentNode) { 4850 endOffset = 1 + Dom.getIndexInParent(endNode); 4851 endNode = endNode.parentNode; 4852 } 4853 4854 // "Let new range be a new range whose start and end nodes and offsets 4855 // are start node, start offset, end node, and end offset." 4856 var newRange = Aloha.createRange(); 4857 newRange.setStart(startNode, startOffset); 4858 newRange.setEnd(endNode, endOffset); 4859 4860 // "Return new range." 4861 return newRange; 4862 } 4863 4864 function getSelectionListState() { 4865 // "Block-extend the active range, and let new range be the result." 4866 var newRange = blockExtend(getActiveRange()); 4867 4868 // "Let node list be a list of nodes, initially empty." 4869 // 4870 // "For each node contained in new range, append node to node list if the 4871 // last member of node list (if any) is not an ancestor of node; node is 4872 // editable; node is not an indentation element; and node is either an ol 4873 // or ul, or the child of an ol or ul, or an allowed child of "li"." 4874 var nodeList = getContainedNodes(newRange, function (node) { 4875 return isEditable(node) && !isIndentationElement(node) && (isHtmlElementInArray(node, ["ol", "ul"]) || isHtmlElementInArray(node.parentNode, ["ol", "ul"]) || isAllowedChild(node, "li")); 4876 }); 4877 4878 // "If node list is empty, return "none"." 4879 if (!nodeList.length) { 4880 return "none"; 4881 } 4882 4883 // "If every member of node list is either an ol or the child of an ol or 4884 // the child of an li child of an ol, and none is a ul or an ancestor of a 4885 // ul, return "ol"." 4886 if ($_(nodeList).every(function (node) { return (isNamedHtmlElement(node, 'ol') 4887 || isNamedHtmlElement(node.parentNode, "ol") 4888 || (isNamedHtmlElement(node.parentNode, "li") 4889 && isNamedHtmlElement(node.parentNode.parentNode, "ol"))); }) 4890 && !$_(nodeList).some(function (node) { return isNamedHtmlElement(node, 'ul') || (node.querySelector && node.querySelector("ul")); })) { 4891 return "ol"; 4892 } 4893 4894 // "If every member of node list is either a ul or the child of a ul or the 4895 // child of an li child of a ul, and none is an ol or an ancestor of an ol, 4896 // return "ul"." 4897 if ($_(nodeList).every(function (node) { return (isNamedHtmlElement(node, 'ul') 4898 || isNamedHtmlElement(node.parentNode, "ul") 4899 || (isNamedHtmlElement(node.parentNode, "li") 4900 && isNamedHtmlElement(node.parentNode.parentNode, "ul"))); }) 4901 && !$_(nodeList).some(function (node) { return isNamedHtmlElement(node, 'ol') || (node.querySelector && node.querySelector("ol")); })) { 4902 return "ul"; 4903 } 4904 4905 var hasOl = $_(nodeList).some(function (node) { 4906 return (isNamedHtmlElement(node, 'ol') 4907 || isNamedHtmlElement(node.parentNode, "ol") 4908 || (node.querySelector && node.querySelector("ol")) 4909 || (isNamedHtmlElement(node.parentNode, "li") 4910 && isNamedHtmlElement(node.parentNode.parentNode, "ol"))); 4911 }); 4912 var hasUl = $_(nodeList).some(function (node) { 4913 return (isNamedHtmlElement(node, 'ul') 4914 || isNamedHtmlElement(node.parentNode, "ul") 4915 || (node.querySelector && node.querySelector("ul")) 4916 || (isNamedHtmlElement(node.parentNode, "li") 4917 && isNamedHtmlElement(node.parentNode.parentNode, "ul"))); 4918 }); 4919 // "If some member of node list is either an ol or the child or ancestor of 4920 // an ol or the child of an li child of an ol, and some member of node list 4921 // is either a ul or the child or ancestor of a ul or the child of an li 4922 // child of a ul, return "mixed"." 4923 if (hasOl && hasUl) { 4924 return "mixed"; 4925 } 4926 4927 // "If some member of node list is either an ol or the child or ancestor of 4928 // an ol or the child of an li child of an ol, return "mixed ol"." 4929 if (hasOl) { 4930 return "mixed ol"; 4931 } 4932 4933 // "If some member of node list is either a ul or the child or ancestor of 4934 // a ul or the child of an li child of a ul, return "mixed ul"." 4935 if (hasUl) { 4936 return "mixed ul"; 4937 } 4938 4939 // "Return "none"." 4940 return "none"; 4941 } 4942 4943 function getAlignmentValue(node) { 4944 // "While node is neither null nor an Element, or it is an Element but its 4945 // "display" property has resolved value "inline" or "none", set node to 4946 // its parent." 4947 while ((node && node.nodeType != $_.Node.ELEMENT_NODE) || (node.nodeType == $_.Node.ELEMENT_NODE && jQuery.inArray($_.getComputedStyle(node).display, ["inline", "none"]) != -1)) { 4948 node = node.parentNode; 4949 } 4950 4951 // "If node is not an Element, return "left"." 4952 if (!node || node.nodeType != $_.Node.ELEMENT_NODE) { 4953 return "left"; 4954 } 4955 4956 var resolvedValue = $_.getComputedStyle(node).textAlign 4957 // Hack around browser non-standardness 4958 .replace(/^-(moz|webkit)-/, "").replace(/^auto$/, "start"); 4959 4960 // "If node's "text-align" property has resolved value "start", return 4961 // "left" if the directionality of node is "ltr", "right" if it is "rtl"." 4962 if (resolvedValue == "start") { 4963 return getDirectionality(node) == "ltr" ? "left" : "right"; 4964 } 4965 4966 // "If node's "text-align" property has resolved value "end", return 4967 // "right" if the directionality of node is "ltr", "left" if it is "rtl"." 4968 if (resolvedValue == "end") { 4969 return getDirectionality(node) == "ltr" ? "right" : "left"; 4970 } 4971 4972 // "If node's "text-align" property has resolved value "center", "justify", 4973 // "left", or "right", return that value." 4974 if (jQuery.inArray(resolvedValue, ["center", "justify", "left", "right"]) != -1) { 4975 return resolvedValue; 4976 } 4977 4978 // "Return "left"." 4979 return "left"; 4980 } 4981 4982 //@} 4983 ///// Recording and restoring overrides ///// 4984 //@{ 4985 4986 function recordCurrentOverrides(range) { 4987 // "Let overrides be a list of (string, string or boolean) ordered pairs, 4988 // initially empty." 4989 var overrides = []; 4990 4991 // "If there is a value override for "createLink", add ("createLink", value 4992 // override for "createLink") to overrides." 4993 if (getValueOverride("createlink", range) !== undefined) { 4994 overrides.push(["createlink", getValueOverride("createlink", range)]); 4995 } 4996 4997 // "For each command in the list "bold", "italic", "strikethrough", 4998 // "subscript", "superscript", "underline", in order: if there is a state 4999 // override for command, add (command, command's state override) to 5000 // overrides." 5001 $_(["bold", "italic", "strikethrough", "subscript", "superscript", "underline"]).forEach(function (command) { 5002 if (getStateOverride(command, range) !== undefined) { 5003 overrides.push([command, getStateOverride(command, range)]); 5004 } 5005 }); 5006 5007 // "For each command in the list "fontName", "fontSize", "foreColor", 5008 // "hiliteColor", in order: if there is a value override for command, add 5009 // (command, command's value override) to overrides." 5010 $_(["fontname", "fontsize", "forecolor", "hilitecolor"]).forEach(function (command) { 5011 if (getValueOverride(command, range) !== undefined) { 5012 overrides.push([command, getValueOverride(command, range)]); 5013 } 5014 }); 5015 5016 // "Return overrides." 5017 return overrides; 5018 } 5019 5020 function recordCurrentStatesAndValues(range) { 5021 // "Let overrides be a list of (string, string or boolean) ordered pairs, 5022 // initially empty." 5023 var overrides = []; 5024 5025 // "Let node be the first editable Text node effectively contained in the 5026 // active range, or null if there is none." 5027 var node = $_(getAllEffectivelyContainedNodes(range)).filter(function (node) { 5028 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 5029 })[0]; 5030 5031 // "If node is null, return overrides." 5032 if (!node) { 5033 return overrides; 5034 } 5035 5036 // "Add ("createLink", value for "createLink") to overrides." 5037 overrides.push(["createlink", commands.createlink.value(range)]); 5038 5039 // "For each command in the list "bold", "italic", "strikethrough", 5040 // "subscript", "superscript", "underline", in order: if node's effective 5041 // command value for command is one of its inline command activated values, 5042 // add (command, true) to overrides, and otherwise add (command, false) to 5043 // overrides." 5044 $_(["bold", "italic", "strikethrough", "subscript", "superscript", "underline"]).forEach(function (command) { 5045 if ($_(commands[command].inlineCommandActivatedValues).indexOf(getEffectiveCommandValue(node, command)) != -1) { 5046 overrides.push([command, true]); 5047 } else { 5048 overrides.push([command, false]); 5049 } 5050 }); 5051 5052 // "For each command in the list "fontName", "foreColor", "hiliteColor", in 5053 // order: add (command, command's value) to overrides." 5054 5055 $_(["fontname", "fontsize", "forecolor", "hilitecolor"]).forEach(function (command) { 5056 overrides.push([command, commands[command].value(range)]); 5057 }); 5058 5059 // "Add ("fontSize", node's effective command value for "fontSize") to 5060 // overrides." 5061 overrides.push(["fontsize", getEffectiveCommandValue(node, "fontsize")]); 5062 5063 // "Return overrides." 5064 return overrides; 5065 } 5066 5067 function restoreStatesAndValues(overrides, range) { 5068 var i; 5069 var command; 5070 var override; 5071 // "Let node be the first editable Text node effectively contained in the 5072 // active range, or null if there is none." 5073 var node = $_(getAllEffectivelyContainedNodes(range)).filter(function (node) { 5074 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 5075 })[0]; 5076 5077 function isEditableTextNode(node) { 5078 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 5079 } 5080 5081 // "If node is not null, then for each (command, override) pair in 5082 // overrides, in order:" 5083 if (node) { 5084 5085 for (i = 0; i < overrides.length; i++) { 5086 command = overrides[i][0]; 5087 override = overrides[i][1]; 5088 5089 // "If override is a boolean, and queryCommandState(command) 5090 // returns something different from override, call 5091 // execCommand(command)." 5092 if (typeof override == "boolean" && myQueryCommandState(command, range) != override) { 5093 myExecCommand(command, false, override, range); 5094 5095 // "Otherwise, if override is a string, and command is not 5096 // "fontSize", and queryCommandValue(command) returns something not 5097 // equivalent to override, call execCommand(command, false, 5098 // override)." 5099 } else if (typeof override == "string" && command != "fontsize" && !areEquivalentValues(command, myQueryCommandValue(command, range), override)) { 5100 myExecCommand(command, false, override, range); 5101 5102 // "Otherwise, if override is a string; and command is "fontSize"; 5103 // and either there is a value override for "fontSize" that is not 5104 // equal to override, or there is no value override for "fontSize" 5105 // and node's effective command value for "fontSize" is not loosely 5106 5107 // equivalent to override: call execCommand("fontSize", false, 5108 // override)." 5109 } else if (typeof override == "string" 5110 && command == "fontsize" 5111 && ((getValueOverride("fontsize", range) !== undefined 5112 && getValueOverride("fontsize", range) !== override) 5113 || (getValueOverride("fontsize", range) === undefined 5114 && !areLooselyEquivalentValues(command, getEffectiveCommandValue(node, "fontsize"), override)))) { 5115 myExecCommand("fontsize", false, override, range); 5116 5117 // "Otherwise, continue this loop from the beginning." 5118 } else { 5119 continue; 5120 } 5121 5122 // "Set node to the first editable Text node effectively contained 5123 // in the active range, if there is one." 5124 node = $_(getAllEffectivelyContainedNodes(range)).filter(isEditableTextNode)[0] || node; 5125 } 5126 5127 // "Otherwise, for each (command, override) pair in overrides, in order:" 5128 } else { 5129 for (i = 0; i < overrides.length; i++) { 5130 command = overrides[i][0]; 5131 override = overrides[i][1]; 5132 5133 // "If override is a boolean, set the state override for command to 5134 // override." 5135 if (typeof override == "boolean") { 5136 setStateOverride(command, override, range); 5137 } 5138 5139 // "If override is a string, set the value override for command to 5140 // override." 5141 if (typeof override == "string") { 5142 setValueOverride(command, override, range); 5143 } 5144 } 5145 } 5146 } 5147 5148 //@} 5149 ///// Canonical space sequences ///// 5150 //@{ 5151 5152 function canonicalSpaceSequence(n, nonBreakingStart, nonBreakingEnd) { 5153 // "If n is zero, return the empty string." 5154 if (n == 0) { 5155 return ""; 5156 } 5157 5158 // "If n is one and both non-breaking start and non-breaking end are false, 5159 // return a single space (U+0020)." 5160 if (n == 1 && !nonBreakingStart && !nonBreakingEnd) { 5161 return " "; 5162 } 5163 5164 // "If n is one, return a single non-breaking space (U+00A0)." 5165 if (n == 1) { 5166 return "\xa0"; 5167 } 5168 5169 // "Let buffer be the empty string." 5170 var buffer = ""; 5171 5172 // "If non-breaking start is true, let repeated pair be U+00A0 U+0020. 5173 // Otherwise, let it be U+0020 U+00A0." 5174 var repeatedPair; 5175 if (nonBreakingStart) { 5176 repeatedPair = "\xa0 "; 5177 } else { 5178 repeatedPair = " \xa0"; 5179 } 5180 5181 // "While n is greater than three, append repeated pair to buffer and 5182 // subtract two from n." 5183 while (n > 3) { 5184 buffer += repeatedPair; 5185 n -= 2; 5186 } 5187 5188 // "If n is three, append a three-element string to buffer depending on 5189 // non-breaking start and non-breaking end:" 5190 if (n == 3) { 5191 buffer += !nonBreakingStart && !nonBreakingEnd ? " \xa0 " : nonBreakingStart && !nonBreakingEnd ? "\xa0\xa0 " : !nonBreakingStart && nonBreakingEnd ? " \xa0\xa0" : nonBreakingStart && nonBreakingEnd ? "\xa0 \xa0" : "impossible"; 5192 5193 // "Otherwise, append a two-element string to buffer depending on 5194 // non-breaking start and non-breaking end:" 5195 } else { 5196 buffer += !nonBreakingStart && !nonBreakingEnd ? "\xa0 " : nonBreakingStart && !nonBreakingEnd ? "\xa0 " : !nonBreakingStart && nonBreakingEnd ? " \xa0" : nonBreakingStart && nonBreakingEnd ? "\xa0\xa0" : "impossible"; 5197 } 5198 5199 // "Return buffer." 5200 return buffer; 5201 } 5202 5203 function canonicalizeWhitespace(node, offset) { 5204 // "If node is neither editable nor an editing host, abort these steps." 5205 if (!isEditable(node) && !isEditingHost(node)) { 5206 return; 5207 } 5208 5209 // "Let start node equal node and let start offset equal offset." 5210 var startNode = node; 5211 var startOffset = offset; 5212 5213 // "Repeat the following steps:" 5214 while (true) { 5215 // "If start node has a child in the same editing host with index start 5216 // offset minus one, set start node to that child, then set start 5217 // offset to start node's length." 5218 if (0 <= startOffset - 1 && inSameEditingHost(startNode, startNode.childNodes[startOffset - 1])) { 5219 startNode = startNode.childNodes[startOffset - 1]; 5220 startOffset = getNodeLength(startNode); 5221 5222 // "Otherwise, if start offset is zero and start node does not follow a 5223 // line break and start node's parent is in the same editing host, set 5224 // start offset to start node's index, then set start node to its 5225 // parent." 5226 } else if (startOffset == 0 && !followsLineBreak(startNode) && inSameEditingHost(startNode, startNode.parentNode)) { 5227 startOffset = Dom.getIndexInParent(startNode); 5228 startNode = startNode.parentNode; 5229 5230 // "Otherwise, if start node is a Text node and its parent's resolved 5231 // value for "white-space" is neither "pre" nor "pre-wrap" and start 5232 // offset is not zero and the (start offset − 1)st element of start 5233 // node's data is a space (0x0020) or non-breaking space (0x00A0), 5234 // subtract one from start offset." 5235 } else if (startNode.nodeType == $_.Node.TEXT_NODE && jQuery.inArray($_.getComputedStyle(startNode.parentNode).whiteSpace, ["pre", "pre-wrap"]) == -1 && startOffset != 0 && /[ \xa0]/.test(startNode.data[startOffset - 1])) { 5236 startOffset--; 5237 5238 // "Otherwise, break from this loop." 5239 } else { 5240 break; 5241 } 5242 } 5243 5244 // "Let end node equal start node and end offset equal start offset." 5245 var endNode = startNode; 5246 var endOffset = startOffset; 5247 5248 // "Let length equal zero." 5249 var length = 0; 5250 5251 // "Let follows space be false." 5252 var followsSpace = false; 5253 5254 // "Repeat the following steps:" 5255 while (true) { 5256 // "If end node has a child in the same editing host with index end 5257 // offset, set end node to that child, then set end offset to zero." 5258 if (endOffset < endNode.childNodes.length && inSameEditingHost(endNode, endNode.childNodes[endOffset])) { 5259 endNode = endNode.childNodes[endOffset]; 5260 endOffset = 0; 5261 5262 // "Otherwise, if end offset is end node's length and end node does not 5263 // precede a line break and end node's parent is in the same editing 5264 // host, set end offset to one plus end node's index, then set end node 5265 // to its parent." 5266 } else if (endOffset == getNodeLength(endNode) && !precedesLineBreak(endNode) && inSameEditingHost(endNode, endNode.parentNode)) { 5267 endOffset = 1 + Dom.getIndexInParent(endNode); 5268 endNode = endNode.parentNode; 5269 5270 // "Otherwise, if end node is a Text node and its parent's resolved 5271 // value for "white-space" is neither "pre" nor "pre-wrap" and end 5272 // offset is not end node's length and the end offsetth element of 5273 // end node's data is a space (0x0020) or non-breaking space (0x00A0):" 5274 } else if (endNode.nodeType == $_.Node.TEXT_NODE && jQuery.inArray($_.getComputedStyle(endNode.parentNode).whiteSpace, ["pre", "pre-wrap"]) == -1 && endOffset != getNodeLength(endNode) && /[ \xa0]/.test(endNode.data[endOffset])) { 5275 // "If follows space is true and the end offsetth element of end 5276 // node's data is a space (0x0020), call deleteData(end offset, 1) 5277 // on end node, then continue this loop from the beginning." 5278 if (followsSpace && " " == endNode.data[endOffset]) { 5279 endNode.deleteData(endOffset, 1); 5280 continue; 5281 } 5282 5283 // "Set follows space to true if the end offsetth element of end 5284 // node's data is a space (0x0020), false otherwise." 5285 followsSpace = " " == endNode.data[endOffset]; 5286 5287 // "Add one to end offset." 5288 endOffset++; 5289 5290 // "Add one to length." 5291 length++; 5292 5293 // "Otherwise, break from this loop." 5294 } else { 5295 break; 5296 } 5297 } 5298 5299 // "Let replacement whitespace be the canonical space sequence of length 5300 // length. non-breaking start is true if start offset is zero and start 5301 // node follows a line break, and false otherwise. non-breaking end is true 5302 // if end offset is end node's length and end node precedes a line break, 5303 // and false otherwise." 5304 var replacementWhitespace = canonicalSpaceSequence(length, startOffset == 0 && followsLineBreak(startNode), endOffset == getNodeLength(endNode) && precedesLineBreak(endNode)); 5305 5306 // "While (start node, start offset) is before (end node, end offset):" 5307 while (getPosition(startNode, startOffset, endNode, endOffset) == "before") { 5308 // "If start node has a child with index start offset, set start node 5309 // to that child, then set start offset to zero." 5310 if (startOffset < startNode.childNodes.length) { 5311 startNode = startNode.childNodes[startOffset]; 5312 startOffset = 0; 5313 5314 // "Otherwise, if start node is not a Text node or if start offset is 5315 5316 // start node's length, set start offset to one plus start node's 5317 // index, then set start node to its parent." 5318 } else if (startNode.nodeType != $_.Node.TEXT_NODE || startOffset == getNodeLength(startNode)) { 5319 startOffset = 1 + Dom.getIndexInParent(startNode); 5320 startNode = startNode.parentNode; 5321 5322 // "Otherwise:" 5323 } else { 5324 // "Remove the first element from replacement whitespace, and let 5325 // element be that element." 5326 var element = replacementWhitespace[0]; 5327 replacementWhitespace = replacementWhitespace.slice(1); 5328 5329 // "If element is not the same as the start offsetth element of 5330 // start node's data:" 5331 if (element != startNode.data[startOffset]) { 5332 // "Call insertData(start offset, element) on start node." 5333 startNode.insertData(startOffset, element); 5334 5335 // "Call deleteData(start offset + 1, 1) on start node." 5336 startNode.deleteData(startOffset + 1, 1); 5337 } 5338 5339 // "Add one to start offset." 5340 startOffset++; 5341 } 5342 } 5343 } 5344 5345 //@} 5346 ///// Deleting the contents of a range ///// 5347 //@{ 5348 5349 function deleteContents(arg1, arg2, arg3, arg4, arg5) { 5350 // We accept several different calling conventions: 5351 // 5352 // 1) A single argument, which is a range. 5353 // 5354 // 2) Two arguments, the first being a range and the second flags. 5355 // 5356 // 3) Four arguments, the start and end of a range. 5357 // 5358 // 4) Five arguments, the start and end of a range plus flags. 5359 // 5360 // The flags argument is a dictionary that can have up to two keys, 5361 // blockMerging and stripWrappers, whose corresponding values are 5362 // interpreted as boolean. E.g., {stripWrappers: false}. 5363 var range; 5364 var flags = {}; 5365 var i; 5366 5367 if (arguments.length < 3) { 5368 range = arg1; 5369 } else { 5370 range = Aloha.createRange(); 5371 range.setStart(arg1, arg2); 5372 range.setEnd(arg3, arg4); 5373 } 5374 if (arguments.length == 2) { 5375 flags = arg2; 5376 } 5377 if (arguments.length == 5) { 5378 flags = arg5; 5379 } 5380 5381 var blockMerging = null != flags.blockMerging ? !!flags.blockMerging : true; 5382 var stripWrappers = null != flags.stripWrappers ? !!flags.stripWrappers : true; 5383 5384 // "If range is null, abort these steps and do nothing." 5385 if (!range) { 5386 return; 5387 } 5388 5389 // "Let start node, start offset, end node, and end offset be range's start 5390 // and end nodes and offsets." 5391 var startNode = range.startContainer; 5392 var startOffset = range.startOffset; 5393 var endNode = range.endContainer; 5394 var endOffset = range.endOffset; 5395 var referenceNode; 5396 5397 // "While start node has at least one child:" 5398 while (startNode.hasChildNodes()) { 5399 // "If start offset is start node's length, and start node's parent is 5400 // in the same editing host, and start node is an inline node, set 5401 // start offset to one plus the index of start node, then set start 5402 // node to its parent and continue this loop from the beginning." 5403 if (startOffset == getNodeLength(startNode) && inSameEditingHost(startNode, startNode.parentNode) && isInlineNode(startNode)) { 5404 startOffset = 1 + Dom.getIndexInParent(startNode); 5405 startNode = startNode.parentNode; 5406 continue; 5407 } 5408 5409 // "If start offset is start node's length, break from this loop." 5410 if (startOffset == getNodeLength(startNode)) { 5411 break; 5412 } 5413 5414 // "Let reference node be the child of start node with index equal to 5415 // start offset." 5416 referenceNode = startNode.childNodes[startOffset]; 5417 5418 // "If reference node is a block node or an Element with no children, 5419 // or is neither an Element nor a Text node, break from this loop." 5420 if (isBlockNode(referenceNode) || (referenceNode.nodeType == $_.Node.ELEMENT_NODE && !referenceNode.hasChildNodes()) || (referenceNode.nodeType != $_.Node.ELEMENT_NODE && referenceNode.nodeType != $_.Node.TEXT_NODE)) { 5421 break; 5422 } 5423 5424 // "Set start node to reference node and start offset to 0." 5425 startNode = referenceNode; 5426 startOffset = 0; 5427 } 5428 5429 // "While end node has at least one child:" 5430 while (endNode.hasChildNodes()) { 5431 // "If end offset is 0, and end node's parent is in the same editing 5432 // host, and end node is an inline node, set end offset to the index of 5433 // end node, then set end node to its parent and continue this loop 5434 // from the beginning." 5435 if (endOffset == 0 && inSameEditingHost(endNode, endNode.parentNode) && isInlineNode(endNode)) { 5436 endOffset = Dom.getIndexInParent(endNode); 5437 endNode = endNode.parentNode; 5438 continue; 5439 } 5440 5441 // "If end offset is 0, break from this loop." 5442 if (endOffset == 0) { 5443 break; 5444 } 5445 5446 // "Let reference node be the child of end node with index equal to end 5447 // offset minus one." 5448 referenceNode = endNode.childNodes[endOffset - 1]; 5449 5450 // "If reference node is a block node or an Element with no children, 5451 // or is neither an Element nor a Text node, break from this loop." 5452 if (isBlockNode(referenceNode) || (referenceNode.nodeType == $_.Node.ELEMENT_NODE && !referenceNode.hasChildNodes()) || (referenceNode.nodeType != $_.Node.ELEMENT_NODE && referenceNode.nodeType != $_.Node.TEXT_NODE)) { 5453 break; 5454 } 5455 5456 // "Set end node to reference node and end offset to the length of 5457 // reference node." 5458 endNode = referenceNode; 5459 endOffset = getNodeLength(referenceNode); 5460 } 5461 5462 // "If (end node, end offset) is not after (start node, start offset), set 5463 // range's end to its start and abort these steps." 5464 if (getPosition(endNode, endOffset, startNode, startOffset) !== "after") { 5465 range.setEnd(range.startContainer, range.startOffset); 5466 return range; 5467 } 5468 5469 // "If start node is a Text node and start offset is 0, set start offset to 5470 // the index of start node, then set start node to its parent." 5471 // Commented out for unknown reason 5472 //if (startNode.nodeType == $_.Node.TEXT_NODE && startOffset == 0 && startNode != endNode) { 5473 // startOffset = Dom.getIndexInParent(startNode); 5474 // startNode = startNode.parentNode; 5475 //} 5476 5477 // "If end node is a Text node and end offset is its length, set end offset 5478 // to one plus the index of end node, then set end node to its parent." 5479 if (endNode.nodeType == $_.Node.TEXT_NODE && endOffset == getNodeLength(endNode) && startNode != endNode) { 5480 endOffset = 1 + Dom.getIndexInParent(endNode); 5481 endNode = endNode.parentNode; 5482 } 5483 5484 // "Set range's start to (start node, start offset) and its end to (end 5485 // node, end offset)." 5486 range.setStart(startNode, startOffset); 5487 range.setEnd(endNode, endOffset); 5488 5489 // "Let start block be the start node of range." 5490 var startBlock = range.startContainer; 5491 5492 // "While start block's parent is in the same editing host and start block 5493 // is an inline node, set start block to its parent." 5494 while (inSameEditingHost(startBlock, startBlock.parentNode) && isInlineNode(startBlock)) { 5495 startBlock = startBlock.parentNode; 5496 5497 } 5498 5499 // "If start block is neither a block node nor an editing host, or "span" 5500 // is not an allowed child of start block, or start block is a td or th, 5501 // set start block to null." 5502 if ((!isBlockNode(startBlock) && !isEditingHost(startBlock)) || !isAllowedChild("span", startBlock) || isHtmlElementInArray(startBlock, ["td", "th"])) { 5503 startBlock = null; 5504 } 5505 5506 // "Let end block be the end node of range." 5507 var endBlock = range.endContainer; 5508 5509 // "While end block's parent is in the same editing host and end block is 5510 // an inline node, set end block to its parent." 5511 while (inSameEditingHost(endBlock, endBlock.parentNode) && isInlineNode(endBlock)) { 5512 endBlock = endBlock.parentNode; 5513 } 5514 5515 // "If end block is neither a block node nor an editing host, or "span" is 5516 // not an allowed child of end block, or end block is a td or th, set end 5517 // block to null." 5518 if ((!isBlockNode(endBlock) && !isEditingHost(endBlock)) || !isAllowedChild("span", endBlock) || isHtmlElementInArray(endBlock, ["td", "th"])) { 5519 endBlock = null; 5520 } 5521 5522 // "Record current states and values, and let overrides be the result." 5523 var overrides = recordCurrentStatesAndValues(range); 5524 var parent_; 5525 // "If start node and end node are the same, and start node is an editable 5526 // Text node:" 5527 if (startNode == endNode && isEditable(startNode) && startNode.nodeType == $_.Node.TEXT_NODE) { 5528 // "Let parent be the parent of node." 5529 parent_ = startNode.parentNode; 5530 5531 // "Call deleteData(start offset, end offset − start offset) on start 5532 // node." 5533 startNode.deleteData(startOffset, endOffset - startOffset); 5534 5535 // if deleting the text moved two spaces together, we replace the left one by a , which makes the two spaces a visible 5536 // two space sequence 5537 if (startOffset > 0 && startNode.data.substr(startOffset - 1, 1) === ' ' && startOffset < startNode.data.length && startNode.data.substr(startOffset, 1) === ' ') { 5538 startNode.replaceData(startOffset - 1, 1, '\xa0'); 5539 } 5540 5541 // "Canonicalize whitespace at (start node, start offset)." 5542 canonicalizeWhitespace(startNode, startOffset); 5543 5544 // "Set range's end to its start." 5545 // Ok, also set the range's start to its start, because modifying the text 5546 // might have somehow corrupted the range 5547 range.setStart(range.startContainer, range.startOffset); 5548 range.setEnd(range.startContainer, range.startOffset); 5549 5550 // "Restore states and values from overrides." 5551 restoreStatesAndValues(overrides, range); 5552 5553 // "If parent is editable or an editing host, is not an inline node, 5554 // and has no children, call createElement("br") on the context object 5555 // and append the result as the last child of parent." 5556 // only do this, if the offsetHeight is 0 5557 if ((isEditable(parent_) || isEditingHost(parent_)) && !isInlineNode(parent_)) { 5558 ensureContainerEditable(parent_); 5559 } 5560 5561 // "Abort these steps." 5562 return range; 5563 } 5564 5565 // "If start node is an editable Text node, call deleteData() on it, with 5566 // start offset as the first argument and (length of start node − start 5567 // offset) as the second argument." 5568 if (isEditable(startNode) && startNode.nodeType == $_.Node.TEXT_NODE) { 5569 startNode.deleteData(startOffset, getNodeLength(startNode) - startOffset); 5570 } 5571 5572 // "Let node list be a list of nodes, initially empty." 5573 // 5574 // "For each node contained in range, append node to node list if the last 5575 // member of node list (if any) is not an ancestor of node; node is 5576 // editable; and node is not a thead, tbody, tfoot, tr, th, or td." 5577 var nodeList = getContainedNodes( 5578 range, 5579 function (node) { 5580 return isEditable(node) && !isHtmlElementInArray(node, ["thead", "tbody", "tfoot", "tr", "th", "td"]); 5581 } 5582 ); 5583 5584 // "For each node in node list:" 5585 for (i = 0; i < nodeList.length; i++) { 5586 var node = nodeList[i]; 5587 5588 // "Let parent be the parent of node." 5589 parent_ = node.parentNode; 5590 5591 // "Remove node from parent." 5592 parent_.removeChild(node); 5593 5594 // "If strip wrappers is true or parent is not an ancestor container of 5595 // start node, while parent is an editable inline node with length 0, 5596 // let grandparent be the parent of parent, then remove parent from 5597 // grandparent, then set parent to grandparent." 5598 if (stripWrappers || (!isAncestor(parent_, startNode) && parent_ != startNode)) { 5599 while (isEditable(parent_) && isInlineNode(parent_) && getNodeLength(parent_) == 0) { 5600 var grandparent = parent_.parentNode; 5601 grandparent.removeChild(parent_); 5602 parent_ = grandparent; 5603 } 5604 } 5605 5606 // "If parent is editable or an editing host, is not an inline node, 5607 // and has no children, call createElement("br") on the context object 5608 // and append the result as the last child of parent." 5609 // only do this, if the offsetHeight is 0 5610 if ((isEditable(parent_) || isEditingHost(parent_)) && !isInlineNode(parent_)) { 5611 ensureContainerEditable(parent_); 5612 } 5613 } 5614 5615 // "If end node is an editable Text node, call deleteData(0, end offset) on 5616 // it." 5617 if (isEditable(endNode) && endNode.nodeType == $_.Node.TEXT_NODE) { 5618 endNode.deleteData(0, endOffset); 5619 } 5620 5621 // "Canonicalize whitespace at range's start." 5622 canonicalizeWhitespace(range.startContainer, range.startOffset); 5623 5624 // "Canonicalize whitespace at range's end." 5625 canonicalizeWhitespace(range.endContainer, range.endOffset); 5626 5627 // A reference to the position where a node is removed. 5628 var pos; 5629 5630 // "If block merging is false, or start block or end block is null, or 5631 // start block is not in the same editing host as end block, or start block 5632 // and end block are the same:" 5633 if (!blockMerging || !startBlock || !endBlock || !inSameEditingHost(startBlock, endBlock) || startBlock == endBlock) { 5634 // "Set range's end to its start." 5635 range.setEnd(range.startContainer, range.startOffset); 5636 5637 // Calling delete on the give markup: 5638 // <editable><block><br>[]</block></editable> 5639 // should result in: 5640 // <editable>[]</editable> 5641 var block = startBlock || endBlock; 5642 if (isEmptyOnlyChildOfEditingHost(block)) { 5643 pos = removeNode(block); 5644 range.setStart(pos.node, pos.offset); 5645 range.setEnd(pos.node, pos.offset); 5646 } 5647 5648 // "Restore states and values from overrides." 5649 restoreStatesAndValues(overrides, range); 5650 5651 // "Abort these steps." 5652 return range; 5653 } 5654 5655 // "If start block has one child, which is a collapsed block prop, remove 5656 // its child from it." 5657 if (startBlock.children.length == 1 && isCollapsedBlockProp(startBlock.firstChild)) { 5658 startBlock.removeChild(startBlock.firstChild); 5659 } 5660 5661 // "If end block has one child, which is a collapsed block prop, remove its 5662 // child from it." 5663 if (endBlock.children.length == 1 && isCollapsedBlockProp(endBlock.firstChild)) { 5664 endBlock.removeChild(endBlock.firstChild); 5665 } 5666 5667 var values; 5668 // "If start block is an ancestor of end block:" 5669 if (isAncestor(startBlock, endBlock)) { 5670 // "Let reference node be end block." 5671 referenceNode = endBlock; 5672 5673 // "While reference node is not a child of start block, set reference 5674 // node to its parent." 5675 while (referenceNode.parentNode != startBlock) { 5676 referenceNode = referenceNode.parentNode; 5677 } 5678 5679 // "Set the start and end of range to (start block, index of reference 5680 // node)." 5681 range.setStart(startBlock, Dom.getIndexInParent(referenceNode)); 5682 range.setEnd(startBlock, Dom.getIndexInParent(referenceNode)); 5683 5684 // "If end block has no children:" 5685 if (!endBlock.hasChildNodes()) { 5686 // "While end block is editable and is the only child of its parent 5687 5688 // and is not a child of start block, let parent equal end block, 5689 // then remove end block from parent, then set end block to 5690 // parent." 5691 while (isEditable(endBlock) && endBlock.parentNode.childNodes.length == 1 && endBlock.parentNode != startBlock) { 5692 parent_ = endBlock; 5693 parent_.removeChild(endBlock); 5694 endBlock = parent_; 5695 } 5696 5697 // "If end block is editable and is not an inline node, and its 5698 // previousSibling and nextSibling are both inline nodes, call 5699 // createElement("br") on the context object and insert it into end 5700 // block's parent immediately after end block." 5701 5702 if (isEditable(endBlock) && !isInlineNode(endBlock) && isInlineNode(endBlock.previousSibling) && isInlineNode(endBlock.nextSibling)) { 5703 endBlock.parentNode.insertBefore(document.createElement("br"), endBlock.nextSibling); 5704 } 5705 5706 // "If end block is editable, remove it from its parent." 5707 if (isEditable(endBlock)) { 5708 endBlock.parentNode.removeChild(endBlock); 5709 } 5710 5711 // "Restore states and values from overrides." 5712 restoreStatesAndValues(overrides, range); 5713 5714 // "Abort these steps." 5715 return range; 5716 } 5717 5718 // "If end block's firstChild is not an inline node, restore states and 5719 // values from overrides, then abort these steps." 5720 if (!isInlineNode(endBlock.firstChild)) { 5721 restoreStatesAndValues(overrides, range); 5722 return range; 5723 } 5724 5725 // "Let children be a list of nodes, initially empty." 5726 var children = []; 5727 5728 // "Append the first child of end block to children." 5729 children.push(endBlock.firstChild); 5730 5731 // "While children's last member is not a br, and children's last 5732 // member's nextSibling is an inline node, append children's last 5733 // member's nextSibling to children." 5734 while (!isNamedHtmlElement(children[children.length - 1], "br") && isInlineNode(children[children.length - 1].nextSibling)) { 5735 children.push(children[children.length - 1].nextSibling); 5736 } 5737 5738 // "Record the values of children, and let values be the result." 5739 values = recordValues(children); 5740 5741 // "While children's first member's parent is not start block, split 5742 // the parent of children." 5743 while (children[0].parentNode != startBlock) { 5744 splitParent(children, range); 5745 } 5746 5747 // "If children's first member's previousSibling is an editable br, 5748 // remove that br from its parent." 5749 if (isEditable(children[0].previousSibling) && isNamedHtmlElement(children[0].previousSibling, "br")) { 5750 children[0].parentNode.removeChild(children[0].previousSibling); 5751 } 5752 5753 // "Otherwise, if start block is a descendant of end block:" 5754 } else if (isDescendant(startBlock, endBlock)) { 5755 // "Set the start and end of range to (start block, length of start 5756 // block)." 5757 range.setStart(startBlock, getNodeLength(startBlock)); 5758 range.setEnd(startBlock, getNodeLength(startBlock)); 5759 5760 // "Let reference node be start block." 5761 referenceNode = startBlock; 5762 5763 // "While reference node is not a child of end block, set reference 5764 // node to its parent." 5765 while (referenceNode.parentNode != endBlock) { 5766 referenceNode = referenceNode.parentNode; 5767 } 5768 5769 // "If reference node's nextSibling is an inline node and start block's 5770 // lastChild is a br, remove start block's lastChild from it." 5771 if (isInlineNode(referenceNode.nextSibling) && isNamedHtmlElement(startBlock.lastChild, "br")) { 5772 startBlock.removeChild(startBlock.lastChild); 5773 } 5774 5775 // "Let nodes to move be a list of nodes, initially empty." 5776 var nodesToMove = []; 5777 5778 // "If reference node's nextSibling is neither null nor a br nor a 5779 // block node, append it to nodes to move." 5780 if (referenceNode.nextSibling && !isNamedHtmlElement(referenceNode.nextSibling, "br") && !isBlockNode(referenceNode.nextSibling)) { 5781 nodesToMove.push(referenceNode.nextSibling); 5782 } 5783 5784 // "While nodes to move is nonempty and its last member's nextSibling 5785 // is neither null nor a br nor a block node, append it to nodes to 5786 // move." 5787 if (nodesToMove.length && nodesToMove[nodesToMove.length - 1].nextSibling && !isNamedHtmlElement(nodesToMove[nodesToMove.length - 1].nextSibling, "br") && !isBlockNode(nodesToMove[nodesToMove.length - 1].nextSibling)) { 5788 nodesToMove.push(nodesToMove[nodesToMove.length - 1].nextSibling); 5789 } 5790 5791 // "Record the values of nodes to move, and let values be the result." 5792 values = recordValues(nodesToMove); 5793 5794 // "For each node in nodes to move, append node as the last child of 5795 // start block, preserving ranges." 5796 $_(nodesToMove).forEach(function (node) { 5797 movePreservingRanges(node, startBlock, -1, range); 5798 }); 5799 5800 // "If the nextSibling of reference node is a br, remove it from its 5801 // parent." 5802 if (isNamedHtmlElement(referenceNode.nextSibling, "br")) { 5803 referenceNode.parentNode.removeChild(referenceNode.nextSibling); 5804 } 5805 5806 // "Otherwise:" 5807 } else { 5808 // "Set the start and end of range to (start block, length of start 5809 // block)." 5810 range.setStart(startBlock, getNodeLength(startBlock)); 5811 range.setEnd(startBlock, getNodeLength(startBlock)); 5812 5813 // "If end block's firstChild is an inline node and start block's 5814 // lastChild is a br, remove start block's lastChild from it." 5815 if (isInlineNode(endBlock.firstChild) && isNamedHtmlElement(startBlock.lastChild, "br")) { 5816 startBlock.removeChild(startBlock.lastChild); 5817 } 5818 5819 // "Record the values of end block's children, and let values be the 5820 // result." 5821 values = recordValues([].slice.call(toArray(endBlock.childNodes))); 5822 5823 // "While end block has children, append the first child of end block 5824 // to start block, preserving ranges." 5825 while (endBlock.hasChildNodes()) { 5826 movePreservingRanges(endBlock.firstChild, startBlock, -1, range); 5827 } 5828 5829 // "While end block has no children, let parent be the parent of end 5830 // block, then remove end block from parent, then set end block to 5831 // parent." 5832 while (!endBlock.hasChildNodes()) { 5833 parent_ = endBlock.parentNode; 5834 parent_.removeChild(endBlock); 5835 endBlock = parent_; 5836 } 5837 } 5838 5839 // "Restore the values from values." 5840 restoreValues(values, range); 5841 5842 // Because otherwise calling deleteContents() with the given selection: 5843 // 5844 // <editable><block>[foo</block><block>bar]</block></editable> 5845 // 5846 // would result in: 5847 // 5848 // <editable><block>[]<br /></block></editable> 5849 // 5850 // instead of: 5851 // 5852 // <editable>[]</editable> 5853 // 5854 // Therefore, the below makes it possible to completely empty contents 5855 // of editing hosts via operations like CTRL+A, DEL. 5856 // 5857 // If startBlock is empty, and startBlock is the immediate and only 5858 // child of its parent editing host, then remove startBlock and collapse 5859 // the selection at the beginning of the editing post. 5860 if (isEmptyOnlyChildOfEditingHost(startBlock)) { 5861 pos = removeNode(startBlock); 5862 range.setStart(pos.node, pos.offset); 5863 range.setEnd(pos.node, pos.offset); 5864 startBlock = pos.node; 5865 } 5866 5867 // "If start block has no children, call createElement("br") on the context 5868 // object and append the result as the last child of start block." 5869 ensureContainerEditable(startBlock); 5870 5871 // "Restore states and values from overrides." 5872 restoreStatesAndValues(overrides, range); 5873 5874 return range; 5875 } 5876 5877 // "To remove a node node while preserving its descendants, split the parent of 5878 // node's children if it has any. If it has no children, instead remove it from 5879 // its parent." 5880 function removePreservingDescendants(node, range) { 5881 if (node.hasChildNodes()) { 5882 splitParent([].slice.call(toArray(node.childNodes)), range); 5883 } else { 5884 node.parentNode.removeChild(node); 5885 } 5886 } 5887 5888 /** 5889 * Determines whether a node must be removed to make the insertparagraph command work in list contexts. 5890 * 5891 * @param {Node} node DOM node to check 5892 * @return {boolean} true if the node should be deleted 5893 */ 5894 function isListWhitespaceToRemove(node) { 5895 // no whitespace node –> no need to remove 5896 if (!isWhitespaceNode(node)) { 5897 return false; 5898 } 5899 5900 // always remove whitespace children from ul and ol 5901 if (node.parentNode.nodeName === 'UL' || node.parentNode.nodeName === 'OL') { 5902 return true; 5903 } 5904 5905 if (node.parentNode.nodeName !== 'LI') { 5906 return false; 5907 } 5908 5909 // only remove whitespace from li if it is between (the opening tag/a block level element) 5910 // and (a block level element/the closing tag) 5911 var index = Dom.getIndexInParent(node); 5912 var last = node.parentNode.childNodes.length - 1; 5913 var cleanElements = Dom.blockLevelElements.concat(Dom.listElements); 5914 5915 return (index === 0 || 5916 cleanElements.indexOf(node.previousSibling.nodeName.toLowerCase()) > -1) && 5917 (index === last || 5918 cleanElements.indexOf(node.nextSibling.nodeName.toLowerCase()) > -1); 5919 } 5920 5921 //@} 5922 ///// Indenting and outdenting ///// 5923 //@{ 5924 5925 function cleanLists(node, range) { 5926 // remove any whitespace nodes around list nodes 5927 if (node) { 5928 jQuery(node).find('ul,ol,li').each(function () { 5929 jQuery(this).contents().each(function () { 5930 if (isListWhitespaceToRemove(this)) { 5931 var index = Dom.getIndexInParent(this); 5932 5933 // if the range points to somewhere behind the removed text node, we reduce the offset 5934 if (range.startContainer === this.parentNode && range.startOffset > index) { 5935 range.startOffset--; 5936 } else if (range.startContainer === this) { 5937 5938 // the range starts in the removed text node, let it start right before 5939 range.startContainer = this.parentNode; 5940 range.startOffset = index; 5941 } 5942 // same thing for end of the range 5943 if (range.endContainer === this.parentNode && range.endOffset > index) { 5944 range.endOffset--; 5945 } else if (range.endContainer === this) { 5946 range.endContainer = this.parentNode; 5947 range.endOffset = index; 5948 } 5949 // finally remove the whitespace node 5950 jQuery(this).remove(); 5951 } 5952 }); 5953 }); 5954 } 5955 } 5956 5957 5958 //@} 5959 ///// Indenting and outdenting ///// 5960 //@{ 5961 5962 function indentNodes(nodeList, range) { 5963 // "If node list is empty, do nothing and abort these steps." 5964 if (!nodeList.length) { 5965 return; 5966 } 5967 5968 // "Let first node be the first member of node list." 5969 var firstNode = nodeList[0]; 5970 5971 // "If first node's parent is an ol or ul:" 5972 if (isHtmlElementInArray(firstNode.parentNode, ["OL", "UL"])) { 5973 // "Let tag be the local name of the parent of first node." 5974 var tag = firstNode.parentNode.tagName; 5975 5976 // "Wrap node list, with sibling criteria returning true for an HTML 5977 // element with local name tag and false otherwise, and new parent 5978 // instructions returning the result of calling createElement(tag) on 5979 // the ownerDocument of first node." 5980 wrap( 5981 nodeList, 5982 function (node) { 5983 return isHtmlElement_obsolete(node, tag); 5984 }, 5985 function () { 5986 return firstNode.ownerDocument.createElement(tag); 5987 }, 5988 range 5989 ); 5990 5991 // "Abort these steps." 5992 return; 5993 } 5994 5995 // "Wrap node list, with sibling criteria returning true for a simple 5996 // indentation element and false otherwise, and new parent instructions 5997 // returning the result of calling createElement("blockquote") on the 5998 // ownerDocument of first node. Let new parent be the result." 5999 var newParent = wrap( 6000 nodeList, 6001 function (node) { 6002 return isSimpleIndentationElement(node); 6003 }, 6004 function () { 6005 return firstNode.ownerDocument.createElement("blockquote"); 6006 }, 6007 range 6008 ); 6009 6010 // "Fix disallowed ancestors of new parent." 6011 fixDisallowedAncestors(newParent, range); 6012 } 6013 6014 function outdentNode(node, range) { 6015 // "If node is not editable, abort these steps." 6016 if (!isEditable(node)) { 6017 return; 6018 } 6019 6020 // "If node is a simple indentation element, remove node, preserving its 6021 // descendants. Then abort these steps." 6022 if (isSimpleIndentationElement(node)) { 6023 removePreservingDescendants(node, range); 6024 return; 6025 } 6026 6027 // "If node is an indentation element:" 6028 if (isIndentationElement(node)) { 6029 // "Unset the class and dir attributes of node, if any." 6030 node.removeAttribute("class"); 6031 node.removeAttribute("dir"); 6032 6033 // "Unset the margin, padding, and border CSS properties of node." 6034 node.style.margin = ""; 6035 node.style.padding = ""; 6036 node.style.border = ""; 6037 if (node.getAttribute("style") == "") { 6038 node.removeAttribute("style"); 6039 } 6040 6041 // "Set the tag name of node to "div"." 6042 setTagName(node, "div", range); 6043 6044 // "Abort these steps." 6045 return; 6046 } 6047 6048 // "Let current ancestor be node's parent." 6049 var currentAncestor = node.parentNode; 6050 6051 // "Let ancestor list be a list of nodes, initially empty." 6052 var ancestorList = []; 6053 6054 // "While current ancestor is an editable Element that is neither a simple 6055 // indentation element nor an ol nor a ul, append current ancestor to 6056 // ancestor list and then set current ancestor to its parent." 6057 while (isEditable(currentAncestor) && currentAncestor.nodeType == $_.Node.ELEMENT_NODE && !isSimpleIndentationElement(currentAncestor) && !isHtmlElementInArray(currentAncestor, ["ol", "ul"])) { 6058 ancestorList.push(currentAncestor); 6059 currentAncestor = currentAncestor.parentNode; 6060 } 6061 6062 // "If current ancestor is not an editable simple indentation element:" 6063 if (!isEditable(currentAncestor) || !isSimpleIndentationElement(currentAncestor)) { 6064 // "Let current ancestor be node's parent." 6065 currentAncestor = node.parentNode; 6066 6067 // "Let ancestor list be the empty list." 6068 ancestorList = []; 6069 6070 // "While current ancestor is an editable Element that is neither an 6071 // indentation element nor an ol nor a ul, append current ancestor to 6072 // ancestor list and then set current ancestor to its parent." 6073 while (isEditable(currentAncestor) && currentAncestor.nodeType == $_.Node.ELEMENT_NODE && !isIndentationElement(currentAncestor) && !isHtmlElementInArray(currentAncestor, ["ol", "ul"])) { 6074 ancestorList.push(currentAncestor); 6075 currentAncestor = currentAncestor.parentNode; 6076 } 6077 } 6078 6079 // "If node is an ol or ul and current ancestor is not an editable 6080 // indentation element:" 6081 if (isHtmlElementInArray(node, ["OL", "UL"]) && (!isEditable(currentAncestor) || !isIndentationElement(currentAncestor))) { 6082 // "Unset the reversed, start, and type attributes of node, if any are 6083 // set." 6084 node.removeAttribute("reversed"); 6085 node.removeAttribute("start"); 6086 node.removeAttribute("type"); 6087 6088 // "Let children be the children of node." 6089 var children = [].slice.call(toArray(node.childNodes)); 6090 6091 // "If node has attributes, and its parent is not an ol or ul, set the 6092 // tag name of node to "div"." 6093 if (node.attributes.length && !isHtmlElementInArray(node.parentNode, ["OL", "UL"])) { 6094 setTagName(node, "div", range); 6095 6096 // "Otherwise:" 6097 } else { 6098 // "Record the values of node's children, and let values be the 6099 // result." 6100 var values = recordValues([].slice.call(toArray(node.childNodes))); 6101 6102 // "Remove node, preserving its descendants." 6103 removePreservingDescendants(node, range); 6104 6105 // "Restore the values from values." 6106 restoreValues(values, range); 6107 } 6108 6109 // "Fix disallowed ancestors of each member of children." 6110 var i; 6111 for (i = 0; i < children.length; i++) { 6112 fixDisallowedAncestors(children[i], range); 6113 } 6114 6115 // "Abort these steps." 6116 return; 6117 } 6118 6119 // "If current ancestor is not an editable indentation element, abort these 6120 // steps." 6121 if (!isEditable(currentAncestor) || !isIndentationElement(currentAncestor)) { 6122 return; 6123 } 6124 6125 // "Append current ancestor to ancestor list." 6126 ancestorList.push(currentAncestor); 6127 6128 // "Let original ancestor be current ancestor." 6129 var originalAncestor = currentAncestor; 6130 6131 // "While ancestor list is not empty:" 6132 while (ancestorList.length) { 6133 // "Let current ancestor be the last member of ancestor list." 6134 // 6135 // "Remove the last member of ancestor list." 6136 currentAncestor = ancestorList.pop(); 6137 6138 // "Let target be the child of current ancestor that is equal to either 6139 // node or the last member of ancestor list." 6140 var target = node.parentNode == currentAncestor ? node : ancestorList[ancestorList.length - 1]; 6141 6142 // "If target is an inline node that is not a br, and its nextSibling 6143 // is a br, remove target's nextSibling from its parent." 6144 if (isInlineNode(target) && !isNamedHtmlElement(target, 'BR') && isNamedHtmlElement(target.nextSibling, "BR")) { 6145 target.parentNode.removeChild(target.nextSibling); 6146 } 6147 6148 // "Let preceding siblings be the preceding siblings of target, and let 6149 // following siblings be the following siblings of target." 6150 6151 var precedingSiblings = [].slice.call(toArray(currentAncestor.childNodes), 0, Dom.getIndexInParent(target)); 6152 var followingSiblings = [].slice.call(toArray(currentAncestor.childNodes), 1 + Dom.getIndexInParent(target)); 6153 6154 // "Indent preceding siblings." 6155 indentNodes(precedingSiblings, range); 6156 6157 // "Indent following siblings." 6158 indentNodes(followingSiblings, range); 6159 } 6160 6161 // "Outdent original ancestor." 6162 outdentNode(originalAncestor, range); 6163 } 6164 6165 6166 //@} 6167 ///// Toggling lists ///// 6168 //@{ 6169 6170 function toggleLists(tagName, range) { 6171 // "Let mode be "disable" if the selection's list state is tag name, and 6172 // "enable" otherwise." 6173 var mode = getSelectionListState() == tagName ? "disable" : "enable"; 6174 6175 tagName = tagName.toUpperCase(); 6176 6177 // "Let other tag name be "ol" if tag name is "ul", and "ul" if tag name is 6178 // "ol"." 6179 var otherTagName = tagName == "OL" ? "UL" : "OL"; 6180 6181 // "Let items be a list of all lis that are ancestor containers of the 6182 // range's start and/or end node." 6183 // 6184 // It's annoying to get this in tree order using functional stuff without 6185 // doing getDescendants(document), which is slow, so I do it imperatively. 6186 var items = []; 6187 (function () { 6188 var ancestorContainer; 6189 for (ancestorContainer = range.endContainer; 6190 ancestorContainer != range.commonAncestorContainer; 6191 ancestorContainer = ancestorContainer.parentNode) { 6192 if (isNamedHtmlElement(ancestorContainer, "li")) { 6193 items.unshift(ancestorContainer); 6194 } 6195 6196 } 6197 for (ancestorContainer = range.startContainer; 6198 ancestorContainer; 6199 ancestorContainer = ancestorContainer.parentNode) { 6200 if (isNamedHtmlElement(ancestorContainer, "li")) { 6201 items.unshift(ancestorContainer); 6202 } 6203 } 6204 }()); 6205 6206 // "For each item in items, normalize sublists of item." 6207 $_(items).forEach(function (thisArg) { 6208 normalizeSublists(thisArg, range); 6209 }); 6210 6211 // "Block-extend the range, and let new range be the result." 6212 var newRange = blockExtend(range); 6213 6214 // "If mode is "enable", then let lists to convert consist of every 6215 // editable HTML element with local name other tag name that is contained 6216 // in new range, and for every list in lists to convert:" 6217 if (mode == "enable") { 6218 $_(getAllContainedNodes(newRange, function (node) { 6219 return isEditable(node) && isHtmlElement_obsolete(node, otherTagName); 6220 })).forEach(function (list) { 6221 // "If list's previousSibling or nextSibling is an editable HTML 6222 // element with local name tag name:" 6223 if ((isEditable(list.previousSibling) && isHtmlElement_obsolete(list.previousSibling, tagName)) || (isEditable(list.nextSibling) && isHtmlElement_obsolete(list.nextSibling, tagName))) { 6224 // "Let children be list's children." 6225 var children = [].slice.call(toArray(list.childNodes)); 6226 6227 // "Record the values of children, and let values be the 6228 // result." 6229 var values = recordValues(children); 6230 6231 // "Split the parent of children." 6232 splitParent(children, range); 6233 6234 // "Wrap children, with sibling criteria returning true for an 6235 // HTML element with local name tag name and false otherwise." 6236 wrap( 6237 children, 6238 function (node) { 6239 return isHtmlElement_obsolete(node, tagName); 6240 }, 6241 function () { 6242 return null; 6243 }, 6244 range 6245 ); 6246 6247 // "Restore the values from values." 6248 restoreValues(values, range); 6249 6250 // "Otherwise, set the tag name of list to tag name." 6251 } else { 6252 setTagName(list, tagName, range); 6253 } 6254 }); 6255 } 6256 6257 // "Let node list be a list of nodes, initially empty." 6258 // 6259 // "For each node node contained in new range, if node is editable; the 6260 // last member of node list (if any) is not an ancestor of node; node 6261 // is not an indentation element; and either node is an ol or ul, or its 6262 // parent is an ol or ul, or it is an allowed child of "li"; then append 6263 // node to node list." 6264 var nodeList = getContainedNodes(newRange, function (node) { 6265 return isEditable(node) && !isIndentationElement(node) && (isHtmlElementInArray(node, ["OL", "UL"]) || isHtmlElementInArray(node.parentNode, ["OL", "UL"]) || isAllowedChild(node, "li")); 6266 }); 6267 6268 // "If mode is "enable", remove from node list any ol or ul whose parent is 6269 // not also an ol or ul." 6270 if (mode == "enable") { 6271 nodeList = $_(nodeList).filter(function (node) { 6272 return !isHtmlElementInArray(node, ["ol", "ul"]) || isHtmlElementInArray(node.parentNode, ["ol", "ul"]); 6273 }); 6274 } 6275 6276 // "If mode is "disable", then while node list is not empty:" 6277 var sublist, values; 6278 6279 function createLi() { 6280 return document.createElement("li"); 6281 } 6282 6283 function isOlUl(node) { 6284 return isHtmlElementInArray(node, ["ol", "ul"]); 6285 } 6286 6287 function makeIsElementPred(tagName) { 6288 return function (node) { 6289 return isHtmlElement_obsolete(node, tagName); 6290 }; 6291 } 6292 6293 function makeCreateElement(tagName) { 6294 return function () { 6295 return document.createElement(tagName); 6296 }; 6297 } 6298 6299 function makeCreateElementSublist(tagName, sublist, range) { 6300 return function () { 6301 // "If sublist's first member's parent is not an editable 6302 // simple indentation element, or sublist's first member's 6303 // parent's previousSibling is not an editable HTML element 6304 // with local name tag name, call createElement(tag name) 6305 // on the context object and return the result." 6306 if (!isEditable(sublist[0].parentNode) || !isSimpleIndentationElement(sublist[0].parentNode) || !isEditable(sublist[0].parentNode.previousSibling) || !isHtmlElement_obsolete(sublist[0].parentNode.previousSibling, tagName)) { 6307 return document.createElement(tagName); 6308 } 6309 6310 // "Let list be sublist's first member's parent's 6311 // previousSibling." 6312 var list = sublist[0].parentNode.previousSibling; 6313 6314 // "Normalize sublists of list's lastChild." 6315 normalizeSublists(list.lastChild, range); 6316 6317 // "If list's lastChild is not an editable HTML element 6318 // with local name tag name, call createElement(tag name) 6319 // on the context object, and append the result as the last 6320 // child of list." 6321 if (!isEditable(list.lastChild) || !isHtmlElement_obsolete(list.lastChild, tagName)) { 6322 list.appendChild(document.createElement(tagName)); 6323 } 6324 6325 // "Return the last child of list." 6326 return list.lastChild; 6327 }; 6328 } 6329 6330 if (mode == "disable") { 6331 while (nodeList.length) { 6332 // "Let sublist be an empty list of nodes." 6333 sublist = []; 6334 6335 // "Remove the first member from node list and append it to 6336 // sublist." 6337 sublist.push(nodeList.shift()); 6338 6339 // "If the first member of sublist is an HTML element with local 6340 // name tag name, outdent it and continue this loop from the 6341 // beginning." 6342 if (isHtmlElement_obsolete(sublist[0], tagName)) { 6343 outdentNode(sublist[0], range); 6344 continue; 6345 } 6346 6347 // "While node list is not empty, and the first member of node list 6348 // is the nextSibling of the last member of sublist and is not an 6349 // HTML element with local name tag name, remove the first member 6350 // from node list and append it to sublist." 6351 while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling && !isHtmlElement_obsolete(nodeList[0], tagName)) { 6352 sublist.push(nodeList.shift()); 6353 } 6354 6355 // "Record the values of sublist, and let values be the result." 6356 values = recordValues(sublist); 6357 6358 // "Split the parent of sublist." 6359 splitParent(sublist, range); 6360 6361 // "Fix disallowed ancestors of each member of sublist." 6362 var i; 6363 for (i = 0; i < sublist.length; i++) { 6364 fixDisallowedAncestors(sublist[i], range); 6365 } 6366 6367 // "Restore the values from values." 6368 restoreValues(values, range); 6369 } 6370 6371 // "Otherwise, while node list is not empty:" 6372 } else { 6373 while (nodeList.length) { 6374 // "Let sublist be an empty list of nodes." 6375 sublist = []; 6376 6377 // "While either sublist is empty, or node list is not empty and 6378 // its first member is the nextSibling of sublist's last member:" 6379 while (!sublist.length || (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling)) { 6380 // "If node list's first member is a p or div, set the tag name 6381 // of node list's first member to "li", and append the result 6382 // to sublist. Remove the first member from node list." 6383 if (isHtmlElementInArray(nodeList[0], ["p", "div"])) { 6384 sublist.push(setTagName(nodeList[0], "li", range)); 6385 nodeList.shift(); 6386 6387 // "Otherwise, if the first member of node list is an li or ol 6388 // or ul, remove it from node list and append it to sublist." 6389 } else if (isHtmlElementInArray(nodeList[0], ["li", "ol", "ul"])) { 6390 sublist.push(nodeList.shift()); 6391 6392 // "Otherwise:" 6393 } else { 6394 // "Let nodes to wrap be a list of nodes, initially empty." 6395 var nodesToWrap = []; 6396 6397 // "While nodes to wrap is empty, or node list is not empty 6398 // and its first member is the nextSibling of nodes to 6399 // wrap's last member and the first member of node list is 6400 // an inline node and the last member of nodes to wrap is 6401 // an inline node other than a br, remove the first member 6402 // from node list and append it to nodes to wrap." 6403 while (!nodesToWrap.length || (nodeList.length && nodeList[0] == nodesToWrap[nodesToWrap.length - 1].nextSibling && isInlineNode(nodeList[0]) && isInlineNode(nodesToWrap[nodesToWrap.length - 1]) && !isNamedHtmlElement(nodesToWrap[nodesToWrap.length - 1], "br"))) { 6404 nodesToWrap.push(nodeList.shift()); 6405 } 6406 6407 // "Wrap nodes to wrap, with new parent instructions 6408 // returning the result of calling createElement("li") on 6409 // the context object. Append the result to sublist." 6410 sublist.push(wrap( 6411 nodesToWrap, 6412 undefined, 6413 createLi, 6414 range 6415 )); 6416 } 6417 } 6418 6419 // "If sublist's first member's parent is an HTML element with 6420 // local name tag name, or if every member of sublist is an ol or 6421 // ul, continue this loop from the beginning." 6422 if (isHtmlElement_obsolete(sublist[0].parentNode, tagName) || $_(sublist).every(isOlUl)) { 6423 continue; 6424 } 6425 6426 // "If sublist's first member's parent is an HTML element with 6427 // local name other tag name:" 6428 if (isHtmlElement_obsolete(sublist[0].parentNode, otherTagName)) { 6429 // "Record the values of sublist, and let values be the 6430 // result." 6431 values = recordValues(sublist); 6432 6433 // "Split the parent of sublist." 6434 splitParent(sublist, range); 6435 6436 // "Wrap sublist, with sibling criteria returning true for an 6437 // HTML element with local name tag name and false otherwise, 6438 // and new parent instructions returning the result of calling 6439 // createElement(tag name) on the context object." 6440 wrap( 6441 sublist, 6442 makeIsElementPred(tagName), 6443 makeCreateElement(tagName), 6444 range 6445 ); 6446 6447 // "Restore the values from values." 6448 restoreValues(values, range); 6449 6450 // "Continue this loop from the beginning." 6451 continue; 6452 } 6453 6454 // "Wrap sublist, with sibling criteria returning true for an HTML 6455 // element with local name tag name and false otherwise, and new 6456 // parent instructions being the following:" 6457 // . . . 6458 // "Fix disallowed ancestors of the previous step's result." 6459 fixDisallowedAncestors(wrap( 6460 sublist, 6461 makeIsElementPred(tagName), 6462 makeCreateElementSublist(tagName, sublist, range), 6463 range 6464 ), range); 6465 } 6466 } 6467 } 6468 6469 6470 //@} 6471 ///// Justifying the selection ///// 6472 //@{ 6473 6474 function justifySelection(alignment, range) { 6475 6476 // "Block-extend the active range, and let new range be the result." 6477 var newRange = blockExtend(range); 6478 6479 // "Let element list be a list of all editable Elements contained in new 6480 // range that either has an attribute in the HTML namespace whose local 6481 // name is "align", or has a style attribute that sets "text-align", or is 6482 // a center." 6483 var elementList = getAllContainedNodes(newRange, function (node) { 6484 return node.nodeType == $_.Node.ELEMENT_NODE && isEditable(node) 6485 // Ignoring namespaces here 6486 && (hasAttribute(node, "align") || node.style.textAlign != "" || isNamedHtmlElement(node, 'center')); 6487 }); 6488 6489 // "For each element in element list:" 6490 var i; 6491 for (i = 0; i < elementList.length; i++) { 6492 var element = elementList[i]; 6493 6494 // "If element has an attribute in the HTML namespace whose local name 6495 // is "align", remove that attribute." 6496 element.removeAttribute("align"); 6497 6498 // "Unset the CSS property "text-align" on element, if it's set by a 6499 // style attribute." 6500 element.style.textAlign = ""; 6501 if (element.getAttribute("style") == "") { 6502 element.removeAttribute("style"); 6503 } 6504 6505 // "If element is a div or span or center with no attributes, remove 6506 6507 // it, preserving its descendants." 6508 if (isHtmlElementInArray(element, ["div", "span", "center"]) && !element.attributes.length) { 6509 removePreservingDescendants(element, range); 6510 } 6511 6512 // "If element is a center with one or more attributes, set the tag 6513 // name of element to "div"." 6514 if (isNamedHtmlElement(element, 'center') && element.attributes.length) { 6515 setTagName(element, "div", range); 6516 } 6517 } 6518 6519 // "Block-extend the active range, and let new range be the result." 6520 newRange = blockExtend(globalRange); 6521 6522 // "Let node list be a list of nodes, initially empty." 6523 var nodeList = []; 6524 6525 // "For each node node contained in new range, append node to node list if 6526 // the last member of node list (if any) is not an ancestor of node; node 6527 // is editable; node is an allowed child of "div"; and node's alignment 6528 // value is not alignment." 6529 nodeList = getContainedNodes(newRange, function (node) { 6530 return isEditable(node) && isAllowedChild(node, "div") && getAlignmentValue(node) != alignment; 6531 }); 6532 6533 function makeIsAlignedDiv(alignment) { 6534 return function (node) { 6535 return isNamedHtmlElement(node, 'div') && $_(node.attributes).every(function (attr) { 6536 return (attr.name == "align" && attr.value.toLowerCase() == alignment) || (attr.name == "style" && getStyleLength(node) == 1 && node.style.textAlign == alignment); 6537 }); 6538 }; 6539 } 6540 6541 function makeCreateAlignedDiv(alignment) { 6542 return function () { 6543 var newParent = document.createElement("div"); 6544 newParent.setAttribute("style", "text-align: " + alignment); 6545 return newParent; 6546 }; 6547 } 6548 6549 // "While node list is not empty:" 6550 while (nodeList.length) { 6551 // "Let sublist be a list of nodes, initially empty." 6552 var sublist = []; 6553 6554 // "Remove the first member of node list and append it to sublist." 6555 sublist.push(nodeList.shift()); 6556 6557 // "While node list is not empty, and the first member of node list is 6558 // the nextSibling of the last member of sublist, remove the first 6559 // member of node list and append it to sublist." 6560 while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling) { 6561 sublist.push(nodeList.shift()); 6562 } 6563 6564 // "Wrap sublist. Sibling criteria returns true for any div that has 6565 // one or both of the following two attributes and no other attributes, 6566 // and false otherwise:" 6567 // 6568 // * "An align attribute whose value is an ASCII case-insensitive 6569 // match for alignment. 6570 // * "A style attribute which sets exactly one CSS property 6571 // (including unrecognized or invalid attributes), which is 6572 // "text-align", which is set to alignment. 6573 // 6574 // "New parent instructions are to call createElement("div") on the 6575 // context object, then set its CSS property "text-align" to alignment 6576 // and return the result." 6577 wrap( 6578 sublist, 6579 makeIsAlignedDiv(alignment), 6580 makeCreateAlignedDiv(alignment), 6581 range 6582 ); 6583 } 6584 } 6585 6586 //@} 6587 ///// Move the given collapsed range over adjacent zero-width whitespace characters. 6588 ///// The range is 6589 //@{ 6590 /** 6591 * Move the given collapsed range over adjacent zero-width whitespace characters. 6592 * If the range is not collapsed or is not contained in a text node, it is not modified 6593 * @param range range to modify 6594 * @param forward {Boolean} true to move forward, false to move backward 6595 */ 6596 function moveOverZWSP(range, forward) { 6597 var offset; 6598 if (!range.collapsed) { 6599 return; 6600 } 6601 6602 offset = range.startOffset; 6603 6604 if (forward) { 6605 // check whether the range starts in a text node 6606 if (range.startContainer && range.startContainer.nodeType === $_.Node.TEXT_NODE) { 6607 // move forward (i.e. increase offset) as long as we stay in the text node and have zwsp characters to the right 6608 while (offset < range.startContainer.data.length && range.startContainer.data.charAt(offset) === '\u200b') { 6609 offset++; 6610 } 6611 } 6612 } else { 6613 // check whether the range starts in a text node 6614 if (range.startContainer && range.startContainer.nodeType === $_.Node.TEXT_NODE) { 6615 // move backward (i.e. decrease offset) as long as we stay in the text node and have zwsp characters to the left 6616 while (offset > 0 && range.startContainer.data.charAt(offset - 1) === '\u200b') { 6617 offset--; 6618 } 6619 } 6620 } 6621 6622 // if the offset was changed, set it back to the collapsed range 6623 if (offset !== range.startOffset) { 6624 range.setStart(range.startContainer, offset); 6625 range.setEnd(range.startContainer, offset); 6626 } 6627 } 6628 6629 /** 6630 * implementation of the delete command 6631 * will attempt to delete contents within range if non-collapsed 6632 * or delete the character left of the cursor position if range 6633 * is collapsed. Is used to define the behaviour of the backspace 6634 * button. 6635 * 6636 * @param value is just there for compatibility with the commands api. parameter is ignored. 6637 * @param range the range to execute the delete command for 6638 * @return void 6639 */ 6640 commands["delete"] = { 6641 action: function (value, range) { 6642 var i; 6643 6644 // special behaviour for skipping zero-width whitespaces in IE7 6645 if (Aloha.browser.msie && Aloha.browser.version <= 7) { 6646 moveOverZWSP(range, false); 6647 } 6648 6649 // "If the active range is not collapsed, delete the contents of the 6650 // active range and abort these steps." 6651 if (!range.collapsed) { 6652 deleteContents(range); 6653 return; 6654 } 6655 6656 // "Canonicalize whitespace at (active range's start node, active 6657 // range's start offset)." 6658 canonicalizeWhitespace(range.startContainer, range.startOffset); 6659 6660 // "Let node and offset be the active range's start node and offset." 6661 var node = range.startContainer; 6662 var offset = range.startOffset; 6663 var isBr = false; 6664 var isHr = false; 6665 6666 // "Repeat the following steps:" 6667 while (true) { 6668 // we need to reset isBr and isHr on every interation of the loop 6669 if (offset > 0) { 6670 isBr = isNamedHtmlElement(node.childNodes[offset - 1], "br") || false; 6671 isHr = isNamedHtmlElement(node.childNodes[offset - 1], "hr") || false; 6672 } 6673 // "If offset is zero and node's previousSibling is an editable 6674 // invisible node, remove node's previousSibling from its parent." 6675 if (offset == 0 && isEditable(node.previousSibling) && isInvisible(node.previousSibling)) { 6676 node.parentNode.removeChild(node.previousSibling); 6677 continue; 6678 } 6679 // "Otherwise, if node has a child with index offset − 1 and that 6680 // child is an editable invisible node, remove that child from 6681 // node, then subtract one from offset." 6682 if (0 <= offset - 1 && offset - 1 < node.childNodes.length && isEditable(node.childNodes[offset - 1]) && (isInvisible(node.childNodes[offset - 1]) || isBr || isHr)) { 6683 node.removeChild(node.childNodes[offset - 1]); 6684 6685 offset--; 6686 if (isBr || isHr) { 6687 range.setStart(node, offset); 6688 range.setEnd(node, offset); 6689 return; 6690 } 6691 continue; 6692 6693 } 6694 // "Otherwise, if offset is zero and node is an inline node, or if 6695 // node is an invisible node, set offset to the index of node, then 6696 // set node to its parent." 6697 if ((offset == 0 && isInlineNode(node)) || isInvisible(node)) { 6698 offset = Dom.getIndexInParent(node); 6699 node = node.parentNode; 6700 continue; 6701 } 6702 // "Otherwise, if node has a child with index offset − 1 and that 6703 // child is an editable a, remove that child from node, preserving 6704 // its descendants. Then abort these steps." 6705 if (0 <= offset - 1 && offset - 1 < node.childNodes.length && isEditable(node.childNodes[offset - 1]) && isNamedHtmlElement(node.childNodes[offset - 1], "a")) { 6706 removePreservingDescendants(node.childNodes[offset - 1], range); 6707 return; 6708 6709 } 6710 // "Otherwise, if node has a child with index offset − 1 and that 6711 // child is not a block node or a br or an img, set node to that 6712 // child, then set offset to the length of node." 6713 if (0 <= offset - 1 && offset - 1 < node.childNodes.length && !isBlockNode(node.childNodes[offset - 1]) && !isHtmlElementInArray(node.childNodes[offset - 1], ["br", "img"])) { 6714 node = node.childNodes[offset - 1]; 6715 offset = getNodeLength(node); 6716 continue; 6717 } 6718 // "Otherwise, break from this loop." 6719 // brk is a quick and dirty jslint workaround since I don't want to rewrite this loop 6720 var brk = true; 6721 if (brk) { 6722 break; 6723 } 6724 } 6725 6726 // if the previous node is an aloha-table we want to delete it 6727 var delBlock = getBlockAtPreviousPosition(node, offset); 6728 if (delBlock) { 6729 delBlock.parentNode.removeChild(delBlock); 6730 return; 6731 } 6732 6733 // "If node is a Text node and offset is not zero, call collapse(node, 6734 // offset) on the Selection. Then delete the contents of the range with 6735 // start (node, offset − 1) and end (node, offset) and abort these 6736 // steps." 6737 if (node.nodeType == $_.Node.TEXT_NODE && offset != 0) { 6738 range.setStart(node, offset - 1); 6739 range.setEnd(node, offset - 1); 6740 deleteContents(node, offset - 1, node, offset); 6741 return; 6742 } 6743 6744 // @iebug 6745 // when inserting a special char via the plugin 6746 // there where problems deleting them again with backspace after insertation 6747 // see https://github.com/alohaeditor/Aloha-Editor/issues/517 6748 if (node.nodeType == $_.Node.TEXT_NODE && offset == 0 && Aloha.browser.msie) { 6749 offset = 1; 6750 range.setStart(node, offset); 6751 range.setEnd(node, offset); 6752 range.startOffset = 0; 6753 deleteContents(range); 6754 return; 6755 } 6756 6757 // "If node is an inline node, abort these steps." 6758 if (isInlineNode(node)) { 6759 return; 6760 } 6761 6762 // "If node has a child with index offset − 1 and that child is a br or 6763 // hr or img, call collapse(node, offset) on the Selection. Then delete 6764 // the contents of the range with start (node, offset − 1) and end 6765 // (node, offset) and abort these steps." 6766 if (0 <= offset - 1 && offset - 1 < node.childNodes.length && isHtmlElementInArray(node.childNodes[offset - 1], ["br", "hr", "img"])) { 6767 range.setStart(node, offset); 6768 range.setEnd(node, offset); 6769 deleteContents(range); 6770 return; 6771 } 6772 6773 // "If node is an li or dt or dd and is the first child of its parent, 6774 // and offset is zero:" 6775 if (isHtmlElementInArray(node, ["li", "dt", "dd"]) && node == node.parentNode.firstChild && offset == 0) { 6776 // "Let items be a list of all lis that are ancestors of node." 6777 // 6778 // Remember, must be in tree order. 6779 var items = []; 6780 var ancestor; 6781 for (ancestor = node.parentNode; ancestor; ancestor = ancestor.parentNode) { 6782 if (isNamedHtmlElement(ancestor, 'li')) { 6783 items.unshift(ancestor); 6784 } 6785 } 6786 6787 // "Normalize sublists of each item in items." 6788 for (i = 0; i < items.length; i++) { 6789 normalizeSublists(items[i], range); 6790 } 6791 6792 // "Record the values of the one-node list consisting of node, and 6793 // let values be the result." 6794 var values = recordValues([node]); 6795 6796 // "Split the parent of the one-node list consisting of node." 6797 splitParent([node], range); 6798 6799 // "Restore the values from values." 6800 restoreValues(values, range); 6801 6802 // "If node is a dd or dt, and it is not an allowed child of any of 6803 // its ancestors in the same editing host, set the tag name of node 6804 // to the default single-line container name and let node be the 6805 // result." 6806 if (isHtmlElementInArray(node, ["dd", "dt"]) && $_(getAncestors(node)).every(function (ancestor) { return !inSameEditingHost(node, ancestor) || !isAllowedChild(node, ancestor); })) { 6807 node = setTagName(node, defaultSingleLineContainerName, range); 6808 } 6809 6810 // "Fix disallowed ancestors of node." 6811 fixDisallowedAncestors(node, range); 6812 6813 // fix the lists to be html5 conformant 6814 for (i = 0; i < items.length; i++) { 6815 unNormalizeSublists(items[i].parentNode, range); 6816 } 6817 6818 // "Abort these steps." 6819 return; 6820 } 6821 6822 // "Let start node equal node and let start offset equal offset." 6823 var startNode = node; 6824 var startOffset = offset; 6825 6826 // "Repeat the following steps:" 6827 while (true) { 6828 // "If start offset is zero, set start offset to the index of start 6829 // node and then set start node to its parent." 6830 if (startOffset == 0) { 6831 startOffset = Dom.getIndexInParent(startNode); 6832 startNode = startNode.parentNode; 6833 6834 // "Otherwise, if start node has an editable invisible child with 6835 // index start offset minus one, remove it from start node and 6836 // subtract one from start offset." 6837 } else if (0 <= startOffset - 1 && startOffset - 1 < startNode.childNodes.length && isEditable(startNode.childNodes[startOffset - 1]) && isInvisible(startNode.childNodes[startOffset - 1])) { 6838 startNode.removeChild(startNode.childNodes[startOffset - 1]); 6839 startOffset--; 6840 6841 // "Otherwise, break from this loop." 6842 } else { 6843 break; 6844 } 6845 } 6846 6847 // "If offset is zero, and node has an editable ancestor container in 6848 // the same editing host that's an indentation element:" 6849 if (offset == 0 && $_(getAncestors(node).concat(node)).filter(function (ancestor) { return isEditable(ancestor) && inSameEditingHost(ancestor, node) && isIndentationElement(ancestor); }).length) { 6850 // "Block-extend the range whose start and end are both (node, 0), 6851 // and let new range be the result." 6852 var newRange = Aloha.createRange(); 6853 newRange.setStart(node, 0); 6854 newRange.setEnd(node, 0); 6855 newRange = blockExtend(newRange); 6856 6857 // "Let node list be a list of nodes, initially empty." 6858 // 6859 // "For each node current node contained in new range, append 6860 // current node to node list if the last member of node list (if 6861 // any) is not an ancestor of current node, and current node is 6862 // editable but has no editable descendants." 6863 var nodeList = getContainedNodes(newRange, function (currentNode) { 6864 return isEditable(currentNode) && !hasEditableDescendants(currentNode); 6865 }); 6866 6867 // "Outdent each node in node list." 6868 for (i = 0; i < nodeList.length; i++) { 6869 outdentNode(nodeList[i], range); 6870 } 6871 6872 // "Abort these steps." 6873 return; 6874 } 6875 6876 // "If the child of start node with index start offset is a table, 6877 // abort these steps." 6878 if (isNamedHtmlElement(startNode.childNodes[startOffset], "table")) { 6879 return; 6880 } 6881 6882 // "If start node has a child with index start offset − 1, and that 6883 // child is a table:" 6884 if (0 <= startOffset - 1 && startOffset - 1 < startNode.childNodes.length && isNamedHtmlElement(startNode.childNodes[startOffset - 1], "table")) { 6885 // "Call collapse(start node, start offset − 1) on the context 6886 // object's Selection." 6887 range.setStart(startNode, startOffset - 1); 6888 6889 // "Call extend(start node, start offset) on the context object's 6890 // Selection." 6891 range.setEnd(startNode, startOffset); 6892 6893 // "Abort these steps." 6894 return; 6895 } 6896 6897 // "If offset is zero; and either the child of start node with index 6898 // start offset minus one is an hr, or the child is a br whose 6899 // previousSibling is either a br or not an inline node:" 6900 if (offset == 0 6901 && (isNamedHtmlElement(startNode.childNodes[startOffset - 1], "hr") 6902 || (isNamedHtmlElement(startNode.childNodes[startOffset - 1], "br") 6903 && (isNamedHtmlElement(startNode.childNodes[startOffset - 1].previousSibling, "br") 6904 || !isInlineNode(startNode.childNodes[startOffset - 1].previousSibling))))) { 6905 // "Call collapse(node, offset) on the Selection." 6906 range.setStart(node, offset); 6907 range.setEnd(node, offset); 6908 6909 // "Delete the contents of the range with start (start node, start 6910 // offset − 1) and end (start node, start offset)." 6911 deleteContents(startNode, startOffset - 1, startNode, startOffset); 6912 6913 // "Abort these steps." 6914 return; 6915 } 6916 6917 // "If the child of start node with index start offset is an li or dt 6918 // or dd, and that child's firstChild is an inline node, and start 6919 // offset is not zero:" 6920 if (isHtmlElementInArray(startNode.childNodes[startOffset], ["li", "dt", "dd"]) && isInlineNode(startNode.childNodes[startOffset].firstChild) && startOffset != 0) { 6921 // "Let previous item be the child of start node with index start 6922 // offset minus one." 6923 var previousItem = startNode.childNodes[startOffset - 1]; 6924 6925 // "If previous item's lastChild is an inline node other than a br, 6926 // call createElement("br") on the context object and append the 6927 // result as the last child of previous item." 6928 if (isInlineNode(previousItem.lastChild) && !isNamedHtmlElement(previousItem.lastChild, "br")) { 6929 previousItem.appendChild(document.createElement("br")); 6930 } 6931 6932 // "If previous item's lastChild is an inline node, call 6933 // createElement("br") on the context object and append the result 6934 // as the last child of previous item." 6935 if (isInlineNode(previousItem.lastChild)) { 6936 previousItem.appendChild(document.createElement("br")); 6937 } 6938 } 6939 6940 // "If the child of start node with index start offset is an li or dt 6941 // or dd, and its previousSibling is also an li or dt or dd, set start 6942 // node to its child with index start offset − 1, then set start offset 6943 // to start node's length, then set node to start node's nextSibling, 6944 // then set offset to 0." 6945 if (isHtmlElementInArray(startNode.childNodes[startOffset], ["li", "dt", "dd"]) && isHtmlElementInArray(startNode.childNodes[startOffset - 1], ["li", "dt", "dd"])) { 6946 startNode = startNode.childNodes[startOffset - 1]; 6947 startOffset = getNodeLength(startNode); 6948 node = startNode.nextSibling; 6949 offset = 0; 6950 6951 // "Otherwise, while start node has a child with index start offset 6952 // minus one:" 6953 } else { 6954 while (0 <= startOffset - 1 && startOffset - 1 < startNode.childNodes.length) { 6955 // "If start node's child with index start offset minus one is 6956 // editable and invisible, remove it from start node, then 6957 // subtract one from start offset." 6958 if (isEditable(startNode.childNodes[startOffset - 1]) && isInvisible(startNode.childNodes[startOffset - 1])) { 6959 startNode.removeChild(startNode.childNodes[startOffset - 1]); 6960 startOffset--; 6961 6962 // "Otherwise, set start node to its child with index start 6963 // offset minus one, then set start offset to the length of 6964 // start node." 6965 } else { 6966 startNode = startNode.childNodes[startOffset - 1]; 6967 startOffset = getNodeLength(startNode); 6968 } 6969 } 6970 } 6971 6972 // "Delete the contents of the range with start (start node, start 6973 // offset) and end (node, offset)." 6974 var delRange = Aloha.createRange(); 6975 delRange.setStart(startNode, startOffset); 6976 delRange.setEnd(node, offset); 6977 deleteContents(delRange); 6978 6979 if (!isAncestorContainer(document.body, range.startContainer)) { 6980 if (delRange.startContainer.hasChildNodes() 6981 || delRange.startContainer.nodeType == $_.Node.TEXT_NODE 6982 || isEditingHost(delRange.startContainer)) { 6983 range.setStart(delRange.startContainer, delRange.startOffset); 6984 range.setEnd(delRange.startContainer, delRange.startOffset); 6985 } else { 6986 range.setStart(delRange.startContainer.parentNode, Dom.getIndexInParent(delRange.startContainer)); 6987 range.setEnd(delRange.startContainer.parentNode, Dom.getIndexInParent(delRange.startContainer)); 6988 } 6989 } 6990 } 6991 }; 6992 6993 //@} 6994 ///// The formatBlock command ///// 6995 6996 //@{ 6997 // "A formattable block name is "address", "dd", "div", "dt", "h1", "h2", "h3", 6998 // "h4", "h5", "h6", "p", or "pre"." 6999 var formattableBlockNames = ["address", "dd", "div", "dt", "h1", "h2", "h3", "h4", "h5", "h6", "p", "pre"]; 7000 7001 commands.formatblock = { 7002 action: function (value) { 7003 var i; 7004 7005 // "If value begins with a "<" character and ends with a ">" character, 7006 // remove the first and last characters from it." 7007 if (/^<.*>$/.test(value)) { 7008 value = value.slice(1, -1); 7009 } 7010 7011 // "Let value be converted to ASCII lowercase." 7012 value = value.toLowerCase(); 7013 7014 // "If value is not a formattable block name, abort these steps and do 7015 // nothing." 7016 if ($_(formattableBlockNames).indexOf(value) == -1) { 7017 return; 7018 } 7019 7020 // "Block-extend the active range, and let new range be the result." 7021 var newRange = blockExtend(getActiveRange()); 7022 7023 // "Let node list be an empty list of nodes." 7024 // 7025 // "For each node node contained in new range, append node to node list 7026 // if it is editable, the last member of original node list (if any) is 7027 // not an ancestor of node, node is either a non-list single-line 7028 // container or an allowed child of "p" or a dd or dt, and node is not 7029 // the ancestor of a prohibited paragraph child." 7030 var nodeList = getContainedNodes(newRange, function (node) { 7031 return isEditable(node) && (isNonListSingleLineContainer(node) || isAllowedChild(node, "p") || isHtmlElementInArray(node, ["dd", "dt"])) && !$_(getDescendants(node)).some(isProhibitedParagraphChild); 7032 }); 7033 7034 // "Record the values of node list, and let values be the result." 7035 var values = recordValues(nodeList); 7036 7037 function makeIsEditableElementInSameEditingHostDoesNotContainProhibitedParagraphChildren(node) { 7038 return function (ancestor) { 7039 return (isEditable(ancestor) 7040 && inSameEditingHost(ancestor, node) 7041 && isHtmlElement_obsolete(ancestor, formattableBlockNames) 7042 && !$_(getDescendants(ancestor)).some(isProhibitedParagraphChild)); 7043 }; 7044 } 7045 7046 function makeIsElementWithoutAttributes(value) { 7047 return function (node) { 7048 return isHtmlElement_obsolete(node, value) && !node.attributes.length; 7049 }; 7050 } 7051 7052 function returnFalse() { 7053 return false; 7054 } 7055 7056 function makeCreateElement(value) { 7057 return function () { 7058 return document.createElement(value); 7059 }; 7060 } 7061 7062 // "For each node in node list, while node is the descendant of an 7063 // editable HTML element in the same editing host, whose local name is 7064 // a formattable block name, and which is not the ancestor of a 7065 // prohibited paragraph child, split the parent of the one-node list 7066 // consisting of node." 7067 for (i = 0; i < nodeList.length; i++) { 7068 var node = nodeList[i]; 7069 while ($_(getAncestors(node)).some(makeIsEditableElementInSameEditingHostDoesNotContainProhibitedParagraphChildren(node))) { 7070 splitParent([node], newRange); 7071 } 7072 } 7073 7074 // "Restore the values from values." 7075 restoreValues(values, newRange); 7076 7077 // "While node list is not empty:" 7078 while (nodeList.length) { 7079 var sublist; 7080 7081 // "If the first member of node list is a single-line 7082 // container:" 7083 if (isSingleLineContainer(nodeList[0])) { 7084 // "Let sublist be the children of the first member of node 7085 // list." 7086 sublist = [].slice.call(toArray(nodeList[0].childNodes)); 7087 7088 // "Record the values of sublist, and let values be the 7089 // result." 7090 values = recordValues(sublist); 7091 7092 // "Remove the first member of node list from its parent, 7093 // preserving its descendants." 7094 removePreservingDescendants(nodeList[0], newRange); 7095 7096 // "Restore the values from values." 7097 restoreValues(values, newRange); 7098 7099 // "Remove the first member from node list." 7100 nodeList.shift(); 7101 7102 // "Otherwise:" 7103 } else { 7104 // "Let sublist be an empty list of nodes." 7105 sublist = []; 7106 7107 // "Remove the first member of node list and append it to 7108 // sublist." 7109 sublist.push(nodeList.shift()); 7110 7111 // "While node list is not empty, and the first member of 7112 // node list is the nextSibling of the last member of 7113 // sublist, and the first member of node list is not a 7114 // single-line container, and the last member of sublist is 7115 // not a br, remove the first member of node list and 7116 // append it to sublist." 7117 while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling && !isSingleLineContainer(nodeList[0]) && !isNamedHtmlElement(sublist[sublist.length - 1], "BR")) { 7118 sublist.push(nodeList.shift()); 7119 } 7120 } 7121 7122 // "Wrap sublist. If value is "div" or "p", sibling criteria 7123 // returns false; otherwise it returns true for an HTML element 7124 // with local name value and no attributes, and false otherwise. 7125 // New parent instructions return the result of running 7126 // createElement(value) on the context object. Then fix disallowed 7127 // ancestors of the result." 7128 fixDisallowedAncestors(wrap( 7129 sublist, 7130 jQuery.inArray(value, ["div", "p"]) == -1 ? makeIsElementWithoutAttributes(value) : returnFalse, 7131 makeCreateElement(value), 7132 newRange 7133 ), newRange); 7134 } 7135 }, 7136 indeterm: function () { 7137 // "Block-extend the active range, and let new range be the result." 7138 var newRange = blockExtend(getActiveRange()); 7139 7140 // "Let node list be all visible editable nodes that are contained in 7141 // new range and have no children." 7142 var nodeList = getAllContainedNodes(newRange, function (node) { 7143 return isVisible(node) && isEditable(node) && !node.hasChildNodes(); 7144 }); 7145 7146 // "If node list is empty, return false." 7147 if (!nodeList.length) { 7148 return false; 7149 } 7150 7151 // "Let type be null." 7152 var type = null; 7153 7154 // "For each node in node list:" 7155 var i; 7156 for (i = 0; i < nodeList.length; i++) { 7157 var node = nodeList[i]; 7158 7159 // "While node's parent is editable and in the same editing host as 7160 // node, and node is not an HTML element whose local name is a 7161 // formattable block name, set node to its parent." 7162 while (isEditable(node.parentNode) && inSameEditingHost(node, node.parentNode) && !isHtmlElement_obsolete(node, formattableBlockNames)) { 7163 node = node.parentNode; 7164 } 7165 7166 // "Let current type be the empty string." 7167 var currentType = ""; 7168 7169 // "If node is an editable HTML element whose local name is a 7170 // formattable block name, and node is not the ancestor of a 7171 // prohibited paragraph child, set current type to node's local 7172 // name." 7173 if (isEditable(node) && isHtmlElement_obsolete(node, formattableBlockNames) && !$_(getDescendants(node)).some(isProhibitedParagraphChild)) { 7174 currentType = node.tagName; 7175 } 7176 7177 // "If type is null, set type to current type." 7178 if (type === null) { 7179 type = currentType; 7180 7181 // "Otherwise, if type does not equal current type, return true." 7182 } else if (type != currentType) { 7183 return true; 7184 } 7185 } 7186 7187 // "Return false." 7188 return false; 7189 }, 7190 value: function () { 7191 // "Block-extend the active range, and let new range be the result." 7192 var newRange = blockExtend(getActiveRange()); 7193 7194 // "Let node be the first visible editable node that is contained in 7195 // new range and has no children. If there is no such node, return the 7196 // empty string." 7197 var nodes = getAllContainedNodes(newRange, function (node) { 7198 return isVisible(node) && isEditable(node) && !node.hasChildNodes(); 7199 }); 7200 if (!nodes.length) { 7201 return ""; 7202 } 7203 var node = nodes[0]; 7204 7205 // "While node's parent is editable and in the same editing host as 7206 // node, and node is not an HTML element whose local name is a 7207 // formattable block name, set node to its parent." 7208 while (isEditable(node.parentNode) && inSameEditingHost(node, node.parentNode) && !isHtmlElement_obsolete(node, formattableBlockNames)) { 7209 node = node.parentNode; 7210 } 7211 7212 // "If node is an editable HTML element whose local name is a 7213 // formattable block name, and node is not the ancestor of a prohibited 7214 // paragraph child, return node's local name, converted to ASCII 7215 // lowercase." 7216 if (isEditable(node) && isHtmlElement_obsolete(node, formattableBlockNames) && !$_(getDescendants(node)).some(isProhibitedParagraphChild)) { 7217 return node.tagName.toLowerCase(); 7218 7219 } 7220 7221 // "Return the empty string." 7222 return ""; 7223 } 7224 }; 7225 7226 //@} 7227 ///// The forwardDelete command ///// 7228 //@{ 7229 commands.forwarddelete = { 7230 action: function (value, range) { 7231 // special behaviour for skipping zero-width whitespaces in IE7 7232 if (Aloha.browser.msie && Aloha.browser.version <= 7) { 7233 moveOverZWSP(range, true); 7234 } 7235 7236 // "If the active range is not collapsed, delete the contents of the 7237 // active range and abort these steps." 7238 if (!range.collapsed) { 7239 deleteContents(range); 7240 return; 7241 } 7242 7243 // "Canonicalize whitespace at (active range's start node, active 7244 // range's start offset)." 7245 canonicalizeWhitespace(range.startContainer, range.startOffset); 7246 7247 // "Let node and offset be the active range's start node and offset." 7248 var node = range.startContainer; 7249 var offset = range.startOffset; 7250 var isBr = false; 7251 var isHr = false; 7252 7253 // "Repeat the following steps:" 7254 while (true) { 7255 // check whether the next element is a br or hr 7256 // Commented out for unknown reason. 7257 //if (offset < node.childNodes.length) { 7258 // isBr = isHtmlElement_obsolete(node.childNodes[offset], "br") || false; 7259 // isHr = isHtmlElement_obsolete(node.childNodes[offset], "hr") || false; 7260 //} 7261 7262 // "If offset is the length of node and node's nextSibling is an 7263 // editable invisible node, remove node's nextSibling from its 7264 // parent." 7265 if (offset == getNodeLength(node) && isEditable(node.nextSibling) && isInvisible(node.nextSibling)) { 7266 node.parentNode.removeChild(node.nextSibling); 7267 7268 // "Otherwise, if node has a child with index offset and that child 7269 // is an editable invisible node, remove that child from node." 7270 } else if (offset < node.childNodes.length && isEditable(node.childNodes[offset]) && (isInvisible(node.childNodes[offset]) || isBr || isHr)) { 7271 node.removeChild(node.childNodes[offset]); 7272 if (isBr || isHr) { 7273 ensureContainerEditable(node); 7274 range.setStart(node, offset); 7275 range.setEnd(node, offset); 7276 return; 7277 } 7278 7279 // "Otherwise, if node has a child with index offset and that child 7280 // is a collapsed block prop, add one to offset." 7281 } else if (offset < node.childNodes.length && isCollapsedBlockProp(node.childNodes[offset])) { 7282 offset++; 7283 7284 // "Otherwise, if offset is the length of node and node is an 7285 // inline node, or if node is invisible, set offset to one plus the 7286 // index of node, then set node to its parent." 7287 } else if ((offset == getNodeLength(node) && isInlineNode(node)) || isInvisible(node)) { 7288 offset = 1 + Dom.getIndexInParent(node); 7289 node = node.parentNode; 7290 7291 // "Otherwise, if node has a child with index offset and that child 7292 // is not a block node or a br or an img, set node to that child, 7293 // then set offset to zero." 7294 } else if (offset < node.childNodes.length && !isBlockNode(node.childNodes[offset]) && !isHtmlElementInArray(node.childNodes[offset], ["br", "img"])) { 7295 node = node.childNodes[offset]; 7296 offset = 0; 7297 7298 // "Otherwise, break from this loop." 7299 } else { 7300 break; 7301 } 7302 } 7303 7304 // collapse whitespace in the node, if it is a text node 7305 canonicalizeWhitespace(range.startContainer, range.startOffset); 7306 7307 // if the next node is an aloha-table we want to delete it 7308 var delBlock = getBlockAtNextPosition(node, offset); 7309 if (delBlock) { 7310 delBlock.parentNode.removeChild(delBlock); 7311 return; 7312 } 7313 7314 var endOffset; 7315 // "If node is a Text node and offset is not node's length:" 7316 if (node.nodeType == $_.Node.TEXT_NODE && offset != getNodeLength(node)) { 7317 // "Call collapse(node, offset) on the Selection." 7318 range.setStart(node, offset); 7319 range.setEnd(node, offset); 7320 7321 // "Let end offset be offset plus one." 7322 endOffset = offset + 1; 7323 7324 // "While end offset is not node's length and the end offsetth 7325 // element of node's data has general category M when interpreted 7326 // as a Unicode code point, add one to end offset." 7327 // 7328 // TODO: Not even going to try handling anything beyond the most 7329 // basic combining marks, since I couldn't find a good list. I 7330 // special-case a few Hebrew diacritics too to test basic coverage 7331 // of non-Latin stuff. 7332 while (endOffset != node.length && /^[\u0300-\u036f\u0591-\u05bd\u05c1\u05c2]$/.test(node.data[endOffset])) { 7333 endOffset++; 7334 } 7335 7336 // "Delete the contents of the range with start (node, offset) and 7337 // end (node, end offset)." 7338 deleteContents(node, offset, node, endOffset); 7339 7340 // "Abort these steps." 7341 return; 7342 } 7343 7344 // "If node has a child with index offset and that child is a br or hr 7345 // or img, call collapse(node, offset) on the Selection. Then delete 7346 // the contents of the range with start (node, offset) and end (node, 7347 // offset + 1) and abort these steps." 7348 if (offset < node.childNodes.length && isHtmlElementInArray(node.childNodes[offset], ["br", "hr", "img"])) { 7349 range.setStart(node, offset); 7350 range.setEnd(node, offset); 7351 deleteContents(node, offset, node, offset + 1); 7352 return; 7353 } 7354 7355 // "If node is an inline node, abort these steps." 7356 if (isInlineNode(node)) { 7357 return; 7358 } 7359 7360 // "Let end node equal node and let end offset equal offset." 7361 var endNode = node; 7362 endOffset = offset; 7363 7364 // "Repeat the following steps:" 7365 while (true) { 7366 // "If end offset is the length of end node, set end offset to one 7367 // plus the index of end node and then set end node to its parent." 7368 if (endOffset == getNodeLength(endNode)) { 7369 endOffset = 1 + Dom.getIndexInParent(endNode); 7370 endNode = endNode.parentNode; 7371 7372 // "Otherwise, if end node has a an editable invisible child with 7373 // index end offset, remove it from end node." 7374 } else if (endOffset < endNode.childNodes.length && isEditable(endNode.childNodes[endOffset]) && isInvisible(endNode.childNodes[endOffset])) { 7375 endNode.removeChild(endNode.childNodes[endOffset]); 7376 7377 // "Otherwise, break from this loop." 7378 } else { 7379 break; 7380 } 7381 } 7382 7383 // "If the child of end node with index end offset minus one is a 7384 // table, abort these steps." 7385 if (isNamedHtmlElement(endNode.childNodes[endOffset - 1], "table")) { 7386 return; 7387 } 7388 7389 // "If the child of end node with index end offset is a table:" 7390 if (isNamedHtmlElement(endNode.childNodes[endOffset], "table")) { 7391 // "Call collapse(end node, end offset) on the context object's 7392 // Selection." 7393 range.setStart(endNode, endOffset); 7394 7395 // "Call extend(end node, end offset + 1) on the context object's 7396 // Selection." 7397 range.setEnd(endNode, endOffset + 1); 7398 7399 // "Abort these steps." 7400 return; 7401 } 7402 7403 // "If offset is the length of node, and the child of end node with 7404 // index end offset is an hr or br:" 7405 if (offset == getNodeLength(node) && isHtmlElementInArray(endNode.childNodes[endOffset], ["br", "hr"])) { 7406 // "Call collapse(node, offset) on the Selection." 7407 range.setStart(node, offset); 7408 range.setEnd(node, offset); 7409 7410 // "Delete the contents of the range with end (end node, end 7411 // offset) and end (end node, end offset + 1)." 7412 deleteContents(endNode, endOffset, endNode, endOffset + 1); 7413 7414 // "Abort these steps." 7415 return; 7416 } 7417 7418 // "While end node has a child with index end offset:" 7419 while (endOffset < endNode.childNodes.length) { 7420 // "If end node's child with index end offset is editable and 7421 // invisible, remove it from end node." 7422 if (isEditable(endNode.childNodes[endOffset]) && isInvisible(endNode.childNodes[endOffset])) { 7423 endNode.removeChild(endNode.childNodes[endOffset]); 7424 7425 // "Otherwise, set end node to its child with index end offset and 7426 // set end offset to zero." 7427 } else { 7428 endNode = endNode.childNodes[endOffset]; 7429 endOffset = 0; 7430 } 7431 } 7432 7433 // "Delete the contents of the range with start (node, offset) and end 7434 // (end node, end offset)." 7435 var newRange = deleteContents(node, offset, endNode, endOffset); 7436 range.setStart(newRange.startContainer, newRange.startOffset); 7437 range.setEnd(newRange.endContainer, newRange.endOffset); 7438 } 7439 }; 7440 7441 //@} 7442 ///// The indent command ///// 7443 //@{ 7444 commands.indent = { 7445 7446 action: function () { 7447 // "Let items be a list of all lis that are ancestor containers of the 7448 // active range's start and/or end node." 7449 // 7450 // Has to be in tree order, remember! 7451 var items = []; 7452 var node; 7453 for (node = getActiveRange().endContainer; node != getActiveRange().commonAncestorContainer; node = node.parentNode) { 7454 if (isNamedHtmlElement(node, "LI")) { 7455 items.unshift(node); 7456 } 7457 } 7458 for (node = getActiveRange().startContainer; node != getActiveRange().commonAncestorContainer; node = node.parentNode) { 7459 if (isNamedHtmlElement(node, "LI")) { 7460 items.unshift(node); 7461 } 7462 } 7463 for (node = getActiveRange().commonAncestorContainer; node; node = node.parentNode) { 7464 if (isNamedHtmlElement(node, "LI")) { 7465 items.unshift(node); 7466 } 7467 } 7468 7469 // "For each item in items, normalize sublists of item." 7470 var i; 7471 for (i = 0; i < items.length; i++) { 7472 normalizeSublists(items[i], getActiveRange()); 7473 } 7474 7475 // "Block-extend the active range, and let new range be the result." 7476 var newRange = blockExtend(getActiveRange()); 7477 7478 // "Let node list be a list of nodes, initially empty." 7479 var nodeList = []; 7480 7481 // "For each node node contained in new range, if node is editable and 7482 // is an allowed child of "div" or "ol" and if the last member of node 7483 // list (if any) is not an ancestor of node, append node to node list." 7484 nodeList = getContainedNodes(newRange, function (node) { 7485 return isEditable(node) && (isAllowedChild(node, "div") || isAllowedChild(node, "ol")); 7486 }); 7487 7488 // "If the first member of node list is an li whose parent is an ol or 7489 // ul, and its previousSibling is an li as well, normalize sublists of 7490 // its previousSibling." 7491 if (nodeList.length && isNamedHtmlElement(nodeList[0], "LI") && isHtmlElementInArray(nodeList[0].parentNode, ["OL", "UL"]) && isNamedHtmlElement(nodeList[0].previousSibling, "LI")) { 7492 normalizeSublists(nodeList[0].previousSibling, newRange); 7493 } 7494 7495 // "While node list is not empty:" 7496 7497 while (nodeList.length) { 7498 // "Let sublist be a list of nodes, initially empty." 7499 var sublist = []; 7500 7501 // "Remove the first member of node list and append it to sublist." 7502 sublist.push(nodeList.shift()); 7503 7504 // "While the first member of node list is the nextSibling of the 7505 // last member of sublist, remove the first member of node list and 7506 // append it to sublist." 7507 while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling) { 7508 sublist.push(nodeList.shift()); 7509 } 7510 7511 // "Indent sublist." 7512 indentNodes(sublist, newRange); 7513 } 7514 } 7515 }; 7516 7517 //@} 7518 ///// The insertHorizontalRule command ///// 7519 //@{ 7520 commands.inserthorizontalrule = { 7521 action: function (value, range) { 7522 7523 // "While range's start offset is 0 and its start node's parent is not 7524 // null, set range's start to (parent of start node, index of start 7525 // node)." 7526 while (range.startOffset == 0 && range.startContainer.parentNode) { 7527 range.setStart(range.startContainer.parentNode, Dom.getIndexInParent(range.startContainer)); 7528 } 7529 7530 // "While range's end offset is the length of its end node, and its end 7531 // node's parent is not null, set range's end to (parent of end node, 1 7532 // + index of start node)." 7533 while (range.endOffset == getNodeLength(range.endContainer) && range.endContainer.parentNode) { 7534 range.setEnd(range.endContainer.parentNode, 1 + Dom.getIndexInParent(range.endContainer)); 7535 } 7536 7537 // "Delete the contents of range, with block merging false." 7538 deleteContents(range, { 7539 blockMerging: false 7540 }); 7541 7542 // "If the active range's start node is neither editable nor an editing 7543 // host, abort these steps." 7544 if (!isEditable(getActiveRange().startContainer) && !isEditingHost(getActiveRange().startContainer)) { 7545 return; 7546 } 7547 7548 // "If the active range's start node is a Text node and its start 7549 // offset is zero, set the active range's start and end to (parent of 7550 // start node, index of start node)." 7551 if (getActiveRange().startContainer.nodeType == $_.Node.TEXT_NODE && getActiveRange().startOffset == 0) { 7552 getActiveRange().setStart(getActiveRange().startContainer.parentNode, Dom.getIndexInParent(getActiveRange().startContainer)); 7553 getActiveRange().collapse(true); 7554 } 7555 7556 // "If the active range's start node is a Text node and its start 7557 // offset is the length of its start node, set the active range's start 7558 // and end to (parent of start node, 1 + index of start node)." 7559 if (getActiveRange().startContainer.nodeType == $_.Node.TEXT_NODE && getActiveRange().startOffset == getNodeLength(getActiveRange().startContainer)) { 7560 getActiveRange().setStart(getActiveRange().startContainer.parentNode, 1 + Dom.getIndexInParent(getActiveRange().startContainer)); 7561 getActiveRange().collapse(true); 7562 } 7563 7564 // "Let hr be the result of calling createElement("hr") on the 7565 // context object." 7566 var hr = document.createElement("hr"); 7567 7568 // "Run insertNode(hr) on the range." 7569 range.insertNode(hr); 7570 7571 // "Fix disallowed ancestors of hr." 7572 fixDisallowedAncestors(hr, range); 7573 7574 // "Run collapse() on the Selection, with first argument equal to the 7575 // parent of hr and the second argument equal to one plus the index of 7576 // hr." 7577 // 7578 // Not everyone actually supports collapse(), so we do it manually 7579 // instead. Also, we need to modify the actual range we're given as 7580 // well, for the sake of autoimplementation.html's range-filling-in. 7581 range.setStart(hr.parentNode, 1 + Dom.getIndexInParent(hr)); 7582 range.setEnd(hr.parentNode, 1 + Dom.getIndexInParent(hr)); 7583 Aloha.getSelection().removeAllRanges(); 7584 Aloha.getSelection().addRange(range); 7585 } 7586 }; 7587 7588 /** 7589 * Publish a message for the links that will be inserted at paste. 7590 * @param {DocumentFragment} frag 7591 */ 7592 function publishPastedLinks(frag) { 7593 var children = frag.childNodes; 7594 var links; 7595 var c; 7596 var i; 7597 var len; 7598 7599 for (c = 0; c < children.length; c++) { 7600 links = jQuery(children[c]).find('a'); 7601 for (i = 0, len = links.length; i < len; i++) { 7602 PubSub.pub('aloha.link.pasted', { 7603 href: links[i].getAttribute('href'), 7604 element: links[i] 7605 }); 7606 } 7607 } 7608 } 7609 7610 //@} 7611 ///// The insertHTML command ///// 7612 //@{ 7613 commands.inserthtml = { 7614 action: function (value, range) { 7615 7616 7617 // "Delete the contents of the active range." 7618 deleteContents(range); 7619 7620 // "If the active range's start node is neither editable nor an editing 7621 // host, abort these steps." 7622 if (!isEditable(range.startContainer) && !isEditingHost(range.startContainer)) { 7623 return; 7624 } 7625 7626 // "Let frag be the result of calling createContextualFragment(value) 7627 // on the active range." 7628 var frag = range.createContextualFragment(value); 7629 7630 publishPastedLinks(frag); 7631 7632 // "Let last child be the lastChild of frag." 7633 var lastChild = frag.lastChild; 7634 7635 // "If last child is null, abort these steps." 7636 if (!lastChild) { 7637 return; 7638 } 7639 7640 // "Let descendants be all descendants of frag." 7641 var descendants = getDescendants(frag); 7642 7643 // "If the active range's start node is a block node:" 7644 if (isBlockNode(range.startContainer)) { 7645 // "Let collapsed block props be all editable collapsed block prop 7646 // children of the active range's start node that have index 7647 // greater than or equal to the active range's start offset." 7648 // 7649 // "For each node in collapsed block props, remove node from its 7650 // parent." 7651 $_(range.startContainer.childNodes).filter(function (node, range) { 7652 return isEditable(node) && isCollapsedBlockProp(node) && Dom.getIndexInParent(node) >= range.startOffset; 7653 }, true).forEach(function (node) { 7654 node.parentNode.removeChild(node); 7655 }); 7656 } 7657 7658 // "Call insertNode(frag) on the active range." 7659 range.insertNode(frag); 7660 7661 // "If the active range's start node is a block node with no visible 7662 // children, call createElement("br") on the context object and append 7663 // the result as the last child of the active range's start node." 7664 if (isBlockNode(range.startContainer)) { 7665 ensureContainerEditable(range.startContainer); 7666 } 7667 7668 // "Call collapse() on the context object's Selection, with last 7669 // child's parent as the first argument and one plus its index as the 7670 // second." 7671 range.setStart(lastChild.parentNode, 1 + Dom.getIndexInParent(lastChild)); 7672 range.setEnd(lastChild.parentNode, 1 + Dom.getIndexInParent(lastChild)); 7673 7674 // "Fix disallowed ancestors of each member of descendants." 7675 var i; 7676 for (i = 0; i < descendants.length; i++) { 7677 fixDisallowedAncestors(descendants[i], range); 7678 } 7679 7680 setActiveRange(range); 7681 } 7682 }; 7683 7684 //@} 7685 ///// The insertImage command ///// 7686 //@{ 7687 commands.insertimage = { 7688 action: function (value) { 7689 // "If value is the empty string, abort these steps and do nothing." 7690 if (value === "") { 7691 return; 7692 } 7693 7694 // "Let range be the active range." 7695 var range = getActiveRange(); 7696 7697 // "Delete the contents of range, with strip wrappers false." 7698 deleteContents(range, { 7699 stripWrappers: false 7700 }); 7701 7702 // "If the active range's start node is neither editable nor an editing 7703 // host, abort these steps." 7704 if (!isEditable(getActiveRange().startContainer) && !isEditingHost(getActiveRange().startContainer)) { 7705 return; 7706 } 7707 7708 // "If range's start node is a block node whose sole child is a br, and 7709 // its start offset is 0, remove its start node's child from it." 7710 if (isBlockNode(range.startContainer) && range.startContainer.childNodes.length == 1 && isNamedHtmlElement(range.startContainer.firstChild, "br") && range.startOffset == 0) { 7711 range.startContainer.removeChild(range.startContainer.firstChild); 7712 } 7713 7714 // "Let img be the result of calling createElement("img") on the 7715 // context object." 7716 var img = document.createElement("img"); 7717 7718 // "Run setAttribute("src", value) on img." 7719 img.setAttribute("src", value); 7720 7721 // "Run insertNode(img) on the range." 7722 range.insertNode(img); 7723 7724 // "Run collapse() on the Selection, with first argument equal to the 7725 // parent of img and the second argument equal to one plus the index of 7726 // img." 7727 // 7728 // Not everyone actually supports collapse(), so we do it manually 7729 // instead. Also, we need to modify the actual range we're given as 7730 // well, for the sake of autoimplementation.html's range-filling-in. 7731 range.setStart(img.parentNode, 1 + Dom.getIndexInParent(img)); 7732 range.setEnd(img.parentNode, 1 + Dom.getIndexInParent(img)); 7733 Aloha.getSelection().removeAllRanges(); 7734 Aloha.getSelection().addRange(range); 7735 7736 // IE adds width and height attributes for some reason, so remove those 7737 // to actually do what the spec says. 7738 img.removeAttribute("width"); 7739 img.removeAttribute("height"); 7740 } 7741 }; 7742 7743 //@} 7744 ///// The insertLineBreak command ///// 7745 //@{ 7746 commands.insertlinebreak = { 7747 action: function (value, range) { 7748 // "Delete the contents of the active range, with strip wrappers false." 7749 deleteContents(range, { 7750 stripWrappers: false 7751 }); 7752 7753 // "If the active range's start node is neither editable nor an editing 7754 // host, abort these steps." 7755 if (!isEditable(range.startContainer) && !isEditingHost(range.startContainer)) { 7756 return; 7757 } 7758 7759 // "If the active range's start node is an Element, and "br" is not an 7760 // allowed child of it, abort these steps." 7761 if (range.startContainer.nodeType == $_.Node.ELEMENT_NODE && !isAllowedChild("br", range.startContainer)) { 7762 return; 7763 } 7764 7765 // "If the active range's start node is not an Element, and "br" is not 7766 // an allowed child of the active range's start node's parent, abort 7767 // these steps." 7768 if (range.startContainer.nodeType != $_.Node.ELEMENT_NODE && !isAllowedChild("br", range.startContainer.parentNode)) { 7769 return; 7770 } 7771 7772 // "If the active range's start node is a Text node and its start 7773 // offset is zero, call collapse() on the context object's Selection, 7774 // with first argument equal to the active range's start node's parent 7775 // and second argument equal to the active range's start node's index." 7776 var newNode, newOffset; 7777 if (range.startContainer.nodeType == $_.Node.TEXT_NODE && range.startOffset == 0) { 7778 newNode = range.startContainer.parentNode; 7779 newOffset = Dom.getIndexInParent(range.startContainer); 7780 Aloha.getSelection().collapse(newNode, newOffset); 7781 range.setStart(newNode, newOffset); 7782 range.setEnd(newNode, newOffset); 7783 } 7784 7785 // "If the active range's start node is a Text node and its start 7786 // offset is the length of its start node, call collapse() on the 7787 // context object's Selection, with first argument equal to the active 7788 // range's start node's parent and second argument equal to one plus 7789 // the active range's start node's index." 7790 if (range.startContainer.nodeType == $_.Node.TEXT_NODE && range.startOffset == getNodeLength(range.startContainer)) { 7791 newNode = range.startContainer.parentNode; 7792 newOffset = 1 + Dom.getIndexInParent(range.startContainer); 7793 Aloha.getSelection().collapse(newNode, newOffset); 7794 range.setStart(newNode, newOffset); 7795 range.setEnd(newNode, newOffset); 7796 } 7797 7798 // "Let br be the result of calling createElement("br") on the context 7799 // object." 7800 var br = document.createElement("br"); 7801 7802 // "Call insertNode(br) on the active range." 7803 range.insertNode(br); 7804 7805 // "Call collapse() on the context object's Selection, with br's parent 7806 // as the first argument and one plus br's index as the second 7807 // argument." 7808 Aloha.getSelection().collapse(br.parentNode, 1 + Dom.getIndexInParent(br)); 7809 range.setStart(br.parentNode, 1 + Dom.getIndexInParent(br)); 7810 range.setEnd(br.parentNode, 1 + Dom.getIndexInParent(br)); 7811 7812 // "If br is a collapsed line break, call createElement("br") on the 7813 // context object and let extra br be the result, then call 7814 // insertNode(extra br) on the active range." 7815 if (isCollapsedLineBreak(br)) { 7816 // TODO 7817 range.insertNode(createEndBreak()); 7818 7819 // Compensate for nonstandard implementations of insertNode 7820 Aloha.getSelection().collapse(br.parentNode, 1 + Dom.getIndexInParent(br)); 7821 range.setStart(br.parentNode, 1 + Dom.getIndexInParent(br)); 7822 range.setEnd(br.parentNode, 1 + Dom.getIndexInParent(br)); 7823 } 7824 7825 // IE7 is adding this styles: height: auto; min-height: 0px; max-height: none; 7826 // with that there is the ugly "IE-editable-outline" 7827 if (Aloha.browser.msie && Aloha.browser.version < 8) { 7828 br.parentNode.removeAttribute("style"); 7829 } 7830 } 7831 }; 7832 7833 //@} 7834 ///// The insertOrderedList command ///// 7835 //@{ 7836 commands.insertorderedlist = { 7837 // "Toggle lists with tag name "ol"." 7838 action: function (value, range) { 7839 toggleLists("ol", range); 7840 }, 7841 // "True if the selection's list state is "mixed" or "mixed ol", false 7842 // otherwise." 7843 indeterm: function () { 7844 return (/^mixed( ol)?$/).test(getSelectionListState()); 7845 }, 7846 // "True if the selection's list state is "ol", false otherwise." 7847 state: function () { 7848 return getSelectionListState() == "ol"; 7849 } 7850 }; 7851 7852 var listRelatedElements = { 7853 "LI": true, 7854 "DT": true, 7855 "DD": true 7856 }; 7857 7858 //@} 7859 ///// The insertParagraph command ///// 7860 //@{ 7861 commands.insertparagraph = { 7862 action: function (value, range) { 7863 var i; 7864 7865 // "Delete the contents of the active range." 7866 deleteContents(range); 7867 7868 // clean lists in the editing host, this will remove any whitespace nodes around lists 7869 // because the following algorithm is not prepared to deal with them 7870 cleanLists(getEditingHostOf(range.startContainer), range); 7871 7872 // "If the active range's start node is neither editable nor an editing 7873 // host, abort these steps." 7874 if (!isEditable(range.startContainer) && !isEditingHost(range.startContainer)) { 7875 return; 7876 } 7877 7878 // "Let node and offset be the active range's start node and offset." 7879 var node = range.startContainer; 7880 var offset = range.startOffset; 7881 7882 // "If node is a Text node, and offset is neither 0 nor the length of 7883 // node, call splitText(offset) on node." 7884 if (node.nodeType == $_.Node.TEXT_NODE && offset != 0 && offset != getNodeLength(node)) { 7885 splitText(node, offset); 7886 } 7887 7888 // "If node is a Text node and offset is its length, set offset to one 7889 // plus the index of node, then set node to its parent." 7890 if (node.nodeType == $_.Node.TEXT_NODE && offset == getNodeLength(node)) { 7891 offset = 1 + Dom.getIndexInParent(node); 7892 node = node.parentNode; 7893 } 7894 7895 // "If node is a Text or Comment node, set offset to the index of node, 7896 // then set node to its parent." 7897 if (node.nodeType == $_.Node.TEXT_NODE || node.nodeType == $_.Node.COMMENT_NODE) { 7898 offset = Dom.getIndexInParent(node); 7899 node = node.parentNode; 7900 } 7901 7902 // "Call collapse(node, offset) on the context object's Selection." 7903 Aloha.getSelection().collapse(node, offset); 7904 range.setStart(node, offset); 7905 range.setEnd(node, offset); 7906 7907 // "Let container equal node." 7908 var container = node; 7909 7910 // "While container is not a single-line container, and container's 7911 // parent is editable and in the same editing host as node, set 7912 // container to its parent." 7913 while (!isSingleLineContainer(container) && isEditable(container.parentNode) && inSameEditingHost(node, container.parentNode)) { 7914 container = container.parentNode; 7915 } 7916 7917 // "If container is not editable or not in the same editing host as 7918 // node or is not a single-line container:" 7919 if (!isEditable(container) || !inSameEditingHost(container, node) || !isSingleLineContainer(container)) { 7920 // "Let tag be the default single-line container name." 7921 var tag = defaultSingleLineContainerName; 7922 7923 // "Block-extend the active range, and let new range be the 7924 // result." 7925 var newRange = blockExtend(range); 7926 7927 // "Let node list be a list of nodes, initially empty." 7928 // 7929 // "Append to node list the first node in tree order that is 7930 // contained in new range and is an allowed child of "p", if any." 7931 var nodeList = getContainedNodes(newRange, function (node) { 7932 return isAllowedChild(node, "p"); 7933 }).slice(0, 1); 7934 7935 // "If node list is empty:" 7936 if (!nodeList.length) { 7937 // "If tag is not an allowed child of the active range's start 7938 // node, abort these steps." 7939 if (!isAllowedChild(tag, range.startContainer)) { 7940 return; 7941 } 7942 7943 // "Set container to the result of calling createElement(tag) 7944 // on the context object." 7945 container = document.createElement(tag); 7946 7947 // "Call insertNode(container) on the active range." 7948 range.insertNode(container); 7949 7950 // "Call createElement("br") on the context object, and append 7951 // the result as the last child of container." 7952 // TODO not always 7953 container.appendChild(createEndBreak()); 7954 7955 // "Call collapse(container, 0) on the context object's 7956 // Selection." 7957 // TODO: remove selection from command 7958 Aloha.getSelection().collapse(container, 0); 7959 range.setStart(container, 0); 7960 range.setEnd(container, 0); 7961 7962 // "Abort these steps." 7963 return; 7964 } 7965 7966 // "While the nextSibling of the last member of node list is not 7967 // null and is an allowed child of "p", append it to node list." 7968 while (nodeList[nodeList.length - 1].nextSibling && isAllowedChild(nodeList[nodeList.length - 1].nextSibling, "p")) { 7969 nodeList.push(nodeList[nodeList.length - 1].nextSibling); 7970 } 7971 7972 // "Wrap node list, with sibling criteria returning false and new 7973 // parent instructions returning the result of calling 7974 // createElement(tag) on the context object. Set container to the 7975 // result." 7976 container = wrap( 7977 nodeList, 7978 function () { 7979 return false; 7980 }, 7981 function () { 7982 return document.createElement(tag); 7983 }, 7984 range 7985 ); 7986 } 7987 7988 // If no container has been set yet, it is not possible to insert a paragraph at this position; 7989 // the following steps are skipped in order to prevent critical errors from occurring; 7990 if (!container) { 7991 return; 7992 } 7993 7994 // "If container's local name is "address", "listing", or "pre":" 7995 var oldHeight, newHeight; 7996 if (container.tagName == "ADDRESS" || container.tagName == "LISTING" || container.tagName == "PRE") { 7997 // "Let br be the result of calling createElement("br") on the 7998 // context object." 7999 var br = document.createElement("br"); 8000 8001 // remember the old height 8002 oldHeight = container.offsetHeight; 8003 8004 // "Call insertNode(br) on the active range." 8005 range.insertNode(br); 8006 8007 // determine the new height 8008 newHeight = container.offsetHeight; 8009 8010 // "Call collapse(node, offset + 1) on the context object's 8011 // Selection." 8012 Aloha.getSelection().collapse(node, offset + 1); 8013 range.setStart(node, offset + 1); 8014 range.setEnd(node, offset + 1); 8015 8016 // "If br is the last descendant of container, let br be the result 8017 // of calling createElement("br") on the context object, then call 8018 // insertNode(br) on the active range." (Fix: only do this, if the container height did not change by inserting a single <br/>) 8019 // 8020 // Work around browser bugs: some browsers select the 8021 // newly-inserted node, not per spec. 8022 if (oldHeight == newHeight && !isDescendant(nextNode(br), container)) { 8023 // TODO check 8024 range.insertNode(createEndBreak()); 8025 Aloha.getSelection().collapse(node, offset + 1); 8026 range.setEnd(node, offset + 1); 8027 } 8028 8029 // "Abort these steps." 8030 return; 8031 } 8032 8033 // "If container's local name is "li", "dt", or "dd"; and either it has 8034 // no children or it has a single child and that child is a br:" 8035 if (listRelatedElements[container.tagName] && (!container.hasChildNodes() || (container.childNodes.length == 1 && isNamedHtmlElement(container.firstChild, "br")))) { 8036 // "Split the parent of the one-node list consisting of container." 8037 splitParent([container], range); 8038 8039 // "If container has no children, call createElement("br") on the 8040 // context object and append the result as the last child of 8041 // container." 8042 // only do this, if inserting the br does NOT modify the offset height of the container 8043 // if (!container.hasChildNodes()) { 8044 // var oldHeight = container.offsetHeight, endBr = createEndBreak(); 8045 // container.appendChild(endBr); 8046 // if (container.offsetHeight !== oldHeight) { 8047 // container.removeChild(endBr); 8048 // } 8049 // } 8050 8051 // "If container is a dd or dt, and it is not an allowed child of 8052 // any of its ancestors in the same editing host, set the tag name 8053 // of container to the default single-line container name and let 8054 // container be the result." 8055 if (isHtmlElementInArray(container, ["dd", "dt"]) && $_(getAncestors(container)).every(function (ancestor) { return !inSameEditingHost(container, ancestor) || !isAllowedChild(container, ancestor); })) { 8056 container = setTagName(container, defaultSingleLineContainerName, range); 8057 } 8058 8059 // "Fix disallowed ancestors of container." 8060 fixDisallowedAncestors(container, range); 8061 8062 // fix invalid nested lists 8063 if (isNamedHtmlElement(container, 'li') && isNamedHtmlElement(container.nextSibling, "li") && isHtmlElementInArray(container.nextSibling.firstChild, ["ol", "ul"])) { 8064 // we found a li containing only a br followed by a li containing a list as first element: merge the two li's 8065 var listParent = container.nextSibling, 8066 length = container.nextSibling.childNodes.length; 8067 for (i = 0; i < length; i++) { 8068 // we always move the first child into the container 8069 container.appendChild(listParent.childNodes[0]); 8070 } 8071 listParent.parentNode.removeChild(listParent); 8072 } 8073 8074 // "Abort these steps." 8075 return; 8076 } 8077 8078 // special behaviour when pressing enter in the last empty paragraph, that is nested in a blockquote 8079 if (isNamedHtmlElement(container, "p") 8080 && isNamedHtmlElement(container.parentNode, "blockquote") 8081 && !container.nextSibling 8082 && (!container.hasChildNodes() 8083 || (container.childNodes.length === 1 8084 && isNamedHtmlElement(container.firstChild, "br")))) { 8085 jQuery(container.parentNode).after(container); 8086 return; 8087 } 8088 8089 // "Let new line range be a new range whose start is the same as 8090 // the active range's, and whose end is (container, length of 8091 // container)." 8092 var newLineRange = Aloha.createRange(); 8093 newLineRange.setStart(range.startContainer, range.startOffset); 8094 newLineRange.setEnd(container, getNodeLength(container)); 8095 8096 // "While new line range's start offset is zero and its start node is 8097 // not container, set its start to (parent of start node, index of 8098 // start node)." 8099 while (newLineRange.startOffset == 0 && newLineRange.startContainer != container) { 8100 newLineRange.setStart(newLineRange.startContainer.parentNode, Dom.getIndexInParent(newLineRange.startContainer)); 8101 } 8102 8103 // "While new line range's start offset is the length of its start node 8104 // and its start node is not container, set its start to (parent of 8105 // start node, 1 + index of start node)." 8106 while (newLineRange.startOffset == getNodeLength(newLineRange.startContainer) && newLineRange.startContainer != container) { 8107 newLineRange.setStart(newLineRange.startContainer.parentNode, 1 + Dom.getIndexInParent(newLineRange.startContainer)); 8108 } 8109 8110 // "Let end of line be true if new line range contains either nothing 8111 // or a single br, and false otherwise." 8112 var containedInNewLineRange = getContainedNodes(newLineRange); 8113 var endOfLine = !containedInNewLineRange.length || (containedInNewLineRange.length == 1 && isNamedHtmlElement(containedInNewLineRange[0], "br")); 8114 8115 // "If the local name of container is "h1", "h2", "h3", "h4", "h5", or 8116 // "h6", and end of line is true, let new container name be the default 8117 // single-line container name." 8118 var newContainerName; 8119 if (/^H[1-6]$/.test(container.tagName) && endOfLine) { 8120 newContainerName = defaultSingleLineContainerName; 8121 8122 // "Otherwise, if the local name of container is "dt" and end of line 8123 // is true, let new container name be "dd"." 8124 } else if (container.tagName == "DT" && endOfLine) { 8125 newContainerName = "dd"; 8126 8127 // "Otherwise, if the local name of container is "dd" and end of line 8128 // is true, let new container name be "dt"." 8129 } else if (container.tagName == "DD" && endOfLine) { 8130 newContainerName = "dt"; 8131 8132 // "Otherwise, let new container name be the local name of container." 8133 } else { 8134 newContainerName = container.tagName.toLowerCase(); 8135 } 8136 8137 // "Let new container be the result of calling createElement(new 8138 // container name) on the context object." 8139 var newContainer = document.createElement(newContainerName); 8140 8141 // "Copy all non empty attributes of the container to new container." 8142 copyAttributes(container, newContainer); 8143 8144 // "If new container has an id attribute, unset it." 8145 newContainer.removeAttribute("id"); 8146 8147 // "Insert new container into the parent of container immediately after 8148 // container." 8149 container.parentNode.insertBefore(newContainer, container.nextSibling); 8150 8151 // "Let contained nodes be all nodes contained in new line range." 8152 var containedNodes = getAllContainedNodes(newLineRange); 8153 8154 // "Let frag be the result of calling extractContents() on new line 8155 // range." 8156 var frag = newLineRange.extractContents(); 8157 8158 // "Unset the id attribute (if any) of each Element descendant of frag 8159 // that is not in contained nodes." 8160 var descendants = getDescendants(frag); 8161 for (i = 0; i < descendants.length; i++) { 8162 if (descendants[i].nodeType == $_.Node.ELEMENT_NODE && $_(containedNodes).indexOf(descendants[i]) == -1) { 8163 descendants[i].removeAttribute("id"); 8164 } 8165 } 8166 8167 var fragChildren = [], 8168 fragChild = frag.firstChild; 8169 if (fragChild) { 8170 do { 8171 if (!isWhitespaceNode(fragChild)) { 8172 fragChildren.push(fragChild); 8173 } 8174 } while (null != (fragChild = fragChild.nextSibling)); 8175 } 8176 8177 // if newContainer is a li and frag contains only a list, we add a br in the li (but only if the height would not change) 8178 if (isNamedHtmlElement(newContainer, 'li') && fragChildren.length && isHtmlElementInArray(fragChildren[0], ["ul", "ol"])) { 8179 oldHeight = newContainer.offsetHeight; 8180 var endBr = createEndBreak(); 8181 newContainer.appendChild(endBr); 8182 newHeight = newContainer.offsetHeight; 8183 if (oldHeight !== newHeight) { 8184 newContainer.removeChild(endBr); 8185 } 8186 } 8187 8188 // "Call appendChild(frag) on new container." 8189 newContainer.appendChild(frag); 8190 8191 // "If container has no visible children, call createElement("br") on 8192 // the context object, and append the result as the last child of 8193 // container." 8194 ensureContainerEditable(container); 8195 8196 // "If new container has no visible children, call createElement("br") 8197 // on the context object, and append the result as the last child of 8198 // new container." 8199 ensureContainerEditable(newContainer); 8200 8201 // "Call collapse(new container, 0) on the context object's Selection." 8202 Aloha.getSelection().collapse(newContainer, 0); 8203 range.setStart(newContainer, 0); 8204 range.setEnd(newContainer, 0); 8205 } 8206 }; 8207 8208 //@} 8209 ///// The insertText command ///// 8210 //@{ 8211 commands.inserttext = { 8212 action: function (value, range) { 8213 var i; 8214 8215 // "Delete the contents of the active range, with strip wrappers 8216 // false." 8217 deleteContents(range, { 8218 stripWrappers: false 8219 }); 8220 8221 // "If the active range's start node is neither editable nor an editing 8222 // host, abort these steps." 8223 if (!isEditable(range.startContainer) && !isEditingHost(range.startContainer)) { 8224 return; 8225 } 8226 8227 // "If value's length is greater than one:" 8228 if (value.length > 1) { 8229 // "For each element el in value, take the action for the 8230 // insertText command, with value equal to el." 8231 for (i = 0; i < value.length; i++) { 8232 commands.inserttext.action(value[i], range); 8233 } 8234 8235 // "Abort these steps." 8236 return; 8237 } 8238 8239 // "If value is the empty string, abort these steps." 8240 if (value == "") { 8241 return; 8242 } 8243 8244 // "If value is a newline (U+00A0), take the action for the 8245 // insertParagraph command and abort these steps." 8246 if (value == "\n") { 8247 commands.insertparagraph.action('', range); 8248 return; 8249 } 8250 8251 // "Let node and offset be the active range's start node and offset." 8252 var node = range.startContainer; 8253 var offset = range.startOffset; 8254 8255 // "If node has a child whose index is offset − 1, and that child is a 8256 // Text node, set node to that child, then set offset to node's 8257 // length." 8258 if (0 <= offset - 1 && offset - 1 < node.childNodes.length && node.childNodes[offset - 1].nodeType == $_.Node.TEXT_NODE) { 8259 node = node.childNodes[offset - 1]; 8260 offset = getNodeLength(node); 8261 } 8262 8263 // "If node has a child whose index is offset, and that child is a Text 8264 // node, set node to that child, then set offset to zero." 8265 if (0 <= offset && offset < node.childNodes.length && node.childNodes[offset].nodeType == $_.Node.TEXT_NODE) { 8266 node = node.childNodes[offset]; 8267 offset = 0; 8268 } 8269 8270 // "If value is a space (U+0020), and either node is an Element whose 8271 // resolved value for "white-space" is neither "pre" nor "pre-wrap" or 8272 // node is not an Element but its parent is an Element whose resolved 8273 // value for "white-space" is neither "pre" nor "pre-wrap", set value 8274 // to a non-breaking space (U+00A0)." 8275 var refElement = node.nodeType == $_.Node.ELEMENT_NODE ? node : node.parentNode; 8276 if (value == " " && refElement.nodeType == $_.Node.ELEMENT_NODE && jQuery.inArray($_.getComputedStyle(refElement).whiteSpace, ["pre", "pre-wrap"]) == -1) { 8277 value = "\xa0"; 8278 } 8279 8280 // "Record current overrides, and let overrides be the result." 8281 var overrides = recordCurrentOverrides(range); 8282 8283 // "If node is a Text node:" 8284 if (node.nodeType == $_.Node.TEXT_NODE) { 8285 // "Call insertData(offset, value) on node." 8286 node.insertData(offset, value); 8287 8288 // "Call collapse(node, offset) on the context object's Selection." 8289 Aloha.getSelection().collapse(node, offset); 8290 range.setStart(node, offset); 8291 8292 // "Call extend(node, offset + 1) on the context object's 8293 // Selection." 8294 Aloha.getSelection().extend(node, offset + 1); 8295 range.setEnd(node, offset + 1); 8296 8297 // "Otherwise:" 8298 } else { 8299 // "If node has only one child, which is a collapsed line break, 8300 // remove its child from it." 8301 // 8302 // FIXME: IE incorrectly returns false here instead of true 8303 // sometimes? 8304 if (node.childNodes.length == 1 && isCollapsedLineBreak(node.firstChild)) { 8305 node.removeChild(node.firstChild); 8306 } 8307 8308 // "Let text be the result of calling createTextNode(value) on the 8309 // context object." 8310 var text = document.createTextNode(value); 8311 8312 // "Call insertNode(text) on the active range." 8313 range.insertNode(text); 8314 8315 // "Call collapse(text, 0) on the context object's Selection." 8316 Aloha.getSelection().collapse(text, 0); 8317 range.setStart(text, 0); 8318 8319 // "Call extend(text, 1) on the context object's Selection." 8320 Aloha.getSelection().extend(text, 1); 8321 range.setEnd(text, 1); 8322 } 8323 8324 // "Restore states and values from overrides." 8325 restoreStatesAndValues(overrides, range); 8326 8327 // "Canonicalize whitespace at the active range's start." 8328 canonicalizeWhitespace(range.startContainer, range.startOffset); 8329 8330 // "Canonicalize whitespace at the active range's end." 8331 canonicalizeWhitespace(range.endContainer, range.endOffset); 8332 8333 // "Call collapseToEnd() on the context object's Selection." 8334 Aloha.getSelection().collapseToEnd(); 8335 range.collapse(false); 8336 } 8337 }; 8338 8339 //@} 8340 ///// The insertUnorderedList command ///// 8341 //@{ 8342 commands.insertunorderedlist = { 8343 // "Toggle lists with tag name "ul"." 8344 action: function (value, range) { 8345 toggleLists("ul", range); 8346 }, 8347 // "True if the selection's list state is "mixed" or "mixed ul", false 8348 // otherwise." 8349 indeterm: function () { 8350 return (/^mixed( ul)?$/).test(getSelectionListState()); 8351 }, 8352 // "True if the selection's list state is "ul", false otherwise." 8353 state: function () { 8354 return getSelectionListState() == "ul"; 8355 } 8356 }; 8357 8358 //@} 8359 ///// The justifyCenter command ///// 8360 //@{ 8361 commands.justifycenter = { 8362 // "Justify the selection with alignment "center"." 8363 action: function (value, range) { 8364 justifySelection("center", range); 8365 }, 8366 indeterm: function () { 8367 // "Block-extend the active range. Return true if among visible 8368 // editable nodes that are contained in the result and have no 8369 // children, at least one has alignment value "center" and at least one 8370 // does not. Otherwise return false." 8371 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8372 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8373 }); 8374 return $_(nodes).some(function (node) { return getAlignmentValue(node) == "center"; }) 8375 && $_(nodes).some(function (node) { return getAlignmentValue(node) != "center"; }); 8376 }, 8377 state: function () { 8378 // "Block-extend the active range. Return true if there is at least one 8379 // visible editable node that is contained in the result and has no 8380 // children, and all such nodes have alignment value "center". 8381 // Otherwise return false." 8382 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8383 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8384 }); 8385 return nodes.length && $_(nodes).every(function (node) { 8386 return getAlignmentValue(node) == "center"; 8387 }); 8388 }, 8389 value: function () { 8390 // "Block-extend the active range, and return the alignment value of 8391 // the first visible editable node that is contained in the result and 8392 // has no children. If there is no such node, return "left"." 8393 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8394 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8395 }); 8396 if (nodes.length) { 8397 return getAlignmentValue(nodes[0]); 8398 } 8399 return "left"; 8400 } 8401 }; 8402 8403 //@} 8404 ///// The justifyFull command ///// 8405 //@{ 8406 commands.justifyfull = { 8407 // "Justify the selection with alignment "justify"." 8408 action: function (value, range) { 8409 justifySelection("justify", range); 8410 }, 8411 indeterm: function () { 8412 // "Block-extend the active range. Return true if among visible 8413 // editable nodes that are contained in the result and have no 8414 // children, at least one has alignment value "justify" and at least 8415 // one does not. Otherwise return false." 8416 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8417 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8418 }); 8419 return $_(nodes).some(function (node) { return getAlignmentValue(node) == "justify"; }) 8420 && $_(nodes).some(function (node) { return getAlignmentValue(node) != "justify"; }); 8421 }, 8422 state: function () { 8423 // "Block-extend the active range. Return true if there is at least one 8424 // visible editable node that is contained in the result and has no 8425 // children, and all such nodes have alignment value "justify". 8426 // Otherwise return false." 8427 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8428 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8429 }); 8430 return nodes.length && $_(nodes).every(function (node) { 8431 return getAlignmentValue(node) == "justify"; 8432 }); 8433 }, 8434 value: function () { 8435 // "Block-extend the active range, and return the alignment value of 8436 // the first visible editable node that is contained in the result and 8437 // has no children. If there is no such node, return "left"." 8438 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8439 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8440 }); 8441 if (nodes.length) { 8442 return getAlignmentValue(nodes[0]); 8443 } 8444 return "left"; 8445 } 8446 }; 8447 8448 //@} 8449 ///// The justifyLeft command ///// 8450 //@{ 8451 commands.justifyleft = { 8452 // "Justify the selection with alignment "left"." 8453 action: function (value, range) { 8454 justifySelection("left", range); 8455 }, 8456 indeterm: function () { 8457 // "Block-extend the active range. Return true if among visible 8458 // editable nodes that are contained in the result and have no 8459 // children, at least one has alignment value "left" and at least one 8460 // does not. Otherwise return false." 8461 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8462 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8463 }); 8464 return $_(nodes).some(function (node) { return getAlignmentValue(node) == "left"; }) 8465 && $_(nodes).some(function (node) { return getAlignmentValue(node) != "left"; }); 8466 }, 8467 state: function () { 8468 // "Block-extend the active range. Return true if there is at least one 8469 // visible editable node that is contained in the result and has no 8470 // children, and all such nodes have alignment value "left". Otherwise 8471 // return false." 8472 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8473 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8474 }); 8475 return nodes.length && $_(nodes).every(function (node) { 8476 return getAlignmentValue(node) == "left"; 8477 }); 8478 }, 8479 value: function () { 8480 // "Block-extend the active range, and return the alignment value of 8481 // the first visible editable node that is contained in the result and 8482 // has no children. If there is no such node, return "left"." 8483 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8484 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8485 }); 8486 if (nodes.length) { 8487 return getAlignmentValue(nodes[0]); 8488 } 8489 return "left"; 8490 } 8491 }; 8492 8493 //@} 8494 ///// The justifyRight command ///// 8495 //@{ 8496 commands.justifyright = { 8497 // "Justify the selection with alignment "right"." 8498 action: function (value, range) { 8499 justifySelection("right", range); 8500 }, 8501 indeterm: function () { 8502 // "Block-extend the active range. Return true if among visible 8503 // editable nodes that are contained in the result and have no 8504 // children, at least one has alignment value "right" and at least one 8505 // does not. Otherwise return false." 8506 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8507 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8508 }); 8509 return $_(nodes).some(function (node) { return getAlignmentValue(node) == "right"; }) 8510 && $_(nodes).some(function (node) { return getAlignmentValue(node) != "right"; }); 8511 }, 8512 state: function () { 8513 // "Block-extend the active range. Return true if there is at least one 8514 // visible editable node that is contained in the result and has no 8515 // children, and all such nodes have alignment value "right". 8516 // Otherwise return false." 8517 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8518 8519 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8520 }); 8521 return nodes.length && $_(nodes).every(function (node) { 8522 return getAlignmentValue(node) == "right"; 8523 }); 8524 }, 8525 value: function () { 8526 // "Block-extend the active range, and return the alignment value of 8527 // the first visible editable node that is contained in the result and 8528 // has no children. If there is no such node, return "left"." 8529 var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function (node) { 8530 return isEditable(node) && isVisible(node) && !node.hasChildNodes(); 8531 }); 8532 if (nodes.length) { 8533 return getAlignmentValue(nodes[0]); 8534 } 8535 return "left"; 8536 } 8537 }; 8538 8539 //@} 8540 ///// The outdent command ///// 8541 //@{ 8542 commands.outdent = { 8543 action: function () { 8544 // "Let items be a list of all lis that are ancestor containers of the 8545 // range's start and/or end node." 8546 // 8547 // It's annoying to get this in tree order using functional stuff 8548 // without doing getDescendants(document), which is slow, so I do it 8549 // imperatively. 8550 var items = []; 8551 (function () { 8552 var ancestorContainer; 8553 for (ancestorContainer = getActiveRange().endContainer; 8554 ancestorContainer != getActiveRange().commonAncestorContainer; 8555 ancestorContainer = ancestorContainer.parentNode) { 8556 if (isNamedHtmlElement(ancestorContainer, "li")) { 8557 items.unshift(ancestorContainer); 8558 } 8559 } 8560 for (ancestorContainer = getActiveRange().startContainer; 8561 ancestorContainer; 8562 ancestorContainer = ancestorContainer.parentNode) { 8563 if (isNamedHtmlElement(ancestorContainer, "li")) { 8564 items.unshift(ancestorContainer); 8565 } 8566 } 8567 }()); 8568 8569 // "For each item in items, normalize sublists of item." 8570 $_(items).forEach(function (thisArg) { 8571 normalizeSublists(thisArg, getActiveRange()); 8572 }); 8573 8574 // "Block-extend the active range, and let new range be the result." 8575 var newRange = blockExtend(getActiveRange()); 8576 8577 // "Let node list be a list of nodes, initially empty." 8578 // 8579 // "For each node node contained in new range, append node to node list 8580 // if the last member of node list (if any) is not an ancestor of node; 8581 // node is editable; and either node has no editable descendants, or is 8582 // an ol or ul, or is an li whose parent is an ol or ul." 8583 var nodeList = getContainedNodes(newRange, function (node) { 8584 return isEditable(node) && (!$_(getDescendants(node)).some(isEditable) || isHtmlElementInArray(node, ["ol", "ul"]) || (isNamedHtmlElement(node, 'li') && isHtmlElementInArray(node.parentNode, ["ol", "ul"]))); 8585 }); 8586 8587 // "While node list is not empty:" 8588 while (nodeList.length) { 8589 // "While the first member of node list is an ol or ul or is not 8590 // the child of an ol or ul, outdent it and remove it from node 8591 // list." 8592 while (nodeList.length && (isHtmlElementInArray(nodeList[0], ["OL", "UL"]) || !isHtmlElementInArray(nodeList[0].parentNode, ["OL", "UL"]))) { 8593 outdentNode(nodeList.shift(), newRange); 8594 } 8595 8596 // "If node list is empty, break from these substeps." 8597 if (!nodeList.length) { 8598 break; 8599 } 8600 8601 // "Let sublist be a list of nodes, initially empty." 8602 var sublist = []; 8603 8604 // "Remove the first member of node list and append it to sublist." 8605 sublist.push(nodeList.shift()); 8606 8607 // "While the first member of node list is the nextSibling of the 8608 // last member of sublist, and the first member of node list is not 8609 // an ol or ul, remove the first member of node list and append it 8610 // to sublist." 8611 while (nodeList.length && nodeList[0] == sublist[sublist.length - 1].nextSibling && !isHtmlElementInArray(nodeList[0], ["OL", "UL"])) { 8612 sublist.push(nodeList.shift()); 8613 } 8614 8615 // "Record the values of sublist, and let values be the result." 8616 var values = recordValues(sublist); 8617 8618 // "Split the parent of sublist, with new parent null." 8619 splitParent(sublist, newRange); 8620 8621 // "Fix disallowed ancestors of each member of sublist." 8622 $_(sublist).forEach(fixDisallowedAncestors); 8623 8624 // "Restore the values from values." 8625 restoreValues(values, newRange); 8626 } 8627 } 8628 }; 8629 8630 //@} 8631 8632 ////////////////////////////////// 8633 ///// Miscellaneous commands ///// 8634 ////////////////////////////////// 8635 8636 ///// The selectAll command ///// 8637 //@{ 8638 commands.selectall = { 8639 // Note, this ignores the whole globalRange/getActiveRange() thing and 8640 // works with actual selections. Not suitable for autoimplementation.html. 8641 action: function () { 8642 // "Let target be the body element of the context object." 8643 var target = document.body; 8644 8645 // "If target is null, let target be the context object's 8646 // documentElement." 8647 if (!target) { 8648 target = document.documentElement; 8649 } 8650 8651 // "If target is null, call getSelection() on the context object, and 8652 // call removeAllRanges() on the result." 8653 if (!target) { 8654 Aloha.getSelection().removeAllRanges(); 8655 8656 // "Otherwise, call getSelection() on the context object, and call 8657 // selectAllChildren(target) on the result." 8658 } else { 8659 Aloha.getSelection().selectAllChildren(target); 8660 } 8661 } 8662 }; 8663 8664 //@} 8665 ///// The styleWithCSS command ///// 8666 //@{ 8667 commands.stylewithcss = { 8668 action: function (value) { 8669 // "If value is an ASCII case-insensitive match for the string 8670 // "false", set the CSS styling flag to false. Otherwise, set the 8671 // CSS styling flag to true." 8672 cssStylingFlag = String(value).toLowerCase() != "false"; 8673 }, 8674 state: function () { 8675 return cssStylingFlag; 8676 } 8677 }; 8678 8679 //@} 8680 ///// The useCSS command ///// 8681 //@{ 8682 commands.usecss = { 8683 action: function (value) { 8684 // "If value is an ASCII case-insensitive match for the string "false", 8685 // set the CSS styling flag to true. Otherwise, set the CSS styling 8686 // flag to false." 8687 cssStylingFlag = String(value).toLowerCase() == "false"; 8688 } 8689 }; 8690 //@} 8691 8692 // Some final setup 8693 //@{ 8694 (function () { 8695 // Opera 11.50 doesn't implement Object.keys, so I have to make an explicit 8696 // temporary, which means I need an extra closure to not leak the temporaries 8697 // into the global namespace. >:( 8698 var commandNames = []; 8699 var command; 8700 for (command in commands) { 8701 if (commands.hasOwnProperty(command)) { 8702 commandNames.push(command); 8703 } 8704 } 8705 $_(commandNames).forEach(function (command) { 8706 // "If a command does not have a relevant CSS property specified, it 8707 // defaults to null." 8708 if (null == commands[command].relevantCssProperty) { 8709 commands[command].relevantCssProperty = null; 8710 } 8711 8712 // "If a command has inline command activated values defined but 8713 // nothing else defines when it is indeterminate, it is indeterminate 8714 // if among editable Text nodes effectively contained in the active 8715 // range, there is at least one whose effective command value is one of 8716 // the given values and at least one whose effective command value is 8717 // not one of the given values." 8718 if (null != commands[command].inlineCommandActivatedValues && null == commands[command].indeterm) { 8719 commands[command].indeterm = function (range) { 8720 var values = $_(getAllEffectivelyContainedNodes(range, function (node) { return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; })) 8721 .map(function (node) { return getEffectiveCommandValue(node, command); }); 8722 8723 var matchingValues = $_(values).filter(function (value) { 8724 return $_(commands[command].inlineCommandActivatedValues).indexOf(value) != -1; 8725 }); 8726 8727 return matchingValues.length >= 1 && values.length - matchingValues.length >= 1; 8728 }; 8729 } 8730 8731 8732 // "If a command has inline command activated values defined, its state 8733 // is true if either no editable Text node is effectively contained in 8734 // the active range, and the active range's start node's effective 8735 // command value is one of the given values; or if there is at least 8736 // one editable Text node effectively contained in the active range, 8737 // and all of them have an effective command value equal to one of the 8738 // given values." 8739 if (null != commands[command].inlineCommandActivatedValues) { 8740 commands[command].state = function (range) { 8741 var nodes = getAllEffectivelyContainedNodes(range, function (node) { 8742 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 8743 }); 8744 8745 if (nodes.length == 0) { 8746 return $_(commands[command].inlineCommandActivatedValues).indexOf(getEffectiveCommandValue(range.startContainer, command)) != -1; 8747 } 8748 return $_(nodes).every(function (node) { 8749 return $_(commands[command].inlineCommandActivatedValues).indexOf(getEffectiveCommandValue(node, command)) != -1; 8750 }); 8751 }; 8752 } 8753 8754 // "If a command is a standard inline value command, it is 8755 // indeterminate if among editable Text nodes that are effectively 8756 // contained in the active range, there are two that have distinct 8757 // effective command values. Its value is the effective command value 8758 // of the first editable Text node that is effectively contained in the 8759 // active range, or if there is no such node, the effective command 8760 // value of the active range's start node." 8761 if (null != commands[command].standardInlineValueCommand) { 8762 commands[command].indeterm = function () { 8763 var values = $_(getAllEffectivelyContainedNodes(getActiveRange())).filter(function (node) { return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; }, true) 8764 .map(function (node) { return getEffectiveCommandValue(node, command); }); 8765 var i; 8766 for (i = 1; i < values.length; i++) { 8767 if (values[i] != values[i - 1]) { 8768 return true; 8769 } 8770 } 8771 return false; 8772 }; 8773 8774 commands[command].value = function (range) { 8775 var refNode = getAllEffectivelyContainedNodes(range, function (node) { 8776 return isEditable(node) && node.nodeType == $_.Node.TEXT_NODE; 8777 })[0]; 8778 8779 if (typeof refNode == "undefined") { 8780 refNode = range.startContainer; 8781 } 8782 8783 return getEffectiveCommandValue(refNode, command); 8784 }; 8785 } 8786 }); 8787 }()); 8788 //@} 8789 return { 8790 commands: commands, 8791 execCommand: myExecCommand, 8792 queryCommandIndeterm: myQueryCommandIndeterm, 8793 8794 queryCommandState: myQueryCommandState, 8795 queryCommandValue: myQueryCommandValue, 8796 queryCommandEnabled: myQueryCommandEnabled, 8797 queryCommandSupported: myQueryCommandSupported, 8798 copyAttributes: copyAttributes, 8799 createEndBreak: createEndBreak, 8800 isEndBreak: isEndBreak, 8801 ensureContainerEditable: ensureContainerEditable, 8802 isEditingHost: isEditingHost, 8803 isEditable: isEditable, 8804 getStateOverride: getStateOverride, 8805 setStateOverride: setStateOverride, 8806 resetOverrides: resetOverrides, 8807 unsetStateOverride: unsetStateOverride 8808 }; 8809 }); // end define 8810 // vim: foldmarker=@{,@} foldmethod=marker 8811