domconverter.js 42 KB

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