Skip to content

Commit ed2a319

Browse files
fix(web): arrow and page keys scroll the conversation again after a click or F6 (#27209)
1 parent 7fb6098 commit ed2a319

6 files changed

Lines changed: 105 additions & 22 deletions

File tree

‎apps/web/src/components/ChatView.logic.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1070,9 +1070,9 @@ export function hasServerAcknowledgedLocalDispatch(input: {
10701070
}
10711071

10721072
// Window return puts the caret in the composer unless focus is deliberate: another text field,
1073-
// a terminal, an open dialog, menu, or popup, a region or sidebar row reached from the keyboard,
1074-
// or a region with its own keys (aria-keyshortcuts). A plain focused button or a clicked row
1075-
// yields to the composer.
1073+
// a terminal, an open dialog, menu, or popup, a region, timeline, or sidebar row reached from the
1074+
// keyboard, or a region with its own keys (aria-keyshortcuts). A plain focused button or a clicked
1075+
// row yields to the composer.
10761076
export function shouldRefocusComposerOnWindowFocus(
10771077
activeElement:
10781078
| (Pick<Element, "tagName" | "closest" | "getAttribute"> & { isContentEditable?: boolean })

‎apps/web/src/components/chat/MessagesTimeline.browser.test.tsx‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender";
22
import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";
33
import { flushSync } from "react-dom";
44
import { AudioPreview } from "../files/AudioPreview";
5-
import { cdp, page } from "vite-plus/test/browser";
5+
import { cdp, page, userEvent } from "vite-plus/test/browser";
66
import {
77
ComposerContextId,
88
EnvironmentId,
@@ -37,6 +37,7 @@ import { environmentThreadDetails } from "../../state/threads";
3737
import { act, fakeTimers, render, stubGlobal } from "../../../test/render";
3838
import { ChangedFilesCard } from "./ChangedFilesTree";
3939
import { MessagesTimeline } from "./MessagesTimeline";
40+
import { createWorkspaceFocusController, workspaceAreaProps } from "../../lib/workspaceFocus";
4041
import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";
4142
import { makeStreamingTimelineFixture } from "../../test-fixtures";
4243
import {
@@ -565,6 +566,38 @@ describe("MessagesTimeline messages", () => {
565566
await expectHeadingInView("Last turn", "Turn 118:");
566567
});
567568

569+
it("scrolls from the keyboard once F6 moves into the conversation", async () => {
570+
setup();
571+
const props = baseProps();
572+
const entries = Array.from({ length: 40 }, (_, index) =>
573+
message(`Turn ${index}:\n\n${"x ".repeat(200)}`, {}, `turn-${index}`),
574+
);
575+
await using _screen = await renderElement(
576+
<>
577+
<div
578+
{...workspaceAreaProps("conversation", 1, "Conversation")}
579+
className="relative flex min-h-0 flex-1 flex-col"
580+
>
581+
<MessagesTimeline {...props} timelineEntries={entries} />
582+
</div>
583+
<div {...workspaceAreaProps("composer", 2, "Message input")}>
584+
<button type="button">Send</button>
585+
</div>
586+
</>,
587+
);
588+
const focus = createWorkspaceFocusController(document);
589+
using _focus = { [Symbol.dispose]: focus.dispose };
590+
const viewport = props.listRef.current!.getScrollableNode()!;
591+
await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0));
592+
const atEnd = viewport.scrollTop;
593+
page.getByRole("button", { name: "Send" }).element().focus();
594+
await userEvent.keyboard("{F6}");
595+
focus.move(-1);
596+
expect(viewport).toHaveAttribute("data-workspace-keyboard-focus");
597+
await userEvent.keyboard("{PageUp}");
598+
await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd));
599+
});
600+
568601
it("disables the minimap's next turn button at the bottom of the thread", async () => {
569602
setup();
570603
const props = baseProps();

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1468,6 +1468,9 @@ const ConversationTimeline = memo(function ConversationTimeline({
14681468
onScroll={handleScroll}
14691469
onItemSizeChanged={scheduleMinimapRefresh}
14701470
onMetricsChange={scheduleMinimapRefresh}
1471+
// Keyboard scrolling only moves the focused element; F6 and clicks land here.
1472+
tabIndex={-1}
1473+
data-workspace-focus-default
14711474
className={cn(
14721475
"messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
14731476
topFadeEnabled && "topbar-scroll-fade",

‎apps/web/src/index.css‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2624,11 +2624,19 @@ code {
26242624
}
26252625

26262626
/* A workspace area with no control of its own takes F6 focus itself; keep that visible.
2627-
workspaceFocus.ts marks those, since :focus-visible also matches a clicked area after a key press. */
2627+
workspaceFocus.ts marks those, since :focus-visible also matches a clicked area after a key press.
2628+
The conversation's timeline takes it instead, and its top fade mask would hide its own ring. */
26282629
[data-workspace-area]:focus-visible {
26292630
outline: none;
26302631
}
2631-
[data-workspace-keyboard-focus]:focus {
2632+
[data-workspace-keyboard-focus]:focus,
2633+
[data-workspace-area="conversation"]:has(
2634+
.messages-timeline-scroll[data-workspace-keyboard-focus]:focus
2635+
) {
26322636
outline: 2px solid var(--ring);
26332637
outline-offset: -2px;
26342638
}
2639+
2640+
.messages-timeline-scroll:focus-visible {
2641+
outline: none;
2642+
}

‎apps/web/src/lib/workspaceFocus.browser.test.ts‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,15 @@ function setup() {
3333
};
3434
}
3535

36+
/** Mirrors MessagesTimeline's scroller, which takes focus so the keyboard scrolls it. */
37+
function conversationScroller(height: number) {
38+
const timeline = document.createElement("div");
39+
timeline.style.cssText = `height: ${height}px; overflow-y: auto`;
40+
timeline.tabIndex = -1;
41+
timeline.dataset.workspaceFocusDefault = "";
42+
return timeline;
43+
}
44+
3645
describe("workspace area focus", () => {
3746
it("cycles in workspace order in both directions, independent of DOM order", () => {
3847
using fixture = setup();
@@ -42,7 +51,7 @@ describe("workspace area focus", () => {
4251
const composer = fixture.area("composer", 2);
4352
sidebar.button.focus();
4453
fixture.controller.move(1);
45-
// The conversation is a region; it takes focus itself rather than its first button.
54+
// Without a timeline (an empty thread), the region takes focus rather than its first button.
4655
expect(document.activeElement).toBe(conversation.element);
4756
fixture.controller.move(1);
4857
expect(document.activeElement).toBe(composer.button);
@@ -204,8 +213,7 @@ describe("workspace area focus", () => {
204213
it("does not scroll the conversation to an old control", () => {
205214
using fixture = setup();
206215
const conversation = fixture.area("conversation", 1);
207-
const timeline = document.createElement("div");
208-
timeline.style.cssText = "height: 50px; overflow-y: auto";
216+
const timeline = conversationScroller(50);
209217
const copy = document.createElement("button");
210218
copy.textContent = "Copy";
211219
timeline.append(copy, Object.assign(document.createElement("div"), { style: "height: 400px" }));
@@ -217,10 +225,28 @@ describe("workspace area focus", () => {
217225
// Live follow moved the timeline to the newest output.
218226
timeline.scrollTop = 300;
219227
fixture.controller.move(-1);
220-
expect(document.activeElement).toBe(conversation.element);
228+
expect(document.activeElement).toBe(timeline);
221229
expect(timeline.scrollTop).toBe(300);
222230
});
223231

232+
it("scrolls the conversation with the keyboard once an empty thread gets a timeline", async () => {
233+
using fixture = setup();
234+
const conversation = fixture.area("conversation", 1);
235+
conversation.button.remove();
236+
conversation.element.style.height = "200px";
237+
const composer = fixture.area("composer", 2);
238+
composer.button.focus();
239+
fixture.controller.move(-1);
240+
expect(document.activeElement).toBe(conversation.element);
241+
fixture.controller.move(1);
242+
const timeline = conversationScroller(200);
243+
timeline.append(Object.assign(document.createElement("div"), { style: "height: 2000px" }));
244+
conversation.element.append(timeline);
245+
fixture.controller.move(-1);
246+
await userEvent.keyboard("{ArrowDown}{PageDown}");
247+
await vi.waitFor(() => expect(timeline.scrollTop).toBeGreaterThan(0));
248+
});
249+
224250
it.each([
225251
["panel", "panel", "removed"],
226252
["conversation", "composer", "removed"],
@@ -281,7 +307,9 @@ describe("workspace area focus", () => {
281307
bringBack.textContent = "Bring back";
282308
content.append(bringBack);
283309
panel.element.append(content);
284-
fixture.area("conversation", 1, content);
310+
const timeline = conversationScroller(50);
311+
timeline.append(Object.assign(document.createElement("div"), { style: "height: 400px" }));
312+
fixture.area("conversation", 1, content).element.append(timeline);
285313
const composer = fixture.area("composer", 2, content);
286314
const editor = document.createElement("div");
287315
editor.contentEditable = "true";

‎apps/web/src/lib/workspaceFocus.ts‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -100,18 +100,22 @@ function revealInScrollers(target: HTMLElement) {
100100
export function createWorkspaceFocusController(doc: Document) {
101101
const lastFocused = new Map<string, HTMLElement>();
102102
let lastArea: string | undefined;
103-
// An area that took focus itself from the keyboard. Chromium's :focus-visible also matches
104-
// a clicked area after any later key press, so the ring and window return read this mark.
103+
// An area that took focus itself from the keyboard, or the non-tabbable default (the
104+
// conversation's scroller) standing in for it. Chromium's :focus-visible also matches a
105+
// clicked area after any later key press, so the ring and window return read this mark.
105106
let keyboardArea: HTMLElement | undefined;
106107
let previousTarget: EventTarget | null = null;
107108
const unmarkKeyboardArea = () => {
108109
keyboardArea?.removeAttribute("data-workspace-keyboard-focus");
109110
keyboardArea = undefined;
110111
};
111-
const markKeyboardArea = (area: HTMLElement) => {
112-
if (!area.matches(":focus-visible")) return;
113-
keyboardArea = area;
114-
area.setAttribute("data-workspace-keyboard-focus", "");
112+
const standsInFor = (element: HTMLElement, area: HTMLElement) =>
113+
element === area ||
114+
(element.tabIndex < 0 && element.hasAttribute("data-workspace-focus-default"));
115+
const markKeyboardArea = (target: HTMLElement) => {
116+
if (!target.matches(":focus-visible")) return;
117+
keyboardArea = target;
118+
target.setAttribute("data-workspace-keyboard-focus", "");
115119
};
116120
const remember = (event: FocusEvent) => {
117121
if (event.target !== keyboardArea) unmarkKeyboardArea();
@@ -121,7 +125,7 @@ export function createWorkspaceFocusController(doc: Document) {
121125
if (!(event.target instanceof HTMLElement)) return;
122126
const area = workspaceArea(event.target);
123127
if (!area?.dataset.workspaceArea) return;
124-
if (arrived && event.target === area) markKeyboardArea(area);
128+
if (arrived && standsInFor(event.target, area)) markKeyboardArea(event.target);
125129
lastArea = area.dataset.workspaceArea;
126130
const key = area.dataset.workspaceFocusKey ?? lastArea;
127131
lastFocused.delete(key);
@@ -141,11 +145,14 @@ export function createWorkspaceFocusController(doc: Document) {
141145
const belongs = (element: HTMLElement) => workspaceArea(element) === area && usable(element);
142146
// A side chat's message input sits in its own area inside the panel. Opening the
143147
// panel focuses it, but F6 visits that area on its own, so it moves past it here.
148+
// A nested timeline stands in only for its own area, never ahead of that input.
144149
const preferred = Array.from(
145150
area.querySelectorAll<HTMLElement>(
146151
'[data-workspace-focus-default], [data-sidebar-row][aria-current="page"], [data-settings-section][aria-current="page"], .xterm-helper-textarea, [contenteditable="true"]',
147152
),
148-
).find(nested ? usable : belongs);
153+
).find((element) =>
154+
nested && !standsInFor(element, area) ? usable(element) : belongs(element),
155+
);
149156
const fallback = Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(
150157
(element) => element.tabIndex >= 0 && belongs(element),
151158
);
@@ -172,10 +179,14 @@ export function createWorkspaceFocusController(doc: Document) {
172179
)
173180
: undefined;
174181
// Moving the timeline to an old control would also stop it following a running turn,
175-
// so the conversation reuses a control only while it is still in view.
182+
// so the conversation reuses a control only while it is still in view. A remembered
183+
// area is only the fallback it was then, so controls mounted since take precedence.
176184
const isConversation = area.dataset.workspaceArea === "conversation";
177185
const targets = new Set([
178-
previous && belongs(previous) && (!isConversation || isInScrollView(previous))
186+
previous &&
187+
previous !== area &&
188+
belongs(previous) &&
189+
(!isConversation || isInScrollView(previous))
179190
? previous
180191
: undefined,
181192
isConversation ? undefined : restored,
@@ -192,7 +203,7 @@ export function createWorkspaceFocusController(doc: Document) {
192203
if (active === target || (active && target.contains(active))) {
193204
if (target !== area && !isConversation) revealInScrollers(target);
194205
// Focusing the already focused area fires no focusin, as when F6 has nowhere else to go.
195-
if (target === area) markKeyboardArea(area);
206+
if (standsInFor(target, area)) markKeyboardArea(target);
196207
return true;
197208
}
198209
}

0 commit comments

Comments
 (0)