domconverter.js 45 KB

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