UNPKG

@spreadtheweb/multi-range-slider

Version:

Simple, small and fast vanilla JavaScript multi range slider without dependencies, with ability to have multiple values and points to slide

109 lines (102 loc) 22.4 kB
/* * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). * This devtool is neither made for production nor for readable output files. * It uses "eval()" calls to create a separate source file in the browser devtools. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) * or disable the default devtool with "devtool: false". * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["RangeSlider"] = factory(); else root["RangeSlider"] = factory(); })(self, () => { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "./src/range-slider.js": /*!*****************************!*\ !*** ./src/range-slider.js ***! \*****************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ RangeSlider)\n/* harmony export */ });\n/* harmony import */ var _range_slider_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./range-slider.css */ \"./src/range-slider.css\");\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n/*\n This is a RangeSlider html component for one of my projects\n It allows to have multiple points and different ranges of values with specified steps to jumb.\n It has a easy api to customize sizes and colors of points, tracks, etc.\n It has onChange method, which receives and callback and calls it with current values\n*/\n\n\nvar RangeSlider = /*#__PURE__*/function () {\n /**\n * Create slider\n * @param {string} selector\n * @param {object} props={}\n */\n function RangeSlider(selector) {\n var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n _classCallCheck(this, RangeSlider);\n\n this.defaultProps = {\n values: [25, 75],\n step: 1,\n min: 0,\n max: 100,\n colors: {\n points: \"rgb(25, 118, 210)\",\n // ['red', 'green', 'blue']\n rail: \"rgba(25, 118, 210, 0.4)\",\n tracks: \"rgb(25, 118, 210)\" // // ['red', 'green']\n\n },\n pointRadius: 15,\n railHeight: 5,\n trackHeight: 5,\n tooltipHandler: null\n };\n this.allProps = _objectSpread(_objectSpread(_objectSpread({}, this.defaultProps), props), {}, {\n values: _toConsumableArray(props.values || this.defaultProps.values),\n colors: _objectSpread(_objectSpread({}, this.defaultProps.colors), props.colors)\n });\n this.container = this.initContainer(selector);\n this.pointPositions = this.generatePointPositions();\n this.possibleValues = this.generatePossibleValues();\n this.jump = this.container.offsetWidth / Math.ceil((this.allProps.max - this.allProps.min) / this.allProps.step);\n this.rail = this.initRail();\n this.tracks = this.initTracks(this.allProps.values.length - 1);\n this.tooltip = this.initTooltip();\n this.points = this.initPoints(this.allProps.values.length);\n this.drawScene();\n this.documentMouseupHandler = this.documentMouseupHandler.bind(this);\n this.documentMouseMoveHandler = this.documentMouseMoveHandler.bind(this);\n this.selectedPointIndex = -1;\n this.changeHandlers = [];\n return this;\n }\n /**\n * Draw all elements with initial positions\n */\n\n\n _createClass(RangeSlider, [{\n key: \"drawScene\",\n value: function drawScene() {\n var _this = this;\n\n this.container.classList.add(\"range-slider__container\");\n this.container.appendChild(this.rail);\n this.container.appendChild(this.tooltip);\n this.tracks.forEach(function (track) {\n return _this.container.appendChild(track);\n });\n this.points.forEach(function (point) {\n return _this.container.appendChild(point);\n });\n }\n }, {\n key: \"generatePointPositions\",\n value: function generatePointPositions() {\n var _this3 = this;\n\n return this.allProps.values.map(function (value) {\n var percentage = (value - _this2.allProps.min) / (_this2.allProps.max - _this2.allProps.min) * 100;\n return Math.floor(percentage / 100 * _this3.container.offsetWidth);\n });\n }\n /**\n * Generate all values that can slider have starting from min, to max increased by step\n */\n\n }, {\n key: \"generatePossibleValues\",\n value: function generatePossibleValues() {\n var values = [];\n\n for (var i = this.allProps.min; i <= this.allProps.max; i += this.allProps.step) {\n values.push(Math.round(i * 100) / 100);\n }\n\n if (this.allProps.max % this.allProps.step > 0) {\n values.push(Math.round(this.allProps.max * 100) / 100);\n }\n\n return values;\n }\n /**\n * Initialize container\n * @param {string} selector\n */\n\n }, {\n key: \"initContainer\",\n value: function initContainer(selector) {\n var container = selector instanceof HTMLElement ? selector : document.querySelector(selector);\n container.classList.add(\"range-slider__container\");\n container.style.height = this.allProps.pointRadius * 2 + \"px\";\n return container;\n }\n /**\n * Initialize Rail\n */\n\n }, {\n key: \"initRail\",\n value: function initRail() {\n var _this4 = this;\n\n var rail = document.createElement(\"span\");\n rail.classList.add(\"range-slider__rail\");\n rail.style.background = this.allProps.colors.rail;\n rail.style.height = this.allProps.railHeight + \"px\";\n rail.style.top = this.allProps.pointRadius + \"px\";\n rail.addEventListener(\"click\", function (e) {\n return _this4.railClickHandler(e);\n });\n return rail;\n }\n /**\n * Initialize all tracks (equal to number of points - 1)\n * @param {number} count\n */\n\n }, {\n key: \"initTracks\",\n value: function initTracks(count) {\n var tracks = [];\n\n for (var i = 0; i < count; i++) {\n tracks.push(this.initTrack(i));\n }\n\n return tracks;\n }\n /**\n * Initialize single track at specific index position\n * @param {number} index\n */\n\n }, {\n key: \"initTrack\",\n value: function initTrack(index) {\n var _this5 = this;\n\n var track = document.createElement(\"span\");\n track.classList.add(\"range-slider__track\");\n var trackPointPositions = this.pointPositions.slice(index, index + 2);\n track.style.left = Math.min.apply(Math, _toConsumableArray(trackPointPositions)) + \"px\";\n track.style.top = this.allProps.pointRadius + \"px\";\n track.style.width = Math.max.apply(Math, _toConsumableArray(trackPointPositions)) - Math.min.apply(Math, _toConsumableArray(trackPointPositions)) + \"px\";\n track.style.height = this.allProps.trackHeight + \"px\";\n var trackColors = this.allProps.colors.tracks;\n track.style.background = Array.isArray(trackColors) ? trackColors[index] || trackColors[trackColors.length - 1] : trackColors;\n track.addEventListener(\"click\", function (e) {\n return _this5.railClickHandler(e);\n });\n return track;\n }\n /**\n * Initialize all points (equal to number of values)\n * @param {number} count\n */\n\n }, {\n key: \"initPoints\",\n value: function initPoints(count) {\n var points = [];\n\n for (var i = 0; i < count; i++) {\n points.push(this.initPoint(i));\n }\n\n return points;\n }\n /**\n * Initialize single track at specific index position\n * @param {number} index\n */\n\n }, {\n key: \"initPoint\",\n value: function initPoint(index) {\n var _this6 = this;\n\n var point = document.createElement(\"span\");\n point.classList.add(\"range-slider__point\");\n point.style.width = this.allProps.pointRadius * 2 + \"px\";\n point.style.height = this.allProps.pointRadius * 2 + \"px\";\n point.style.left = \"\".concat(this.pointPositions[index] / this.container.offsetWidth * 100, \"%\");\n var pointColors = this.allProps.colors.points;\n point.style.background = Array.isArray(pointColors) ? pointColors[index] || pointColors[pointColors.length - 1] : pointColors;\n point.addEventListener(\"mousedown\", function (e) {\n return _this6.pointClickHandler(e, index);\n });\n point.addEventListener(\"mouseover\", function (e) {\n return _this6.pointMouseoverHandler(e, index);\n });\n point.addEventListener(\"mouseout\", function (e) {\n return _this6.pointMouseOutHandler(e, index);\n });\n return point;\n }\n /**\n * Initialize tooltip\n */\n\n }, {\n key: \"initTooltip\",\n value: function initTooltip() {\n var tooltip = document.createElement(\"span\");\n tooltip.classList.add(\"range-slider__tooltip\");\n tooltip.style.fontSize = this.allProps.pointRadius + \"px\";\n return tooltip;\n }\n /**\n * Draw points, tracks and tooltip (on rail click or on drag)\n */\n\n }, {\n key: \"draw\",\n value: function draw() {\n var _this7 = this;\n\n this.points.forEach(function (point, i) {\n point.style.left = \"\".concat(_this7.pointPositions[i] / _this7.container.offsetWidth * 100, \"%\");\n });\n this.tracks.forEach(function (track, i) {\n var trackPointPositions = _this7.pointPositions.slice(i, i + 2);\n\n track.style.left = Math.min.apply(Math, _toConsumableArray(trackPointPositions)) + \"px\";\n track.style.width = Math.max.apply(Math, _toConsumableArray(trackPointPositions)) - Math.min.apply(Math, _toConsumableArray(trackPointPositions)) + \"px\";\n });\n this.tooltip.style.left = this.pointPositions[this.selectedPointIndex] + \"px\";\n var content = this.allProps.values[this.selectedPointIndex];\n\n if (this.allProps.tooltipHandler !== null) {\n content = this.allProps.tooltipHandler(content);\n }\n\n this.tooltip.textContent = content;\n }\n /**\n * Redraw on rail click\n * @param {Event} e\n */\n\n }, {\n key: \"railClickHandler\",\n value: function railClickHandler(e) {\n var newPosition = this.getMouseRelativePosition(e.pageX);\n var closestPositionIndex = this.getClosestPointIndex(newPosition);\n this.pointPositions[closestPositionIndex] = newPosition;\n this.draw();\n }\n /**\n * Find the closest possible point position fro current mouse position\n * in order to move the point\n * @param {number} mousePoisition\n */\n\n }, {\n key: \"getClosestPointIndex\",\n value: function getClosestPointIndex(mousePoisition) {\n var shortestDistance = Infinity;\n var index = 0;\n\n for (var i in this.pointPositions) {\n var dist = Math.abs(mousePoisition - this.pointPositions[i]);\n\n if (shortestDistance > dist) {\n shortestDistance = dist;\n index = i;\n }\n }\n\n return index;\n }\n /**\n * Stop point moving on mouse up\n */\n\n }, {\n key: \"documentMouseupHandler\",\n value: function documentMouseupHandler() {\n var _this8 = this;\n\n this.changeHandlers.forEach(function (func) {\n return func(_this8.allProps.values);\n });\n this.points[this.selectedPointIndex].style.boxShadow = \"none\";\n this.selectedPointIndex = -1;\n this.tooltip.style.transform = \"translate(-50%, -60%) scale(0)\";\n document.removeEventListener(\"mouseup\", this.documentMouseupHandler);\n document.removeEventListener(\"mousemove\", this.documentMouseMoveHandler);\n }\n /**\n * Start point moving on mouse move\n * @param {Event} e\n */\n\n }, {\n key: \"documentMouseMoveHandler\",\n value: function documentMouseMoveHandler(e) {\n var newPoisition = this.getMouseRelativePosition(e.pageX);\n var extra = Math.floor(newPoisition % this.jump);\n\n if (extra > this.jump / 2) {\n newPoisition += this.jump - extra;\n } else {\n newPoisition -= extra;\n }\n\n if (newPoisition < 0) {\n newPoisition = 0;\n } else if (newPoisition > this.container.offsetWidth) {\n newPoisition = this.container.offsetWidth;\n }\n\n this.pointPositions[this.selectedPointIndex] = newPoisition;\n this.allProps.values[this.selectedPointIndex] = this.possibleValues[Math.floor(newPoisition / this.jump)];\n this.draw();\n }\n /**\n * Register document listeners on point click\n * and save clicked point index\n * @param {Event} e\n */\n\n }, {\n key: \"pointClickHandler\",\n value: function pointClickHandler(e, index) {\n e.preventDefault();\n this.selectedPointIndex = index;\n document.addEventListener(\"mouseup\", this.documentMouseupHandler);\n document.addEventListener(\"mousemove\", this.documentMouseMoveHandler);\n }\n /**\n * Point mouse over box shadow and tooltip displaying\n * @param {Event} e\n * @param {number} index\n */\n\n }, {\n key: \"pointMouseoverHandler\",\n value: function pointMouseoverHandler(e, index) {\n var transparentColor = RangeSlider.addTransparencyToColor(this.points[index].style.backgroundColor, 16);\n\n if (this.selectedPointIndex < 0) {\n this.points[index].style.boxShadow = \"0px 0px 0px \".concat(Math.floor(this.allProps.pointRadius / 1.5), \"px \").concat(transparentColor);\n }\n\n this.tooltip.style.transform = \"translate(-50%, -60%) scale(1)\";\n this.tooltip.style.left = this.pointPositions[index] + \"px\";\n var content = this.allProps.values[index];\n\n if (this.allProps.tooltipHandler !== null) {\n content = this.allProps.tooltipHandler(content);\n }\n\n this.tooltip.textContent = content;\n }\n /**\n * Add transparency for rgb, rgba or hex color\n * @param {string} color\n * @param {number} percentage\n */\n\n }, {\n key: \"pointMouseOutHandler\",\n value:\n /**\n * Hide shadow and tooltip on mouse out\n * @param {Event} e\n * @param {number} index\n */\n function pointMouseOutHandler(e, index) {\n if (this.selectedPointIndex < 0) {\n this.points[index].style.boxShadow = \"none\";\n this.tooltip.style.transform = \"translate(-50%, -60%) scale(0)\";\n }\n }\n /**\n * Get mouse position relatively from containers left position on the page\n */\n\n }, {\n key: \"getMouseRelativePosition\",\n value: function getMouseRelativePosition(pageX) {\n var containerPosition = this.container.getBoundingClientRect();\n return pageX - containerPosition.left;\n }\n /**\n * Register onChange callback to call it on slider move end passing all the present values\n */\n\n }, {\n key: \"onChange\",\n value: function onChange(func) {\n if (typeof func !== \"function\") {\n throw new Error(\"Please provide function as onChange callback\");\n }\n\n this.changeHandlers.push(func);\n return this;\n }\n }], [{\n key: \"addTransparencyToColor\",\n value: function addTransparencyToColor(color, percentage) {\n if (color.startsWith(\"rgba\")) {\n return color.replace(/(\\d+)(?!.*\\d)/, percentage + \"%\");\n }\n\n if (color.startsWith(\"rgb\")) {\n var newColor = color.replace(/(\\))(?!.*\\))/, \", \".concat(percentage, \"%)\"));\n return newColor.replace(\"rgb\", \"rgba\");\n }\n\n if (color.startsWith(\"#\")) {\n return color + percentage.toString(16);\n }\n\n return color;\n }\n }]);\n\n return RangeSlider;\n}();\n\n\n\n//# sourceURL=webpack://RangeSlider/./src/range-slider.js?"); /***/ }), /***/ "./src/range-slider.css": /*!******************************!*\ !*** ./src/range-slider.css ***! \******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n// extracted by mini-css-extract-plugin\n\n\n//# sourceURL=webpack://RangeSlider/./src/range-slider.css?"); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module can't be inlined because the eval devtool is used. /******/ var __webpack_exports__ = __webpack_require__("./src/range-slider.js"); /******/ __webpack_exports__ = __webpack_exports__["default"]; /******/ /******/ return __webpack_exports__; /******/ })() ; });