input.js 10 KB

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