renderer.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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 ViewElement from './element';
  10. import ViewPosition from './position';
  11. import { INLINE_FILLER, INLINE_FILLER_LENGTH, startsWithFiller, isInlineFiller, isBlockFiller } from './filler';
  12. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  13. import diff from '@ckeditor/ckeditor5-utils/src/diff';
  14. import insertAt from '@ckeditor/ckeditor5-utils/src/dom/insertat';
  15. import remove from '@ckeditor/ckeditor5-utils/src/dom/remove';
  16. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  17. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  18. /* global Range */
  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 the view nodes with the 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/selection~Selection} selection View selection.
  38. */
  39. constructor( domConverter, selection ) {
  40. /**
  41. * Set of DOM Documents instances.
  42. *
  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 to make it match this one.
  76. *
  77. * @readonly
  78. * @member {module:engine/view/selection~Selection}
  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 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.getCorrespondingDom( 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.getCorrespondingDom( 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 do find a
  154. * {@link module:engine/view/domconverter~DomConverter#getCorrespondingDomText corresponding DOM text}. The change will be handled
  155. * 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. // Othewise, 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 ( let node of this.markedTexts ) {
  183. if ( !this.markedChildren.has( node.parent ) && this.domConverter.getCorrespondingDom( node.parent ) ) {
  184. this._updateText( node, { inlineFillerPosition } );
  185. }
  186. }
  187. for ( let element of this.markedAttributes ) {
  188. this._updateAttrs( element );
  189. }
  190. for ( let element of this.markedChildren ) {
  191. this._updateChildren( element, { inlineFillerPosition } );
  192. }
  193. this._updateSelection();
  194. this._updateFocus();
  195. this.markedTexts.clear();
  196. this.markedAttributes.clear();
  197. this.markedChildren.clear();
  198. // Remember the filler by its node.
  199. this._inlineFiller = this._getInlineFillerNode( inlineFillerPosition );
  200. }
  201. /**
  202. * Gets the text node in which the inline filler is kept.
  203. *
  204. * @private
  205. * @param {module:engine/view/position~Position} fillerPosition The position on which the filler is needed in the view.
  206. * @returns {Text} The text node with the filler.
  207. */
  208. _getInlineFillerNode( fillerPosition ) {
  209. if ( !fillerPosition ) {
  210. this._inlineFiller = null;
  211. return;
  212. }
  213. const domPosition = this.domConverter.viewPositionToDom( fillerPosition );
  214. /* istanbul ignore if */
  215. if ( !domPosition || !startsWithFiller( domPosition.parent ) ) {
  216. /**
  217. * Cannot find filler node by its position.
  218. *
  219. * @error view-renderer-cannot-find-filler
  220. */
  221. throw new CKEditorError( 'view-renderer-cannot-find-filler: Cannot find filler node by its position.' );
  222. }
  223. return domPosition.parent;
  224. }
  225. /**
  226. * Gets the position of the inline filler based on the current selection.
  227. * Here, we assume that we know that the filler is needed and
  228. * {@link #_isSelectionInInlineFiller is at the selection position}, and, since it's needed,
  229. * it's somewhere at the selection postion.
  230. *
  231. * Note: we cannot restore the filler position based on the filler's DOM text node, because
  232. * when this method is called (before rendering) the bindings will often be broken. View to DOM
  233. * bindings are only dependable after rendering.
  234. *
  235. * @private
  236. * @returns {module:engine/view/position~Position}
  237. */
  238. _getInlineFillerPosition() {
  239. const firstPos = this.selection.getFirstPosition();
  240. if ( firstPos.parent instanceof ViewText ) {
  241. return ViewPosition.createBefore( this.selection.getFirstPosition().parent );
  242. } else {
  243. return firstPos;
  244. }
  245. }
  246. /**
  247. * Returns `true` if the selection hasn't left the inline filler's text node.
  248. * If it is `true` it means that the filler had been added for a reason and the selection does not
  249. * left the filler's text node. E.g. the user can be in the middle of a composition so it should not be touched.
  250. *
  251. * @private
  252. * @returns {Boolean} True if the inline filler and selection are in the same place.
  253. */
  254. _isSelectionInInlineFiller() {
  255. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  256. return false;
  257. }
  258. // Note, we can't check if selection's position equals position of the
  259. // this._inlineFiller node, because of #663. We may not be able to calculate
  260. // the filler's position in the view at this stage.
  261. // Instead, we check it the other way – whether selection is anchored in
  262. // that text node or next to it.
  263. // Possible options are:
  264. // "FILLER{}"
  265. // "FILLERadded-text{}"
  266. const selectionPosition = this.selection.getFirstPosition();
  267. const position = this.domConverter.viewPositionToDom( selectionPosition );
  268. if ( position && this.domConverter.isText( position.parent ) && startsWithFiller( position.parent ) ) {
  269. return true;
  270. }
  271. return false;
  272. }
  273. /**
  274. * Removes the inline filler.
  275. *
  276. * @private
  277. */
  278. _removeInlineFiller() {
  279. const domFillerNode = this._inlineFiller;
  280. // Something weird happened and the stored node doesn't contain the filler's text.
  281. if ( !startsWithFiller( domFillerNode ) ) {
  282. /**
  283. * The inline filler node was lost. Most likely, something overwrote the filler text node
  284. * in the DOM.
  285. *
  286. * @error view-renderer-filler-was-lost
  287. */
  288. throw new CKEditorError( 'view-renderer-filler-was-lost: The inline filler node was lost.' );
  289. }
  290. if ( isInlineFiller( domFillerNode ) ) {
  291. domFillerNode.parentNode.removeChild( domFillerNode );
  292. } else {
  293. domFillerNode.data = domFillerNode.data.substr( INLINE_FILLER_LENGTH );
  294. }
  295. this._inlineFiller = null;
  296. }
  297. /**
  298. * Checks if the inline {@link module:engine/view/filler filler} should be added.
  299. *
  300. * @private
  301. * @returns {Boolean} True if the inline fillers should be added.
  302. */
  303. _needsInlineFillerAtSelection() {
  304. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  305. return false;
  306. }
  307. const selectionPosition = this.selection.getFirstPosition();
  308. const selectionParent = selectionPosition.parent;
  309. const selectionOffset = selectionPosition.offset;
  310. // If there is no DOM root we do not care about fillers.
  311. if ( !this.domConverter.getCorrespondingDomElement( selectionParent.root ) ) {
  312. return false;
  313. }
  314. if ( !( selectionParent instanceof ViewElement ) ) {
  315. return false;
  316. }
  317. // We have block filler, we do not need inline one.
  318. if ( selectionOffset === selectionParent.getFillerOffset() ) {
  319. return false;
  320. }
  321. const nodeBefore = selectionPosition.nodeBefore;
  322. const nodeAfter = selectionPosition.nodeAfter;
  323. if ( nodeBefore instanceof ViewText || nodeAfter instanceof ViewText ) {
  324. return false;
  325. }
  326. return true;
  327. }
  328. /**
  329. * Checks if text needs to be updated and possibly updates it.
  330. *
  331. * @private
  332. * @param {module:engine/view/text~Text} viewText View text to update.
  333. * @param {Object} options
  334. * @param {module:engine/view/position~Position} options.inlineFillerPosition The position on which the inline
  335. * filler should be rendered.
  336. */
  337. _updateText( viewText, options ) {
  338. const domText = this.domConverter.getCorrespondingDom( viewText );
  339. const newDomText = this.domConverter.viewToDom( viewText, domText.ownerDocument );
  340. const actualText = domText.data;
  341. let expectedText = newDomText.data;
  342. const filler = options.inlineFillerPosition;
  343. if ( filler && filler.parent == viewText.parent && filler.offset == viewText.index ) {
  344. expectedText = INLINE_FILLER + expectedText;
  345. }
  346. if ( actualText != expectedText ) {
  347. domText.data = expectedText;
  348. }
  349. }
  350. /**
  351. * Checks if attributes list needs to be updated and possibly updates it.
  352. *
  353. * @private
  354. * @param {module:engine/view/element~Element} viewElement View element to update.
  355. */
  356. _updateAttrs( viewElement ) {
  357. const domElement = this.domConverter.getCorrespondingDom( viewElement );
  358. const domAttrKeys = Array.from( domElement.attributes ).map( attr => attr.name );
  359. const viewAttrKeys = viewElement.getAttributeKeys();
  360. // Add or overwrite attributes.
  361. for ( let key of viewAttrKeys ) {
  362. domElement.setAttribute( key, viewElement.getAttribute( key ) );
  363. }
  364. // Remove from DOM attributes which do not exists in the view.
  365. for ( let key of domAttrKeys ) {
  366. if ( !viewElement.hasAttribute( key ) ) {
  367. domElement.removeAttribute( key );
  368. }
  369. }
  370. }
  371. /**
  372. * Checks if elements child list needs to be updated and possibly updates it.
  373. *
  374. * @private
  375. * @param {module:engine/view/element~Element} viewElement View element to update.
  376. * @param {Object} options
  377. * @param {module:engine/view/position~Position} options.inlineFillerPosition The position on which the inline
  378. * filler should be rendered.
  379. */
  380. _updateChildren( viewElement, options ) {
  381. const domConverter = this.domConverter;
  382. const domElement = domConverter.getCorrespondingDom( viewElement );
  383. const domDocument = domElement.ownerDocument;
  384. const filler = options.inlineFillerPosition;
  385. const actualDomChildren = domElement.childNodes;
  386. const expectedDomChildren = Array.from( domConverter.viewChildrenToDom( viewElement, domDocument, { bind: true } ) );
  387. if ( filler && filler.parent == viewElement ) {
  388. const expectedNodeAfterFiller = expectedDomChildren[ filler.offset ];
  389. if ( this.domConverter.isText( expectedNodeAfterFiller ) ) {
  390. expectedNodeAfterFiller.data = INLINE_FILLER + expectedNodeAfterFiller.data;
  391. } else {
  392. expectedDomChildren.splice( filler.offset, 0, domDocument.createTextNode( INLINE_FILLER ) );
  393. }
  394. }
  395. const actions = diff( actualDomChildren, expectedDomChildren, sameNodes );
  396. let i = 0;
  397. for ( let action of actions ) {
  398. if ( action === 'insert' ) {
  399. insertAt( domElement, i, expectedDomChildren[ i ] );
  400. i++;
  401. } else if ( action === 'delete' ) {
  402. remove( actualDomChildren[ i ] );
  403. } else { // 'equal'
  404. i++;
  405. }
  406. }
  407. function sameNodes( actualDomChild, expectedDomChild ) {
  408. // Elements.
  409. if ( actualDomChild === expectedDomChild ) {
  410. return true;
  411. }
  412. // Texts.
  413. else if ( domConverter.isText( actualDomChild ) && domConverter.isText( expectedDomChild ) ) {
  414. return actualDomChild.data === expectedDomChild.data;
  415. }
  416. // Block fillers.
  417. else if ( isBlockFiller( actualDomChild, domConverter.blockFiller ) &&
  418. isBlockFiller( expectedDomChild, domConverter.blockFiller ) ) {
  419. return true;
  420. }
  421. // Not matching types.
  422. return false;
  423. }
  424. }
  425. /**
  426. * Checks if selection needs to be updated and possibly updates it.
  427. *
  428. * @private
  429. */
  430. _updateSelection() {
  431. // If there is no selection - remove DOM and fake selections.
  432. if ( this.selection.rangeCount === 0 ) {
  433. this._removeDomSelection();
  434. this._removeFakeSelection();
  435. return;
  436. }
  437. const domRoot = this.domConverter.getCorrespondingDomElement( this.selection.editableElement );
  438. // Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.
  439. if ( !this.isFocused || !domRoot ) {
  440. return;
  441. }
  442. // Render selection.
  443. if ( this.selection.isFake ) {
  444. this._updateFakeSelection( domRoot );
  445. } else {
  446. this._removeFakeSelection();
  447. this._updateDomSelection( domRoot );
  448. }
  449. }
  450. /**
  451. * Updates fake selection.
  452. *
  453. * @private
  454. * @param {HTMLElement} domRoot Valid DOM root where fake selection container should be added.
  455. */
  456. _updateFakeSelection( domRoot ) {
  457. const domDocument = domRoot.ownerDocument;
  458. // Create fake selection container if one does not exist.
  459. if ( !this._fakeSelectionContainer ) {
  460. this._fakeSelectionContainer = domDocument.createElement( 'div' );
  461. this._fakeSelectionContainer.style.position = 'fixed';
  462. this._fakeSelectionContainer.style.top = 0;
  463. this._fakeSelectionContainer.style.left = '-9999px';
  464. this._fakeSelectionContainer.appendChild( domDocument.createTextNode( '\u00A0' ) );
  465. }
  466. // Add fake container if not already added.
  467. if ( !this._fakeSelectionContainer.parentElement ) {
  468. domRoot.appendChild( this._fakeSelectionContainer );
  469. }
  470. // Update contents.
  471. const content = this.selection.fakeSelectionLabel || '\u00A0';
  472. this._fakeSelectionContainer.firstChild.data = content;
  473. // Update selection.
  474. const domSelection = domDocument.getSelection();
  475. domSelection.removeAllRanges();
  476. const domRange = new Range();
  477. domRange.selectNodeContents( this._fakeSelectionContainer );
  478. domSelection.addRange( domRange );
  479. // Bind fake selection container with current selection.
  480. this.domConverter.bindFakeSelection( this._fakeSelectionContainer, this.selection );
  481. }
  482. /**
  483. * Updates DOM selection.
  484. *
  485. * @private
  486. * @param {HTMLElement} domRoot Valid DOM root where DOM selection should be rendered.
  487. */
  488. _updateDomSelection( domRoot ) {
  489. const domSelection = domRoot.ownerDocument.defaultView.getSelection();
  490. const oldViewSelection = domSelection && this.domConverter.domSelectionToView( domSelection );
  491. if ( oldViewSelection && this.selection.isEqual( oldViewSelection ) ) {
  492. return;
  493. }
  494. // Multi-range selection is not available in most browsers, and, at least in Chrome, trying to
  495. // set such selection, that is not continuous, throws an error. Because of that, we will just use anchor
  496. // and focus of view selection.
  497. // Since we are not supporting multi-range selection, we also do not need to check if proper editable is
  498. // selected. If there is any editable selected, it is okay (editable is taken from selection anchor).
  499. const anchor = this.domConverter.viewPositionToDom( this.selection.anchor );
  500. const focus = this.domConverter.viewPositionToDom( this.selection.focus );
  501. domSelection.collapse( anchor.parent, anchor.offset );
  502. domSelection.extend( focus.parent, focus.offset );
  503. }
  504. /**
  505. * Removes DOM selection.
  506. *
  507. * @private
  508. */
  509. _removeDomSelection() {
  510. for ( let doc of this.domDocuments ) {
  511. const domSelection = doc.getSelection();
  512. if ( domSelection.rangeCount ) {
  513. const activeDomElement = doc.activeElement;
  514. const viewElement = this.domConverter.getCorrespondingViewElement( activeDomElement );
  515. if ( activeDomElement && viewElement ) {
  516. doc.getSelection().removeAllRanges();
  517. }
  518. }
  519. }
  520. }
  521. /**
  522. * Removes fake selection.
  523. *
  524. * @private
  525. */
  526. _removeFakeSelection() {
  527. const container = this._fakeSelectionContainer;
  528. if ( container ) {
  529. container.remove();
  530. }
  531. }
  532. /**
  533. * Checks if focus needs to be updated and possibly updates it.
  534. *
  535. * @private
  536. */
  537. _updateFocus() {
  538. if ( this.isFocused ) {
  539. const editable = this.selection.editableElement;
  540. if ( editable ) {
  541. this.domConverter.focus( editable );
  542. }
  543. }
  544. }
  545. }
  546. mix( Renderer, ObservableMixin );