domconverter.js 40 KB

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