mapper.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/conversion/mapper
  7. */
  8. import ModelPosition from '../model/position';
  9. import ModelRange from '../model/range';
  10. import ViewPosition from '../view/position';
  11. import ViewRange from '../view/range';
  12. import ViewText from '../view/text';
  13. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  14. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  15. /**
  16. * Maps elements and positions between {@link module:engine/view/document~Document view} and {@link module:engine/model/model model}.
  17. *
  18. * Mapper use bound elements to find corresponding elements and positions, so, to get proper results,
  19. * all model elements should be {@link module:engine/conversion/mapper~Mapper#bindElements bound}.
  20. *
  21. * To map complex model to/from view relations, you may provide custom callbacks for
  22. * {@link module:engine/conversion/mapper~Mapper#event:modelToViewPosition modelToViewPosition event} and
  23. * {@link module:engine/conversion/mapper~Mapper#event:viewToModelPosition viewToModelPosition event} that are fired whenever
  24. * a position mapping request occurs.
  25. * Those events are fired by {@link module:engine/conversion/mapper~Mapper#toViewPosition toViewPosition}
  26. * and {@link module:engine/conversion/mapper~Mapper#toModelPosition toModelPosition} methods. `Mapper` adds it's own default callbacks
  27. * with `'lowest'` priority. To override default `Mapper` mapping, add custom callback with higher priority and
  28. * stop the event.
  29. */
  30. export default class Mapper {
  31. /**
  32. * Creates an instance of the mapper.
  33. */
  34. constructor() {
  35. /**
  36. * Model element to view element mapping.
  37. *
  38. * @private
  39. * @member {WeakMap}
  40. */
  41. this._modelToViewMapping = new WeakMap();
  42. /**
  43. * View element to model element mapping.
  44. *
  45. * @private
  46. * @member {WeakMap}
  47. */
  48. this._viewToModelMapping = new WeakMap();
  49. /**
  50. * A map containing callbacks between view element names and functions evaluating length of view elements
  51. * in model.
  52. *
  53. * @private
  54. * @member {Map}
  55. */
  56. this._viewToModelLengthCallbacks = new Map();
  57. // Default mapper algorithm for mapping model position to view position.
  58. this.on( 'modelToViewPosition', ( evt, data ) => {
  59. if ( data.viewPosition ) {
  60. return;
  61. }
  62. const viewContainer = this._modelToViewMapping.get( data.modelPosition.parent );
  63. data.viewPosition = this._findPositionIn( viewContainer, data.modelPosition.offset );
  64. }, { priority: 'low' } );
  65. // Default mapper algorithm for mapping view position to model position.
  66. this.on( 'viewToModelPosition', ( evt, data ) => {
  67. if ( data.modelPosition ) {
  68. return;
  69. }
  70. let viewBlock = data.viewPosition.parent;
  71. let modelParent = this._viewToModelMapping.get( viewBlock );
  72. while ( !modelParent ) {
  73. viewBlock = viewBlock.parent;
  74. modelParent = this._viewToModelMapping.get( viewBlock );
  75. }
  76. const modelOffset = this._toModelOffset( data.viewPosition.parent, data.viewPosition.offset, viewBlock );
  77. data.modelPosition = ModelPosition.createFromParentAndOffset( modelParent, modelOffset );
  78. }, { priority: 'low' } );
  79. }
  80. /**
  81. * Marks model and view elements as corresponding. Corresponding elements can be retrieved by using
  82. * the {@link module:engine/conversion/mapper~Mapper#toModelElement toModelElement} and
  83. * {@link module:engine/conversion/mapper~Mapper#toViewElement toViewElement} methods.
  84. * The information that elements are bound is also used to translate positions.
  85. *
  86. * @param {module:engine/model/element~Element} modelElement Model element.
  87. * @param {module:engine/view/element~Element} viewElement View element.
  88. */
  89. bindElements( modelElement, viewElement ) {
  90. this._modelToViewMapping.set( modelElement, viewElement );
  91. this._viewToModelMapping.set( viewElement, modelElement );
  92. }
  93. /**
  94. * Unbinds given {@link module:engine/view/element~Element view element} from the map.
  95. *
  96. * **Note:** view-to-model binding will be removed, if it existed. However, corresponding model-to-view binding
  97. * will be removed only if model element is still bound to passed `viewElement`.
  98. *
  99. * This behavior lets for re-binding model element to another view element without fear of losing the new binding
  100. * when the previously bound view element is unbound.
  101. *
  102. * @param {module:engine/view/element~Element} viewElement View element to unbind.
  103. */
  104. unbindViewElement( viewElement ) {
  105. const modelElement = this.toModelElement( viewElement );
  106. this._viewToModelMapping.delete( viewElement );
  107. if ( this._modelToViewMapping.get( modelElement ) == viewElement ) {
  108. this._modelToViewMapping.delete( modelElement );
  109. }
  110. }
  111. /**
  112. * Unbinds given {@link module:engine/model/element~Element model element} from the map.
  113. *
  114. * **Note:** model-to-view binding will be removed, if it existed. However, corresponding view-to-model binding
  115. * will be removed only if view element is still bound to passed `modelElement`.
  116. *
  117. * This behavior lets for re-binding view element to another model element without fear of losing the new binding
  118. * when the previously bound model element is unbound.
  119. *
  120. * @param {module:engine/model/element~Element} modelElement Model element to unbind.
  121. */
  122. unbindModelElement( modelElement ) {
  123. const viewElement = this.toViewElement( modelElement );
  124. this._modelToViewMapping.delete( modelElement );
  125. if ( this._viewToModelMapping.get( viewElement ) == modelElement ) {
  126. this._viewToModelMapping.delete( viewElement );
  127. }
  128. }
  129. /**
  130. * Removes all model to view and view to model bindings.
  131. */
  132. clearBindings() {
  133. this._modelToViewMapping = new WeakMap();
  134. this._viewToModelMapping = new WeakMap();
  135. }
  136. /**
  137. * Gets the corresponding model element.
  138. *
  139. * **Note:** {@link module:engine/view/uielement~UIElement} does not have corresponding element in model.
  140. *
  141. * @param {module:engine/view/element~Element} viewElement View element.
  142. * @returns {module:engine/model/element~Element|undefined} Corresponding model element or `undefined` if not found.
  143. */
  144. toModelElement( viewElement ) {
  145. return this._viewToModelMapping.get( viewElement );
  146. }
  147. /**
  148. * Gets the corresponding view element.
  149. *
  150. * @param {module:engine/model/element~Element} modelElement Model element.
  151. * @returns {module:engine/view/element~Element|undefined} Corresponding view element or `undefined` if not found.
  152. */
  153. toViewElement( modelElement ) {
  154. return this._modelToViewMapping.get( modelElement );
  155. }
  156. /**
  157. * Gets the corresponding model range.
  158. *
  159. * @param {module:engine/view/range~Range} viewRange View range.
  160. * @returns {module:engine/model/range~Range} Corresponding model range.
  161. */
  162. toModelRange( viewRange ) {
  163. return new ModelRange( this.toModelPosition( viewRange.start ), this.toModelPosition( viewRange.end ) );
  164. }
  165. /**
  166. * Gets the corresponding view range.
  167. *
  168. * @param {module:engine/model/range~Range} modelRange Model range.
  169. * @returns {module:engine/view/range~Range} Corresponding view range.
  170. */
  171. toViewRange( modelRange ) {
  172. return new ViewRange( this.toViewPosition( modelRange.start ), this.toViewPosition( modelRange.end ) );
  173. }
  174. /**
  175. * Gets the corresponding model position.
  176. *
  177. * @fires viewToModelPosition
  178. * @param {module:engine/view/position~Position} viewPosition View position.
  179. * @returns {module:engine/model/position~Position} Corresponding model position.
  180. */
  181. toModelPosition( viewPosition ) {
  182. const data = {
  183. viewPosition,
  184. mapper: this
  185. };
  186. this.fire( 'viewToModelPosition', data );
  187. return data.modelPosition;
  188. }
  189. /**
  190. * Gets the corresponding view position.
  191. *
  192. * @fires modelToViewPosition
  193. * @param {module:engine/model/position~Position} modelPosition Model position.
  194. * @param {Object} [options] Additional options for position mapping process.
  195. * @param {Boolean} [options.isPhantom=false] Should be set to `true` if the model position to map is pointing to a place
  196. * in model tree which no longer exists. For example, it could be an end of a removed model range.
  197. * @returns {module:engine/view/position~Position} Corresponding view position.
  198. */
  199. toViewPosition( modelPosition, options = { isPhantom: false } ) {
  200. const data = {
  201. modelPosition,
  202. mapper: this,
  203. isPhantom: options.isPhantom
  204. };
  205. this.fire( 'modelToViewPosition', data );
  206. return data.viewPosition;
  207. }
  208. /**
  209. * Registers a callback that evaluates the length in the model of a view element with given name.
  210. *
  211. * The callback is fired with one argument, which is a view element instance. The callback is expected to return
  212. * a number representing the length of view element in model.
  213. *
  214. * // List item in view may contain nested list, which have other list items. In model though,
  215. * // the lists are represented by flat structure. Because of those differences, length of list view element
  216. * // may be greater than one. In the callback it's checked how many nested list items are in evaluated list item.
  217. *
  218. * function getViewListItemLength( element ) {
  219. * let length = 1;
  220. *
  221. * for ( let child of element.getChildren() ) {
  222. * if ( child.name == 'ul' || child.name == 'ol' ) {
  223. * for ( let item of child.getChildren() ) {
  224. * length += getViewListItemLength( item );
  225. * }
  226. * }
  227. * }
  228. *
  229. * return length;
  230. * }
  231. *
  232. * mapper.registerViewToModelLength( 'li', getViewListItemLength );
  233. *
  234. * @param {String} viewElementName Name of view element for which callback is registered.
  235. * @param {Function} lengthCallback Function return a length of view element instance in model.
  236. */
  237. registerViewToModelLength( viewElementName, lengthCallback ) {
  238. this._viewToModelLengthCallbacks.set( viewElementName, lengthCallback );
  239. }
  240. /**
  241. * Calculates model offset based on the view position and the block element.
  242. *
  243. * Example:
  244. *
  245. * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, p ) -> 5
  246. *
  247. * Is a sum of:
  248. *
  249. * <p>foo|<b>bar</b></p> // _toModelOffset( p, 3, p ) -> 3
  250. * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, b ) -> 2
  251. *
  252. * @private
  253. * @param {module:engine/view/element~Element} viewParent Position parent.
  254. * @param {Number} viewOffset Position offset.
  255. * @param {module:engine/view/element~Element} viewBlock Block used as a base to calculate offset.
  256. * @returns {Number} Offset in the model.
  257. */
  258. _toModelOffset( viewParent, viewOffset, viewBlock ) {
  259. if ( viewBlock != viewParent ) {
  260. // See example.
  261. const offsetToParentStart = this._toModelOffset( viewParent.parent, viewParent.index, viewBlock );
  262. const offsetInParent = this._toModelOffset( viewParent, viewOffset, viewParent );
  263. return offsetToParentStart + offsetInParent;
  264. }
  265. // viewBlock == viewParent, so we need to calculate the offset in the parent element.
  266. // If the position is a text it is simple ("ba|r" -> 2).
  267. if ( viewParent.is( 'text' ) ) {
  268. return viewOffset;
  269. }
  270. // If the position is in an element we need to sum lengths of siblings ( <b> bar </b> foo | -> 3 + 3 = 6 ).
  271. let modelOffset = 0;
  272. for ( let i = 0; i < viewOffset; i++ ) {
  273. modelOffset += this.getModelLength( viewParent.getChild( i ) );
  274. }
  275. return modelOffset;
  276. }
  277. /**
  278. * Gets the length of the view element in the model.
  279. *
  280. * The length is calculated as follows:
  281. * * if {@link #registerViewToModelLength length mapping callback} is provided for given `viewNode` it is used to
  282. * evaluate model length (`viewNode` is used as first and only parameter passed to the callback),
  283. * * length of a {@link module:engine/view/text~Text text node} is equal to the length of it's
  284. * {@link module:engine/view/text~Text#data data},
  285. * * length of a {@link module:engine/view/uielement~UIElement ui element} is equal to 0,
  286. * * length of a mapped {@link module:engine/view/element~Element element} is equal to 1,
  287. * * length of a not-mapped {@link module:engine/view/element~Element element} is equal to the length of it's children.
  288. *
  289. * Examples:
  290. *
  291. * foo -> 3 // Text length is equal to it's data length.
  292. * <p>foo</p> -> 1 // Length of an element which is mapped is by default equal to 1.
  293. * <b>foo</b> -> 3 // Length of an element which is not mapped is a length of its children.
  294. * <div><p>x</p><p>y</p></div> -> 2 // Assuming that <div> is not mapped and <p> are mapped.
  295. *
  296. * @param {module:engine/view/element~Element} viewNode View node.
  297. * @returns {Number} Length of the node in the tree model.
  298. */
  299. getModelLength( viewNode ) {
  300. if ( this._viewToModelLengthCallbacks.get( viewNode.name ) ) {
  301. const callback = this._viewToModelLengthCallbacks.get( viewNode.name );
  302. return callback( viewNode );
  303. } else if ( this._viewToModelMapping.has( viewNode ) ) {
  304. return 1;
  305. } else if ( viewNode.is( 'text' ) ) {
  306. return viewNode.data.length;
  307. } else if ( viewNode.is( 'uiElement' ) ) {
  308. return 0;
  309. } else {
  310. let len = 0;
  311. for ( const child of viewNode.getChildren() ) {
  312. len += this.getModelLength( child );
  313. }
  314. return len;
  315. }
  316. }
  317. /**
  318. * Finds the position in the view node (or its children) with the expected model offset.
  319. *
  320. * Example:
  321. *
  322. * <p>fo<b>bar</b>bom</p> -> expected offset: 4
  323. *
  324. * _findPositionIn( p, 4 ):
  325. * <p>|fo<b>bar</b>bom</p> -> expected offset: 4, actual offset: 0
  326. * <p>fo|<b>bar</b>bom</p> -> expected offset: 4, actual offset: 2
  327. * <p>fo<b>bar</b>|bom</p> -> expected offset: 4, actual offset: 5 -> we are too far
  328. *
  329. * _findPositionIn( b, 4 - ( 5 - 3 ) ):
  330. * <p>fo<b>|bar</b>bom</p> -> expected offset: 2, actual offset: 0
  331. * <p>fo<b>bar|</b>bom</p> -> expected offset: 2, actual offset: 3 -> we are too far
  332. *
  333. * _findPositionIn( bar, 2 - ( 3 - 3 ) ):
  334. * We are in the text node so we can simple find the offset.
  335. * <p>fo<b>ba|r</b>bom</p> -> expected offset: 2, actual offset: 2 -> position found
  336. *
  337. * @private
  338. * @param {module:engine/view/element~Element} viewParent Tree view element in which we are looking for the position.
  339. * @param {Number} expectedOffset Expected offset.
  340. * @returns {module:engine/view/position~Position} Found position.
  341. */
  342. _findPositionIn( viewParent, expectedOffset ) {
  343. // Last scanned view node.
  344. let viewNode;
  345. // Length of the last scanned view node.
  346. let lastLength = 0;
  347. let modelOffset = 0;
  348. let viewOffset = 0;
  349. // In the text node it is simple: offset in the model equals offset in the text.
  350. if ( viewParent.is( 'text' ) ) {
  351. return new ViewPosition( viewParent, expectedOffset );
  352. }
  353. // In other cases we add lengths of child nodes to find the proper offset.
  354. // If it is smaller we add the length.
  355. while ( modelOffset < expectedOffset ) {
  356. viewNode = viewParent.getChild( viewOffset );
  357. lastLength = this.getModelLength( viewNode );
  358. modelOffset += lastLength;
  359. viewOffset++;
  360. }
  361. // If it equals we found the position.
  362. if ( modelOffset == expectedOffset ) {
  363. return this._moveViewPositionToTextNode( new ViewPosition( viewParent, viewOffset ) );
  364. }
  365. // If it is higher we need to enter last child.
  366. else {
  367. // ( modelOffset - lastLength ) is the offset to the child we enter,
  368. // so we subtract it from the expected offset to fine the offset in the child.
  369. return this._findPositionIn( viewNode, expectedOffset - ( modelOffset - lastLength ) );
  370. }
  371. }
  372. /**
  373. * Because we prefer positions in text nodes over positions next to text node moves view position to the text node
  374. * if it was next to it.
  375. *
  376. * <p>[]<b>foo</b></p> -> <p>[]<b>foo</b></p> // do not touch if position is not directly next to text
  377. * <p>foo[]<b>foo</b></p> -> <p>foo{}<b>foo</b></p> // move to text node
  378. * <p><b>[]foo</b></p> -> <p><b>{}foo</b></p> // move to text node
  379. *
  380. * @private
  381. * @param {module:engine/view/position~Position} viewPosition Position potentially next to text node.
  382. * @returns {module:engine/view/position~Position} Position in text node if possible.
  383. */
  384. _moveViewPositionToTextNode( viewPosition ) {
  385. // If the position is just after text node, put it at the end of that text node.
  386. // If the position is just before text node, put it at the beginning of that text node.
  387. const nodeBefore = viewPosition.nodeBefore;
  388. const nodeAfter = viewPosition.nodeAfter;
  389. if ( nodeBefore instanceof ViewText ) {
  390. return new ViewPosition( nodeBefore, nodeBefore.data.length );
  391. } else if ( nodeAfter instanceof ViewText ) {
  392. return new ViewPosition( nodeAfter, 0 );
  393. }
  394. // Otherwise, just return the given position.
  395. return viewPosition;
  396. }
  397. /**
  398. * Fired for each model-to-view position mapping request. The purpose of this event is to enable custom model-to-view position
  399. * mapping. Callbacks added to this event take {@link module:engine/model/position~Position model position} and are expected to
  400. * calculate {@link module:engine/view/position~Position view position}. Calculated view position should be added as `viewPosition`
  401. * value in `data` object that is passed as one of parameters to the event callback.
  402. *
  403. * // Assume that "captionedImage" model element is converted to <img> and following <span> elements in view,
  404. * // and the model element is bound to <img> element. Force mapping model positions inside "captionedImage" to that
  405. * // <span> element.
  406. * mapper.on( 'modelToViewPosition', ( evt, data ) => {
  407. * const positionParent = modelPosition.parent;
  408. *
  409. * if ( positionParent.name == 'captionedImage' ) {
  410. * const viewImg = data.mapper.toViewElement( positionParent );
  411. * const viewCaption = viewImg.nextSibling; // The <span> element.
  412. *
  413. * data.viewPosition = new ViewPosition( viewCaption, modelPosition.offset );
  414. *
  415. * // Stop the event if other callbacks should not modify calculated value.
  416. * evt.stop();
  417. * }
  418. * } );
  419. *
  420. * **Note:** keep in mind that sometimes a "phantom" model position is being converted. "Phantom" model position is
  421. * a position that points to a non-existing place in model. Such position might still be valid for conversion, though
  422. * (it would point to a correct place in view when converted). One example of such situation is when a range is
  423. * removed from model, there may be a need to map the range's end (which is no longer valid model position). To
  424. * handle such situation, check `data.isPhantom` flag:
  425. *
  426. * // Assume that there is "customElement" model element and whenever position is before it, we want to move it
  427. * // to the inside of the view element bound to "customElement".
  428. * mapper.on( 'modelToViewPosition', ( evt, data ) => {
  429. * if ( data.isPhantom ) {
  430. * return;
  431. * }
  432. *
  433. * // Below line might crash for phantom position that does not exist in model.
  434. * const sibling = data.modelPosition.nodeBefore;
  435. *
  436. * // Check if this is the element we are interested in.
  437. * if ( !sibling.is( 'customElement' ) ) {
  438. * return;
  439. * }
  440. *
  441. * const viewElement = data.mapper.toViewElement( sibling );
  442. *
  443. * data.viewPosition = new ViewPosition( sibling, 0 );
  444. *
  445. * evt.stop();
  446. * } );
  447. *
  448. * **Note:** default mapping callback is provided with `low` priority setting and does not cancel the event, so it is possible to
  449. * attach a custom callback after default callback and also use `data.viewPosition` calculated by default callback
  450. * (for example to fix it).
  451. *
  452. * **Note:** default mapping callback will not fire if `data.viewPosition` is already set.
  453. *
  454. * **Note:** these callbacks are called **very often**. For efficiency reasons, it is advised to use them only when position
  455. * mapping between given model and view elements is unsolvable using just elements mapping and default algorithm. Also,
  456. * the condition that checks if special case scenario happened should be as simple as possible.
  457. *
  458. * @event modelToViewPosition
  459. * @param {Object} data Data pipeline object that can store and pass data between callbacks. The callback should add
  460. * `viewPosition` value to that object with calculated {@link module:engine/view/position~Position view position}.
  461. * @param {module:engine/conversion/mapper~Mapper} data.mapper Mapper instance that fired the event.
  462. */
  463. /**
  464. * Fired for each view-to-model position mapping request. See {@link module:engine/conversion/mapper~Mapper#event:modelToViewPosition}.
  465. *
  466. * // See example in `modelToViewPosition` event description.
  467. * // This custom mapping will map positions from <span> element next to <img> to the "captionedImage" element.
  468. * mapper.on( 'viewToModelPosition', ( evt, data ) => {
  469. * const positionParent = viewPosition.parent;
  470. *
  471. * if ( positionParent.hasClass( 'image-caption' ) ) {
  472. * const viewImg = positionParent.previousSibling;
  473. * const modelImg = data.mapper.toModelElement( viewImg );
  474. *
  475. * data.modelPosition = new ModelPosition( modelImg, viewPosition.offset );
  476. * evt.stop();
  477. * }
  478. * } );
  479. *
  480. * **Note:** default mapping callback is provided with `low` priority setting and does not cancel the event, so it is possible to
  481. * attach a custom callback after default callback and also use `data.modelPosition` calculated by default callback
  482. * (for example to fix it).
  483. *
  484. * **Note:** default mapping callback will not fire if `data.modelPosition` is already set.
  485. *
  486. * **Note:** these callbacks are called **very often**. For efficiency reasons, it is advised to use them only when position
  487. * mapping between given model and view elements is unsolvable using just elements mapping and default algorithm. Also,
  488. * the condition that checks if special case scenario happened should be as simple as possible.
  489. *
  490. * @event viewToModelPosition
  491. * @param {Object} data Data pipeline object that can store and pass data between callbacks. The callback should add
  492. * `modelPosition` value to that object with calculated {@link module:engine/model/position~Position model position}.
  493. * @param {module:engine/conversion/mapper~Mapper} data.mapper Mapper instance that fired the event.
  494. */
  495. }
  496. mix( Mapper, EmitterMixin );