瀏覽代碼

Extract MentionCommand.

Maciej Gołaszewski 6 年之前
父節點
當前提交
c78ff5c327

+ 55 - 0
packages/ckeditor5-mention/src/mentioncommand.js

@@ -0,0 +1,55 @@
+/**
+ * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/**
+ * @module mention/mentioncommand
+ */
+
+import Command from '@ckeditor/ckeditor5-core/src/command';
+
+/**
+ * The mention command.
+ *
+ * @extends module:core/command~Command
+ */
+export default class MentionCommand extends Command {
+	/**
+	 * @inheritDoc
+	 */
+	refresh() {
+		// @todo implement refresh
+		this.isEnabled = true;
+	}
+
+	/**
+	 * Executes the command.
+	 *
+	 * @protected
+	 * @param {Object} [options] Options for the executed command.
+	 * @param {String} [options.marker='@'] The mention marker.
+	 * @param {String} options.mention.
+	 * @param {String} [options.range].
+	 * @fires execute
+	 */
+	execute( options = {} ) {
+		const model = this.editor.model;
+		const document = model.document;
+		const selection = document.selection;
+
+		const marker = options.marker || '@';
+
+		const mention = options.mention;
+		const range = options.range || selection.getFirstRange();
+
+		const label = mention.label || mention;
+
+		model.change( writer => {
+			writer.remove( range );
+
+			writer.insertText( `${ marker }${ label }`, { mention }, range.start );
+			writer.insertText( ' ', model.document.selection.focus );
+		} );
+	}
+}

+ 3 - 0
packages/ckeditor5-mention/src/mentionediting.js

@@ -8,6 +8,7 @@
  */
 
 import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
+import MentionCommand from './mentioncommand';
 
 /**
  * The mention editing feature.
@@ -97,5 +98,7 @@ export default class MentionEditing extends Plugin {
 				return true;
 			}
 		} );
+
+		editor.commands.add( 'mention', new MentionCommand( editor ) );
 	}
 }

+ 9 - 9
packages/ckeditor5-mention/src/mentionui.js

@@ -80,18 +80,18 @@ export default class MentionUI extends Plugin {
 
 			const matched = getMatchedText( text );
 
-			editor.model.change( writer => {
-				const end = writer.createPositionAt( editor.model.document.selection.focus );
-				const start = end.getShiftedBy( -( 1 + matched.feedText.length ) );
+			const end = editor.model.createPositionAt( editor.model.document.selection.focus );
+			const start = end.getShiftedBy( -( 1 + matched.feedText.length ) );
 
-				const range = writer.createRange( start, end );
+			const range = editor.model.createRange( start, end );
 
-				writer.setAttribute( 'mention', label, range );
-				writer.remove( range );
-
-				writer.insertText( `@${ label }`, { mention: 'label' }, start );
-				writer.insertText( ' ', editor.model.document.selection.focus );
+			editor.execute( 'mention', {
+				mention: label,
+				marker: '@',
+				range
 			} );
+
+			this._hideForm();
 		} );
 
 		function testCallback( text ) {