input.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 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 the keyboard or other input methods.
  16. *
  17. * @memberOf typing
  18. * @extends core.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 configuration value should be defined using editor.config.define() once it's fixed.
  35. this.listenTo( editingView, 'keydown', ( evt, data ) => {
  36. this._handleKeydown( data );
  37. }, { priority: '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 the keydown event. We need to guess whether such keystroke is going to result
  52. * in typing. If so, then before character insertion happens, any selected content needs
  53. * to be deleted. Otherwise the default browser deletion mechanism would be
  54. * triggered, resulting in:
  55. *
  56. * * Hundreds of mutations which could not be handled.
  57. * * But most importantly, loss of control over how the content is being deleted.
  58. *
  59. * The method is used in a low-priority 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 an 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. * The number of inserted characters which need to be fed 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. * The position to which the selection should be moved on {@link #commit}.
  120. *
  121. * Note: Currently, the mutation handler will move the 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 autocorrect or spell checking. 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. * Handles 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. // Replace &nbsp; inserted by the browser with normal space.
  150. // We want only normal spaces in the model and in the view. Renderer and DOM Converter will be then responsible
  151. // for rendering consecutive spaces using &nbsp;, but the model and the view has to be clear.
  152. // Other feature may introduce inserting non-breakable space on specific key stroke (for example shift + space).
  153. // However then it will be handled outside of mutations, like enter key is.
  154. // The replacing is here because it has to be done before `diff` and `diffToChanges` functions, as they
  155. // take `newText` and compare it to (cleaned up) view.
  156. // It could also be done in mutation observer too, however if any outside plugin would like to
  157. // introduce additional events for mutations, they would get already cleaned up version (this may be good or not).
  158. const newText = mutation.newText.replace( /\u00A0/g, ' ' );
  159. const diffResult = diff( mutation.oldText, newText );
  160. const changes = diffToChanges( diffResult, newText );
  161. for ( let change of changes ) {
  162. const viewPos = new ViewPosition( mutation.node, change.index );
  163. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  164. if ( change.type == 'insert' ) {
  165. const insertedText = change.values.join( '' );
  166. this._insert( modelPos, insertedText );
  167. this.selectionPosition = ModelPosition.createAt( modelPos.parent, modelPos.offset + insertedText.length );
  168. } else /* if ( change.type == 'delete' ) */ {
  169. this._remove( new ModelRange( modelPos, modelPos.getShiftedBy( change.howMany ) ), change.howMany );
  170. this.selectionPosition = modelPos;
  171. }
  172. }
  173. }
  174. _handleTextNodeInsertion( mutation ) {
  175. if ( mutation.type != 'children' ) {
  176. return;
  177. }
  178. // One new node.
  179. if ( mutation.newChildren.length - mutation.oldChildren.length != 1 ) {
  180. return;
  181. }
  182. const diffResult = diff( mutation.oldChildren, mutation.newChildren, compare );
  183. const changes = diffToChanges( diffResult, mutation.newChildren );
  184. // In case of [ delete, insert, insert ] the previous check will not exit.
  185. if ( changes.length > 1 ) {
  186. return;
  187. }
  188. const change = changes[ 0 ];
  189. // Which is text.
  190. if ( !( change.values[ 0 ] instanceof ViewText ) ) {
  191. return;
  192. }
  193. const viewPos = new ViewPosition( mutation.node, change.index );
  194. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  195. let insertedText = change.values[ 0 ].data;
  196. // Replace &nbsp; inserted by the browser with normal space.
  197. // See comment in `_handleTextMutation`.
  198. // In this case we don't need to do this before `diff` because we diff whole nodes.
  199. // Just change &nbsp; in case there are some.
  200. insertedText = insertedText.replace( /\u00A0/g, ' ' );
  201. this._insert( modelPos, insertedText );
  202. this.selectionPosition = ModelPosition.createAt( modelPos.parent, 'end' );
  203. function compare( oldChild, newChild ) {
  204. if ( oldChild instanceof ViewText && newChild instanceof ViewText ) {
  205. return oldChild.data === newChild.data;
  206. } else {
  207. return oldChild === newChild;
  208. }
  209. }
  210. }
  211. _insert( position, text ) {
  212. this.buffer.batch.weakInsert( position, text );
  213. this.insertedCharacterCount += text.length;
  214. }
  215. _remove( range, length ) {
  216. this.buffer.batch.remove( range );
  217. this.insertedCharacterCount -= length;
  218. }
  219. }
  220. const safeKeycodes = [
  221. getCode( 'arrowUp' ),
  222. getCode( 'arrowRight' ),
  223. getCode( 'arrowDown' ),
  224. getCode( 'arrowLeft' ),
  225. 16, // Shift
  226. 17, // Ctrl
  227. 18, // Alt
  228. 20, // CapsLock
  229. 27, // Escape
  230. 33, // PageUp
  231. 34, // PageDown
  232. 35, // Home
  233. 36, // End
  234. ];
  235. // Function keys.
  236. for ( let code = 112; code <= 135; code++ ) {
  237. safeKeycodes.push( code );
  238. }
  239. // Returns `true` if a keystroke should not cause any content change caused by "typing".
  240. //
  241. // Note: This implementation is very simple and will need to be refined with time.
  242. //
  243. // @param {engine.view.observer.keyObserver.KeyEventData} keyData
  244. // @returns {Boolean}
  245. function isSafeKeystroke( keyData ) {
  246. // Keystrokes which contain Ctrl don't represent typing.
  247. if ( keyData.ctrlKey ) {
  248. return true;
  249. }
  250. return safeKeycodes.includes( keyData.keyCode );
  251. }