8
0

input.js 9.4 KB

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