8
0

modelconsumable.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/conversion/modelconsumable
  7. */
  8. import TextProxy from '../model/textproxy';
  9. /**
  10. * Manages a list of consumable values for {@link module:engine/model/item~Item model items}.
  11. *
  12. * Consumables are various aspects of the model. A model item can be broken down into singular properties that might be
  13. * taken into consideration when converting that item.
  14. *
  15. * `ModelConsumable` is used by {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher} while analyzing changed
  16. * parts of {@link module:engine/model/document~Document the document}. The added / changed / removed model items are broken down
  17. * into singular properties (the item itself and it's attributes). All those parts are saved in `ModelConsumable`. Then,
  18. * during conversion, when given part of model item is converted (i.e. the view element has been inserted into the view,
  19. * but without attributes), consumable value is removed from `ModelConsumable`.
  20. *
  21. * For model items, `ModelConsumable` stores consumable values of one of following types: `insert`, `addattribute:<attributeKey>`,
  22. * `changeattributes:<attributeKey>`, `removeattributes:<attributeKey>`.
  23. *
  24. * In most cases, it is enough to let {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher}
  25. * gather consumable values, so there is no need to use
  26. * {@link module:engine/conversion/modelconsumable~ModelConsumable#add add method} directly.
  27. * However, it is important to understand how consumable values can be
  28. * {@link module:engine/conversion/modelconsumable~ModelConsumable#consume consumed}.
  29. * See {@link module:engine/conversion/downcast-selection-converters default downcast converters} for more information.
  30. *
  31. * Keep in mind, that one conversion event may have multiple callbacks (converters) attached to it. Each of those is
  32. * able to convert one or more parts of the model. However, when one of those callbacks actually converts
  33. * something, other should not, because they would duplicate the results. Using `ModelConsumable` helps avoiding
  34. * this situation, because callbacks should only convert those values, which were not yet consumed from `ModelConsumable`.
  35. *
  36. * Consuming multiple values in a single callback:
  37. *
  38. * // Converter for custom `image` element that might have a `caption` element inside which changes
  39. * // how the image is displayed in the view:
  40. * //
  41. * // Model:
  42. * //
  43. * // [image]
  44. * // └─ [caption]
  45. * // └─ foo
  46. * //
  47. * // View:
  48. * //
  49. * // <figure>
  50. * // ├─ <img />
  51. * // └─ <caption>
  52. * // └─ foo
  53. * modelConversionDispatcher.on( 'insert:image', ( evt, data, conversionApi ) => {
  54. * // First, consume the `image` element.
  55. * conversionApi.consumable.consume( data.item, 'insert' );
  56. *
  57. * // Just create normal image element for the view.
  58. * // Maybe it will be "decorated" later.
  59. * const viewImage = new ViewElement( 'img' );
  60. * const insertPosition = conversionApi.mapper.toViewPosition( data.range.start );
  61. *
  62. * // Check if the `image` element has children.
  63. * if ( data.item.childCount > 0 ) {
  64. * const modelCaption = data.item.getChild( 0 );
  65. *
  66. * // `modelCaption` insertion change is consumed from consumable values.
  67. * // It will not be converted by other converters, but it's children (probably some text) will be.
  68. * // Through mapping, converters for text will know where to insert contents of `modelCaption`.
  69. * if ( conversionApi.consumable.consume( modelCaption, 'insert' ) ) {
  70. * const viewCaption = new ViewElement( 'figcaption' );
  71. *
  72. * const viewImageHolder = new ViewElement( 'figure', null, [ viewImage, viewCaption ] );
  73. *
  74. * conversionApi.mapper.bindElements( modelCaption, viewCaption );
  75. * conversionApi.mapper.bindElements( data.item, viewImageHolder );
  76. * viewWriter.insert( insertPosition, viewImageHolder );
  77. * }
  78. * } else {
  79. * conversionApi.mapper.bindElements( data.item, viewImage );
  80. * viewWriter.insert( insertPosition, viewImage );
  81. * }
  82. *
  83. * evt.stop();
  84. * } );
  85. */
  86. export default class ModelConsumable {
  87. /**
  88. * Creates an empty consumables list.
  89. */
  90. constructor() {
  91. /**
  92. * Contains list of consumable values.
  93. *
  94. * @private
  95. * @member {Map} module:engine/conversion/modelconsumable~ModelConsumable#_consumable
  96. */
  97. this._consumable = new Map();
  98. /**
  99. * For each {@link module:engine/model/textproxy~TextProxy} added to `ModelConsumable`, this registry holds parent
  100. * of that `TextProxy` and start and end indices of that `TextProxy`. This allows identification of `TextProxy`
  101. * instances that points to the same part of the model but are different instances. Each distinct `TextProxy`
  102. * is given unique `Symbol` which is then registered as consumable. This process is transparent for `ModelConsumable`
  103. * API user because whenever `TextProxy` is added, tested, consumed or reverted, internal mechanisms of
  104. * `ModelConsumable` translates `TextProxy` to that unique `Symbol`.
  105. *
  106. * @private
  107. * @member {Map} module:engine/conversion/modelconsumable~ModelConsumable#_textProxyRegistry
  108. */
  109. this._textProxyRegistry = new Map();
  110. }
  111. /**
  112. * Adds a consumable value to the consumables list and links it with given model item.
  113. *
  114. * modelConsumable.add( modelElement, 'insert' ); // Add `modelElement` insertion change to consumable values.
  115. * modelConsumable.add( modelElement, 'addAttribute:bold' ); // Add `bold` attribute insertion on `modelElement` change.
  116. * modelConsumable.add( modelElement, 'removeAttribute:bold' ); // Add `bold` attribute removal on `modelElement` change.
  117. * modelConsumable.add( modelSelection, 'selection' ); // Add `modelSelection` to consumable values.
  118. * modelConsumable.add( modelRange, 'range' ); // Add `modelRange` to consumable values.
  119. *
  120. * @param {module:engine/model/item~Item|module:engine/model/selection~Selection|module:engine/model/range~Range} item
  121. * Model item, range or selection that has the consumable.
  122. * @param {String} type Consumable type. Will be normalized to a proper form, that is either `<word>` or `<part>:<part>`.
  123. * Second colon and everything after will be cut. Passing event name is a safe and good practice.
  124. */
  125. add( item, type ) {
  126. type = _normalizeConsumableType( type );
  127. if ( item instanceof TextProxy ) {
  128. item = this._getSymbolForTextProxy( item );
  129. }
  130. if ( !this._consumable.has( item ) ) {
  131. this._consumable.set( item, new Map() );
  132. }
  133. this._consumable.get( item ).set( type, true );
  134. }
  135. /**
  136. * Removes given consumable value from given model item.
  137. *
  138. * modelConsumable.consume( modelElement, 'insert' ); // Remove `modelElement` insertion change from consumable values.
  139. * modelConsumable.consume( modelElement, 'addAttribute:bold' ); // Remove `bold` attribute insertion on `modelElement` change.
  140. * modelConsumable.consume( modelElement, 'removeAttribute:bold' ); // Remove `bold` attribute removal on `modelElement` change.
  141. * modelConsumable.consume( modelSelection, 'selection' ); // Remove `modelSelection` from consumable values.
  142. * modelConsumable.consume( modelRange, 'range' ); // Remove 'modelRange' from consumable values.
  143. *
  144. * @param {module:engine/model/item~Item|module:engine/model/selection~Selection|module:engine/model/range~Range} item
  145. * Model item, range or selection from which consumable will be consumed.
  146. * @param {String} type Consumable type. Will be normalized to a proper form, that is either `<word>` or `<part>:<part>`.
  147. * Second colon and everything after will be cut. Passing event name is a safe and good practice.
  148. * @returns {Boolean} `true` if consumable value was available and was consumed, `false` otherwise.
  149. */
  150. consume( item, type ) {
  151. type = _normalizeConsumableType( type );
  152. if ( item instanceof TextProxy ) {
  153. item = this._getSymbolForTextProxy( item );
  154. }
  155. if ( this.test( item, type ) ) {
  156. this._consumable.get( item ).set( type, false );
  157. return true;
  158. } else {
  159. return false;
  160. }
  161. }
  162. /**
  163. * Tests whether there is a consumable value of given type connected with given model item.
  164. *
  165. * modelConsumable.test( modelElement, 'insert' ); // Check for `modelElement` insertion change.
  166. * modelConsumable.test( modelElement, 'addAttribute:bold' ); // Check for `bold` attribute insertion on `modelElement` change.
  167. * modelConsumable.test( modelElement, 'removeAttribute:bold' ); // Check for `bold` attribute removal on `modelElement` change.
  168. * modelConsumable.test( modelSelection, 'selection' ); // Check if `modelSelection` is consumable.
  169. * modelConsumable.test( modelRange, 'range' ); // Check if `modelRange` is consumable.
  170. *
  171. * @param {module:engine/model/item~Item|module:engine/model/selection~Selection|module:engine/model/range~Range} item
  172. * Model item, range or selection to be tested.
  173. * @param {String} type Consumable type. Will be normalized to a proper form, that is either `<word>` or `<part>:<part>`.
  174. * Second colon and everything after will be cut. Passing event name is a safe and good practice.
  175. * @returns {null|Boolean} `null` if such consumable was never added, `false` if the consumable values was
  176. * already consumed or `true` if it was added and not consumed yet.
  177. */
  178. test( item, type ) {
  179. type = _normalizeConsumableType( type );
  180. if ( item instanceof TextProxy ) {
  181. item = this._getSymbolForTextProxy( item );
  182. }
  183. const itemConsumables = this._consumable.get( item );
  184. if ( itemConsumables === undefined ) {
  185. return null;
  186. }
  187. const value = itemConsumables.get( type );
  188. if ( value === undefined ) {
  189. return null;
  190. }
  191. return value;
  192. }
  193. /**
  194. * Reverts consuming of consumable value.
  195. *
  196. * modelConsumable.revert( modelElement, 'insert' ); // Revert consuming `modelElement` insertion change.
  197. * modelConsumable.revert( modelElement, 'addAttribute:bold' ); // Revert consuming `bold` attribute insert from `modelElement`.
  198. * modelConsumable.revert( modelElement, 'removeAttribute:bold' ); // Revert consuming `bold` attribute remove from `modelElement`.
  199. * modelConsumable.revert( modelSelection, 'selection' ); // Revert consuming `modelSelection`.
  200. * modelConsumable.revert( modelRange, 'range' ); // Revert consuming `modelRange`.
  201. *
  202. * @param {module:engine/model/item~Item|module:engine/model/selection~Selection|module:engine/model/range~Range} item
  203. * Model item, range or selection to be reverted.
  204. * @param {String} type Consumable type.
  205. * @returns {null|Boolean} `true` if consumable has been reversed, `false` otherwise. `null` if the consumable has
  206. * never been added.
  207. */
  208. revert( item, type ) {
  209. type = _normalizeConsumableType( type );
  210. if ( item instanceof TextProxy ) {
  211. item = this._getSymbolForTextProxy( item );
  212. }
  213. const test = this.test( item, type );
  214. if ( test === false ) {
  215. this._consumable.get( item ).set( type, true );
  216. return true;
  217. } else if ( test === true ) {
  218. return false;
  219. }
  220. return null;
  221. }
  222. /**
  223. * Gets a unique symbol for passed {@link module:engine/model/textproxy~TextProxy} instance. All `TextProxy` instances that
  224. * have same parent, same start index and same end index will get the same symbol.
  225. *
  226. * Used internally to correctly consume `TextProxy` instances.
  227. *
  228. * @private
  229. * @param {module:engine/model/textproxy~TextProxy} textProxy `TextProxy` instance to get a symbol for.
  230. * @returns {Symbol} Symbol representing all equal instances of `TextProxy`.
  231. */
  232. _getSymbolForTextProxy( textProxy ) {
  233. let symbol = null;
  234. const startMap = this._textProxyRegistry.get( textProxy.startOffset );
  235. if ( startMap ) {
  236. const endMap = startMap.get( textProxy.endOffset );
  237. if ( endMap ) {
  238. symbol = endMap.get( textProxy.parent );
  239. }
  240. }
  241. if ( !symbol ) {
  242. symbol = this._addSymbolForTextProxy( textProxy.startOffset, textProxy.endOffset, textProxy.parent );
  243. }
  244. return symbol;
  245. }
  246. /**
  247. * Adds a symbol for given properties that characterizes a {@link module:engine/model/textproxy~TextProxy} instance.
  248. *
  249. * Used internally to correctly consume `TextProxy` instances.
  250. *
  251. * @private
  252. * @param {Number} startIndex Text proxy start index in it's parent.
  253. * @param {Number} endIndex Text proxy end index in it's parent.
  254. * @param {module:engine/model/element~Element} parent Text proxy parent.
  255. * @returns {Symbol} Symbol generated for given properties.
  256. */
  257. _addSymbolForTextProxy( start, end, parent ) {
  258. const symbol = Symbol( 'textProxySymbol' );
  259. let startMap, endMap;
  260. startMap = this._textProxyRegistry.get( start );
  261. if ( !startMap ) {
  262. startMap = new Map();
  263. this._textProxyRegistry.set( start, startMap );
  264. }
  265. endMap = startMap.get( end );
  266. if ( !endMap ) {
  267. endMap = new Map();
  268. startMap.set( end, endMap );
  269. }
  270. endMap.set( parent, symbol );
  271. return symbol;
  272. }
  273. }
  274. // Returns a normalized consumable type name from given string. A normalized consumable type name is a string that has
  275. // at most one colon, for example: `insert` or `addMarker:highlight`. If string to normalize has more "parts" (more colons),
  276. // the other parts are dropped, for example: `addattribute:bold:$text` -> `addattributes:bold`.
  277. //
  278. // @param {String} type Consumable type.
  279. // @returns {String} Normalized consumable type.
  280. function _normalizeConsumableType( type ) {
  281. const parts = type.split( ':' );
  282. return parts.length > 1 ? parts[ 0 ] + ':' + parts[ 1 ] : parts[ 0 ];
  283. }