domconverter.js 40 KB

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