renderer.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import ViewText from './text.js';
  6. import ViewElement from './element.js';
  7. import ViewPosition from './position.js';
  8. import { INLINE_FILLER, INLINE_FILLER_LENGTH, startsWithFiller, isInlineFiller, isBlockFiller } from './filler.js';
  9. import mix from '../../utils/mix.js';
  10. import diff from '../../utils/diff.js';
  11. import insertAt from '../../utils/dom/insertat.js';
  12. import remove from '../../utils/dom/remove.js';
  13. import ObservableMixin from '../../utils/observablemixin.js';
  14. import CKEditorError from '../../utils/ckeditorerror.js';
  15. /* global Range */
  16. /**
  17. * Renderer updates DOM structure and selection, to make them a reflection of the view structure and selection.
  18. *
  19. * View nodes which may need to be rendered needs to be {@link engine.view.Renderer#markToSync marked}.
  20. * Then, on {@link engine.view.Renderer#render render}, renderer compares the view nodes with the DOM nodes
  21. * in order to check which ones really need to be refreshed. Finally, it creates DOM nodes from these view nodes,
  22. * {@link engine.view.DomConverter#bindElements binds} them and inserts into the DOM tree.
  23. *
  24. * Every time {@link engine.view.Renderer#render render} is called, renderer additionally checks if
  25. * {@link engine.view.Renderer#selection selection} needs update and updates it if so.
  26. *
  27. * Renderer uses {@link engine.view.DomConverter} to transform and bind nodes.
  28. *
  29. * @memberOf engine.view
  30. */
  31. export default class Renderer {
  32. /**
  33. * Creates a renderer instance.
  34. *
  35. * @param {engine.view.DomConverter} domConverter Converter instance.
  36. * @param {engine.view.Selection} selection View selection.
  37. */
  38. constructor( domConverter, selection ) {
  39. /**
  40. * Set of DOM Documents instances.
  41. *
  42. * @member {Set.<Document>} engine.view.Renderer#domDocuments
  43. */
  44. this.domDocuments = new Set();
  45. /**
  46. * Converter instance.
  47. *
  48. * @readonly
  49. * @member {engine.view.DomConverter} engine.view.Renderer#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.<engine.view.Node>} engine.view.Renderer#markedAttributes
  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.<engine.view.Node>} engine.view.Renderer#markedChildren
  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.<engine.view.Node>} engine.view.Renderer#markedTexts
  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 {engine.view.Selection} engine.view.Renderer#selection
  78. */
  79. this.selection = selection;
  80. /**
  81. * Position of the inline {@link engine.view.filler filler}.
  82. * It should always be put before the text which contains filler.
  83. *
  84. * @private
  85. * @member {engine.view.Position} engine.view.Renderer#_inlineFillerPosition
  86. */
  87. this._inlineFillerPosition = 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} engine.view.Renderer#isFocused
  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 engine.view.Renderer#markedAttributes
  109. * @see engine.view.Renderer#markedChildren
  110. * @see engine.view.Renderer#markedTexts
  111. *
  112. * @param {engine.view.ChangeType} type Type of the change.
  113. * @param {engine.view.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 engine.view.Renderer#markedAttributes},
  142. * {@link engine.view.Renderer#markedChildren} and {@link engine.view.Renderer#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 engine.view.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 diff} and adds or removes children which have changed.
  158. *
  159. * Rendering also handles {@link 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. if ( !this._isInlineFillerAtSelection() ) {
  165. this._removeInlineFiller();
  166. if ( this._needAddInlineFiller() ) {
  167. this._inlineFillerPosition = this.selection.getFirstPosition();
  168. // Do not use `markToSync` so it will be added even if the parent is already added.
  169. this.markedChildren.add( this._inlineFillerPosition.parent );
  170. } else {
  171. this._inlineFillerPosition = null;
  172. }
  173. }
  174. for ( let node of this.markedTexts ) {
  175. if ( !this.markedChildren.has( node.parent ) && this.domConverter.getCorrespondingDom( node.parent ) ) {
  176. this._updateText( node );
  177. }
  178. }
  179. for ( let element of this.markedAttributes ) {
  180. this._updateAttrs( element );
  181. }
  182. for ( let element of this.markedChildren ) {
  183. this._updateChildren( element );
  184. }
  185. this._updateSelection();
  186. this._updateFocus();
  187. this.markedTexts.clear();
  188. this.markedAttributes.clear();
  189. this.markedChildren.clear();
  190. }
  191. /**
  192. * Returns `true` if the inline filler and selection are in the same place.
  193. * If it is true it means filler had been added for a reason and selection does not
  194. * left text node, user can be in the middle of the composition so it should not be touched.
  195. *
  196. * @private
  197. * @returns {Boolean} True if the inline filler and selection are in the same place.
  198. */
  199. _isInlineFillerAtSelection() {
  200. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  201. return false;
  202. }
  203. const selectionPosition = this.selection.getFirstPosition();
  204. const fillerPosition = this._inlineFillerPosition;
  205. if ( !fillerPosition ) {
  206. return false;
  207. }
  208. if ( fillerPosition.isEqual( selectionPosition ) ) {
  209. return true;
  210. }
  211. if ( selectionPosition.parent instanceof ViewText ) {
  212. if ( fillerPosition.isEqual( ViewPosition.createBefore( selectionPosition.parent ) ) ) {
  213. return true;
  214. }
  215. }
  216. return false;
  217. }
  218. /**
  219. * Removes inline filler.
  220. *
  221. * @private
  222. */
  223. _removeInlineFiller() {
  224. if ( !this._inlineFillerPosition ) {
  225. // Nothing to remove.
  226. return;
  227. }
  228. const domFillerPosition = this.domConverter.viewPositionToDom( this._inlineFillerPosition );
  229. const domFillerNode = domFillerPosition.parent;
  230. // If there is no filler viewPositionToDom will return parent node, so domFillerNode will be an element.
  231. if ( !( this.domConverter.isText( domFillerNode ) ) || !startsWithFiller( domFillerNode ) ) {
  232. /**
  233. * No inline filler on expected position.
  234. *
  235. * @error renderer-render-no-inline-filler.
  236. */
  237. throw new CKEditorError( 'view-renderer-render-no-inline-filler: No inline filler on expected position.' );
  238. }
  239. if ( isInlineFiller( domFillerNode ) ) {
  240. domFillerNode.parentNode.removeChild( domFillerNode );
  241. } else {
  242. domFillerNode.data = domFillerNode.data.substr( INLINE_FILLER_LENGTH );
  243. }
  244. }
  245. /**
  246. * Checks if the inline {@link engine.view.filler fillers} should be added.
  247. *
  248. * @private
  249. * @returns {Boolean} True if the inline fillers should be added.
  250. */
  251. _needAddInlineFiller() {
  252. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  253. return false;
  254. }
  255. const selectionPosition = this.selection.getFirstPosition();
  256. const selectionParent = selectionPosition.parent;
  257. const selectionOffset = selectionPosition.offset;
  258. // If there is no DOM root we do not care about fillers.
  259. if ( !this.domConverter.getCorrespondingDomElement( selectionParent.root ) ) {
  260. return false;
  261. }
  262. if ( !( selectionParent instanceof ViewElement ) ) {
  263. return false;
  264. }
  265. // We have block filler, we do not need inline one.
  266. if ( selectionOffset === selectionParent.getFillerOffset() ) {
  267. return false;
  268. }
  269. const nodeBefore = selectionPosition.nodeBefore;
  270. const nodeAfter = selectionPosition.nodeAfter;
  271. if ( nodeBefore instanceof ViewText || nodeAfter instanceof ViewText ) {
  272. return false;
  273. }
  274. return true;
  275. }
  276. /**
  277. * Checks if text needs to be updated and possibly updates it.
  278. *
  279. * @private
  280. * @param {engine.view.Text} viewText View text to update.
  281. */
  282. _updateText( viewText ) {
  283. const domText = this.domConverter.getCorrespondingDom( viewText );
  284. const newDomText = this.domConverter.viewToDom( viewText, domText.ownerDocument );
  285. const actualText = domText.data;
  286. let expectedText = newDomText.data;
  287. const filler = this._inlineFillerPosition;
  288. if ( filler && filler.parent == viewText.parent && filler.offset == viewText.index ) {
  289. expectedText = INLINE_FILLER + expectedText;
  290. }
  291. if ( actualText != expectedText ) {
  292. domText.data = expectedText;
  293. }
  294. }
  295. /**
  296. * Checks if attributes list needs to be updated and possibly updates it.
  297. *
  298. * @private
  299. * @param {engine.view.Element} viewElement View element to update.
  300. */
  301. _updateAttrs( viewElement ) {
  302. const domElement = this.domConverter.getCorrespondingDom( viewElement );
  303. const domAttrKeys = Array.from( domElement.attributes ).map( attr => attr.name );
  304. const viewAttrKeys = viewElement.getAttributeKeys();
  305. // Add or overwrite attributes.
  306. for ( let key of viewAttrKeys ) {
  307. domElement.setAttribute( key, viewElement.getAttribute( key ) );
  308. }
  309. // Remove from DOM attributes which do not exists in the view.
  310. for ( let key of domAttrKeys ) {
  311. if ( !viewElement.hasAttribute( key ) ) {
  312. domElement.removeAttribute( key );
  313. }
  314. }
  315. }
  316. /**
  317. * Checks if elements child list needs to be updated and possibly updates it.
  318. *
  319. * @private
  320. * @param {engine.view.Element} viewElement View element to update.
  321. */
  322. _updateChildren( viewElement ) {
  323. const domConverter = this.domConverter;
  324. const domElement = domConverter.getCorrespondingDom( viewElement );
  325. const domDocument = domElement.ownerDocument;
  326. const filler = this._inlineFillerPosition;
  327. const actualDomChildren = domElement.childNodes;
  328. const expectedDomChildren = Array.from( domConverter.viewChildrenToDom( viewElement, domDocument, { bind: true } ) );
  329. if ( filler && filler.parent == viewElement ) {
  330. const expectedNodeAfterFiller = expectedDomChildren[ filler.offset ];
  331. if ( this.domConverter.isText( expectedNodeAfterFiller ) ) {
  332. expectedNodeAfterFiller.data = INLINE_FILLER + expectedNodeAfterFiller.data;
  333. } else {
  334. expectedDomChildren.splice( filler.offset, 0, domDocument.createTextNode( INLINE_FILLER ) );
  335. }
  336. }
  337. const actions = diff( actualDomChildren, expectedDomChildren, sameNodes );
  338. let i = 0;
  339. for ( let action of actions ) {
  340. if ( action === 'insert' ) {
  341. insertAt( domElement, i, expectedDomChildren[ i ] );
  342. i++;
  343. } else if ( action === 'delete' ) {
  344. remove( actualDomChildren[ i ] );
  345. } else { // 'equal'
  346. i++;
  347. }
  348. }
  349. function sameNodes( actualDomChild, expectedDomChild ) {
  350. // Elements.
  351. if ( actualDomChild === expectedDomChild ) {
  352. return true;
  353. }
  354. // Texts.
  355. else if ( domConverter.isText( actualDomChild ) && domConverter.isText( expectedDomChild ) ) {
  356. return actualDomChild.data === expectedDomChild.data;
  357. }
  358. // Block fillers.
  359. else if ( isBlockFiller( actualDomChild, domConverter.blockFiller ) &&
  360. isBlockFiller( expectedDomChild, domConverter.blockFiller ) ) {
  361. return true;
  362. }
  363. // Not matching types.
  364. return false;
  365. }
  366. }
  367. /**
  368. * Checks if selection needs to be updated and possibly updates it.
  369. *
  370. * @private
  371. */
  372. _updateSelection() {
  373. // If there is no selection - remove DOM and fake selections.
  374. if ( this.selection.rangeCount === 0 ) {
  375. this._removeDomSelection();
  376. this._removeFakeSelection();
  377. return;
  378. }
  379. const domRoot = this.domConverter.getCorrespondingDomElement( this.selection.editableElement );
  380. // Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.
  381. if ( !this.isFocused || !domRoot ) {
  382. return;
  383. }
  384. // Render selection.
  385. if ( this.selection.isFake ) {
  386. this._updateFakeSelection( domRoot );
  387. } else {
  388. this._removeFakeSelection();
  389. this._updateDomSelection( domRoot );
  390. }
  391. }
  392. /**
  393. * Updates fake selection.
  394. *
  395. * @private
  396. * @param {HTMLElement} domRoot Valid DOM root where fake selection container should be added.
  397. */
  398. _updateFakeSelection( domRoot ) {
  399. const domDocument = domRoot.ownerDocument;
  400. // Create fake selection container if one does not exist.
  401. if ( !this._fakeSelectionContainer ) {
  402. this._fakeSelectionContainer = domDocument.createElement( 'div' );
  403. this._fakeSelectionContainer.style.position = 'fixed';
  404. this._fakeSelectionContainer.style.top = 0;
  405. this._fakeSelectionContainer.style.left = '-9999px';
  406. this._fakeSelectionContainer.appendChild( domDocument.createTextNode( '\u00A0' ) );
  407. }
  408. // Add fake container if not already added.
  409. if ( !this._fakeSelectionContainer.parentElement ) {
  410. domRoot.appendChild( this._fakeSelectionContainer );
  411. }
  412. // Update contents.
  413. const content = this.selection.fakeSelectionLabel || '\u00A0';
  414. this._fakeSelectionContainer.firstChild.data = content;
  415. // Update selection.
  416. const domSelection = domDocument.getSelection();
  417. domSelection.removeAllRanges();
  418. const domRange = new Range();
  419. domRange.selectNodeContents( this._fakeSelectionContainer );
  420. domSelection.addRange( domRange );
  421. // Bind fake selection container with current selection.
  422. this.domConverter.bindFakeSelection( this._fakeSelectionContainer, this.selection );
  423. }
  424. /**
  425. * Updates DOM selection.
  426. *
  427. * @private
  428. * @param {HTMLElement} domRoot Valid DOM root where DOM selection should be rendered.
  429. */
  430. _updateDomSelection( domRoot ) {
  431. const domSelection = domRoot.ownerDocument.defaultView.getSelection();
  432. const oldViewSelection = domSelection && this.domConverter.domSelectionToView( domSelection );
  433. if ( oldViewSelection && this.selection.isEqual( oldViewSelection ) ) {
  434. return;
  435. }
  436. // Multi-range selection is not available in most browsers, and, at least in Chrome, trying to
  437. // set such selection, that is not continuous, throws an error. Because of that, we will just use anchor
  438. // and focus of view selection.
  439. // Since we are not supporting multi-range selection, we also do not need to check if proper editable is
  440. // selected. If there is any editable selected, it is okay (editable is taken from selection anchor).
  441. const anchor = this.domConverter.viewPositionToDom( this.selection.anchor );
  442. const focus = this.domConverter.viewPositionToDom( this.selection.focus );
  443. domSelection.collapse( anchor.parent, anchor.offset );
  444. domSelection.extend( focus.parent, focus.offset );
  445. }
  446. /**
  447. * Removes DOM selection.
  448. *
  449. * @private
  450. */
  451. _removeDomSelection() {
  452. for ( let doc of this.domDocuments ) {
  453. const domSelection = doc.getSelection();
  454. if ( domSelection.rangeCount ) {
  455. const activeDomElement = doc.activeElement;
  456. const viewElement = this.domConverter.getCorrespondingViewElement( activeDomElement );
  457. if ( activeDomElement && viewElement ) {
  458. doc.getSelection().removeAllRanges();
  459. }
  460. }
  461. }
  462. }
  463. /**
  464. * Removes fake selection.
  465. *
  466. * @private
  467. */
  468. _removeFakeSelection() {
  469. const container = this._fakeSelectionContainer;
  470. if ( container ) {
  471. container.remove();
  472. }
  473. }
  474. /**
  475. * Checks if focus needs to be updated and possibly updates it.
  476. *
  477. * @private
  478. */
  479. _updateFocus() {
  480. if ( this.isFocused ) {
  481. const editable = this.selection.editableElement;
  482. if ( editable ) {
  483. this.domConverter.focus( editable );
  484. }
  485. }
  486. }
  487. }
  488. mix( Renderer, ObservableMixin );