UNPKG

react-rater-plus

Version:

A star rater in react.js with support for CSS modules and theming

813 lines (697 loc) 26.3 kB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("prop-types"), require("react"), require("react-css-themr")); else if(typeof define === 'function' && define.amd) define("ReactRaterPlus", ["prop-types", "react", "react-css-themr"], factory); else if(typeof exports === 'object') exports["ReactRaterPlus"] = factory(require("prop-types"), require("react"), require("react-css-themr")); else root["ReactRaterPlus"] = factory(root["prop-types"], root["react"], root["react-css-themr"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_7__, __WEBPACK_EXTERNAL_MODULE_8__, __WEBPACK_EXTERNAL_MODULE_9__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.css = exports.ThemedRater = exports.Rater = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(8); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(7); var _propTypes2 = _interopRequireDefault(_propTypes); var _rater = __webpack_require__(6); var _rater2 = _interopRequireDefault(_rater); var _reactCssThemr = __webpack_require__(9); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Rater = exports.Rater = function (_Component) { _inherits(Rater, _Component); function Rater() { _classCallCheck(this, Rater); return _possibleConstructorReturn(this, (Rater.__proto__ || Object.getPrototypeOf(Rater)).apply(this, arguments)); } _createClass(Rater, [{ key: 'setRate', value: function setRate(rating) { this.setState({ newRating: rating }); } }, { key: 'bindFunctions', value: function bindFunctions() { var _this2 = this; this.onCancelRate = this.setRate.bind(this, null); this.onRate = []; this.willRate = []; this.interactive = false; var _loop = function _loop(i) { if (typeof _this2.props.onRate === 'function') { _this2.interactive = true; // Enable interactivity _this2.onRate[i] = function () { _this2.props.onRate(i + 1); }; } _this2.willRate[i] = _this2.setRate.bind(_this2, i + 1); }; for (var i = this.props.total - 1; i >= 0; i--) { _loop(i); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.total > this.props.total || !this.props.onRate === nextProps.onRate) this.bindFunctions(); } }, { key: 'componentWillMount', value: function componentWillMount() { this.bindFunctions(); } }, { key: 'render', value: function render() { var _this3 = this; var _props = this.props, theme = _props.theme, total = _props.total, rating = _props.rating, item = _props.item, restProps = _objectWithoutProperties(_props, ['theme', 'total', 'rating', 'item']); delete restProps.onRate; delete restProps.children; var newRating = this.state && this.state.newRating; var children = this.props.children ? this.props.children.filter(Boolean) : []; var nodes = Array(total).fill(1).map(function (_, i) { var tags = { active: !newRating && rating - i >= 1, willBeActive: !!newRating && i < newRating, halfActive: !newRating && rating - i >= 0.5 && rating - i < 1, disabled: !_this3.interactive }; var props = { // sets key key: i, // maps tags to classnames from theme className: Object.keys(tags).map(function (tag) { return tags[tag] && theme[tag]; }).filter(Boolean).join(" "), // callback for willRate onMouseEnter: _this3.interactive && typeof _this3.willRate[i] === 'function' ? _this3.willRate[i] : null, // callback for onClick onClick: _this3.interactive && typeof _this3.onRate[i] === 'function' ? _this3.onRate[i] : null }; if (children.length) { return _react2.default.cloneElement(children[i % children.length], _extends({}, props, tags)); } else if (tags.halfActive) { // Render extra item to display half item return _react2.default.createElement( 'a', props, _react2.default.createElement( 'span', null, item ), item ); } else { return _react2.default.createElement( 'a', props, item ); } }); // Set onMouseLeave for props on div when interactive if (this.interactive) restProps.onMouseLeave = this.onCancelRate; return _react2.default.createElement( 'div', _extends({ className: theme['rater'] }, restProps), nodes ); } }]); return Rater; }(_react.Component); Rater.propTypes = { theme: _propTypes2.default.object, total: _propTypes2.default.number, rating: _propTypes2.default.number, children: _propTypes2.default.any, onRate: _propTypes2.default.func, item: _propTypes2.default.any }; Rater.defaultProps = { total: 5, rating: 0, theme: { active: 'active', willBeActive: 'willBeActive', halfActive: 'halfActive', disabled: 'disabled', rater: 'rater' }, item: "★" }; var ThemedRater = exports.ThemedRater = (0, _reactCssThemr.themr)('Rater', _rater2.default)(Rater); exports.css = _rater2.default; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _Rater = __webpack_require__(0); Object.defineProperty(exports, 'Rater', { enumerable: true, get: function get() { return _Rater.Rater; } }); Object.defineProperty(exports, 'ThemedRater', { enumerable: true, get: function get() { return _Rater.ThemedRater; } }); Object.defineProperty(exports, 'default', { enumerable: true, get: function get() { return _Rater.ThemedRater; } }); /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(3)(); // imports // module exports.push([module.i, ".rater_rater_Pjc {\n display: inline-block;\n line-height: normal\n}\n.rater_rater_Pjc a {\n cursor: pointer;\n color: #ccc;\n position: relative\n}\n.rater_rater_Pjc a.rater_willBeActive_1U9 {\n color: #666\n}\n.rater_rater_Pjc a.rater_active_3Pu {\n color: #f4e242\n}\n.rater_rater_Pjc a.rater_halfActive_Nob span {\n color: #f4e242;\n position: absolute;\n left: 0;\n width: 50%;\n overflow: hidden\n}\n.rater_rater_Pjc a.rater_disabled_2p_ {\n cursor: default\n}\n", ""]); // exports exports.locals = { "rater": "rater_rater_Pjc", "willBeActive": "rater_willBeActive_1U9", "active": "rater_active_3Pu", "halfActive": "rater_halfActive_Nob", "disabled": "rater_disabled_2p_" }; /***/ }), /* 3 */ /***/ (function(module, exports) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function() { var list = []; // return the list of modules as css string list.toString = function toString() { var result = []; for(var i = 0; i < this.length; i++) { var item = this[i]; if(item[2]) { result.push("@media " + item[2] + "{" + item[1] + "}"); } else { result.push(item[1]); } } return result.join(""); }; // import a list of modules into the list list.i = function(modules, mediaQuery) { if(typeof modules === "string") modules = [[null, modules, ""]]; var alreadyImportedModules = {}; for(var i = 0; i < this.length; i++) { var id = this[i][0]; if(typeof id === "number") alreadyImportedModules[id] = true; } for(i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) { if(mediaQuery && !item[2]) { item[2] = mediaQuery; } else if(mediaQuery) { item[2] = "(" + item[2] + ") and (" + mediaQuery + ")"; } list.push(item); } } }; return list; }; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}, memoize = function(fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }, isOldIE = memoize(function() { // Test for IE <= 9 as proposed by Browserhacks // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 // Tests for existence of standard globals is to allow style-loader // to operate correctly into non-standard environments // @see https://github.com/webpack-contrib/style-loader/issues/177 return window && document && document.all && !window.atob; }), getElement = (function(fn) { var memo = {}; return function(selector) { if (typeof memo[selector] === "undefined") { memo[selector] = fn.call(this, selector); } return memo[selector] }; })(function (styleTarget) { return document.querySelector(styleTarget) }), singletonElement = null, singletonCounter = 0, styleElementsInsertedAtTop = [], fixUrls = __webpack_require__(5); module.exports = function(list, options) { if(typeof DEBUG !== "undefined" && DEBUG) { if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; options.attrs = typeof options.attrs === "object" ? options.attrs : {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (typeof options.singleton === "undefined") options.singleton = isOldIE(); // By default, add <style> tags to the <head> element if (typeof options.insertInto === "undefined") options.insertInto = "head"; // By default, add <style> tags to the bottom of the target if (typeof options.insertAt === "undefined") options.insertAt = "bottom"; var styles = listToStyles(list); addStylesToDom(styles, options); return function update(newList) { var mayRemove = []; for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; domStyle.refs--; mayRemove.push(domStyle); } if(newList) { var newStyles = listToStyles(newList); addStylesToDom(newStyles, options); } for(var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i]; if(domStyle.refs === 0) { for(var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j](); delete stylesInDom[domStyle.id]; } } }; }; function addStylesToDom(styles, options) { for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; if(domStyle) { domStyle.refs++; for(var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]); } for(; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j], options)); } } else { var parts = []; for(var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j], options)); } stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts}; } } } function listToStyles(list) { var styles = []; var newStyles = {}; for(var i = 0; i < list.length; i++) { var item = list[i]; var id = item[0]; var css = item[1]; var media = item[2]; var sourceMap = item[3]; var part = {css: css, media: media, sourceMap: sourceMap}; if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]}); else newStyles[id].parts.push(part); } return styles; } function insertStyleElement(options, styleElement) { var styleTarget = getElement(options.insertInto) if (!styleTarget) { throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid."); } var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1]; if (options.insertAt === "top") { if(!lastStyleElementInsertedAtTop) { styleTarget.insertBefore(styleElement, styleTarget.firstChild); } else if(lastStyleElementInsertedAtTop.nextSibling) { styleTarget.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling); } else { styleTarget.appendChild(styleElement); } styleElementsInsertedAtTop.push(styleElement); } else if (options.insertAt === "bottom") { styleTarget.appendChild(styleElement); } else { throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'."); } } function removeStyleElement(styleElement) { styleElement.parentNode.removeChild(styleElement); var idx = styleElementsInsertedAtTop.indexOf(styleElement); if(idx >= 0) { styleElementsInsertedAtTop.splice(idx, 1); } } function createStyleElement(options) { var styleElement = document.createElement("style"); options.attrs.type = "text/css"; attachTagAttrs(styleElement, options.attrs); insertStyleElement(options, styleElement); return styleElement; } function createLinkElement(options) { var linkElement = document.createElement("link"); options.attrs.type = "text/css"; options.attrs.rel = "stylesheet"; attachTagAttrs(linkElement, options.attrs); insertStyleElement(options, linkElement); return linkElement; } function attachTagAttrs(element, attrs) { Object.keys(attrs).forEach(function (key) { element.setAttribute(key, attrs[key]); }); } function addStyle(obj, options) { var styleElement, update, remove; if (options.singleton) { var styleIndex = singletonCounter++; styleElement = singletonElement || (singletonElement = createStyleElement(options)); update = applyToSingletonTag.bind(null, styleElement, styleIndex, false); remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true); } else if(obj.sourceMap && typeof URL === "function" && typeof URL.createObjectURL === "function" && typeof URL.revokeObjectURL === "function" && typeof Blob === "function" && typeof btoa === "function") { styleElement = createLinkElement(options); update = updateLink.bind(null, styleElement, options); remove = function() { removeStyleElement(styleElement); if(styleElement.href) URL.revokeObjectURL(styleElement.href); }; } else { styleElement = createStyleElement(options); update = applyToTag.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); }; } update(obj); return function updateStyle(newObj) { if(newObj) { if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) return; update(obj = newObj); } else { remove(); } }; } var replaceText = (function () { var textStore = []; return function (index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; })(); function applyToSingletonTag(styleElement, index, remove, obj) { var css = remove ? "" : obj.css; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = styleElement.childNodes; if (childNodes[index]) styleElement.removeChild(childNodes[index]); if (childNodes.length) { styleElement.insertBefore(cssNode, childNodes[index]); } else { styleElement.appendChild(cssNode); } } } function applyToTag(styleElement, obj) { var css = obj.css; var media = obj.media; if(media) { styleElement.setAttribute("media", media) } if(styleElement.styleSheet) { styleElement.styleSheet.cssText = css; } else { while(styleElement.firstChild) { styleElement.removeChild(styleElement.firstChild); } styleElement.appendChild(document.createTextNode(css)); } } function updateLink(linkElement, options, obj) { var css = obj.css; var sourceMap = obj.sourceMap; /* If convertToAbsoluteUrls isn't defined, but sourcemaps are enabled and there is no publicPath defined then lets turn convertToAbsoluteUrls on by default. Otherwise default to the convertToAbsoluteUrls option directly */ var autoFixUrls = options.convertToAbsoluteUrls === undefined && sourceMap; if (options.convertToAbsoluteUrls || autoFixUrls){ css = fixUrls(css); } if(sourceMap) { // http://stackoverflow.com/a/26603875 css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */"; } var blob = new Blob([css], { type: "text/css" }); var oldSrc = linkElement.href; linkElement.href = URL.createObjectURL(blob); if(oldSrc) URL.revokeObjectURL(oldSrc); } /***/ }), /* 5 */ /***/ (function(module, exports) { /** * When source maps are enabled, `style-loader` uses a link element with a data-uri to * embed the css on the page. This breaks all relative urls because now they are relative to a * bundle instead of the current page. * * One solution is to only use full urls, but that may be impossible. * * Instead, this function "fixes" the relative urls to be absolute according to the current page location. * * A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command. * */ module.exports = function (css) { // get current location var location = typeof window !== "undefined" && window.location; if (!location) { throw new Error("fixUrls requires window.location"); } // blank or null? if (!css || typeof css !== "string") { return css; } var baseUrl = location.protocol + "//" + location.host; var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/"); // convert each url(...) /* This regular expression is just a way to recursively match brackets within a string. /url\s*\( = Match on the word "url" with any whitespace after it and then a parens ( = Start a capturing group (?: = Start a non-capturing group [^)(] = Match anything that isn't a parentheses | = OR \( = Match a start parentheses (?: = Start another non-capturing groups [^)(]+ = Match anything that isn't a parentheses | = OR \( = Match a start parentheses [^)(]* = Match anything that isn't a parentheses \) = Match a end parentheses ) = End Group *\) = Match anything and then a close parens ) = Close non-capturing group * = Match anything ) = Close capturing group \) = Match a close parens /gi = Get all matches, not the first. Be case insensitive. */ var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function(fullMatch, origUrl) { // strip quotes (if they exist) var unquotedOrigUrl = origUrl .trim() .replace(/^"(.*)"$/, function(o, $1){ return $1; }) .replace(/^'(.*)'$/, function(o, $1){ return $1; }); // already a full url? no change if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(unquotedOrigUrl)) { return fullMatch; } // convert the url to a full url var newUrl; if (unquotedOrigUrl.indexOf("//") === 0) { //TODO: should we add protocol? newUrl = unquotedOrigUrl; } else if (unquotedOrigUrl.indexOf("/") === 0) { // path should be relative to the base url newUrl = baseUrl + unquotedOrigUrl; // already starts with '/' } else { // path should be relative to current directory newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './' } // send back the fixed url(...) return "url(" + JSON.stringify(newUrl) + ")"; }); // send back the fixed css return fixedCss; }; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(2); if(typeof content === 'string') content = [[module.i, content, '']]; // add the styles to the DOM var update = __webpack_require__(4)(content, {}); if(content.locals) module.exports = content.locals; // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!../node_modules/css-loader/index.js?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:3]!../node_modules/postcss-loader/index.js!./rater.css", function() { var newContent = require("!!../node_modules/css-loader/index.js?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:3]!../node_modules/postcss-loader/index.js!./rater.css"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }), /* 7 */ /***/ (function(module, exports) { module.exports = require("prop-types"); /***/ }), /* 8 */ /***/ (function(module, exports) { module.exports = require("react"); /***/ }), /* 9 */ /***/ (function(module, exports) { module.exports = require("react-css-themr"); /***/ }) /******/ ]); });