8
0

domconverter.js 38 KB

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