datacontroller.js 15 KB

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