renderer.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /**
  2. * @license Copyright (c) 2003-2017, 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. /* global Range */
  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 the view nodes with the 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/selection~Selection} selection View selection.
  37. */
  38. constructor( domConverter, selection ) {
  39. /**
  40. * Set of DOM Documents instances.
  41. *
  42. * @member {Set.<Document>}
  43. */
  44. this.domDocuments = new Set();
  45. /**
  46. * Converter instance.
  47. *
  48. * @readonly
  49. * @member {module:engine/view/domconverter~DomConverter}
  50. */
  51. this.domConverter = domConverter;
  52. /**
  53. * Set of nodes which attributes changed and may need to be rendered.
  54. *
  55. * @readonly
  56. * @member {Set.<module:engine/view/node~Node>}
  57. */
  58. this.markedAttributes = new Set();
  59. /**
  60. * Set of elements which child lists changed and may need to be rendered.
  61. *
  62. * @readonly
  63. * @member {Set.<module:engine/view/node~Node>}
  64. */
  65. this.markedChildren = new Set();
  66. /**
  67. * Set of text nodes which text data changed and may need to be rendered.
  68. *
  69. * @readonly
  70. * @member {Set.<module:engine/view/node~Node>}
  71. */
  72. this.markedTexts = new Set();
  73. /**
  74. * View selection. Renderer updates DOM Selection to make it match this one.
  75. *
  76. * @readonly
  77. * @member {module:engine/view/selection~Selection}
  78. */
  79. this.selection = selection;
  80. /**
  81. * The text node in which the inline filler was rendered.
  82. *
  83. * @private
  84. * @member {Text}
  85. */
  86. this._inlineFiller = null;
  87. /**
  88. * Indicates if view document is focused and selection can be rendered. Selection will not be rendered if
  89. * this is set to `false`.
  90. *
  91. * @member {Boolean}
  92. */
  93. this.isFocused = false;
  94. /**
  95. * DOM element containing fake selection.
  96. *
  97. * @private
  98. * @type {null|HTMLElement}
  99. */
  100. this._fakeSelectionContainer = null;
  101. }
  102. /**
  103. * Mark node to be synchronized.
  104. *
  105. * Note that only view nodes which parents have corresponding DOM elements need to be marked to be synchronized.
  106. *
  107. * @see #markedAttributes
  108. * @see #markedChildren
  109. * @see #markedTexts
  110. *
  111. * @param {module:engine/view/document~ChangeType} type Type of the change.
  112. * @param {module:engine/view/node~Node} node Node to be marked.
  113. */
  114. markToSync( type, node ) {
  115. if ( type === 'text' ) {
  116. if ( this.domConverter.getCorrespondingDom( node.parent ) ) {
  117. this.markedTexts.add( node );
  118. }
  119. } else {
  120. // If the node has no DOM element it is not rendered yet,
  121. // its children/attributes do not need to be marked to be sync.
  122. if ( !this.domConverter.getCorrespondingDom( node ) ) {
  123. return;
  124. }
  125. if ( type === 'attributes' ) {
  126. this.markedAttributes.add( node );
  127. } else if ( type === 'children' ) {
  128. this.markedChildren.add( node );
  129. } else {
  130. /**
  131. * Unknown type passed to Renderer.markToSync.
  132. *
  133. * @error renderer-unknown-type
  134. */
  135. throw new CKEditorError( 'view-renderer-unknown-type: Unknown type passed to Renderer.markToSync.' );
  136. }
  137. }
  138. }
  139. /**
  140. * Render method checks {@link #markedAttributes},
  141. * {@link #markedChildren} and {@link #markedTexts} and updates all
  142. * nodes which need to be updated. Then it clears all three sets. Also, every time render is called it compares and
  143. * if needed updates the selection.
  144. *
  145. * Renderer tries not to break text composition (e.g. IME) and x-index of the selection,
  146. * so it does as little as it is needed to update the DOM.
  147. *
  148. * For attributes it adds new attributes to DOM elements, updates values and removes
  149. * attributes which do not exist in the view element.
  150. *
  151. * For text nodes it updates the text string if it is different. Note that if parent element is marked as an element
  152. * which changed child list, text node update will not be done, because it may not be possible do find a
  153. * {@link module:engine/view/domconverter~DomConverter#getCorrespondingDomText corresponding DOM text}. The change will be handled
  154. * in the parent element.
  155. *
  156. * For elements, which child lists have changed, it calculates a {@link module:utils/diff~diff} and adds or removes children which have
  157. * changed.
  158. *
  159. * Rendering also handles {@link module:engine/view/filler fillers}. Especially, it checks if the inline filler is needed
  160. * at selection position and adds or removes it. To prevent breaking text composition inline filler will not be
  161. * removed as long selection is in the text node which needed it at first.
  162. */
  163. render() {
  164. let inlineFillerPosition;
  165. // There was inline filler rendered in the DOM but it's not
  166. // at the selection position any more, so we can remove it
  167. // (cause even if it's needed, it must be placed in another location).
  168. if ( this._inlineFiller && !this._isSelectionInInlineFiller() ) {
  169. this._removeInlineFiller();
  170. }
  171. // If we've got the filler, let's try to guess its position in the view.
  172. if ( this._inlineFiller ) {
  173. inlineFillerPosition = this._getInlineFillerPosition();
  174. }
  175. // Othewise, if it's needed, create it at the selection position.
  176. else if ( this._needsInlineFillerAtSelection() ) {
  177. inlineFillerPosition = this.selection.getFirstPosition();
  178. // Do not use `markToSync` so it will be added even if the parent is already added.
  179. this.markedChildren.add( inlineFillerPosition.parent );
  180. }
  181. for ( let node of this.markedTexts ) {
  182. if ( !this.markedChildren.has( node.parent ) && this.domConverter.getCorrespondingDom( node.parent ) ) {
  183. this._updateText( node, { inlineFillerPosition } );
  184. }
  185. }
  186. for ( let element of this.markedAttributes ) {
  187. this._updateAttrs( element );
  188. }
  189. for ( let element of this.markedChildren ) {
  190. this._updateChildren( element, { inlineFillerPosition } );
  191. }
  192. this._updateSelection();
  193. this._updateFocus();
  194. this.markedTexts.clear();
  195. this.markedAttributes.clear();
  196. this.markedChildren.clear();
  197. // Remember the filler by its node.
  198. this._inlineFiller = this._getInlineFillerNode( inlineFillerPosition );
  199. }
  200. /**
  201. * Gets the text node in which the inline filler is kept.
  202. *
  203. * @private
  204. * @param {module:engine/view/position~Position} fillerPosition The position on which the filler is needed in the view.
  205. * @returns {Text} The text node with the filler.
  206. */
  207. _getInlineFillerNode( fillerPosition ) {
  208. if ( !fillerPosition ) {
  209. this._inlineFiller = null;
  210. return;
  211. }
  212. const domPosition = this.domConverter.viewPositionToDom( fillerPosition );
  213. /* istanbul ignore if */
  214. if ( !domPosition || !startsWithFiller( domPosition.parent ) ) {
  215. /**
  216. * Cannot find filler node by its position.
  217. *
  218. * @error view-renderer-cannot-find-filler
  219. */
  220. throw new CKEditorError( 'view-renderer-cannot-find-filler: Cannot find filler node by its position.' );
  221. }
  222. return domPosition.parent;
  223. }
  224. /**
  225. * Gets the position of the inline filler based on the current selection.
  226. * Here, we assume that we know that the filler is needed and
  227. * {@link #_isSelectionInInlineFiller is at the selection position}, and, since it's needed,
  228. * it's somewhere at the selection postion.
  229. *
  230. * Note: we cannot restore the filler position based on the filler's DOM text node, because
  231. * when this method is called (before rendering) the bindings will often be broken. View to DOM
  232. * bindings are only dependable after rendering.
  233. *
  234. * @private
  235. * @returns {module:engine/view/position~Position}
  236. */
  237. _getInlineFillerPosition() {
  238. const firstPos = this.selection.getFirstPosition();
  239. if ( firstPos.parent.is( 'text' ) ) {
  240. return ViewPosition.createBefore( this.selection.getFirstPosition().parent );
  241. } else {
  242. return firstPos;
  243. }
  244. }
  245. /**
  246. * Returns `true` if the selection hasn't left the inline filler's text node.
  247. * If it is `true` it means that the filler had been added for a reason and the selection does not
  248. * left the filler's text node. E.g. the user can be in the middle of a composition so it should not be touched.
  249. *
  250. * @private
  251. * @returns {Boolean} True if the inline filler and selection are in the same place.
  252. */
  253. _isSelectionInInlineFiller() {
  254. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  255. return false;
  256. }
  257. // Note, we can't check if selection's position equals position of the
  258. // this._inlineFiller node, because of #663. We may not be able to calculate
  259. // the filler's position in the view at this stage.
  260. // Instead, we check it the other way – whether selection is anchored in
  261. // that text node or next to it.
  262. // Possible options are:
  263. // "FILLER{}"
  264. // "FILLERadded-text{}"
  265. const selectionPosition = this.selection.getFirstPosition();
  266. const position = this.domConverter.viewPositionToDom( selectionPosition );
  267. if ( position && this.domConverter.isText( position.parent ) && startsWithFiller( position.parent ) ) {
  268. return true;
  269. }
  270. return false;
  271. }
  272. /**
  273. * Removes the inline filler.
  274. *
  275. * @private
  276. */
  277. _removeInlineFiller() {
  278. const domFillerNode = this._inlineFiller;
  279. // Something weird happened and the stored node doesn't contain the filler's text.
  280. if ( !startsWithFiller( domFillerNode ) ) {
  281. /**
  282. * The inline filler node was lost. Most likely, something overwrote the filler text node
  283. * in the DOM.
  284. *
  285. * @error view-renderer-filler-was-lost
  286. */
  287. throw new CKEditorError( 'view-renderer-filler-was-lost: The inline filler node was lost.' );
  288. }
  289. if ( isInlineFiller( domFillerNode ) ) {
  290. domFillerNode.parentNode.removeChild( domFillerNode );
  291. } else {
  292. domFillerNode.data = domFillerNode.data.substr( INLINE_FILLER_LENGTH );
  293. }
  294. this._inlineFiller = null;
  295. }
  296. /**
  297. * Checks if the inline {@link module:engine/view/filler filler} should be added.
  298. *
  299. * @private
  300. * @returns {Boolean} True if the inline fillers should be added.
  301. */
  302. _needsInlineFillerAtSelection() {
  303. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  304. return false;
  305. }
  306. const selectionPosition = this.selection.getFirstPosition();
  307. const selectionParent = selectionPosition.parent;
  308. const selectionOffset = selectionPosition.offset;
  309. // If there is no DOM root we do not care about fillers.
  310. if ( !this.domConverter.getCorrespondingDomElement( selectionParent.root ) ) {
  311. return false;
  312. }
  313. if ( !( selectionParent.is( 'element' ) ) ) {
  314. return false;
  315. }
  316. // We have block filler, we do not need inline one.
  317. if ( selectionOffset === selectionParent.getFillerOffset() ) {
  318. return false;
  319. }
  320. const nodeBefore = selectionPosition.nodeBefore;
  321. const nodeAfter = selectionPosition.nodeAfter;
  322. if ( nodeBefore instanceof ViewText || nodeAfter instanceof ViewText ) {
  323. return false;
  324. }
  325. return true;
  326. }
  327. /**
  328. * Checks if text needs to be updated and possibly updates it.
  329. *
  330. * @private
  331. * @param {module:engine/view/text~Text} viewText View text to update.
  332. * @param {Object} options
  333. * @param {module:engine/view/position~Position} options.inlineFillerPosition The position on which the inline
  334. * filler should be rendered.
  335. */
  336. _updateText( viewText, options ) {
  337. const domText = this.domConverter.getCorrespondingDom( viewText );
  338. const newDomText = this.domConverter.viewToDom( viewText, domText.ownerDocument );
  339. const actualText = domText.data;
  340. let expectedText = newDomText.data;
  341. const filler = options.inlineFillerPosition;
  342. if ( filler && filler.parent == viewText.parent && filler.offset == viewText.index ) {
  343. expectedText = INLINE_FILLER + expectedText;
  344. }
  345. if ( actualText != expectedText ) {
  346. domText.data = expectedText;
  347. }
  348. }
  349. /**
  350. * Checks if attributes list needs to be updated and possibly updates it.
  351. *
  352. * @private
  353. * @param {module:engine/view/element~Element} viewElement View element to update.
  354. */
  355. _updateAttrs( viewElement ) {
  356. const domElement = this.domConverter.getCorrespondingDom( viewElement );
  357. const domAttrKeys = Array.from( domElement.attributes ).map( attr => attr.name );
  358. const viewAttrKeys = viewElement.getAttributeKeys();
  359. // Add or overwrite attributes.
  360. for ( let key of viewAttrKeys ) {
  361. domElement.setAttribute( key, viewElement.getAttribute( key ) );
  362. }
  363. // Remove from DOM attributes which do not exists in the view.
  364. for ( let key of domAttrKeys ) {
  365. if ( !viewElement.hasAttribute( key ) ) {
  366. domElement.removeAttribute( key );
  367. }
  368. }
  369. }
  370. /**
  371. * Checks if elements child list needs to be updated and possibly updates it.
  372. *
  373. * @private
  374. * @param {module:engine/view/element~Element} viewElement View element to update.
  375. * @param {Object} options
  376. * @param {module:engine/view/position~Position} options.inlineFillerPosition The position on which the inline
  377. * filler should be rendered.
  378. */
  379. _updateChildren( viewElement, options ) {
  380. const domConverter = this.domConverter;
  381. const domElement = domConverter.getCorrespondingDom( viewElement );
  382. if ( !domElement ) {
  383. // If there is no `domElement` it means that it was already removed from DOM.
  384. // There is no need to update it. It will be updated when re-inserted.
  385. return;
  386. }
  387. const domDocument = domElement.ownerDocument;
  388. const filler = options.inlineFillerPosition;
  389. const actualDomChildren = domElement.childNodes;
  390. const expectedDomChildren = Array.from( domConverter.viewChildrenToDom( viewElement, domDocument, { bind: true } ) );
  391. if ( filler && filler.parent == viewElement ) {
  392. const expectedNodeAfterFiller = expectedDomChildren[ filler.offset ];
  393. if ( this.domConverter.isText( expectedNodeAfterFiller ) ) {
  394. expectedNodeAfterFiller.data = INLINE_FILLER + expectedNodeAfterFiller.data;
  395. } else {
  396. expectedDomChildren.splice( filler.offset, 0, domDocument.createTextNode( INLINE_FILLER ) );
  397. }
  398. }
  399. const actions = diff( actualDomChildren, expectedDomChildren, sameNodes );
  400. let i = 0;
  401. for ( let action of actions ) {
  402. if ( action === 'insert' ) {
  403. insertAt( domElement, i, expectedDomChildren[ i ] );
  404. i++;
  405. } else if ( action === 'delete' ) {
  406. // Whenever element is removed from DOM, unbind it.
  407. this.domConverter.unbindDomElement( actualDomChildren[ i ] );
  408. remove( actualDomChildren[ i ] );
  409. } else { // 'equal'
  410. i++;
  411. }
  412. }
  413. function sameNodes( actualDomChild, expectedDomChild ) {
  414. // Elements.
  415. if ( actualDomChild === expectedDomChild ) {
  416. return true;
  417. }
  418. // Texts.
  419. else if ( domConverter.isText( actualDomChild ) && domConverter.isText( expectedDomChild ) ) {
  420. return actualDomChild.data === expectedDomChild.data;
  421. }
  422. // Block fillers.
  423. else if ( isBlockFiller( actualDomChild, domConverter.blockFiller ) &&
  424. isBlockFiller( expectedDomChild, domConverter.blockFiller ) ) {
  425. return true;
  426. }
  427. // Not matching types.
  428. return false;
  429. }
  430. }
  431. /**
  432. * Checks if selection needs to be updated and possibly updates it.
  433. *
  434. * @private
  435. */
  436. _updateSelection() {
  437. // If there is no selection - remove DOM and fake selections.
  438. if ( this.selection.rangeCount === 0 ) {
  439. this._removeDomSelection();
  440. this._removeFakeSelection();
  441. return;
  442. }
  443. const domRoot = this.domConverter.getCorrespondingDomElement( this.selection.editableElement );
  444. // Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.
  445. if ( !this.isFocused || !domRoot ) {
  446. return;
  447. }
  448. // Render selection.
  449. if ( this.selection.isFake ) {
  450. this._updateFakeSelection( domRoot );
  451. } else {
  452. this._removeFakeSelection();
  453. this._updateDomSelection( domRoot );
  454. }
  455. }
  456. /**
  457. * Updates fake selection.
  458. *
  459. * @private
  460. * @param {HTMLElement} domRoot Valid DOM root where fake selection container should be added.
  461. */
  462. _updateFakeSelection( domRoot ) {
  463. const domDocument = domRoot.ownerDocument;
  464. // Create fake selection container if one does not exist.
  465. if ( !this._fakeSelectionContainer ) {
  466. this._fakeSelectionContainer = domDocument.createElement( 'div' );
  467. this._fakeSelectionContainer.style.position = 'fixed';
  468. this._fakeSelectionContainer.style.top = 0;
  469. this._fakeSelectionContainer.style.left = '-9999px';
  470. this._fakeSelectionContainer.appendChild( domDocument.createTextNode( '\u00A0' ) );
  471. }
  472. // Add fake container if not already added.
  473. if ( !this._fakeSelectionContainer.parentElement ) {
  474. domRoot.appendChild( this._fakeSelectionContainer );
  475. }
  476. // Update contents.
  477. const content = this.selection.fakeSelectionLabel || '\u00A0';
  478. this._fakeSelectionContainer.firstChild.data = content;
  479. // Update selection.
  480. const domSelection = domDocument.getSelection();
  481. domSelection.removeAllRanges();
  482. const domRange = new Range();
  483. domRange.selectNodeContents( this._fakeSelectionContainer );
  484. domSelection.addRange( domRange );
  485. // Bind fake selection container with current selection.
  486. this.domConverter.bindFakeSelection( this._fakeSelectionContainer, this.selection );
  487. }
  488. /**
  489. * Updates DOM selection.
  490. *
  491. * @private
  492. * @param {HTMLElement} domRoot Valid DOM root where DOM selection should be rendered.
  493. */
  494. _updateDomSelection( domRoot ) {
  495. const domSelection = domRoot.ownerDocument.defaultView.getSelection();
  496. const oldViewSelection = domSelection && this.domConverter.domSelectionToView( domSelection );
  497. if ( oldViewSelection && this.selection.isEqual( oldViewSelection ) ) {
  498. return;
  499. }
  500. // Multi-range selection is not available in most browsers, and, at least in Chrome, trying to
  501. // set such selection, that is not continuous, throws an error. Because of that, we will just use anchor
  502. // and focus of view selection.
  503. // Since we are not supporting multi-range selection, we also do not need to check if proper editable is
  504. // selected. If there is any editable selected, it is okay (editable is taken from selection anchor).
  505. const anchor = this.domConverter.viewPositionToDom( this.selection.anchor );
  506. const focus = this.domConverter.viewPositionToDom( this.selection.focus );
  507. domSelection.collapse( anchor.parent, anchor.offset );
  508. domSelection.extend( focus.parent, focus.offset );
  509. }
  510. /**
  511. * Removes DOM selection.
  512. *
  513. * @private
  514. */
  515. _removeDomSelection() {
  516. for ( let doc of this.domDocuments ) {
  517. const domSelection = doc.getSelection();
  518. if ( domSelection.rangeCount ) {
  519. const activeDomElement = doc.activeElement;
  520. const viewElement = this.domConverter.getCorrespondingViewElement( activeDomElement );
  521. if ( activeDomElement && viewElement ) {
  522. doc.getSelection().removeAllRanges();
  523. }
  524. }
  525. }
  526. }
  527. /**
  528. * Removes fake selection.
  529. *
  530. * @private
  531. */
  532. _removeFakeSelection() {
  533. const container = this._fakeSelectionContainer;
  534. if ( container ) {
  535. container.remove();
  536. }
  537. }
  538. /**
  539. * Checks if focus needs to be updated and possibly updates it.
  540. *
  541. * @private
  542. */
  543. _updateFocus() {
  544. if ( this.isFocused ) {
  545. const editable = this.selection.editableElement;
  546. if ( editable ) {
  547. this.domConverter.focus( editable );
  548. }
  549. }
  550. }
  551. }
  552. mix( Renderer, ObservableMixin );