Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions apps/web/src/components/ChatView.composer.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1288,6 +1288,90 @@ describe("ChatView (full app): composer", () => {
}
});

it("keeps words selected after Tab when Tab's own focus lands a frame late", async () => {
const suggestion = "Commit this and open the PR";
const { mounted, composerEditor } = await mountPromptSuggestion(suggestion);
// A busy tab draws its next frame late: what Tab put off until then
// runs after the user's next keys.
const realRequestAnimationFrame = window.requestAnimationFrame;
const heldFrames: FrameRequestCallback[] = [];
try {
await page.getByTestId("composer-editor").fill("commit this");
await waitForElement(
() => document.querySelector<HTMLElement>('[data-prompt-suggestion-remainder="true"]'),
"Typing the suggestion's first words dropped the rest of it.",
);
window.requestAnimationFrame = (callback) => {
heldFrames.push(callback);
return heldFrames.length;
};
composerEditor.focus();
composerEditor.dispatchEvent(
new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }),
);
await waitForElement(
() =>
composerEditor.textContent?.trim() === "commit this and open the PR"
? composerEditor
: null,
"Tab never finished the suggestion.",
);
await page.getByTestId("composer-editor").fill("commit this");
await waitForElement(
() => document.querySelector<HTMLElement>('[data-prompt-suggestion-remainder="true"]'),
"The rest did not come back after retyping the suggestion's first words.",
);
await userEvent.keyboard("{Shift>}{ArrowLeft}{ArrowLeft}{/Shift}");
window.requestAnimationFrame = realRequestAnimationFrame;
for (const callback of heldFrames.splice(0)) callback(performance.now());
await nextFrames(3);
await waitForSuggestionGone("The rest stayed after the cursor while words were selected.");
expect(window.getSelection()?.toString()).toBe("is");
} finally {
window.requestAnimationFrame = realRequestAnimationFrame;
await mounted.cleanup();
}
});

it("keeps words selected right after Tab when Tab's own focus lands a frame late", async () => {
const suggestion = "Commit this and open the PR";
const { mounted, composerEditor } = await mountPromptSuggestion(suggestion);
const realRequestAnimationFrame = window.requestAnimationFrame;
const heldFrames: FrameRequestCallback[] = [];
try {
await page.getByTestId("composer-editor").fill("commit this");
await waitForElement(
() => document.querySelector<HTMLElement>('[data-prompt-suggestion-remainder="true"]'),
"Typing the suggestion's first words dropped the rest of it.",
);
window.requestAnimationFrame = (callback) => {
heldFrames.push(callback);
return heldFrames.length;
};
composerEditor.focus();
composerEditor.dispatchEvent(
new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }),
);
await waitForElement(
() =>
composerEditor.textContent?.trim() === "commit this and open the PR"
? composerEditor
: null,
"Tab never finished the suggestion.",
);
// The text is still what Tab wrote; only words got selected since.
await userEvent.keyboard("{Shift>}{ArrowLeft}{ArrowLeft}{/Shift}");
await vi.waitFor(() => expect(window.getSelection()?.toString()).toBe("PR"));
window.requestAnimationFrame = realRequestAnimationFrame;
for (const callback of heldFrames.splice(0)) callback(performance.now());
await nextFrames(3);
expect(window.getSelection()?.toString()).toBe("PR");
} finally {
window.requestAnimationFrame = realRequestAnimationFrame;
await mounted.cleanup();
}
});

