autosave.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /* globals ClassicEditor, console, window, document, setTimeout */
  6. import { CS_CONFIG } from '@ckeditor/ckeditor5-cloud-services/tests/_utils/cloud-services-config';
  7. let HTTP_SERVER_LAG = 500;
  8. document.querySelector( '#snippet-autosave-lag' ).addEventListener( 'change', evt => {
  9. HTTP_SERVER_LAG = evt.target.value;
  10. } );
  11. ClassicEditor
  12. .create( document.querySelector( '#snippet-autosave' ), {
  13. cloudServices: CS_CONFIG,
  14. toolbar: {
  15. viewportTopOffset: 60
  16. },
  17. autosave: {
  18. save( editor ) {
  19. return saveData( editor.getData() );
  20. }
  21. }
  22. } )
  23. .then( editor => {
  24. window.editor = editor;
  25. displayStatus( editor );
  26. } )
  27. .catch( err => {
  28. console.error( err.stack );
  29. } );
  30. function saveData( data ) {
  31. return new Promise( resolve => {
  32. // Fake HTTP server's lag.
  33. setTimeout( () => {
  34. log( data );
  35. resolve();
  36. }, HTTP_SERVER_LAG );
  37. } );
  38. }
  39. function displayStatus( editor ) {
  40. const pendingActions = editor.plugins.get( 'PendingActions' );
  41. const statusIndicator = document.querySelector( '.snippet-autosave-status' );
  42. const console = document.querySelector( '#snippet-autosave-console' );
  43. pendingActions.on( 'change:hasAny', ( evt, propertyName, newValue ) => {
  44. if ( newValue ) {
  45. statusIndicator.classList.add( 'busy' );
  46. console.classList.remove( 'received' );
  47. } else {
  48. statusIndicator.classList.remove( 'busy' );
  49. console.classList.add( 'received' );
  50. }
  51. } );
  52. }
  53. function log( msg ) {
  54. const console = document.querySelector( '#snippet-autosave-console' );
  55. console.textContent = msg;
  56. }