datacontroller.js 18 KB

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