├── .babelrc ├── .eslintrc.js ├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── example ├── index.html ├── index.js └── style.css ├── lib ├── smoothie.js └── smoothie.min.js ├── package-lock.json ├── package.json ├── smoothie.png ├── src ├── hijack.js ├── index.js ├── scrollbar.js └── utils │ ├── after-transition.js │ ├── bindAll.js │ ├── clone.js │ ├── component.js │ ├── support.js │ └── ui-manager.js ├── webpack.config.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "production": { 4 | "presets": [ 5 | [ 6 | "es2015", 7 | { 8 | "loose": true, 9 | "modules": false 10 | } 11 | ] 12 | ] 13 | }, 14 | "cjs": { 15 | "presets": [ 16 | [ 17 | "es2015", 18 | { 19 | "loose": true, 20 | "modules": "commonjs" 21 | } 22 | ] 23 | ], 24 | "plugins": [ 25 | [ 26 | "add-module-exports" 27 | ] 28 | ] 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | "env": { 4 | "browser": true, 5 | "es6": true 6 | }, 7 | "extends": "airbnb-base", 8 | // add your custom rules here 9 | 'rules': { 10 | // allow paren-less arrow functions 11 | 'arrow-parens': 0, 12 | // allow debugger during development 13 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, 14 | 'comma-dangle': 0, 15 | 'no-unused-vars': 1, 16 | 'indent': [2, 4], 17 | 'camelcase': 0, 18 | 'space-before-function-paren': 0, 19 | } 20 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | .DS_Store -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | .vscode 4 | npm-debug.log 5 | npm-debug.log.* 6 | .eslintrc 7 | .eslintignore 8 | .babelrc 9 | example/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Alessandro Rigobello 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | 4 | 5 |

Smooth fake scrollbar for your `awesome` projects

6 |

7 | 8 | Inspired and written on top of smooth-scrolling by Baptiste Briel and VirtualScroll by Florian Morel 9 | 10 | ### Install 11 | ``` 12 | npm i smoothie-scroll --s 13 | ``` 14 | 15 | ### Usage 16 | 17 | Init your Smoothie with `new Smoothie(el, options)` with el as smoothie wrapper 18 | 19 | ``` 20 | el: DOM element or DOM selector 21 | ``` 22 | and the following options (if you want) 23 | ``` 24 | orientation: 'vertical', 25 | deltaX: true, || default: false (if you want horizontal scroll with side delta on mouse/trackpad) 26 | ease: 0.075, 27 | prefix: prefix('transform'), 28 | listener: document.body, 29 | 30 | vs: { 31 | limitInertia: false, 32 | mouseMultiplier: 1, 33 | touchMultiplier: 1.5, 34 | firefoxMultiplier: 30, 35 | preventTouch: true, 36 | }, 37 | ``` 38 | 39 | `vs` is options are for VirtualScroll utility 40 | 41 | You can tween enter and exit of scrollbar using css classes: 42 | `.is-entering` and `.is-leaving` on: 43 | `.scrollbar-track` 44 | 45 | ### API 46 | - `new Smoothie(options)` 47 | Return a new instance of Smoothie. See the options below. 48 | 49 | - `instance.init(: initial position :)` 50 | Life comes here! 51 | Optional you can set initial position 52 | 53 | - `instance.update()` 54 | Update the instance with new bounds. 55 | 56 | - `instance.on()` 57 | Listen to the scroll. 58 | 59 | - `instance.off()` 60 | Remove the listener. 61 | 62 | - `instance.destroy()` 63 | Will remove all events and unbind the DOM listeners. 64 | 65 | - `instance.setTo()` 66 | Immediatly set position of your scrollbar. 67 | 68 | Events note: 69 | Each instance will listen only once to any DOM listener. These listener are enabled/disabled automatically. However, it's a good practice to always call `destroy()` on your Smoothie instance, especially if you are working with a SPA. 70 | 71 | ### Todo 72 | - High priority: Unit and E2E tests 73 | 74 | ### License 75 | MIT. 76 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Smoothie 8 | 9 | 10 | 11 | 12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | 22 |
23 |
24 | 25 |
26 |
27 |
28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | const Smoothie = window.smoothie; 2 | 3 | let smoothie; 4 | let nested; 5 | function init() { 6 | smoothie = new Smoothie('.smoothie', { 7 | listener: document.querySelector('.smoothie-container') 8 | }); 9 | smoothie.init(1000); 10 | smoothie.stop(); 11 | 12 | nested = new Smoothie('.nested', { 13 | orientation: 'horizontal', 14 | listener: document.querySelector('.nested-container') 15 | }); 16 | nested.init(); 17 | } 18 | 19 | init(); 20 | 21 | setTimeout(() => { 22 | const els = document.querySelectorAll('.el'); 23 | 24 | smoothie.addListener((status) => { 25 | els.forEach((el) => { 26 | if (smoothie.inViewport(el)) { 27 | el.setAttribute('data-animated', ''); 28 | } else { 29 | el.removeAttribute('data-animated'); 30 | } 31 | }); 32 | }); 33 | }, 3000); 34 | 35 | 36 | // console.log('start from bottom!'); 37 | // smoothie.setTo('bottom'); 38 | 39 | 40 | let toggle = true; 41 | const $switch = document.querySelector('#switch'); 42 | $switch.addEventListener('click', () => { 43 | toggle = !toggle; 44 | 45 | if (!toggle) { 46 | smoothie.stop(); 47 | nested.start(); 48 | } else { 49 | smoothie.start(); 50 | nested.stop(); 51 | } 52 | }); 53 | 54 | let enable = true; 55 | const $enabler = document.querySelector('#enable'); 56 | $enabler.addEventListener('click', () => { 57 | enable = !enable; 58 | 59 | if (!enable) { 60 | smoothie.destroy(); 61 | nested.destroy(); 62 | } else { 63 | init(); 64 | } 65 | }); 66 | -------------------------------------------------------------------------------- /example/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | } 5 | 6 | .smoothie-container { 7 | position: fixed; 8 | top: 0; 9 | left: 0; 10 | right: 0; 11 | bottom: 0; 12 | width: 100%; 13 | overflow: hidden; 14 | } 15 | 16 | .smoothie { 17 | min-height: 3000px; 18 | will-change: transform; 19 | background: #141414; 20 | position: relative; 21 | } 22 | 23 | .smoothie { 24 | background: url('https://source.unsplash.com/1200x1200'); 25 | background-size: contain; 26 | background-repeat: repeat; 27 | min-height: 10000px; 28 | } 29 | 30 | 31 | img { 32 | display: block; 33 | width: 100%; 34 | } 35 | 36 | .scrollbar-track { 37 | position: absolute; 38 | top: 0%; 39 | right: 0; 40 | width: 10px; 41 | height: 100%; 42 | background: lightgray; 43 | opacity: 1; 44 | visibility: visible; 45 | transition: all 1.5s; 46 | } 47 | 48 | .scrollbar-track.is-entering, 49 | .scrollbar-track.is-leaving { 50 | transform: translate3d(100%, 0, 0); 51 | } 52 | 53 | .scrollbar { 54 | position: absolute; 55 | top: 0; 56 | left: 0; 57 | width: 100%; 58 | will-change: transform; 59 | } 60 | 61 | .scrollbar::after { 62 | content: ""; 63 | position: absolute; 64 | top: 0; 65 | left: 0; 66 | right: 0; 67 | bottom: 0; 68 | margin: 2px; 69 | background: black; 70 | z-index: 1; 71 | } 72 | 73 | .nested { 74 | min-width: 3000px; 75 | will-change: transform; 76 | background: #141414; 77 | position: relative; 78 | } 79 | 80 | .nested-container { 81 | position: fixed; 82 | top: 0; 83 | left: 0; 84 | right: 0; 85 | bottom: 0; 86 | height: 50%; 87 | width: 50%; 88 | overflow: hidden; 89 | z-index: 0; 90 | margin: auto; 91 | } 92 | .nested-container img { 93 | display: block; 94 | width: auto; 95 | height: 100%; 96 | } 97 | 98 | .nested-container .scrollbar-track { 99 | position: absolute; 100 | top: auto; 101 | left: 0; 102 | right: 0; 103 | bottom: 0; 104 | width: 100%; 105 | height: 10px; 106 | background: white; 107 | z-index: 2; 108 | } 109 | 110 | .nested-container .scrollbar { 111 | height: 100%; 112 | background: red; 113 | } 114 | 115 | #switch { 116 | position: fixed; 117 | top: 0; 118 | left: 0; 119 | z-index: 3; 120 | } 121 | 122 | #enable { 123 | position: fixed; 124 | top: 0; 125 | right: 0; 126 | z-index: 3; 127 | } 128 | 129 | .elements { 130 | position: absolute; 131 | top: 0; 132 | left: 0; 133 | margin-top: 80vh; 134 | z-index: 20; 135 | } 136 | 137 | .elements > div { 138 | width: 40px; 139 | height: 300px; 140 | margin: 200px 20px; 141 | transition: all 1s ease-out; 142 | background: firebrick; 143 | } 144 | 145 | .elements > [data-animated] { 146 | background: green; 147 | transform: translate3d(100px, 0, 0); 148 | } 149 | -------------------------------------------------------------------------------- /lib/smoothie.min.js: -------------------------------------------------------------------------------- 1 | !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.smoothie=e():t.smoothie=e()}("undefined"!=typeof self?self:this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=5)}([function(t,e,n){t.exports=n(7)},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e){function n(t){t=t||{};var e=document.createElement(t.selector);if(t.attr)for(var n in t.attr)t.attr.hasOwnProperty(n)&&e.setAttribute(n,t.attr[n]);return"a"==t.selector&&t.link&&(e.href=t.link,t.target&&e.setAttribute("target",t.target)),"img"==t.selector&&t.src&&(e.src=t.src,t.lazyload&&(e.style.opacity=0,e.onload=function(){e.style.opacity=1})),t.id&&(e.id=t.id),t.styles&&(e.className=t.styles),t.html&&(e.innerHTML=t.html),t.children&&e.appendChild(t.children),e}t.exports=n},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var s=n(17),a=n.n(s),c=n(21),u=n.n(c),l=n(22),h=n.n(l),f=n(24),p=(n.n(f),n(25)),d=function(){function t(t,e){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:{state:{}};r(this,e);var c=i(this,t.call(this));if(c.setMaxListeners(0),c.el=c.$el="string"==typeof n?document.querySelector(n):n,!u()(c.$el)){var l;return console.warn("Element "+c.$el+" is not a DOM element"),l=c,i(c,l)}c.$els={},c.$refs={},c.options=h()(c.getDefaultOptions,s);var f=new a.a(c.$el,c);return c.delegate=function(t,e,n){return f.bind(t+(e?" "+e:""),n)},c.undelegate=function(){return f.unbind.apply(f,o)},c.state=new Map,c}return o(e,t),e.prototype.setRef=function(t,n){for(var r=this,i=arguments.length,o=Array(i>2?i-2:0),s=2;s0&&void 0!==arguments[0]?arguments[0]:{};if(this.$el.getAttribute("data-ui-uid"))return console.log("Element "+this.$el.getAttribute("data-ui-uid")+" is already created",this.$el),this;this._uid=Object(p.a)(),this.$el.setAttribute("data-ui-uid",this._uid),this.$el.id||(this.$el.id="component"+this._uid),this.beforeInit();var n=this.bindStateEvents();Object.keys(n).forEach(function(e){t.on("change:"+e,n[e].bind(t))});var r=Object.assign({},this.getInitialState,e);return Object.keys(r).forEach(function(e){t.setState(e,r[e])}),this._active=!0,this},e.prototype.broadcast=function(t){for(var e=this,n=arguments.length,r=Array(n>1?n-1:0),i=1;i2&&void 0!==arguments[2]&&arguments[2],r=this.state.get(t);if(r!==e)return this.state.set(t,e),n||this.emit("change:"+t,e,r),e},e.prototype.bindStateEvents=function(){return{}},e.prototype.getPizza=function(){console.log("🍕 enjoy!")},e.prototype.getBomb=function(){console.log("💣 aaaaaaaaaa!")},e.prototype.animationIn=function(){},e.prototype.beforeInit=function(){},e.prototype.closeRefs=function(){var t=this;return Promise.all(Object.keys(this.$refs).map(function(e){return t.$refs[e].destroy()})).then(function(){t.$refs={}}).catch(function(t){console.log("close refs",t)})},e.prototype.destroy=function(){var t=this;return this.emit("destroy"),this.undelegate(),this.removeAllListeners(),this.$el.removeAttribute("data-ui-uid"),this.closeRefs().then(function(){t._active=!1}).catch(function(t){console.log("destroy catch: ",t)})},d(e,[{key:"getInitialState",get:function(){return{}}},{key:"getDefaultOptions",get:function(){return{}}}]),e}(f.EventEmitter);e.a=v},function(t,e){var n=window.addEventListener?"addEventListener":"attachEvent",r=window.removeEventListener?"removeEventListener":"detachEvent",i="addEventListener"!==n?"on":"";e.bind=function(t,e,r,o){return t[n](i+e,r,o||!1),r},e.unbind=function(t,e,n,o){return t[r](i+e,n,o||!1),n}},function(t,e,n){t.exports=n(6)},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var s=n(0),a=n.n(s),c=n(2),u=n.n(c),l=n(9),h=n.n(l),f=n(10),p=n(16),d=n(3),v=function(){function t(t,e){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:".smoothie",o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};r(this,e);var s=i(this,t.call(this,n,o));s.createBound(),s.rAF=void 0,s.isRAFCanceled=!1;var a=s.constructor.name?s.constructor.name:"Smoothie";return s.extends="Smoothie"!==a,s.current=0,s.target=0,s}return o(e,t),e.prototype.createBound=function(){var t=this;["run","calc","resize","scrollTo","mouseUp","mouseDown","mouseMove","calcScroll","inViewport","addListener"].forEach(function(e){t[e]=t[e].bind(t)})},e.prototype.addListener=function(t){this.setState("emitEventOnScrolling",!0),this.on("scrolling",function(e){t(e)})},e.prototype.removeListener=function(t){this.setState("emitEventOnScrolling",!1)},e.prototype.inViewport=function(t,e){var n=t.getBoundingClientRect(),r={top:n.top+this.current},i={};return i.top=this.current,i.bottom=this.current+window.innerHeight,r.bottom=r.top+t.clientHeight,r.bottom>=i.top&&r.bottom<=i.bottom||r.top<=i.bottom&&r.top>=i.top},e.prototype.init=function(e){t.prototype.init.call(this),e&&void 0!==e&&null!==e&&(this.current=e,this.target=e),this.addClasses(),this.setRef("hijack",f.a,this.options.vs),this.$els.scrollbar=u()({selector:"div",styles:"scrollbar-track scrollbar-"+this.options.orientation+" is-entering"}),this.setRef("scrollbar",p.a,this.$els.scrollbar,this.options),this.resize(),this.update=this.resize,this.addEvents()},e.prototype.addClasses=function(){var t="vertical"===this.options.orientation?"y":"x";a.a.add(this.options.listener,"is-smoothed"),a.a.add(this.options.listener,t+"-scroll")},e.prototype.calc=function(t){var e="horizontal"===this.options.orientation&&this.options.deltaX?t.deltaX:t.deltaY;this.target+=-1*e,this.setState("direction",this.target>this.current?"down":"up"),this.clampTarget()},e.prototype.run=function(){if(!this.isRAFCanceled){this.current+=(this.target-this.current)*this.options.ease,this.current<.1&&(this.current=0),this.rAF=window.requestAnimationFrame(this.run);var t=this.current.toFixed(2);this.options.renderByPixels&&(t=Math.round(this.current)),this.$el.style[this.options.prefix]=this.getTransform(-t),this.$refs.scrollbar.update(this.current),this.getState("emitEventOnScrolling")&&this.emit("scrolling",{current:this.current,direction:this.getState("direction")})}},e.prototype.getTransform=function(t){return"vertical"===this.options.orientation?"translate3d(0, "+t+"px, 0)":"translate3d("+t+"px,0,0)"},e.prototype.start=function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isRAFCanceled&&(this.isRAFCanceled=!1);this.options.listener===document.body?window:this.options.listener;this.$refs.hijack.on(this.calc),t&&this.requestAnimationFrame()},e.prototype.stop=function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.options.listener===document.body?window:this.options.listener;this.$refs.hijack.off(this.calc),t&&this.cancelAnimationFrame()},e.prototype.requestAnimationFrame=function(t){function e(){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(){this.rAF=requestAnimationFrame(this.run)}),e.prototype.cancelAnimationFrame=function(t){function e(){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(){this.isRAFCanceled=!0,cancelAnimationFrame(this.rAF)}),e.prototype.addEvents=function(){this.start(),window.addEventListener("resize",this.resize),this.$refs.scrollbar.el.addEventListener("click",this.calcScroll),this.$refs.scrollbar.el.addEventListener("mousedown",this.mouseDown),document.addEventListener("mousemove",this.mouseMove),document.addEventListener("mouseup",this.mouseUp)},e.prototype.removeEvents=function(){this.stop(),window.removeEventListener("resize",this.resize)},e.prototype.scrollTo=function(t){this.target=t,this.clampTarget()},e.prototype.setTo=function(t){var e=t;if("string"==typeof e)switch(e){case"bottom":e=this.getState("bounding");break;default:e=0}this.target=e,this.current=e,this.$el.style[this.options.prefix]=this.getTransform(-e),this.$refs.scrollbar.update(this.current),this.clampTarget()},e.prototype.resize=function(){var t=(this.options.orientation,this.options.listener===document.body?window.innerHeight:this.options.listener.clientHeight),e=this.options.listener===document.body?window.innerWidth:this.options.listener.clientWidth;this.setState("height",t),this.setState("width",e),this.$refs.scrollbar.setState("height",t),this.$refs.scrollbar.setState("width",e);var n=this.$el.getBoundingClientRect(),r="vertical"===this.options.orientation?n.height-this.getState("height"):n.right-this.getState("width");this.setState("bounding",r),this.$refs.scrollbar.setState("bounding",r),this.clampTarget(),this.$refs.scrollbar.resize()},e.prototype.clampTarget=function(){this.target=Math.round(Math.max(0,Math.min(this.target,this.getState("bounding"))))},e.prototype.mouseDown=function(t){t.preventDefault(),1===t.which&&this.setState("clicked",!0)},e.prototype.mouseUp=function(t){this.setState("clicked",!1),a.a.remove(this.options.listener,"is-dragging")},e.prototype.mouseMove=function(t){this.getState("clicked")&&this.calcScroll(t)},e.prototype.calcScroll=function(t){var e="vertical"===this.options.orientation?t.clientY:t.clientX,n="vertical"===this.options.orientation?this.getState("height"):this.getState("width"),r=e*(this.getState("bounding")/n);a.a.add(this.options.listener,"is-dragging"),this.target=r,this.clampTarget(),this.$refs.scrollbar.setState("delta",this.target)},e.prototype.destroy=function(){t.prototype.destroy.call(this),a.a.remove(this.options.listener,"is-smoothed"),this.$el.style[this.options.prefix]="","vertical"===this.options.orientation?a.a.remove(this.options.listener,"y-scroll"):a.a.remove(this.options.listener,"x-scroll"),this.current=0,this.removeEvents()},v(e,[{key:"getInitialState",get:function(){return{height:window.innerHeight,width:window.innerWidth,currentItem:0,isAnimating:!1,emitEventOnScrolling:!1}}},{key:"getDefaultOptions",get:function(){return{orientation:"vertical",ease:.075,prefix:h()("transform"),listener:document.body,renderByPixels:!0,deltaY:!1,vs:{limitInertia:!1,mouseMultiplier:1,touchMultiplier:1.5,firefoxMultiplier:30,preventTouch:!0,listenToScroll:!0}}}}]),e}(d.a);e.default=y},function(t,e,n){"use strict";(function(t){function r(){}function i(t){return!!Array.isArray(t)||"[object Array]"===Object.prototype.toString.call(t)}function o(){var t=arguments[1],e=arguments[0];t.forEach(function(t){p.has(e,t)&&r(),p.removeClass(e,t)})}function s(){var t=arguments[1],e=arguments[0];t.forEach(function(t){p.has(e,t)&&r(),p.addClass(e,t)})}function a(t,e){return t.classList.contains(e)}function c(t,e){i(e)?s.apply(this,arguments):t.classList.add(e)}function u(t,e){i(e)?o.apply(this,arguments):t.classList.remove(e)}function l(t,e){(a(t,e)?u:c)(t,e)}var h,f,p,p=(n(8),{hasClass:a,addClass:c,removeClass:u,toggleClass:l,has:a,add:c,remove:u,toggle:l});"object"==typeof t&&t&&"object"==typeof t.exports?t.exports=p:(h=p,void 0!==(f="function"==typeof h?h.call(e,n,e,t):h)&&(t.exports=f))}).call(e,n(1)(t))},function(t,e){/*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/ 2 | "document"in self&&("classList"in document.createElement("_")&&(!document.createElementNS||"classList"in document.createElementNS("http://www.w3.org/2000/svg","g"))?function(){"use strict";var t=document.createElement("_");if(t.classList.add("c1","c2"),!t.classList.contains("c2")){var e=function(t){var e=DOMTokenList.prototype[t];DOMTokenList.prototype[t]=function(t){var n,r=arguments.length;for(n=0;n=e;1<=e?t++:t--)n.push(null);return n}.call(this),this.lastDownDeltas=function(){var t,e,n;for(n=[],t=1,e=2*this.stability;1<=e?t<=e:t>=e;1<=e?t++:t--)n.push(null);return n}.call(this),this.deltasTimestamp=function(){var t,e,n;for(n=[],t=1,e=2*this.stability;1<=e?t<=e:t>=e;1<=e?t++:t--)n.push(null);return n}.call(this)}return t.prototype.check=function(t){var e;return t=t.originalEvent||t,null!=t.wheelDelta?e=t.wheelDelta:null!=t.deltaY?e=-40*t.deltaY:null==t.detail&&0!==t.detail||(e=-40*t.detail),this.deltasTimestamp.push(Date.now()),this.deltasTimestamp.shift(),e>0?(this.lastUpDeltas.push(e),this.lastUpDeltas.shift(),this.isInertia(1)):(this.lastDownDeltas.push(e),this.lastDownDeltas.shift(),this.isInertia(-1))},t.prototype.isInertia=function(t){var e,n,r,i,o,s,a;return e=-1===t?this.lastDownDeltas:this.lastUpDeltas,null===e[0]?t:!(this.deltasTimestamp[2*this.stability-2]+this.delay>Date.now()&&e[0]===e[2*this.stability-1])&&(r=e.slice(0,this.stability),n=e.slice(this.stability,2*this.stability),a=r.reduce(function(t,e){return t+e}),o=n.reduce(function(t,e){return t+e}),s=a/r.length,i=o/n.length,Math.abs(s)1,hasPointer:!!window.navigator.msPointerEnabled,hasKeyDown:"onkeydown"in document,isFirefox:navigator.userAgent.indexOf("Firefox")>-1}}()},function(t,e,n){"use strict"},function(t,e,n){"use strict";var r=function(t,e){e.forEach(function(e){t[e]=t[e].bind(t)})};e.a=r},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var s=n(0),a=n.n(s),c=n(2),u=n.n(c),l=n(3),h=n(26),f=function(){function t(t,e){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:{};return r(this,e),i(this,t.call(this,n,o))}return o(e,t),e.prototype.init=function(){t.prototype.init.call(this),this.$els.drag=u()({selector:"div",styles:"scrollbar"}),this.resize(),this.addScrollBar()},e.prototype.resize=function(){var t="vertical"===this.options.orientation?"height":"width";this.dragHeight=Math.round(this.getState("height")*(this.getState("height")/(this.getState("bounding")+this.getState("height")))),this.$els.drag.style[t]=this.dragHeight+"px"},e.prototype.addScrollBar=function(){var t=this;new Promise(function(e){t.$el.appendChild(t.$els.drag),t.options.listener.appendChild(t.$el),e()}).then(function(){a.a.remove(t.$el,"is-entering")})},e.prototype.removeScrollBar=function(){var t=this;a.a.add(this.$el,"is-leaving"),Object(h.a)(this.$el,function(){t.options.listener.removeChild(t.$el)})},e.prototype.getTransform=function(t){return"vertical"===this.options.orientation?"translate3d(0, "+t+"px, 0)":"translate3d("+t+"px,0,0)"},e.prototype.update=function(t){var e=this.dragHeight,n="vertical"===this.options.orientation?this.getState("height"):this.getState("width"),r=Math.abs(t)/(this.getState("bounding")/(n-e))+e/.5-e,i=Math.round(Math.max(0,Math.min(r-e,r+e)));this.$els.drag.style[this.options.prefix]=this.getTransform(i)},e.prototype.destroy=function(){t.prototype.destroy.call(this),this.removeScrollBar()},f(e,[{key:"getInitialState",get:function(){return{height:0,width:0,delta:0,clicked:!1,x:0}}}]),e}(l.a);e.a=p},function(t,e,n){function r(t,e){if(!(this instanceof r))return new r(t,e);if(!t)throw new Error("element required");if(!e)throw new Error("object required");this.el=t,this.obj=e,this._events={}}function i(t){var e=t.split(/ +/);return{name:e.shift(),selector:e.join(" ")}}var o=n(4),s=n(18),a=["focus","blur"];t.exports=r,r.prototype.sub=function(t,e,n){this._events[t]=this._events[t]||{},this._events[t][e]=n},r.prototype.bind=function(t,e){var n=function(t,e){function n(){var t=[].slice.call(arguments).concat(l);if("function"==typeof e)return void e.apply(c,t);if(!c[e])throw new Error(e+" method is not defined");c[e].apply(c,t)}var r=i(t),a=this.el,c=this.obj,u=r.name,e=e||"on"+u,l=[].slice.call(arguments,2);return r.selector?n=s.bind(a,r.selector,u,n):o.bind(a,u,n),this.sub(u,e,n),n};if("string"==typeof t)n.apply(this,arguments);else for(var r in t)t.hasOwnProperty(r)&&n.call(this,r,t[r])},r.prototype.unbind=function(t,e){if(0==arguments.length)return this.unbindAll();if(1==arguments.length)return this.unbindAllOf(t);var n=this._events[t],r=-1!==a.indexOf(t);if(n){var i=n[e];i&&o.unbind(this.el,t,i,r)}},r.prototype.unbindAll=function(){for(var t in this._events)this.unbindAllOf(t)},r.prototype.unbindAllOf=function(t){var e=this._events[t];if(e)for(var n in e)this.unbind(t,n)}},function(t,e,n){var r=n(19),i=n(4),o=["focus","blur"];e.bind=function(t,e,n,s,a){return-1!==o.indexOf(n)&&(a=!0),i.bind(t,n,function(n){var i=n.target||n.srcElement;n.delegateTarget=r(i,e,!0,t),n.delegateTarget&&s.call(t,n)},a)},e.unbind=function(t,e,n,r){-1!==o.indexOf(e)&&(r=!0),i.unbind(t,e,n,r)}},function(t,e,n){var r=n(20);t.exports=function(t,e,n){for(var i=n?t:t.parentNode;i&&i!==document;){if(r(i,e))return i;i=i.parentNode}}},function(t,e){function n(t,e){if(i)return i.call(t,e);for(var n=t.parentNode.querySelectorAll(e),r=0;r-1}function x(t,e){var n=this.__data__,r=U(n,t);return r<0?n.push([t,e]):n[r][1]=e,this}function A(t){var e=-1,n=t?t.length:0;for(this.clear();++e-1&&t%1==0&&t-1&&t%1==0&&t<=Xt}function kt(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function $t(t){return!!t&&"object"==typeof t}function Dt(t){if(!$t(t)||Ce.call(t)!=Kt||h(t))return!1;var e=Re(t);if(null===e)return!0;var n=De.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&$e.call(n)==Pe}function Pt(t){return lt(t,Yt(t))}function Ct(t){return At(t)?W(t):V(t)}function Yt(t){return At(t)?W(t,!0):Z(t)}function Ft(){return[]}function It(){return!1}var Wt=200,Rt="__lodash_hash_undefined__",Xt=9007199254740991,Ut="[object Arguments]",zt="[object Boolean]",Nt="[object Date]",Bt="[object Function]",Ht="[object GeneratorFunction]",Gt="[object Map]",qt="[object Number]",Kt="[object Object]",Vt="[object RegExp]",Zt="[object Set]",Jt="[object String]",Qt="[object Symbol]",te="[object WeakMap]",ee="[object ArrayBuffer]",ne="[object DataView]",re="[object Float32Array]",ie="[object Float64Array]",oe="[object Int8Array]",se="[object Int16Array]",ae="[object Int32Array]",ce="[object Uint8Array]",ue="[object Uint8ClampedArray]",le="[object Uint16Array]",he="[object Uint32Array]",fe=/[\\^$.*+?()[\]{}|]/g,pe=/\w*$/,de=/^\[object .+?Constructor\]$/,ve=/^(?:0|[1-9]\d*)$/,ye={};ye[re]=ye[ie]=ye[oe]=ye[se]=ye[ae]=ye[ce]=ye[ue]=ye[le]=ye[he]=!0,ye[Ut]=ye["[object Array]"]=ye[ee]=ye[zt]=ye[ne]=ye[Nt]=ye["[object Error]"]=ye[Bt]=ye[Gt]=ye[qt]=ye[Kt]=ye[Vt]=ye[Zt]=ye[Jt]=ye[te]=!1;var ge={};ge[Ut]=ge["[object Array]"]=ge[ee]=ge[ne]=ge[zt]=ge[Nt]=ge[re]=ge[ie]=ge[oe]=ge[se]=ge[ae]=ge[Gt]=ge[qt]=ge[Kt]=ge[Vt]=ge[Zt]=ge[Jt]=ge[Qt]=ge[ce]=ge[ue]=ge[le]=ge[he]=!0,ge["[object Error]"]=ge[Bt]=ge[te]=!1;var be="object"==typeof t&&t&&t.Object===Object&&t,me="object"==typeof self&&self&&self.Object===Object&&self,we=be||me||Function("return this")(),_e="object"==typeof e&&e&&!e.nodeType&&e,je=_e&&"object"==typeof n&&n&&!n.nodeType&&n,Ee=je&&je.exports===_e,Se=Ee&&be.process,Oe=function(){try{return Se&&Se.binding("util")}catch(t){}}(),xe=Oe&&Oe.isTypedArray,Ae=Array.prototype,Le=Function.prototype,Te=Object.prototype,Me=we["__core-js_shared__"],ke=function(){var t=/[^.]+$/.exec(Me&&Me.keys&&Me.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),$e=Le.toString,De=Te.hasOwnProperty,Pe=$e.call(Object),Ce=Te.toString,Ye=RegExp("^"+$e.call(De).replace(fe,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Fe=Ee?we.Buffer:void 0,Ie=we.Symbol,We=we.Uint8Array,Re=p(Object.getPrototypeOf,Object),Xe=Object.create,Ue=Te.propertyIsEnumerable,ze=Ae.splice,Ne=Object.getOwnPropertySymbols,Be=Fe?Fe.isBuffer:void 0,He=p(Object.keys,Object),Ge=Math.max,qe=dt(we,"DataView"),Ke=dt(we,"Map"),Ve=dt(we,"Promise"),Ze=dt(we,"Set"),Je=dt(we,"WeakMap"),Qe=dt(Object,"create"),tn=St(qe),en=St(Ke),nn=St(Ve),rn=St(Ze),on=St(Je),sn=Ie?Ie.prototype:void 0,an=sn?sn.valueOf:void 0;v.prototype.clear=y,v.prototype.delete=g,v.prototype.get=b,v.prototype.has=m,v.prototype.set=w,_.prototype.clear=j,_.prototype.delete=E,_.prototype.get=S,_.prototype.has=O,_.prototype.set=x,A.prototype.clear=L,A.prototype.delete=T,A.prototype.get=M,A.prototype.has=k,A.prototype.set=$,D.prototype.clear=P,D.prototype.delete=C,D.prototype.get=Y,D.prototype.has=F,D.prototype.set=I;var cn=Ne?p(Ne,Object):Ft,un=G;(qe&&un(new qe(new ArrayBuffer(1)))!=ne||Ke&&un(new Ke)!=Gt||Ve&&"[object Promise]"!=un(Ve.resolve())||Ze&&un(new Ze)!=Zt||Je&&un(new Je)!=te)&&(un=function(t){var e=Ce.call(t),n=e==Kt?t.constructor:void 0,r=n?St(n):void 0;if(r)switch(r){case tn:return ne;case en:return Gt;case nn:return"[object Promise]";case rn:return Zt;case on:return te}return e});var ln=Array.isArray,hn=Be||It,fn=xe?function(t){return function(e){return t(e)}}(xe):K,pn=function(t){return tt(function(e,n){var r=-1,i=n.length,o=i>1?n[i-1]:void 0,s=i>2?n[2]:void 0;for(o=t.length>3&&"function"==typeof o?(i--,o):void 0,s&&mt(n[0],n[1],s)&&(o=i<3?void 0:o,i=1),e=Object(e);++r0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function n(){this.removeListener(t,n),i||(i=!0,e.apply(this,arguments))}if(!r(e))throw TypeError("listener must be a function");var i=!1;return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var n,i,s,a;if(!r(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(n=this._events[t],s=n.length,i=-1,n===e||r(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(n)){for(a=s;a-- >0;)if(n[a]===e||n[a].listener&&n[a].listener===e){i=a;break}if(i<0)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[t],r(n))this.removeListener(t,n);else if(n)for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){return this._events&&this._events[t]?r(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(r(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,n){"use strict";n.d(e,"a",function(){return i});var r=-1,i=function(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"_ui.")+ ++r}},function(t,e,n){"use strict";var r=document.createElement("div"),i={webkit:"webkitTransitionEnd",Moz:"transitionend",O:"oTransitionEnd",ms:"MSTransitionEnd"},o=function(){var t=void 0;return t="transitionend",Object.keys(i).some(function(e){if(e+"TransitionProperty"in r.style)return t=i[e],!0}),t}();e.a=function(t,e){return t.addEventListener(o,function n(r){r.target&&r.target!==r.currentTarget||(t.removeEventListener(o,n),e(r))})}}])}); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "smoothie-scroll", 3 | "version": "0.4.3", 4 | "description": "Fake scroll with a smooth engine", 5 | "main": "lib/smoothie.js", 6 | "scripts": { 7 | "dev": "cross-env BABEL_ENV=cjs webpack-dev-server --hot --config ./webpack.config.js --inline", 8 | "build": "cross-env NODE_ENV=development webpack --config webpack.config.js", 9 | "build:min": "cross-env NODE_ENV=production webpack --config webpack.config.js" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "https://github.com/sndrgb/smoothie" 14 | }, 15 | "keywords": [ 16 | "virtual", 17 | "scroll", 18 | "smooth" 19 | ], 20 | "author": "Alessandro Rigobello", 21 | "license": "MIT", 22 | "bugs": { 23 | "url": "https://github.com/sndrgb/smoothie/issues" 24 | }, 25 | "homepage": "https://github.com/sndrgb/smoothie", 26 | "dependencies": { 27 | "classie": "^1.0.0", 28 | "dom-create-element": "^1.0.2", 29 | "events-mixin": "^1.3.0", 30 | "lethargy": "^1.0.2", 31 | "lodash.iselement": "^4.1.1", 32 | "lodash.merge": "^4.6.0", 33 | "prefix": "^1.0.0", 34 | "tiny-emitter": "^2.0.1", 35 | "yuzu": "^0.1.0" 36 | }, 37 | "devDependencies": { 38 | "babel-core": "^6.26.0", 39 | "babel-eslint": "^7.2.3", 40 | "babel-loader": "^7.1.2", 41 | "babel-plugin-add-module-exports": "^0.2.1", 42 | "babel-plugin-transform-object-assign": "^6.22.0", 43 | "babel-preset-env": "^1.6.0", 44 | "babel-preset-es2015": "^6.24.1", 45 | "cross-env": "^5.0.1", 46 | "eslint": "^3.19.0", 47 | "eslint-config-airbnb-base": "^11.2.0", 48 | "eslint-loader": "^1.9.0", 49 | "eslint-plugin-import": "^2.7.0", 50 | "express": "^4.15.3", 51 | "uglifyjs-webpack-plugin": "^0.4.6", 52 | "webpack": "^3.7.1", 53 | "webpack-dev-server": "^2.5.1" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /smoothie.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sndrgb/smoothie/6fcdae0fad63faa30412b2eb0bb9c97ece0c1e62/smoothie.png -------------------------------------------------------------------------------- /src/hijack.js: -------------------------------------------------------------------------------- 1 | import Emitter from 'tiny-emitter'; 2 | import { Lethargy } from 'lethargy'; 3 | 4 | import support from './utils/support'; 5 | import clone from './utils/clone'; 6 | import bindAll from './utils/bindAll'; 7 | 8 | const eventId = 'hijack'; 9 | const keyCodes = { LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SPACE: 32, PAGEUP: 33, PAGEDOWN: 34 }; 10 | 11 | class Hijack { 12 | constructor(options) { 13 | bindAll(this, ['onWheel', 'onMouseWheel', 'onTouchStart', 'onTouchMove', 'onKeyDown']); 14 | 15 | this.el = window; 16 | 17 | if (options && options.el) { 18 | this.el = options.el; 19 | delete options.el; 20 | } 21 | 22 | this.options = Object.assign({ 23 | mouseMultiplier: 1, 24 | touchMultiplier: 2, 25 | firefoxMultiplier: 15, 26 | keyStep: 120, 27 | preventTouch: false, 28 | unpreventTouchClass: 'hijack-touchmove-allowed', 29 | limitInertia: false 30 | }, options); 31 | 32 | if (this.options.limitInertia) this.lethargy = new Lethargy(); 33 | 34 | this.emitter = new Emitter(); 35 | this.event = { 36 | y: 0, 37 | x: 0, 38 | deltaX: 0, 39 | deltaY: 0 40 | }; 41 | this.touchStartX = null; 42 | this.touchStartY = null; 43 | this.bodyTouchAction = null; 44 | 45 | if (this.options.passive !== undefined) { 46 | this.listenerOptions = { passive: this.options.passive }; 47 | } 48 | } 49 | 50 | init() {} 51 | 52 | notify(e) { 53 | const evt = this.event; 54 | evt.x += evt.deltaX; 55 | evt.y += evt.deltaY; 56 | 57 | this.emitter.emit(eventId, { 58 | x: evt.x, 59 | y: evt.y, 60 | deltaX: evt.deltaX, 61 | deltaY: evt.deltaY, 62 | originalEvent: e 63 | }); 64 | } 65 | 66 | onWheel(e) { 67 | const options = this.options; 68 | if (this.lethargy && this.lethargy.check(e) === false) return; 69 | const evt = this.event; 70 | 71 | // In Chrome and in Firefox (at least the new one) 72 | evt.deltaX = e.wheelDeltaX || e.deltaX * -1; 73 | evt.deltaY = e.wheelDeltaY || e.deltaY * -1; 74 | 75 | // for our purpose deltamode = 1 means user is on a wheel mouse, not touch pad 76 | // real meaning: https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent#Delta_modes 77 | if (support.isFirefox && e.deltaMode === 1) { 78 | evt.deltaX *= options.firefoxMultiplier; 79 | evt.deltaY *= options.firefoxMultiplier; 80 | } 81 | 82 | evt.deltaX *= options.mouseMultiplier; 83 | evt.deltaY *= options.mouseMultiplier; 84 | this.notify(e); 85 | } 86 | 87 | onMouseWheel(e) { 88 | if (this.options.limitInertia && this.lethargy.check(e) === false) return; 89 | 90 | const evt = this.event; 91 | 92 | // In Safari, IE and in Chrome if 'wheel' isn't defined 93 | evt.deltaX = (e.wheelDeltaX) ? e.wheelDeltaX : 0; 94 | evt.deltaY = (e.wheelDeltaY) ? e.wheelDeltaY : e.wheelDelta; 95 | this.notify(e); 96 | } 97 | 98 | onTouchStart(e) { 99 | const t = (e.targetTouches) ? e.targetTouches[0] : e; 100 | this.touchStartX = t.pageX; 101 | this.touchStartY = t.pageY; 102 | } 103 | 104 | onTouchMove(e) { 105 | const options = this.options; 106 | 107 | if (options.preventTouch 108 | && !e.target.classList.contains(options.unpreventTouchClass)) { 109 | e.preventDefault(); 110 | } 111 | 112 | const evt = this.event; 113 | const t = (e.targetTouches) ? e.targetTouches[0] : e; 114 | 115 | evt.deltaX = (t.pageX - this.touchStartX) * options.touchMultiplier; 116 | evt.deltaY = (t.pageY - this.touchStartY) * options.touchMultiplier; 117 | 118 | this.touchStartX = t.pageX; 119 | this.touchStartY = t.pageY; 120 | 121 | this.notify(e); 122 | } 123 | 124 | onKeyDown(e) { 125 | const evt = this.event; 126 | const windowHeight = window.innerHeight - 40; 127 | 128 | evt.deltaX = 0; 129 | evt.deltaY = 0; 130 | 131 | switch (e.keyCode) { 132 | case keyCodes.LEFT: 133 | case keyCodes.UP: 134 | evt.deltaY = this.options.keyStep; 135 | break; 136 | case keyCodes.RIGHT: 137 | case keyCodes.DOWN: 138 | evt.deltaY = -this.options.keyStep; 139 | break; 140 | case keyCodes.SPACE && e.shiftKey: 141 | evt.deltaY = windowHeight; 142 | break; 143 | case keyCodes.SPACE: 144 | evt.deltaY = -windowHeight; 145 | break; 146 | case keyCodes.PAGEUP: 147 | evt.deltaY = this.options.keyStep * 4; 148 | break; 149 | case keyCodes.PAGEDOWN: 150 | evt.deltaY = -this.options.keyStep * 4; 151 | break; 152 | default: 153 | return; 154 | } 155 | 156 | this.notify(e); 157 | } 158 | 159 | bind() { 160 | if (support.hasWheelEvent) this.el.addEventListener('wheel', this.onWheel, this.listenerOptions); 161 | if (support.hasMouseWheelEvent) this.el.addEventListener('mousewheel', this.onMouseWheel, this.listenerOptions); 162 | 163 | if (support.hasTouch) { 164 | this.el.addEventListener('touchstart', this.onTouchStart, this.listenerOptions); 165 | this.el.addEventListener('touchmove', this.onTouchMove, this.listenerOptions); 166 | } 167 | 168 | if (support.hasPointer && support.hasTouchWin) { 169 | this.bodyTouchAction = document.body.style.msTouchAction; 170 | document.body.style.msTouchAction = 'none'; 171 | this.el.addEventListener('MSPointerDown', this.onTouchStart, true); 172 | this.el.addEventListener('MSPointerMove', this.onTouchMove, true); 173 | } 174 | 175 | if (support.hasKeyDown) document.addEventListener('keydown', this.onKeyDown); 176 | } 177 | 178 | unbind() { 179 | if (support.hasWheelEvent) this.el.removeEventListener('wheel', this.onWheel); 180 | if (support.hasMouseWheelEvent) this.el.removeEventListener('mousewheel', this.onMouseWheel); 181 | 182 | if (support.hasTouch) { 183 | this.el.removeEventListener('touchstart', this.onTouchStart); 184 | this.el.removeEventListener('touchmove', this.onTouchMove); 185 | } 186 | 187 | if (support.hasPointer && support.hasTouchWin) { 188 | document.body.style.msTouchAction = this.bodyTouchAction; 189 | this.el.removeEventListener('MSPointerDown', this.onTouchStart, true); 190 | this.el.removeEventListener('MSPointerMove', this.onTouchMove, true); 191 | } 192 | 193 | if (support.hasKeyDown) document.removeEventListener('keydown', this.onKeyDown); 194 | } 195 | 196 | on(cb, ctx) { 197 | this.emitter.on(eventId, cb, ctx); 198 | 199 | const events = this.emitter.e; 200 | if (events && events[eventId] && events[eventId].length === 1) this.bind(); 201 | } 202 | 203 | off(cb, ctx) { 204 | this.emitter.off(eventId, cb, ctx); 205 | 206 | const events = this.emitter.e; 207 | if (!events[eventId] || events[eventId].length <= 0) this.unbind(); 208 | } 209 | 210 | reset() { 211 | const evt = this.event; 212 | evt.x = 0; 213 | evt.y = 0; 214 | } 215 | 216 | destroy() { 217 | this.emitter.off(); 218 | this.unbind(); 219 | } 220 | } 221 | 222 | export default Hijack; 223 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import classie from 'classie'; 2 | import create from 'dom-create-element'; 3 | import prefix from 'prefix'; 4 | 5 | import Hijack from './hijack'; 6 | import Scrollbar from './scrollbar'; 7 | import Component from './utils/component'; 8 | 9 | class Smoothie extends Component { 10 | constructor(el = '.smoothie', opt = {}) { 11 | super(el, opt); 12 | 13 | this.createBound(); 14 | this.rAF = undefined; 15 | this.isRAFCanceled = false; 16 | 17 | const constructorName = this.constructor.name ? this.constructor.name : 'Smoothie'; 18 | this.extends = constructorName !== 'Smoothie'; 19 | 20 | this.current = 0; 21 | this.target = 0; 22 | } 23 | 24 | get getInitialState() { 25 | return { 26 | height: window.innerHeight, 27 | width: window.innerWidth, 28 | currentItem: 0, 29 | isAnimating: false, 30 | emitEventOnScrolling: false, 31 | }; 32 | } 33 | 34 | get getDefaultOptions() { 35 | return { 36 | orientation: 'vertical', 37 | ease: 0.075, 38 | prefix: prefix('transform'), 39 | listener: document.body, 40 | renderByPixels: true, 41 | deltaY: false, 42 | 43 | vs: { 44 | limitInertia: false, 45 | mouseMultiplier: 1, 46 | touchMultiplier: 1.5, 47 | firefoxMultiplier: 30, 48 | preventTouch: true, 49 | listenToScroll: true, 50 | }, 51 | }; 52 | } 53 | 54 | createBound() { 55 | ['run', 'calc', 'resize', 'scrollTo', 'mouseUp', 'mouseDown', 'mouseMove', 'calcScroll', 'inViewport', 'addListener'] 56 | .forEach((fn) => { this[fn] = this[fn].bind(this); }); 57 | } 58 | 59 | addListener(callback) { 60 | this.setState('emitEventOnScrolling', true); 61 | 62 | this.on('scrolling', (stat) => { 63 | callback(stat); 64 | }); 65 | } 66 | 67 | removeListener(callback) { 68 | this.setState('emitEventOnScrolling', false); 69 | } 70 | 71 | inViewport(el, index) { 72 | // if (!this.cache || this.resizing) return false; 73 | const bounding = el.getBoundingClientRect(); 74 | const bounds = { 75 | top: bounding.top + this.current 76 | } 77 | const viewport = {}; 78 | viewport.top = this.current; 79 | viewport.bottom = this.current + window.innerHeight; 80 | 81 | bounds.bottom = bounds.top + el.clientHeight; 82 | 83 | return (bounds.bottom >= viewport.top && bounds.bottom <= viewport.bottom) 84 | || (bounds.top <= viewport.bottom && bounds.top >= viewport.top); 85 | } 86 | 87 | init(initialPosition) { 88 | super.init(); 89 | 90 | if (initialPosition && initialPosition !== undefined && initialPosition !== null) { 91 | this.current = initialPosition; 92 | this.target = initialPosition; 93 | } 94 | 95 | this.addClasses(); 96 | 97 | // starting hijacking 98 | this.setRef('hijack', Hijack, this.options.vs); 99 | 100 | // passing scrollbar track 101 | this.$els.scrollbar = create({ 102 | selector: 'div', 103 | styles: `scrollbar-track scrollbar-${this.options.orientation} is-entering` 104 | }); 105 | this.setRef('scrollbar', Scrollbar, this.$els.scrollbar, this.options); 106 | 107 | this.resize(); 108 | this.update = this.resize; 109 | this.addEvents(); 110 | } 111 | 112 | addClasses() { 113 | const orientation = this.options.orientation === 'vertical' ? 'y' : 'x'; 114 | 115 | classie.add(this.options.listener, 'is-smoothed'); 116 | classie.add(this.options.listener, `${orientation}-scroll`); 117 | } 118 | 119 | calc(e) { 120 | const delta = (this.options.orientation === 'horizontal' && this.options.deltaX) ? e.deltaX : e.deltaY; 121 | 122 | this.target += delta * -1; 123 | 124 | // set direction to up or down 125 | this.setState('direction', (this.target > this.current) ? 'down' : 'up'); 126 | 127 | this.clampTarget(); 128 | } 129 | 130 | run() { 131 | if (this.isRAFCanceled) return; 132 | 133 | this.current += (this.target - this.current) * this.options.ease; 134 | this.current < 0.1 && (this.current = 0); 135 | this.rAF = window.requestAnimationFrame(this.run); 136 | 137 | let position = this.current.toFixed(2); 138 | 139 | if (this.options.renderByPixels) { 140 | position = Math.round(this.current); 141 | } 142 | 143 | this.$el.style[this.options.prefix] = this.getTransform(-position); 144 | this.$refs.scrollbar.update(this.current); 145 | 146 | if (this.getState('emitEventOnScrolling')) { 147 | this.emit('scrolling', { 148 | current: this.current, 149 | direction: this.getState('direction') 150 | }); 151 | } 152 | } 153 | 154 | getTransform(value) { 155 | return this.options.orientation === 'vertical' ? `translate3d(0, ${value}px, 0)` : `translate3d(${value}px,0,0)`; 156 | } 157 | 158 | start(requestAnimationFrame = true) { 159 | if (this.isRAFCanceled) this.isRAFCanceled = false; 160 | 161 | const node = this.options.listener === document.body ? window : this.options.listener; 162 | this.$refs.hijack.on(this.calc); 163 | 164 | if (requestAnimationFrame) this.requestAnimationFrame(); 165 | } 166 | 167 | stop(cancelAnimationFrame = true) { 168 | const node = this.options.listener === document.body ? window : this.options.listener; 169 | 170 | this.$refs.hijack.off(this.calc); 171 | if (cancelAnimationFrame) this.cancelAnimationFrame(); 172 | } 173 | 174 | requestAnimationFrame() { 175 | this.rAF = requestAnimationFrame(this.run); 176 | } 177 | 178 | cancelAnimationFrame() { 179 | this.isRAFCanceled = true; 180 | cancelAnimationFrame(this.rAF); 181 | } 182 | 183 | addEvents() { 184 | this.start(); 185 | window.addEventListener('resize', this.resize); 186 | 187 | this.$refs.scrollbar.el.addEventListener('click', this.calcScroll); 188 | this.$refs.scrollbar.el.addEventListener('mousedown', this.mouseDown); 189 | 190 | document.addEventListener('mousemove', this.mouseMove); 191 | document.addEventListener('mouseup', this.mouseUp); 192 | } 193 | 194 | removeEvents() { 195 | this.stop(); 196 | window.removeEventListener('resize', this.resize); 197 | } 198 | 199 | scrollTo(offset) { 200 | this.target = offset; 201 | this.clampTarget(); 202 | } 203 | 204 | setTo(offset) { 205 | let target = offset; 206 | 207 | if (typeof (target) === 'string') { 208 | switch (target) { 209 | case 'bottom': 210 | target = this.getState('bounding'); 211 | break; 212 | default: 213 | target = 0; 214 | 215 | } 216 | } 217 | 218 | this.target = target; 219 | this.current = target; 220 | this.$el.style[this.options.prefix] = this.getTransform(-target); 221 | this.$refs.scrollbar.update(this.current); 222 | this.clampTarget(); 223 | } 224 | 225 | resize() { 226 | const prop = this.options.orientation === 'vertical' ? 'height' : 'width'; 227 | 228 | const h = this.options.listener === document.body ? 229 | window.innerHeight : this.options.listener.clientHeight; 230 | const w = this.options.listener === document.body ? 231 | window.innerWidth : this.options.listener.clientWidth; 232 | 233 | this.setState('height', h); 234 | this.setState('width', w); 235 | this.$refs.scrollbar.setState('height', h); 236 | this.$refs.scrollbar.setState('width', w); 237 | 238 | const bounding = this.$el.getBoundingClientRect(); 239 | const bounds = this.options.orientation === 'vertical' ? 240 | bounding.height - this.getState('height') : 241 | bounding.right - this.getState('width'); 242 | 243 | this.setState('bounding', bounds); 244 | this.$refs.scrollbar.setState('bounding', bounds); 245 | 246 | this.clampTarget(); 247 | 248 | this.$refs.scrollbar.resize(); 249 | } 250 | 251 | clampTarget() { 252 | this.target = Math.round(Math.max(0, Math.min(this.target, this.getState('bounding')))); 253 | } 254 | 255 | mouseDown(e) { 256 | e.preventDefault(); 257 | 258 | if (e.which === 1) this.setState('clicked', true); 259 | } 260 | 261 | mouseUp(e) { 262 | this.setState('clicked', false); 263 | classie.remove(this.options.listener, 'is-dragging'); 264 | } 265 | 266 | mouseMove(e) { 267 | if (this.getState('clicked')) this.calcScroll(e); 268 | } 269 | 270 | calcScroll(e) { 271 | const client = this.options.orientation === 'vertical' ? e.clientY : e.clientX; 272 | const bounds = this.options.orientation === 'vertical' ? this.getState('height') : this.getState('width'); 273 | const delta = client * (this.getState('bounding') / bounds); 274 | 275 | classie.add(this.options.listener, 'is-dragging'); 276 | 277 | this.target = delta; 278 | this.clampTarget(); 279 | this.$refs.scrollbar.setState('delta', this.target); 280 | } 281 | 282 | destroy() { 283 | super.destroy(); 284 | classie.remove(this.options.listener, 'is-smoothed'); 285 | 286 | this.$el.style[this.options.prefix] = ''; 287 | this.options.orientation === 'vertical' ? classie.remove(this.options.listener, 'y-scroll') : classie.remove(this.options.listener, 'x-scroll'); 288 | this.current = 0; 289 | 290 | this.removeEvents(); 291 | } 292 | } 293 | 294 | export default Smoothie; 295 | -------------------------------------------------------------------------------- /src/scrollbar.js: -------------------------------------------------------------------------------- 1 | import classie from 'classie'; 2 | import create from 'dom-create-element'; 3 | 4 | import Component from './utils/component'; 5 | import transitionEnd from './utils/after-transition'; 6 | 7 | class Scrollbar extends Component { 8 | constructor(el, opts = {}) { 9 | super(el, opts); 10 | } 11 | 12 | init() { 13 | super.init(); 14 | 15 | this.$els.drag = create({ selector: 'div', styles: 'scrollbar' }); 16 | 17 | this.resize(); 18 | this.addScrollBar(); 19 | } 20 | 21 | get getInitialState() { 22 | return { 23 | height: 0, 24 | width: 0, 25 | delta: 0, 26 | clicked: false, 27 | x: 0 28 | }; 29 | } 30 | 31 | resize() { 32 | const prop = this.options.orientation === 'vertical' ? 'height' : 'width'; 33 | this.dragHeight = Math.round(this.getState('height') * (this.getState('height') / (this.getState('bounding') + this.getState('height')))); 34 | this.$els.drag.style[prop] = `${this.dragHeight}px`; 35 | } 36 | 37 | addScrollBar() { 38 | const p1 = new Promise((resolve) => { 39 | this.$el.appendChild(this.$els.drag); 40 | this.options.listener.appendChild(this.$el); 41 | resolve(); 42 | }); 43 | 44 | p1.then(() => { 45 | classie.remove(this.$el, 'is-entering'); 46 | }); 47 | } 48 | 49 | removeScrollBar() { 50 | classie.add(this.$el, 'is-leaving'); 51 | 52 | transitionEnd(this.$el, () => { 53 | this.options.listener.removeChild(this.$el); 54 | }); 55 | } 56 | 57 | getTransform(value) { 58 | return this.options.orientation === 'vertical' ? `translate3d(0, ${value}px, 0)` : `translate3d(${value}px,0,0)`; 59 | } 60 | 61 | update(current) { 62 | const size = this.dragHeight; 63 | const bounds = this.options.orientation === 'vertical' ? this.getState('height') : this.getState('width'); 64 | const value = (Math.abs(current) / (this.getState('bounding') / (bounds - size))) + (size / 0.5) - size; 65 | const clamp = Math.round(Math.max(0, Math.min(value - size, value + size))); 66 | 67 | this.$els.drag.style[this.options.prefix] = this.getTransform(clamp); 68 | } 69 | 70 | 71 | destroy() { 72 | super.destroy(); 73 | this.removeScrollBar(); 74 | } 75 | } 76 | 77 | export default Scrollbar; 78 | -------------------------------------------------------------------------------- /src/utils/after-transition.js: -------------------------------------------------------------------------------- 1 | const dummy = document.createElement('div'); 2 | const eventNameHash = { 3 | webkit: 'webkitTransitionEnd', 4 | Moz: 'transitionend', 5 | O: 'oTransitionEnd', 6 | ms: 'MSTransitionEnd' 7 | }; 8 | 9 | const transitionEnd = (() => { 10 | let retValue; 11 | let transitions 12 | retValue = 'transitionend'; 13 | 14 | Object.keys(eventNameHash).some((vendor) => { 15 | if (`${vendor}TransitionProperty` in dummy.style) { 16 | retValue = eventNameHash[vendor]; 17 | return true; 18 | } 19 | }); 20 | 21 | return retValue; 22 | })(); 23 | 24 | export default function (element, callback) { 25 | return element.addEventListener(transitionEnd, function eventend(event) { 26 | if (event.target && event.target !== event.currentTarget) return; 27 | 28 | element.removeEventListener(transitionEnd, eventend); 29 | callback(event); 30 | }); 31 | } 32 | -------------------------------------------------------------------------------- /src/utils/bindAll.js: -------------------------------------------------------------------------------- 1 | const bindAll = (ctx, methods) => { 2 | methods.forEach((m) => { ctx[m] = ctx[m].bind(ctx); }); 3 | }; 4 | 5 | export default bindAll; 6 | -------------------------------------------------------------------------------- /src/utils/clone.js: -------------------------------------------------------------------------------- 1 | export default function(source) { 2 | return JSON.parse(JSON.stringify(source)); 3 | } 4 | -------------------------------------------------------------------------------- /src/utils/component.js: -------------------------------------------------------------------------------- 1 | import DOMEvents from 'events-mixin'; 2 | import isElement from 'lodash.isElement'; 3 | import merge from 'lodash.merge'; 4 | 5 | import { EventEmitter } from 'events'; 6 | import { nextUid } from './ui-manager'; 7 | 8 | class Component extends EventEmitter { 9 | constructor(el, options = { state: {} }) { 10 | super(); 11 | this.setMaxListeners(0); 12 | 13 | this.el = this.$el = typeof el === 'string' ? document.querySelector(el) : el; 14 | 15 | if (!isElement(this.$el)) { 16 | // fail silently (kinda...); 17 | console.warn(`Element ${this.$el} is not a DOM element`); 18 | return this; 19 | } 20 | 21 | // DOM references 22 | this.$els = {}; 23 | 24 | // sub components references 25 | this.$refs = {}; 26 | 27 | this.options = merge(this.getDefaultOptions, options); 28 | 29 | const domEvents = new DOMEvents(this.$el, this); 30 | this.delegate = (event, selector, fn) => domEvents.bind(event + (selector ? ' ' + selector : ''), fn); 31 | this.undelegate = () => domEvents.unbind(...arguments); 32 | 33 | this.state = new Map(); 34 | } 35 | 36 | setRef(id, ComponentClass, ...opts) { 37 | const ref = ComponentClass instanceof Component ? ComponentClass : new ComponentClass(...opts); 38 | const prevRef = this.$refs[id]; 39 | this.$refs[id] = ref; 40 | 41 | if (prevRef) { 42 | return prevRef.destroy().then(() => { 43 | if (this.$el.contains(prevRef.$el)) { 44 | this.$el.replaceChild(ref.$el, prevRef.$el); 45 | } else { 46 | this.$el.appendChild(ref.$el); 47 | } 48 | return ref.init(); 49 | }); 50 | } 51 | 52 | return Promise.resolve(ref.init()); 53 | } 54 | 55 | init(state = {}) { 56 | // initialization placeholder 57 | if (this.$el.getAttribute('data-ui-uid')) { 58 | console.log(`Element ${this.$el.getAttribute('data-ui-uid')} is already created`, this.$el); 59 | return this; 60 | } 61 | 62 | this._uid = nextUid(); 63 | this.$el.setAttribute('data-ui-uid', this._uid); 64 | 65 | if (!this.$el.id) { 66 | this.$el.id = `component${this._uid}`; 67 | } 68 | 69 | this.beforeInit(); 70 | 71 | const stateEventsMap = this.bindStateEvents(); 72 | Object.keys(stateEventsMap).forEach((key) => { 73 | this.on('change:' + key, stateEventsMap[key].bind(this)); 74 | }); 75 | 76 | const initialState = Object.assign({}, this.getInitialState, state); 77 | Object.keys(initialState).forEach((key) => { 78 | this.setState(key, initialState[key]); 79 | }); 80 | 81 | this._active = true; 82 | 83 | return this; 84 | } 85 | 86 | broadcast(event, ...params) { 87 | Object.keys(this.$refs).forEach((ref) => this.$refs[ref].emit('broadcast:' + event, ...params)); 88 | } 89 | 90 | getState(key) { 91 | return this.state.get(key); 92 | } 93 | 94 | setState(key, newValue, silent = false) { 95 | const oldValue = this.state.get(key); 96 | if (oldValue !== newValue) { 97 | this.state.set(key, newValue); 98 | if (!silent) { 99 | this.emit('change:' + key, newValue, oldValue); 100 | } 101 | 102 | return newValue; 103 | } 104 | } 105 | 106 | bindStateEvents() { 107 | return {}; 108 | } 109 | 110 | getPizza() { 111 | console.log('🍕 enjoy!'); 112 | } 113 | 114 | getBomb() { 115 | console.log('💣 aaaaaaaaaa!'); 116 | } 117 | 118 | get getInitialState() { 119 | return {}; 120 | } 121 | 122 | get getDefaultOptions() { 123 | return {}; 124 | } 125 | 126 | animationIn() { 127 | 128 | } 129 | 130 | beforeInit() { 131 | } 132 | 133 | closeRefs() { 134 | return Promise.all(Object.keys(this.$refs).map((ref) => { 135 | return this.$refs[ref].destroy(); 136 | })).then(() => { 137 | this.$refs = {}; 138 | }).catch((error) => { 139 | console.log('close refs', error); 140 | }); 141 | } 142 | 143 | destroy() { 144 | this.emit('destroy'); 145 | this.undelegate(); 146 | this.removeAllListeners(); 147 | this.$el.removeAttribute('data-ui-uid'); 148 | 149 | return this.closeRefs().then(() => { 150 | this._active = false; 151 | }).catch((error) => { 152 | console.log('destroy catch: ', error); 153 | }); 154 | } 155 | 156 | } 157 | 158 | export default Component; -------------------------------------------------------------------------------- /src/utils/support.js: -------------------------------------------------------------------------------- 1 | module.exports = (function getSupport() { 2 | return { 3 | hasWheelEvent: 'onwheel' in document, 4 | hasMouseWheelEvent: 'onmousewheel' in document, 5 | hasTouch: 'ontouchstart' in document, 6 | hasTouchWin: navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 1, 7 | hasPointer: !!window.navigator.msPointerEnabled, 8 | hasKeyDown: 'onkeydown' in document, 9 | isFirefox: navigator.userAgent.indexOf('Firefox') > -1 10 | }; 11 | })(); 12 | -------------------------------------------------------------------------------- /src/utils/ui-manager.js: -------------------------------------------------------------------------------- 1 | let uid = -1; 2 | 3 | export const UID_PREFIX = '_ui.'; 4 | 5 | export const nextUid = (prefix = UID_PREFIX) => prefix + (++uid); 6 | 7 | const uiManager = { 8 | UID_PREFIX, 9 | nextUid 10 | }; 11 | 12 | 13 | export default uiManager; 14 | 15 | 16 | /** WEBPACK FOOTER ** 17 | ** ./base/ui-manager.js 18 | **/ -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack'); 2 | const path = require('path'); 3 | const express = require('express'); 4 | const version = require('./package.json').version; 5 | 6 | /*eslint-disable */ 7 | const banner = 8 | "/**\n" + 9 | " * smoothie v" + version + "\n" + 10 | " * Copyright (c) " + (new Date().getFullYear()) + " Alessandro Rigobello\n" + 11 | " * MIT License\n" + 12 | " */\n"; 13 | /*eslint-enable */ 14 | 15 | console.log(process.env.NODE_ENV); 16 | 17 | const plugins = [ 18 | new webpack.BannerPlugin({ raw: true, banner }), 19 | new webpack.NoEmitOnErrorsPlugin(), 20 | new webpack.DefinePlugin({ 21 | 'process.env': { 22 | NODE_ENV: JSON.stringify(process.env.NODE_ENV) 23 | } 24 | }) 25 | ]; 26 | 27 | if (process.env.NODE_ENV === 'production') { 28 | plugins.push( 29 | new webpack.optimize.UglifyJsPlugin({ 30 | compress: { 31 | warnings: false 32 | } 33 | }) 34 | ); 35 | } 36 | 37 | module.exports = { 38 | entry: { 39 | smoothie: ['./src/index.js'] 40 | }, 41 | 42 | output: { 43 | library: 'smoothie', 44 | libraryTarget: 'umd', 45 | path: path.join(process.cwd(), 'lib'), 46 | filename: process.env.NODE_ENV === 'production' ? 'smoothie.min.js' : 'smoothie.js', 47 | }, 48 | 49 | plugins, 50 | 51 | devServer: { 52 | contentBase: './example', 53 | hot: true, 54 | historyApiFallback: true, 55 | publicPath: '/dist/' 56 | }, 57 | 58 | module: { 59 | rules: [{ 60 | test: /\.js$/, 61 | include: [ 62 | path.join(process.cwd(), 'src') 63 | ], 64 | loader: 'babel-loader', 65 | }] 66 | } 67 | }; 68 | --------------------------------------------------------------------------------