input.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import Feature from '../feature.js';
  6. import ChangeBuffer from './changebuffer.js';
  7. import ModelPosition from '../engine/model/position.js';
  8. import ModelRange from '../engine/model/range.js';
  9. import ViewPosition from '../engine/view/position.js';
  10. import ViewText from '../engine/view/text.js';
  11. import diff from '../utils/diff.js';
  12. import diffToChanges from '../utils/difftochanges.js';
  13. import { getCode } from '../utils/keyboard.js';
  14. /**
  15. * Handles text input, coming from keyboard or other input methods.
  16. *
  17. * @memberOf typing
  18. * @extends ckeditor5.Feature
  19. */
  20. export default class Input extends Feature {
  21. /**
  22. * @inheritDoc
  23. */
  24. init() {
  25. const editor = this.editor;
  26. const editingView = editor.editing.view;
  27. /**
  28. * Typing's change buffer used to group subsequent changes into batches.
  29. *
  30. * @protected
  31. * @member {typing.ChangeBuffer} typing.Input#_buffer
  32. */
  33. this._buffer = new ChangeBuffer( editor.document, editor.config.get( 'typing.undoStep' ) || 20 );
  34. // TODO The above default config value should be defines using editor.config.define() once it's fixed.
  35. this.listenTo( editingView, 'keydown', ( evt, data ) => {
  36. this._handleKeydown( data );
  37. }, null, 9999 ); // LOWEST
  38. this.listenTo( editingView, 'mutations', ( evt, mutations ) => {
  39. this._handleMutations( mutations );
  40. } );
  41. }
  42. /**
  43. * @inheritDoc
  44. */
  45. destroy() {
  46. super.destroy();
  47. this._buffer.destroy();
  48. this._buffer = null;
  49. }
  50. /**
  51. * Handles keydown event. We need to guess whether such a keystroke is going to result
  52. * in typing. If so, then before character insertion happens, we need to delete
  53. * any selected content. Otherwise, a default browser deletion mechanism would be
  54. * triggered, resulting in:
  55. *
  56. * * hundreds of mutations which couldn't be handled,
  57. * * but most importantly, loss of a control over how content is being deleted.
  58. *
  59. * The method is used in a low-prior listener, hence allowing other listeners (e.g. delete or enter features)
  60. * to handle the event.
  61. *
  62. * @private
  63. * @param {engine.view.observer.keyObserver.KeyEventData} evtData
  64. */
  65. _handleKeydown( evtData ) {
  66. const doc = this.editor.document;
  67. if ( isSafeKeystroke( evtData ) || doc.selection.isCollapsed ) {
  68. return;
  69. }
  70. doc.enqueueChanges( () => {
  71. doc.composer.deleteContents( this._buffer.batch, doc.selection );
  72. } );
  73. }
  74. /**
  75. * Handles DOM mutations.
  76. *
  77. * @param {Array.<engine.view.Document~MutatatedText|engine.view.Document~MutatatedChildren>} mutations
  78. */
  79. _handleMutations( mutations ) {
  80. const doc = this.editor.document;
  81. const handler = new MutationHandler( this.editor.editing, this._buffer );
  82. doc.enqueueChanges( () => handler.handle( mutations ) );
  83. }
  84. }
  85. /**
  86. * Helper class for translating DOM mutations into model changes.
  87. *
  88. * @private
  89. * @member typing.Input
  90. */
  91. class MutationHandler {
  92. /**
  93. * Creates instance of the mutation handler.
  94. *
  95. * @param {engine.EditingController} editing
  96. * @param {typing.ChangeBuffer} buffer
  97. */
  98. constructor( editing, buffer ) {
  99. /**
  100. * The editing controller.
  101. *
  102. * @member {engine.EditingController} typing.Input.MutationHandler#editing
  103. */
  104. this.editing = editing;
  105. /**
  106. * The change buffer.
  107. *
  108. * @member {engine.EditingController} typing.Input.MutationHandler#buffer
  109. */
  110. this.buffer = buffer;
  111. /**
  112. * Number of inserted characters which need to be feed to the {@link #buffer change buffer}
  113. * on {@link #commit}.
  114. *
  115. * @member {Number} typing.Input.MutationHandler#insertedCharacterCount
  116. */
  117. this.insertedCharacterCount = 0;
  118. /**
  119. * Position to which the selection should be moved on {@link #commit}.
  120. *
  121. * Note: Currently, the mutation handler will move selection to the position set by the
  122. * last consumer. Placing the selection right after the last change will work for many cases, but not
  123. * for ones like autocorrection or spellchecking. The caret should be placed after the whole piece
  124. * which was corrected (e.g. a word), not after the letter that was replaced.
  125. *
  126. * @member {engine.model.Position} typing.Input.MutationHandler#selectionPosition
  127. */
  128. }
  129. /**
  130. * Handle given mutations.
  131. *
  132. * @param {Array.<engine.view.Document~MutatatedText|engine.view.Document~MutatatedChildren>} mutations
  133. */
  134. handle( mutations ) {
  135. for ( let mutation of mutations ) {
  136. // Fortunately it will never be both.
  137. this._handleTextMutation( mutation );
  138. this._handleTextNodeInsertion( mutation );
  139. }
  140. this.buffer.input( Math.max( this.insertedCharacterCount, 0 ) );
  141. if ( this.selectionPosition ) {
  142. this.editing.model.selection.collapse( this.selectionPosition );
  143. }
  144. }
  145. _handleTextMutation( mutation ) {
  146. if ( mutation.type != 'text' ) {
  147. return;
  148. }
  149. const diffResult = diff( mutation.oldText, mutation.newText );
  150. const changes = diffToChanges( diffResult, mutation.newText );
  151. for ( let change of changes ) {
  152. const viewPos = new ViewPosition( mutation.node, change.index );
  153. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  154. if ( change.type == 'insert' ) {
  155. const insertedText = change.values.join( '' );
  156. this._insert( modelPos, insertedText );
  157. this.selectionPosition = ModelPosition.createAt( modelPos.parent, modelPos.offset + insertedText.length );
  158. } else /* if ( change.type == 'delete' ) */ {
  159. this._remove( new ModelRange( modelPos, modelPos.getShiftedBy( change.howMany ) ), change.howMany );
  160. this.selectionPosition = modelPos;
  161. }
  162. }
  163. }
  164. _handleTextNodeInsertion( mutation ) {
  165. if ( mutation.type != 'children' ) {
  166. return;
  167. }
  168. // One new node.
  169. if ( mutation.newChildren.length - mutation.oldChildren.length != 1 ) {
  170. return;
  171. }
  172. // Which is text.
  173. const diffResult = diff( mutation.oldChildren, mutation.newChildren, compare );
  174. const changes = diffToChanges( diffResult, mutation.newChildren );
  175. // In case of [ delete, insert, insert ] the previous check will not exit.
  176. if ( changes.length > 1 ) {
  177. return;
  178. }
  179. const change = changes[ 0 ];
  180. if ( !( change.values[ 0 ] instanceof ViewText ) ) {
  181. return;
  182. }
  183. const viewPos = new ViewPosition( mutation.node, change.index );
  184. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  185. const insertedText = change.values[ 0 ].data;
  186. this._insert( modelPos, insertedText );
  187. this.selectionPosition = ModelPosition.createAt( modelPos.parent, 'end' );
  188. function compare( oldChild, newChild ) {
  189. if ( oldChild instanceof ViewText && newChild instanceof ViewText ) {
  190. return oldChild.data === newChild.data;
  191. } else {
  192. return oldChild === newChild;
  193. }
  194. }
  195. }
  196. _insert( position, text ) {
  197. this.buffer.batch.weakInsert( position, text );
  198. this.insertedCharacterCount += text.length;
  199. }
  200. _remove( range, length ) {
  201. this.buffer.batch.remove( range );
  202. this.insertedCharacterCount -= length;
  203. }
  204. }
  205. const safeKeycodes = [
  206. getCode( 'arrowUp' ),
  207. getCode( 'arrowRight' ),
  208. getCode( 'arrowDown' ),
  209. getCode( 'arrowLeft' ),
  210. 16, // Shift
  211. 17, // Ctrl
  212. 18, // Alt
  213. 20, // CapsLock
  214. 27, // Escape
  215. 33, // PageUp
  216. 34, // PageDown
  217. 35, // Home
  218. 36, // End
  219. ];
  220. // Function keys.
  221. for ( let code = 112; code <= 135; code++ ) {
  222. safeKeycodes.push( code );
  223. }
  224. // Returns true if a keystroke should not cause any content change caused by "typing".
  225. //
  226. // Note: this implementation is very simple and will need to be refined with time.
  227. //
  228. // @param {engine.view.observer.keyObserver.KeyEventData} keyData
  229. // @returns {Boolean}
  230. function isSafeKeystroke( keyData ) {
  231. // Keystrokes which contain Ctrl don't represent typing.
  232. if ( keyData.ctrlKey ) {
  233. return true;
  234. }
  235. return safeKeycodes.includes( keyData.keyCode );
  236. }