domconverter.js 37 KB

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