datacontroller.js 14 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/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/model~Model} model Data model.
  39. * @param {module:engine/dataprocessor/dataprocessor~DataProcessor} [dataProcessor] Data processor which should used by the controller.
  40. */
  41. constructor( model, dataProcessor ) {
  42. /**
  43. * Data model.
  44. *
  45. * @readonly
  46. * @member {module:engine/model/model~Model}
  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( this.model, {
  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.document.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.document.getRoot( rootName );
  166. this.model.enqueueChange( 'transparent', writer => {
  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.document.selection.removeAllRanges();
  170. this.model.document.selection.clearAttributes();
  171. writer.remove( ModelRange.createIn( modelRoot ) );
  172. writer.insert( this.parse( data ), modelRoot );
  173. } );
  174. }
  175. /**
  176. * Returns data parsed by the {@link #processor data processor} and then
  177. * converted by the {@link #viewToModel view to model converters}.
  178. *
  179. * @see #set
  180. * @param {String} data Data to parse.
  181. * @param {String} [context='$root'] Base context in which the view will be converted to the model. See:
  182. * {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#convert}.
  183. * @returns {module:engine/model/documentfragment~DocumentFragment} Parsed data.
  184. */
  185. parse( data, context = '$root' ) {
  186. // data -> view
  187. const viewDocumentFragment = this.processor.toView( data );
  188. // view -> model
  189. return this.toModel( viewDocumentFragment, context );
  190. }
  191. /**
  192. * Returns wrapped by {module:engine/model/documentfragment~DocumentFragment} result of the given
  193. * {@link module:engine/view/element~Element view element} or
  194. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment} converted by the
  195. * {@link #viewToModel view to model converters}.
  196. *
  197. * When marker elements were converted during conversion process then will be set as DocumentFragment's
  198. * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
  199. *
  200. * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment} viewElementOrFragment
  201. * Element or document fragment which content will be converted.
  202. * @param {String} [context='$root'] Base context in which the view will be converted to the model. See:
  203. * {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#convert}.
  204. * @returns {module:engine/model/documentfragment~DocumentFragment} Output document fragment.
  205. */
  206. toModel( viewElementOrFragment, context = '$root' ) {
  207. return this.viewToModel.convert( viewElementOrFragment, { context: [ context ] } );
  208. }
  209. /**
  210. * Removes all event listeners set by the DataController.
  211. */
  212. destroy() {}
  213. /**
  214. * See {@link module:engine/controller/insertcontent.insertContent}.
  215. *
  216. * @fires insertContent
  217. * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
  218. * @param {module:engine/model/selection~Selection} selection Selection into which the content should be inserted.
  219. */
  220. insertContent( content, selection ) {
  221. insertContent( this, content, selection );
  222. }
  223. /**
  224. * See {@link module:engine/controller/deletecontent.deleteContent}.
  225. *
  226. * Note: For the sake of predictability, the resulting selection should always be collapsed.
  227. * In cases where a feature wants to modify deleting behavior so selection isn't collapsed
  228. * (e.g. a table feature may want to keep row selection after pressing <kbd>Backspace</kbd>),
  229. * then that behavior should be implemented in the view's listener. At the same time, the table feature
  230. * will need to modify this method's behavior too, e.g. to "delete contents and then collapse
  231. * the selection inside the last selected cell" or "delete the row and collapse selection somewhere near".
  232. * That needs to be done in order to ensure that other features which use `deleteContent()` will work well with tables.
  233. *
  234. * @fires deleteContent
  235. * @param {module:engine/model/selection~Selection} selection Selection of which the content should be deleted.
  236. * @param {Object} options See {@link module:engine/controller/deletecontent~deleteContent}'s options.
  237. */
  238. deleteContent( selection, options ) {
  239. deleteContent( this, selection, options );
  240. }
  241. /**
  242. * See {@link module:engine/controller/modifyselection.modifySelection}.
  243. *
  244. * @fires modifySelection
  245. * @param {module:engine/model/selection~Selection} selection The selection to modify.
  246. * @param {Object} options See {@link module:engine/controller/modifyselection~modifySelection}'s options.
  247. */
  248. modifySelection( selection, options ) {
  249. modifySelection( this, selection, options );
  250. }
  251. /**
  252. * See {@link module:engine/controller/getselectedcontent.getSelectedContent}.
  253. *
  254. * @fires module:engine/controller/datacontroller~DataController#getSelectedContent
  255. * @param {module:engine/model/selection~Selection} selection The selection of which content will be retrieved.
  256. * @returns {module:engine/model/documentfragment~DocumentFragment} Document fragment holding the clone of the selected content.
  257. */
  258. getSelectedContent( selection ) {
  259. return getSelectedContent( this, selection );
  260. }
  261. /**
  262. * Checks whether given {@link module:engine/model/range~Range range} or {@link module:engine/model/element~Element element}
  263. * has any content.
  264. *
  265. * Content is any text node or element which is registered in {@link module:engine/model/schema~Schema schema}.
  266. *
  267. * @param {module:engine/model/range~Range|module:engine/model/element~Element} rangeOrElement Range or element to check.
  268. * @returns {Boolean}
  269. */
  270. hasContent( rangeOrElement ) {
  271. if ( rangeOrElement instanceof ModelElement ) {
  272. rangeOrElement = ModelRange.createIn( rangeOrElement );
  273. }
  274. if ( rangeOrElement.isCollapsed ) {
  275. return false;
  276. }
  277. for ( const item of rangeOrElement.getItems() ) {
  278. // Remember, `TreeWalker` returns always `textProxy` nodes.
  279. if ( item.is( 'textProxy' ) || this.model.schema.objects.has( item.name ) ) {
  280. return true;
  281. }
  282. }
  283. return false;
  284. }
  285. }
  286. mix( DataController, ObservableMixin );
  287. /**
  288. * Event fired when {@link #insertContent} method is called.
  289. *
  290. * The {@link #insertContent default action of that method} is implemented as a
  291. * listener to this event so it can be fully customized by the features.
  292. *
  293. * @event insertContent
  294. * @param {Array} args The arguments passed to the original method.
  295. */
  296. /**
  297. * Event fired when {@link #deleteContent} method is called.
  298. *
  299. * The {@link #deleteContent default action of that method} is implemented as a
  300. * listener to this event so it can be fully customized by the features.
  301. *
  302. * @event deleteContent
  303. * @param {Array} args The arguments passed to the original method.
  304. */
  305. /**
  306. * Event fired when {@link #modifySelection} method is called.
  307. *
  308. * The {@link #modifySelection default action of that method} is implemented as a
  309. * listener to this event so it can be fully customized by the features.
  310. *
  311. * @event modifySelection
  312. * @param {Array} args The arguments passed to the original method.
  313. */
  314. /**
  315. * Event fired when {@link #getSelectedContent} method is called.
  316. *
  317. * The {@link #getSelectedContent default action of that method} is implemented as a
  318. * listener to this event so it can be fully customized by the features.
  319. *
  320. * @event getSelectedContent
  321. * @param {Array} args The arguments passed to the original method.
  322. */