8
0

datacontroller.js 17 KB

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