input.js 17 KB

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