datacontroller.js 19 KB

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