feat(terminal): scroll mobile passthrough terminal scrollback via touch (#1046)
* feat(terminal): add touch-scroll helper for xterm scrollback Pure helper that translates single-finger vertical drags into `terminal.scrollLines(n)` calls. Handles threshold gating so taps still reach xterm, ignores multi-touch, yields to horizontal-dominant drags. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(terminal): wire mobile touch scrollback into passthrough terminal Adds an `enableTouchScroll` prop on PassthroughTerminal and a thin hook that calls `attachTouchScroll` while the terminal is mounted. The two mobile mount points (terminal panel + chat-panel passthrough embed) opt in; desktop callers are unaffected. Fixes the bug where xterm.js's canvas absorbed touch gestures and left the scrollback unreachable. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(terminal): mobile e2e for passthrough touch-scroll Pixel 5-emulated Playwright spec: produce 200 lines of output, simulate a single-finger down-swipe, assert `terminal.buffer.active.viewportY` moved into the scrollback, then swipe back to return. Extends the e2e buffer reader to expose viewportY alongside `__xtermReadBuffer`. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(terminal): relax mobile swipe-back assertion against late shell output Replace the exact `.toBe(bottomViewportY)` check with `.toBeGreaterThanOrEqual` so the test doesn't flake if shell echo arrives between the snapshot and the post-swipe read. xterm clamps at the buffer boundary, so overshooting back-to-bottom is impossible. Addresses PR #1046 Claude review thread 3293258085. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(terminal): document useTouchScroll's isTerminalReady invariant Adds a comment next to the eslint-disable explaining why the deps array can safely omit terminalRef/xtermRef: useTerminalInit only flips isTerminalReady false→true once per mount. A future refactor that recreates the terminal mid-mount must add a new dep. Addresses PR #1046 Claude review thread 3293258175. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore(terminal): clear all exposed buffer-reader fields on dispose clearBufferReader now nulls `__xtermGetFontFamily` and `__xtermGetFontSize` alongside the buffer readers. The two predated this PR and were never cleaned up; keeping the teardown symmetric with exposeBufferReader prevents stale references if the container is ever reused. Addresses PR #1046 Claude review thread 3293274674. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(terminal): reset document.body between touch-scroll cases Adds an afterEach to wipe jsdom's body so orphan divs from one test don't bleed into the next. Avoids cross-test pollution if a future case queries document.body for containers. Addresses PR #1046 Claude review thread 3293274769. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Kandev Agent <agent@kandev.dev> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -70,6 +70,7 @@ function TerminalSlot({
|
||||
autoFocus={isActive}
|
||||
disableWebgl
|
||||
manualInputRouting
|
||||
enableTouchScroll
|
||||
onXtermReady={setXterm}
|
||||
onWsReady={handleWsReady}
|
||||
/>
|
||||
|
||||
@@ -71,6 +71,7 @@ function MobileChatPanelContent({
|
||||
key={effectiveSessionId}
|
||||
sessionId={effectiveSessionId}
|
||||
mode="agent"
|
||||
enableTouchScroll
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
useSendInput,
|
||||
useFitAndResize,
|
||||
} from "./use-passthrough-terminal";
|
||||
import { useTouchScroll } from "./use-touch-scroll";
|
||||
import { useEnvironmentSessionId } from "@/hooks/use-environment-session-id";
|
||||
import { useTerminalSearch } from "./use-terminal-search";
|
||||
import { TerminalSearchBar } from "./terminal-search-bar";
|
||||
@@ -48,6 +49,10 @@ type BaseProps = {
|
||||
* Mobile uses this to register a key-bar sender that writes raw bytes
|
||||
* directly to this terminal's socket. */
|
||||
onWsReady?: (ws: WebSocket) => void;
|
||||
/** Translate single-finger touch swipes on the terminal area into xterm
|
||||
* scrollback navigation. Mobile callers set this so the xterm canvas no
|
||||
* longer silently absorbs touch gestures. */
|
||||
enableTouchScroll?: boolean;
|
||||
};
|
||||
type AgentTerminalProps = BaseProps & { mode: "agent"; sessionId?: string | null; label?: string };
|
||||
type ShellTerminalProps = BaseProps & {
|
||||
@@ -146,6 +151,7 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
|
||||
disableWebgl,
|
||||
manualInputRouting,
|
||||
onWsReady,
|
||||
enableTouchScroll,
|
||||
} = props;
|
||||
const terminalId = mode === "shell" ? props.terminalId : undefined;
|
||||
const environmentId = mode === "shell" ? props.environmentId : undefined;
|
||||
@@ -227,6 +233,13 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
|
||||
onFindInPanelRef,
|
||||
});
|
||||
|
||||
useTouchScroll({
|
||||
terminalRef: refs.terminalRef,
|
||||
xtermRef: refs.xtermRef,
|
||||
enabled: !!enableTouchScroll,
|
||||
isTerminalReady,
|
||||
});
|
||||
|
||||
useWebSocketConnection({
|
||||
taskId,
|
||||
sessionId,
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Terminal } from "@xterm/xterm";
|
||||
|
||||
type TerminalContainerWithBuffer = HTMLDivElement & {
|
||||
__xtermReadBuffer?: () => string;
|
||||
__xtermReadViewportY?: () => number;
|
||||
__xtermGetFontFamily?: () => string;
|
||||
__xtermGetFontSize?: () => number;
|
||||
};
|
||||
@@ -17,10 +18,15 @@ export function exposeBufferReader(container: HTMLDivElement, terminal: Terminal
|
||||
}
|
||||
return lines.join("\n");
|
||||
};
|
||||
c.__xtermReadViewportY = () => terminal.buffer.active.viewportY;
|
||||
c.__xtermGetFontFamily = () => terminal.options.fontFamily ?? "";
|
||||
c.__xtermGetFontSize = () => terminal.options.fontSize ?? 13;
|
||||
}
|
||||
|
||||
export function clearBufferReader(container: HTMLDivElement) {
|
||||
(container as TerminalContainerWithBuffer).__xtermReadBuffer = undefined;
|
||||
const c = container as TerminalContainerWithBuffer;
|
||||
c.__xtermReadBuffer = undefined;
|
||||
c.__xtermReadViewportY = undefined;
|
||||
c.__xtermGetFontFamily = undefined;
|
||||
c.__xtermGetFontSize = undefined;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useEffect } from "react";
|
||||
import type { Terminal } from "@xterm/xterm";
|
||||
import { attachTouchScroll } from "@/lib/terminal/touch-scroll";
|
||||
|
||||
export type TouchScrollOptions = {
|
||||
terminalRef: React.RefObject<HTMLDivElement | null>;
|
||||
xtermRef: React.MutableRefObject<Terminal | null>;
|
||||
/** When false, the hook is a no-op (desktop / non-mobile callers). */
|
||||
enabled: boolean;
|
||||
/** Gate to wait until the terminal instance has been created. */
|
||||
isTerminalReady: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wire touch-drag-to-scrollback on the terminal container while `enabled`.
|
||||
* No-op on desktop callers — touchstart/touchmove never fire from mouse input.
|
||||
*/
|
||||
export function useTouchScroll({
|
||||
terminalRef,
|
||||
xtermRef,
|
||||
enabled,
|
||||
isTerminalReady,
|
||||
}: TouchScrollOptions) {
|
||||
useEffect(() => {
|
||||
if (!enabled || !isTerminalReady) return;
|
||||
const container = terminalRef.current;
|
||||
const terminal = xtermRef.current;
|
||||
if (!container || !terminal) return;
|
||||
return attachTouchScroll(container, terminal);
|
||||
// Invariant: `useTerminalInit` creates the xterm instance once per mount
|
||||
// and only flips `isTerminalReady` from false → true. If a future change
|
||||
// ever recreates the terminal mid-mount, add the new identity as a dep so
|
||||
// the listener re-attaches to the new instance.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- refs are stable
|
||||
}, [enabled, isTerminalReady]);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// Routing: /t/{taskId} (task-keyed). File name starts with "mobile-" so it
|
||||
// runs on the mobile-chrome Playwright project (Pixel 5 emulation).
|
||||
//
|
||||
// Covers the bug: xterm.js's canvas absorbs touch events, so a vertical swipe
|
||||
// over the mobile terminal does nothing. The mobile passthrough wires the
|
||||
// container so single-finger drags translate into `terminal.scrollLines`.
|
||||
import { type Page, expect } from "@playwright/test";
|
||||
import { test } from "../../fixtures/test-base";
|
||||
import type { SeedData } from "../../fixtures/test-base";
|
||||
import type { ApiClient } from "../../helpers/api-client";
|
||||
import { SessionPage } from "../../pages/session-page";
|
||||
|
||||
async function seedTaskWithSession(
|
||||
testPage: Page,
|
||||
apiClient: ApiClient,
|
||||
seedData: SeedData,
|
||||
title: string,
|
||||
): Promise<SessionPage> {
|
||||
const task = await apiClient.createTaskWithAgent(
|
||||
seedData.workspaceId,
|
||||
title,
|
||||
seedData.agentProfileId,
|
||||
{
|
||||
description: "/e2e:simple-message",
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
},
|
||||
);
|
||||
await testPage.goto(`/t/${task.id}`);
|
||||
const session = new SessionPage(testPage);
|
||||
await session.waitForLoad();
|
||||
await session.waitForChatIdle();
|
||||
return session;
|
||||
}
|
||||
|
||||
async function switchToTerminalPanel(testPage: Page): Promise<void> {
|
||||
await testPage.getByRole("button", { name: "Terminal" }).tap();
|
||||
}
|
||||
|
||||
async function waitForShellReady(testPage: Page, timeout = 45_000): Promise<void> {
|
||||
await expect
|
||||
.poll(() => readTerminalBuffer(testPage).then((b) => b.length > 0), {
|
||||
timeout,
|
||||
message: "Waiting for mobile terminal shell to connect",
|
||||
})
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function readTerminalBuffer(page: Page): Promise<string> {
|
||||
return page.evaluate(() => {
|
||||
const panel = document.querySelector('[data-testid="terminal-panel"]');
|
||||
const xtermEl = panel?.querySelector(".xterm");
|
||||
type XC = HTMLElement & { __xtermReadBuffer?: () => string };
|
||||
const container = xtermEl?.parentElement as XC | null | undefined;
|
||||
return container?.__xtermReadBuffer?.() ?? "";
|
||||
});
|
||||
}
|
||||
|
||||
async function readViewportY(page: Page): Promise<number> {
|
||||
return page.evaluate(() => {
|
||||
const panel = document.querySelector('[data-testid="terminal-panel"]');
|
||||
const xtermEl = panel?.querySelector(".xterm");
|
||||
type XC = HTMLElement & { __xtermReadViewportY?: () => number };
|
||||
const container = xtermEl?.parentElement as XC | null | undefined;
|
||||
return container?.__xtermReadViewportY?.() ?? -1;
|
||||
});
|
||||
}
|
||||
|
||||
async function focusTerminalForTyping(session: SessionPage): Promise<void> {
|
||||
await session.terminal.locator(".xterm").click();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a synthetic single-finger swipe on the xterm container. We bypass
|
||||
* Playwright's touchscreen because the gesture coordinates need to be relative
|
||||
* to the .xterm element's bounding box, and we want guaranteed delivery
|
||||
* regardless of overlay z-index.
|
||||
*/
|
||||
async function swipe(
|
||||
page: Page,
|
||||
direction: "down" | "up",
|
||||
steps = 5,
|
||||
rowsToScroll = 8,
|
||||
): Promise<void> {
|
||||
await page.evaluate(
|
||||
({ direction, steps, rowsToScroll }) => {
|
||||
const panel = document.querySelector('[data-testid="terminal-panel"]');
|
||||
const xtermEl = panel?.querySelector(".xterm") as HTMLElement | null;
|
||||
if (!xtermEl) throw new Error("xterm element not found");
|
||||
const rect = xtermEl.getBoundingClientRect();
|
||||
const cx = rect.left + rect.width / 2;
|
||||
const startY = direction === "down" ? rect.top + 16 : rect.bottom - 16;
|
||||
const rowHeight = rect.height / 24;
|
||||
const totalDy = rowHeight * rowsToScroll * (direction === "down" ? 1 : -1);
|
||||
const stepDy = totalDy / steps;
|
||||
|
||||
const makeTouch = (clientX: number, clientY: number) =>
|
||||
({ clientX, clientY, identifier: 1 }) as unknown as Touch;
|
||||
const fire = (type: string, clientY: number) => {
|
||||
const event = new Event(type, { bubbles: true, cancelable: true }) as TouchEvent;
|
||||
const touches = [makeTouch(cx, clientY)];
|
||||
Object.defineProperty(event, "touches", { value: touches, configurable: true });
|
||||
Object.defineProperty(event, "changedTouches", { value: touches, configurable: true });
|
||||
xtermEl.dispatchEvent(event);
|
||||
};
|
||||
|
||||
fire("touchstart", startY);
|
||||
for (let i = 1; i <= steps; i++) {
|
||||
fire("touchmove", startY + stepDy * i);
|
||||
}
|
||||
fire("touchend", startY + totalDy);
|
||||
},
|
||||
{ direction, steps, rowsToScroll },
|
||||
);
|
||||
}
|
||||
|
||||
async function typeAndRun(page: Page, command: string): Promise<void> {
|
||||
await page.keyboard.type(command);
|
||||
await page.keyboard.press("Enter");
|
||||
}
|
||||
|
||||
test.describe("Mobile passthrough terminal — touch scroll", () => {
|
||||
test.describe.configure({ retries: 1 });
|
||||
|
||||
test("user swipes down on the terminal to scroll into scrollback, then up to return", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const session = await seedTaskWithSession(testPage, apiClient, seedData, "Touch scroll");
|
||||
await switchToTerminalPanel(testPage);
|
||||
await waitForShellReady(testPage);
|
||||
await focusTerminalForTyping(session);
|
||||
|
||||
// Produce enough output to populate the scrollback past one viewport.
|
||||
await typeAndRun(testPage, "for i in $(seq 1 200); do echo line $i; done");
|
||||
|
||||
await expect
|
||||
.poll(() => readTerminalBuffer(testPage), {
|
||||
timeout: 30_000,
|
||||
message: "Waiting for the 200th echo to land",
|
||||
})
|
||||
.toContain("line 200");
|
||||
|
||||
const bottomViewportY = await readViewportY(testPage);
|
||||
expect(bottomViewportY).toBeGreaterThan(0);
|
||||
|
||||
// Swipe down — finger drags down → reveals older lines → viewportY drops.
|
||||
await swipe(testPage, "down");
|
||||
|
||||
await expect
|
||||
.poll(() => readViewportY(testPage), {
|
||||
timeout: 5_000,
|
||||
message: "Downward swipe should scroll xterm into the scrollback (viewportY decreases)",
|
||||
})
|
||||
.toBeLessThan(bottomViewportY);
|
||||
|
||||
// Swipe up enough rows to return to the bottom of the buffer.
|
||||
await swipe(testPage, "up", 5, 50);
|
||||
|
||||
// Match-or-beat: any late shell output that arrives between captures bumps
|
||||
// the buffer's bottom further down, so the new viewportY may legitimately
|
||||
// exceed the snapshot. xterm clamps at the buffer boundary, so overshoot
|
||||
// is impossible.
|
||||
await expect
|
||||
.poll(() => readViewportY(testPage), {
|
||||
timeout: 5_000,
|
||||
message: "Upward swipe should return viewportY to the bottom",
|
||||
})
|
||||
.toBeGreaterThanOrEqual(bottomViewportY);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { attachTouchScroll, computeScrollLines } from "./touch-scroll";
|
||||
|
||||
afterEach(() => {
|
||||
// Each test appends a fresh container to document.body. Without this, jsdom
|
||||
// accumulates orphan divs across the suite and a future test that queries
|
||||
// document.body could pick up containers from prior runs.
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("computeScrollLines", () => {
|
||||
it("returns negative line count for a downward drag (reveal older)", () => {
|
||||
// 30px down with 10px per row → finger moved 3 rows → scroll 3 lines up.
|
||||
expect(computeScrollLines(30, 10)).toBe(-3);
|
||||
});
|
||||
|
||||
it("returns positive line count for an upward drag (reveal newer)", () => {
|
||||
expect(computeScrollLines(-25, 10)).toBe(2);
|
||||
});
|
||||
|
||||
it("rounds sub-row drags toward zero", () => {
|
||||
expect(computeScrollLines(9, 10)).toBe(0);
|
||||
expect(computeScrollLines(-9, 10)).toBe(0);
|
||||
});
|
||||
|
||||
it("returns 0 for non-finite or non-positive row heights", () => {
|
||||
expect(computeScrollLines(50, 0)).toBe(0);
|
||||
expect(computeScrollLines(50, -10)).toBe(0);
|
||||
expect(computeScrollLines(Number.NaN, 10)).toBe(0);
|
||||
expect(computeScrollLines(10, Number.NaN)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
type TerminalStub = { scrollLines: ReturnType<typeof vi.fn>; rows: number };
|
||||
|
||||
function makeContainer(): HTMLElement {
|
||||
const el = document.createElement("div");
|
||||
document.body.appendChild(el);
|
||||
return el;
|
||||
}
|
||||
|
||||
function makeTouch(clientX: number, clientY: number): Touch {
|
||||
// jsdom doesn't ship a Touch constructor; the structural shape is enough
|
||||
// for the handler, which only reads clientX/clientY/identifier.
|
||||
return { clientX, clientY, identifier: 1 } as unknown as Touch;
|
||||
}
|
||||
|
||||
function makeTouchEvent(type: string, touches: Touch[]): TouchEvent {
|
||||
const event = new Event(type, { bubbles: true, cancelable: true }) as TouchEvent;
|
||||
Object.defineProperty(event, "touches", { value: touches, configurable: true });
|
||||
Object.defineProperty(event, "changedTouches", { value: touches, configurable: true });
|
||||
return event;
|
||||
}
|
||||
|
||||
function fire(container: HTMLElement, type: string, touches: Touch[]): TouchEvent {
|
||||
const event = makeTouchEvent(type, touches);
|
||||
container.dispatchEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
describe("attachTouchScroll", () => {
|
||||
it("does not scroll or preventDefault for a single-finger drag below threshold", () => {
|
||||
const container = makeContainer();
|
||||
const terminal: TerminalStub = { scrollLines: vi.fn(), rows: 24 };
|
||||
const cleanup = attachTouchScroll(container, terminal, {
|
||||
threshold: 10,
|
||||
rowHeightFn: () => 10,
|
||||
});
|
||||
|
||||
fire(container, "touchstart", [makeTouch(50, 100)]);
|
||||
const move = fire(container, "touchmove", [makeTouch(50, 104)]);
|
||||
|
||||
expect(terminal.scrollLines).not.toHaveBeenCalled();
|
||||
expect(move.defaultPrevented).toBe(false);
|
||||
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it("scrolls into scrollback (negative lines) for a downward drag past threshold", () => {
|
||||
const container = makeContainer();
|
||||
const terminal: TerminalStub = { scrollLines: vi.fn(), rows: 24 };
|
||||
const cleanup = attachTouchScroll(container, terminal, {
|
||||
threshold: 6,
|
||||
rowHeightFn: () => 10,
|
||||
});
|
||||
|
||||
fire(container, "touchstart", [makeTouch(50, 100)]);
|
||||
// Drag 30px down — should scroll 3 lines into scrollback (-3).
|
||||
const move = fire(container, "touchmove", [makeTouch(50, 130)]);
|
||||
|
||||
expect(terminal.scrollLines).toHaveBeenCalledTimes(1);
|
||||
expect(terminal.scrollLines).toHaveBeenCalledWith(-3);
|
||||
expect(move.defaultPrevented).toBe(true);
|
||||
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it("scrolls toward newer output (positive lines) for an upward drag", () => {
|
||||
const container = makeContainer();
|
||||
const terminal: TerminalStub = { scrollLines: vi.fn(), rows: 24 };
|
||||
const cleanup = attachTouchScroll(container, terminal, {
|
||||
threshold: 6,
|
||||
rowHeightFn: () => 10,
|
||||
});
|
||||
|
||||
fire(container, "touchstart", [makeTouch(50, 200)]);
|
||||
fire(container, "touchmove", [makeTouch(50, 170)]);
|
||||
|
||||
expect(terminal.scrollLines).toHaveBeenCalledWith(3);
|
||||
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it("accumulates partial-row motion across successive move events", () => {
|
||||
const container = makeContainer();
|
||||
const terminal: TerminalStub = { scrollLines: vi.fn(), rows: 24 };
|
||||
const cleanup = attachTouchScroll(container, terminal, {
|
||||
threshold: 1,
|
||||
rowHeightFn: () => 10,
|
||||
});
|
||||
|
||||
fire(container, "touchstart", [makeTouch(50, 100)]);
|
||||
fire(container, "touchmove", [makeTouch(50, 115)]); // dy=15 → -1 line (5 px residual)
|
||||
fire(container, "touchmove", [makeTouch(50, 121)]); // 6 + 5 residual = 11 → -1 line
|
||||
fire(container, "touchmove", [makeTouch(50, 124)]); // residual + 3 → 4 → 0
|
||||
|
||||
expect(terminal.scrollLines).toHaveBeenNthCalledWith(1, -1);
|
||||
expect(terminal.scrollLines).toHaveBeenNthCalledWith(2, -1);
|
||||
expect(terminal.scrollLines).toHaveBeenCalledTimes(2);
|
||||
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it("ignores multi-touch (pinch) gestures", () => {
|
||||
const container = makeContainer();
|
||||
const terminal: TerminalStub = { scrollLines: vi.fn(), rows: 24 };
|
||||
const cleanup = attachTouchScroll(container, terminal, {
|
||||
threshold: 6,
|
||||
rowHeightFn: () => 10,
|
||||
});
|
||||
|
||||
fire(container, "touchstart", [makeTouch(50, 100), makeTouch(80, 100)]);
|
||||
const move = fire(container, "touchmove", [makeTouch(50, 130), makeTouch(80, 130)]);
|
||||
|
||||
expect(terminal.scrollLines).not.toHaveBeenCalled();
|
||||
expect(move.defaultPrevented).toBe(false);
|
||||
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it("yields to horizontal-dominant drags", () => {
|
||||
const container = makeContainer();
|
||||
const terminal: TerminalStub = { scrollLines: vi.fn(), rows: 24 };
|
||||
const cleanup = attachTouchScroll(container, terminal, {
|
||||
threshold: 6,
|
||||
rowHeightFn: () => 10,
|
||||
});
|
||||
|
||||
fire(container, "touchstart", [makeTouch(50, 100)]);
|
||||
// |dx|=40, |dy|=10 — horizontal dominates; no scroll, no preventDefault.
|
||||
const move = fire(container, "touchmove", [makeTouch(90, 110)]);
|
||||
|
||||
expect(terminal.scrollLines).not.toHaveBeenCalled();
|
||||
expect(move.defaultPrevented).toBe(false);
|
||||
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it("cleanup removes the listeners", () => {
|
||||
const container = makeContainer();
|
||||
const terminal: TerminalStub = { scrollLines: vi.fn(), rows: 24 };
|
||||
const cleanup = attachTouchScroll(container, terminal, {
|
||||
threshold: 6,
|
||||
rowHeightFn: () => 10,
|
||||
});
|
||||
|
||||
cleanup();
|
||||
|
||||
fire(container, "touchstart", [makeTouch(50, 100)]);
|
||||
fire(container, "touchmove", [makeTouch(50, 200)]);
|
||||
|
||||
expect(terminal.scrollLines).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import type { Terminal } from "@xterm/xterm";
|
||||
|
||||
/**
|
||||
* Translate touch swipes on an xterm.js container into scrollback navigation.
|
||||
*
|
||||
* xterm.js renders to a canvas under `.xterm-screen`; that canvas has the
|
||||
* default `pointer-events: auto` and absorbs touchstart/touchmove before they
|
||||
* can bubble to any ancestor scroll container. xterm itself does not wire
|
||||
* touch events to its scrollback API (`scrollLines`), so on a mobile viewport
|
||||
* the user has no way to review prior output.
|
||||
*
|
||||
* This module bridges that gap with a small touch handler that maps single-
|
||||
* finger vertical drag distance onto `terminal.scrollLines(n)`.
|
||||
*/
|
||||
|
||||
export type AttachTouchScrollOptions = {
|
||||
/** Minimum vertical drag (px) before we start treating the gesture as a
|
||||
* scroll. Below this, taps still reach xterm (focus / selection). */
|
||||
threshold?: number;
|
||||
/** Override row-height resolution for tests. Defaults to
|
||||
* container.clientHeight / terminal.rows. */
|
||||
rowHeightFn?: () => number;
|
||||
};
|
||||
|
||||
const DEFAULT_THRESHOLD_PX = 6;
|
||||
|
||||
/**
|
||||
* Compute the number of lines to scroll for a given vertical drag delta.
|
||||
*
|
||||
* Sign convention matches xterm's `scrollLines`: positive = scroll down toward
|
||||
* newer output, negative = scroll up into scrollback. A downward finger drag
|
||||
* (deltaY positive) reveals older lines, so we return a negative count.
|
||||
*
|
||||
* Sub-row drags round to 0 so the viewport doesn't flicker on micro-motion.
|
||||
*/
|
||||
export function computeScrollLines(deltaY: number, rowHeight: number): number {
|
||||
if (!Number.isFinite(deltaY) || !Number.isFinite(rowHeight) || rowHeight <= 0) {
|
||||
return 0;
|
||||
}
|
||||
// Drag down (positive deltaY) → reveal older lines → negative scrollLines.
|
||||
// `|| 0` normalises -0 from `-Math.trunc(0.x)` to a plain 0 so equality
|
||||
// checks (and callers' `lines !== 0` short-circuits) behave intuitively.
|
||||
return -Math.trunc(deltaY / rowHeight) || 0;
|
||||
}
|
||||
|
||||
type TouchScrollMinimalTerminal = Pick<Terminal, "scrollLines" | "rows">;
|
||||
|
||||
function defaultRowHeight(container: HTMLElement, terminal: TouchScrollMinimalTerminal): number {
|
||||
const rows = terminal.rows;
|
||||
if (!rows || rows <= 0) return 0;
|
||||
return container.clientHeight / rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach touch listeners to `container` that scroll `terminal` on vertical
|
||||
* drag. Returns a cleanup function.
|
||||
*
|
||||
* Behavior:
|
||||
* - Single-finger drag only — multi-touch (pinch/zoom) is ignored.
|
||||
* - Vertical-dominant only — if |dx| > |dy| we yield to the surrounding UI
|
||||
* (e.g. horizontal swipes on a sibling key-bar).
|
||||
* - `preventDefault` fires only after the drag passes `threshold` so a pure
|
||||
* tap still focuses xterm (via xterm's own click handler).
|
||||
* - Drag distance is quantized to whole rows; intermediate motion accumulates
|
||||
* in `lastY` so a slow drag still scrolls eventually.
|
||||
*/
|
||||
export function attachTouchScroll(
|
||||
container: HTMLElement,
|
||||
terminal: TouchScrollMinimalTerminal,
|
||||
opts: AttachTouchScrollOptions = {},
|
||||
): () => void {
|
||||
const threshold = opts.threshold ?? DEFAULT_THRESHOLD_PX;
|
||||
const rowHeightFn = opts.rowHeightFn ?? (() => defaultRowHeight(container, terminal));
|
||||
|
||||
let startX = 0;
|
||||
let startY = 0;
|
||||
let lastY = 0;
|
||||
let active = false;
|
||||
let crossedThreshold = false;
|
||||
|
||||
const onTouchStart = (event: TouchEvent) => {
|
||||
if (event.touches.length !== 1) {
|
||||
active = false;
|
||||
return;
|
||||
}
|
||||
const touch = event.touches[0];
|
||||
startX = touch.clientX;
|
||||
startY = touch.clientY;
|
||||
lastY = touch.clientY;
|
||||
active = true;
|
||||
crossedThreshold = false;
|
||||
};
|
||||
|
||||
const onTouchMove = (event: TouchEvent) => {
|
||||
if (!active) return;
|
||||
if (event.touches.length !== 1) {
|
||||
active = false;
|
||||
return;
|
||||
}
|
||||
const touch = event.touches[0];
|
||||
const dx = touch.clientX - startX;
|
||||
const dy = touch.clientY - startY;
|
||||
|
||||
if (!crossedThreshold) {
|
||||
if (Math.abs(dy) < threshold) return;
|
||||
// Horizontal-dominant — yield to sibling gestures (e.g. key-bar swipes).
|
||||
if (Math.abs(dx) > Math.abs(dy)) {
|
||||
active = false;
|
||||
return;
|
||||
}
|
||||
crossedThreshold = true;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
const rowHeight = rowHeightFn();
|
||||
const lines = computeScrollLines(touch.clientY - lastY, rowHeight);
|
||||
if (lines !== 0) {
|
||||
terminal.scrollLines(lines);
|
||||
// Consume the portion of the drag we just applied so the next move
|
||||
// event is relative to a fresh row boundary. We scrolled `lines` xterm
|
||||
// rows, which corresponds to `-lines * rowHeight` px of finger motion
|
||||
// (downward drag → negative lines → positive px consumed).
|
||||
lastY -= lines * rowHeight;
|
||||
}
|
||||
};
|
||||
|
||||
const onTouchEnd = () => {
|
||||
active = false;
|
||||
crossedThreshold = false;
|
||||
};
|
||||
|
||||
container.addEventListener("touchstart", onTouchStart, { passive: true });
|
||||
container.addEventListener("touchmove", onTouchMove, { passive: false });
|
||||
container.addEventListener("touchend", onTouchEnd, { passive: true });
|
||||
container.addEventListener("touchcancel", onTouchEnd, { passive: true });
|
||||
|
||||
return () => {
|
||||
container.removeEventListener("touchstart", onTouchStart);
|
||||
container.removeEventListener("touchmove", onTouchMove);
|
||||
container.removeEventListener("touchend", onTouchEnd);
|
||||
container.removeEventListener("touchcancel", onTouchEnd);
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user