Browse Source

Handle delete right after mention tag.

Maciej Gołaszewski 6 years ago
parent
commit
ab85ab537e

+ 28 - 11
packages/ckeditor5-mention/src/mentionediting.js

@@ -56,29 +56,46 @@ export default class MentionEditing extends Plugin {
 		editor.model.schema.extend( '$text', { allowAttributes: 'mention' } );
 
 		// Remove mention attribute if text was edited.
-		editor.model.document.registerPostFixer( writer => {
-			const selection = editor.model.document.selection;
-			const focus = selection.focus;
-
-			if ( selection.hasAttribute( 'mention' ) && selection.isCollapsed && focus.nodeBefore && focus.nodeBefore.is( 'text' ) ) {
-				writer.removeSelectionAttribute( 'mention' );
-
-				return true;
-			}
-		} );
-
 		editor.model.document.registerPostFixer( writer => {
 			const changes = editor.model.document.differ.getChanges();
 
+			let wasChanged = false;
+
 			for ( const change of changes ) {
 				if ( change.type == 'insert' || change.type == 'remove' ) {
 					const textNode = change.position.textNode;
 
 					if ( change.name == '$text' && textNode && textNode.hasAttribute( 'mention' ) ) {
 						writer.removeAttribute( 'mention', textNode );
+						wasChanged = true;
+					}
+				}
+
+				if ( change.type == 'remove' ) {
+					const nodeBefore = change.position.nodeBefore;
+
+					if ( nodeBefore && nodeBefore.hasAttribute( 'mention' ) ) {
+						const text = nodeBefore.data;
+						if ( text != nodeBefore.getAttribute( 'mention' ) ) {
+							writer.removeAttribute( 'mention', nodeBefore );
+							wasChanged = true;
+						}
 					}
 				}
 			}
+
+			return wasChanged;
+		} );
+
+		editor.model.document.registerPostFixer( writer => {
+			const selection = editor.model.document.selection;
+			const focus = selection.focus;
+
+			if ( selection.hasAttribute( 'mention' ) && selection.isCollapsed && focus.nodeBefore && focus.nodeBefore.is( 'text' ) ) {
+				writer.removeSelectionAttribute( 'mention' );
+
+				return true;
+			}
 		} );
 	}
 }

+ 17 - 0
packages/ckeditor5-mention/tests/mentionediting.js

@@ -87,6 +87,23 @@ describe( 'MentionEditing', () => {
 				expect( editor.getData() ).to.equal( '<p>foo Jhn bar</p>' );
 			} );
 
+			it( 'should remove mention on removing a text at the and of a mention', () => {
+				editor.setData( '<p>foo <span class="mention" data-mention="John">John</span> bar</p>' );
+
+				const paragraph = doc.getRoot().getChild( 0 );
+
+				// Set selection at the end of a John.
+				model.change( writer => {
+					writer.setSelection( paragraph, 8 );
+				} );
+
+				model.change( writer => {
+					writer.remove( writer.createRange( writer.createPositionAt( paragraph, 7 ), writer.createPositionAt( paragraph, 8 ) ) );
+				} );
+
+				expect( editor.getData() ).to.equal( '<p>foo Joh bar</p>' );
+			} );
+
 			it( 'should work on insert text to an empty node', () => {
 				editor.setData( '<p></p>' );