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. wordCount: {
  31. onUpdate: ( () => {
  32. const progressBar = document.querySelector( '.customized-count progress' );
  33. const colorBox = document.querySelector( '.customized-count__color-box' );
  34. return data => {
  35. const charactersHue = calculateHue( {
  36. characters: data.characters,
  37. greenUntil: 70,
  38. maxCharacters: 120
  39. } );
  40. progressBar.value = data.words;
  41. colorBox.style.setProperty( '--hue', charactersHue );
  42. };
  43. // Calculates the hue based on the number of characters.
  44. //
  45. // For the character counter:
  46. //
  47. // * below greenUntil - Returns green.
  48. // * between greenUntil and maxCharacters - Returns a hue between green and red.
  49. // * above maxCharacters - Returns red.
  50. function calculateHue( { characters, greenUntil, maxCharacters } ) {
  51. const greenHue = 70;
  52. const redHue = 0;
  53. const progress = Math.max( 0, Math.min( 1, ( characters - greenUntil ) / ( maxCharacters - greenUntil ) ) ); // 0-1
  54. const discreetProgress = Math.floor( progress * 10 ) / 10; // 0, 0.1, 0.2, ..., 1
  55. return ( redHue - greenHue ) * discreetProgress + greenHue;
  56. }
  57. } )()
  58. }
  59. } )
  60. .catch( err => {
  61. console.error( err.stack );
  62. } );