renderer.js 24 KB

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