8
0

datacontroller.js 19 KB

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