rating.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /*!
  2. * # Fomantic-UI - Rating
  3. * http://github.com/fomantic/Fomantic-UI/
  4. *
  5. *
  6. * Released under the MIT license
  7. * http://opensource.org/licenses/MIT
  8. *
  9. */
  10. ;(function ($, window, document, undefined) {
  11. 'use strict';
  12. $.isFunction = $.isFunction || function(obj) {
  13. return typeof obj === "function" && typeof obj.nodeType !== "number";
  14. };
  15. window = (typeof window != 'undefined' && window.Math == Math)
  16. ? window
  17. : (typeof self != 'undefined' && self.Math == Math)
  18. ? self
  19. : Function('return this')()
  20. ;
  21. $.fn.rating = function(parameters) {
  22. var
  23. $allModules = $(this),
  24. moduleSelector = $allModules.selector || '',
  25. time = new Date().getTime(),
  26. performance = [],
  27. query = arguments[0],
  28. methodInvoked = (typeof query == 'string'),
  29. queryArguments = [].slice.call(arguments, 1),
  30. returnedValue
  31. ;
  32. $allModules
  33. .each(function() {
  34. var
  35. settings = ( $.isPlainObject(parameters) )
  36. ? $.extend(true, {}, $.fn.rating.settings, parameters)
  37. : $.extend({}, $.fn.rating.settings),
  38. namespace = settings.namespace,
  39. className = settings.className,
  40. metadata = settings.metadata,
  41. selector = settings.selector,
  42. cssVars = settings.cssVars,
  43. eventNamespace = '.' + namespace,
  44. moduleNamespace = 'module-' + namespace,
  45. element = this,
  46. instance = $(this).data(moduleNamespace),
  47. $module = $(this),
  48. $icon = $module.find(selector.icon),
  49. initialLoad,
  50. module
  51. ;
  52. module = {
  53. initialize: function() {
  54. module.verbose('Initializing rating module', settings);
  55. if($icon.length === 0) {
  56. module.setup.layout();
  57. }
  58. if(settings.interactive && !module.is.disabled()) {
  59. module.enable();
  60. }
  61. else {
  62. module.disable();
  63. }
  64. module.set.initialLoad();
  65. module.set.rating( module.get.initialRating() );
  66. module.remove.initialLoad();
  67. module.instantiate();
  68. },
  69. instantiate: function() {
  70. module.verbose('Instantiating module', settings);
  71. instance = module;
  72. $module
  73. .data(moduleNamespace, module)
  74. ;
  75. },
  76. destroy: function() {
  77. module.verbose('Destroying previous instance', instance);
  78. module.remove.events();
  79. $module
  80. .removeData(moduleNamespace)
  81. ;
  82. },
  83. refresh: function() {
  84. $icon = $module.find(selector.icon);
  85. },
  86. setup: {
  87. layout: function() {
  88. var
  89. maxRating = module.get.maxRating(),
  90. icon = module.get.icon(),
  91. html = $.fn.rating.settings.templates.icon(maxRating, icon)
  92. ;
  93. module.debug('Generating icon html dynamically');
  94. $module
  95. .html(html)
  96. ;
  97. module.refresh();
  98. }
  99. },
  100. event: {
  101. mouseenter: function() {
  102. var
  103. $activeIcon = $(this)
  104. ;
  105. $activeIcon
  106. .nextAll()
  107. .removeClass(className.selected)
  108. ;
  109. $module
  110. .addClass(className.selected)
  111. ;
  112. $activeIcon
  113. .addClass(className.selected)
  114. .prevAll()
  115. .addClass(className.selected)
  116. ;
  117. },
  118. mouseleave: function() {
  119. $module
  120. .removeClass(className.selected)
  121. ;
  122. $icon
  123. .removeClass(className.selected)
  124. ;
  125. },
  126. click: function() {
  127. var
  128. $activeIcon = $(this),
  129. currentRating = module.get.rating(),
  130. rating = $icon.index($activeIcon) + 1,
  131. canClear = (settings.clearable == 'auto')
  132. ? ($icon.length === 1)
  133. : settings.clearable
  134. ;
  135. if(canClear && currentRating == rating) {
  136. module.clearRating();
  137. }
  138. else {
  139. module.set.rating( rating );
  140. }
  141. }
  142. },
  143. clearRating: function() {
  144. module.debug('Clearing current rating');
  145. module.set.rating(0);
  146. },
  147. bind: {
  148. events: function() {
  149. module.verbose('Binding events');
  150. $module
  151. .on('mouseenter' + eventNamespace, selector.icon, module.event.mouseenter)
  152. .on('mouseleave' + eventNamespace, selector.icon, module.event.mouseleave)
  153. .on('click' + eventNamespace, selector.icon, module.event.click)
  154. ;
  155. }
  156. },
  157. remove: {
  158. events: function() {
  159. module.verbose('Removing events');
  160. $module
  161. .off(eventNamespace)
  162. ;
  163. },
  164. initialLoad: function() {
  165. initialLoad = false;
  166. }
  167. },
  168. enable: function() {
  169. module.debug('Setting rating to interactive mode');
  170. module.bind.events();
  171. $module
  172. .removeClass(className.disabled)
  173. ;
  174. },
  175. disable: function() {
  176. module.debug('Setting rating to read-only mode');
  177. module.remove.events();
  178. $module
  179. .addClass(className.disabled)
  180. ;
  181. },
  182. is: {
  183. initialLoad: function() {
  184. return initialLoad;
  185. },
  186. disabled: function() {
  187. return $module.hasClass(className.disabled);
  188. }
  189. },
  190. get: {
  191. icon: function(){
  192. var icon = $module.data(metadata.icon);
  193. if (icon) {
  194. $module.removeData(metadata.icon);
  195. }
  196. return icon || settings.icon;
  197. },
  198. initialRating: function() {
  199. if($module.data(metadata.rating) !== undefined) {
  200. $module.removeData(metadata.rating);
  201. return $module.data(metadata.rating);
  202. }
  203. return settings.initialRating;
  204. },
  205. maxRating: function() {
  206. if($module.data(metadata.maxRating) !== undefined) {
  207. $module.removeData(metadata.maxRating);
  208. return $module.data(metadata.maxRating);
  209. }
  210. return settings.maxRating;
  211. },
  212. rating: function() {
  213. var
  214. currentRating = $icon.filter('.' + className.active).length
  215. ;
  216. module.verbose('Current rating retrieved', currentRating);
  217. return currentRating;
  218. }
  219. },
  220. set: {
  221. rating: function(rating) {
  222. var
  223. ratingIndex = Math.floor(
  224. (rating - 1 >= 0)
  225. ? (rating - 1)
  226. : 0
  227. ),
  228. $activeIcon = $icon.eq(ratingIndex),
  229. $partialActiveIcon = rating <= 1
  230. ? $activeIcon
  231. : $activeIcon.next()
  232. ,
  233. filledPercentage = (rating % 1) * 100
  234. ;
  235. $module
  236. .removeClass(className.selected)
  237. ;
  238. $icon
  239. .removeClass(className.selected)
  240. .removeClass(className.active)
  241. .removeClass(className.partiallyActive)
  242. ;
  243. if(rating > 0) {
  244. module.verbose('Setting current rating to', rating);
  245. $activeIcon
  246. .prevAll()
  247. .addBack()
  248. .addClass(className.active)
  249. ;
  250. if($activeIcon.next() && rating % 1 !== 0) {
  251. $partialActiveIcon
  252. .addClass(className.partiallyActive)
  253. .addClass(className.active)
  254. ;
  255. $partialActiveIcon
  256. .css(cssVars.filledCustomPropName, filledPercentage + '%')
  257. ;
  258. if($partialActiveIcon.css('backgroundColor') === 'transparent') {
  259. $partialActiveIcon
  260. .removeClass(className.partiallyActive)
  261. .removeClass(className.active)
  262. ;
  263. }
  264. }
  265. }
  266. if(!module.is.initialLoad()) {
  267. settings.onRate.call(element, rating);
  268. }
  269. },
  270. initialLoad: function() {
  271. initialLoad = true;
  272. }
  273. },
  274. setting: function(name, value) {
  275. module.debug('Changing setting', name, value);
  276. if( $.isPlainObject(name) ) {
  277. $.extend(true, settings, name);
  278. }
  279. else if(value !== undefined) {
  280. if($.isPlainObject(settings[name])) {
  281. $.extend(true, settings[name], value);
  282. }
  283. else {
  284. settings[name] = value;
  285. }
  286. }
  287. else {
  288. return settings[name];
  289. }
  290. },
  291. internal: function(name, value) {
  292. if( $.isPlainObject(name) ) {
  293. $.extend(true, module, name);
  294. }
  295. else if(value !== undefined) {
  296. module[name] = value;
  297. }
  298. else {
  299. return module[name];
  300. }
  301. },
  302. debug: function() {
  303. if(!settings.silent && settings.debug) {
  304. if(settings.performance) {
  305. module.performance.log(arguments);
  306. }
  307. else {
  308. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  309. module.debug.apply(console, arguments);
  310. }
  311. }
  312. },
  313. verbose: function() {
  314. if(!settings.silent && settings.verbose && settings.debug) {
  315. if(settings.performance) {
  316. module.performance.log(arguments);
  317. }
  318. else {
  319. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  320. module.verbose.apply(console, arguments);
  321. }
  322. }
  323. },
  324. error: function() {
  325. if(!settings.silent) {
  326. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  327. module.error.apply(console, arguments);
  328. }
  329. },
  330. performance: {
  331. log: function(message) {
  332. var
  333. currentTime,
  334. executionTime,
  335. previousTime
  336. ;
  337. if(settings.performance) {
  338. currentTime = new Date().getTime();
  339. previousTime = time || currentTime;
  340. executionTime = currentTime - previousTime;
  341. time = currentTime;
  342. performance.push({
  343. 'Name' : message[0],
  344. 'Arguments' : [].slice.call(message, 1) || '',
  345. 'Element' : element,
  346. 'Execution Time' : executionTime
  347. });
  348. }
  349. clearTimeout(module.performance.timer);
  350. module.performance.timer = setTimeout(module.performance.display, 500);
  351. },
  352. display: function() {
  353. var
  354. title = settings.name + ':',
  355. totalTime = 0
  356. ;
  357. time = false;
  358. clearTimeout(module.performance.timer);
  359. $.each(performance, function(index, data) {
  360. totalTime += data['Execution Time'];
  361. });
  362. title += ' ' + totalTime + 'ms';
  363. if(moduleSelector) {
  364. title += ' \'' + moduleSelector + '\'';
  365. }
  366. if($allModules.length > 1) {
  367. title += ' ' + '(' + $allModules.length + ')';
  368. }
  369. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  370. console.groupCollapsed(title);
  371. if(console.table) {
  372. console.table(performance);
  373. }
  374. else {
  375. $.each(performance, function(index, data) {
  376. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  377. });
  378. }
  379. console.groupEnd();
  380. }
  381. performance = [];
  382. }
  383. },
  384. invoke: function(query, passedArguments, context) {
  385. var
  386. object = instance,
  387. maxDepth,
  388. found,
  389. response
  390. ;
  391. passedArguments = passedArguments || queryArguments;
  392. context = element || context;
  393. if(typeof query == 'string' && object !== undefined) {
  394. query = query.split(/[\. ]/);
  395. maxDepth = query.length - 1;
  396. $.each(query, function(depth, value) {
  397. var camelCaseValue = (depth != maxDepth)
  398. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  399. : query
  400. ;
  401. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  402. object = object[camelCaseValue];
  403. }
  404. else if( object[camelCaseValue] !== undefined ) {
  405. found = object[camelCaseValue];
  406. return false;
  407. }
  408. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  409. object = object[value];
  410. }
  411. else if( object[value] !== undefined ) {
  412. found = object[value];
  413. return false;
  414. }
  415. else {
  416. return false;
  417. }
  418. });
  419. }
  420. if ( $.isFunction( found ) ) {
  421. response = found.apply(context, passedArguments);
  422. }
  423. else if(found !== undefined) {
  424. response = found;
  425. }
  426. if(Array.isArray(returnedValue)) {
  427. returnedValue.push(response);
  428. }
  429. else if(returnedValue !== undefined) {
  430. returnedValue = [returnedValue, response];
  431. }
  432. else if(response !== undefined) {
  433. returnedValue = response;
  434. }
  435. return found;
  436. }
  437. };
  438. if(methodInvoked) {
  439. if(instance === undefined) {
  440. module.initialize();
  441. }
  442. module.invoke(query);
  443. }
  444. else {
  445. if(instance !== undefined) {
  446. instance.invoke('destroy');
  447. }
  448. module.initialize();
  449. }
  450. })
  451. ;
  452. return (returnedValue !== undefined)
  453. ? returnedValue
  454. : this
  455. ;
  456. };
  457. $.fn.rating.settings = {
  458. name : 'Rating',
  459. namespace : 'rating',
  460. icon : 'star',
  461. silent : false,
  462. debug : false,
  463. verbose : false,
  464. performance : true,
  465. initialRating : 0,
  466. interactive : true,
  467. maxRating : 4,
  468. clearable : 'auto',
  469. fireOnInit : false,
  470. onRate : function(rating){},
  471. error : {
  472. method : 'The method you called is not defined',
  473. noMaximum : 'No maximum rating specified. Cannot generate HTML automatically'
  474. },
  475. metadata: {
  476. rating : 'rating',
  477. maxRating : 'maxRating',
  478. icon : 'icon'
  479. },
  480. className : {
  481. active : 'active',
  482. disabled : 'disabled',
  483. selected : 'selected',
  484. loading : 'loading',
  485. partiallyActive : 'partial'
  486. },
  487. cssVars : {
  488. filledCustomPropName : '--full'
  489. },
  490. selector : {
  491. icon : '.icon'
  492. },
  493. templates: {
  494. icon: function(maxRating, iconClass) {
  495. var
  496. icon = 1,
  497. html = ''
  498. ;
  499. while(icon <= maxRating) {
  500. html += '<i class="'+iconClass+' icon"></i>';
  501. icon++;
  502. }
  503. return html;
  504. }
  505. }
  506. };
  507. })( jQuery, window, document );