mapper.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. }
  58. /**
  59. * Marks model and view elements as corresponding. Corresponding elements can be retrieved by using
  60. * the {@link module:engine/conversion/mapper~Mapper#toModelElement toModelElement} and
  61. * {@link module:engine/conversion/mapper~Mapper#toViewElement toViewElement} methods.
  62. * The information that elements are bound is also used to translate positions.
  63. *
  64. * @param {module:engine/model/element~Element} modelElement Model element.
  65. * @param {module:engine/view/element~Element} viewElement View element.
  66. */
  67. bindElements( modelElement, viewElement ) {
  68. this._modelToViewMapping.set( modelElement, viewElement );
  69. this._viewToModelMapping.set( viewElement, modelElement );
  70. }
  71. /**
  72. * Unbinds given {@link module:engine/view/element~Element view element} from the map.
  73. *
  74. * @param {module:engine/view/element~Element} viewElement View element to unbind.
  75. */
  76. unbindViewElement( viewElement ) {
  77. const modelElement = this.toModelElement( viewElement );
  78. this._unbindElements( modelElement, viewElement );
  79. }
  80. /**
  81. * Unbinds given {@link module:engine/model/element~Element model element} from the map.
  82. *
  83. * @param {module:engine/model/element~Element} modelElement Model element to unbind.
  84. */
  85. unbindModelElement( modelElement ) {
  86. const viewElement = this.toViewElement( modelElement );
  87. this._unbindElements( modelElement, viewElement );
  88. }
  89. /**
  90. * Removes all model to view and view to model bindings.
  91. */
  92. clearBindings() {
  93. this._modelToViewMapping = new WeakMap();
  94. this._viewToModelMapping = new WeakMap();
  95. }
  96. /**
  97. * Gets the corresponding model element.
  98. *
  99. * @param {module:engine/view/element~Element} viewElement View element.
  100. * @returns {module:engine/model/element~Element|undefined} Corresponding model element or `undefined` if not found.
  101. */
  102. toModelElement( viewElement ) {
  103. return this._viewToModelMapping.get( viewElement );
  104. }
  105. /**
  106. * Gets the corresponding view element.
  107. *
  108. * @param {module:engine/model/element~Element} modelElement Model element.
  109. * @returns {module:engine/view/element~Element|undefined} Corresponding view element or `undefined` if not found.
  110. */
  111. toViewElement( modelElement ) {
  112. return this._modelToViewMapping.get( modelElement );
  113. }
  114. /**
  115. * Gets the corresponding model range.
  116. *
  117. * @param {module:engine/view/range~Range} viewRange View range.
  118. * @returns {module:engine/model/range~Range} Corresponding model range.
  119. */
  120. toModelRange( viewRange ) {
  121. return new ModelRange( this.toModelPosition( viewRange.start ), this.toModelPosition( viewRange.end ) );
  122. }
  123. /**
  124. * Gets the corresponding view range.
  125. *
  126. * @param {module:engine/model/range~Range} modelRange Model range.
  127. * @returns {module:engine/view/range~Range} Corresponding view range.
  128. */
  129. toViewRange( modelRange ) {
  130. return new ViewRange( this.toViewPosition( modelRange.start ), this.toViewPosition( modelRange.end ) );
  131. }
  132. /**
  133. * Gets the corresponding model position.
  134. *
  135. * @fires viewToModelPosition
  136. * @param {module:engine/view/position~Position} viewPosition View position.
  137. * @returns {module:engine/model/position~Position} Corresponding model position.
  138. */
  139. toModelPosition( viewPosition ) {
  140. const data = {
  141. viewPosition: viewPosition,
  142. modelPosition: this._defaultToModelPosition( viewPosition ),
  143. mapper: this
  144. };
  145. this.fire( 'viewToModelPosition', data );
  146. return data.modelPosition;
  147. }
  148. /**
  149. * Maps model position to view position using default mapper algorithm.
  150. *
  151. * @private
  152. * @param {module:engine/model/position~Position} modelPosition
  153. * @returns {module:engine/view/position~Position} View position mapped from model position.
  154. */
  155. _defaultToViewPosition( modelPosition ) {
  156. let viewContainer = this._modelToViewMapping.get( modelPosition.parent );
  157. return this._findPositionIn( viewContainer, modelPosition.offset );
  158. }
  159. /**
  160. * Gets the corresponding view position.
  161. *
  162. * @fires modelToViewPosition
  163. * @param {module:engine/model/position~Position} modelPosition Model position.
  164. * @returns {module:engine/view/position~Position} Corresponding view position.
  165. */
  166. toViewPosition( modelPosition ) {
  167. const data = {
  168. viewPosition: this._defaultToViewPosition( modelPosition ),
  169. modelPosition: modelPosition,
  170. mapper: this
  171. };
  172. this.fire( 'modelToViewPosition', data );
  173. return data.viewPosition;
  174. }
  175. /**
  176. * Maps view position to model position using default mapper algorithm.
  177. *
  178. * @private
  179. * @param {module:engine/view/position~Position} viewPosition
  180. * @returns {module:engine/model/position~Position} Model position mapped from view position.
  181. */
  182. _defaultToModelPosition( viewPosition ) {
  183. let viewBlock = viewPosition.parent;
  184. let modelParent = this._viewToModelMapping.get( viewBlock );
  185. while ( !modelParent ) {
  186. viewBlock = viewBlock.parent;
  187. modelParent = this._viewToModelMapping.get( viewBlock );
  188. }
  189. let modelOffset = this._toModelOffset( viewPosition.parent, viewPosition.offset, viewBlock );
  190. return ModelPosition.createFromParentAndOffset( modelParent, modelOffset );
  191. }
  192. /**
  193. * Registers a callback that evaluates the length in the model of a view element with given name.
  194. *
  195. * The callback is fired with one argument, which is a view element instance. The callback is expected to return
  196. * a number representing the length of view element in model.
  197. *
  198. * // List item in view may contain nested list, which have other list items. In model though,
  199. * // the lists are represented by flat structure. Because of those differences, length of list view element
  200. * // may be greater than one. In the callback it's checked how many nested list items are in evaluated list item.
  201. *
  202. * function getViewListItemLength( element ) {
  203. * let length = 1;
  204. *
  205. * for ( let child of element.getChildren() ) {
  206. * if ( child.name == 'ul' || child.name == 'ol' ) {
  207. * for ( let item of child.getChildren() ) {
  208. * length += getViewListItemLength( item );
  209. * }
  210. * }
  211. * }
  212. *
  213. * return length;
  214. * }
  215. *
  216. * mapper.registerViewToModelLength( 'li', getViewListItemLength );
  217. *
  218. * @param {String} viewElementName Name of view element for which callback is registered.
  219. * @param {Function} lengthCallback Function return a length of view element instance in model.
  220. */
  221. registerViewToModelLength( viewElementName, lengthCallback ) {
  222. this._viewToModelLengthCallbacks.set( viewElementName, lengthCallback );
  223. }
  224. /**
  225. * Calculates model offset based on the view position and the block element.
  226. *
  227. * Example:
  228. *
  229. * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, p ) -> 5
  230. *
  231. * Is a sum of:
  232. *
  233. * <p>foo|<b>bar</b></p> // _toModelOffset( p, 3, p ) -> 3
  234. * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, b ) -> 2
  235. *
  236. * @private
  237. * @param {module:engine/view/element~Element} viewParent Position parent.
  238. * @param {Number} viewOffset Position offset.
  239. * @param {module:engine/view/element~Element} viewBlock Block used as a base to calculate offset.
  240. * @returns {Number} Offset in the model.
  241. */
  242. _toModelOffset( viewParent, viewOffset, viewBlock ) {
  243. if ( viewBlock != viewParent ) {
  244. // See example.
  245. const offsetToParentStart = this._toModelOffset( viewParent.parent, viewParent.index, viewBlock );
  246. const offsetInParent = this._toModelOffset( viewParent, viewOffset, viewParent );
  247. return offsetToParentStart + offsetInParent;
  248. }
  249. // viewBlock == viewParent, so we need to calculate the offset in the parent element.
  250. // If the position is a text it is simple ("ba|r" -> 2).
  251. if ( viewParent instanceof ViewText ) {
  252. return viewOffset;
  253. }
  254. // If the position is in an element we need to sum lengths of siblings ( <b> bar </b> foo | -> 3 + 3 = 6 ).
  255. let modelOffset = 0;
  256. for ( let i = 0; i < viewOffset; i++ ) {
  257. modelOffset += this.getModelLength( viewParent.getChild( i ) );
  258. }
  259. return modelOffset;
  260. }
  261. /**
  262. * Removes binding between given elements.
  263. *
  264. * @private
  265. * @param {module:engine/model/element~Element} modelElement Model element to unbind.
  266. * @param {module:engine/view/element~Element} viewElement View element to unbind.
  267. */
  268. _unbindElements( modelElement, viewElement ) {
  269. this._viewToModelMapping.delete( viewElement );
  270. this._modelToViewMapping.delete( modelElement );
  271. }
  272. /**
  273. * Gets the length of the view element in the model.
  274. *
  275. * The length is calculated as follows:
  276. * * length of a {@link module:engine/view/text~Text text node}
  277. * is equal to the length of it's {@link module:engine/view/text~Text#data data},
  278. * * length of a mapped {@link module:engine/view/element~Element element} is equal to 1 or to the value evaluated by the callback
  279. * added through {@link module:engine/conversion/mapper~Mapper#registerViewToModelLength},
  280. * * length of a not-mapped {@link module:engine/view/element~Element element} is equal to the length of it's children.
  281. *
  282. * Examples:
  283. *
  284. * foo -> 3 // Text length is equal to it's data length.
  285. * <p>foo</p> -> 1 // Length of an element which is mapped is by default equal to 1.
  286. * <b>foo</b> -> 3 // Length of an element which is not mapped is a length of its children.
  287. * <div><p>x</p><p>y</p> -> 2 // Assuming that <div> is not mapped and <p> are mapped.
  288. *
  289. * @param {module:engine/view/element~Element} viewNode View node.
  290. * @returns {Number} Length of the node in the tree model.
  291. */
  292. getModelLength( viewNode ) {
  293. if ( this._viewToModelMapping.has( viewNode ) ) {
  294. const callback = this._viewToModelLengthCallbacks.get( viewNode.name );
  295. return callback ? callback( viewNode ) : 1;
  296. } else if ( viewNode instanceof ViewText ) {
  297. return viewNode.data.length;
  298. } else {
  299. let len = 0;
  300. for ( let child of viewNode.getChildren() ) {
  301. len += this.getModelLength( child );
  302. }
  303. return len;
  304. }
  305. }
  306. /**
  307. * Finds the position in the view node (or its children) with the expected model offset.
  308. *
  309. * Example:
  310. *
  311. * <p>fo<b>bar</b>bom</p> -> expected offset: 4
  312. *
  313. * _findPositionIn( p, 4 ):
  314. * <p>|fo<b>bar</b>bom</p> -> expected offset: 4, actual offset: 0
  315. * <p>fo|<b>bar</b>bom</p> -> expected offset: 4, actual offset: 2
  316. * <p>fo<b>bar</b>|bom</p> -> expected offset: 4, actual offset: 5 -> we are too far
  317. *
  318. * _findPositionIn( b, 4 - ( 5 - 3 ) ):
  319. * <p>fo<b>|bar</b>bom</p> -> expected offset: 2, actual offset: 0
  320. * <p>fo<b>bar|</b>bom</p> -> expected offset: 2, actual offset: 3 -> we are too far
  321. *
  322. * _findPositionIn( bar, 2 - ( 3 - 3 ) ):
  323. * We are in the text node so we can simple find the offset.
  324. * <p>fo<b>ba|r</b>bom</p> -> expected offset: 2, actual offset: 2 -> position found
  325. *
  326. * @private
  327. * @param {module:engine/view/element~Element} viewParent Tree view element in which we are looking for the position.
  328. * @param {Number} expectedOffset Expected offset.
  329. * @returns {module:engine/view/position~Position} Found position.
  330. */
  331. _findPositionIn( viewParent, expectedOffset ) {
  332. // Last scanned view node.
  333. let viewNode;
  334. // Length of the last scanned view node.
  335. let lastLength = 0;
  336. let modelOffset = 0;
  337. let viewOffset = 0;
  338. // In the text node it is simple: offset in the model equals offset in the text.
  339. if ( viewParent instanceof ViewText ) {
  340. return new ViewPosition( viewParent, expectedOffset );
  341. }
  342. // In other cases we add lengths of child nodes to find the proper offset.
  343. // If it is smaller we add the length.
  344. while ( modelOffset < expectedOffset ) {
  345. viewNode = viewParent.getChild( viewOffset );
  346. lastLength = this.getModelLength( viewNode );
  347. modelOffset += lastLength;
  348. viewOffset++;
  349. }
  350. // If it equals we found the position.
  351. if ( modelOffset == expectedOffset ) {
  352. return this._moveViewPositionToTextNode( new ViewPosition( viewParent, viewOffset ) );
  353. }
  354. // If it is higher we need to enter last child.
  355. else {
  356. // ( modelOffset - lastLength ) is the offset to the child we enter,
  357. // so we subtract it from the expected offset to fine the offset in the child.
  358. return this._findPositionIn( viewNode, expectedOffset - ( modelOffset - lastLength ) );
  359. }
  360. }
  361. /**
  362. * Because we prefer positions in text nodes over positions next to text node moves view position to the text node
  363. * if it was next to it.
  364. *
  365. * <p>[]<b>foo</b></p> -> <p>[]<b>foo</b></p> // do not touch if position is not directly next to text
  366. * <p>foo[]<b>foo</b></p> -> <p>foo{}<b>foo</b></p> // move to text node
  367. * <p><b>[]foo</b></p> -> <p><b>{}foo</b></p> // move to text node
  368. *
  369. * @private
  370. * @param {module:engine/view/position~Position} viewPosition Position potentially next to text node.
  371. * @returns {module:engine/view/position~Position} Position in text node if possible.
  372. */
  373. _moveViewPositionToTextNode( viewPosition ) {
  374. // If the position is just after text node, put it at the end of that text node.
  375. // If the position is just before text node, put it at the beginning of that text node.
  376. const nodeBefore = viewPosition.nodeBefore;
  377. const nodeAfter = viewPosition.nodeAfter;
  378. if ( nodeBefore instanceof ViewText ) {
  379. return new ViewPosition( nodeBefore, nodeBefore.data.length );
  380. } else if ( nodeAfter instanceof ViewText ) {
  381. return new ViewPosition( nodeAfter, 0 );
  382. }
  383. // Otherwise, just return the given position.
  384. return viewPosition;
  385. }
  386. }
  387. mix( Mapper, EmitterMixin );
  388. /**
  389. * Fired for each model-to-view position mapping request. The purpose of this event is to enable custom model-to-view position
  390. * mapping. Callbacks added to this event take {@link module:engine/model/position~Position model position} and are expected to calculate
  391. * {@link module:engine/view/position~Position view position}. Calculated view position should be added as `viewPosition` value in
  392. * `data` object that is passed as one of parameters to the event callback.
  393. *
  394. * // Assume that "captionedImage" model element is converted to <img> and following <span> elements in view,
  395. * // and the model element is bound to <img> element. Force mapping model positions inside "captionedImage" to that <span> element.
  396. * mapper.on( 'modelToViewPosition', ( evt, data ) => {
  397. * const positionParent = modelPosition.parent;
  398. *
  399. * if ( positionParent.name == 'captionedImage' ) {
  400. * const viewImg = mapper.toViewElement( positionParent );
  401. * const viewCaption = viewImg.nextSibling; // The <span> element.
  402. *
  403. * data.viewPosition = new ViewPosition( viewCaption, modelPosition.offset );
  404. * evt.stop();
  405. * }
  406. * } );
  407. *
  408. * **Note:** these callbacks are called **very often**. For efficiency reasons, it is advised to use them only when position
  409. * mapping between given model and view elements is unsolvable using just elements mapping and default algorithm. Also,
  410. * the condition that checks if special case scenario happened should be as simple as possible.
  411. *
  412. * @event modelToViewPosition
  413. * @param {Object} data Data pipeline object that can store and pass data between callbacks. The callback should add
  414. * `viewPosition` value to that object with calculated {@link module:engine/view/position~Position view position}.
  415. * @param {module:engine/model/position~Position} data.modelPosition Model position to be mapped.
  416. * @param {module:engine/view/position~Position} data.viewPosition View position that is a result of mapping
  417. * `modelPosition` using `Mapper` default algorithm.
  418. * @param {module:engine/conversion/mapper~Mapper} data.mapper Mapper instance that fired the event.
  419. */
  420. /**
  421. * Fired for each view-to-model position mapping request. See {@link module:engine/conversion/mapper~Mapper#event:modelToViewPosition}.
  422. *
  423. * // See example in `modelToViewPosition` event description.
  424. * // This custom mapping will map positions from <span> element next to <img> to the "captionedImage" element.
  425. * mapper.on( 'viewToModelPosition', ( evt, data ) => {
  426. * const positionParent = viewPosition.parent;
  427. *
  428. * if ( positionParent.hasClass( 'image-caption' ) ) {
  429. * const viewImg = positionParent.previousSibling;
  430. * const modelImg = mapper.toModelElement( viewImg );
  431. *
  432. * data.modelPosition = new ModelPosition( modelImg, viewPosition.offset );
  433. * evt.stop();
  434. * }
  435. * } );
  436. *
  437. * @event viewToModelPosition
  438. * @param {Object} data Data pipeline object that can store and pass data between callbacks. The callback should add
  439. * `modelPosition` value to that object with calculated {@link module:engine/model/position~Position model position}.
  440. * @param {module:engine/view/position~Position} data.viewPosition View position to be mapped.
  441. * @param {module:engine/model/position~Position} data.modelPosition Model position that is a result of mapping
  442. * `viewPosition` using `Mapper` default algorithm.
  443. * @param {module:engine/conversion/mapper~Mapper} data.mapper Mapper instance that fired the event.
  444. */