viewconversiondispatcher.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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/viewconversiondispatcher
  7. */
  8. import ViewConsumable from './viewconsumable';
  9. import ModelRange from '../model/range';
  10. import ModelPosition from '../model/position';
  11. import ModelTreeWalker from '../model/treewalker';
  12. import ModelNode from '../model/node';
  13. import ModelDocumentFragment from '../model/documentfragment';
  14. import { remove } from '../model/writer';
  15. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  16. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  17. import extend from '@ckeditor/ckeditor5-utils/src/lib/lodash/extend';
  18. import log from '@ckeditor/ckeditor5-utils/src/log';
  19. /**
  20. * `ViewConversionDispatcher` is a central point of {@link module:engine/view/view view} conversion, which is a process of
  21. * converting given {@link module:engine/view/documentfragment~DocumentFragment view document fragment} or
  22. * {@link module:engine/view/element~Element}
  23. * into another structure. In default application, {@link module:engine/view/view view} is converted to {@link module:engine/model/model}.
  24. *
  25. * During conversion process, for all {@link module:engine/view/node~Node view nodes} from the converted view document fragment,
  26. * `ViewConversionDispatcher` fires corresponding events. Special callbacks called "converters" should listen to
  27. * `ViewConversionDispatcher` for those events.
  28. *
  29. * Each callback, as a first argument, is passed a special object `data` that has `input` and `output` properties.
  30. * `input` property contains {@link module:engine/view/node~Node view node} or
  31. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}
  32. * that is converted at the moment and might be handled by the callback. `output` property should be used to save the result
  33. * of conversion. Keep in mind that the `data` parameter is customizable and may contain other values - see
  34. * {@link ~ViewConversionDispatcher#convert}. It is also shared by reference by all callbacks
  35. * listening to given event. **Note**: in view to model conversion - `data` contains `context` property that is an array
  36. * of {@link module:engine/model/element~Element model elements}. These are model elements that will be the parent of currently
  37. * converted view item. `context` property is used in examples below.
  38. *
  39. * The second parameter passed to a callback is an instance of {@link module:engine/conversion/viewconsumable~ViewConsumable}. It stores
  40. * information about what parts of processed view item are still waiting to be handled. After a piece of view item
  41. * was converted, appropriate consumable value should be {@link module:engine/conversion/viewconsumable~ViewConsumable#consume consumed}.
  42. *
  43. * The third parameter passed to a callback is an instance of {@link ~ViewConversionDispatcher}
  44. * which provides additional tools for converters.
  45. *
  46. * Examples of providing callbacks for `ViewConversionDispatcher`:
  47. *
  48. * // Converter for paragraphs (<p>).
  49. * viewDispatcher.on( 'element:p', ( evt, data, consumable, conversionApi ) => {
  50. * const paragraph = new ModelElement( 'paragraph' );
  51. * const schemaQuery = {
  52. * name: 'paragraph',
  53. * inside: data.context
  54. * };
  55. *
  56. * if ( conversionApi.schema.check( schemaQuery ) ) {
  57. * if ( !consumable.consume( data.input, { name: true } ) ) {
  58. * // Before converting this paragraph's children we have to update their context by this paragraph.
  59. * data.context.push( paragraph );
  60. * const children = conversionApi.convertChildren( data.input, consumable, data );
  61. * data.context.pop();
  62. * paragraph.appendChildren( children );
  63. * data.output = paragraph;
  64. * }
  65. * }
  66. * } );
  67. *
  68. * // Converter for links (<a>).
  69. * viewDispatcher.on( 'element:a', ( evt, data, consumable, conversionApi ) => {
  70. * if ( consumable.consume( data.input, { name: true, attributes: [ 'href' ] } ) ) {
  71. * // <a> element is inline and is represented by an attribute in the model.
  72. * // This is why we are not updating `context` property.
  73. * data.output = conversionApi.convertChildren( data.input, consumable, data );
  74. *
  75. * for ( let item of Range.createFrom( data.output ) ) {
  76. * const schemaQuery = {
  77. * name: item.name || '$text',
  78. * attribute: 'link',
  79. * inside: data.context
  80. * };
  81. *
  82. * if ( conversionApi.schema.check( schemaQuery ) ) {
  83. * item.setAttribute( 'link', data.input.getAttribute( 'href' ) );
  84. * }
  85. * }
  86. * }
  87. * } );
  88. *
  89. * // Fire conversion.
  90. * // Always take care where the converted model structure will be appended to. If this `viewDocumentFragment`
  91. * // is going to be appended directly to a '$root' element, use that in `context`.
  92. * viewDispatcher.convert( viewDocumentFragment, { context: [ '$root' ] } );
  93. *
  94. * Before each conversion process, `ViewConversionDispatcher` fires {@link ~ViewConversionDispatcher#event:viewCleanup}
  95. * event which can be used to prepare tree view for conversion.
  96. *
  97. * @mixes module:utils/emittermixin~EmitterMixin
  98. * @fires viewCleanup
  99. * @fires element
  100. * @fires text
  101. * @fires documentFragment
  102. */
  103. export default class ViewConversionDispatcher {
  104. /**
  105. * Creates a `ViewConversionDispatcher` that operates using passed API.
  106. *
  107. * @see module:engine/conversion/viewconversiondispatcher~ViewConversionApi
  108. * @param {Object} [conversionApi] Additional properties for interface that will be passed to events fired
  109. * by `ViewConversionDispatcher`.
  110. */
  111. constructor( conversionApi = {} ) {
  112. /**
  113. * Interface passed by dispatcher to the events callbacks.
  114. *
  115. * @member {module:engine/conversion/viewconversiondispatcher~ViewConversionApi}
  116. */
  117. this.conversionApi = extend( {}, conversionApi );
  118. // `convertItem` and `convertChildren` are bound to this `ViewConversionDispatcher` instance and
  119. // set on `conversionApi`. This way only a part of `ViewConversionDispatcher` API is exposed.
  120. this.conversionApi.convertItem = this._convertItem.bind( this );
  121. this.conversionApi.convertChildren = this._convertChildren.bind( this );
  122. }
  123. /**
  124. * Starts the conversion process. The entry point for the conversion.
  125. *
  126. * @fires element
  127. * @fires text
  128. * @fires documentFragment
  129. * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element} viewItem
  130. * Part of the view to be converted.
  131. * @param {Object} [additionalData] Additional data to be passed in `data` argument when firing `ViewConversionDispatcher`
  132. * events. See also {@link ~ViewConversionDispatcher#event:element element event}.
  133. * @returns {module:engine/model/documentfragment~DocumentFragment} Model data that is a result of the conversion process
  134. * wrapped in `DocumentFragment`. Converted marker elements will be set as that document fragment's
  135. * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
  136. */
  137. convert( viewItem, additionalData = {} ) {
  138. this.fire( 'viewCleanup', viewItem );
  139. const consumable = ViewConsumable.createFrom( viewItem );
  140. let conversionResult = this._convertItem( viewItem, consumable, additionalData );
  141. // We can get a null here if conversion failed (see _convertItem())
  142. // or simply if an item could not be converted (e.g. due to the schema).
  143. if ( !conversionResult ) {
  144. return new ModelDocumentFragment();
  145. }
  146. // When conversion result is not a document fragment we need to wrap it in document fragment.
  147. if ( !conversionResult.is( 'documentFragment' ) ) {
  148. conversionResult = new ModelDocumentFragment( [ conversionResult ] );
  149. }
  150. // Extract temporary markers elements from model and set as static markers collection.
  151. conversionResult.markers = extractMarkersFromModelFragment( conversionResult );
  152. return conversionResult;
  153. }
  154. /**
  155. * @private
  156. * @see module:engine/conversion/viewconversiondispatcher~ViewConversionApi#convertItem
  157. */
  158. _convertItem( input, consumable, additionalData = {} ) {
  159. const data = extend( {}, additionalData, {
  160. input,
  161. output: null
  162. } );
  163. if ( input.is( 'element' ) ) {
  164. this.fire( 'element:' + input.name, data, consumable, this.conversionApi );
  165. } else if ( input.is( 'text' ) ) {
  166. this.fire( 'text', data, consumable, this.conversionApi );
  167. } else {
  168. this.fire( 'documentFragment', data, consumable, this.conversionApi );
  169. }
  170. // Handle incorrect `data.output`.
  171. if ( data.output && !( data.output instanceof ModelNode || data.output instanceof ModelDocumentFragment ) ) {
  172. /**
  173. * Dropped incorrect conversion result.
  174. *
  175. * Item may be converted to either {@link module:engine/model/node~Node model node} or
  176. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment}.
  177. *
  178. * @error view-conversion-dispatcher-incorrect-result
  179. */
  180. log.warn( 'view-conversion-dispatcher-incorrect-result: Dropped incorrect conversion result.', [ input, data.output ] );
  181. return null;
  182. }
  183. return data.output;
  184. }
  185. /**
  186. * @private
  187. * @see module:engine/conversion/viewconversiondispatcher~ViewConversionApi#convertChildren
  188. */
  189. _convertChildren( input, consumable, additionalData = {} ) {
  190. // Get all children of view input item.
  191. const viewChildren = Array.from( input.getChildren() );
  192. // 1. Map those children to model.
  193. // 2. Filter out items that has not been converted or for which conversion returned wrong result (for those warning is logged).
  194. // 3. Extract children from document fragments to flatten results.
  195. const convertedChildren = viewChildren
  196. .map( viewChild => this._convertItem( viewChild, consumable, additionalData ) )
  197. .filter( converted => converted instanceof ModelNode || converted instanceof ModelDocumentFragment )
  198. .reduce( ( result, filtered ) => {
  199. return result.concat(
  200. filtered.is( 'documentFragment' ) ? Array.from( filtered.getChildren() ) : filtered
  201. );
  202. }, [] );
  203. // Normalize array to model document fragment.
  204. return new ModelDocumentFragment( convertedChildren );
  205. }
  206. /**
  207. * Fired before the first conversion event, at the beginning of view to model conversion process.
  208. *
  209. * @event viewCleanup
  210. * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element}
  211. * viewItem Part of the view to be converted.
  212. */
  213. /**
  214. * Fired when {@link module:engine/view/element~Element} is converted.
  215. *
  216. * `element` is a namespace event for a class of events. Names of actually called events follow this pattern:
  217. * `element:<elementName>` where `elementName` is the name of converted element. This way listeners may listen to
  218. * all elements conversion or to conversion of specific elements.
  219. *
  220. * @event element
  221. * @param {Object} data Object containing conversion input and a placeholder for conversion output and possibly other
  222. * values (see {@link #convert}).
  223. * Keep in mind that this object is shared by reference between all callbacks that will be called.
  224. * This means that callbacks can add their own values if needed,
  225. * and those values will be available in other callbacks.
  226. * @param {module:engine/view/element~Element} data.input Converted element.
  227. * @param {*} data.output The current state of conversion result. Every change to converted element should
  228. * be reflected by setting or modifying this property.
  229. * @param {module:engine/model/schema~SchemaPath} data.context The conversion context.
  230. * @param {module:engine/conversion/viewconsumable~ViewConsumable} consumable Values to consume.
  231. * @param {Object} conversionApi Conversion interface to be used by callback, passed in `ViewConversionDispatcher` constructor.
  232. * Besides of properties passed in constructor, it also has `convertItem` and `convertChildren` methods which are references
  233. * to {@link #_convertItem} and
  234. * {@link ~ViewConversionDispatcher#_convertChildren}. Those methods are needed to convert
  235. * the whole view-tree they were exposed in `conversionApi` for callbacks.
  236. */
  237. /**
  238. * Fired when {@link module:engine/view/text~Text} is converted.
  239. *
  240. * @event text
  241. * @see #event:element
  242. */
  243. /**
  244. * Fired when {@link module:engine/view/documentfragment~DocumentFragment} is converted.
  245. *
  246. * @event documentFragment
  247. * @see #event:element
  248. */
  249. }
  250. mix( ViewConversionDispatcher, EmitterMixin );
  251. // Traverses given model item and searches elements which marks marker range. Found element is removed from
  252. // DocumentFragment but path of this element is stored in a Map which is then returned.
  253. //
  254. // @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/node~Node} modelItem Fragment of model.
  255. // @returns {Map<String, module:engine/model/range~Range>} List of static markers.
  256. function extractMarkersFromModelFragment( modelItem ) {
  257. const markerElements = new Set();
  258. const markers = new Map();
  259. // Create ModelTreeWalker.
  260. const walker = new ModelTreeWalker( {
  261. startPosition: ModelPosition.createAt( modelItem, 0 ),
  262. ignoreElementEnd: true
  263. } );
  264. // Walk through DocumentFragment and collect marker elements.
  265. for ( const value of walker ) {
  266. // Check if current element is a marker.
  267. if ( value.item.name == '$marker' ) {
  268. markerElements.add( value.item );
  269. }
  270. }
  271. // Walk through collected marker elements store its path and remove its from the DocumentFragment.
  272. for ( const markerElement of markerElements ) {
  273. const markerName = markerElement.getAttribute( 'data-name' );
  274. const currentPosition = ModelPosition.createBefore( markerElement );
  275. // When marker of given name is not stored it means that we have found the beginning of the range.
  276. if ( !markers.has( markerName ) ) {
  277. markers.set( markerName, new ModelRange( ModelPosition.createFromPosition( currentPosition ) ) );
  278. // Otherwise is means that we have found end of the marker range.
  279. } else {
  280. markers.get( markerName ).end = ModelPosition.createFromPosition( currentPosition );
  281. }
  282. // Remove marker element from DocumentFragment.
  283. remove( ModelRange.createOn( markerElement ) );
  284. }
  285. return markers;
  286. }
  287. /**
  288. * Conversion interface that is registered for given {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher}
  289. * and is passed as one of parameters when {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher dispatcher}
  290. * fires it's events.
  291. *
  292. * `ViewConversionApi` object is built by {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher} constructor.
  293. * The exact list of properties of this object is determined by the object passed to the constructor.
  294. *
  295. * @interface ViewConversionApi
  296. */
  297. /**
  298. * Starts conversion of given item by firing an appropriate event.
  299. *
  300. * Every fired event is passed (as first parameter) an object with `output` property. Every event may set and/or
  301. * modify that property. When all callbacks are done, the final value of `output` property is returned by this method.
  302. * The `output` must be either {@link module:engine/model/node~Node model node} or
  303. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} or `null` (as set by default).
  304. *
  305. * @method #convertItem
  306. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:element
  307. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:text
  308. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:documentFragment
  309. * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element|module:engine/view/text~Text}
  310. * input Item to convert.
  311. * @param {module:engine/conversion/viewconsumable~ViewConsumable} consumable Values to consume.
  312. * @param {Object} [additionalData] Additional data to be passed in `data` argument when firing `ViewConversionDispatcher`
  313. * events. See also {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:element element event}.
  314. * @returns {module:engine/model/node~Node|module:engine/model/documentfragment~DocumentFragment|null} The result of item conversion,
  315. * created and modified by callbacks attached to fired event, or `null` if the conversion result was incorrect.
  316. */
  317. /**
  318. * Starts conversion of all children of given item by firing appropriate events for all those children.
  319. *
  320. * @method #convertChildren
  321. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:element
  322. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:text
  323. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:documentFragment
  324. * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element}
  325. * input Item which children will be converted.
  326. * @param {module:engine/conversion/viewconsumable~ViewConsumable} consumable Values to consume.
  327. * @param {Object} [additionalData] Additional data to be passed in `data` argument when firing `ViewConversionDispatcher`
  328. * events. See also {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:element element event}.
  329. * @returns {module:engine/model/documentfragment~DocumentFragment} Model document fragment containing results of conversion
  330. * of all children of given item.
  331. */