datacontroller.js 11 KB

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