mapper.js 19 KB

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