domconverter.js 45 KB

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