8
0

input.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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(
  173. freshDomConverter.domToView( domMutationCommonAncestor ),
  174. this.editor.commands.get( 'input' ).buffer.batch
  175. ).getChild( 0 );
  176. // Current model.
  177. const currentModel = this.editor.editing.mapper.toModelElement( mutationsCommonAncestor );
  178. // Get children from both ancestors.
  179. const modelFromDomChildren = Array.from( modelFromCurrentDom.getChildren() );
  180. const currentModelChildren = Array.from( currentModel.getChildren() );
  181. // Skip situations when common ancestor has any elements (cause they are too hard).
  182. if ( !hasOnlyTextNodes( modelFromDomChildren ) || !hasOnlyTextNodes( currentModelChildren ) ) {
  183. return;
  184. }
  185. // Replace &nbsp; inserted by the browser with normal space.
  186. // See comment in `_handleTextMutation`.
  187. const newText = modelFromDomChildren.map( item => item.data ).join( '' ).replace( /\u00A0/g, ' ' );
  188. const oldText = currentModelChildren.map( item => item.data ).join( '' );
  189. // Do nothing if mutations created same text.
  190. if ( oldText === newText ) {
  191. return;
  192. }
  193. const diffResult = diff( oldText, newText );
  194. const { firstChangeAt, insertions, deletions } = calculateChanges( diffResult );
  195. // Try setting new model selection according to passed view selection.
  196. let modelSelectionRange = null;
  197. if ( viewSelection ) {
  198. modelSelectionRange = this.editing.mapper.toModelRange( viewSelection.getFirstRange() );
  199. }
  200. const insertText = newText.substr( firstChangeAt, insertions );
  201. const removeRange = ModelRange.createFromParentsAndOffsets(
  202. currentModel,
  203. firstChangeAt,
  204. currentModel,
  205. firstChangeAt + deletions
  206. );
  207. this.editor.execute( 'input', {
  208. text: insertText,
  209. range: removeRange,
  210. resultRange: modelSelectionRange
  211. } );
  212. }
  213. _handleTextMutation( mutation, viewSelection ) {
  214. if ( mutation.type != 'text' ) {
  215. return;
  216. }
  217. // Replace &nbsp; inserted by the browser with normal space.
  218. // We want only normal spaces in the model and in the view. Renderer and DOM Converter will be then responsible
  219. // for rendering consecutive spaces using &nbsp;, but the model and the view has to be clear.
  220. // Other feature may introduce inserting non-breakable space on specific key stroke (for example shift + space).
  221. // However then it will be handled outside of mutations, like enter key is.
  222. // The replacing is here because it has to be done before `diff` and `diffToChanges` functions, as they
  223. // take `newText` and compare it to (cleaned up) view.
  224. // It could also be done in mutation observer too, however if any outside plugin would like to
  225. // introduce additional events for mutations, they would get already cleaned up version (this may be good or not).
  226. const newText = mutation.newText.replace( /\u00A0/g, ' ' );
  227. // To have correct `diffResult`, we also compare view node text data with &nbsp; replaced by space.
  228. const oldText = mutation.oldText.replace( /\u00A0/g, ' ' );
  229. const diffResult = diff( oldText, newText );
  230. const { firstChangeAt, insertions, deletions } = calculateChanges( diffResult );
  231. // Try setting new model selection according to passed view selection.
  232. let modelSelectionRange = null;
  233. if ( viewSelection ) {
  234. modelSelectionRange = this.editing.mapper.toModelRange( viewSelection.getFirstRange() );
  235. }
  236. // Get the position in view and model where the changes will happen.
  237. const viewPos = new ViewPosition( mutation.node, firstChangeAt );
  238. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  239. const removeRange = ModelRange.createFromPositionAndShift( modelPos, deletions );
  240. const insertText = newText.substr( firstChangeAt, insertions );
  241. this.editor.execute( 'input', {
  242. text: insertText,
  243. range: removeRange,
  244. resultRange: modelSelectionRange
  245. } );
  246. }
  247. _handleTextNodeInsertion( mutation ) {
  248. if ( mutation.type != 'children' ) {
  249. return;
  250. }
  251. const change = getSingleTextNodeChange( mutation );
  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 that is either {@link module:engine/view/containerelement~ContainerElement}
  333. // or {@link module:engine/view/rootelement~RootElement}.
  334. //
  335. // @private
  336. // @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  337. // module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  338. // @returns {module:engine/view/containerelement~ContainerElement|engine/view/rootelement~RootElement|undefined}
  339. function getMutationsContainer( mutations ) {
  340. const lca = mutations
  341. .map( mutation => mutation.node )
  342. .reduce( ( commonAncestor, node ) => {
  343. return commonAncestor.getCommonAncestor( node, { includeSelf: true } );
  344. } );
  345. if ( !lca ) {
  346. return;
  347. }
  348. // We need to look for container and root elements only, so check all LCA's
  349. // ancestors (starting from itself).
  350. return lca.getAncestors( { includeSelf: true, parentFirst: true } )
  351. .find( element => element.is( 'containerElement' ) || element.is( 'rootElement' ) );
  352. }
  353. // Returns true if container children have mutated or more than a single text node was changed.
  354. //
  355. // Single text node child insertion is handled in {@link module:typing/input~MutationHandler#_handleTextNodeInsertion}
  356. // while text mutation is handled in {@link module:typing/input~MutationHandler#_handleTextMutation}.
  357. //
  358. // @private
  359. // @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  360. // module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  361. // @returns {Boolean}
  362. function containerChildrenMutated( mutations ) {
  363. if ( mutations.length == 0 ) {
  364. return false;
  365. }
  366. // Check if there is any mutation of `children` type or any mutation that changes more than one text node.
  367. for ( const mutation of mutations ) {
  368. if ( mutation.type === 'children' && !getSingleTextNodeChange( mutation ) ) {
  369. return true;
  370. }
  371. }
  372. return false;
  373. }
  374. // Returns true if provided array contains only {@link module:engine/model/text~Text model text nodes}.
  375. //
  376. // @param {Array.<module:engine/model/node~Node>} children
  377. // @returns {Boolean}
  378. function hasOnlyTextNodes( children ) {
  379. return children.every( child => child.is( 'text' ) );
  380. }
  381. // Calculates first change index and number of characters that should be inserted and deleted starting from that index.
  382. //
  383. // @private
  384. // @param diffResult
  385. // @return {{insertions: number, deletions: number, firstChangeAt: *}}
  386. function calculateChanges( diffResult ) {
  387. // Index where the first change happens. Used to set the position from which nodes will be removed and where will be inserted.
  388. let firstChangeAt = null;
  389. // Index where the last change happens. Used to properly count how many characters have to be removed and inserted.
  390. let lastChangeAt = null;
  391. // Get `firstChangeAt` and `lastChangeAt`.
  392. for ( let i = 0; i < diffResult.length; i++ ) {
  393. const change = diffResult[ i ];
  394. if ( change != 'equal' ) {
  395. firstChangeAt = firstChangeAt === null ? i : firstChangeAt;
  396. lastChangeAt = i;
  397. }
  398. }
  399. // How many characters, starting from `firstChangeAt`, should be removed.
  400. let deletions = 0;
  401. // How many characters, starting from `firstChangeAt`, should be inserted.
  402. let insertions = 0;
  403. for ( let i = firstChangeAt; i <= lastChangeAt; i++ ) {
  404. // If there is no change (equal) or delete, the character is existing in `oldText`. We count it for removing.
  405. if ( diffResult[ i ] != 'insert' ) {
  406. deletions++;
  407. }
  408. // If there is no change (equal) or insert, the character is existing in `newText`. We count it for inserting.
  409. if ( diffResult[ i ] != 'delete' ) {
  410. insertions++;
  411. }
  412. }
  413. return { insertions, deletions, firstChangeAt };
  414. }