浏览代码

Changed: getCommonAncestor internals, getAncestors should not return Document object. Docs: fixes.

Szymon Cofalik 9 年之前
父节点
当前提交
9d85f82d97

+ 10 - 4
packages/ckeditor5-utils/src/dom/getancestors.js

@@ -3,16 +3,22 @@
  * For licensing, see LICENSE.md.
  */
 
+/* globals Document */
+
 /**
- * Returns all ancestors of given DOM node, starting from the top-most (root). Includes the given node itself.
+ * Returns all ancestors of given DOM node, starting from the top-most (root). Includes the given node itself. If the
+ * node is a part of `DocumentFragment` that `DocumentFragment` will be returned. In contrary, if the node is
+ * appended to a `Document`, that `Document` will not be returned (algorithms operating on DOM tree care for `Document#documentElement`
+ * at most, which will be returned).
  *
- * @param {Element|Text} node DOM node.
- * @returns {Array.<Node>} Array of given `node` parents.
+ * @param {Node} node DOM node.
+ * @returns {Array.<Node|DocumentFragment>} Array of given `node` parents.
  */
 export default function getAncestors( node ) {
 	const nodes = [];
 
-	while ( node ) {
+	// Do not return Document object since it's not a `Node` and we are interested in `Node`s (and `DocumentFragment`s).
+	while ( node && !( node instanceof Document ) ) {
 		nodes.unshift( node );
 		node = node.parentNode;
 	}

+ 6 - 11
packages/ckeditor5-utils/src/dom/getcommonancestor.js

@@ -10,23 +10,18 @@ import getAncestors from './getancestors.js';
  *
  * @param {Node} nodeA First node.
  * @param {Node} nodeB Second node.
- * @returns {Node|null} Lowest common ancestor of both nodes or `null` if nodes do not have a common ancestor.
+ * @returns {Node|DocumentFragment|Document|null} Lowest common ancestor of both nodes or `null` if nodes do not have a common ancestor.
  */
 export default function getCommonAncestor( nodeA, nodeB ) {
-	if ( nodeA == nodeB ) {
-		return nodeA;
-	}
-
 	const ancestorsA = getAncestors( nodeA );
 	const ancestorsB = getAncestors( nodeB );
 
-	const minLength = Math.min( ancestorsA.length, ancestorsB.length );
+	let i = 0;
 
-	for ( let i = minLength - 1; i >= 0; i-- ) {
-		if ( ancestorsA[ i ] == ancestorsB[ i ] ) {
-			return ancestorsA[ i ];
-		}
+	// It does not matter which array is shorter.
+	while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
+		i++;
 	}
 
-	return null;
+	return i === 0 ? null : ancestorsA[ i - 1 ];
 }

+ 9 - 0
packages/ckeditor5-utils/tests/dom/getparents.js

@@ -26,4 +26,13 @@ describe( 'getParents', () => {
 
 		expect( getAncestors( b ) ).to.deep.equal( [ div, p1, span, b ] );
 	} );
+
+	it( 'should not return document object', () => {
+		const span = createElement( document, 'span' );
+		document.documentElement.appendChild( span );
+
+		const ancestors = getAncestors( span );
+
+		expect( ancestors.includes( document ) ).to.be.false;
+	} );
 } );