A local-first multi-agent app development platform, built on PenguinHarness
feat(web,ui): 手机上能选中并复制终端里的文本
lmliheng06d8b0c0c256
diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.tsindex 8fb887bf..c340452c 100644--- a/packages/ui/src/components/icons/icons.ts+++ b/packages/ui/src/components/icons/icons.ts@@ -225,6 +225,11 @@ export const ICONS = {* returns with an arrow. The turn is the whole mark, so it keeps the full bulge.*/wrapText: "M4 6h16M4 12h12a3 3 0 1 1 0 6h-3m2-2-2 2 2 2M4 18h5",+ /**+ * A text cursor: the I-beam a text field shows over the character it would insert at, with+ * the serifs that tell it apart from a plain bar. The mark for selecting text by hand.+ */+ textCursor: "M9 5h6M12 5v14M9 19h6",// --- Messages and actions -----------------------------------------------------------------diff --git a/packages/web/e2e/terminal-touch.spec.mjs b/packages/web/e2e/terminal-touch.spec.mjsindex 724587c1..8ee91455 100644--- a/packages/web/e2e/terminal-touch.spec.mjs+++ b/packages/web/e2e/terminal-touch.spec.mjs@@ -4,6 +4,10 @@* reach the real pty — an arrow that types `[A` into the prompt, or a Ctrl that never* composes, looks like a working button and is not one — and that none of it appears where a* physical keyboard already exists.+ *+ * The same bar is where a phone copies from: xterm has no touch selection, so a press that+ * rests still makes one (terminal-selection.ts, wired in terminal-view.tsx) and the bar's+ * copy cap takes it. Both halves are checked against the clipboard the browser really holds.*/import { test, expect } from "@playwright/test";import { provisionAndLogin } from "./auth.mjs";@@ -70,6 +74,55 @@ async function dragFinger(page, from, to) {await cdp.detach();}+/** One finger down at `point` and up again without travelling: a tap. */+async function touchTap(page, point) {+ const cdp = await page.context().newCDPSession(page);+ await cdp.send("Input.dispatchTouchEvent", {+ type: "touchStart",+ touchPoints: [{ x: point.x, y: point.y }],+ });+ await page.waitForTimeout(40);+ await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });+ await cdp.detach();+}++/** One finger from `from` to `to`, in steps, then up. */+async function touchDrag(page, from, to) {+ const cdp = await page.context().newCDPSession(page);+ await cdp.send("Input.dispatchTouchEvent", {+ type: "touchStart",+ touchPoints: [{ x: from.x, y: from.y }],+ });+ const steps = 6;+ for (let i = 1; i <= steps; i++) {+ await cdp.send("Input.dispatchTouchEvent", {+ type: "touchMove",+ touchPoints: [+ { x: from.x + ((to.x - from.x) * i) / steps, y: from.y + ((to.y - from.y) * i) / steps },+ ],+ });+ }+ await page.waitForTimeout(60);+ await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });+ await cdp.detach();+}++/** A point inside the screen, on the buffer row whose text carries `marker`. */+async function pointOnRow(page, marker, fraction) {+ const point = await page.evaluate(+ ({ marker, fraction }) => {+ const rows = [...document.querySelectorAll(".xterm-rows > div")];+ const row = rows.filter((r) => r.textContent?.includes(marker)).pop();+ if (!row) return null;+ const box = row.getBoundingClientRect();+ return { x: box.x + box.width * fraction, y: box.y + box.height / 2 };+ },+ { marker, fraction },+ );+ expect(point, `no row carrying ${marker}`).not.toBeNull();+ return point;+}+test.describe("touch", () => {test.use({ viewport: { width: 412, height: 915 }, hasTouch: true, isMobile: true });@@ -162,6 +215,94 @@ test.describe("touch", () => {});});+test.describe("touch selection", () => {+ test.use({ viewport: { width: 412, height: 915 }, hasTouch: true, isMobile: true });++ const A_ROW = "A".repeat(20);+ const B_ROW = "B".repeat(20);++ /**+ * Two dense rows of output: a row of one unbroken run is the shape where "which word did+ * this touch take" has one answer, so the clipboard can be asserted to the character+ * instead of to a substring that happens to be somewhere on the line.+ */+ async function printTwoRows(page) {+ await type(page, String.raw`printf '%s\n' ${A_ROW} ${B_ROW}`);+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain(B_ROW);+ }++ const clipboard = (page) => page.evaluate(() => navigator.clipboard.readText());++ test("the select cap arms a mode, and the copy cap copies what it took", async ({ page }) => {+ await provisionAndLogin(page.request, U, P);+ await killAllTerminals(page.request);+ await page.goto(`${BASE}/terminal`);+ await waitForShell(page, "TOUCH_COPY_1");+ await printTwoRows(page);++ const selectCap = page.getByTestId("terminal-key-select");+ const copyCap = page.getByTestId("terminal-key-copy");+ await expect(selectCap).toHaveAttribute("aria-pressed", "false");++ // Pulling a finger across the output with the mode off is the scroll it has always been,+ // and leaves nothing to copy — the drags in the test above are that behaviour's own.+ await touchDrag(page, await pointOnRow(page, A_ROW, 0.2), await pointOnRow(page, B_ROW, 0.2));+ await expect(copyCap).toHaveCount(0);++ await selectCap.click();+ await expect(selectCap).toHaveAttribute("aria-pressed", "true");+ await touchTap(page, await pointOnRow(page, A_ROW, 0.5));++ // One unbroken run is one word, so the touch takes the row and the cap offers it.+ await expect(copyCap).toBeVisible();+ await copyCap.click();+ expect(await clipboard(page)).toBe(A_ROW);+ // The cap lives exactly as long as the selection does, and the copy cleared it — which+ // only a write that actually landed does.+ await expect(copyCap).toHaveCount(0);++ // The mode is still armed, and leaving it is its own tap.+ await expect(selectCap).toHaveAttribute("aria-pressed", "true");+ await selectCap.click();+ await expect(selectCap).toHaveAttribute("aria-pressed", "false");+ });++ test("a finger that travels after the touch extends the selection", async ({ page }) => {+ await provisionAndLogin(page.request, U, P);+ await killAllTerminals(page.request);+ await page.goto(`${BASE}/terminal`);+ await waitForShell(page, "TOUCH_COPY_2");+ await printTwoRows(page);++ await page.getByTestId("terminal-key-select").click();+ // Down through the second row: the selection runs from the word the touch took to the+ // cell the finger stopped on.+ await touchDrag(page, await pointOnRow(page, A_ROW, 0.2), await pointOnRow(page, B_ROW, 0.2));++ const copyCap = page.getByTestId("terminal-key-copy");+ await expect(copyCap).toBeVisible();+ await copyCap.click();+ expect(await clipboard(page)).toMatch(new RegExp(`^${A_ROW}\nB{1,20}$`));+ });++ test("leaving the mode drops the selection", async ({ page }) => {+ await provisionAndLogin(page.request, U, P);+ await killAllTerminals(page.request);+ await page.goto(`${BASE}/terminal`);+ await waitForShell(page, "TOUCH_COPY_3");+ await printTwoRows(page);++ const selectCap = page.getByTestId("terminal-key-select");+ const copyCap = page.getByTestId("terminal-key-copy");+ await selectCap.click();+ await touchTap(page, await pointOnRow(page, A_ROW, 0.5));+ await expect(copyCap).toBeVisible();++ await selectCap.click();+ await expect(copyCap).toHaveCount(0);+ });+});+test("no key bar where there is a real keyboard", async ({ page }) => {await provisionAndLogin(page.request, U, P);await killAllTerminals(page.request);diff --git a/packages/web/src/features/terminal/terminal-keybar.tsx b/packages/web/src/features/terminal/terminal-keybar.tsxindex be33f938..6065a8ae 100644--- a/packages/web/src/features/terminal/terminal-keybar.tsx+++ b/packages/web/src/features/terminal/terminal-keybar.tsx@@ -15,8 +15,12 @@* - **Ctrl and Alt are sticky, one shot.** A phone cannot hold a modifier down, so a tap* arms it and the next character typed on the soft keyboard consumes it (the composition* happens on the data path in terminal-view.tsx). Tapping again disarms.+ * - **Copy appears with a selection.** The select cap arms a mode in which a finger drags a+ * selection out of the terminal (terminal-view.tsx); a phone has no Ctrl+C to copy it with,+ * so the copy cap shows up for exactly as long as there is something to copy, and costs+ * the other caps no width the rest of the time.*/-import { GlyphIcon, ICON_SIZE } from "@lmliheng/penguin-ui";+import { GlyphIcon, ICON_SIZE, ICONS } from "@lmliheng/penguin-ui";import { useTerminalChrome } from "./terminal-appearance";import { S } from "../../lib/strings";import {@@ -40,6 +44,8 @@ const KEYBOARD_SHOW_ICON =export interface TerminalControl {/** Writes into the shell's input stream — the bar's keys never reach xterm's key handler. */send(data: string): void;+ /** Copies the current selection (the copy cap's whole job; the surface owns the selection). */+ copy(): void;paste(): void;focus(): void;blur(): void;@@ -55,9 +61,22 @@ export interface TerminalKeyBarProps {onModifiers: (mods: TerminalModifiers) => void;/** Whether xterm currently holds focus — decides which way the keyboard cap points. */focused: boolean;+ /** Whether the terminal has a selection — the one thing the copy cap needs to exist. */+ hasSelection: boolean;+ /** Whether the select cap's mode is armed (a finger then drags a selection out). */+ selectMode: boolean;+ onToggleSelect: () => void;}-export function TerminalKeyBar({ control, modifiers, onModifiers, focused }: TerminalKeyBarProps) {+export function TerminalKeyBar({+ control,+ modifiers,+ onModifiers,+ focused,+ hasSelection,+ selectMode,+ onToggleSelect,+}: TerminalKeyBarProps) {const chrome = useTerminalChrome();// The caps SHARE the width the way a keyboard row does, rather than each taking what its// label needs: the whole set has to be on screen at once, because a cap that must be@@ -147,6 +166,20 @@ export function TerminalKeyBar({ control, modifiers, onModifiers, focused }: TeronPress: () => send("\x03"),children: "^C",})}+ {cap({+ testId: "terminal-key-select",+ label: S.terminal.touchKeys.select,+ pressed: selectMode,+ onPress: onToggleSelect,+ children: <GlyphIcon d={ICONS.textCursor} size={ICON_SIZE.rowLead} />,+ })}+ {hasSelection &&+ cap({+ testId: "terminal-key-copy",+ label: S.terminal.touchKeys.copy,+ onPress: () => control.current?.copy(),+ children: <GlyphIcon d={ICONS.copy} size={ICON_SIZE.rowLead} />,+ })}{cap({testId: "terminal-key-paste",label: S.terminal.touchKeys.paste,@@ -164,7 +197,7 @@ export function TerminalKeyBar({ control, modifiers, onModifiers, focused }: Ter/>),})}- {/* Last on purpose, away from its sibling Ctrl: eleven caps are a hair wider than a+ {/* Last on purpose, away from its sibling Ctrl: the caps are a hair wider than aphone, and this is the one to leave under the fold. Alt on a phone is Alt+. andword motion — worth a swipe, not worth a slot ahead of interrupting a command. */}{cap({diff --git a/packages/web/src/features/terminal/terminal-selection.ts b/packages/web/src/features/terminal/terminal-selection.tsnew file mode 100644index 00000000..be0e1618--- /dev/null+++ b/packages/web/src/features/terminal/terminal-selection.ts@@ -0,0 +1,88 @@+/**+ * Selecting terminal text with a finger.+ *+ * xterm has no touch selection: its own touch handling is the scroll in Viewport, and+ * xterm.css turns `user-select` off for the whole surface, so the browser's own+ * press-and-hold selection cannot start either. On a phone that leaves the terminal+ * pastable and not copyable — the key bar has a paste cap and no way to make a selection+ * for a copy to take.+ *+ * So the selection has a mode of its own (the key bar's select cap, wired in+ * terminal-view.tsx): while it is on, a touch down takes the "word" under the finger and the+ * finger's travel extends it. It is a mode rather than the press-and-hold a phone reaches+ * for first because that gesture belongs to the browser — a resting press does not reach the+ * page at all (measured in Chromium: no touchmove and no touchend after one, only pointer+ * events), so a page cannot build on it.+ *+ * This module is the arithmetic that mode needs: which cells a touch takes, and what xterm's+ * `select(column, row, length)` has to be told to cover a drag.+ *+ * A word is a run of non-blank cells, the grain a terminal's own output is read at: a path,+ * a URL, a commit hash and a command are each one run. A touch that lands on blank padding+ * takes the whole line the way its text reads, which is the only thing there is to take+ * there.+ */++/** A cell in xterm's own selection coordinates: 0-based column, absolute (scrollback-inclusive) row. */+export interface BufferCell {+ col: number;+ row: number;+}++/** A run of cells in one buffer row, as a word: `start` inclusive, `end` exclusive. */+export interface WordSpan {+ start: number;+ end: number;+ row: number;+}++/** Whether the cell at `index` holds something other than a blank. */+function isText(line: string, index: number): boolean {+ if (index < 0 || index >= line.length) return false;+ return !/\s/.test(line[index]!);+}++/**+ * The word a press at `col` takes — the run of non-blank cells around it, or the line's own+ * text when the press landed on blank padding. Null for a line with nothing on it: there is+ * no selection to make, and the gesture leaves the terminal alone.+ *+ * `line` is the row's text as xterm reads it back (`translateToString(true)`, trailing+ * blanks already gone), so anything past its end is blank by definition.+ */+export function wordAt(line: string, col: number): { start: number; end: number } | null {+ if (line.trim() === "") return null;+ if (isText(line, col)) {+ let start = col;+ while (isText(line, start - 1)) start--;+ let end = col;+ while (isText(line, end + 1)) end++;+ return { start, end: end + 1 };+ }+ return { start: line.length - line.trimStart().length, end: line.length };+}++/**+ * What xterm's `select()` needs to cover the drag from a word to the finger: the earlier of+ * the two ends becomes the anchor, the later one is the selection's last cell.+ *+ * Dragging to the right of the word grows it rightwards; dragging back through it shrinks+ * it and then grows it leftwards, the way a handle on either end behaves. The rows are+ * flattened to a cell index across the row width, so a selection that runs over several+ * rows — wrapped lengths included — is one interval, which is exactly how xterm's own+ * selection model reads a range that `length` crosses.+ */+export function selectionSpan(+ word: WordSpan,+ focus: BufferCell,+ cols: number,+): { col: number; row: number; length: number } | null {+ if (cols <= 0) return null;+ const first = word.row * cols + word.start;+ const last = word.row * cols + word.end - 1;+ const at = focus.row * cols + focus.col;+ const from = Math.min(at, first);+ const to = Math.max(at, last);+ const row = Math.floor(from / cols);+ return { col: from - row * cols, row, length: to - from + 1 };+}diff --git a/packages/web/src/features/terminal/terminal-view.tsx b/packages/web/src/features/terminal/terminal-view.tsxindex c444e276..a8820a1f 100644--- a/packages/web/src/features/terminal/terminal-view.tsx+++ b/packages/web/src/features/terminal/terminal-view.tsx@@ -22,6 +22,7 @@ import { LinkClickTracker, openTerminalLink, positionFromPointer } from "./termiimport { writeClipboard } from "../../lib/clipboard";import { TerminalKeyBar, type TerminalControl } from "./terminal-keybar";import { NO_MODIFIERS, applyModifiers, hasModifier, type TerminalModifiers } from "./terminal-keys";+import { selectionSpan, wordAt, type BufferCell, type WordSpan } from "./terminal-selection";import { TouchScroll } from "./terminal-touch";import { useCoarsePointer } from "../../lib/use-coarse-pointer";import { useTheme } from "../../state/theme";@@ -254,6 +255,25 @@ export function TerminalView({const modifiersRef = useRef(modifiers);modifiersRef.current = modifiers;const [focused, setFocused] = useState(false);+ // Whether a selection is waiting to be copied. Only the touch key bar reads it: on a+ // phone the copy has no key of its own, so the bar's copy cap appears exactly while+ // there is something to copy.+ const [hasSelection, setHasSelection] = useState(false);+ // The touch selection mode, armed by the bar's select cap. A mode rather than a gesture+ // because the obvious gesture belongs to the browser — see the touch block in the effect.+ const [selectMode, setSelectMode] = useState(false);+ const selectModeRef = useRef(selectMode);+ selectModeRef.current = selectMode;+ /**+ * Turning the mode off drops the selection with it — the highlight is what the mode is+ * for, and leaving it behind would hide the caps that came with it.+ */+ const toggleSelectMode = (): void => {+ const next = !selectModeRef.current;+ selectModeRef.current = next; // before the re-render: a touch may land in between+ setSelectMode(next);+ if (!next) termRef.current?.clearSelection();+ };useEffect(() => {if (termRef.current) termRef.current.options.theme = terminalTheme(terminalDark);}, [terminalDark]);@@ -383,12 +403,22 @@ export function TerminalView({);}- /** Copies the active selection and clears it — the visual ack that the copy happened. */+ /**+ * Copies the active selection and clears it — the visual ack that the copy happened.+ *+ * Cleared only once the write landed, though. A failed write that also took the+ * selection away leaves the reader worse off than before the keypress, and it is the+ * one case the browser could still have rescued: xterm serves the browser's own copy+ * event out of this same selection, so keeping it is what lets the native path fire+ * after ours declined. (jsdom's `copy-to-clipboard` refuses; a plain-HTTP origin has+ * no async clipboard API. Both are real on a LAN address.)+ */const copySelection = (): void => {const selection = term.getSelection();if (!selection) return;- void writeClipboard(selection);- term.clearSelection();+ void writeClipboard(selection).then((copied) => {+ if (copied && !disposed) term.clearSelection();+ });};/** Async-clipboard paste (the paths where no native paste event exists). */const pasteFromClipboard = (): void => {@@ -553,6 +583,147 @@ export function TerminalView({container.addEventListener("touchend", () => touchScroll.end(), { signal, passive: true });container.addEventListener("touchcancel", () => touchScroll.end(), { signal, passive: true });+ /**+ * Selecting with a finger, in the mode the key bar's select cap turns on.+ *+ * The selection cannot hang off the gesture a phone reaches for first: a press that+ * rests belongs to the browser, which takes it for its own and stops delivering+ * touches to the page (measured in Chromium: after a resting press, no touchmove and+ * no touchend — only pointer events). So it gets an explicit mode instead, one no+ * gesture recognizer competes for: while it is on, a touch down takes the word under+ * the finger and the finger's travel extends it. While it is off, every touch here+ * behaves exactly as it did before — the scroll stays a scroll.+ */+ let pressWord: WordSpan | null = null;+ let dragging = false;+ /** Where an armed gesture began, until the selection itself is made. */+ let touchStartPoint: { x: number; y: number } | null = null;+ /** The buffer cell under a client point; a drag may leave the grid, so it is clamped. */+ const cellAt = (clientX: number, clientY: number): BufferCell | null => {+ const screen = term.element?.querySelector(".xterm-screen");+ if (!screen) return null;+ const box = screen.getBoundingClientRect();+ if (box.width <= 0 || box.height <= 0) return null;+ const pos = positionFromPointer(+ {+ x: Math.min(Math.max(clientX, box.left), box.left + box.width - 1),+ y: Math.min(Math.max(clientY, box.top), box.top + box.height - 1),+ },+ { left: box.left, top: box.top, width: box.width, height: box.height },+ { cols: term.cols, rows: term.rows, viewportY: term.buffer.active.viewportY },+ );+ return pos === null ? null : { col: pos.x - 1, row: pos.y - 1 };+ };+ /** A touch landed here: take the word it landed on. */+ const beginSelection = (clientX: number, clientY: number): void => {+ const cell = cellAt(clientX, clientY);+ const line = cell === null ? undefined : term.buffer.active.getLine(cell.row);+ if (cell === null || line === undefined) return;+ const word = wordAt(line.translateToString(true), cell.col);+ if (word === null) return; // blank line: nothing to take, and nothing to extend from+ pressWord = { ...word, row: cell.row };+ term.select(word.start, cell.row, word.end - word.start);+ };+ /** The finger moved with a selection live: extend it from the word to the finger. */+ const extendSelection = (clientX: number, clientY: number): void => {+ if (pressWord === null) return;+ const cell = cellAt(clientX, clientY);+ if (cell === null) return;+ const span = selectionSpan(pressWord, cell, term.cols);+ if (span !== null) term.select(span.col, span.row, span.length);+ };+ container.addEventListener(+ "touchstart",+ (event) => {+ pressWord = null;+ dragging = false;+ touchStartPoint = null;+ const touch = event.touches[0];+ if (!selectModeRef.current || event.touches.length !== 1 || touch === undefined) return;+ dragging = true;+ // Deliberately nothing else. Making the selection here stops Chromium from+ // delivering the rest of the gesture at all — measured: a `term.select()` inside+ // the touchstart handler is followed by no touchmove and no touchend, only pointer+ // events, so the drag the mode exists for would never arrive. It is made on the+ // first movement instead, and at the end when there was none (a tap).+ touchStartPoint = { x: touch.clientX, y: touch.clientY };+ },+ { signal, capture: true, passive: true },+ );+ container.addEventListener(+ "touchmove",+ (event) => {+ if (!dragging) return;+ const touch = event.touches[0];+ if (touch === undefined) return;+ // Capture phase, and both calls matter: xterm's viewport would otherwise scroll+ // the text out from under the finger that is selecting it.+ event.preventDefault();+ event.stopPropagation();+ // The word the gesture took is the one under where it began, or under the cell it+ // has reached when that beginning was blank padding and held nothing to take.+ if (pressWord === null) {+ const from = touchStartPoint ?? { x: touch.clientX, y: touch.clientY };+ touchStartPoint = null;+ beginSelection(from.x, from.y);+ }+ extendSelection(touch.clientX, touch.clientY);+ },+ { signal, capture: true, passive: false },+ );+ const endTouch = (event: TouchEvent): void => {+ if (!dragging) return;+ dragging = false;+ const start = touchStartPoint;+ touchStartPoint = null;+ if (event.touches.length > 0) {+ // A second finger is not the end of the gesture.+ pressWord = null;+ return;+ }+ // No movement at all: this was a tap, and the tap itself is what takes the word.+ if (pressWord === null && start !== null) beginSelection(start.x, start.y);+ const selected = pressWord !== null;+ pressWord = null;+ if (!selected) {+ term.clearSelection(); // a touch that took nothing takes the selection away too+ return;+ }+ selectionMade = true; // see swallowTouchMouse+ event.preventDefault();+ };+ container.addEventListener("touchend", endTouch, { signal, capture: true, passive: false });+ container.addEventListener("touchcancel", endTouch, { signal, capture: true, passive: true });++ /**+ * Chrome renders a touch as mouse events as well (`mousedown`, then `click`), and xterm+ * reads a mousedown on its surface as "begin a new selection" — it would replace, or+ * drop, the one the finger just made. So a gesture that made a selection swallows them.+ * Only those: `sourceCapabilities.firesTouchEvents` is the browser saying the event came+ * from a finger (the DOM lib does not type the field, hence the widening below), and a+ * real mouse never sets it, so a pointer on a touchscreen laptop is untouched. The next+ * press disarms the guard.+ */+ let selectionMade = false;+ const swallowTouchMouse = (event: MouseEvent): void => {+ const fromTouch =+ (event as MouseEvent & { sourceCapabilities?: { firesTouchEvents?: boolean } })+ .sourceCapabilities?.firesTouchEvents === true;+ if (!selectionMade || !fromTouch) return;+ event.preventDefault();+ event.stopPropagation();+ };+ container.addEventListener("mousedown", swallowTouchMouse, { signal, capture: true });+ container.addEventListener("mouseup", swallowTouchMouse, { signal, capture: true });+ container.addEventListener("click", swallowTouchMouse, { signal, capture: true });+ container.addEventListener("pointerdown", () => (selectionMade = false), {+ signal,+ capture: true,+ });++ // What the key bar's copy cap reads, and what makes it show up at all.+ term.onSelectionChange(() => setHasSelection(term.hasSelection()));+// Click-to-focus anywhere in the view, padding included — finishing a selection drag// also lands here, which is fine: focusing xterm's textarea keeps the selection.container.addEventListener("mouseup", () => term.focus(), { signal });@@ -656,6 +827,7 @@ export function TerminalView({// dispose, so a bar tap between two attaches is a no-op rather than a throw.control.current = {send,+ copy: copySelection,paste: pasteFromClipboard,focus: () => term.focus(),blur: () => term.blur(),@@ -693,6 +865,9 @@ export function TerminalView({modifiers={modifiers}onModifiers={setModifiers}focused={focused}+ hasSelection={hasSelection}+ selectMode={selectMode}+ onToggleSelect={toggleSelectMode}/>)}</div>diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 95ac9490..bcb116e2 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -222,6 +222,10 @@ export const en: Strings = {left: "Arrow left",right: "Arrow right",interrupt: "Interrupt (Ctrl+C)",+ /** Arms the touch selection mode; a finger then drags a selection out. */+ select: "Select text (then drag on the terminal)",+ /** Shown only while the terminal has a selection. */+ copy: "Copy selection",paste: "Paste",hideKeyboard: "Dismiss the keyboard",showKeyboard: "Show the keyboard",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 0592d75a..32aed0f4 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -246,6 +246,10 @@ export const zh = {left: "左方向键",right: "右方向键",interrupt: "中断(Ctrl+C)",+ /** Arms the touch selection mode; a finger then drags a selection out. */+ select: "选择文本(打开后在终端上拖动)",+ /** Shown only while the terminal has a selection. */+ copy: "复制选区",paste: "粘贴",hideKeyboard: "收起键盘",showKeyboard: "调出键盘",diff --git a/packages/web/test/terminal-selection.test.ts b/packages/web/test/terminal-selection.test.tsnew file mode 100644index 00000000..7109df19--- /dev/null+++ b/packages/web/test/terminal-selection.test.ts@@ -0,0 +1,66 @@+/**+ * The touch selection's arithmetic (terminal-selection.ts): which cells a long press takes,+ * and the `select(col, row, length)` a drag from there asks xterm for.+ */+import { describe, expect, it } from "vitest";+import { selectionSpan, wordAt } from "../src/features/terminal/terminal-selection";++const COLS = 10;++describe("wordAt", () => {+ it("takes the run of non-blank cells the press landed in", () => {+ // "root@host:~# echo SELECT_ME" — the prompt, a command and its argument.+ expect(wordAt("root@host:~# echo SELECT_ME", 20)).toEqual({ start: 18, end: 27 });+ });++ it("keeps punctuation with the word — a path, a URL, a hash are each one run", () => {+ const line = " /usr/local/bin/node:12:5 ";+ expect(wordAt(line, 10)).toEqual({ start: 2, end: 26 });+ });++ it("takes the whole word from either of its edges", () => {+ const line = "alpha beta";+ expect(wordAt(line, 0)).toEqual({ start: 0, end: 5 });+ expect(wordAt(line, 4)).toEqual({ start: 0, end: 5 });+ expect(wordAt(line, 6)).toEqual({ start: 6, end: 10 });+ expect(wordAt(line, 9)).toEqual({ start: 6, end: 10 });+ });++ it("falls back to the line's own text when the press lands on blank padding", () => {+ // What xterm reads back: trailing blanks are already gone.+ expect(wordAt("SELECT_ME_LINE", 20)).toEqual({ start: 0, end: 14 });+ expect(wordAt(" indented tail", 0)).toEqual({ start: 3, end: 16 });+ });++ it("has nothing to take on a blank line", () => {+ expect(wordAt("", 0)).toBeNull();+ expect(wordAt(" ", 3)).toBeNull();+ });+});++describe("selectionSpan", () => {+ it("extends the word to the finger, the finger's own cell included", () => {+ const word = { start: 2, end: 5, row: 3 }; // cells 2..4 of row 3+ expect(selectionSpan(word, { col: 7, row: 3 }, COLS)).toEqual({ col: 2, row: 3, length: 6 });+ });++ it("a drag that stays inside the word keeps the word the press took", () => {+ const word = { start: 2, end: 6, row: 0 };+ expect(selectionSpan(word, { col: 3, row: 0 }, COLS)).toEqual({ col: 2, row: 0, length: 4 });+ });++ it("a drag to the left of the word anchors at the finger and ends at the word's last cell", () => {+ const word = { start: 4, end: 7, row: 1 };+ expect(selectionSpan(word, { col: 1, row: 1 }, COLS)).toEqual({ col: 1, row: 1, length: 6 });+ });++ it("carries a selection across rows as one interval, the way xterm reads it", () => {+ const word = { start: 8, end: 10, row: 2 }; // cells 28..29+ // Down one row and back to column 2: the selection runs to cell 32.+ expect(selectionSpan(word, { col: 2, row: 3 }, COLS)).toEqual({ col: 8, row: 2, length: 5 });+ });++ it("has no span for a grid it cannot flatten", () => {+ expect(selectionSpan({ start: 0, end: 1, row: 0 }, { col: 0, row: 0 }, 0)).toBeNull();+ });+});