renderer.js 32 KB

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