datacontroller.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. } );
  83. this.downcastDispatcher.on( 'insert:$text', insertText(), { priority: 'lowest' } );
  84. /**
  85. * Upcast dispatcher used by the {@link #set set method}. Upcast converters should be attached to it.
  86. *
  87. * @readonly
  88. * @member {module:engine/conversion/upcastdispatcher~UpcastDispatcher}
  89. */
  90. this.upcastDispatcher = new UpcastDispatcher( {
  91. schema: model.schema
  92. } );
  93. /**
  94. * The view document used by the data controller.
  95. *
  96. * @readonly
  97. * @member {module:engine/view/document~Document}
  98. */
  99. this.viewDocument = new ViewDocument( stylesProcessor );
  100. /**
  101. * The view downcast writer just for data conversion purposes, i.e. to modify
  102. * the {@link #viewDocument}.
  103. *
  104. * @private
  105. * @readonly
  106. * @member {module:engine/view/downcastwriter~DowncastWriter}
  107. */
  108. this._viewWriter = new ViewDowncastWriter( this.viewDocument );
  109. // Define default converters for text and elements.
  110. //
  111. // Note that if there is no default converter for the element it will be skipped, for instance `<b>foo</b>` will be
  112. // converted to nothing. We add `convertToModelFragment` as a last converter so it converts children of that
  113. // element to the document fragment so `<b>foo</b>` will be converted to `foo` if there is no converter for `<b>`.
  114. this.upcastDispatcher.on( 'text', convertText(), { priority: 'lowest' } );
  115. this.upcastDispatcher.on( 'element', convertToModelFragment(), { priority: 'lowest' } );
  116. this.upcastDispatcher.on( 'documentFragment', convertToModelFragment(), { priority: 'lowest' } );
  117. this.decorate( 'init' );
  118. this.decorate( 'set' );
  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. * @fires set
  282. * @param {String|Object.<String,String>} data Input data as a string or an object containing `rootName` - `data`
  283. * pairs to set data on multiple roots at once.
  284. */
  285. set( data ) {
  286. let newData = {};
  287. if ( typeof data === 'string' ) {
  288. newData.main = data; // Default root is 'main'. To set data on a different root, object should be passed.
  289. } else {
  290. newData = data;
  291. }
  292. if ( !this._checkIfRootsExists( Object.keys( newData ) ) ) {
  293. /**
  294. * Cannot set data on a non-existing root. This error is thrown when {@link #set DataController#set() method}
  295. * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
  296. * calling {@link #set} like:
  297. *
  298. * data.set( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
  299. *
  300. * will throw this error.
  301. *
  302. * @error datacontroller-set-non-existent-root
  303. */
  304. throw new CKEditorError( 'datacontroller-set-non-existent-root: Attempting to set data on a non-existing root.', this );
  305. }
  306. this.model.enqueueChange( 'transparent', writer => {
  307. writer.setSelection( null );
  308. writer.removeSelectionAttribute( this.model.document.selection.getAttributeKeys() );
  309. for ( const rootName of Object.keys( newData ) ) {
  310. // Save to model.
  311. const modelRoot = this.model.document.getRoot( rootName );
  312. writer.remove( writer.createRangeIn( modelRoot ) );
  313. writer.insert( this.parse( newData[ rootName ], modelRoot ), modelRoot, 0 );
  314. }
  315. } );
  316. }
  317. /**
  318. * Returns the data parsed by the {@link #processor data processor} and then converted by upcast converters
  319. * attached to the {@link #upcastDispatcher}.
  320. *
  321. * @see #set
  322. * @param {String} data Data to parse.
  323. * @param {module:engine/model/schema~SchemaContextDefinition} [context='$root'] Base context in which the view will
  324. * be converted to the model. See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
  325. * @returns {module:engine/model/documentfragment~DocumentFragment} Parsed data.
  326. */
  327. parse( data, context = '$root' ) {
  328. // data -> view
  329. const viewDocumentFragment = this.processor.toView( data );
  330. // view -> model
  331. return this.toModel( viewDocumentFragment, context );
  332. }
  333. /**
  334. * Returns the result of the given {@link module:engine/view/element~Element view element} or
  335. * {@link module:engine/view/documentfragment~DocumentFragment view document fragment} converted by the
  336. * {@link #upcastDispatcher view-to-model converters}, wrapped by {@link module:engine/model/documentfragment~DocumentFragment}.
  337. *
  338. * When marker elements were converted during the conversion process, it will be set as a document fragment's
  339. * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
  340. *
  341. * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment} viewElementOrFragment
  342. * Element or document fragment whose content will be converted.
  343. * @param {module:engine/model/schema~SchemaContextDefinition} [context='$root'] Base context in which the view will
  344. * be converted to the model. See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
  345. * @returns {module:engine/model/documentfragment~DocumentFragment} Output document fragment.
  346. */
  347. toModel( viewElementOrFragment, context = '$root' ) {
  348. return this.model.change( writer => {
  349. return this.upcastDispatcher.convert( viewElementOrFragment, writer, context );
  350. } );
  351. }
  352. /**
  353. * Adds a style processor normalization rules.
  354. *
  355. * You can implement your own rules as well as use one of the available processor rules:
  356. *
  357. * * background: {@link module:engine/view/styles/background~addBackgroundRules}
  358. * * border: {@link module:engine/view/styles/border~addBorderRules}
  359. * * margin: {@link module:engine/view/styles/margin~addMarginRules}
  360. * * padding: {@link module:engine/view/styles/padding~addPaddingRules}
  361. *
  362. * @param {Function} callback
  363. */
  364. addStyleProcessorRules( callback ) {
  365. callback( this.stylesProcessor );
  366. }
  367. /**
  368. * Removes all event listeners set by the DataController.
  369. */
  370. destroy() {
  371. this.stopListening();
  372. }
  373. /**
  374. * Checks if all provided root names are existing editor roots.
  375. *
  376. * @private
  377. * @param {Array.<String>} rootNames Root names to check.
  378. * @returns {Boolean} Whether all provided root names are existing editor roots.
  379. */
  380. _checkIfRootsExists( rootNames ) {
  381. for ( const rootName of rootNames ) {
  382. if ( !this.model.document.getRootNames().includes( rootName ) ) {
  383. return false;
  384. }
  385. }
  386. return true;
  387. }
  388. /**
  389. * Event fired once data initialisation has finished.
  390. *
  391. * @event ready
  392. */
  393. /**
  394. * Event fired after {@link #init init() method} has been run. It can be {@link #listenTo listened to} to adjust/modify
  395. * the initialisation flow. However, if the `init` event is stopped or prevented, the {@link #event:ready ready event}
  396. * should be fired manually.
  397. *
  398. * The `init` event is fired by decorated {@link #init} method.
  399. * See {@link module:utils/observablemixin~ObservableMixin#decorate} for more information and samples.
  400. *
  401. * @event init
  402. */
  403. }
  404. mix( DataController, ObservableMixin );
  405. // Helper function for downcast conversion.
  406. //
  407. // Takes a document element (element that is added to a model document) and checks which markers are inside it
  408. // and which markers are containing it. If the marker is intersecting with element, the intersection is returned.
  409. function _getMarkersRelativeToElement( element ) {
  410. const result = [];
  411. const doc = element.root.document;
  412. if ( !doc ) {
  413. return [];
  414. }
  415. const elementRange = ModelRange._createIn( element );
  416. for ( const marker of doc.model.markers ) {
  417. const intersection = elementRange.getIntersection( marker.getRange() );
  418. if ( intersection ) {
  419. result.push( [ marker.name, intersection ] );
  420. }
  421. }
  422. return result;
  423. }