8
0

datacontroller.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  11. import Mapper from '../conversion/mapper';
  12. import DowncastDispatcher from '../conversion/downcastdispatcher';
  13. import { insertText } from '../conversion/downcasthelpers';
  14. import UpcastDispatcher from '../conversion/upcastdispatcher';
  15. import { convertText, convertToModelFragment } from '../conversion/upcasthelpers';
  16. import ViewDocumentFragment from '../view/documentfragment';
  17. import ViewDocument from '../view/document';
  18. import ViewDowncastWriter from '../view/downcastwriter';
  19. import ModelRange from '../model/range';
  20. /**
  21. * Controller for the data pipeline. The data pipeline controls how data is retrieved from the document
  22. * and set inside it. Hence, the controller features two methods which allow to {@link ~DataController#get get}
  23. * and {@link ~DataController#set set} data of the {@link ~DataController#model model}
  24. * using given:
  25. *
  26. * * {@link module:engine/dataprocessor/dataprocessor~DataProcessor data processor},
  27. * * downcast converters,
  28. * * upcast converters.
  29. *
  30. * @mixes module:utils/observablemixin~ObservableMixin
  31. */
  32. export default class DataController {
  33. /**
  34. * Creates a data controller instance.
  35. *
  36. * @param {module:engine/model/model~Model} model Data model.
  37. * @param {module:engine/dataprocessor/dataprocessor~DataProcessor} [dataProcessor] Data processor that should be used
  38. * by the controller.
  39. */
  40. constructor( model, dataProcessor ) {
  41. /**
  42. * Data model.
  43. *
  44. * @readonly
  45. * @member {module:engine/model/model~Model}
  46. */
  47. this.model = model;
  48. /**
  49. * Data processor used during the conversion.
  50. *
  51. * @readonly
  52. * @member {module:engine/dataProcessor~DataProcessor}
  53. */
  54. this.processor = dataProcessor;
  55. /**
  56. * Mapper used for the conversion. It has no permanent bindings, because they are created when getting data and
  57. * cleared directly after the data are converted. However, the mapper is defined as a class property, because
  58. * it needs to be passed to the `DowncastDispatcher` as a conversion API.
  59. *
  60. * @readonly
  61. * @member {module:engine/conversion/mapper~Mapper}
  62. */
  63. this.mapper = new Mapper();
  64. /**
  65. * Downcast dispatcher used by the {@link #get get method}. Downcast converters should be attached to it.
  66. *
  67. * @readonly
  68. * @member {module:engine/conversion/downcastdispatcher~DowncastDispatcher}
  69. */
  70. this.downcastDispatcher = new DowncastDispatcher( {
  71. mapper: this.mapper
  72. } );
  73. this.downcastDispatcher.on( 'insert:$text', insertText(), { priority: 'lowest' } );
  74. /**
  75. * Upcast dispatcher used by the {@link #set set method}. Upcast converters should be attached to it.
  76. *
  77. * @readonly
  78. * @member {module:engine/conversion/upcastdispatcher~UpcastDispatcher}
  79. */
  80. this.upcastDispatcher = new UpcastDispatcher( {
  81. schema: model.schema
  82. } );
  83. // Define default converters for text and elements.
  84. //
  85. // Note that if there is no default converter for the element it will be skipped, for instance `<b>foo</b>` will be
  86. // converted to nothing. We add `convertToModelFragment` as a last converter so it converts children of that
  87. // element to the document fragment so `<b>foo</b>` will be converted to `foo` if there is no converter for `<b>`.
  88. this.upcastDispatcher.on( 'text', convertText(), { priority: 'lowest' } );
  89. this.upcastDispatcher.on( 'element', convertToModelFragment(), { priority: 'lowest' } );
  90. this.upcastDispatcher.on( 'documentFragment', convertToModelFragment(), { priority: 'lowest' } );
  91. this.decorate( 'init' );
  92. }
  93. /**
  94. * Returns the model's data converted by downcast dispatchers attached to {@link #downcastDispatcher} and
  95. * formatted by the {@link #processor data processor}.
  96. *
  97. * @param {String} [rootName='main'] Root name.
  98. * @returns {String} Output data.
  99. */
  100. get( rootName = 'main' ) {
  101. // Get model range.
  102. return this.stringify( this.model.document.getRoot( rootName ) );
  103. }
  104. /**
  105. * Returns the content of the given {@link module:engine/model/element~Element model's element} or
  106. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast converters
  107. * attached to {@link #downcastDispatcher} and formatted by the {@link #processor data processor}.
  108. *
  109. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
  110. * Element whose content will be stringified.
  111. * @returns {String} Output data.
  112. */
  113. stringify( modelElementOrFragment ) {
  114. // Model -> view.
  115. const viewDocumentFragment = this.toView( modelElementOrFragment );
  116. // View -> data.
  117. return this.processor.toData( viewDocumentFragment );
  118. }
  119. /**
  120. * Returns the content of the given {@link module:engine/model/element~Element model element} or
  121. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast
  122. * converters attached to {@link #downcastDispatcher} to a
  123. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}.
  124. *
  125. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
  126. * Element or document fragment whose content will be converted.
  127. * @returns {module:engine/view/documentfragment~DocumentFragment} Output view DocumentFragment.
  128. */
  129. toView( modelElementOrFragment ) {
  130. // Clear bindings so the call to this method gives correct results.
  131. this.mapper.clearBindings();
  132. // First, convert elements.
  133. const modelRange = ModelRange._createIn( modelElementOrFragment );
  134. const viewDocumentFragment = new ViewDocumentFragment();
  135. // Create separate ViewDowncastWriter just for data conversion purposes.
  136. // We have no view controller and rendering do DOM in DataController so view.change() block is not used here.
  137. const viewWriter = new ViewDowncastWriter( new ViewDocument() );
  138. this.mapper.bindElements( modelElementOrFragment, viewDocumentFragment );
  139. this.downcastDispatcher.convertInsert( modelRange, viewWriter );
  140. if ( !modelElementOrFragment.is( 'documentFragment' ) ) {
  141. // Then, if a document element is converted, convert markers.
  142. // From all document markers, get those, which "intersect" with the converter element.
  143. const markers = _getMarkersRelativeToElement( modelElementOrFragment );
  144. for ( const [ name, range ] of markers ) {
  145. this.downcastDispatcher.convertMarkerAdd( name, range, viewWriter );
  146. }
  147. }
  148. return viewDocumentFragment;
  149. }
  150. /**
  151. * Sets initial input data parsed by the {@link #processor data processor} and
  152. * converted by the {@link #upcastDispatcher view-to-model converters}.
  153. * Initial data can be set only to document that {@link module:engine/model/document~Document#version} is equal 0.
  154. *
  155. * **Note** This method is {@link module:utils/observablemixin~ObservableMixin#decorate decorated} which is
  156. * used by e.g. collaborative editing plugin that syncs remote data on init.
  157. *
  158. * @fires init
  159. * @param {String} data Input data.
  160. * @param {String} [rootName='main'] Root name.
  161. * @returns {Promise} Promise that is resolved after the data is set on the editor.
  162. */
  163. init( data, rootName = 'main' ) {
  164. if ( this.model.document.version ) {
  165. /**
  166. * Cannot set initial data to not empty {@link module:engine/model/document~Document}.
  167. * Initial data should be set once, during {@link module:core/editor/editor~Editor} initialization,
  168. * when the {@link module:engine/model/document~Document#version} is equal 0.
  169. *
  170. * @error datacontroller-init-document-not-empty
  171. */
  172. throw new CKEditorError( 'datacontroller-init-document-not-empty: Trying to set initial data to not empty document.' );
  173. }
  174. const modelRoot = this.model.document.getRoot( rootName );
  175. this.model.enqueueChange( 'transparent', writer => {
  176. writer.insert( this.parse( data, modelRoot ), modelRoot, 0 );
  177. } );
  178. return Promise.resolve();
  179. }
  180. /**
  181. * Sets input data parsed by the {@link #processor data processor} and
  182. * converted by the {@link #upcastDispatcher view-to-model converters}.
  183. * This method can be used any time to replace existing editor data by the new one without clearing the
  184. * {@link module:engine/model/document~Document#history document history}.
  185. *
  186. * This method also creates a batch with all the changes applied. If all you need is to parse data, use
  187. * the {@link #parse} method.
  188. *
  189. * @param {String} data Input data.
  190. * @param {String} [rootName='main'] Root name.
  191. */
  192. set( data, rootName = 'main' ) {
  193. // Save to model.
  194. const modelRoot = this.model.document.getRoot( rootName );
  195. this.model.enqueueChange( 'transparent', writer => {
  196. writer.setSelection( null );
  197. writer.removeSelectionAttribute( this.model.document.selection.getAttributeKeys() );
  198. writer.remove( writer.createRangeIn( modelRoot ) );
  199. writer.insert( this.parse( data, modelRoot ), modelRoot, 0 );
  200. } );
  201. }
  202. /**
  203. * Returns the data parsed by the {@link #processor data processor} and then converted by upcast converters
  204. * attached to the {@link #upcastDispatcher}.
  205. *
  206. * @see #set
  207. * @param {String} data Data to parse.
  208. * @param {module:engine/model/schema~SchemaContextDefinition} [context='$root'] Base context in which the view will
  209. * be converted to the model. See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
  210. * @returns {module:engine/model/documentfragment~DocumentFragment} Parsed data.
  211. */
  212. parse( data, context = '$root' ) {
  213. // data -> view
  214. const viewDocumentFragment = this.processor.toView( data );
  215. // view -> model
  216. return this.toModel( viewDocumentFragment, context );
  217. }
  218. /**
  219. * Returns the result of the given {@link module:engine/view/element~Element view element} or
  220. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment} converted by the
  221. * {@link #upcastDispatcher view-to-model converters}, wrapped by {@link module:engine/model/documentfragment~DocumentFragment}.
  222. *
  223. * When marker elements were converted during the conversion process, it will be set as a document fragment's
  224. * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
  225. *
  226. * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment} viewElementOrFragment
  227. * Element or document fragment whose content will be converted.
  228. * @param {module:engine/model/schema~SchemaContextDefinition} [context='$root'] Base context in which the view will
  229. * be converted to the model. See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
  230. * @returns {module:engine/model/documentfragment~DocumentFragment} Output document fragment.
  231. */
  232. toModel( viewElementOrFragment, context = '$root' ) {
  233. return this.model.change( writer => {
  234. return this.upcastDispatcher.convert( viewElementOrFragment, writer, context );
  235. } );
  236. }
  237. /**
  238. * Removes all event listeners set by the DataController.
  239. */
  240. destroy() {}
  241. /**
  242. * Event fired by decorated {@link #init} method.
  243. * See {@link module:utils/observablemixin~ObservableMixin.decorate} for more information and samples.
  244. *
  245. * @event init
  246. */
  247. }
  248. mix( DataController, ObservableMixin );
  249. // Helper function for downcast conversion.
  250. //
  251. // Takes a document element (element that is added to a model document) and checks which markers are inside it
  252. // and which markers are containing it. If the marker is intersecting with element, the intersection is returned.
  253. function _getMarkersRelativeToElement( element ) {
  254. const result = [];
  255. const doc = element.root.document;
  256. if ( !doc ) {
  257. return [];
  258. }
  259. const elementRange = ModelRange._createIn( element );
  260. for ( const marker of doc.model.markers ) {
  261. const intersection = elementRange.getIntersection( marker.getRange() );
  262. if ( intersection ) {
  263. result.push( [ marker.name, intersection ] );
  264. }
  265. }
  266. return result;
  267. }