Procházet zdrojové kódy

Initial AutoLink implementation using text watcher.

Maciej Gołaszewski před 5 roky
rodič
revize
026ec376ca

+ 38 - 0
packages/ckeditor5-link/src/autolink.js

@@ -8,6 +8,9 @@
  */
 
 import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
+import TextWatcher from '@ckeditor/ckeditor5-typing/src/textwatcher';
+
+const regexp = /(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)) $/;
 
 /**
  * The auto link plugin.
@@ -21,4 +24,39 @@ export default class AutoLink extends Plugin {
 	static get pluginName() {
 		return 'AutoLink';
 	}
+
+	/**
+	 * @inheritDoc
+	 */
+	init() {
+		const editor = this.editor;
+
+		const watcher = new TextWatcher( editor.model, text => {
+			const match = regexp.exec( text );
+
+			if ( match ) {
+				return { match };
+			}
+		} );
+
+		const input = editor.plugins.get( 'Input' );
+
+		watcher.on( 'matched:data', ( evt, data ) => {
+			const { batch, range, match } = data;
+
+			if ( !input.isInput( batch ) ) {
+				return;
+			}
+
+			const url = match[ 1 ];
+
+			// Enqueue change to make undo step.
+			editor.model.enqueueChange( writer => {
+				writer.setAttribute( 'linkHref', url, writer.createRange(
+					range.start,
+					range.end.getShiftedBy( -1 )
+				) );
+			} );
+		} );
+	}
 }

+ 2 - 1
packages/ckeditor5-link/tests/autolink.js

@@ -10,6 +10,7 @@ import { getData, setData } from '@ckeditor/ckeditor5-engine/src/dev-utils/model
 
 import LinkEditing from '../src/linkediting';
 import AutoLink from '../src/autolink';
+import UndoEditing from '@ckeditor/ckeditor5-undo/src/undoediting';
 
 describe( 'AutoLink', () => {
 	it( 'should be named', () => {
@@ -20,7 +21,7 @@ describe( 'AutoLink', () => {
 		let editor;
 
 		beforeEach( async () => {
-			editor = await ModelTestEditor.create( { plugins: [ Paragraph, Input, LinkEditing, AutoLink ] } );
+			editor = await ModelTestEditor.create( { plugins: [ Paragraph, Input, LinkEditing, AutoLink, UndoEditing ] } );
 
 			setData( editor.model, '<paragraph>[]</paragraph>' );
 		} );