injecttypingmutationshandling.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module typing/utils/injecttypingmutationshandling
  7. */
  8. import diff from '@ckeditor/ckeditor5-utils/src/diff';
  9. import DomConverter from '@ckeditor/ckeditor5-engine/src/view/domconverter';
  10. import { getSingleTextNodeChange, containerChildrenMutated } from './utils';
  11. /**
  12. * Handles mutations caused by normal typing.
  13. *
  14. * @param {module:core/editor/editor~Editor} editor The editor instance.
  15. */
  16. export default function injectTypingMutationsHandling( editor ) {
  17. editor.editing.view.document.on( 'mutations', ( evt, mutations, viewSelection ) => {
  18. new MutationHandler( editor ).handle( mutations, viewSelection );
  19. } );
  20. }
  21. /**
  22. * Helper class for translating DOM mutations into model changes.
  23. *
  24. * @private
  25. */
  26. class MutationHandler {
  27. /**
  28. * Creates an instance of the mutation handler.
  29. *
  30. * @param {module:core/editor/editor~Editor} editor
  31. */
  32. constructor( editor ) {
  33. /**
  34. * Editor instance for which mutations are handled.
  35. *
  36. * @readonly
  37. * @member {module:core/editor/editor~Editor} #editor
  38. */
  39. this.editor = editor;
  40. /**
  41. * The editing controller.
  42. *
  43. * @readonly
  44. * @member {module:engine/controller/editingcontroller~EditingController} #editing
  45. */
  46. this.editing = this.editor.editing;
  47. }
  48. /**
  49. * Handles given mutations.
  50. *
  51. * @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  52. * module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  53. * @param {module:engine/view/selection~Selection|null} viewSelection
  54. */
  55. handle( mutations, viewSelection ) {
  56. if ( containerChildrenMutated( mutations ) ) {
  57. this._handleContainerChildrenMutations( mutations, viewSelection );
  58. } else {
  59. for ( const mutation of mutations ) {
  60. // Fortunately it will never be both.
  61. this._handleTextMutation( mutation, viewSelection );
  62. this._handleTextNodeInsertion( mutation );
  63. }
  64. }
  65. }
  66. /**
  67. * Handles situations when container's children mutated during input. This can happen when
  68. * the browser is trying to "fix" DOM in certain situations. For example, when the user starts to type
  69. * in `<p><a href=""><i>Link{}</i></a></p>`, the browser might change the order of elements
  70. * to `<p><i><a href="">Link</a>x{}</i></p>`. A similar situation happens when the spell checker
  71. * replaces a word wrapped with `<strong>` with a word wrapped with a `<b>` element.
  72. *
  73. * To handle such situations, the common DOM ancestor of all mutations is converted to the model representation
  74. * and then compared with the current model to calculate the proper text change.
  75. *
  76. * Note: Single text node insertion is handled in {@link #_handleTextNodeInsertion} and text node mutation is handled
  77. * in {@link #_handleTextMutation}).
  78. *
  79. * @private
  80. * @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  81. * module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  82. * @param {module:engine/view/selection~Selection|null} viewSelection
  83. */
  84. _handleContainerChildrenMutations( mutations, viewSelection ) {
  85. // Get common ancestor of all mutations.
  86. const mutationsCommonAncestor = getMutationsContainer( mutations );
  87. // Quit if there is no common ancestor.
  88. if ( !mutationsCommonAncestor ) {
  89. return;
  90. }
  91. const domConverter = this.editor.editing.view.domConverter;
  92. // Get common ancestor in DOM.
  93. const domMutationCommonAncestor = domConverter.mapViewToDom( mutationsCommonAncestor );
  94. // Create fresh DomConverter so it will not use existing mapping and convert current DOM to model.
  95. // This wouldn't be needed if DomConverter would allow to create fresh view without checking any mappings.
  96. const freshDomConverter = new DomConverter( this.editor.editing.view.document );
  97. const modelFromCurrentDom = this.editor.data.toModel(
  98. freshDomConverter.domToView( domMutationCommonAncestor )
  99. ).getChild( 0 );
  100. // Current model.
  101. const currentModel = this.editor.editing.mapper.toModelElement( mutationsCommonAncestor );
  102. // If common ancestor is not mapped, do not do anything. It probably is a parent of another view element.
  103. // That means that we would need to diff model elements (see `if` below). Better return early instead of
  104. // trying to get a reasonable model ancestor. It will fell into the `if` below anyway.
  105. // This situation happens for example for lists. If `<ul>` is a common ancestor, `currentModel` is `undefined`
  106. // because `<ul>` is not mapped (`<li>`s are).
  107. // See https://github.com/ckeditor/ckeditor5/issues/718.
  108. if ( !currentModel ) {
  109. return;
  110. }
  111. // Get children from both ancestors.
  112. const modelFromDomChildren = Array.from( modelFromCurrentDom.getChildren() );
  113. const currentModelChildren = Array.from( currentModel.getChildren() );
  114. // Remove the last `<softBreak>` from the end of `modelFromDomChildren` if there is no `<softBreak>` in current model.
  115. // If the described scenario happened, it means that this is a bogus `<br />` added by a browser.
  116. const lastDomChild = modelFromDomChildren[ modelFromDomChildren.length - 1 ];
  117. const lastCurrentChild = currentModelChildren[ currentModelChildren.length - 1 ];
  118. if ( lastDomChild && lastDomChild.is( 'softBreak' ) && lastCurrentChild && !lastCurrentChild.is( 'softBreak' ) ) {
  119. modelFromDomChildren.pop();
  120. }
  121. const schema = this.editor.model.schema;
  122. // Skip situations when common ancestor has any container elements.
  123. if ( !isSafeForTextMutation( modelFromDomChildren, schema ) || !isSafeForTextMutation( currentModelChildren, schema ) ) {
  124. return;
  125. }
  126. // Replace &nbsp; inserted by the browser with normal space. See comment in `_handleTextMutation`.
  127. // Replace non-texts with any character. This is potentially dangerous but passes in manual tests. The thing is
  128. // that we need to take care of proper indexes so we cannot simply remove non-text elements from the content.
  129. // By inserting a character we keep all the real texts on their indexes.
  130. const newText = modelFromDomChildren.map( item => item.is( 'text' ) ? item.data : '@' ).join( '' ).replace( /\u00A0/g, ' ' );
  131. const oldText = currentModelChildren.map( item => item.is( 'text' ) ? item.data : '@' ).join( '' ).replace( /\u00A0/g, ' ' );
  132. // Do nothing if mutations created same text.
  133. if ( oldText === newText ) {
  134. return;
  135. }
  136. const diffResult = diff( oldText, newText );
  137. const { firstChangeAt, insertions, deletions } = calculateChanges( diffResult );
  138. // Try setting new model selection according to passed view selection.
  139. let modelSelectionRange = null;
  140. if ( viewSelection ) {
  141. modelSelectionRange = this.editing.mapper.toModelRange( viewSelection.getFirstRange() );
  142. }
  143. const insertText = newText.substr( firstChangeAt, insertions );
  144. const removeRange = this.editor.model.createRange(
  145. this.editor.model.createPositionAt( currentModel, firstChangeAt ),
  146. this.editor.model.createPositionAt( currentModel, firstChangeAt + deletions )
  147. );
  148. this.editor.execute( 'input', {
  149. text: insertText,
  150. range: removeRange,
  151. resultRange: modelSelectionRange
  152. } );
  153. }
  154. /**
  155. * @private
  156. */
  157. _handleTextMutation( mutation, viewSelection ) {
  158. if ( mutation.type != 'text' ) {
  159. return;
  160. }
  161. // Replace &nbsp; inserted by the browser with normal space.
  162. // We want only normal spaces in the model and in the view. Renderer and DOM Converter will be then responsible
  163. // for rendering consecutive spaces using &nbsp;, but the model and the view has to be clear.
  164. // Other feature may introduce inserting non-breakable space on specific key stroke (for example shift + space).
  165. // However then it will be handled outside of mutations, like enter key is.
  166. // The replacing is here because it has to be done before `diff` and `diffToChanges` functions, as they
  167. // take `newText` and compare it to (cleaned up) view.
  168. // It could also be done in mutation observer too, however if any outside plugin would like to
  169. // introduce additional events for mutations, they would get already cleaned up version (this may be good or not).
  170. const newText = mutation.newText.replace( /\u00A0/g, ' ' );
  171. // To have correct `diffResult`, we also compare view node text data with &nbsp; replaced by space.
  172. const oldText = mutation.oldText.replace( /\u00A0/g, ' ' );
  173. // Do nothing if mutations created same text.
  174. if ( oldText === newText ) {
  175. return;
  176. }
  177. const diffResult = diff( oldText, newText );
  178. const { firstChangeAt, insertions, deletions } = calculateChanges( diffResult );
  179. // Try setting new model selection according to passed view selection.
  180. let modelSelectionRange = null;
  181. if ( viewSelection ) {
  182. modelSelectionRange = this.editing.mapper.toModelRange( viewSelection.getFirstRange() );
  183. }
  184. // Get the position in view and model where the changes will happen.
  185. const viewPos = this.editing.view.createPositionAt( mutation.node, firstChangeAt );
  186. const modelPos = this.editing.mapper.toModelPosition( viewPos );
  187. const removeRange = this.editor.model.createRange( modelPos, modelPos.getShiftedBy( deletions ) );
  188. const insertText = newText.substr( firstChangeAt, insertions );
  189. this.editor.execute( 'input', {
  190. text: insertText,
  191. range: removeRange,
  192. resultRange: modelSelectionRange
  193. } );
  194. }
  195. /**
  196. * @private
  197. */
  198. _handleTextNodeInsertion( mutation ) {
  199. if ( mutation.type != 'children' ) {
  200. return;
  201. }
  202. const change = getSingleTextNodeChange( mutation );
  203. const viewPos = this.editing.view.createPositionAt( 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: this.editor.model.createRange( modelPos )
  213. } );
  214. }
  215. }
  216. // Returns first common ancestor of all mutations that is either {@link module:engine/view/containerelement~ContainerElement}
  217. // or {@link module:engine/view/rootelement~RootElement}.
  218. //
  219. // @private
  220. // @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
  221. // module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
  222. // @returns {module:engine/view/containerelement~ContainerElement|engine/view/rootelement~RootElement|undefined}
  223. function getMutationsContainer( mutations ) {
  224. const lca = mutations
  225. .map( mutation => mutation.node )
  226. .reduce( ( commonAncestor, node ) => {
  227. return commonAncestor.getCommonAncestor( node, { includeSelf: true } );
  228. } );
  229. if ( !lca ) {
  230. return;
  231. }
  232. // We need to look for container and root elements only, so check all LCA's
  233. // ancestors (starting from itself).
  234. return lca.getAncestors( { includeSelf: true, parentFirst: true } )
  235. .find( element => element.is( 'containerElement' ) || element.is( 'rootElement' ) );
  236. }
  237. // Returns true if provided array contains content that won't be problematic during diffing and text mutation handling.
  238. //
  239. // @param {Array.<module:engine/model/node~Node>} children
  240. // @param {module:engine/model/schema~Schema} schema
  241. // @returns {Boolean}
  242. function isSafeForTextMutation( children, schema ) {
  243. return children.every( child => schema.isInline( child ) );
  244. }
  245. // Calculates first change index and number of characters that should be inserted and deleted starting from that index.
  246. //
  247. // @private
  248. // @param diffResult
  249. // @returns {{insertions: number, deletions: number, firstChangeAt: *}}
  250. function calculateChanges( diffResult ) {
  251. // Index where the first change happens. Used to set the position from which nodes will be removed and where will be inserted.
  252. let firstChangeAt = null;
  253. // Index where the last change happens. Used to properly count how many characters have to be removed and inserted.
  254. let lastChangeAt = null;
  255. // Get `firstChangeAt` and `lastChangeAt`.
  256. for ( let i = 0; i < diffResult.length; i++ ) {
  257. const change = diffResult[ i ];
  258. if ( change != 'equal' ) {
  259. firstChangeAt = firstChangeAt === null ? i : firstChangeAt;
  260. lastChangeAt = i;
  261. }
  262. }
  263. // How many characters, starting from `firstChangeAt`, should be removed.
  264. let deletions = 0;
  265. // How many characters, starting from `firstChangeAt`, should be inserted.
  266. let insertions = 0;
  267. for ( let i = firstChangeAt; i <= lastChangeAt; i++ ) {
  268. // If there is no change (equal) or delete, the character is existing in `oldText`. We count it for removing.
  269. if ( diffResult[ i ] != 'insert' ) {
  270. deletions++;
  271. }
  272. // If there is no change (equal) or insert, the character is existing in `newText`. We count it for inserting.
  273. if ( diffResult[ i ] != 'delete' ) {
  274. insertions++;
  275. }
  276. }
  277. return { insertions, deletions, firstChangeAt };
  278. }