domconverter.js 40 KB

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