datacontroller.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /**
  2. * @license Copyright (c) 2003-2018, 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. /**
  18. * Controller for the data pipeline. The data pipeline controls how data is retrieved from the document
  19. * and set inside it. Hence, the controller features two methods which allow to {@link ~DataController#get get}
  20. * and {@link ~DataController#set set} data of the {@link ~DataController#model model}
  21. * using the given:
  22. *
  23. * * {@link module:engine/dataprocessor/dataprocessor~DataProcessor data processor},
  24. * * {@link module:engine/conversion/modelconversiondispatcher~ModelConversionDispatcher model to view} and
  25. * * {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher view to model} converters.
  26. *
  27. * @mixes module:utils/observablemixin~ObservableMixin
  28. */
  29. export default class DataController {
  30. /**
  31. * Creates a data controller instance.
  32. *
  33. * @param {module:engine/model/model~Model} model Data model.
  34. * @param {module:engine/dataprocessor/dataprocessor~DataProcessor} [dataProcessor] Data processor that should be used
  35. * by the controller.
  36. */
  37. constructor( model, dataProcessor ) {
  38. /**
  39. * Data model.
  40. *
  41. * @readonly
  42. * @member {module:engine/model/model~Model}
  43. */
  44. this.model = model;
  45. /**
  46. * Data processor used during the conversion.
  47. *
  48. * @readonly
  49. * @member {module:engine/dataProcessor~DataProcessor}
  50. */
  51. this.processor = dataProcessor;
  52. /**
  53. * Mapper used for the conversion. It has no permanent bindings, because they are created when getting data and
  54. * cleared directly after the data are converted. However, the mapper is defined as a class property, because
  55. * it needs to be passed to the `ModelConversionDispatcher` as a conversion API.
  56. *
  57. * @member {module:engine/conversion/mapper~Mapper}
  58. */
  59. this.mapper = new Mapper();
  60. /**
  61. * Model-to-view conversion dispatcher used by the {@link #get get method}.
  62. * To attach the model-to-view converter to the data pipeline you need to add a listener to this property:
  63. *
  64. * data.modelToView( 'insert:$element', customInsertConverter );
  65. *
  66. * Or use {@link module:engine/conversion/buildmodelconverter~ModelConverterBuilder}:
  67. *
  68. * buildModelConverter().for( data.modelToView ).fromAttribute( 'bold' ).toElement( 'b' );
  69. *
  70. * @readonly
  71. * @member {module:engine/conversion/modelconversiondispatcher~ModelConversionDispatcher}
  72. */
  73. this.modelToView = new ModelConversionDispatcher( this.model, {
  74. mapper: this.mapper
  75. } );
  76. this.modelToView.on( 'insert:$text', insertText(), { priority: 'lowest' } );
  77. /**
  78. * View-to-model conversion dispatcher used by the {@link #set set method}.
  79. * To attach the view-to-model converter to the data pipeline you need to add a listener to this property:
  80. *
  81. * data.viewToModel( 'element', customElementConverter );
  82. *
  83. * Or use {@link module:engine/conversion/buildviewconverter~ViewConverterBuilder}:
  84. *
  85. * buildViewConverter().for( data.viewToModel ).fromElement( 'b' ).toAttribute( 'bold', 'true' );
  86. *
  87. * @readonly
  88. * @member {module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher}
  89. */
  90. this.viewToModel = new ViewConversionDispatcher( this.model, {
  91. schema: model.schema
  92. } );
  93. // Define default converters for text and elements.
  94. //
  95. // Note that if there is no default converter for the element it will be skipped, for instance `<b>foo</b>` will be
  96. // converted to nothing. We add `convertToModelFragment` as a last converter so it converts children of that
  97. // element to the document fragment so `<b>foo</b>` will be converted to `foo` if there is no converter for `<b>`.
  98. this.viewToModel.on( 'text', convertText(), { priority: 'lowest' } );
  99. this.viewToModel.on( 'element', convertToModelFragment(), { priority: 'lowest' } );
  100. this.viewToModel.on( 'documentFragment', convertToModelFragment(), { priority: 'lowest' } );
  101. }
  102. /**
  103. * Returns the model's data converted by the {@link #modelToView model-to-view converters} and
  104. * formatted by the {@link #processor data processor}.
  105. *
  106. * @param {String} [rootName='main'] Root name.
  107. * @returns {String} Output data.
  108. */
  109. get( rootName = 'main' ) {
  110. // Get model range.
  111. return this.stringify( this.model.document.getRoot( rootName ) );
  112. }
  113. /**
  114. * Returns the content of the given {@link module:engine/model/element~Element model's element} or
  115. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the
  116. * {@link #modelToView model-to-view converters} and formatted by the
  117. * {@link #processor data processor}.
  118. *
  119. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
  120. * Element whose content will be stringified.
  121. * @returns {String} Output data.
  122. */
  123. stringify( modelElementOrFragment ) {
  124. // Model -> view.
  125. const viewDocumentFragment = this.toView( modelElementOrFragment );
  126. // View -> data.
  127. return this.processor.toData( viewDocumentFragment );
  128. }
  129. /**
  130. * Returns the content of the given {@link module:engine/model/element~Element model element} or
  131. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the
  132. * {@link #modelToView model-to-view converters} to a
  133. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}.
  134. *
  135. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
  136. * Element or document fragment whose content will be converted.
  137. * @returns {module:engine/view/documentfragment~DocumentFragment} Output view DocumentFragment.
  138. */
  139. toView( modelElementOrFragment ) {
  140. // First, convert elements.
  141. const modelRange = ModelRange.createIn( modelElementOrFragment );
  142. const viewDocumentFragment = new ViewDocumentFragment();
  143. this.mapper.bindElements( modelElementOrFragment, viewDocumentFragment );
  144. this.modelToView.convertInsert( modelRange );
  145. if ( !modelElementOrFragment.is( 'documentFragment' ) ) {
  146. // Then, if a document element is converted, convert markers.
  147. // From all document markers, get those, which "intersect" with the converter element.
  148. const markers = _getMarkersRelativeToElement( modelElementOrFragment );
  149. for ( const [ name, range ] of markers ) {
  150. this.modelToView.convertMarkerAdd( name, range );
  151. }
  152. }
  153. // Clear bindings so the next call to this method gives correct results.
  154. this.mapper.clearBindings();
  155. return viewDocumentFragment;
  156. }
  157. /**
  158. * Sets input data parsed by the {@link #processor data processor} and
  159. * converted by the {@link #viewToModel view-to-model converters}.
  160. *
  161. * This method also creates a batch with all the changes applied. If all you need is to parse data, use
  162. * the {@link #parse} method.
  163. *
  164. * @param {String} data Input data.
  165. * @param {String} [rootName='main'] Root name.
  166. */
  167. set( data, rootName = 'main' ) {
  168. // Save to model.
  169. const modelRoot = this.model.document.getRoot( rootName );
  170. this.model.enqueueChange( 'transparent', writer => {
  171. // Clearing selection is a workaround for ticket #569 (LiveRange loses position after removing data from document).
  172. // After fixing it this code should be removed.
  173. writer.setSelection( null );
  174. writer.removeSelectionAttribute( this.model.document.selection.getAttributeKeys() );
  175. writer.remove( ModelRange.createIn( modelRoot ) );
  176. writer.insert( this.parse( data ), modelRoot );
  177. } );
  178. }
  179. /**
  180. * Returns the data parsed by the {@link #processor data processor} and then
  181. * converted by the {@link #viewToModel view-to-model converters}.
  182. *
  183. * @see #set
  184. * @param {String} data Data to parse.
  185. * @param {module:engine/model/schema~SchemaContextDefinition} [context=['$root']] Base context in which the view will
  186. * be converted to the model. See: {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#convert}.
  187. * @returns {module:engine/model/documentfragment~DocumentFragment} Parsed data.
  188. */
  189. parse( data, context = [ '$root' ] ) {
  190. // data -> view
  191. const viewDocumentFragment = this.processor.toView( data );
  192. // view -> model
  193. return this.toModel( viewDocumentFragment, context );
  194. }
  195. /**
  196. * Returns the result of the given {@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}, wrapped by {module:engine/model/documentfragment~DocumentFragment}.
  199. *
  200. * When marker elements were converted during the conversion process, it will be set as a document fragment'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 whose content will be converted.
  205. * @param {module:engine/model/schema~SchemaContextDefinition} [context=['$root']] Base context in which the view will
  206. * be converted to the model. See: {@link module:engine/conversion/viewconversiondispatcher~ViewConversionDispatcher#convert}.
  207. * @returns {module:engine/model/documentfragment~DocumentFragment} Output document fragment.
  208. */
  209. toModel( viewElementOrFragment, context = [ '$root' ] ) {
  210. return this.viewToModel.convert( viewElementOrFragment, context );
  211. }
  212. /**
  213. * Removes all event listeners set by the DataController.
  214. */
  215. destroy() {}
  216. }
  217. mix( DataController, ObservableMixin );
  218. // Helper function for converting part of a model to view.
  219. //
  220. // Takes a document element (element that is added to a model document) and checks which markers are inside it
  221. // and which markers are containing it. If the marker is intersecting with element, the intersection is returned.
  222. function _getMarkersRelativeToElement( element ) {
  223. const result = [];
  224. const doc = element.root.document;
  225. if ( !doc ) {
  226. return [];
  227. }
  228. const elementRange = ModelRange.createIn( element );
  229. for ( const marker of doc.model.markers ) {
  230. const intersection = elementRange.getIntersection( marker.getRange() );
  231. if ( intersection ) {
  232. result.push( [ marker.name, intersection ] );
  233. }
  234. }
  235. return result;
  236. }