Explorar el Código

Merge pull request #174 from ckeditor/t/173

Feature: Created various DOM utilities to allow the view document scroll to the selection. Closes #173.

BREAKING CHANGE: The static `Rect.getViewportRect()` method has been removed. Use `new Rect( window )` instead.
Piotrek Koszuliński hace 8 años
padre
commit
103198e2f7

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

@@ -0,0 +1,28 @@
+/**
+ * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/**
+ * @module utils/dom/getborderwidths
+ */
+
+import global from './global';
+
+/**
+ * Returns an object containing CSS border widths of a specified HTML element.
+ *
+ * @param {HTMLElement} element An element which has CSS borders.
+ * @param {Object} An object containing `top`, `left`, `right` and `bottom` properties
+ * with numerical values of the `border-[top,left,right,bottom]-width` CSS styles.
+ */
+export default function getBorderWidths( element ) {
+	const style = global.window.getComputedStyle( element );
+
+	return {
+		top: parseInt( style.borderTopWidth, 10 ),
+		right: parseInt( style.borderRightWidth, 10 ),
+		bottom: parseInt( style.borderBottomWidth, 10 ),
+		left: parseInt( style.borderLeftWidth, 10 )
+	};
+}

+ 5 - 4
packages/ckeditor5-utils/src/dom/position.js

@@ -10,6 +10,7 @@
 import global from './global';
 import Rect from './rect';
 import getPositionedAncestor from './getpositionedancestor';
