8
0

datacontroller.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /**
  2. * @license Copyright (c) 2003-2019, 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~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. // Fire `ready` event when initialisation has completed. Such low level listener gives possibility
  93. // to plug into initialisation pipeline without interrupting the initialisation flow.
  94. this.on( 'init', () => {
  95. this.fire( 'ready' );
  96. }, { priority: 'lowest' } );
  97. }
  98. /**
  99. * Returns the model's data converted by downcast dispatchers attached to {@link #downcastDispatcher} and
  100. * formatted by the {@link #processor data processor}.
  101. *
  102. * @param {Object} [options]
  103. * @param {String} [options.rootName='main'] Root name.
  104. * @param {String} [options.trim='empty'] Whether returned data should be trimmed. This option is set to `empty` by default,
  105. * which means whenever editor content is considered empty, an empty string will be returned. To turn off trimming completely
  106. * use `'none'`. In such cases exact content will be returned (for example `<p>&nbsp;</p>` for an empty editor).
  107. * @returns {String} Output data.
  108. */
  109. get( options ) {
  110. const { rootName = 'main', trim = 'empty' } = options || {};
  111. if ( !this._checkIfRootsExists( [ rootName ] ) ) {
  112. /**
  113. * Cannot get data from a non-existing root. This error is thrown when {@link #get DataController#get() method}
  114. * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
  115. * calling {@link #get} like:
  116. *
  117. * data.get( 'root2' );
  118. *
  119. * will throw this error.
  120. *
  121. * @error datacontroller-get-non-existent-root
  122. */
  123. throw new CKEditorError( 'datacontroller-get-non-existent-root: Attempting to get data from a non-existing root.' );
  124. }
  125. const root = this.model.document.getRoot( rootName );
  126. if ( trim === 'empty' && !this.model.hasContent( root, { ignoreWhitespaces: true } ) ) {
  127. return '';
  128. }
  129. return this.stringify( root );
  130. }
  131. /**
  132. * Returns the content of the given {@link module:engine/model/element~Element model's element} or
  133. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast converters
  134. * attached to {@link #downcastDispatcher} and formatted by the {@link #processor data processor}.
  135. *
  136. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
  137. * Element whose content will be stringified.
  138. * @returns {String} Output data.
  139. */
  140. stringify( modelElementOrFragment ) {
  141. // Model -> view.
  142. const viewDocumentFragment = this.toView( modelElementOrFragment );
  143. // View -> data.
  144. return this.processor.toData( viewDocumentFragment );
  145. }
  146. /**
  147. * Returns the content of the given {@link module:engine/model/element~Element model element} or
  148. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast
  149. * converters attached to {@link #downcastDispatcher} to a
  150. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}.
  151. *
  152. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} modelElementOrFragment
  153. * Element or document fragment whose content will be converted.
  154. * @returns {module:engine/view/documentfragment~DocumentFragment} Output view DocumentFragment.
  155. */
  156. toView( modelElementOrFragment ) {
  157. // Clear bindings so the call to this method gives correct results.
  158. this.mapper.clearBindings();
  159. // First, convert elements.
  160. const modelRange = ModelRange._createIn( modelElementOrFragment );
  161. const viewDocumentFragment = new ViewDocumentFragment();
  162. // Create separate ViewDowncastWriter just for data conversion purposes.
  163. // We have no view controller and rendering do DOM in DataController so view.change() block is not used here.
  164. const viewWriter = new ViewDowncastWriter( new ViewDocument() );
  165. this.mapper.bindElements( modelElementOrFragment, viewDocumentFragment );
  166. this.downcastDispatcher.convertInsert( modelRange, viewWriter );
  167. if ( !modelElementOrFragment.is( 'documentFragment' ) ) {
  168. // Then, if a document element is converted, convert markers.
  169. // From all document markers, get those, which "intersect" with the converter element.
  170. const markers = _getMarkersRelativeToElement( modelElementOrFragment );
  171. for ( const [ name, range ] of markers ) {
  172. this.downcastDispatcher.convertMarkerAdd( name, range, viewWriter );
  173. }
  174. }
  175. return viewDocumentFragment;
  176. }
  177. /**
  178. * Sets initial input data parsed by the {@link #processor data processor} and
  179. * converted by the {@link #upcastDispatcher view-to-model converters}.
  180. * Initial data can be set only to document that {@link module:engine/model/document~Document#version} is equal 0.
  181. *
  182. * **Note** This method is {@link module:utils/observablemixin~ObservableMixin#decorate decorated} which is
  183. * used by e.g. collaborative editing plugin that syncs remote data on init.
  184. *
  185. * When data is passed as a string it is initialized on a default `main` root:
  186. *
  187. * dataController.init( '<p>Foo</p>' ); // Initializes data on the `main` root.
  188. *
  189. * To initialize data on a different root or multiple roots at once, object containing `rootName` - `data` pairs should be passed:
  190. *
  191. * dataController.init( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Initializes data on the `main` and `title` roots.
  192. *
  193. * @fires init
  194. * @param {String|Object.<String,String>} data Input data as a string or an object containing `rootName` - `data`
  195. * pairs to initialize data on multiple roots at once.
  196. * @returns {Promise} Promise that is resolved after the data is set on the editor.
  197. */
  198. init( data ) {
  199. if ( this.model.document.version ) {
  200. /**
  201. * Cannot set initial data to not empty {@link module:engine/model/document~Document}.
  202. * Initial data should be set once, during {@link module:core/editor/editor~Editor} initialization,
  203. * when the {@link module:engine/model/document~Document#version} is equal 0.
  204. *
  205. * @error datacontroller-init-document-not-empty
  206. */
  207. throw new CKEditorError( 'datacontroller-init-document-not-empty: Trying to set initial data to not empty document.' );
  208. }
  209. let initialData = {};
  210. if ( typeof data === 'string' ) {
  211. initialData.main = data; // Default root is 'main'. To initiate data on a different root, object should be passed.
  212. } else {
  213. initialData = data;
  214. }
  215. if ( !this._checkIfRootsExists( Object.keys( initialData ) ) ) {
  216. /**
  217. * Cannot init data on a non-existing root. This error is thrown when {@link #init DataController#init() method}
  218. * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
  219. * calling {@link #init} like:
  220. *
  221. * data.init( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
  222. *
  223. * will throw this error.
  224. *
  225. * @error datacontroller-init-non-existent-root
  226. */
  227. throw new CKEditorError( 'datacontroller-init-non-existent-root: Attempting to init data on a non-existing root.' );
  228. }
  229. this.model.enqueueChange( 'transparent', writer => {
  230. for ( const rootName of Object.keys( initialData ) ) {
  231. const modelRoot = this.model.document.getRoot( rootName );
  232. writer.insert( this.parse( initialData[ rootName ], modelRoot ), modelRoot, 0 );
  233. }
  234. } );
  235. return Promise.resolve();
  236. }
  237. /**
  238. * Sets input data parsed by the {@link #processor data processor} and
  239. * converted by the {@link #upcastDispatcher view-to-model converters}.
  240. * This method can be used any time to replace existing editor data by the new one without clearing the
  241. * {@link module:engine/model/document~Document#history document history}.
  242. *
  243. * This method also creates a batch with all the changes applied. If all you need is to parse data, use
  244. * the {@link #parse} method.
  245. *
  246. * When data is passed as a string it is set on a default `main` root:
  247. *
  248. * dataController.set( '<p>Foo</p>' ); // Sets data on the `main` root.
  249. *
  250. * To set data on a different root or multiple roots at once, object containing `rootName` - `data` pairs should be passed:
  251. *
  252. * dataController.set( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Sets data on the `main` and `title` roots.
  253. *
  254. * @param {String|Object.<String,String>} data Input data as a string or an object containing `rootName` - `data`
  255. * pairs to set data on multiple roots at once.
  256. */
  257. set( data ) {
  258. let newData = {};
  259. if ( typeof data === 'string' ) {
  260. newData.main = data; // Default root is 'main'. To set data on a different root, object should be passed.
  261. } else {
  262. newData = data;
  263. }
  264. if ( !this._checkIfRootsExists( Object.keys( newData ) ) ) {
  265. /**
  266. * Cannot set data on a non-existing root. This error is thrown when {@link #set DataController#set() method}
  267. * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
  268. * calling {@link #set} like:
  269. *
  270. * data.set( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
  271. *
  272. * will throw this error.
  273. *
  274. * @error datacontroller-set-non-existent-root
  275. */
  276. throw new CKEditorError( 'datacontroller-set-non-existent-root: Attempting to set data on a non-existing root.' );
  277. }
  278. this.model.enqueueChange( 'transparent', writer => {
  279. writer.setSelection( null );
  280. writer.removeSelectionAttribute( this.model.document.selection.getAttributeKeys() );
  281. for ( const rootName of Object.keys( newData ) ) {
  282. // Save to model.
  283. const modelRoot = this.model.document.getRoot( rootName );
  284. writer.remove( writer.createRangeIn( modelRoot ) );
  285. writer.insert( this.parse( newData[ rootName ], modelRoot ), modelRoot, 0 );
  286. }
  287. } );
  288. }
  289. /**
  290. * Returns the data parsed by the {@link #processor data processor} and then converted by upcast converters
  291. * attached to the {@link #upcastDispatcher}.
  292. *
  293. * @see #set
  294. * @param {String} data Data to parse.
  295. * @param {module:engine/model/schema~SchemaContextDefinition} [context='$root'] Base context in which the view will
  296. * be converted to the model. See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
  297. * @returns {module:engine/model/documentfragment~DocumentFragment} Parsed data.
  298. */
  299. parse( data, context = '$root' ) {
  300. // data -> view
  301. const viewDocumentFragment = this.processor.toView( data );
  302. // view -> model
  303. return this.toModel( viewDocumentFragment, context );
  304. }
  305. /**
  306. * Returns the result of the given {@link module:engine/view/element~Element view element} or
  307. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment} converted by the
  308. * {@link #upcastDispatcher view-to-model converters}, wrapped by {@link module:engine/model/documentfragment~DocumentFragment}.
  309. *
  310. * When marker elements were converted during the conversion process, it will be set as a document fragment's
  311. * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
  312. *
  313. * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment} viewElementOrFragment
  314. * Element or document fragment whose content will be converted.
  315. * @param {module:engine/model/schema~SchemaContextDefinition} [context='$root'] Base context in which the view will
  316. * be converted to the model. See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
  317. * @returns {module:engine/model/documentfragment~DocumentFragment} Output document fragment.
  318. */
  319. toModel( viewElementOrFragment, context = '$root' ) {
  320. return this.model.change( writer => {
  321. return this.upcastDispatcher.convert( viewElementOrFragment, writer, context );
  322. } );
  323. }
  324. /**
  325. * Removes all event listeners set by the DataController.
  326. */
  327. destroy() {
  328. this.stopListening();
  329. }
  330. /**
  331. * Checks if all provided root names are existing editor roots.
  332. *
  333. * @private
  334. * @param {Array.<String>} rootNames Root names to check.
  335. * @returns {Boolean} Whether all provided root names are existing editor roots.
  336. */
  337. _checkIfRootsExists( rootNames ) {
  338. for ( const rootName of rootNames ) {
  339. if ( !this.model.document.getRootNames().includes( rootName ) ) {
  340. return false;
  341. }
  342. }
  343. return true;
  344. }
  345. /**
  346. * Event fired once data initialisation has finished.
  347. *
  348. * @event ready
  349. */
  350. /**
  351. * Event fired after {@link #init init() method} has been run. It can be {@link #listenTo listened to} to adjust/modify
  352. * the initialisation flow. However, if the `init` event is stopped or prevented, the {@link #event:ready ready event}
  353. * should be fired manually.
  354. *
  355. * The `init` event is fired by decorated {@link #init} method.
  356. * See {@link module:utils/observablemixin~ObservableMixin.decorate} for more information and samples.
  357. *
  358. * @event init
  359. */
  360. }
  361. mix( DataController, ObservableMixin );
  362. // Helper function for downcast conversion.
  363. //
  364. // Takes a document element (element that is added to a model document) and checks which markers are inside it
  365. // and which markers are containing it. If the marker is intersecting with element, the intersection is returned.
  366. function _getMarkersRelativeToElement( element ) {
  367. const result = [];
  368. const doc = element.root.document;
  369. if ( !doc ) {
  370. return [];
  371. }
  372. const elementRange = ModelRange._createIn( element );
  373. for ( const marker of doc.model.markers ) {
  374. const intersection = elementRange.getIntersection( marker.getRange() );
  375. if ( intersection ) {
  376. result.push( [ marker.name, intersection ] );
  377. }
  378. }
  379. return result;
  380. }