8
0

renderer.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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. /* 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 } 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.', this );
  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.', this );
  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. // Handle deletions first.
  477. // This is to prevent a situation where an element that already exists in `actualDomChildren` is inserted at a different
  478. // index in `actualDomChildren`. Since `actualDomChildren` is a `NodeList`, this works like move, not like an insert,
  479. // and it disrupts the whole algorithm. See https://github.com/ckeditor/ckeditor5/issues/6367.
  480. //
  481. // It doesn't matter in what order we remove or add nodes, as long as we remove and add correct nodes at correct indexes.
  482. for ( const action of diff ) {
  483. if ( action === 'delete' ) {
  484. nodesToUnbind.add( actualDomChildren[ i ] );
  485. remove( actualDomChildren[ i ] );
  486. } else if ( action === 'equal' ) {
  487. i++;
  488. }
  489. }
  490. i = 0;
  491. for ( const action of diff ) {
  492. if ( action === 'insert' ) {
  493. insertAt( domElement, i, expectedDomChildren[ i ] );
  494. i++;
  495. } else if ( action === 'equal' ) {
  496. // Force updating text nodes inside elements which did not change and do not need to be re-rendered (#1125).
  497. // Do it here (not in the loop above) because only after insertions the `i` index is correct.
  498. this._markDescendantTextToSync( this.domConverter.domToView( expectedDomChildren[ i ] ) );
  499. i++;
  500. }
  501. }
  502. // Unbind removed nodes. When node does not have a parent it means that it was removed from DOM tree during
  503. // comparison with the expected DOM. We don't need to check child nodes, because if child node was reinserted,
  504. // it was moved to DOM tree out of the removed node.
  505. for ( const node of nodesToUnbind ) {
  506. if ( !node.parentNode ) {
  507. this.domConverter.unbindDomElement( node );
  508. }
  509. }
  510. }
  511. /**
  512. * Shorthand for diffing two arrays or node lists of DOM nodes.
  513. *
  514. * @private
  515. * @param {Array.<Node>|NodeList} actualDomChildren Actual DOM children
  516. * @param {Array.<Node>|NodeList} expectedDomChildren Expected DOM children.
  517. * @returns {Array.<String>} The list of actions based on the {@link module:utils/diff~diff} function.
  518. */
  519. _diffNodeLists( actualDomChildren, expectedDomChildren ) {
  520. actualDomChildren = filterOutFakeSelectionContainer( actualDomChildren, this._fakeSelectionContainer );
  521. return diff( actualDomChildren, expectedDomChildren, sameNodes.bind( null, this.domConverter ) );
  522. }
  523. /**
  524. * Finds DOM nodes that were replaced with the similar nodes (same tag name) in the view. All nodes are compared
  525. * within one `insert`/`delete` action group, for example:
  526. *
  527. * Actual DOM: <p><b>Foo</b>Bar<i>Baz</i><b>Bax</b></p>
  528. * Expected DOM: <p>Bar<b>123</b><i>Baz</i><b>456</b></p>
  529. * Input actions: [ insert, insert, delete, delete, equal, insert, delete ]
  530. * Output actions: [ insert, replace, delete, equal, replace ]
  531. *
  532. * @private
  533. * @param {Array.<String>} actions Actions array which is a result of the {@link module:utils/diff~diff} function.
  534. * @param {Array.<Node>|NodeList} actualDom Actual DOM children
  535. * @param {Array.<Node>} expectedDom Expected DOM children.
  536. * @returns {Array.<String>} Actions array modified with the `replace` actions.
  537. */
  538. _findReplaceActions( actions, actualDom, expectedDom ) {
  539. // If there is no both 'insert' and 'delete' actions, no need to check for replaced elements.
  540. if ( actions.indexOf( 'insert' ) === -1 || actions.indexOf( 'delete' ) === -1 ) {
  541. return actions;
  542. }
  543. let newActions = [];
  544. let actualSlice = [];
  545. let expectedSlice = [];
  546. const counter = { equal: 0, insert: 0, delete: 0 };
  547. for ( const action of actions ) {
  548. if ( action === 'insert' ) {
  549. expectedSlice.push( expectedDom[ counter.equal + counter.insert ] );
  550. } else if ( action === 'delete' ) {
  551. actualSlice.push( actualDom[ counter.equal + counter.delete ] );
  552. } else { // equal
  553. newActions = newActions.concat( diff( actualSlice, expectedSlice, areSimilar ).map( x => x === 'equal' ? 'replace' : x ) );
  554. newActions.push( 'equal' );
  555. // Reset stored elements on 'equal'.
  556. actualSlice = [];
  557. expectedSlice = [];
  558. }
  559. counter[ action ]++;
  560. }
  561. return newActions.concat( diff( actualSlice, expectedSlice, areSimilar ).map( x => x === 'equal' ? 'replace' : x ) );
  562. }
  563. /**
  564. * Marks text nodes to be synchronized.
  565. *
  566. * If a text node is passed, it will be marked. If an element is passed, all descendant text nodes inside it will be marked.
  567. *
  568. * @private
  569. * @param {module:engine/view/node~Node} viewNode View node to sync.
  570. */
  571. _markDescendantTextToSync( viewNode ) {
  572. if ( !viewNode ) {
  573. return;
  574. }
  575. if ( viewNode.is( 'text' ) ) {
  576. this.markedTexts.add( viewNode );
  577. } else if ( viewNode.is( 'element' ) ) {
  578. for ( const child of viewNode.getChildren() ) {
  579. this._markDescendantTextToSync( child );
  580. }
  581. }
  582. }
  583. /**
  584. * Checks if the selection needs to be updated and possibly updates it.
  585. *
  586. * @private
  587. */
  588. _updateSelection() {
  589. // If there is no selection - remove DOM and fake selections.
  590. if ( this.selection.rangeCount === 0 ) {
  591. this._removeDomSelection();
  592. this._removeFakeSelection();
  593. return;
  594. }
  595. const domRoot = this.domConverter.mapViewToDom( this.selection.editableElement );
  596. // Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.
  597. if ( !this.isFocused || !domRoot ) {
  598. return;
  599. }
  600. // Render selection.
  601. if ( this.selection.isFake ) {
  602. this._updateFakeSelection( domRoot );
  603. } else {
  604. this._removeFakeSelection();
  605. this._updateDomSelection( domRoot );
  606. }
  607. }
  608. /**
  609. * Updates the fake selection.
  610. *
  611. * @private
  612. * @param {HTMLElement} domRoot A valid DOM root where the fake selection container should be added.
  613. */
  614. _updateFakeSelection( domRoot ) {
  615. const domDocument = domRoot.ownerDocument;
  616. if ( !this._fakeSelectionContainer ) {
  617. this._fakeSelectionContainer = createFakeSelectionContainer( domDocument );
  618. }
  619. const container = this._fakeSelectionContainer;
  620. // Bind fake selection container with the current selection *position*.
  621. this.domConverter.bindFakeSelection( container, this.selection );
  622. if ( !this._fakeSelectionNeedsUpdate( domRoot ) ) {
  623. return;
  624. }
  625. if ( !container.parentElement || container.parentElement != domRoot ) {
  626. domRoot.appendChild( container );
  627. }
  628. container.textContent = this.selection.fakeSelectionLabel || '\u00A0';
  629. const domSelection = domDocument.getSelection();
  630. const domRange = domDocument.createRange();
  631. domSelection.removeAllRanges();
  632. domRange.selectNodeContents( container );
  633. domSelection.addRange( domRange );
  634. }
  635. /**
  636. * Updates the DOM selection.
  637. *
  638. * @private
  639. * @param {HTMLElement} domRoot A valid DOM root where the DOM selection should be rendered.
  640. */
  641. _updateDomSelection( domRoot ) {
  642. const domSelection = domRoot.ownerDocument.defaultView.getSelection();
  643. // Let's check whether DOM selection needs updating at all.
  644. if ( !this._domSelectionNeedsUpdate( domSelection ) ) {
  645. return;
  646. }
  647. // Multi-range selection is not available in most browsers, and, at least in Chrome, trying to
  648. // set such selection, that is not continuous, throws an error. Because of that, we will just use anchor
  649. // and focus of view selection.
  650. // Since we are not supporting multi-range selection, we also do not need to check if proper editable is
  651. // selected. If there is any editable selected, it is okay (editable is taken from selection anchor).
  652. const anchor = this.domConverter.viewPositionToDom( this.selection.anchor );
  653. const focus = this.domConverter.viewPositionToDom( this.selection.focus );
  654. // Focus the new editing host.
  655. // Otherwise, FF may throw an error (https://github.com/ckeditor/ckeditor5/issues/721).
  656. domRoot.focus();
  657. domSelection.collapse( anchor.parent, anchor.offset );
  658. domSelection.extend( focus.parent, focus.offset );
  659. // Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439).
  660. if ( env.isGecko ) {
  661. fixGeckoSelectionAfterBr( focus, domSelection );
  662. }
  663. }
  664. /**
  665. * Checks whether a given DOM selection needs to be updated.
  666. *
  667. * @private
  668. * @param {Selection} domSelection The DOM selection to check.
  669. * @returns {Boolean}
  670. */
  671. _domSelectionNeedsUpdate( domSelection ) {
  672. if ( !this.domConverter.isDomSelectionCorrect( domSelection ) ) {
  673. // Current DOM selection is in incorrect position. We need to update it.
  674. return true;
  675. }
  676. const oldViewSelection = domSelection && this.domConverter.domSelectionToView( domSelection );
  677. if ( oldViewSelection && this.selection.isEqual( oldViewSelection ) ) {
  678. return false;
  679. }
  680. // If selection is not collapsed, it does not need to be updated if it is similar.
  681. if ( !this.selection.isCollapsed && this.selection.isSimilar( oldViewSelection ) ) {
  682. // Selection did not changed and is correct, do not update.
  683. return false;
  684. }
  685. // Selections are not similar.
  686. return true;
  687. }
  688. /**
  689. * Checks whether the fake selection needs to be updated.
  690. *
  691. * @private
  692. * @param {HTMLElement} domRoot A valid DOM root where a new fake selection container should be added.
  693. * @returns {Boolean}
  694. */
  695. _fakeSelectionNeedsUpdate( domRoot ) {
  696. const container = this._fakeSelectionContainer;
  697. const domSelection = domRoot.ownerDocument.getSelection();
  698. // Fake selection needs to be updated if there's no fake selection container, or the container currently sits
  699. // in a different root.
  700. if ( !container || container.parentElement !== domRoot ) {
  701. return true;
  702. }
  703. // Make sure that the selection actually is within the fake selection.
  704. if ( domSelection.anchorNode !== container && !container.contains( domSelection.anchorNode ) ) {
  705. return true;
  706. }
  707. return container.textContent !== this.selection.fakeSelectionLabel;
  708. }
  709. /**
  710. * Removes the DOM selection.
  711. *
  712. * @private
  713. */
  714. _removeDomSelection() {
  715. for ( const doc of this.domDocuments ) {
  716. const domSelection = doc.getSelection();
  717. if ( domSelection.rangeCount ) {
  718. const activeDomElement = doc.activeElement;
  719. const viewElement = this.domConverter.mapDomToView( activeDomElement );
  720. if ( activeDomElement && viewElement ) {
  721. doc.getSelection().removeAllRanges();
  722. }
  723. }
  724. }
  725. }
  726. /**
  727. * Removes the fake selection.
  728. *
  729. * @private
  730. */
  731. _removeFakeSelection() {
  732. const container = this._fakeSelectionContainer;
  733. if ( container ) {
  734. container.remove();
  735. }
  736. }
  737. /**
  738. * Checks if focus needs to be updated and possibly updates it.
  739. *
  740. * @private
  741. */
  742. _updateFocus() {
  743. if ( this.isFocused ) {
  744. const editable = this.selection.editableElement;
  745. if ( editable ) {
  746. this.domConverter.focus( editable );
  747. }
  748. }
  749. }
  750. }
  751. mix( Renderer, ObservableMixin );
  752. // Checks if provided element is editable.
  753. //
  754. // @private
  755. // @param {module:engine/view/element~Element} element
  756. // @returns {Boolean}
  757. function isEditable( element ) {
  758. if ( element.getAttribute( 'contenteditable' ) == 'false' ) {
  759. return false;
  760. }
  761. const parent = element.findAncestor( element => element.hasAttribute( 'contenteditable' ) );
  762. return !parent || parent.getAttribute( 'contenteditable' ) == 'true';
  763. }
  764. // Adds inline filler at a given position.
  765. //
  766. // The position can be given as an array of DOM nodes and an offset in that array,
  767. // or a DOM parent element and an offset in that element.
  768. //
  769. // @private
  770. // @param {Document} domDocument
  771. // @param {Element|Array.<Node>} domParentOrArray
  772. // @param {Number} offset
  773. // @returns {Text} The DOM text node that contains an inline filler.
  774. function addInlineFiller( domDocument, domParentOrArray, offset ) {
  775. const childNodes = domParentOrArray instanceof Array ? domParentOrArray : domParentOrArray.childNodes;
  776. const nodeAfterFiller = childNodes[ offset ];
  777. if ( isText( nodeAfterFiller ) ) {
  778. nodeAfterFiller.data = INLINE_FILLER + nodeAfterFiller.data;
  779. return nodeAfterFiller;
  780. } else {
  781. const fillerNode = domDocument.createTextNode( INLINE_FILLER );
  782. if ( Array.isArray( domParentOrArray ) ) {
  783. childNodes.splice( offset, 0, fillerNode );
  784. } else {
  785. insertAt( domParentOrArray, offset, fillerNode );
  786. }
  787. return fillerNode;
  788. }
  789. }
  790. // Whether two DOM nodes should be considered as similar.
  791. // Nodes are considered similar if they have the same tag name.
  792. //
  793. // @private
  794. // @param {Node} node1
  795. // @param {Node} node2
  796. // @returns {Boolean}
  797. function areSimilar( node1, node2 ) {
  798. return isNode( node1 ) && isNode( node2 ) &&
  799. !isText( node1 ) && !isText( node2 ) &&
  800. node1.nodeType !== Node.COMMENT_NODE && node2.nodeType !== Node.COMMENT_NODE &&
  801. node1.tagName.toLowerCase() === node2.tagName.toLowerCase();
  802. }
  803. // Whether two dom nodes should be considered as the same.
  804. // Two nodes which are considered the same are:
  805. //
  806. // * Text nodes with the same text.
  807. // * Element nodes represented by the same object.
  808. // * Two block filler elements.
  809. //
  810. // @private
  811. // @param {String} blockFillerMode Block filler mode, see {@link module:engine/view/domconverter~DomConverter#blockFillerMode}.
  812. // @param {Node} node1
  813. // @param {Node} node2
  814. // @returns {Boolean}
  815. function sameNodes( domConverter, actualDomChild, expectedDomChild ) {
  816. // Elements.
  817. if ( actualDomChild === expectedDomChild ) {
  818. return true;
  819. }
  820. // Texts.
  821. else if ( isText( actualDomChild ) && isText( expectedDomChild ) ) {
  822. return actualDomChild.data === expectedDomChild.data;
  823. }
  824. // Block fillers.
  825. else if ( domConverter.isBlockFiller( actualDomChild ) &&
  826. domConverter.isBlockFiller( expectedDomChild ) ) {
  827. return true;
  828. }
  829. // Not matching types.
  830. return false;
  831. }
  832. // The following is a Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439).
  833. // When the native DOM selection is at the end of the block and preceded by <br /> e.g.
  834. //
  835. // <p>foo<br/>[]</p>
  836. //
  837. // which happens a lot when using the soft line break, the browser fails to (visually) move the
  838. // caret to the new line. A quick fix is as simple as force–refreshing the selection with the same range.
  839. function fixGeckoSelectionAfterBr( focus, domSelection ) {
  840. const parent = focus.parent;
  841. // This fix works only when the focus point is at the very end of an element.
  842. // There is no point in running it in cases unrelated to the browser bug.
  843. if ( parent.nodeType != Node.ELEMENT_NODE || focus.offset != parent.childNodes.length - 1 ) {
  844. return;
  845. }
  846. const childAtOffset = parent.childNodes[ focus.offset ];
  847. // To stay on the safe side, the fix being as specific as possible, it targets only the
  848. // selection which is at the very end of the element and preceded by <br />.
  849. if ( childAtOffset && childAtOffset.tagName == 'BR' ) {
  850. domSelection.addRange( domSelection.getRangeAt( 0 ) );
  851. }
  852. }
  853. function filterOutFakeSelectionContainer( domChildList, fakeSelectionContainer ) {
  854. const childList = Array.from( domChildList );
  855. if ( childList.length == 0 || !fakeSelectionContainer ) {
  856. return childList;
  857. }
  858. const last = childList[ childList.length - 1 ];
  859. if ( last == fakeSelectionContainer ) {
  860. childList.pop();
  861. }
  862. return childList;
  863. }
  864. // Creates a fake selection container for a given document.
  865. //
  866. // @private
  867. // @param {Document} domDocument
  868. // @returns {HTMLElement}
  869. function createFakeSelectionContainer( domDocument ) {
  870. const container = domDocument.createElement( 'div' );
  871. Object.assign( container.style, {
  872. position: 'fixed',
  873. top: 0,
  874. left: '-9999px',
  875. // See https://github.com/ckeditor/ckeditor5/issues/752.
  876. width: '42px'
  877. } );
  878. // Fill it with a text node so we can update it later.
  879. container.textContent = '\u00A0';
  880. return container;
  881. }