renderer.js 24 KB

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