Integrate swipe and d-pad to transit entry_view #2

Merged
joshlaymon merged 10 commits from develop into main 2025-09-07 17:58:35 +00:00
Showing only changes of commit cb895c50c4 - Show all commits

View File

@ -1,117 +1,170 @@
/* Swipe/Keyboard navigation for Entry View /* swipe-nav.js
- Respects localStorage 'swipeNavEnabled' (default ON) Mobile/desktop swipe & keyboard navigation for entry view.
- Touch swipe on mobile, ArrowLeft/ArrowRight on keyboards - One navigation per gesture
- Edge protection and input-safe - Edge protection: horizontal intent + distance + max duration
- Cooldown prevents multi-advance on long swipes
- Keyboard: Left/Right arrows (when not typing)
*/ */
(function () { (function () {
// Feature flag (client-side). Default ON. // Bail if not on an entry page with forms
let swipeEnabled = true; const prevForm = document.getElementById("navPrevForm");
try { swipeEnabled = (localStorage.getItem('swipeNavEnabled') !== 'false'); } catch (e) {} const nextForm = document.getElementById("navNextForm");
if (!prevForm && !nextForm) return;
// Only attach if enabled // Prefer a dedicated swipe zone if present; fall back to body
if (!swipeEnabled) return; const zone = document.getElementById("swipeZone") || document.body;
// Forms to submit for previous/next (your existing IDs) // State
const prevForm = document.getElementById('navPrevForm'); let tracking = false;
const nextForm = document.getElementById('navNextForm'); let startX = 0, startY = 0, startT = 0, pointerId = null;
let didNavigate = false;
let cooldown = false;
// Create toast + hints lazily to keep HTML clean // Tunables
const toast = document.createElement('div'); const MIN_X = 48; // px horizontal distance
toast.id = 'toast-swipe-error'; const MAX_ANGLE = 30; // deg off pure horizontal
toast.style.cssText = [ const MAX_MS = 650; // must complete within this time
'position:fixed', 'left:50%', 'bottom:16px', 'transform:translateX(-50%)', const COOLDOWN_MS = 450; // after we navigate, ignore further moves briefly
'padding:10px 14px', 'border-radius:10px', 'background:#111827', 'color:#fff',
'box-shadow:0 6px 20px rgba(0,0,0,.25)', 'opacity:0', 'pointer-events:none',
'transition:opacity .25s', 'z-index:1200', 'font-size:14px'
].join(';');
toast.textContent = "Can't navigate here.";
document.body.appendChild(toast);
function showToast() { // Helpers
toast.style.opacity = '1'; function degrees(dx, dy) {
setTimeout(() => { toast.style.opacity = '0'; }, 1200); const a = Math.atan2(Math.abs(dy), Math.abs(dx)) * (180 / Math.PI);
return a; // 0 = pure horizontal
}
function now() { return performance.now ? performance.now() : Date.now(); }
function reset() {
tracking = false;
pointerId = null;
startX = startY = 0;
startT = 0;
didNavigate = false;
} }
// Only show swipe hints on touch devices, once per session function submit(form) {
const isTouch = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0); if (!form || cooldown) return;
let hintL, hintR; cooldown = true;
if (isTouch) { form.submit();
try { // If navigation is prevented (e.g., disabled button), release cooldown after a tick
if (!sessionStorage.getItem('swipeHintShown')) { setTimeout(() => { cooldown = false; }, COOLDOWN_MS);
sessionStorage.setItem('swipeHintShown', '1');
const base = 'position:fixed;width:34px;height:34px;display:flex;align-items:center;justify-content:center;' +
'background:rgba(0,0,0,.35);color:#fff;border-radius:999px;box-shadow:0 6px 20px rgba(0,0,0,.25);' +
'z-index:1100;opacity:0;transform:scale(.9);transition:opacity .25s,transform .25s;top:45%';
hintL = document.createElement('div');
hintL.style.cssText = base + ';left:10px;';
hintL.textContent = '';
document.body.appendChild(hintL);
hintR = document.createElement('div');
hintR.style.cssText = base + ';right:10px;';
hintR.textContent = '';
document.body.appendChild(hintR);
setTimeout(() => { hintL.style.opacity = '1'; hintR.style.opacity = '1'; hintL.style.transform = 'scale(1)'; hintR.style.transform = 'scale(1)'; }, 300);
setTimeout(() => { hintL.style.opacity = '0'; hintR.style.opacity = '0'; }, 2200);
}
} catch (e) {}
} }
function navigate(dir) { // Pointer events if supported (best across devices). Fallback to touch.
try { const usePointer = "PointerEvent" in window;
if (dir < 0 && prevForm) { prevForm.submit(); return true; }
if (dir > 0 && nextForm) { nextForm.submit(); return true; } function onDown(e) {
} catch (e) {} if (cooldown) return;
showToast(); // Ignore right click / secondary
return false; if (usePointer && e.pointerType === "mouse" && e.button !== 0) return;
tracking = true;
didNavigate = false;
const pt = usePointer ? e : (e.touches && e.touches[0]);
if (!pt) return;
pointerId = usePointer ? e.pointerId : pt.identifier;
startX = pt.clientX;
startY = pt.clientY;
startT = now();
// Once we suspect horizontal motion, we'll call preventDefault in move
} }
// Keyboard shortcuts function onMove(e) {
document.addEventListener('keydown', function (e) { if (!tracking || didNavigate || cooldown) return;
if (!swipeEnabled) return;
const tag = (e.target && e.target.tagName) || '';
if (/INPUT|TEXTAREA|SELECT/.test(tag)) return;
if (e.key === 'ArrowLeft') { e.preventDefault(); navigate(-1); }
if (e.key === 'ArrowRight') { e.preventDefault(); navigate(1); }
});
// Touch swipe (edge-protected, vertical tolerance) const pt = usePointer ? e : (e.touches && e.touches[0]);
if (isTouch) { if (!pt) return;
let startX = 0, startY = 0, tracking = false; if (usePointer && e.pointerId !== pointerId) return;
const EDGE = 20, THRESH = 40;
const area = document.querySelector('main.page') || document.body;
function isInteractive(el) { const dx = pt.clientX - startX;
return !!(el.closest && el.closest('input, textarea, select, button, a, [contenteditable], .no-swipe')); const dy = pt.clientY - startY;
// If user is panning mostly horizontally, stop the browser from doing a horizontal scroll/jiggle
if (Math.abs(dx) > 8 && Math.abs(dx) > Math.abs(dy)) {
// In touch events you must preventDefault during move to suppress scroll
if (e.cancelable) e.preventDefault();
}
}
function onUp(e) {
if (!tracking || didNavigate || cooldown) { reset(); return; }
let pt;
if (usePointer) {
if (e.pointerId !== pointerId) return reset();
pt = e;
} else {
// On touchend, touches[] is empty; use changedTouches[]
pt = (e.changedTouches && e.changedTouches[0]) || null;
if (!pt) return reset();
} }
area.addEventListener('touchstart', function (e) { const dx = pt.clientX - startX;
const t = e.touches[0]; const dy = pt.clientY - startY;
if (!t) return; const dt = now() - startT;
if (isInteractive(e.target)) return;
startX = t.clientX; startY = t.clientY; tracking = true;
}, { passive: true });
area.addEventListener('touchmove', function (e) { const ang = degrees(dx, dy);
if (!tracking) return; const horizontalEnough = ang <= MAX_ANGLE;
const t = e.touches[0];
if (!t) return;
const dx = t.clientX - startX;
const dy = t.clientY - startY;
if (Math.abs(dx) > THRESH && Math.abs(dy) < 28) { // Must be a deliberate, reasonably quick horizontal swipe
// Edge-protection: avoid accidental from extreme edges if (Math.abs(dx) >= MIN_X && horizontalEnough && dt <= MAX_MS) {
if (startX < EDGE && dx > 0) { tracking = false; return; } didNavigate = true;
if (startX > (window.innerWidth - EDGE) && dx < 0) { tracking = false; return; } if (dx < 0) {
e.preventDefault(); // left swipe -> NEXT
navigate(dx > 0 ? -1 : 1); const btn = nextForm && nextForm.querySelector("button[disabled]");
tracking = false; if (!btn) submit(nextForm);
} else {
// right swipe -> PREV
const btn = prevForm && prevForm.querySelector("button[disabled]");
if (!btn) submit(prevForm);
} }
}, { passive: false }); if (e.cancelable) e.preventDefault();
}
area.addEventListener('touchend', function () { tracking = false; }, { passive: true }); reset();
} }
function onCancel() { reset(); }
if (usePointer) {
zone.addEventListener("pointerdown", onDown, { passive: true });
zone.addEventListener("pointermove", onMove, { passive: false });
zone.addEventListener("pointerup", onUp, { passive: false });
zone.addEventListener("pointercancel", onCancel, { passive: true });
zone.addEventListener("pointerleave", onCancel, { passive: true });
} else {
zone.addEventListener("touchstart", onDown, { passive: true });
zone.addEventListener("touchmove", onMove, { passive: false });
zone.addEventListener("touchend", onUp, { passive: false });
zone.addEventListener("touchcancel", onCancel, { passive: true });
}
// Keyboard support (left/right arrows) ignore if typing
document.addEventListener("keydown", (e) => {
if (cooldown) return;
const tag = (e.target && e.target.tagName) || "";
const typing = /INPUT|TEXTAREA|SELECT/.test(tag);
if (typing) return;
if (e.key === "ArrowRight") {
const btn = nextForm && nextForm.querySelector("button[disabled]");
if (!btn) { e.preventDefault(); submit(nextForm); }
} else if (e.key === "ArrowLeft") {
const btn = prevForm && prevForm.querySelector("button[disabled]");
if (!btn) { e.preventDefault(); submit(prevForm); }
}
});
// Defensive CSS: lock horizontal gestures to our handler only inside the zone
(function injectCSS() {
const css = `
#swipeZone{ touch-action: pan-y; overscroll-behavior-x: none; overflow-x: hidden; }
html, body{ overscroll-behavior-x: none; }
`;
const el = document.createElement("style");
el.textContent = css;
document.head.appendChild(el);
})();
})(); })();