Files
ipx/web/src/gestures.ts
rays 9e3ffd80c1 The reader rebuilds its scroller when an item opens on a phone (#450)
Every scroll_stuck report since the added fields was a short drag over
text in a reader whose content had just been swapped, with nothing over
it, nothing inert and the touch left alone by the page: iOS kept the drag
and did not scroll. That fits WebKit keeping an overflow box's scroller
sized for what was there before. Overflow is taken away for two frames
after each open, and after a stuck drag is caught, so the scroller is
built again; the report now says how long since the last one, which tells
whether this freed it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVCCH8YcP2Y3i8VNYWA
2026-11-27 17:26:41 -05:00

271 lines
16 KiB
TypeScript

/* ---------------- touch gestures ---------------- */
// On a touch screen: pull the item list down from its top to check the feed for new items, and
// swipe the item you are reading left for the next one, right for the one before, or back to
// the list from the first. Touch events only, so a mouse never sets these off. Listened for on
// the document because the panes are rebuilt every time a feed renders.
const PULL = 70; // px down, from the list's top, that counts as a pull
// A quarter of the reader's width across, and never less than 100px: at a flat 60px a thumb
// scrolling slightly on the diagonal jumped to the next item by accident (issue #49).
const swipeMin = () => Math.max(100, ($('#detail')?.clientWidth || 0) / 4);
const GAP = 16; // px of page between two items side by side, so they read as two sheets
const narrow = () => !!window.matchMedia?.('(max-width:820px)')?.matches;
const still = () => !!window.matchMedia?.('(prefers-reduced-motion:reduce)')?.matches;
let touch: {x: number, y: number, t: number, pane: 'list' | 'detail', dx: number, dy: number} | null = null;
/// Something that scrolls sideways, or takes typing, keeps its own gestures: a wide code block
/// or table in a post, the player's seek bar, a text box.
function ownsSwipe(el: Element | null){
for(let n = el; n && n.id !== 'detail'; n = n.parentElement){
if(/^(INPUT|TEXTAREA|SELECT|AUDIO|VIDEO)$/.test(n.tagName)) return true;
if(n.scrollWidth > n.clientWidth + 1 && /(auto|scroll)/.test(getComputedStyle(n).overflowX)) return true;
}
return false;
}
/// How far the list has been pulled: a note at its top, growing with the pull and pushing the
/// items down, that says what letting go will do.
function pullShow(dy: number){
const list = $('#list'); if(!list) return;
const d = Math.round(Math.min(dy, PULL * 1.6) / 2);
let tip = $('#pulltip');
if(!d){ tip?.remove(); return; }
if(!tip){ tip = document.createElement('div'); tip.id = 'pulltip'; list.prepend(tip); }
tip.style.height = d + 'px';
tip.textContent = dy >= PULL ? 'Release to check for new items' : 'Pull to check for new items';
}
/// A check started by a pull, while its spinner is up. Letting go showed nothing before (issue
/// #68), the sidebar's spinner is hidden on a phone, and people pulled again and again.
let refreshing = false;
function refreshFeed(){
const f = S.feeds.find(x => x.id === S.feed);
if(!f && S.feed !== ':all') return;
if(refreshing) return;
refreshing = true;
// Outside #list, which a feed's render rebuilds and would take the spinner with it.
const spin = document.createElement('div');
spin.id = 'pullspin'; spin.setAttribute('role', 'status'); spin.textContent = 'Checking for new items';
document.body.append(spin);
// New items arrive by the event stream when the scan finishes, as they do for a button press.
const asked = api('/api/fetch', {method: 'POST', body: JSON.stringify(f ? {feed: f.id, force: true} : {force: true})})
.catch(e => toast(why(e), true));
loadEntries();
// Up for two seconds at least, so it is seen even when the server answers at once.
Promise.all([asked, new Promise(r => setTimeout(r, 2000))]).then(() => { spin.remove(); refreshing = false; });
}
document.addEventListener('touchstart', ev => {
touch = null;
if(ev.touches.length !== 1 || $('#modal')?.classList.contains('on')) return;
const t = ev.touches[0], target = ev.target as Element;
const detail = target.closest?.('#detail'), list = target.closest?.('#list');
// Reading means an item is open; the reader is its own screen on a phone, a pane otherwise.
if(detail && S.sel && !ownsSwipe(target)){
touch = {x: t.clientX, y: t.clientY, t: Date.now(), pane: 'detail', dx: 0, dy: 0};
// Safari takes a swipe from the screen's left edge as Back, which leaves the page halfway
// through going back to the list. Kept narrower than the reader's padding, so a tap on the
// back button is never swallowed with it.
if(t.clientX < 14 && narrow() && ev.cancelable) ev.preventDefault();
}
else if(list && list.scrollTop <= 0 && !VIEWS[S.feed ?? '']?.url) touch = {x: t.clientX, y: t.clientY, t: Date.now(), pane: 'list', dx: 0, dy: 0};
}, {passive: false});
document.addEventListener('touchmove', ev => {
if(!touch) return;
const t = ev.touches[0];
touch.dx = t.clientX - touch.x; touch.dy = t.clientY - touch.y;
if(touch.pane === 'list'){
// Only a pull that starts at the top and goes down; anything else is an ordinary scroll.
if(touch.dy < 0 || $('#list').scrollTop > 0){ pullShow(0); touch = null; return; }
pullShow(touch.dy);
if(ev.cancelable) ev.preventDefault(); // or the list rubber-bands under the finger as well
}else if(Math.abs(touch.dy) > 10 && Math.abs(touch.dy) > Math.abs(touch.dx)){
slide(0); touch = null; // scrolling the text, not swiping; the first few px
// decide nothing, being mostly jitter
}else if(Math.abs(touch.dx) > 10){
// The reader follows the finger, so it is plain before letting go whether this will move on;
// with nothing that way it only gives a little.
const i = S.entries.findIndex(x => entryKey(x) === S.sel);
const end = touch.dx < 0 && i >= S.entries.length - 1;
slide(end ? touch.dx / 3 : touch.dx, 0);
}
}, {passive: false});
/// On a phone, what lies beside the reader while it is dragged by dx: the item it will move on
/// to, the accent past the last one, or, going back to the list, a dimmer over the list. The
/// reader sits over the list there, and moving it alone showed the list through the gap it left
/// (issue #52). Kept outside #content, which every feed render rebuilds, and inert, since its
/// copy of the reader's markup repeats the reader's ids.
function beside(dx: number){
const i = S.entries.findIndex(x => entryKey(x) === S.sel), e = S.entries[i + (dx < 0 ? 1 : -1)];
const kind = dx < 0 ? (e ? 'next' : 'end') : (e ? 'prev' : 'dim');
let p = $('#dpeek');
if(!p){
p = document.createElement('div'); p.id = 'dpeek'; p.inert = true; p.setAttribute('aria-hidden', 'true');
document.body.append(p);
}
if(p.dataset.key !== kind + (e?.guid || '')){
p.dataset.key = kind + (e?.guid || ''); p.className = kind;
p.innerHTML = e ? `<div>${detailHtml(e)}</div>` : '';
}
return p;
}
/// Moves the reader across by dx over ms, or at once (when following a finger), and what lies
/// beside it with it.
function slide(dx: number, ms = 160){
const d = $('#detail'); if(!d) return;
// Only a move across: every touch in the reader that is not a swipe ends in slide(0) (#488).
if(dx) slidAt = Date.now();
dx = Math.round(dx); // whole pixels, or the seam between the reader and its neighbour blurs
const w = d.clientWidth || 1, tr = ms ? `transform ${ms}ms ease-out, opacity ${ms}ms ease-out` : 'none';
d.style.transition = tr;
d.style.transform = dx ? `translateX(${dx}px)` : '';
// A wider screen has the reader as a pane beside the list, with nothing under it to show.
if(!narrow()){ d.style.opacity = dx ? String(Math.max(.4, 1 - Math.abs(dx) / w)) : ''; return; }
const p = dx ? beside(dx) : $('#dpeek');
d.classList.toggle('popping', !!dx && p?.className === 'dim');
if(!p) return;
p.style.transition = tr;
if(p.className === 'dim') p.style.opacity = String(.35 * (1 - Math.abs(dx) / w));
else p.style.transform = `translateX(${dx + (p.className === 'prev' ? -w - GAP : w)}px)`;
// Gone once the reader is back, unless another drag has already begun.
if(!dx){ if(ms) setTimeout(() => { if(!touch) $('#dpeek')?.remove(); }, ms); else p.remove(); }
}
/// The reader carries on the way the finger went, from wherever it was let go, and the item
/// beside it becomes the reader in its place. Timers, not transitionend, because with reduced
/// motion the stylesheet turns transitions off and transitionend never comes.
function slideOn(dx: number, go: () => void){
const d = $('#detail'), w = d?.clientWidth || 0, dir = Math.sign(dx);
if(!narrow()){
// A pane beside the list: off one side, and the next item in from the other.
slide(dir * w);
setTimeout(() => { go(); slide(-dir * w, 0); requestAnimationFrame(() => requestAnimationFrame(() => slide(0))); }, 160);
return;
}
const to = dir * (w + (beside(dx).className === 'dim' ? 0 : GAP));
const ms = still() ? 0 : Math.round(Math.max(120, 250 * (1 - Math.abs(dx) / (w || 1))));
slide(to, ms);
// The preview stays over the reader until the new item's pictures are drawn (#471): swapped at
// once, its text came a frame before the picture above it, and flashed where the picture would be.
setTimeout(() => { go(); drawn($('#detail'), 300).then(() => { if(!touch) slide(0, 0); }); }, ms);
}
/// The pictures of the items either side of the one open, fetched and decoded ahead (#471): the
/// preview a swipe draws is built as the drag begins, and its picture loaded only then came in
/// after its text, flashing and pushing the text down under the finger. Held here, so the browser
/// keeps them decoded; a few each, since only the top of an item shows in the preview.
let warm: HTMLImageElement[] = [];
function warmNeighbours(){
if(!narrow()) return;
const i = S.entries.findIndex(x => entryKey(x) === S.sel);
const html = [S.entries[i - 1], S.entries[i + 1]].filter(e => e).map(e => textOf(e!)).join('');
// Parsed, not put in the page: a document from DOMParser loads none of its pictures.
const srcs = [...new DOMParser().parseFromString(html, 'text/html').images].slice(0, 6).map(i => i.src);
warm = srcs.map(src => { const im = new Image(); im.src = src; im.decode().catch(() => {}); return im; });
}
/// When the pictures in `el` are decoded and ready to draw, or `max` ms, whichever is sooner, so a
/// slow picture never holds up the page.
function drawn(el: HTMLElement | null, max: number): Promise<unknown> {
const pending = [...el?.querySelectorAll('img') ?? []].filter(i => !i.complete || !i.naturalWidth);
if(!pending.length) return Promise.resolve();
return Promise.race([Promise.all(pending.map(i => i.decode().catch(() => {}))), new Promise(r => setTimeout(r, max))]);
}
document.addEventListener('touchend', () => {
const g = touch; touch = null;
if(!g) return;
if(g.pane === 'list'){
pullShow(0);
if(g.dy >= PULL){ haptic('tap'); refreshFeed(); }
return;
}
const i = S.entries.findIndex(x => entryKey(x) === S.sel);
// What came of it, where the reader stood (#384): a swipe that only bounces sends no request,
// and #383's stop at the 50th item was seen by nobody but the person swiping.
const swiped = (what: string) => report('swipe', {msg: what, ms: Date.now() - g.t, feed: S.feed, filter: S.filter,
state: `${i + 1}/${S.entries.length} of ${S.total}${hasMore() ? ', more to load' : ''}`});
// Across, mostly sideways, and not a slow drag while selecting text. A tap is not a swipe at all.
if(Math.abs(g.dx) < swipeMin() || Math.abs(g.dx) < 2 * Math.abs(g.dy) || Date.now() - g.t > 800){
if(Math.abs(g.dx) > 30) swiped('short');
return slide(0);
}
if(g.dx < 0 && i >= S.entries.length - 1){ swiped('end'); return slide(0); }
if(g.dx < 0){ swiped('next'); return slideOn(g.dx, () => stepEntry(1)); }
if(i > 0){ swiped('prev'); return slideOn(g.dx, () => stepEntry(-1)); }
swiped('list');
slideOn(g.dx, () => showDetail(null));
});
document.addEventListener('touchcancel', () => { if(touch?.pane === 'list') pullShow(0); else slide(0); touch = null; });
/// A reader that will not scroll (#384): a drag up or down over an item with room to move that
/// way, after which it has not moved. Watched by where the finger is, not by what it landed on,
/// so something lying over the reader is caught too, and named. Reported with what could hold it,
/// since the cause of the one in #383 was never found.
// What #450's three reports could not say (#450): where the finger began, whether the page saw it
// move at all (none means the browser kept the drag for itself), whether the page cancelled the
// touch, and how long since the reader was last slid across, the one thing a swipe changes on it.
let drag: {x: number, y: number, t: number, top: number, on: string, moves: number, cancelled: boolean} | null = null,
shownAt = Date.now(), slidAt = 0;
document.addEventListener('visibilitychange', () => { if(!document.hidden) shownAt = Date.now(); });
const named = (el: Element | null) => !el ? 'nothing'
: el.id ? '#' + el.id : el.tagName.toLowerCase() + (typeof el.className === 'string' && el.className ? '.' + el.className.split(' ')[0] : '');
/// A drag of dy down (dx across) that left the reader at the same scrollTop, from `before`, with
/// `room` to scroll in all. Only one with somewhere to go: up with more below, down with more above.
const stuckDrag = (dy: number, dx: number, before: number, after: number, room: number) =>
Math.abs(dy) >= 40 && Math.abs(dy) >= 2 * Math.abs(dx) && room >= 2 && after === before
&& (dy < 0 ? before < room - 1 : before > 0);
document.addEventListener('touchstart', ev => {
const d = $('#detail'), t = ev.touches[0];
drag = null;
if(ev.touches.length !== 1 || !d || !S.sel) return;
const r = d.getBoundingClientRect();
if(t.clientX < r.left || t.clientX > r.right || t.clientY < r.top || t.clientY > r.bottom) return;
drag = {x: t.clientX, y: t.clientY, t: Date.now(), top: d.scrollTop, on: named(ev.target as Element), moves: 0, cancelled: false};
// After the swipe's own touchstart, which may cancel it, has run.
queueMicrotask(() => { if(drag) drag.cancelled = ev.defaultPrevented; });
}, {passive: true});
document.addEventListener('touchmove', () => { if(drag) drag.moves++; }, {passive: true});
document.addEventListener('touchend', ev => {
const d = $('#detail'), t = ev.changedTouches[0], g = drag;
drag = null;
if(!g || !d || !t) return;
const dy = t.clientY - g.y, dx = t.clientX - g.x, room = d.scrollHeight - d.clientHeight, ms = Date.now() - g.t;
if(!stuckDrag(dy, dx, g.top, d.scrollTop, room)) return;
// Looked at again a moment later: iOS scrolls off the main thread, and a fast flick can end
// before the page has been told where it went (#488).
setTimeout(() => {
if(stuckDrag(dy, dx, g.top, d.scrollTop, room)) stuck(d, t, g, dy, room, ms);
}, 300);
});
/// Makes iOS build the reader's scroller again (#450): every stuck drag was on a reader whose
/// content had been swapped, with nothing over it and the touch left alone, which is WebKit keeping
/// a scroller sized for what was there before. Two frames without overflow, so the hidden state is
/// committed and not merged away with the change back.
function rearm(d: HTMLElement){
d.style.overflowY = 'hidden';
requestAnimationFrame(() => requestAnimationFrame(() => { d.style.overflowY = ''; }));
}
let stuckAt = 0;
function stuck(d: HTMLElement, t: Touch, g: NonNullable<typeof drag>, dy: number, room: number, ms: number){
rearm(d);
// A second report soon after the first says rearm did not free it.
const again = stuckAt ? Math.round((Date.now() - stuckAt) / 1000) + 's ago' : 'never';
stuckAt = Date.now();
const inert = ([...document.body.children] as HTMLElement[]).filter(el => el.inert).map(named).join(' ');
report('scroll_stuck', {feed: S.feed, state: [
`top ${g.top} of ${room}`, `drag ${Math.round(dy)}px`, `started on ${g.on}`,
`under the finger ${named(document.elementFromPoint(t.clientX, t.clientY))}`,
`inert ${inert || 'none'}`, `dialog ${$('#modal')?.classList.contains('on') ? 'open' : 'closed'}`,
`transform ${d.style.transform || 'none'}`, `peek ${$('#dpeek') ? 'left behind' : 'gone'}`,
`overflow ${getComputedStyle(d).overflowY}`, `reading ${document.body.classList.contains('reading')}`,
`shown ${Math.round((Date.now() - shownAt) / 1000)}s ago`, `${S.entries.length} loaded`,
`from x ${Math.round(g.x)}`, `${g.moves} moves seen in ${ms}ms`, `touch ${g.cancelled ? 'cancelled' : 'left alone'}`,
`slid ${slidAt ? Math.round((Date.now() - slidAt) / 1000) + 's ago' : 'never'}`, `last stuck ${again}`].join(', ')});
}