Skip to content

Commit 0fc225e

Browse files
committed
feat(web): press R to cite selected assistant text
While the Cite action is shown for a selection in an assistant response, pressing R cites it and focuses the comment editor, same as clicking Cite. Type-to-focus leaves R for the Cite action so it is not typed into the composer. Cmd, Ctrl and Alt+R still reach the browser.
1 parent 210b2e7 commit 0fc225e

4 files changed

Lines changed: 199 additions & 13 deletions

File tree

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2+
import { useState, type ComponentProps } from "react";
3+
import { describe, expect, it, vi } from "vite-plus/test";
4+
import { page, userEvent } from "vite-plus/test/browser";
5+
6+
import { render } from "../../../test/render";
7+
import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";
8+
import type { ChatComposerHandle } from "./ChatComposer";
9+
import { useChatShortcuts } from "./useChatShortcuts";
10+
11+
type OnCite = ComponentProps<typeof AssistantSelectionToolbar>["onCite"];
12+
13+
const threadRef = {
14+
environmentId: EnvironmentId.make("environment"),
15+
threadId: ThreadId.make("thread"),
16+
};
17+
18+
// The chat's window capture listener runs before the toolbar's document listener, so
19+
// type-to-focus sees every key first. The stand-in composer records what it receives.
20+
function ChatShortcuts(props: { composerKeys: string[] }) {
21+
useChatShortcuts({
22+
enabled: true,
23+
keybindings: [],
24+
scriptKeybindings: [],
25+
getShortcutContext: () => ({
26+
terminalFocus: false,
27+
terminalOpen: false,
28+
previewFocus: false,
29+
previewOpen: false,
30+
isWeb: true,
31+
isDesktop: false,
32+
modelPickerOpen: false,
33+
}),
34+
threadFindActive: false,
35+
composerRef: {
36+
current: {
37+
insertTextAtEnd: (key: string) => {
38+
props.composerKeys.push(key);
39+
return true;
40+
},
41+
} as Partial<ChatComposerHandle> as ChatComposerHandle,
42+
},
43+
branchToolbarRef: { current: null },
44+
closeThreadFind: () => {},
45+
commands: {},
46+
fallback: () => undefined,
47+
});
48+
return null;
49+
}
50+
51+
function Transcript(props: { onCite: OnCite; composerKeys?: string[] }) {
52+
const [viewport, setViewport] = useState<HTMLElement | null>(null);
53+
return (
54+
<>
55+
{props.composerKeys ? <ChatShortcuts composerKeys={props.composerKeys} /> : null}
56+
<input aria-label="Find in thread" />
57+
<div ref={setViewport}>
58+
<div data-assistant-citation-source="message-1">
59+
<p>Render the citation chip</p>
60+
</div>
61+
</div>
62+
<AssistantSelectionToolbar viewport={viewport} threadRef={threadRef} onCite={props.onCite} />
63+
</>
64+
);
65+
}
66+
67+
// router: false because the transcript never navigates.
68+
const options = { router: false } as const;
69+
const citeButton = page.getByRole("button", { name: "Cite selection in composer" });
70+
71+
async function selectAssistantText(container: HTMLElement) {
72+
const text = container.querySelector("p")!.firstChild!;
73+
window.getSelection()!.setBaseAndExtent(text, 7, text, 15);
74+
await expect.element(citeButton).toBeVisible();
75+
}
76+
77+
describe("AssistantSelectionToolbar", () => {
78+
it.each(["r", "R"])("cites the selection when %s is pressed", async (key) => {
79+
const onCite = vi.fn<OnCite>(() => true);
80+
await using screen = await render(<Transcript onCite={onCite} />, options);
81+
await selectAssistantText(screen.container);
82+
83+
await userEvent.keyboard(key);
84+
85+
expect(onCite).toHaveBeenCalledOnce();
86+
expect(onCite.mock.lastCall![0]).toMatchObject({ messageId: "message-1", text: "the cita" });
87+
expect(window.getSelection()!.isCollapsed).toBe(true);
88+
await expect.element(citeButton).not.toBeInTheDocument();
89+
});
90+
91+
it("cites with R instead of typing it into the composer", async () => {
92+
const onCite = vi.fn<OnCite>(() => true);
93+
const composerKeys: string[] = [];
94+
await using screen = await render(
95+
<Transcript onCite={onCite} composerKeys={composerKeys} />,
96+
options,
97+
);
98+
await selectAssistantText(screen.container);
99+
100+
await userEvent.keyboard("r");
101+
102+
expect(onCite).toHaveBeenCalledOnce();
103+
expect(composerKeys).toEqual([]);
104+
});
105+
106+
it("types R into the composer when nothing is selected", async () => {
107+
const onCite = vi.fn<OnCite>(() => true);
108+
const composerKeys: string[] = [];
109+
await using _screen = await render(
110+
<Transcript onCite={onCite} composerKeys={composerKeys} />,
111+
options,
112+
);
113+
114+
await userEvent.keyboard("r");
115+
116+
expect(composerKeys).toEqual(["r"]);
117+
expect(onCite).not.toHaveBeenCalled();
118+
});
119+
120+
it("lets a focused text field keep R", async () => {
121+
const onCite = vi.fn<OnCite>(() => true);
122+
await using screen = await render(<Transcript onCite={onCite} />, options);
123+
await selectAssistantText(screen.container);
124+
const find = screen.getByRole("textbox", { name: "Find in thread" });
125+
await userEvent.click(find);
126+
127+
await userEvent.keyboard("r");
128+
129+
await expect.element(find).toHaveValue("r");
130+
expect(onCite).not.toHaveBeenCalled();
131+
});
132+
133+
// Dispatched rather than typed so a real Ctrl+R cannot reload the test page.
134+
it.each([
135+
["Cmd+R", { metaKey: true }],
136+
["Ctrl+R", { ctrlKey: true }],
137+
["Alt+R", { altKey: true }],
138+
])("leaves %s to the browser", async (_name, modifier) => {
139+
const onCite = vi.fn<OnCite>(() => true);
140+
await using screen = await render(<Transcript onCite={onCite} />, options);
141+
await selectAssistantText(screen.container);
142+
143+
const event = new KeyboardEvent("keydown", {
144+
key: "r",
145+
bubbles: true,
146+
cancelable: true,
147+
...modifier,
148+
});
149+
document.body.dispatchEvent(event);
150+
151+
expect(event.defaultPrevented).toBe(false);
152+
expect(onCite).not.toHaveBeenCalled();
153+
});
154+
155+
it("still focuses the Cite action on Tab", async () => {
156+
const onCite = vi.fn<OnCite>(() => true);
157+
await using screen = await render(<Transcript onCite={onCite} />, options);
158+
await selectAssistantText(screen.container);
159+
160+
await userEvent.keyboard("{Tab}");
161+
162+
await expect.element(citeButton).toHaveFocus();
163+
expect(onCite).not.toHaveBeenCalled();
164+
});
165+
});

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

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,17 @@ import {
1818
type SelectionActionPoint,
1919
} from "~/lib/selectionActions";
2020
import { Button } from "../ui/button";
21+
import { Kbd } from "../ui/kbd";
22+
23+
const CITE_ACTION_SELECTOR = "button[data-cite-selection-action]:enabled";
24+
25+
/**
26+
* Whether this key press is R while the Cite action is shown. Type-to-focus
27+
* checks it so the key cites instead of being typed into the composer.
28+
*/
29+
export function isCiteSelectionShortcut(event: KeyboardEvent): boolean {
30+
return event.key.toLowerCase() === "r" && document.querySelector(CITE_ACTION_SELECTOR) !== null;
31+
}
2132

