renderer.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /* globals Node */
  6. /**
  7. * @module engine/view/renderer
  8. */
  9. import ViewText from './text';
  10. import ViewPosition from './position';
  11. import { INLINE_FILLER, INLINE_FILLER_LENGTH, startsWithFiller, isInlineFiller, isBlockFiller } from './filler';
  12. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  13. import diff from '@ckeditor/ckeditor5-utils/src/diff';
  14. import insertAt from '@ckeditor/ckeditor5-utils/src/dom/insertat';
  15. import remove from '@ckeditor/ckeditor5-utils/src/dom/remove';
  16. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  17. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  18. import isText from '@ckeditor/ckeditor5-utils/src/dom/istext';
  19. import isNode from '@ckeditor/ckeditor5-utils/src/dom/isnode';
  20. import fastDiff from '@ckeditor/ckeditor5-utils/src/fastdiff';
  21. import env from '@ckeditor/ckeditor5-utils/src/env';
  22. /**
  23. * Renderer is responsible for updating the DOM structure and the DOM selection based on
  24. * the {@link module:engine/view/renderer~Renderer#markToSync information about updated view nodes}.
  25. * In other words, it renders the view to the DOM.
  26. *
  27. * Its main responsibility is to make only the necessary, minimal changes to the DOM. However, unlike in many
  28. * virtual DOM implementations, the primary reason for doing minimal changes is not the performance but ensuring
  29. * that native editing features such as text composition, autocompletion, spell checking, selection's x-index are
  30. * affected as little as possible.
  31. *
  32. * Renderer uses {@link module:engine/view/domconverter~DomConverter} to transform view nodes and positions
  33. * to and from the DOM.
  34. */
  35. export default class Renderer {
  36. /**
  37. * Creates a renderer instance.
  38. *
  39. * @param {module:engine/view/domconverter~DomConverter} domConverter Converter instance.
  40. * @param {module:engine/view/documentselection~DocumentSelection} selection View selection.
  41. */
  42. constructor( domConverter, selection ) {
  43. /**
  44. * Set of DOM Documents instances.
  45. *
  46. * @readonly
  47. * @member {Set.<Document>}
  48. */
  49. this.domDocuments = new Set();
  50. /**
  51. * Converter instance.
  52. *
  53. * @readonly
  54. * @member {module:engine/view/domconverter~DomConverter}
  55. */
  56. this.domConverter = domConverter;
  57. /**
  58. * Set of nodes which attributes changed and may need to be rendered.
  59. *
  60. * @readonly
  61. * @member {Set.<module:engine/view/node~Node>}
  62. */
  63. this.markedAttributes = new Set();
  64. /**
  65. * Set of elements which child lists changed and may need to be rendered.
  66. *
  67. * @readonly
  68. * @member {Set.<module:engine/view/node~Node>}
  69. */
  70. this.markedChildren = new Set();
  71. /**
  72. * Set of text nodes which text data changed and may need to be rendered.
  73. *
  74. * @readonly
  75. * @member {Set.<module:engine/view/node~Node>}
  76. */
  77. this.markedTexts = new Set();
  78. /**
  79. * View selection. Renderer updates DOM selection based on the view selection.
  80. *
  81. * @readonly
  82. * @member {module:engine/view/documentselection~DocumentSelection}
  83. */
  84. this.selection = selection;
  85. /**
  86. * Indicates if the view document is focused and selection can be rendered. Selection will not be rendered if
  87. * this is set to `false`.
  88. *
  89. * @member {Boolean}
  90. */
  91. this.isFocused = false;
  92. /**
  93. * The text node in which the inline filler was rendered.
  94. *
  95. * @private
  96. * @member {Text}
  97. */
  98. this._inlineFiller = null;
  99. /**
  100. * DOM element containing fake selection.
  101. *
  102. * @private
  103. * @type {null|HTMLElement}
  104. */
  105. this._fakeSelectionContainer = null;
  106. }
  107. /**
  108. * Marks a view node to be updated in the DOM by {@link #render `render()`}.
  109. *
  110. * Note that only view nodes whose parents have corresponding DOM elements need to be marked to be synchronized.
  111. *
  112. * @see #markedAttributes
  113. * @see #markedChildren
  114. * @see #markedTexts
  115. *
  116. * @param {module:engine/view/document~ChangeType} type Type of the change.
  117. * @param {module:engine/view/node~Node} node Node to be marked.
  118. */
  119. markToSync( type, node ) {
  120. if ( type === 'text' ) {
  121. if ( this.domConverter.mapViewToDom( node.parent ) ) {
  122. this.markedTexts.add( node );
  123. }
  124. } else {
  125. // If the node has no DOM element it is not rendered yet,
  126. // its children/attributes do not need to be marked to be sync.
  127. if ( !this.domConverter.mapViewToDom( node ) ) {
  128. return;
  129. }
  130. if ( type === 'attributes' ) {
  131. this.markedAttributes.add( node );
  132. } else if ( type === 'children' ) {
  133. this.markedChildren.add( node );
  134. } else {
  135. /**
  136. * Unknown type passed to Renderer.markToSync.
  137. *
  138. * @error renderer-unknown-type
  139. */
  140. throw new CKEditorError( 'view-renderer-unknown-type: Unknown type passed to Renderer.markToSync.' );
  141. }
  142. }
  143. }
  144. /**
  145. * Renders all buffered changes ({@link #markedAttributes}, {@link #markedChildren} and {@link #markedTexts}) and
  146. * the current view selection (if needed) to the DOM by applying a minimal set of changes to it.
  147. *
  148. * Renderer tries not to break the text composition (e.g. IME) and x-index of the selection,
  149. * so it does as little as it is needed to update the DOM.
  150. *
  151. * Renderer also handles {@link module:engine/view/filler fillers}. Especially, it checks if the inline filler is needed
  152. * at the selection position and adds or removes it. To prevent breaking text composition inline filler will not be
  153. * removed as long as the selection is in the text node which needed it at first.
  154. */
  155. render() {
  156. let inlineFillerPosition;
  157. // Refresh mappings.
  158. for ( const element of this.markedChildren ) {
  159. this._updateChildrenMappings( element );
  160. }
  161. // There was inline filler rendered in the DOM but it's not
  162. // at the selection position any more, so we can remove it
  163. // (cause even if it's needed, it must be placed in another location).
  164. if ( this._inlineFiller && !this._isSelectionInInlineFiller() ) {
  165. this._removeInlineFiller();
  166. }
  167. // If we've got the filler, let's try to guess its position in the view.
  168. if ( this._inlineFiller ) {
  169. inlineFillerPosition = this._getInlineFillerPosition();
  170. }
  171. // Otherwise, if it's needed, create it at the selection position.
  172. else if ( this._needsInlineFillerAtSelection() ) {
  173. inlineFillerPosition = this.selection.getFirstPosition();
  174. // Do not use `markToSync` so it will be added even if the parent is already added.
  175. this.markedChildren.add( inlineFillerPosition.parent );
  176. }
  177. for ( const element of this.markedAttributes ) {
  178. this._updateAttrs( element );
  179. }
  180. for ( const element of this.markedChildren ) {
  181. this._updateChildren( element, { inlineFillerPosition } );
  182. }
  183. for ( const node of this.markedTexts ) {
  184. if ( !this.markedChildren.has( node.parent ) && this.domConverter.mapViewToDom( node.parent ) ) {
  185. this._updateText( node, { inlineFillerPosition } );
  186. }
  187. }
  188. // Check whether the inline filler is required and where it really is in the DOM.
  189. // At this point in most cases it will be in the DOM, but there are exceptions.
  190. // For example, if the inline filler was deep in the created DOM structure, it will not be created.
  191. // Similarly, if it was removed at the beginning of this function and then neither text nor children were updated,
  192. // it will not be present.
  193. // Fix those and similar scenarios.
  194. if ( inlineFillerPosition ) {
  195. const fillerDomPosition = this.domConverter.viewPositionToDom( inlineFillerPosition );
  196. const domDocument = fillerDomPosition.parent.ownerDocument;
  197. if ( !startsWithFiller( fillerDomPosition.parent ) ) {
  198. // Filler has not been created at filler position. Create it now.
  199. this._inlineFiller = addInlineFiller( domDocument, fillerDomPosition.parent, fillerDomPosition.offset );
  200. } else {
  201. // Filler has been found, save it.
  202. this._inlineFiller = fillerDomPosition.parent;
  203. }
  204. } else {
  205. // There is no filler needed.
  206. this._inlineFiller = null;
  207. }
  208. this._updateSelection();
  209. this._updateFocus();
  210. this.markedTexts.clear();
  211. this.markedAttributes.clear();
  212. this.markedChildren.clear();
  213. }
  214. /**
  215. * Updates mappings of view element's children.
  216. *
  217. * Children that were replaced in the view structure by similar elements (same tag name) are treated as 'replaced'.
  218. * This means that their mappings can be updated so the new view elements are mapped to the existing DOM elements.
  219. * Thanks to that these elements do not need to be re-rendered completely.
  220. *
  221. * @private
  222. * @param {module:engine/view/node~Node} viewElement The view element whose children mappings will be updated.
  223. */
  224. _updateChildrenMappings( viewElement ) {
  225. const domElement = this.domConverter.mapViewToDom( viewElement );
  226. if ( !domElement ) {
  227. // If there is no `domElement` it means that it was already removed from DOM and there is no need to process it.
  228. return;
  229. }
  230. const actualDomChildren = this.domConverter.mapViewToDom( viewElement ).childNodes;
  231. const expectedDomChildren = Array.from(
  232. this.domConverter.viewChildrenToDom( viewElement, domElement.ownerDocument, { withChildren: false } )
  233. );
  234. const diff = this._diffNodeLists( actualDomChildren, expectedDomChildren );
  235. const actions = this._findReplaceActions( diff, actualDomChildren, expectedDomChildren );
  236. if ( actions.indexOf( 'replace' ) !== -1 ) {
  237. const counter = { equal: 0, insert: 0, delete: 0 };
  238. for ( const action of actions ) {
  239. if ( action === 'replace' ) {
  240. const insertIndex = counter.equal + counter.insert;
  241. const deleteIndex = counter.equal + counter.delete;
  242. const viewChild = viewElement.getChild( insertIndex );
  243. // The 'uiElement' is a special one and its children are not stored in a view (#799),
  244. // so we cannot use it with replacing flow (since it uses view children during rendering
  245. // which will always result in rendering empty element).
  246. if ( viewChild && !viewChild.is( 'uiElement' ) ) {
  247. this._updateElementMappings( viewChild, actualDomChildren[ deleteIndex ] );
  248. }
  249. remove( expectedDomChildren[ insertIndex ] );
  250. counter.equal++;
  251. } else {
  252. counter[ action ]++;
  253. }
  254. }
  255. }
  256. }
  257. /**
  258. * Updates mappings of a given view element.
  259. *
  260. * @private
  261. * @param {module:engine/view/node~Node} viewElement The view element whose mappings will be updated.
  262. * @param {Node} domElement The DOM element representing the given view element.
  263. */
  264. _updateElementMappings( viewElement, domElement ) {
  265. // Remap 'DomConverter' bindings.
  266. this.domConverter.unbindDomElement( domElement );
  267. this.domConverter.bindElements( domElement, viewElement );
  268. // View element may have children which needs to be updated, but are not marked, mark them to update.
  269. this.markedChildren.add( viewElement );
  270. // Because we replace new view element mapping with the existing one, the corresponding DOM element
  271. // will not be rerendered. The new view element may have different attributes than the previous one.
  272. // Since its corresponding DOM element will not be rerendered, new attributes will not be added
  273. // to the DOM, so we need to mark it here to make sure its attributes gets updated. See #1427 for more
  274. // detailed case study.
  275. // Also there are cases where replaced element is removed from the view structure and then has
  276. // its attributes changed or removed. In such cases the element will not be present in `markedAttributes`
  277. // and also may be the same (`element.isSimilar()`) as the reused element not having its attributes updated.
  278. // To prevent such situations we always mark reused element to have its attributes rerenderd (#1560).
  279. this.markedAttributes.add( viewElement );
  280. }
  281. /**
  282. * Gets the position of the inline filler based on the current selection.
  283. * Here, we assume that we know that the filler is needed and
  284. * {@link #_isSelectionInInlineFiller is at the selection position}, and, since it is needed,
  285. * it is somewhere at the selection position.
  286. *
  287. * Note: The filler position cannot be restored based on the filler's DOM text node, because
  288. * when this method is called (before rendering), the bindings will often be broken. View-to-DOM
  289. * bindings are only dependable after rendering.
  290. *
  291. * @private
  292. * @returns {module:engine/view/position~Position}
  293. */
  294. _getInlineFillerPosition() {
  295. const firstPos = this.selection.getFirstPosition();
  296. if ( firstPos.parent.is( 'text' ) ) {
  297. return ViewPosition._createBefore( this.selection.getFirstPosition().parent );
  298. } else {
  299. return firstPos;
  300. }
  301. }
  302. /**
  303. * Returns `true` if the selection has not left the inline filler's text node.
  304. * If it is `true`, it means that the filler had been added for a reason and the selection did not
  305. * leave the filler's text node. For example, the user can be in the middle of a composition so it should not be touched.
  306. *
  307. * @private
  308. * @returns {Boolean} `true` if the inline filler and selection are in the same place.
  309. */
  310. _isSelectionInInlineFiller() {
  311. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  312. return false;
  313. }
  314. // Note, we can't check if selection's position equals position of the
  315. // this._inlineFiller node, because of #663. We may not be able to calculate
  316. // the filler's position in the view at this stage.
  317. // Instead, we check it the other way – whether selection is anchored in
  318. // that text node or next to it.
  319. // Possible options are:
  320. // "FILLER{}"
  321. // "FILLERadded-text{}"
  322. const selectionPosition = this.selection.getFirstPosition();
  323. const position = this.domConverter.viewPositionToDom( selectionPosition );
  324. if ( position && isText( position.parent ) && startsWithFiller( position.parent ) ) {
  325. return true;
  326. }
  327. return false;
  328. }
  329. /**
  330. * Removes the inline filler.
  331. *
  332. * @private
  333. */
  334. _removeInlineFiller() {
  335. const domFillerNode = this._inlineFiller;
  336. // Something weird happened and the stored node doesn't contain the filler's text.
  337. if ( !startsWithFiller( domFillerNode ) ) {
  338. /**
  339. * The inline filler node was lost. Most likely, something overwrote the filler text node
  340. * in the DOM.
  341. *
  342. * @error view-renderer-filler-was-lost
  343. */
  344. throw new CKEditorError( 'view-renderer-filler-was-lost: The inline filler node was lost.' );
  345. }
  346. if ( isInlineFiller( domFillerNode ) ) {
  347. domFillerNode.parentNode.removeChild( domFillerNode );
  348. } else {
  349. domFillerNode.data = domFillerNode.data.substr( INLINE_FILLER_LENGTH );
  350. }
  351. this._inlineFiller = null;
  352. }
  353. /**
  354. * Checks if the inline {@link module:engine/view/filler filler} should be added.
  355. *
  356. * @private
  357. * @returns {Boolean} `true` if the inline filler should be added.
  358. */
  359. _needsInlineFillerAtSelection() {
  360. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  361. return false;
  362. }
  363. const selectionPosition = this.selection.getFirstPosition();
  364. const selectionParent = selectionPosition.parent;
  365. const selectionOffset = selectionPosition.offset;
  366. // If there is no DOM root we do not care about fillers.
  367. if ( !this.domConverter.mapViewToDom( selectionParent.root ) ) {
  368. return false;
  369. }
  370. if ( !( selectionParent.is( 'element' ) ) ) {
  371. return false;
  372. }
  373. // Prevent adding inline filler inside elements with contenteditable=false.
  374. // https://github.com/ckeditor/ckeditor5-engine/issues/1170
  375. if ( !isEditable( selectionParent ) ) {
  376. return false;
  377. }
  378. // We have block filler, we do not need inline one.
  379. if ( selectionOffset === selectionParent.getFillerOffset() ) {
  380. return false;
  381. }
  382. const nodeBefore = selectionPosition.nodeBefore;
  383. const nodeAfter = selectionPosition.nodeAfter;
  384. if ( nodeBefore instanceof ViewText || nodeAfter instanceof ViewText ) {
  385. return false;
  386. }
  387. return true;
  388. }
  389. /**
  390. * Checks if text needs to be updated and possibly updates it.
  391. *
  392. * @private
  393. * @param {module:engine/view/text~Text} viewText View text to update.
  394. * @param {Object} options
  395. * @param {module:engine/view/position~Position} options.inlineFillerPosition The position where the inline
  396. * filler should be rendered.
  397. */
  398. _updateText( viewText, options ) {
  399. const domText = this.domConverter.findCorrespondingDomText( viewText );
  400. const newDomText = this.domConverter.viewToDom( viewText, domText.ownerDocument );
  401. const actualText = domText.data;
  402. let expectedText = newDomText.data;
  403. const filler = options.inlineFillerPosition;
  404. if ( filler && filler.parent == viewText.parent && filler.offset == viewText.index ) {
  405. expectedText = INLINE_FILLER + expectedText;
  406. }
  407. if ( actualText != expectedText ) {
  408. const actions = fastDiff( actualText, expectedText );
  409. for ( const action of actions ) {
  410. if ( action.type === 'insert' ) {
  411. domText.insertData( action.index, action.values.join( '' ) );
  412. } else { // 'delete'
  413. domText.deleteData( action.index, action.howMany );
  414. }
  415. }
  416. }
  417. }
  418. /**
  419. * Checks if attribute list needs to be updated and possibly updates it.
  420. *
  421. * @private
  422. * @param {module:engine/view/element~Element} viewElement The view element to update.
  423. */
  424. _updateAttrs( viewElement ) {
  425. const domElement = this.domConverter.mapViewToDom( viewElement );
  426. if ( !domElement ) {
  427. // If there is no `domElement` it means that 'viewElement' is outdated as its mapping was updated
  428. // in 'this._updateChildrenMappings()'. There is no need to process it as new view element which
  429. // replaced old 'viewElement' mapping was also added to 'this.markedAttributes'
  430. // in 'this._updateChildrenMappings()' so it will be processed separately.
  431. return;
  432. }
  433. const domAttrKeys = Array.from( domElement.attributes ).map( attr => attr.name );
  434. const viewAttrKeys = viewElement.getAttributeKeys();
  435. // Add or overwrite attributes.
  436. for ( const key of viewAttrKeys ) {
  437. domElement.setAttribute( key, viewElement.getAttribute( key ) );
  438. }
  439. // Remove from DOM attributes which do not exists in the view.
  440. for ( const key of domAttrKeys ) {
  441. if ( !viewElement.hasAttribute( key ) ) {
  442. domElement.removeAttribute( key );
  443. }
  444. }
  445. }
  446. /**
  447. * Checks if elements child list needs to be updated and possibly updates it.
  448. *
  449. * @private
  450. * @param {module:engine/view/element~Element} viewElement View element to update.
  451. * @param {Object} options
  452. * @param {module:engine/view/position~Position} options.inlineFillerPosition The position where the inline
  453. * filler should be rendered.
  454. */
  455. _updateChildren( viewElement, options ) {
  456. const domElement = this.domConverter.mapViewToDom( viewElement );
  457. if ( !domElement ) {
  458. // If there is no `domElement` it means that it was already removed from DOM.
  459. // There is no need to process it. It will be processed when re-inserted.
  460. return;
  461. }
  462. const inlineFillerPosition = options.inlineFillerPosition;
  463. const actualDomChildren = this.domConverter.mapViewToDom( viewElement ).childNodes;
  464. const expectedDomChildren = Array.from(
  465. this.domConverter.viewChildrenToDom( viewElement, domElement.ownerDocument, { bind: true, inlineFillerPosition } )
  466. );
  467. // Inline filler element has to be created as it is present in the DOM, but not in the view. It is required
  468. // during diffing so text nodes could be compared correctly and also during rendering to maintain
  469. // proper order and indexes while updating the DOM.
  470. if ( inlineFillerPosition && inlineFillerPosition.parent === viewElement ) {
  471. addInlineFiller( domElement.ownerDocument, expectedDomChildren, inlineFillerPosition.offset );
  472. }
  473. const diff = this._diffNodeLists( actualDomChildren, expectedDomChildren );
  474. let i = 0;
  475. const nodesToUnbind = new Set();
  476. for ( const action of diff ) {
  477. if ( action === 'insert' ) {
  478. insertAt( domElement, i, expectedDomChildren[ i ] );
  479. i++;
  480. } else if ( action === 'delete' ) {
  481. nodesToUnbind.add( actualDomChildren[ i ] );
  482. remove( actualDomChildren[ i ] );
  483. } else { // 'equal'
  484. // Force updating text nodes inside elements which did not change and do not need to be re-rendered (#1125).
  485. this._markDescendantTextToSync( this.domConverter.domToView( expectedDomChildren[ i ] ) );
  486. i++;
  487. }
  488. }
  489. // Unbind removed nodes. When node does not have a parent it means that it was removed from DOM tree during
  490. // comparision with the expected DOM. We don't need to check child nodes, because if child node was reinserted,
  491. // it was moved to DOM tree out of the removed node.
  492. for ( const node of nodesToUnbind ) {
  493. if ( !node.parentNode ) {
  494. this.domConverter.unbindDomElement( node );
  495. }
  496. }
  497. }
  498. /**
  499. * Shorthand for diffing two arrays or node lists of DOM nodes.
  500. *
  501. * @private
  502. * @param {Array.<Node>|NodeList} actualDomChildren Actual DOM children
  503. * @param {Array.<Node>|NodeList} expectedDomChildren Expected DOM children.
  504. * @returns {Array.<String>} The list of actions based on the {@link module:utils/diff~diff} function.
  505. */
  506. _diffNodeLists( actualDomChildren, expectedDomChildren ) {
  507. return diff( actualDomChildren, expectedDomChildren, sameNodes.bind( null, this.domConverter.blockFiller ) );
  508. }
  509. /**
  510. * Finds DOM nodes that were replaced with the similar nodes (same tag name) in the view. All nodes are compared
  511. * within one `insert`/`delete` action group, for example:
  512. *
  513. * Actual DOM: <p><b>Foo</b>Bar<i>Baz</i><b>Bax</b></p>
  514. * Expected DOM: <p>Bar<b>123</b><i>Baz</i><b>456</b></p>
  515. * Input actions: [ insert, insert, delete, delete, equal, insert, delete ]
  516. * Output actions: [ insert, replace, delete, equal, replace ]
  517. *
  518. * @private
  519. * @param {Array.<String>} actions Actions array which is a result of the {@link module:utils/diff~diff} function.
  520. * @param {Array.<Node>|NodeList} actualDom Actual DOM children
  521. * @param {Array.<Node>} expectedDom Expected DOM children.
  522. * @returns {Array.<String>} Actions array modified with the `replace` actions.
  523. */
  524. _findReplaceActions( actions, actualDom, expectedDom ) {
  525. // If there is no both 'insert' and 'delete' actions, no need to check for replaced elements.
  526. if ( actions.indexOf( 'insert' ) === -1 || actions.indexOf( 'delete' ) === -1 ) {
  527. return actions;
  528. }
  529. let newActions = [];
  530. let actualSlice = [];
  531. let expectedSlice = [];
  532. const counter = { equal: 0, insert: 0, delete: 0 };
  533. for ( const action of actions ) {
  534. if ( action === 'insert' ) {
  535. expectedSlice.push( expectedDom[ counter.equal + counter.insert ] );
  536. } else if ( action === 'delete' ) {
  537. actualSlice.push( actualDom[ counter.equal + counter.delete ] );
  538. } else { // equal
  539. newActions = newActions.concat( diff( actualSlice, expectedSlice, areSimilar ).map( x => x === 'equal' ? 'replace' : x ) );
  540. newActions.push( 'equal' );
  541. // Reset stored elements on 'equal'.
  542. actualSlice = [];
  543. expectedSlice = [];
  544. }
  545. counter[ action ]++;
  546. }
  547. return newActions.concat( diff( actualSlice, expectedSlice, areSimilar ).map( x => x === 'equal' ? 'replace' : x ) );
  548. }
  549. /**
  550. * Marks text nodes to be synchronized.
  551. *
  552. * If a text node is passed, it will be marked. If an element is passed, all descendant text nodes inside it will be marked.
  553. *
  554. * @private
  555. * @param {module:engine/view/node~Node} viewNode View node to sync.
  556. */
  557. _markDescendantTextToSync( viewNode ) {
  558. if ( !viewNode ) {
  559. return;
  560. }
  561. if ( viewNode.is( 'text' ) ) {
  562. this.markedTexts.add( viewNode );
  563. } else if ( viewNode.is( 'element' ) ) {
  564. for ( const child of viewNode.getChildren() ) {
  565. this._markDescendantTextToSync( child );
  566. }
  567. }
  568. }
  569. /**
  570. * Checks if the selection needs to be updated and possibly updates it.
  571. *
  572. * @private
  573. */
  574. _updateSelection() {
  575. // If there is no selection - remove DOM and fake selections.
  576. if ( this.selection.rangeCount === 0 ) {
  577. this._removeDomSelection();
  578. this._removeFakeSelection();
  579. return;
  580. }
  581. const domRoot = this.domConverter.mapViewToDom( this.selection.editableElement );
  582. // Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.
  583. if ( !this.isFocused || !domRoot ) {
  584. return;
  585. }
  586. // Render selection.
  587. if ( this.selection.isFake ) {
  588. this._updateFakeSelection( domRoot );
  589. } else {
  590. this._removeFakeSelection();
  591. this._updateDomSelection( domRoot );
  592. }
  593. }
  594. /**
  595. * Updates the fake selection.
  596. *
  597. * @private
  598. * @param {HTMLElement} domRoot A valid DOM root where the fake selection container should be added.
  599. */
  600. _updateFakeSelection( domRoot ) {
  601. const domDocument = domRoot.ownerDocument;
  602. let container = this._fakeSelectionContainer;
  603. // Create fake selection container if one does not exist.
  604. if ( !container ) {
  605. this._fakeSelectionContainer = container = domDocument.createElement( 'div' );
  606. Object.assign( container.style, {
  607. position: 'fixed',
  608. top: 0,
  609. left: '-9999px',
  610. // See https://github.com/ckeditor/ckeditor5/issues/752.
  611. width: '42px'
  612. } );
  613. // Fill it with a text node so we can update it later.
  614. container.appendChild( domDocument.createTextNode( '\u00A0' ) );
  615. }
  616. if ( container.parentElement && container.parentElement != domRoot ) {
  617. container.remove( container );
  618. }
  619. if ( !container.parentElement ) {
  620. domRoot.appendChild( container );
  621. }
  622. // Update contents.
  623. container.firstChild.data = this.selection.fakeSelectionLabel || '\u00A0';
  624. // Update selection.
  625. const domSelection = domDocument.getSelection();
  626. const domRange = domDocument.createRange();
  627. domSelection.removeAllRanges();
  628. domRange.selectNodeContents( container );
  629. domSelection.addRange( domRange );
  630. // Bind fake selection container with current selection.
  631. this.domConverter.bindFakeSelection( container, this.selection );
  632. }
  633. /**
  634. * Updates the DOM selection.
  635. *
  636. * @private
  637. * @param {HTMLElement} domRoot A valid DOM root where the DOM selection should be rendered.
  638. */
  639. _updateDomSelection( domRoot ) {
  640. const domSelection = domRoot.ownerDocument.defaultView.getSelection();
  641. // Let's check whether DOM selection needs updating at all.
  642. if ( !this._domSelectionNeedsUpdate( domSelection ) ) {
  643. return;
  644. }
  645. // Multi-range selection is not available in most browsers, and, at least in Chrome, trying to
  646. // set such selection, that is not continuous, throws an error. Because of that, we will just use anchor
  647. // and focus of view selection.
  648. // Since we are not supporting multi-range selection, we also do not need to check if proper editable is
  649. // selected. If there is any editable selected, it is okay (editable is taken from selection anchor).
  650. const anchor = this.domConverter.viewPositionToDom( this.selection.anchor );
  651. const focus = this.domConverter.viewPositionToDom( this.selection.focus );
  652. // Focus the new editing host.
  653. // Otherwise, FF may throw an error (https://github.com/ckeditor/ckeditor5/issues/721).
  654. domRoot.focus();
  655. domSelection.collapse( anchor.parent, anchor.offset );
  656. domSelection.extend( focus.parent, focus.offset );
  657. // Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439).
  658. if ( env.isGecko ) {
  659. fixGeckoSelectionAfterBr( focus, domSelection );
  660. }
  661. }
  662. /**
  663. * Checks whether a given DOM selection needs to be updated.
  664. *
  665. * @private
  666. * @param {Selection} domSelection The DOM selection to check.
  667. * @returns {Boolean}
  668. */
  669. _domSelectionNeedsUpdate( domSelection ) {
  670. if ( !this.domConverter.isDomSelectionCorrect( domSelection ) ) {
  671. // Current DOM selection is in incorrect position. We need to update it.
  672. return true;
  673. }
  674. const oldViewSelection = domSelection && this.domConverter.domSelectionToView( domSelection );
  675. if ( oldViewSelection && this.selection.isEqual( oldViewSelection ) ) {
  676. return false;
  677. }
  678. // If selection is not collapsed, it does not need to be updated if it is similar.
  679. if ( !this.selection.isCollapsed && this.selection.isSimilar( oldViewSelection ) ) {
  680. // Selection did not changed and is correct, do not update.
  681. return false;
  682. }
  683. // Selections are not similar.
  684. return true;
  685. }
  686. /**
  687. * Removes the DOM selection.
  688. *
  689. * @private
  690. */
  691. _removeDomSelection() {
  692. for ( const doc of this.domDocuments ) {
  693. const domSelection = doc.getSelection();
  694. if ( domSelection.rangeCount ) {
  695. const activeDomElement = doc.activeElement;
  696. const viewElement = this.domConverter.mapDomToView( activeDomElement );
  697. if ( activeDomElement && viewElement ) {
  698. doc.getSelection().removeAllRanges();
  699. }
  700. }
  701. }
  702. }
  703. /**
  704. * Removes the fake selection.
  705. *
  706. * @private
  707. */
  708. _removeFakeSelection() {
  709. const container = this._fakeSelectionContainer;
  710. if ( container ) {
  711. container.remove();
  712. }
  713. }
  714. /**
  715. * Checks if focus needs to be updated and possibly updates it.
  716. *
  717. * @private
  718. */
  719. _updateFocus() {
  720. if ( this.isFocused ) {
  721. const editable = this.selection.editableElement;
  722. if ( editable ) {
  723. this.domConverter.focus( editable );
  724. }
  725. }
  726. }
  727. }
  728. mix( Renderer, ObservableMixin );
  729. // Checks if provided element is editable.
  730. //
  731. // @private
  732. // @param {module:engine/view/element~Element} element
  733. // @returns {Boolean}
  734. function isEditable( element ) {
  735. if ( element.getAttribute( 'contenteditable' ) == 'false' ) {
  736. return false;
  737. }
  738. const parent = element.findAncestor( element => element.hasAttribute( 'contenteditable' ) );
  739. return !parent || parent.getAttribute( 'contenteditable' ) == 'true';
  740. }
  741. // Adds inline filler at a given position.
  742. //
  743. // The position can be given as an array of DOM nodes and an offset in that array,
  744. // or a DOM parent element and an offset in that element.
  745. //
  746. // @private
  747. // @param {Document} domDocument
  748. // @param {Element|Array.<Node>} domParentOrArray
  749. // @param {Number} offset
  750. // @returns {Text} The DOM text node that contains an inline filler.
  751. function addInlineFiller( domDocument, domParentOrArray, offset ) {
  752. const childNodes = domParentOrArray instanceof Array ? domParentOrArray : domParentOrArray.childNodes;
  753. const nodeAfterFiller = childNodes[ offset ];
  754. if ( isText( nodeAfterFiller ) ) {
  755. nodeAfterFiller.data = INLINE_FILLER + nodeAfterFiller.data;
  756. return nodeAfterFiller;
  757. } else {
  758. const fillerNode = domDocument.createTextNode( INLINE_FILLER );
  759. if ( Array.isArray( domParentOrArray ) ) {
  760. childNodes.splice( offset, 0, fillerNode );
  761. } else {
  762. insertAt( domParentOrArray, offset, fillerNode );
  763. }
  764. return fillerNode;
  765. }
  766. }
  767. // Whether two DOM nodes should be considered as similar.
  768. // Nodes are considered similar if they have the same tag name.
  769. //
  770. // @private
  771. // @param {Node} node1
  772. // @param {Node} node2
  773. // @returns {Boolean}
  774. function areSimilar( node1, node2 ) {
  775. return isNode( node1 ) && isNode( node2 ) &&
  776. !isText( node1 ) && !isText( node2 ) &&
  777. node1.tagName.toLowerCase() === node2.tagName.toLowerCase();
  778. }
  779. // Whether two dom nodes should be considered as the same.
  780. // Two nodes which are considered the same are:
  781. //
  782. // * Text nodes with the same text.
  783. // * Element nodes represented by the same object.
  784. // * Two block filler elements.
  785. //
  786. // @private
  787. // @param {Function} blockFiller Block filler creator function, see {@link module:engine/view/domconverter~DomConverter#blockFiller}.
  788. // @param {Node} node1
  789. // @param {Node} node2
  790. // @returns {Boolean}
  791. function sameNodes( blockFiller, actualDomChild, expectedDomChild ) {
  792. // Elements.
  793. if ( actualDomChild === expectedDomChild ) {
  794. return true;
  795. }
  796. // Texts.
  797. else if ( isText( actualDomChild ) && isText( expectedDomChild ) ) {
  798. return actualDomChild.data === expectedDomChild.data;
  799. }
  800. // Block fillers.
  801. else if ( isBlockFiller( actualDomChild, blockFiller ) &&
  802. isBlockFiller( expectedDomChild, blockFiller ) ) {
  803. return true;
  804. }
  805. // Not matching types.
  806. return false;
  807. }
  808. // The following is a Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439).
  809. // When the native DOM selection is at the end of the block and preceded by <br /> e.g.
  810. //
  811. // <p>foo<br/>[]</p>
  812. //
  813. // which happens a lot when using the soft line break, the browser fails to (visually) move the
  814. // caret to the new line. A quick fix is as simple as force–refreshing the selection with the same range.
  815. function fixGeckoSelectionAfterBr( focus, domSelection ) {
  816. const parent = focus.parent;
  817. // This fix works only when the focus point is at the very end of an element.
  818. // There is no point in running it in cases unrelated to the browser bug.
  819. if ( parent.nodeType != Node.ELEMENT_NODE || focus.offset != parent.childNodes.length - 1 ) {
  820. return;
  821. }
  822. const childAtOffset = parent.childNodes[ focus.offset ];
  823. // To stay on the safe side, the fix being as specific as possible, it targets only the
  824. // selection which is at the very end of the element and preceded by <br />.
  825. if ( childAtOffset && childAtOffset.tagName == 'BR' ) {
  826. domSelection.addRange( domSelection.getRangeAt( 0 ) );
  827. }
  828. }