datacontroller.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/controller/datacontroller
  7. */
  8. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  9. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  10. import Mapper from '../conversion/mapper';
  11. import ModelConversionDispatcher from '../conversion/modelconversiondispatcher';
  12. import { insertText } from '../conversion/model-to-view-converters';
  13. import ViewConversionDispatcher from '../conversion/viewconversiondispatcher';
  14. import { convertText, convertToModelFragment } from '../conversion/view-to-model-converters';
  15. import ViewDocumentFragment from '../view/documentfragment';
  16. import ModelRange from '../model/range';
  17. import ModelPosition from '../model/position';
  18. import ModelDocumentFragment from '../model/documentfragment';
  19. import insertContent from './insertcontent';
  20. import deleteContent from './deletecontent';
  21. import modifySelection from './modifyselection';
  22. import getSelectedContent from './getselectedcontent';
  23. /**
  24. * Controller for the data pipeline. The data pipeline controls how data is retrieved from the document
  25. * and set inside it. Hence, the controller features two methods which allow to {@link ~DataController#get get}
  26. * and {@link ~DataController#set set} data of the {@link ~DataController#model model}
  27. * using given:
  28. *
  29. * * {@link module:engine/dataprocessor/dataprocessor~DataProcessor data processor},
  30. * * {@link module:engine/conversion/modelconversiondispatcher~ModelConversionDispatcher model to view} and
  31. * * {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher view to model} converters.
  32. *
  33. * @mixes module:utils/emittermixin~EmitterMixin
  34. */
  35. export default class DataController {
  36. /**
  37. * Creates data controller instance.
  38. *
  39. * @param {module:engine/model/document~Document} model Document model.
  40. * @param {module:engine/dataprocessor/dataprocessor~DataProcessor} [dataProcessor] Data processor which should used by the controller.
  41. */
  42. constructor( model, dataProcessor ) {
  43. /**
  44. * Document model.
  45. *
  46. * @readonly
  47. * @member {module:engine/model/document~Document}
  48. */
  49. this.model = model;
  50. /**
  51. * Data processor used during the conversion.
  52. *
  53. * @readonly
  54. * @member {module:engine/dataProcessor~DataProcessor}
  55. */
  56. this.processor = dataProcessor;
  57. /**
  58. * Mapper used for the conversion. It has no permanent bindings, because they are created when getting data and
  59. * cleared directly after data are converted. However, the mapper is defined as class property, because
  60. * it needs to be passed to the `ModelConversionDispatcher` as a conversion API.
  61. *
  62. * @member {module:engine/conversion/mapper~Mapper}
  63. */
  64. this.mapper = new Mapper();
  65. /**
  66. * Model to view conversion dispatcher used by the {@link #get get method}.
  67. * To attach model to view converter to the data pipeline you need to add lister to this property:
  68. *
  69. * data.modelToView( 'insert:$element', customInsertConverter );
  70. *
  71. * Or use {@link module:engine/conversion/buildmodelconverter~ModelConverterBuilder}:
  72. *
  73. * buildModelConverter().for( data.modelToView ).fromAttribute( 'bold' ).toElement( 'b' );
  74. *
  75. * @readonly
  76. * @member {module:engine/conversion/modelconversiondispatcher~ModelConversionDispatcher}
  77. */
  78. this.modelToView = new ModelConversionDispatcher( this.model, {
  79. mapper: this.mapper
  80. } );
  81. this.modelToView.on( 'insert:$text', insertText(), { priority: 'lowest' } );
  82. /**
  83. * View to model conversion dispatcher used by the {@link #set set method}.
  84. * To attach view to model converter to the data pipeline you need to add lister to this property:
  85. *
  86. * data.viewToModel( 'element', customElementConverter );
  87. *
  88. * Or use {@link module:engine/conversion/buildviewconverter~ViewConverterBuilder}:
  89. *
  90. * buildViewConverter().for( data.viewToModel ).fromElement( 'b' ).toAttribute( 'bold', 'true' );
  91. *
  92. * @readonly
  93. * @member {module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher}
  94. */
  95. this.viewToModel = new ViewConversionDispatcher( {
  96. schema: model.schema
  97. } );
  98. // Define default converters for text and elements.
  99. //
  100. // Note that if there is no default converter for the element it will be skipped, for instance `<b>foo</b>` will be
  101. // converted to nothing. We add `convertToModelFragment` as a last converter so it converts children of that
  102. // element to the document fragment so `<b>foo</b>` will be converted to `foo` if there is no converter for `<b>`.
  103. this.viewToModel.on( 'text', convertText(), { priority: 'lowest' } );
  104. this.viewToModel.on( 'element', convertToModelFragment(), { priority: 'lowest' } );
  105. this.viewToModel.on( 'documentFragment', convertToModelFragment(), { priority: 'lowest' } );
  106. this.on( 'insertContent', ( evt, data ) => insertContent( this, data.content, data.selection, data.batch ) );
  107. this.on( 'deleteContent', ( evt, data ) => deleteContent( data.selection, data.batch, data.options ) );
  108. this.on( 'modifySelection', ( evt, data ) => modifySelection( this, data.selection, data.options ) );
  109. this.on( 'getSelectedContent', ( evt, data ) => {
  110. data.content = getSelectedContent( data.selection );
  111. } );
  112. }
  113. /**
  114. * Returns model's data converted by the {@link #modelToView model to view converters} and
  115. * formatted by the {@link #processor data processor}.
  116. *
  117. * @param {String} [rootName='main'] Root name.
  118. * @returns {String} Output data.
  119. */
  120. get( rootName = 'main' ) {
  121. // Get model range.
  122. return this.stringify( this.model.getRoot( rootName ) );
  123. }
  124. /**
  125. * Returns the content of the given {@link module:engine/model/element~Element model's element} or
  126. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the
  127. * {@link #modelToView model to view converters} and formatted by the
  128. * {@link #processor data processor}.
  129. *
  130. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
  131. * Element which content will be stringified.
  132. * @returns {String} Output data.
  133. */
  134. stringify( modelElementOrFragment ) {
  135. // model -> view
  136. const viewDocumentFragment = this.toView( modelElementOrFragment );
  137. // view -> data
  138. return this.processor.toData( viewDocumentFragment );
  139. }
  140. /**
  141. * Returns the content of the given {@link module:engine/model/element~Element model element} or
  142. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the
  143. * {@link #modelToView model to view converters} to a
  144. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}.
  145. *
  146. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
  147. * Element or document fragment which content will be converted.
  148. * @returns {module:engine/view/documentfragment~DocumentFragment} Output view DocumentFragment.
  149. */
  150. toView( modelElementOrFragment ) {
  151. const modelRange = ModelRange.createIn( modelElementOrFragment );
  152. const viewDocumentFragment = new ViewDocumentFragment();
  153. this.mapper.bindElements( modelElementOrFragment, viewDocumentFragment );
  154. this.modelToView.convertInsertion( modelRange );
  155. this.mapper.clearBindings();
  156. return viewDocumentFragment;
  157. }
  158. /**
  159. * Sets input data parsed by the {@link #processor data processor} and
  160. * converted by the {@link #viewToModel view to model converters}.
  161. *
  162. * This method also creates a batch with all the changes applied. If all you need is to parse data use
  163. * the {@link #parse} method.
  164. *
  165. * @param {String} data Input data.
  166. * @param {String} [rootName='main'] Root name.
  167. */
  168. set( data, rootName = 'main' ) {
  169. // Save to model.
  170. const modelRoot = this.model.getRoot( rootName );
  171. this.model.enqueueChanges( () => {
  172. // Clearing selection is a workaround for ticket #569 (LiveRange loses position after removing data from document).
  173. // After fixing it this code should be removed.
  174. this.model.selection.removeAllRanges();
  175. this.model.selection.clearAttributes();
  176. // Initial batch should be ignored by features like undo, etc.
  177. this.model.batch( 'transparent' )
  178. .remove( ModelRange.createIn( modelRoot ) )
  179. .insert( ModelPosition.createAt( modelRoot, 0 ), this.parse( data ) );
  180. } );
  181. }
  182. /**
  183. * Returns data parsed by the {@link #processor data processor} and then
  184. * converted by the {@link #viewToModel view to model converters}.
  185. *
  186. * @see #set
  187. * @param {String} data Data to parse.
  188. * @param {String} [context='$root'] Base context in which the view will be converted to the model. See:
  189. * {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#convert}.
  190. * @returns {engine/model/documentfragment~DocumentFragment} Model DocumentFragment as a result of view parsing.
  191. */
  192. parse( data, context = '$root' ) {
  193. // data -> view
  194. const viewDocumentFragment = this.processor.toView( data );
  195. // view -> model
  196. return this.toModel( viewDocumentFragment, context );
  197. }
  198. /**
  199. * Returns wrapped by {engine/model/documentfragment~DocumentFragment} result of the given
  200. * {@link module:engine/view/element~Element view element} or
  201. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment} converted by the
  202. * {@link #viewToModel view to model converters}.
  203. *
  204. * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment} viewElementOrFragment
  205. * Element or document fragment which content will be converted.
  206. * @param {String} [context='$root'] Base context in which the view will be converted to the model. See:
  207. * {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#convert}.
  208. * @returns {engine/model/documentfragment~DocumentFragment} View item converted to Model DocumentFragment.
  209. */
  210. toModel( viewElementOrFragment, context = '$root' ) {
  211. const { conversionResult, markers } = this.viewToModel.convert( viewElementOrFragment, { context: [ context ] } );
  212. let documentFragment;
  213. if ( !conversionResult.is( 'documentFragment' ) ) {
  214. documentFragment = new ModelDocumentFragment( [ conversionResult ] );
  215. } else {
  216. documentFragment = conversionResult;
  217. }
  218. // Set markers to the documentFragment.
  219. for ( const marker of markers ) {
  220. documentFragment.markers.set( marker[ 0 ], marker[ 1 ] );
  221. }
  222. return documentFragment;
  223. }
  224. /**
  225. * Removes all event listeners set by the DataController.
  226. */
  227. destroy() {}
  228. /**
  229. * See {@link module:engine/controller/insertcontent~insertContent}.
  230. *
  231. * @fires insertContent
  232. * @param {module:engine/model/documentfragment~DocumentFragment} content The content to insert.
  233. * @param {module:engine/model/selection~Selection} selection Selection into which the content should be inserted.
  234. * @param {module:engine/model/batch~Batch} [batch] Batch to which deltas will be added. If not specified, then
  235. * changes will be added to a new batch.
  236. */
  237. insertContent( content, selection, batch ) {
  238. this.fire( 'insertContent', { content, selection, batch } );
  239. }
  240. /**
  241. * See {@link module:engine/controller/deletecontent~deleteContent}.
  242. *
  243. * Note: For the sake of predictability, the resulting selection should always be collapsed.
  244. * In cases where a feature wants to modify deleting behavior so selection isn't collapsed
  245. * (e.g. a table feature may want to keep row selection after pressing <kbd>Backspace</kbd>),
  246. * then that behavior should be implemented in the view's listener. At the same time, the table feature
  247. * will need to modify this method's behavior too, e.g. to "delete contents and then collapse
  248. * the selection inside the last selected cell" or "delete the row and collapse selection somewhere near".
  249. * That needs to be done in order to ensure that other features which use `deleteContent()` will work well with tables.
  250. *
  251. * @fires deleteContent
  252. * @param {module:engine/model/selection~Selection} selection Selection of which the content should be deleted.
  253. * @param {module:engine/model/batch~Batch} batch Batch to which deltas will be added.
  254. * @param {Object} options See {@link module:engine/controller/deletecontent~deleteContent}'s options.
  255. */
  256. deleteContent( selection, batch, options ) {
  257. this.fire( 'deleteContent', { batch, selection, options } );
  258. }
  259. /**
  260. * See {@link module:engine/controller/modifyselection~modifySelection}.
  261. *
  262. * @fires modifySelection
  263. * @param {module:engine/model/selection~Selection} selection The selection to modify.
  264. * @param {Object} options See {@link module:engine/controller/modifyselection~modifySelection}'s options.
  265. */
  266. modifySelection( selection, options ) {
  267. this.fire( 'modifySelection', { selection, options } );
  268. }
  269. /**
  270. * See {@link module:engine/controller/getselectedcontent~getSelectedContent}.
  271. *
  272. * @fires module:engine/controller/datacontroller~DataController#getSelectedContent
  273. * @param {module:engine/model/selection~Selection} selection The selection of which content will be retrieved.
  274. * @returns {module:engine/model/documentfragment~DocumentFragment} Document fragment holding the clone of the selected content.
  275. */
  276. getSelectedContent( selection ) {
  277. const evtData = { selection };
  278. this.fire( 'getSelectedContent', evtData );
  279. return evtData.content;
  280. }
  281. }
  282. mix( DataController, EmitterMixin );
  283. /**
  284. * Result of parsing view to model.
  285. *
  286. * @typedef {Object} {engine/controller/datacontroller~ParsedModelData}
  287. * @property {module:engine/model/documentfragment~DocumentFragment|module:engine/model/node~Node} modelItem
  288. * Fragment of parsed model.
  289. * @property {Map<String, module:engine/model/range~Range>} markers List of parsed marker stamps.
  290. */
  291. /**
  292. * Event fired when {@link #insertContent} method is called.
  293. * The {@link #insertContent default action of that method} is implemented as a
  294. * listener to this event so it can be fully customized by the features.
  295. *
  296. * @event insertContent
  297. * @param {Object} data
  298. * @param {module:engine/view/documentfragment~DocumentFragment} data.content The content to insert.
  299. * @param {module:engine/model/selection~Selection} data.selection Selection into which the content should be inserted.
  300. * @param {module:engine/model/batch~Batch} [data.batch] Batch to which deltas will be added.
  301. */
  302. /**
  303. * Event fired when {@link #deleteContent} method is called.
  304. * The {@link module:engine/controller/deletecontent~deleteContent default action of that method} is implemented as a
  305. * listener to this event so it can be fully customized by the features.
  306. *
  307. * @event deleteContent
  308. * @param {Object} data
  309. * @param {module:engine/model/batch~Batch} data.batch
  310. * @param {module:engine/model/selection~Selection} data.selection
  311. * @param {Object} data.options See {@link module:engine/controller/deletecontent~deleteContent}'s options.
  312. */
  313. /**
  314. * Event fired when {@link #modifySelection} method is called.
  315. * The {@link module:engine/controller/modifyselection~modifySelection default action of that method} is implemented as a
  316. * listener to this event so it can be fully customized by the features.
  317. *
  318. * @event modifySelection
  319. * @param {Object} data
  320. * @param {module:engine/model/selection~Selection} data.selection
  321. * @param {Object} data.options See {@link module:engine/controller/modifyselection~modifySelection}'s options.
  322. */
  323. /**
  324. * Event fired when {@link module:engine/controller/datacontroller~DataController#getSelectedContent} method is called.
  325. * The {@link module:engine/controller/getselectedcontent~getSelectedContent default action of that method} is implemented as a
  326. * listener to this event so it can be fully customized by the features.
  327. *
  328. * @event module:engine/controller/datacontroller~DataController#getSelectedContent
  329. * @param {Object} data
  330. * @param {module:engine/model/selection~Selection} data.selection
  331. * @param {module:engine/model/documentfragment~DocumentFragment} data.content The document fragment to return
  332. * (holding a clone of the selected content).
  333. */