autosave.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module autosave/autosave
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import PendingActions from '@ckeditor/ckeditor5-core/src/pendingactions';
  10. import DomEmitterMixin from '@ckeditor/ckeditor5-utils/src/dom/emittermixin';
  11. import debounce from '@ckeditor/ckeditor5-utils/src/lib/lodash/debounce';
  12. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  13. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  14. /* globals window */
  15. /**
  16. * The {@link module:autosave/autosave~Autosave} allows you to automatically save the data (e.g. send it to the server)
  17. * when needed (when the user changed the content).
  18. *
  19. * It listens to the {@link module:engine/model/document~Document#event:change:data `editor.model.document#change:data`}
  20. * and `window#beforeunload` events and calls the
  21. * {@link module:autosave/autosave~AutosaveAdapter#save `config.autosave.save()`} function.
  22. *
  23. * ClassicEditor
  24. * .create( document.querySelector( '#editor' ), {
  25. * plugins: [ ArticlePluginSet, Autosave ],
  26. * toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'undo', 'redo' ],
  27. * image: {
  28. * toolbar: [ 'imageStyle:full', 'imageStyle:side', '|', 'imageTextAlternative' ],
  29. * },
  30. * autosave: {
  31. * save( editor ) {
  32. * // The saveData() function must return a promise
  33. * // which should be resolved when the data is successfully saved.
  34. * return saveData( editor.getData() );
  35. * }
  36. * }
  37. * } );
  38. *
  39. * Read more about this feature in the {@glink builds/guides/integration/saving-data#the-autosave-feature Autosave feature}
  40. * section of the {@glink builds/guides/integration/saving-data Saving and getting data}.
  41. */
  42. export default class Autosave extends Plugin {
  43. /**
  44. * @inheritDoc
  45. */
  46. static get pluginName() {
  47. return 'Autosave';
  48. }
  49. /**
  50. * @inheritDoc
  51. */
  52. static get requires() {
  53. return [ PendingActions ];
  54. }
  55. /**
  56. * @inheritDoc
  57. */
  58. constructor( editor ) {
  59. super( editor );
  60. /**
  61. * The adapter is an object with a `save()` method. That method will be called whenever
  62. * the data changes. It might be called some time after the change,
  63. * since the event is throttled for performance reasons.
  64. *
  65. * @member {module:autosave/autosave~AutosaveAdapter} #adapter
  66. */
  67. /**
  68. * The state of this plugin.
  69. *
  70. * The plugin can be in the following states:
  71. *
  72. * * synchronized - when all changes are saved
  73. * * waiting - when the plugin is waiting for other changes before calling `adapter#save()` and `config.autosave.save()`
  74. * * saving - when the provided save method is called and the plugin waits for the response
  75. *
  76. * @member {'synchronized'|'waiting'|'saving'} #state
  77. */
  78. this.set( 'state', 'synchronized' );
  79. /**
  80. * Throttled save method.
  81. *
  82. * @protected
  83. * @type {Function}
  84. */
  85. this._debouncedSave = debounce( this._save.bind( this ), 2000 );
  86. /**
  87. * Last document version.
  88. *
  89. * @protected
  90. * @type {Number}
  91. */
  92. this._lastDocumentVersion = editor.model.document.version;
  93. /**
  94. * DOM emitter.
  95. *
  96. * @private
  97. * @type {DomEmitterMixin}
  98. */
  99. this._domEmitter = Object.create( DomEmitterMixin );
  100. /**
  101. * An action that will be added to pending action manager for actions happening in that plugin.
  102. *
  103. * @private
  104. * @member {Object} #_action
  105. */
  106. /**
  107. * The config of this plugins.
  108. *
  109. * @private
  110. * @type {Object}
  111. */
  112. this._config = editor.config.get( 'autosave' ) || {};
  113. /**
  114. * Editor's pending actions manager.
  115. *
  116. * @private
  117. * @member {@module:core/pendingactions~PendingActions} #_pendingActions
  118. */
  119. }
  120. /**
  121. * @inheritDoc
  122. */
  123. init() {
  124. const editor = this.editor;
  125. const doc = editor.model.document;
  126. this._pendingActions = editor.plugins.get( PendingActions );
  127. this.listenTo( doc, 'change:data', () => {
  128. if ( !this._saveCallbacks.length ) {
  129. return;
  130. }
  131. if ( this.state == 'synchronized' ) {
  132. this._action = this._pendingActions.add( this.editor.t( 'Saving changes' ) );
  133. this.state = 'waiting';
  134. this._debouncedSave();
  135. }
  136. else if ( this.state == 'waiting' ) {
  137. this._debouncedSave();
  138. }
  139. // Do nothing if the plugin is in `external-saving` state.
  140. } );
  141. // Flush on the editor's destroy listener with the highest priority to ensure that
  142. // `editor.getData()` will be called before plugins are destroyed.
  143. this.listenTo( editor, 'destroy', () => this._flush(), { priority: 'highest' } );
  144. // It's not possible to easy test it because karma uses `beforeunload` event
  145. // to warn before full page reload and this event cannot be dispatched manually.
  146. /* istanbul ignore next */
  147. this._domEmitter.listenTo( window, 'beforeunload', ( evtInfo, domEvt ) => {
  148. if ( this._pendingActions.hasAny ) {
  149. domEvt.returnValue = this._pendingActions.first.message;
  150. }
  151. } );
  152. }
  153. /**
  154. * @inheritDoc
  155. */
  156. destroy() {
  157. // There's no need for canceling or flushing the throttled save, as
  158. // it's done on the editor's destroy event with the highest priority.
  159. this._domEmitter.stopListening();
  160. super.destroy();
  161. }
  162. /**
  163. * Invokes remaining `_save` method call.
  164. *
  165. * @protected
  166. */
  167. _flush() {
  168. this._debouncedSave.flush();
  169. }
  170. /**
  171. * If the adapter is set and new document version exists,
  172. * `_save()` method creates a pending action and calls `adapter.save()` method.
  173. * It waits for the result and then removes the created pending action.
  174. *
  175. * @private
  176. */
  177. _save() {
  178. const version = this.editor.model.document.version;
  179. // Change may not produce an operation, so the document's version
  180. // can be the same after that change.
  181. if (
  182. version < this._lastDocumentVersion ||
  183. this.editor.state === 'initializing'
  184. ) {
  185. this._debouncedSave.cancel();
  186. return;
  187. }
  188. this._lastDocumentVersion = version;
  189. this.state = 'saving';
  190. // Wait one promise cycle to be sure that save callbacks are not called
  191. // inside a conversion or when the editor's state changes.
  192. Promise.resolve()
  193. .then( () => Promise.all(
  194. this._saveCallbacks.map( cb => cb( this.editor ) )
  195. ) )
  196. .then( () => {
  197. if ( this.editor.model.document.version > this._lastDocumentVersion ) {
  198. this.state = 'waiting';
  199. this._debouncedSave();
  200. } else {
  201. this.state = 'synchronized';
  202. this._pendingActions.remove( this._action );
  203. this._action = null;
  204. }
  205. } );
  206. }
  207. /**
  208. * Save callbacks.
  209. *
  210. * @private
  211. * @type {Array.<Function>}
  212. */
  213. get _saveCallbacks() {
  214. const saveCallbacks = [];
  215. if ( this.adapter && this.adapter.save ) {
  216. saveCallbacks.push( this.adapter.save );
  217. }
  218. if ( this._config.save ) {
  219. saveCallbacks.push( this._config.save );
  220. }
  221. return saveCallbacks;
  222. }
  223. }
  224. mix( Autosave, ObservableMixin );
  225. /**
  226. * An interface that requires the `save()` method.
  227. *
  228. * Used by {module:autosave/autosave~Autosave#adapter}
  229. *
  230. * @interface module:autosave/autosave~AutosaveAdapter
  231. */
  232. /**
  233. * Method that will be called when the data changes. It should return a promise (e.g. in case of saving content to the database),
  234. * so the `Autosave` plugin will wait for that action before removing it from pending actions.
  235. *
  236. * @method #save
  237. * @param {module:core/editor/editor~Editor} editor The editor instance.
  238. * @returns {Promise.<*>}
  239. */
  240. /**
  241. * The configuration of the {@link module:autosave/autosave~Autosave autosave feature}.
  242. *
  243. * Read more in {@link module:autosave/autosave~AutosaveConfig}.
  244. *
  245. * @member {module:autosave/autosave~AutosaveConfig} module:core/editor/editorconfig~EditorConfig#autosave
  246. */
  247. /**
  248. * The configuration of the {@link module:autosave/autosave~Autosave autosave feature}.
  249. *
  250. * ClassicEditor
  251. * .create( editorElement, {
  252. * autosave: {
  253. * save( editor ) {
  254. * // The saveData() function must return a promise
  255. * // which should be resolved when the data is successfully saved.
  256. * return saveData( editor.getData() );
  257. * }
  258. * }
  259. * } );
  260. * .then( ... )
  261. * .catch( ... );
  262. *
  263. * See {@link module:core/editor/editorconfig~EditorConfig all editor configuration options}.
  264. *
  265. * See also the demo of the {@glink builds/guides/integration/saving-data#autosave-feature autosave feature}.
  266. *
  267. * @interface AutosaveConfig
  268. */
  269. /**
  270. * The callback to be executed when the data needs to be saved.
  271. *
  272. * This function must return a promise which should be which should be resolved when the data is successfully saved.
  273. *
  274. * ClassicEditor
  275. * .create( editorElement, {
  276. * autosave: {
  277. * save( editor ) {
  278. * return saveData( editor.getData() );
  279. * }
  280. * }
  281. * } );
  282. * .then( ... )
  283. * .catch( ... );
  284. *
  285. * @method module:autosave/autosave~AutosaveConfig#save
  286. * @param {module:core/editor/editor~Editor} editor The editor instance.
  287. * @returns {Promise.<*>}
  288. */