input.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 DomConverter from '@ckeditor/ckeditor5-engine/src/view/domconverter';
  16. import InputCommand from './inputcommand';
  17. /**
  18. * Handles text input coming from the keyboard or other input methods.
  19. *
  20. * @extends module:core/plugin~Plugin
  21. */
  22. export default class Input extends Plugin {
  23. /**
  24. * @inheritDoc
  25. */
  26. static get pluginName() {
  27. return 'Input';
  28. }
  29. /**
  30. * @inheritDoc
  31. */
  32. init() {
  33. const editor = this.editor;
  34. const editingView = editor.editing.view;
  35. const inputCommand = new InputCommand( editor, editor.config.get( 'typing.undoStep' ) || 20 );
  36. // TODO The above default configuration value should be defined using editor.config.define() once it's fixed.
  37. editor.commands.add( 'input', inputCommand );
  38. this.listenTo( editingView, 'keydown', ( evt, data ) => {
  39. this._handleKeydown( data, inputCommand );
  40. }, { priority: 'lowest' } );
  41. this.listenTo( editingView, 'mutations', ( evt, mutations, viewSelection ) => {
  42. this._handleMutations( mutations, viewSelection );
  43. } );
  44. }
  45. /**
  46. * Handles the keydown event. We need to guess whether such keystroke is going to result
  47. * in typing. If so, then before character insertion happens, any selected content needs
  48. * to be deleted. Otherwise the default browser deletion mechanism would be
  49. * triggered, resulting in:
  50. *
  51. * * Hundreds of mutations which could not be handled.
  52. * * But most importantly, loss of control over how the content is being deleted.
  53. *
  54. * The method is used in a low-priority listener, hence allowing other listeners (e.g. delete or enter features)
  55. * to handle the event.
  56. *
  57. * @private
  58. * @param {module:engine/view/observer/keyobserver~KeyEventData} evtData
  59. * @param {module:typing/inputcommand~InputCommand} inputCommand
  60. */
  61. _handleKeydown( evtData, inputCommand ) {
  62. const doc = this.editor.document;
  63. const buffer = inputCommand.buffer;
  64. // By relying on the state of the input command we allow disabling the entire input easily
  65. // by just disabling the input command. We could’ve used here the delete command but that
  66. // would mean requiring the delete feature which would block loading one without the other.
  67. // We could also check the editor.isReadOnly property, but that wouldn't allow to block
  68. // the input without blocking other features.
  69. if ( !inputCommand.isEnabled ) {
  70. return;
  71. }
  72. if ( isSafeKeystroke( evtData ) || doc.selection.isCollapsed ) {
  73. return;
  74. }
  75. buffer.lock();
  76. doc.enqueueChanges( () => {
  77. this.editor.data.deleteContent( doc.selection, buffer.batch );
  78. } );
  79. buffer.unlock();
  80. }
  81. /**
  82. * Handles DOM mutations.
  83. *
  84. * @private
  85. * @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  86. * module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  87. * @param {module:engine/view/selection~Selection|null} viewSelection
  88. */
  89. _handleMutations( mutations, viewSelection ) {
  90. new MutationHandler( this.editor ).handle( mutations, viewSelection );
  91. }
  92. }
  93. /**
  94. * Helper class for translating DOM mutations into model changes.
  95. *
  96. * @private
  97. */
  98. class MutationHandler {
  99. /**
  100. * Creates an instance of the mutation handler.
  101. *
  102. * @param {module:core/editor/editor~Editor} editor
  103. */
  104. constructor( editor ) {
  105. /**
  106. * Editor instance for which mutations are handled.
  107. *
  108. * @readonly
  109. * @member {module:core/editor/editor~Editor} #editor
  110. */
  111. this.editor = editor;
  112. /**
  113. * The editing controller.
  114. *
  115. * @readonly
  116. * @member {module:engine/controller/editingcontroller~EditingController} #editing
  117. */
  118. this.editing = this.editor.editing;
  119. }
  120. /**
  121. * Handles given mutations.
  122. *
  123. * @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  124. * module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  125. * @param {module:engine/view/selection~Selection|null} viewSelection
  126. */
  127. handle( mutations, viewSelection ) {
  128. if ( containerChildrenMutated( mutations ) ) {
  129. this._handleContainerChildrenMutations( mutations, viewSelection );
  130. } else {
  131. for ( const mutation of mutations ) {
  132. // Fortunately it will never be both.
  133. this._handleTextMutation( mutation, viewSelection );
  134. this._handleTextNodeInsertion( mutation );
  135. }
  136. }
  137. }
  138. /**
  139. * Handles situations when container's children mutated during input. This can happen when
  140. * browser is trying to "fix" DOM in certain situations. For example, when user starts to type
  141. * in `<p><a href=""><i>Link{}</i></a></p>` browser might change order of elements
  142. * to `<p><i><a href="">Link</a>x{}</i></p>`. Similar situation happens when spell checker
  143. * replaces a word wrapped with `<strong>` to a word wrapped with `<b>` element.
  144. *
  145. * To handle such situations, DOM common ancestor of all mutations is converted to the model representation
  146. * and then compared with current model to calculate proper text change.
  147. *
  148. * NOTE: Single text node insertion is handled in {@link #_handleTextNodeInsertion} and text node mutation is handled
  149. * in {@link #_handleTextMutation}).
  150. *
  151. * @private
  152. * @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  153. * module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  154. * @param {module:engine/view/selection~Selection|null} viewSelection
  155. */
  156. _handleContainerChildrenMutations( mutations, viewSelection ) {
  157. // Get common ancestor of all mutations.
  158. const mutationsCommonAncestor = getMutationsCommonAncestor( mutations );
  159. // Quit if there is no common ancestor.
  160. if ( !mutationsCommonAncestor ) {
  161. return;
  162. }
  163. const domConverter = this.editor.editing.view.domConverter;
  164. // Get common ancestor in DOM.
  165. const domMutationCommonAncestor = domConverter.mapViewToDom( mutationsCommonAncestor );
  166. if ( !domMutationCommonAncestor ) {
  167. return;
  168. }
  169. // Create fresh DomConverter so it will not use existing mapping and convert current DOM to model.
  170. // This wouldn't be needed if DomConverter would allow to create fresh view without checking any mappings.
  171. const freshDomConverter = new DomConverter();
  172. const modelFromCurrentDom = this.editor.data.toModel( freshDomConverter.domToView( domMutationCommonAncestor ) ).getChild( 0 );
  173. // Current model.
  174. const currentModel = this.editor.editing.mapper.toModelElement( mutationsCommonAncestor );
  175. // Get children from both ancestors.
  176. const modelFromDomChildren = [ ...modelFromCurrentDom.getChildren() ];
  177. const currentModelChildren = [ ...currentModel.getChildren() ];
  178. // Fix situations when common ancestor has only text nodes inside.
  179. if ( !containsOnlyTextNodes( modelFromDomChildren ) || !containsOnlyTextNodes( currentModelChildren ) ) {
  180. return;
  181. }
  182. // Replace &nbsp; inserted by the browser with normal space.
  183. // See comment in `_handleTextMutation`.
  184. const newText = modelFromDomChildren.map( item => item.data ).join( '' ).replace( /\u00A0/g, ' ' );
  185. const oldText = currentModelChildren.map( item => item.data ).join( '' );
  186. // Do nothing if mutations created same text.
  187. if ( oldText === newText ) {
  188. return;
  189. }
  190. const diffResult = diff( oldText, newText );
  191. const { firstChangeAt, insertions, deletions } = calculateChanges( diffResult );
  192. // Try setting new model selection according to passed view selection.
  193. let modelSelectionRange = null;
  194. if ( viewSelection ) {
  195. modelSelectionRange = this.editing.mapper.toModelRange( viewSelection.getFirstRange() );
  196. }
  197. const insertText = newText.substr( firstChangeAt, insertions );
  198. const removeRange = ModelRange.createFromParentsAndOffsets(
  199. currentModel,
  200. firstChangeAt,
  201. currentModel,
  202. firstChangeAt + deletions
  203. );
  204. this.editor.execute( 'input', {
  205. text: insertText,
  206. range: removeRange,
  207. resultRange: modelSelectionRange
  208. } );
  209. }
  210. _handleTextMutation( mutation, viewSelection ) {
  211. if ( mutation.type != 'text' ) {
  212. return;
  213. }
  214. // Replace &nbsp; inserted by the browser with normal space.
  215. // We want only normal spaces in the model and in the view. Renderer and DOM Converter will be then responsible
  216. // for rendering consecutive spaces using &nbsp;, but the model and the view has to be clear.
  217. // Other feature may introduce inserting non-breakable space on specific key stroke (for example shift + space).
  218. // However then it will be handled outside of mutations, like enter key is.
  219. // The replacing is here because it has to be done before `diff` and `diffToChanges` functions, as they
  220. // take `newText` and compare it to (cleaned up) view.
  221. // It could also be done in mutation observer too, however if any outside plugin would like to
  222. // introduce additional events for mutations, they would get already cleaned up version (this may be good or not).
  223. const newText = mutation.newText.replace( /\u00A0/g, ' ' );
  224. // To have correct `diffResult`, we also compare view node text data with &nbsp; replaced by space.
  225. const oldText = mutation.oldText.replace( /\u00A0/g, ' ' );
  226. const diffResult = diff( oldText, newText );
  227. const { firstChangeAt, insertions, deletions } = calculateChanges( diffResult );
  228. // Try setting new model selection according to passed view selection.
  229. let modelSelectionRange = null;
  230. if ( viewSelection ) {
  231. modelSelectionRange = this.editing.mapper.toModelRange( viewSelection.getFirstRange() );
  232. }
  233. // Get the position in view and model where the changes will happen.
  234. const viewPos = new ViewPosition( mutation.node, firstChangeAt );
  235. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  236. const removeRange = ModelRange.createFromPositionAndShift( modelPos, deletions );
  237. const insertText = newText.substr( firstChangeAt, insertions );
  238. this.editor.execute( 'input', {
  239. text: insertText,
  240. range: removeRange,
  241. resultRange: modelSelectionRange
  242. } );
  243. }
  244. _handleTextNodeInsertion( mutation ) {
  245. if ( mutation.type != 'children' ) {
  246. return;
  247. }
  248. const change = getSingleTextNodeChange( mutation );
  249. if ( !change ) {
  250. return;
  251. }
  252. const viewPos = new ViewPosition( mutation.node, change.index );
  253. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  254. const insertedText = change.values[ 0 ].data;
  255. this.editor.execute( 'input', {
  256. // Replace &nbsp; inserted by the browser with normal space.
  257. // See comment in `_handleTextMutation`.
  258. // In this case we don't need to do this before `diff` because we diff whole nodes.
  259. // Just change &nbsp; in case there are some.
  260. text: insertedText.replace( /\u00A0/g, ' ' ),
  261. range: new ModelRange( modelPos )
  262. } );
  263. }
  264. }
  265. const safeKeycodes = [
  266. getCode( 'arrowUp' ),
  267. getCode( 'arrowRight' ),
  268. getCode( 'arrowDown' ),
  269. getCode( 'arrowLeft' ),
  270. 9, // Tab
  271. 16, // Shift
  272. 17, // Ctrl
  273. 18, // Alt
  274. 20, // CapsLock
  275. 27, // Escape
  276. 33, // PageUp
  277. 34, // PageDown
  278. 35, // Home
  279. 36, // End
  280. 229 // Composition start key
  281. ];
  282. // Function keys.
  283. for ( let code = 112; code <= 135; code++ ) {
  284. safeKeycodes.push( code );
  285. }
  286. // Returns `true` if a keystroke should not cause any content change caused by "typing".
  287. //
  288. // Note: This implementation is very simple and will need to be refined with time.
  289. //
  290. // @private
  291. // @param {engine.view.observer.keyObserver.KeyEventData} keyData
  292. // @returns {Boolean}
  293. function isSafeKeystroke( keyData ) {
  294. // Keystrokes which contain Ctrl don't represent typing.
  295. if ( keyData.ctrlKey ) {
  296. return true;
  297. }
  298. return safeKeycodes.includes( keyData.keyCode );
  299. }
  300. // Helper function that compares whether two given view nodes are same. It is used in `diff` when it's passed an array
  301. // with child nodes.
  302. function compareChildNodes( oldChild, newChild ) {
  303. if ( oldChild instanceof ViewText && newChild instanceof ViewText ) {
  304. return oldChild.data === newChild.data;
  305. } else {
  306. return oldChild === newChild;
  307. }
  308. }
  309. // Returns change made to a single text node. Returns `undefined` if more than a single text node was changed.
  310. //
  311. // @private
  312. // @param mutation
  313. function getSingleTextNodeChange( mutation ) {
  314. // One new node.
  315. if ( mutation.newChildren.length - mutation.oldChildren.length != 1 ) {
  316. return;
  317. }
  318. // Which is text.
  319. const diffResult = diff( mutation.oldChildren, mutation.newChildren, compareChildNodes );
  320. const changes = diffToChanges( diffResult, mutation.newChildren );
  321. // In case of [ delete, insert, insert ] the previous check will not exit.
  322. if ( changes.length > 1 ) {
  323. return;
  324. }
  325. const change = changes[ 0 ];
  326. // Which is text.
  327. if ( !( change.values[ 0 ] instanceof ViewText ) ) {
  328. return;
  329. }
  330. return change;
  331. }
  332. // Returns first common ancestor of all mutations.
  333. //
  334. // @private
  335. // @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  336. // module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  337. function getMutationsCommonAncestor( mutations ) {
  338. // If just 1 mutation present - return mutation node.
  339. if ( mutations.length == 1 ) {
  340. return mutations[ 0 ].node;
  341. }
  342. // Get array of ancestor lists without root element.
  343. const ancestorsLists = mutations
  344. .map( mutation => mutation.node.getAncestors( { includeNode: true } ).filter( ancestor => !ancestor.is( 'rootElement' ) ) );
  345. // Calculate shortest ancestors lists.
  346. const shortestListLength = Math.min( ...ancestorsLists.map( list => list.length ) );
  347. let i = 0;
  348. // Check if all mutations have common ancestor.
  349. while ( i < shortestListLength ) {
  350. const ancestor = ancestorsLists[ 0 ][ i ];
  351. let same = true;
  352. for ( let j = 1; j < ancestorsLists.length; j++ ) {
  353. if ( ancestorsLists[ j ][ i ] !== ancestor ) {
  354. same = false;
  355. break;
  356. }
  357. }
  358. if ( !same ) {
  359. break;
  360. }
  361. i++;
  362. }
  363. return i == 0 ? null : ancestorsLists[ 0 ][ i - 1 ];
  364. }
  365. // Returns true if container children have mutated and more than a single text node was changed. Single text node
  366. // child insertion is handled in {@link module:typing/input~MutationHandler#_handleTextNodeInsertion} and text
  367. // mutation is handled in {@link module:typing/input~MutationHandler#_handleTextMutation}.
  368. //
  369. // @private
  370. // @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  371. // module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  372. // @returns {Boolean}
  373. function containerChildrenMutated( mutations ) {
  374. if ( mutations.length == 0 ) {
  375. return false;
  376. }
  377. // Check if all mutations are `children` type, and there is no single text node mutation
  378. for ( const mutation of mutations ) {
  379. if ( mutation.type !== 'children' || getSingleTextNodeChange( mutation ) ) {
  380. return false;
  381. }
  382. }
  383. return true;
  384. }
  385. // Returns true if provided array contains only {@link module:engine/model/text~Text model text nodes}.
  386. //
  387. // @param {Array<module:engine/model/node~Node>} children
  388. // @returns {Boolean}
  389. function containsOnlyTextNodes( children ) {
  390. for ( const child of children ) {
  391. if ( !child.is( 'text' ) ) {
  392. return false;
  393. }
  394. }
  395. return true;
  396. }
  397. // Calculates first change index and number of characters that should be inserted and deleted starting from that index.
  398. //
  399. // @private
  400. // @param diffResult
  401. // @return {{insertions: number, deletions: number, firstChangeAt: *}}
  402. function calculateChanges( diffResult ) {
  403. // Index where the first change happens. Used to set the position from which nodes will be removed and where will be inserted.
  404. let firstChangeAt = null;
  405. // Index where the last change happens. Used to properly count how many characters have to be removed and inserted.
  406. let lastChangeAt = null;
  407. // Get `firstChangeAt` and `lastChangeAt`.
  408. for ( let i = 0; i < diffResult.length; i++ ) {
  409. const change = diffResult[ i ];
  410. if ( change != 'equal' ) {
  411. firstChangeAt = firstChangeAt === null ? i : firstChangeAt;
  412. lastChangeAt = i;
  413. }
  414. }
  415. // How many characters, starting from `firstChangeAt`, should be removed.
  416. let deletions = 0;
  417. // How many characters, starting from `firstChangeAt`, should be inserted.
  418. let insertions = 0;
  419. for ( let i = firstChangeAt; i <= lastChangeAt; i++ ) {
  420. // If there is no change (equal) or delete, the character is existing in `oldText`. We count it for removing.
  421. if ( diffResult[ i ] != 'insert' ) {
  422. deletions++;
  423. }
  424. // If there is no change (equal) or insert, the character is existing in `newText`. We count it for inserting.
  425. if ( diffResult[ i ] != 'delete' ) {
  426. insertions++;
  427. }
  428. }
  429. return { insertions, deletions, firstChangeAt };
  430. }