Procházet zdrojové kódy

Introduced `Writer#overrideSelectionGravity()` method.

Oskar Wróbel před 8 roky
rodič
revize
3d6589ebeb

+ 16 - 0
packages/ckeditor5-engine/src/model/writer.js

@@ -1016,6 +1016,22 @@ export default class Writer {
 		}
 	}
 
+	/**
+	 * Temporarily (until selection won't be changed directly by the user) disables default gravity behaviour that tries
+	 * to get attributes from nodes surrounding the caret. When gravity is marked as overridden then attributes from the
+	 * node before the caret won't be taken into consideration while updating selection attributes.
+	 *
+	 * For the following model fragment:
+	 *
+	 * 		<$text bold="true" linkHref="url">bar[]</$text><$text bold="true">biz</$text>
+	 *
+	 * Selection attribute keys before override will be equal `[ 'bold', 'linkHref' ]`
+	 * Selection attribute keys after override will be equal `[ 'bold' ]`
+	 */
+	overrideSelectionGravity() {
+		this.model.document.selection._overrideGravity();
+	}
+
 	/**
 	 * @private
 	 * @param {String} key Key of the attribute to remove.

+ 39 - 0
packages/ckeditor5-engine/tests/model/writer.js

@@ -2347,6 +2347,39 @@ describe( 'Writer', () => {
 		} );
 	} );
 
+	describe( 'overrideSelectionGravity()', () => {
+		it( 'should use DocumentSelection#_overrideGravity', () => {
+			const overrideGravitySpy = sinon.spy( DocumentSelection.prototype, '_overrideGravity' );
+
+			overrideSelectionGravity();
+
+			sinon.assert.calledOnce( overrideGravitySpy );
+			overrideGravitySpy.restore();
+		} );
+
+		it( 'should not get attributes from the node before the caret when gravity is overridden', () => {
+			const root = doc.createRoot();
+			root.appendChildren( [
+				new Text( 'foo', { foo: true } ),
+				new Text( 'bar', { foo: true, bar: true } ),
+				new Text( 'biz', { foo: true } )
+			] );
+
+			setSelection( new Position( root, [ 6 ] ) );
+
+			expect( Array.from( model.document.selection.getAttributeKeys() ) ).to.deep.equal( [ 'foo', 'bar' ] );
+
+			overrideSelectionGravity();
+
+			expect( Array.from( model.document.selection.getAttributeKeys() ) ).to.deep.equal( [ 'foo' ] );
+
+			// Disable override by moving selection.
+			setSelection( new Position( root, [ 5 ] ) );
+
+			expect( Array.from( model.document.selection.getAttributeKeys() ) ).to.deep.equal( [ 'foo', 'bar' ] );
+		} );
+	} );
+
 	function createText( data, attributes ) {
 		return model.change( writer => {
 			return writer.createText( data, attributes );
@@ -2506,4 +2539,10 @@ describe( 'Writer', () => {
 			writer.removeSelectionAttribute( key );
 		} );
 	}
+
+	function overrideSelectionGravity() {
+		model.change( writer => {
+			writer.overrideSelectionGravity();
+		} );
+	}
 } );