plugin.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @file Plugin to count symbols, symbols without blanks and words
  3. */
  4. ( function(){
  5. var emptyHtml = '<span class="cke_empty">&nbsp;</span>';
  6. CKEDITOR.plugins.add( 'counter',
  7. {
  8. init : function( editor )
  9. {
  10. var spaceId = 'cke_counter_' + editor.name;
  11. var spaceElement;
  12. var ckeditorEventThemeSpace = 'uiSpace';
  13. var getSpaceElement = function()
  14. {
  15. if ( !spaceElement )
  16. spaceElement = CKEDITOR.document.getById( spaceId );
  17. return spaceElement;
  18. };
  19. if (Drupal.ckeditor_ver == 3) {
  20. ckeditorEventThemeSpace = 'themeSpace';
  21. }
  22. editor.on( ckeditorEventThemeSpace, function( event )
  23. {
  24. if ( event.data.space == 'bottom' )
  25. {
  26. event.data.html +=
  27. '<span id="' + spaceId + '_label" class="cke_voice_label">Counter</span>' +
  28. '<div id="' + spaceId + '" class="cke_counter" role="group" aria-labelledby="' + spaceId + '_label">' + emptyHtml + '</div>';
  29. }
  30. });
  31. function count( ev )
  32. {
  33. var space = getSpaceElement();
  34. var text = ev.editor.getData();
  35. // decode HTML entities; it also removes HTML tags, but works only if jQuery is available
  36. text = jQuery('<div/>').html(text).text();
  37. // remove all redundant blank symbols
  38. text = text.replace(new RegExp('\\s+', 'g'), ' ');
  39. // remove all blank symbols at the start and at the end
  40. text = text.replace(new RegExp('(^\\s+)|(\\s+$)', 'g'), '');
  41. var symbols = text.length;
  42. var words = text.split(' ').length;
  43. //remove all blank symbols
  44. text = text.replace(new RegExp('\\s+', 'g'), '');
  45. var symbols_wo_blanks = text.length;
  46. space.setHtml( '<span class="cke_counter" style="float: right">' + symbols + ' / ' + symbols_wo_blanks + ' symbols; ' + words + ' words</span>' );
  47. }
  48. editor.on( 'dataReady', count );
  49. editor.on( 'blur', count );
  50. editor.on( 'focus', count );
  51. // Almost useless
  52. //editor.on( 'saveSnapshot', count );
  53. // Requires too much resources
  54. //editor.on( 'key', count );
  55. }
  56. });
  57. })();