Swipe between panes on a phone, and slide a bot's panel in from the right

Below `md` the rail slides over the page, so two swipes anywhere on the page
move between panes: to the right opens the rail's drawer, to the left the
conversation's bot panel. A touch on a field, a code editor, something that
scrolls sideways, or a panel the app slid in belongs to it, and so does a
long press, a selection, a mostly vertical drag, a modal already up and any
swipe wider than a phone.

The panel that used to be the centred "Edit <bot>" modal is the same at every
width: the bot's avatar, its name, or the swipe all open it from the right
over the conversation, and Escape or the backdrop closes it.
This commit is contained in:
2026-11-21 13:55:03 +01:00
parent 4ae176f41b
commit 37bb3f0470
18 changed files with 984 additions and 147 deletions
+2 -2
View File
@@ -90,7 +90,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_plans` (a plan a bot wrote for work in pieces, its steps and their state), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts` and `src/dict/bot-plan-dict.ts`.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. A routine and a hook each keep a thread of their own, never the chat that happens to be active: `bot_sessions.routine_id` and `hook_id` mark it, `ensureRoutineSession`/`ensureHookSession` open it `closed` (so it takes nothing over) with the routine's or hook's title, roll it over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and it is read and chatted in with `?session_id=` like any session. A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change) **until the user writes in it**: a human message takes the thread from the hook (`adoptHookSession`, from `insertUserMessage`, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **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.
- **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, the bot panel (`BotPanel`) sliding in from the right when its avatar or its name is tapped, or a phone swipes that way, over the conversation rather than taking width; `?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. The thread follows new messages while it sits at its bottom and offers "Jump to latest" (`ScrollToBottomButton`) when scrolled up; End does what that button does and Home goes back to the top of the messages loaded so far, both keeping away from a field being typed in, an open menu and an open modal (`typingInField`, `scrollThreadToTop`). 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. A message sent in **Plan mode** (`bot_messages.plan_mode`, turned on by Tab anywhere on the conversation page or the composer's Plan button, remembered per conversation in `localStorage`) is answered by a planning run: `run-bot-reply` holds the tools to `PlanModeToolNames` (reads and the plan/question/suggestion cards, never `load_tools`), `send_reply` refuses `work` and `working`, and the computer and browser notes are left out; Retry and Run again copy the flag from the message they answer. A Plan mode reply whose result belongs in a file or another place outside the chat may not paste it or say a write tool is missing: it says the mode stops the save and asks with `ask_user` whether to save it (the answer runs without the mode), and `planModeFileEscape` sends a reply back when it hands the save to the user instead.
@@ -191,7 +191,7 @@ Set in Settings > Environment (super admin), not `.env`. `envs` (private; encryp
- Notification `badge` is `icons/badge-96.png` (white silhouette; Android masks by alpha, so never the opaque app icon). Brave on Android has no WebAPK, so its notifications always carry Brave's name and icon.
- `public/sw.js` is served `no-store`; navigations network-only (authenticated HTML never cached); `/api/`, `/ws`, `/media/`, `/computers/`, `/build-info.json` never intercepted. A new worker takes over by itself (`skipWaiting` on install; nothing in it is per-version) and never reloads a page; there is no update prompt. In development the worker and caches are actively removed (`clear-development-service-worker.ts`, stub `/sw.js`).
- **Precache (production):** a navigation without the current build cookie gets `loading.html`, which downloads all of `.bunext/public` into `cobble-assets-<build_id>`, verifies, sets the cookie and reloads (falls back to network on stall). React knows nothing of this.
- Phone shell: rail is a slide-over below `md`; rail internals use the `@rail:` container variant, not viewport `lg:`. `LiveSocket` is remounted on online/pageshow/visibility since twui stops retrying after three attempts. Nothing is queued offline.
- Phone shell: rail is a slide-over below `md` (the shared `src/components/general/side-panel.tsx`, always mounted so it slides both ways; the rail passes `inertWhenClosed={false}` since it is the page's own rail from `md` up); rail internals use the `@rail:` container variant, not viewport `lg:`. Two swipes anywhere on a phone page move between panes: to the right opens the rail's drawer, to the left the conversation's bot panel (`cobble:open-bot-panel`, `src/utils/bot-panel-open-event.ts`, answered only by a conversation's header, so a page without one slides nothing). They are flicks, read by `src/hooks/use-horizontal-swipe.ts` (a field, a `data-no-swipe` panel, a box that scrolls sideways, a text selection, a finger down longer than `AppData.MobileSwipeMaxMs`, an open twui modal, a screen from `md` up and the open drawer all own the touch), with the thresholds and the one-decision state machine in `src/utils/swipe-gesture.ts` (`AppData.MobileSwipeMinPx`, `MobileSwipeAxisRatio`), tested without a browser. `LiveSocket` is remounted on online/pageshow/visibility since twui stops retrying after three attempts. Nothing is queued offline.
- **Web Push:** `push_subscriptions`, `user_presence`; VAPID keys generated into `envs` by `ensureVapidKeys`. `pushBotNotice` is the one trigger, skipped while the user is present (`AppData.PushPresenceWindowMs`, per user not per device). Best effort, no retry. Needs HTTPS.
### Bot files and folders
@@ -0,0 +1,91 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import SidePanel from "./side-panel";
const onClose = () => {};
describe("SidePanel", () => {
test("a closed panel waits off its edge, untabbed, with no backdrop", () => {
const html = renderToString(
<SidePanel side="left" open={false} onClose={onClose} label="Bots">
<p>crew</p>
</SidePanel>,
);
expect(html).toContain("-translate-x-full");
expect(html).toContain("left-0");
expect(html).toContain('aria-hidden="true"');
expect(html).toContain("inert");
expect(html).not.toContain("bg-ink/40");
/**
* Its contents are still in the page, ready to slide in.
*/
expect(html).toContain("crew");
});
test("an open panel sits on its edge over a backdrop that closes it", () => {
const html = renderToString(
<SidePanel side="right" open onClose={onClose} label="Edit Ada">
<p>form</p>
</SidePanel>,
);
expect(html).toContain("right-0");
expect(html).toContain("border-l");
expect(html).toContain("translate-x-0");
expect(html).not.toContain("translate-x-full");
expect(html).not.toContain("inert");
/**
* The backdrop is the hidden-from-assistive-tech part; the panel
* itself is a labelled region.
*/
expect(html).toMatch(/<div aria-label="Edit Ada"/);
expect(html).toContain("bg-ink/40");
expect(html).toContain('aria-label="Edit Ada"');
});
test("both panel and backdrop keep a phone swipe from starting on them", () => {
const html = renderToString(
<SidePanel side="left" open onClose={onClose} label="Bots">
<p>crew</p>
</SidePanel>,
);
expect(html.match(/data-no-swipe/g)?.length).toBe(2);
});
test("a panel that is also part of the page is never inert", () => {
const html = renderToString(
<SidePanel
side="left"
open={false}
onClose={onClose}
label="Bots"
inertWhenClosed={false}
>
<p>crew</p>
</SidePanel>,
);
expect(html).not.toContain("inert");
expect(html).not.toContain('aria-hidden="true"');
});
test("the caller's classes win over the panel's own", () => {
const html = renderToString(
<SidePanel
side="left"
open
onClose={onClose}
label="Bots"
className="md:static md:w-16"
backdropClassName="md:hidden"
>
<p>crew</p>
</SidePanel>,
);
expect(html).toContain("md:w-16");
expect(html).toContain("md:hidden");
});
});
+78
View File
@@ -0,0 +1,78 @@
"use client";
import type { ReactNode } from "react";
import Stack from "@moduletrace/twui/layout/Stack";
import { twMerge } from "tailwind-merge";
type Props = {
/** Which edge it slides in from. */
side: "left" | "right";
open: boolean;
onClose: () => void;
/** What it holds, for a screen reader. */
label: string;
className?: string;
backdropClassName?: string;
/**
* Whether the closed panel is hidden from screen readers and untabbed.
* On, unless the panel is also a permanent part of the page (`false`
* for the rail, which is the inline rail from `md` up).
*/
inertWhenClosed?: boolean;
children: ReactNode;
};
const Edges = {
left: { place: "left-0 border-r", closed: "-translate-x-full" },
right: { place: "right-0 border-l", closed: "translate-x-full" },
};
/**
* A panel that slides in from an edge over the page, with a dimmed backdrop
* that closes it. Panel and backdrop are always mounted, as the rail is, so
* the panel slides both ways instead of appearing and vanishing: nothing has
* to wait on a timer for an exit to play.
*
* The panel carries `data-no-swipe`, so a phone's sideways swipes never
* start on it or on its backdrop: what is open stays the one on top.
*/
export default function SidePanel({
side,
open,
onClose,
label,
className,
backdropClassName,
inertWhenClosed = true,
children,
}: Props) {
const edge = Edges[side];
const hidden = !open && inertWhenClosed;
return (
<>
{open ? (
<Stack
aria-hidden
data-no-swipe
onClick={onClose}
className={twMerge("fixed inset-0 z-30 bg-ink/40", backdropClassName)}
/>
) : null}
<Stack
aria-label={label}
aria-hidden={hidden || undefined}
inert={hidden}
data-no-swipe
className={twMerge(
"fixed inset-y-0 z-40 w-[280px] max-w-[85vw] shrink-0 h-full gap-0! items-stretch bg-paper border-0 border-solid border-hairline shadow-popover transition-transform duration-[var(--m-base)] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",
edge.place,
open ? "translate-x-0" : edge.closed,
className,
)}
>
{children}
</Stack>
</>
);
}
+16
View File
@@ -1037,6 +1037,22 @@ export const AppData = {
* the server answers at once still says it happened.
*/
PullToRefreshMinLoadingMs: 1000,
/**
* The phone's sideways swipes, anywhere on a page, in pixels: how far
* the finger travels before the drag counts as a swipe at all
* (`MobileSwipeMinPx`), and how much more sideways than up or down it
* has to be (`MobileSwipeAxisRatio`), so a diagonal drag that is
* mostly scrolling stays a scroll.
*/
MobileSwipeMinPx: 50,
MobileSwipeAxisRatio: 1.5,
/**
* How long the finger may be down before the drag stops counting as a
* swipe, in milliseconds: a swipe is a flick, while a finger that has
* rested on the page is scrolling, selecting text or reaching for a
* quote, not changing panes.
*/
MobileSwipeMaxMs: 800,
/**
* The most model calls a message's details modal lists one by one. A
* long task can take hundreds; the totals still count every one.
+153
View File
@@ -0,0 +1,153 @@
"use client";
import { useEffect, useRef } from "react";
import { AppData } from "@/src/data/app-data";
import swipeGesture, {
IdleSwipeGesture,
type SwipeGesture,
} from "@/src/utils/swipe-gesture";
/**
* Below this width the rail is a slide-over (Tailwind's `md`), so the
* swipes that open it and the bot panel are the phone's alone: from `md` up
* the rail is already inline and a mouse drag is selection.
*/
const PhoneMaxWidth = 768;
/**
* What a touch on belongs to instead of the page: a field being typed in,
* a code editor, or a panel the app slid in itself.
*/
const OwnedTargets =
"input, textarea, select, [contenteditable='true'], .cm-editor, [data-no-swipe]";
type Params = {
/**
* False while a side panel is already open: a swipe on the open drawer
* must not open the other one above it.
*/
enabled: boolean;
on_swipe_left: () => void;
on_swipe_right: () => void;
};
/**
* A touch that belongs to something other than the page: a field, a box
* that scrolls sideways on its own (a wide code block, a table, a strip of
* images), or anything inside a panel the app slid in.
*/
function ownsTouch({ target }: { target: EventTarget | null }): boolean {
if (!(target instanceof Element)) return true;
if (target.closest(OwnedTargets)) return true;
for (let node: Element | null = target; node; node = node.parentElement) {
const style = getComputedStyle(node);
if (!/auto|scroll/.test(style.overflowX)) continue;
if (node.scrollWidth > node.clientWidth + 2) return true;
}
return false;
}
/**
* The phone's two sideways swipes, read anywhere on the page: a drag to the
* right opens the rail's drawer, a drag to the left the bot panel. They are
* flicks: a long drag, one that is mostly up or down, one that selects
* text, one on a field or on something that scrolls sideways, and one
* landing while a modal is up all belong to whatever they landed on, and
* so do all the swipes while the drawer is open or the screen is wider
* than a phone.
*
* The thresholds and the state machine live in `swipe-gesture.ts`, proven
* without a browser; this reads the finger and calls back.
*/
export default function useHorizontalSwipe({
enabled,
on_swipe_left,
on_swipe_right,
}: Params) {
const on = useRef(enabled);
const left = useRef(on_swipe_left);
const right = useRef(on_swipe_right);
on.current = enabled;
left.current = on_swipe_left;
right.current = on_swipe_right;
useEffect(() => {
let gesture: SwipeGesture = IdleSwipeGesture;
let touched_at = 0;
const restart = () => {
gesture = IdleSwipeGesture;
};
const onStart = (event: TouchEvent) => {
restart();
if (!on.current) return;
if (window.innerWidth >= PhoneMaxWidth) return;
if (event.touches.length != 1) return;
if (document.getElementById("twui-modal-root")?.childElementCount) return;
if (ownsTouch({ target: event.target })) return;
const touch = event.touches[0];
if (!touch) return;
touched_at = Date.now();
gesture = swipeGesture({
gesture: IdleSwipeGesture,
input: { type: "start", x: touch.clientX, y: touch.clientY },
}).gesture;
};
const onMove = (event: TouchEvent) => {
if (!gesture.touching) return;
const touch = event.touches[0];
if (!touch || event.touches.length != 1) {
restart();
return;
}
/**
* A finger that has rested on the page is selecting text or
* reaching for a quote, not changing panes.
*/
if (Date.now() - touched_at > AppData.MobileSwipeMaxMs) {
restart();
return;
}
if (window.getSelection()?.toString()) {
restart();
return;
}
const step = swipeGesture({
gesture,
input: { type: "move", x: touch.clientX, y: touch.clientY },
});
gesture = step.gesture;
if (step.swipe == "right") right.current();
if (step.swipe == "left") left.current();
};
window.addEventListener("touchstart", onStart, { passive: true });
window.addEventListener("touchmove", onMove, { passive: true });
window.addEventListener("touchend", restart);
window.addEventListener("touchcancel", restart);
return () => {
window.removeEventListener("touchstart", onStart);
window.removeEventListener("touchmove", onMove);
window.removeEventListener("touchend", restart);
window.removeEventListener("touchcancel", restart);
};
}, []);
}
+11 -2
View File
@@ -11,13 +11,22 @@ const OpenModals: string[] = [];
* a file) would take both away. Listening first, on the window's capture
* phase, the modal on top closes itself and the press goes no further.
*/
export default function useTopModalEscape({ onClose }: { onClose: () => void }) {
export default function useTopModalEscape({
onClose,
enabled = true,
}: {
onClose: () => void;
/** Off while the modal only exists on the page, closed (`SidePanel`). */
enabled?: boolean;
}) {
const id = useId();
const close_ref = useRef(onClose);
close_ref.current = onClose;
useEffect(() => {
if (!enabled) return;
OpenModals.push(id);
const onKey = (event: KeyboardEvent) => {
@@ -36,5 +45,5 @@ export default function useTopModalEscape({ onClose }: { onClose: () => void })
if (index >= 0) OpenModals.splice(index, 1);
};
}, [id]);
}, [id, enabled]);
}
+44 -47
View File
@@ -15,6 +15,7 @@ import RailCrewList from "../(partials)/rail-crew-list";
import RailSettingsAside from "../(partials)/rail-settings-aside";
import RailUserRow from "../(partials)/rail-user-row";
import RailWorkspaceList from "../(partials)/rail-workspace-list";
import SidePanel from "@/src/components/general/side-panel";
/**
* Left rail: wordmark and Add, then the crew (pinned coordinator first,
@@ -53,55 +54,51 @@ export default function BotsRail() {
});
const live_workspace = workspaces.find((w) => w.id == workspace?.id);
/**
* The rail is the page's own from `md` up, so the closed state only
* hides it on a phone.
*/
return (
<>
{open ? (
<Stack
aria-hidden
onClick={() => setOpen(false)}
className="fixed inset-0 z-30 bg-ink/40 md:hidden"
/>
<SidePanel
side="left"
open={open}
onClose={() => setOpen(false)}
inertWhenClosed={false}
backdropClassName="md:hidden"
className="@container md:static md:z-auto md:w-16 md:max-w-none md:shadow-none md:pt-0 md:pb-0 xl:w-[320px] md:translate-x-0"
label={
is_settings_page
? "Settings"
: in_workspace
? workspace?.name || "Workspace"
: "Bots"
}
>
<RailHeader show_add={!is_settings_page && !is_rail_page} />
{(is_settings_page || is_rail_page) && pageProps?.last_conversation ? (
<RailLastConversation conversation={pageProps.last_conversation} />
) : null}
<Stack
className={`@container fixed inset-y-0 left-0 z-40 w-[280px] max-w-[85vw] shrink-0 h-full gap-0! items-stretch bg-paper border-0 border-r border-solid border-hairline shadow-popover transition-transform duration-[var(--m-base)] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)] md:static md:z-auto md:w-16 md:max-w-none md:shadow-none md:pt-0 md:pb-0 xl:w-[320px] ${
open
? "translate-x-0"
: "-translate-x-full md:translate-x-0"
}`}
aria-label={
is_settings_page
? "Settings"
: in_workspace
? workspace?.name || "Workspace"
: "Bots"
}
>
<RailHeader show_add={!is_settings_page && !is_rail_page} />
{(is_settings_page || is_rail_page) && pageProps?.last_conversation ? (
<RailLastConversation conversation={pageProps.last_conversation} />
) : null}
<Stack className="grow min-h-0 overflow-y-auto gap-0! items-stretch px-2 @rail:px-3 pt-1 pb-3">
{is_settings_page ? (
<RailSettingsAside pathname={pathname} />
) : is_rail_page ? (
<RailPagesList pathname={pathname} />
) : in_workspace && live_workspace ? (
<RailWorkspaceList
workspace={live_workspace}
bots={bots}
selected_id={pageProps?.bot?.id || undefined}
on_workspace_page={pathname == `/admin/workspaces/${workspace?.id}`}
/>
) : (
<RailCrewList
bots={bots}
workspaces={workspaces}
selected_id={pageProps?.bot?.id || undefined}
/>
)}
</Stack>
<RailUserRow />
<Stack className="grow min-h-0 overflow-y-auto gap-0! items-stretch px-2 @rail:px-3 pt-1 pb-3">
{is_settings_page ? (
<RailSettingsAside pathname={pathname} />
) : is_rail_page ? (
<RailPagesList pathname={pathname} />
) : in_workspace && live_workspace ? (
<RailWorkspaceList
workspace={live_workspace}
bots={bots}
selected_id={pageProps?.bot?.id || undefined}
on_workspace_page={pathname == `/admin/workspaces/${workspace?.id}`}
/>
) : (
<RailCrewList
bots={bots}
workspaces={workspaces}
selected_id={pageProps?.bot?.id || undefined}
/>
)}
</Stack>
</>
<RailUserRow />
</SidePanel>
);
}
+19 -1
View File
@@ -6,6 +6,8 @@ import Row from "@moduletrace/twui/layout/Row";
import { AppContext } from "@/src/pages/__root";
import useConnectionEpoch from "@/src/hooks/use-connection-epoch";
import useOnlineStatus from "@/src/hooks/use-online-status";
import useHorizontalSwipe from "@/src/hooks/use-horizontal-swipe";
import requestBotPanel from "@/src/utils/bot-panel-open-event";
import { RailDrawerContext } from "./(data)/rail-drawer-context";
import BotsRail from "./(sections)/bots-rail";
import LiveSocket from "./(sections)/live-socket";
@@ -21,7 +23,9 @@ import railWorkspaceId from "./(utils)/rail-workspace-id";
* settings), inside the Add flow both can open. A graphic's own page
* (`isRaillessPage`) goes without the rail. No cards, no shadows;
* regions are separated by 1px hairlines. Below `md` the rail slides over
* the page instead of taking width. Height is `dvh`, so the on-screen
* the page instead of taking width, and two swipes anywhere on the page
* move between panes: to the right opens the rail's drawer, to the left the
* conversation's bot panel. Height is `dvh`, so the on-screen
* keyboard doesn't push the composer out of view.
*/
export default function BotsLayout({
@@ -56,6 +60,20 @@ export default function BotsLayout({
const has_rail = !isRaillessPage({ pathname });
/**
* The phone's sideways swipes: right opens the rail's drawer, left asks
* the page for its bot panel (`cobble:open-bot-panel`, which the
* conversation's header answers). Neither runs while the drawer is
* open, so a swipe on it cannot open the other panel above it.
*/
useHorizontalSwipe({
enabled: !drawer_open,
on_swipe_right: () => {
if (has_rail) setDrawerOpen(true);
},
on_swipe_left: () => requestBotPanel(),
});
/**
* The crew the rail lists, read again whenever the user comes back to
* the page: pushes that never arrived leave it stale until a reload.
@@ -0,0 +1,75 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import type {
AppContextObject,
BotWithLastMessage,
PagePropsType,
} from "@/src/types";
import { AppContext } from "@/src/pages/__root";
import BotPanelName from "./bot-panel-name";
function bot(overrides: Partial<BotWithLastMessage> = {}): BotWithLastMessage {
return {
id: 5,
name: "Assistant",
color: "#33c9cc",
stone: "ember",
face: "idle",
...overrides,
} as BotWithLastMessage;
}
type RenderProps = {
user_type: string;
name?: string;
};
/**
* The name is the header's heading either way; only a crew manager's is a
* button that opens the bot's panel.
*/
function render({ user_type, name = "Assistant" }: RenderProps) {
const pageProps: PagePropsType = {
url: { pathname: "/admin/bots/5" } as PagePropsType["url"],
user_types: [{ user_type }] as PagePropsType["user_types"],
};
return renderToString(
<AppContext.Provider value={{ pageProps } as AppContextObject}>
<BotPanelName bot={bot({ name })} on_open={() => {}} />
</AppContext.Provider>,
);
}
describe("BotPanelName", () => {
test("a member reads the name as a plain heading", () => {
const html = render({ user_type: "member" });
expect(html).toContain("<h1");
expect(html).toContain(">Assistant<");
expect(html).not.toContain("<button");
expect(html).not.toContain('aria-haspopup="dialog"');
});
test("a crew manager's name is a button that opens the panel", () => {
const html = render({ user_type: "super_admin" });
expect(html).toContain("<h1");
expect(html).toContain("<button");
expect(html).toContain('aria-haspopup="dialog"');
expect(html).toContain('aria-label="Edit Assistant"');
});
test("the name itself still shows, so the heading reads right", () => {
const html = render({ user_type: "admin", name: "Software Engineer" });
expect(html).toContain(">Software Engineer<");
expect(html).toContain('aria-label="Edit Software Engineer"');
});
test("an unnamed bot is called this bot in the button's label", () => {
const html = render({ user_type: "super_admin", name: "" });
expect(html).toContain('aria-label="Edit This bot"');
});
});
@@ -0,0 +1,50 @@
"use client";
import { useContext } from "react";
import H1 from "@moduletrace/twui/layout/H1";
import Span from "@moduletrace/twui/layout/Span";
import Button from "@moduletrace/twui/layout/Button";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import type { BotWithLastMessage } from "@/src/types";
type Props = {
bot: BotWithLastMessage;
on_open: () => void;
};
/**
* The conversation's name: the page's heading, and for super admins and
* admins a second way into the bot's panel, beside its avatar. Everyone else
* reads the name alone.
*/
export default function BotPanelName({ bot, on_open }: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
if (!can_edit) {
return (
<H1 className="min-w-0 text-lg! leading-6! tracking-normal! font-bold text-ink truncate line-clamp-1">
{bot.name}
</H1>
);
}
return (
<H1 className="min-w-0 text-lg! leading-6! tracking-normal! font-bold text-ink">
<Button
title={`Edit ${name}`}
type="button"
variant="ghost"
color="text"
aria-haspopup="dialog"
onClick={on_open}
buttonContentProps={{ className: "min-w-0 gap-0!" }}
className="min-w-0 max-w-full justify-start px-0! py-0! text-lg! leading-6! tracking-normal! font-bold! text-ink! text-left rounded-default hover:bg-transparent! hover:opacity-80 focus-visible:ring-2 focus-visible:ring-ink"
>
<Span className="min-w-0 truncate">{bot.name}</Span>
</Button>
</H1>
);
}
@@ -0,0 +1,54 @@
"use client";
import { useContext } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Stack from "@moduletrace/twui/layout/Stack";
import BotAvatar from "@/src/components/general/bot-avatar";
import type { BotFace } from "@/src/dict/bot-dict";
import botStoneProps from "@/src/utils/bot-stone-props";
import type { BotWithLastMessage } from "@/src/types";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
type Props = {
bot: BotWithLastMessage;
on_open: () => void;
};
/**
* The avatar beside the conversation's name: opens the bot's panel to edit
* it, for super admins and admins. Everyone else sees the avatar alone.
*/
export default function BotPanelTrigger({ bot, on_open }: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const avatar = (
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
face={(bot.face || "idle") as BotFace}
size={35}
/>
);
if (!can_edit) {
return <Stack className="shrink-0">{avatar}</Stack>;
}
return (
<Button
title={`Edit ${name}`}
type="button"
variant="ghost"
color="text"
aria-label={`Edit ${name}`}
aria-haspopup="dialog"
onClick={on_open}
className="shrink-0 p-0! rounded-default hover:opacity-80 focus-visible:ring-2 focus-visible:ring-ink focus-visible:ring-offset-2 focus-visible:ring-offset-paper"
>
{avatar}
</Button>
);
}
@@ -0,0 +1,129 @@
"use client";
import { useContext, useEffect } from "react";
import Button from "@moduletrace/twui/layout/Button";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import Loading from "@moduletrace/twui/elements/Loading";
import { X } from "lucide-react";
import SidePanel from "@/src/components/general/side-panel";
import BotAvatar from "@/src/components/general/bot-avatar";
import type { BotFace } from "@/src/dict/bot-dict";
import botStoneProps from "@/src/utils/bot-stone-props";
import { BotPanelOpenEvent } from "@/src/utils/bot-panel-open-event";
import type { BotWithLastMessage } from "@/src/types";
import BotForm from "@/src/layouts/bots/(partials)/bot-form";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import useBotInstructions from "../(hooks)/use-bot-instructions";
import BotPanelTrigger from "./bot-panel-trigger";
type Props = {
bot: BotWithLastMessage;
/**
* The header owns it, since the avatar and the name both open the panel.
*/
open: boolean;
on_open: () => void;
on_close: () => void;
};
/**
* The bot's profile (picture, name, job, colour, instructions) to edit,
* sliding in from the right over the conversation, for super admins and
* admins. The avatar and the name beside it open it, and so does a swipe from
* the right on a phone (`BotPanelOpenEvent`, sent by the layout, so a page
* without a conversation has nobody listening). The instructions load when
* it opens, and Escape, the backdrop or the X closes it.
*/
export default function BotPanel({ bot, open, on_open, on_close }: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const { system_prompt, error } = useBotInstructions({
bot_id: Number(bot.id) || 0,
enabled: open && can_edit,
});
useTopModalEscape({ onClose: on_close, enabled: open });
useEffect(() => {
if (!can_edit) return;
const openPanel = () => on_open();
window.addEventListener(BotPanelOpenEvent, openPanel);
return () => window.removeEventListener(BotPanelOpenEvent, openPanel);
}, [can_edit, on_open]);
/**
* A swipe from the right is a request for the panel, but a bot that
* cannot be edited keeps the avatar plain: a slide-over holding nothing
* would be worse than nothing happening.
*/
if (!can_edit) {
return <BotPanelTrigger bot={bot} on_open={() => {}} />;
}
return (
<>
<BotPanelTrigger bot={bot} on_open={on_open} />
<SidePanel
side="right"
open={open}
onClose={on_close}
label={`Edit ${name}`}
className="w-[420px] max-w-[92vw]"
>
<Row className="shrink-0 gap-3! flex-nowrap items-center px-4 py-3 border-0 border-b border-solid border-hairline">
<Stack className="shrink-0">
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
face={(bot.face || "idle") as BotFace}
size={35}
/>
</Stack>
<H2 className="min-w-0 grow text-lg! leading-6! tracking-normal! font-bold text-ink truncate">
{`Edit ${name}`}
</H2>
<Button
title="Close"
type="button"
variant="ghost"
color="text"
aria-label="Close"
onClick={on_close}
className="shrink-0 p-2! text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink"
>
<X size={18} aria-hidden />
</Button>
</Row>
<Stack className="grow min-h-0 overflow-y-auto gap-1! items-stretch px-4 pt-4 pb-6">
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{bot.kind == "coordinator"
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
</Span>
{!open ? null : system_prompt != undefined ? (
<BotForm
bot={{ ...bot, system_prompt }}
onCancel={on_close}
/>
) : error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</Stack>
</SidePanel>
</>
);
}
@@ -1,87 +0,0 @@
import { useContext, useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import Loading from "@moduletrace/twui/elements/Loading";
import Button from "@moduletrace/twui/layout/Button";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import BotAvatar from "@/src/components/general/bot-avatar";
import type { BotFace } from "@/src/dict/bot-dict";
import botStoneProps from "@/src/utils/bot-stone-props";
import type { BotWithLastMessage } from "@/src/types";
import BotForm from "@/src/layouts/bots/(partials)/bot-form";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import useBotInstructions from "../(hooks)/use-bot-instructions";
type Props = {
bot: BotWithLastMessage;
};
/**
* The header's avatar: opens the bot's profile (picture, name, job,
* colour, instructions) to edit, for super admins and admins. Everyone
* else sees the avatar alone. The instructions load when it opens.
*/
export default function BotProfileModal({ bot }: Props) {
const { pageProps } = useContext(AppContext);
const [open, setOpen] = useState(false);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const { system_prompt, error } = useBotInstructions({
bot_id: Number(bot.id) || 0,
enabled: open && can_edit,
});
const avatar = (
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
face={(bot.face || "idle") as BotFace}
size={35}
/>
);
if (!can_edit) {
return <Stack className="shrink-0">{avatar}</Stack>;
}
return (
<Modal
target={
<Button
title={`Edit ${name}`}
type="button"
variant="ghost"
color="text"
aria-label={`Edit ${name}`}
className="shrink-0 p-0! rounded-default hover:opacity-80 focus-visible:ring-2 focus-visible:ring-ink focus-visible:ring-offset-2 focus-visible:ring-offset-paper"
>
{avatar}
</Button>
}
targetWrapperProps={{ className: "shrink-0" }}
open={open}
setOpen={setOpen}
className="max-w-lg bg-paper p-6"
>
<Stack className="w-full gap-1! items-stretch">
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">{`Edit ${name}`}</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{bot.kind == "coordinator"
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
</Span>
</Stack>
{!open ? null : system_prompt != undefined ? (
<BotForm bot={{ ...bot, system_prompt }} onCancel={() => setOpen(false)} />
) : error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">{error}</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</Modal>
);
}
@@ -1,7 +1,6 @@
import { useContext, useEffect, useState } from "react";
import { useCallback, useContext, useEffect, useState } from "react";
import Row from "@moduletrace/twui/layout/Row";
import Stack from "@moduletrace/twui/layout/Stack";
import H1 from "@moduletrace/twui/layout/H1";
import Span from "@moduletrace/twui/layout/Span";
import Button from "@moduletrace/twui/layout/Button";
import Dropdown from "@moduletrace/twui/elements/Dropdown";
@@ -18,7 +17,8 @@ import { AppContext } from "@/src/pages/__root";
import WorkspaceAvatar from "@/src/components/general/workspace-avatar";
import RailDrawerButton from "@/src/layouts/bots/(partials)/rail-drawer-button";
import { BotComputersContext } from "../(data)/bot-computers-context";
import BotProfileModal from "./bot-profile-modal";
import BotPanel from "./bot-panel";
import BotPanelName from "./bot-panel-name";
import BotModelsModal from "./bot-models-modal";
import BotComputersModal from "./bot-computers-modal";
import ConversationHeaderMenu from "./conversation-header-menu";
@@ -51,7 +51,8 @@ type Props = {
* computer it's on. On the right, one menu
* holding everything the header used to show as icons: sessions, a new
* session, the computer, the models and the bot's settings. Kept here so a
* save or a switch shows under the name at once.
* save or a switch shows under the name at once. The avatar and the name both
* open the bot's panel, slid in over the conversation.
*/
export default function ConversationHeader({
bot,
@@ -73,6 +74,13 @@ export default function ConversationHeader({
setIsAdmin(Boolean(bot.is_admin));
}, [bot.is_admin]);
const { open: open_menu, setOpen: set_open_menu } = useStatus();
/**
* The bot's panel, slid in from the right: its avatar, its name or a
* swipe bring it.
*/
const [bot_panel_open, set_bot_panel_open] = useState(false);
const open_bot_panel = useCallback(() => set_bot_panel_open(true), []);
const close_bot_panel = useCallback(() => set_bot_panel_open(false), []);
const computer = computers[0];
const computer_name = computer?.id
? computer.name || `Computer ${computer.id}`
@@ -98,12 +106,15 @@ export default function ConversationHeader({
<Row className="h-16 shrink-0 gap-2! md:gap-3! flex-nowrap items-center px-3 md:px-6 border-0 border-b border-solid border-hairline">
<RailDrawerButton />
{is_workspace ? <BackButton /> : null}
<BotProfileModal bot={bot} />
<BotPanel
bot={bot}
open={bot_panel_open}
on_open={open_bot_panel}
on_close={close_bot_panel}
/>
<Stack className="min-w-0 gap-0!">
<Row className="w-full min-w-0 gap-1.5! flex-nowrap">
<H1 className="min-w-0 text-lg! leading-6! tracking-normal! font-bold text-ink truncate line-clamp-1">
{bot.name}
</H1>
<BotPanelName bot={bot} on_open={open_bot_panel} />
{plan_mode ? (
<Tag
color="success"
+21
View File
@@ -0,0 +1,21 @@
import { describe, expect, test } from "bun:test";
import requestBotPanel, { BotPanelOpenEvent } from "./bot-panel-open-event";
describe("requestBotPanel", () => {
test("announces that the panel should open", () => {
const target = new EventTarget();
let heard = 0;
target.addEventListener(BotPanelOpenEvent, () => {
heard += 1;
});
requestBotPanel({ target });
expect(heard).toBe(1);
expect(BotPanelOpenEvent).toBe("cobble:open-bot-panel");
});
test("says nothing to a target that isn't there", () => {
expect(() => requestBotPanel({ target: null })).not.toThrow();
});
});
+17
View File
@@ -0,0 +1,17 @@
export const BotPanelOpenEvent = "cobble:open-bot-panel";
type Params = {
target?: EventTarget | null;
};
/**
* Asks the page to slide its bot panel in, the way the avatar beside the
* conversation's name does: a swipe from the right on a phone. The layout
* sends it from outside the conversation, so a page without one (a
* graphic's own page, settings) simply has nobody listening.
*/
export default function requestBotPanel({
target = typeof window == "undefined" ? null : window,
}: Params = {}) {
target?.dispatchEvent(new Event(BotPanelOpenEvent));
}
+107
View File
@@ -0,0 +1,107 @@
import { describe, expect, test } from "bun:test";
import swipeGesture, { IdleSwipeGesture, type SwipeGesture } from "./swipe-gesture";
function started({ x = 0, y = 0 }: { x?: number; y?: number } = {}): SwipeGesture {
return swipeGesture({ gesture: IdleSwipeGesture, input: { type: "start", x, y } }).gesture;
}
function dragged({ gesture, x, y }: { gesture: SwipeGesture; x: number; y: number }) {
return swipeGesture({ gesture, input: { type: "move", x, y } });
}
describe("swipeGesture", () => {
test("says nothing before a finger is down", () => {
expect(swipeGesture({ gesture: IdleSwipeGesture, input: { type: "move", x: 200, y: 0 } })).toEqual({
gesture: IdleSwipeGesture,
swipe: null,
});
});
test("a short drag decides nothing", () => {
const step = dragged({ gesture: started(), x: 20, y: 5 });
expect(step.swipe).toBeNull();
expect(step.gesture.decided).toBeNull();
expect(step.gesture.touching).toBe(true);
});
test("a drag far enough sideways is a swipe to that side", () => {
const right = dragged({ gesture: started(), x: 60, y: 10 });
expect(right.swipe).toBe("right");
const left = dragged({ gesture: started({ x: 300 }), x: 240, y: 10 });
expect(left.swipe).toBe("left");
});
test("a swipe fires on the exact minimum and not a pixel short of it", () => {
expect(dragged({ gesture: started(), x: 49, y: 0 }).swipe).toBeNull();
expect(dragged({ gesture: started(), x: 50, y: 0 }).swipe).toBe("right");
});
test("a drag that is mostly up or down locks the gesture to scrolling", () => {
const step = dragged({ gesture: started(), x: 5, y: 60 });
expect(step.swipe).toBeNull();
expect(step.gesture.decided).toBe("vertical");
});
test("a scroll never becomes a swipe, however far the finger drifts sideways afterwards", () => {
const scroll = dragged({ gesture: started(), x: 5, y: 60 }).gesture;
const drift = dragged({ gesture: scroll, x: 300, y: 70 });
expect(drift.swipe).toBeNull();
expect(drift.gesture.decided).toBe("vertical");
});
test("a diagonal drag waits until one direction clearly wins", () => {
const diagonal = dragged({ gesture: started(), x: 40, y: 45 });
expect(diagonal.swipe).toBeNull();
expect(diagonal.gesture.decided).toBeNull();
const resolved = dragged({ gesture: diagonal.gesture, x: 90, y: 50 });
expect(resolved.swipe).toBe("right");
});
test("a drag as far sideways as it is long fires no swipe", () => {
const step = dragged({ gesture: started(), x: 60, y: 50 });
expect(step.swipe).toBeNull();
expect(step.gesture.decided).toBeNull();
});
test("fires once: the rest of the finger's travel says nothing", () => {
const swiped = dragged({ gesture: started(), x: 80, y: 0 });
expect(swiped.swipe).toBe("right");
const further = dragged({ gesture: swiped.gesture, x: 200, y: 0 });
expect(further.swipe).toBeNull();
expect(further.gesture.decided).toBe("right");
});
test("lifting the finger starts over", () => {
const swiped = dragged({ gesture: started(), x: 80, y: 0 }).gesture;
const ended = swipeGesture({ gesture: swiped, input: { type: "end" } });
expect(ended.gesture).toEqual(IdleSwipeGesture);
expect(dragged({ gesture: ended.gesture, x: 200, y: 0 }).swipe).toBeNull();
});
test("a cancelled touch starts over too", () => {
const scroll = dragged({ gesture: started(), x: 0, y: 90 }).gesture;
expect(
swipeGesture({ gesture: scroll, input: { type: "cancel" } }).gesture,
).toEqual(IdleSwipeGesture);
});
test("the thresholds are the caller's to set", () => {
const step = swipeGesture({
gesture: started(),
input: { type: "move", x: 20, y: 2 },
min_px: 10,
axis_ratio: 1.2,
});
expect(step.swipe).toBe("right");
});
});
+98
View File
@@ -0,0 +1,98 @@
import { AppData } from "@/src/data/app-data";
/**
* The way one finger's drag across a page turned out: long enough
* sideways, and clearly more sideways than up or down, is a swipe; long
* enough up or down means the page's own scroll owns the gesture, and it
* stays that way until the finger lifts.
*/
export type SwipeDirection = "left" | "right" | "vertical";
export type SwipeGesture = {
/** A finger is down; nothing has been decided about its drag yet. */
touching: boolean;
start_x: number;
start_y: number;
/** What the drag is, once it has gone far enough to tell. */
decided: SwipeDirection | null;
};
export type SwipeInput =
| { type: "start"; x: number; y: number }
| { type: "move"; x: number; y: number }
| { type: "end" }
| { type: "cancel" };
export type SwipeStep = {
gesture: SwipeGesture;
/** The swipe this move handed over, once per gesture; null otherwise. */
swipe: "left" | "right" | null;
};
export const IdleSwipeGesture: SwipeGesture = {
touching: false,
start_x: 0,
start_y: 0,
decided: null,
};
type Params = {
gesture: SwipeGesture;
input: SwipeInput;
min_px?: number;
axis_ratio?: number;
};
/**
* One step of a phone's sideways swipe, as a plain function so its cases
* are proven without a browser. A drag decides once (`decided`): a swipe
* fires on the move that made it, and further moves of the same finger
* say nothing more.
*/
export default function swipeGesture({
gesture,
input,
min_px = AppData.MobileSwipeMinPx,
axis_ratio = AppData.MobileSwipeAxisRatio,
}: Params): SwipeStep {
if (input.type == "start") {
return {
gesture: {
touching: true,
start_x: input.x,
start_y: input.y,
decided: null,
},
swipe: null,
};
}
if (input.type == "end" || input.type == "cancel") {
return { gesture: IdleSwipeGesture, swipe: null };
}
if (!gesture.touching || gesture.decided) {
return { gesture, swipe: null };
}
const dx = input.x - gesture.start_x;
const dy = input.y - gesture.start_y;
const across = Math.abs(dx);
const along = Math.abs(dy);
if (across >= min_px && across >= along * axis_ratio) {
const swipe = dx > 0 ? "right" : "left";
return { gesture: { ...gesture, decided: swipe }, swipe };
}
/**
* A drag that is mostly up or down is the page's scroll: it stays
* un-decided as a swipe even if it later drifts sideways.
*/
if (along >= min_px && along > across) {
return { gesture: { ...gesture, decided: "vertical" }, swipe: null };
}
return { gesture, swipe: null };
}