Przeglądaj źródła

Added getPositionedAncestor() helper function with tests.

Aleksander Nowodzinski 9 lat temu
rodzic
commit
c07f0294d7

+ 28 - 0
packages/ckeditor5-utils/src/dom/getpositionedancestor.js

@@ -0,0 +1,28 @@
+/**
+ * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* globals window */
+
+/**
+ * @module utils/dom/getpositionedancestor
+ */
+
+/**
+ * For a given element, returns the nearest ancestor element which CSS position is not "static".
+ *
+ * @param {HTMLElement} element Native DOM element to be checked.
+ * @returns {HTMLElement|null}
+ */
+export default function getPositionedAncestor( element ) {
+	while ( element && element.tagName.toLowerCase() != 'html' ) {
+		if ( window.getComputedStyle( element ).position != 'static' ) {
+			return element;
+		}
+
+		element = element.parentElement;
+	}
+
+	return null;
+}

+ 54 - 0
packages/ckeditor5-utils/tests/dom/getpositionedancestor.js

@@ -0,0 +1,54 @@
+/**
+ * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* global document */
+
+import getPositionedAncestor from 'ckeditor5/utils/dom/getpositionedancestor.js';
+
+describe( 'getPositionedAncestor', () => {
+	let element;
+
+	beforeEach( () => {
+		element = document.createElement( 'a' );
+
+		document.body.appendChild( element );
+	} );
+
+	it( 'should return null when there is no element', () => {
+		expect( getPositionedAncestor() ).to.be.null;
+	} );
+
+	it( 'should return null when there is no parent', () => {
+		expect( getPositionedAncestor( element ) ).to.be.null;
+	} );
+
+	it( 'should consider passed element', () => {
+		element.style.position = 'relative';
+
+		expect( getPositionedAncestor( element ) ).to.equal( element );
+	} );
+
+	it( 'should find the positioned ancestor (direct parent)', () => {
+		const parent = document.createElement( 'div' );
+
+		parent.appendChild( element );
+		document.body.appendChild( parent );
+		parent.style.position = 'absolute';
+
+		expect( getPositionedAncestor( element ) ).to.equal( parent );
+	} );
+
+	it( 'should find the positioned ancestor (far ancestor)', () => {
+		const parentA = document.createElement( 'div' );
+		const parentB = document.createElement( 'div' );
+
+		parentB.appendChild( element );
+		parentA.appendChild( parentB );
+		document.body.appendChild( parentA );
+		parentA.style.position = 'absolute';
+
+		expect( getPositionedAncestor( element ) ).to.equal( parentA );
+	} );
+} );