8
0

renderer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. * 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. /**
  97. * Mark node to be synchronized.
  98. *
  99. * Note that only view nodes which parents have corresponding DOM elements need to be marked to be synchronized.
  100. *
  101. * @see engine.view.Renderer#markedAttributes
  102. * @see engine.view.Renderer#markedChildren
  103. * @see engine.view.Renderer#markedTexts
  104. *
  105. * @param {engine.view.ChangeType} type Type of the change.
  106. * @param {engine.view.Node} node Node to be marked.
  107. */
  108. markToSync( type, node ) {
  109. if ( type === 'text' ) {
  110. if ( this.domConverter.getCorrespondingDom( node.parent ) ) {
  111. this.markedTexts.add( node );
  112. }
  113. } else {
  114. // If the node has no DOM element it is not rendered yet,
  115. // its children/attributes do not need to be marked to be sync.
  116. if ( !this.domConverter.getCorrespondingDom( node ) ) {
  117. return;
  118. }
  119. if ( type === 'attributes' ) {
  120. this.markedAttributes.add( node );
  121. } else if ( type === 'children' ) {
  122. this.markedChildren.add( node );
  123. } else {
  124. /**
  125. * Unknown type passed to Renderer.markToSync.
  126. *
  127. * @error renderer-unknown-type
  128. */
  129. throw new CKEditorError( 'renderer-unknown-type: Unknown type passed to Renderer.markToSync.' );
  130. }
  131. }
  132. }
  133. /**
  134. * Render method checks {@link engine.view.Renderer#markedAttributes},
  135. * {@link engine.view.Renderer#markedChildren} and {@link engine.view.Renderer#markedTexts} and updats all
  136. * nodes which need to be updated. Then it clears all three sets. Also, every time render is called it compares and
  137. * if needed updates the selection.
  138. *
  139. * Renderer tries not to break text composition (e.g. IME) and x-index of the selection,
  140. * so it does as little as it is needed to update the DOM.
  141. *
  142. * For attributes it adds new attributes to DOM elements, updates values and removes
  143. * attributes which do not exist in the view element.
  144. *
  145. * For text nodes it updates the text string if it is different. Note that if parent element is marked as an element
  146. * which changed child list, text node update will not be done, because it may not be possible do find a
  147. * {@link engine.view.DomConverter#getCorrespondingDomText corresponding DOM text}. The change will be handled
  148. * in the parent element.
  149. *
  150. * For elements, which child lists have changed, it calculates a {@link diff} and adds or removs children which have changed.
  151. *
  152. * Rendering also handles {@link engine.view.filler fillers}. Especially, it checks if the inline filler is needed
  153. * at selection position and adds or removes it. To prevent breaking text composition inline filler will not be
  154. * removed as long selection is in the text node which needed it at first.
  155. */
  156. render() {
  157. if ( !this._isInlineFillerAtSelection() ) {
  158. this._removeInlineFiller();
  159. if ( this._needAddInlineFiller() ) {
  160. this._inlineFillerPosition = this.selection.getFirstPosition();
  161. // Do not use `markToSync` so it will be added even if the parent is already added.
  162. this.markedChildren.add( this._inlineFillerPosition.parent );
  163. } else {
  164. this._inlineFillerPosition = null;
  165. }
  166. }
  167. for ( let node of this.markedTexts ) {
  168. if ( !this.markedChildren.has( node.parent ) && this.domConverter.getCorrespondingDom( node.parent ) ) {
  169. this._updateText( node );
  170. }
  171. }
  172. for ( let element of this.markedAttributes ) {
  173. this._updateAttrs( element );
  174. }
  175. for ( let element of this.markedChildren ) {
  176. this._updateChildren( element );
  177. }
  178. this._updateSelection();
  179. this._updateFocus();
  180. this.markedTexts.clear();
  181. this.markedAttributes.clear();
  182. this.markedChildren.clear();
  183. }
  184. /**
  185. * Returns `true` if the inline filler and selection are in the same place.
  186. * If it is true it means filler had been added for a reason and selection does not
  187. * left text node, user can be in the middle of the composition so it should not be touched.
  188. *
  189. * @private
  190. * @returns {Boolean} True if the inline filler and selection are in the same place.
  191. */
  192. _isInlineFillerAtSelection() {
  193. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  194. return false;
  195. }
  196. const selectionPosition = this.selection.getFirstPosition();
  197. const fillerPosition = this._inlineFillerPosition;
  198. if ( !fillerPosition ) {
  199. return false;
  200. }
  201. if ( fillerPosition.isEqual( selectionPosition ) ) {
  202. return true;
  203. }
  204. if ( selectionPosition.parent instanceof ViewText ) {
  205. if ( fillerPosition.isEqual( ViewPosition.createBefore( selectionPosition.parent ) ) ) {
  206. return true;
  207. }
  208. }
  209. return false;
  210. }
  211. /**
  212. * Removes inline filler.
  213. *
  214. * @private
  215. */
  216. _removeInlineFiller() {
  217. if ( !this._inlineFillerPosition ) {
  218. // Nothing to remove.
  219. return;
  220. }
  221. const domFillerPosition = this.domConverter.viewPositionToDom( this._inlineFillerPosition );
  222. const domFillerNode = domFillerPosition.parent;
  223. // If there is no filler viewPositionToDom will return parent node, so domFillerNode will be an element.
  224. if ( !( this.domConverter.isText( domFillerNode ) ) || !startsWithFiller( domFillerNode ) ) {
  225. /**
  226. * No inline filler on expected position.
  227. *
  228. * @error renderer-render-no-inline-filler.
  229. */
  230. throw new CKEditorError( 'renderer-render-no-inline-filler: No inline filler on expected position.' );
  231. }
  232. if ( isInlineFiller( domFillerNode ) ) {
  233. domFillerNode.parentNode.removeChild( domFillerNode );
  234. } else {
  235. domFillerNode.data = domFillerNode.data.substr( INLINE_FILLER_LENGTH );
  236. }
  237. }
  238. /**
  239. * Checks if the inline {@link engine.view.filler fillers} should be added.
  240. *
  241. * @private
  242. * @returns {Boolean} True if the inline fillers should be added.
  243. */
  244. _needAddInlineFiller() {
  245. if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
  246. return false;
  247. }
  248. const selectionPosition = this.selection.getFirstPosition();
  249. const selectionParent = selectionPosition.parent;
  250. const selectionOffset = selectionPosition.offset;
  251. // If there is no DOM root we do not care about fillers.
  252. if ( !this.domConverter.getCorrespondingDomElement( selectionParent.getRoot() ) ) {
  253. return false;
  254. }
  255. if ( !( selectionParent instanceof ViewElement ) ) {
  256. return false;
  257. }
  258. // We have block filler, we do not need inline one.
  259. if ( selectionOffset === selectionParent.getFillerOffset() ) {
  260. return false;
  261. }
  262. const nodeBefore = selectionPosition.nodeBefore;
  263. const nodeAfter = selectionPosition.nodeAfter;
  264. if ( nodeBefore instanceof ViewText || nodeAfter instanceof ViewText ) {
  265. return false;
  266. }
  267. return true;
  268. }
  269. /**
  270. * Checks if text needs to be updated and possibly updates it.
  271. *
  272. * @private
  273. * @param {engine.view.Text} viewText View text to update.
  274. */
  275. _updateText( viewText ) {
  276. const domText = this.domConverter.getCorrespondingDom( viewText );
  277. const actualText = domText.data;
  278. let expectedText = viewText.data;
  279. const filler = this._inlineFillerPosition;
  280. if ( filler && filler.parent == viewText.parent && filler.offset == viewText.getIndex() ) {
  281. expectedText = INLINE_FILLER + expectedText;
  282. }
  283. if ( actualText != expectedText ) {
  284. domText.data = expectedText;
  285. }
  286. }
  287. /**
  288. * Checks if attributes list needs to be updated and possibly updates it.
  289. *
  290. * @private
  291. * @param {engine.view.Element} viewElement View element to update.
  292. */
  293. _updateAttrs( viewElement ) {
  294. const domElement = this.domConverter.getCorrespondingDom( viewElement );
  295. const domAttrKeys = Array.from( domElement.attributes ).map( attr => attr.name );
  296. const viewAttrKeys = viewElement.getAttributeKeys();
  297. // Add or overwrite attributes.
  298. for ( let key of viewAttrKeys ) {
  299. domElement.setAttribute( key, viewElement.getAttribute( key ) );
  300. }
  301. // Remove from DOM attributes which do not exists in the view.
  302. for ( let key of domAttrKeys ) {
  303. if ( !viewElement.hasAttribute( key ) ) {
  304. domElement.removeAttribute( key );
  305. }
  306. }
  307. }
  308. /**
  309. * Checks if elements child list needs to be updated and possibly updates it.
  310. *
  311. * @private
  312. * @param {engine.view.Element} viewElement View element to update.
  313. */
  314. _updateChildren( viewElement ) {
  315. const domConverter = this.domConverter;
  316. const domElement = domConverter.getCorrespondingDom( viewElement );
  317. const domDocument = domElement.ownerDocument;
  318. const filler = this._inlineFillerPosition;
  319. const actualDomChildren = domElement.childNodes;
  320. const expectedDomChildren = Array.from( domConverter.viewChildrenToDom( viewElement, domDocument, { bind: true } ) );
  321. if ( filler && filler.parent == viewElement ) {
  322. const expectedNodeAfterFiller = expectedDomChildren[ filler.offset ];
  323. if ( this.domConverter.isText( expectedNodeAfterFiller ) ) {
  324. expectedNodeAfterFiller.data = INLINE_FILLER + expectedNodeAfterFiller.data;
  325. } else {
  326. expectedDomChildren.splice( filler.offset, 0, domDocument.createTextNode( INLINE_FILLER ) );
  327. }
  328. }
  329. const actions = diff( actualDomChildren, expectedDomChildren, sameNodes );
  330. let i = 0;
  331. for ( let action of actions ) {
  332. if ( action === 'INSERT' ) {
  333. insertAt( domElement, i, expectedDomChildren[ i ] );
  334. i++;
  335. } else if ( action === 'DELETE' ) {
  336. remove( actualDomChildren[ i ] );
  337. } else { // 'EQUAL'
  338. i++;
  339. }
  340. }
  341. function sameNodes( actualDomChild, expectedDomChild ) {
  342. // Elements.
  343. if ( actualDomChild === expectedDomChild ) {
  344. return true;
  345. }
  346. // Texts.
  347. else if ( domConverter.isText( actualDomChild ) && domConverter.isText( expectedDomChild ) ) {
  348. return actualDomChild.data === expectedDomChild.data;
  349. }
  350. // Block fillers.
  351. else if ( isBlockFiller( actualDomChild, domConverter.blockFiller ) &&
  352. isBlockFiller( expectedDomChild, domConverter.blockFiller ) ) {
  353. return true;
  354. }
  355. // Not matching types.
  356. return false;
  357. }
  358. }
  359. /**
  360. * Checks if selection needs to be updated and possibly updates it.
  361. *
  362. * @private
  363. */
  364. _updateSelection() {
  365. if ( !this.isFocused ) {
  366. return;
  367. }
  368. // If there is no selection - remove it from DOM elements that belongs to the editor.
  369. if ( this.selection.rangeCount === 0 ) {
  370. this._removeDomSelction();
  371. return;
  372. }
  373. const selectedEditable = this.selection.getEditableElement();
  374. const domRoot = this.domConverter.getCorrespondingDomElement( selectedEditable );
  375. if ( !domRoot ) {
  376. return;
  377. }
  378. const domSelection = domRoot.ownerDocument.defaultView.getSelection();
  379. const oldViewSelection = domSelection && this.domConverter.domSelectionToView( domSelection );
  380. if ( oldViewSelection && this.selection.isEqual( oldViewSelection ) ) {
  381. return;
  382. }
  383. domSelection.removeAllRanges();
  384. for ( let range of this.selection.getRanges() ) {
  385. // Update ranges only in currently selected editable.
  386. if ( range.start.parent.getRoot() == selectedEditable ) {
  387. const domRangeStart = this.domConverter.viewPositionToDom( range.start );
  388. const domRangeEnd = this.domConverter.viewPositionToDom( range.end );
  389. const domRange = new Range();
  390. domRange.setStart( domRangeStart.parent, domRangeStart.offset );
  391. domRange.setEnd( domRangeEnd.parent, domRangeEnd.offset );
  392. domSelection.addRange( domRange );
  393. }
  394. }
  395. }
  396. _removeDomSelction() {
  397. for ( let doc of this.domDocuments ) {
  398. const domSelection = doc.getSelection();
  399. if ( domSelection.rangeCount ) {
  400. const activeDomElement = doc.activeElement;
  401. const viewElement = this.domConverter.getCorrespondingViewElement( activeDomElement );
  402. if ( activeDomElement && viewElement ) {
  403. doc.getSelection().removeAllRanges();
  404. }
  405. }
  406. }
  407. }
  408. /**
  409. * Checks if focus needs to be updated and possibly updates it.
  410. *
  411. * @private
  412. */
  413. _updateFocus() {
  414. if ( this.isFocused ) {
  415. const editable = this.selection.getEditableElement();
  416. if ( editable ) {
  417. this.domConverter.focus( editable );
  418. }
  419. }
  420. }
  421. }
  422. mix( Renderer, ObservableMixin );