|
| 1 | +export function setupPullToRefresh(element, onRefresh) { |
| 2 | + let startY = 0; |
| 3 | + let currentY = 0; |
| 4 | + let pulling = false; |
| 5 | + let refreshing = false; |
| 6 | + const threshold = 130; |
| 7 | + const maxPull = 170; |
| 8 | + |
| 9 | + const container = document.createElement('div'); |
| 10 | + container.className = 'ptr-indicator'; |
| 11 | + container.innerHTML = ` |
| 12 | + <div class="ptr-indicator-wrapper"> |
| 13 | + <md-circular-progress value="0" class="ptr-progress"></md-circular-progress> |
| 14 | + </div> |
| 15 | + `; |
| 16 | + |
| 17 | + element.parentElement.insertBefore(container, element); |
| 18 | + |
| 19 | + const progress = container.querySelector('.ptr-progress'); |
| 20 | + |
| 21 | + element.addEventListener('touchstart', (e) => { |
| 22 | + if (element.scrollTop <= 0 && !refreshing) { |
| 23 | + startY = e.touches[0].pageY; |
| 24 | + pulling = true; |
| 25 | + container.style.transition = 'none'; |
| 26 | + } |
| 27 | + }, { passive: true }); |
| 28 | + |
| 29 | + element.addEventListener('touchmove', (e) => { |
| 30 | + if (!pulling) return; |
| 31 | + currentY = e.touches[0].pageY; |
| 32 | + const diff = currentY - startY; |
| 33 | + |
| 34 | + if (diff > 0) { |
| 35 | + if (e.cancelable) e.preventDefault(); |
| 36 | + |
| 37 | + const pullDistance = Math.min(diff * 0.5, maxPull); |
| 38 | + const scale = Math.min(diff / 50, 1); |
| 39 | + container.style.transform = `translateY(${pullDistance}px) scale(${scale})`; |
| 40 | + container.style.opacity = Math.min(diff / 50, 1); |
| 41 | + const progressValue = Math.max(0, Math.min((diff - 50) / (threshold - 50), 1)); |
| 42 | + progress.value = progressValue; |
| 43 | + } else { |
| 44 | + pulling = false; |
| 45 | + container.style.opacity = '0'; |
| 46 | + container.style.transform = `translateY(0) scale(0)`; |
| 47 | + } |
| 48 | + }, { passive: false }); |
| 49 | + |
| 50 | + element.addEventListener('touchend', async () => { |
| 51 | + if (!pulling) return; |
| 52 | + pulling = false; |
| 53 | + const diff = currentY - startY; |
| 54 | + |
| 55 | + if (diff > threshold) { |
| 56 | + refreshing = true; |
| 57 | + progress.indeterminate = true; |
| 58 | + container.style.transition = 'all 0.3s ease'; |
| 59 | + container.style.transform = `translateY(${threshold * 0.5}px) scale(1)`; |
| 60 | + container.style.opacity = '1'; |
| 61 | + |
| 62 | + try { |
| 63 | + await onRefresh(); |
| 64 | + } finally { |
| 65 | + refreshing = false; |
| 66 | + progress.indeterminate = false; |
| 67 | + progress.value = 0; |
| 68 | + container.style.transform = `translateY(0) scale(0)`; |
| 69 | + container.style.opacity = '0'; |
| 70 | + } |
| 71 | + } else { |
| 72 | + container.style.transition = 'all 0.3s ease'; |
| 73 | + container.style.transform = `translateY(0) scale(0)`; |
| 74 | + container.style.opacity = '0'; |
| 75 | + } |
| 76 | + }); |
| 77 | +} |
0 commit comments