Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

swiper.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. import _Promise from 'babel-runtime/core-js/promise';
  2. import _Map from 'babel-runtime/core-js/map';
  3. import _setImmediate from 'babel-runtime/core-js/set-immediate';
  4. import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
  5. import _createClass from 'babel-runtime/helpers/createClass';
  6. import util from '../util';
  7. import platform from '../platform';
  8. import animit from '../animit';
  9. import GestureDetector from '../gesture-detector';
  10. var directionMap = {
  11. vertical: {
  12. axis: 'Y',
  13. size: 'Height',
  14. dir: ['up', 'down'],
  15. t3d: ['0px, ', 'px, 0px']
  16. },
  17. horizontal: {
  18. axis: 'X',
  19. size: 'Width',
  20. dir: ['left', 'right'],
  21. t3d: ['', 'px, 0px, 0px']
  22. }
  23. };
  24. var Swiper = function () {
  25. function Swiper(params) {
  26. var _this = this;
  27. _classCallCheck(this, Swiper);
  28. // Parameters
  29. var FALSE = function FALSE() {
  30. return false;
  31. };
  32. 'getInitialIndex getBubbleWidth isVertical isOverScrollable isCentered\n isAutoScrollable refreshHook preChangeHook postChangeHook overScrollHook'.split(/\s+/).forEach(function (key) {
  33. return _this[key] = params[key] || FALSE;
  34. });
  35. this.getElement = params.getElement; // Required
  36. this.scrollHook = params.scrollHook; // Optional
  37. this.itemSize = params.itemSize || '100%';
  38. this.getAutoScrollRatio = function () {
  39. var ratio = params.getAutoScrollRatio && params.getAutoScrollRatio.apply(params, arguments);
  40. ratio = typeof ratio === 'number' && ratio === ratio ? ratio : .5;
  41. if (ratio < 0.0 || ratio > 1.0) {
  42. util.throw('Invalid auto-scroll-ratio ' + ratio + '. Must be between 0 and 1');
  43. }
  44. return ratio;
  45. };
  46. // Prevent clicks only on desktop
  47. this.shouldBlock = util.globals.actualMobileOS === 'other';
  48. // Bind handlers
  49. this.onDragStart = this.onDragStart.bind(this);
  50. this.onDrag = this.onDrag.bind(this);
  51. this.onDragEnd = this.onDragEnd.bind(this);
  52. this.onResize = this.onResize.bind(this);
  53. this._shouldFixScroll = util.globals.actualMobileOS === 'ios';
  54. }
  55. _createClass(Swiper, [{
  56. key: 'init',
  57. value: function init() {
  58. var _this2 = this;
  59. var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  60. swipeable = _ref.swipeable,
  61. autoRefresh = _ref.autoRefresh;
  62. this.initialized = true;
  63. this.target = this.getElement().children[0];
  64. this.blocker = this.getElement().children[1];
  65. if (!this.target || !this.blocker) {
  66. util.throw('Expected "target" and "blocker" elements to exist before initializing Swiper');
  67. }
  68. if (!this.shouldBlock) {
  69. this.blocker.style.display = 'none';
  70. }
  71. // Add classes
  72. this.getElement().classList.add('ons-swiper');
  73. this.target.classList.add('ons-swiper-target');
  74. this.blocker.classList.add('ons-swiper-blocker');
  75. // Setup listeners
  76. this._gestureDetector = new GestureDetector(this.getElement(), { dragMinDistance: 1, dragLockToAxis: true, passive: !this._shouldFixScroll });
  77. this._mutationObserver = new MutationObserver(function () {
  78. return _this2.refresh();
  79. });
  80. this.updateSwipeable(swipeable);
  81. this.updateAutoRefresh(autoRefresh);
  82. // Setup initial layout
  83. this._scroll = this._offset = this._lastActiveIndex = 0;
  84. this._updateLayout();
  85. this._setupInitialIndex();
  86. _setImmediate(function () {
  87. return _this2.initialized && _this2._setupInitialIndex();
  88. });
  89. // Fix rendering glitch on Android 4.1
  90. // Fix for iframes where the width is inconsistent at the beginning
  91. if (window !== window.parent || this.offsetHeight === 0) {
  92. window.requestAnimationFrame(function () {
  93. return _this2.initialized && _this2.onResize();
  94. });
  95. }
  96. }
  97. }, {
  98. key: 'dispose',
  99. value: function dispose() {
  100. this.initialized = false;
  101. this.updateSwipeable(false);
  102. this.updateAutoRefresh(false);
  103. this._gestureDetector && this._gestureDetector.dispose();
  104. this.target = this.blocker = this._gestureDetector = this._mutationObserver = null;
  105. this.setupResize(false);
  106. }
  107. }, {
  108. key: 'onResize',
  109. value: function onResize() {
  110. var i = this._scroll / this.targetSize;
  111. this._reset();
  112. this.setActiveIndex(i);
  113. this.refresh();
  114. }
  115. }, {
  116. key: '_calculateItemSize',
  117. value: function _calculateItemSize() {
  118. var matches = this.itemSize.match(/^(\d+)(px|%)/);
  119. if (!matches) {
  120. util.throw('Invalid state: swiper\'s size unit must be \'%\' or \'px\'');
  121. }
  122. var value = parseInt(matches[1], 10);
  123. return matches[2] === '%' ? Math.round(value / 100 * this.targetSize) : value;
  124. }
  125. }, {
  126. key: '_setupInitialIndex',
  127. value: function _setupInitialIndex() {
  128. this._reset();
  129. this._lastActiveIndex = Math.max(Math.min(Number(this.getInitialIndex()), this.itemCount), 0);
  130. this._scroll = this._offset + this.itemNumSize * this._lastActiveIndex;
  131. this._scrollTo(this._scroll);
  132. }
  133. }, {
  134. key: '_setSwiping',
  135. value: function _setSwiping(toggle) {
  136. this.target.classList.toggle('swiping', toggle); // Hides everything except shown pages
  137. }
  138. }, {
  139. key: 'setActiveIndex',
  140. value: function setActiveIndex(index) {
  141. var _this3 = this;
  142. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  143. this._setSwiping(true);
  144. index = Math.max(0, Math.min(index, this.itemCount - 1));
  145. var scroll = Math.max(0, Math.min(this.maxScroll, this._offset + this.itemNumSize * index));
  146. if (platform.isUIWebView()) {
  147. /* Dirty fix for #2231(https://github.com/OnsenUI/OnsenUI/issues/2231). begin */
  148. var concat = function concat(arrayOfArray) {
  149. return Array.prototype.concat.apply([], arrayOfArray);
  150. };
  151. var contents = concat(util.arrayFrom(this.target.children).map(function (page) {
  152. return util.arrayFrom(page.children).filter(function (child) {
  153. return child.classList.contains('page__content');
  154. });
  155. }));
  156. var map = new _Map();
  157. return new _Promise(function (resolve) {
  158. contents.forEach(function (content) {
  159. map.set(content, content.getAttribute('class'));
  160. content.classList.add('page__content--suppress-layer-creation');
  161. });
  162. requestAnimationFrame(resolve);
  163. }).then(function () {
  164. return _this3._changeTo(scroll, options);
  165. }).then(function () {
  166. return new _Promise(function (resolve) {
  167. contents.forEach(function (content) {
  168. content.setAttribute('class', map.get(content));
  169. });
  170. requestAnimationFrame(resolve);
  171. });
  172. });
  173. /* end */
  174. } else {
  175. return this._changeTo(scroll, options);
  176. }
  177. }
  178. }, {
  179. key: 'getActiveIndex',
  180. value: function getActiveIndex() {
  181. var scroll = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._scroll;
  182. scroll -= this._offset;
  183. var count = this.itemCount,
  184. size = this.itemNumSize;
  185. if (this.itemNumSize === 0 || !util.isInteger(scroll)) {
  186. return this._lastActiveIndex;
  187. }
  188. if (scroll <= 0) {
  189. return 0;
  190. }
  191. for (var i = 0; i < count; i++) {
  192. if (size * i <= scroll && size * (i + 1) > scroll) {
  193. return i;
  194. }
  195. }
  196. return count - 1;
  197. }
  198. }, {
  199. key: 'setupResize',
  200. value: function setupResize(add) {
  201. window[(add ? 'add' : 'remove') + 'EventListener']('resize', this.onResize, true);
  202. }
  203. }, {
  204. key: 'show',
  205. value: function show() {
  206. var _this4 = this;
  207. this.setupResize(true);
  208. this.onResize();
  209. setTimeout(function () {
  210. return _this4.target && _this4.target.classList.add('active');
  211. }, 1000 / 60); // Hide elements after animations
  212. }
  213. }, {
  214. key: 'hide',
  215. value: function hide() {
  216. this.setupResize(false);
  217. this.target.classList.remove('active'); // Show elements before animations
  218. }
  219. }, {
  220. key: 'updateSwipeable',
  221. value: function updateSwipeable(shouldUpdate) {
  222. if (this._gestureDetector) {
  223. var action = shouldUpdate ? 'on' : 'off';
  224. this._gestureDetector[action]('drag', this.onDrag);
  225. this._gestureDetector[action]('dragstart', this.onDragStart);
  226. this._gestureDetector[action]('dragend', this.onDragEnd);
  227. }
  228. }
  229. }, {
  230. key: 'updateAutoRefresh',
  231. value: function updateAutoRefresh(shouldWatch) {
  232. if (this._mutationObserver) {
  233. shouldWatch ? this._mutationObserver.observe(this.target, { childList: true }) : this._mutationObserver.disconnect();
  234. }
  235. }
  236. }, {
  237. key: 'updateItemSize',
  238. value: function updateItemSize(newSize) {
  239. this.itemSize = newSize || '100%';
  240. this.refresh();
  241. }
  242. }, {
  243. key: 'toggleBlocker',
  244. value: function toggleBlocker(block) {
  245. this.blocker.style.pointerEvents = block ? 'auto' : 'none';
  246. }
  247. }, {
  248. key: '_canConsumeGesture',
  249. value: function _canConsumeGesture(gesture) {
  250. var d = gesture.direction;
  251. var isFirst = this._scroll === 0 && !this.isOverScrollable();
  252. var isLast = this._scroll === this.maxScroll && !this.isOverScrollable();
  253. return this.isVertical() ? d === 'down' && !isFirst || d === 'up' && !isLast : d === 'right' && !isFirst || d === 'left' && !isLast;
  254. }
  255. }, {
  256. key: 'onDragStart',
  257. value: function onDragStart(event) {
  258. var _this5 = this;
  259. this._ignoreDrag = event.consumed || !util.isValidGesture(event);
  260. if (!this._ignoreDrag) {
  261. var consume = event.consume;
  262. event.consume = function () {
  263. consume && consume();_this5._ignoreDrag = true;
  264. };
  265. if (this._canConsumeGesture(event.gesture)) {
  266. var startX = event.gesture.center && event.gesture.center.clientX || 0,
  267. distFromEdge = this.getBubbleWidth() || 0,
  268. start = function start() {
  269. consume && consume();
  270. event.consumed = true;
  271. _this5._started = true; // Avoid starting drag from outside
  272. _this5.shouldBlock && _this5.toggleBlocker(true);
  273. _this5._setSwiping(true);
  274. util.iosPreventScroll(_this5._gestureDetector);
  275. };
  276. // Let parent elements consume the gesture or consume it right away
  277. startX < distFromEdge || startX > this.targetSize - distFromEdge ? _setImmediate(function () {
  278. return !_this5._ignoreDrag && start();
  279. }) : start();
  280. }
  281. }
  282. }
  283. }, {
  284. key: 'onDrag',
  285. value: function onDrag(event) {
  286. if (!event.gesture || this._ignoreDrag || !this._started) {
  287. return;
  288. }
  289. this._continued = true; // Fix for random 'dragend' without 'drag'
  290. event.stopPropagation();
  291. this._scrollTo(this._scroll - this._getDelta(event), { throttle: true });
  292. }
  293. }, {
  294. key: 'onDragEnd',
  295. value: function onDragEnd(event) {
  296. this._started = false;
  297. if (!event.gesture || this._ignoreDrag || !this._continued) {
  298. this._ignoreDrag = true; // onDragEnd might fire before onDragStart's setImmediate
  299. return;
  300. }
  301. this._continued = false;
  302. event.stopPropagation();
  303. var scroll = this._scroll - this._getDelta(event);
  304. var normalizedScroll = this._normalizeScroll(scroll);
  305. scroll === normalizedScroll ? this._startMomentumScroll(scroll, event) : this._killOverScroll(normalizedScroll);
  306. this.shouldBlock && this.toggleBlocker(false);
  307. }
  308. }, {
  309. key: '_startMomentumScroll',
  310. value: function _startMomentumScroll(scroll, event) {
  311. var velocity = this._getVelocity(event),
  312. matchesDirection = event.gesture.interimDirection === this.dM.dir[this._getDelta(event) < 0 ? 0 : 1];
  313. var nextScroll = this._getAutoScroll(scroll, velocity, matchesDirection);
  314. var duration = Math.abs(nextScroll - scroll) / (velocity + 0.01) / 1000;
  315. duration = Math.min(.25, Math.max(.1, duration));
  316. this._changeTo(nextScroll, { swipe: true, animationOptions: { duration: duration, timing: 'cubic-bezier(.4, .7, .5, 1)' } });
  317. }
  318. }, {
  319. key: '_killOverScroll',
  320. value: function _killOverScroll(scroll) {
  321. var _this6 = this;
  322. this._scroll = scroll;
  323. var direction = this.dM.dir[Number(scroll > 0)];
  324. var killOverScroll = function killOverScroll() {
  325. return _this6._changeTo(scroll, { animationOptions: { duration: .4, timing: 'cubic-bezier(.1, .4, .1, 1)' } });
  326. };
  327. this.overScrollHook({ direction: direction, killOverScroll: killOverScroll }) || killOverScroll();
  328. }
  329. }, {
  330. key: '_changeTo',
  331. value: function _changeTo(scroll) {
  332. var _this7 = this;
  333. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  334. var e = { activeIndex: this.getActiveIndex(scroll), lastActiveIndex: this._lastActiveIndex, swipe: options.swipe || false };
  335. var change = e.activeIndex !== e.lastActiveIndex;
  336. var canceled = change ? this.preChangeHook(e) : false;
  337. this._scroll = canceled ? this._offset + e.lastActiveIndex * this.itemNumSize : scroll;
  338. this._lastActiveIndex = canceled ? e.lastActiveIndex : e.activeIndex;
  339. return this._scrollTo(this._scroll, options).then(function () {
  340. if (scroll === _this7._scroll && !canceled) {
  341. _this7._setSwiping(false);
  342. change && _this7.postChangeHook(e);
  343. } else if (options.reject) {
  344. _this7._setSwiping(false);
  345. return _Promise.reject('Canceled');
  346. }
  347. });
  348. }
  349. }, {
  350. key: '_scrollTo',
  351. value: function _scrollTo(scroll) {
  352. var _this8 = this;
  353. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  354. if (options.throttle) {
  355. var ratio = 0.35;
  356. if (scroll < 0) {
  357. scroll = this.isOverScrollable() ? Math.round(scroll * ratio) : 0;
  358. } else {
  359. var maxScroll = this.maxScroll;
  360. if (maxScroll < scroll) {
  361. scroll = this.isOverScrollable() ? maxScroll + Math.round((scroll - maxScroll) * ratio) : maxScroll;
  362. }
  363. }
  364. }
  365. var opt = options.animation === 'none' ? {} : options.animationOptions;
  366. this.scrollHook && this.itemNumSize > 0 && this.scrollHook((scroll / this.itemNumSize).toFixed(2), options.animationOptions || {});
  367. return new _Promise(function (resolve) {
  368. return animit(_this8.target).queue({ transform: _this8._getTransform(scroll) }, opt).play(resolve);
  369. });
  370. }
  371. }, {
  372. key: '_getAutoScroll',
  373. value: function _getAutoScroll(scroll, velocity, matchesDirection) {
  374. var max = this.maxScroll,
  375. offset = this._offset,
  376. size = this.itemNumSize;
  377. if (!this.isAutoScrollable()) {
  378. return Math.max(0, Math.min(max, scroll));
  379. }
  380. var arr = [];
  381. for (var s = offset; s < max; s += size) {
  382. arr.push(s);
  383. }
  384. arr.push(max);
  385. arr = arr.sort(function (left, right) {
  386. return Math.abs(left - scroll) - Math.abs(right - scroll);
  387. }).filter(function (item, pos) {
  388. return !pos || item !== arr[pos - 1];
  389. });
  390. var result = arr[0];
  391. var lastScroll = this._lastActiveIndex * size + offset;
  392. var scrollRatio = Math.abs(scroll - lastScroll) / size;
  393. if (scrollRatio <= this.getAutoScrollRatio(matchesDirection, velocity, size)) {
  394. result = lastScroll;
  395. } else {
  396. if (scrollRatio < 1.0 && arr[0] === lastScroll && arr.length > 1) {
  397. result = arr[1];
  398. }
  399. }
  400. return Math.max(0, Math.min(max, result));
  401. }
  402. }, {
  403. key: '_reset',
  404. value: function _reset() {
  405. this._targetSize = this._itemNumSize = undefined;
  406. }
  407. }, {
  408. key: '_normalizeScroll',
  409. value: function _normalizeScroll(scroll) {
  410. return Math.max(Math.min(scroll, this.maxScroll), 0);
  411. }
  412. }, {
  413. key: 'refresh',
  414. value: function refresh() {
  415. this._reset();
  416. this._updateLayout();
  417. if (util.isInteger(this._scroll)) {
  418. var scroll = this._normalizeScroll(this._scroll);
  419. scroll !== this._scroll ? this._killOverScroll(scroll) : this._changeTo(scroll);
  420. } else {
  421. this._setupInitialIndex();
  422. }
  423. this.refreshHook();
  424. }
  425. }, {
  426. key: '_getDelta',
  427. value: function _getDelta(event) {
  428. return event.gesture['delta' + this.dM.axis];
  429. }
  430. }, {
  431. key: '_getVelocity',
  432. value: function _getVelocity(event) {
  433. return event.gesture['velocity' + this.dM.axis];
  434. }
  435. }, {
  436. key: '_getTransform',
  437. value: function _getTransform(scroll) {
  438. return 'translate3d(' + this.dM.t3d[0] + -scroll + this.dM.t3d[1] + ')';
  439. }
  440. }, {
  441. key: '_updateLayout',
  442. value: function _updateLayout() {
  443. this.dM = directionMap[this.isVertical() ? 'vertical' : 'horizontal'];
  444. this.target.classList.toggle('ons-swiper-target--vertical', this.isVertical());
  445. for (var c = this.target.children[0]; c; c = c.nextElementSibling) {
  446. c.style[this.dM.size.toLowerCase()] = this.itemSize;
  447. }
  448. if (this.isCentered()) {
  449. this._offset = (this.targetSize - this.itemNumSize) / -2 || 0;
  450. }
  451. }
  452. }, {
  453. key: 'itemCount',
  454. get: function get() {
  455. return this.target.children.length;
  456. }
  457. }, {
  458. key: 'itemNumSize',
  459. get: function get() {
  460. if (typeof this._itemNumSize !== 'number' || this._itemNumSize !== this._itemNumSize) {
  461. this._itemNumSize = this._calculateItemSize();
  462. }
  463. return this._itemNumSize;
  464. }
  465. }, {
  466. key: 'maxScroll',
  467. get: function get() {
  468. var max = this.itemCount * this.itemNumSize - this.targetSize;
  469. return Math.ceil(max < 0 ? 0 : max); // Need to return an integer value.
  470. }
  471. }, {
  472. key: 'targetSize',
  473. get: function get() {
  474. if (!this._targetSize) {
  475. this._targetSize = this.target['offset' + this.dM.size];
  476. }
  477. return this._targetSize;
  478. }
  479. }]);
  480. return Swiper;
  481. }();
  482. export default Swiper;