8
0

autosave.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 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: window.getViewportTopOffsetConfig()
  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. updateServerDataConsole( 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. pendingActions.on( 'change:hasAny', ( evt, propertyName, newValue ) => {
  43. if ( newValue ) {
  44. statusIndicator.classList.add( 'busy' );
  45. } else {
  46. statusIndicator.classList.remove( 'busy' );
  47. }
  48. } );
  49. }
  50. let consoleUpdates = 0;
  51. function updateServerDataConsole( msg ) {
  52. const console = document.querySelector( '#snippet-autosave-console' );
  53. consoleUpdates++;
  54. console.classList.add( 'updated' );
  55. console.textContent = msg;
  56. setTimeout( () => {
  57. if ( --consoleUpdates == 0 ) {
  58. console.classList.remove( 'updated' );
  59. }
  60. }, 500 );
  61. }