Repository navigation
feat(web): press R to cite selected assistant text #25570
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
0fc225e
ab6f01f
ec71712
a5b0cb3
7e3bb52
3edab75
abc9f7e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| import { EnvironmentId, ThreadId } from "@t3tools/contracts"; | ||
| import { useState, type ComponentProps } from "react"; | ||
| import { describe, expect, it, vi } from "vite-plus/test"; | ||
| import { page, userEvent } from "vite-plus/test/browser"; | ||
|
|
||
| import { render } from "../../../test/render"; | ||
| import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar"; | ||
| import type { ChatComposerHandle } from "./ChatComposer"; | ||
| import { useChatShortcuts } from "./useChatShortcuts"; | ||
|
|
||
| type OnCite = ComponentProps<typeof AssistantSelectionToolbar>["onCite"]; | ||
|
|
||
| const threadRef = { | ||
| environmentId: EnvironmentId.make("environment"), | ||
| threadId: ThreadId.make("thread"), | ||
| }; | ||
|
|
||
| // The chat's window capture listener runs before the toolbar's document listener, so | ||
| // type-to-focus sees every key first. The stand-in composer records what it receives. | ||
| function ChatShortcuts(props: { composerKeys: string[] }) { | ||
| useChatShortcuts({ | ||
| enabled: true, | ||
| keybindings: [], | ||
| scriptKeybindings: [], | ||
| getShortcutContext: () => ({ | ||
| terminalFocus: false, | ||
| terminalOpen: false, | ||
| previewFocus: false, | ||
| previewOpen: false, | ||
| isWeb: true, | ||
| isDesktop: false, | ||
| modelPickerOpen: false, | ||
| }), | ||
| threadFindActive: false, | ||
| composerRef: { | ||
| current: { | ||
| insertTextAtEnd: (key: string) => { | ||
| props.composerKeys.push(key); | ||
| return true; | ||
| }, | ||
| } as Partial<ChatComposerHandle> as ChatComposerHandle, | ||
| }, | ||
| branchToolbarRef: { current: null }, | ||
| closeThreadFind: () => {}, | ||
| commands: {}, | ||
| fallback: () => undefined, | ||
| }); | ||
| return null; | ||
| } | ||
|
|
||
| function Transcript(props: { onCite: OnCite; composerKeys?: string[] }) { | ||
| const [viewport, setViewport] = useState<HTMLElement | null>(null); | ||
| return ( | ||
| <> | ||
| {props.composerKeys ? <ChatShortcuts composerKeys={props.composerKeys} /> : null} | ||
| <div ref={setViewport}> | ||
| <div data-assistant-citation-source="message-1"> | ||
| <p>Render the citation chip</p> | ||
| </div> | ||
| </div> | ||
| <AssistantSelectionToolbar viewport={viewport} threadRef={threadRef} onCite={props.onCite} /> | ||
| </> | ||
| ); | ||
| } | ||
|
|
||
| // router: false because the transcript never navigates. | ||
| const options = { router: false } as const; | ||
| const citeButton = page.getByRole("button", { name: "Cite selection in composer" }); | ||
|
|
||
| async function selectAssistantText(container: HTMLElement) { | ||
| const text = container.querySelector("p")!.firstChild!; | ||
| window.getSelection()!.setBaseAndExtent(text, 7, text, 15); | ||
| await expect.element(citeButton).toBeVisible(); | ||
| } | ||
|
|
||
| describe("AssistantSelectionToolbar", () => { | ||
| it.each(["r", "R"])("cites with %s instead of typing it into the composer", async (key) => { | ||
| const onCite = vi.fn<OnCite>(() => true); | ||
| const composerKeys: string[] = []; | ||
| await using screen = await render( | ||
| <Transcript onCite={onCite} composerKeys={composerKeys} />, | ||
| options, | ||
| ); | ||
| await selectAssistantText(screen.container); | ||
|
|
||
| await userEvent.keyboard(key); | ||
|
|
||
| expect(onCite).toHaveBeenCalledOnce(); | ||
| expect(onCite.mock.lastCall![0]).toMatchObject({ messageId: "message-1", text: "the cita" }); | ||
| expect(composerKeys).toEqual([]); | ||
| expect(window.getSelection()!.isCollapsed).toBe(true); | ||
| await expect.element(citeButton).not.toBeInTheDocument(); | ||
| }); | ||
|
|
||
| it("types R into the composer when nothing is selected", async () => { | ||
| const onCite = vi.fn<OnCite>(() => true); | ||
| const composerKeys: string[] = []; | ||
| await using _screen = await render( | ||
| <Transcript onCite={onCite} composerKeys={composerKeys} />, | ||
| options, | ||
| ); | ||
|
|
||
| await userEvent.keyboard("r"); | ||
|
|
||
| expect(composerKeys).toEqual(["r"]); | ||
| expect(onCite).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| // Dispatched rather than typed so a real Ctrl+R cannot reload the test page. | ||
| it.each([ | ||
| ["Cmd+R", { metaKey: true }], | ||
| ["Ctrl+R", { ctrlKey: true }], | ||
| ["Alt+R", { altKey: true }], | ||
| ])("leaves %s to the browser", async (_name, modifier) => { | ||
| const onCite = vi.fn<OnCite>(() => true); | ||
| await using screen = await render(<Transcript onCite={onCite} />, options); | ||
| await selectAssistantText(screen.container); | ||
|
|
||
| const event = new KeyboardEvent("keydown", { | ||
| key: "r", | ||
| bubbles: true, | ||
| cancelable: true, | ||
| ...modifier, | ||
| }); | ||
| document.body.dispatchEvent(event); | ||
|
|
||
| expect(event.defaultPrevented).toBe(false); | ||
| expect(onCite).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("still focuses the Cite action on Tab", async () => { | ||
| const onCite = vi.fn<OnCite>(() => true); | ||
| await using screen = await render(<Transcript onCite={onCite} />, options); | ||
| await selectAssistantText(screen.container); | ||
|
|
||
| await userEvent.keyboard("{Tab}"); | ||
|
|
||
| await expect.element(citeButton).toHaveFocus(); | ||
| expect(onCite).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -19,7 +19,9 @@ import { | |
| type SelectionActionPoint, | ||
| } from "~/lib/selectionActions"; | ||
| import { Button } from "../ui/button"; | ||
| import { Kbd } from "../ui/kbd"; | ||
| import { BackgroundThreadContext } from "./backgroundThread"; | ||
| import { isCiteSelectionShortcut } from "./composerFocusRedirect"; | ||
|
|
||
| export function AssistantSelectionToolbar({ | ||
| viewport, | ||
|
|
@@ -147,31 +149,34 @@ export function AssistantSelectionToolbar({ | |
| onDismiss: clear, | ||
| }); | ||
| actionsRef.current = actions; | ||
| const focusActions = (event: KeyboardEvent) => { | ||
| const handleShortcut = (event: KeyboardEvent) => { | ||
| const toolbar = toolbarRef.current; | ||
| if ( | ||
| event.key !== "Tab" || | ||
| event.shiftKey || | ||
| !toolbar || | ||
| toolbar.disabled || | ||
| event.altKey || | ||
| event.ctrlKey || | ||
| event.metaKey || | ||
| event.isComposing || | ||
| event.defaultPrevented || | ||
| !toolbar || | ||
| toolbar.contains(event.target as Node) | ||
| event.defaultPrevented | ||
| ) { | ||
| return; | ||
| } | ||
| if (toolbar.disabled) return; | ||
| event.preventDefault(); | ||
| event.stopPropagation(); | ||
| toolbar.focus({ preventScroll: true }); | ||
| if (event.key === "Tab" && !event.shiftKey && !toolbar.contains(event.target as Node)) { | ||
| event.preventDefault(); | ||
| event.stopPropagation(); | ||
| toolbar.focus({ preventScroll: true }); | ||
| } else if (isCiteSelectionShortcut(event)) { | ||
| event.preventDefault(); | ||
| event.stopPropagation(); | ||
| toolbar.click(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Refresh the selection before keyboard citation. If the user extends the selection with Shift+ArrowRight and presses R before the pending selection refresh runs, Validate or refresh the selected text before shortcut activation. Add a case to the keyboard coverage that changes the selection and presses R before the scheduled refresh.
|
||
| } | ||
| }; | ||
| // Tab belongs to the foreground chat; a background timeline only follows its selection. | ||
| if (!backgroundThread) document.addEventListener("keydown", focusActions, true); | ||
| // Tab and R belong to the foreground chat; a background timeline only follows its selection. | ||
| if (!backgroundThread) document.addEventListener("keydown", handleShortcut, true); | ||
| document.addEventListener("selectionchange", actions.selectionChanged); | ||
| return () => { | ||
| document.removeEventListener("keydown", focusActions, true); | ||
| document.removeEventListener("keydown", handleShortcut, true); | ||
| document.removeEventListener("selectionchange", actions.selectionChanged); | ||
| actions.dispose(); | ||
| actionsRef.current = null; | ||
|
|
@@ -180,6 +185,7 @@ export function AssistantSelectionToolbar({ | |
|
|
||
| if (!selection) return null; | ||
| const tooLong = selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH; | ||
| const shortcut = !tooLong && !backgroundThread; | ||
| const dismiss = () => { | ||
| actionsRef.current?.cancel(); | ||
| setSelection(null); | ||
|
|
@@ -198,6 +204,8 @@ export function AssistantSelectionToolbar({ | |
| variant="glass" | ||
| disabled={tooLong} | ||
| aria-label={tooLong ? gt("Selection is too long to cite") : gt("Cite selection in composer")} | ||
| aria-keyshortcuts={shortcut ? "R" : undefined} | ||
| data-cite-selection-action={shortcut ? "" : undefined} | ||
| className="fixed z-50 max-w-[calc(100vw-1rem)]" | ||
| style={{ left: selection.position.x, top: selection.position.y }} | ||
| onPointerDown={(event) => event.preventDefault()} | ||
|
|
@@ -214,6 +222,7 @@ export function AssistantSelectionToolbar({ | |
| {tooLong | ||
| ? gt("Shorten selection") | ||
| : gt("Cite", { $context: "verb, button that quotes the selected text" })} | ||
| {shortcut ? <Kbd>R</Kbd> : null} | ||
| </Button>, | ||
| document.body, | ||
| ); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: pingdotgg/t3code
Length of output: 13920
Script executed:
Repository: pingdotgg/t3code
Length of output: 41754
Script executed:
Repository: pingdotgg/t3code
Length of output: 41557
Script executed:
Repository: pingdotgg/t3code
Length of output: 36774
Script executed:
Repository: pingdotgg/t3code
Length of output: 15187
Script executed:
Repository: pingdotgg/t3code
Length of output: 11252
Do not consume the cite shortcut from editable fields.
A field can remain focused while a pointer selection is made in the assistant response. The selection observer then restores the toolbar after
mouseup. The document capture handler currently preventsrand clicks Cite before the focused field receives it. Check for input and textarea targets before handling the cite shortcut.Suggested fix
Committable suggestion