domconverter.js 46 KB

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