jquery.rateyo.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  1. 'use strict';
  2. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  3. var $$1 = _interopDefault(require('jquery'));
  4. function _typeof(obj) {
  5. "@babel/helpers - typeof";
  6. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  7. _typeof = function (obj) {
  8. return typeof obj;
  9. };
  10. } else {
  11. _typeof = function (obj) {
  12. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  13. };
  14. }
  15. return _typeof(obj);
  16. }
  17. function _typeof$1(obj) {
  18. "@babel/helpers - typeof";
  19. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  20. _typeof$1 = function (obj) {
  21. return typeof obj;
  22. };
  23. } else {
  24. _typeof$1 = function (obj) {
  25. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  26. };
  27. }
  28. return _typeof$1(obj);
  29. }
  30. function _defineProperty(obj, key, value) {
  31. if (key in obj) {
  32. Object.defineProperty(obj, key, {
  33. value: value,
  34. enumerable: true,
  35. configurable: true,
  36. writable: true
  37. });
  38. } else {
  39. obj[key] = value;
  40. }
  41. return obj;
  42. }
  43. function ownKeys(object, enumerableOnly) {
  44. var keys = Object.keys(object);
  45. if (Object.getOwnPropertySymbols) {
  46. var symbols = Object.getOwnPropertySymbols(object);
  47. if (enumerableOnly) symbols = symbols.filter(function (sym) {
  48. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  49. });
  50. keys.push.apply(keys, symbols);
  51. }
  52. return keys;
  53. }
  54. function _objectSpread2(target) {
  55. for (var i = 1; i < arguments.length; i++) {
  56. var source = arguments[i] != null ? arguments[i] : {};
  57. if (i % 2) {
  58. ownKeys(Object(source), true).forEach(function (key) {
  59. _defineProperty(target, key, source[key]);
  60. });
  61. } else if (Object.getOwnPropertyDescriptors) {
  62. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  63. } else {
  64. ownKeys(Object(source)).forEach(function (key) {
  65. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  66. });
  67. }
  68. }
  69. return target;
  70. }
  71. // The basic svg string required to generate stars
  72. var BASICSTAR = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<svg version=\"1.1\"" + "xmlns=\"http://www.w3.org/2000/svg\"" + "viewBox=\"0 12.705 512 486.59\"" + "x=\"0px\" y=\"0px\"" + "xml:space=\"preserve\">" + "<polygon " + "points=\"256.814,12.705 317.205,198.566" + " 512.631,198.566 354.529,313.435 " + "414.918,499.295 256.814,384.427 " + "98.713,499.295 159.102,313.435 " + "1,198.566 196.426,198.566 \"/>" + "</svg>"; // The Default values of different options available in the Plugin
  73. var DEFAULTS = {
  74. starWidth: "32px",
  75. normalFill: "gray",
  76. ratedFill: "#f39c12",
  77. numStars: 5,
  78. maxValue: 5,
  79. precision: 1,
  80. rating: 0,
  81. fullStar: false,
  82. halfStar: false,
  83. hover: true,
  84. readOnly: false,
  85. spacing: "0px",
  86. rtl: false,
  87. multiColor: null,
  88. onInit: null,
  89. onChange: null,
  90. onSet: null,
  91. starSvg: null
  92. }; //Default colors for multi-color rating
  93. var MULTICOLOR_OPTIONS = {
  94. startColor: "#c0392b",
  95. //red
  96. endColor: "#f1c40f" //yellow
  97. };
  98. // http://stackoverflow.com/questions/11381673/detecting-a-mobile-browser
  99. function isMobileBrowser() {
  100. var check = false;
  101. (function (a) {
  102. if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true;
  103. })(navigator.userAgent || navigator.vendor || window.opera);
  104. return check;
  105. }
  106. function checkPrecision(value, minValue, maxValue) {
  107. /*
  108. * This function removes the unnecessary precision, at Min and Max Values
  109. */
  110. // Its like comparing 0.0 with 0, which is true
  111. if (value === minValue) {
  112. value = minValue;
  113. } else if (value === maxValue) {
  114. value = maxValue;
  115. }
  116. return value;
  117. }
  118. function checkBounds(value, minValue, maxValue) {
  119. /*
  120. * Check if the value is between min and max values, if not, throw an error
  121. */
  122. var isValid = value >= minValue && value <= maxValue;
  123. if (!isValid) {
  124. throw Error("Invalid Rating, expected value between " + minValue + " and " + maxValue);
  125. }
  126. return value;
  127. }
  128. function isType(value, type) {
  129. return _typeof$1(value) === type;
  130. }
  131. function isDefined(value) {
  132. // Better way to check if a variable is defined or not
  133. return typeof value !== "undefined";
  134. }
  135. var isNumber = function isNumber(input) {
  136. return isType(input, "number");
  137. };
  138. var isString = function isString(input) {
  139. return isType(input, "string");
  140. };
  141. var isFunction = function isFunction(input) {
  142. return isType(input, "function");
  143. };
  144. var hexRegex = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;
  145. function hexToRGB(hex) {
  146. /*
  147. * Extracts and returns the Red, Blue, Green Channel values,
  148. * in the form of decimals
  149. */
  150. if (!hexRegex.test(hex)) {
  151. return null;
  152. }
  153. var hexValues = hexRegex.exec(hex),
  154. r = parseInt(hexValues[1], 16),
  155. g = parseInt(hexValues[2], 16),
  156. b = parseInt(hexValues[3], 16);
  157. return {
  158. r: r,
  159. g: g,
  160. b: b
  161. };
  162. }
  163. function getChannelValue(startVal, endVal, percent) {
  164. /*
  165. * Returns a value between `startVal` and `endVal` based on the percent
  166. */
  167. var newVal = (endVal - startVal) * (percent / 100);
  168. newVal = Math.round(startVal + newVal).toString(16);
  169. if (newVal.length === 1) {
  170. newVal = "0" + newVal;
  171. }
  172. return newVal;
  173. }
  174. function getColor(startColor, endColor, percent) {
  175. /*
  176. * Given the percentage( `percent` ) of `endColor` to be mixed
  177. * with the `startColor`, returns the mixed color.
  178. * Colors should be only in Hex Format
  179. */
  180. if (!startColor || !endColor) {
  181. return null;
  182. }
  183. percent = isDefined(percent) ? percent : 0;
  184. startColor = hexToRGB(startColor);
  185. endColor = hexToRGB(endColor);
  186. var r = getChannelValue(startColor.r, endColor.r, percent),
  187. b = getChannelValue(startColor.b, endColor.b, percent),
  188. g = getChannelValue(startColor.g, endColor.g, percent);
  189. return "#" + r + g + b;
  190. }
  191. var eventObjectMap = {};
  192. function getEventObject(event) {
  193. return eventObjectMap[event] || (eventObjectMap[event] = new String(event));
  194. }
  195. var handlerProxyMap = new WeakMap();
  196. function proxy(node, fn, event) {
  197. event = getEventObject(event);
  198. var eventHandlerMap = handlerProxyMap.get(node);
  199. if (!eventHandlerMap) {
  200. handlerProxyMap.set(node, eventHandlerMap = new WeakMap());
  201. }
  202. var handlerMap = eventHandlerMap.get(event);
  203. if (!handlerMap) {
  204. eventHandlerMap.set(event, handlerMap = new Map());
  205. }
  206. var handler = handlerMap.get(fn);
  207. if (handler) {
  208. return handler;
  209. }
  210. function proxy(e) {
  211. var data = e.detail;
  212. fn.call(node, e, data);
  213. }
  214. handlerMap.set(fn, proxy);
  215. return proxy;
  216. }
  217. proxy.get = function getOriginalFunction(node, fn, event) {
  218. event = getEventObject(event);
  219. var eventHandlerMap = handlerProxyMap.get(node);
  220. if (!eventHandlerMap) {
  221. return fn;
  222. }
  223. var handlerMap = eventHandlerMap.get(event);
  224. if (!handlerMap) {
  225. return fn;
  226. }
  227. return handlerMap.get(fn) || fn;
  228. };
  229. var Event = isFunction(window.Event) ? window.Event : function Event(event) {
  230. var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  231. var _params$bubbles = params.bubbles,
  232. bubbles = _params$bubbles === void 0 ? false : _params$bubbles,
  233. _params$cancelable = params.cancelable,
  234. cancelable = _params$cancelable === void 0 ? false : _params$cancelable;
  235. var evt = document.createEvent("Event");
  236. evt.initEvent(event, bubbles, cancelable);
  237. return evt;
  238. };
  239. var CustomEvent = isFunction(window.CustomEvent) ? window.CustomEvent : (CustomEvent.prototype = Object.create(Event.prototype), CustomEvent);
  240. var events = {
  241. trigger: function trigger(event, detail) {
  242. var eventProps = {
  243. bubbles: true
  244. };
  245. if (!isDefined(detail)) {
  246. this.node.dispatchEvent(new Event(event, eventProps));
  247. } else {
  248. this.node.dispatchEvent(new CustomEvent(event, _objectSpread2({
  249. detail: detail
  250. }, eventProps)));
  251. }
  252. return this;
  253. },
  254. on: function on(event, handler) {
  255. this.node.addEventListener(event, proxy(this.node, handler, event));
  256. return this;
  257. },
  258. off: function off(event, handler) {
  259. this.node.removeEventListener(event, proxy.get(this.node, handler, event));
  260. return this;
  261. }
  262. };
  263. var rateyoAttrRegex = /^rateyo(.+)$/;
  264. function classList(node, operation, input) {
  265. var className = node.className.trim();
  266. var classes = className && className.split(/\s/) || [],
  267. classMap = {};
  268. classes = classes.reduce(function (result, item, index) {
  269. if (!classMap.hasOwnProperty(item)) {
  270. result.push(item);
  271. classMap[item] = index;
  272. }
  273. return result;
  274. }, []);
  275. if (operation === classList.add) {
  276. if (classMap.hasOwnProperty(input)) {
  277. return;
  278. }
  279. classes.push(input);
  280. } else if (operation === classList.remove) {
  281. if (!classMap.hasOwnProperty(input)) {
  282. return;
  283. }
  284. classes.splice(classMap[input], 1);
  285. }
  286. node.className = classes.join(" ");
  287. }
  288. classList.add = "add";
  289. classList.remove = "remove";
  290. function El(node) {
  291. this.node = node;
  292. }
  293. El.prototype = {
  294. empty: function empty() {
  295. this.node.innerHTML = "";
  296. return this;
  297. },
  298. addClass: function addClass(className) {
  299. classList(this.node, classList.add, className);
  300. return this;
  301. },
  302. removeClass: function removeClass(className) {
  303. classList(this.node, classList.remove, className);
  304. return this;
  305. },
  306. appendTo: function appendTo(parent) {
  307. (El.isEl(parent) ? parent.node : parent).appendChild(this.node);
  308. return this;
  309. },
  310. css: function css(styleAttribute, value) {
  311. this.node.style[styleAttribute] = value;
  312. return this;
  313. },
  314. width: function width(_width) {
  315. if (!isDefined(_width)) {
  316. return this.node.getBoundingClientRect().width;
  317. }
  318. this.css("width", _width + (isNumber(_width) ? "px" : ""));
  319. },
  320. find: function find(selector) {
  321. return $(this.node.querySelectorAll(selector));
  322. },
  323. attr: function attr(attrObj) {
  324. for (var attrName in attrObj) {
  325. if (attrObj.hasOwnProperty(attrName)) {
  326. this.node.setAttribute(attrName, attrObj[attrName]);
  327. }
  328. }
  329. return this;
  330. },
  331. removeAttr: function removeAttr(attributeName) {
  332. this.node.removeAttribute(attributeName);
  333. return this;
  334. },
  335. children: function children() {
  336. return $(this.node.childNodes);
  337. },
  338. remove: function remove() {
  339. return this.node.remove();
  340. },
  341. offset: function offset() {
  342. var _this$node$getBoundin = this.node.getBoundingClientRect(),
  343. top = _this$node$getBoundin.top,
  344. left = _this$node$getBoundin.left,
  345. bottom = _this$node$getBoundin.bottom,
  346. right = _this$node$getBoundin.right;
  347. return {
  348. top: top,
  349. left: left,
  350. bottom: bottom,
  351. right: right
  352. };
  353. },
  354. dataAttrOptions: function dataAttrOptions() {
  355. var dataset = this.node.dataset;
  356. return Object.keys(dataset).reduce(function (options, attr) {
  357. var match = attr.match(rateyoAttrRegex);
  358. if (!match) {
  359. return options;
  360. }
  361. var rateyoAttr = match[1],
  362. option = rateyoAttr[0].toLowerCase() + rateyoAttr.slice(1);
  363. options[option] = dataset[attr];
  364. return options;
  365. }, {});
  366. }
  367. };
  368. El.prototype = _objectSpread2(_objectSpread2({}, El.prototype), events);
  369. El.isEl = function (node) {
  370. return node instanceof El;
  371. };
  372. function Collection(nodeList) {
  373. var _this = this;
  374. this.collection = [];
  375. Array.prototype.forEach.call(nodeList, function (node) {
  376. _this.collection.push(new El(node));
  377. });
  378. }
  379. Collection.isCollection = function (input) {
  380. return input instanceof Collection;
  381. };
  382. Collection.prototype = {};
  383. var _loop = function _loop(method) {
  384. if (!El.prototype.hasOwnProperty(method)) {
  385. return "continue";
  386. }
  387. function proxy() {
  388. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  389. args[_key] = arguments[_key];
  390. }
  391. this.collection.forEach(function (el) {
  392. return El.isEl(el) && el[method].apply(el, args);
  393. });
  394. return this;
  395. }
  396. Collection.prototype[method] = proxy;
  397. };
  398. for (var method in El.prototype) {
  399. var _ret = _loop(method);
  400. if (_ret === "continue") continue;
  401. }
  402. var parser = new DOMParser();
  403. function parseHTML(html) {
  404. return parser.parseFromString(html.trim(), "text/html").body.childNodes;
  405. }
  406. function $(node) {
  407. node = isString(node) && parseHTML(node) || node;
  408. if (El.isEl(node) || Collection.isCollection(node)) {
  409. return node;
  410. }
  411. if (node instanceof NodeList) {
  412. return new Collection(node);
  413. }
  414. return new El(node);
  415. }
  416. $.El = El;
  417. var instanceMap = new WeakMap();
  418. function RateYo(node) {
  419. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  420. if (!(this instanceof RateYo)) {
  421. return new RateYo(node, options);
  422. }
  423. if (instanceMap.has(node)) {
  424. return instanceMap.get(node);
  425. }
  426. var that = this;
  427. this.node = node;
  428. var $node = $(node);
  429. options = _objectSpread2(_objectSpread2(_objectSpread2({}, DEFAULTS), options), $node.dataAttrOptions()); // Remove any stuff that is present inside the container, and add the plugin class
  430. $node.empty().addClass("jq-ry-container");
  431. /*
  432. * Basically the plugin displays the rating using two rows of stars lying one above
  433. * the other, the row that is on the top represents the actual rating, and the one
  434. * behind acts just like a background.
  435. *
  436. * `$groupWrapper`: is an element that wraps both the rows
  437. * `$normalGroup`: is the container for row of stars thats behind and
  438. * acts as background
  439. * `$ratedGroup`: is the container for row of stars that display the actual rating.
  440. *
  441. * The rating is displayed by adjusting the width of `$ratedGroup`
  442. */
  443. var $groupWrapper = $(document.createElement("div")).addClass("jq-ry-group-wrapper").appendTo($node);
  444. var $normalGroup = $(document.createElement("div")).addClass("jq-ry-normal-group").addClass("jq-ry-group").appendTo($groupWrapper);
  445. var $ratedGroup = $(document.createElement("div")).addClass("jq-ry-rated-group").addClass("jq-ry-group").appendTo($groupWrapper);
  446. /*
  447. * Variable `step`: store the value of the rating for each star
  448. * eg: if `maxValue` is 5 and `numStars` is 5, value of each star
  449. * is 1.
  450. * Variable `starWidth`: stores the decimal value of width of star in units of px
  451. * Variable `percentOfStar`: stores the percentage of width each star takes w.r.t
  452. * the container
  453. * Variable `spacing`: stores the decimal value of the spacing between stars
  454. * in the units of px
  455. * Variable `percentOfSpacing`: stores the percentage of width of the spacing
  456. * between stars w.r.t the container
  457. */
  458. var step,
  459. starWidth,
  460. percentOfStar,
  461. spacing,
  462. percentOfSpacing,
  463. containerWidth,
  464. minValue = 0;
  465. /*
  466. * `currentRating` contains rating that is being displayed at the latest point of
  467. * time.
  468. *
  469. * When ever you hover over the plugin UI, the rating value changes
  470. * according to the place where you point the cursor, currentRating contains
  471. * the current value of rating that is being shown in the UI
  472. */
  473. var currentRating = options.rating; // A flag to store if the plugin is already being displayed in the UI
  474. var isInitialized = false;
  475. function showRating(ratingVal) {
  476. /*
  477. * The function is responsible for displaying the rating by changing
  478. * the width of `$ratedGroup`
  479. */
  480. if (!isDefined(ratingVal)) {
  481. ratingVal = options.rating;
  482. } // Storing the value that is being shown in `currentRating`.
  483. currentRating = ratingVal;
  484. var numStarsToShow = ratingVal / step; // calculating the percentage of width of $ratedGroup with respect to its parent
  485. var percent = numStarsToShow * percentOfStar;
  486. if (numStarsToShow > 1) {
  487. // adding the percentage of space that is taken by the gap the stars
  488. percent += (Math.ceil(numStarsToShow) - 1) * percentOfSpacing;
  489. }
  490. setRatedFill(options.ratedFill);
  491. percent = options.rtl ? 100 - percent : percent;
  492. if (percent < 0) {
  493. percent = 0;
  494. } else if (percent > 100) {
  495. percent = 100;
  496. }
  497. $ratedGroup.css("width", percent + "%");
  498. }
  499. function setContainerWidth() {
  500. /*
  501. * Set the width of the `this.node` based on the width of each star and
  502. * the space between them
  503. */
  504. containerWidth = starWidth * options.numStars + spacing * (options.numStars - 1);
  505. percentOfStar = starWidth / containerWidth * 100;
  506. percentOfSpacing = spacing / containerWidth * 100;
  507. $node.width(containerWidth);
  508. showRating();
  509. }
  510. function setStarWidth(newWidth) {
  511. /*
  512. * Set the width and height of each SVG star, called whenever one changes the
  513. * `starWidth` option
  514. */
  515. // The width and height of the star should be the same
  516. var starHeight = options.starWidth = newWidth;
  517. starWidth = window.parseFloat(options.starWidth.replace("px", ""));
  518. $normalGroup.find("svg").attr({
  519. width: options.starWidth,
  520. height: starHeight
  521. });
  522. $ratedGroup.find("svg").attr({
  523. width: options.starWidth,
  524. height: starHeight
  525. });
  526. setContainerWidth();
  527. return $node;
  528. }
  529. function setSpacing(newSpacing) {
  530. /*
  531. * Set spacing between the SVG stars, called whenever one changes
  532. * the `spacing` option
  533. */
  534. options.spacing = newSpacing;
  535. spacing = parseFloat(options.spacing.replace("px", ""));
  536. $normalGroup.find("svg:not(:first-child)").css("margin-left", newSpacing);
  537. $ratedGroup.find("svg:not(:first-child)").css("margin-left", newSpacing);
  538. setContainerWidth();
  539. return $node;
  540. }
  541. function setNormalFill(newFill) {
  542. /*
  543. * Set the background fill of the Stars, called whenever one changes the
  544. * `normalFill` option
  545. */
  546. options.normalFill = newFill;
  547. var $svgs = (options.rtl ? $ratedGroup : $normalGroup).find("svg");
  548. $svgs.attr({
  549. fill: options.normalFill
  550. });
  551. return $node;
  552. }
  553. /*
  554. * Store the recent `ratedFill` option in a variable
  555. * so that if multiColor is unset, we can use the perviously set `ratedFill`
  556. * from this variable
  557. */
  558. var ratedFill = options.ratedFill;
  559. function setRatedFill(newFill) {
  560. /*
  561. * Set ratedFill of the stars, called when one changes the `ratedFill` option
  562. */
  563. /*
  564. * If `multiColor` option is set, `newFill` variable is dynamically set
  565. * based on the rating, what ever set as parameter will be discarded
  566. */
  567. if (options.multiColor) {
  568. var ratingDiff = currentRating - minValue,
  569. percentCovered = ratingDiff / options.maxValue * 100;
  570. var colorOpts = options.multiColor || {},
  571. startColor = colorOpts.startColor || MULTICOLOR_OPTIONS.startColor,
  572. endColor = colorOpts.endColor || MULTICOLOR_OPTIONS.endColor;
  573. newFill = getColor(startColor, endColor, percentCovered);
  574. } else {
  575. ratedFill = newFill;
  576. }
  577. options.ratedFill = newFill;
  578. var $svgs = (options.rtl ? $normalGroup : $ratedGroup).find("svg");
  579. $svgs.attr({
  580. fill: options.ratedFill
  581. });
  582. return $node;
  583. }
  584. function setRtl(newValue) {
  585. newValue = !!newValue;
  586. options.rtl = newValue;
  587. setNormalFill(options.normalFill);
  588. showRating();
  589. }
  590. function setMultiColor(colorOptions) {
  591. /*
  592. * called whenever one changes the `multiColor` option
  593. */
  594. options.multiColor = colorOptions; // set the recently set `ratedFill` option, if multiColor Options are unset
  595. setRatedFill(colorOptions ? colorOptions : ratedFill);
  596. }
  597. function setNumStars(newValue) {
  598. /*
  599. * Set the number of stars to use to display the rating, called whenever one
  600. * changes the `numStars` option
  601. */
  602. options.numStars = newValue;
  603. step = options.maxValue / options.numStars;
  604. $normalGroup.empty();
  605. $ratedGroup.empty();
  606. for (var i = 0; i < options.numStars; i++) {
  607. $(options.starSvg || BASICSTAR).appendTo($normalGroup);
  608. $(options.starSvg || BASICSTAR).appendTo($ratedGroup);
  609. }
  610. setStarWidth(options.starWidth);
  611. setNormalFill(options.normalFill);
  612. setSpacing(options.spacing);
  613. showRating();
  614. return $node;
  615. }
  616. function setMaxValue(newValue) {
  617. /*
  618. * set the Maximum Value of rating to be allowed, called whenever
  619. * one changes the `maxValue` option
  620. */
  621. options.maxValue = newValue;
  622. step = options.maxValue / options.numStars;
  623. if (options.rating > newValue) {
  624. setRating(newValue);
  625. }
  626. showRating();
  627. return $node;
  628. }
  629. function setPrecision(newValue) {
  630. /*
  631. * Set the precision of the rating value, called if one changes the
  632. * `precision` option
  633. */
  634. options.precision = newValue;
  635. setRating(options.rating);
  636. return $node;
  637. }
  638. function setHalfStar(newValue) {
  639. /*
  640. * This function will be called if one changes the `halfStar` option
  641. */
  642. options.halfStar = newValue;
  643. return $node;
  644. }
  645. function setFullStar(newValue) {
  646. /*
  647. * This function will be called if one changes the `fullStar` option
  648. */
  649. options.fullStar = newValue;
  650. return $node;
  651. }
  652. function round(value) {
  653. /*
  654. * Rounds the value of rating if `halfStar` or `fullStar` options are chosen
  655. */
  656. var remainder = value % step,
  657. halfStep = step / 2,
  658. isHalfStar = options.halfStar,
  659. isFullStar = options.fullStar;
  660. if (!isFullStar && !isHalfStar) {
  661. return value;
  662. }
  663. if (isFullStar || isHalfStar && remainder > halfStep) {
  664. value += step - remainder;
  665. } else {
  666. value = value - remainder;
  667. if (remainder > 0) {
  668. value += halfStep;
  669. }
  670. }
  671. return value;
  672. }
  673. function calculateRating(e) {
  674. /*
  675. * Calculates and returns the rating based on the position of cursor w.r.t the
  676. * plugin container
  677. */
  678. var position = $normalGroup.offset(),
  679. nodeStartX = position.left,
  680. nodeEndX = nodeStartX + $normalGroup.width();
  681. var maxValue = options.maxValue; // The x-coordinate(position) of the mouse pointer w.r.t page
  682. var pageX = e.pageX;
  683. var calculatedRating = 0; // If the mouse pointer is to the left of the container
  684. if (pageX < nodeStartX) {
  685. calculatedRating = minValue;
  686. } else if (pageX > nodeEndX) {
  687. // If the mouse pointer is right of the container
  688. calculatedRating = maxValue;
  689. } else {
  690. // If the mouse pointer is inside the continer
  691. /*
  692. * The fraction of width covered by the pointer w.r.t to the total width
  693. * of the container.
  694. */
  695. var calcPrcnt = (pageX - nodeStartX) / (nodeEndX - nodeStartX);
  696. if (spacing > 0) {
  697. /*
  698. * If there is spacing between stars, take the percentage of width covered
  699. * and subtract the percentage of width covered by stars and spacing, to find
  700. * how many stars are covered, the number of stars covered is the rating
  701. *
  702. * TODO: I strongly feel that this logic can be improved!, Please help!
  703. */
  704. calcPrcnt *= 100;
  705. var remPrcnt = calcPrcnt;
  706. while (remPrcnt > 0) {
  707. if (remPrcnt > percentOfStar) {
  708. calculatedRating += step;
  709. remPrcnt -= percentOfStar + percentOfSpacing;
  710. } else {
  711. calculatedRating += remPrcnt / percentOfStar * step;
  712. remPrcnt = 0;
  713. }
  714. }
  715. } else {
  716. /*
  717. * If there is not spacing between stars, the fraction of width covered per
  718. * `maxValue` is the rating
  719. */
  720. calculatedRating = calcPrcnt * options.maxValue;
  721. } // Round the rating if `halfStar` or `fullStar` options are chosen
  722. calculatedRating = round(calculatedRating);
  723. }
  724. if (options.rtl) {
  725. calculatedRating = maxValue - calculatedRating;
  726. }
  727. return parseFloat(calculatedRating);
  728. }
  729. function setReadOnly(newValue) {
  730. /*
  731. * UnBinds mouse event handlers, called when whenever one changes the
  732. * `readOnly` option
  733. */
  734. options.readOnly = newValue;
  735. $node.attr({
  736. "readonly": true
  737. });
  738. unbindEvents();
  739. if (!newValue) {
  740. $node.removeAttr("readonly");
  741. bindEvents();
  742. }
  743. return $node;
  744. }
  745. function setRating(newValue) {
  746. /*
  747. * Sets the rating of the Plugin, Called when option `rating` is changed
  748. * or, when `rating` method is called
  749. */
  750. var rating = newValue;
  751. var maxValue = options.maxValue;
  752. if (typeof rating === "string") {
  753. // If rating is given in percentage, maxValue should be 100
  754. if (rating[rating.length - 1] === "%") {
  755. rating = rating.substr(0, rating.length - 1);
  756. maxValue = 100;
  757. setMaxValue(maxValue);
  758. }
  759. rating = parseFloat(rating);
  760. }
  761. checkBounds(rating, minValue, maxValue);
  762. rating = parseFloat(rating.toFixed(options.precision));
  763. checkPrecision(parseFloat(rating), minValue, maxValue);
  764. options.rating = rating;
  765. showRating();
  766. if (isInitialized) {
  767. $node.trigger("rateyo.set", {
  768. rating: rating
  769. });
  770. }
  771. return $node;
  772. }
  773. function setOnInit(method) {
  774. /*
  775. * set what method to be called on Initialization
  776. */
  777. options.onInit = method;
  778. return $node;
  779. }
  780. function setOnSet(method) {
  781. /*
  782. * set what method to be called when rating is set
  783. */
  784. options.onSet = method;
  785. return $node;
  786. }
  787. function setOnChange(method) {
  788. /*
  789. * set what method to be called rating in the UI is changed
  790. */
  791. options.onChange = method;
  792. return $node;
  793. }
  794. this.rating = function (newValue) {
  795. /*
  796. * rating getter/setter
  797. */
  798. if (!isDefined(newValue)) {
  799. return options.rating;
  800. }
  801. setRating(newValue);
  802. return $node;
  803. };
  804. this.destroy = function () {
  805. /*
  806. * Removes the Rating UI by clearing the content, and removing the custom classes
  807. */
  808. if (!options.readOnly) {
  809. unbindEvents();
  810. }
  811. instanceMap["delete"](node);
  812. $node.removeClass("jq-ry-container").children().remove();
  813. return $node;
  814. };
  815. this.method = function (methodName) {
  816. /*
  817. * Method to call the methods of RateYo Instance
  818. */
  819. if (!methodName) {
  820. throw Error("Method name not specified!");
  821. }
  822. if (!isDefined(this[methodName])) {
  823. throw Error("Method " + methodName + " doesn't exist!");
  824. }
  825. var args = Array.prototype.slice.apply(arguments, []),
  826. params = args.slice(1),
  827. method = this[methodName];
  828. return method.apply(this, params);
  829. };
  830. this.option = function (optionName, param) {
  831. /*
  832. * Method to get/set Options
  833. */
  834. if (!isDefined(optionName)) {
  835. return options;
  836. }
  837. var method;
  838. switch (optionName) {
  839. case "starWidth":
  840. method = setStarWidth;
  841. break;
  842. case "numStars":
  843. method = setNumStars;
  844. break;
  845. case "normalFill":
  846. method = setNormalFill;
  847. break;
  848. case "ratedFill":
  849. method = setRatedFill;
  850. break;
  851. case "multiColor":
  852. method = setMultiColor;
  853. break;
  854. case "maxValue":
  855. method = setMaxValue;
  856. break;
  857. case "precision":
  858. method = setPrecision;
  859. break;
  860. case "rating":
  861. method = setRating;
  862. break;
  863. case "halfStar":
  864. method = setHalfStar;
  865. break;
  866. case "fullStar":
  867. method = setFullStar;
  868. break;
  869. case "readOnly":
  870. method = setReadOnly;
  871. break;
  872. case "spacing":
  873. method = setSpacing;
  874. break;
  875. case "rtl":
  876. method = setRtl;
  877. break;
  878. case "onInit":
  879. method = setOnInit;
  880. break;
  881. case "onSet":
  882. method = setOnSet;
  883. break;
  884. case "onChange":
  885. method = setOnChange;
  886. break;
  887. default:
  888. throw Error("No such option as " + optionName);
  889. }
  890. return isDefined(param) ? method(param) : options[optionName];
  891. };
  892. function onMouseEnter(e) {
  893. if (!options.hover) {
  894. return;
  895. }
  896. /*
  897. * If the Mouse Pointer is inside the container, calculate and show the rating
  898. * in UI
  899. */
  900. var rating = calculateRating(e).toFixed(options.precision);
  901. var maxValue = options.maxValue;
  902. rating = checkPrecision(parseFloat(rating), minValue, maxValue);
  903. showRating(rating);
  904. $node.trigger("rateyo.change", {
  905. rating: rating
  906. });
  907. }
  908. function onMouseLeave() {
  909. if (isMobileBrowser() || !options.hover) {
  910. return;
  911. }
  912. /*
  913. * If mouse leaves, revert the rating in UI to previously set rating,
  914. * when empty value is passed to showRating, it will take the previously set
  915. * rating
  916. */
  917. showRating();
  918. $node.trigger("rateyo.change", {
  919. rating: options.rating
  920. });
  921. }
  922. function onMouseClick(e) {
  923. /*
  924. * On clicking the mouse inside the container, calculate and set the rating
  925. */
  926. var resultantRating = calculateRating(e).toFixed(options.precision);
  927. resultantRating = parseFloat(resultantRating);
  928. that.rating(resultantRating);
  929. }
  930. function onInit(e, data) {
  931. if (options.onInit && typeof options.onInit === "function") {
  932. options.onInit.apply(this, [data.rating, that]);
  933. }
  934. }
  935. function onChange(e, data) {
  936. if (options.onChange && typeof options.onChange === "function") {
  937. options.onChange.apply(this, [data.rating, that]);
  938. }
  939. }
  940. function onSet(e, data) {
  941. if (options.onSet && typeof options.onSet === "function") {
  942. options.onSet.apply(this, [data.rating, that]);
  943. }
  944. }
  945. function bindEvents() {
  946. $node.on("mousemove", onMouseEnter).on("mouseenter", onMouseEnter).on("mouseleave", onMouseLeave).on("click", onMouseClick).on("rateyo.init", onInit).on("rateyo.change", onChange).on("rateyo.set", onSet);
  947. }
  948. function unbindEvents() {
  949. $node.off("mousemove", onMouseEnter).off("mouseenter", onMouseEnter).off("mouseleave", onMouseLeave).off("click", onMouseClick).off("rateyo.init", onInit).off("rateyo.change", onChange).off("rateyo.set", onSet);
  950. }
  951. setNumStars(options.numStars);
  952. setReadOnly(options.readOnly);
  953. if (options.rtl) {
  954. setRtl(options.rtl);
  955. }
  956. instanceMap.set(node, this);
  957. this.rating(options.rating, true);
  958. isInitialized = true;
  959. $node.trigger("rateyo.init", {
  960. rating: options.rating
  961. });
  962. }
  963. Object.defineProperty(RateYo.prototype, "on", {
  964. value: function on(eventName, handler) {
  965. $(this.node).on(eventName, handler);
  966. return this;
  967. }
  968. });
  969. Object.defineProperty(RateYo.prototype, "off", {
  970. value: function off(eventName, handler) {
  971. $(this.node).off(eventName, handler);
  972. return this;
  973. }
  974. });
  975. Object.defineProperty(RateYo, "has", {
  976. value: function has(node) {
  977. return instanceMap.has(node);
  978. }
  979. });
  980. Object.defineProperty(RateYo, "get", {
  981. value: function get(node) {
  982. return instanceMap.get(node);
  983. }
  984. });
  985. Object.defineProperty(RateYo, "_$", {
  986. get: function get() {
  987. return $;
  988. }
  989. });
  990. var dollar = RateYo._$;
  991. var eventsTrigger = dollar.El.prototype.trigger;
  992. dollar.El.prototype.trigger = function overrideTrigger() {
  993. var _$;
  994. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  995. args[_key] = arguments[_key];
  996. }
  997. eventsTrigger.apply(this, args); // seems like jquery .on() does not handle custom events
  998. // also handlers registered using .addEventListener will not
  999. // be called when event is triggered using .trigger()
  1000. // triggering with jquery .trigger() again for those handlers
  1001. // registered using
  1002. (_$ = $$1(this.node)).trigger.apply(_$, args);
  1003. };
  1004. function _rateYo(options) {
  1005. /* jshint validthis:true */
  1006. var $nodes = $$1(this);
  1007. if ($nodes.length === 0) {
  1008. return $nodes;
  1009. }
  1010. var args = Array.prototype.slice.apply(arguments, []);
  1011. if (args.length === 0) {
  1012. //If args length is 0, Initialize the UI with default settings
  1013. options = args[0] = {};
  1014. } else if (args.length === 1 && _typeof(args[0]) === "object") {
  1015. //If an Object is specified as first argument, it is considered as options
  1016. options = args[0];
  1017. } else if (args.length >= 1 && typeof args[0] === "string") {
  1018. /*
  1019. * if there is only one argument, and if its a string, it is supposed to be a
  1020. * method name, if more than one argument is specified, the remaining arguments
  1021. * except the first argument, will be passed as a params to the specified method
  1022. */
  1023. var methodName = args[0],
  1024. params = args.slice(1);
  1025. var result = [];
  1026. $$1.each($nodes, function (i, node) {
  1027. var existingInstance = RateYo.get(node);
  1028. if (!existingInstance) {
  1029. throw Error("Trying to set options before even initialization");
  1030. }
  1031. var method = existingInstance[methodName];
  1032. if (!method) {
  1033. throw Error("Method " + methodName + " does not exist!");
  1034. }
  1035. var returnVal = method.apply(existingInstance, params);
  1036. result.push(returnVal);
  1037. });
  1038. /*
  1039. * If the plugin in being called on only one jQuery Element, return only the
  1040. * first value, to support chaining.
  1041. */
  1042. result = result.length === 1 ? result[0] : result;
  1043. return result;
  1044. } else {
  1045. throw Error("Invalid Arguments");
  1046. }
  1047. return $$1.each($nodes, function () {
  1048. return new RateYo(this, $$1.extend({}, options));
  1049. });
  1050. }
  1051. function rateYo() {
  1052. /* jshint validthis:true */
  1053. return _rateYo.apply(this, Array.prototype.slice.apply(arguments, []));
  1054. }
  1055. $$1.fn.rateYo = rateYo;