Let the phone's pull reach the thread's end and hand over mid-swipe

Pull-to-refresh did nothing at all on Android, in Chrome as much as in
the installed app: no icon, no room, no movement. Two silent gates were
shut.

The pull required the content to sit at exactly zero pixels from the
bottom, while every other piece of thread logic calls 48px the bottom.
A phone's fractional device pixel ratio (2.625 on a Pixel) leaves the
content a hair short, and a thumb that stops one pixel early does too,
so atBottom() was false with nothing on screen to say why. atThreadEnd
reads the same measurement with PullToRefreshEndSlackPx (2px) of slack:
still stricter than near_bottom, since a pull needs the content to have
nowhere of its own to scroll, but no longer an exact zero. The old
`?? 1` fallback went too, which read a failed measurement as being at
the bottom.

The anchor was also taken once, at touchstart, and only if the thread
was already at its end, so the way a thumb actually uses it (flick up
until it stops, then keep going) handed over to nothing. The gesture is
now a plain state machine in pull-to-refresh-gesture.ts, tested without
a browser: a move that finds the thread at its end takes the anchor
then, which is the handover, while a move with conversation left gives
the finger back to the scroller and re-anchors if the end comes back.
The hold still arms only a full room, and a hold that outlives the room
no longer reloads.

Listeners stay on the scroll column. The wrapper would also catch taps
on the refresh button itself and could reload twice.
This commit is contained in:
2026-11-19 06:42:59 +01:00
parent 51041fb1d3
commit 3df20b940e
8 changed files with 530 additions and 101 deletions
+1 -1
View File
@@ -92,7 +92,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; the gesture is a plain state machine in `(utils)/pull-to-refresh-gesture.ts`, its steps tested without a browser, which takes the pull's anchor the moment the thread reaches its end, so one swipe that runs out of conversation hands over instead of stopping dead, and reads the end with `AppData.PullToRefreshEndSlackPx` of slack through `atThreadEnd`, since a phone's fractional device pixel ratio leaves the content a hair short and demanding an exact zero made the whole gesture do nothing; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[graphic:ID]` (a bot graphic, framed inline), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers another bot passed on keep working.
+7
View File
@@ -1004,6 +1004,13 @@ export const AppData = {
PullToRefreshMinPx: 8,
PullToRefreshResistance: 0.6,
PullToRefreshRoomPx: 64,
/**
* How far short of the column's edge the content still counts as the
* thread's end for the pull: a phone's fractional device pixel ratio
* leaves it a fraction of a pixel short, and a thumb that comes to rest
* a pixel above the newest message is at the bottom too.
*/
PullToRefreshEndSlackPx: 2,
/**
* How long that room must stay full, in milliseconds, before letting go
* reloads: an exhausted thread reaches the limit by accident too easily,
@@ -3,7 +3,11 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { AppData } from "@/src/data/app-data";
import minimumWait from "../(utils)/minimum-wait";
import pullToRefreshState from "../(utils)/pull-to-refresh";
import pullGesture, {
IdlePullGesture,
type PullGesture,
type PullGestureInput,
} from "../(utils)/pull-to-refresh-gesture";
/**
* What the pull indicator shows: nothing yet, a pull that isn't far
* enough, one that will reload on release, or a reload in flight.
@@ -43,10 +47,15 @@ type Params = {
* and reloads nothing.
*
* Touches are read rather than `scrollTop`, whose sign a reversed column
* reports differently across engines. Once the pull has started it owns the
* gesture until the finger lifts: it is not interrupted by a scroll, a
* resize or a text selection, so a press that is still down always shows
* its icon, and the reload happens on release, never before.
* reports differently across engines. The finger is read wherever it lands
* and the pull's anchor is taken when the thread reaches its end, so a swipe
* that starts halfway up the conversation and runs out of it keeps going
* into the pull instead of stopping dead at the last message
* (`pull-to-refresh-gesture.ts` holds that state, and its tests, without a
* browser). Once the pull has started it owns the gesture until the finger
* lifts: it is not interrupted by a scroll, a resize or a text selection, so
* a press that is still down always shows its icon, and the reload happens
* on release, never before.
*
* The room is written straight onto the content as the finger moves, never
* through a render: a phone drags in steps of a couple of pixels, and
@@ -68,18 +77,12 @@ export default function usePullToRefresh({
useEffect(() => {
const column = column_ref.current;
const content = content_ref.current;
if (!column) return;
let start_y: number | null = null;
/** The pull has begun: it runs to the release regardless. */
let engaged = false;
/** The room has stayed full long enough: letting go now reloads. */
let armed = false;
/** When the room last became full, while the finger holds it there. */
let held_since: number | null = null;
let gesture: PullGesture = IdlePullGesture;
let held_timer: ReturnType<typeof setTimeout> | null = null;
let selection_held = false;
let busy = false;
/**
@@ -88,6 +91,8 @@ export default function usePullToRefresh({
* grew under the finger would send it there mid-pull.
*/
const setRoom = (distance: number) => {
const content = content_ref.current;
if (!content) return;
content.style.transform = distance > 0 ? `translate3d(0, -${distance}px, 0)` : "";
@@ -100,119 +105,121 @@ export default function usePullToRefresh({
* pull has begun, since the pull is what this finger is doing.
*/
const holdSelection = (held: boolean) => {
if (selection_held == held) return;
const content = content_ref.current;
if (!content) return;
selection_held = held;
content.style.userSelect = held ? "none" : "";
if (held) window.getSelection()?.removeAllRanges();
};
const showState = () => {
const next: PullToRefreshState = gesture.armed
? "ready"
: gesture.engaged
? "pulling"
: "idle";
setState(next);
};
function stopHold() {
if (held_timer == null) return;
clearTimeout(held_timer);
held_timer = null;
}
/**
* The room is full: the hold that makes it a reload starts, or is
* already running. A finger that rests on the limit fires no further
* touches, so the timer is what notices the hold, not the moves.
*/
const beginHold = () => {
if (held_since != null) return;
function beginHold() {
if (held_timer != null) return;
held_since = Date.now();
held_timer = setTimeout(() => {
held_timer = null;
if (held_since == null) return;
armed = true;
setState("ready");
step({ type: "hold" });
}, AppData.PullToRefreshHoldMs);
}
/**
* One step of the gesture, written out: the room straight onto the
* content, the hold's timer started or dropped with it, and the
* icon's state from what the step left behind.
*/
function step(input: PullGestureInput) {
const was_full = gesture.full;
gesture = pullGesture({ gesture, input }).gesture;
setRoom(gesture.distance);
holdSelection(gesture.engaged);
if (gesture.full && !was_full) beginHold();
if (!gesture.full && was_full) stopHold();
showState();
}
const onStart = (event: TouchEvent) => {
if (busy || event.touches.length != 1) return;
const y = event.touches[0]?.clientY;
if (y == undefined) return;
step({ type: "start", y, at_end: bottom.current() });
};
/** Not full any more: the hold starts again from nothing. */
const dropHold = () => {
held_since = null;
armed = false;
const onMove = (event: TouchEvent) => {
if (busy || !gesture.touching) return;
if (held_timer == null) return;
const y = event.touches[0]?.clientY;
clearTimeout(held_timer);
held_timer = null;
if (y == undefined || event.touches.length != 1) {
/**
* A move that arrives without its touch holds no finger
* position; the release's own event is on its way, and it is
* that one that decides.
*/
if (!event.touches.length) return;
cancel();
return;
}
step({ type: "move", y, at_end: bottom.current() });
};
const reset = () => {
start_y = null;
engaged = false;
dropHold();
const cancel = () => {
if (busy) return;
gesture = IdlePullGesture;
stopHold();
setRoom(0);
holdSelection(false);
setState("idle");
};
const onStart = (event: TouchEvent) => {
start_y = null;
engaged = false;
dropHold();
if (busy || event.touches.length != 1) return;
if (!bottom.current()) return;
start_y = event.touches[0]?.clientY ?? null;
};
const onMove = (event: TouchEvent) => {
if (busy || start_y == null) return;
const current_y = event.touches[0]?.clientY;
if (current_y == undefined || event.touches.length != 1) {
/**
* A move that arrives without its touch holds no finger
* position; the release's own event is on its way, and it
* is that one that decides.
*/
if (!event.touches.length) return;
reset();
return;
}
if (!engaged) {
if (!bottom.current()) {
reset();
return;
}
if (pullToRefreshState({ start_y, current_y }).pulling) {
engaged = true;
holdSelection(true);
}
}
/**
* A finger dragged back down before it was let go takes the
* room back down with it and hides the icon at the very travel
* that showed it, so the pull reads the same in either
* direction. The gesture stays its own until the release, and
* a hold that has not finished yet starts over from nothing.
*/
const pulled = pullToRefreshState({ start_y, current_y });
if (pulled.ready) beginHold();
else dropHold();
setRoom(pulled.distance);
setState(armed ? "ready" : pulled.pulling ? "pulling" : "idle");
};
const onEnd = async () => {
if (busy) return;
const reload = engaged && armed;
const reload = pullGesture({ gesture, input: { type: "end" } }).reload;
start_y = null;
engaged = false;
dropHold();
gesture = IdlePullGesture;
stopHold();
holdSelection(false);
if (!reload) {
reset();
setRoom(0);
setState("idle");
return;
}
@@ -230,21 +237,21 @@ export default function usePullToRefresh({
});
} finally {
busy = false;
reset();
cancel();
}
};
column.addEventListener("touchstart", onStart, { passive: true });
column.addEventListener("touchmove", onMove, { passive: true });
column.addEventListener("touchend", onEnd);
column.addEventListener("touchcancel", reset);
column.addEventListener("touchcancel", cancel);
return () => {
column.removeEventListener("touchstart", onStart);
column.removeEventListener("touchmove", onMove);
column.removeEventListener("touchend", onEnd);
column.removeEventListener("touchcancel", reset);
dropHold();
column.removeEventListener("touchcancel", cancel);
stopHold();
setRoom(0);
holdSelection(false);
};
@@ -2,6 +2,7 @@ import { useLayoutEffect, useRef, useState, type RefObject } from "react";
import type { BotMessageWithAttachments } from "@/src/types";
import {
ThreadJumpWindowMs,
atThreadEnd,
scrollThreadToBottom,
shouldFollowThread,
threadOffset,
@@ -53,11 +54,19 @@ export default function useThreadScroll({ messages }: Params) {
};
/**
* Whether the content's end is exactly at the column's bottom, with no
* slack: the pull-to-reload gesture reads it, since a thread a few
* pixels short still has somewhere of its own to scroll to.
* Whether the content's end is at the column's bottom, as the
* pull-to-reload gesture reads it: the thread has nowhere of its own
* left to scroll, so the finger's travel is the pull's. `atThreadEnd`
* keeps a couple of pixels of slack, which a fractional device pixel
* ratio and a thumb that stops just short both need.
*/
const atBottom = () => (measure()?.distance ?? 1) <= 0;
const atBottom = () => {
const offset = measure();
if (!offset) return false;
return atThreadEnd({ distance: offset.distance });
};
/** The user's own scrolling: it decides whether the thread follows. */
const onScroll = () => {
@@ -0,0 +1,200 @@
import { describe, expect, test } from "bun:test";
import pullGesture, {
IdlePullGesture,
type PullGesture,
type PullGestureInput,
} from "./pull-to-refresh-gesture";
function run(
inputs: PullGestureInput[],
from: PullGesture = IdlePullGesture,
): PullGesture {
return inputs.reduce(
(gesture, input) => pullGesture({ gesture, input }).gesture,
from,
);
}
/** A finger on a thread already at its end, at `y`. */
const landedAtEnd = (y = 500): PullGestureInput => ({
type: "start",
y,
at_end: true,
});
const climb = (y: number, at_end = true): PullGestureInput => ({
type: "move",
y,
at_end,
});
const hold: PullGestureInput = { type: "hold" };
const release: PullGestureInput = { type: "end" };
describe("pullGesture", () => {
test("a touch on a thread at its end pulls as the finger climbs", () => {
const gesture = run([landedAtEnd(), climb(490)]);
expect(gesture.engaged).toBe(true);
expect(gesture.distance).toBe(6);
expect(gesture.full).toBe(false);
});
test("the room stops at its full depth however far the drag goes", () => {
const gesture = run([landedAtEnd(), climb(300)]);
expect(gesture.distance).toBe(64);
expect(gesture.full).toBe(true);
});
test("a touch on a thread with conversation left pulls nothing", () => {
const gesture = run([
{ type: "start", y: 500, at_end: false },
climb(300, false),
]);
expect(gesture.engaged).toBe(false);
expect(gesture.distance).toBe(0);
});
test("a swipe that runs out of conversation keeps going into the pull", () => {
const at_end = run([
{ type: "start", y: 500, at_end: false },
climb(400, false),
]);
expect(at_end.engaged).toBe(false);
expect(at_end.distance).toBe(0);
const anchored = run([climb(380, true)], at_end);
expect(anchored.anchor_y).toBe(380);
expect(anchored.distance).toBe(0);
expect(anchored.engaged).toBe(false);
const pulling = run([climb(370, true)], anchored);
expect(pulling.engaged).toBe(true);
expect(pulling.distance).toBe(6);
});
test("a pull dragged back down closes the room and lifts again from the same anchor", () => {
const down = run([landedAtEnd(), climb(400), climb(500)]);
expect(down.anchor_y).toBe(500);
expect(down.distance).toBe(0);
expect(down.engaged).toBe(true);
const up = run([climb(450)], down);
expect(up.distance).toBe(30);
});
test("a move that finds conversation left gives the finger back", () => {
const gesture = run([landedAtEnd(), climb(400), climb(420, false)]);
expect(gesture.engaged).toBe(false);
expect(gesture.distance).toBe(0);
expect(gesture.anchor_y).toBeNull();
});
test("a moved thread can pull again later in the same gesture", () => {
const gesture = run([
landedAtEnd(),
climb(400),
climb(420, false),
climb(400, true),
climb(390, true),
]);
expect(gesture.anchor_y).toBe(400);
expect(gesture.engaged).toBe(true);
expect(gesture.distance).toBe(6);
});
test("the hold only arms a room that is full", () => {
const pulled = run([landedAtEnd(), climb(450)]);
expect(pulled.full).toBe(false);
expect(run([hold], pulled).armed).toBe(false);
const full = run([landedAtEnd(), climb(300)]);
expect(full.full).toBe(true);
expect(run([hold], full).armed).toBe(true);
});
test("a hold that outlives the room closing does not reload", () => {
const closed = run([landedAtEnd(), climb(300), hold, climb(480)]);
expect(closed.full).toBe(false);
expect(closed.armed).toBe(false);
expect(run([hold], closed).armed).toBe(false);
expect(
pullGesture({ gesture: closed, input: release }).reload,
).toBe(false);
});
test("letting go of a full room before the hold reloads nothing", () => {
const step = pullGesture({
gesture: run([landedAtEnd(), climb(300)]),
input: release,
});
expect(step.reload).toBe(false);
expect(step.gesture).toEqual(IdlePullGesture);
});
test("letting go of a full room it held reloads", () => {
const step = pullGesture({
gesture: run([landedAtEnd(), climb(300), hold]),
input: release,
});
expect(step.reload).toBe(true);
expect(step.gesture).toEqual(IdlePullGesture);
});
test("a pull that was never the finger's reloads nothing however armed", () => {
const step = pullGesture({
gesture: { ...IdlePullGesture, armed: true, full: true },
input: release,
});
expect(step.reload).toBe(false);
});
test("dropping the hold disarms the room", () => {
const gesture = run([
landedAtEnd(),
climb(300),
hold,
{ type: "drop_hold" },
]);
expect(gesture.armed).toBe(false);
expect(gesture.full).toBe(true);
});
test("a cancel clears the whole gesture", () => {
const gesture = run([
landedAtEnd(),
climb(300),
hold,
{ type: "cancel" },
]);
expect(gesture).toEqual(IdlePullGesture);
});
test("moves without a finger on the thread change nothing", () => {
expect(run([climb(300)])).toEqual(IdlePullGesture);
});
test("a touch that lifts without moving leaves the thread alone", () => {
const step = pullGesture({ gesture: run([landedAtEnd()]), input: release });
expect(step.gesture).toEqual(IdlePullGesture);
expect(step.reload).toBe(false);
});
});
@@ -0,0 +1,144 @@
import pullToRefreshState from "./pull-to-refresh";
/**
* One finger's pull-to-reload gesture, as the thread reads it. Every step is
* a plain function of the step before, so the whole gesture can be checked
* without a browser.
*/
export type PullGesture = {
/**
* A finger is on the thread. The gesture ends only when it lifts, even
* after the pull has given the finger back to the scroller.
*/
touching: boolean;
/**
* Where the pull's travel is measured from: null until the thread is at
* its end, then the finger's place at that moment.
*
* The anchor is what lets one continuous swipe hand over. A thumb that
* starts halfway up the conversation and runs out of it scrolls until
* the newest message reaches the bottom and then keeps going: fixing the
* start at the touchstart alone meant such a swipe never pulled, since
* the thread was not at its end yet when the finger landed.
*/
anchor_y: number | null;
/**
* The pull is what the finger is doing. It stays the gesture's until the
* finger lifts, or the thread has somewhere of its own to scroll again.
*/
engaged: boolean;
/** The room under the newest message is as deep as it opens. */
full: boolean;
/** The full room has been held long enough: letting go reloads. */
armed: boolean;
/** How far the content is lifted off the bottom, in pixels. */
distance: number;
};
export const IdlePullGesture: PullGesture = {
touching: false,
anchor_y: null,
engaged: false,
full: false,
armed: false,
distance: 0,
};
export type PullGestureInput =
| { type: "start"; y: number; at_end: boolean }
| { type: "move"; y: number; at_end: boolean }
| { type: "hold" }
| { type: "drop_hold" }
| { type: "end" }
| { type: "cancel" };
export type PullGestureStep = {
gesture: PullGesture;
/** The finger lifted on a room it had held full: reload now. */
reload: boolean;
};
export default function pullGesture({
gesture,
input,
}: {
gesture: PullGesture;
input: PullGestureInput;
}): PullGestureStep {
switch (input.type) {
case "start":
return {
gesture: {
...IdlePullGesture,
touching: true,
anchor_y: input.at_end ? input.y : null,
},
reload: false,
};
case "move": {
if (!gesture.touching) return { gesture, reload: false };
/**
* Not at the end: there is conversation left to scroll, so the
* finger belongs to the scroller. A pull already begun goes back
* down with it, and the anchor is taken again the next time the
* thread reaches its end.
*/
if (!input.at_end) {
return {
gesture: {
...gesture,
anchor_y: null,
engaged: false,
full: false,
armed: false,
distance: 0,
},
reload: false,
};
}
const anchor_y = gesture.anchor_y ?? input.y;
const pulled = pullToRefreshState({
start_y: anchor_y,
current_y: input.y,
});
return {
gesture: {
...gesture,
anchor_y,
engaged: gesture.engaged || pulled.pulling,
full: pulled.ready,
armed: pulled.ready && gesture.armed,
distance: pulled.distance,
},
reload: false,
};
}
/**
* The full room has been held long enough. It only arms while the
* room is full: a hold that started on the way up must not reload
* after the finger drifted back out of the room.
*/
case "hold":
return {
gesture: { ...gesture, armed: gesture.full },
reload: false,
};
case "drop_hold":
return { gesture: { ...gesture, armed: false }, reload: false };
case "end":
return {
gesture: IdlePullGesture,
reload: gesture.engaged && gesture.armed,
};
case "cancel":
return { gesture: IdlePullGesture, reload: false };
}
}
@@ -1,6 +1,8 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import {
ThreadBottomSlack,
atThreadEnd,
shouldFollowThread,
threadOffset,
} from "./thread-scroll";
@@ -55,6 +57,39 @@ describe("threadOffset", () => {
});
});
describe("atThreadEnd", () => {
test("content ending at the column's bottom is the end", () => {
expect(atThreadEnd({ distance: 0 })).toBe(true);
});
test("a fraction of a pixel short is still the end", () => {
expect(
atThreadEnd({
distance: threadOffset({
content_bottom: 799.6,
column_bottom: 800,
}).distance,
}),
).toBe(true);
});
test("a couple of pixels short is still the end", () => {
expect(atThreadEnd({ distance: AppData.PullToRefreshEndSlackPx })).toBe(
true,
);
});
test("past the slack the thread has somewhere of its own to scroll", () => {
expect(
atThreadEnd({ distance: AppData.PullToRefreshEndSlackPx + 1 }),
).toBe(false);
});
test("the slack is configurable", () => {
expect(atThreadEnd({ distance: 20, slack: 24 })).toBe(true);
});
});
describe("shouldFollowThread", () => {
test("a chat at the bottom follows a bot's reply", () => {
expect(
@@ -1,3 +1,5 @@
import { AppData } from "@/src/data/app-data";
/**
* Pixels from the bottom that still count as being at it, so a mouse wheel
* tick or a rounding difference doesn't hide the latest message.
@@ -37,6 +39,31 @@ export function threadOffset({
};
}
/**
* Whether the thread's content ends as far down as it goes, for the pull
* that opens room under the newest message. It is stricter than
* `threadOffset`'s `near_bottom`, which lets a wheel tick or a rounding
* difference pass so the newest message stays in view: a pull needs the
* content to have nowhere left of its own to scroll, or the finger's travel
* would be the scroller's.
*
* It still keeps a couple of pixels of slack. A phone's fractional device
* pixel ratio leaves the content a fraction of a pixel past the column's
* edge while a reversed column sits at its end, and a thumb that comes to
* rest a pixel above the newest message is at the bottom by any reading.
* Demanding an exact zero there made the gesture do nothing at all, with no
* hint why.
*/
export function atThreadEnd({
distance,
slack = AppData.PullToRefreshEndSlackPx,
}: {
distance: number;
slack?: number;
}) {
return distance <= slack;
}
/**
* Whether the thread should show a change of its messages, which keeps the
* bottom in view while the user is there: it follows while at the bottom, a