model-to-view-converters.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import ModelTreeWalker from '../model/treewalker.js';
  7. import ModelRange from '../model/range.js';
  8. import ViewElement from '../view/element.js';
  9. import ViewText from '../view/text.js';
  10. /**
  11. * Contains {@link engine.model model} to {@link engine.view view} converters for
  12. * {@link engine.conversion.ModelConversionDispatcher}.
  13. *
  14. * @namespace engine.conversion.modelToView
  15. */
  16. /**
  17. * Function factory, creates a converter that converts node insertion changes from the model to the view.
  18. * The view element that will be added to the view depends on passed parameter. If {@link engine.view.Element} was passed,
  19. * it will be cloned and the copy will be inserted. If `Function` is provided, it is passed all the parameters of the
  20. * dispatcher's {@link engine.conversion.ModelConversionDispatcher#event:insert insert event}. It's expected that the
  21. * function returns a {@link engine.view.Element}. The result of the function will be inserted to the view.
  22. *
  23. * The converter automatically consumes corresponding value from consumables list, stops the event (see
  24. * {@link engine.conversion.ModelConversionDispatcher}) and bind model and view elements.
  25. *
  26. * modelDispatcher.on( 'insert:paragraph', insertElement( new ViewElement( 'p' ) ) );
  27. *
  28. * modelDispatcher.on(
  29. * 'insert:myElem',
  30. * insertElement( ( data, consumable, conversionApi ) => {
  31. * let myElem = new ViewElement( 'myElem', { myAttr: true }, new ViewText( 'myText' ) );
  32. *
  33. * // Do something fancy with myElem using data/consumable/conversionApi ...
  34. *
  35. * return myElem;
  36. * }
  37. * ) );
  38. *
  39. * @external engine.conversion.modelToView
  40. * @function engine.conversion.modelToView.insertElement
  41. * @param {engine.view.Element|Function} elementCreator View element, or function returning a view element, which
  42. * will be inserted.
  43. * @returns {Function} Insert element event converter.
  44. */
  45. export function insertElement( elementCreator ) {
  46. return ( evt, data, consumable, conversionApi ) => {
  47. consumable.consume( data.item, 'insert' );
  48. const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  49. const viewElement = ( elementCreator instanceof ViewElement ) ?
  50. elementCreator.clone( true ) :
  51. elementCreator( data, consumable, conversionApi );
  52. conversionApi.mapper.bindElements( data.item, viewElement );
  53. conversionApi.writer.insert( viewPosition, viewElement );
  54. evt.stop();
  55. };
  56. }
  57. /**
  58. * Function factory, creates a default model-to-view converter for text insertion changes.
  59. *
  60. * The converter automatically consumes corresponding value from consumables list and stops the event (see
  61. * {@link engine.conversion.ModelConversionDispatcher}).
  62. *
  63. * modelDispatcher.on( 'insert:$text', insertText() );
  64. *
  65. * @external engine.conversion.modelToView
  66. * @function engine.conversion.modelToView.insertText
  67. * @returns {Function} Insert text event converter.
  68. */
  69. export function insertText() {
  70. return ( evt, data, consumable, conversionApi ) => {
  71. consumable.consume( data.item, 'insert' );
  72. const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  73. const viewText = new ViewText( data.item.text );
  74. conversionApi.writer.insert( viewPosition, viewText );
  75. evt.stop();
  76. };
  77. }
  78. /**
  79. * Function factory, creates a converter that converts set/change attribute changes from the model to the view. Attributes
  80. * from model are converted to the view element attributes in the view. You may provide a custom function to generate a
  81. * key-value attribute pair to add/change. If not provided, model attributes will be converted to view elements attributes
  82. * on 1-to-1 basis.
  83. *
  84. * **Note:** Provided attribute creator should always return the same `key` for given attribute from the model.
  85. *
  86. * The converter automatically consumes corresponding value from consumables list and stops the event (see
  87. * {@link engine.conversion.ModelConversionDispatcher}).
  88. *
  89. * modelDispatcher.on( 'addAttribute:customAttr:myElem', setAttribute( ( data ) => {
  90. * // Change attribute key from `customAttr` to `class` in view.
  91. * const key = 'class';
  92. * let value = data.attributeNewValue;
  93. *
  94. * // Force attribute value to 'empty' if the model element is empty.
  95. * if ( data.item.getChildCount() === 0 ) {
  96. * value = 'empty';
  97. * }
  98. *
  99. * // Return key-value pair.
  100. * return { key, value };
  101. * } ) );
  102. *
  103. * @external engine.conversion.modelToView
  104. * @function engine.conversion.modelToView.setAttribute
  105. * @param {Function} [attributeCreator] Function returning an object with two properties: `key` and `value`, which
  106. * represents attribute key and attribute value to be set on a {@link engine.view.Element view element}. The function
  107. * is passed all the parameters of the {@link engine.conversion.ModelConversionDispatcher.addAttribute}
  108. * or {@link engine.conversion.ModelConversionDispatcher.changeAttribute} event.
  109. * @returns {Function} Set/change attribute converter.
  110. */
  111. export function setAttribute( attributeCreator ) {
  112. attributeCreator = attributeCreator || ( ( value, key ) => ( { value, key } ) );
  113. return ( evt, data, consumable, conversionApi ) => {
  114. const { key, value } = attributeCreator( data.attributeNewValue, data.attributeKey, data, consumable, conversionApi );
  115. consumable.consume( data.item, eventNameToConsumableType( evt.name ) );
  116. conversionApi.mapper.toViewElement( data.item ).setAttribute( key, value );
  117. evt.stop();
  118. };
  119. }
  120. /**
  121. * Function factory, creates a converter that converts remove attribute changes from the model to the view. Removes attributes
  122. * that were converted to the view element attributes in the view. You may provide a custom function to generate a
  123. * key-value attribute pair to remove. If not provided, model attributes will be removed from view elements on 1-to-1 basis.
  124. *
  125. * **Note:** Provided attribute creator should always return the same `key` for given attribute from the model.
  126. *
  127. * **Note:** You can use the same attribute creator as in {@link engine.conversion.modelToView.setAttribute}.
  128. *
  129. * The converter automatically consumes corresponding value from consumables list and stops the event (see
  130. * {@link engine.conversion.ModelConversionDispatcher}).
  131. *
  132. * modelDispatcher.on( 'removeAttribute:customAttr:myElem', removeAttribute( ( data ) => {
  133. * // Change attribute key from `customAttr` to `class` in view.
  134. * const key = 'class';
  135. * let value = data.attributeNewValue;
  136. *
  137. * // Force attribute value to 'empty' if the model element is empty.
  138. * if ( data.item.getChildCount() === 0 ) {
  139. * value = 'empty';
  140. * }
  141. *
  142. * // Return key-value pair.
  143. * return { key, value };
  144. * } ) );
  145. *
  146. * @external engine.conversion.modelToView
  147. * @function engine.conversion.modelToView.removeAttribute
  148. * @param {Function} [attributeCreator] Function returning an object with two properties: `key` and `value`, which
  149. * represents attribute key and attribute value to be removed from {@link engine.view.Element view element}. The function
  150. * is passed all the parameters of the {@link engine.conversion.ModelConversionDispatcher#event:addAttribute addAttribute event}
  151. * or {@link engine.conversion.ModelConversionDispatcher#event:changeAttribute changeAttribute event}.
  152. * @returns {Function} Remove attribute converter.
  153. */
  154. export function removeAttribute( attributeCreator ) {
  155. attributeCreator = attributeCreator || ( ( value, key ) => ( { key } ) );
  156. return ( evt, data, consumable, conversionApi ) => {
  157. const { key } = attributeCreator( data.attributeOldValue, data.attributeKey, data, consumable, conversionApi );
  158. consumable.consume( data.item, eventNameToConsumableType( evt.name ) );
  159. conversionApi.mapper.toViewElement( data.item ).removeAttribute( key );
  160. evt.stop();
  161. };
  162. }
  163. /**
  164. * Function factory, creates a converter that converts set/change attribute changes from the model to the view. In this case,
  165. * model attributes are converted to a view element that will be wrapping view nodes which corresponding model nodes had
  166. * the attribute set. This is useful for attributes like `bold`, which may be set on a text nodes in model but are
  167. * represented as an element in the view:
  168. *
  169. * [paragraph] MODEL ====> VIEW <p>
  170. * |- a {bold: true} |- <b>
  171. * |- b {bold: true} | |- ab
  172. * |- c |- c
  173. *
  174. * The wrapping node depends on passed parameter. If {@link engine.view.Element} was passed, it will be cloned and
  175. * the copy will become the wrapping element. If `Function` is provided, it is passed all the parameters of the
  176. * {@link engine.conversion.ModelConversionDispatcher#event:setAttribute setAttribute event}. It's expected that the
  177. * function returns a {@link engine.view.Element}. The result of the function will be the wrapping element.
  178. *
  179. * The converter automatically consumes corresponding value from consumables list, stops the event (see
  180. * {@link engine.conversion.ModelConversionDispatcher}).
  181. *
  182. * modelDispatcher.on( 'addAttribute:bold', wrap( new ViewElement( 'strong' ) ) );
  183. *
  184. * @external engine.conversion.modelToView
  185. * @function engine.conversion.modelToView.wrap
  186. * @param {engine.view.Element|Function} elementCreator View element, or function returning a view element, which will
  187. * be used for wrapping.
  188. * @returns {Function} Set/change attribute converter.
  189. */
  190. export function wrap( elementCreator ) {
  191. return ( evt, data, consumable, conversionApi ) => {
  192. consumable.consume( data.item, eventNameToConsumableType( evt.name ) );
  193. let viewRange = conversionApi.mapper.toViewRange( data.range );
  194. const viewElement = ( elementCreator instanceof ViewElement ) ?
  195. elementCreator.clone( true ) :
  196. elementCreator( data.attributeNewValue, data, consumable, conversionApi );
  197. // If this is a change event (because old value is not empty) and the creator is a function (so
  198. // it may create different view elements basing on attribute value) we have to create
  199. // view element basing on old value and unwrap it before wrapping with a newly created view element.
  200. if ( data.attributeOldValue !== null && !( elementCreator instanceof ViewElement ) ) {
  201. const oldViewElement = elementCreator( data.attributeOldValue, data, consumable, conversionApi );
  202. viewRange = conversionApi.writer.unwrap( viewRange, oldViewElement, evt.priority );
  203. }
  204. conversionApi.writer.wrap( viewRange, viewElement, evt.priority );
  205. evt.stop();
  206. };
  207. }
  208. /**
  209. * Function factory, creates a converter that converts remove attribute changes from the model to the view. It assumes, that
  210. * attributes from model were converted to elements in the view. This converter will unwrap view nodes from corresponding
  211. * view element if given attribute was removed.
  212. *
  213. * The view element type that will be unwrapped depends on passed parameter.
  214. * If {@link engine.view.Element} was passed, it will be used to look for similar element in the view for unwrapping. If `Function`
  215. * is provided, it is passed all the parameters of the
  216. * {@link engine.conversion.ModelConversionDispatcher#event:setAttribute setAttribute event}. It's expected that the
  217. * function returns a {@link engine.view.Element}. The result of the function will be used to look for similar element
  218. * in the view for unwrapping.
  219. *
  220. * The converter automatically consumes corresponding value from consumables list, stops the event (see
  221. * {@link engine.conversion.ModelConversionDispatcher}) and bind model and view elements.
  222. *
  223. * modelDispatcher.on( 'removeAttribute:bold', unwrap( new ViewElement( 'strong' ) ) );
  224. *
  225. * @see engine.conversion.modelToView.wrap
  226. * @external engine.conversion.modelToView
  227. * @function engine.conversion.modelToView.unwrap
  228. * @param {engine.view.Element|Function} elementCreator View element, or function returning a view element, which will
  229. * be used for unwrapping.
  230. * @returns {Function} Remove attribute converter.
  231. */
  232. export function unwrap( elementCreator ) {
  233. return ( evt, data, consumable, conversionApi ) => {
  234. consumable.consume( data.item, eventNameToConsumableType( evt.name ) );
  235. const viewRange = conversionApi.mapper.toViewRange( data.range );
  236. const viewNode = ( elementCreator instanceof ViewElement ) ?
  237. elementCreator.clone( true ) :
  238. elementCreator( data.attributeOldValue, data, consumable, conversionApi );
  239. conversionApi.writer.unwrap( viewRange, viewNode );
  240. evt.stop();
  241. };
  242. }
  243. /**
  244. * Function factory, creates a default model-to-view converter for nodes move changes.
  245. *
  246. * modelDispatcher.on( 'move', move() );
  247. *
  248. * @external engine.conversion.modelToView
  249. * @function engine.conversion.modelToView.move
  250. * @returns {Function} Move event converter.
  251. */
  252. export function move() {
  253. return ( evt, data, conversionApi ) => {
  254. const walker = new ModelTreeWalker( { boundaries: data.range, shallow: true } );
  255. let length = 0;
  256. for ( let value of walker ) {
  257. length += value.length;
  258. }
  259. const sourceModelRange = ModelRange.createFromPositionAndShift( data.sourcePosition, length );
  260. const sourceViewRange = conversionApi.mapper.toViewRange( sourceModelRange );
  261. const targetViewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  262. conversionApi.writer.move( sourceViewRange, targetViewPosition );
  263. };
  264. }
  265. /**
  266. * Function factory, creates a default model-to-view converter for nodes remove changes.
  267. *
  268. * modelDispatcher.on( 'remove', remove() );
  269. *
  270. * @external engine.conversion.modelToView
  271. * @function engine.conversion.modelToView.remove
  272. * @returns {Function} Remove event converter.
  273. */
  274. export function remove() {
  275. return ( evt, data, conversionApi ) => {
  276. const walker = new ModelTreeWalker( { boundaries: data.range, shallow: true } );
  277. let length = 0;
  278. for ( let value of walker ) {
  279. length += value.length;
  280. }
  281. const sourceModelRange = ModelRange.createFromPositionAndShift( data.sourcePosition, length );
  282. const sourceViewRange = conversionApi.mapper.toViewRange( sourceModelRange );
  283. conversionApi.writer.remove( sourceViewRange );
  284. };
  285. }
  286. /**
  287. * Returns the consumable type that is to be consumed in an event, basing on that event name.
  288. *
  289. * @param {String} evtName Event name.
  290. * @returns {String} Consumable type.
  291. */
  292. export function eventNameToConsumableType( evtName ) {
  293. const parts = evtName.split( ':' );
  294. return parts[ 0 ] + ':' + parts[ 1 ];
  295. }