word-count-update.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* global window, document, console, ClassicEditor */
  6. ClassicEditor
  7. .create( document.querySelector( '#demo-editor-update' ), {
  8. toolbar: {
  9. items: [
  10. 'heading',
  11. '|',
  12. 'bold',
  13. 'italic',
  14. 'bulletedList',
  15. 'numberedList',
  16. 'blockQuote',
  17. 'link',
  18. '|',
  19. 'mediaEmbed',
  20. 'insertTable',
  21. '|',
  22. 'undo',
  23. 'redo'
  24. ],
  25. viewportTopOffset: window.getViewportTopOffsetConfig()
  26. },
  27. table: {
  28. contentToolbar: [ 'tableColumn', 'tableRow', 'mergeTableCells' ]
  29. }
  30. } )
  31. .then( editor => {
  32. const wordCountPlugin = editor.plugins.get( 'WordCount' );
  33. const progressBar = document.querySelector( '.customized-count progress' );
  34. const colorBox = document.querySelector( '.customized-count__color-box' );
  35. wordCountPlugin.on( 'update', ( evt, data ) => {
  36. const charactersHue = calculateHue( {
  37. characters: data.characters,
  38. greenUntil: 70,
  39. maxCharacters: 120
  40. } );
  41. progressBar.value = data.words;
  42. colorBox.style.setProperty( '--hue', charactersHue );
  43. } );
  44. // Calculates the hue based on the number of characters.
  45. //
  46. // For the character counter:
  47. //
  48. // * below greenUntil - Returns green.
  49. // * between greenUntil and maxCharacters - Returns a hue between green and red.
  50. // * above maxCharacters - Returns red.
  51. function calculateHue( { characters, greenUntil, maxCharacters } ) {
  52. const greenHue = 70;
  53. const redHue = 0;
  54. const progress = Math.max( 0, Math.min( 1, ( characters - greenUntil ) / ( maxCharacters - greenUntil ) ) ); // 0-1
  55. const discreetProgress = Math.floor( progress * 10 ) / 10; // 0, 0.1, 0.2, ..., 1
  56. return ( redHue - greenHue ) * discreetProgress + greenHue;
  57. }
  58. } )
  59. .catch( err => {
  60. console.error( err.stack );
  61. } );