swipe-back.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*!
  2. * (C) Ionic http://ionicframework.com - MIT License
  3. */
  4. import { k as clamp } from './helpers.js';
  5. import { i as isRTL } from './dir.js';
  6. import { createGesture } from './index3.js';
  7. const createSwipeBackGesture = (el, canStartHandler, onStartHandler, onMoveHandler, onEndHandler) => {
  8. const win = el.ownerDocument.defaultView;
  9. let rtl = isRTL(el);
  10. /**
  11. * Determine if a gesture is near the edge
  12. * of the screen. If true, then the swipe
  13. * to go back gesture should proceed.
  14. */
  15. const isAtEdge = (detail) => {
  16. const threshold = 50;
  17. const { startX } = detail;
  18. if (rtl) {
  19. return startX >= win.innerWidth - threshold;
  20. }
  21. return startX <= threshold;
  22. };
  23. const getDeltaX = (detail) => {
  24. return rtl ? -detail.deltaX : detail.deltaX;
  25. };
  26. const getVelocityX = (detail) => {
  27. return rtl ? -detail.velocityX : detail.velocityX;
  28. };
  29. const canStart = (detail) => {
  30. /**
  31. * The user's locale can change mid-session,
  32. * so we need to check text direction at
  33. * the beginning of every gesture.
  34. */
  35. rtl = isRTL(el);
  36. return isAtEdge(detail) && canStartHandler();
  37. };
  38. const onMove = (detail) => {
  39. // set the transition animation's progress
  40. const delta = getDeltaX(detail);
  41. const stepValue = delta / win.innerWidth;
  42. onMoveHandler(stepValue);
  43. };
  44. const onEnd = (detail) => {
  45. // the swipe back gesture has ended
  46. const delta = getDeltaX(detail);
  47. const width = win.innerWidth;
  48. const stepValue = delta / width;
  49. const velocity = getVelocityX(detail);
  50. const z = width / 2.0;
  51. const shouldComplete = velocity >= 0 && (velocity > 0.2 || delta > z);
  52. const missing = shouldComplete ? 1 - stepValue : stepValue;
  53. const missingDistance = missing * width;
  54. let realDur = 0;
  55. if (missingDistance > 5) {
  56. const dur = missingDistance / Math.abs(velocity);
  57. realDur = Math.min(dur, 540);
  58. }
  59. onEndHandler(shouldComplete, stepValue <= 0 ? 0.01 : clamp(0, stepValue, 0.9999), realDur);
  60. };
  61. return createGesture({
  62. el,
  63. gestureName: 'goback-swipe',
  64. /**
  65. * Swipe to go back should have priority over other horizontal swipe
  66. * gestures. These gestures have a priority of 100 which is why 101 was chosen here.
  67. */
  68. gesturePriority: 101,
  69. threshold: 10,
  70. canStart,
  71. onStart: onStartHandler,
  72. onMove,
  73. onEnd,
  74. });
  75. };
  76. export { createSwipeBackGesture };