autosave.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /* globals document, window, console */
  6. import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
  7. import ArticlePluginSet from '@ckeditor/ckeditor5-core/tests/_utils/articlepluginset';
  8. import Autosave from '../../src/autosave';
  9. ClassicEditor
  10. .create( document.querySelector( '#editor' ), {
  11. plugins: [ ArticlePluginSet, Autosave ],
  12. toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'undo', 'redo' ],
  13. image: {
  14. toolbar: [ 'imageStyle:full', 'imageStyle:side', '|', 'imageTextAlternative' ]
  15. }
  16. } )
  17. .then( editor => {
  18. window.editor = editor;
  19. const destroyButton = document.getElementById( 'destroy-editor-button' );
  20. destroyButton.addEventListener( 'click', () => editor.destroy() );
  21. const autosave = editor.plugins.get( Autosave );
  22. autosave.adapter = {
  23. save() {
  24. const data = editor.getData();
  25. return wait( 1000 )
  26. .then( () => console.log( `${ getTime() } Saved content: ${ data }` ) );
  27. }
  28. };
  29. autosave.listenTo( autosave, 'change:state',
  30. ( evt, propName, newValue, oldValue ) => console.log( `${ getTime() } Changed state: ${ oldValue } -> ${ newValue }` ) );
  31. } );
  32. function wait( time ) {
  33. return new Promise( res => {
  34. window.setTimeout( res, time );
  35. } );
  36. }
  37. function getTime() {
  38. const date = new Date();
  39. return '[' +
  40. date.getHours() + ':' +
  41. setDigitSize( date.getMinutes(), 2 ) + ':' +
  42. setDigitSize( date.getSeconds(), 2 ) + '.' +
  43. setDigitSize( date.getMilliseconds(), 2 ) +
  44. ']';
  45. }
  46. function setDigitSize( number, size ) {
  47. const string = String( number );
  48. if ( string.length >= size ) {
  49. return string.slice( 0, size );
  50. }
  51. return '0'.repeat( size - string.length ) + string;
  52. }