8
0

domconverter.js 38 KB

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