8
0

domconverter.js 45 KB

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