plugin.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /**
  2. * @license Copyright (c) CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.html or http://ckeditor.com/license
  4. */
  5. CKEDITOR.plugins.add("wordcount", {
  6. lang: "ar,ca,da,de,el,en,es,eu,fa,fi,fr,he,hr,hu,it,ja,nl,no,pl,pt,pt-br,ru,sk,sv,tr,zh-cn", // %REMOVE_LINE_CORE%
  7. version: 1.16,
  8. requires: 'htmlwriter,notification,undo',
  9. bbcodePluginLoaded: false,
  10. onLoad: function(editor) {
  11. CKEDITOR.document.appendStyleSheet(this.path + "css/wordcount.css");
  12. },
  13. init: function (editor) {
  14. var defaultFormat = "",
  15. intervalId,
  16. lastWordCount = -1,
  17. lastCharCount = -1,
  18. limitReachedNotified = false,
  19. limitRestoredNotified = false,
  20. snapShot = editor.getSnapshot(),
  21. notification = null;
  22. var dispatchEvent = function (type, currentLength, maxLength) {
  23. if (typeof document.dispatchEvent == 'undefined') {
  24. return;
  25. }
  26. type = 'ckeditor.wordcount.' + type;
  27. var cEvent;
  28. var eventInitDict = {
  29. bubbles: false,
  30. cancelable: true,
  31. detail: {
  32. currentLength: currentLength,
  33. maxLength: maxLength
  34. }
  35. };
  36. try {
  37. cEvent = new CustomEvent(type, eventInitDict);
  38. } catch (o_O) {
  39. cEvent = document.createEvent('CustomEvent');
  40. cEvent.initCustomEvent(
  41. type,
  42. eventInitDict.bubbles,
  43. eventInitDict.cancelable,
  44. eventInitDict.detail
  45. );
  46. }
  47. document.dispatchEvent(cEvent);
  48. };
  49. // Default Config
  50. var defaultConfig = {
  51. showParagraphs: true,
  52. showWordCount: true,
  53. showCharCount: false,
  54. countSpacesAsChars: false,
  55. countHTML: false,
  56. hardLimit: true,
  57. //MAXLENGTH Properties
  58. maxWordCount: -1,
  59. maxCharCount: -1,
  60. // Filter
  61. filter: null,
  62. // How long to show the 'paste' warning
  63. pasteWarningDuration: 0,
  64. //DisAllowed functions
  65. wordCountGreaterThanMaxLengthEvent: function (currentLength, maxLength) {
  66. dispatchEvent('wordCountGreaterThanMaxLengthEvent', currentLength, maxLength);
  67. },
  68. charCountGreaterThanMaxLengthEvent: function (currentLength, maxLength) {
  69. dispatchEvent('charCountGreaterThanMaxLengthEvent', currentLength, maxLength);
  70. },
  71. //Allowed Functions
  72. wordCountLessThanMaxLengthEvent: function (currentLength, maxLength) {
  73. dispatchEvent('wordCountLessThanMaxLengthEvent', currentLength, maxLength);
  74. },
  75. charCountLessThanMaxLengthEvent: function (currentLength, maxLength) {
  76. dispatchEvent('charCountLessThanMaxLengthEvent', currentLength, maxLength);
  77. }
  78. };
  79. // Get Config & Lang
  80. var config = CKEDITOR.tools.extend(defaultConfig, editor.config.wordcount || {}, true);
  81. if (config.showParagraphs) {
  82. defaultFormat += editor.lang.wordcount.Paragraphs + " %paragraphs%";
  83. }
  84. if (config.showParagraphs && (config.showWordCount || config.showCharCount)) {
  85. defaultFormat += ", ";
  86. }
  87. if (config.showWordCount) {
  88. defaultFormat += editor.lang.wordcount.WordCount + " %wordCount%";
  89. if (config.maxWordCount > -1) {
  90. defaultFormat += "/" + config.maxWordCount;
  91. }
  92. }
  93. if (config.showCharCount && config.showWordCount) {
  94. defaultFormat += ", ";
  95. }
  96. if (config.showCharCount) {
  97. var charLabel = editor.lang.wordcount[config.countHTML ? "CharCountWithHTML" : "CharCount"];
  98. defaultFormat += charLabel + " %charCount%";
  99. if (config.maxCharCount > -1) {
  100. defaultFormat += "/" + config.maxCharCount;
  101. }
  102. }
  103. var format = defaultFormat;
  104. bbcodePluginLoaded = typeof editor.plugins.bbcode != 'undefined';
  105. function counterId(editorInstance) {
  106. return "cke_wordcount_" + editorInstance.name;
  107. }
  108. function counterElement(editorInstance) {
  109. return document.getElementById(counterId(editorInstance));
  110. }
  111. function strip(html) {
  112. if (bbcodePluginLoaded) {
  113. // stripping out BBCode tags [...][/...]
  114. return html.replace(/\[.*?\]/gi, '');
  115. }
  116. var tmp = document.createElement("div");
  117. // Add filter before strip
  118. html = filter(html);
  119. tmp.innerHTML = html;
  120. if (tmp.textContent == "" && typeof tmp.innerText == "undefined") {
  121. return "";
  122. }
  123. return tmp.textContent || tmp.innerText;
  124. }
  125. /**
  126. * Implement filter to add or remove before counting
  127. * @param html
  128. * @returns string
  129. */
  130. function filter(html) {
  131. if(config.filter instanceof CKEDITOR.htmlParser.filter) {
  132. var fragment = CKEDITOR.htmlParser.fragment.fromHtml(html),
  133. writer = new CKEDITOR.htmlParser.basicWriter();
  134. config.filter.applyTo( fragment );
  135. fragment.writeHtml( writer );
  136. return writer.getHtml();
  137. }
  138. return html;
  139. }
  140. function countCharacters(text, editorInstance) {
  141. if (config.countHTML) {
  142. return (filter(text).length);
  143. } else {
  144. var normalizedText;
  145. // strip body tags
  146. if (editor.config.fullPage) {
  147. var i = text.search(new RegExp("<body>", "i"));
  148. if (i != -1) {
  149. var j = text.search(new RegExp("</body>", "i"));
  150. text = text.substring(i + 6, j);
  151. }
  152. }
  153. normalizedText = text;
  154. if (!config.countSpacesAsChars) {
  155. normalizedText = text.
  156. replace(/\s/g, "").
  157. replace(/&nbsp;/g, "");
  158. }
  159. normalizedText = normalizedText.
  160. replace(/(\r\n|\n|\r)/gm, "").
  161. replace(/&nbsp;/gi, " ");
  162. normalizedText = strip(normalizedText).replace(/^([\t\r\n]*)$/, "");
  163. return(normalizedText.length);
  164. }
  165. }
  166. function countParagraphs(text) {
  167. return (text.replace(/&nbsp;/g, " ").replace(/(<([^>]+)>)/ig, "").replace(/^\s*$[\n\r]{1,}/gm, "++").split("++").length);
  168. }
  169. function countWords(text) {
  170. var normalizedText = text.
  171. replace(/(\r\n|\n|\r)/gm, " ").
  172. replace(/^\s+|\s+$/g, "").
  173. replace("&nbsp;", " ");
  174. normalizedText = strip(normalizedText);
  175. var words = normalizedText.split(/\s+/);
  176. for (var wordIndex = words.length - 1; wordIndex >= 0; wordIndex--) {
  177. if (words[wordIndex].match(/^([\s\t\r\n]*)$/)) {
  178. words.splice(wordIndex, 1);
  179. }
  180. }
  181. return (words.length);
  182. }
  183. function limitReached(editorInstance, notify) {
  184. limitReachedNotified = true;
  185. limitRestoredNotified = false;
  186. if (config.hardLimit) {
  187. editorInstance.loadSnapshot(snapShot);
  188. // lock editor
  189. editorInstance.config.Locked = 1;
  190. }
  191. if (!notify) {
  192. counterElement(editorInstance).className = "cke_path_item cke_wordcountLimitReached";
  193. editorInstance.fire("limitReached", {}, editor);
  194. }
  195. }
  196. function limitRestored(editorInstance) {
  197. limitRestoredNotified = true;
  198. limitReachedNotified = false;
  199. editorInstance.config.Locked = 0;
  200. snapShot = editor.getSnapshot();
  201. counterElement(editorInstance).className = "cke_path_item";
  202. }
  203. function updateCounter(editorInstance) {
  204. var paragraphs = 0,
  205. wordCount = 0,
  206. charCount = 0,
  207. text;
  208. if (text = editorInstance.getData()) {
  209. if (config.showCharCount) {
  210. charCount = countCharacters(text, editorInstance);
  211. }
  212. if (config.showParagraphs) {
  213. paragraphs = countParagraphs(text);
  214. }
  215. if (config.showWordCount) {
  216. wordCount = countWords(text);
  217. }
  218. }
  219. var html = format.replace("%wordCount%", wordCount).replace("%charCount%", charCount).replace("%paragraphs%", paragraphs);
  220. (editorInstance.config.wordcount || (editorInstance.config.wordcount = {})).wordCount = wordCount;
  221. (editorInstance.config.wordcount || (editorInstance.config.wordcount = {})).charCount = charCount;
  222. if (CKEDITOR.env.gecko) {
  223. counterElement(editorInstance).innerHTML = html;
  224. } else {
  225. counterElement(editorInstance).innerText = html;
  226. }
  227. if (charCount == lastCharCount && wordCount == lastWordCount) {
  228. return true;
  229. }
  230. //If the limit is already over, allow the deletion of characters/words. Otherwise,
  231. //the user would have to delete at one go the number of offending characters
  232. var deltaWord = wordCount - lastWordCount;
  233. var deltaChar = charCount - lastCharCount;
  234. lastWordCount = wordCount;
  235. lastCharCount = charCount;
  236. if (lastWordCount == -1) {
  237. lastWordCount = wordCount;
  238. }
  239. if (lastCharCount == -1) {
  240. lastCharCount = charCount;
  241. }
  242. // Check for word limit and/or char limit
  243. if ((config.maxWordCount > -1 && wordCount > config.maxWordCount && deltaWord > 0) ||
  244. (config.maxCharCount > -1 && charCount > config.maxCharCount && deltaChar > 0)) {
  245. limitReached(editorInstance, limitReachedNotified);
  246. } else if ((config.maxWordCount == -1 || wordCount <= config.maxWordCount) &&
  247. (config.maxCharCount == -1 || charCount <= config.maxCharCount)) {
  248. limitRestored(editorInstance);
  249. } else {
  250. snapShot = editorInstance.getSnapshot();
  251. }
  252. // Fire Custom Events
  253. if (config.charCountGreaterThanMaxLengthEvent && config.charCountLessThanMaxLengthEvent) {
  254. if (charCount > config.maxCharCount && config.maxCharCount > -1) {
  255. config.charCountGreaterThanMaxLengthEvent(charCount, config.maxCharCount);
  256. } else {
  257. config.charCountLessThanMaxLengthEvent(charCount, config.maxCharCount);
  258. }
  259. }
  260. if (config.wordCountGreaterThanMaxLengthEvent && config.wordCountLessThanMaxLengthEvent) {
  261. if (wordCount > config.maxWordCount && config.maxWordCount > -1) {
  262. config.wordCountGreaterThanMaxLengthEvent(wordCount, config.maxWordCount);
  263. } else {
  264. config.wordCountLessThanMaxLengthEvent(wordCount, config.maxWordCount);
  265. }
  266. }
  267. return true;
  268. }
  269. editor.on("key", function (event) {
  270. if (editor.mode === "source") {
  271. updateCounter(event.editor);
  272. }
  273. }, editor, null, 100);
  274. editor.on("change", function (event) {
  275. updateCounter(event.editor);
  276. }, editor, null, 100);
  277. editor.on("uiSpace", function (event) {
  278. if (editor.elementMode === CKEDITOR.ELEMENT_MODE_INLINE) {
  279. if (event.data.space == "top") {
  280. event.data.html += "<div class=\"cke_wordcount\" style=\"\"" +
  281. " title=\"" +
  282. editor.lang.wordcount.title +
  283. "\"" +
  284. "><span id=\"" +
  285. counterId(event.editor) +
  286. "\" class=\"cke_path_item\">&nbsp;</span></div>";
  287. }
  288. } else {
  289. if (event.data.space == "bottom") {
  290. event.data.html += "<div class=\"cke_wordcount\" style=\"\"" +
  291. " title=\"" +
  292. editor.lang.wordcount.title +
  293. "\"" +
  294. "><span id=\"" +
  295. counterId(event.editor) +
  296. "\" class=\"cke_path_item\">&nbsp;</span></div>";
  297. }
  298. }
  299. }, editor, null, 100);
  300. editor.on("dataReady", function (event) {
  301. updateCounter(event.editor);
  302. }, editor, null, 100);
  303. editor.on("paste", function(event) {
  304. if (config.maxWordCount > 0 || config.maxCharCount > 0) {
  305. // Check if pasted content is above the limits
  306. var wordCount = -1,
  307. charCount = -1,
  308. text = event.editor.getData() + event.data.dataValue;
  309. if (config.showCharCount) {
  310. charCount = countCharacters(text, event.editor);
  311. }
  312. if (config.showWordCount) {
  313. wordCount = countWords(text);
  314. }
  315. // Instantiate the notification when needed and only have one instance
  316. if(notification === null) {
  317. notification = new CKEDITOR.plugins.notification(event.editor, {
  318. message: event.editor.lang.wordcount.pasteWarning,
  319. type: 'warning',
  320. duration: config.pasteWarningDuration
  321. });
  322. }
  323. if (config.maxCharCount > 0 && charCount > config.maxCharCount && config.hardLimit) {
  324. if(!notification.isVisible()) {
  325. notification.show();
  326. }
  327. event.cancel();
  328. }
  329. if (config.maxWordCount > 0 && wordCount > config.maxWordCount && config.hardLimit) {
  330. if(!notification.isVisible()) {
  331. notification.show();
  332. }
  333. event.cancel();
  334. }
  335. }
  336. }, editor, null, 100);
  337. editor.on("afterPaste", function (event) {
  338. updateCounter(event.editor);
  339. }, editor, null, 100);
  340. editor.on("blur", function () {
  341. if (intervalId) {
  342. window.clearInterval(intervalId);
  343. }
  344. }, editor, null, 300);
  345. }
  346. });