it("lines the rest of the suggestion up with the typed words wherever they wrap", async () => {
// The long word starts past the middle of the first line, so while it is
// half typed it fits there, but the whole word does not.
Expand Down
13 changes: 12 additions & 1 deletion apps/web/src/components/ComposerPromptEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1190,6 +1190,8 @@ export interface ComposerPromptEditorHandle {
focusAtEnd: () => void;
/** Whether a suggestion's rest can show after the cursor; see `canShowPromptCompletion`. */
canShowCompletion: () => boolean;
/** Whether words are selected in the editor (a range, not a caret). */
hasSelectedText: () => boolean;
readSnapshot: () => {
value: string;
cursor: number;
Expand Down Expand Up @@ -1921,6 +1923,14 @@ function ComposerPromptEditorInner({
return snapshot;
}, [editor]);
const canShowCompletion = useCallback(() => canShowPromptCompletion(editor), [editor]);
const hasSelectedText = useCallback(
() =>
editor.getEditorState().read(() => {
const selection = $getSelection();
return $isRangeSelection(selection) && !selection.isCollapsed();
}),
[editor],
);

useImperativeHandle(
editorRef,
Expand All @@ -1930,6 +1940,7 @@ function ComposerPromptEditorInner({
},
focusAt,
canShowCompletion,
hasSelectedText,
focusAtEnd: () => {
focusAt(
collapseExpandedComposerCursor(
Expand All @@ -1940,7 +1951,7 @@ function ComposerPromptEditorInner({
},
readSnapshot,
}),
[canShowCompletion, focusAt, readSnapshot],
[canShowCompletion, focusAt, hasSelectedText, readSnapshot],
);

const handleEditorChange = useCallback((editorState: EditorState) => {
Expand Down
55 changes: 36 additions & 19 deletions apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2007,6 +2007,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[composerDraftTarget, setComposerDraftPrompt],
);

/**
* Puts the cursor at `cursor` (or the end) after a write to the message box,
* a frame later, once the write has rendered. A busy page draws that frame
* late, after the user's next keys: when the box no longer holds what was
* written, or the user has selected words in it since, it is left as is
* (moving the cursor then would undo the typing or collapse the selection).
*/
const focusAfterWrite = useCallback(
(writtenPrompt: string, cursor: number | "end") => {
window.requestAnimationFrame(() => {
const editor = composerEditorRef.current;
if (!editor || promptRef.current !== writtenPrompt || editor.hasSelectedText()) return;
if (cursor === "end") editor.focusAtEnd();
else editor.focusAt(cursor);
});
},
[promptRef],
);

/** Replaces what the message box holds and puts the cursor at its end. */
const fillComposerPrompt = useCallback(
(nextPrompt: string) => {
Expand All @@ -2015,11 +2034,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length);
setComposerCursor(nextCursor);
setComposerTrigger(null);
window.requestAnimationFrame(() => {
composerEditorRef.current?.focusAt(nextCursor);
});
focusAfterWrite(nextPrompt, nextCursor);
},
[promptRef, setPrompt],
[focusAfterWrite, promptRef, setPrompt],
);

const addComposerAttachment = useCallback(
Expand Down Expand Up @@ -2209,9 +2226,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// Only yank the caret to the end when text was actually inserted;
// restoring attachments alone should leave the user where they were.
if (promptChanged) {
window.requestAnimationFrame(() => {
composerEditorRef.current?.focusAtEnd();
});
focusAfterWrite(nextPrompt, "end");
}
},
[
Expand All @@ -2224,6 +2239,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerAttachmentsRef,
composerDraftTarget,
composerPickedElementContextsRef,
focusAfterWrite,
promptRef,
setPrompt,
takeStashEntry,
Expand Down Expand Up @@ -2789,13 +2805,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
setComposerCursor(nextCursor);
setComposerTrigger(detectComposerTrigger(next.text, nextExpandedCursor));
if (options?.focusEditorAfterReplace !== false) {
window.requestAnimationFrame(() => {
composerEditorRef.current?.focusAt(nextCursor);
});
focusAfterWrite(next.text, nextCursor);
}
return true;
},
[promptRef, setPrompt],
[focusAfterWrite, promptRef, setPrompt],
);

// Dictation adds to what is typed instead of replacing it, so it lands at
Expand Down Expand Up @@ -2882,11 +2896,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length);
setComposerCursor(nextCursor);
setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length));
window.requestAnimationFrame(() => {
composerEditorRef.current?.focusAt(nextCursor);
});
focusAfterWrite(nextPrompt, nextCursor);
return true;
}, [promptRef, promptSuggestion, promptSuggestionView, readComposerSnapshot, setPrompt]);
}, [
focusAfterWrite,
promptRef,
promptSuggestion,
promptSuggestionView,
readComposerSnapshot,
setPrompt,
]);
// Up and Down bring back what the user wrote here before (shell style):
// see stepPromptRecall. The recalled text is remembered so an edit hands
// the arrows back to the caret.
Expand All @@ -2909,12 +2928,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const nextCursor = collapseExpandedComposerCursor(step.value, step.value.length);
setComposerCursor(nextCursor);
setComposerTrigger(null);
window.requestAnimationFrame(() => {
composerEditorRef.current?.focusAt(nextCursor);
});
focusAfterWrite(step.value, nextCursor);
return true;
},
[promptRef, readComposerSnapshot, setPrompt, threadMessages],
[focusAfterWrite, promptRef, readComposerSnapshot, setPrompt, threadMessages],
);
// Stays set while the box fills and empties again, so the editor keeps the
// suggestion mounted and its fade-in plays once.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2114,7 +2114,7 @@ describe("text selection popover with the real virtual list", () => {
expect(window.getSelection()!.toString()).toBe("pelican");
expect(isShown(selectionPopover())).toBe(true);
expect(Math.abs(gapBelowWord() - gap)).toBeLessThanOrEqual(1);
});
}, AFTER_SCROLL);
moveRow();
await expectSelectionBack();

Expand Down
Loading