wheel.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /*!
  2. * better-scroll / wheel
  3. * (c) 2016-2021 ustbhuangyi
  4. * Released under the MIT License.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Wheel = factory());
  10. }(this, (function () { 'use strict';
  11. // ssr support
  12. var inBrowser = typeof window !== 'undefined';
  13. var ua = inBrowser && navigator.userAgent.toLowerCase();
  14. !!(ua && /wechatdevtools/.test(ua));
  15. ua && ua.indexOf('android') > 0;
  16. /* istanbul ignore next */
  17. ((function () {
  18. if (typeof ua === 'string') {
  19. var regex = /os (\d\d?_\d(_\d)?)/;
  20. var matches = regex.exec(ua);
  21. if (!matches)
  22. return false;
  23. var parts = matches[1].split('_').map(function (item) {
  24. return parseInt(item, 10);
  25. });
  26. // ios version >= 13.4 issue 982
  27. return !!(parts[0] === 13 && parts[1] >= 4);
  28. }
  29. return false;
  30. }))();
  31. /* istanbul ignore next */
  32. var supportsPassive = false;
  33. /* istanbul ignore next */
  34. if (inBrowser) {
  35. var EventName = 'test-passive';
  36. try {
  37. var opts = {};
  38. Object.defineProperty(opts, 'passive', {
  39. get: function () {
  40. supportsPassive = true;
  41. },
  42. }); // https://github.com/facebook/flow/issues/285
  43. window.addEventListener(EventName, function () { }, opts);
  44. }
  45. catch (e) { }
  46. }
  47. var extend = function (target, source) {
  48. for (var key in source) {
  49. target[key] = source[key];
  50. }
  51. return target;
  52. };
  53. var elementStyle = (inBrowser &&
  54. document.createElement('div').style);
  55. var vendor = (function () {
  56. /* istanbul ignore if */
  57. if (!inBrowser) {
  58. return false;
  59. }
  60. var transformNames = [
  61. {
  62. key: 'standard',
  63. value: 'transform',
  64. },
  65. {
  66. key: 'webkit',
  67. value: 'webkitTransform',
  68. },
  69. {
  70. key: 'Moz',
  71. value: 'MozTransform',
  72. },
  73. {
  74. key: 'O',
  75. value: 'OTransform',
  76. },
  77. {
  78. key: 'ms',
  79. value: 'msTransform',
  80. },
  81. ];
  82. for (var _i = 0, transformNames_1 = transformNames; _i < transformNames_1.length; _i++) {
  83. var obj = transformNames_1[_i];
  84. if (elementStyle[obj.value] !== undefined) {
  85. return obj.key;
  86. }
  87. }
  88. /* istanbul ignore next */
  89. return false;
  90. })();
  91. /* istanbul ignore next */
  92. function prefixStyle(style) {
  93. if (vendor === false) {
  94. return style;
  95. }
  96. if (vendor === 'standard') {
  97. if (style === 'transitionEnd') {
  98. return 'transitionend';
  99. }
  100. return style;
  101. }
  102. return vendor + style.charAt(0).toUpperCase() + style.substr(1);
  103. }
  104. vendor && vendor !== 'standard' ? '-' + vendor.toLowerCase() + '-' : '';
  105. var transform = prefixStyle('transform');
  106. var transition = prefixStyle('transition');
  107. inBrowser && prefixStyle('perspective') in elementStyle;
  108. var style = {
  109. transform: transform,
  110. transition: transition,
  111. transitionTimingFunction: prefixStyle('transitionTimingFunction'),
  112. transitionDuration: prefixStyle('transitionDuration'),
  113. transitionDelay: prefixStyle('transitionDelay'),
  114. transformOrigin: prefixStyle('transformOrigin'),
  115. transitionEnd: prefixStyle('transitionEnd'),
  116. transitionProperty: prefixStyle('transitionProperty'),
  117. };
  118. function hasClass(el, className) {
  119. var reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
  120. return reg.test(el.className);
  121. }
  122. function HTMLCollectionToArray(el) {
  123. return Array.prototype.slice.call(el, 0);
  124. }
  125. var ease = {
  126. // easeOutQuint
  127. swipe: {
  128. style: 'cubic-bezier(0.23, 1, 0.32, 1)',
  129. fn: function (t) {
  130. return 1 + --t * t * t * t * t;
  131. }
  132. },
  133. // easeOutQuard
  134. swipeBounce: {
  135. style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
  136. fn: function (t) {
  137. return t * (2 - t);
  138. }
  139. },
  140. // easeOutQuart
  141. bounce: {
  142. style: 'cubic-bezier(0.165, 0.84, 0.44, 1)',
  143. fn: function (t) {
  144. return 1 - --t * t * t * t;
  145. }
  146. }
  147. };
  148. var sourcePrefix = 'plugins.wheel';
  149. var propertiesMap = [
  150. {
  151. key: 'wheelTo',
  152. name: 'wheelTo',
  153. },
  154. {
  155. key: 'getSelectedIndex',
  156. name: 'getSelectedIndex',
  157. },
  158. {
  159. key: 'restorePosition',
  160. name: 'restorePosition',
  161. },
  162. ];
  163. var propertiesConfig = propertiesMap.map(function (item) {
  164. return {
  165. key: item.key,
  166. sourceKey: sourcePrefix + "." + item.name,
  167. };
  168. });
  169. var WHEEL_INDEX_CHANGED_EVENT_NAME = 'wheelIndexChanged';
  170. var CONSTANTS = {
  171. rate: 4
  172. };
  173. var Wheel = /** @class */ (function () {
  174. function Wheel(scroll) {
  175. this.scroll = scroll;
  176. this.init();
  177. }
  178. Wheel.prototype.init = function () {
  179. this.handleBScroll();
  180. this.handleOptions();
  181. this.handleHooks();
  182. // init boundary for Wheel
  183. this.refreshBoundary();
  184. this.setSelectedIndex(this.options.selectedIndex);
  185. };
  186. Wheel.prototype.handleBScroll = function () {
  187. this.scroll.proxy(propertiesConfig);
  188. this.scroll.registerType([WHEEL_INDEX_CHANGED_EVENT_NAME]);
  189. };
  190. Wheel.prototype.handleOptions = function () {
  191. var userOptions = (this.scroll.options.wheel === true
  192. ? {}
  193. : this.scroll.options.wheel);
  194. var defaultOptions = {
  195. wheelWrapperClass: 'wheel-scroll',
  196. wheelItemClass: 'wheel-item',
  197. rotate: 25,
  198. adjustTime: 400,
  199. selectedIndex: 0,
  200. wheelDisabledItemClass: 'wheel-disabled-item'
  201. };
  202. this.options = extend(defaultOptions, userOptions);
  203. };
  204. Wheel.prototype.handleHooks = function () {
  205. var _this = this;
  206. var scroll = this.scroll;
  207. var scroller = this.scroll.scroller;
  208. var actionsHandler = scroller.actionsHandler, scrollBehaviorX = scroller.scrollBehaviorX, scrollBehaviorY = scroller.scrollBehaviorY, animater = scroller.animater;
  209. var prevContent = scroller.content;
  210. // BScroll
  211. scroll.on(scroll.eventTypes.scrollEnd, function (position) {
  212. var index = _this.findNearestValidWheel(position.y).index;
  213. if (scroller.animater.forceStopped && !_this.isAdjustingPosition) {
  214. _this.target = _this.items[index];
  215. // since stopped from an animation.
  216. // prevent user's scrollEnd callback triggered twice
  217. return true;
  218. }
  219. else {
  220. _this.setSelectedIndex(index);
  221. if (_this.isAdjustingPosition) {
  222. _this.isAdjustingPosition = false;
  223. }
  224. }
  225. });
  226. // BScroll.hooks
  227. this.scroll.hooks.on(this.scroll.hooks.eventTypes.refresh, function (content) {
  228. if (content !== prevContent) {
  229. prevContent = content;
  230. _this.setSelectedIndex(_this.options.selectedIndex, true);
  231. }
  232. // rotate all wheel-items
  233. // because position may not change
  234. _this.rotateX(_this.scroll.y);
  235. // check we are stop at a disable item or not
  236. _this.wheelTo(_this.selectedIndex, 0);
  237. });
  238. this.scroll.hooks.on(this.scroll.hooks.eventTypes.beforeInitialScrollTo, function (position) {
  239. // selectedIndex has higher priority than bs.options.startY
  240. position.x = 0;
  241. position.y = -(_this.selectedIndex * _this.itemHeight);
  242. });
  243. // Scroller
  244. scroller.hooks.on(scroller.hooks.eventTypes.checkClick, function () {
  245. var index = HTMLCollectionToArray(_this.items).indexOf(_this.target);
  246. if (index === -1)
  247. return true;
  248. _this.wheelTo(index, _this.options.adjustTime, ease.swipe);
  249. return true;
  250. });
  251. scroller.hooks.on(scroller.hooks.eventTypes.scrollTo, function (endPoint) {
  252. endPoint.y = _this.findNearestValidWheel(endPoint.y).y;
  253. });
  254. // when content is scrolling
  255. // click wheel-item DOM repeatedly and crazily will cause scrollEnd not triggered
  256. // so reset forceStopped
  257. scroller.hooks.on(scroller.hooks.eventTypes.minDistanceScroll, function () {
  258. var animater = scroller.animater;
  259. if (animater.forceStopped === true) {
  260. animater.forceStopped = false;
  261. }
  262. });
  263. scroller.hooks.on(scroller.hooks.eventTypes.scrollToElement, function (el, pos) {
  264. if (!hasClass(el, _this.options.wheelItemClass)) {
  265. return true;
  266. }
  267. else {
  268. pos.top = _this.findNearestValidWheel(pos.top).y;
  269. }
  270. });
  271. // ActionsHandler
  272. actionsHandler.hooks.on(actionsHandler.hooks.eventTypes.beforeStart, function (e) {
  273. _this.target = e.target;
  274. });
  275. // ScrollBehaviorX
  276. // Wheel has no x direction now
  277. scrollBehaviorX.hooks.on(scrollBehaviorX.hooks.eventTypes.computeBoundary, function (boundary) {
  278. boundary.maxScrollPos = 0;
  279. boundary.minScrollPos = 0;
  280. });
  281. // ScrollBehaviorY
  282. scrollBehaviorY.hooks.on(scrollBehaviorY.hooks.eventTypes.computeBoundary, function (boundary) {
  283. _this.items = _this.scroll.scroller.content.children;
  284. _this.checkWheelAllDisabled();
  285. _this.itemHeight =
  286. _this.items.length > 0
  287. ? scrollBehaviorY.contentSize / _this.items.length
  288. : 0;
  289. boundary.maxScrollPos = -_this.itemHeight * (_this.items.length - 1);
  290. boundary.minScrollPos = 0;
  291. });
  292. scrollBehaviorY.hooks.on(scrollBehaviorY.hooks.eventTypes.momentum, function (momentumInfo) {
  293. momentumInfo.rate = CONSTANTS.rate;
  294. momentumInfo.destination = _this.findNearestValidWheel(momentumInfo.destination).y;
  295. });
  296. scrollBehaviorY.hooks.on(scrollBehaviorY.hooks.eventTypes.end, function (momentumInfo) {
  297. var validWheel = _this.findNearestValidWheel(scrollBehaviorY.currentPos);
  298. momentumInfo.destination = validWheel.y;
  299. momentumInfo.duration = _this.options.adjustTime;
  300. });
  301. // Animater
  302. animater.hooks.on(animater.hooks.eventTypes.time, function (time) {
  303. _this.transitionDuration(time);
  304. });
  305. animater.hooks.on(animater.hooks.eventTypes.timeFunction, function (easing) {
  306. _this.timeFunction(easing);
  307. });
  308. // bs.stop() to make wheel stop at a correct position when pending
  309. animater.hooks.on(animater.hooks.eventTypes.callStop, function () {
  310. var index = _this.findNearestValidWheel(_this.scroll.y).index;
  311. _this.isAdjustingPosition = true;
  312. _this.wheelTo(index, 0);
  313. });
  314. // Translater
  315. animater.translater.hooks.on(animater.translater.hooks.eventTypes.translate, function (endPoint) {
  316. _this.rotateX(endPoint.y);
  317. });
  318. };
  319. Wheel.prototype.refreshBoundary = function () {
  320. var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY, content = _a.content;
  321. scrollBehaviorX.refresh(content);
  322. scrollBehaviorY.refresh(content);
  323. };
  324. Wheel.prototype.setSelectedIndex = function (index, contentChanged) {
  325. if (contentChanged === void 0) { contentChanged = false; }
  326. var prevSelectedIndex = this.selectedIndex;
  327. this.selectedIndex = index;
  328. // if content DOM changed, should not trigger event
  329. if (prevSelectedIndex !== index && !contentChanged) {
  330. this.scroll.trigger(WHEEL_INDEX_CHANGED_EVENT_NAME, index);
  331. }
  332. };
  333. Wheel.prototype.getSelectedIndex = function () {
  334. return this.selectedIndex;
  335. };
  336. Wheel.prototype.wheelTo = function (index, time, ease) {
  337. if (index === void 0) { index = 0; }
  338. if (time === void 0) { time = 0; }
  339. var y = -index * this.itemHeight;
  340. this.scroll.scrollTo(0, y, time, ease);
  341. };
  342. Wheel.prototype.restorePosition = function () {
  343. // bs is scrolling
  344. var isPending = this.scroll.pending;
  345. if (isPending) {
  346. var selectedIndex = this.getSelectedIndex();
  347. this.scroll.scroller.animater.clearTimer();
  348. this.wheelTo(selectedIndex, 0);
  349. }
  350. };
  351. Wheel.prototype.transitionDuration = function (time) {
  352. for (var i = 0; i < this.items.length; i++) {
  353. this.items[i].style[style.transitionDuration] =
  354. time + 'ms';
  355. }
  356. };
  357. Wheel.prototype.timeFunction = function (easing) {
  358. for (var i = 0; i < this.items.length; i++) {
  359. this.items[i].style[style.transitionTimingFunction] = easing;
  360. }
  361. };
  362. Wheel.prototype.rotateX = function (y) {
  363. var _a = this.options.rotate, rotate = _a === void 0 ? 25 : _a;
  364. for (var i = 0; i < this.items.length; i++) {
  365. var deg = rotate * (y / this.itemHeight + i);
  366. // Too small value is invalid in some phones, issue 1026
  367. var SafeDeg = deg.toFixed(3);
  368. this.items[i].style[style.transform] = "rotateX(" + SafeDeg + "deg)";
  369. }
  370. };
  371. Wheel.prototype.findNearestValidWheel = function (y) {
  372. y = y > 0 ? 0 : y < this.scroll.maxScrollY ? this.scroll.maxScrollY : y;
  373. var currentIndex = Math.abs(Math.round(-y / this.itemHeight));
  374. var cacheIndex = currentIndex;
  375. var items = this.items;
  376. var wheelDisabledItemClassName = this.options
  377. .wheelDisabledItemClass;
  378. // implement web native select element
  379. // first, check whether there is a enable item whose index is smaller than currentIndex
  380. // then, check whether there is a enable item whose index is bigger than currentIndex
  381. // otherwise, there are all disabled items, just keep currentIndex unchange
  382. while (currentIndex >= 0) {
  383. if (!hasClass(items[currentIndex], wheelDisabledItemClassName)) {
  384. break;
  385. }
  386. currentIndex--;
  387. }
  388. if (currentIndex < 0) {
  389. currentIndex = cacheIndex;
  390. while (currentIndex <= items.length - 1) {
  391. if (!hasClass(items[currentIndex], wheelDisabledItemClassName)) {
  392. break;
  393. }
  394. currentIndex++;
  395. }
  396. }
  397. // keep it unchange when all the items are disabled
  398. if (currentIndex === items.length) {
  399. currentIndex = cacheIndex;
  400. }
  401. // when all the items are disabled, selectedIndex should always be -1
  402. return {
  403. index: this.wheelItemsAllDisabled ? -1 : currentIndex,
  404. y: -currentIndex * this.itemHeight
  405. };
  406. };
  407. Wheel.prototype.checkWheelAllDisabled = function () {
  408. var wheelDisabledItemClassName = this.options.wheelDisabledItemClass;
  409. var items = this.items;
  410. this.wheelItemsAllDisabled = true;
  411. for (var i = 0; i < items.length; i++) {
  412. if (!hasClass(items[i], wheelDisabledItemClassName)) {
  413. this.wheelItemsAllDisabled = false;
  414. break;
  415. }
  416. }
  417. };
  418. Wheel.pluginName = 'wheel';
  419. return Wheel;
  420. }());
  421. return Wheel;
  422. })));