michael@0: "use strict"; michael@0: michael@0: var htmlNamespace = "http://www.w3.org/1999/xhtml"; michael@0: michael@0: var cssStylingFlag = false; michael@0: michael@0: var defaultSingleLineContainerName = "p"; michael@0: michael@0: // This is bad :( michael@0: var globalRange = null; michael@0: michael@0: // Commands are stored in a dictionary where we call their actions and such michael@0: var commands = {}; michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: ////////////////////////////// Utility functions ////////////////////////////// michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: //@{ michael@0: michael@0: function nextNode(node) { michael@0: if (node.hasChildNodes()) { michael@0: return node.firstChild; michael@0: } michael@0: return nextNodeDescendants(node); michael@0: } michael@0: michael@0: function previousNode(node) { michael@0: if (node.previousSibling) { michael@0: node = node.previousSibling; michael@0: while (node.hasChildNodes()) { michael@0: node = node.lastChild; michael@0: } michael@0: return node; michael@0: } michael@0: if (node.parentNode michael@0: && node.parentNode.nodeType == Node.ELEMENT_NODE) { michael@0: return node.parentNode; michael@0: } michael@0: return null; michael@0: } michael@0: michael@0: function nextNodeDescendants(node) { michael@0: while (node && !node.nextSibling) { michael@0: node = node.parentNode; michael@0: } michael@0: if (!node) { michael@0: return null; michael@0: } michael@0: return node.nextSibling; michael@0: } michael@0: michael@0: /** michael@0: * Returns true if ancestor is an ancestor of descendant, false otherwise. michael@0: */ michael@0: function isAncestor(ancestor, descendant) { michael@0: return ancestor michael@0: && descendant michael@0: && Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY); michael@0: } michael@0: michael@0: /** michael@0: * Returns true if ancestor is an ancestor of or equal to descendant, false michael@0: * otherwise. michael@0: */ michael@0: function isAncestorContainer(ancestor, descendant) { michael@0: return (ancestor || descendant) michael@0: && (ancestor == descendant || isAncestor(ancestor, descendant)); michael@0: } michael@0: michael@0: /** michael@0: * Returns true if descendant is a descendant of ancestor, false otherwise. michael@0: */ michael@0: function isDescendant(descendant, ancestor) { michael@0: return ancestor michael@0: && descendant michael@0: && Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY); michael@0: } michael@0: michael@0: /** michael@0: * Returns true if node1 is before node2 in tree order, false otherwise. michael@0: */ michael@0: function isBefore(node1, node2) { michael@0: return Boolean(node1.compareDocumentPosition(node2) & Node.DOCUMENT_POSITION_FOLLOWING); michael@0: } michael@0: michael@0: /** michael@0: * Returns true if node1 is after node2 in tree order, false otherwise. michael@0: */ michael@0: function isAfter(node1, node2) { michael@0: return Boolean(node1.compareDocumentPosition(node2) & Node.DOCUMENT_POSITION_PRECEDING); michael@0: } michael@0: michael@0: function getAncestors(node) { michael@0: var ancestors = []; michael@0: while (node.parentNode) { michael@0: ancestors.unshift(node.parentNode); michael@0: node = node.parentNode; michael@0: } michael@0: return ancestors; michael@0: } michael@0: michael@0: function getInclusiveAncestors(node) { michael@0: return getAncestors(node).concat(node); michael@0: } michael@0: michael@0: function getDescendants(node) { michael@0: var descendants = []; michael@0: var stop = nextNodeDescendants(node); michael@0: while ((node = nextNode(node)) michael@0: && node != stop) { michael@0: descendants.push(node); michael@0: } michael@0: return descendants; michael@0: } michael@0: michael@0: function getInclusiveDescendants(node) { michael@0: return [node].concat(getDescendants(node)); michael@0: } michael@0: michael@0: function convertProperty(property) { michael@0: // Special-case for now michael@0: var map = { michael@0: "fontFamily": "font-family", michael@0: "fontSize": "font-size", michael@0: "fontStyle": "font-style", michael@0: "fontWeight": "font-weight", michael@0: "textDecoration": "text-decoration", michael@0: }; michael@0: if (typeof map[property] != "undefined") { michael@0: return map[property]; michael@0: } michael@0: michael@0: return property; michael@0: } michael@0: michael@0: // Return the value for the given CSS size, or undefined if there michael@0: // is none. michael@0: function cssSizeToLegacy(cssVal) { michael@0: return { michael@0: "x-small": 1, michael@0: "small": 2, michael@0: "medium": 3, michael@0: "large": 4, michael@0: "x-large": 5, michael@0: "xx-large": 6, michael@0: "xxx-large": 7 michael@0: }[cssVal]; michael@0: } michael@0: michael@0: // Return the CSS size given a legacy size. michael@0: function legacySizeToCss(legacyVal) { michael@0: return { michael@0: 1: "x-small", michael@0: 2: "small", michael@0: 3: "medium", michael@0: 4: "large", michael@0: 5: "x-large", michael@0: 6: "xx-large", michael@0: 7: "xxx-large", michael@0: }[legacyVal]; michael@0: } michael@0: michael@0: // Opera 11 puts HTML elements in the null namespace, it seems. michael@0: function isHtmlNamespace(ns) { michael@0: return ns === null michael@0: || ns === htmlNamespace; michael@0: } michael@0: michael@0: // "the directionality" from HTML. I don't bother caring about non-HTML michael@0: // elements. michael@0: // michael@0: // "The directionality of an element is either 'ltr' or 'rtl', and is michael@0: // determined as per the first appropriate set of steps from the following michael@0: // list:" michael@0: function getDirectionality(element) { michael@0: // "If the element's dir attribute is in the ltr state michael@0: // The directionality of the element is 'ltr'." michael@0: if (element.dir == "ltr") { michael@0: return "ltr"; michael@0: } michael@0: michael@0: // "If the element's dir attribute is in the rtl state michael@0: // The directionality of the element is 'rtl'." michael@0: if (element.dir == "rtl") { michael@0: return "rtl"; michael@0: } michael@0: michael@0: // "If the element's dir attribute is in the auto state michael@0: // "If the element is a bdi element and the dir attribute is not in a michael@0: // defined state (i.e. it is not present or has an invalid value) michael@0: // [lots of complicated stuff] michael@0: // michael@0: // Skip this, since no browser implements it anyway. michael@0: michael@0: // "If the element is a root element and the dir attribute is not in a michael@0: // defined state (i.e. it is not present or has an invalid value) michael@0: // The directionality of the element is 'ltr'." michael@0: if (!isHtmlElement(element.parentNode)) { michael@0: return "ltr"; michael@0: } michael@0: michael@0: // "If the element has a parent element and the dir attribute is not in a michael@0: // defined state (i.e. it is not present or has an invalid value) michael@0: // The directionality of the element is the same as the element's michael@0: // parent element's directionality." michael@0: return getDirectionality(element.parentNode); michael@0: } michael@0: michael@0: //@} michael@0: michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: ///////////////////////////// DOM Range functions ///////////////////////////// michael@0: /////////////////////////////////////////////////////////////////////////////// michael@0: //@{ michael@0: michael@0: function getNodeIndex(node) { michael@0: var ret = 0; michael@0: while (node.previousSibling) { michael@0: ret++; michael@0: node = node.previousSibling; michael@0: } michael@0: return ret; michael@0: } michael@0: michael@0: // "The length of a Node node is the following, depending on node: michael@0: // michael@0: // ProcessingInstruction michael@0: // DocumentType michael@0: // Always 0. michael@0: // Text michael@0: // Comment michael@0: // node's length. michael@0: // Any other node michael@0: // node's childNodes's length." michael@0: function getNodeLength(node) { michael@0: switch (node.nodeType) { michael@0: case Node.PROCESSING_INSTRUCTION_NODE: michael@0: case Node.DOCUMENT_TYPE_NODE: michael@0: return 0; michael@0: michael@0: case Node.TEXT_NODE: michael@0: case Node.COMMENT_NODE: michael@0: return node.length; michael@0: michael@0: default: michael@0: return node.childNodes.length; michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * The position of two boundary points relative to one another, as defined by michael@0: * DOM Range. michael@0: */ michael@0: function getPosition(nodeA, offsetA, nodeB, offsetB) { michael@0: // "If node A is the same as node B, return equal if offset A equals offset michael@0: // B, before if offset A is less than offset B, and after if offset A is michael@0: // greater than offset B." michael@0: if (nodeA == nodeB) { michael@0: if (offsetA == offsetB) { michael@0: return "equal"; michael@0: } michael@0: if (offsetA < offsetB) { michael@0: return "before"; michael@0: } michael@0: if (offsetA > offsetB) { michael@0: return "after"; michael@0: } michael@0: } michael@0: michael@0: // "If node A is after node B in tree order, compute the position of (node michael@0: // B, offset B) relative to (node A, offset A). If it is before, return michael@0: // after. If it is after, return before." michael@0: if (nodeB.compareDocumentPosition(nodeA) & Node.DOCUMENT_POSITION_FOLLOWING) { michael@0: var pos = getPosition(nodeB, offsetB, nodeA, offsetA); michael@0: if (pos == "before") { michael@0: return "after"; michael@0: } michael@0: if (pos == "after") { michael@0: return "before"; michael@0: } michael@0: } michael@0: michael@0: // "If node A is an ancestor of node B:" michael@0: if (nodeB.compareDocumentPosition(nodeA) & Node.DOCUMENT_POSITION_CONTAINS) { michael@0: // "Let child equal node B." michael@0: var child = nodeB; michael@0: michael@0: // "While child is not a child of node A, set child to its parent." michael@0: while (child.parentNode != nodeA) { michael@0: child = child.parentNode; michael@0: } michael@0: michael@0: // "If the index of child is less than offset A, return after." michael@0: if (getNodeIndex(child) < offsetA) { michael@0: return "after"; michael@0: } michael@0: } michael@0: michael@0: // "Return before." michael@0: return "before"; michael@0: } michael@0: michael@0: /** michael@0: * Returns the furthest ancestor of a Node as defined by DOM Range. michael@0: */ michael@0: function getFurthestAncestor(node) { michael@0: var root = node; michael@0: while (root.parentNode != null) { michael@0: root = root.parentNode; michael@0: } michael@0: return root; michael@0: } michael@0: michael@0: /** michael@0: * "contained" as defined by DOM Range: "A Node node is contained in a range michael@0: * range if node's furthest ancestor is the same as range's root, and (node, 0) michael@0: * is after range's start, and (node, length of node) is before range's end." michael@0: */ michael@0: function isContained(node, range) { michael@0: var pos1 = getPosition(node, 0, range.startContainer, range.startOffset); michael@0: var pos2 = getPosition(node, getNodeLength(node), range.endContainer, range.endOffset); michael@0: michael@0: return getFurthestAncestor(node) == getFurthestAncestor(range.startContainer) michael@0: && pos1 == "after" michael@0: && pos2 == "before"; michael@0: } michael@0: michael@0: /** michael@0: * Return all nodes contained in range that the provided function returns true michael@0: * for, omitting any with an ancestor already being returned. michael@0: */ michael@0: function getContainedNodes(range, condition) { michael@0: if (typeof condition == "undefined") { michael@0: condition = function() { return true }; michael@0: } michael@0: var node = range.startContainer; michael@0: if (node.hasChildNodes() michael@0: && range.startOffset < node.childNodes.length) { michael@0: // A child is contained michael@0: node = node.childNodes[range.startOffset]; michael@0: } else if (range.startOffset == getNodeLength(node)) { michael@0: // No descendant can be contained michael@0: node = nextNodeDescendants(node); michael@0: } else { michael@0: // No children; this node at least can't be contained michael@0: node = nextNode(node); michael@0: } michael@0: michael@0: var stop = range.endContainer; michael@0: if (stop.hasChildNodes() michael@0: && range.endOffset < stop.childNodes.length) { michael@0: // The node after the last contained node is a child michael@0: stop = stop.childNodes[range.endOffset]; michael@0: } else { michael@0: // This node and/or some of its children might be contained michael@0: stop = nextNodeDescendants(stop); michael@0: } michael@0: michael@0: var nodeList = []; michael@0: while (isBefore(node, stop)) { michael@0: if (isContained(node, range) michael@0: && condition(node)) { michael@0: nodeList.push(node); michael@0: node = nextNodeDescendants(node); michael@0: continue; michael@0: } michael@0: node = nextNode(node); michael@0: } michael@0: return nodeList; michael@0: } michael@0: michael@0: /** michael@0: * As above, but includes nodes with an ancestor that's already been returned. michael@0: */ michael@0: function getAllContainedNodes(range, condition) { michael@0: if (typeof condition == "undefined") { michael@0: condition = function() { return true }; michael@0: } michael@0: var node = range.startContainer; michael@0: if (node.hasChildNodes() michael@0: && range.startOffset < node.childNodes.length) { michael@0: // A child is contained michael@0: node = node.childNodes[range.startOffset]; michael@0: } else if (range.startOffset == getNodeLength(node)) { michael@0: // No descendant can be contained michael@0: node = nextNodeDescendants(node); michael@0: } else { michael@0: // No children; this node at least can't be contained michael@0: node = nextNode(node); michael@0: } michael@0: michael@0: var stop = range.endContainer; michael@0: if (stop.hasChildNodes() michael@0: && range.endOffset < stop.childNodes.length) { michael@0: // The node after the last contained node is a child michael@0: stop = stop.childNodes[range.endOffset]; michael@0: } else { michael@0: // This node and/or some of its children might be contained michael@0: stop = nextNodeDescendants(stop); michael@0: } michael@0: michael@0: var nodeList = []; michael@0: while (isBefore(node, stop)) { michael@0: if (isContained(node, range) michael@0: && condition(node)) { michael@0: nodeList.push(node); michael@0: } michael@0: node = nextNode(node); michael@0: } michael@0: return nodeList; michael@0: } michael@0: michael@0: // Returns either null, or something of the form rgb(x, y, z), or something of michael@0: // the form rgb(x, y, z, w) with w != 0. michael@0: function normalizeColor(color) { michael@0: if (color.toLowerCase() == "currentcolor") { michael@0: return null; michael@0: } michael@0: michael@0: if (normalizeColor.resultCache === undefined) { michael@0: normalizeColor.resultCache = {}; michael@0: } michael@0: michael@0: if (normalizeColor.resultCache[color] !== undefined) { michael@0: return normalizeColor.resultCache[color]; michael@0: } michael@0: michael@0: var originalColor = color; michael@0: michael@0: var outerSpan = document.createElement("span"); michael@0: document.body.appendChild(outerSpan); michael@0: outerSpan.style.color = "black"; michael@0: michael@0: var innerSpan = document.createElement("span"); michael@0: outerSpan.appendChild(innerSpan); michael@0: innerSpan.style.color = color; michael@0: color = getComputedStyle(innerSpan).color; michael@0: michael@0: if (color == "rgb(0, 0, 0)") { michael@0: // Maybe it's really black, maybe it's invalid. michael@0: outerSpan.color = "white"; michael@0: color = getComputedStyle(innerSpan).color; michael@0: if (color != "rgb(0, 0, 0)") { michael@0: return normalizeColor.resultCache[originalColor] = null; michael@0: } michael@0: } michael@0: michael@0: document.body.removeChild(outerSpan); michael@0: michael@0: // I rely on the fact that browsers generally provide consistent syntax for michael@0: // getComputedStyle(), although it's not standardized. There are only michael@0: // three exceptions I found: michael@0: if (/^rgba\([0-9]+, [0-9]+, [0-9]+, 1\)$/.test(color)) { michael@0: // IE10PP2 seems to do this sometimes. michael@0: return normalizeColor.resultCache[originalColor] = michael@0: color.replace("rgba", "rgb").replace(", 1)", ")"); michael@0: } michael@0: if (color == "transparent") { michael@0: // IE10PP2, Firefox 7.0a2, and Opera 11.50 all return "transparent" if michael@0: // the specified value is "transparent". michael@0: return normalizeColor.resultCache[originalColor] = michael@0: "rgba(0, 0, 0, 0)"; michael@0: } michael@0: // Chrome 15 dev adds way too many significant figures. This isn't a full michael@0: // fix, it just fixes one case that comes up in tests. michael@0: color = color.replace(/, 0.496094\)$/, ", 0.5)"); michael@0: return normalizeColor.resultCache[originalColor] = color; michael@0: } michael@0: michael@0: // Returns either null, or something of the form #xxxxxx. michael@0: function parseSimpleColor(color) { michael@0: color = normalizeColor(color); michael@0: var matches = /^rgb\(([0-9]+), ([0-9]+), ([0-9]+)\)$/.exec(color); michael@0: if (matches) { michael@0: return "#" michael@0: + parseInt(matches[1]).toString(16).replace(/^.$/, "0$&") michael@0: + parseInt(matches[2]).toString(16).replace(/^.$/, "0$&") michael@0: + parseInt(matches[3]).toString(16).replace(/^.$/, "0$&"); michael@0: } michael@0: return null; michael@0: } michael@0: michael@0: //@} michael@0: michael@0: ////////////////////////////////////////////////////////////////////////////// michael@0: /////////////////////////// Edit command functions /////////////////////////// michael@0: ////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: ///////////////////////////////////////////////// michael@0: ///// Methods of the HTMLDocument interface ///// michael@0: ///////////////////////////////////////////////// michael@0: //@{ michael@0: michael@0: var executionStackDepth = 0; michael@0: michael@0: // Helper function for common behavior. michael@0: function editCommandMethod(command, range, callback) { michael@0: // Set up our global range magic, but only if we're the outermost function michael@0: if (executionStackDepth == 0 && typeof range != "undefined") { michael@0: globalRange = range; michael@0: } else if (executionStackDepth == 0) { michael@0: globalRange = null; michael@0: globalRange = getActiveRange(); michael@0: } michael@0: michael@0: executionStackDepth++; michael@0: try { michael@0: var ret = callback(); michael@0: } catch(e) { michael@0: executionStackDepth--; michael@0: throw e; michael@0: } michael@0: executionStackDepth--; michael@0: return ret; michael@0: } michael@0: michael@0: function myExecCommand(command, showUi, value, range) { michael@0: // "All of these methods must treat their command argument ASCII michael@0: // case-insensitively." michael@0: command = command.toLowerCase(); michael@0: michael@0: // "If only one argument was provided, let show UI be false." michael@0: // michael@0: // If range was passed, I can't actually detect how many args were passed michael@0: // . . . michael@0: if (arguments.length == 1 michael@0: || (arguments.length >=4 && typeof showUi == "undefined")) { michael@0: showUi = false; michael@0: } michael@0: michael@0: // "If only one or two arguments were provided, let value be the empty michael@0: // string." michael@0: if (arguments.length <= 2 michael@0: || (arguments.length >=4 && typeof value == "undefined")) { michael@0: value = ""; michael@0: } michael@0: michael@0: return editCommandMethod(command, range, (function(command, showUi, value) { return function() { michael@0: // "If command is not supported or not enabled, return false." michael@0: if (!(command in commands) || !myQueryCommandEnabled(command)) { michael@0: return false; michael@0: } michael@0: michael@0: // "Take the action for command, passing value to the instructions as an michael@0: // argument." michael@0: var ret = commands[command].action(value); michael@0: michael@0: // Check for bugs michael@0: if (ret !== true && ret !== false) { michael@0: throw "execCommand() didn't return true or false: " + ret; michael@0: } michael@0: michael@0: // "If the previous step returned false, return false." michael@0: if (ret === false) { michael@0: return false; michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: }})(command, showUi, value)); michael@0: } michael@0: michael@0: function myQueryCommandEnabled(command, range) { michael@0: // "All of these methods must treat their command argument ASCII michael@0: // case-insensitively." michael@0: command = command.toLowerCase(); michael@0: michael@0: return editCommandMethod(command, range, (function(command) { return function() { michael@0: // "Return true if command is both supported and enabled, false michael@0: // otherwise." michael@0: if (!(command in commands)) { michael@0: return false; michael@0: } michael@0: michael@0: // "Among commands defined in this specification, those listed in michael@0: // Miscellaneous commands are always enabled, except for the cut michael@0: // command and the paste command. The other commands defined here are michael@0: // enabled if the active range is not null, its start node is either michael@0: // editable or an editing host, its end node is either editable or an michael@0: // editing host, and there is some editing host that is an inclusive michael@0: // ancestor of both its start node and its end node." michael@0: return ["copy", "defaultparagraphseparator", "selectall", "stylewithcss", michael@0: "usecss"].indexOf(command) != -1 michael@0: || ( michael@0: getActiveRange() !== null michael@0: && (isEditable(getActiveRange().startContainer) || isEditingHost(getActiveRange().startContainer)) michael@0: && (isEditable(getActiveRange().endContainer) || isEditingHost(getActiveRange().endContainer)) michael@0: && (getInclusiveAncestors(getActiveRange().commonAncestorContainer).some(isEditingHost)) michael@0: ); michael@0: }})(command)); michael@0: } michael@0: michael@0: function myQueryCommandIndeterm(command, range) { michael@0: // "All of these methods must treat their command argument ASCII michael@0: // case-insensitively." michael@0: command = command.toLowerCase(); michael@0: michael@0: return editCommandMethod(command, range, (function(command) { return function() { michael@0: // "If command is not supported or has no indeterminacy, return false." michael@0: if (!(command in commands) || !("indeterm" in commands[command])) { michael@0: return false; michael@0: } michael@0: michael@0: // "Return true if command is indeterminate, otherwise false." michael@0: return commands[command].indeterm(); michael@0: }})(command)); michael@0: } michael@0: michael@0: function myQueryCommandState(command, range) { michael@0: // "All of these methods must treat their command argument ASCII michael@0: // case-insensitively." michael@0: command = command.toLowerCase(); michael@0: michael@0: return editCommandMethod(command, range, (function(command) { return function() { michael@0: // "If command is not supported or has no state, return false." michael@0: if (!(command in commands) || !("state" in commands[command])) { michael@0: return false; michael@0: } michael@0: michael@0: // "If the state override for command is set, return it." michael@0: if (typeof getStateOverride(command) != "undefined") { michael@0: return getStateOverride(command); michael@0: } michael@0: michael@0: // "Return true if command's state is true, otherwise false." michael@0: return commands[command].state(); michael@0: }})(command)); michael@0: } michael@0: michael@0: // "When the queryCommandSupported(command) method on the HTMLDocument michael@0: // interface is invoked, the user agent must return true if command is michael@0: // supported, and false otherwise." michael@0: function myQueryCommandSupported(command) { michael@0: // "All of these methods must treat their command argument ASCII michael@0: // case-insensitively." michael@0: command = command.toLowerCase(); michael@0: michael@0: return command in commands; michael@0: } michael@0: michael@0: function myQueryCommandValue(command, range) { michael@0: // "All of these methods must treat their command argument ASCII michael@0: // case-insensitively." michael@0: command = command.toLowerCase(); michael@0: michael@0: return editCommandMethod(command, range, function() { michael@0: // "If command is not supported or has no value, return the empty string." michael@0: if (!(command in commands) || !("value" in commands[command])) { michael@0: return ""; michael@0: } michael@0: michael@0: // "If command is "fontSize" and its value override is set, convert the michael@0: // value override to an integer number of pixels and return the legacy michael@0: // font size for the result." michael@0: if (command == "fontsize" michael@0: && getValueOverride("fontsize") !== undefined) { michael@0: return getLegacyFontSize(getValueOverride("fontsize")); michael@0: } michael@0: michael@0: // "If the value override for command is set, return it." michael@0: if (typeof getValueOverride(command) != "undefined") { michael@0: return getValueOverride(command); michael@0: } michael@0: michael@0: // "Return command's value." michael@0: return commands[command].value(); michael@0: }); michael@0: } michael@0: //@} michael@0: michael@0: ////////////////////////////// michael@0: ///// Common definitions ///// michael@0: ////////////////////////////// michael@0: //@{ michael@0: michael@0: // "An HTML element is an Element whose namespace is the HTML namespace." michael@0: // michael@0: // I allow an extra argument to more easily check whether something is a michael@0: // particular HTML element, like isHtmlElement(node, "OL"). It accepts arrays michael@0: // too, like isHtmlElement(node, ["OL", "UL"]) to check if it's an ol or ul. michael@0: function isHtmlElement(node, tags) { michael@0: if (typeof tags == "string") { michael@0: tags = [tags]; michael@0: } michael@0: if (typeof tags == "object") { michael@0: tags = tags.map(function(tag) { return tag.toUpperCase() }); michael@0: } michael@0: return node michael@0: && node.nodeType == Node.ELEMENT_NODE michael@0: && isHtmlNamespace(node.namespaceURI) michael@0: && (typeof tags == "undefined" || tags.indexOf(node.tagName) != -1); michael@0: } michael@0: michael@0: // "A prohibited paragraph child name is "address", "article", "aside", michael@0: // "blockquote", "caption", "center", "col", "colgroup", "dd", "details", michael@0: // "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", michael@0: // "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li", michael@0: // "listing", "menu", "nav", "ol", "p", "plaintext", "pre", "section", michael@0: // "summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul", or michael@0: // "xmp"." michael@0: var prohibitedParagraphChildNames = ["address", "article", "aside", michael@0: "blockquote", "caption", "center", "col", "colgroup", "dd", "details", michael@0: "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", michael@0: "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li", michael@0: "listing", "menu", "nav", "ol", "p", "plaintext", "pre", "section", michael@0: "summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul", michael@0: "xmp"]; michael@0: michael@0: // "A prohibited paragraph child is an HTML element whose local name is a michael@0: // prohibited paragraph child name." michael@0: function isProhibitedParagraphChild(node) { michael@0: return isHtmlElement(node, prohibitedParagraphChildNames); michael@0: } michael@0: michael@0: // "A block node is either an Element whose "display" property does not have michael@0: // resolved value "inline" or "inline-block" or "inline-table" or "none", or a michael@0: // Document, or a DocumentFragment." michael@0: function isBlockNode(node) { michael@0: return node michael@0: && ((node.nodeType == Node.ELEMENT_NODE && ["inline", "inline-block", "inline-table", "none"].indexOf(getComputedStyle(node).display) == -1) michael@0: || node.nodeType == Node.DOCUMENT_NODE michael@0: || node.nodeType == Node.DOCUMENT_FRAGMENT_NODE); michael@0: } michael@0: michael@0: // "An inline node is a node that is not a block node." michael@0: function isInlineNode(node) { michael@0: return node && !isBlockNode(node); michael@0: } michael@0: michael@0: // "An editing host is a node that is either an HTML element with a michael@0: // contenteditable attribute set to the true state, or the HTML element child michael@0: // of a Document whose designMode is enabled." michael@0: function isEditingHost(node) { michael@0: return node michael@0: && isHtmlElement(node) michael@0: && (node.contentEditable == "true" michael@0: || (node.parentNode michael@0: && node.parentNode.nodeType == Node.DOCUMENT_NODE michael@0: && node.parentNode.designMode == "on")); michael@0: } michael@0: michael@0: // "Something is editable if it is a node; it is not an editing host; it does michael@0: // not have a contenteditable attribute set to the false state; its parent is michael@0: // an editing host or editable; and either it is an HTML element, or it is an michael@0: // svg or math element, or it is not an Element and its parent is an HTML michael@0: // element." michael@0: function isEditable(node) { michael@0: return node michael@0: && !isEditingHost(node) michael@0: && (node.nodeType != Node.ELEMENT_NODE || node.contentEditable != "false") michael@0: && (isEditingHost(node.parentNode) || isEditable(node.parentNode)) michael@0: && (isHtmlElement(node) michael@0: || (node.nodeType == Node.ELEMENT_NODE && node.namespaceURI == "http://www.w3.org/2000/svg" && node.localName == "svg") michael@0: || (node.nodeType == Node.ELEMENT_NODE && node.namespaceURI == "http://www.w3.org/1998/Math/MathML" && node.localName == "math") michael@0: || (node.nodeType != Node.ELEMENT_NODE && isHtmlElement(node.parentNode))); michael@0: } michael@0: michael@0: // Helper function, not defined in the spec michael@0: function hasEditableDescendants(node) { michael@0: for (var i = 0; i < node.childNodes.length; i++) { michael@0: if (isEditable(node.childNodes[i]) michael@0: || hasEditableDescendants(node.childNodes[i])) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: // "The editing host of node is null if node is neither editable nor an editing michael@0: // host; node itself, if node is an editing host; or the nearest ancestor of michael@0: // node that is an editing host, if node is editable." michael@0: function getEditingHostOf(node) { michael@0: if (isEditingHost(node)) { michael@0: return node; michael@0: } else if (isEditable(node)) { michael@0: var ancestor = node.parentNode; michael@0: while (!isEditingHost(ancestor)) { michael@0: ancestor = ancestor.parentNode; michael@0: } michael@0: return ancestor; michael@0: } else { michael@0: return null; michael@0: } michael@0: } michael@0: michael@0: // "Two nodes are in the same editing host if the editing host of the first is michael@0: // non-null and the same as the editing host of the second." michael@0: function inSameEditingHost(node1, node2) { michael@0: return getEditingHostOf(node1) michael@0: && getEditingHostOf(node1) == getEditingHostOf(node2); michael@0: } michael@0: michael@0: // "A collapsed line break is a br that begins a line box which has nothing michael@0: // else in it, and therefore has zero height." michael@0: function isCollapsedLineBreak(br) { michael@0: if (!isHtmlElement(br, "br")) { michael@0: return false; michael@0: } michael@0: michael@0: // Add a zwsp after it and see if that changes the height of the nearest michael@0: // non-inline parent. Note: this is not actually reliable, because the michael@0: // parent might have a fixed height or something. michael@0: var ref = br.parentNode; michael@0: while (getComputedStyle(ref).display == "inline") { michael@0: ref = ref.parentNode; michael@0: } michael@0: var refStyle = ref.hasAttribute("style") ? ref.getAttribute("style") : null; michael@0: ref.style.height = "auto"; michael@0: ref.style.maxHeight = "none"; michael@0: ref.style.minHeight = "0"; michael@0: var space = document.createTextNode("\u200b"); michael@0: var origHeight = ref.offsetHeight; michael@0: if (origHeight == 0) { michael@0: throw "isCollapsedLineBreak: original height is zero, bug?"; michael@0: } michael@0: br.parentNode.insertBefore(space, br.nextSibling); michael@0: var finalHeight = ref.offsetHeight; michael@0: space.parentNode.removeChild(space); michael@0: if (refStyle === null) { michael@0: // Without the setAttribute() line, removeAttribute() doesn't work in michael@0: // Chrome 14 dev. I have no idea why. michael@0: ref.setAttribute("style", ""); michael@0: ref.removeAttribute("style"); michael@0: } else { michael@0: ref.setAttribute("style", refStyle); michael@0: } michael@0: michael@0: // Allow some leeway in case the zwsp didn't create a whole new line, but michael@0: // only made an existing line slightly higher. Firefox 6.0a2 shows this michael@0: // behavior when the first line is bold. michael@0: return origHeight < finalHeight - 5; michael@0: } michael@0: michael@0: // "An extraneous line break is a br that has no visual effect, in that michael@0: // removing it from the DOM would not change layout, except that a br that is michael@0: // the sole child of an li is not extraneous." michael@0: // michael@0: // FIXME: This doesn't work in IE, since IE ignores display: none in michael@0: // contenteditable. michael@0: function isExtraneousLineBreak(br) { michael@0: if (!isHtmlElement(br, "br")) { michael@0: return false; michael@0: } michael@0: michael@0: if (isHtmlElement(br.parentNode, "li") michael@0: && br.parentNode.childNodes.length == 1) { michael@0: return false; michael@0: } michael@0: michael@0: // Make the line break disappear and see if that changes the block's michael@0: // height. Yes, this is an absurd hack. We have to reset height etc. on michael@0: // the reference node because otherwise its height won't change if it's not michael@0: // auto. michael@0: var ref = br.parentNode; michael@0: while (getComputedStyle(ref).display == "inline") { michael@0: ref = ref.parentNode; michael@0: } michael@0: var refStyle = ref.hasAttribute("style") ? ref.getAttribute("style") : null; michael@0: ref.style.height = "auto"; michael@0: ref.style.maxHeight = "none"; michael@0: ref.style.minHeight = "0"; michael@0: var brStyle = br.hasAttribute("style") ? br.getAttribute("style") : null; michael@0: var origHeight = ref.offsetHeight; michael@0: if (origHeight == 0) { michael@0: throw "isExtraneousLineBreak: original height is zero, bug?"; michael@0: } michael@0: br.setAttribute("style", "display:none"); michael@0: var finalHeight = ref.offsetHeight; michael@0: if (refStyle === null) { michael@0: // Without the setAttribute() line, removeAttribute() doesn't work in michael@0: // Chrome 14 dev. I have no idea why. michael@0: ref.setAttribute("style", ""); michael@0: ref.removeAttribute("style"); michael@0: } else { michael@0: ref.setAttribute("style", refStyle); michael@0: } michael@0: if (brStyle === null) { michael@0: br.removeAttribute("style"); michael@0: } else { michael@0: br.setAttribute("style", brStyle); michael@0: } michael@0: michael@0: return origHeight == finalHeight; michael@0: } michael@0: michael@0: // "A whitespace node is either a Text node whose data is the empty string; or michael@0: // a Text node whose data consists only of one or more tabs (0x0009), line michael@0: // feeds (0x000A), carriage returns (0x000D), and/or spaces (0x0020), and whose michael@0: // parent is an Element whose resolved value for "white-space" is "normal" or michael@0: // "nowrap"; or a Text node whose data consists only of one or more tabs michael@0: // (0x0009), carriage returns (0x000D), and/or spaces (0x0020), and whose michael@0: // parent is an Element whose resolved value for "white-space" is "pre-line"." michael@0: function isWhitespaceNode(node) { michael@0: return node michael@0: && node.nodeType == Node.TEXT_NODE michael@0: && (node.data == "" michael@0: || ( michael@0: /^[\t\n\r ]+$/.test(node.data) michael@0: && node.parentNode michael@0: && node.parentNode.nodeType == Node.ELEMENT_NODE michael@0: && ["normal", "nowrap"].indexOf(getComputedStyle(node.parentNode).whiteSpace) != -1 michael@0: ) || ( michael@0: /^[\t\r ]+$/.test(node.data) michael@0: && node.parentNode michael@0: && node.parentNode.nodeType == Node.ELEMENT_NODE michael@0: && getComputedStyle(node.parentNode).whiteSpace == "pre-line" michael@0: )); michael@0: } michael@0: michael@0: // "node is a collapsed whitespace node if the following algorithm returns michael@0: // true:" michael@0: function isCollapsedWhitespaceNode(node) { michael@0: // "If node is not a whitespace node, return false." michael@0: if (!isWhitespaceNode(node)) { michael@0: return false; michael@0: } michael@0: michael@0: // "If node's data is the empty string, return true." michael@0: if (node.data == "") { michael@0: return true; michael@0: } michael@0: michael@0: // "Let ancestor be node's parent." michael@0: var ancestor = node.parentNode; michael@0: michael@0: // "If ancestor is null, return true." michael@0: if (!ancestor) { michael@0: return true; michael@0: } michael@0: michael@0: // "If the "display" property of some ancestor of node has resolved value michael@0: // "none", return true." michael@0: if (getAncestors(node).some(function(ancestor) { michael@0: return ancestor.nodeType == Node.ELEMENT_NODE michael@0: && getComputedStyle(ancestor).display == "none"; michael@0: })) { michael@0: return true; michael@0: } michael@0: michael@0: // "While ancestor is not a block node and its parent is not null, set michael@0: // ancestor to its parent." michael@0: while (!isBlockNode(ancestor) michael@0: && ancestor.parentNode) { michael@0: ancestor = ancestor.parentNode; michael@0: } michael@0: michael@0: // "Let reference be node." michael@0: var reference = node; michael@0: michael@0: // "While reference is a descendant of ancestor:" michael@0: while (reference != ancestor) { michael@0: // "Let reference be the node before it in tree order." michael@0: reference = previousNode(reference); michael@0: michael@0: // "If reference is a block node or a br, return true." michael@0: if (isBlockNode(reference) michael@0: || isHtmlElement(reference, "br")) { michael@0: return true; michael@0: } michael@0: michael@0: // "If reference is a Text node that is not a whitespace node, or is an michael@0: // img, break from this loop." michael@0: if ((reference.nodeType == Node.TEXT_NODE && !isWhitespaceNode(reference)) michael@0: || isHtmlElement(reference, "img")) { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // "Let reference be node." michael@0: reference = node; michael@0: michael@0: // "While reference is a descendant of ancestor:" michael@0: var stop = nextNodeDescendants(ancestor); michael@0: while (reference != stop) { michael@0: // "Let reference be the node after it in tree order, or null if there michael@0: // is no such node." michael@0: reference = nextNode(reference); michael@0: michael@0: // "If reference is a block node or a br, return true." michael@0: if (isBlockNode(reference) michael@0: || isHtmlElement(reference, "br")) { michael@0: return true; michael@0: } michael@0: michael@0: // "If reference is a Text node that is not a whitespace node, or is an michael@0: // img, break from this loop." michael@0: if ((reference && reference.nodeType == Node.TEXT_NODE && !isWhitespaceNode(reference)) michael@0: || isHtmlElement(reference, "img")) { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // "Return false." michael@0: return false; michael@0: } michael@0: michael@0: // "Something is visible if it is a node that either is a block node, or a Text michael@0: // node that is not a collapsed whitespace node, or an img, or a br that is not michael@0: // an extraneous line break, or any node with a visible descendant; excluding michael@0: // any node with an ancestor container Element whose "display" property has michael@0: // resolved value "none"." michael@0: function isVisible(node) { michael@0: if (!node) { michael@0: return false; michael@0: } michael@0: michael@0: if (getAncestors(node).concat(node) michael@0: .filter(function(node) { return node.nodeType == Node.ELEMENT_NODE }) michael@0: .some(function(node) { return getComputedStyle(node).display == "none" })) { michael@0: return false; michael@0: } michael@0: michael@0: if (isBlockNode(node) michael@0: || (node.nodeType == Node.TEXT_NODE && !isCollapsedWhitespaceNode(node)) michael@0: || isHtmlElement(node, "img") michael@0: || (isHtmlElement(node, "br") && !isExtraneousLineBreak(node))) { michael@0: return true; michael@0: } michael@0: michael@0: for (var i = 0; i < node.childNodes.length; i++) { michael@0: if (isVisible(node.childNodes[i])) { michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: // "Something is invisible if it is a node that is not visible." michael@0: function isInvisible(node) { michael@0: return node && !isVisible(node); michael@0: } michael@0: michael@0: // "A collapsed block prop is either a collapsed line break that is not an michael@0: // extraneous line break, or an Element that is an inline node and whose michael@0: // children are all either invisible or collapsed block props and that has at michael@0: // least one child that is a collapsed block prop." michael@0: function isCollapsedBlockProp(node) { michael@0: if (isCollapsedLineBreak(node) michael@0: && !isExtraneousLineBreak(node)) { michael@0: return true; michael@0: } michael@0: michael@0: if (!isInlineNode(node) michael@0: || node.nodeType != Node.ELEMENT_NODE) { michael@0: return false; michael@0: } michael@0: michael@0: var hasCollapsedBlockPropChild = false; michael@0: for (var i = 0; i < node.childNodes.length; i++) { michael@0: if (!isInvisible(node.childNodes[i]) michael@0: && !isCollapsedBlockProp(node.childNodes[i])) { michael@0: return false; michael@0: } michael@0: if (isCollapsedBlockProp(node.childNodes[i])) { michael@0: hasCollapsedBlockPropChild = true; michael@0: } michael@0: } michael@0: michael@0: return hasCollapsedBlockPropChild; michael@0: } michael@0: michael@0: // "The active range is the range of the selection given by calling michael@0: // getSelection() on the context object. (Thus the active range may be null.)" michael@0: // michael@0: // We cheat and return globalRange if that's defined. We also ensure that the michael@0: // active range meets the requirements that selection boundary points are michael@0: // supposed to meet, i.e., that the nodes are both Text or Element nodes that michael@0: // descend from a Document. michael@0: function getActiveRange() { michael@0: var ret; michael@0: if (globalRange) { michael@0: ret = globalRange; michael@0: } else if (getSelection().rangeCount) { michael@0: ret = getSelection().getRangeAt(0); michael@0: } else { michael@0: return null; michael@0: } michael@0: if ([Node.TEXT_NODE, Node.ELEMENT_NODE].indexOf(ret.startContainer.nodeType) == -1 michael@0: || [Node.TEXT_NODE, Node.ELEMENT_NODE].indexOf(ret.endContainer.nodeType) == -1 michael@0: || !ret.startContainer.ownerDocument michael@0: || !ret.endContainer.ownerDocument michael@0: || !isDescendant(ret.startContainer, ret.startContainer.ownerDocument) michael@0: || !isDescendant(ret.endContainer, ret.endContainer.ownerDocument)) { michael@0: throw "Invalid active range; test bug?"; michael@0: } michael@0: return ret; michael@0: } michael@0: michael@0: // "For some commands, each HTMLDocument must have a boolean state override michael@0: // and/or a string value override. These do not change the command's state or michael@0: // value, but change the way some algorithms behave, as specified in those michael@0: // algorithms' definitions. Initially, both must be unset for every command. michael@0: // Whenever the number of ranges in the Selection changes to something michael@0: // different, and whenever a boundary point of the range at a given index in michael@0: // the Selection changes to something different, the state override and value michael@0: // override must be unset for every command." michael@0: // michael@0: // We implement this crudely by using setters and getters. To verify that the michael@0: // selection hasn't changed, we copy the active range and just check the michael@0: // endpoints match. This isn't really correct, but it's good enough for us. michael@0: // Unset state/value overrides are undefined. We put everything in a function michael@0: // so no one can access anything except via the provided functions, since michael@0: // otherwise callers might mistakenly use outdated overrides (if the selection michael@0: // has changed). michael@0: var getStateOverride, setStateOverride, unsetStateOverride, michael@0: getValueOverride, setValueOverride, unsetValueOverride; michael@0: (function() { michael@0: var stateOverrides = {}; michael@0: var valueOverrides = {}; michael@0: var storedRange = null; michael@0: michael@0: function resetOverrides() { michael@0: if (!storedRange michael@0: || storedRange.startContainer != getActiveRange().startContainer michael@0: || storedRange.endContainer != getActiveRange().endContainer michael@0: || storedRange.startOffset != getActiveRange().startOffset michael@0: || storedRange.endOffset != getActiveRange().endOffset) { michael@0: stateOverrides = {}; michael@0: valueOverrides = {}; michael@0: storedRange = getActiveRange().cloneRange(); michael@0: } michael@0: } michael@0: michael@0: getStateOverride = function(command) { michael@0: resetOverrides(); michael@0: return stateOverrides[command]; michael@0: }; michael@0: michael@0: setStateOverride = function(command, newState) { michael@0: resetOverrides(); michael@0: stateOverrides[command] = newState; michael@0: }; michael@0: michael@0: unsetStateOverride = function(command) { michael@0: resetOverrides(); michael@0: delete stateOverrides[command]; michael@0: } michael@0: michael@0: getValueOverride = function(command) { michael@0: resetOverrides(); michael@0: return valueOverrides[command]; michael@0: } michael@0: michael@0: // "The value override for the backColor command must be the same as the michael@0: // value override for the hiliteColor command, such that setting one sets michael@0: // the other to the same thing and unsetting one unsets the other." michael@0: setValueOverride = function(command, newValue) { michael@0: resetOverrides(); michael@0: valueOverrides[command] = newValue; michael@0: if (command == "backcolor") { michael@0: valueOverrides.hilitecolor = newValue; michael@0: } else if (command == "hilitecolor") { michael@0: valueOverrides.backcolor = newValue; michael@0: } michael@0: } michael@0: michael@0: unsetValueOverride = function(command) { michael@0: resetOverrides(); michael@0: delete valueOverrides[command]; michael@0: if (command == "backcolor") { michael@0: delete valueOverrides.hilitecolor; michael@0: } else if (command == "hilitecolor") { michael@0: delete valueOverrides.backcolor; michael@0: } michael@0: } michael@0: })(); michael@0: michael@0: //@} michael@0: michael@0: ///////////////////////////// michael@0: ///// Common algorithms ///// michael@0: ///////////////////////////// michael@0: michael@0: ///// Assorted common algorithms ///// michael@0: //@{ michael@0: michael@0: // Magic array of extra ranges whose endpoints we want to preserve. michael@0: var extraRanges = []; michael@0: michael@0: function movePreservingRanges(node, newParent, newIndex) { michael@0: // For convenience, I allow newIndex to be -1 to mean "insert at the end". michael@0: if (newIndex == -1) { michael@0: newIndex = newParent.childNodes.length; michael@0: } michael@0: michael@0: // "When the user agent is to move a Node to a new location, preserving michael@0: // ranges, it must remove the Node from its original parent (if any), then michael@0: // insert it in the new location. In doing so, however, it must ignore the michael@0: // regular range mutation rules, and instead follow these rules:" michael@0: michael@0: // "Let node be the moved Node, old parent and old index be the old parent michael@0: // (which may be null) and index, and new parent and new index be the new michael@0: // parent and index." michael@0: var oldParent = node.parentNode; michael@0: var oldIndex = getNodeIndex(node); michael@0: michael@0: // We preserve the global range object, the ranges in the selection, and michael@0: // any range that's in the extraRanges array. Any other ranges won't get michael@0: // updated, because we have no references to them. michael@0: var ranges = [globalRange].concat(extraRanges); michael@0: for (var i = 0; i < getSelection().rangeCount; i++) { michael@0: ranges.push(getSelection().getRangeAt(i)); michael@0: } michael@0: var boundaryPoints = []; michael@0: ranges.forEach(function(range) { michael@0: boundaryPoints.push([range.startContainer, range.startOffset]); michael@0: boundaryPoints.push([range.endContainer, range.endOffset]); michael@0: }); michael@0: michael@0: boundaryPoints.forEach(function(boundaryPoint) { michael@0: // "If a boundary point's node is the same as or a descendant of node, michael@0: // leave it unchanged, so it moves to the new location." michael@0: // michael@0: // No modifications necessary. michael@0: michael@0: // "If a boundary point's node is new parent and its offset is greater michael@0: // than new index, add one to its offset." michael@0: if (boundaryPoint[0] == newParent michael@0: && boundaryPoint[1] > newIndex) { michael@0: boundaryPoint[1]++; michael@0: } michael@0: michael@0: // "If a boundary point's node is old parent and its offset is old index or michael@0: // old index + 1, set its node to new parent and add new index − old index michael@0: // to its offset." michael@0: if (boundaryPoint[0] == oldParent michael@0: && (boundaryPoint[1] == oldIndex michael@0: || boundaryPoint[1] == oldIndex + 1)) { michael@0: boundaryPoint[0] = newParent; michael@0: boundaryPoint[1] += newIndex - oldIndex; michael@0: } michael@0: michael@0: // "If a boundary point's node is old parent and its offset is greater than michael@0: // old index + 1, subtract one from its offset." michael@0: if (boundaryPoint[0] == oldParent michael@0: && boundaryPoint[1] > oldIndex + 1) { michael@0: boundaryPoint[1]--; michael@0: } michael@0: }); michael@0: michael@0: // Now actually move it and preserve the ranges. michael@0: if (newParent.childNodes.length == newIndex) { michael@0: newParent.appendChild(node); michael@0: } else { michael@0: newParent.insertBefore(node, newParent.childNodes[newIndex]); michael@0: } michael@0: michael@0: globalRange.setStart(boundaryPoints[0][0], boundaryPoints[0][1]); michael@0: globalRange.setEnd(boundaryPoints[1][0], boundaryPoints[1][1]); michael@0: michael@0: for (var i = 0; i < extraRanges.length; i++) { michael@0: extraRanges[i].setStart(boundaryPoints[2*i + 2][0], boundaryPoints[2*i + 2][1]); michael@0: extraRanges[i].setEnd(boundaryPoints[2*i + 3][0], boundaryPoints[2*i + 3][1]); michael@0: } michael@0: michael@0: getSelection().removeAllRanges(); michael@0: for (var i = 1 + extraRanges.length; i < ranges.length; i++) { michael@0: var newRange = document.createRange(); michael@0: newRange.setStart(boundaryPoints[2*i][0], boundaryPoints[2*i][1]); michael@0: newRange.setEnd(boundaryPoints[2*i + 1][0], boundaryPoints[2*i + 1][1]); michael@0: getSelection().addRange(newRange); michael@0: } michael@0: } michael@0: michael@0: function setTagName(element, newName) { michael@0: // "If element is an HTML element with local name equal to new name, return michael@0: // element." michael@0: if (isHtmlElement(element, newName.toUpperCase())) { michael@0: return element; michael@0: } michael@0: michael@0: // "If element's parent is null, return element." michael@0: if (!element.parentNode) { michael@0: return element; michael@0: } michael@0: michael@0: // "Let replacement element be the result of calling createElement(new michael@0: // name) on the ownerDocument of element." michael@0: var replacementElement = element.ownerDocument.createElement(newName); michael@0: michael@0: // "Insert replacement element into element's parent immediately before michael@0: // element." michael@0: element.parentNode.insertBefore(replacementElement, element); michael@0: michael@0: // "Copy all attributes of element to replacement element, in order." michael@0: for (var i = 0; i < element.attributes.length; i++) { michael@0: replacementElement.setAttributeNS(element.attributes[i].namespaceURI, element.attributes[i].name, element.attributes[i].value); michael@0: } michael@0: michael@0: // "While element has children, append the first child of element as the michael@0: // last child of replacement element, preserving ranges." michael@0: while (element.childNodes.length) { michael@0: movePreservingRanges(element.firstChild, replacementElement, replacementElement.childNodes.length); michael@0: } michael@0: michael@0: // "Remove element from its parent." michael@0: element.parentNode.removeChild(element); michael@0: michael@0: // "Return replacement element." michael@0: return replacementElement; michael@0: } michael@0: michael@0: function removeExtraneousLineBreaksBefore(node) { michael@0: // "Let ref be the previousSibling of node." michael@0: var ref = node.previousSibling; michael@0: michael@0: // "If ref is null, abort these steps." michael@0: if (!ref) { michael@0: return; michael@0: } michael@0: michael@0: // "While ref has children, set ref to its lastChild." michael@0: while (ref.hasChildNodes()) { michael@0: ref = ref.lastChild; michael@0: } michael@0: michael@0: // "While ref is invisible but not an extraneous line break, and ref does michael@0: // not equal node's parent, set ref to the node before it in tree order." michael@0: while (isInvisible(ref) michael@0: && !isExtraneousLineBreak(ref) michael@0: && ref != node.parentNode) { michael@0: ref = previousNode(ref); michael@0: } michael@0: michael@0: // "If ref is an editable extraneous line break, remove it from its michael@0: // parent." michael@0: if (isEditable(ref) michael@0: && isExtraneousLineBreak(ref)) { michael@0: ref.parentNode.removeChild(ref); michael@0: } michael@0: } michael@0: michael@0: function removeExtraneousLineBreaksAtTheEndOf(node) { michael@0: // "Let ref be node." michael@0: var ref = node; michael@0: michael@0: // "While ref has children, set ref to its lastChild." michael@0: while (ref.hasChildNodes()) { michael@0: ref = ref.lastChild; michael@0: } michael@0: michael@0: // "While ref is invisible but not an extraneous line break, and ref does michael@0: // not equal node, set ref to the node before it in tree order." michael@0: while (isInvisible(ref) michael@0: && !isExtraneousLineBreak(ref) michael@0: && ref != node) { michael@0: ref = previousNode(ref); michael@0: } michael@0: michael@0: // "If ref is an editable extraneous line break:" michael@0: if (isEditable(ref) michael@0: && isExtraneousLineBreak(ref)) { michael@0: // "While ref's parent is editable and invisible, set ref to its michael@0: // parent." michael@0: while (isEditable(ref.parentNode) michael@0: && isInvisible(ref.parentNode)) { michael@0: ref = ref.parentNode; michael@0: } michael@0: michael@0: // "Remove ref from its parent." michael@0: ref.parentNode.removeChild(ref); michael@0: } michael@0: } michael@0: michael@0: // "To remove extraneous line breaks from a node, first remove extraneous line michael@0: // breaks before it, then remove extraneous line breaks at the end of it." michael@0: function removeExtraneousLineBreaksFrom(node) { michael@0: removeExtraneousLineBreaksBefore(node); michael@0: removeExtraneousLineBreaksAtTheEndOf(node); michael@0: } michael@0: michael@0: //@} michael@0: ///// Wrapping a list of nodes ///// michael@0: //@{ michael@0: michael@0: function wrap(nodeList, siblingCriteria, newParentInstructions) { michael@0: // "If not provided, sibling criteria returns false and new parent michael@0: // instructions returns null." michael@0: if (typeof siblingCriteria == "undefined") { michael@0: siblingCriteria = function() { return false }; michael@0: } michael@0: if (typeof newParentInstructions == "undefined") { michael@0: newParentInstructions = function() { return null }; michael@0: } michael@0: michael@0: // "If every member of node list is invisible, and none is a br, return michael@0: // null and abort these steps." michael@0: if (nodeList.every(isInvisible) michael@0: && !nodeList.some(function(node) { return isHtmlElement(node, "br") })) { michael@0: return null; michael@0: } michael@0: michael@0: // "If node list's first member's parent is null, return null and abort michael@0: // these steps." michael@0: if (!nodeList[0].parentNode) { michael@0: return null; michael@0: } michael@0: michael@0: // "If node list's last member is an inline node that's not a br, and node michael@0: // list's last member's nextSibling is a br, append that br to node list." michael@0: if (isInlineNode(nodeList[nodeList.length - 1]) michael@0: && !isHtmlElement(nodeList[nodeList.length - 1], "br") michael@0: && isHtmlElement(nodeList[nodeList.length - 1].nextSibling, "br")) { michael@0: nodeList.push(nodeList[nodeList.length - 1].nextSibling); michael@0: } michael@0: michael@0: // "While node list's first member's previousSibling is invisible, prepend michael@0: // it to node list." michael@0: while (isInvisible(nodeList[0].previousSibling)) { michael@0: nodeList.unshift(nodeList[0].previousSibling); michael@0: } michael@0: michael@0: // "While node list's last member's nextSibling is invisible, append it to michael@0: // node list." michael@0: while (isInvisible(nodeList[nodeList.length - 1].nextSibling)) { michael@0: nodeList.push(nodeList[nodeList.length - 1].nextSibling); michael@0: } michael@0: michael@0: // "If the previousSibling of the first member of node list is editable and michael@0: // running sibling criteria on it returns true, let new parent be the michael@0: // previousSibling of the first member of node list." michael@0: var newParent; michael@0: if (isEditable(nodeList[0].previousSibling) michael@0: && siblingCriteria(nodeList[0].previousSibling)) { michael@0: newParent = nodeList[0].previousSibling; michael@0: michael@0: // "Otherwise, if the nextSibling of the last member of node list is michael@0: // editable and running sibling criteria on it returns true, let new parent michael@0: // be the nextSibling of the last member of node list." michael@0: } else if (isEditable(nodeList[nodeList.length - 1].nextSibling) michael@0: && siblingCriteria(nodeList[nodeList.length - 1].nextSibling)) { michael@0: newParent = nodeList[nodeList.length - 1].nextSibling; michael@0: michael@0: // "Otherwise, run new parent instructions, and let new parent be the michael@0: // result." michael@0: } else { michael@0: newParent = newParentInstructions(); michael@0: } michael@0: michael@0: // "If new parent is null, abort these steps and return null." michael@0: if (!newParent) { michael@0: return null; michael@0: } michael@0: michael@0: // "If new parent's parent is null:" michael@0: if (!newParent.parentNode) { michael@0: // "Insert new parent into the parent of the first member of node list michael@0: // immediately before the first member of node list." michael@0: nodeList[0].parentNode.insertBefore(newParent, nodeList[0]); michael@0: michael@0: // "If any range has a boundary point with node equal to the parent of michael@0: // new parent and offset equal to the index of new parent, add one to michael@0: // that boundary point's offset." michael@0: // michael@0: // Only try to fix the global range. michael@0: if (globalRange.startContainer == newParent.parentNode michael@0: && globalRange.startOffset == getNodeIndex(newParent)) { michael@0: globalRange.setStart(globalRange.startContainer, globalRange.startOffset + 1); michael@0: } michael@0: if (globalRange.endContainer == newParent.parentNode michael@0: && globalRange.endOffset == getNodeIndex(newParent)) { michael@0: globalRange.setEnd(globalRange.endContainer, globalRange.endOffset + 1); michael@0: } michael@0: } michael@0: michael@0: // "Let original parent be the parent of the first member of node list." michael@0: var originalParent = nodeList[0].parentNode; michael@0: michael@0: // "If new parent is before the first member of node list in tree order:" michael@0: if (isBefore(newParent, nodeList[0])) { michael@0: // "If new parent is not an inline node, but the last visible child of michael@0: // new parent and the first visible member of node list are both inline michael@0: // nodes, and the last child of new parent is not a br, call michael@0: // createElement("br") on the ownerDocument of new parent and append michael@0: // the result as the last child of new parent." michael@0: if (!isInlineNode(newParent) michael@0: && isInlineNode([].filter.call(newParent.childNodes, isVisible).slice(-1)[0]) michael@0: && isInlineNode(nodeList.filter(isVisible)[0]) michael@0: && !isHtmlElement(newParent.lastChild, "BR")) { michael@0: newParent.appendChild(newParent.ownerDocument.createElement("br")); michael@0: } michael@0: michael@0: // "For each node in node list, append node as the last child of new michael@0: // parent, preserving ranges." michael@0: for (var i = 0; i < nodeList.length; i++) { michael@0: movePreservingRanges(nodeList[i], newParent, -1); michael@0: } michael@0: michael@0: // "Otherwise:" michael@0: } else { michael@0: // "If new parent is not an inline node, but the first visible child of michael@0: // new parent and the last visible member of node list are both inline michael@0: // nodes, and the last member of node list is not a br, call michael@0: // createElement("br") on the ownerDocument of new parent and insert michael@0: // the result as the first child of new parent." michael@0: if (!isInlineNode(newParent) michael@0: && isInlineNode([].filter.call(newParent.childNodes, isVisible)[0]) michael@0: && isInlineNode(nodeList.filter(isVisible).slice(-1)[0]) michael@0: && !isHtmlElement(nodeList[nodeList.length - 1], "BR")) { michael@0: newParent.insertBefore(newParent.ownerDocument.createElement("br"), newParent.firstChild); michael@0: } michael@0: michael@0: // "For each node in node list, in reverse order, insert node as the michael@0: // first child of new parent, preserving ranges." michael@0: for (var i = nodeList.length - 1; i >= 0; i--) { michael@0: movePreservingRanges(nodeList[i], newParent, 0); michael@0: } michael@0: } michael@0: michael@0: // "If original parent is editable and has no children, remove it from its michael@0: // parent." michael@0: if (isEditable(originalParent) && !originalParent.hasChildNodes()) { michael@0: originalParent.parentNode.removeChild(originalParent); michael@0: } michael@0: michael@0: // "If new parent's nextSibling is editable and running sibling criteria on michael@0: // it returns true:" michael@0: if (isEditable(newParent.nextSibling) michael@0: && siblingCriteria(newParent.nextSibling)) { michael@0: // "If new parent is not an inline node, but new parent's last child michael@0: // and new parent's nextSibling's first child are both inline nodes, michael@0: // and new parent's last child is not a br, call createElement("br") on michael@0: // the ownerDocument of new parent and append the result as the last michael@0: // child of new parent." michael@0: if (!isInlineNode(newParent) michael@0: && isInlineNode(newParent.lastChild) michael@0: && isInlineNode(newParent.nextSibling.firstChild) michael@0: && !isHtmlElement(newParent.lastChild, "BR")) { michael@0: newParent.appendChild(newParent.ownerDocument.createElement("br")); michael@0: } michael@0: michael@0: // "While new parent's nextSibling has children, append its first child michael@0: // as the last child of new parent, preserving ranges." michael@0: while (newParent.nextSibling.hasChildNodes()) { michael@0: movePreservingRanges(newParent.nextSibling.firstChild, newParent, -1); michael@0: } michael@0: michael@0: // "Remove new parent's nextSibling from its parent." michael@0: newParent.parentNode.removeChild(newParent.nextSibling); michael@0: } michael@0: michael@0: // "Remove extraneous line breaks from new parent." michael@0: removeExtraneousLineBreaksFrom(newParent); michael@0: michael@0: // "Return new parent." michael@0: return newParent; michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Allowed children ///// michael@0: //@{ michael@0: michael@0: // "A name of an element with inline contents is "a", "abbr", "b", "bdi", michael@0: // "bdo", "cite", "code", "dfn", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i", michael@0: // "kbd", "mark", "p", "pre", "q", "rp", "rt", "ruby", "s", "samp", "small", michael@0: // "span", "strong", "sub", "sup", "u", "var", "acronym", "listing", "strike", michael@0: // "xmp", "big", "blink", "font", "marquee", "nobr", or "tt"." michael@0: var namesOfElementsWithInlineContents = ["a", "abbr", "b", "bdi", "bdo", michael@0: "cite", "code", "dfn", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i", michael@0: "kbd", "mark", "p", "pre", "q", "rp", "rt", "ruby", "s", "samp", "small", michael@0: "span", "strong", "sub", "sup", "u", "var", "acronym", "listing", "strike", michael@0: "xmp", "big", "blink", "font", "marquee", "nobr", "tt"]; michael@0: michael@0: // "An element with inline contents is an HTML element whose local name is a michael@0: // name of an element with inline contents." michael@0: function isElementWithInlineContents(node) { michael@0: return isHtmlElement(node, namesOfElementsWithInlineContents); michael@0: } michael@0: michael@0: function isAllowedChild(child, parent_) { michael@0: // "If parent is "colgroup", "table", "tbody", "tfoot", "thead", "tr", or michael@0: // an HTML element with local name equal to one of those, and child is a michael@0: // Text node whose data does not consist solely of space characters, return michael@0: // false." michael@0: if ((["colgroup", "table", "tbody", "tfoot", "thead", "tr"].indexOf(parent_) != -1 michael@0: || isHtmlElement(parent_, ["colgroup", "table", "tbody", "tfoot", "thead", "tr"])) michael@0: && typeof child == "object" michael@0: && child.nodeType == Node.TEXT_NODE michael@0: && !/^[ \t\n\f\r]*$/.test(child.data)) { michael@0: return false; michael@0: } michael@0: michael@0: // "If parent is "script", "style", "plaintext", or "xmp", or an HTML michael@0: // element with local name equal to one of those, and child is not a Text michael@0: // node, return false." michael@0: if ((["script", "style", "plaintext", "xmp"].indexOf(parent_) != -1 michael@0: || isHtmlElement(parent_, ["script", "style", "plaintext", "xmp"])) michael@0: && (typeof child != "object" || child.nodeType != Node.TEXT_NODE)) { michael@0: return false; michael@0: } michael@0: michael@0: // "If child is a Document, DocumentFragment, or DocumentType, return michael@0: // false." michael@0: if (typeof child == "object" michael@0: && (child.nodeType == Node.DOCUMENT_NODE michael@0: || child.nodeType == Node.DOCUMENT_FRAGMENT_NODE michael@0: || child.nodeType == Node.DOCUMENT_TYPE_NODE)) { michael@0: return false; michael@0: } michael@0: michael@0: // "If child is an HTML element, set child to the local name of child." michael@0: if (isHtmlElement(child)) { michael@0: child = child.tagName.toLowerCase(); michael@0: } michael@0: michael@0: // "If child is not a string, return true." michael@0: if (typeof child != "string") { michael@0: return true; michael@0: } michael@0: michael@0: // "If parent is an HTML element:" michael@0: if (isHtmlElement(parent_)) { michael@0: // "If child is "a", and parent or some ancestor of parent is an a, michael@0: // return false." michael@0: // michael@0: // "If child is a prohibited paragraph child name and parent or some michael@0: // ancestor of parent is an element with inline contents, return michael@0: // false." michael@0: // michael@0: // "If child is "h1", "h2", "h3", "h4", "h5", or "h6", and parent or michael@0: // some ancestor of parent is an HTML element with local name "h1", michael@0: // "h2", "h3", "h4", "h5", or "h6", return false." michael@0: var ancestor = parent_; michael@0: while (ancestor) { michael@0: if (child == "a" && isHtmlElement(ancestor, "a")) { michael@0: return false; michael@0: } michael@0: if (prohibitedParagraphChildNames.indexOf(child) != -1 michael@0: && isElementWithInlineContents(ancestor)) { michael@0: return false; michael@0: } michael@0: if (/^h[1-6]$/.test(child) michael@0: && isHtmlElement(ancestor) michael@0: && /^H[1-6]$/.test(ancestor.tagName)) { michael@0: return false; michael@0: } michael@0: ancestor = ancestor.parentNode; michael@0: } michael@0: michael@0: // "Let parent be the local name of parent." michael@0: parent_ = parent_.tagName.toLowerCase(); michael@0: } michael@0: michael@0: // "If parent is an Element or DocumentFragment, return true." michael@0: if (typeof parent_ == "object" michael@0: && (parent_.nodeType == Node.ELEMENT_NODE michael@0: || parent_.nodeType == Node.DOCUMENT_FRAGMENT_NODE)) { michael@0: return true; michael@0: } michael@0: michael@0: // "If parent is not a string, return false." michael@0: if (typeof parent_ != "string") { michael@0: return false; michael@0: } michael@0: michael@0: // "If parent is on the left-hand side of an entry on the following list, michael@0: // then return true if child is listed on the right-hand side of that michael@0: // entry, and false otherwise." michael@0: switch (parent_) { michael@0: case "colgroup": michael@0: return child == "col"; michael@0: case "table": michael@0: return ["caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"].indexOf(child) != -1; michael@0: case "tbody": michael@0: case "thead": michael@0: case "tfoot": michael@0: return ["td", "th", "tr"].indexOf(child) != -1; michael@0: case "tr": michael@0: return ["td", "th"].indexOf(child) != -1; michael@0: case "dl": michael@0: return ["dt", "dd"].indexOf(child) != -1; michael@0: case "dir": michael@0: case "ol": michael@0: case "ul": michael@0: return ["dir", "li", "ol", "ul"].indexOf(child) != -1; michael@0: case "hgroup": michael@0: return /^h[1-6]$/.test(child); michael@0: } michael@0: michael@0: // "If child is "body", "caption", "col", "colgroup", "frame", "frameset", michael@0: // "head", "html", "tbody", "td", "tfoot", "th", "thead", or "tr", return michael@0: // false." michael@0: if (["body", "caption", "col", "colgroup", "frame", "frameset", "head", michael@0: "html", "tbody", "td", "tfoot", "th", "thead", "tr"].indexOf(child) != -1) { michael@0: return false; michael@0: } michael@0: michael@0: // "If child is "dd" or "dt" and parent is not "dl", return false." michael@0: if (["dd", "dt"].indexOf(child) != -1 michael@0: && parent_ != "dl") { michael@0: return false; michael@0: } michael@0: michael@0: // "If child is "li" and parent is not "ol" or "ul", return false." michael@0: if (child == "li" michael@0: && parent_ != "ol" michael@0: && parent_ != "ul") { michael@0: return false; michael@0: } michael@0: michael@0: // "If parent is on the left-hand side of an entry on the following list michael@0: // and child is listed on the right-hand side of that entry, return false." michael@0: var table = [ michael@0: [["a"], ["a"]], michael@0: [["dd", "dt"], ["dd", "dt"]], michael@0: [["h1", "h2", "h3", "h4", "h5", "h6"], ["h1", "h2", "h3", "h4", "h5", "h6"]], michael@0: [["li"], ["li"]], michael@0: [["nobr"], ["nobr"]], michael@0: [namesOfElementsWithInlineContents, prohibitedParagraphChildNames], michael@0: [["td", "th"], ["caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"]], michael@0: ]; michael@0: for (var i = 0; i < table.length; i++) { michael@0: if (table[i][0].indexOf(parent_) != -1 michael@0: && table[i][1].indexOf(child) != -1) { michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: michael@0: //@} michael@0: michael@0: ////////////////////////////////////// michael@0: ///// Inline formatting commands ///// michael@0: ////////////////////////////////////// michael@0: michael@0: ///// Inline formatting command definitions ///// michael@0: //@{ michael@0: michael@0: // "A node node is effectively contained in a range range if range is not michael@0: // collapsed, and at least one of the following holds:" michael@0: function isEffectivelyContained(node, range) { michael@0: if (range.collapsed) { michael@0: return false; michael@0: } michael@0: michael@0: // "node is contained in range." michael@0: if (isContained(node, range)) { michael@0: return true; michael@0: } michael@0: michael@0: // "node is range's start node, it is a Text node, and its length is michael@0: // different from range's start offset." michael@0: if (node == range.startContainer michael@0: && node.nodeType == Node.TEXT_NODE michael@0: && getNodeLength(node) != range.startOffset) { michael@0: return true; michael@0: } michael@0: michael@0: // "node is range's end node, it is a Text node, and range's end offset is michael@0: // not 0." michael@0: if (node == range.endContainer michael@0: && node.nodeType == Node.TEXT_NODE michael@0: && range.endOffset != 0) { michael@0: return true; michael@0: } michael@0: michael@0: // "node has at least one child; and all its children are effectively michael@0: // contained in range; and either range's start node is not a descendant of michael@0: // node or is not a Text node or range's start offset is zero; and either michael@0: // range's end node is not a descendant of node or is not a Text node or michael@0: // range's end offset is its end node's length." michael@0: if (node.hasChildNodes() michael@0: && [].every.call(node.childNodes, function(child) { return isEffectivelyContained(child, range) }) michael@0: && (!isDescendant(range.startContainer, node) michael@0: || range.startContainer.nodeType != Node.TEXT_NODE michael@0: || range.startOffset == 0) michael@0: && (!isDescendant(range.endContainer, node) michael@0: || range.endContainer.nodeType != Node.TEXT_NODE michael@0: || range.endOffset == getNodeLength(range.endContainer))) { michael@0: return true; michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: // Like get(All)ContainedNodes(), but for effectively contained nodes. michael@0: function getEffectivelyContainedNodes(range, condition) { michael@0: if (typeof condition == "undefined") { michael@0: condition = function() { return true }; michael@0: } michael@0: var node = range.startContainer; michael@0: while (isEffectivelyContained(node.parentNode, range)) { michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: var stop = nextNodeDescendants(range.endContainer); michael@0: michael@0: var nodeList = []; michael@0: while (isBefore(node, stop)) { michael@0: if (isEffectivelyContained(node, range) michael@0: && condition(node)) { michael@0: nodeList.push(node); michael@0: node = nextNodeDescendants(node); michael@0: continue; michael@0: } michael@0: node = nextNode(node); michael@0: } michael@0: return nodeList; michael@0: } michael@0: michael@0: function getAllEffectivelyContainedNodes(range, condition) { michael@0: if (typeof condition == "undefined") { michael@0: condition = function() { return true }; michael@0: } michael@0: var node = range.startContainer; michael@0: while (isEffectivelyContained(node.parentNode, range)) { michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: var stop = nextNodeDescendants(range.endContainer); michael@0: michael@0: var nodeList = []; michael@0: while (isBefore(node, stop)) { michael@0: if (isEffectivelyContained(node, range) michael@0: && condition(node)) { michael@0: nodeList.push(node); michael@0: } michael@0: node = nextNode(node); michael@0: } michael@0: return nodeList; michael@0: } michael@0: michael@0: // "A modifiable element is a b, em, i, s, span, strong, sub, sup, or u element michael@0: // with no attributes except possibly style; or a font element with no michael@0: // attributes except possibly style, color, face, and/or size; or an a element michael@0: // with no attributes except possibly style and/or href." michael@0: function isModifiableElement(node) { michael@0: if (!isHtmlElement(node)) { michael@0: return false; michael@0: } michael@0: michael@0: if (["B", "EM", "I", "S", "SPAN", "STRIKE", "STRONG", "SUB", "SUP", "U"].indexOf(node.tagName) != -1) { michael@0: if (node.attributes.length == 0) { michael@0: return true; michael@0: } michael@0: michael@0: if (node.attributes.length == 1 michael@0: && node.hasAttribute("style")) { michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: if (node.tagName == "FONT" || node.tagName == "A") { michael@0: var numAttrs = node.attributes.length; michael@0: michael@0: if (node.hasAttribute("style")) { michael@0: numAttrs--; michael@0: } michael@0: michael@0: if (node.tagName == "FONT") { michael@0: if (node.hasAttribute("color")) { michael@0: numAttrs--; michael@0: } michael@0: michael@0: if (node.hasAttribute("face")) { michael@0: numAttrs--; michael@0: } michael@0: michael@0: if (node.hasAttribute("size")) { michael@0: numAttrs--; michael@0: } michael@0: } michael@0: michael@0: if (node.tagName == "A" michael@0: && node.hasAttribute("href")) { michael@0: numAttrs--; michael@0: } michael@0: michael@0: if (numAttrs == 0) { michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: function isSimpleModifiableElement(node) { michael@0: // "A simple modifiable element is an HTML element for which at least one michael@0: // of the following holds:" michael@0: if (!isHtmlElement(node)) { michael@0: return false; michael@0: } michael@0: michael@0: // Only these elements can possibly be a simple modifiable element. michael@0: if (["A", "B", "EM", "FONT", "I", "S", "SPAN", "STRIKE", "STRONG", "SUB", "SUP", "U"].indexOf(node.tagName) == -1) { michael@0: return false; michael@0: } michael@0: michael@0: // "It is an a, b, em, font, i, s, span, strike, strong, sub, sup, or u michael@0: // element with no attributes." michael@0: if (node.attributes.length == 0) { michael@0: return true; michael@0: } michael@0: michael@0: // If it's got more than one attribute, everything after this fails. michael@0: if (node.attributes.length > 1) { michael@0: return false; michael@0: } michael@0: michael@0: // "It is an a, b, em, font, i, s, span, strike, strong, sub, sup, or u michael@0: // element with exactly one attribute, which is style, which sets no CSS michael@0: // properties (including invalid or unrecognized properties)." michael@0: // michael@0: // Not gonna try for invalid or unrecognized. michael@0: if (node.hasAttribute("style") michael@0: && node.style.length == 0) { michael@0: return true; michael@0: } michael@0: michael@0: // "It is an a element with exactly one attribute, which is href." michael@0: if (node.tagName == "A" michael@0: && node.hasAttribute("href")) { michael@0: return true; michael@0: } michael@0: michael@0: // "It is a font element with exactly one attribute, which is either color, michael@0: // face, or size." michael@0: if (node.tagName == "FONT" michael@0: && (node.hasAttribute("color") michael@0: || node.hasAttribute("face") michael@0: || node.hasAttribute("size") michael@0: )) { michael@0: return true; michael@0: } michael@0: michael@0: // "It is a b or strong element with exactly one attribute, which is style, michael@0: // and the style attribute sets exactly one CSS property (including invalid michael@0: // or unrecognized properties), which is "font-weight"." michael@0: if ((node.tagName == "B" || node.tagName == "STRONG") michael@0: && node.hasAttribute("style") michael@0: && node.style.length == 1 michael@0: && node.style.fontWeight != "") { michael@0: return true; michael@0: } michael@0: michael@0: // "It is an i or em element with exactly one attribute, which is style, michael@0: // and the style attribute sets exactly one CSS property (including invalid michael@0: // or unrecognized properties), which is "font-style"." michael@0: if ((node.tagName == "I" || node.tagName == "EM") michael@0: && node.hasAttribute("style") michael@0: && node.style.length == 1 michael@0: && node.style.fontStyle != "") { michael@0: return true; michael@0: } michael@0: michael@0: // "It is an a, font, or span element with exactly one attribute, which is michael@0: // style, and the style attribute sets exactly one CSS property (including michael@0: // invalid or unrecognized properties), and that property is not michael@0: // "text-decoration"." michael@0: if ((node.tagName == "A" || node.tagName == "FONT" || node.tagName == "SPAN") michael@0: && node.hasAttribute("style") michael@0: && node.style.length == 1 michael@0: && node.style.textDecoration == "") { michael@0: return true; michael@0: } michael@0: michael@0: // "It is an a, font, s, span, strike, or u element with exactly one michael@0: // attribute, which is style, and the style attribute sets exactly one CSS michael@0: // property (including invalid or unrecognized properties), which is michael@0: // "text-decoration", which is set to "line-through" or "underline" or michael@0: // "overline" or "none"." michael@0: // michael@0: // The weird extra node.style.length check is for Firefox, which as of michael@0: // 8.0a2 has annoying and weird behavior here. michael@0: if (["A", "FONT", "S", "SPAN", "STRIKE", "U"].indexOf(node.tagName) != -1 michael@0: && node.hasAttribute("style") michael@0: && (node.style.length == 1 michael@0: || (node.style.length == 4 michael@0: && "MozTextBlink" in node.style michael@0: && "MozTextDecorationColor" in node.style michael@0: && "MozTextDecorationLine" in node.style michael@0: && "MozTextDecorationStyle" in node.style) michael@0: ) michael@0: && (node.style.textDecoration == "line-through" michael@0: || node.style.textDecoration == "underline" michael@0: || node.style.textDecoration == "overline" michael@0: || node.style.textDecoration == "none")) { michael@0: return true; michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: // "A formattable node is an editable visible node that is either a Text node, michael@0: // an img, or a br." michael@0: function isFormattableNode(node) { michael@0: return isEditable(node) michael@0: && isVisible(node) michael@0: && (node.nodeType == Node.TEXT_NODE michael@0: || isHtmlElement(node, ["img", "br"])); michael@0: } michael@0: michael@0: // "Two quantities are equivalent values for a command if either both are null, michael@0: // or both are strings and they're equal and the command does not define any michael@0: // equivalent values, or both are strings and the command defines equivalent michael@0: // values and they match the definition." michael@0: function areEquivalentValues(command, val1, val2) { michael@0: if (val1 === null && val2 === null) { michael@0: return true; michael@0: } michael@0: michael@0: if (typeof val1 == "string" michael@0: && typeof val2 == "string" michael@0: && val1 == val2 michael@0: && !("equivalentValues" in commands[command])) { michael@0: return true; michael@0: } michael@0: michael@0: if (typeof val1 == "string" michael@0: && typeof val2 == "string" michael@0: && "equivalentValues" in commands[command] michael@0: && commands[command].equivalentValues(val1, val2)) { michael@0: return true; michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: // "Two quantities are loosely equivalent values for a command if either they michael@0: // are equivalent values for the command, or if the command is the fontSize michael@0: // command; one of the quantities is one of "x-small", "small", "medium", michael@0: // "large", "x-large", "xx-large", or "xxx-large"; and the other quantity is michael@0: // the resolved value of "font-size" on a font element whose size attribute has michael@0: // the corresponding value set ("1" through "7" respectively)." michael@0: function areLooselyEquivalentValues(command, val1, val2) { michael@0: if (areEquivalentValues(command, val1, val2)) { michael@0: return true; michael@0: } michael@0: michael@0: if (command != "fontsize" michael@0: || typeof val1 != "string" michael@0: || typeof val2 != "string") { michael@0: return false; michael@0: } michael@0: michael@0: // Static variables in JavaScript? michael@0: var callee = areLooselyEquivalentValues; michael@0: if (callee.sizeMap === undefined) { michael@0: callee.sizeMap = {}; michael@0: var font = document.createElement("font"); michael@0: document.body.appendChild(font); michael@0: ["x-small", "small", "medium", "large", "x-large", "xx-large", michael@0: "xxx-large"].forEach(function(keyword) { michael@0: font.size = cssSizeToLegacy(keyword); michael@0: callee.sizeMap[keyword] = getComputedStyle(font).fontSize; michael@0: }); michael@0: document.body.removeChild(font); michael@0: } michael@0: michael@0: return val1 === callee.sizeMap[val2] michael@0: || val2 === callee.sizeMap[val1]; michael@0: } michael@0: michael@0: //@} michael@0: ///// Assorted inline formatting command algorithms ///// michael@0: //@{ michael@0: michael@0: function getEffectiveCommandValue(node, command) { michael@0: // "If neither node nor its parent is an Element, return null." michael@0: if (node.nodeType != Node.ELEMENT_NODE michael@0: && (!node.parentNode || node.parentNode.nodeType != Node.ELEMENT_NODE)) { michael@0: return null; michael@0: } michael@0: michael@0: // "If node is not an Element, return the effective command value of its michael@0: // parent for command." michael@0: if (node.nodeType != Node.ELEMENT_NODE) { michael@0: return getEffectiveCommandValue(node.parentNode, command); michael@0: } michael@0: michael@0: // "If command is "createLink" or "unlink":" michael@0: if (command == "createlink" || command == "unlink") { michael@0: // "While node is not null, and is not an a element that has an href michael@0: // attribute, set node to its parent." michael@0: while (node michael@0: && (!isHtmlElement(node) michael@0: || node.tagName != "A" michael@0: || !node.hasAttribute("href"))) { michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: // "If node is null, return null." michael@0: if (!node) { michael@0: return null; michael@0: } michael@0: michael@0: // "Return the value of node's href attribute." michael@0: return node.getAttribute("href"); michael@0: } michael@0: michael@0: // "If command is "backColor" or "hiliteColor":" michael@0: if (command == "backcolor" michael@0: || command == "hilitecolor") { michael@0: // "While the resolved value of "background-color" on node is any michael@0: // fully transparent value, and node's parent is an Element, set michael@0: // node to its parent." michael@0: // michael@0: // Another lame hack to avoid flawed APIs. michael@0: while ((getComputedStyle(node).backgroundColor == "rgba(0, 0, 0, 0)" michael@0: || getComputedStyle(node).backgroundColor === "" michael@0: || getComputedStyle(node).backgroundColor == "transparent") michael@0: && node.parentNode michael@0: && node.parentNode.nodeType == Node.ELEMENT_NODE) { michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: // "Return the resolved value of "background-color" for node." michael@0: return getComputedStyle(node).backgroundColor; michael@0: } michael@0: michael@0: // "If command is "subscript" or "superscript":" michael@0: if (command == "subscript" || command == "superscript") { michael@0: // "Let affected by subscript and affected by superscript be two michael@0: // boolean variables, both initially false." michael@0: var affectedBySubscript = false; michael@0: var affectedBySuperscript = false; michael@0: michael@0: // "While node is an inline node:" michael@0: while (isInlineNode(node)) { michael@0: var verticalAlign = getComputedStyle(node).verticalAlign; michael@0: michael@0: // "If node is a sub, set affected by subscript to true." michael@0: if (isHtmlElement(node, "sub")) { michael@0: affectedBySubscript = true; michael@0: // "Otherwise, if node is a sup, set affected by superscript to michael@0: // true." michael@0: } else if (isHtmlElement(node, "sup")) { michael@0: affectedBySuperscript = true; michael@0: } michael@0: michael@0: // "Set node to its parent." michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: // "If affected by subscript and affected by superscript are both true, michael@0: // return the string "mixed"." michael@0: if (affectedBySubscript && affectedBySuperscript) { michael@0: return "mixed"; michael@0: } michael@0: michael@0: // "If affected by subscript is true, return "subscript"." michael@0: if (affectedBySubscript) { michael@0: return "subscript"; michael@0: } michael@0: michael@0: // "If affected by superscript is true, return "superscript"." michael@0: if (affectedBySuperscript) { michael@0: return "superscript"; michael@0: } michael@0: michael@0: // "Return null." michael@0: return null; michael@0: } michael@0: michael@0: // "If command is "strikethrough", and the "text-decoration" property of michael@0: // node or any of its ancestors has resolved value containing michael@0: // "line-through", return "line-through". Otherwise, return null." michael@0: if (command == "strikethrough") { michael@0: do { michael@0: if (getComputedStyle(node).textDecoration.indexOf("line-through") != -1) { michael@0: return "line-through"; michael@0: } michael@0: node = node.parentNode; michael@0: } while (node && node.nodeType == Node.ELEMENT_NODE); michael@0: return null; michael@0: } michael@0: michael@0: // "If command is "underline", and the "text-decoration" property of node michael@0: // or any of its ancestors has resolved value containing "underline", michael@0: // return "underline". Otherwise, return null." michael@0: if (command == "underline") { michael@0: do { michael@0: if (getComputedStyle(node).textDecoration.indexOf("underline") != -1) { michael@0: return "underline"; michael@0: } michael@0: node = node.parentNode; michael@0: } while (node && node.nodeType == Node.ELEMENT_NODE); michael@0: return null; michael@0: } michael@0: michael@0: if (!("relevantCssProperty" in commands[command])) { michael@0: throw "Bug: no relevantCssProperty for " + command + " in getEffectiveCommandValue"; michael@0: } michael@0: michael@0: // "Return the resolved value for node of the relevant CSS property for michael@0: // command." michael@0: return getComputedStyle(node)[commands[command].relevantCssProperty]; michael@0: } michael@0: michael@0: function getSpecifiedCommandValue(element, command) { michael@0: // "If command is "backColor" or "hiliteColor" and element's display michael@0: // property does not have resolved value "inline", return null." michael@0: if ((command == "backcolor" || command == "hilitecolor") michael@0: && getComputedStyle(element).display != "inline") { michael@0: return null; michael@0: } michael@0: michael@0: // "If command is "createLink" or "unlink":" michael@0: if (command == "createlink" || command == "unlink") { michael@0: // "If element is an a element and has an href attribute, return the michael@0: // value of that attribute." michael@0: if (isHtmlElement(element) michael@0: && element.tagName == "A" michael@0: && element.hasAttribute("href")) { michael@0: return element.getAttribute("href"); michael@0: } michael@0: michael@0: // "Return null." michael@0: return null; michael@0: } michael@0: michael@0: // "If command is "subscript" or "superscript":" michael@0: if (command == "subscript" || command == "superscript") { michael@0: // "If element is a sup, return "superscript"." michael@0: if (isHtmlElement(element, "sup")) { michael@0: return "superscript"; michael@0: } michael@0: michael@0: // "If element is a sub, return "subscript"." michael@0: if (isHtmlElement(element, "sub")) { michael@0: return "subscript"; michael@0: } michael@0: michael@0: // "Return null." michael@0: return null; michael@0: } michael@0: michael@0: // "If command is "strikethrough", and element has a style attribute set, michael@0: // and that attribute sets "text-decoration":" michael@0: if (command == "strikethrough" michael@0: && element.style.textDecoration != "") { michael@0: // "If element's style attribute sets "text-decoration" to a value michael@0: // containing "line-through", return "line-through"." michael@0: if (element.style.textDecoration.indexOf("line-through") != -1) { michael@0: return "line-through"; michael@0: } michael@0: michael@0: // "Return null." michael@0: return null; michael@0: } michael@0: michael@0: // "If command is "strikethrough" and element is a s or strike element, michael@0: // return "line-through"." michael@0: if (command == "strikethrough" michael@0: && isHtmlElement(element, ["S", "STRIKE"])) { michael@0: return "line-through"; michael@0: } michael@0: michael@0: // "If command is "underline", and element has a style attribute set, and michael@0: // that attribute sets "text-decoration":" michael@0: if (command == "underline" michael@0: && element.style.textDecoration != "") { michael@0: // "If element's style attribute sets "text-decoration" to a value michael@0: // containing "underline", return "underline"." michael@0: if (element.style.textDecoration.indexOf("underline") != -1) { michael@0: return "underline"; michael@0: } michael@0: michael@0: // "Return null." michael@0: return null; michael@0: } michael@0: michael@0: // "If command is "underline" and element is a u element, return michael@0: // "underline"." michael@0: if (command == "underline" michael@0: && isHtmlElement(element, "U")) { michael@0: return "underline"; michael@0: } michael@0: michael@0: // "Let property be the relevant CSS property for command." michael@0: var property = commands[command].relevantCssProperty; michael@0: michael@0: // "If property is null, return null." michael@0: if (property === null) { michael@0: return null; michael@0: } michael@0: michael@0: // "If element has a style attribute set, and that attribute has the michael@0: // effect of setting property, return the value that it sets property to." michael@0: if (element.style[property] != "") { michael@0: return element.style[property]; michael@0: } michael@0: michael@0: // "If element is a font element that has an attribute whose effect is michael@0: // to create a presentational hint for property, return the value that the michael@0: // hint sets property to. (For a size of 7, this will be the non-CSS value michael@0: // "xxx-large".)" michael@0: if (isHtmlNamespace(element.namespaceURI) michael@0: && element.tagName == "FONT") { michael@0: if (property == "color" && element.hasAttribute("color")) { michael@0: return element.color; michael@0: } michael@0: if (property == "fontFamily" && element.hasAttribute("face")) { michael@0: return element.face; michael@0: } michael@0: if (property == "fontSize" && element.hasAttribute("size")) { michael@0: // This is not even close to correct in general. michael@0: var size = parseInt(element.size); michael@0: if (size < 1) { michael@0: size = 1; michael@0: } michael@0: if (size > 7) { michael@0: size = 7; michael@0: } michael@0: return { michael@0: 1: "x-small", michael@0: 2: "small", michael@0: 3: "medium", michael@0: 4: "large", michael@0: 5: "x-large", michael@0: 6: "xx-large", michael@0: 7: "xxx-large" michael@0: }[size]; michael@0: } michael@0: } michael@0: michael@0: // "If element is in the following list, and property is equal to the michael@0: // CSS property name listed for it, return the string listed for it." michael@0: // michael@0: // A list follows, whose meaning is copied here. michael@0: if (property == "fontWeight" michael@0: && (element.tagName == "B" || element.tagName == "STRONG")) { michael@0: return "bold"; michael@0: } michael@0: if (property == "fontStyle" michael@0: && (element.tagName == "I" || element.tagName == "EM")) { michael@0: return "italic"; michael@0: } michael@0: michael@0: // "Return null." michael@0: return null; michael@0: } michael@0: michael@0: function reorderModifiableDescendants(node, command, newValue) { michael@0: // "Let candidate equal node." michael@0: var candidate = node; michael@0: michael@0: // "While candidate is a modifiable element, and candidate has exactly one michael@0: // child, and that child is also a modifiable element, and candidate is not michael@0: // a simple modifiable element or candidate's specified command value for michael@0: // command is not equivalent to new value, set candidate to its child." michael@0: while (isModifiableElement(candidate) michael@0: && candidate.childNodes.length == 1 michael@0: && isModifiableElement(candidate.firstChild) michael@0: && (!isSimpleModifiableElement(candidate) michael@0: || !areEquivalentValues(command, getSpecifiedCommandValue(candidate, command), newValue))) { michael@0: candidate = candidate.firstChild; michael@0: } michael@0: michael@0: // "If candidate is node, or is not a simple modifiable element, or its michael@0: // specified command value is not equivalent to new value, or its effective michael@0: // command value is not loosely equivalent to new value, abort these michael@0: // steps." michael@0: if (candidate == node michael@0: || !isSimpleModifiableElement(candidate) michael@0: || !areEquivalentValues(command, getSpecifiedCommandValue(candidate, command), newValue) michael@0: || !areLooselyEquivalentValues(command, getEffectiveCommandValue(candidate, command), newValue)) { michael@0: return; michael@0: } michael@0: michael@0: // "While candidate has children, insert the first child of candidate into michael@0: // candidate's parent immediately before candidate, preserving ranges." michael@0: while (candidate.hasChildNodes()) { michael@0: movePreservingRanges(candidate.firstChild, candidate.parentNode, getNodeIndex(candidate)); michael@0: } michael@0: michael@0: // "Insert candidate into node's parent immediately after node." michael@0: node.parentNode.insertBefore(candidate, node.nextSibling); michael@0: michael@0: // "Append the node as the last child of candidate, preserving ranges." michael@0: movePreservingRanges(node, candidate, -1); michael@0: } michael@0: michael@0: function recordValues(nodeList) { michael@0: // "Let values be a list of (node, command, specified command value) michael@0: // triples, initially empty." michael@0: var values = []; michael@0: michael@0: // "For each node in node list, for each command in the list "subscript", michael@0: // "bold", "fontName", "fontSize", "foreColor", "hiliteColor", "italic", michael@0: // "strikethrough", and "underline" in that order:" michael@0: nodeList.forEach(function(node) { michael@0: ["subscript", "bold", "fontname", "fontsize", "forecolor", michael@0: "hilitecolor", "italic", "strikethrough", "underline"].forEach(function(command) { michael@0: // "Let ancestor equal node." michael@0: var ancestor = node; michael@0: michael@0: // "If ancestor is not an Element, set it to its parent." michael@0: if (ancestor.nodeType != Node.ELEMENT_NODE) { michael@0: ancestor = ancestor.parentNode; michael@0: } michael@0: michael@0: // "While ancestor is an Element and its specified command value michael@0: // for command is null, set it to its parent." michael@0: while (ancestor michael@0: && ancestor.nodeType == Node.ELEMENT_NODE michael@0: && getSpecifiedCommandValue(ancestor, command) === null) { michael@0: ancestor = ancestor.parentNode; michael@0: } michael@0: michael@0: // "If ancestor is an Element, add (node, command, ancestor's michael@0: // specified command value for command) to values. Otherwise add michael@0: // (node, command, null) to values." michael@0: if (ancestor && ancestor.nodeType == Node.ELEMENT_NODE) { michael@0: values.push([node, command, getSpecifiedCommandValue(ancestor, command)]); michael@0: } else { michael@0: values.push([node, command, null]); michael@0: } michael@0: }); michael@0: }); michael@0: michael@0: // "Return values." michael@0: return values; michael@0: } michael@0: michael@0: function restoreValues(values) { michael@0: // "For each (node, command, value) triple in values:" michael@0: values.forEach(function(triple) { michael@0: var node = triple[0]; michael@0: var command = triple[1]; michael@0: var value = triple[2]; michael@0: michael@0: // "Let ancestor equal node." michael@0: var ancestor = node; michael@0: michael@0: // "If ancestor is not an Element, set it to its parent." michael@0: if (!ancestor || ancestor.nodeType != Node.ELEMENT_NODE) { michael@0: ancestor = ancestor.parentNode; michael@0: } michael@0: michael@0: // "While ancestor is an Element and its specified command value for michael@0: // command is null, set it to its parent." michael@0: while (ancestor michael@0: && ancestor.nodeType == Node.ELEMENT_NODE michael@0: && getSpecifiedCommandValue(ancestor, command) === null) { michael@0: ancestor = ancestor.parentNode; michael@0: } michael@0: michael@0: // "If value is null and ancestor is an Element, push down values on michael@0: // node for command, with new value null." michael@0: if (value === null michael@0: && ancestor michael@0: && ancestor.nodeType == Node.ELEMENT_NODE) { michael@0: pushDownValues(node, command, null); michael@0: michael@0: // "Otherwise, if ancestor is an Element and its specified command michael@0: // value for command is not equivalent to value, or if ancestor is not michael@0: // an Element and value is not null, force the value of command to michael@0: // value on node." michael@0: } else if ((ancestor michael@0: && ancestor.nodeType == Node.ELEMENT_NODE michael@0: && !areEquivalentValues(command, getSpecifiedCommandValue(ancestor, command), value)) michael@0: || ((!ancestor || ancestor.nodeType != Node.ELEMENT_NODE) michael@0: && value !== null)) { michael@0: forceValue(node, command, value); michael@0: } michael@0: }); michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Clearing an element's value ///// michael@0: //@{ michael@0: michael@0: function clearValue(element, command) { michael@0: // "If element is not editable, return the empty list." michael@0: if (!isEditable(element)) { michael@0: return []; michael@0: } michael@0: michael@0: // "If element's specified command value for command is null, return the michael@0: // empty list." michael@0: if (getSpecifiedCommandValue(element, command) === null) { michael@0: return []; michael@0: } michael@0: michael@0: // "If element is a simple modifiable element:" michael@0: if (isSimpleModifiableElement(element)) { michael@0: // "Let children be the children of element." michael@0: var children = Array.prototype.slice.call(element.childNodes); michael@0: michael@0: // "For each child in children, insert child into element's parent michael@0: // immediately before element, preserving ranges." michael@0: for (var i = 0; i < children.length; i++) { michael@0: movePreservingRanges(children[i], element.parentNode, getNodeIndex(element)); michael@0: } michael@0: michael@0: // "Remove element from its parent." michael@0: element.parentNode.removeChild(element); michael@0: michael@0: // "Return children." michael@0: return children; michael@0: } michael@0: michael@0: // "If command is "strikethrough", and element has a style attribute that michael@0: // sets "text-decoration" to some value containing "line-through", delete michael@0: // "line-through" from the value." michael@0: if (command == "strikethrough" michael@0: && element.style.textDecoration.indexOf("line-through") != -1) { michael@0: if (element.style.textDecoration == "line-through") { michael@0: element.style.textDecoration = ""; michael@0: } else { michael@0: element.style.textDecoration = element.style.textDecoration.replace("line-through", ""); michael@0: } michael@0: if (element.getAttribute("style") == "") { michael@0: element.removeAttribute("style"); michael@0: } michael@0: } michael@0: michael@0: // "If command is "underline", and element has a style attribute that sets michael@0: // "text-decoration" to some value containing "underline", delete michael@0: // "underline" from the value." michael@0: if (command == "underline" michael@0: && element.style.textDecoration.indexOf("underline") != -1) { michael@0: if (element.style.textDecoration == "underline") { michael@0: element.style.textDecoration = ""; michael@0: } else { michael@0: element.style.textDecoration = element.style.textDecoration.replace("underline", ""); michael@0: } michael@0: if (element.getAttribute("style") == "") { michael@0: element.removeAttribute("style"); michael@0: } michael@0: } michael@0: michael@0: // "If the relevant CSS property for command is not null, unset the CSS michael@0: // property property of element." michael@0: if (commands[command].relevantCssProperty !== null) { michael@0: element.style[commands[command].relevantCssProperty] = ''; michael@0: if (element.getAttribute("style") == "") { michael@0: element.removeAttribute("style"); michael@0: } michael@0: } michael@0: michael@0: // "If element is a font element:" michael@0: if (isHtmlNamespace(element.namespaceURI) && element.tagName == "FONT") { michael@0: // "If command is "foreColor", unset element's color attribute, if set." michael@0: if (command == "forecolor") { michael@0: element.removeAttribute("color"); michael@0: } michael@0: michael@0: // "If command is "fontName", unset element's face attribute, if set." michael@0: if (command == "fontname") { michael@0: element.removeAttribute("face"); michael@0: } michael@0: michael@0: // "If command is "fontSize", unset element's size attribute, if set." michael@0: if (command == "fontsize") { michael@0: element.removeAttribute("size"); michael@0: } michael@0: } michael@0: michael@0: // "If element is an a element and command is "createLink" or "unlink", michael@0: // unset the href property of element." michael@0: if (isHtmlElement(element, "A") michael@0: && (command == "createlink" || command == "unlink")) { michael@0: element.removeAttribute("href"); michael@0: } michael@0: michael@0: // "If element's specified command value for command is null, return the michael@0: // empty list." michael@0: if (getSpecifiedCommandValue(element, command) === null) { michael@0: return []; michael@0: } michael@0: michael@0: // "Set the tag name of element to "span", and return the one-node list michael@0: // consisting of the result." michael@0: return [setTagName(element, "span")]; michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Pushing down values ///// michael@0: //@{ michael@0: michael@0: function pushDownValues(node, command, newValue) { michael@0: // "If node's parent is not an Element, abort this algorithm." michael@0: if (!node.parentNode michael@0: || node.parentNode.nodeType != Node.ELEMENT_NODE) { michael@0: return; michael@0: } michael@0: michael@0: // "If the effective command value of command is loosely equivalent to new michael@0: // value on node, abort this algorithm." michael@0: if (areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) { michael@0: return; michael@0: } michael@0: michael@0: // "Let current ancestor be node's parent." michael@0: var currentAncestor = node.parentNode; michael@0: michael@0: // "Let ancestor list be a list of Nodes, initially empty." michael@0: var ancestorList = []; michael@0: michael@0: // "While current ancestor is an editable Element and the effective command michael@0: // value of command is not loosely equivalent to new value on it, append michael@0: // current ancestor to ancestor list, then set current ancestor to its michael@0: // parent." michael@0: while (isEditable(currentAncestor) michael@0: && currentAncestor.nodeType == Node.ELEMENT_NODE michael@0: && !areLooselyEquivalentValues(command, getEffectiveCommandValue(currentAncestor, command), newValue)) { michael@0: ancestorList.push(currentAncestor); michael@0: currentAncestor = currentAncestor.parentNode; michael@0: } michael@0: michael@0: // "If ancestor list is empty, abort this algorithm." michael@0: if (!ancestorList.length) { michael@0: return; michael@0: } michael@0: michael@0: // "Let propagated value be the specified command value of command on the michael@0: // last member of ancestor list." michael@0: var propagatedValue = getSpecifiedCommandValue(ancestorList[ancestorList.length - 1], command); michael@0: michael@0: // "If propagated value is null and is not equal to new value, abort this michael@0: // algorithm." michael@0: if (propagatedValue === null && propagatedValue != newValue) { michael@0: return; michael@0: } michael@0: michael@0: // "If the effective command value for the parent of the last member of michael@0: // ancestor list is not loosely equivalent to new value, and new value is michael@0: // not null, abort this algorithm." michael@0: if (newValue !== null michael@0: && !areLooselyEquivalentValues(command, getEffectiveCommandValue(ancestorList[ancestorList.length - 1].parentNode, command), newValue)) { michael@0: return; michael@0: } michael@0: michael@0: // "While ancestor list is not empty:" michael@0: while (ancestorList.length) { michael@0: // "Let current ancestor be the last member of ancestor list." michael@0: // "Remove the last member from ancestor list." michael@0: var currentAncestor = ancestorList.pop(); michael@0: michael@0: // "If the specified command value of current ancestor for command is michael@0: // not null, set propagated value to that value." michael@0: if (getSpecifiedCommandValue(currentAncestor, command) !== null) { michael@0: propagatedValue = getSpecifiedCommandValue(currentAncestor, command); michael@0: } michael@0: michael@0: // "Let children be the children of current ancestor." michael@0: var children = Array.prototype.slice.call(currentAncestor.childNodes); michael@0: michael@0: // "If the specified command value of current ancestor for command is michael@0: // not null, clear the value of current ancestor." michael@0: if (getSpecifiedCommandValue(currentAncestor, command) !== null) { michael@0: clearValue(currentAncestor, command); michael@0: } michael@0: michael@0: // "For every child in children:" michael@0: for (var i = 0; i < children.length; i++) { michael@0: var child = children[i]; michael@0: michael@0: // "If child is node, continue with the next child." michael@0: if (child == node) { michael@0: continue; michael@0: } michael@0: michael@0: // "If child is an Element whose specified command value for michael@0: // command is neither null nor equivalent to propagated value, michael@0: // continue with the next child." michael@0: if (child.nodeType == Node.ELEMENT_NODE michael@0: && getSpecifiedCommandValue(child, command) !== null michael@0: && !areEquivalentValues(command, propagatedValue, getSpecifiedCommandValue(child, command))) { michael@0: continue; michael@0: } michael@0: michael@0: // "If child is the last member of ancestor list, continue with the michael@0: // next child." michael@0: if (child == ancestorList[ancestorList.length - 1]) { michael@0: continue; michael@0: } michael@0: michael@0: // "Force the value of child, with command as in this algorithm michael@0: // and new value equal to propagated value." michael@0: forceValue(child, command, propagatedValue); michael@0: } michael@0: } michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Forcing the value of a node ///// michael@0: //@{ michael@0: michael@0: function forceValue(node, command, newValue) { michael@0: // "If node's parent is null, abort this algorithm." michael@0: if (!node.parentNode) { michael@0: return; michael@0: } michael@0: michael@0: // "If new value is null, abort this algorithm." michael@0: if (newValue === null) { michael@0: return; michael@0: } michael@0: michael@0: // "If node is an allowed child of "span":" michael@0: if (isAllowedChild(node, "span")) { michael@0: // "Reorder modifiable descendants of node's previousSibling." michael@0: reorderModifiableDescendants(node.previousSibling, command, newValue); michael@0: michael@0: // "Reorder modifiable descendants of node's nextSibling." michael@0: reorderModifiableDescendants(node.nextSibling, command, newValue); michael@0: michael@0: // "Wrap the one-node list consisting of node, with sibling criteria michael@0: // returning true for a simple modifiable element whose specified michael@0: // command value is equivalent to new value and whose effective command michael@0: // value is loosely equivalent to new value and false otherwise, and michael@0: // with new parent instructions returning null." michael@0: wrap([node], michael@0: function(node) { michael@0: return isSimpleModifiableElement(node) michael@0: && areEquivalentValues(command, getSpecifiedCommandValue(node, command), newValue) michael@0: && areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue); michael@0: }, michael@0: function() { return null } michael@0: ); michael@0: } michael@0: michael@0: // "If node is invisible, abort this algorithm." michael@0: if (isInvisible(node)) { michael@0: return; michael@0: } michael@0: michael@0: // "If the effective command value of command is loosely equivalent to new michael@0: // value on node, abort this algorithm." michael@0: if (areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) { michael@0: return; michael@0: } michael@0: michael@0: // "If node is not an allowed child of "span":" michael@0: if (!isAllowedChild(node, "span")) { michael@0: // "Let children be all children of node, omitting any that are michael@0: // Elements whose specified command value for command is neither null michael@0: // nor equivalent to new value." michael@0: var children = []; michael@0: for (var i = 0; i < node.childNodes.length; i++) { michael@0: if (node.childNodes[i].nodeType == Node.ELEMENT_NODE) { michael@0: var specifiedValue = getSpecifiedCommandValue(node.childNodes[i], command); michael@0: michael@0: if (specifiedValue !== null michael@0: && !areEquivalentValues(command, newValue, specifiedValue)) { michael@0: continue; michael@0: } michael@0: } michael@0: children.push(node.childNodes[i]); michael@0: } michael@0: michael@0: // "Force the value of each Node in children, with command and new michael@0: // value as in this invocation of the algorithm." michael@0: for (var i = 0; i < children.length; i++) { michael@0: forceValue(children[i], command, newValue); michael@0: } michael@0: michael@0: // "Abort this algorithm." michael@0: return; michael@0: } michael@0: michael@0: // "If the effective command value of command is loosely equivalent to new michael@0: // value on node, abort this algorithm." michael@0: if (areLooselyEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) { michael@0: return; michael@0: } michael@0: michael@0: // "Let new parent be null." michael@0: var newParent = null; michael@0: michael@0: // "If the CSS styling flag is false:" michael@0: if (!cssStylingFlag) { michael@0: // "If command is "bold" and new value is "bold", let new parent be the michael@0: // result of calling createElement("b") on the ownerDocument of node." michael@0: if (command == "bold" && (newValue == "bold" || newValue == "700")) { michael@0: newParent = node.ownerDocument.createElement("b"); michael@0: } michael@0: michael@0: // "If command is "italic" and new value is "italic", let new parent be michael@0: // the result of calling createElement("i") on the ownerDocument of michael@0: // node." michael@0: if (command == "italic" && newValue == "italic") { michael@0: newParent = node.ownerDocument.createElement("i"); michael@0: } michael@0: michael@0: // "If command is "strikethrough" and new value is "line-through", let michael@0: // new parent be the result of calling createElement("s") on the michael@0: // ownerDocument of node." michael@0: if (command == "strikethrough" && newValue == "line-through") { michael@0: newParent = node.ownerDocument.createElement("s"); michael@0: } michael@0: michael@0: // "If command is "underline" and new value is "underline", let new michael@0: // parent be the result of calling createElement("u") on the michael@0: // ownerDocument of node." michael@0: if (command == "underline" && newValue == "underline") { michael@0: newParent = node.ownerDocument.createElement("u"); michael@0: } michael@0: michael@0: // "If command is "foreColor", and new value is fully opaque with red, michael@0: // green, and blue components in the range 0 to 255:" michael@0: if (command == "forecolor" && parseSimpleColor(newValue)) { michael@0: // "Let new parent be the result of calling createElement("font") michael@0: // on the ownerDocument of node." michael@0: newParent = node.ownerDocument.createElement("font"); michael@0: michael@0: // "Set the color attribute of new parent to the result of applying michael@0: // the rules for serializing simple color values to new value michael@0: // (interpreted as a simple color)." michael@0: newParent.setAttribute("color", parseSimpleColor(newValue)); michael@0: } michael@0: michael@0: // "If command is "fontName", let new parent be the result of calling michael@0: // createElement("font") on the ownerDocument of node, then set the michael@0: // face attribute of new parent to new value." michael@0: if (command == "fontname") { michael@0: newParent = node.ownerDocument.createElement("font"); michael@0: newParent.face = newValue; michael@0: } michael@0: } michael@0: michael@0: // "If command is "createLink" or "unlink":" michael@0: if (command == "createlink" || command == "unlink") { michael@0: // "Let new parent be the result of calling createElement("a") on the michael@0: // ownerDocument of node." michael@0: newParent = node.ownerDocument.createElement("a"); michael@0: michael@0: // "Set the href attribute of new parent to new value." michael@0: newParent.setAttribute("href", newValue); michael@0: michael@0: // "Let ancestor be node's parent." michael@0: var ancestor = node.parentNode; michael@0: michael@0: // "While ancestor is not null:" michael@0: while (ancestor) { michael@0: // "If ancestor is an a, set the tag name of ancestor to "span", michael@0: // and let ancestor be the result." michael@0: if (isHtmlElement(ancestor, "A")) { michael@0: ancestor = setTagName(ancestor, "span"); michael@0: } michael@0: michael@0: // "Set ancestor to its parent." michael@0: ancestor = ancestor.parentNode; michael@0: } michael@0: } michael@0: michael@0: // "If command is "fontSize"; and new value is one of "x-small", "small", michael@0: // "medium", "large", "x-large", "xx-large", or "xxx-large"; and either the michael@0: // CSS styling flag is false, or new value is "xxx-large": let new parent michael@0: // be the result of calling createElement("font") on the ownerDocument of michael@0: // node, then set the size attribute of new parent to the number from the michael@0: // following table based on new value: [table omitted]" michael@0: if (command == "fontsize" michael@0: && ["x-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"].indexOf(newValue) != -1 michael@0: && (!cssStylingFlag || newValue == "xxx-large")) { michael@0: newParent = node.ownerDocument.createElement("font"); michael@0: newParent.size = cssSizeToLegacy(newValue); michael@0: } michael@0: michael@0: // "If command is "subscript" or "superscript" and new value is michael@0: // "subscript", let new parent be the result of calling michael@0: // createElement("sub") on the ownerDocument of node." michael@0: if ((command == "subscript" || command == "superscript") michael@0: && newValue == "subscript") { michael@0: newParent = node.ownerDocument.createElement("sub"); michael@0: } michael@0: michael@0: // "If command is "subscript" or "superscript" and new value is michael@0: // "superscript", let new parent be the result of calling michael@0: // createElement("sup") on the ownerDocument of node." michael@0: if ((command == "subscript" || command == "superscript") michael@0: && newValue == "superscript") { michael@0: newParent = node.ownerDocument.createElement("sup"); michael@0: } michael@0: michael@0: // "If new parent is null, let new parent be the result of calling michael@0: // createElement("span") on the ownerDocument of node." michael@0: if (!newParent) { michael@0: newParent = node.ownerDocument.createElement("span"); michael@0: } michael@0: michael@0: // "Insert new parent in node's parent before node." michael@0: node.parentNode.insertBefore(newParent, node); michael@0: michael@0: // "If the effective command value of command for new parent is not loosely michael@0: // equivalent to new value, and the relevant CSS property for command is michael@0: // not null, set that CSS property of new parent to new value (if the new michael@0: // value would be valid)." michael@0: var property = commands[command].relevantCssProperty; michael@0: if (property !== null michael@0: && !areLooselyEquivalentValues(command, getEffectiveCommandValue(newParent, command), newValue)) { michael@0: newParent.style[property] = newValue; michael@0: } michael@0: michael@0: // "If command is "strikethrough", and new value is "line-through", and the michael@0: // effective command value of "strikethrough" for new parent is not michael@0: // "line-through", set the "text-decoration" property of new parent to michael@0: // "line-through"." michael@0: if (command == "strikethrough" michael@0: && newValue == "line-through" michael@0: && getEffectiveCommandValue(newParent, "strikethrough") != "line-through") { michael@0: newParent.style.textDecoration = "line-through"; michael@0: } michael@0: michael@0: // "If command is "underline", and new value is "underline", and the michael@0: // effective command value of "underline" for new parent is not michael@0: // "underline", set the "text-decoration" property of new parent to michael@0: // "underline"." michael@0: if (command == "underline" michael@0: && newValue == "underline" michael@0: && getEffectiveCommandValue(newParent, "underline") != "underline") { michael@0: newParent.style.textDecoration = "underline"; michael@0: } michael@0: michael@0: // "Append node to new parent as its last child, preserving ranges." michael@0: movePreservingRanges(node, newParent, newParent.childNodes.length); michael@0: michael@0: // "If node is an Element and the effective command value of command for michael@0: // node is not loosely equivalent to new value:" michael@0: if (node.nodeType == Node.ELEMENT_NODE michael@0: && !areEquivalentValues(command, getEffectiveCommandValue(node, command), newValue)) { michael@0: // "Insert node into the parent of new parent before new parent, michael@0: // preserving ranges." michael@0: movePreservingRanges(node, newParent.parentNode, getNodeIndex(newParent)); michael@0: michael@0: // "Remove new parent from its parent." michael@0: newParent.parentNode.removeChild(newParent); michael@0: michael@0: // "Let children be all children of node, omitting any that are michael@0: // Elements whose specified command value for command is neither null michael@0: // nor equivalent to new value." michael@0: var children = []; michael@0: for (var i = 0; i < node.childNodes.length; i++) { michael@0: if (node.childNodes[i].nodeType == Node.ELEMENT_NODE) { michael@0: var specifiedValue = getSpecifiedCommandValue(node.childNodes[i], command); michael@0: michael@0: if (specifiedValue !== null michael@0: && !areEquivalentValues(command, newValue, specifiedValue)) { michael@0: continue; michael@0: } michael@0: } michael@0: children.push(node.childNodes[i]); michael@0: } michael@0: michael@0: // "Force the value of each Node in children, with command and new michael@0: // value as in this invocation of the algorithm." michael@0: for (var i = 0; i < children.length; i++) { michael@0: forceValue(children[i], command, newValue); michael@0: } michael@0: } michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Setting the selection's value ///// michael@0: //@{ michael@0: michael@0: function setSelectionValue(command, newValue) { michael@0: // "If there is no formattable node effectively contained in the active michael@0: // range:" michael@0: if (!getAllEffectivelyContainedNodes(getActiveRange()) michael@0: .some(isFormattableNode)) { michael@0: // "If command has inline command activated values, set the state michael@0: // override to true if new value is among them and false if it's not." michael@0: if ("inlineCommandActivatedValues" in commands[command]) { michael@0: setStateOverride(command, commands[command].inlineCommandActivatedValues michael@0: .indexOf(newValue) != -1); michael@0: } michael@0: michael@0: // "If command is "subscript", unset the state override for michael@0: // "superscript"." michael@0: if (command == "subscript") { michael@0: unsetStateOverride("superscript"); michael@0: } michael@0: michael@0: // "If command is "superscript", unset the state override for michael@0: // "subscript"." michael@0: if (command == "superscript") { michael@0: unsetStateOverride("subscript"); michael@0: } michael@0: michael@0: // "If new value is null, unset the value override (if any)." michael@0: if (newValue === null) { michael@0: unsetValueOverride(command); michael@0: michael@0: // "Otherwise, if command is "createLink" or it has a value specified, michael@0: // set the value override to new value." michael@0: } else if (command == "createlink" || "value" in commands[command]) { michael@0: setValueOverride(command, newValue); michael@0: } michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "If the active range's start node is an editable Text node, and its michael@0: // start offset is neither zero nor its start node's length, call michael@0: // splitText() on the active range's start node, with argument equal to the michael@0: // active range's start offset. Then set the active range's start node to michael@0: // the result, and its start offset to zero." michael@0: if (isEditable(getActiveRange().startContainer) michael@0: && getActiveRange().startContainer.nodeType == Node.TEXT_NODE michael@0: && getActiveRange().startOffset != 0 michael@0: && getActiveRange().startOffset != getNodeLength(getActiveRange().startContainer)) { michael@0: // Account for browsers not following range mutation rules michael@0: var newActiveRange = document.createRange(); michael@0: var newNode; michael@0: if (getActiveRange().startContainer == getActiveRange().endContainer) { michael@0: var newEndOffset = getActiveRange().endOffset - getActiveRange().startOffset; michael@0: newNode = getActiveRange().startContainer.splitText(getActiveRange().startOffset); michael@0: newActiveRange.setEnd(newNode, newEndOffset); michael@0: getActiveRange().setEnd(newNode, newEndOffset); michael@0: } else { michael@0: newNode = getActiveRange().startContainer.splitText(getActiveRange().startOffset); michael@0: } michael@0: newActiveRange.setStart(newNode, 0); michael@0: getSelection().removeAllRanges(); michael@0: getSelection().addRange(newActiveRange); michael@0: michael@0: getActiveRange().setStart(newNode, 0); michael@0: } michael@0: michael@0: // "If the active range's end node is an editable Text node, and its end michael@0: // offset is neither zero nor its end node's length, call splitText() on michael@0: // the active range's end node, with argument equal to the active range's michael@0: // end offset." michael@0: if (isEditable(getActiveRange().endContainer) michael@0: && getActiveRange().endContainer.nodeType == Node.TEXT_NODE michael@0: && getActiveRange().endOffset != 0 michael@0: && getActiveRange().endOffset != getNodeLength(getActiveRange().endContainer)) { michael@0: // IE seems to mutate the range incorrectly here, so we need correction michael@0: // here as well. The active range will be temporarily in orphaned michael@0: // nodes, so calling getActiveRange() after splitText() but before michael@0: // fixing the range will throw an exception. michael@0: var activeRange = getActiveRange(); michael@0: var newStart = [activeRange.startContainer, activeRange.startOffset]; michael@0: var newEnd = [activeRange.endContainer, activeRange.endOffset]; michael@0: activeRange.endContainer.splitText(activeRange.endOffset); michael@0: activeRange.setStart(newStart[0], newStart[1]); michael@0: activeRange.setEnd(newEnd[0], newEnd[1]); michael@0: michael@0: getSelection().removeAllRanges(); michael@0: getSelection().addRange(activeRange); michael@0: } michael@0: michael@0: // "Let element list be all editable Elements effectively contained in the michael@0: // active range. michael@0: // michael@0: // "For each element in element list, clear the value of element." michael@0: getAllEffectivelyContainedNodes(getActiveRange(), function(node) { michael@0: return isEditable(node) && node.nodeType == Node.ELEMENT_NODE; michael@0: }).forEach(function(element) { michael@0: clearValue(element, command); michael@0: }); michael@0: michael@0: // "Let node list be all editable nodes effectively contained in the active michael@0: // range. michael@0: // michael@0: // "For each node in node list:" michael@0: getAllEffectivelyContainedNodes(getActiveRange(), isEditable).forEach(function(node) { michael@0: // "Push down values on node." michael@0: pushDownValues(node, command, newValue); michael@0: michael@0: // "If node is an allowed child of span, force the value of node." michael@0: if (isAllowedChild(node, "span")) { michael@0: forceValue(node, command, newValue); michael@0: } michael@0: }); michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// The backColor command ///// michael@0: //@{ michael@0: commands.backcolor = { michael@0: // Copy-pasted, same as hiliteColor michael@0: action: function(value) { michael@0: // Action is further copy-pasted, same as foreColor michael@0: michael@0: // "If value is not a valid CSS color, prepend "#" to it." michael@0: // michael@0: // "If value is still not a valid CSS color, or if it is currentColor, michael@0: // return false." michael@0: // michael@0: // Cheap hack for testing, no attempt to be comprehensive. michael@0: if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) { michael@0: value = "#" + value; michael@0: } michael@0: if (!/^(rgba?|hsla?)\(.*\)$/.test(value) michael@0: && !parseSimpleColor(value) michael@0: && value.toLowerCase() != "transparent") { michael@0: return false; michael@0: } michael@0: michael@0: // "Set the selection's value to value." michael@0: setSelectionValue("backcolor", value); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: }, standardInlineValueCommand: true, relevantCssProperty: "backgroundColor", michael@0: equivalentValues: function(val1, val2) { michael@0: // "Either both strings are valid CSS colors and have the same red, michael@0: // green, blue, and alpha components, or neither string is a valid CSS michael@0: // color." michael@0: return normalizeColor(val1) === normalizeColor(val2); michael@0: }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The bold command ///// michael@0: //@{ michael@0: commands.bold = { michael@0: action: function() { michael@0: // "If queryCommandState("bold") returns true, set the selection's michael@0: // value to "normal". Otherwise set the selection's value to "bold". michael@0: // Either way, return true." michael@0: if (myQueryCommandState("bold")) { michael@0: setSelectionValue("bold", "normal"); michael@0: } else { michael@0: setSelectionValue("bold", "bold"); michael@0: } michael@0: return true; michael@0: }, inlineCommandActivatedValues: ["bold", "600", "700", "800", "900"], michael@0: relevantCssProperty: "fontWeight", michael@0: equivalentValues: function(val1, val2) { michael@0: // "Either the two strings are equal, or one is "bold" and the other is michael@0: // "700", or one is "normal" and the other is "400"." michael@0: return val1 == val2 michael@0: || (val1 == "bold" && val2 == "700") michael@0: || (val1 == "700" && val2 == "bold") michael@0: || (val1 == "normal" && val2 == "400") michael@0: || (val1 == "400" && val2 == "normal"); michael@0: }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The createLink command ///// michael@0: //@{ michael@0: commands.createlink = { michael@0: action: function(value) { michael@0: // "If value is the empty string, return false." michael@0: if (value === "") { michael@0: return false; michael@0: } michael@0: michael@0: // "For each editable a element that has an href attribute and is an michael@0: // ancestor of some node effectively contained in the active range, set michael@0: // that a element's href attribute to value." michael@0: // michael@0: // TODO: We don't actually do this in tree order, not that it matters michael@0: // unless you're spying with mutation events. michael@0: getAllEffectivelyContainedNodes(getActiveRange()).forEach(function(node) { michael@0: getAncestors(node).forEach(function(ancestor) { michael@0: if (isEditable(ancestor) michael@0: && isHtmlElement(ancestor, "a") michael@0: && ancestor.hasAttribute("href")) { michael@0: ancestor.setAttribute("href", value); michael@0: } michael@0: }); michael@0: }); michael@0: michael@0: // "Set the selection's value to value." michael@0: setSelectionValue("createlink", value); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The fontName command ///// michael@0: //@{ michael@0: commands.fontname = { michael@0: action: function(value) { michael@0: // "Set the selection's value to value, then return true." michael@0: setSelectionValue("fontname", value); michael@0: return true; michael@0: }, standardInlineValueCommand: true, relevantCssProperty: "fontFamily" michael@0: }; michael@0: michael@0: //@} michael@0: ///// The fontSize command ///// michael@0: //@{ michael@0: michael@0: // Helper function for fontSize's action plus queryOutputHelper. It's just the michael@0: // middle of fontSize's action, ripped out into its own function. Returns null michael@0: // if the size is invalid. michael@0: function normalizeFontSize(value) { michael@0: // "Strip leading and trailing whitespace from value." michael@0: // michael@0: // Cheap hack, not following the actual algorithm. michael@0: value = value.trim(); michael@0: michael@0: // "If value is not a valid floating point number, and would not be a valid michael@0: // floating point number if a single leading "+" character were stripped, michael@0: // return false." michael@0: if (!/^[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/.test(value)) { michael@0: return null; michael@0: } michael@0: michael@0: var mode; michael@0: michael@0: // "If the first character of value is "+", delete the character and let michael@0: // mode be "relative-plus"." michael@0: if (value[0] == "+") { michael@0: value = value.slice(1); michael@0: mode = "relative-plus"; michael@0: // "Otherwise, if the first character of value is "-", delete the character michael@0: // and let mode be "relative-minus"." michael@0: } else if (value[0] == "-") { michael@0: value = value.slice(1); michael@0: mode = "relative-minus"; michael@0: // "Otherwise, let mode be "absolute"." michael@0: } else { michael@0: mode = "absolute"; michael@0: } michael@0: michael@0: // "Apply the rules for parsing non-negative integers to value, and let michael@0: // number be the result." michael@0: // michael@0: // Another cheap hack. michael@0: var num = parseInt(value); michael@0: michael@0: // "If mode is "relative-plus", add three to number." michael@0: if (mode == "relative-plus") { michael@0: num += 3; michael@0: } michael@0: michael@0: // "If mode is "relative-minus", negate number, then add three to it." michael@0: if (mode == "relative-minus") { michael@0: num = 3 - num; michael@0: } michael@0: michael@0: // "If number is less than one, let number equal 1." michael@0: if (num < 1) { michael@0: num = 1; michael@0: } michael@0: michael@0: // "If number is greater than seven, let number equal 7." michael@0: if (num > 7) { michael@0: num = 7; michael@0: } michael@0: michael@0: // "Set value to the string here corresponding to number:" [table omitted] michael@0: value = { michael@0: 1: "x-small", michael@0: 2: "small", michael@0: 3: "medium", michael@0: 4: "large", michael@0: 5: "x-large", michael@0: 6: "xx-large", michael@0: 7: "xxx-large" michael@0: }[num]; michael@0: michael@0: return value; michael@0: } michael@0: michael@0: commands.fontsize = { michael@0: action: function(value) { michael@0: value = normalizeFontSize(value); michael@0: if (value === null) { michael@0: return false; michael@0: } michael@0: michael@0: // "Set the selection's value to value." michael@0: setSelectionValue("fontsize", value); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: }, indeterm: function() { michael@0: // "True if among formattable nodes that are effectively contained in michael@0: // the active range, there are two that have distinct effective command michael@0: // values. Otherwise false." michael@0: return getAllEffectivelyContainedNodes(getActiveRange(), isFormattableNode) michael@0: .map(function(node) { michael@0: return getEffectiveCommandValue(node, "fontsize"); michael@0: }).filter(function(value, i, arr) { michael@0: return arr.slice(0, i).indexOf(value) == -1; michael@0: }).length >= 2; michael@0: }, value: function() { michael@0: // "If the active range is null, return the empty string." michael@0: if (!getActiveRange()) { michael@0: return ""; michael@0: } michael@0: michael@0: // "Let pixel size be the effective command value of the first michael@0: // formattable node that is effectively contained in the active range, michael@0: // or if there is no such node, the effective command value of the michael@0: // active range's start node, in either case interpreted as a number of michael@0: // pixels." michael@0: var node = getAllEffectivelyContainedNodes(getActiveRange(), isFormattableNode)[0]; michael@0: if (node === undefined) { michael@0: node = getActiveRange().startContainer; michael@0: } michael@0: var pixelSize = getEffectiveCommandValue(node, "fontsize"); michael@0: michael@0: // "Return the legacy font size for pixel size." michael@0: return getLegacyFontSize(pixelSize); michael@0: }, relevantCssProperty: "fontSize" michael@0: }; michael@0: michael@0: function getLegacyFontSize(size) { michael@0: if (getLegacyFontSize.resultCache === undefined) { michael@0: getLegacyFontSize.resultCache = {}; michael@0: } michael@0: michael@0: if (getLegacyFontSize.resultCache[size] !== undefined) { michael@0: return getLegacyFontSize.resultCache[size]; michael@0: } michael@0: michael@0: // For convenience in other places in my code, I handle all sizes, not just michael@0: // pixel sizes as the spec says. This means pixel sizes have to be passed michael@0: // in suffixed with "px", not as plain numbers. michael@0: if (normalizeFontSize(size) !== null) { michael@0: return getLegacyFontSize.resultCache[size] = cssSizeToLegacy(normalizeFontSize(size)); michael@0: } michael@0: michael@0: if (["x-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "xxx-large"].indexOf(size) == -1 michael@0: && !/^[0-9]+(\.[0-9]+)?(cm|mm|in|pt|pc|px)$/.test(size)) { michael@0: // There is no sensible legacy size for things like "2em". michael@0: return getLegacyFontSize.resultCache[size] = null; michael@0: } michael@0: michael@0: var font = document.createElement("font"); michael@0: document.body.appendChild(font); michael@0: if (size == "xxx-large") { michael@0: font.size = 7; michael@0: } else { michael@0: font.style.fontSize = size; michael@0: } michael@0: var pixelSize = parseInt(getComputedStyle(font).fontSize); michael@0: document.body.removeChild(font); michael@0: michael@0: // "Let returned size be 1." michael@0: var returnedSize = 1; michael@0: michael@0: // "While returned size is less than 7:" michael@0: while (returnedSize < 7) { michael@0: // "Let lower bound be the resolved value of "font-size" in pixels michael@0: // of a font element whose size attribute is set to returned size." michael@0: var font = document.createElement("font"); michael@0: font.size = returnedSize; michael@0: document.body.appendChild(font); michael@0: var lowerBound = parseInt(getComputedStyle(font).fontSize); michael@0: michael@0: // "Let upper bound be the resolved value of "font-size" in pixels michael@0: // of a font element whose size attribute is set to one plus michael@0: // returned size." michael@0: font.size = 1 + returnedSize; michael@0: var upperBound = parseInt(getComputedStyle(font).fontSize); michael@0: document.body.removeChild(font); michael@0: michael@0: // "Let average be the average of upper bound and lower bound." michael@0: var average = (upperBound + lowerBound)/2; michael@0: michael@0: // "If pixel size is less than average, return the one-element michael@0: // string consisting of the digit returned size." michael@0: if (pixelSize < average) { michael@0: return getLegacyFontSize.resultCache[size] = String(returnedSize); michael@0: } michael@0: michael@0: // "Add one to returned size." michael@0: returnedSize++; michael@0: } michael@0: michael@0: // "Return "7"." michael@0: return getLegacyFontSize.resultCache[size] = "7"; michael@0: } michael@0: michael@0: //@} michael@0: ///// The foreColor command ///// michael@0: //@{ michael@0: commands.forecolor = { michael@0: action: function(value) { michael@0: // Copy-pasted, same as backColor and hiliteColor michael@0: michael@0: // "If value is not a valid CSS color, prepend "#" to it." michael@0: // michael@0: // "If value is still not a valid CSS color, or if it is currentColor, michael@0: // return false." michael@0: // michael@0: // Cheap hack for testing, no attempt to be comprehensive. michael@0: if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) { michael@0: value = "#" + value; michael@0: } michael@0: if (!/^(rgba?|hsla?)\(.*\)$/.test(value) michael@0: && !parseSimpleColor(value) michael@0: && value.toLowerCase() != "transparent") { michael@0: return false; michael@0: } michael@0: michael@0: // "Set the selection's value to value." michael@0: setSelectionValue("forecolor", value); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: }, standardInlineValueCommand: true, relevantCssProperty: "color", michael@0: equivalentValues: function(val1, val2) { michael@0: // "Either both strings are valid CSS colors and have the same red, michael@0: // green, blue, and alpha components, or neither string is a valid CSS michael@0: // color." michael@0: return normalizeColor(val1) === normalizeColor(val2); michael@0: }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The hiliteColor command ///// michael@0: //@{ michael@0: commands.hilitecolor = { michael@0: // Copy-pasted, same as backColor michael@0: action: function(value) { michael@0: // Action is further copy-pasted, same as foreColor michael@0: michael@0: // "If value is not a valid CSS color, prepend "#" to it." michael@0: // michael@0: // "If value is still not a valid CSS color, or if it is currentColor, michael@0: // return false." michael@0: // michael@0: // Cheap hack for testing, no attempt to be comprehensive. michael@0: if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) { michael@0: value = "#" + value; michael@0: } michael@0: if (!/^(rgba?|hsla?)\(.*\)$/.test(value) michael@0: && !parseSimpleColor(value) michael@0: && value.toLowerCase() != "transparent") { michael@0: return false; michael@0: } michael@0: michael@0: // "Set the selection's value to value." michael@0: setSelectionValue("hilitecolor", value); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: }, indeterm: function() { michael@0: // "True if among editable Text nodes that are effectively contained in michael@0: // the active range, there are two that have distinct effective command michael@0: // values. Otherwise false." michael@0: return getAllEffectivelyContainedNodes(getActiveRange(), function(node) { michael@0: return isEditable(node) && node.nodeType == Node.TEXT_NODE; michael@0: }).map(function(node) { michael@0: return getEffectiveCommandValue(node, "hilitecolor"); michael@0: }).filter(function(value, i, arr) { michael@0: return arr.slice(0, i).indexOf(value) == -1; michael@0: }).length >= 2; michael@0: }, standardInlineValueCommand: true, relevantCssProperty: "backgroundColor", michael@0: equivalentValues: function(val1, val2) { michael@0: // "Either both strings are valid CSS colors and have the same red, michael@0: // green, blue, and alpha components, or neither string is a valid CSS michael@0: // color." michael@0: return normalizeColor(val1) === normalizeColor(val2); michael@0: }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The italic command ///// michael@0: //@{ michael@0: commands.italic = { michael@0: action: function() { michael@0: // "If queryCommandState("italic") returns true, set the selection's michael@0: // value to "normal". Otherwise set the selection's value to "italic". michael@0: // Either way, return true." michael@0: if (myQueryCommandState("italic")) { michael@0: setSelectionValue("italic", "normal"); michael@0: } else { michael@0: setSelectionValue("italic", "italic"); michael@0: } michael@0: return true; michael@0: }, inlineCommandActivatedValues: ["italic", "oblique"], michael@0: relevantCssProperty: "fontStyle" michael@0: }; michael@0: michael@0: //@} michael@0: ///// The removeFormat command ///// michael@0: //@{ michael@0: commands.removeformat = { michael@0: action: function() { michael@0: // "A removeFormat candidate is an editable HTML element with local michael@0: // name "abbr", "acronym", "b", "bdi", "bdo", "big", "blink", "cite", michael@0: // "code", "dfn", "em", "font", "i", "ins", "kbd", "mark", "nobr", "q", michael@0: // "s", "samp", "small", "span", "strike", "strong", "sub", "sup", michael@0: // "tt", "u", or "var"." michael@0: function isRemoveFormatCandidate(node) { michael@0: return isEditable(node) michael@0: && isHtmlElement(node, ["abbr", "acronym", "b", "bdi", "bdo", michael@0: "big", "blink", "cite", "code", "dfn", "em", "font", "i", michael@0: "ins", "kbd", "mark", "nobr", "q", "s", "samp", "small", michael@0: "span", "strike", "strong", "sub", "sup", "tt", "u", "var"]); michael@0: } michael@0: michael@0: // "Let elements to remove be a list of every removeFormat candidate michael@0: // effectively contained in the active range." michael@0: var elementsToRemove = getAllEffectivelyContainedNodes(getActiveRange(), isRemoveFormatCandidate); michael@0: michael@0: // "For each element in elements to remove:" michael@0: elementsToRemove.forEach(function(element) { michael@0: // "While element has children, insert the first child of element michael@0: // into the parent of element immediately before element, michael@0: // preserving ranges." michael@0: while (element.hasChildNodes()) { michael@0: movePreservingRanges(element.firstChild, element.parentNode, getNodeIndex(element)); michael@0: } michael@0: michael@0: // "Remove element from its parent." michael@0: element.parentNode.removeChild(element); michael@0: }); michael@0: michael@0: // "If the active range's start node is an editable Text node, and its michael@0: // start offset is neither zero nor its start node's length, call michael@0: // splitText() on the active range's start node, with argument equal to michael@0: // the active range's start offset. Then set the active range's start michael@0: // node to the result, and its start offset to zero." michael@0: if (isEditable(getActiveRange().startContainer) michael@0: && getActiveRange().startContainer.nodeType == Node.TEXT_NODE michael@0: && getActiveRange().startOffset != 0 michael@0: && getActiveRange().startOffset != getNodeLength(getActiveRange().startContainer)) { michael@0: // Account for browsers not following range mutation rules michael@0: if (getActiveRange().startContainer == getActiveRange().endContainer) { michael@0: var newEnd = getActiveRange().endOffset - getActiveRange().startOffset; michael@0: var newNode = getActiveRange().startContainer.splitText(getActiveRange().startOffset); michael@0: getActiveRange().setStart(newNode, 0); michael@0: getActiveRange().setEnd(newNode, newEnd); michael@0: } else { michael@0: getActiveRange().setStart(getActiveRange().startContainer.splitText(getActiveRange().startOffset), 0); michael@0: } michael@0: } michael@0: michael@0: // "If the active range's end node is an editable Text node, and its michael@0: // end offset is neither zero nor its end node's length, call michael@0: // splitText() on the active range's end node, with argument equal to michael@0: // the active range's end offset." michael@0: if (isEditable(getActiveRange().endContainer) michael@0: && getActiveRange().endContainer.nodeType == Node.TEXT_NODE michael@0: && getActiveRange().endOffset != 0 michael@0: && getActiveRange().endOffset != getNodeLength(getActiveRange().endContainer)) { michael@0: // IE seems to mutate the range incorrectly here, so we need michael@0: // correction here as well. Have to be careful to set the range to michael@0: // something not including the text node so that getActiveRange() michael@0: // doesn't throw an exception due to a temporarily detached michael@0: // endpoint. michael@0: var newStart = [getActiveRange().startContainer, getActiveRange().startOffset]; michael@0: var newEnd = [getActiveRange().endContainer, getActiveRange().endOffset]; michael@0: getActiveRange().setEnd(document.documentElement, 0); michael@0: newEnd[0].splitText(newEnd[1]); michael@0: getActiveRange().setStart(newStart[0], newStart[1]); michael@0: getActiveRange().setEnd(newEnd[0], newEnd[1]); michael@0: } michael@0: michael@0: // "Let node list consist of all editable nodes effectively contained michael@0: // in the active range." michael@0: // michael@0: // "For each node in node list, while node's parent is a removeFormat michael@0: // candidate in the same editing host as node, split the parent of the michael@0: // one-node list consisting of node." michael@0: getAllEffectivelyContainedNodes(getActiveRange(), isEditable).forEach(function(node) { michael@0: while (isRemoveFormatCandidate(node.parentNode) michael@0: && inSameEditingHost(node.parentNode, node)) { michael@0: splitParent([node]); michael@0: } michael@0: }); michael@0: michael@0: // "For each of the entries in the following list, in the given order, michael@0: // set the selection's value to null, with command as given." michael@0: [ michael@0: "subscript", michael@0: "bold", michael@0: "fontname", michael@0: "fontsize", michael@0: "forecolor", michael@0: "hilitecolor", michael@0: "italic", michael@0: "strikethrough", michael@0: "underline", michael@0: ].forEach(function(command) { michael@0: setSelectionValue(command, null); michael@0: }); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The strikethrough command ///// michael@0: //@{ michael@0: commands.strikethrough = { michael@0: action: function() { michael@0: // "If queryCommandState("strikethrough") returns true, set the michael@0: // selection's value to null. Otherwise set the selection's value to michael@0: // "line-through". Either way, return true." michael@0: if (myQueryCommandState("strikethrough")) { michael@0: setSelectionValue("strikethrough", null); michael@0: } else { michael@0: setSelectionValue("strikethrough", "line-through"); michael@0: } michael@0: return true; michael@0: }, inlineCommandActivatedValues: ["line-through"] michael@0: }; michael@0: michael@0: //@} michael@0: ///// The subscript command ///// michael@0: //@{ michael@0: commands.subscript = { michael@0: action: function() { michael@0: // "Call queryCommandState("subscript"), and let state be the result." michael@0: var state = myQueryCommandState("subscript"); michael@0: michael@0: // "Set the selection's value to null." michael@0: setSelectionValue("subscript", null); michael@0: michael@0: // "If state is false, set the selection's value to "subscript"." michael@0: if (!state) { michael@0: setSelectionValue("subscript", "subscript"); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: }, indeterm: function() { michael@0: // "True if either among formattable nodes that are effectively michael@0: // contained in the active range, there is at least one with effective michael@0: // command value "subscript" and at least one with some other effective michael@0: // command value; or if there is some formattable node effectively michael@0: // contained in the active range with effective command value "mixed". michael@0: // Otherwise false." michael@0: var nodes = getAllEffectivelyContainedNodes(getActiveRange(), isFormattableNode); michael@0: return (nodes.some(function(node) { return getEffectiveCommandValue(node, "subscript") == "subscript" }) michael@0: && nodes.some(function(node) { return getEffectiveCommandValue(node, "subscript") != "subscript" })) michael@0: || nodes.some(function(node) { return getEffectiveCommandValue(node, "subscript") == "mixed" }); michael@0: }, inlineCommandActivatedValues: ["subscript"], michael@0: }; michael@0: michael@0: //@} michael@0: ///// The superscript command ///// michael@0: //@{ michael@0: commands.superscript = { michael@0: action: function() { michael@0: // "Call queryCommandState("superscript"), and let state be the michael@0: // result." michael@0: var state = myQueryCommandState("superscript"); michael@0: michael@0: // "Set the selection's value to null." michael@0: setSelectionValue("superscript", null); michael@0: michael@0: // "If state is false, set the selection's value to "superscript"." michael@0: if (!state) { michael@0: setSelectionValue("superscript", "superscript"); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: }, indeterm: function() { michael@0: // "True if either among formattable nodes that are effectively michael@0: // contained in the active range, there is at least one with effective michael@0: // command value "superscript" and at least one with some other michael@0: // effective command value; or if there is some formattable node michael@0: // effectively contained in the active range with effective command michael@0: // value "mixed". Otherwise false." michael@0: var nodes = getAllEffectivelyContainedNodes(getActiveRange(), isFormattableNode); michael@0: return (nodes.some(function(node) { return getEffectiveCommandValue(node, "superscript") == "superscript" }) michael@0: && nodes.some(function(node) { return getEffectiveCommandValue(node, "superscript") != "superscript" })) michael@0: || nodes.some(function(node) { return getEffectiveCommandValue(node, "superscript") == "mixed" }); michael@0: }, inlineCommandActivatedValues: ["superscript"], michael@0: }; michael@0: michael@0: //@} michael@0: ///// The underline command ///// michael@0: //@{ michael@0: commands.underline = { michael@0: action: function() { michael@0: // "If queryCommandState("underline") returns true, set the selection's michael@0: // value to null. Otherwise set the selection's value to "underline". michael@0: // Either way, return true." michael@0: if (myQueryCommandState("underline")) { michael@0: setSelectionValue("underline", null); michael@0: } else { michael@0: setSelectionValue("underline", "underline"); michael@0: } michael@0: return true; michael@0: }, inlineCommandActivatedValues: ["underline"] michael@0: }; michael@0: michael@0: //@} michael@0: ///// The unlink command ///// michael@0: //@{ michael@0: commands.unlink = { michael@0: action: function() { michael@0: // "Let hyperlinks be a list of every a element that has an href michael@0: // attribute and is contained in the active range or is an ancestor of michael@0: // one of its boundary points." michael@0: // michael@0: // As usual, take care to ensure it's tree order. The correctness of michael@0: // the following is left as an exercise for the reader. michael@0: var range = getActiveRange(); michael@0: var hyperlinks = []; michael@0: for ( michael@0: var node = range.startContainer; michael@0: node; michael@0: node = node.parentNode michael@0: ) { michael@0: if (isHtmlElement(node, "A") michael@0: && node.hasAttribute("href")) { michael@0: hyperlinks.unshift(node); michael@0: } michael@0: } michael@0: for ( michael@0: var node = range.startContainer; michael@0: node != nextNodeDescendants(range.endContainer); michael@0: node = nextNode(node) michael@0: ) { michael@0: if (isHtmlElement(node, "A") michael@0: && node.hasAttribute("href") michael@0: && (isContained(node, range) michael@0: || isAncestor(node, range.endContainer) michael@0: || node == range.endContainer)) { michael@0: hyperlinks.push(node); michael@0: } michael@0: } michael@0: michael@0: // "Clear the value of each member of hyperlinks." michael@0: for (var i = 0; i < hyperlinks.length; i++) { michael@0: clearValue(hyperlinks[i], "unlink"); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: michael@0: ///////////////////////////////////// michael@0: ///// Block formatting commands ///// michael@0: ///////////////////////////////////// michael@0: michael@0: ///// Block formatting command definitions ///// michael@0: //@{ michael@0: michael@0: // "An indentation element is either a blockquote, or a div that has a style michael@0: // attribute that sets "margin" or some subproperty of it." michael@0: function isIndentationElement(node) { michael@0: if (!isHtmlElement(node)) { michael@0: return false; michael@0: } michael@0: michael@0: if (node.tagName == "BLOCKQUOTE") { michael@0: return true; michael@0: } michael@0: michael@0: if (node.tagName != "DIV") { michael@0: return false; michael@0: } michael@0: michael@0: for (var i = 0; i < node.style.length; i++) { michael@0: // Approximate check michael@0: if (/^(-[a-z]+-)?margin/.test(node.style[i])) { michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: // "A simple indentation element is an indentation element that has no michael@0: // attributes except possibly michael@0: // michael@0: // * "a style attribute that sets no properties other than "margin", michael@0: // "border", "padding", or subproperties of those; and/or michael@0: // * "a dir attribute." michael@0: function isSimpleIndentationElement(node) { michael@0: if (!isIndentationElement(node)) { michael@0: return false; michael@0: } michael@0: michael@0: for (var i = 0; i < node.attributes.length; i++) { michael@0: if (!isHtmlNamespace(node.attributes[i].namespaceURI) michael@0: || ["style", "dir"].indexOf(node.attributes[i].name) == -1) { michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: for (var i = 0; i < node.style.length; i++) { michael@0: // This is approximate, but it works well enough for my purposes. michael@0: if (!/^(-[a-z]+-)?(margin|border|padding)/.test(node.style[i])) { michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: // "A non-list single-line container is an HTML element with local name michael@0: // "address", "div", "h1", "h2", "h3", "h4", "h5", "h6", "listing", "p", "pre", michael@0: // or "xmp"." michael@0: function isNonListSingleLineContainer(node) { michael@0: return isHtmlElement(node, ["address", "div", "h1", "h2", "h3", "h4", "h5", michael@0: "h6", "listing", "p", "pre", "xmp"]); michael@0: } michael@0: michael@0: // "A single-line container is either a non-list single-line container, or an michael@0: // HTML element with local name "li", "dt", or "dd"." michael@0: function isSingleLineContainer(node) { michael@0: return isNonListSingleLineContainer(node) michael@0: || isHtmlElement(node, ["li", "dt", "dd"]); michael@0: } michael@0: michael@0: function getBlockNodeOf(node) { michael@0: // "While node is an inline node, set node to its parent." michael@0: while (isInlineNode(node)) { michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: // "Return node." michael@0: return node; michael@0: } michael@0: michael@0: //@} michael@0: ///// Assorted block formatting command algorithms ///// michael@0: //@{ michael@0: michael@0: function fixDisallowedAncestors(node) { michael@0: // "If node is not editable, abort these steps." michael@0: if (!isEditable(node)) { michael@0: return; michael@0: } michael@0: michael@0: // "If node is not an allowed child of any of its ancestors in the same michael@0: // editing host:" michael@0: if (getAncestors(node).every(function(ancestor) { michael@0: return !inSameEditingHost(node, ancestor) michael@0: || !isAllowedChild(node, ancestor) michael@0: })) { michael@0: // "If node is a dd or dt, wrap the one-node list consisting of node, michael@0: // with sibling criteria returning true for any dl with no attributes michael@0: // and false otherwise, and new parent instructions returning the michael@0: // result of calling createElement("dl") on the context object. Then michael@0: // abort these steps." michael@0: if (isHtmlElement(node, ["dd", "dt"])) { michael@0: wrap([node], michael@0: function(sibling) { return isHtmlElement(sibling, "dl") && !sibling.attributes.length }, michael@0: function() { return document.createElement("dl") }); michael@0: return; michael@0: } michael@0: michael@0: // "If "p" is not an allowed child of the editing host of node, abort michael@0: // these steps." michael@0: if (!isAllowedChild("p", getEditingHostOf(node))) { michael@0: return; michael@0: } michael@0: michael@0: // "If node is not a prohibited paragraph child, abort these steps." michael@0: if (!isProhibitedParagraphChild(node)) { michael@0: return; michael@0: } michael@0: michael@0: // "Set the tag name of node to the default single-line container name, michael@0: // and let node be the result." michael@0: node = setTagName(node, defaultSingleLineContainerName); michael@0: michael@0: // "Fix disallowed ancestors of node." michael@0: fixDisallowedAncestors(node); michael@0: michael@0: // "Let children be node's children." michael@0: var children = [].slice.call(node.childNodes); michael@0: michael@0: // "For each child in children, if child is a prohibited paragraph michael@0: // child:" michael@0: children.filter(isProhibitedParagraphChild) michael@0: .forEach(function(child) { michael@0: // "Record the values of the one-node list consisting of child, and michael@0: // let values be the result." michael@0: var values = recordValues([child]); michael@0: michael@0: // "Split the parent of the one-node list consisting of child." michael@0: splitParent([child]); michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: }); michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "Record the values of the one-node list consisting of node, and let michael@0: // values be the result." michael@0: var values = recordValues([node]); michael@0: michael@0: // "While node is not an allowed child of its parent, split the parent of michael@0: // the one-node list consisting of node." michael@0: while (!isAllowedChild(node, node.parentNode)) { michael@0: splitParent([node]); michael@0: } michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: } michael@0: michael@0: function normalizeSublists(item) { michael@0: // "If item is not an li or it is not editable or its parent is not michael@0: // editable, abort these steps." michael@0: if (!isHtmlElement(item, "LI") michael@0: || !isEditable(item) michael@0: || !isEditable(item.parentNode)) { michael@0: return; michael@0: } michael@0: michael@0: // "Let new item be null." michael@0: var newItem = null; michael@0: michael@0: // "While item has an ol or ul child:" michael@0: while ([].some.call(item.childNodes, function (node) { return isHtmlElement(node, ["OL", "UL"]) })) { michael@0: // "Let child be the last child of item." michael@0: var child = item.lastChild; michael@0: michael@0: // "If child is an ol or ul, or new item is null and child is a Text michael@0: // node whose data consists of zero of more space characters:" michael@0: if (isHtmlElement(child, ["OL", "UL"]) michael@0: || (!newItem && child.nodeType == Node.TEXT_NODE && /^[ \t\n\f\r]*$/.test(child.data))) { michael@0: // "Set new item to null." michael@0: newItem = null; michael@0: michael@0: // "Insert child into the parent of item immediately following michael@0: // item, preserving ranges." michael@0: movePreservingRanges(child, item.parentNode, 1 + getNodeIndex(item)); michael@0: michael@0: // "Otherwise:" michael@0: } else { michael@0: // "If new item is null, let new item be the result of calling michael@0: // createElement("li") on the ownerDocument of item, then insert michael@0: // new item into the parent of item immediately after item." michael@0: if (!newItem) { michael@0: newItem = item.ownerDocument.createElement("li"); michael@0: item.parentNode.insertBefore(newItem, item.nextSibling); michael@0: } michael@0: michael@0: // "Insert child into new item as its first child, preserving michael@0: // ranges." michael@0: movePreservingRanges(child, newItem, 0); michael@0: } michael@0: } michael@0: } michael@0: michael@0: function getSelectionListState() { michael@0: // "If the active range is null, return "none"." michael@0: if (!getActiveRange()) { michael@0: return "none"; michael@0: } michael@0: michael@0: // "Block-extend the active range, and let new range be the result." michael@0: var newRange = blockExtend(getActiveRange()); michael@0: michael@0: // "Let node list be a list of nodes, initially empty." michael@0: // michael@0: // "For each node contained in new range, append node to node list if the michael@0: // last member of node list (if any) is not an ancestor of node; node is michael@0: // editable; node is not an indentation element; and node is either an ol michael@0: // or ul, or the child of an ol or ul, or an allowed child of "li"." michael@0: var nodeList = getContainedNodes(newRange, function(node) { michael@0: return isEditable(node) michael@0: && !isIndentationElement(node) michael@0: && (isHtmlElement(node, ["ol", "ul"]) michael@0: || isHtmlElement(node.parentNode, ["ol", "ul"]) michael@0: || isAllowedChild(node, "li")); michael@0: }); michael@0: michael@0: // "If node list is empty, return "none"." michael@0: if (!nodeList.length) { michael@0: return "none"; michael@0: } michael@0: michael@0: // "If every member of node list is either an ol or the child of an ol or michael@0: // the child of an li child of an ol, and none is a ul or an ancestor of a michael@0: // ul, return "ol"." michael@0: if (nodeList.every(function(node) { michael@0: return isHtmlElement(node, "ol") michael@0: || isHtmlElement(node.parentNode, "ol") michael@0: || (isHtmlElement(node.parentNode, "li") && isHtmlElement(node.parentNode.parentNode, "ol")); michael@0: }) michael@0: && !nodeList.some(function(node) { return isHtmlElement(node, "ul") || ("querySelector" in node && node.querySelector("ul")) })) { michael@0: return "ol"; michael@0: } michael@0: michael@0: // "If every member of node list is either a ul or the child of a ul or the michael@0: // child of an li child of a ul, and none is an ol or an ancestor of an ol, michael@0: // return "ul"." michael@0: if (nodeList.every(function(node) { michael@0: return isHtmlElement(node, "ul") michael@0: || isHtmlElement(node.parentNode, "ul") michael@0: || (isHtmlElement(node.parentNode, "li") && isHtmlElement(node.parentNode.parentNode, "ul")); michael@0: }) michael@0: && !nodeList.some(function(node) { return isHtmlElement(node, "ol") || ("querySelector" in node && node.querySelector("ol")) })) { michael@0: return "ul"; michael@0: } michael@0: michael@0: var hasOl = nodeList.some(function(node) { michael@0: return isHtmlElement(node, "ol") michael@0: || isHtmlElement(node.parentNode, "ol") michael@0: || ("querySelector" in node && node.querySelector("ol")) michael@0: || (isHtmlElement(node.parentNode, "li") && isHtmlElement(node.parentNode.parentNode, "ol")); michael@0: }); michael@0: var hasUl = nodeList.some(function(node) { michael@0: return isHtmlElement(node, "ul") michael@0: || isHtmlElement(node.parentNode, "ul") michael@0: || ("querySelector" in node && node.querySelector("ul")) michael@0: || (isHtmlElement(node.parentNode, "li") && isHtmlElement(node.parentNode.parentNode, "ul")); michael@0: }); michael@0: // "If some member of node list is either an ol or the child or ancestor of michael@0: // an ol or the child of an li child of an ol, and some member of node list michael@0: // is either a ul or the child or ancestor of a ul or the child of an li michael@0: // child of a ul, return "mixed"." michael@0: if (hasOl && hasUl) { michael@0: return "mixed"; michael@0: } michael@0: michael@0: // "If some member of node list is either an ol or the child or ancestor of michael@0: // an ol or the child of an li child of an ol, return "mixed ol"." michael@0: if (hasOl) { michael@0: return "mixed ol"; michael@0: } michael@0: michael@0: // "If some member of node list is either a ul or the child or ancestor of michael@0: // a ul or the child of an li child of a ul, return "mixed ul"." michael@0: if (hasUl) { michael@0: return "mixed ul"; michael@0: } michael@0: michael@0: // "Return "none"." michael@0: return "none"; michael@0: } michael@0: michael@0: function getAlignmentValue(node) { michael@0: // "While node is neither null nor an Element, or it is an Element but its michael@0: // "display" property has resolved value "inline" or "none", set node to michael@0: // its parent." michael@0: while ((node && node.nodeType != Node.ELEMENT_NODE) michael@0: || (node.nodeType == Node.ELEMENT_NODE michael@0: && ["inline", "none"].indexOf(getComputedStyle(node).display) != -1)) { michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: // "If node is not an Element, return "left"." michael@0: if (!node || node.nodeType != Node.ELEMENT_NODE) { michael@0: return "left"; michael@0: } michael@0: michael@0: var resolvedValue = getComputedStyle(node).textAlign michael@0: // Hack around browser non-standardness michael@0: .replace(/^-(moz|webkit)-/, "") michael@0: .replace(/^auto$/, "start"); michael@0: michael@0: // "If node's "text-align" property has resolved value "start", return michael@0: // "left" if the directionality of node is "ltr", "right" if it is "rtl"." michael@0: if (resolvedValue == "start") { michael@0: return getDirectionality(node) == "ltr" ? "left" : "right"; michael@0: } michael@0: michael@0: // "If node's "text-align" property has resolved value "end", return michael@0: // "right" if the directionality of node is "ltr", "left" if it is "rtl"." michael@0: if (resolvedValue == "end") { michael@0: return getDirectionality(node) == "ltr" ? "right" : "left"; michael@0: } michael@0: michael@0: // "If node's "text-align" property has resolved value "center", "justify", michael@0: // "left", or "right", return that value." michael@0: if (["center", "justify", "left", "right"].indexOf(resolvedValue) != -1) { michael@0: return resolvedValue; michael@0: } michael@0: michael@0: // "Return "left"." michael@0: return "left"; michael@0: } michael@0: michael@0: function getNextEquivalentPoint(node, offset) { michael@0: // "If node's length is zero, return null." michael@0: if (getNodeLength(node) == 0) { michael@0: return null; michael@0: } michael@0: michael@0: // "If offset is node's length, and node's parent is not null, and node is michael@0: // an inline node, return (node's parent, 1 + node's index)." michael@0: if (offset == getNodeLength(node) michael@0: && node.parentNode michael@0: && isInlineNode(node)) { michael@0: return [node.parentNode, 1 + getNodeIndex(node)]; michael@0: } michael@0: michael@0: // "If node has a child with index offset, and that child's length is not michael@0: // zero, and that child is an inline node, return (that child, 0)." michael@0: if (0 <= offset michael@0: && offset < node.childNodes.length michael@0: && getNodeLength(node.childNodes[offset]) != 0 michael@0: && isInlineNode(node.childNodes[offset])) { michael@0: return [node.childNodes[offset], 0]; michael@0: } michael@0: michael@0: // "Return null." michael@0: return null; michael@0: } michael@0: michael@0: function getPreviousEquivalentPoint(node, offset) { michael@0: // "If node's length is zero, return null." michael@0: if (getNodeLength(node) == 0) { michael@0: return null; michael@0: } michael@0: michael@0: // "If offset is 0, and node's parent is not null, and node is an inline michael@0: // node, return (node's parent, node's index)." michael@0: if (offset == 0 michael@0: && node.parentNode michael@0: && isInlineNode(node)) { michael@0: return [node.parentNode, getNodeIndex(node)]; michael@0: } michael@0: michael@0: // "If node has a child with index offset − 1, and that child's length is michael@0: // not zero, and that child is an inline node, return (that child, that michael@0: // child's length)." michael@0: if (0 <= offset - 1 michael@0: && offset - 1 < node.childNodes.length michael@0: && getNodeLength(node.childNodes[offset - 1]) != 0 michael@0: && isInlineNode(node.childNodes[offset - 1])) { michael@0: return [node.childNodes[offset - 1], getNodeLength(node.childNodes[offset - 1])]; michael@0: } michael@0: michael@0: // "Return null." michael@0: return null; michael@0: } michael@0: michael@0: function getFirstEquivalentPoint(node, offset) { michael@0: // "While (node, offset)'s previous equivalent point is not null, set michael@0: // (node, offset) to its previous equivalent point." michael@0: var prev; michael@0: while (prev = getPreviousEquivalentPoint(node, offset)) { michael@0: node = prev[0]; michael@0: offset = prev[1]; michael@0: } michael@0: michael@0: // "Return (node, offset)." michael@0: return [node, offset]; michael@0: } michael@0: michael@0: function getLastEquivalentPoint(node, offset) { michael@0: // "While (node, offset)'s next equivalent point is not null, set (node, michael@0: // offset) to its next equivalent point." michael@0: var next; michael@0: while (next = getNextEquivalentPoint(node, offset)) { michael@0: node = next[0]; michael@0: offset = next[1]; michael@0: } michael@0: michael@0: // "Return (node, offset)." michael@0: return [node, offset]; michael@0: } michael@0: michael@0: //@} michael@0: ///// Block-extending a range ///// michael@0: //@{ michael@0: michael@0: // "A boundary point (node, offset) is a block start point if either node's michael@0: // parent is null and offset is zero; or node has a child with index offset − michael@0: // 1, and that child is either a visible block node or a visible br." michael@0: function isBlockStartPoint(node, offset) { michael@0: return (!node.parentNode && offset == 0) michael@0: || (0 <= offset - 1 michael@0: && offset - 1 < node.childNodes.length michael@0: && isVisible(node.childNodes[offset - 1]) michael@0: && (isBlockNode(node.childNodes[offset - 1]) michael@0: || isHtmlElement(node.childNodes[offset - 1], "br"))); michael@0: } michael@0: michael@0: // "A boundary point (node, offset) is a block end point if either node's michael@0: // parent is null and offset is node's length; or node has a child with index michael@0: // offset, and that child is a visible block node." michael@0: function isBlockEndPoint(node, offset) { michael@0: return (!node.parentNode && offset == getNodeLength(node)) michael@0: || (offset < node.childNodes.length michael@0: && isVisible(node.childNodes[offset]) michael@0: && isBlockNode(node.childNodes[offset])); michael@0: } michael@0: michael@0: // "A boundary point is a block boundary point if it is either a block start michael@0: // point or a block end point." michael@0: function isBlockBoundaryPoint(node, offset) { michael@0: return isBlockStartPoint(node, offset) michael@0: || isBlockEndPoint(node, offset); michael@0: } michael@0: michael@0: function blockExtend(range) { michael@0: // "Let start node, start offset, end node, and end offset be the start michael@0: // and end nodes and offsets of the range." michael@0: var startNode = range.startContainer; michael@0: var startOffset = range.startOffset; michael@0: var endNode = range.endContainer; michael@0: var endOffset = range.endOffset; michael@0: michael@0: // "If some ancestor container of start node is an li, set start offset to michael@0: // the index of the last such li in tree order, and set start node to that michael@0: // li's parent." michael@0: var liAncestors = getAncestors(startNode).concat(startNode) michael@0: .filter(function(ancestor) { return isHtmlElement(ancestor, "li") }) michael@0: .slice(-1); michael@0: if (liAncestors.length) { michael@0: startOffset = getNodeIndex(liAncestors[0]); michael@0: startNode = liAncestors[0].parentNode; michael@0: } michael@0: michael@0: // "If (start node, start offset) is not a block start point, repeat the michael@0: // following steps:" michael@0: if (!isBlockStartPoint(startNode, startOffset)) do { michael@0: // "If start offset is zero, set it to start node's index, then set michael@0: // start node to its parent." michael@0: if (startOffset == 0) { michael@0: startOffset = getNodeIndex(startNode); michael@0: startNode = startNode.parentNode; michael@0: michael@0: // "Otherwise, subtract one from start offset." michael@0: } else { michael@0: startOffset--; michael@0: } michael@0: michael@0: // "If (start node, start offset) is a block boundary point, break from michael@0: // this loop." michael@0: } while (!isBlockBoundaryPoint(startNode, startOffset)); michael@0: michael@0: // "While start offset is zero and start node's parent is not null, set michael@0: // start offset to start node's index, then set start node to its parent." michael@0: while (startOffset == 0 michael@0: && startNode.parentNode) { michael@0: startOffset = getNodeIndex(startNode); michael@0: startNode = startNode.parentNode; michael@0: } michael@0: michael@0: // "If some ancestor container of end node is an li, set end offset to one michael@0: // plus the index of the last such li in tree order, and set end node to michael@0: // that li's parent." michael@0: var liAncestors = getAncestors(endNode).concat(endNode) michael@0: .filter(function(ancestor) { return isHtmlElement(ancestor, "li") }) michael@0: .slice(-1); michael@0: if (liAncestors.length) { michael@0: endOffset = 1 + getNodeIndex(liAncestors[0]); michael@0: endNode = liAncestors[0].parentNode; michael@0: } michael@0: michael@0: // "If (end node, end offset) is not a block end point, repeat the michael@0: // following steps:" michael@0: if (!isBlockEndPoint(endNode, endOffset)) do { michael@0: // "If end offset is end node's length, set it to one plus end node's michael@0: // index, then set end node to its parent." michael@0: if (endOffset == getNodeLength(endNode)) { michael@0: endOffset = 1 + getNodeIndex(endNode); michael@0: endNode = endNode.parentNode; michael@0: michael@0: // "Otherwise, add one to end offset. michael@0: } else { michael@0: endOffset++; michael@0: } michael@0: michael@0: // "If (end node, end offset) is a block boundary point, break from michael@0: // this loop." michael@0: } while (!isBlockBoundaryPoint(endNode, endOffset)); michael@0: michael@0: // "While end offset is end node's length and end node's parent is not michael@0: // null, set end offset to one plus end node's index, then set end node to michael@0: // its parent." michael@0: while (endOffset == getNodeLength(endNode) michael@0: && endNode.parentNode) { michael@0: endOffset = 1 + getNodeIndex(endNode); michael@0: endNode = endNode.parentNode; michael@0: } michael@0: michael@0: // "Let new range be a new range whose start and end nodes and offsets michael@0: // are start node, start offset, end node, and end offset." michael@0: var newRange = startNode.ownerDocument.createRange(); michael@0: newRange.setStart(startNode, startOffset); michael@0: newRange.setEnd(endNode, endOffset); michael@0: michael@0: // "Return new range." michael@0: return newRange; michael@0: } michael@0: michael@0: function followsLineBreak(node) { michael@0: // "Let offset be zero." michael@0: var offset = 0; michael@0: michael@0: // "While (node, offset) is not a block boundary point:" michael@0: while (!isBlockBoundaryPoint(node, offset)) { michael@0: // "If node has a visible child with index offset minus one, return michael@0: // false." michael@0: if (0 <= offset - 1 michael@0: && offset - 1 < node.childNodes.length michael@0: && isVisible(node.childNodes[offset - 1])) { michael@0: return false; michael@0: } michael@0: michael@0: // "If offset is zero or node has no children, set offset to node's michael@0: // index, then set node to its parent." michael@0: if (offset == 0 michael@0: || !node.hasChildNodes()) { michael@0: offset = getNodeIndex(node); michael@0: node = node.parentNode; michael@0: michael@0: // "Otherwise, set node to its child with index offset minus one, then michael@0: // set offset to node's length." michael@0: } else { michael@0: node = node.childNodes[offset - 1]; michael@0: offset = getNodeLength(node); michael@0: } michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: function precedesLineBreak(node) { michael@0: // "Let offset be node's length." michael@0: var offset = getNodeLength(node); michael@0: michael@0: // "While (node, offset) is not a block boundary point:" michael@0: while (!isBlockBoundaryPoint(node, offset)) { michael@0: // "If node has a visible child with index offset, return false." michael@0: if (offset < node.childNodes.length michael@0: && isVisible(node.childNodes[offset])) { michael@0: return false; michael@0: } michael@0: michael@0: // "If offset is node's length or node has no children, set offset to michael@0: // one plus node's index, then set node to its parent." michael@0: if (offset == getNodeLength(node) michael@0: || !node.hasChildNodes()) { michael@0: offset = 1 + getNodeIndex(node); michael@0: node = node.parentNode; michael@0: michael@0: // "Otherwise, set node to its child with index offset and set offset michael@0: // to zero." michael@0: } else { michael@0: node = node.childNodes[offset]; michael@0: offset = 0; michael@0: } michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: //@} michael@0: ///// Recording and restoring overrides ///// michael@0: //@{ michael@0: michael@0: function recordCurrentOverrides() { michael@0: // "Let overrides be a list of (string, string or boolean) ordered pairs, michael@0: // initially empty." michael@0: var overrides = []; michael@0: michael@0: // "If there is a value override for "createLink", add ("createLink", value michael@0: // override for "createLink") to overrides." michael@0: if (getValueOverride("createlink") !== undefined) { michael@0: overrides.push(["createlink", getValueOverride("createlink")]); michael@0: } michael@0: michael@0: // "For each command in the list "bold", "italic", "strikethrough", michael@0: // "subscript", "superscript", "underline", in order: if there is a state michael@0: // override for command, add (command, command's state override) to michael@0: // overrides." michael@0: ["bold", "italic", "strikethrough", "subscript", "superscript", michael@0: "underline"].forEach(function(command) { michael@0: if (getStateOverride(command) !== undefined) { michael@0: overrides.push([command, getStateOverride(command)]); michael@0: } michael@0: }); michael@0: michael@0: // "For each command in the list "fontName", "fontSize", "foreColor", michael@0: // "hiliteColor", in order: if there is a value override for command, add michael@0: // (command, command's value override) to overrides." michael@0: ["fontname", "fontsize", "forecolor", michael@0: "hilitecolor"].forEach(function(command) { michael@0: if (getValueOverride(command) !== undefined) { michael@0: overrides.push([command, getValueOverride(command)]); michael@0: } michael@0: }); michael@0: michael@0: // "Return overrides." michael@0: return overrides; michael@0: } michael@0: michael@0: function recordCurrentStatesAndValues() { michael@0: // "Let overrides be a list of (string, string or boolean) ordered pairs, michael@0: // initially empty." michael@0: var overrides = []; michael@0: michael@0: // "Let node be the first formattable node effectively contained in the michael@0: // active range, or null if there is none." michael@0: var node = getAllEffectivelyContainedNodes(getActiveRange()) michael@0: .filter(isFormattableNode)[0]; michael@0: michael@0: // "If node is null, return overrides." michael@0: if (!node) { michael@0: return overrides; michael@0: } michael@0: michael@0: // "Add ("createLink", node's effective command value for "createLink") to michael@0: // overrides." michael@0: overrides.push(["createlink", getEffectiveCommandValue(node, "createlink")]); michael@0: michael@0: // "For each command in the list "bold", "italic", "strikethrough", michael@0: // "subscript", "superscript", "underline", in order: if node's effective michael@0: // command value for command is one of its inline command activated values, michael@0: // add (command, true) to overrides, and otherwise add (command, false) to michael@0: // overrides." michael@0: ["bold", "italic", "strikethrough", "subscript", "superscript", michael@0: "underline"].forEach(function(command) { michael@0: if (commands[command].inlineCommandActivatedValues michael@0: .indexOf(getEffectiveCommandValue(node, command)) != -1) { michael@0: overrides.push([command, true]); michael@0: } else { michael@0: overrides.push([command, false]); michael@0: } michael@0: }); michael@0: michael@0: // "For each command in the list "fontName", "foreColor", "hiliteColor", in michael@0: // order: add (command, command's value) to overrides." michael@0: ["fontname", "fontsize", "forecolor", "hilitecolor"].forEach(function(command) { michael@0: overrides.push([command, commands[command].value()]); michael@0: }); michael@0: michael@0: // "Add ("fontSize", node's effective command value for "fontSize") to michael@0: // overrides." michael@0: overrides.push(["fontsize", getEffectiveCommandValue(node, "fontsize")]); michael@0: michael@0: // "Return overrides." michael@0: return overrides; michael@0: } michael@0: michael@0: function restoreStatesAndValues(overrides) { michael@0: // "Let node be the first formattable node effectively contained in the michael@0: // active range, or null if there is none." michael@0: var node = getAllEffectivelyContainedNodes(getActiveRange()) michael@0: .filter(isFormattableNode)[0]; michael@0: michael@0: // "If node is not null, then for each (command, override) pair in michael@0: // overrides, in order:" michael@0: if (node) { michael@0: for (var i = 0; i < overrides.length; i++) { michael@0: var command = overrides[i][0]; michael@0: var override = overrides[i][1]; michael@0: michael@0: // "If override is a boolean, and queryCommandState(command) michael@0: // returns something different from override, take the action for michael@0: // command, with value equal to the empty string." michael@0: if (typeof override == "boolean" michael@0: && myQueryCommandState(command) != override) { michael@0: commands[command].action(""); michael@0: michael@0: // "Otherwise, if override is a string, and command is neither michael@0: // "createLink" nor "fontSize", and queryCommandValue(command) michael@0: // returns something not equivalent to override, take the action michael@0: // for command, with value equal to override." michael@0: } else if (typeof override == "string" michael@0: && command != "createlink" michael@0: && command != "fontsize" michael@0: && !areEquivalentValues(command, myQueryCommandValue(command), override)) { michael@0: commands[command].action(override); michael@0: michael@0: // "Otherwise, if override is a string; and command is michael@0: // "createLink"; and either there is a value override for michael@0: // "createLink" that is not equal to override, or there is no value michael@0: // override for "createLink" and node's effective command value for michael@0: // "createLink" is not equal to override: take the action for michael@0: // "createLink", with value equal to override." michael@0: } else if (typeof override == "string" michael@0: && command == "createlink" michael@0: && ( michael@0: ( michael@0: getValueOverride("createlink") !== undefined michael@0: && getValueOverride("createlink") !== override michael@0: ) || ( michael@0: getValueOverride("createlink") === undefined michael@0: && getEffectiveCommandValue(node, "createlink") !== override michael@0: ) michael@0: )) { michael@0: commands.createlink.action(override); michael@0: michael@0: // "Otherwise, if override is a string; and command is "fontSize"; michael@0: // and either there is a value override for "fontSize" that is not michael@0: // equal to override, or there is no value override for "fontSize" michael@0: // and node's effective command value for "fontSize" is not loosely michael@0: // equivalent to override:" michael@0: } else if (typeof override == "string" michael@0: && command == "fontsize" michael@0: && ( michael@0: ( michael@0: getValueOverride("fontsize") !== undefined michael@0: && getValueOverride("fontsize") !== override michael@0: ) || ( michael@0: getValueOverride("fontsize") === undefined michael@0: && !areLooselyEquivalentValues(command, getEffectiveCommandValue(node, "fontsize"), override) michael@0: ) michael@0: )) { michael@0: // "Convert override to an integer number of pixels, and set michael@0: // override to the legacy font size for the result." michael@0: override = getLegacyFontSize(override); michael@0: michael@0: // "Take the action for "fontSize", with value equal to michael@0: // override." michael@0: commands.fontsize.action(override); michael@0: michael@0: // "Otherwise, continue this loop from the beginning." michael@0: } else { michael@0: continue; michael@0: } michael@0: michael@0: // "Set node to the first formattable node effectively contained in michael@0: // the active range, if there is one." michael@0: node = getAllEffectivelyContainedNodes(getActiveRange()) michael@0: .filter(isFormattableNode)[0] michael@0: || node; michael@0: } michael@0: michael@0: // "Otherwise, for each (command, override) pair in overrides, in order:" michael@0: } else { michael@0: for (var i = 0; i < overrides.length; i++) { michael@0: var command = overrides[i][0]; michael@0: var override = overrides[i][1]; michael@0: michael@0: // "If override is a boolean, set the state override for command to michael@0: // override." michael@0: if (typeof override == "boolean") { michael@0: setStateOverride(command, override); michael@0: } michael@0: michael@0: // "If override is a string, set the value override for command to michael@0: // override." michael@0: if (typeof override == "string") { michael@0: setValueOverride(command, override); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: //@} michael@0: ///// Deleting the selection ///// michael@0: //@{ michael@0: michael@0: // The flags argument is a dictionary that can have blockMerging, michael@0: // stripWrappers, and/or direction as keys. michael@0: function deleteSelection(flags) { michael@0: if (flags === undefined) { michael@0: flags = {}; michael@0: } michael@0: michael@0: var blockMerging = "blockMerging" in flags ? Boolean(flags.blockMerging) : true; michael@0: var stripWrappers = "stripWrappers" in flags ? Boolean(flags.stripWrappers) : true; michael@0: var direction = "direction" in flags ? flags.direction : "forward"; michael@0: michael@0: // "If the active range is null, abort these steps and do nothing." michael@0: if (!getActiveRange()) { michael@0: return; michael@0: } michael@0: michael@0: // "Canonicalize whitespace at the active range's start." michael@0: canonicalizeWhitespace(getActiveRange().startContainer, getActiveRange().startOffset); michael@0: michael@0: // "Canonicalize whitespace at the active range's end." michael@0: canonicalizeWhitespace(getActiveRange().endContainer, getActiveRange().endOffset); michael@0: michael@0: // "Let (start node, start offset) be the last equivalent point for the michael@0: // active range's start." michael@0: var start = getLastEquivalentPoint(getActiveRange().startContainer, getActiveRange().startOffset); michael@0: var startNode = start[0]; michael@0: var startOffset = start[1]; michael@0: michael@0: // "Let (end node, end offset) be the first equivalent point for the active michael@0: // range's end." michael@0: var end = getFirstEquivalentPoint(getActiveRange().endContainer, getActiveRange().endOffset); michael@0: var endNode = end[0]; michael@0: var endOffset = end[1]; michael@0: michael@0: // "If (end node, end offset) is not after (start node, start offset):" michael@0: if (getPosition(endNode, endOffset, startNode, startOffset) !== "after") { michael@0: // "If direction is "forward", call collapseToStart() on the context michael@0: // object's Selection." michael@0: // michael@0: // Here and in a few other places, we check rangeCount to work around a michael@0: // WebKit bug: it will sometimes incorrectly remove ranges from the michael@0: // selection if nodes are removed, so collapseToStart() will throw. michael@0: // This will break everything if we're using an actual selection, but michael@0: // if getActiveRange() is really just returning globalRange and that's michael@0: // all we care about, it will work fine. I only add the extra check michael@0: // for errors I actually hit in testing. michael@0: if (direction == "forward") { michael@0: if (getSelection().rangeCount) { michael@0: getSelection().collapseToStart(); michael@0: } michael@0: getActiveRange().collapse(true); michael@0: michael@0: // "Otherwise, call collapseToEnd() on the context object's Selection." michael@0: } else { michael@0: getSelection().collapseToEnd(); michael@0: getActiveRange().collapse(false); michael@0: } michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "If start node is a Text node and start offset is 0, set start offset to michael@0: // the index of start node, then set start node to its parent." michael@0: if (startNode.nodeType == Node.TEXT_NODE michael@0: && startOffset == 0) { michael@0: startOffset = getNodeIndex(startNode); michael@0: startNode = startNode.parentNode; michael@0: } michael@0: michael@0: // "If end node is a Text node and end offset is its length, set end offset michael@0: // to one plus the index of end node, then set end node to its parent." michael@0: if (endNode.nodeType == Node.TEXT_NODE michael@0: && endOffset == getNodeLength(endNode)) { michael@0: endOffset = 1 + getNodeIndex(endNode); michael@0: endNode = endNode.parentNode; michael@0: } michael@0: michael@0: // "Call collapse(start node, start offset) on the context object's michael@0: // Selection." michael@0: getSelection().collapse(startNode, startOffset); michael@0: getActiveRange().setStart(startNode, startOffset); michael@0: michael@0: // "Call extend(end node, end offset) on the context object's Selection." michael@0: getSelection().extend(endNode, endOffset); michael@0: getActiveRange().setEnd(endNode, endOffset); michael@0: michael@0: // "Let start block be the active range's start node." michael@0: var startBlock = getActiveRange().startContainer; michael@0: michael@0: // "While start block's parent is in the same editing host and start block michael@0: // is an inline node, set start block to its parent." michael@0: while (inSameEditingHost(startBlock, startBlock.parentNode) michael@0: && isInlineNode(startBlock)) { michael@0: startBlock = startBlock.parentNode; michael@0: } michael@0: michael@0: // "If start block is neither a block node nor an editing host, or "span" michael@0: // is not an allowed child of start block, or start block is a td or th, michael@0: // set start block to null." michael@0: if ((!isBlockNode(startBlock) && !isEditingHost(startBlock)) michael@0: || !isAllowedChild("span", startBlock) michael@0: || isHtmlElement(startBlock, ["td", "th"])) { michael@0: startBlock = null; michael@0: } michael@0: michael@0: // "Let end block be the active range's end node." michael@0: var endBlock = getActiveRange().endContainer; michael@0: michael@0: // "While end block's parent is in the same editing host and end block is michael@0: // an inline node, set end block to its parent." michael@0: while (inSameEditingHost(endBlock, endBlock.parentNode) michael@0: && isInlineNode(endBlock)) { michael@0: endBlock = endBlock.parentNode; michael@0: } michael@0: michael@0: // "If end block is neither a block node nor an editing host, or "span" is michael@0: // not an allowed child of end block, or end block is a td or th, set end michael@0: // block to null." michael@0: if ((!isBlockNode(endBlock) && !isEditingHost(endBlock)) michael@0: || !isAllowedChild("span", endBlock) michael@0: || isHtmlElement(endBlock, ["td", "th"])) { michael@0: endBlock = null; michael@0: } michael@0: michael@0: // "Record current states and values, and let overrides be the result." michael@0: var overrides = recordCurrentStatesAndValues(); michael@0: michael@0: // "If start node and end node are the same, and start node is an editable michael@0: // Text node:" michael@0: if (startNode == endNode michael@0: && isEditable(startNode) michael@0: && startNode.nodeType == Node.TEXT_NODE) { michael@0: // "Call deleteData(start offset, end offset − start offset) on start michael@0: // node." michael@0: startNode.deleteData(startOffset, endOffset - startOffset); michael@0: michael@0: // "Canonicalize whitespace at (start node, start offset), with fix michael@0: // collapsed space false." michael@0: canonicalizeWhitespace(startNode, startOffset, false); michael@0: michael@0: // "If direction is "forward", call collapseToStart() on the context michael@0: // object's Selection." michael@0: if (direction == "forward") { michael@0: if (getSelection().rangeCount) { michael@0: getSelection().collapseToStart(); michael@0: } michael@0: getActiveRange().collapse(true); michael@0: michael@0: // "Otherwise, call collapseToEnd() on the context object's Selection." michael@0: } else { michael@0: getSelection().collapseToEnd(); michael@0: getActiveRange().collapse(false); michael@0: } michael@0: michael@0: // "Restore states and values from overrides." michael@0: restoreStatesAndValues(overrides); michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "If start node is an editable Text node, call deleteData() on it, with michael@0: // start offset as the first argument and (length of start node − start michael@0: // offset) as the second argument." michael@0: if (isEditable(startNode) michael@0: && startNode.nodeType == Node.TEXT_NODE) { michael@0: startNode.deleteData(startOffset, getNodeLength(startNode) - startOffset); michael@0: } michael@0: michael@0: // "Let node list be a list of nodes, initially empty." michael@0: // michael@0: // "For each node contained in the active range, append node to node list michael@0: // if the last member of node list (if any) is not an ancestor of node; michael@0: // node is editable; and node is not a thead, tbody, tfoot, tr, th, or td." michael@0: var nodeList = getContainedNodes(getActiveRange(), michael@0: function(node) { michael@0: return isEditable(node) michael@0: && !isHtmlElement(node, ["thead", "tbody", "tfoot", "tr", "th", "td"]); michael@0: } michael@0: ); michael@0: michael@0: // "For each node in node list:" michael@0: for (var i = 0; i < nodeList.length; i++) { michael@0: var node = nodeList[i]; michael@0: michael@0: // "Let parent be the parent of node." michael@0: var parent_ = node.parentNode; michael@0: michael@0: // "Remove node from parent." michael@0: parent_.removeChild(node); michael@0: michael@0: // "If the block node of parent has no visible children, and parent is michael@0: // editable or an editing host, call createElement("br") on the context michael@0: // object and append the result as the last child of parent." michael@0: if (![].some.call(getBlockNodeOf(parent_).childNodes, isVisible) michael@0: && (isEditable(parent_) || isEditingHost(parent_))) { michael@0: parent_.appendChild(document.createElement("br")); michael@0: } michael@0: michael@0: // "If strip wrappers is true or parent is not an ancestor container of michael@0: // start node, while parent is an editable inline node with length 0, michael@0: // let grandparent be the parent of parent, then remove parent from michael@0: // grandparent, then set parent to grandparent." michael@0: if (stripWrappers michael@0: || (!isAncestor(parent_, startNode) && parent_ != startNode)) { michael@0: while (isEditable(parent_) michael@0: && isInlineNode(parent_) michael@0: && getNodeLength(parent_) == 0) { michael@0: var grandparent = parent_.parentNode; michael@0: grandparent.removeChild(parent_); michael@0: parent_ = grandparent; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // "If end node is an editable Text node, call deleteData(0, end offset) on michael@0: // it." michael@0: if (isEditable(endNode) michael@0: && endNode.nodeType == Node.TEXT_NODE) { michael@0: endNode.deleteData(0, endOffset); michael@0: } michael@0: michael@0: // "Canonicalize whitespace at the active range's start, with fix collapsed michael@0: // space false." michael@0: canonicalizeWhitespace(getActiveRange().startContainer, getActiveRange().startOffset, false); michael@0: michael@0: // "Canonicalize whitespace at the active range's end, with fix collapsed michael@0: // space false." michael@0: canonicalizeWhitespace(getActiveRange().endContainer, getActiveRange().endOffset, false); michael@0: michael@0: // "If block merging is false, or start block or end block is null, or michael@0: // start block is not in the same editing host as end block, or start block michael@0: // and end block are the same:" michael@0: if (!blockMerging michael@0: || !startBlock michael@0: || !endBlock michael@0: || !inSameEditingHost(startBlock, endBlock) michael@0: || startBlock == endBlock) { michael@0: // "If direction is "forward", call collapseToStart() on the context michael@0: // object's Selection." michael@0: if (direction == "forward") { michael@0: if (getSelection().rangeCount) { michael@0: getSelection().collapseToStart(); michael@0: } michael@0: getActiveRange().collapse(true); michael@0: michael@0: // "Otherwise, call collapseToEnd() on the context object's Selection." michael@0: } else { michael@0: if (getSelection().rangeCount) { michael@0: getSelection().collapseToEnd(); michael@0: } michael@0: getActiveRange().collapse(false); michael@0: } michael@0: michael@0: // "Restore states and values from overrides." michael@0: restoreStatesAndValues(overrides); michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "If start block has one child, which is a collapsed block prop, remove michael@0: // its child from it." michael@0: if (startBlock.children.length == 1 michael@0: && isCollapsedBlockProp(startBlock.firstChild)) { michael@0: startBlock.removeChild(startBlock.firstChild); michael@0: } michael@0: michael@0: // "If start block is an ancestor of end block:" michael@0: if (isAncestor(startBlock, endBlock)) { michael@0: // "Let reference node be end block." michael@0: var referenceNode = endBlock; michael@0: michael@0: // "While reference node is not a child of start block, set reference michael@0: // node to its parent." michael@0: while (referenceNode.parentNode != startBlock) { michael@0: referenceNode = referenceNode.parentNode; michael@0: } michael@0: michael@0: // "Call collapse() on the context object's Selection, with first michael@0: // argument start block and second argument the index of reference michael@0: // node." michael@0: getSelection().collapse(startBlock, getNodeIndex(referenceNode)); michael@0: getActiveRange().setStart(startBlock, getNodeIndex(referenceNode)); michael@0: getActiveRange().collapse(true); michael@0: michael@0: // "If end block has no children:" michael@0: if (!endBlock.hasChildNodes()) { michael@0: // "While end block is editable and is the only child of its parent michael@0: // and is not a child of start block, let parent equal end block, michael@0: // then remove end block from parent, then set end block to michael@0: // parent." michael@0: while (isEditable(endBlock) michael@0: && endBlock.parentNode.childNodes.length == 1 michael@0: && endBlock.parentNode != startBlock) { michael@0: var parent_ = endBlock; michael@0: parent_.removeChild(endBlock); michael@0: endBlock = parent_; michael@0: } michael@0: michael@0: // "If end block is editable and is not an inline node, and its michael@0: // previousSibling and nextSibling are both inline nodes, call michael@0: // createElement("br") on the context object and insert it into end michael@0: // block's parent immediately after end block." michael@0: if (isEditable(endBlock) michael@0: && !isInlineNode(endBlock) michael@0: && isInlineNode(endBlock.previousSibling) michael@0: && isInlineNode(endBlock.nextSibling)) { michael@0: endBlock.parentNode.insertBefore(document.createElement("br"), endBlock.nextSibling); michael@0: } michael@0: michael@0: // "If end block is editable, remove it from its parent." michael@0: if (isEditable(endBlock)) { michael@0: endBlock.parentNode.removeChild(endBlock); michael@0: } michael@0: michael@0: // "Restore states and values from overrides." michael@0: restoreStatesAndValues(overrides); michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "If end block's firstChild is not an inline node, restore states and michael@0: // values from overrides, then abort these steps." michael@0: if (!isInlineNode(endBlock.firstChild)) { michael@0: restoreStatesAndValues(overrides); michael@0: return; michael@0: } michael@0: michael@0: // "Let children be a list of nodes, initially empty." michael@0: var children = []; michael@0: michael@0: // "Append the first child of end block to children." michael@0: children.push(endBlock.firstChild); michael@0: michael@0: // "While children's last member is not a br, and children's last michael@0: // member's nextSibling is an inline node, append children's last michael@0: // member's nextSibling to children." michael@0: while (!isHtmlElement(children[children.length - 1], "br") michael@0: && isInlineNode(children[children.length - 1].nextSibling)) { michael@0: children.push(children[children.length - 1].nextSibling); michael@0: } michael@0: michael@0: // "Record the values of children, and let values be the result." michael@0: var values = recordValues(children); michael@0: michael@0: // "While children's first member's parent is not start block, split michael@0: // the parent of children." michael@0: while (children[0].parentNode != startBlock) { michael@0: splitParent(children); michael@0: } michael@0: michael@0: // "If children's first member's previousSibling is an editable br, michael@0: // remove that br from its parent." michael@0: if (isEditable(children[0].previousSibling) michael@0: && isHtmlElement(children[0].previousSibling, "br")) { michael@0: children[0].parentNode.removeChild(children[0].previousSibling); michael@0: } michael@0: michael@0: // "Otherwise, if start block is a descendant of end block:" michael@0: } else if (isDescendant(startBlock, endBlock)) { michael@0: // "Call collapse() on the context object's Selection, with first michael@0: // argument start block and second argument start block's length." michael@0: getSelection().collapse(startBlock, getNodeLength(startBlock)); michael@0: getActiveRange().setStart(startBlock, getNodeLength(startBlock)); michael@0: getActiveRange().collapse(true); michael@0: michael@0: // "Let reference node be start block." michael@0: var referenceNode = startBlock; michael@0: michael@0: // "While reference node is not a child of end block, set reference michael@0: // node to its parent." michael@0: while (referenceNode.parentNode != endBlock) { michael@0: referenceNode = referenceNode.parentNode; michael@0: } michael@0: michael@0: // "If reference node's nextSibling is an inline node and start block's michael@0: // lastChild is a br, remove start block's lastChild from it." michael@0: if (isInlineNode(referenceNode.nextSibling) michael@0: && isHtmlElement(startBlock.lastChild, "br")) { michael@0: startBlock.removeChild(startBlock.lastChild); michael@0: } michael@0: michael@0: // "Let nodes to move be a list of nodes, initially empty." michael@0: var nodesToMove = []; michael@0: michael@0: // "If reference node's nextSibling is neither null nor a block node, michael@0: // append it to nodes to move." michael@0: if (referenceNode.nextSibling michael@0: && !isBlockNode(referenceNode.nextSibling)) { michael@0: nodesToMove.push(referenceNode.nextSibling); michael@0: } michael@0: michael@0: // "While nodes to move is nonempty and its last member isn't a br and michael@0: // its last member's nextSibling is neither null nor a block node, michael@0: // append its last member's nextSibling to nodes to move." michael@0: if (nodesToMove.length michael@0: && !isHtmlElement(nodesToMove[nodesToMove.length - 1], "br") michael@0: && nodesToMove[nodesToMove.length - 1].nextSibling michael@0: && !isBlockNode(nodesToMove[nodesToMove.length - 1].nextSibling)) { michael@0: nodesToMove.push(nodesToMove[nodesToMove.length - 1].nextSibling); michael@0: } michael@0: michael@0: // "Record the values of nodes to move, and let values be the result." michael@0: var values = recordValues(nodesToMove); michael@0: michael@0: // "For each node in nodes to move, append node as the last child of michael@0: // start block, preserving ranges." michael@0: nodesToMove.forEach(function(node) { michael@0: movePreservingRanges(node, startBlock, -1); michael@0: }); michael@0: michael@0: // "Otherwise:" michael@0: } else { michael@0: // "Call collapse() on the context object's Selection, with first michael@0: // argument start block and second argument start block's length." michael@0: getSelection().collapse(startBlock, getNodeLength(startBlock)); michael@0: getActiveRange().setStart(startBlock, getNodeLength(startBlock)); michael@0: getActiveRange().collapse(true); michael@0: michael@0: // "If end block's firstChild is an inline node and start block's michael@0: // lastChild is a br, remove start block's lastChild from it." michael@0: if (isInlineNode(endBlock.firstChild) michael@0: && isHtmlElement(startBlock.lastChild, "br")) { michael@0: startBlock.removeChild(startBlock.lastChild); michael@0: } michael@0: michael@0: // "Record the values of end block's children, and let values be the michael@0: // result." michael@0: var values = recordValues([].slice.call(endBlock.childNodes)); michael@0: michael@0: // "While end block has children, append the first child of end block michael@0: // to start block, preserving ranges." michael@0: while (endBlock.hasChildNodes()) { michael@0: movePreservingRanges(endBlock.firstChild, startBlock, -1); michael@0: } michael@0: michael@0: // "While end block has no children, let parent be the parent of end michael@0: // block, then remove end block from parent, then set end block to michael@0: // parent." michael@0: while (!endBlock.hasChildNodes()) { michael@0: var parent_ = endBlock.parentNode; michael@0: parent_.removeChild(endBlock); michael@0: endBlock = parent_; michael@0: } michael@0: } michael@0: michael@0: // "Let ancestor be start block." michael@0: var ancestor = startBlock; michael@0: michael@0: // "While ancestor has an inclusive ancestor ol in the same editing host michael@0: // whose nextSibling is also an ol in the same editing host, or an michael@0: // inclusive ancestor ul in the same editing host whose nextSibling is also michael@0: // a ul in the same editing host:" michael@0: while (getInclusiveAncestors(ancestor).some(function(node) { michael@0: return inSameEditingHost(ancestor, node) michael@0: && ( michael@0: (isHtmlElement(node, "ol") && isHtmlElement(node.nextSibling, "ol")) michael@0: || (isHtmlElement(node, "ul") && isHtmlElement(node.nextSibling, "ul")) michael@0: ) && inSameEditingHost(ancestor, node.nextSibling); michael@0: })) { michael@0: // "While ancestor and its nextSibling are not both ols in the same michael@0: // editing host, and are also not both uls in the same editing host, michael@0: // set ancestor to its parent." michael@0: while (!( michael@0: isHtmlElement(ancestor, "ol") michael@0: && isHtmlElement(ancestor.nextSibling, "ol") michael@0: && inSameEditingHost(ancestor, ancestor.nextSibling) michael@0: ) && !( michael@0: isHtmlElement(ancestor, "ul") michael@0: && isHtmlElement(ancestor.nextSibling, "ul") michael@0: && inSameEditingHost(ancestor, ancestor.nextSibling) michael@0: )) { michael@0: ancestor = ancestor.parentNode; michael@0: } michael@0: michael@0: // "While ancestor's nextSibling has children, append ancestor's michael@0: // nextSibling's firstChild as the last child of ancestor, preserving michael@0: // ranges." michael@0: while (ancestor.nextSibling.hasChildNodes()) { michael@0: movePreservingRanges(ancestor.nextSibling.firstChild, ancestor, -1); michael@0: } michael@0: michael@0: // "Remove ancestor's nextSibling from its parent." michael@0: ancestor.parentNode.removeChild(ancestor.nextSibling); michael@0: } michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: michael@0: // "If start block has no children, call createElement("br") on the context michael@0: // object and append the result as the last child of start block." michael@0: if (!startBlock.hasChildNodes()) { michael@0: startBlock.appendChild(document.createElement("br")); michael@0: } michael@0: michael@0: // "Remove extraneous line breaks at the end of start block." michael@0: removeExtraneousLineBreaksAtTheEndOf(startBlock); michael@0: michael@0: // "Restore states and values from overrides." michael@0: restoreStatesAndValues(overrides); michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Splitting a node list's parent ///// michael@0: //@{ michael@0: michael@0: function splitParent(nodeList) { michael@0: // "Let original parent be the parent of the first member of node list." michael@0: var originalParent = nodeList[0].parentNode; michael@0: michael@0: // "If original parent is not editable or its parent is null, do nothing michael@0: // and abort these steps." michael@0: if (!isEditable(originalParent) michael@0: || !originalParent.parentNode) { michael@0: return; michael@0: } michael@0: michael@0: // "If the first child of original parent is in node list, remove michael@0: // extraneous line breaks before original parent." michael@0: if (nodeList.indexOf(originalParent.firstChild) != -1) { michael@0: removeExtraneousLineBreaksBefore(originalParent); michael@0: } michael@0: michael@0: // "If the first child of original parent is in node list, and original michael@0: // parent follows a line break, set follows line break to true. Otherwise, michael@0: // set follows line break to false." michael@0: var followsLineBreak_ = nodeList.indexOf(originalParent.firstChild) != -1 michael@0: && followsLineBreak(originalParent); michael@0: michael@0: // "If the last child of original parent is in node list, and original michael@0: // parent precedes a line break, set precedes line break to true. michael@0: // Otherwise, set precedes line break to false." michael@0: var precedesLineBreak_ = nodeList.indexOf(originalParent.lastChild) != -1 michael@0: && precedesLineBreak(originalParent); michael@0: michael@0: // "If the first child of original parent is not in node list, but its last michael@0: // child is:" michael@0: if (nodeList.indexOf(originalParent.firstChild) == -1 michael@0: && nodeList.indexOf(originalParent.lastChild) != -1) { michael@0: // "For each node in node list, in reverse order, insert node into the michael@0: // parent of original parent immediately after original parent, michael@0: // preserving ranges." michael@0: for (var i = nodeList.length - 1; i >= 0; i--) { michael@0: movePreservingRanges(nodeList[i], originalParent.parentNode, 1 + getNodeIndex(originalParent)); michael@0: } michael@0: michael@0: // "If precedes line break is true, and the last member of node list michael@0: // does not precede a line break, call createElement("br") on the michael@0: // context object and insert the result immediately after the last michael@0: // member of node list." michael@0: if (precedesLineBreak_ michael@0: && !precedesLineBreak(nodeList[nodeList.length - 1])) { michael@0: nodeList[nodeList.length - 1].parentNode.insertBefore(document.createElement("br"), nodeList[nodeList.length - 1].nextSibling); michael@0: } michael@0: michael@0: // "Remove extraneous line breaks at the end of original parent." michael@0: removeExtraneousLineBreaksAtTheEndOf(originalParent); michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "If the first child of original parent is not in node list:" michael@0: if (nodeList.indexOf(originalParent.firstChild) == -1) { michael@0: // "Let cloned parent be the result of calling cloneNode(false) on michael@0: // original parent." michael@0: var clonedParent = originalParent.cloneNode(false); michael@0: michael@0: // "If original parent has an id attribute, unset it." michael@0: originalParent.removeAttribute("id"); michael@0: michael@0: // "Insert cloned parent into the parent of original parent immediately michael@0: // before original parent." michael@0: originalParent.parentNode.insertBefore(clonedParent, originalParent); michael@0: michael@0: // "While the previousSibling of the first member of node list is not michael@0: // null, append the first child of original parent as the last child of michael@0: // cloned parent, preserving ranges." michael@0: while (nodeList[0].previousSibling) { michael@0: movePreservingRanges(originalParent.firstChild, clonedParent, clonedParent.childNodes.length); michael@0: } michael@0: } michael@0: michael@0: // "For each node in node list, insert node into the parent of original michael@0: // parent immediately before original parent, preserving ranges." michael@0: for (var i = 0; i < nodeList.length; i++) { michael@0: movePreservingRanges(nodeList[i], originalParent.parentNode, getNodeIndex(originalParent)); michael@0: } michael@0: michael@0: // "If follows line break is true, and the first member of node list does michael@0: // not follow a line break, call createElement("br") on the context object michael@0: // and insert the result immediately before the first member of node list." michael@0: if (followsLineBreak_ michael@0: && !followsLineBreak(nodeList[0])) { michael@0: nodeList[0].parentNode.insertBefore(document.createElement("br"), nodeList[0]); michael@0: } michael@0: michael@0: // "If the last member of node list is an inline node other than a br, and michael@0: // the first child of original parent is a br, and original parent is not michael@0: // an inline node, remove the first child of original parent from original michael@0: // parent." michael@0: if (isInlineNode(nodeList[nodeList.length - 1]) michael@0: && !isHtmlElement(nodeList[nodeList.length - 1], "br") michael@0: && isHtmlElement(originalParent.firstChild, "br") michael@0: && !isInlineNode(originalParent)) { michael@0: originalParent.removeChild(originalParent.firstChild); michael@0: } michael@0: michael@0: // "If original parent has no children:" michael@0: if (!originalParent.hasChildNodes()) { michael@0: // "Remove original parent from its parent." michael@0: originalParent.parentNode.removeChild(originalParent); michael@0: michael@0: // "If precedes line break is true, and the last member of node list michael@0: // does not precede a line break, call createElement("br") on the michael@0: // context object and insert the result immediately after the last michael@0: // member of node list." michael@0: if (precedesLineBreak_ michael@0: && !precedesLineBreak(nodeList[nodeList.length - 1])) { michael@0: nodeList[nodeList.length - 1].parentNode.insertBefore(document.createElement("br"), nodeList[nodeList.length - 1].nextSibling); michael@0: } michael@0: michael@0: // "Otherwise, remove extraneous line breaks before original parent." michael@0: } else { michael@0: removeExtraneousLineBreaksBefore(originalParent); michael@0: } michael@0: michael@0: // "If node list's last member's nextSibling is null, but its parent is not michael@0: // null, remove extraneous line breaks at the end of node list's last michael@0: // member's parent." michael@0: if (!nodeList[nodeList.length - 1].nextSibling michael@0: && nodeList[nodeList.length - 1].parentNode) { michael@0: removeExtraneousLineBreaksAtTheEndOf(nodeList[nodeList.length - 1].parentNode); michael@0: } michael@0: } michael@0: michael@0: // "To remove a node node while preserving its descendants, split the parent of michael@0: // node's children if it has any. If it has no children, instead remove it from michael@0: // its parent." michael@0: function removePreservingDescendants(node) { michael@0: if (node.hasChildNodes()) { michael@0: splitParent([].slice.call(node.childNodes)); michael@0: } else { michael@0: node.parentNode.removeChild(node); michael@0: } michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Canonical space sequences ///// michael@0: //@{ michael@0: michael@0: function canonicalSpaceSequence(n, nonBreakingStart, nonBreakingEnd) { michael@0: // "If n is zero, return the empty string." michael@0: if (n == 0) { michael@0: return ""; michael@0: } michael@0: michael@0: // "If n is one and both non-breaking start and non-breaking end are false, michael@0: // return a single space (U+0020)." michael@0: if (n == 1 && !nonBreakingStart && !nonBreakingEnd) { michael@0: return " "; michael@0: } michael@0: michael@0: // "If n is one, return a single non-breaking space (U+00A0)." michael@0: if (n == 1) { michael@0: return "\xa0"; michael@0: } michael@0: michael@0: // "Let buffer be the empty string." michael@0: var buffer = ""; michael@0: michael@0: // "If non-breaking start is true, let repeated pair be U+00A0 U+0020. michael@0: // Otherwise, let it be U+0020 U+00A0." michael@0: var repeatedPair; michael@0: if (nonBreakingStart) { michael@0: repeatedPair = "\xa0 "; michael@0: } else { michael@0: repeatedPair = " \xa0"; michael@0: } michael@0: michael@0: // "While n is greater than three, append repeated pair to buffer and michael@0: // subtract two from n." michael@0: while (n > 3) { michael@0: buffer += repeatedPair; michael@0: n -= 2; michael@0: } michael@0: michael@0: // "If n is three, append a three-element string to buffer depending on michael@0: // non-breaking start and non-breaking end:" michael@0: if (n == 3) { michael@0: buffer += michael@0: !nonBreakingStart && !nonBreakingEnd ? " \xa0 " michael@0: : nonBreakingStart && !nonBreakingEnd ? "\xa0\xa0 " michael@0: : !nonBreakingStart && nonBreakingEnd ? " \xa0\xa0" michael@0: : nonBreakingStart && nonBreakingEnd ? "\xa0 \xa0" michael@0: : "impossible"; michael@0: michael@0: // "Otherwise, append a two-element string to buffer depending on michael@0: // non-breaking start and non-breaking end:" michael@0: } else { michael@0: buffer += michael@0: !nonBreakingStart && !nonBreakingEnd ? "\xa0 " michael@0: : nonBreakingStart && !nonBreakingEnd ? "\xa0 " michael@0: : !nonBreakingStart && nonBreakingEnd ? " \xa0" michael@0: : nonBreakingStart && nonBreakingEnd ? "\xa0\xa0" michael@0: : "impossible"; michael@0: } michael@0: michael@0: // "Return buffer." michael@0: return buffer; michael@0: } michael@0: michael@0: function canonicalizeWhitespace(node, offset, fixCollapsedSpace) { michael@0: if (fixCollapsedSpace === undefined) { michael@0: // "an optional boolean argument fix collapsed space that defaults to michael@0: // true" michael@0: fixCollapsedSpace = true; michael@0: } michael@0: michael@0: // "If node is neither editable nor an editing host, abort these steps." michael@0: if (!isEditable(node) && !isEditingHost(node)) { michael@0: return; michael@0: } michael@0: michael@0: // "Let start node equal node and let start offset equal offset." michael@0: var startNode = node; michael@0: var startOffset = offset; michael@0: michael@0: // "Repeat the following steps:" michael@0: while (true) { michael@0: // "If start node has a child in the same editing host with index start michael@0: // offset minus one, set start node to that child, then set start michael@0: // offset to start node's length." michael@0: if (0 <= startOffset - 1 michael@0: && inSameEditingHost(startNode, startNode.childNodes[startOffset - 1])) { michael@0: startNode = startNode.childNodes[startOffset - 1]; michael@0: startOffset = getNodeLength(startNode); michael@0: michael@0: // "Otherwise, if start offset is zero and start node does not follow a michael@0: // line break and start node's parent is in the same editing host, set michael@0: // start offset to start node's index, then set start node to its michael@0: // parent." michael@0: } else if (startOffset == 0 michael@0: && !followsLineBreak(startNode) michael@0: && inSameEditingHost(startNode, startNode.parentNode)) { michael@0: startOffset = getNodeIndex(startNode); michael@0: startNode = startNode.parentNode; michael@0: michael@0: // "Otherwise, if start node is a Text node and its parent's resolved michael@0: // value for "white-space" is neither "pre" nor "pre-wrap" and start michael@0: // offset is not zero and the (start offset − 1)st element of start michael@0: // node's data is a space (0x0020) or non-breaking space (0x00A0), michael@0: // subtract one from start offset." michael@0: } else if (startNode.nodeType == Node.TEXT_NODE michael@0: && ["pre", "pre-wrap"].indexOf(getComputedStyle(startNode.parentNode).whiteSpace) == -1 michael@0: && startOffset != 0 michael@0: && /[ \xa0]/.test(startNode.data[startOffset - 1])) { michael@0: startOffset--; michael@0: michael@0: // "Otherwise, break from this loop." michael@0: } else { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // "Let end node equal start node and end offset equal start offset." michael@0: var endNode = startNode; michael@0: var endOffset = startOffset; michael@0: michael@0: // "Let length equal zero." michael@0: var length = 0; michael@0: michael@0: // "Let collapse spaces be true if start offset is zero and start node michael@0: // follows a line break, otherwise false." michael@0: var collapseSpaces = startOffset == 0 && followsLineBreak(startNode); michael@0: michael@0: // "Repeat the following steps:" michael@0: while (true) { michael@0: // "If end node has a child in the same editing host with index end michael@0: // offset, set end node to that child, then set end offset to zero." michael@0: if (endOffset < endNode.childNodes.length michael@0: && inSameEditingHost(endNode, endNode.childNodes[endOffset])) { michael@0: endNode = endNode.childNodes[endOffset]; michael@0: endOffset = 0; michael@0: michael@0: // "Otherwise, if end offset is end node's length and end node does not michael@0: // precede a line break and end node's parent is in the same editing michael@0: // host, set end offset to one plus end node's index, then set end node michael@0: // to its parent." michael@0: } else if (endOffset == getNodeLength(endNode) michael@0: && !precedesLineBreak(endNode) michael@0: && inSameEditingHost(endNode, endNode.parentNode)) { michael@0: endOffset = 1 + getNodeIndex(endNode); michael@0: endNode = endNode.parentNode; michael@0: michael@0: // "Otherwise, if end node is a Text node and its parent's resolved michael@0: // value for "white-space" is neither "pre" nor "pre-wrap" and end michael@0: // offset is not end node's length and the end offsetth element of michael@0: // end node's data is a space (0x0020) or non-breaking space (0x00A0):" michael@0: } else if (endNode.nodeType == Node.TEXT_NODE michael@0: && ["pre", "pre-wrap"].indexOf(getComputedStyle(endNode.parentNode).whiteSpace) == -1 michael@0: && endOffset != getNodeLength(endNode) michael@0: && /[ \xa0]/.test(endNode.data[endOffset])) { michael@0: // "If fix collapsed space is true, and collapse spaces is true, michael@0: // and the end offsetth code unit of end node's data is a space michael@0: // (0x0020): call deleteData(end offset, 1) on end node, then michael@0: // continue this loop from the beginning." michael@0: if (fixCollapsedSpace michael@0: && collapseSpaces michael@0: && " " == endNode.data[endOffset]) { michael@0: endNode.deleteData(endOffset, 1); michael@0: continue; michael@0: } michael@0: michael@0: // "Set collapse spaces to true if the end offsetth element of end michael@0: // node's data is a space (0x0020), false otherwise." michael@0: collapseSpaces = " " == endNode.data[endOffset]; michael@0: michael@0: // "Add one to end offset." michael@0: endOffset++; michael@0: michael@0: // "Add one to length." michael@0: length++; michael@0: michael@0: // "Otherwise, break from this loop." michael@0: } else { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // "If fix collapsed space is true, then while (start node, start offset) michael@0: // is before (end node, end offset):" michael@0: if (fixCollapsedSpace) { michael@0: while (getPosition(startNode, startOffset, endNode, endOffset) == "before") { michael@0: // "If end node has a child in the same editing host with index end michael@0: // offset − 1, set end node to that child, then set end offset to end michael@0: // node's length." michael@0: if (0 <= endOffset - 1 michael@0: && endOffset - 1 < endNode.childNodes.length michael@0: && inSameEditingHost(endNode, endNode.childNodes[endOffset - 1])) { michael@0: endNode = endNode.childNodes[endOffset - 1]; michael@0: endOffset = getNodeLength(endNode); michael@0: michael@0: // "Otherwise, if end offset is zero and end node's parent is in the michael@0: // same editing host, set end offset to end node's index, then set end michael@0: // node to its parent." michael@0: } else if (endOffset == 0 michael@0: && inSameEditingHost(endNode, endNode.parentNode)) { michael@0: endOffset = getNodeIndex(endNode); michael@0: endNode = endNode.parentNode; michael@0: michael@0: // "Otherwise, if end node is a Text node and its parent's resolved michael@0: // value for "white-space" is neither "pre" nor "pre-wrap" and end michael@0: // offset is end node's length and the last code unit of end node's michael@0: // data is a space (0x0020) and end node precedes a line break:" michael@0: } else if (endNode.nodeType == Node.TEXT_NODE michael@0: && ["pre", "pre-wrap"].indexOf(getComputedStyle(endNode.parentNode).whiteSpace) == -1 michael@0: && endOffset == getNodeLength(endNode) michael@0: && endNode.data[endNode.data.length - 1] == " " michael@0: && precedesLineBreak(endNode)) { michael@0: // "Subtract one from end offset." michael@0: endOffset--; michael@0: michael@0: // "Subtract one from length." michael@0: length--; michael@0: michael@0: // "Call deleteData(end offset, 1) on end node." michael@0: endNode.deleteData(endOffset, 1); michael@0: michael@0: // "Otherwise, break from this loop." michael@0: } else { michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // "Let replacement whitespace be the canonical space sequence of length michael@0: // length. non-breaking start is true if start offset is zero and start michael@0: // node follows a line break, and false otherwise. non-breaking end is true michael@0: // if end offset is end node's length and end node precedes a line break, michael@0: // and false otherwise." michael@0: var replacementWhitespace = canonicalSpaceSequence(length, michael@0: startOffset == 0 && followsLineBreak(startNode), michael@0: endOffset == getNodeLength(endNode) && precedesLineBreak(endNode)); michael@0: michael@0: // "While (start node, start offset) is before (end node, end offset):" michael@0: while (getPosition(startNode, startOffset, endNode, endOffset) == "before") { michael@0: // "If start node has a child with index start offset, set start node michael@0: // to that child, then set start offset to zero." michael@0: if (startOffset < startNode.childNodes.length) { michael@0: startNode = startNode.childNodes[startOffset]; michael@0: startOffset = 0; michael@0: michael@0: // "Otherwise, if start node is not a Text node or if start offset is michael@0: // start node's length, set start offset to one plus start node's michael@0: // index, then set start node to its parent." michael@0: } else if (startNode.nodeType != Node.TEXT_NODE michael@0: || startOffset == getNodeLength(startNode)) { michael@0: startOffset = 1 + getNodeIndex(startNode); michael@0: startNode = startNode.parentNode; michael@0: michael@0: // "Otherwise:" michael@0: } else { michael@0: // "Remove the first element from replacement whitespace, and let michael@0: // element be that element." michael@0: var element = replacementWhitespace[0]; michael@0: replacementWhitespace = replacementWhitespace.slice(1); michael@0: michael@0: // "If element is not the same as the start offsetth element of michael@0: // start node's data:" michael@0: if (element != startNode.data[startOffset]) { michael@0: // "Call insertData(start offset, element) on start node." michael@0: startNode.insertData(startOffset, element); michael@0: michael@0: // "Call deleteData(start offset + 1, 1) on start node." michael@0: startNode.deleteData(startOffset + 1, 1); michael@0: } michael@0: michael@0: // "Add one to start offset." michael@0: startOffset++; michael@0: } michael@0: } michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Indenting and outdenting ///// michael@0: //@{ michael@0: michael@0: function indentNodes(nodeList) { michael@0: // "If node list is empty, do nothing and abort these steps." michael@0: if (!nodeList.length) { michael@0: return; michael@0: } michael@0: michael@0: // "Let first node be the first member of node list." michael@0: var firstNode = nodeList[0]; michael@0: michael@0: // "If first node's parent is an ol or ul:" michael@0: if (isHtmlElement(firstNode.parentNode, ["OL", "UL"])) { michael@0: // "Let tag be the local name of the parent of first node." michael@0: var tag = firstNode.parentNode.tagName; michael@0: michael@0: // "Wrap node list, with sibling criteria returning true for an HTML michael@0: // element with local name tag and false otherwise, and new parent michael@0: // instructions returning the result of calling createElement(tag) on michael@0: // the ownerDocument of first node." michael@0: wrap(nodeList, michael@0: function(node) { return isHtmlElement(node, tag) }, michael@0: function() { return firstNode.ownerDocument.createElement(tag) }); michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "Wrap node list, with sibling criteria returning true for a simple michael@0: // indentation element and false otherwise, and new parent instructions michael@0: // returning the result of calling createElement("blockquote") on the michael@0: // ownerDocument of first node. Let new parent be the result." michael@0: var newParent = wrap(nodeList, michael@0: function(node) { return isSimpleIndentationElement(node) }, michael@0: function() { return firstNode.ownerDocument.createElement("blockquote") }); michael@0: michael@0: // "Fix disallowed ancestors of new parent." michael@0: fixDisallowedAncestors(newParent); michael@0: } michael@0: michael@0: function outdentNode(node) { michael@0: // "If node is not editable, abort these steps." michael@0: if (!isEditable(node)) { michael@0: return; michael@0: } michael@0: michael@0: // "If node is a simple indentation element, remove node, preserving its michael@0: // descendants. Then abort these steps." michael@0: if (isSimpleIndentationElement(node)) { michael@0: removePreservingDescendants(node); michael@0: return; michael@0: } michael@0: michael@0: // "If node is an indentation element:" michael@0: if (isIndentationElement(node)) { michael@0: // "Unset the dir attribute of node, if any." michael@0: node.removeAttribute("dir"); michael@0: michael@0: // "Unset the margin, padding, and border CSS properties of node." michael@0: node.style.margin = ""; michael@0: node.style.padding = ""; michael@0: node.style.border = ""; michael@0: if (node.getAttribute("style") == "" michael@0: // Crazy WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=68551 michael@0: || node.getAttribute("style") == "border-width: initial; border-color: initial; ") { michael@0: node.removeAttribute("style"); michael@0: } michael@0: michael@0: // "Set the tag name of node to "div"." michael@0: setTagName(node, "div"); michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "Let current ancestor be node's parent." michael@0: var currentAncestor = node.parentNode; michael@0: michael@0: // "Let ancestor list be a list of nodes, initially empty." michael@0: var ancestorList = []; michael@0: michael@0: // "While current ancestor is an editable Element that is neither a simple michael@0: // indentation element nor an ol nor a ul, append current ancestor to michael@0: // ancestor list and then set current ancestor to its parent." michael@0: while (isEditable(currentAncestor) michael@0: && currentAncestor.nodeType == Node.ELEMENT_NODE michael@0: && !isSimpleIndentationElement(currentAncestor) michael@0: && !isHtmlElement(currentAncestor, ["ol", "ul"])) { michael@0: ancestorList.push(currentAncestor); michael@0: currentAncestor = currentAncestor.parentNode; michael@0: } michael@0: michael@0: // "If current ancestor is not an editable simple indentation element:" michael@0: if (!isEditable(currentAncestor) michael@0: || !isSimpleIndentationElement(currentAncestor)) { michael@0: // "Let current ancestor be node's parent." michael@0: currentAncestor = node.parentNode; michael@0: michael@0: // "Let ancestor list be the empty list." michael@0: ancestorList = []; michael@0: michael@0: // "While current ancestor is an editable Element that is neither an michael@0: // indentation element nor an ol nor a ul, append current ancestor to michael@0: // ancestor list and then set current ancestor to its parent." michael@0: while (isEditable(currentAncestor) michael@0: && currentAncestor.nodeType == Node.ELEMENT_NODE michael@0: && !isIndentationElement(currentAncestor) michael@0: && !isHtmlElement(currentAncestor, ["ol", "ul"])) { michael@0: ancestorList.push(currentAncestor); michael@0: currentAncestor = currentAncestor.parentNode; michael@0: } michael@0: } michael@0: michael@0: // "If node is an ol or ul and current ancestor is not an editable michael@0: // indentation element:" michael@0: if (isHtmlElement(node, ["OL", "UL"]) michael@0: && (!isEditable(currentAncestor) michael@0: || !isIndentationElement(currentAncestor))) { michael@0: // "Unset the reversed, start, and type attributes of node, if any are michael@0: // set." michael@0: node.removeAttribute("reversed"); michael@0: node.removeAttribute("start"); michael@0: node.removeAttribute("type"); michael@0: michael@0: // "Let children be the children of node." michael@0: var children = [].slice.call(node.childNodes); michael@0: michael@0: // "If node has attributes, and its parent is not an ol or ul, set the michael@0: // tag name of node to "div"." michael@0: if (node.attributes.length michael@0: && !isHtmlElement(node.parentNode, ["OL", "UL"])) { michael@0: setTagName(node, "div"); michael@0: michael@0: // "Otherwise:" michael@0: } else { michael@0: // "Record the values of node's children, and let values be the michael@0: // result." michael@0: var values = recordValues([].slice.call(node.childNodes)); michael@0: michael@0: // "Remove node, preserving its descendants." michael@0: removePreservingDescendants(node); michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: } michael@0: michael@0: // "Fix disallowed ancestors of each member of children." michael@0: for (var i = 0; i < children.length; i++) { michael@0: fixDisallowedAncestors(children[i]); michael@0: } michael@0: michael@0: // "Abort these steps." michael@0: return; michael@0: } michael@0: michael@0: // "If current ancestor is not an editable indentation element, abort these michael@0: // steps." michael@0: if (!isEditable(currentAncestor) michael@0: || !isIndentationElement(currentAncestor)) { michael@0: return; michael@0: } michael@0: michael@0: // "Append current ancestor to ancestor list." michael@0: ancestorList.push(currentAncestor); michael@0: michael@0: // "Let original ancestor be current ancestor." michael@0: var originalAncestor = currentAncestor; michael@0: michael@0: // "While ancestor list is not empty:" michael@0: while (ancestorList.length) { michael@0: // "Let current ancestor be the last member of ancestor list." michael@0: // michael@0: // "Remove the last member of ancestor list." michael@0: currentAncestor = ancestorList.pop(); michael@0: michael@0: // "Let target be the child of current ancestor that is equal to either michael@0: // node or the last member of ancestor list." michael@0: var target = node.parentNode == currentAncestor michael@0: ? node michael@0: : ancestorList[ancestorList.length - 1]; michael@0: michael@0: // "If target is an inline node that is not a br, and its nextSibling michael@0: // is a br, remove target's nextSibling from its parent." michael@0: if (isInlineNode(target) michael@0: && !isHtmlElement(target, "BR") michael@0: && isHtmlElement(target.nextSibling, "BR")) { michael@0: target.parentNode.removeChild(target.nextSibling); michael@0: } michael@0: michael@0: // "Let preceding siblings be the preceding siblings of target, and let michael@0: // following siblings be the following siblings of target." michael@0: var precedingSiblings = [].slice.call(currentAncestor.childNodes, 0, getNodeIndex(target)); michael@0: var followingSiblings = [].slice.call(currentAncestor.childNodes, 1 + getNodeIndex(target)); michael@0: michael@0: // "Indent preceding siblings." michael@0: indentNodes(precedingSiblings); michael@0: michael@0: // "Indent following siblings." michael@0: indentNodes(followingSiblings); michael@0: } michael@0: michael@0: // "Outdent original ancestor." michael@0: outdentNode(originalAncestor); michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Toggling lists ///// michael@0: //@{ michael@0: michael@0: function toggleLists(tagName) { michael@0: // "Let mode be "disable" if the selection's list state is tag name, and michael@0: // "enable" otherwise." michael@0: var mode = getSelectionListState() == tagName ? "disable" : "enable"; michael@0: michael@0: var range = getActiveRange(); michael@0: tagName = tagName.toUpperCase(); michael@0: michael@0: // "Let other tag name be "ol" if tag name is "ul", and "ul" if tag name is michael@0: // "ol"." michael@0: var otherTagName = tagName == "OL" ? "UL" : "OL"; michael@0: michael@0: // "Let items be a list of all lis that are ancestor containers of the michael@0: // range's start and/or end node." michael@0: // michael@0: // It's annoying to get this in tree order using functional stuff without michael@0: // doing getDescendants(document), which is slow, so I do it imperatively. michael@0: var items = []; michael@0: (function(){ michael@0: for ( michael@0: var ancestorContainer = range.endContainer; michael@0: ancestorContainer != range.commonAncestorContainer; michael@0: ancestorContainer = ancestorContainer.parentNode michael@0: ) { michael@0: if (isHtmlElement(ancestorContainer, "li")) { michael@0: items.unshift(ancestorContainer); michael@0: } michael@0: } michael@0: for ( michael@0: var ancestorContainer = range.startContainer; michael@0: ancestorContainer; michael@0: ancestorContainer = ancestorContainer.parentNode michael@0: ) { michael@0: if (isHtmlElement(ancestorContainer, "li")) { michael@0: items.unshift(ancestorContainer); michael@0: } michael@0: } michael@0: })(); michael@0: michael@0: // "For each item in items, normalize sublists of item." michael@0: items.forEach(normalizeSublists); michael@0: michael@0: // "Block-extend the range, and let new range be the result." michael@0: var newRange = blockExtend(range); michael@0: michael@0: // "If mode is "enable", then let lists to convert consist of every michael@0: // editable HTML element with local name other tag name that is contained michael@0: // in new range, and for every list in lists to convert:" michael@0: if (mode == "enable") { michael@0: getAllContainedNodes(newRange, function(node) { michael@0: return isEditable(node) michael@0: && isHtmlElement(node, otherTagName); michael@0: }).forEach(function(list) { michael@0: // "If list's previousSibling or nextSibling is an editable HTML michael@0: // element with local name tag name:" michael@0: if ((isEditable(list.previousSibling) && isHtmlElement(list.previousSibling, tagName)) michael@0: || (isEditable(list.nextSibling) && isHtmlElement(list.nextSibling, tagName))) { michael@0: // "Let children be list's children." michael@0: var children = [].slice.call(list.childNodes); michael@0: michael@0: // "Record the values of children, and let values be the michael@0: // result." michael@0: var values = recordValues(children); michael@0: michael@0: // "Split the parent of children." michael@0: splitParent(children); michael@0: michael@0: // "Wrap children, with sibling criteria returning true for an michael@0: // HTML element with local name tag name and false otherwise." michael@0: wrap(children, function(node) { return isHtmlElement(node, tagName) }); michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: michael@0: // "Otherwise, set the tag name of list to tag name." michael@0: } else { michael@0: setTagName(list, tagName); michael@0: } michael@0: }); michael@0: } michael@0: michael@0: // "Let node list be a list of nodes, initially empty." michael@0: // michael@0: // "For each node node contained in new range, if node is editable; the michael@0: // last member of node list (if any) is not an ancestor of node; node michael@0: // is not an indentation element; and either node is an ol or ul, or its michael@0: // parent is an ol or ul, or it is an allowed child of "li"; then append michael@0: // node to node list." michael@0: var nodeList = getContainedNodes(newRange, function(node) { michael@0: return isEditable(node) michael@0: && !isIndentationElement(node) michael@0: && (isHtmlElement(node, ["OL", "UL"]) michael@0: || isHtmlElement(node.parentNode, ["OL", "UL"]) michael@0: || isAllowedChild(node, "li")); michael@0: }); michael@0: michael@0: // "If mode is "enable", remove from node list any ol or ul whose parent is michael@0: // not also an ol or ul." michael@0: if (mode == "enable") { michael@0: nodeList = nodeList.filter(function(node) { michael@0: return !isHtmlElement(node, ["ol", "ul"]) michael@0: || isHtmlElement(node.parentNode, ["ol", "ul"]); michael@0: }); michael@0: } michael@0: michael@0: // "If mode is "disable", then while node list is not empty:" michael@0: if (mode == "disable") { michael@0: while (nodeList.length) { michael@0: // "Let sublist be an empty list of nodes." michael@0: var sublist = []; michael@0: michael@0: // "Remove the first member from node list and append it to michael@0: // sublist." michael@0: sublist.push(nodeList.shift()); michael@0: michael@0: // "If the first member of sublist is an HTML element with local michael@0: // name tag name, outdent it and continue this loop from the michael@0: // beginning." michael@0: if (isHtmlElement(sublist[0], tagName)) { michael@0: outdentNode(sublist[0]); michael@0: continue; michael@0: } michael@0: michael@0: // "While node list is not empty, and the first member of node list michael@0: // is the nextSibling of the last member of sublist and is not an michael@0: // HTML element with local name tag name, remove the first member michael@0: // from node list and append it to sublist." michael@0: while (nodeList.length michael@0: && nodeList[0] == sublist[sublist.length - 1].nextSibling michael@0: && !isHtmlElement(nodeList[0], tagName)) { michael@0: sublist.push(nodeList.shift()); michael@0: } michael@0: michael@0: // "Record the values of sublist, and let values be the result." michael@0: var values = recordValues(sublist); michael@0: michael@0: // "Split the parent of sublist." michael@0: splitParent(sublist); michael@0: michael@0: // "Fix disallowed ancestors of each member of sublist." michael@0: for (var i = 0; i < sublist.length; i++) { michael@0: fixDisallowedAncestors(sublist[i]); michael@0: } michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: } michael@0: michael@0: // "Otherwise, while node list is not empty:" michael@0: } else { michael@0: while (nodeList.length) { michael@0: // "Let sublist be an empty list of nodes." michael@0: var sublist = []; michael@0: michael@0: // "While either sublist is empty, or node list is not empty and michael@0: // its first member is the nextSibling of sublist's last member:" michael@0: while (!sublist.length michael@0: || (nodeList.length michael@0: && nodeList[0] == sublist[sublist.length - 1].nextSibling)) { michael@0: // "If node list's first member is a p or div, set the tag name michael@0: // of node list's first member to "li", and append the result michael@0: // to sublist. Remove the first member from node list." michael@0: if (isHtmlElement(nodeList[0], ["p", "div"])) { michael@0: sublist.push(setTagName(nodeList[0], "li")); michael@0: nodeList.shift(); michael@0: michael@0: // "Otherwise, if the first member of node list is an li or ol michael@0: // or ul, remove it from node list and append it to sublist." michael@0: } else if (isHtmlElement(nodeList[0], ["li", "ol", "ul"])) { michael@0: sublist.push(nodeList.shift()); michael@0: michael@0: // "Otherwise:" michael@0: } else { michael@0: // "Let nodes to wrap be a list of nodes, initially empty." michael@0: var nodesToWrap = []; michael@0: michael@0: // "While nodes to wrap is empty, or node list is not empty michael@0: // and its first member is the nextSibling of nodes to michael@0: // wrap's last member and the first member of node list is michael@0: // an inline node and the last member of nodes to wrap is michael@0: // an inline node other than a br, remove the first member michael@0: // from node list and append it to nodes to wrap." michael@0: while (!nodesToWrap.length michael@0: || (nodeList.length michael@0: && nodeList[0] == nodesToWrap[nodesToWrap.length - 1].nextSibling michael@0: && isInlineNode(nodeList[0]) michael@0: && isInlineNode(nodesToWrap[nodesToWrap.length - 1]) michael@0: && !isHtmlElement(nodesToWrap[nodesToWrap.length - 1], "br"))) { michael@0: nodesToWrap.push(nodeList.shift()); michael@0: } michael@0: michael@0: // "Wrap nodes to wrap, with new parent instructions michael@0: // returning the result of calling createElement("li") on michael@0: // the context object. Append the result to sublist." michael@0: sublist.push(wrap(nodesToWrap, michael@0: undefined, michael@0: function() { return document.createElement("li") })); michael@0: } michael@0: } michael@0: michael@0: // "If sublist's first member's parent is an HTML element with michael@0: // local name tag name, or if every member of sublist is an ol or michael@0: // ul, continue this loop from the beginning." michael@0: if (isHtmlElement(sublist[0].parentNode, tagName) michael@0: || sublist.every(function(node) { return isHtmlElement(node, ["ol", "ul"]) })) { michael@0: continue; michael@0: } michael@0: michael@0: // "If sublist's first member's parent is an HTML element with michael@0: // local name other tag name:" michael@0: if (isHtmlElement(sublist[0].parentNode, otherTagName)) { michael@0: // "Record the values of sublist, and let values be the michael@0: // result." michael@0: var values = recordValues(sublist); michael@0: michael@0: // "Split the parent of sublist." michael@0: splitParent(sublist); michael@0: michael@0: // "Wrap sublist, with sibling criteria returning true for an michael@0: // HTML element with local name tag name and false otherwise, michael@0: // and new parent instructions returning the result of calling michael@0: // createElement(tag name) on the context object." michael@0: wrap(sublist, michael@0: function(node) { return isHtmlElement(node, tagName) }, michael@0: function() { return document.createElement(tagName) }); michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: michael@0: // "Continue this loop from the beginning." michael@0: continue; michael@0: } michael@0: michael@0: // "Wrap sublist, with sibling criteria returning true for an HTML michael@0: // element with local name tag name and false otherwise, and new michael@0: // parent instructions being the following:" michael@0: // . . . michael@0: // "Fix disallowed ancestors of the previous step's result." michael@0: fixDisallowedAncestors(wrap(sublist, michael@0: function(node) { return isHtmlElement(node, tagName) }, michael@0: function() { michael@0: // "If sublist's first member's parent is not an editable michael@0: // simple indentation element, or sublist's first member's michael@0: // parent's previousSibling is not an editable HTML element michael@0: // with local name tag name, call createElement(tag name) michael@0: // on the context object and return the result." michael@0: if (!isEditable(sublist[0].parentNode) michael@0: || !isSimpleIndentationElement(sublist[0].parentNode) michael@0: || !isEditable(sublist[0].parentNode.previousSibling) michael@0: || !isHtmlElement(sublist[0].parentNode.previousSibling, tagName)) { michael@0: return document.createElement(tagName); michael@0: } michael@0: michael@0: // "Let list be sublist's first member's parent's michael@0: // previousSibling." michael@0: var list = sublist[0].parentNode.previousSibling; michael@0: michael@0: // "Normalize sublists of list's lastChild." michael@0: normalizeSublists(list.lastChild); michael@0: michael@0: // "If list's lastChild is not an editable HTML element michael@0: // with local name tag name, call createElement(tag name) michael@0: // on the context object, and append the result as the last michael@0: // child of list." michael@0: if (!isEditable(list.lastChild) michael@0: || !isHtmlElement(list.lastChild, tagName)) { michael@0: list.appendChild(document.createElement(tagName)); michael@0: } michael@0: michael@0: // "Return the last child of list." michael@0: return list.lastChild; michael@0: } michael@0: )); michael@0: } michael@0: } michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Justifying the selection ///// michael@0: //@{ michael@0: michael@0: function justifySelection(alignment) { michael@0: // "Block-extend the active range, and let new range be the result." michael@0: var newRange = blockExtend(globalRange); michael@0: michael@0: // "Let element list be a list of all editable Elements contained in new michael@0: // range that either has an attribute in the HTML namespace whose local michael@0: // name is "align", or has a style attribute that sets "text-align", or is michael@0: // a center." michael@0: var elementList = getAllContainedNodes(newRange, function(node) { michael@0: return node.nodeType == Node.ELEMENT_NODE michael@0: && isEditable(node) michael@0: // Ignoring namespaces here michael@0: && ( michael@0: node.hasAttribute("align") michael@0: || node.style.textAlign != "" michael@0: || isHtmlElement(node, "center") michael@0: ); michael@0: }); michael@0: michael@0: // "For each element in element list:" michael@0: for (var i = 0; i < elementList.length; i++) { michael@0: var element = elementList[i]; michael@0: michael@0: // "If element has an attribute in the HTML namespace whose local name michael@0: // is "align", remove that attribute." michael@0: element.removeAttribute("align"); michael@0: michael@0: // "Unset the CSS property "text-align" on element, if it's set by a michael@0: // style attribute." michael@0: element.style.textAlign = ""; michael@0: if (element.getAttribute("style") == "") { michael@0: element.removeAttribute("style"); michael@0: } michael@0: michael@0: // "If element is a div or span or center with no attributes, remove michael@0: // it, preserving its descendants." michael@0: if (isHtmlElement(element, ["div", "span", "center"]) michael@0: && !element.attributes.length) { michael@0: removePreservingDescendants(element); michael@0: } michael@0: michael@0: // "If element is a center with one or more attributes, set the tag michael@0: // name of element to "div"." michael@0: if (isHtmlElement(element, "center") michael@0: && element.attributes.length) { michael@0: setTagName(element, "div"); michael@0: } michael@0: } michael@0: michael@0: // "Block-extend the active range, and let new range be the result." michael@0: newRange = blockExtend(globalRange); michael@0: michael@0: // "Let node list be a list of nodes, initially empty." michael@0: var nodeList = []; michael@0: michael@0: // "For each node node contained in new range, append node to node list if michael@0: // the last member of node list (if any) is not an ancestor of node; node michael@0: // is editable; node is an allowed child of "div"; and node's alignment michael@0: // value is not alignment." michael@0: nodeList = getContainedNodes(newRange, function(node) { michael@0: return isEditable(node) michael@0: && isAllowedChild(node, "div") michael@0: && getAlignmentValue(node) != alignment; michael@0: }); michael@0: michael@0: // "While node list is not empty:" michael@0: while (nodeList.length) { michael@0: // "Let sublist be a list of nodes, initially empty." michael@0: var sublist = []; michael@0: michael@0: // "Remove the first member of node list and append it to sublist." michael@0: sublist.push(nodeList.shift()); michael@0: michael@0: // "While node list is not empty, and the first member of node list is michael@0: // the nextSibling of the last member of sublist, remove the first michael@0: // member of node list and append it to sublist." michael@0: while (nodeList.length michael@0: && nodeList[0] == sublist[sublist.length - 1].nextSibling) { michael@0: sublist.push(nodeList.shift()); michael@0: } michael@0: michael@0: // "Wrap sublist. Sibling criteria returns true for any div that has michael@0: // one or both of the following two attributes and no other attributes, michael@0: // and false otherwise:" michael@0: // michael@0: // * "An align attribute whose value is an ASCII case-insensitive michael@0: // match for alignment. michael@0: // * "A style attribute which sets exactly one CSS property michael@0: // (including unrecognized or invalid attributes), which is michael@0: // "text-align", which is set to alignment. michael@0: // michael@0: // "New parent instructions are to call createElement("div") on the michael@0: // context object, then set its CSS property "text-align" to alignment michael@0: // and return the result." michael@0: wrap(sublist, michael@0: function(node) { michael@0: return isHtmlElement(node, "div") michael@0: && [].every.call(node.attributes, function(attr) { michael@0: return (attr.name == "align" && attr.value.toLowerCase() == alignment) michael@0: || (attr.name == "style" && node.style.length == 1 && node.style.textAlign == alignment); michael@0: }); michael@0: }, michael@0: function() { michael@0: var newParent = document.createElement("div"); michael@0: newParent.setAttribute("style", "text-align: " + alignment); michael@0: return newParent; michael@0: } michael@0: ); michael@0: } michael@0: } michael@0: michael@0: michael@0: //@} michael@0: ///// Automatic linking ///// michael@0: //@{ michael@0: // "An autolinkable URL is a string of the following form:" michael@0: var autolinkableUrlRegexp = michael@0: // "Either a string matching the scheme pattern from RFC 3986 section 3.1 michael@0: // followed by the literal string ://, or the literal string mailto:; michael@0: // followed by" michael@0: // michael@0: // From the RFC: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) michael@0: "([a-zA-Z][a-zA-Z0-9+.-]*://|mailto:)" michael@0: // "Zero or more characters other than space characters; followed by" michael@0: + "[^ \t\n\f\r]*" michael@0: // "A character that is not one of the ASCII characters !"'(),-.:;<>[]`{}." michael@0: + "[^!\"'(),\\-.:;<>[\\]`{}]"; michael@0: michael@0: // "A valid e-mail address is a string that matches the ABNF production 1*( michael@0: // atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined in RFC michael@0: // 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section 3.5." michael@0: // michael@0: // atext: ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / michael@0: // "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" michael@0: // michael@0: // ::= | michael@0: // ::= | "-" michael@0: // ::= | michael@0: var validEmailRegexp = michael@0: "[a-zA-Z0-9!#$%&'*+\\-/=?^_`{|}~.]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*"; michael@0: michael@0: function autolink(node, endOffset) { michael@0: // "While (node, end offset)'s previous equivalent point is not null, set michael@0: // it to its previous equivalent point." michael@0: while (getPreviousEquivalentPoint(node, endOffset)) { michael@0: var prev = getPreviousEquivalentPoint(node, endOffset); michael@0: node = prev[0]; michael@0: endOffset = prev[1]; michael@0: } michael@0: michael@0: // "If node is not a Text node, or has an a ancestor, do nothing and abort michael@0: // these steps." michael@0: if (node.nodeType != Node.TEXT_NODE michael@0: || getAncestors(node).some(function(ancestor) { return isHtmlElement(ancestor, "a") })) { michael@0: return; michael@0: } michael@0: michael@0: // "Let search be the largest substring of node's data whose end is end michael@0: // offset and that contains no space characters." michael@0: var search = /[^ \t\n\f\r]*$/.exec(node.substringData(0, endOffset))[0]; michael@0: michael@0: // "If some substring of search is an autolinkable URL:" michael@0: if (new RegExp(autolinkableUrlRegexp).test(search)) { michael@0: // "While there is no substring of node's data ending at end offset michael@0: // that is an autolinkable URL, decrement end offset." michael@0: while (!(new RegExp(autolinkableUrlRegexp + "$").test(node.substringData(0, endOffset)))) { michael@0: endOffset--; michael@0: } michael@0: michael@0: // "Let start offset be the start index of the longest substring of michael@0: // node's data that is an autolinkable URL ending at end offset." michael@0: var startOffset = new RegExp(autolinkableUrlRegexp + "$").exec(node.substringData(0, endOffset)).index; michael@0: michael@0: // "Let href be the substring of node's data starting at start offset michael@0: // and ending at end offset." michael@0: var href = node.substringData(startOffset, endOffset - startOffset); michael@0: michael@0: // "Otherwise, if some substring of search is a valid e-mail address:" michael@0: } else if (new RegExp(validEmailRegexp).test(search)) { michael@0: // "While there is no substring of node's data ending at end offset michael@0: // that is a valid e-mail address, decrement end offset." michael@0: while (!(new RegExp(validEmailRegexp + "$").test(node.substringData(0, endOffset)))) { michael@0: endOffset--; michael@0: } michael@0: michael@0: // "Let start offset be the start index of the longest substring of michael@0: // node's data that is a valid e-mail address ending at end offset." michael@0: var startOffset = new RegExp(validEmailRegexp + "$").exec(node.substringData(0, endOffset)).index; michael@0: michael@0: // "Let href be "mailto:" concatenated with the substring of node's michael@0: // data starting at start offset and ending at end offset." michael@0: var href = "mailto:" + node.substringData(startOffset, endOffset - startOffset); michael@0: michael@0: // "Otherwise, do nothing and abort these steps." michael@0: } else { michael@0: return; michael@0: } michael@0: michael@0: // "Let original range be the active range." michael@0: var originalRange = getActiveRange(); michael@0: michael@0: // "Create a new range with start (node, start offset) and end (node, end michael@0: // offset), and set the context object's selection's range to it." michael@0: var newRange = document.createRange(); michael@0: newRange.setStart(node, startOffset); michael@0: newRange.setEnd(node, endOffset); michael@0: getSelection().removeAllRanges(); michael@0: getSelection().addRange(newRange); michael@0: globalRange = newRange; michael@0: michael@0: // "Take the action for "createLink", with value equal to href." michael@0: commands.createlink.action(href); michael@0: michael@0: // "Set the context object's selection's range to original range." michael@0: getSelection().removeAllRanges(); michael@0: getSelection().addRange(originalRange); michael@0: globalRange = originalRange; michael@0: } michael@0: //@} michael@0: ///// The delete command ///// michael@0: //@{ michael@0: commands["delete"] = { michael@0: preservesOverrides: true, michael@0: action: function() { michael@0: // "If the active range is not collapsed, delete the selection and michael@0: // return true." michael@0: if (!getActiveRange().collapsed) { michael@0: deleteSelection(); michael@0: return true; michael@0: } michael@0: michael@0: // "Canonicalize whitespace at the active range's start." michael@0: canonicalizeWhitespace(getActiveRange().startContainer, getActiveRange().startOffset); michael@0: michael@0: // "Let node and offset be the active range's start node and offset." michael@0: var node = getActiveRange().startContainer; michael@0: var offset = getActiveRange().startOffset; michael@0: michael@0: // "Repeat the following steps:" michael@0: while (true) { michael@0: // "If offset is zero and node's previousSibling is an editable michael@0: // invisible node, remove node's previousSibling from its parent." michael@0: if (offset == 0 michael@0: && isEditable(node.previousSibling) michael@0: && isInvisible(node.previousSibling)) { michael@0: node.parentNode.removeChild(node.previousSibling); michael@0: michael@0: // "Otherwise, if node has a child with index offset − 1 and that michael@0: // child is an editable invisible node, remove that child from michael@0: // node, then subtract one from offset." michael@0: } else if (0 <= offset - 1 michael@0: && offset - 1 < node.childNodes.length michael@0: && isEditable(node.childNodes[offset - 1]) michael@0: && isInvisible(node.childNodes[offset - 1])) { michael@0: node.removeChild(node.childNodes[offset - 1]); michael@0: offset--; michael@0: michael@0: // "Otherwise, if offset is zero and node is an inline node, or if michael@0: // node is an invisible node, set offset to the index of node, then michael@0: // set node to its parent." michael@0: } else if ((offset == 0 michael@0: && isInlineNode(node)) michael@0: || isInvisible(node)) { michael@0: offset = getNodeIndex(node); michael@0: node = node.parentNode; michael@0: michael@0: // "Otherwise, if node has a child with index offset − 1 and that michael@0: // child is an editable a, remove that child from node, preserving michael@0: // its descendants. Then return true." michael@0: } else if (0 <= offset - 1 michael@0: && offset - 1 < node.childNodes.length michael@0: && isEditable(node.childNodes[offset - 1]) michael@0: && isHtmlElement(node.childNodes[offset - 1], "a")) { michael@0: removePreservingDescendants(node.childNodes[offset - 1]); michael@0: return true; michael@0: michael@0: // "Otherwise, if node has a child with index offset − 1 and that michael@0: // child is not a block node or a br or an img, set node to that michael@0: // child, then set offset to the length of node." michael@0: } else if (0 <= offset - 1 michael@0: && offset - 1 < node.childNodes.length michael@0: && !isBlockNode(node.childNodes[offset - 1]) michael@0: && !isHtmlElement(node.childNodes[offset - 1], ["br", "img"])) { michael@0: node = node.childNodes[offset - 1]; michael@0: offset = getNodeLength(node); michael@0: michael@0: // "Otherwise, break from this loop." michael@0: } else { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // "If node is a Text node and offset is not zero, or if node is a michael@0: // block node that has a child with index offset − 1 and that child is michael@0: // a br or hr or img:" michael@0: if ((node.nodeType == Node.TEXT_NODE michael@0: && offset != 0) michael@0: || (isBlockNode(node) michael@0: && 0 <= offset - 1 michael@0: && offset - 1 < node.childNodes.length michael@0: && isHtmlElement(node.childNodes[offset - 1], ["br", "hr", "img"]))) { michael@0: // "Call collapse(node, offset) on the context object's Selection." michael@0: getSelection().collapse(node, offset); michael@0: getActiveRange().setEnd(node, offset); michael@0: michael@0: // "Call extend(node, offset − 1) on the context object's michael@0: // Selection." michael@0: getSelection().extend(node, offset - 1); michael@0: getActiveRange().setStart(node, offset - 1); michael@0: michael@0: // "Delete the selection." michael@0: deleteSelection(); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "If node is an inline node, return true." michael@0: if (isInlineNode(node)) { michael@0: return true; michael@0: } michael@0: michael@0: // "If node is an li or dt or dd and is the first child of its parent, michael@0: // and offset is zero:" michael@0: if (isHtmlElement(node, ["li", "dt", "dd"]) michael@0: && node == node.parentNode.firstChild michael@0: && offset == 0) { michael@0: // "Let items be a list of all lis that are ancestors of node." michael@0: // michael@0: // Remember, must be in tree order. michael@0: var items = []; michael@0: for (var ancestor = node.parentNode; ancestor; ancestor = ancestor.parentNode) { michael@0: if (isHtmlElement(ancestor, "li")) { michael@0: items.unshift(ancestor); michael@0: } michael@0: } michael@0: michael@0: // "Normalize sublists of each item in items." michael@0: for (var i = 0; i < items.length; i++) { michael@0: normalizeSublists(items[i]); michael@0: } michael@0: michael@0: // "Record the values of the one-node list consisting of node, and michael@0: // let values be the result." michael@0: var values = recordValues([node]); michael@0: michael@0: // "Split the parent of the one-node list consisting of node." michael@0: splitParent([node]); michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: michael@0: // "If node is a dd or dt, and it is not an allowed child of any of michael@0: // its ancestors in the same editing host, set the tag name of node michael@0: // to the default single-line container name and let node be the michael@0: // result." michael@0: if (isHtmlElement(node, ["dd", "dt"]) michael@0: && getAncestors(node).every(function(ancestor) { michael@0: return !inSameEditingHost(node, ancestor) michael@0: || !isAllowedChild(node, ancestor) michael@0: })) { michael@0: node = setTagName(node, defaultSingleLineContainerName); michael@0: } michael@0: michael@0: // "Fix disallowed ancestors of node." michael@0: fixDisallowedAncestors(node); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "Let start node equal node and let start offset equal offset." michael@0: var startNode = node; michael@0: var startOffset = offset; michael@0: michael@0: // "Repeat the following steps:" michael@0: while (true) { michael@0: // "If start offset is zero, set start offset to the index of start michael@0: // node and then set start node to its parent." michael@0: if (startOffset == 0) { michael@0: startOffset = getNodeIndex(startNode); michael@0: startNode = startNode.parentNode; michael@0: michael@0: // "Otherwise, if start node has an editable invisible child with michael@0: // index start offset minus one, remove it from start node and michael@0: // subtract one from start offset." michael@0: } else if (0 <= startOffset - 1 michael@0: && startOffset - 1 < startNode.childNodes.length michael@0: && isEditable(startNode.childNodes[startOffset - 1]) michael@0: && isInvisible(startNode.childNodes[startOffset - 1])) { michael@0: startNode.removeChild(startNode.childNodes[startOffset - 1]); michael@0: startOffset--; michael@0: michael@0: // "Otherwise, break from this loop." michael@0: } else { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // "If offset is zero, and node has an editable ancestor container in michael@0: // the same editing host that's an indentation element:" michael@0: if (offset == 0 michael@0: && getAncestors(node).concat(node).filter(function(ancestor) { michael@0: return isEditable(ancestor) michael@0: && inSameEditingHost(ancestor, node) michael@0: && isIndentationElement(ancestor); michael@0: }).length) { michael@0: // "Block-extend the range whose start and end are both (node, 0), michael@0: // and let new range be the result." michael@0: var newRange = document.createRange(); michael@0: newRange.setStart(node, 0); michael@0: newRange = blockExtend(newRange); michael@0: michael@0: // "Let node list be a list of nodes, initially empty." michael@0: // michael@0: // "For each node current node contained in new range, append michael@0: // current node to node list if the last member of node list (if michael@0: // any) is not an ancestor of current node, and current node is michael@0: // editable but has no editable descendants." michael@0: var nodeList = getContainedNodes(newRange, function(currentNode) { michael@0: return isEditable(currentNode) michael@0: && !hasEditableDescendants(currentNode); michael@0: }); michael@0: michael@0: // "Outdent each node in node list." michael@0: for (var i = 0; i < nodeList.length; i++) { michael@0: outdentNode(nodeList[i]); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "If the child of start node with index start offset is a table, michael@0: // return true." michael@0: if (isHtmlElement(startNode.childNodes[startOffset], "table")) { michael@0: return true; michael@0: } michael@0: michael@0: // "If start node has a child with index start offset − 1, and that michael@0: // child is a table:" michael@0: if (0 <= startOffset - 1 michael@0: && startOffset - 1 < startNode.childNodes.length michael@0: && isHtmlElement(startNode.childNodes[startOffset - 1], "table")) { michael@0: // "Call collapse(start node, start offset − 1) on the context michael@0: // object's Selection." michael@0: getSelection().collapse(startNode, startOffset - 1); michael@0: getActiveRange().setStart(startNode, startOffset - 1); michael@0: michael@0: // "Call extend(start node, start offset) on the context object's michael@0: // Selection." michael@0: getSelection().extend(startNode, startOffset); michael@0: getActiveRange().setEnd(startNode, startOffset); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "If offset is zero; and either the child of start node with index michael@0: // start offset minus one is an hr, or the child is a br whose michael@0: // previousSibling is either a br or not an inline node:" michael@0: if (offset == 0 michael@0: && (isHtmlElement(startNode.childNodes[startOffset - 1], "hr") michael@0: || ( michael@0: isHtmlElement(startNode.childNodes[startOffset - 1], "br") michael@0: && ( michael@0: isHtmlElement(startNode.childNodes[startOffset - 1].previousSibling, "br") michael@0: || !isInlineNode(startNode.childNodes[startOffset - 1].previousSibling) michael@0: ) michael@0: ) michael@0: )) { michael@0: // "Call collapse(start node, start offset − 1) on the context michael@0: // object's Selection." michael@0: getSelection().collapse(startNode, startOffset - 1); michael@0: getActiveRange().setStart(startNode, startOffset - 1); michael@0: michael@0: // "Call extend(start node, start offset) on the context object's michael@0: // Selection." michael@0: getSelection().extend(startNode, startOffset); michael@0: getActiveRange().setEnd(startNode, startOffset); michael@0: michael@0: // "Delete the selection." michael@0: deleteSelection(); michael@0: michael@0: // "Call collapse(node, offset) on the Selection." michael@0: getSelection().collapse(node, offset); michael@0: getActiveRange().setStart(node, offset); michael@0: getActiveRange().collapse(true); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "If the child of start node with index start offset is an li or dt michael@0: // or dd, and that child's firstChild is an inline node, and start michael@0: // offset is not zero:" michael@0: if (isHtmlElement(startNode.childNodes[startOffset], ["li", "dt", "dd"]) michael@0: && isInlineNode(startNode.childNodes[startOffset].firstChild) michael@0: && startOffset != 0) { michael@0: // "Let previous item be the child of start node with index start michael@0: // offset minus one." michael@0: var previousItem = startNode.childNodes[startOffset - 1]; michael@0: michael@0: // "If previous item's lastChild is an inline node other than a br, michael@0: // call createElement("br") on the context object and append the michael@0: // result as the last child of previous item." michael@0: if (isInlineNode(previousItem.lastChild) michael@0: && !isHtmlElement(previousItem.lastChild, "br")) { michael@0: previousItem.appendChild(document.createElement("br")); michael@0: } michael@0: michael@0: // "If previous item's lastChild is an inline node, call michael@0: // createElement("br") on the context object and append the result michael@0: // as the last child of previous item." michael@0: if (isInlineNode(previousItem.lastChild)) { michael@0: previousItem.appendChild(document.createElement("br")); michael@0: } michael@0: } michael@0: michael@0: // "If start node's child with index start offset is an li or dt or dd, michael@0: // and that child's previousSibling is also an li or dt or dd:" michael@0: if (isHtmlElement(startNode.childNodes[startOffset], ["li", "dt", "dd"]) michael@0: && isHtmlElement(startNode.childNodes[startOffset].previousSibling, ["li", "dt", "dd"])) { michael@0: // "Call cloneRange() on the active range, and let original range michael@0: // be the result." michael@0: // michael@0: // We need to add it to extraRanges so it will actually get updated michael@0: // when moving preserving ranges. michael@0: var originalRange = getActiveRange().cloneRange(); michael@0: extraRanges.push(originalRange); michael@0: michael@0: // "Set start node to its child with index start offset − 1." michael@0: startNode = startNode.childNodes[startOffset - 1]; michael@0: michael@0: // "Set start offset to start node's length." michael@0: startOffset = getNodeLength(startNode); michael@0: michael@0: // "Set node to start node's nextSibling." michael@0: node = startNode.nextSibling; michael@0: michael@0: // "Call collapse(start node, start offset) on the context object's michael@0: // Selection." michael@0: getSelection().collapse(startNode, startOffset); michael@0: getActiveRange().setStart(startNode, startOffset); michael@0: michael@0: // "Call extend(node, 0) on the context object's Selection." michael@0: getSelection().extend(node, 0); michael@0: getActiveRange().setEnd(node, 0); michael@0: michael@0: // "Delete the selection." michael@0: deleteSelection(); michael@0: michael@0: // "Call removeAllRanges() on the context object's Selection." michael@0: getSelection().removeAllRanges(); michael@0: michael@0: // "Call addRange(original range) on the context object's michael@0: // Selection." michael@0: getSelection().addRange(originalRange); michael@0: getActiveRange().setStart(originalRange.startContainer, originalRange.startOffset); michael@0: getActiveRange().setEnd(originalRange.endContainer, originalRange.endOffset); michael@0: michael@0: // "Return true." michael@0: extraRanges.pop(); michael@0: return true; michael@0: } michael@0: michael@0: // "While start node has a child with index start offset minus one:" michael@0: while (0 <= startOffset - 1 michael@0: && startOffset - 1 < startNode.childNodes.length) { michael@0: // "If start node's child with index start offset minus one is michael@0: // editable and invisible, remove it from start node, then subtract michael@0: // one from start offset." michael@0: if (isEditable(startNode.childNodes[startOffset - 1]) michael@0: && isInvisible(startNode.childNodes[startOffset - 1])) { michael@0: startNode.removeChild(startNode.childNodes[startOffset - 1]); michael@0: startOffset--; michael@0: michael@0: // "Otherwise, set start node to its child with index start offset michael@0: // minus one, then set start offset to the length of start node." michael@0: } else { michael@0: startNode = startNode.childNodes[startOffset - 1]; michael@0: startOffset = getNodeLength(startNode); michael@0: } michael@0: } michael@0: michael@0: // "Call collapse(start node, start offset) on the context object's michael@0: // Selection." michael@0: getSelection().collapse(startNode, startOffset); michael@0: getActiveRange().setStart(startNode, startOffset); michael@0: michael@0: // "Call extend(node, offset) on the context object's Selection." michael@0: getSelection().extend(node, offset); michael@0: getActiveRange().setEnd(node, offset); michael@0: michael@0: // "Delete the selection, with direction "backward"." michael@0: deleteSelection({direction: "backward"}); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The formatBlock command ///// michael@0: //@{ michael@0: // "A formattable block name is "address", "dd", "div", "dt", "h1", "h2", "h3", michael@0: // "h4", "h5", "h6", "p", or "pre"." michael@0: var formattableBlockNames = ["address", "dd", "div", "dt", "h1", "h2", "h3", michael@0: "h4", "h5", "h6", "p", "pre"]; michael@0: michael@0: commands.formatblock = { michael@0: preservesOverrides: true, michael@0: action: function(value) { michael@0: // "If value begins with a "<" character and ends with a ">" character, michael@0: // remove the first and last characters from it." michael@0: if (/^<.*>$/.test(value)) { michael@0: value = value.slice(1, -1); michael@0: } michael@0: michael@0: // "Let value be converted to ASCII lowercase." michael@0: value = value.toLowerCase(); michael@0: michael@0: // "If value is not a formattable block name, return false." michael@0: if (formattableBlockNames.indexOf(value) == -1) { michael@0: return false; michael@0: } michael@0: michael@0: // "Block-extend the active range, and let new range be the result." michael@0: var newRange = blockExtend(getActiveRange()); michael@0: michael@0: // "Let node list be an empty list of nodes." michael@0: // michael@0: // "For each node node contained in new range, append node to node list michael@0: // if it is editable, the last member of original node list (if any) is michael@0: // not an ancestor of node, node is either a non-list single-line michael@0: // container or an allowed child of "p" or a dd or dt, and node is not michael@0: // the ancestor of a prohibited paragraph child." michael@0: var nodeList = getContainedNodes(newRange, function(node) { michael@0: return isEditable(node) michael@0: && (isNonListSingleLineContainer(node) michael@0: || isAllowedChild(node, "p") michael@0: || isHtmlElement(node, ["dd", "dt"])) michael@0: && !getDescendants(node).some(isProhibitedParagraphChild); michael@0: }); michael@0: michael@0: // "Record the values of node list, and let values be the result." michael@0: var values = recordValues(nodeList); michael@0: michael@0: // "For each node in node list, while node is the descendant of an michael@0: // editable HTML element in the same editing host, whose local name is michael@0: // a formattable block name, and which is not the ancestor of a michael@0: // prohibited paragraph child, split the parent of the one-node list michael@0: // consisting of node." michael@0: for (var i = 0; i < nodeList.length; i++) { michael@0: var node = nodeList[i]; michael@0: while (getAncestors(node).some(function(ancestor) { michael@0: return isEditable(ancestor) michael@0: && inSameEditingHost(ancestor, node) michael@0: && isHtmlElement(ancestor, formattableBlockNames) michael@0: && !getDescendants(ancestor).some(isProhibitedParagraphChild); michael@0: })) { michael@0: splitParent([node]); michael@0: } michael@0: } michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: michael@0: // "While node list is not empty:" michael@0: while (nodeList.length) { michael@0: var sublist; michael@0: michael@0: // "If the first member of node list is a single-line michael@0: // container:" michael@0: if (isSingleLineContainer(nodeList[0])) { michael@0: // "Let sublist be the children of the first member of node michael@0: // list." michael@0: sublist = [].slice.call(nodeList[0].childNodes); michael@0: michael@0: // "Record the values of sublist, and let values be the michael@0: // result." michael@0: var values = recordValues(sublist); michael@0: michael@0: // "Remove the first member of node list from its parent, michael@0: // preserving its descendants." michael@0: removePreservingDescendants(nodeList[0]); michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: michael@0: // "Remove the first member from node list." michael@0: nodeList.shift(); michael@0: michael@0: // "Otherwise:" michael@0: } else { michael@0: // "Let sublist be an empty list of nodes." michael@0: sublist = []; michael@0: michael@0: // "Remove the first member of node list and append it to michael@0: // sublist." michael@0: sublist.push(nodeList.shift()); michael@0: michael@0: // "While node list is not empty, and the first member of michael@0: // node list is the nextSibling of the last member of michael@0: // sublist, and the first member of node list is not a michael@0: // single-line container, and the last member of sublist is michael@0: // not a br, remove the first member of node list and michael@0: // append it to sublist." michael@0: while (nodeList.length michael@0: && nodeList[0] == sublist[sublist.length - 1].nextSibling michael@0: && !isSingleLineContainer(nodeList[0]) michael@0: && !isHtmlElement(sublist[sublist.length - 1], "BR")) { michael@0: sublist.push(nodeList.shift()); michael@0: } michael@0: } michael@0: michael@0: // "Wrap sublist. If value is "div" or "p", sibling criteria michael@0: // returns false; otherwise it returns true for an HTML element michael@0: // with local name value and no attributes, and false otherwise. michael@0: // New parent instructions return the result of running michael@0: // createElement(value) on the context object. Then fix disallowed michael@0: // ancestors of the result." michael@0: fixDisallowedAncestors(wrap(sublist, michael@0: ["div", "p"].indexOf(value) == - 1 michael@0: ? function(node) { return isHtmlElement(node, value) && !node.attributes.length } michael@0: : function() { return false }, michael@0: function() { return document.createElement(value) })); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: }, indeterm: function() { michael@0: // "If the active range is null, return false." michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: michael@0: // "Block-extend the active range, and let new range be the result." michael@0: var newRange = blockExtend(getActiveRange()); michael@0: michael@0: // "Let node list be all visible editable nodes that are contained in michael@0: // new range and have no children." michael@0: var nodeList = getAllContainedNodes(newRange, function(node) { michael@0: return isVisible(node) michael@0: && isEditable(node) michael@0: && !node.hasChildNodes(); michael@0: }); michael@0: michael@0: // "If node list is empty, return false." michael@0: if (!nodeList.length) { michael@0: return false; michael@0: } michael@0: michael@0: // "Let type be null." michael@0: var type = null; michael@0: michael@0: // "For each node in node list:" michael@0: for (var i = 0; i < nodeList.length; i++) { michael@0: var node = nodeList[i]; michael@0: michael@0: // "While node's parent is editable and in the same editing host as michael@0: // node, and node is not an HTML element whose local name is a michael@0: // formattable block name, set node to its parent." michael@0: while (isEditable(node.parentNode) michael@0: && inSameEditingHost(node, node.parentNode) michael@0: && !isHtmlElement(node, formattableBlockNames)) { michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: // "Let current type be the empty string." michael@0: var currentType = ""; michael@0: michael@0: // "If node is an editable HTML element whose local name is a michael@0: // formattable block name, and node is not the ancestor of a michael@0: // prohibited paragraph child, set current type to node's local michael@0: // name." michael@0: if (isEditable(node) michael@0: && isHtmlElement(node, formattableBlockNames) michael@0: && !getDescendants(node).some(isProhibitedParagraphChild)) { michael@0: currentType = node.tagName; michael@0: } michael@0: michael@0: // "If type is null, set type to current type." michael@0: if (type === null) { michael@0: type = currentType; michael@0: michael@0: // "Otherwise, if type does not equal current type, return true." michael@0: } else if (type != currentType) { michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: // "Return false." michael@0: return false; michael@0: }, value: function() { michael@0: // "If the active range is null, return the empty string." michael@0: if (!getActiveRange()) { michael@0: return ""; michael@0: } michael@0: michael@0: // "Block-extend the active range, and let new range be the result." michael@0: var newRange = blockExtend(getActiveRange()); michael@0: michael@0: // "Let node be the first visible editable node that is contained in michael@0: // new range and has no children. If there is no such node, return the michael@0: // empty string." michael@0: var nodes = getAllContainedNodes(newRange, function(node) { michael@0: return isVisible(node) michael@0: && isEditable(node) michael@0: && !node.hasChildNodes(); michael@0: }); michael@0: if (!nodes.length) { michael@0: return ""; michael@0: } michael@0: var node = nodes[0]; michael@0: michael@0: // "While node's parent is editable and in the same editing host as michael@0: // node, and node is not an HTML element whose local name is a michael@0: // formattable block name, set node to its parent." michael@0: while (isEditable(node.parentNode) michael@0: && inSameEditingHost(node, node.parentNode) michael@0: && !isHtmlElement(node, formattableBlockNames)) { michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: // "If node is an editable HTML element whose local name is a michael@0: // formattable block name, and node is not the ancestor of a prohibited michael@0: // paragraph child, return node's local name, converted to ASCII michael@0: // lowercase." michael@0: if (isEditable(node) michael@0: && isHtmlElement(node, formattableBlockNames) michael@0: && !getDescendants(node).some(isProhibitedParagraphChild)) { michael@0: return node.tagName.toLowerCase(); michael@0: } michael@0: michael@0: // "Return the empty string." michael@0: return ""; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The forwardDelete command ///// michael@0: //@{ michael@0: commands.forwarddelete = { michael@0: preservesOverrides: true, michael@0: action: function() { michael@0: // "If the active range is not collapsed, delete the selection and michael@0: // return true." michael@0: if (!getActiveRange().collapsed) { michael@0: deleteSelection(); michael@0: return true; michael@0: } michael@0: michael@0: // "Canonicalize whitespace at the active range's start." michael@0: canonicalizeWhitespace(getActiveRange().startContainer, getActiveRange().startOffset); michael@0: michael@0: // "Let node and offset be the active range's start node and offset." michael@0: var node = getActiveRange().startContainer; michael@0: var offset = getActiveRange().startOffset; michael@0: michael@0: // "Repeat the following steps:" michael@0: while (true) { michael@0: // "If offset is the length of node and node's nextSibling is an michael@0: // editable invisible node, remove node's nextSibling from its michael@0: // parent." michael@0: if (offset == getNodeLength(node) michael@0: && isEditable(node.nextSibling) michael@0: && isInvisible(node.nextSibling)) { michael@0: node.parentNode.removeChild(node.nextSibling); michael@0: michael@0: // "Otherwise, if node has a child with index offset and that child michael@0: // is an editable invisible node, remove that child from node." michael@0: } else if (offset < node.childNodes.length michael@0: && isEditable(node.childNodes[offset]) michael@0: && isInvisible(node.childNodes[offset])) { michael@0: node.removeChild(node.childNodes[offset]); michael@0: michael@0: // "Otherwise, if offset is the length of node and node is an michael@0: // inline node, or if node is invisible, set offset to one plus the michael@0: // index of node, then set node to its parent." michael@0: } else if ((offset == getNodeLength(node) michael@0: && isInlineNode(node)) michael@0: || isInvisible(node)) { michael@0: offset = 1 + getNodeIndex(node); michael@0: node = node.parentNode; michael@0: michael@0: // "Otherwise, if node has a child with index offset and that child michael@0: // is neither a block node nor a br nor an img nor a collapsed michael@0: // block prop, set node to that child, then set offset to zero." michael@0: } else if (offset < node.childNodes.length michael@0: && !isBlockNode(node.childNodes[offset]) michael@0: && !isHtmlElement(node.childNodes[offset], ["br", "img"]) michael@0: && !isCollapsedBlockProp(node.childNodes[offset])) { michael@0: node = node.childNodes[offset]; michael@0: offset = 0; michael@0: michael@0: // "Otherwise, break from this loop." michael@0: } else { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // "If node is a Text node and offset is not node's length:" michael@0: if (node.nodeType == Node.TEXT_NODE michael@0: && offset != getNodeLength(node)) { michael@0: // "Let end offset be offset plus one." michael@0: var endOffset = offset + 1; michael@0: michael@0: // "While end offset is not node's length and the end offsetth michael@0: // element of node's data has general category M when interpreted michael@0: // as a Unicode code point, add one to end offset." michael@0: // michael@0: // TODO: Not even going to try handling anything beyond the most michael@0: // basic combining marks, since I couldn't find a good list. I michael@0: // special-case a few Hebrew diacritics too to test basic coverage michael@0: // of non-Latin stuff. michael@0: while (endOffset != node.length michael@0: && /^[\u0300-\u036f\u0591-\u05bd\u05c1\u05c2]$/.test(node.data[endOffset])) { michael@0: endOffset++; michael@0: } michael@0: michael@0: // "Call collapse(node, offset) on the context object's Selection." michael@0: getSelection().collapse(node, offset); michael@0: getActiveRange().setStart(node, offset); michael@0: michael@0: // "Call extend(node, end offset) on the context object's michael@0: // Selection." michael@0: getSelection().extend(node, endOffset); michael@0: getActiveRange().setEnd(node, endOffset); michael@0: michael@0: // "Delete the selection." michael@0: deleteSelection(); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "If node is an inline node, return true." michael@0: if (isInlineNode(node)) { michael@0: return true; michael@0: } michael@0: michael@0: // "If node has a child with index offset and that child is a br or hr michael@0: // or img, but is not a collapsed block prop:" michael@0: if (offset < node.childNodes.length michael@0: && isHtmlElement(node.childNodes[offset], ["br", "hr", "img"]) michael@0: && !isCollapsedBlockProp(node.childNodes[offset])) { michael@0: // "Call collapse(node, offset) on the context object's Selection." michael@0: getSelection().collapse(node, offset); michael@0: getActiveRange().setStart(node, offset); michael@0: michael@0: // "Call extend(node, offset + 1) on the context object's michael@0: // Selection." michael@0: getSelection().extend(node, offset + 1); michael@0: getActiveRange().setEnd(node, offset + 1); michael@0: michael@0: // "Delete the selection." michael@0: deleteSelection(); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "Let end node equal node and let end offset equal offset." michael@0: var endNode = node; michael@0: var endOffset = offset; michael@0: michael@0: // "If end node has a child with index end offset, and that child is a michael@0: // collapsed block prop, add one to end offset." michael@0: if (endOffset < endNode.childNodes.length michael@0: && isCollapsedBlockProp(endNode.childNodes[endOffset])) { michael@0: endOffset++; michael@0: } michael@0: michael@0: // "Repeat the following steps:" michael@0: while (true) { michael@0: // "If end offset is the length of end node, set end offset to one michael@0: // plus the index of end node and then set end node to its parent." michael@0: if (endOffset == getNodeLength(endNode)) { michael@0: endOffset = 1 + getNodeIndex(endNode); michael@0: endNode = endNode.parentNode; michael@0: michael@0: // "Otherwise, if end node has a an editable invisible child with michael@0: // index end offset, remove it from end node." michael@0: } else if (endOffset < endNode.childNodes.length michael@0: && isEditable(endNode.childNodes[endOffset]) michael@0: && isInvisible(endNode.childNodes[endOffset])) { michael@0: endNode.removeChild(endNode.childNodes[endOffset]); michael@0: michael@0: // "Otherwise, break from this loop." michael@0: } else { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // "If the child of end node with index end offset minus one is a michael@0: // table, return true." michael@0: if (isHtmlElement(endNode.childNodes[endOffset - 1], "table")) { michael@0: return true; michael@0: } michael@0: michael@0: // "If the child of end node with index end offset is a table:" michael@0: if (isHtmlElement(endNode.childNodes[endOffset], "table")) { michael@0: // "Call collapse(end node, end offset) on the context object's michael@0: // Selection." michael@0: getSelection().collapse(endNode, endOffset); michael@0: getActiveRange().setStart(endNode, endOffset); michael@0: michael@0: // "Call extend(end node, end offset + 1) on the context object's michael@0: // Selection." michael@0: getSelection().extend(endNode, endOffset + 1); michael@0: getActiveRange().setEnd(endNode, endOffset + 1); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "If offset is the length of node, and the child of end node with michael@0: // index end offset is an hr or br:" michael@0: if (offset == getNodeLength(node) michael@0: && isHtmlElement(endNode.childNodes[endOffset], ["br", "hr"])) { michael@0: // "Call collapse(end node, end offset) on the context object's michael@0: // Selection." michael@0: getSelection().collapse(endNode, endOffset); michael@0: getActiveRange().setStart(endNode, endOffset); michael@0: michael@0: // "Call extend(end node, end offset + 1) on the context object's michael@0: // Selection." michael@0: getSelection().extend(endNode, endOffset + 1); michael@0: getActiveRange().setEnd(endNode, endOffset + 1); michael@0: michael@0: // "Delete the selection." michael@0: deleteSelection(); michael@0: michael@0: // "Call collapse(node, offset) on the Selection." michael@0: getSelection().collapse(node, offset); michael@0: getActiveRange().setStart(node, offset); michael@0: getActiveRange().collapse(true); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "While end node has a child with index end offset:" michael@0: while (endOffset < endNode.childNodes.length) { michael@0: // "If end node's child with index end offset is editable and michael@0: // invisible, remove it from end node." michael@0: if (isEditable(endNode.childNodes[endOffset]) michael@0: && isInvisible(endNode.childNodes[endOffset])) { michael@0: endNode.removeChild(endNode.childNodes[endOffset]); michael@0: michael@0: // "Otherwise, set end node to its child with index end offset and michael@0: // set end offset to zero." michael@0: } else { michael@0: endNode = endNode.childNodes[endOffset]; michael@0: endOffset = 0; michael@0: } michael@0: } michael@0: michael@0: // "Call collapse(node, offset) on the context object's Selection." michael@0: getSelection().collapse(node, offset); michael@0: getActiveRange().setStart(node, offset); michael@0: michael@0: // "Call extend(end node, end offset) on the context object's michael@0: // Selection." michael@0: getSelection().extend(endNode, endOffset); michael@0: getActiveRange().setEnd(endNode, endOffset); michael@0: michael@0: // "Delete the selection." michael@0: deleteSelection(); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The indent command ///// michael@0: //@{ michael@0: commands.indent = { michael@0: preservesOverrides: true, michael@0: action: function() { michael@0: // "Let items be a list of all lis that are ancestor containers of the michael@0: // active range's start and/or end node." michael@0: // michael@0: // Has to be in tree order, remember! michael@0: var items = []; michael@0: for (var node = getActiveRange().endContainer; node != getActiveRange().commonAncestorContainer; node = node.parentNode) { michael@0: if (isHtmlElement(node, "LI")) { michael@0: items.unshift(node); michael@0: } michael@0: } michael@0: for (var node = getActiveRange().startContainer; node != getActiveRange().commonAncestorContainer; node = node.parentNode) { michael@0: if (isHtmlElement(node, "LI")) { michael@0: items.unshift(node); michael@0: } michael@0: } michael@0: for (var node = getActiveRange().commonAncestorContainer; node; node = node.parentNode) { michael@0: if (isHtmlElement(node, "LI")) { michael@0: items.unshift(node); michael@0: } michael@0: } michael@0: michael@0: // "For each item in items, normalize sublists of item." michael@0: for (var i = 0; i < items.length; i++) { michael@0: normalizeSublists(items[i]); michael@0: } michael@0: michael@0: // "Block-extend the active range, and let new range be the result." michael@0: var newRange = blockExtend(getActiveRange()); michael@0: michael@0: // "Let node list be a list of nodes, initially empty." michael@0: var nodeList = []; michael@0: michael@0: // "For each node node contained in new range, if node is editable and michael@0: // is an allowed child of "div" or "ol" and if the last member of node michael@0: // list (if any) is not an ancestor of node, append node to node list." michael@0: nodeList = getContainedNodes(newRange, function(node) { michael@0: return isEditable(node) michael@0: && (isAllowedChild(node, "div") michael@0: || isAllowedChild(node, "ol")); michael@0: }); michael@0: michael@0: // "If the first visible member of node list is an li whose parent is michael@0: // an ol or ul:" michael@0: if (isHtmlElement(nodeList.filter(isVisible)[0], "li") michael@0: && isHtmlElement(nodeList.filter(isVisible)[0].parentNode, ["ol", "ul"])) { michael@0: // "Let sibling be node list's first visible member's michael@0: // previousSibling." michael@0: var sibling = nodeList.filter(isVisible)[0].previousSibling; michael@0: michael@0: // "While sibling is invisible, set sibling to its michael@0: // previousSibling." michael@0: while (isInvisible(sibling)) { michael@0: sibling = sibling.previousSibling; michael@0: } michael@0: michael@0: // "If sibling is an li, normalize sublists of sibling." michael@0: if (isHtmlElement(sibling, "li")) { michael@0: normalizeSublists(sibling); michael@0: } michael@0: } michael@0: michael@0: // "While node list is not empty:" michael@0: while (nodeList.length) { michael@0: // "Let sublist be a list of nodes, initially empty." michael@0: var sublist = []; michael@0: michael@0: // "Remove the first member of node list and append it to sublist." michael@0: sublist.push(nodeList.shift()); michael@0: michael@0: // "While the first member of node list is the nextSibling of the michael@0: // last member of sublist, remove the first member of node list and michael@0: // append it to sublist." michael@0: while (nodeList.length michael@0: && nodeList[0] == sublist[sublist.length - 1].nextSibling) { michael@0: sublist.push(nodeList.shift()); michael@0: } michael@0: michael@0: // "Indent sublist." michael@0: indentNodes(sublist); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The insertHorizontalRule command ///// michael@0: //@{ michael@0: commands.inserthorizontalrule = { michael@0: preservesOverrides: true, michael@0: action: function() { michael@0: // "Let start node, start offset, end node, and end offset be the michael@0: // active range's start and end nodes and offsets." michael@0: var startNode = getActiveRange().startContainer; michael@0: var startOffset = getActiveRange().startOffset; michael@0: var endNode = getActiveRange().endContainer; michael@0: var endOffset = getActiveRange().endOffset; michael@0: michael@0: // "While start offset is 0 and start node's parent is not null, set michael@0: // start offset to start node's index, then set start node to its michael@0: // parent." michael@0: while (startOffset == 0 michael@0: && startNode.parentNode) { michael@0: startOffset = getNodeIndex(startNode); michael@0: startNode = startNode.parentNode; michael@0: } michael@0: michael@0: // "While end offset is end node's length, and end node's parent is not michael@0: // null, set end offset to one plus end node's index, then set end node michael@0: // to its parent." michael@0: while (endOffset == getNodeLength(endNode) michael@0: && endNode.parentNode) { michael@0: endOffset = 1 + getNodeIndex(endNode); michael@0: endNode = endNode.parentNode; michael@0: } michael@0: michael@0: // "Call collapse(start node, start offset) on the context object's michael@0: // Selection." michael@0: getSelection().collapse(startNode, startOffset); michael@0: getActiveRange().setStart(startNode, startOffset); michael@0: michael@0: // "Call extend(end node, end offset) on the context object's michael@0: // Selection." michael@0: getSelection().extend(endNode, endOffset); michael@0: getActiveRange().setEnd(endNode, endOffset); michael@0: michael@0: // "Delete the selection, with block merging false." michael@0: deleteSelection({blockMerging: false}); michael@0: michael@0: // "If the active range's start node is neither editable nor an editing michael@0: // host, return true." michael@0: if (!isEditable(getActiveRange().startContainer) michael@0: && !isEditingHost(getActiveRange().startContainer)) { michael@0: return true; michael@0: } michael@0: michael@0: // "If the active range's start node is a Text node and its start michael@0: // offset is zero, call collapse() on the context object's Selection, michael@0: // with first argument the active range's start node's parent and michael@0: // second argument the active range's start node's index." michael@0: if (getActiveRange().startContainer.nodeType == Node.TEXT_NODE michael@0: && getActiveRange().startOffset == 0) { michael@0: var newNode = getActiveRange().startContainer.parentNode; michael@0: var newOffset = getNodeIndex(getActiveRange().startContainer); michael@0: getSelection().collapse(newNode, newOffset); michael@0: getActiveRange().setStart(newNode, newOffset); michael@0: getActiveRange().collapse(true); michael@0: } michael@0: michael@0: // "If the active range's start node is a Text node and its start michael@0: // offset is the length of its start node, call collapse() on the michael@0: // context object's Selection, with first argument the active range's michael@0: // start node's parent, and the second argument one plus the active michael@0: // range's start node's index." michael@0: if (getActiveRange().startContainer.nodeType == Node.TEXT_NODE michael@0: && getActiveRange().startOffset == getNodeLength(getActiveRange().startContainer)) { michael@0: var newNode = getActiveRange().startContainer.parentNode; michael@0: var newOffset = 1 + getNodeIndex(getActiveRange().startContainer); michael@0: getSelection().collapse(newNode, newOffset); michael@0: getActiveRange().setStart(newNode, newOffset); michael@0: getActiveRange().collapse(true); michael@0: } michael@0: michael@0: // "Let hr be the result of calling createElement("hr") on the michael@0: // context object." michael@0: var hr = document.createElement("hr"); michael@0: michael@0: // "Run insertNode(hr) on the active range." michael@0: getActiveRange().insertNode(hr); michael@0: michael@0: // "Fix disallowed ancestors of hr." michael@0: fixDisallowedAncestors(hr); michael@0: michael@0: // "Run collapse() on the context object's Selection, with first michael@0: // argument hr's parent and the second argument equal to one plus hr's michael@0: // index." michael@0: getSelection().collapse(hr.parentNode, 1 + getNodeIndex(hr)); michael@0: getActiveRange().setStart(hr.parentNode, 1 + getNodeIndex(hr)); michael@0: getActiveRange().collapse(true); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The insertHTML command ///// michael@0: //@{ michael@0: commands.inserthtml = { michael@0: preservesOverrides: true, michael@0: action: function(value) { michael@0: // "Delete the selection." michael@0: deleteSelection(); michael@0: michael@0: // "If the active range's start node is neither editable nor an editing michael@0: // host, return true." michael@0: if (!isEditable(getActiveRange().startContainer) michael@0: && !isEditingHost(getActiveRange().startContainer)) { michael@0: return true; michael@0: } michael@0: michael@0: // "Let frag be the result of calling createContextualFragment(value) michael@0: // on the active range." michael@0: var frag = getActiveRange().createContextualFragment(value); michael@0: michael@0: // "Let last child be the lastChild of frag." michael@0: var lastChild = frag.lastChild; michael@0: michael@0: // "If last child is null, return true." michael@0: if (!lastChild) { michael@0: return true; michael@0: } michael@0: michael@0: // "Let descendants be all descendants of frag." michael@0: var descendants = getDescendants(frag); michael@0: michael@0: // "If the active range's start node is a block node:" michael@0: if (isBlockNode(getActiveRange().startContainer)) { michael@0: // "Let collapsed block props be all editable collapsed block prop michael@0: // children of the active range's start node that have index michael@0: // greater than or equal to the active range's start offset." michael@0: // michael@0: // "For each node in collapsed block props, remove node from its michael@0: // parent." michael@0: [].filter.call(getActiveRange().startContainer.childNodes, function(node) { michael@0: return isEditable(node) michael@0: && isCollapsedBlockProp(node) michael@0: && getNodeIndex(node) >= getActiveRange().startOffset; michael@0: }).forEach(function(node) { michael@0: node.parentNode.removeChild(node); michael@0: }); michael@0: } michael@0: michael@0: // "Call insertNode(frag) on the active range." michael@0: getActiveRange().insertNode(frag); michael@0: michael@0: // "If the active range's start node is a block node with no visible michael@0: // children, call createElement("br") on the context object and append michael@0: // the result as the last child of the active range's start node." michael@0: if (isBlockNode(getActiveRange().startContainer) michael@0: && ![].some.call(getActiveRange().startContainer.childNodes, isVisible)) { michael@0: getActiveRange().startContainer.appendChild(document.createElement("br")); michael@0: } michael@0: michael@0: // "Call collapse() on the context object's Selection, with last michael@0: // child's parent as the first argument and one plus its index as the michael@0: // second." michael@0: getActiveRange().setStart(lastChild.parentNode, 1 + getNodeIndex(lastChild)); michael@0: getActiveRange().setEnd(lastChild.parentNode, 1 + getNodeIndex(lastChild)); michael@0: michael@0: // "Fix disallowed ancestors of each member of descendants." michael@0: for (var i = 0; i < descendants.length; i++) { michael@0: fixDisallowedAncestors(descendants[i]); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The insertImage command ///// michael@0: //@{ michael@0: commands.insertimage = { michael@0: preservesOverrides: true, michael@0: action: function(value) { michael@0: // "If value is the empty string, return false." michael@0: if (value === "") { michael@0: return false; michael@0: } michael@0: michael@0: // "Delete the selection, with strip wrappers false." michael@0: deleteSelection({stripWrappers: false}); michael@0: michael@0: // "Let range be the active range." michael@0: var range = getActiveRange(); michael@0: michael@0: // "If the active range's start node is neither editable nor an editing michael@0: // host, return true." michael@0: if (!isEditable(getActiveRange().startContainer) michael@0: && !isEditingHost(getActiveRange().startContainer)) { michael@0: return true; michael@0: } michael@0: michael@0: // "If range's start node is a block node whose sole child is a br, and michael@0: // its start offset is 0, remove its start node's child from it." michael@0: if (isBlockNode(range.startContainer) michael@0: && range.startContainer.childNodes.length == 1 michael@0: && isHtmlElement(range.startContainer.firstChild, "br") michael@0: && range.startOffset == 0) { michael@0: range.startContainer.removeChild(range.startContainer.firstChild); michael@0: } michael@0: michael@0: // "Let img be the result of calling createElement("img") on the michael@0: // context object." michael@0: var img = document.createElement("img"); michael@0: michael@0: // "Run setAttribute("src", value) on img." michael@0: img.setAttribute("src", value); michael@0: michael@0: // "Run insertNode(img) on the range." michael@0: range.insertNode(img); michael@0: michael@0: // "Run collapse() on the Selection, with first argument equal to the michael@0: // parent of img and the second argument equal to one plus the index of michael@0: // img." michael@0: // michael@0: // Not everyone actually supports collapse(), so we do it manually michael@0: // instead. Also, we need to modify the actual range we're given as michael@0: // well, for the sake of autoimplementation.html's range-filling-in. michael@0: range.setStart(img.parentNode, 1 + getNodeIndex(img)); michael@0: range.setEnd(img.parentNode, 1 + getNodeIndex(img)); michael@0: getSelection().removeAllRanges(); michael@0: getSelection().addRange(range); michael@0: michael@0: // IE adds width and height attributes for some reason, so remove those michael@0: // to actually do what the spec says. michael@0: img.removeAttribute("width"); michael@0: img.removeAttribute("height"); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The insertLineBreak command ///// michael@0: //@{ michael@0: commands.insertlinebreak = { michael@0: preservesOverrides: true, michael@0: action: function(value) { michael@0: // "Delete the selection, with strip wrappers false." michael@0: deleteSelection({stripWrappers: false}); michael@0: michael@0: // "If the active range's start node is neither editable nor an editing michael@0: // host, return true." michael@0: if (!isEditable(getActiveRange().startContainer) michael@0: && !isEditingHost(getActiveRange().startContainer)) { michael@0: return true; michael@0: } michael@0: michael@0: // "If the active range's start node is an Element, and "br" is not an michael@0: // allowed child of it, return true." michael@0: if (getActiveRange().startContainer.nodeType == Node.ELEMENT_NODE michael@0: && !isAllowedChild("br", getActiveRange().startContainer)) { michael@0: return true; michael@0: } michael@0: michael@0: // "If the active range's start node is not an Element, and "br" is not michael@0: // an allowed child of the active range's start node's parent, return michael@0: // true." michael@0: if (getActiveRange().startContainer.nodeType != Node.ELEMENT_NODE michael@0: && !isAllowedChild("br", getActiveRange().startContainer.parentNode)) { michael@0: return true; michael@0: } michael@0: michael@0: // "If the active range's start node is a Text node and its start michael@0: // offset is zero, call collapse() on the context object's Selection, michael@0: // with first argument equal to the active range's start node's parent michael@0: // and second argument equal to the active range's start node's index." michael@0: if (getActiveRange().startContainer.nodeType == Node.TEXT_NODE michael@0: && getActiveRange().startOffset == 0) { michael@0: var newNode = getActiveRange().startContainer.parentNode; michael@0: var newOffset = getNodeIndex(getActiveRange().startContainer); michael@0: getSelection().collapse(newNode, newOffset); michael@0: getActiveRange().setStart(newNode, newOffset); michael@0: getActiveRange().setEnd(newNode, newOffset); michael@0: } michael@0: michael@0: // "If the active range's start node is a Text node and its start michael@0: // offset is the length of its start node, call collapse() on the michael@0: // context object's Selection, with first argument equal to the active michael@0: // range's start node's parent and second argument equal to one plus michael@0: // the active range's start node's index." michael@0: if (getActiveRange().startContainer.nodeType == Node.TEXT_NODE michael@0: && getActiveRange().startOffset == getNodeLength(getActiveRange().startContainer)) { michael@0: var newNode = getActiveRange().startContainer.parentNode; michael@0: var newOffset = 1 + getNodeIndex(getActiveRange().startContainer); michael@0: getSelection().collapse(newNode, newOffset); michael@0: getActiveRange().setStart(newNode, newOffset); michael@0: getActiveRange().setEnd(newNode, newOffset); michael@0: } michael@0: michael@0: // "Let br be the result of calling createElement("br") on the context michael@0: // object." michael@0: var br = document.createElement("br"); michael@0: michael@0: // "Call insertNode(br) on the active range." michael@0: getActiveRange().insertNode(br); michael@0: michael@0: // "Call collapse() on the context object's Selection, with br's parent michael@0: // as the first argument and one plus br's index as the second michael@0: // argument." michael@0: getSelection().collapse(br.parentNode, 1 + getNodeIndex(br)); michael@0: getActiveRange().setStart(br.parentNode, 1 + getNodeIndex(br)); michael@0: getActiveRange().setEnd(br.parentNode, 1 + getNodeIndex(br)); michael@0: michael@0: // "If br is a collapsed line break, call createElement("br") on the michael@0: // context object and let extra br be the result, then call michael@0: // insertNode(extra br) on the active range." michael@0: if (isCollapsedLineBreak(br)) { michael@0: getActiveRange().insertNode(document.createElement("br")); michael@0: michael@0: // Compensate for nonstandard implementations of insertNode michael@0: getSelection().collapse(br.parentNode, 1 + getNodeIndex(br)); michael@0: getActiveRange().setStart(br.parentNode, 1 + getNodeIndex(br)); michael@0: getActiveRange().setEnd(br.parentNode, 1 + getNodeIndex(br)); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The insertOrderedList command ///// michael@0: //@{ michael@0: commands.insertorderedlist = { michael@0: preservesOverrides: true, michael@0: // "Toggle lists with tag name "ol", then return true." michael@0: action: function() { toggleLists("ol"); return true }, michael@0: // "True if the selection's list state is "mixed" or "mixed ol", false michael@0: // otherwise." michael@0: indeterm: function() { return /^mixed( ol)?$/.test(getSelectionListState()) }, michael@0: // "True if the selection's list state is "ol", false otherwise." michael@0: state: function() { return getSelectionListState() == "ol" }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The insertParagraph command ///// michael@0: //@{ michael@0: commands.insertparagraph = { michael@0: preservesOverrides: true, michael@0: action: function() { michael@0: // "Delete the selection." michael@0: deleteSelection(); michael@0: michael@0: // "If the active range's start node is neither editable nor an editing michael@0: // host, return true." michael@0: if (!isEditable(getActiveRange().startContainer) michael@0: && !isEditingHost(getActiveRange().startContainer)) { michael@0: return true; michael@0: } michael@0: michael@0: // "Let node and offset be the active range's start node and offset." michael@0: var node = getActiveRange().startContainer; michael@0: var offset = getActiveRange().startOffset; michael@0: michael@0: // "If node is a Text node, and offset is neither 0 nor the length of michael@0: // node, call splitText(offset) on node." michael@0: if (node.nodeType == Node.TEXT_NODE michael@0: && offset != 0 michael@0: && offset != getNodeLength(node)) { michael@0: node.splitText(offset); michael@0: } michael@0: michael@0: // "If node is a Text node and offset is its length, set offset to one michael@0: // plus the index of node, then set node to its parent." michael@0: if (node.nodeType == Node.TEXT_NODE michael@0: && offset == getNodeLength(node)) { michael@0: offset = 1 + getNodeIndex(node); michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: // "If node is a Text or Comment node, set offset to the index of node, michael@0: // then set node to its parent." michael@0: if (node.nodeType == Node.TEXT_NODE michael@0: || node.nodeType == Node.COMMENT_NODE) { michael@0: offset = getNodeIndex(node); michael@0: node = node.parentNode; michael@0: } michael@0: michael@0: // "Call collapse(node, offset) on the context object's Selection." michael@0: getSelection().collapse(node, offset); michael@0: getActiveRange().setStart(node, offset); michael@0: getActiveRange().setEnd(node, offset); michael@0: michael@0: // "Let container equal node." michael@0: var container = node; michael@0: michael@0: // "While container is not a single-line container, and container's michael@0: // parent is editable and in the same editing host as node, set michael@0: // container to its parent." michael@0: while (!isSingleLineContainer(container) michael@0: && isEditable(container.parentNode) michael@0: && inSameEditingHost(node, container.parentNode)) { michael@0: container = container.parentNode; michael@0: } michael@0: michael@0: // "If container is an editable single-line container in the same michael@0: // editing host as node, and its local name is "p" or "div":" michael@0: if (isEditable(container) michael@0: && isSingleLineContainer(container) michael@0: && inSameEditingHost(node, container.parentNode) michael@0: && (container.tagName == "P" || container.tagName == "DIV")) { michael@0: // "Let outer container equal container." michael@0: var outerContainer = container; michael@0: michael@0: // "While outer container is not a dd or dt or li, and outer michael@0: // container's parent is editable, set outer container to its michael@0: // parent." michael@0: while (!isHtmlElement(outerContainer, ["dd", "dt", "li"]) michael@0: && isEditable(outerContainer.parentNode)) { michael@0: outerContainer = outerContainer.parentNode; michael@0: } michael@0: michael@0: // "If outer container is a dd or dt or li, set container to outer michael@0: // container." michael@0: if (isHtmlElement(outerContainer, ["dd", "dt", "li"])) { michael@0: container = outerContainer; michael@0: } michael@0: } michael@0: michael@0: // "If container is not editable or not in the same editing host as michael@0: // node or is not a single-line container:" michael@0: if (!isEditable(container) michael@0: || !inSameEditingHost(container, node) michael@0: || !isSingleLineContainer(container)) { michael@0: // "Let tag be the default single-line container name." michael@0: var tag = defaultSingleLineContainerName; michael@0: michael@0: // "Block-extend the active range, and let new range be the michael@0: // result." michael@0: var newRange = blockExtend(getActiveRange()); michael@0: michael@0: // "Let node list be a list of nodes, initially empty." michael@0: // michael@0: // "Append to node list the first node in tree order that is michael@0: // contained in new range and is an allowed child of "p", if any." michael@0: var nodeList = getContainedNodes(newRange, function(node) { return isAllowedChild(node, "p") }) michael@0: .slice(0, 1); michael@0: michael@0: // "If node list is empty:" michael@0: if (!nodeList.length) { michael@0: // "If tag is not an allowed child of the active range's start michael@0: // node, return true." michael@0: if (!isAllowedChild(tag, getActiveRange().startContainer)) { michael@0: return true; michael@0: } michael@0: michael@0: // "Set container to the result of calling createElement(tag) michael@0: // on the context object." michael@0: container = document.createElement(tag); michael@0: michael@0: // "Call insertNode(container) on the active range." michael@0: getActiveRange().insertNode(container); michael@0: michael@0: // "Call createElement("br") on the context object, and append michael@0: // the result as the last child of container." michael@0: container.appendChild(document.createElement("br")); michael@0: michael@0: // "Call collapse(container, 0) on the context object's michael@0: // Selection." michael@0: getSelection().collapse(container, 0); michael@0: getActiveRange().setStart(container, 0); michael@0: getActiveRange().setEnd(container, 0); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "While the nextSibling of the last member of node list is not michael@0: // null and is an allowed child of "p", append it to node list." michael@0: while (nodeList[nodeList.length - 1].nextSibling michael@0: && isAllowedChild(nodeList[nodeList.length - 1].nextSibling, "p")) { michael@0: nodeList.push(nodeList[nodeList.length - 1].nextSibling); michael@0: } michael@0: michael@0: // "Wrap node list, with sibling criteria returning false and new michael@0: // parent instructions returning the result of calling michael@0: // createElement(tag) on the context object. Set container to the michael@0: // result." michael@0: container = wrap(nodeList, michael@0: function() { return false }, michael@0: function() { return document.createElement(tag) } michael@0: ); michael@0: } michael@0: michael@0: // "If container's local name is "address", "listing", or "pre":" michael@0: if (container.tagName == "ADDRESS" michael@0: || container.tagName == "LISTING" michael@0: || container.tagName == "PRE") { michael@0: // "Let br be the result of calling createElement("br") on the michael@0: // context object." michael@0: var br = document.createElement("br"); michael@0: michael@0: // "Call insertNode(br) on the active range." michael@0: getActiveRange().insertNode(br); michael@0: michael@0: // "Call collapse(node, offset + 1) on the context object's michael@0: // Selection." michael@0: getSelection().collapse(node, offset + 1); michael@0: getActiveRange().setStart(node, offset + 1); michael@0: getActiveRange().setEnd(node, offset + 1); michael@0: michael@0: // "If br is the last descendant of container, let br be the result michael@0: // of calling createElement("br") on the context object, then call michael@0: // insertNode(br) on the active range." michael@0: // michael@0: // Work around browser bugs: some browsers select the michael@0: // newly-inserted node, not per spec. michael@0: if (!isDescendant(nextNode(br), container)) { michael@0: getActiveRange().insertNode(document.createElement("br")); michael@0: getSelection().collapse(node, offset + 1); michael@0: getActiveRange().setEnd(node, offset + 1); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "If container's local name is "li", "dt", or "dd"; and either it has michael@0: // no children or it has a single child and that child is a br:" michael@0: if (["LI", "DT", "DD"].indexOf(container.tagName) != -1 michael@0: && (!container.hasChildNodes() michael@0: || (container.childNodes.length == 1 michael@0: && isHtmlElement(container.firstChild, "br")))) { michael@0: // "Split the parent of the one-node list consisting of container." michael@0: splitParent([container]); michael@0: michael@0: // "If container has no children, call createElement("br") on the michael@0: // context object and append the result as the last child of michael@0: // container." michael@0: if (!container.hasChildNodes()) { michael@0: container.appendChild(document.createElement("br")); michael@0: } michael@0: michael@0: // "If container is a dd or dt, and it is not an allowed child of michael@0: // any of its ancestors in the same editing host, set the tag name michael@0: // of container to the default single-line container name and let michael@0: // container be the result." michael@0: if (isHtmlElement(container, ["dd", "dt"]) michael@0: && getAncestors(container).every(function(ancestor) { michael@0: return !inSameEditingHost(container, ancestor) michael@0: || !isAllowedChild(container, ancestor) michael@0: })) { michael@0: container = setTagName(container, defaultSingleLineContainerName); michael@0: } michael@0: michael@0: // "Fix disallowed ancestors of container." michael@0: fixDisallowedAncestors(container); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "Let new line range be a new range whose start is the same as michael@0: // the active range's, and whose end is (container, length of michael@0: // container)." michael@0: var newLineRange = document.createRange(); michael@0: newLineRange.setStart(getActiveRange().startContainer, getActiveRange().startOffset); michael@0: newLineRange.setEnd(container, getNodeLength(container)); michael@0: michael@0: // "While new line range's start offset is zero and its start node is michael@0: // not a prohibited paragraph child, set its start to (parent of start michael@0: // node, index of start node)." michael@0: while (newLineRange.startOffset == 0 michael@0: && !isProhibitedParagraphChild(newLineRange.startContainer)) { michael@0: newLineRange.setStart(newLineRange.startContainer.parentNode, getNodeIndex(newLineRange.startContainer)); michael@0: } michael@0: michael@0: // "While new line range's start offset is the length of its start node michael@0: // and its start node is not a prohibited paragraph child, set its michael@0: // start to (parent of start node, 1 + index of start node)." michael@0: while (newLineRange.startOffset == getNodeLength(newLineRange.startContainer) michael@0: && !isProhibitedParagraphChild(newLineRange.startContainer)) { michael@0: newLineRange.setStart(newLineRange.startContainer.parentNode, 1 + getNodeIndex(newLineRange.startContainer)); michael@0: } michael@0: michael@0: // "Let end of line be true if new line range contains either nothing michael@0: // or a single br, and false otherwise." michael@0: var containedInNewLineRange = getContainedNodes(newLineRange); michael@0: var endOfLine = !containedInNewLineRange.length michael@0: || (containedInNewLineRange.length == 1 michael@0: && isHtmlElement(containedInNewLineRange[0], "br")); michael@0: michael@0: // "If the local name of container is "h1", "h2", "h3", "h4", "h5", or michael@0: // "h6", and end of line is true, let new container name be the default michael@0: // single-line container name." michael@0: var newContainerName; michael@0: if (/^H[1-6]$/.test(container.tagName) michael@0: && endOfLine) { michael@0: newContainerName = defaultSingleLineContainerName; michael@0: michael@0: // "Otherwise, if the local name of container is "dt" and end of line michael@0: // is true, let new container name be "dd"." michael@0: } else if (container.tagName == "DT" michael@0: && endOfLine) { michael@0: newContainerName = "dd"; michael@0: michael@0: // "Otherwise, if the local name of container is "dd" and end of line michael@0: // is true, let new container name be "dt"." michael@0: } else if (container.tagName == "DD" michael@0: && endOfLine) { michael@0: newContainerName = "dt"; michael@0: michael@0: // "Otherwise, let new container name be the local name of container." michael@0: } else { michael@0: newContainerName = container.tagName.toLowerCase(); michael@0: } michael@0: michael@0: // "Let new container be the result of calling createElement(new michael@0: // container name) on the context object." michael@0: var newContainer = document.createElement(newContainerName); michael@0: michael@0: // "Copy all attributes of container to new container." michael@0: for (var i = 0; i < container.attributes.length; i++) { michael@0: newContainer.setAttributeNS(container.attributes[i].namespaceURI, container.attributes[i].name, container.attributes[i].value); michael@0: } michael@0: michael@0: // "If new container has an id attribute, unset it." michael@0: newContainer.removeAttribute("id"); michael@0: michael@0: // "Insert new container into the parent of container immediately after michael@0: // container." michael@0: container.parentNode.insertBefore(newContainer, container.nextSibling); michael@0: michael@0: // "Let contained nodes be all nodes contained in new line range." michael@0: var containedNodes = getAllContainedNodes(newLineRange); michael@0: michael@0: // "Let frag be the result of calling extractContents() on new line michael@0: // range." michael@0: var frag = newLineRange.extractContents(); michael@0: michael@0: // "Unset the id attribute (if any) of each Element descendant of frag michael@0: // that is not in contained nodes." michael@0: var descendants = getDescendants(frag); michael@0: for (var i = 0; i < descendants.length; i++) { michael@0: if (descendants[i].nodeType == Node.ELEMENT_NODE michael@0: && containedNodes.indexOf(descendants[i]) == -1) { michael@0: descendants[i].removeAttribute("id"); michael@0: } michael@0: } michael@0: michael@0: // "Call appendChild(frag) on new container." michael@0: newContainer.appendChild(frag); michael@0: michael@0: // "While container's lastChild is a prohibited paragraph child, set michael@0: // container to its lastChild." michael@0: while (isProhibitedParagraphChild(container.lastChild)) { michael@0: container = container.lastChild; michael@0: } michael@0: michael@0: // "While new container's lastChild is a prohibited paragraph child, michael@0: // set new container to its lastChild." michael@0: while (isProhibitedParagraphChild(newContainer.lastChild)) { michael@0: newContainer = newContainer.lastChild; michael@0: } michael@0: michael@0: // "If container has no visible children, call createElement("br") on michael@0: // the context object, and append the result as the last child of michael@0: // container." michael@0: if (![].some.call(container.childNodes, isVisible)) { michael@0: container.appendChild(document.createElement("br")); michael@0: } michael@0: michael@0: // "If new container has no visible children, call createElement("br") michael@0: // on the context object, and append the result as the last child of michael@0: // new container." michael@0: if (![].some.call(newContainer.childNodes, isVisible)) { michael@0: newContainer.appendChild(document.createElement("br")); michael@0: } michael@0: michael@0: // "Call collapse(new container, 0) on the context object's Selection." michael@0: getSelection().collapse(newContainer, 0); michael@0: getActiveRange().setStart(newContainer, 0); michael@0: getActiveRange().setEnd(newContainer, 0); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The insertText command ///// michael@0: //@{ michael@0: commands.inserttext = { michael@0: action: function(value) { michael@0: // "Delete the selection, with strip wrappers false." michael@0: deleteSelection({stripWrappers: false}); michael@0: michael@0: // "If the active range's start node is neither editable nor an editing michael@0: // host, return true." michael@0: if (!isEditable(getActiveRange().startContainer) michael@0: && !isEditingHost(getActiveRange().startContainer)) { michael@0: return true; michael@0: } michael@0: michael@0: // "If value's length is greater than one:" michael@0: if (value.length > 1) { michael@0: // "For each element el in value, take the action for the michael@0: // insertText command, with value equal to el." michael@0: for (var i = 0; i < value.length; i++) { michael@0: commands.inserttext.action(value[i]); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: michael@0: // "If value is the empty string, return true." michael@0: if (value == "") { michael@0: return true; michael@0: } michael@0: michael@0: // "If value is a newline (U+00A0), take the action for the michael@0: // insertParagraph command and return true." michael@0: if (value == "\n") { michael@0: commands.insertparagraph.action(); michael@0: return true; michael@0: } michael@0: michael@0: // "Let node and offset be the active range's start node and offset." michael@0: var node = getActiveRange().startContainer; michael@0: var offset = getActiveRange().startOffset; michael@0: michael@0: // "If node has a child whose index is offset − 1, and that child is a michael@0: // Text node, set node to that child, then set offset to node's michael@0: // length." michael@0: if (0 <= offset - 1 michael@0: && offset - 1 < node.childNodes.length michael@0: && node.childNodes[offset - 1].nodeType == Node.TEXT_NODE) { michael@0: node = node.childNodes[offset - 1]; michael@0: offset = getNodeLength(node); michael@0: } michael@0: michael@0: // "If node has a child whose index is offset, and that child is a Text michael@0: // node, set node to that child, then set offset to zero." michael@0: if (0 <= offset michael@0: && offset < node.childNodes.length michael@0: && node.childNodes[offset].nodeType == Node.TEXT_NODE) { michael@0: node = node.childNodes[offset]; michael@0: offset = 0; michael@0: } michael@0: michael@0: // "Record current overrides, and let overrides be the result." michael@0: var overrides = recordCurrentOverrides(); michael@0: michael@0: // "Call collapse(node, offset) on the context object's Selection." michael@0: getSelection().collapse(node, offset); michael@0: getActiveRange().setStart(node, offset); michael@0: getActiveRange().setEnd(node, offset); michael@0: michael@0: // "Canonicalize whitespace at (node, offset)." michael@0: canonicalizeWhitespace(node, offset); michael@0: michael@0: // "Let (node, offset) be the active range's start." michael@0: node = getActiveRange().startContainer; michael@0: offset = getActiveRange().startOffset; michael@0: michael@0: // "If node is a Text node:" michael@0: if (node.nodeType == Node.TEXT_NODE) { michael@0: // "Call insertData(offset, value) on node." michael@0: node.insertData(offset, value); michael@0: michael@0: // "Call collapse(node, offset) on the context object's Selection." michael@0: getSelection().collapse(node, offset); michael@0: getActiveRange().setStart(node, offset); michael@0: michael@0: // "Call extend(node, offset + 1) on the context object's michael@0: // Selection." michael@0: // michael@0: // Work around WebKit bug: the extend() can throw if the text we're michael@0: // adding is trailing whitespace. michael@0: try { getSelection().extend(node, offset + 1); } catch(e) {} michael@0: getActiveRange().setEnd(node, offset + 1); michael@0: michael@0: // "Otherwise:" michael@0: } else { michael@0: // "If node has only one child, which is a collapsed line break, michael@0: // remove its child from it." michael@0: // michael@0: // FIXME: IE incorrectly returns false here instead of true michael@0: // sometimes? michael@0: if (node.childNodes.length == 1 michael@0: && isCollapsedLineBreak(node.firstChild)) { michael@0: node.removeChild(node.firstChild); michael@0: } michael@0: michael@0: // "Let text be the result of calling createTextNode(value) on the michael@0: // context object." michael@0: var text = document.createTextNode(value); michael@0: michael@0: // "Call insertNode(text) on the active range." michael@0: getActiveRange().insertNode(text); michael@0: michael@0: // "Call collapse(text, 0) on the context object's Selection." michael@0: getSelection().collapse(text, 0); michael@0: getActiveRange().setStart(text, 0); michael@0: michael@0: // "Call extend(text, 1) on the context object's Selection." michael@0: getSelection().extend(text, 1); michael@0: getActiveRange().setEnd(text, 1); michael@0: } michael@0: michael@0: // "Restore states and values from overrides." michael@0: restoreStatesAndValues(overrides); michael@0: michael@0: // "Canonicalize whitespace at the active range's start, with fix michael@0: // collapsed space false." michael@0: canonicalizeWhitespace(getActiveRange().startContainer, getActiveRange().startOffset, false); michael@0: michael@0: // "Canonicalize whitespace at the active range's end, with fix michael@0: // collapsed space false." michael@0: canonicalizeWhitespace(getActiveRange().endContainer, getActiveRange().endOffset, false); michael@0: michael@0: // "If value is a space character, autolink the active range's start." michael@0: if (/^[ \t\n\f\r]$/.test(value)) { michael@0: autolink(getActiveRange().startContainer, getActiveRange().startOffset); michael@0: } michael@0: michael@0: // "Call collapseToEnd() on the context object's Selection." michael@0: // michael@0: // Work around WebKit bug: sometimes it blows up the selection and michael@0: // throws, which we don't want. michael@0: try { getSelection().collapseToEnd(); } catch(e) {} michael@0: getActiveRange().collapse(false); michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The insertUnorderedList command ///// michael@0: //@{ michael@0: commands.insertunorderedlist = { michael@0: preservesOverrides: true, michael@0: // "Toggle lists with tag name "ul", then return true." michael@0: action: function() { toggleLists("ul"); return true }, michael@0: // "True if the selection's list state is "mixed" or "mixed ul", false michael@0: // otherwise." michael@0: indeterm: function() { return /^mixed( ul)?$/.test(getSelectionListState()) }, michael@0: // "True if the selection's list state is "ul", false otherwise." michael@0: state: function() { return getSelectionListState() == "ul" }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The justifyCenter command ///// michael@0: //@{ michael@0: commands.justifycenter = { michael@0: preservesOverrides: true, michael@0: // "Justify the selection with alignment "center", then return true." michael@0: action: function() { justifySelection("center"); return true }, michael@0: indeterm: function() { michael@0: // "Return false if the active range is null. Otherwise, block-extend michael@0: // the active range. Return true if among visible editable nodes that michael@0: // are contained in the result and have no children, at least one has michael@0: // alignment value "center" and at least one does not. Otherwise return michael@0: // false." michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: return nodes.some(function(node) { return getAlignmentValue(node) == "center" }) michael@0: && nodes.some(function(node) { return getAlignmentValue(node) != "center" }); michael@0: }, state: function() { michael@0: // "Return false if the active range is null. Otherwise, block-extend michael@0: // the active range. Return true if there is at least one visible michael@0: // editable node that is contained in the result and has no children, michael@0: // and all such nodes have alignment value "center". Otherwise return michael@0: // false." michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: return nodes.length michael@0: && nodes.every(function(node) { return getAlignmentValue(node) == "center" }); michael@0: }, value: function() { michael@0: // "Return the empty string if the active range is null. Otherwise, michael@0: // block-extend the active range, and return the alignment value of the michael@0: // first visible editable node that is contained in the result and has michael@0: // no children. If there is no such node, return "left"." michael@0: if (!getActiveRange()) { michael@0: return ""; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: if (nodes.length) { michael@0: return getAlignmentValue(nodes[0]); michael@0: } else { michael@0: return "left"; michael@0: } michael@0: }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The justifyFull command ///// michael@0: //@{ michael@0: commands.justifyfull = { michael@0: preservesOverrides: true, michael@0: // "Justify the selection with alignment "justify", then return true." michael@0: action: function() { justifySelection("justify"); return true }, michael@0: indeterm: function() { michael@0: // "Return false if the active range is null. Otherwise, block-extend michael@0: // the active range. Return true if among visible editable nodes that michael@0: // are contained in the result and have no children, at least one has michael@0: // alignment value "justify" and at least one does not. Otherwise michael@0: // return false." michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: return nodes.some(function(node) { return getAlignmentValue(node) == "justify" }) michael@0: && nodes.some(function(node) { return getAlignmentValue(node) != "justify" }); michael@0: }, state: function() { michael@0: // "Return false if the active range is null. Otherwise, block-extend michael@0: // the active range. Return true if there is at least one visible michael@0: // editable node that is contained in the result and has no children, michael@0: // and all such nodes have alignment value "justify". Otherwise return michael@0: // false." michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: return nodes.length michael@0: && nodes.every(function(node) { return getAlignmentValue(node) == "justify" }); michael@0: }, value: function() { michael@0: // "Return the empty string if the active range is null. Otherwise, michael@0: // block-extend the active range, and return the alignment value of the michael@0: // first visible editable node that is contained in the result and has michael@0: // no children. If there is no such node, return "left"." michael@0: if (!getActiveRange()) { michael@0: return ""; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: if (nodes.length) { michael@0: return getAlignmentValue(nodes[0]); michael@0: } else { michael@0: return "left"; michael@0: } michael@0: }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The justifyLeft command ///// michael@0: //@{ michael@0: commands.justifyleft = { michael@0: preservesOverrides: true, michael@0: // "Justify the selection with alignment "left", then return true." michael@0: action: function() { justifySelection("left"); return true }, michael@0: indeterm: function() { michael@0: // "Return false if the active range is null. Otherwise, block-extend michael@0: // the active range. Return true if among visible editable nodes that michael@0: // are contained in the result and have no children, at least one has michael@0: // alignment value "left" and at least one does not. Otherwise return michael@0: // false." michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: return nodes.some(function(node) { return getAlignmentValue(node) == "left" }) michael@0: && nodes.some(function(node) { return getAlignmentValue(node) != "left" }); michael@0: }, state: function() { michael@0: // "Return false if the active range is null. Otherwise, block-extend michael@0: // the active range. Return true if there is at least one visible michael@0: // editable node that is contained in the result and has no children, michael@0: // and all such nodes have alignment value "left". Otherwise return michael@0: // false." michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: return nodes.length michael@0: && nodes.every(function(node) { return getAlignmentValue(node) == "left" }); michael@0: }, value: function() { michael@0: // "Return the empty string if the active range is null. Otherwise, michael@0: // block-extend the active range, and return the alignment value of the michael@0: // first visible editable node that is contained in the result and has michael@0: // no children. If there is no such node, return "left"." michael@0: if (!getActiveRange()) { michael@0: return ""; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: if (nodes.length) { michael@0: return getAlignmentValue(nodes[0]); michael@0: } else { michael@0: return "left"; michael@0: } michael@0: }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The justifyRight command ///// michael@0: //@{ michael@0: commands.justifyright = { michael@0: preservesOverrides: true, michael@0: // "Justify the selection with alignment "right", then return true." michael@0: action: function() { justifySelection("right"); return true }, michael@0: indeterm: function() { michael@0: // "Return false if the active range is null. Otherwise, block-extend michael@0: // the active range. Return true if among visible editable nodes that michael@0: // are contained in the result and have no children, at least one has michael@0: // alignment value "right" and at least one does not. Otherwise return michael@0: // false." michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: return nodes.some(function(node) { return getAlignmentValue(node) == "right" }) michael@0: && nodes.some(function(node) { return getAlignmentValue(node) != "right" }); michael@0: }, state: function() { michael@0: // "Return false if the active range is null. Otherwise, block-extend michael@0: // the active range. Return true if there is at least one visible michael@0: // editable node that is contained in the result and has no children, michael@0: // and all such nodes have alignment value "right". Otherwise return michael@0: // false." michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: return nodes.length michael@0: && nodes.every(function(node) { return getAlignmentValue(node) == "right" }); michael@0: }, value: function() { michael@0: // "Return the empty string if the active range is null. Otherwise, michael@0: // block-extend the active range, and return the alignment value of the michael@0: // first visible editable node that is contained in the result and has michael@0: // no children. If there is no such node, return "left"." michael@0: if (!getActiveRange()) { michael@0: return ""; michael@0: } michael@0: var nodes = getAllContainedNodes(blockExtend(getActiveRange()), function(node) { michael@0: return isEditable(node) && isVisible(node) && !node.hasChildNodes(); michael@0: }); michael@0: if (nodes.length) { michael@0: return getAlignmentValue(nodes[0]); michael@0: } else { michael@0: return "left"; michael@0: } michael@0: }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The outdent command ///// michael@0: //@{ michael@0: commands.outdent = { michael@0: preservesOverrides: true, michael@0: action: function() { michael@0: // "Let items be a list of all lis that are ancestor containers of the michael@0: // range's start and/or end node." michael@0: // michael@0: // It's annoying to get this in tree order using functional stuff michael@0: // without doing getDescendants(document), which is slow, so I do it michael@0: // imperatively. michael@0: var items = []; michael@0: (function(){ michael@0: for ( michael@0: var ancestorContainer = getActiveRange().endContainer; michael@0: ancestorContainer != getActiveRange().commonAncestorContainer; michael@0: ancestorContainer = ancestorContainer.parentNode michael@0: ) { michael@0: if (isHtmlElement(ancestorContainer, "li")) { michael@0: items.unshift(ancestorContainer); michael@0: } michael@0: } michael@0: for ( michael@0: var ancestorContainer = getActiveRange().startContainer; michael@0: ancestorContainer; michael@0: ancestorContainer = ancestorContainer.parentNode michael@0: ) { michael@0: if (isHtmlElement(ancestorContainer, "li")) { michael@0: items.unshift(ancestorContainer); michael@0: } michael@0: } michael@0: })(); michael@0: michael@0: // "For each item in items, normalize sublists of item." michael@0: items.forEach(normalizeSublists); michael@0: michael@0: // "Block-extend the active range, and let new range be the result." michael@0: var newRange = blockExtend(getActiveRange()); michael@0: michael@0: // "Let node list be a list of nodes, initially empty." michael@0: // michael@0: // "For each node node contained in new range, append node to node list michael@0: // if the last member of node list (if any) is not an ancestor of node; michael@0: // node is editable; and either node has no editable descendants, or is michael@0: // an ol or ul, or is an li whose parent is an ol or ul." michael@0: var nodeList = getContainedNodes(newRange, function(node) { michael@0: return isEditable(node) michael@0: && (!getDescendants(node).some(isEditable) michael@0: || isHtmlElement(node, ["ol", "ul"]) michael@0: || (isHtmlElement(node, "li") && isHtmlElement(node.parentNode, ["ol", "ul"]))); michael@0: }); michael@0: michael@0: // "While node list is not empty:" michael@0: while (nodeList.length) { michael@0: // "While the first member of node list is an ol or ul or is not michael@0: // the child of an ol or ul, outdent it and remove it from node michael@0: // list." michael@0: while (nodeList.length michael@0: && (isHtmlElement(nodeList[0], ["OL", "UL"]) michael@0: || !isHtmlElement(nodeList[0].parentNode, ["OL", "UL"]))) { michael@0: outdentNode(nodeList.shift()); michael@0: } michael@0: michael@0: // "If node list is empty, break from these substeps." michael@0: if (!nodeList.length) { michael@0: break; michael@0: } michael@0: michael@0: // "Let sublist be a list of nodes, initially empty." michael@0: var sublist = []; michael@0: michael@0: // "Remove the first member of node list and append it to sublist." michael@0: sublist.push(nodeList.shift()); michael@0: michael@0: // "While the first member of node list is the nextSibling of the michael@0: // last member of sublist, and the first member of node list is not michael@0: // an ol or ul, remove the first member of node list and append it michael@0: // to sublist." michael@0: while (nodeList.length michael@0: && nodeList[0] == sublist[sublist.length - 1].nextSibling michael@0: && !isHtmlElement(nodeList[0], ["OL", "UL"])) { michael@0: sublist.push(nodeList.shift()); michael@0: } michael@0: michael@0: // "Record the values of sublist, and let values be the result." michael@0: var values = recordValues(sublist); michael@0: michael@0: // "Split the parent of sublist, with new parent null." michael@0: splitParent(sublist); michael@0: michael@0: // "Fix disallowed ancestors of each member of sublist." michael@0: sublist.forEach(fixDisallowedAncestors); michael@0: michael@0: // "Restore the values from values." michael@0: restoreValues(values); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: michael@0: ////////////////////////////////// michael@0: ///// Miscellaneous commands ///// michael@0: ////////////////////////////////// michael@0: michael@0: ///// The defaultParagraphSeparator command ///// michael@0: //@{ michael@0: commands.defaultparagraphseparator = { michael@0: action: function(value) { michael@0: // "Let value be converted to ASCII lowercase. If value is then equal michael@0: // to "p" or "div", set the context object's default single-line michael@0: // container name to value and return true. Otherwise, return false." michael@0: value = value.toLowerCase(); michael@0: if (value == "p" || value == "div") { michael@0: defaultSingleLineContainerName = value; michael@0: return true; michael@0: } michael@0: return false; michael@0: }, value: function() { michael@0: // "Return the context object's default single-line container name." michael@0: return defaultSingleLineContainerName; michael@0: }, michael@0: }; michael@0: michael@0: //@} michael@0: ///// The selectAll command ///// michael@0: //@{ michael@0: commands.selectall = { michael@0: // Note, this ignores the whole globalRange/getActiveRange() thing and michael@0: // works with actual selections. Not suitable for autoimplementation.html. michael@0: action: function() { michael@0: // "Let target be the body element of the context object." michael@0: var target = document.body; michael@0: michael@0: // "If target is null, let target be the context object's michael@0: // documentElement." michael@0: if (!target) { michael@0: target = document.documentElement; michael@0: } michael@0: michael@0: // "If target is null, call getSelection() on the context object, and michael@0: // call removeAllRanges() on the result." michael@0: if (!target) { michael@0: getSelection().removeAllRanges(); michael@0: michael@0: // "Otherwise, call getSelection() on the context object, and call michael@0: // selectAllChildren(target) on the result." michael@0: } else { michael@0: getSelection().selectAllChildren(target); michael@0: } michael@0: michael@0: // "Return true." michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The styleWithCSS command ///// michael@0: //@{ michael@0: commands.stylewithcss = { michael@0: action: function(value) { michael@0: // "If value is an ASCII case-insensitive match for the string michael@0: // "false", set the CSS styling flag to false. Otherwise, set the michael@0: // CSS styling flag to true. Either way, return true." michael@0: cssStylingFlag = String(value).toLowerCase() != "false"; michael@0: return true; michael@0: }, state: function() { return cssStylingFlag } michael@0: }; michael@0: michael@0: //@} michael@0: ///// The useCSS command ///// michael@0: //@{ michael@0: commands.usecss = { michael@0: action: function(value) { michael@0: // "If value is an ASCII case-insensitive match for the string "false", michael@0: // set the CSS styling flag to true. Otherwise, set the CSS styling michael@0: // flag to false. Either way, return true." michael@0: cssStylingFlag = String(value).toLowerCase() == "false"; michael@0: return true; michael@0: } michael@0: }; michael@0: //@} michael@0: michael@0: // Some final setup michael@0: //@{ michael@0: (function() { michael@0: // Opera 11.50 doesn't implement Object.keys, so I have to make an explicit michael@0: // temporary, which means I need an extra closure to not leak the temporaries michael@0: // into the global namespace. >:( michael@0: var commandNames = []; michael@0: for (var command in commands) { michael@0: commandNames.push(command); michael@0: } michael@0: commandNames.forEach(function(command) { michael@0: // "If a command does not have a relevant CSS property specified, it michael@0: // defaults to null." michael@0: if (!("relevantCssProperty" in commands[command])) { michael@0: commands[command].relevantCssProperty = null; michael@0: } michael@0: michael@0: // "If a command has inline command activated values defined but nothing michael@0: // else defines when it is indeterminate, it is indeterminate if among michael@0: // formattable nodes effectively contained in the active range, there is at michael@0: // least one whose effective command value is one of the given values and michael@0: // at least one whose effective command value is not one of the given michael@0: // values." michael@0: if ("inlineCommandActivatedValues" in commands[command] michael@0: && !("indeterm" in commands[command])) { michael@0: commands[command].indeterm = function() { michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: michael@0: var values = getAllEffectivelyContainedNodes(getActiveRange(), isFormattableNode) michael@0: .map(function(node) { return getEffectiveCommandValue(node, command) }); michael@0: michael@0: var matchingValues = values.filter(function(value) { michael@0: return commands[command].inlineCommandActivatedValues.indexOf(value) != -1; michael@0: }); michael@0: michael@0: return matchingValues.length >= 1 michael@0: && values.length - matchingValues.length >= 1; michael@0: }; michael@0: } michael@0: michael@0: // "If a command has inline command activated values defined, its state is michael@0: // true if either no formattable node is effectively contained in the michael@0: // active range, and the active range's start node's effective command michael@0: // value is one of the given values; or if there is at least one michael@0: // formattable node effectively contained in the active range, and all of michael@0: // them have an effective command value equal to one of the given values." michael@0: if ("inlineCommandActivatedValues" in commands[command]) { michael@0: commands[command].state = function() { michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: michael@0: var nodes = getAllEffectivelyContainedNodes(getActiveRange(), isFormattableNode); michael@0: michael@0: if (nodes.length == 0) { michael@0: return commands[command].inlineCommandActivatedValues michael@0: .indexOf(getEffectiveCommandValue(getActiveRange().startContainer, command)) != -1; michael@0: } else { michael@0: return nodes.every(function(node) { michael@0: return commands[command].inlineCommandActivatedValues michael@0: .indexOf(getEffectiveCommandValue(node, command)) != -1; michael@0: }); michael@0: } michael@0: }; michael@0: } michael@0: michael@0: // "If a command is a standard inline value command, it is indeterminate if michael@0: // among formattable nodes that are effectively contained in the active michael@0: // range, there are two that have distinct effective command values. Its michael@0: // value is the effective command value of the first formattable node that michael@0: // is effectively contained in the active range; or if there is no such michael@0: // node, the effective command value of the active range's start node; or michael@0: // if that is null, the empty string." michael@0: if ("standardInlineValueCommand" in commands[command]) { michael@0: commands[command].indeterm = function() { michael@0: if (!getActiveRange()) { michael@0: return false; michael@0: } michael@0: michael@0: var values = getAllEffectivelyContainedNodes(getActiveRange()) michael@0: .filter(isFormattableNode) michael@0: .map(function(node) { return getEffectiveCommandValue(node, command) }); michael@0: for (var i = 1; i < values.length; i++) { michael@0: if (values[i] != values[i - 1]) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: }; michael@0: michael@0: commands[command].value = function() { michael@0: if (!getActiveRange()) { michael@0: return ""; michael@0: } michael@0: michael@0: var refNode = getAllEffectivelyContainedNodes(getActiveRange(), isFormattableNode)[0]; michael@0: michael@0: if (typeof refNode == "undefined") { michael@0: refNode = getActiveRange().startContainer; michael@0: } michael@0: michael@0: var ret = getEffectiveCommandValue(refNode, command); michael@0: if (ret === null) { michael@0: return ""; michael@0: } michael@0: return ret; michael@0: }; michael@0: } michael@0: michael@0: // "If a command preserves overrides, then before taking its action, the michael@0: // user agent must record current overrides. After taking the action, if michael@0: // the active range is collapsed, it must restore states and values from michael@0: // the recorded list." michael@0: if ("preservesOverrides" in commands[command]) { michael@0: var oldAction = commands[command].action; michael@0: michael@0: commands[command].action = function(value) { michael@0: var overrides = recordCurrentOverrides(); michael@0: var ret = oldAction(value); michael@0: if (getActiveRange().collapsed) { michael@0: restoreStatesAndValues(overrides); michael@0: } michael@0: return ret; michael@0: }; michael@0: } michael@0: }); michael@0: })(); michael@0: //@} michael@0: michael@0: // vim: foldmarker=@{,@} foldmethod=marker