8
0

autoimage.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. /**
  6. * @module image/autoimage
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import Clipboard from '@ckeditor/ckeditor5-clipboard/src/clipboard';
  10. import LiveRange from '@ckeditor/ckeditor5-engine/src/model/liverange';
  11. import LivePosition from '@ckeditor/ckeditor5-engine/src/model/liveposition';
  12. import Undo from '@ckeditor/ckeditor5-undo/src/undo';
  13. import global from '@ckeditor/ckeditor5-utils/src/dom/global';
  14. import { insertImage } from './image/utils';
  15. // implements pattern: http(s)://(www.)example.com/path/to/resource.ext?query=params&maybe=too
  16. const IMAGE_URL_REGEXP = new RegExp(''
  17. + /^(http(s)?:\/\/)?[\w-]+(\.[\w-]+)+[\w._~:/?#[\]@!$&'()*+,;=%-]+/.source
  18. + /\.(jpg|jpeg|png|gif|ico|JPG|JPEG|PNG|GIF|ICO)\??[\w._~:/#[\]@!$&'()*+,;=%-]*$/.source
  19. );
  20. /**
  21. * The auto-image plugin. It recognizes image links in the pasted content and embeds
  22. * them shortly after they are injected into the document.
  23. *
  24. * @extends module:core/plugin~Plugin
  25. */
  26. export default class AutoImage extends Plugin {
  27. /**
  28. * @inheritDoc
  29. */
  30. static get requires() {
  31. return [ Clipboard, Undo ];
  32. }
  33. /**
  34. * @inheritDoc
  35. */
  36. static get pluginName() {
  37. return 'AutoImage';
  38. }
  39. /**
  40. * @inheritDoc
  41. */
  42. constructor( editor ) {
  43. super( editor );
  44. /**
  45. * The paste–to–embed `setTimeout` ID. Stored as a property to allow
  46. * cleaning of the timeout.
  47. *
  48. * @private
  49. * @member {Number} #_timeoutId
  50. */
  51. this._timeoutId = null;
  52. /**
  53. * The position where the `<image>` element will be inserted after the timeout,
  54. * determined each time the new content is pasted into the document.
  55. *
  56. * @private
  57. * @member {module:engine/model/liveposition~LivePosition} #_positionToInsert
  58. */
  59. this._positionToInsert = null;
  60. }
  61. /**
  62. * @inheritDoc
  63. */
  64. init() {
  65. const editor = this.editor;
  66. const modelDocument = editor.model.document;
  67. // We need to listen on `Clipboard#inputTransformation` because we need to save positions of selection.
  68. // After pasting, the content between those positions will be checked for a URL that could be transformed
  69. // into image.
  70. this.listenTo( editor.plugins.get( Clipboard ), 'inputTransformation', () => {
  71. const firstRange = modelDocument.selection.getFirstRange();
  72. const leftLivePosition = LivePosition.fromPosition( firstRange.start );
  73. leftLivePosition.stickiness = 'toPrevious';
  74. const rightLivePosition = LivePosition.fromPosition( firstRange.end );
  75. rightLivePosition.stickiness = 'toNext';
  76. modelDocument.once( 'change:data', () => {
  77. this._embedImageBetweenPositions( leftLivePosition, rightLivePosition );
  78. leftLivePosition.detach();
  79. rightLivePosition.detach();
  80. }, { priority: 'high' } );
  81. } );
  82. editor.commands.get( 'undo' ).on( 'execute', () => {
  83. if ( this._timeoutId ) {
  84. global.window.clearTimeout( this._timeoutId );
  85. this._positionToInsert.detach();
  86. this._timeoutId = null;
  87. this._positionToInsert = null;
  88. }
  89. }, { priority: 'high' } );
  90. }
  91. /**
  92. * Analyzes the part of the document between provided positions in search for an URL representing an image.
  93. * When the URL is found, it is automatically converted into an image.
  94. *
  95. * @protected
  96. * @param {module:engine/model/liveposition~LivePosition} leftPosition Left position of the selection.
  97. * @param {module:engine/model/liveposition~LivePosition} rightPosition Right position of the selection.
  98. */
  99. _embedImageBetweenPositions( leftPosition, rightPosition ) {
  100. const editor = this.editor;
  101. // TODO: Use marker instead of LiveRange & LivePositions.
  102. const urlRange = new LiveRange( leftPosition, rightPosition );
  103. const walker = urlRange.getWalker( { ignoreElementEnd: true } );
  104. let src = '';
  105. for ( const node of walker ) {
  106. if ( node.item.is( '$textProxy' ) ) {
  107. src += node.item.data;
  108. }
  109. }
  110. src = src.trim();
  111. // If the URL does not match to image URL regexp, let's skip that.
  112. if ( !src.match( IMAGE_URL_REGEXP ) ) {
  113. urlRange.detach();
  114. return;
  115. }
  116. // Position won't be available in the `setTimeout` function so let's clone it.
  117. this._positionToInsert = LivePosition.fromPosition( leftPosition );
  118. // This action mustn't be executed if undo was called between pasting and auto-embedding.
  119. this._timeoutId = global.window.setTimeout( () => {
  120. // Don't do anything if image element cannot be inserted at the current position (#47).
  121. // Condition must be checked after timeout - pasting may take place on an element, replacing it. The final position matters.
  122. const imageCommand = editor.commands.get( 'imageInsert' );
  123. if ( !imageCommand.isEnabled ) {
  124. urlRange.detach();
  125. return;
  126. }
  127. editor.model.change( writer => {
  128. this._timeoutId = null;
  129. writer.remove( urlRange );
  130. urlRange.detach();
  131. let insertionPosition;
  132. // Check if position where the element should be inserted is still valid.
  133. // Otherwise leave it as undefined to use the logic of insertImage().
  134. if ( this._positionToInsert.root.rootName !== '$graveyard' ) {
  135. insertionPosition = this._positionToInsert.toPosition();
  136. }
  137. insertImage( editor.model, { src }, insertionPosition );
  138. this._positionToInsert.detach();
  139. this._positionToInsert = null;
  140. } );
  141. }, 100 );
  142. }
  143. }