domconverter.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/view/domconverter
  7. */
  8. /* globals document, Node, NodeFilter, Text */
  9. import ViewText from './text';
  10. import ViewElement from './element';
  11. import ViewPosition from './position';
  12. import ViewRange from './range';
  13. import ViewSelection from './selection';
  14. import ViewDocumentFragment from './documentfragment';
  15. import ViewTreeWalker from './treewalker';
  16. import { BR_FILLER, INLINE_FILLER_LENGTH, isBlockFiller, isInlineFiller, startsWithFiller, getDataWithoutFiller } from './filler';
  17. import global from '@ckeditor/ckeditor5-utils/src/dom/global';
  18. import indexOf from '@ckeditor/ckeditor5-utils/src/dom/indexof';
  19. import getAncestors from '@ckeditor/ckeditor5-utils/src/dom/getancestors';
  20. import getCommonAncestor from '@ckeditor/ckeditor5-utils/src/dom/getcommonancestor';
  21. import isText from '@ckeditor/ckeditor5-utils/src/dom/istext';
  22. import { isElement } from 'lodash-es';
  23. /**
  24. * DomConverter is a set of tools to do transformations between DOM nodes and view nodes. It also handles
  25. * {@link module:engine/view/domconverter~DomConverter#bindElements binding} these nodes.
  26. *
  27. * DomConverter does not check which nodes should be rendered (use {@link module:engine/view/renderer~Renderer}), does not keep a
  28. * state of a tree nor keeps synchronization between tree view and DOM tree (use {@link module:engine/view/document~Document}).
  29. *
  30. * DomConverter keeps DOM elements to View element bindings, so when the converter will be destroyed, the binding will
  31. * be lost. Two converters will keep separate binding maps, so one tree view can be bound with two DOM trees.
  32. */
  33. export default class DomConverter {
  34. /**
  35. * Creates DOM converter.
  36. *
  37. * @param {Object} options Object with configuration options.
  38. * @param {Function} [options.blockFiller=module:engine/view/filler~BR_FILLER] Block filler creator.
  39. */
  40. constructor( options = {} ) {
  41. // Using WeakMap prevent memory leaks: when the converter will be destroyed all referenced between View and DOM
  42. // will be removed. Also because it is a *Weak*Map when both view and DOM elements will be removed referenced
  43. // will be also removed, isn't it brilliant?
  44. //
  45. // Yes, PJ. It is.
  46. //
  47. // You guys so smart.
  48. //
  49. // I've been here. Seen stuff. Afraid of code now.
  50. /**
  51. * Block {@link module:engine/view/filler filler} creator, which is used to create all block fillers during the
  52. * view to DOM conversion and to recognize block fillers during the DOM to view conversion.
  53. *
  54. * @readonly
  55. * @member {Function} module:engine/view/domconverter~DomConverter#blockFiller
  56. */
  57. this.blockFiller = options.blockFiller || BR_FILLER;
  58. /**
  59. * Tag names of DOM `Element`s which are considered pre-formatted elements.
  60. *
  61. * @readonly
  62. * @member {Array.<String>} module:engine/view/domconverter~DomConverter#preElements
  63. */
  64. this.preElements = [ 'pre' ];
  65. /**
  66. * Tag names of DOM `Element`s which are considered block elements.
  67. *
  68. * @readonly
  69. * @member {Array.<String>} module:engine/view/domconverter~DomConverter#blockElements
  70. */
  71. this.blockElements = [ 'p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ];
  72. /**
  73. * DOM to View mapping.
  74. *
  75. * @private
  76. * @member {WeakMap} module:engine/view/domconverter~DomConverter#_domToViewMapping
  77. */
  78. this._domToViewMapping = new WeakMap();
  79. /**
  80. * View to DOM mapping.
  81. *
  82. * @private
  83. * @member {WeakMap} module:engine/view/domconverter~DomConverter#_viewToDomMapping
  84. */
  85. this._viewToDomMapping = new WeakMap();
  86. /**
  87. * Holds mapping between fake selection containers and corresponding view selections.
  88. *
  89. * @private
  90. * @member {WeakMap} module:engine/view/domconverter~DomConverter#_fakeSelectionMapping
  91. */
  92. this._fakeSelectionMapping = new WeakMap();
  93. }
  94. /**
  95. * Binds given DOM element that represents fake selection to {@link module:engine/view/documentselection~DocumentSelection
  96. * document selection}. Document selection copy is stored and can be retrieved by
  97. * {@link module:engine/view/domconverter~DomConverter#fakeSelectionToView} method.
  98. *
  99. * @param {HTMLElement} domElement
  100. * @param {module:engine/view/documentselection~DocumentSelection} viewDocumentSelection
  101. */
  102. bindFakeSelection( domElement, viewDocumentSelection ) {
  103. this._fakeSelectionMapping.set( domElement, new ViewSelection( viewDocumentSelection ) );
  104. }
  105. /**
  106. * Returns {@link module:engine/view/selection~Selection view selection} instance corresponding to
  107. * given DOM element that represents fake selection. Returns `undefined` if binding to given DOM element does not exists.
  108. *
  109. * @param {HTMLElement} domElement
  110. * @returns {module:engine/view/selection~Selection|undefined}
  111. */
  112. fakeSelectionToView( domElement ) {
  113. return this._fakeSelectionMapping.get( domElement );
  114. }
  115. /**
  116. * Binds DOM and View elements, so it will be possible to get corresponding elements using
  117. * {@link module:engine/view/domconverter~DomConverter#mapDomToView} and
  118. * {@link module:engine/view/domconverter~DomConverter#mapViewToDom}.
  119. *
  120. * @param {HTMLElement} domElement DOM element to bind.
  121. * @param {module:engine/view/element~Element} viewElement View element to bind.
  122. */
  123. bindElements( domElement, viewElement ) {
  124. this._domToViewMapping.set( domElement, viewElement );
  125. this._viewToDomMapping.set( viewElement, domElement );
  126. }
  127. /**
  128. * Unbinds given `domElement` from the view element it was bound to. Unbinding is deep, meaning that all children of
  129. * `domElement` will be unbound too.
  130. *
  131. * @param {HTMLElement} domElement DOM element to unbind.
  132. */
  133. unbindDomElement( domElement ) {
  134. const viewElement = this._domToViewMapping.get( domElement );
  135. if ( viewElement ) {
  136. this._domToViewMapping.delete( domElement );
  137. this._viewToDomMapping.delete( viewElement );
  138. // Use Array.from because of MS Edge (#923).
  139. for ( const child of Array.from( domElement.childNodes ) ) {
  140. this.unbindDomElement( child );
  141. }
  142. }
  143. }
  144. /**
  145. * Binds DOM and View document fragments, so it will be possible to get corresponding document fragments using
  146. * {@link module:engine/view/domconverter~DomConverter#mapDomToView} and
  147. * {@link module:engine/view/domconverter~DomConverter#mapViewToDom}.
  148. *
  149. * @param {DocumentFragment} domFragment DOM document fragment to bind.
  150. * @param {module:engine/view/documentfragment~DocumentFragment} viewFragment View document fragment to bind.
  151. */
  152. bindDocumentFragments( domFragment, viewFragment ) {
  153. this._domToViewMapping.set( domFragment, viewFragment );
  154. this._viewToDomMapping.set( viewFragment, domFragment );
  155. }
  156. /**
  157. * Converts view to DOM. For all text nodes, not bound elements and document fragments new items will
  158. * be created. For bound elements and document fragments function will return corresponding items.
  159. *
  160. * @param {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment} viewNode
  161. * View node or document fragment to transform.
  162. * @param {Document} domDocument Document which will be used to create DOM nodes.
  163. * @param {Object} [options] Conversion options.
  164. * @param {Boolean} [options.bind=false] Determines whether new elements will be bound.
  165. * @param {Boolean} [options.withChildren=true] If `true`, node's and document fragment's children will be converted too.
  166. * @returns {Node|DocumentFragment} Converted node or DocumentFragment.
  167. */
  168. viewToDom( viewNode, domDocument, options = {} ) {
  169. if ( viewNode.is( 'text' ) ) {
  170. const textData = this._processDataFromViewText( viewNode );
  171. return domDocument.createTextNode( textData );
  172. } else {
  173. if ( this.mapViewToDom( viewNode ) ) {
  174. return this.mapViewToDom( viewNode );
  175. }
  176. let domElement;
  177. if ( viewNode.is( 'documentFragment' ) ) {
  178. // Create DOM document fragment.
  179. domElement = domDocument.createDocumentFragment();
  180. if ( options.bind ) {
  181. this.bindDocumentFragments( domElement, viewNode );
  182. }
  183. } else if ( viewNode.is( 'uiElement' ) ) {
  184. // UIElement has its own render() method (see #799).
  185. domElement = viewNode.render( domDocument );
  186. if ( options.bind ) {
  187. this.bindElements( domElement, viewNode );
  188. }
  189. return domElement;
  190. } else {
  191. // Create DOM element.
  192. domElement = domDocument.createElement( viewNode.name );
  193. if ( options.bind ) {
  194. this.bindElements( domElement, viewNode );
  195. }
  196. // Copy element's attributes.
  197. for ( const key of viewNode.getAttributeKeys() ) {
  198. domElement.setAttribute( key, viewNode.getAttribute( key ) );
  199. }
  200. }
  201. if ( options.withChildren || options.withChildren === undefined ) {
  202. for ( const child of this.viewChildrenToDom( viewNode, domDocument, options ) ) {
  203. domElement.appendChild( child );
  204. }
  205. }
  206. return domElement;
  207. }
  208. }
  209. /**
  210. * Converts children of the view element to DOM using the
  211. * {@link module:engine/view/domconverter~DomConverter#viewToDom} method.
  212. * Additionally, this method adds block {@link module:engine/view/filler filler} to the list of children, if needed.
  213. *
  214. * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment} viewElement Parent view element.
  215. * @param {Document} domDocument Document which will be used to create DOM nodes.
  216. * @param {Object} options See {@link module:engine/view/domconverter~DomConverter#viewToDom} options parameter.
  217. * @returns {Iterable.<Node>} DOM nodes.
  218. */
  219. * viewChildrenToDom( viewElement, domDocument, options = {} ) {
  220. const fillerPositionOffset = viewElement.getFillerOffset && viewElement.getFillerOffset();
  221. let offset = 0;
  222. for ( const childView of viewElement.getChildren() ) {
  223. if ( fillerPositionOffset === offset ) {
  224. yield this.blockFiller( domDocument );
  225. }
  226. yield this.viewToDom( childView, domDocument, options );
  227. offset++;
  228. }
  229. if ( fillerPositionOffset === offset ) {
  230. yield this.blockFiller( domDocument );
  231. }
  232. }
  233. /**
  234. * Converts view {@link module:engine/view/range~Range} to DOM range.
  235. * Inline and block {@link module:engine/view/filler fillers} are handled during the conversion.
  236. *
  237. * @param {module:engine/view/range~Range} viewRange View range.
  238. * @returns {Range} DOM range.
  239. */
  240. viewRangeToDom( viewRange ) {
  241. const domStart = this.viewPositionToDom( viewRange.start );
  242. const domEnd = this.viewPositionToDom( viewRange.end );
  243. const domRange = document.createRange();
  244. domRange.setStart( domStart.parent, domStart.offset );
  245. domRange.setEnd( domEnd.parent, domEnd.offset );
  246. return domRange;
  247. }
  248. /**
  249. * Converts view {@link module:engine/view/position~Position} to DOM parent and offset.
  250. *
  251. * Inline and block {@link module:engine/view/filler fillers} are handled during the conversion.
  252. * If the converted position is directly before inline filler it is moved inside the filler.
  253. *
  254. * @param {module:engine/view/position~Position} viewPosition View position.
  255. * @returns {Object|null} position DOM position or `null` if view position could not be converted to DOM.
  256. * @returns {Node} position.parent DOM position parent.
  257. * @returns {Number} position.offset DOM position offset.
  258. */
  259. viewPositionToDom( viewPosition ) {
  260. const viewParent = viewPosition.parent;
  261. if ( viewParent.is( 'text' ) ) {
  262. const domParent = this.findCorrespondingDomText( viewParent );
  263. if ( !domParent ) {
  264. // Position is in a view text node that has not been rendered to DOM yet.
  265. return null;
  266. }
  267. let offset = viewPosition.offset;
  268. if ( startsWithFiller( domParent ) ) {
  269. offset += INLINE_FILLER_LENGTH;
  270. }
  271. return { parent: domParent, offset };
  272. } else {
  273. // viewParent is instance of ViewElement.
  274. let domParent, domBefore, domAfter;
  275. if ( viewPosition.offset === 0 ) {
  276. domParent = this.mapViewToDom( viewParent );
  277. if ( !domParent ) {
  278. // Position is in a view element that has not been rendered to DOM yet.
  279. return null;
  280. }
  281. domAfter = domParent.childNodes[ 0 ];
  282. } else {
  283. const nodeBefore = viewPosition.nodeBefore;
  284. domBefore = nodeBefore.is( 'text' ) ?
  285. this.findCorrespondingDomText( nodeBefore ) :
  286. this.mapViewToDom( viewPosition.nodeBefore );
  287. if ( !domBefore ) {
  288. // Position is after a view element that has not been rendered to DOM yet.
  289. return null;
  290. }
  291. domParent = domBefore.parentNode;
  292. domAfter = domBefore.nextSibling;
  293. }
  294. // If there is an inline filler at position return position inside the filler. We should never return
  295. // the position before the inline filler.
  296. if ( isText( domAfter ) && startsWithFiller( domAfter ) ) {
  297. return { parent: domAfter, offset: INLINE_FILLER_LENGTH };
  298. }
  299. const offset = domBefore ? indexOf( domBefore ) + 1 : 0;
  300. return { parent: domParent, offset };
  301. }
  302. }
  303. /**
  304. * Converts DOM to view. For all text nodes, not bound elements and document fragments new items will
  305. * be created. For bound elements and document fragments function will return corresponding items. For
  306. * {@link module:engine/view/filler fillers} `null` will be returned.
  307. * For all DOM elements rendered by {@link module:engine/view/uielement~UIElement} that UIElement will be returned.
  308. *
  309. * @param {Node|DocumentFragment} domNode DOM node or document fragment to transform.
  310. * @param {Object} [options] Conversion options.
  311. * @param {Boolean} [options.bind=false] Determines whether new elements will be bound.
  312. * @param {Boolean} [options.withChildren=true] If `true`, node's and document fragment's children will be converted too.
  313. * @param {Boolean} [options.keepOriginalCase=false] If `false`, node's tag name will be converter to lower case.
  314. * @returns {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment|null} Converted node or document fragment
  315. * or `null` if DOM node is a {@link module:engine/view/filler filler} or the given node is an empty text node.
  316. */
  317. domToView( domNode, options = {} ) {
  318. if ( isBlockFiller( domNode, this.blockFiller ) ) {
  319. return null;
  320. }
  321. // When node is inside UIElement return that UIElement as it's view representation.
  322. const uiElement = this.getParentUIElement( domNode, this._domToViewMapping );
  323. if ( uiElement ) {
  324. return uiElement;
  325. }
  326. if ( isText( domNode ) ) {
  327. if ( isInlineFiller( domNode ) ) {
  328. return null;
  329. } else {
  330. const textData = this._processDataFromDomText( domNode );
  331. return textData === '' ? null : new ViewText( textData );
  332. }
  333. } else if ( this.isComment( domNode ) ) {
  334. return null;
  335. } else {
  336. if ( this.mapDomToView( domNode ) ) {
  337. return this.mapDomToView( domNode );
  338. }
  339. let viewElement;
  340. if ( this.isDocumentFragment( domNode ) ) {
  341. // Create view document fragment.
  342. viewElement = new ViewDocumentFragment();
  343. if ( options.bind ) {
  344. this.bindDocumentFragments( domNode, viewElement );
  345. }
  346. } else {
  347. // Create view element.
  348. const viewName = options.keepOriginalCase ? domNode.tagName : domNode.tagName.toLowerCase();
  349. viewElement = new ViewElement( viewName );
  350. if ( options.bind ) {
  351. this.bindElements( domNode, viewElement );
  352. }
  353. // Copy element's attributes.
  354. const attrs = domNode.attributes;
  355. for ( let i = attrs.length - 1; i >= 0; i-- ) {
  356. viewElement._setAttribute( attrs[ i ].name, attrs[ i ].value );
  357. }
  358. }
  359. if ( options.withChildren || options.withChildren === undefined ) {
  360. for ( const child of this.domChildrenToView( domNode, options ) ) {
  361. viewElement._appendChild( child );
  362. }
  363. }
  364. return viewElement;
  365. }
  366. }
  367. /**
  368. * Converts children of the DOM element to view nodes using
  369. * the {@link module:engine/view/domconverter~DomConverter#domToView} method.
  370. * Additionally this method omits block {@link module:engine/view/filler filler}, if it exists in the DOM parent.
  371. *
  372. * @param {HTMLElement} domElement Parent DOM element.
  373. * @param {Object} options See {@link module:engine/view/domconverter~DomConverter#domToView} options parameter.
  374. * @returns {Iterable.<module:engine/view/node~Node>} View nodes.
  375. */
  376. * domChildrenToView( domElement, options = {} ) {
  377. for ( let i = 0; i < domElement.childNodes.length; i++ ) {
  378. const domChild = domElement.childNodes[ i ];
  379. const viewChild = this.domToView( domChild, options );
  380. if ( viewChild !== null ) {
  381. yield viewChild;
  382. }
  383. }
  384. }
  385. /**
  386. * Converts DOM selection to view {@link module:engine/view/selection~Selection}.
  387. * Ranges which cannot be converted will be omitted.
  388. *
  389. * @param {Selection} domSelection DOM selection.
  390. * @returns {module:engine/view/selection~Selection} View selection.
  391. */
  392. domSelectionToView( domSelection ) {
  393. // DOM selection might be placed in fake selection container.
  394. // If container contains fake selection - return corresponding view selection.
  395. if ( domSelection.rangeCount === 1 ) {
  396. let container = domSelection.getRangeAt( 0 ).startContainer;
  397. // The DOM selection might be moved to the text node inside the fake selection container.
  398. if ( isText( container ) ) {
  399. container = container.parentNode;
  400. }
  401. const viewSelection = this.fakeSelectionToView( container );
  402. if ( viewSelection ) {
  403. return viewSelection;
  404. }
  405. }
  406. const isBackward = this.isDomSelectionBackward( domSelection );
  407. const viewRanges = [];
  408. for ( let i = 0; i < domSelection.rangeCount; i++ ) {
  409. // DOM Range have correct start and end, no matter what is the DOM Selection direction. So we don't have to fix anything.
  410. const domRange = domSelection.getRangeAt( i );
  411. const viewRange = this.domRangeToView( domRange );
  412. if ( viewRange ) {
  413. viewRanges.push( viewRange );
  414. }
  415. }
  416. return new ViewSelection( viewRanges, { backward: isBackward } );
  417. }
  418. /**
  419. * Converts DOM Range to view {@link module:engine/view/range~Range}.
  420. * If the start or end position can not be converted `null` is returned.
  421. *
  422. * @param {Range} domRange DOM range.
  423. * @returns {module:engine/view/range~Range|null} View range.
  424. */
  425. domRangeToView( domRange ) {
  426. const viewStart = this.domPositionToView( domRange.startContainer, domRange.startOffset );
  427. const viewEnd = this.domPositionToView( domRange.endContainer, domRange.endOffset );
  428. if ( viewStart && viewEnd ) {
  429. return new ViewRange( viewStart, viewEnd );
  430. }
  431. return null;
  432. }
  433. /**
  434. * Converts DOM parent and offset to view {@link module:engine/view/position~Position}.
  435. *
  436. * If the position is inside a {@link module:engine/view/filler filler} which has no corresponding view node,
  437. * position of the filler will be converted and returned.
  438. *
  439. * If the position is inside DOM element rendered by {@link module:engine/view/uielement~UIElement}
  440. * that position will be converted to view position before that UIElement.
  441. *
  442. * If structures are too different and it is not possible to find corresponding position then `null` will be returned.
  443. *
  444. * @param {Node} domParent DOM position parent.
  445. * @param {Number} domOffset DOM position offset.
  446. * @returns {module:engine/view/position~Position} viewPosition View position.
  447. */
  448. domPositionToView( domParent, domOffset ) {
  449. if ( isBlockFiller( domParent, this.blockFiller ) ) {
  450. return this.domPositionToView( domParent.parentNode, indexOf( domParent ) );
  451. }
  452. // If position is somewhere inside UIElement - return position before that element.
  453. const viewElement = this.mapDomToView( domParent );
  454. if ( viewElement && viewElement.is( 'uiElement' ) ) {
  455. return ViewPosition._createBefore( viewElement );
  456. }
  457. if ( isText( domParent ) ) {
  458. if ( isInlineFiller( domParent ) ) {
  459. return this.domPositionToView( domParent.parentNode, indexOf( domParent ) );
  460. }
  461. const viewParent = this.findCorrespondingViewText( domParent );
  462. let offset = domOffset;
  463. if ( !viewParent ) {
  464. return null;
  465. }
  466. if ( startsWithFiller( domParent ) ) {
  467. offset -= INLINE_FILLER_LENGTH;
  468. offset = offset < 0 ? 0 : offset;
  469. }
  470. return new ViewPosition( viewParent, offset );
  471. }
  472. // domParent instanceof HTMLElement.
  473. else {
  474. if ( domOffset === 0 ) {
  475. const viewParent = this.mapDomToView( domParent );
  476. if ( viewParent ) {
  477. return new ViewPosition( viewParent, 0 );
  478. }
  479. } else {
  480. const domBefore = domParent.childNodes[ domOffset - 1 ];
  481. const viewBefore = isText( domBefore ) ?
  482. this.findCorrespondingViewText( domBefore ) :
  483. this.mapDomToView( domBefore );
  484. // TODO #663
  485. if ( viewBefore && viewBefore.parent ) {
  486. return new ViewPosition( viewBefore.parent, viewBefore.index + 1 );
  487. }
  488. }
  489. return null;
  490. }
  491. }
  492. /**
  493. * Returns corresponding view {@link module:engine/view/element~Element Element} or
  494. * {@link module:engine/view/documentfragment~DocumentFragment} for provided DOM element or
  495. * document fragment. If there is no view item {@link module:engine/view/domconverter~DomConverter#bindElements bound}
  496. * to the given DOM - `undefined` is returned.
  497. * For all DOM elements rendered by {@link module:engine/view/uielement~UIElement} that UIElement will be returned.
  498. *
  499. * @param {DocumentFragment|Element} domElementOrDocumentFragment DOM element or document fragment.
  500. * @returns {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|undefined}
  501. * Corresponding view element, document fragment or `undefined` if no element was bound.
  502. */
  503. mapDomToView( domElementOrDocumentFragment ) {
  504. return this.getParentUIElement( domElementOrDocumentFragment ) || this._domToViewMapping.get( domElementOrDocumentFragment );
  505. }
  506. /**
  507. * Finds corresponding text node. Text nodes are not {@link module:engine/view/domconverter~DomConverter#bindElements bound},
  508. * corresponding text node is returned based on the sibling or parent.
  509. *
  510. * If the directly previous sibling is a {@link module:engine/view/domconverter~DomConverter#bindElements bound} element, it is used
  511. * to find the corresponding text node.
  512. *
  513. * If this is a first child in the parent and the parent is a {@link module:engine/view/domconverter~DomConverter#bindElements bound}
  514. * element, it is used to find the corresponding text node.
  515. *
  516. * For all text nodes rendered by {@link module:engine/view/uielement~UIElement} that UIElement will be returned.
  517. *
  518. * Otherwise `null` is returned.
  519. *
  520. * Note that for the block or inline {@link module:engine/view/filler filler} this method returns `null`.
  521. *
  522. * @param {Text} domText DOM text node.
  523. * @returns {module:engine/view/text~Text|null} Corresponding view text node or `null`, if it was not possible to find a
  524. * corresponding node.
  525. */
  526. findCorrespondingViewText( domText ) {
  527. if ( isInlineFiller( domText ) ) {
  528. return null;
  529. }
  530. // If DOM text was rendered by UIElement - return that element.
  531. const uiElement = this.getParentUIElement( domText );
  532. if ( uiElement ) {
  533. return uiElement;
  534. }
  535. const previousSibling = domText.previousSibling;
  536. // Try to use previous sibling to find the corresponding text node.
  537. if ( previousSibling ) {
  538. if ( !( this.isElement( previousSibling ) ) ) {
  539. // The previous is text or comment.
  540. return null;
  541. }
  542. const viewElement = this.mapDomToView( previousSibling );
  543. if ( viewElement ) {
  544. const nextSibling = viewElement.nextSibling;
  545. // It might be filler which has no corresponding view node.
  546. if ( nextSibling instanceof ViewText ) {
  547. return viewElement.nextSibling;
  548. } else {
  549. return null;
  550. }
  551. }
  552. }
  553. // Try to use parent to find the corresponding text node.
  554. else {
  555. const viewElement = this.mapDomToView( domText.parentNode );
  556. if ( viewElement ) {
  557. const firstChild = viewElement.getChild( 0 );
  558. // It might be filler which has no corresponding view node.
  559. if ( firstChild instanceof ViewText ) {
  560. return firstChild;
  561. } else {
  562. return null;
  563. }
  564. }
  565. }
  566. return null;
  567. }
  568. /**
  569. * Returns corresponding DOM item for provided {@link module:engine/view/element~Element Element} or
  570. * {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment}.
  571. * To find a corresponding text for {@link module:engine/view/text~Text view Text instance}
  572. * use {@link #findCorrespondingDomText}.
  573. *
  574. * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment} viewNode
  575. * View element or document fragment.
  576. * @returns {Node|DocumentFragment|undefined} Corresponding DOM node or document fragment.
  577. */
  578. mapViewToDom( documentFragmentOrElement ) {
  579. return this._viewToDomMapping.get( documentFragmentOrElement );
  580. }
  581. /**
  582. * Finds corresponding text node. Text nodes are not {@link module:engine/view/domconverter~DomConverter#bindElements bound},
  583. * corresponding text node is returned based on the sibling or parent.
  584. *
  585. * If the directly previous sibling is a {@link module:engine/view/domconverter~DomConverter#bindElements bound} element, it is used
  586. * to find the corresponding text node.
  587. *
  588. * If this is a first child in the parent and the parent is a {@link module:engine/view/domconverter~DomConverter#bindElements bound}
  589. * element, it is used to find the corresponding text node.
  590. *
  591. * Otherwise `null` is returned.
  592. *
  593. * @param {module:engine/view/text~Text} viewText View text node.
  594. * @returns {Text|null} Corresponding DOM text node or `null`, if it was not possible to find a corresponding node.
  595. */
  596. findCorrespondingDomText( viewText ) {
  597. const previousSibling = viewText.previousSibling;
  598. // Try to use previous sibling to find the corresponding text node.
  599. if ( previousSibling && this.mapViewToDom( previousSibling ) ) {
  600. return this.mapViewToDom( previousSibling ).nextSibling;
  601. }
  602. // If this is a first node, try to use parent to find the corresponding text node.
  603. if ( !previousSibling && viewText.parent && this.mapViewToDom( viewText.parent ) ) {
  604. return this.mapViewToDom( viewText.parent ).childNodes[ 0 ];
  605. }
  606. return null;
  607. }
  608. /**
  609. * Focuses DOM editable that is corresponding to provided {@link module:engine/view/editableelement~EditableElement}.
  610. *
  611. * @param {module:engine/view/editableelement~EditableElement} viewEditable
  612. */
  613. focus( viewEditable ) {
  614. const domEditable = this.mapViewToDom( viewEditable );
  615. if ( domEditable && domEditable.ownerDocument.activeElement !== domEditable ) {
  616. // Save the scrollX and scrollY positions before the focus.
  617. const { scrollX, scrollY } = global.window;
  618. const scrollPositions = [];
  619. // Save all scrollLeft and scrollTop values starting from domEditable up to
  620. // document#documentElement.
  621. forEachDomNodeAncestor( domEditable, node => {
  622. const { scrollLeft, scrollTop } = node;
  623. scrollPositions.push( [ scrollLeft, scrollTop ] );
  624. } );
  625. domEditable.focus();
  626. // Restore scrollLeft and scrollTop values starting from domEditable up to
  627. // document#documentElement.
  628. // https://github.com/ckeditor/ckeditor5-engine/issues/951
  629. // https://github.com/ckeditor/ckeditor5-engine/issues/957
  630. forEachDomNodeAncestor( domEditable, node => {
  631. const [ scrollLeft, scrollTop ] = scrollPositions.shift();
  632. node.scrollLeft = scrollLeft;
  633. node.scrollTop = scrollTop;
  634. } );
  635. // Restore the scrollX and scrollY positions after the focus.
  636. // https://github.com/ckeditor/ckeditor5-engine/issues/951
  637. global.window.scrollTo( scrollX, scrollY );
  638. }
  639. }
  640. /**
  641. * Returns `true` when `node.nodeType` equals `Node.ELEMENT_NODE`.
  642. *
  643. * @param {Node} node Node to check.
  644. * @returns {Boolean}
  645. */
  646. isElement( node ) {
  647. return node && node.nodeType == Node.ELEMENT_NODE;
  648. }
  649. /**
  650. * Returns `true` when `node.nodeType` equals `Node.DOCUMENT_FRAGMENT_NODE`.
  651. *
  652. * @param {Node} node Node to check.
  653. * @returns {Boolean}
  654. */
  655. isDocumentFragment( node ) {
  656. return node && node.nodeType == Node.DOCUMENT_FRAGMENT_NODE;
  657. }
  658. /**
  659. * Returns `true` when `node.nodeType` equals `Node.COMMENT_NODE`.
  660. *
  661. * @param {Node} node Node to check.
  662. * @returns {Boolean}
  663. */
  664. isComment( node ) {
  665. return node && node.nodeType == Node.COMMENT_NODE;
  666. }
  667. /**
  668. * Returns `true` if given selection is a backward selection, that is, if it's `focus` is before `anchor`.
  669. *
  670. * @param {Selection} DOM Selection instance to check.
  671. * @returns {Boolean}
  672. */
  673. isDomSelectionBackward( selection ) {
  674. if ( selection.isCollapsed ) {
  675. return false;
  676. }
  677. // Since it takes multiple lines of code to check whether a "DOM Position" is before/after another "DOM Position",
  678. // we will use the fact that range will collapse if it's end is before it's start.
  679. const range = document.createRange();
  680. range.setStart( selection.anchorNode, selection.anchorOffset );
  681. range.setEnd( selection.focusNode, selection.focusOffset );
  682. const backward = range.collapsed;
  683. range.detach();
  684. return backward;
  685. }
  686. /**
  687. * Returns parent {@link module:engine/view/uielement~UIElement} for provided DOM node. Returns `null` if there is no
  688. * parent UIElement.
  689. *
  690. * @param {Node} domNode
  691. * @returns {module:engine/view/uielement~UIElement|null}
  692. */
  693. getParentUIElement( domNode ) {
  694. const ancestors = getAncestors( domNode );
  695. // Remove domNode from the list.
  696. ancestors.pop();
  697. while ( ancestors.length ) {
  698. const domNode = ancestors.pop();
  699. const viewNode = this._domToViewMapping.get( domNode );
  700. if ( viewNode && viewNode.is( 'uiElement' ) ) {
  701. return viewNode;
  702. }
  703. }
  704. return null;
  705. }
  706. /**
  707. * Checks if given selection's boundaries are at correct places.
  708. *
  709. * The following places are considered as incorrect for selection boundaries:
  710. * * before or in the middle of the inline filler sequence,
  711. * * inside the DOM element which represents {@link module:engine/view/uielement~UIElement a view ui element}.
  712. *
  713. * @param {Selection} domSelection DOM Selection object to be checked.
  714. * @returns {Boolean} `true` if the given selection is at a correct place, `false` otherwise.
  715. */
  716. isDomSelectionCorrect( domSelection ) {
  717. return this._isDomSelectionPositionCorrect( domSelection.anchorNode, domSelection.anchorOffset ) &&
  718. this._isDomSelectionPositionCorrect( domSelection.focusNode, domSelection.focusOffset );
  719. }
  720. /**
  721. * Checks if the given DOM position is a correct place for selection boundary. See {@link #isDomSelectionCorrect}.
  722. *
  723. * @private
  724. * @param {Element} domParent Position parent.
  725. * @param {Number} offset Position offset.
  726. * @returns {Boolean} `true` if given position is at a correct place for selection boundary, `false` otherwise.
  727. */
  728. _isDomSelectionPositionCorrect( domParent, offset ) {
  729. // If selection is before or in the middle of inline filler string, it is incorrect.
  730. if ( isText( domParent ) && startsWithFiller( domParent ) && offset < INLINE_FILLER_LENGTH ) {
  731. // Selection in a text node, at wrong position (before or in the middle of filler).
  732. return false;
  733. }
  734. if ( this.isElement( domParent ) && startsWithFiller( domParent.childNodes[ offset ] ) ) {
  735. // Selection in an element node, before filler text node.
  736. return false;
  737. }
  738. const viewParent = this.mapDomToView( domParent );
  739. // If selection is in `view.UIElement`, it is incorrect. Note that `mapDomToView()` returns `view.UIElement`
  740. // also for any dom element that is inside the view ui element (so we don't need to perform any additional checks).
  741. if ( viewParent && viewParent.is( 'uiElement' ) ) {
  742. return false;
  743. }
  744. return true;
  745. }
  746. /**
  747. * Takes text data from a given {@link module:engine/view/text~Text#data} and processes it so
  748. * it is correctly displayed in the DOM.
  749. *
  750. * Following changes are done:
  751. *
  752. * * a space at the beginning is changed to `&nbsp;` if this is the first text node in its container
  753. * element or if a previous text node ends with a space character,
  754. * * space at the end of the text node is changed to `&nbsp;` if this is the last text node in its container,
  755. * * remaining spaces are replaced to a chain of spaces and `&nbsp;` (e.g. `'x x'` becomes `'x &nbsp; x'`).
  756. *
  757. * Content of {@link #preElements} is not processed.
  758. *
  759. * @private
  760. * @param {module:engine/view/text~Text} node View text node to process.
  761. * @returns {String} Processed text data.
  762. */
  763. _processDataFromViewText( node ) {
  764. let data = node.data;
  765. // If any of node ancestors has a name which is in `preElements` array, then currently processed
  766. // view text node is (will be) in preformatted element. We should not change whitespaces then.
  767. if ( node.getAncestors().some( parent => this.preElements.includes( parent.name ) ) ) {
  768. return data;
  769. }
  770. // 1. Replace the first space with a nbsp if the previous node ends with a space or there is no previous node
  771. // (container element boundary).
  772. if ( data.charAt( 0 ) == ' ' ) {
  773. const prevNode = this._getTouchingViewTextNode( node, false );
  774. const prevEndsWithSpace = prevNode && this._nodeEndsWithSpace( prevNode );
  775. if ( prevEndsWithSpace || !prevNode ) {
  776. data = '\u00A0' + data.substr( 1 );
  777. }
  778. }
  779. // 2. Replace the last space with a nbsp if this is the last text node (container element boundary).
  780. if ( data.charAt( data.length - 1 ) == ' ' ) {
  781. const nextNode = this._getTouchingViewTextNode( node, true );
  782. if ( !nextNode ) {
  783. data = data.substr( 0, data.length - 1 ) + '\u00A0';
  784. }
  785. }
  786. return data.replace( / {2}/g, ' \u00A0' );
  787. }
  788. /**
  789. * Checks whether given node ends with a space character after changing appropriate space characters to `&nbsp;`s.
  790. *
  791. * @private
  792. * @param {module:engine/view/text~Text} node Node to check.
  793. * @returns {Boolean} `true` if given `node` ends with space, `false` otherwise.
  794. */
  795. _nodeEndsWithSpace( node ) {
  796. if ( node.getAncestors().some( parent => this.preElements.includes( parent.name ) ) ) {
  797. return false;
  798. }
  799. const data = this._processDataFromViewText( node );
  800. return data.charAt( data.length - 1 ) == ' ';
  801. }
  802. /**
  803. * Takes text data from native `Text` node and processes it to a correct {@link module:engine/view/text~Text view text node} data.
  804. *
  805. * Following changes are done:
  806. *
  807. * * multiple whitespaces are replaced to a single space,
  808. * * space at the beginning of a text node is removed if it is the first text node in its container
  809. * element or if the previous text node ends with a space character,
  810. * * space at the end of the text node is removed, if it is the last text node in its container.
  811. *
  812. * @param {Node} node DOM text node to process.
  813. * @returns {String} Processed data.
  814. * @private
  815. */
  816. _processDataFromDomText( node ) {
  817. let data = node.data;
  818. if ( _hasDomParentOfType( node, this.preElements ) ) {
  819. return getDataWithoutFiller( node );
  820. }
  821. // Change all consecutive whitespace characters (from the [ \n\t\r] set –
  822. // see https://github.com/ckeditor/ckeditor5-engine/issues/822#issuecomment-311670249) to a single space character.
  823. // That's how multiple whitespaces are treated when rendered, so we normalize those whitespaces.
  824. // We're replacing 1+ (and not 2+) to also normalize singular \n\t\r characters (#822).
  825. data = data.replace( /[ \n\t\r]{1,}/g, ' ' );
  826. const prevNode = this._getTouchingInlineDomNode( node, false );
  827. const nextNode = this._getTouchingInlineDomNode( node, true );
  828. const shouldLeftTrim = this._checkShouldLeftTrimDomText( prevNode );
  829. const shouldRightTrim = this._checkShouldRightTrimDomText( node, nextNode );
  830. // If the previous dom text node does not exist or it ends by whitespace character, remove space character from the beginning
  831. // of this text node. Such space character is treated as a whitespace.
  832. if ( shouldLeftTrim ) {
  833. data = data.replace( /^ /, '' );
  834. }
  835. // If the next text node does not exist remove space character from the end of this text node.
  836. if ( shouldRightTrim ) {
  837. data = data.replace( / $/, '' );
  838. }
  839. // At the beginning and end of a block element, Firefox inserts normal space + <br> instead of non-breaking space.
  840. // This means that the text node starts/end with normal space instead of non-breaking space.
  841. // This causes a problem because the normal space would be removed in `.replace` calls above. To prevent that,
  842. // the inline filler is removed only after the data is initially processed (by the `.replace` above). See ckeditor5#692.
  843. data = getDataWithoutFiller( new Text( data ) );
  844. // At this point we should have removed all whitespaces from DOM text data.
  845. // Now we have to change &nbsp; chars, that were in DOM text data because of rendering reasons, to spaces.
  846. // First, change all ` \u00A0` pairs (space + &nbsp;) to two spaces. DOM converter changes two spaces from model/view as
  847. // ` \u00A0` to ensure proper rendering. Since here we convert back, we recognize those pairs and change them
  848. // to ` ` which is what we expect to have in model/view.
  849. data = data.replace( / \u00A0/g, ' ' );
  850. // Then, change &nbsp; character that is at the beginning of the text node to space character.
  851. // As above, that &nbsp; was created for rendering reasons but it's real meaning is just a space character.
  852. // We do that replacement only if this is the first node or the previous node ends on whitespace character.
  853. if ( shouldLeftTrim ) {
  854. data = data.replace( /^\u00A0/, ' ' );
  855. }
  856. // Since input text data could be: `x_ _`, we would not replace the first &nbsp; after `x` character.
  857. // We have to fix it. Since we already change all ` &nbsp;`, we will have something like this at the end of text data:
  858. // `x_ _ _` -> `x_ `. Find &nbsp; at the end of string (can be followed only by spaces).
  859. // We do that replacement only if this is the last node or the next node starts with &nbsp; or is a <br>.
  860. if ( isText( nextNode ) ? nextNode.data.charAt( 0 ) == '\u00A0' : true ) {
  861. data = data.replace( /\u00A0( *)$/, ' $1' );
  862. }
  863. // At this point, all whitespaces should be removed and all &nbsp; created for rendering reasons should be
  864. // changed to normal space. All left &nbsp; are &nbsp; inserted intentionally.
  865. return data;
  866. }
  867. /**
  868. * Helper function which checks if a DOM text node, preceded by the given `prevNode` should
  869. * be trimmed from the left side.
  870. *
  871. * @param {Node} prevNode
  872. */
  873. _checkShouldLeftTrimDomText( prevNode ) {
  874. if ( !prevNode ) {
  875. return true;
  876. }
  877. if ( isElement( prevNode ) ) {
  878. return true;
  879. }
  880. return /[^\S\u00A0]/.test( prevNode.data.charAt( prevNode.data.length - 1 ) );
  881. }
  882. /**
  883. * Helper function which checks if a DOM text node, succeeded by the given `nextNode` should
  884. * be trimmed from the right side.
  885. *
  886. * @param {Node} node
  887. * @param {Node} prevNode
  888. */
  889. _checkShouldRightTrimDomText( node, nextNode ) {
  890. if ( nextNode ) {
  891. return false;
  892. }
  893. return !startsWithFiller( node );
  894. }
  895. /**
  896. * Helper function. For given {@link module:engine/view/text~Text view text node}, it finds previous or next sibling
  897. * that is contained in the same container element. If there is no such sibling, `null` is returned.
  898. *
  899. * @param {module:engine/view/text~Text} node Reference node.
  900. * @param {Boolean} getNext
  901. * @returns {module:engine/view/text~Text|null} Touching text node or `null` if there is no next or previous touching text node.
  902. */
  903. _getTouchingViewTextNode( node, getNext ) {
  904. const treeWalker = new ViewTreeWalker( {
  905. startPosition: getNext ? ViewPosition._createAfter( node ) : ViewPosition._createBefore( node ),
  906. direction: getNext ? 'forward' : 'backward'
  907. } );
  908. for ( const value of treeWalker ) {
  909. // ViewContainerElement is found on a way to next ViewText node, so given `node` was first/last
  910. // text node in its container element.
  911. if ( value.item.is( 'containerElement' ) ) {
  912. return null;
  913. }
  914. // <br> found – it works like a block boundary, so do not scan further.
  915. else if ( value.item.is( 'br' ) ) {
  916. return null;
  917. }
  918. // Found a text node in the same container element.
  919. else if ( value.item.is( 'textProxy' ) ) {
  920. return value.item;
  921. }
  922. }
  923. return null;
  924. }
  925. /**
  926. * Helper function. For the given text node, it finds the closest touching node which is either
  927. * a text node or a `<br>`. The search is terminated at block element boundaries and if a matching node
  928. * wasn't found so far, `null` is returned.
  929. *
  930. * In the following DOM structure:
  931. *
  932. * <p>foo<b>bar</b><br>bom</p>
  933. *
  934. * * `foo` doesn't have its previous touching inline node (`null` is returned),
  935. * * `foo`'s next touching inline node is `bar`
  936. * * `bar`'s next touching inline node is `<br>`
  937. *
  938. * This method returns text nodes and `<br>` elements because these types of nodes affect how
  939. * spaces in the given text node need to be converted.
  940. *
  941. * @private
  942. * @param {Text} node
  943. * @param {Boolean} getNext
  944. * @returns {Text|Element|null}
  945. */
  946. _getTouchingInlineDomNode( node, getNext ) {
  947. if ( !node.parentNode ) {
  948. return null;
  949. }
  950. const direction = getNext ? 'nextNode' : 'previousNode';
  951. const document = node.ownerDocument;
  952. const topmostParent = getAncestors( node )[ 0 ];
  953. const treeWalker = document.createTreeWalker( topmostParent, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
  954. acceptNode( node ) {
  955. if ( isText( node ) ) {
  956. return NodeFilter.FILTER_ACCEPT;
  957. }
  958. if ( node.tagName == 'BR' ) {
  959. return NodeFilter.FILTER_ACCEPT;
  960. }
  961. return NodeFilter.FILTER_SKIP;
  962. }
  963. } );
  964. treeWalker.currentNode = node;
  965. const touchingNode = treeWalker[ direction ]();
  966. if ( touchingNode !== null ) {
  967. const lca = getCommonAncestor( node, touchingNode );
  968. // If there is common ancestor between the text node and next/prev text node,
  969. // and there are no block elements on a way from the text node to that ancestor,
  970. // and there are no block elements on a way from next/prev text node to that ancestor...
  971. if (
  972. lca &&
  973. !_hasDomParentOfType( node, this.blockElements, lca ) &&
  974. !_hasDomParentOfType( touchingNode, this.blockElements, lca )
  975. ) {
  976. // Then they are in the same container element.
  977. return touchingNode;
  978. }
  979. }
  980. return null;
  981. }
  982. }
  983. // Helper function.
  984. // Used to check if given native `Element` or `Text` node has parent with tag name from `types` array.
  985. //
  986. // @param {Node} node
  987. // @param {Array.<String>} types
  988. // @param {Boolean} [boundaryParent] Can be given if parents should be checked up to a given element (excluding that element).
  989. // @returns {Boolean} `true` if such parent exists or `false` if it does not.
  990. function _hasDomParentOfType( node, types, boundaryParent ) {
  991. let parents = getAncestors( node );
  992. if ( boundaryParent ) {
  993. parents = parents.slice( parents.indexOf( boundaryParent ) + 1 );
  994. }
  995. return parents.some( parent => parent.tagName && types.includes( parent.tagName.toLowerCase() ) );
  996. }
  997. // A helper that executes given callback for each DOM node's ancestor, starting from the given node
  998. // and ending in document#documentElement.
  999. //
  1000. // @param {Node} node
  1001. // @param {Function} callback A callback to be executed for each ancestor.
  1002. function forEachDomNodeAncestor( node, callback ) {
  1003. while ( node && node != global.document ) {
  1004. callback( node );
  1005. node = node.parentNode;
  1006. }
  1007. }