+import getBorderWidths from './getborderwidths';
 
 /**
  * Calculates the `position: absolute` coordinates of a given element so it can be positioned with respect to the
@@ -94,7 +95,7 @@ export function getOptimalPosition( { element, target, positions, limiter, fitIn
 		[ name, bestPosition ] = getPosition( positions[ 0 ], targetRect, elementRect );
 	} else {
 		const limiterRect = limiter && new Rect( limiter ).getVisible();
-		const viewportRect = fitInViewport && Rect.getViewportRect();
+		const viewportRect = fitInViewport && new Rect( global.window );
 
 		[ name, bestPosition ] =
 			getBestPosition( positions, targetRect, elementRect, limiterRect, viewportRect ) ||
@@ -107,7 +108,7 @@ export function getOptimalPosition( { element, target, positions, limiter, fitIn
 
 	if ( positionedElementAncestor ) {
 		const ancestorPosition = getAbsoluteRectCoordinates( new Rect( positionedElementAncestor ) );
-		const ancestorComputedStyles = global.window.getComputedStyle( positionedElementAncestor );
+		const ancestorBorderWidths = getBorderWidths( positionedElementAncestor );
 
 		// (https://github.com/ckeditor/ckeditor5-ui-default/issues/126)
 		// If there's some positioned ancestor of the panel, then its `Rect` must be taken into
@@ -129,8 +130,8 @@ export function getOptimalPosition( { element, target, positions, limiter, fitIn
 		// while `position: absolute` positioning does not consider it.
 		// E.g. `{ position: absolute, top: 0, left: 0 }` means upper left corner of the element,
 		// not upper-left corner of its border.
-		left -= parseInt( ancestorComputedStyles.borderLeftWidth, 10 );
-		top -= parseInt( ancestorComputedStyles.borderTopWidth, 10 );
+		left -= ancestorBorderWidths.left;
+		top -= ancestorBorderWidths.top;
 	}
 
 	return { left, top, name };

+ 85 - 20
packages/ckeditor5-utils/src/dom/rect.js

@@ -10,11 +10,12 @@
 import global from './global';
 import isRange from './isrange';
 import isElement from '../lib/lodash/isElement';
+import getBorderWidths from './getborderwidths';
 
 /**
  * A helper class representing a `ClientRect` object, e.g. value returned by
  * the native `object.getBoundingClientRect()` method. Provides a set of methods
- * to manipulate the rect and compare it against other `Rect` instances.
+ * to manipulate the rect and compare it against other rect instances.
  */
 export default class Rect {
 	/**
@@ -26,16 +27,23 @@ export default class Rect {
 	 *		// Rect of a DOM Range.
 	 *		const rectB = new Rect( document.getSelection().getRangeAt( 0 ) );
 	 *
+	 *		// Rect of a window (web browser viewport).
+	 *		const rectC = new Rect( window );
+	 *
 	 *		// Rect out of an object.
-	 *		const rectC = new Rect( { top: 0, right: 10, bottom: 10, left: 0, width: 10, height: 10 } );
+	 *		const rectD = new Rect( { top: 0, right: 10, bottom: 10, left: 0, width: 10, height: 10 } );
 	 *
 	 *		// Rect out of another Rect instance.
-	 *		const rectD = new Rect( rectC );
+	 *		const rectE = new Rect( rectD );
 	 *
 	 *		// Rect out of a ClientRect.
-	 *		const rectE = new Rect( document.body.getClientRects().item( 0 ) );
+	 *		const rectF = new Rect( document.body.getClientRects().item( 0 ) );
+	 *
+	 * **Note**: By default a rect of an HTML element includes its CSS borders and scrollbars (if any)
+	 * ant the rect of a `window` includes scrollbars too. Use {@link #excludeScrollbarsAndBorders}
+	 * to get the inner part of the rect.
 	 *
-	 * @param {HTMLElement|Range|ClientRect|module:utils/dom/rect~Rect|Object} source A source object to create the rect.
+	 * @param {HTMLElement|Range|Window|ClientRect|module:utils/dom/rect~Rect|Object} source A source object to create the rect.
 	 */
 	constructor( source ) {
 		/**
@@ -46,9 +54,9 @@ export default class Rect {
 		 * @member {HTMLElement|Range|ClientRect|module:utils/dom/rect~Rect|Object} #_source
 		 */
 		Object.defineProperty( this, '_source', {
-			// source._source if already the Rect instance
+			// If the source is a Rect instance, copy it's #_source.
 			value: source._source || source,
-			writable: false,
+			writable: true,
 			enumerable: false
 		} );
 
@@ -56,6 +64,17 @@ export default class Rect {
 			copyRectProperties( this, source.getBoundingClientRect() );
 		} else if ( isRange( source ) ) {
 			copyRectProperties( this, Rect.getDomRangeRects( source )[ 0 ] );
+		} else if ( source === global.window ) {
+			const { innerWidth, innerHeight } = global.window;
+
+			copyRectProperties( this, {
+				top: 0,
+				right: innerWidth,
+				bottom: innerHeight,
+				left: 0,
+				width: innerWidth,
+				height: innerHeight
+			} );
 		} else {
 			copyRectProperties( this, source );
 		}
@@ -234,21 +253,67 @@ export default class Rect {
 	}
 
 	/**
-	 * Returns a rect of the web browser viewport.
+	 * Checks if all property values ({@link #top}, {@link #left}, {@link #right},
+	 * {@link #bottom}, {@link #width} and {@link #height}) are the equal in both rect
+	 * instances.
 	 *
-	 * @returns {module:utils/dom/rect~Rect} A viewport rect.
+	 * @param {module:utils/dom/rect~Rect} rect A rect instance to compare with.
+	 * @returns {Boolean} `true` when Rects are equal. `false` otherwise.
 	 */
-	static getViewportRect() {
-		const { innerWidth, innerHeight } = global.window;
-
-		return new Rect( {
-			top: 0,
-			right: innerWidth,
-			bottom: innerHeight,
-			left: 0,
-			width: innerWidth,
-			height: innerHeight
-		} );
+	isEqual( anotherRect ) {
+		for ( const prop of rectProperties ) {
+			if ( this[ prop ] !== anotherRect[ prop ] ) {
+				return false;
+			}
+		}
+
+		return true;
+	}
+
+	/**
+	 * Checks whether a rect fully contains another rect instance.
+	 *
+	 * @param {module:utils/dom/rect~Rect} anotherRect
+	 * @returns {Boolean} `true` if contains, `false` otherwise.
+	 */
+	contains( anotherRect ) {
+		const intersectRect = this.getIntersection( anotherRect );
+
+		return !!( intersectRect && intersectRect.isEqual( anotherRect ) );
+	}
+
+	/**
+	 * Excludes scrollbars and CSS borders from the rect.
+	 *
+	 * * Borders are removed when {@link #_source} is an HTML element.
+	 * * Scrollbars are excluded from HTML elements and the `window`.
+	 *
+	 * @returns {module:utils/dom/rect~Rect} A rect which has been updated.
+	 */
+	excludeScrollbarsAndBorders() {
+		const source = this._source;
+		let scrollBarWidth, scrollBarHeight;
+
+		if ( source === global.window ) {
+			scrollBarWidth = global.window.innerWidth - global.document.documentElement.clientWidth;
+			scrollBarHeight = global.window.innerHeight - global.document.documentElement.clientHeight;
+		} else {
+			const borderWidths = getBorderWidths( this._source );
+
+			scrollBarWidth = source.offsetWidth - source.clientWidth;
+			scrollBarHeight = source.offsetHeight - source.clientHeight;
+
+			this.moveBy( borderWidths.left, borderWidths.top );
+		}
+
+		// Assuming LTR scrollbars. TODO: RTL.
+		this.width -= scrollBarWidth;
+		this.right -= scrollBarWidth;
+
+		this.height -= scrollBarHeight;
+		this.bottom -= scrollBarHeight;
+
+		return this;
 	}
 
 	/**

+ 167 - 0
packages/ckeditor5-utils/src/dom/scroll.js

@@ -0,0 +1,167 @@
+/**
+ * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* global Node */
+
+/**
+ * @module utils/dom/scroll
+ */
+
+import global from './global';
+import isRange from './isrange';
+import Rect from './rect';
+
+const utils = {};
+
+/**
+ * Makes any page `HTMLElement` or `Range` (`target`) visible inside the browser viewport.
+ * This helper will scroll all `target` ancestors and the web browser viewport to reveal the target to
+ * the user. If the `target` is already visible, nothing will happen.
+ *
+ * @param {HTMLElement|Range} options.target A target, which supposed to become visible to the user.
+ * @param {Number} [options.viewportOffset] An offset from the edge of the viewport (in pixels)
+ * the `target` will be moved by when the viewport is scrolled. It enhances the user experience
+ * by keeping the `target` some distance from the edge of the viewport and thus making it easier to
+ * read or edit by the user.
+ */
+export function scrollViewportToShowTarget( { target, viewportOffset = 0 } ) {
+	// Scroll the ancestors of the target to reveal it first, then focus on scrolling
+	// the viewport, when the position of the target is fixed.
+	utils.scrollAncestorsToShowTarget( target );
+
+	const targetRect = new Rect( target );
+	const targetShiftedDownRect = targetRect.clone().moveBy( 0, viewportOffset );
+	const targetShiftedUpRect = targetRect.clone().moveBy( 0, -viewportOffset );
+	const viewportRect = new Rect( global.window ).excludeScrollbarsAndBorders();
+
+	// Avoid the situation where the caret is still in the viewport, but totally
+	// at the edge. If it moved beyond the viewport in the next action e.g. due to enter,
+	// the scrolling would move it to the viewportOffset level and it all would look like the
+	// caret visually moved up/down.
+	//
+	// To prevent this, we're checking the rects moved by the viewportOffset to cover
+	// the upper/lower edge of the viewport.
+	const rects = [ targetShiftedUpRect, targetShiftedDownRect ];
+
+	if ( !rects.every( rect => viewportRect.contains( rect ) ) ) {
+		let { scrollX, scrollY } = global.window;
+
+		if ( isAbove( targetShiftedUpRect, viewportRect ) ) {
+			scrollY -= viewportRect.top - targetRect.top + viewportOffset;
+		} else if ( isBelow( targetShiftedDownRect, viewportRect ) ) {
+			scrollY += targetRect.bottom - viewportRect.bottom + viewportOffset;
+		}
+
+		// TODO: Web browsers scroll natively to place the target in the middle
+		// of the viewport. It's not a very popular case, though.
+		if ( isLeftOf( targetRect, viewportRect ) ) {
+			scrollX -= viewportRect.left - targetRect.left + viewportOffset;
+		} else if ( isRightOf( targetRect, viewportRect ) ) {
+			scrollX += targetRect.right - viewportRect.right + viewportOffset;
+		}
+
+		global.window.scrollTo( scrollX, scrollY );
+	}
+}
+
+/**
+ * Makes any page `HTMLElement` or `Range` (target) visible within its scrollable ancestors,
+ * e.g. if they have `overflow: scroll` CSS style.
+ *
+ * @param {HTMLElement|Range} target A target, which supposed to become visible to the user.
+ */
+export function scrollAncestorsToShowTarget( target ) {
+	let parent, parentRect, targetRect;
+
+	if ( isRange( target ) ) {
+		parent = target.commonAncestorContainer;
+
+		// If a Range is attached to the Text, use the closest element ancestor.
+		if ( parent.nodeType == Node.TEXT_NODE ) {
+			parent = parent.parentNode;
+		}
+	} else {
+		parent = target.parentNode;
+	}
+
+	do {
+		if ( parent === global.document.body ) {
+			return;
+		}
+
+		targetRect = new Rect( target );
+		parentRect = new Rect( parent ).excludeScrollbarsAndBorders();
+
+		if ( !parentRect.contains( targetRect ) ) {
+			scrollAncestorToShowTarget( { targetRect, parent, parentRect } );
+		}
+	} while ( ( parent = parent.parentNode ) );
+}
+
+// TODO: Using a property value shorthand in the top of the file
+// causes JSDoc to throw errors. See https://github.com/cksource/docs-builder/issues/75.
+Object.assign( utils, {
+	scrollViewportToShowTarget,
+	scrollAncestorsToShowTarget
+} );
+
+// For testing purposes (easy helper stubbing).
+export { utils as _test };
+
+// Makes any page `HTMLElement` or `Range` (target) visible within its parent.
+//
+// @private
+// @param {module:utils/dom/rect~Rect} options.targetRect The `Rect` of the `target`.
+// @param {HTMLElement} options.parent The parent element of the `target`.
+// @param {module:utils/dom/rect~Rect} options.parentRect The `Rect` of the parent.
+function scrollAncestorToShowTarget( { targetRect, parent, parentRect } ) {
+	if ( isAbove( targetRect, parentRect ) ) {
+		parent.scrollTop -= parentRect.top - targetRect.top;
+	} else if ( isBelow( targetRect, parentRect ) ) {
+		parent.scrollTop += targetRect.bottom - parentRect.bottom;
+	}
+
+	if ( isLeftOf( targetRect, parentRect ) ) {
+		parent.scrollLeft -= parentRect.left - targetRect.left;
+	} else if ( isRightOf( targetRect, parentRect ) ) {
+		parent.scrollLeft += targetRect.right - parentRect.right;
+	}
+}
+
+// Determines if a given `Rect` extends beyond the bottom edge of the second `Rect`.
+//
+// @private
+// @param {module:utils/dom/rect~Rect} firstRect
+// @param {module:utils/dom/rect~Rect} secondRect
+function isBelow( firstRect, secondRect ) {
+	return firstRect.bottom > secondRect.bottom;
+}
+
+// Determines if a given `Rect` extends beyond the top edge of the second `Rect`.
+//
+// @private
+// @param {module:utils/dom/rect~Rect} firstRect
+// @param {module:utils/dom/rect~Rect} secondRect
+function isAbove( firstRect, secondRect ) {
+	return firstRect.top < secondRect.top;
+}
+
+// Determines if a given `Rect` extends beyond the left edge of the second `Rect`.
+//
+// @private
+// @param {module:utils/dom/rect~Rect} firstRect
+// @param {module:utils/dom/rect~Rect} secondRect
+function isLeftOf( firstRect, secondRect ) {
+	return firstRect.left < secondRect.left;
+}
+
+// Determines if a given `Rect` extends beyond the right edge of the second `Rect`.
+//
+// @private
+// @param {module:utils/dom/rect~Rect} firstRect
+// @param {module:utils/dom/rect~Rect} secondRect
+function isRightOf( firstRect, secondRect ) {
+	return firstRect.right > secondRect.right;
+}

+ 30 - 0
packages/ckeditor5-utils/tests/dom/getborderwidths.js

@@ -0,0 +1,30 @@
+/**
+ * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+import global from '../../src/dom/global';
+import getBorderWidths from '../../src/dom/getborderwidths';
+import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils';
+
+testUtils.createSinonSandbox();
+
+describe( 'getBorderWidths()', () => {
+	it( 'returns CSS border widths', () => {
+		testUtils.sinon.stub( global.window, 'getComputedStyle' ).returns( {
+			borderTopWidth: '10px',
+			borderRightWidth: '20px',
+			borderBottomWidth: '30px',
+			borderLeftWidth: '40px'
+		} );
+
+		const elementMock = {};
+
+		expect( getBorderWidths( elementMock ) ).to.deep.equal( {
+			top: 10,
+			right: 20,
+			bottom: 30,
+			left: 40
+		} );
+	} );
+} );

+ 211 - 9
packages/ckeditor5-utils/tests/dom/rect.js

@@ -77,6 +77,24 @@ describe( 'Rect', () => {
 			assertRect( new Rect( range ), expectedGeometry );
 		} );
 
+		it( 'should accept the window (viewport)', () => {
+			testUtils.sinon.stub( global, 'window' ).value( {
+				innerWidth: 1000,
+				innerHeight: 500,
+				scrollX: 100,
+				scrollY: 200
+			} );
+
+			assertRect( new Rect( global.window ), {
+				top: 0,
+				right: 1000,
+				bottom: 500,
+				left: 0,
+				width: 1000,
+				height: 500
+			} );
+		} );
+
 		it( 'should accept Rect', () => {
 			const sourceRect = new Rect( geometry );
 			const rect = new Rect( sourceRect );
@@ -562,12 +580,189 @@ describe( 'Rect', () => {
 		} );
 	} );
 
-	describe( 'getViewportRect()', () => {
-		it( 'should reaturn a rect', () => {
-			expect( Rect.getViewportRect() ).to.be.instanceOf( Rect );
+	describe( 'isEqual()', () => {
+		it( 'returns `true` when rects are equal', () => {
+			const rectA = new Rect( {
+				top: 10,
+				right: 20,
+				bottom: 30,
+				left: 40,
+				width: 10,
+				height: 20
+			} );
+
+			const rectB = new Rect( {
+				top: 10,
+				right: 20,
+				bottom: 30,
+				left: 40,
+				width: 10,
+				height: 20
+			} );
+
+			expect( rectA.isEqual( rectB ) ).to.be.true;
+			expect( rectB.isEqual( rectA ) ).to.be.true;
+			expect( rectA.isEqual( rectA ) ).to.be.true;
+		} );
+
+		it( 'returns `false` when rects are different', () => {
+			const rectA = new Rect( {
+				top: 10,
+				right: 20,
+				bottom: 30,
+				left: 40,
+				width: 10,
+				height: 20
+			} );
+
+			const rectB = new Rect( {
+				top: 10,
+				right: 20,
+				bottom: 30,
+				left: 40,
+				width: 10,
+				height: 30 // !
+			} );
+
+			expect( rectA.isEqual( rectB ) ).to.be.false;
+			expect( rectB.isEqual( rectA ) ).to.be.false;
+		} );
+	} );
+
+	describe( 'contains()', () => {
+		it( 'should return true if rects are the same', () => {
+			const rectA = new Rect( {
+				top: 0,
+				right: 100,
+				bottom: 100,
+				left: 0,
+				width: 100,
+				height: 100
+			} );
+
+			const rectB = new Rect( {
+				top: 0,
+				right: 100,
+				bottom: 100,
+				left: 0,
+				width: 100,
+				height: 100
+			} );
+
+			expect( rectA.isEqual( rectB ) ).to.be.true;
+			expect( rectA.contains( rectB ) ).to.be.true;
+			expect( rectB.contains( rectA ) ).to.be.true;
+		} );
+
+		it( 'should return true if rect is within', () => {
+			const rectA = new Rect( {
+				top: 0,
+				right: 100,
+				bottom: 100,
+				left: 0,
+				width: 100,
+				height: 100
+			} );
+
+			const rectB = new Rect( {
+				top: 10,
+				right: 90,
+				bottom: 90,
+				left: 10,
+				width: 80,
+				height: 80
+			} );
+
+			expect( rectA.contains( rectB ) ).to.be.true;
+			expect( rectB.contains( rectA ) ).to.be.false;
+		} );
+
+		it( 'should return false if rect extends beyond the boundaries', () => {
+			const rectA = new Rect( {
+				top: 0,
+				right: 100,
+				bottom: 100,
+				left: 0,
+				width: 100,
+				height: 100
+			} );
+
+			const rectB = new Rect( {
+				top: 10,
+				right: 100,
+				bottom: 110,
+				left: 0,
+				width: 100,
+				height: 100
+			} );
+
+			expect( rectA.contains( rectB ) ).to.be.false;
+			expect( rectB.contains( rectA ) ).to.be.false;
 		} );
 
-		it( 'should return the viewport\'s rect', () => {
+		it( 'should return false if rect is completely beyond the boundaries', () => {
+			const rectA = new Rect( {
+				top: 0,
+				right: 100,
+				bottom: 100,
+				left: 0,
+				width: 100,
+				height: 100
+			} );
+
+			const rectB = new Rect( {
+				top: 110,
+				right: 100,
+				bottom: 210,
+				left: 0,
+				width: 100,
+				height: 100
+			} );
+
+			expect( rectA.contains( rectB ) ).to.be.false;
+			expect( rectB.contains( rectA ) ).to.be.false;
+		} );
+	} );
+
+	describe( 'excludeScrollbarsAndBorders()', () => {
+		it( 'should exclude scrollbars and borders of a HTMLElement', () => {
+			const element = document.createElement( 'div' );
+
+			testUtils.sinon.stub( element, 'getBoundingClientRect' ).returns( geometry );
+			testUtils.sinon.stub( global.window, 'getComputedStyle' ).returns( {
+				borderTopWidth: '5px',
+				borderRightWidth: '10px',
+				borderLeftWidth: '5px',
+				borderBottomWidth: '10px'
+			} );
+
+			// Simulate 5px srollbars.
+			Object.defineProperties( element, {
+				offsetWidth: {
+					value: 20
+				},
+				offsetHeight: {
+					value: 20
+				},
+				clientWidth: {
+					value: 10
+				},
+				clientHeight: {
+					value: 10
+				}
+			} );
+
+			assertRect( new Rect( element ).excludeScrollbarsAndBorders(), {
+				top: 15,
+				right: 35,
+				bottom: 25,
+				left: 25,
+				width: 10,
+				height: 10
+			} );
+		} );
+
+		it( 'should exclude scrollbars from viewport\'s rect', () => {
 			testUtils.sinon.stub( global, 'window' ).value( {
 				innerWidth: 1000,
 				innerHeight: 500,
@@ -575,13 +770,20 @@ describe( 'Rect', () => {
 				scrollY: 200
 			} );
 
-			assertRect( Rect.getViewportRect(), {
+			testUtils.sinon.stub( global, 'document' ).value( {
+				documentElement: {
+					clientWidth: 990,
+					clientHeight: 490
+				}
+			} );
+
+			assertRect( new Rect( global.window ).excludeScrollbarsAndBorders(), {
 				top: 0,
-				right: 1000,
-				bottom: 500,
+				right: 990,
+				bottom: 490,
 				left: 0,
-				width: 1000,
-				height: 500
+				width: 990,
+				height: 490
 			} );
 		} );
 	} );

+ 455 - 0
packages/ckeditor5-utils/tests/dom/scroll.js

@@ -0,0 +1,455 @@
+/**
+ * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* global document, Text */
+
+import global from '../../src/dom/global';
+import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils';
+import isRange from '../../src/dom/isrange';
+import { scrollViewportToShowTarget, scrollAncestorsToShowTarget, _test } from '../../src/dom/scroll';
+
+testUtils.createSinonSandbox();
+
+describe( 'scrollAncestorsToShowTarget()', () => {
+	let target, element, firstAncestor, secondAncestor, body;
+
+	beforeEach( () => {
+		element = document.createElement( 'p' );
+		firstAncestor = document.createElement( 'blockquote' );
+		secondAncestor = document.createElement( 'div' );
+		body = document.createElement( 'div' );
+
+		testUtils.sinon.stub( global, 'document' ).value( { body } );
+
+		document.body.appendChild( body );
+		body.appendChild( secondAncestor );
+		secondAncestor.appendChild( firstAncestor );
+		firstAncestor.appendChild( element );
+
+		// Make the element immune to the border-width-* styles in the test environment.
+		testUtils.sinon.stub( global.window, 'getComputedStyle' ).returns( {
+			borderTopWidth: '0px',
+			borderRightWidth: '0px',
+			borderBottomWidth: '0px',
+			borderLeftWidth: '0px'
+		} );
+
+		stubRect( firstAncestor, {
+			top: 0, right: 100, bottom: 100, left: 0, width: 100, height: 100
+		}, {
+			scrollLeft: 100, scrollTop: 100
+		} );
+
+		stubRect( secondAncestor, {
+			top: -100, right: 0, bottom: 0, left: -100, width: 100, height: 100
+		}, {
+			scrollLeft: 100, scrollTop: 100
+		} );
+
+		stubRect( body, {
+			top: 1000, right: 2000, bottom: 1000, left: 1000, width: 1000, height: 1000
+		}, {
+			scrollLeft: 1000, scrollTop: 1000
+		} );
+	} );
+
+	afterEach( () => {
+		body.remove();
+	} );
+
+	describe( 'for an HTMLElement', () => {
+		beforeEach( () => {
+			target = element;
+		} );
+
+		test();
+	} );
+
+	describe( 'for a DOM Range', () => {
+		beforeEach( () => {
+			target = document.createRange();
+			target.setStart( firstAncestor, 0 );
+			target.setEnd( firstAncestor, 0 );
+		} );
+
+		test();
+
+		it( 'should set #scrollTop and #scrollLeft of the ancestor to show the target (above, attached to the Text)', () => {
+			const text = new Text( 'foo' );
+			firstAncestor.appendChild( text );
+			target.setStart( text, 1 );
+			target.setEnd( text, 2 );
+
+			stubRect( target, { top: -100, right: 75, bottom: 0, left: 25, width: 50, height: 100 } );
+
+			scrollAncestorsToShowTarget( target );
+			assertScrollPosition( firstAncestor, { scrollTop: 0, scrollLeft: 100 } );
+		} );
+	} );
+
+	function test() {
+		it( 'should not touch the #scrollTop #scrollLeft of the ancestor if target is visible', () => {
+			stubRect( target, { top: 25, right: 75, bottom: 75, left: 25, width: 50, height: 50 } );
+
+			scrollAncestorsToShowTarget( target );
+			assertScrollPosition( firstAncestor, { scrollLeft: 100, scrollTop: 100 } );
+		} );
+
+		it( 'should not touch the #scrollTop #scrollLeft of the document.body', () => {
+			stubRect( target, { top: 25, right: 75, bottom: 75, left: 25, width: 50, height: 50 } );
+
+			scrollAncestorsToShowTarget( target );
+			assertScrollPosition( body, { scrollLeft: 1000, scrollTop: 1000 } );
+		} );
+
+		it( 'should set #scrollTop and #scrollLeft of the ancestor to show the target (above)', () => {
+			stubRect( target, { top: -100, right: 75, bottom: 0, left: 25, width: 50, height: 100 } );
+
+			scrollAncestorsToShowTarget( target );
+			assertScrollPosition( firstAncestor, { scrollTop: 0, scrollLeft: 100 } );
+		} );
+
+		it( 'should set #scrollTop and #scrollLeft of the ancestor to show the target (below)', () => {
+			stubRect( target, { top: 200, right: 75, bottom: 300, left: 25, width: 50, height: 100 } );
+
+			scrollAncestorsToShowTarget( target );
+			assertScrollPosition( firstAncestor, { scrollTop: 300, scrollLeft: 100 } );
+		} );
+
+		it( 'should set #scrollTop and #scrollLeft of the ancestor to show the target (left of)', () => {
+			stubRect( target, { top: 0, right: 0, bottom: 100, left: -100, width: 100, height: 100 } );
+
+			scrollAncestorsToShowTarget( target );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 0 } );
+		} );
+
+		it( 'should set #scrollTop and #scrollLeft of the ancestor to show the target (right of)', () => {
+			stubRect( target, { top: 0, right: 200, bottom: 100, left: 100, width: 100, height: 100 } );
+
+			scrollAncestorsToShowTarget( target );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 200 } );
+		} );
+
+		it( 'should set #scrollTop and #scrollLeft of all the ancestors', () => {
+			stubRect( target, { top: 0, right: 200, bottom: 100, left: 100, width: 100, height: 100 } );
+
+			scrollAncestorsToShowTarget( target );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 200 } );
+			// Note: Because everything is a mock, scrolling the firstAncestor doesn't really change
+			// the getBoundingClientRect geometry of the target. That's why scrolling secondAncestor
+			// works like the target remained in the original position and hence scrollLeft is 300 instead
+			// of 200.
+			assertScrollPosition( secondAncestor, { scrollTop: 200, scrollLeft: 300 } );
+		} );
+	}
+} );
+
+describe( 'scrollViewportToShowTarget()', () => {
+	let target, firstAncestor, element;
+	const viewportOffset = 30;
+
+	beforeEach( () => {
+		element = document.createElement( 'p' );
+		firstAncestor = document.createElement( 'blockquote' );
+
+		document.body.appendChild( firstAncestor );
+		firstAncestor.appendChild( element );
+
+		stubRect( firstAncestor, {
+			top: 0, right: 100, bottom: 100, left: 0, width: 100, height: 100
+		}, {
+			scrollLeft: 100, scrollTop: 100
+		} );
+
+		testUtils.sinon.stub( global, 'window' ).value( {
+			innerWidth: 1000,
+			innerHeight: 500,
+			scrollX: 100,
+			scrollY: 100,
+			scrollTo: sinon.spy(),
+			getComputedStyle: () => ( {
+				borderTopWidth: '0px',
+				borderRightWidth: '0px',
+				borderBottomWidth: '0px',
+				borderLeftWidth: '0px'
+			} )
+		} );
+
+		// Assuming 20px v- and h-scrollbars here.
+		testUtils.sinon.stub( global, 'document' ).value( {
+			body: document.body,
+			documentElement: {
+				clientWidth: 980,
+				clientHeight: 480
+			}
+		} );
+	} );
+
+	afterEach( () => {
+		firstAncestor.remove();
+	} );
+
+	describe( 'for an HTMLElement', () => {
+		beforeEach( () => {
+			target = element;
+		} );
+
+		testNoOffset();
+
+		describe( 'with a viewportOffset', () => {
+			testWithOffset();
+		} );
+	} );
+
+	describe( 'for a DOM Range', () => {
+		beforeEach( () => {
+			target = document.createRange();
+			target.setStart( firstAncestor, 0 );
+			target.setEnd( firstAncestor, 0 );
+		} );
+
+		testNoOffset();
+
+		describe( 'with a viewportOffset', () => {
+			testWithOffset();
+		} );
+	} );
+
+	// Note: Because everything is a mock, scrolling the firstAncestor doesn't really change
+	// the getBoundingClientRect geometry of the target. That's why scrolling the viewport
+	// works like the target remained in the original position. It's tricky but much faster
+	// and still shows that the whole thing works as expected.
+	//
+	// Note: Negative scrollTo arguments make no sense in reality, but in mocks with arbitrary
+	// initial geometry and scroll position they give the right, relative picture of what's going on.
+	function testNoOffset() {
+		it( 'calls scrollAncestorsToShowTarget first', () => {
+			const spy = testUtils.sinon.stub( _test, 'scrollAncestorsToShowTarget' );
+
+			stubRect( target, { top: -200, right: 200, bottom: -100, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			sinon.assert.calledOnce( spy );
+			sinon.assert.calledWithExactly( spy, target );
+		} );
+
+		it( 'does not scroll the viewport when the target is fully visible', () => {
+			stubRect( target, { top: 0, right: 200, bottom: 100, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 200 } );
+			sinon.assert.notCalled( global.window.scrollTo );
+		} );
+
+		it( 'scrolls the viewport to show the target (above)', () => {
+			stubRect( target, { top: -200, right: 200, bottom: -100, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			assertScrollPosition( firstAncestor, { scrollTop: -100, scrollLeft: 200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 100, -100 );
+		} );
+
+		it( 'scrolls the viewport to show the target (partially above)', () => {
+			stubRect( target, { top: -50, right: 200, bottom: 50, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			assertScrollPosition( firstAncestor, { scrollTop: 50, scrollLeft: 200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 100, 50 );
+		} );
+
+		it( 'scrolls the viewport to show the target (below)', () => {
+			stubRect( target, { top: 600, right: 200, bottom: 700, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			assertScrollPosition( firstAncestor, { scrollTop: 700, scrollLeft: 200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 100, 320 );
+		} );
+
+		it( 'scrolls the viewport to show the target (partially below)', () => {
+			stubRect( target, { top: 450, right: 200, bottom: 550, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			assertScrollPosition( firstAncestor, { scrollTop: 550, scrollLeft: 200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 100, 170 );
+		} );
+
+		it( 'scrolls the viewport to show the target (to the left)', () => {
+			stubRect( target, { top: 0, right: -100, bottom: 100, left: -200, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: -100 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, -100, 100 );
+		} );
+
+		it( 'scrolls the viewport to show the target (partially to the left)', () => {
+			stubRect( target, { top: 0, right: 50, bottom: 100, left: -50, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 50 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 50, 100 );
+		} );
+
+		it( 'scrolls the viewport to show the target (to the right)', () => {
+			stubRect( target, { top: 0, right: 1200, bottom: 100, left: 1100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 1200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 320, 100 );
+		} );
+
+		it( 'scrolls the viewport to show the target (partially to the right)', () => {
+			stubRect( target, { top: 0, right: 1050, bottom: 100, left: 950, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target } );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 1050 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 170, 100 );
+		} );
+	}
+
+	// Note: Because everything is a mock, scrolling the firstAncestor doesn't really change
+	// the getBoundingClientRect geometry of the target. That's why scrolling the viewport
+	// works like the target remained in the original position. It's tricky but much faster
+	// and still shows that the whole thing works as expected.
+	//
+	// Note: Negative scrollTo arguments make no sense in reality, but in mocks with arbitrary
+	// initial geometry and scroll position they give the right, relative picture of what's going on.
+	function testWithOffset() {
+		it( 'calls scrollAncestorsToShowTarget first', () => {
+			const spy = testUtils.sinon.stub( _test, 'scrollAncestorsToShowTarget' );
+
+			stubRect( target, { top: -200, right: 200, bottom: -100, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			sinon.assert.calledOnce( spy );
+			sinon.assert.calledWithExactly( spy, target );
+		} );
+
+		it( 'does not scroll the viewport when the target is fully visible', () => {
+			stubRect( target, { top: 50, right: 200, bottom: 150, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			assertScrollPosition( firstAncestor, { scrollTop: 150, scrollLeft: 200 } );
+			sinon.assert.notCalled( global.window.scrollTo );
+		} );
+
+		it( 'scrolls the viewport to show the target (above)', () => {
+			stubRect( target, { top: -200, right: 200, bottom: -100, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			assertScrollPosition( firstAncestor, { scrollTop: -100, scrollLeft: 200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 100, -130 );
+		} );
+
+		it( 'scrolls the viewport to show the target (partially above)', () => {
+			stubRect( target, { top: -50, right: 200, bottom: 50, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			assertScrollPosition( firstAncestor, { scrollTop: 50, scrollLeft: 200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 100, 20 );
+		} );
+
+		it( 'scrolls the viewport to show the target (below)', () => {
+			stubRect( target, { top: 600, right: 200, bottom: 700, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			assertScrollPosition( firstAncestor, { scrollTop: 700, scrollLeft: 200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 100, 350 );
+		} );
+
+		it( 'scrolls the viewport to show the target (partially below)', () => {
+			stubRect( target, { top: 450, right: 200, bottom: 550, left: 100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			assertScrollPosition( firstAncestor, { scrollTop: 550, scrollLeft: 200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 100, 200 );
+		} );
+
+		it( 'scrolls the viewport to show the target (to the left)', () => {
+			stubRect( target, { top: 0, right: -100, bottom: 100, left: -200, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: -100 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, -130, 70 );
+		} );
+
+		it( 'scrolls the viewport to show the target (partially to the left)', () => {
+			stubRect( target, { top: 0, right: 50, bottom: 100, left: -50, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 50 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 20, 70 );
+		} );
+
+		it( 'scrolls the viewport to show the target (to the right)', () => {
+			stubRect( target, { top: 0, right: 1200, bottom: 100, left: 1100, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 1200 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 350, 70 );
+		} );
+
+		it( 'scrolls the viewport to show the target (partially to the right)', () => {
+			stubRect( target, { top: 0, right: 1050, bottom: 100, left: 950, width: 100, height: 100 } );
+
+			scrollViewportToShowTarget( { target, viewportOffset } );
+			assertScrollPosition( firstAncestor, { scrollTop: 100, scrollLeft: 1050 } );
+			sinon.assert.calledWithExactly( global.window.scrollTo, 200, 70 );
+		} );
+	}
+} );
+
+function stubRect( target, geometryStub, scrollStub ) {
+	if ( isRange( target ) ) {
+		testUtils.sinon.stub( target, 'getClientRects' ).returns( [ geometryStub ] );
+	} else {
+		testUtils.sinon.stub( target, 'getBoundingClientRect' ).returns( geometryStub );
+
+		// Make the element immune to the border-width-* styles in the test environment.
+		Object.defineProperties( target, {
+			offsetWidth: {
+				value: geometryStub.width
+			},
+			clientWidth: {
+				value: geometryStub.width
+			},
+			offsetHeight: {
+				value: geometryStub.height
+			},
+			clientHeight: {
+				value: geometryStub.height
+			}
+		} );
+	}
+
+	if ( scrollStub ) {
+		let { scrollLeft, scrollTop } = scrollStub;
+
+		// There's no way to stub scrollLeft|Top with Sinon. defineProperties
+		// must be used instead.
+		Object.defineProperties( target, {
+			scrollLeft: {
+				get() {
+					return scrollLeft;
+				},
+				set( value ) {
+					scrollLeft = value;
+				}
+			},
+			scrollTop: {
+				get() {
+					return scrollTop;
+				},
+				set( value ) {
+					scrollTop = value;
+				}
+			}
+		} );
+	}
+}
+
+function assertScrollPosition( element, expected ) {
+	expect( element.scrollTop ).to.equal( expected.scrollTop, 'scrollTop' );
+	expect( element.scrollLeft ).to.equal( expected.scrollLeft, 'scrollLeft' );
+}

+ 107 - 0
packages/ckeditor5-utils/tests/manual/scroll/scroll.html

@@ -0,0 +1,107 @@
+<p>
+	<button id="scrollToBlue">Go to blue</button>
+</p>
+
+<div id="target-blue" class="test-box">
+	<div class="test-box">
+		<div class="test-box">
+			<div class="target">
+				<button>Go to red</button>
+			</div>
+		</div>
+	</div>
+</div>
+
+<div id="target-red" class="test-box">
+	<div class="test-box">
+		<div class="test-box">
+			<div class="target">
+				<button>Go to green</button>
+			</div>
+		</div>
+	</div>
+</div>
+
+<div id="target-green" class="test-box">
+	<div class="test-box">
+		<div class="test-box">
+			<div class="target">
+				<button>Go to blue</button>
+			</div>
+		</div>
+	</div>
+</div>
+
+<style>
+	body {
+		height: 2000px;
+		width: 2000px;
+	}
+
+	body > .test-box {
+		position: absolute;
+	}
+
+	.test-box {
+		background: #fff;
+		padding: 15px;
+		border: 25px solid #eee;
+		overflow: scroll;
+		position: relative;
+	}
+
+	.test-box > .test-box {
+		margin-top: 1000px;
+		margin-bottom: 1000px;
+		height: 400px;
+		width: 400px;
+	}
+
+	.test-box > .test-box > .test-box {
+		height: 800px;
+		width: 800px;
+	}
+
+	.target {
+		width: 80px;
+		height: 80px;
+		position: absolute;
+		bottom: 0;
+		right: 0;
+		color: #fff;
+	}
+
+	#target-blue .target {
+		background: blue;
+	}
+
+	#target-red .target {
+		background: red;
+	}
+
+	#target-green .target {
+		background: green;
+	}
+
+	#target-blue,
+	#target-red,
+	#target-green {
+		width: 100px;
+		height: 100px;
+	}
+
+	#target-blue {
+		left: 1500px;
+		top: 1500px;
+	}
+
+	#target-red {
+		left: 1200px;
+		top: 100px;
+	}
+
+	#target-green {
+		left: 500px;
+		top: 1300px;
+	}
+</style>

+ 32 - 0
packages/ckeditor5-utils/tests/manual/scroll/scroll.js

@@ -0,0 +1,32 @@
+/**
+ * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* global document */
+
+import { scrollViewportToShowTarget } from '@ckeditor/ckeditor5-utils/src/dom/scroll';
+
+document.getElementById( 'scrollToBlue' ).addEventListener( 'click', () => {
+	const target = document.querySelector( '#target-blue .target' );
+
+	scrollViewportToShowTarget( { target } );
+} );
+
+document.querySelector( '#target-blue button' ).addEventListener( 'click', () => {
+	const target = document.querySelector( '#target-red .target' );
+
+	scrollViewportToShowTarget( { target } );
+} );
+
+document.querySelector( '#target-red button' ).addEventListener( 'click', () => {
+	const target = document.querySelector( '#target-green .target' );
+
+	scrollViewportToShowTarget( { target } );
+} );
+
+document.querySelector( '#target-green button' ).addEventListener( 'click', () => {
+	const target = document.querySelector( '#target-blue .target' );
+
+	scrollViewportToShowTarget( { target } );
+} );

+ 21 - 0
packages/ckeditor5-utils/tests/manual/scroll/scroll.md

@@ -0,0 +1,21 @@
+## scrollViewportToShowTarget() helper
+
+1. Click the "Go to blue" button.
+
+**Expected:** The viewport is scrolled to **fully** reveal the 80x80px blue square in the bottom-right corner.
+
+2. Scroll the **viewport** right and down just a little bit.
+3. Make sure the blue square is right in the **bottom-right corner** of the topmost div containing it. **There should be only one set of scrollbars visible**.
+4. Click "Go to red".
+
+**Expected:** The viewport is scrolled to **fully** reveal the 80x80px red square in in the top area of the page.
+
+5. Scroll the **viewport** top and left just a little bit.
+6. Make sure the red square is right in the **bottom-right corner** of the topmost div containing it. **There should be only one set of scrollbars visible**.
+7. Click "Go to green".
+
+**Expected:** The viewport is scrolled to **fully** reveal the 80x80px green square in in the bottom-left corner of the page.
+
+8. Scroll the **viewport** to the bottom and left just a little bit.
+9. Make sure the green square is right in the **bottom-right corner** of the topmost div containing it. **There should be only one set of scrollbars visible**.
+10. Click "Go to blue" to repeat the cycle.