2233
export function AssistantSelectionToolbar({
2334
viewport,
@@ -141,30 +152,34 @@ export function AssistantSelectionToolbar({
141152
onDismiss: clear,
142153
});
143154
actionsRef.current = actions;
144-
const focusActions = (event: KeyboardEvent) => {
155+
// While the action is shown, Tab focuses it and R cites straight into the comment editor.
156+
const handleShortcut = (event: KeyboardEvent) => {
145157
const toolbar = toolbarRef.current;
146158
if (
147-
event.key !== "Tab" ||
148-
event.shiftKey ||
159+
!toolbar ||
160+
toolbar.disabled ||
149161
event.altKey ||
150162
event.ctrlKey ||
151163
event.metaKey ||
152164
event.isComposing ||
153-
event.defaultPrevented ||
154-
!toolbar ||
155-
toolbar.contains(event.target as Node)
165+
event.defaultPrevented
156166
) {
157167
return;
158168
}
159-
if (toolbar.disabled) return;
160-
event.preventDefault();
161-
event.stopPropagation();
162-
toolbar.focus({ preventScroll: true });
169+
if (event.key === "Tab" && !event.shiftKey && !toolbar.contains(event.target as Node)) {
170+
event.preventDefault();
171+
event.stopPropagation();
172+
toolbar.focus({ preventScroll: true });
173+
} else if (isCiteSelectionShortcut(event)) {
174+
event.preventDefault();
175+
event.stopPropagation();
176+
toolbar.click();
177+
}
163178
};
164-
document.addEventListener("keydown", focusActions, true);
179+
document.addEventListener("keydown", handleShortcut, true);
165180
document.addEventListener("selectionchange", actions.selectionChanged);
166181
return () => {
167-
document.removeEventListener("keydown", focusActions, true);
182+
document.removeEventListener("keydown", handleShortcut, true);
168183
document.removeEventListener("selectionchange", actions.selectionChanged);
169184
actions.dispose();
170185
actionsRef.current = null;
@@ -191,6 +206,8 @@ export function AssistantSelectionToolbar({
191206
variant="glass"
192207
disabled={tooLong}
193208
aria-label={tooLong ? "Selection is too long to cite" : "Cite selection in composer"}
209+
aria-keyshortcuts={tooLong ? undefined : "R"}
210+
data-cite-selection-action=""
194211
className="fixed z-50 max-w-[calc(100vw-1rem)]"
195212
style={{ left: selection.position.x, top: selection.position.y }}
196213
onPointerDown={(event) => event.preventDefault()}
@@ -205,6 +222,7 @@ export function AssistantSelectionToolbar({
205222
>
206223
<QuoteIcon aria-hidden="true" className="size-3.5" />
207224
{tooLong ? "Shorten selection" : "Cite"}
225+
{tooLong ? null : <Kbd>R</Kbd>}
208226
</Button>,
209227
document.body,
210228
);

‎apps/web/src/components/chat/composerFocusRedirect.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { isCiteSelectionShortcut } from "./AssistantSelectionToolbar";
2+
13
export const TYPE_TO_FOCUS_EDITABLE_SELECTOR = [
24
"input",
35
"textarea",
@@ -71,6 +73,7 @@ export function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
7173
if (event.key.length !== 1) return false;
7274
if (!shouldRedirectInputToComposer(event)) return false;
7375
if (isSurfaceLauncherKey(event.key)) return false;
76+
if (isCiteSelectionShortcut(event)) return false;
7477

7578
return true;
7679
}

‎docs/user/composer.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ Leaving reasoning level or service tier unset uses the provider's own configurat
116116
## Quote an assistant response
117117

118118
On web and desktop, select text within one assistant response and choose
119-
**Cite in composer**. You can add a comment about the quote and write instructions
119+
**Cite**, or press `R`. You can add a comment about the quote and write instructions
120120
around it.
121121

122122
Select the quote in a draft or sent message to return to its source. If the source

0 commit comments

Comments
 (0)