renderer.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import ViewText from './text.js';
  7. import ViewElement from './element.js';
  8. import ViewPosition from './position.js';
  9. import { INLINE_FILLER, INLINE_FILLER_LENGTH, startsWithFiller, isInlineFiller, isBlockFiller } from './filler.js';
  10. import mix from '../../utils/mix.js';
  11. import diff from '../../utils/diff.js';
  12. import insertAt from '../../utils/dom/insertat.js';
  13. import remove from '../../utils/dom/remove.js';
  14. import ObservableMixin from '../../utils/observablemixin.js';
  15. import CKEditorError from '../../utils/ckeditorerror.js';
  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. * Converter instance.
  41. *
  42. * @readonly
  43. * @member {engine.view.DomConverter} engine.view.Renderer#domConverter
  44. */
  45. this.domConverter = domConverter;
  46. /**
  47. * Set of nodes which attributes changed and may need to be rendered.
  48. *
  49. * @readonly
  50. * @member {Set.<engine.view.Node>} engine.view.Renderer#markedAttributes
  51. */
  52. this.markedAttributes = new Set();
  53. /**
  54. * Set of elements which child lists changed and may need to be rendered.
  55. *
  56. * @readonly
  57. * @member {Set.<engine.view.Node>} engine.view.Renderer#markedChildren
  58. */
  59. this.markedChildren = new Set();
  60. /**
  61. * Set of text nodes which text data changed and may need to be rendered.
  62. *
  63. * @readonly
  64. * @member {Set.<engine.view.Node>} engine.view.Renderer#markedTexts
  65. */
  66. this.markedTexts = new Set();
  67. /**
  68. * View selection. Renderer updates DOM Selection to make it match this one.
  69. *
  70. * @readonly
  71. * @member {engine.view.Selection} engine.view.Renderer#selection
  72. */
  73. this.selection = selection;
  74. /**
  75. * Position of the inline {@link engine.view.filler filler}.
  76. * It should always be put BEFORE the text which contains filler.
  77. *
  78. * @private
  79. * @member {engine.view.Position} engine.view.Renderer#_inlineFillerPosition
  80. */
  81. this._inlineFillerPosition = null;
  82. /**
  83. * Indicates if view document is focused and selection can be rendered. Selection will not be rendered if
  84. * this is set to `false`.
  85. *
  86. * @type {boolean}
  87. */
  88. this.isFocused = false;
  89. }
  90. /**
  91. * Mark node to be synchronized.
  92. *
  93. * Note that only view nodes which parents have corresponding DOM elements need to be marked to be synchronized.
  94. *
  95. * @see engine.view.Renderer#markedAttributes
  96. * @see engine.view.Renderer#markedChildren
  97. * @see engine.view.Renderer#markedTexts
  98. *
  99. * @param {engine.view.ChangeType} type Type of the change.
  100. * @param {engine.view.Node} node Node to be marked.
  101. */
  102. markToSync( type, node ) {
  103. if ( type === 'text' ) {
  104. if ( this.domConverter.getCorrespondingDom( node.parent ) ) {
  105. this.markedTexts.add( node );
  106. }
  107. } else {
  108. // If the node has no DOM element it is not rendered yet,
  109. // its children/attributes do not need to be marked to be sync.
  110. if ( !this.domConverter.getCorrespondingDom( node ) ) {
  111. return;
  112. }
  113. if ( type === 'attributes' ) {
  114. this.markedAttributes.add( node );
  115. } else if ( type === 'children' ) {
  116. this.markedChildren.add( node );
  117. } else {
  118. /**
  119. * Unknown type passed to Renderer.markToSync.
  120. *
  121. * @error renderer-unknown-type
  122. */
  123. throw new CKEditorError( 'renderer-unknown-type: Unknown type passed to Renderer.markToSync.' );
  124. }
  125. }
  126. }
  127. /**
  128. * Render method checks {@link engine.view.Renderer#markedAttributes},
  129. * {@link engine.view.Renderer#markedChildren} and {@link engine.view.Renderer#markedTexts} and updats all
  130. * nodes which need to be updated. Then it clears all three sets. Also, every time render is called it compares and
  131. * if needed updates the selection.
  132. *
  133. * Renderer tries not to break text composition (e.g. IME) and x-index of the selection,
  134. * so it does as little as it is needed to update the DOM.
  135. *
  136. * For attributes it adds new attributes to DOM elements, updates values and removes
  137. * attributes which do not exist in the view element.
  138. *
  139. * For text nodes it updates the text string if it is different. Note that if parent element is marked as an element
  140. * which changed child list, text node update will not be done, because it may not be possible do find a
  141. * {@link engine.view.DomConverter#getCorrespondingDomText corresponding DOM text}. The change will be handled
  142. * in the parent element.
  143. *
  144. * For elements, which child lists have changed, it calculates a {@link diff} and adds or removs children which have changed.
  145. *
  146. * Rendering also handles {@link engine.view.filler fillers}. Especially, it checks if the inline filler is needed
  147. * at selection position and adds or removes it. To prevent breaking text composition inline filler will not be
  148. * removed as long selection is in the text node which needed it at first.
  149. */
  150. render() {
  151. if ( !this._isInlineFillerAtSelection() ) {
  152. this._removeInlineFiller();
  153. if ( this._needAddInlineFiller() ) {
  154. this._inlineFillerPosition = this.selection.getFirstPosition();
  155. // Do not use `markToSync` so it will be added even if the parent is already added.
  156. this.markedChildren.add( this._inlineFillerPosition.parent );
  157. } else {
  158. this._inlineFillerPosition = null;
  159. }
  160. }
  161. for ( let node of this.markedTexts ) {
  162. if ( !this.markedChildren.has( node.parent ) && this.domConverter.getCorrespondingDom( node.parent ) ) {
  163. this._updateText( node );
  164. }
  165. }
  166. for ( let element of this.markedAttributes ) {
  167. this._updateAttrs( element );
  168. }
  169. for ( let element of this.markedChildren ) {
  170. this._updateChildren( element );
  171. }
  172. this._updateSelection();
  173. this.markedTexts.clear();
  174. this.markedAttributes.clear();
  175. this.markedChildren.clear();
  176. }
  177. /**
  178. * Returns `true` if the inline filler and selection are in the same place.
  179. * If it is true it means filler had been added for a reason and selection does not
  180. * left text node, user can be in the middle of the composition so it should not be touched.
  181. *
  182. * @private
  183. * @returns {Boolean} True if the inline filler and selection are in the same place.
  184. */
  185. _isInlineFillerAtSelection() {
  186. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  187. return false;
  188. }
  189. const selectionPosition = this.selection.getFirstPosition();
  190. const fillerPosition = this._inlineFillerPosition;
  191. if ( !fillerPosition ) {
  192. return false;
  193. }
  194. if ( fillerPosition.isEqual( selectionPosition ) ) {
  195. return true;
  196. }
  197. if ( selectionPosition.parent instanceof ViewText ) {
  198. if ( fillerPosition.isEqual( ViewPosition.createBefore( selectionPosition.parent ) ) ) {
  199. return true;
  200. }
  201. }
  202. return false;
  203. }
  204. /**
  205. * Removes inline filler.
  206. *
  207. * @private
  208. */
  209. _removeInlineFiller() {
  210. if ( !this._inlineFillerPosition ) {
  211. // Nothing to remove.
  212. return;
  213. }
  214. const domFillerPosition = this.domConverter.viewPositionToDom( this._inlineFillerPosition );
  215. const domFillerNode = domFillerPosition.parent;
  216. // If there is no filler viewPositionToDom will return parent node, so domFillerNode will be an element.
  217. if ( !( domFillerNode instanceof Text ) || !startsWithFiller( domFillerNode ) ) {
  218. /**
  219. * No inline filler on expected position.
  220. *
  221. * @error renderer-render-no-inline-filler.
  222. */
  223. throw new CKEditorError( 'renderer-render-no-inline-filler: No inline filler on expected position.' );
  224. }
  225. if ( isInlineFiller( domFillerNode ) ) {
  226. domFillerNode.parentNode.removeChild( domFillerNode );
  227. } else {
  228. domFillerNode.data = domFillerNode.data.substr( INLINE_FILLER_LENGTH );
  229. }
  230. }
  231. /**
  232. * Checks if the inline {@link engine.view.filler fillers} should be added.
  233. *
  234. * @private
  235. * @returns {Boolean} True if the inline fillers should be added.
  236. */
  237. _needAddInlineFiller() {
  238. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  239. return false;
  240. }
  241. const selectionPosition = this.selection.getFirstPosition();
  242. const selectionParent = selectionPosition.parent;
  243. const selectionOffset = selectionPosition.offset;
  244. // If there is no DOM root we do not care about fillers.
  245. if ( !this.domConverter.getCorrespondingDomElement( selectionParent.getRoot() ) ) {
  246. return false;
  247. }
  248. if ( !( selectionParent instanceof ViewElement ) ) {
  249. return false;
  250. }
  251. // We have block filler, we do not need inline one.
  252. if ( selectionOffset === selectionParent.getFillerOffset() ) {
  253. return false;
  254. }
  255. const nodeBefore = selectionPosition.nodeBefore;
  256. const nodeAfter = selectionPosition.nodeAfter;
  257. if ( nodeBefore instanceof ViewText || nodeAfter instanceof ViewText ) {
  258. return false;
  259. }
  260. return true;
  261. }
  262. /**
  263. * Checks if text needs to be updated and possibly updates it.
  264. *
  265. * @private
  266. * @param {engine.view.Text} viewText View text to update.
  267. */
  268. _updateText( viewText ) {
  269. const domText = this.domConverter.getCorrespondingDom( viewText );
  270. const actualText = domText.data;
  271. let expectedText = viewText.data;
  272. const filler = this._inlineFillerPosition;
  273. if ( filler && filler.parent == viewText.parent && filler.offset == viewText.getIndex() ) {
  274. expectedText = INLINE_FILLER + expectedText;
  275. }
  276. if ( actualText != expectedText ) {
  277. domText.data = expectedText;
  278. }
  279. }
  280. /**
  281. * Checks if attributes list needs to be updated and possibly updates it.
  282. *
  283. * @private
  284. * @param {engine.view.Element} viewElement View element to update.
  285. */
  286. _updateAttrs( viewElement ) {
  287. const domElement = this.domConverter.getCorrespondingDom( viewElement );
  288. const domAttrKeys = Array.from( domElement.attributes ).map( attr => attr.name );
  289. const viewAttrKeys = viewElement.getAttributeKeys();
  290. // Add or overwrite attributes.
  291. for ( let key of viewAttrKeys ) {
  292. domElement.setAttribute( key, viewElement.getAttribute( key ) );
  293. }
  294. // Remove from DOM attributes which do not exists in the view.
  295. for ( let key of domAttrKeys ) {
  296. if ( !viewElement.hasAttribute( key ) ) {
  297. domElement.removeAttribute( key );
  298. }
  299. }
  300. }
  301. /**
  302. * Checks if elements child list needs to be updated and possibly updates it.
  303. *
  304. * @private
  305. * @param {engine.view.Element} viewElement View element to update.
  306. */
  307. _updateChildren( viewElement ) {
  308. const domConverter = this.domConverter;
  309. const domElement = domConverter.getCorrespondingDom( viewElement );
  310. const domDocument = domElement.ownerDocument;
  311. const filler = this._inlineFillerPosition;
  312. const actualDomChildren = domElement.childNodes;
  313. const expectedDomChildren = Array.from( domConverter.viewChildrenToDom( viewElement, domDocument, { bind: true } ) );
  314. if ( filler && filler.parent == viewElement ) {
  315. const expectedNodeAfterFiller = expectedDomChildren[ filler.offset ];
  316. if ( expectedNodeAfterFiller instanceof Text ) {
  317. expectedNodeAfterFiller.data = INLINE_FILLER + expectedNodeAfterFiller.data;
  318. } else {
  319. expectedDomChildren.splice( filler.offset, 0, domDocument.createTextNode( INLINE_FILLER ) );
  320. }
  321. }
  322. const actions = diff( actualDomChildren, expectedDomChildren, sameNodes );
  323. let i = 0;
  324. for ( let action of actions ) {
  325. if ( action === 'INSERT' ) {
  326. insertAt( domElement, i, expectedDomChildren[ i ] );
  327. i++;
  328. } else if ( action === 'DELETE' ) {
  329. remove( actualDomChildren[ i ] );
  330. } else { // 'EQUAL'
  331. i++;
  332. }
  333. }
  334. function sameNodes( actualDomChild, expectedDomChild ) {
  335. // Elements.
  336. if ( actualDomChild === expectedDomChild ) {
  337. return true;
  338. }
  339. // Texts.
  340. else if ( actualDomChild instanceof Text && expectedDomChild instanceof Text ) {
  341. return actualDomChild.data === expectedDomChild.data;
  342. }
  343. // Block fillers.
  344. else if ( isBlockFiller( actualDomChild, domConverter.blockFiller ) &&
  345. isBlockFiller( expectedDomChild, domConverter.blockFiller ) ) {
  346. return true;
  347. }
  348. // Not matching types.
  349. return false;
  350. }
  351. }
  352. /**
  353. * Checks if selection needs to be updated and possibly updates it.
  354. *
  355. * @private
  356. */
  357. _updateSelection() {
  358. if ( !this.isFocused ) {
  359. return;
  360. }
  361. const selectedEditable = this.selection.getEditableElement();
  362. const domRoot = this.domConverter.getCorrespondingDomElement( selectedEditable );
  363. if ( !domRoot ) {
  364. return;
  365. }
  366. const domSelection = domRoot.ownerDocument.defaultView.getSelection();
  367. const oldViewSelection = domSelection && this.domConverter.domSelectionToView( domSelection );
  368. if ( oldViewSelection && this.selection.isEqual( oldViewSelection ) ) {
  369. return;
  370. }
  371. domSelection.removeAllRanges();
  372. for ( let range of this.selection.getRanges() ) {
  373. // Update ranges only in currently selected editable.
  374. if ( range.start.parent.getRoot() == selectedEditable ) {
  375. const domRangeStart = this.domConverter.viewPositionToDom( range.start );
  376. const domRangeEnd = this.domConverter.viewPositionToDom( range.end );
  377. const domRange = new Range();
  378. domRange.setStart( domRangeStart.parent, domRangeStart.offset );
  379. domRange.setEnd( domRangeEnd.parent, domRangeEnd.offset );
  380. domSelection.addRange( domRange );
  381. }
  382. }
  383. }
  384. }
  385. mix( Renderer, ObservableMixin );