8
0

viewconversiondispatcher.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 stamps will be set as that document fragment's
  135. * {@link module:engine/view/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. // If conversion failed, `null` will be returned.
  142. if ( !conversionResult ) {
  143. return new ModelDocumentFragment();
  144. }
  145. // When conversion result is not a document fragment we need to wrap it in document fragment.
  146. if ( !conversionResult.is( 'documentFragment' ) ) {
  147. conversionResult = new ModelDocumentFragment( [ conversionResult ] );
  148. }
  149. // Extract temporary markers stamp from model and set as static markers collection.
  150. conversionResult.markers = extractMarkersFromModelFragment( conversionResult );
  151. return conversionResult;
  152. }
  153. /**
  154. * @private
  155. * @see module:engine/conversion/viewconversiondispatcher~ViewConversionApi#convertItem
  156. */
  157. _convertItem( input, consumable, additionalData = {} ) {
  158. const data = extend( {}, additionalData, {
  159. input: input
  160. } );
  161. if ( input.is( 'element' ) ) {
  162. this.fire( 'element:' + input.name, data, consumable, this.conversionApi );
  163. } else if ( input.is( 'text' ) ) {
  164. this.fire( 'text', data, consumable, this.conversionApi );
  165. } else {
  166. this.fire( 'documentFragment', data, consumable, this.conversionApi );
  167. }
  168. // Handle incorrect `data.output`.
  169. if ( data.output === undefined ) {
  170. /**
  171. * Item has not been converted (output is undefined).
  172. *
  173. * @error view-conversion-dispatcher-item-not-converted
  174. */
  175. log.warn( 'view-conversion-dispatcher-item-not-converted: Item has not been converted (output is undefined).', input );
  176. data.output = null;
  177. } else if ( !( data.output instanceof ModelNode || data.output instanceof ModelDocumentFragment ) ) {
  178. /**
  179. * Dropped incorrect conversion result.
  180. *
  181. * Item may be converted to either {@link module:engine/model/node~Node model node} or
  182. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment}.
  183. *
  184. * @error view-conversion-dispatcher-incorrect-result
  185. */
  186. log.warn( 'view-conversion-dispatcher-incorrect-result: Dropped incorrect conversion result.', [ input, data.output ] );
  187. data.output = null;
  188. }
  189. return data.output;
  190. }
  191. /**
  192. * @private
  193. * @see module:engine/conversion/viewconversiondispatcher~ViewConversionApi#convertChildren
  194. */
  195. _convertChildren( input, consumable, additionalData = {} ) {
  196. // Get all children of view input item.
  197. const viewChildren = Array.from( input.getChildren() );
  198. // 1. Map those children to model.
  199. // 2. Filter out wrong results.
  200. // 3. Extract children from document fragments to flatten results.
  201. const convertedChildren = viewChildren
  202. .map( ( viewChild ) => this._convertItem( viewChild, consumable, additionalData ) )
  203. .filter( ( converted ) => converted instanceof ModelNode || converted instanceof ModelDocumentFragment )
  204. .reduce( ( result, filtered ) => {
  205. return result.concat(
  206. filtered.is( 'documentFragment' ) ? Array.from( filtered.getChildren() ) : filtered
  207. );
  208. }, [] );
  209. // Normalize array to model document fragment.
  210. return new ModelDocumentFragment( convertedChildren );
  211. }
  212. /**
  213. * Fired before the first conversion event, at the beginning of view to model conversion process.
  214. *
  215. * @event viewCleanup
  216. * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element}
  217. * viewItem Part of the view to be converted.
  218. */
  219. /**
  220. * Fired when {@link module:engine/view/element~Element} is converted.
  221. *
  222. * `element` is a namespace event for a class of events. Names of actually called events follow this pattern:
  223. * `element:<elementName>` where `elementName` is the name of converted element. This way listeners may listen to
  224. * all elements conversion or to conversion of specific elements.
  225. *
  226. * @event element
  227. * @param {Object} data Object containing conversion input and a placeholder for conversion output and possibly other
  228. * values (see {@link #convert}).
  229. * Keep in mind that this object is shared by reference between all callbacks that will be called.
  230. * This means that callbacks can add their own values if needed,
  231. * and those values will be available in other callbacks.
  232. * @param {module:engine/view/element~Element} data.input Converted element.
  233. * @param {*} data.output The current state of conversion result. Every change to converted element should
  234. * be reflected by setting or modifying this property.
  235. * @param {module:engine/model/schema~SchemaPath} data.context The conversion context.
  236. * @param {module:engine/conversion/viewconsumable~ViewConsumable} consumable Values to consume.
  237. * @param {Object} conversionApi Conversion interface to be used by callback, passed in `ViewConversionDispatcher` constructor.
  238. * Besides of properties passed in constructor, it also has `convertItem` and `convertChildren` methods which are references
  239. * to {@link #_convertItem} and
  240. * {@link ~ViewConversionDispatcher#_convertChildren}. Those methods are needed to convert
  241. * the whole view-tree they were exposed in `conversionApi` for callbacks.
  242. */
  243. /**
  244. * Fired when {@link module:engine/view/text~Text} is converted.
  245. *
  246. * @event text
  247. * @see #event:element
  248. */
  249. /**
  250. * Fired when {@link module:engine/view/documentfragment~DocumentFragment} is converted.
  251. *
  252. * @event documentFragment
  253. * @see #event:element
  254. */
  255. }
  256. mix( ViewConversionDispatcher, EmitterMixin );
  257. // Traverses given model item and searches elements which marks marker range. Found element is removed from
  258. // DocumentFragment but path of this element is stored in a Map which is then returned.
  259. //
  260. // @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/node~Node} modelItem Fragment of model.
  261. // @returns {Map<String, module:engine/model/range~Range>} List of static markers.
  262. function extractMarkersFromModelFragment( modelItem ) {
  263. const markerStamps = new Set();
  264. const markers = new Map();
  265. // Create ModelTreeWalker.
  266. const walker = new ModelTreeWalker( {
  267. startPosition: ModelPosition.createAt( modelItem, 0 ),
  268. ignoreElementEnd: true
  269. } );
  270. // Walk through DocumentFragment and collect marker elements.
  271. for ( const value of walker ) {
  272. // Check if current element is a marker stamp.
  273. if ( value.item.name == '$marker' ) {
  274. markerStamps.add( value.item );
  275. }
  276. }
  277. // Walk through collected marker elements store its path and remove its from the DocumentFragment.
  278. for ( const stamp of markerStamps ) {
  279. const markerName = stamp.getAttribute( 'data-name' );
  280. const currentPosition = ModelPosition.createBefore( stamp );
  281. // When marker of given name is not stored it means that we have found the beginning of the range.
  282. if ( !markers.has( markerName ) ) {
  283. markers.set( markerName, new ModelRange( ModelPosition.createFromPosition( currentPosition ) ) );
  284. // Otherwise is means that we have found end of the marker range.
  285. } else {
  286. markers.get( markerName ).end = ModelPosition.createFromPosition( currentPosition );
  287. }
  288. // Remove marker stamp element from DocumentFragment.
  289. remove( ModelRange.createOn( stamp ) );
  290. }
  291. return markers;
  292. }
  293. /**
  294. * Conversion interface that is registered for given {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher}
  295. * and is passed as one of parameters when {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher dispatcher}
  296. * fires it's events.
  297. *
  298. * `ViewConversionApi` object is built by {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher} constructor.
  299. * The exact list of properties of this object is determined by the object passed to the constructor.
  300. *
  301. * @interface ViewConversionApi
  302. */
  303. /**
  304. * Starts conversion of given item by firing an appropriate event.
  305. *
  306. * Every fired event is passed (as first parameter) an object with `output` property. Every event may set and/or
  307. * modify that property. When all callbacks are done, the final value of `output` property is returned by this method.
  308. * The `output` must be either {@link module:engine/model/node~Node model node} or
  309. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment}.
  310. *
  311. * @method #convertItem
  312. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:element
  313. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:text
  314. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:documentFragment
  315. * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element|module:engine/view/text~Text}
  316. * input Item to convert.
  317. * @param {module:engine/conversion/viewconsumable~ViewConsumable} consumable Values to consume.
  318. * @param {Object} [additionalData] Additional data to be passed in `data` argument when firing `ViewConversionDispatcher`
  319. * events. See also {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:element element event}.
  320. * @returns {*} The result of item conversion, created and modified by callbacks attached to fired event.
  321. */
  322. /**
  323. * Starts conversion of all children of given item by firing appropriate events for all those children.
  324. *
  325. * @method #convertChildren
  326. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:element
  327. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:text
  328. * @fires module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:documentFragment
  329. * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element}
  330. * input Item which children will be converted.
  331. * @param {module:engine/conversion/viewconsumable~ViewConsumable} consumable Values to consume.
  332. * @param {Object} [additionalData] Additional data to be passed in `data` argument when firing `ViewConversionDispatcher`
  333. * events. See also {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#event:element element event}.
  334. * @returns {module:engine/model/documentfragment} Model document fragment containing results of conversion of all children of given item.
  335. */