1.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* globals document */
  6. import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
  7. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  8. import Range from '../../../../src/model/range';
  9. import LivePosition from '../../../../src/model/liveposition';
  10. import Enter from '@ckeditor/ckeditor5-enter/src/enter';
  11. import Typing from '@ckeditor/ckeditor5-typing/src/typing';
  12. import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
  13. import Undo from '@ckeditor/ckeditor5-undo/src/undo';
  14. class Link extends Plugin {
  15. init() {
  16. const editor = this.editor;
  17. // Allow bold attribute on all inline nodes.
  18. editor.model.schema.extend( '$text', { allowAttributes: 'link' } );
  19. editor.conversion.for( 'downcast' ).attributeToElement( {
  20. model: 'link',
  21. view: ( modelAttributeValue, { writer } ) => {
  22. return writer.createAttributeElement( 'a', { href: modelAttributeValue } );
  23. }
  24. } );
  25. editor.conversion.for( 'upcast' ).elementToAttribute( {
  26. view: 'a',
  27. model: {
  28. key: 'link',
  29. value: viewElement => viewElement.getAttribute( 'href' )
  30. }
  31. } );
  32. }
  33. }
  34. class AutoLinker extends Plugin {
  35. init() {
  36. this.editor.model.document.on( 'change', () => {
  37. const changes = this.editor.model.document.differ.getChanges();
  38. for ( const entry of changes ) {
  39. if ( entry.type != 'insert' || entry.name != '$text' || !entry.position.parent ) {
  40. continue;
  41. }
  42. const parent = entry.position.parent;
  43. const text = Array.from( parent.getChildren() ).map( item => item.data ).join( '' );
  44. const regexp = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/g;
  45. let match;
  46. while ( ( match = regexp.exec( text ) ) !== null ) {
  47. const index = match.index;
  48. const url = match[ 0 ];
  49. const length = url.length;
  50. if ( entry.position.offset + entry.length == index + length ) {
  51. const livePos = LivePosition._createAt( parent, index );
  52. this.editor.model.enqueueChange( writer => {
  53. const urlRange = Range._createFromPositionAndShift( livePos, length );
  54. writer.setAttribute( 'link', url, urlRange );
  55. } );
  56. return;
  57. }
  58. }
  59. }
  60. } );
  61. }
  62. }
  63. ClassicEditor.create( document.querySelector( '#editor' ), {
  64. plugins: [ Enter, Typing, Paragraph, Undo, Link, AutoLinker ],
  65. toolbar: [ 'undo', 'redo' ]
  66. } );