浏览代码

Added Position.getShiftedBy.

Szymon Cofalik 10 年之前
父节点
当前提交
90415a72e5

+ 15 - 0
packages/ckeditor5-engine/src/treemodel/position.js

@@ -173,6 +173,21 @@ CKEDITOR.define( [ 'treemodel/rootelement', 'utils', 'ckeditorerror' ], ( RootEl
 			return this.path.slice( 0, -1 );
 		}
 
+		/**
+		 * Returns a new instance of Position with offset incremented by `shift` value.
+		 *
+		 * @param {Number} shift How position offset should get changed. Accepts negative values.
+		 * @returns {treeModel.Position} Shifted position.
+		 */
+		getShiftedBy( shift ) {
+			let shifted = Position.createFromPosition( this );
+
+			let offset = shifted.offset + shift;
+			shifted.offset = offset < 0 ? 0 : offset;
+
+			return shifted;
+		}
+
 		/**
 		 * Returns this position after being updated by removing `howMany` nodes starting from `deletePosition`.
 		 * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.

+ 1 - 4
packages/ckeditor5-engine/src/treemodel/range.js

@@ -362,10 +362,7 @@ CKEDITOR.define( [ 'treemodel/position', 'treemodel/positioniterator', 'utils' ]
 		 * @returns {treeModel.Range}
 		 */
 		static createFromPositionAndShift( position, shift ) {
-			let endPosition = Position.createFromPosition( position );
-			endPosition.offset += shift;
-
-			return new this( position, endPosition );
+			return new this( position, position.getShiftedBy( shift ) );
 		}
 
 		/**

+ 25 - 0
packages/ckeditor5-engine/tests/treemodel/position.js

@@ -555,4 +555,29 @@ describe( 'position', () => {
 			expect( combined.path ).to.deep.equal( [ 2, 7, 4, 2 ] );
 		} );
 	} );
+
+	describe( 'getShiftedBy', () => {
+		it( 'should return a new instance of Position with offset changed by shift value', () => {
+			let position = new Position( root, [ 1, 2, 3 ] );
+			let shifted = position.getShiftedBy( 2 );
+
+			expect( shifted ).to.be.instanceof( Position );
+			expect( shifted ).to.not.equal( position );
+			expect( shifted.path ).to.deep.equal( [ 1, 2, 5 ] );
+		} );
+
+		it( 'should accept negative values', () => {
+			let position = new Position( root, [ 1, 2, 3 ] );
+			let shifted = position.getShiftedBy( -2 );
+
+			expect( shifted.path ).to.deep.equal( [ 1, 2, 1 ] );
+		} );
+
+		it( 'should not let setting offset lower than zero', () => {
+			let position = new Position( root, [ 1, 2, 3 ] );
+			let shifted = position.getShiftedBy( -7 );
+
+			expect( shifted.path ).to.deep.equal( [ 1, 2, 0 ] );
+		} );
+	} );
 } );