input.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. * the browser is trying to "fix" DOM in certain situations. For example, when the user starts to type
  141. * in `<p><a href=""><i>Link{}</i></a></p>`, the browser might change the order of elements
  142. * to `<p><i><a href="">Link</a>x{}</i></p>`. A similar situation happens when the spell checker
  143. * replaces a word wrapped with `<strong>` with a word wrapped with a `<b>` element.
  144. *
  145. * To handle such situations, the common DOM ancestor of all mutations is converted to the model representation
  146. * and then compared with the current model to calculate the 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 = getMutationsContainer( 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 = Array.from( modelFromCurrentDom.getChildren() );
  177. const currentModelChildren = Array.from( currentModel.getChildren() );
  178. // Skip situations when common ancestor has any elements (cause they are too hard).
  179. if ( !hasOnlyTextNodes( modelFromDomChildren ) || !hasOnlyTextNodes( 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. const viewPos = new ViewPosition( mutation.node, change.index );
  250. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  251. const insertedText = change.values[ 0 ].data;
  252. this.editor.execute( 'input', {
  253. // Replace &nbsp; inserted by the browser with normal space.
  254. // See comment in `_handleTextMutation`.
  255. // In this case we don't need to do this before `diff` because we diff whole nodes.
  256. // Just change &nbsp; in case there are some.
  257. text: insertedText.replace( /\u00A0/g, ' ' ),
  258. range: new ModelRange( modelPos )
  259. } );
  260. }
  261. }
  262. const safeKeycodes = [
  263. getCode( 'arrowUp' ),
  264. getCode( 'arrowRight' ),
  265. getCode( 'arrowDown' ),
  266. getCode( 'arrowLeft' ),
  267. 9, // Tab
  268. 16, // Shift
  269. 17, // Ctrl
  270. 18, // Alt
  271. 20, // CapsLock
  272. 27, // Escape
  273. 33, // PageUp
  274. 34, // PageDown
  275. 35, // Home
  276. 36, // End
  277. 229 // Composition start key
  278. ];
  279. // Function keys.
  280. for ( let code = 112; code <= 135; code++ ) {
  281. safeKeycodes.push( code );
  282. }
  283. // Returns `true` if a keystroke should not cause any content change caused by "typing".
  284. //
  285. // Note: This implementation is very simple and will need to be refined with time.
  286. //
  287. // @private
  288. // @param {engine.view.observer.keyObserver.KeyEventData} keyData
  289. // @returns {Boolean}
  290. function isSafeKeystroke( keyData ) {
  291. // Keystrokes which contain Ctrl don't represent typing.
  292. if ( keyData.ctrlKey ) {
  293. return true;
  294. }
  295. return safeKeycodes.includes( keyData.keyCode );
  296. }
  297. // Helper function that compares whether two given view nodes are same. It is used in `diff` when it's passed an array
  298. // with child nodes.
  299. function compareChildNodes( oldChild, newChild ) {
  300. if ( oldChild instanceof ViewText && newChild instanceof ViewText ) {
  301. return oldChild.data === newChild.data;
  302. } else {
  303. return oldChild === newChild;
  304. }
  305. }
  306. // Returns change made to a single text node. Returns `undefined` if more than a single text node was changed.
  307. //
  308. // @private
  309. // @param mutation
  310. function getSingleTextNodeChange( mutation ) {
  311. // One new node.
  312. if ( mutation.newChildren.length - mutation.oldChildren.length != 1 ) {
  313. return;
  314. }
  315. // Which is text.
  316. const diffResult = diff( mutation.oldChildren, mutation.newChildren, compareChildNodes );
  317. const changes = diffToChanges( diffResult, mutation.newChildren );
  318. // In case of [ delete, insert, insert ] the previous check will not exit.
  319. if ( changes.length > 1 ) {
  320. return;
  321. }
  322. const change = changes[ 0 ];
  323. // Which is text.
  324. if ( !( change.values[ 0 ] instanceof ViewText ) ) {
  325. return;
  326. }
  327. return change;
  328. }
  329. // Returns first common ancestor of all mutations that is either {@link module:engine/view/containerelement~ContainerElement}
  330. // or {@link module:engine/view/rootelement~RootElement}.
  331. //
  332. // @private
  333. // @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  334. // module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  335. // @returns {module:engine/view/containerelement~ContainerElement|engine/view/rootelement~RootElement|undefined}
  336. function getMutationsContainer( mutations ) {
  337. const lca = mutations
  338. .map( mutation => mutation.node )
  339. .reduce( ( commonAncestor, node ) => {
  340. return commonAncestor.getCommonAncestor( node, { includeSelf: true } );
  341. } );
  342. if ( !lca ) {
  343. return;
  344. }
  345. // We need to look for container and root elements only, so check all LCA's
  346. // ancestors (starting from itself).
  347. return lca.getAncestors( { includeSelf: true, parentFirst: true } )
  348. .find( element => element.is( 'containerElement' ) || element.is( 'rootElement' ) );
  349. }
  350. // Returns true if container children have mutated or more than a single text node was changed.
  351. //
  352. // Single text node child insertion is handled in {@link module:typing/input~MutationHandler#_handleTextNodeInsertion}
  353. // while text mutation is handled in {@link module:typing/input~MutationHandler#_handleTextMutation}.
  354. //
  355. // @private
  356. // @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  357. // module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  358. // @returns {Boolean}
  359. function containerChildrenMutated( mutations ) {
  360. if ( mutations.length == 0 ) {
  361. return false;
  362. }
  363. // Check if there is any mutation of `children` type or any mutation that changes more than one text node.
  364. for ( const mutation of mutations ) {
  365. if ( mutation.type === 'children' && !getSingleTextNodeChange( mutation ) ) {
  366. return true;
  367. }
  368. }
  369. return false;
  370. }
  371. // Returns true if provided array contains only {@link module:engine/model/text~Text model text nodes}.
  372. //
  373. // @param {Array.<module:engine/model/node~Node>} children
  374. // @returns {Boolean}
  375. function hasOnlyTextNodes( children ) {
  376. return children.every( child => child.is( 'text' ) );
  377. }
  378. // Calculates first change index and number of characters that should be inserted and deleted starting from that index.
  379. //
  380. // @private
  381. // @param diffResult
  382. // @return {{insertions: number, deletions: number, firstChangeAt: *}}
  383. function calculateChanges( diffResult ) {
  384. // Index where the first change happens. Used to set the position from which nodes will be removed and where will be inserted.
  385. let firstChangeAt = null;
  386. // Index where the last change happens. Used to properly count how many characters have to be removed and inserted.
  387. let lastChangeAt = null;
  388. // Get `firstChangeAt` and `lastChangeAt`.
  389. for ( let i = 0; i < diffResult.length; i++ ) {
  390. const change = diffResult[ i ];
  391. if ( change != 'equal' ) {
  392. firstChangeAt = firstChangeAt === null ? i : firstChangeAt;
  393. lastChangeAt = i;
  394. }
  395. }
  396. // How many characters, starting from `firstChangeAt`, should be removed.
  397. let deletions = 0;
  398. // How many characters, starting from `firstChangeAt`, should be inserted.
  399. let insertions = 0;
  400. for ( let i = firstChangeAt; i <= lastChangeAt; i++ ) {
  401. // If there is no change (equal) or delete, the character is existing in `oldText`. We count it for removing.
  402. if ( diffResult[ i ] != 'insert' ) {
  403. deletions++;
  404. }
  405. // If there is no change (equal) or insert, the character is existing in `newText`. We count it for inserting.
  406. if ( diffResult[ i ] != 'delete' ) {
  407. insertions++;
  408. }
  409. }
  410. return { insertions, deletions, firstChangeAt };
  411. }