input.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module typing/input
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import ModelRange from '@ckeditor/ckeditor5-engine/src/model/range';
  10. import ViewPosition from '@ckeditor/ckeditor5-engine/src/view/position';
  11. import ViewText from '@ckeditor/ckeditor5-engine/src/view/text';
  12. import diff from '@ckeditor/ckeditor5-utils/src/diff';
  13. import diffToChanges from '@ckeditor/ckeditor5-utils/src/difftochanges';
  14. import { getCode } from '@ckeditor/ckeditor5-utils/src/keyboard';
  15. import InputCommand from './inputcommand';
  16. /**
  17. * Handles text input coming from the keyboard or other input methods.
  18. *
  19. * @extends module:core/plugin~Plugin
  20. */
  21. export default class Input extends Plugin {
  22. /**
  23. * @inheritDoc
  24. */
  25. init() {
  26. const editor = this.editor;
  27. const editingView = editor.editing.view;
  28. const inputCommand = new InputCommand( editor, editor.config.get( 'typing.undoStep' ) || 20 );
  29. // TODO The above default configuration value should be defined using editor.config.define() once it's fixed.
  30. editor.commands.set( 'input', inputCommand );
  31. this.listenTo( editingView, 'keydown', ( evt, data ) => {
  32. this._handleKeydown( data, inputCommand.buffer );
  33. }, { priority: 'lowest' } );
  34. this.listenTo( editingView, 'mutations', ( evt, mutations, viewSelection ) => {
  35. this._handleMutations( mutations, viewSelection );
  36. } );
  37. }
  38. /**
  39. * Handles the keydown event. We need to guess whether such keystroke is going to result
  40. * in typing. If so, then before character insertion happens, any selected content needs
  41. * to be deleted. Otherwise the default browser deletion mechanism would be
  42. * triggered, resulting in:
  43. *
  44. * * Hundreds of mutations which could not be handled.
  45. * * But most importantly, loss of control over how the content is being deleted.
  46. *
  47. * The method is used in a low-priority listener, hence allowing other listeners (e.g. delete or enter features)
  48. * to handle the event.
  49. *
  50. * @private
  51. * @param {module:engine/view/observer/keyobserver~KeyEventData} evtData
  52. * @param {module:typing/changebuffer~ChangeBuffer} buffer
  53. */
  54. _handleKeydown( evtData, buffer ) {
  55. const doc = this.editor.document;
  56. if ( isSafeKeystroke( evtData ) || doc.selection.isCollapsed ) {
  57. return;
  58. }
  59. buffer.lock();
  60. doc.enqueueChanges( () => {
  61. this.editor.data.deleteContent( doc.selection, buffer.batch );
  62. } );
  63. buffer.unlock();
  64. }
  65. /**
  66. * Handles DOM mutations.
  67. *
  68. * @private
  69. * @param {Array.<module:engine/view/document~MutatatedText|module:engine/view/document~MutatatedChildren>} mutations
  70. * @param {module:engine/view/selection~Selection|null} viewSelection
  71. */
  72. _handleMutations( mutations, viewSelection ) {
  73. new MutationHandler( this.editor ).handle( mutations, viewSelection );
  74. }
  75. }
  76. /**
  77. * Helper class for translating DOM mutations into model changes.
  78. *
  79. * @private
  80. */
  81. class MutationHandler {
  82. /**
  83. * Creates an instance of the mutation handler.
  84. *
  85. * @param {module:core/editor/editor~Editor} editor
  86. */
  87. constructor( editor ) {
  88. /**
  89. * Editor instance for which mutations are handled.
  90. *
  91. * @readonly
  92. * @member {module:core/editor/editor~Editor} #editor
  93. */
  94. this.editor = editor;
  95. /**
  96. * The editing controller.
  97. *
  98. * @readonly
  99. * @member {module:engine/controller/editingcontroller~EditingController} #editing
  100. */
  101. this.editing = this.editor.editing;
  102. }
  103. /**
  104. * Handles given mutations.
  105. *
  106. * @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  107. * module:engine/view/observer/mutationobserver~MutatatedChildren>} mutations
  108. * @param {module:engine/view/selection~Selection|null} viewSelection
  109. */
  110. handle( mutations, viewSelection ) {
  111. for ( let mutation of mutations ) {
  112. // Fortunately it will never be both.
  113. this._handleTextMutation( mutation, viewSelection );
  114. this._handleTextNodeInsertion( mutation );
  115. }
  116. }
  117. _handleTextMutation( mutation, viewSelection ) {
  118. if ( mutation.type != 'text' ) {
  119. return;
  120. }
  121. // Replace &nbsp; inserted by the browser with normal space.
  122. // We want only normal spaces in the model and in the view. Renderer and DOM Converter will be then responsible
  123. // for rendering consecutive spaces using &nbsp;, but the model and the view has to be clear.
  124. // Other feature may introduce inserting non-breakable space on specific key stroke (for example shift + space).
  125. // However then it will be handled outside of mutations, like enter key is.
  126. // The replacing is here because it has to be done before `diff` and `diffToChanges` functions, as they
  127. // take `newText` and compare it to (cleaned up) view.
  128. // It could also be done in mutation observer too, however if any outside plugin would like to
  129. // introduce additional events for mutations, they would get already cleaned up version (this may be good or not).
  130. const newText = mutation.newText.replace( /\u00A0/g, ' ' );
  131. // To have correct `diffResult`, we also compare view node text data with &nbsp; replaced by space.
  132. const oldText = mutation.oldText.replace( /\u00A0/g, ' ' );
  133. const diffResult = diff( oldText, newText );
  134. // Index where the first change happens. Used to set the position from which nodes will be removed and where will be inserted.
  135. let firstChangeAt = null;
  136. // Index where the last change happens. Used to properly count how many characters have to be removed and inserted.
  137. let lastChangeAt = null;
  138. // Get `firstChangeAt` and `lastChangeAt`.
  139. for ( let i = 0; i < diffResult.length; i++ ) {
  140. const change = diffResult[ i ];
  141. if ( change != 'equal' ) {
  142. firstChangeAt = firstChangeAt === null ? i : firstChangeAt;
  143. lastChangeAt = i;
  144. }
  145. }
  146. // How many characters, starting from `firstChangeAt`, should be removed.
  147. let deletions = 0;
  148. // How many characters, starting from `firstChangeAt`, should be inserted (basing on mutation.newText).
  149. let insertions = 0;
  150. for ( let i = firstChangeAt; i <= lastChangeAt; i++ ) {
  151. // If there is no change (equal) or delete, the character is existing in `oldText`. We count it for removing.
  152. if ( diffResult[ i ] != 'insert' ) {
  153. deletions++;
  154. }
  155. // If there is no change (equal) or insert, the character is existing in `newText`. We count it for inserting.
  156. if ( diffResult[ i ] != 'delete' ) {
  157. insertions++;
  158. }
  159. }
  160. // Try setting new model selection according to passed view selection.
  161. let modelSelectionRange = null;
  162. if ( viewSelection ) {
  163. modelSelectionRange = this.editing.mapper.toModelRange( viewSelection.getFirstRange() );
  164. }
  165. // Get the position in view and model where the changes will happen.
  166. const viewPos = new ViewPosition( mutation.node, firstChangeAt );
  167. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  168. const removeRange = ModelRange.createFromPositionAndShift( modelPos, deletions );
  169. const insertText = newText.substr( firstChangeAt, insertions );
  170. this.editor.execute( 'input', {
  171. text: insertText,
  172. range: removeRange,
  173. resultRange: modelSelectionRange
  174. } );
  175. }
  176. _handleTextNodeInsertion( mutation ) {
  177. if ( mutation.type != 'children' ) {
  178. return;
  179. }
  180. // One new node.
  181. if ( mutation.newChildren.length - mutation.oldChildren.length != 1 ) {
  182. return;
  183. }
  184. // Which is text.
  185. const diffResult = diff( mutation.oldChildren, mutation.newChildren, compareChildNodes );
  186. const changes = diffToChanges( diffResult, mutation.newChildren );
  187. // In case of [ delete, insert, insert ] the previous check will not exit.
  188. if ( changes.length > 1 ) {
  189. return;
  190. }
  191. const change = changes[ 0 ];
  192. // Which is text.
  193. if ( !( change.values[ 0 ] instanceof ViewText ) ) {
  194. return;
  195. }
  196. const viewPos = new ViewPosition( mutation.node, change.index );
  197. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  198. const insertedText = change.values[ 0 ].data;
  199. this.editor.execute( 'input', {
  200. // Replace &nbsp; inserted by the browser with normal space.
  201. // See comment in `_handleTextMutation`.
  202. // In this case we don't need to do this before `diff` because we diff whole nodes.
  203. // Just change &nbsp; in case there are some.
  204. text: insertedText.replace( /\u00A0/g, ' ' ),
  205. range: new ModelRange( modelPos )
  206. } );
  207. }
  208. }
  209. const safeKeycodes = [
  210. getCode( 'arrowUp' ),
  211. getCode( 'arrowRight' ),
  212. getCode( 'arrowDown' ),
  213. getCode( 'arrowLeft' ),
  214. 9, // Tab
  215. 16, // Shift
  216. 17, // Ctrl
  217. 18, // Alt
  218. 20, // CapsLock
  219. 27, // Escape
  220. 33, // PageUp
  221. 34, // PageDown
  222. 35, // Home
  223. 36, // End
  224. 229 // Composition start key
  225. ];
  226. // Function keys.
  227. for ( let code = 112; code <= 135; code++ ) {
  228. safeKeycodes.push( code );
  229. }
  230. // Returns `true` if a keystroke should not cause any content change caused by "typing".
  231. //
  232. // Note: This implementation is very simple and will need to be refined with time.
  233. //
  234. // @param {engine.view.observer.keyObserver.KeyEventData} keyData
  235. // @returns {Boolean}
  236. function isSafeKeystroke( keyData ) {
  237. // Keystrokes which contain Ctrl don't represent typing.
  238. if ( keyData.ctrlKey ) {
  239. return true;
  240. }
  241. return safeKeycodes.includes( keyData.keyCode );
  242. }
  243. // Helper function that compares whether two given view nodes are same. It is used in `diff` when it's passed an array
  244. // with child nodes.
  245. function compareChildNodes( oldChild, newChild ) {
  246. if ( oldChild instanceof ViewText && newChild instanceof ViewText ) {
  247. return oldChild.data === newChild.data;
  248. } else {
  249. return oldChild === newChild;
  250. }
  251. }