GeezerVison is showing github.com — fix(web): add copying terminal selection with ctrl+c in the web app by UtkarshUsername · Pull Request #5638 · pingdotgg/t3code
fix(web): add copying terminal selection with ctrl+c in the web app
#5638
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
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.ts
(7)
.tsx
(2)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -440,7 +440,6 @@ export function TerminalViewport({
onData: (data) => handleData(data),
onResize: (cols, rows) => void resizeTerminal(cols, rows),
onSelectionChange: () => handleSelectionChange(),
onCopy: (text) => handleCopy(text),
beforeKey: (event) => handleBeforeKey(event),
onLinkActivate: (text, event) => handleLinkActivate(text, event),
};
Expand Down
Expand Up
@@ -668,17 +667,6 @@ export function TerminalViewport({
})();
}
function handleCopy(text: string): void {
void writeTextToClipboard(text, "terminal selection").catch((error: unknown) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
writeSystemMessage(
activeTerminal,
error instanceof Error ? error.message : "Unable to copy terminal selection",
);
});
}
function handleData(data: string): void {
void (async () => {
const result = await writeTerminal(data);
Expand All
@@ -696,6 +684,12 @@ export function TerminalViewport({
return;
}
clearSelectionAction();
// A copy shortcut that clears the selection (Ctrl+C) must also close
// the context menu that appears with the selection, but a clear that
// never opened a menu must not dismiss an unrelated one.
if (selectionActionMenuOpenRef.current) {
void localApi?.contextMenu.close();
}
}
const handleMouseUp = (event: MouseEvent) => {
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -238,7 +238,6 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
onData: echo,
onResize: noop,
onSelectionChange: noop,
onCopy: (text) => void navigator.clipboard?.writeText(text).catch(noop),
// Tab keeps walking the settings page instead of feeding the echo loop.
beforeKey: (event) => event.key !== "Tab",
onLinkActivate: noop,
Expand Down
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { showContextMenuFallback } from "./contextMenuFallback";
import { dismissContextMenu, showContextMenuFallback } from "./contextMenuFallback";
type FakeListener = (event: FakeDomEvent) => void;
Expand Down
Expand Up
@@ -236,3 +236,37 @@ describe("showContextMenuFallback", () => {
await expect(selectionPromise).resolves.toBe("rename:project-b");
});
});
describe("dismissContextMenu", () => {
it("resolves an open menu with null", async () => {
const selectionPromise = showContextMenuFallback([
{ id: "rename", label: "Rename" },
{ id: "delete", label: "Delete" },
]);
expect(findButton("Rename")).toBeTruthy();
dismissContextMenu();
await expect(selectionPromise).resolves.toBeNull();
expect(findButton("Rename")).toBeUndefined();
});
it("is a no-op when no menu is open", async () => {
dismissContextMenu();
expect(findButton("Rename")).toBeUndefined();
});
it("dismisses the prior menu when a new one opens", async () => {
const firstPromise = showContextMenuFallback([{ id: "first", label: "First" }]);
expect(findButton("First")).toBeTruthy();
const secondPromise = showContextMenuFallback([{ id: "second", label: "Second" }]);
await expect(firstPromise).resolves.toBeNull();
expect(findButton("First")).toBeUndefined();
expect(findButton("Second")).toBeTruthy();
dismissContextMenu();
await expect(secondPromise).resolves.toBeNull();
});
});
Original file line number
Diff line number
Diff line change
Expand Up
@@ -101,6 +101,21 @@ function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly H
return false;
}
// Only one fallback menu exists at a time in the renderer; the active one is
// tracked so a state change (for example a terminal selection clearing) can
// dismiss it with the same result as an outside click or Escape.
let activeContextMenuDismiss: (() => void) | null = null;
/**
* Closes the currently open fallback context menu, resolving its show() with
* null (the same result as dismissing by outside click or Escape). No-op when
* no fallback menu is open.
*/
export function dismissContextMenu(): void {
activeContextMenuDismiss?.();
activeContextMenuDismiss = null;
}
/**
* Imperative DOM-based context menu for non-Electron environments.
* Supports nested submenus and resolves with the clicked leaf item id.
Expand All
@@ -114,11 +129,16 @@ export function showContextMenuFallback<T extends string>(
let isDisposed = false;
let canDismissFromPointer = false;
const dismiss = () => cleanup(null);
const cleanup = (result: T | null) => {
if (isDisposed) {
return;
}
isDisposed = true;
if (activeContextMenuDismiss === dismiss) {
activeContextMenuDismiss = null;
}
document.removeEventListener("keydown", onKeyDown);
document.removeEventListener("pointerdown", onPointerDown, true);
document.removeEventListener("contextmenu", onContextMenu, true);
Expand Down
Expand Up
@@ -299,6 +319,13 @@ export function showContextMenuFallback<T extends string>(
document.addEventListener("pointerdown", onPointerDown, true);
document.addEventListener("contextmenu", onContextMenu, true);
openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
// Only one fallback menu can be open at a time: a new show must dismiss
// any prior one, or its DOM and listeners leak and close() can only ever
// reach the newest menu.
if (activeContextMenuDismiss) {
activeContextMenuDismiss();
}
activeContextMenuDismiss = dismiss;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
requestAnimationFrame(() => {
canDismissFromPointer = true;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -13,12 +13,14 @@ const showContextMenuFallbackMock =
position?: { x: number; y: number },
) => Promise<T | null>
>();
const dismissContextMenuMock = vi.fn<() => void>();
const requestConfirmDialogMock =
vi.fn<(message: string, options?: ConfirmDialogOptions) => Promise<boolean> | undefined>();
vi.mock("./contextMenuFallback", () => ({
showContextMenuFallback: showContextMenuFallbackMock,
dismissContextMenu: dismissContextMenuMock,
}));
vi.mock("./confirmDialog", () => ({
Expand Down
Expand Up
@@ -85,6 +87,14 @@ describe("LocalApi", () => {
expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });
});
it("dismisses an open browser context menu without a desktop bridge", async () => {
const { createLocalApi } = await import("./localApi");
await createLocalApi().contextMenu.close();
expect(dismissContextMenuMock).toHaveBeenCalledOnce();
});
it("uses the themed confirmation host when it is available", async () => {
requestConfirmDialogMock.mockResolvedValue(true);
const { createLocalApi } = await import("./localApi");
Expand Down
Original file line number
Diff line number
Diff line change
@@ -1,7 +1,7 @@
import type { ConfirmDialogOptions, ContextMenuItem, LocalApi } from "@t3tools/contracts";
import { requestConfirmDialog } from "./confirmDialog";
import { showContextMenuFallback } from "./contextMenuFallback";
import { dismissContextMenu, showContextMenuFallback } from "./contextMenuFallback";
import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientPersistenceStorage";
import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
Expand Down
Expand Up
@@ -41,6 +41,14 @@ function createBrowserLocalApi(): LocalApi {
}
return showContextMenuFallback(items, position);
},
// A native desktop menu blocks keyboard input and closes on outside
// interaction, so nothing to do there; the DOM fallback needs an explicit
// dismiss when the state behind it goes away.
close: async () => {
if (!window.desktopBridge) {
dismissContextMenu();
}
},
},
persistence: {
getClientSettings: async () => {
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -219,11 +219,12 @@ describe("isTerminalCopyShortcut", () => {
expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
});
it("uses the conventional Ctrl+Shift+C shortcut elsewhere", () => {
expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(false );
it("copies with Ctrl+C and Ctrl+Shift+C elsewhere", () => {
expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(true );
expect(isTerminalCopyShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
true,
);
expect(isTerminalCopyShortcut(event({}), "Linux x86_64")).toBe(false);
});
it("uses the produced character instead of the physical key position", () => {
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -333,7 +333,7 @@ export function isTerminalCopyShortcut(
platform = navigator.platform,
) {
if (event.key.toLowerCase() !== "c") return false;
return isMacPlatform(platform) ? event.metaKey : event.ctrlKey && event.shiftKey ;
return isMacPlatform(platform) ? event.metaKey : event.ctrlKey;
}
export function isTerminalPasteShortcut(
Expand Down
Expand Up
@@ -463,7 +463,6 @@ export interface GhosttyTerminalSurfaceOptions {
readonly onData: (data: string) => void;
readonly onResize: (cols: number, rows: number) => void;
readonly onSelectionChange: () => void;
readonly onCopy: (text: string) => void;
readonly beforeKey: (event: KeyboardEvent) => boolean;
readonly onLinkActivate: (text: string, event: MouseEvent) => void;
}
Expand Down
Expand Up
@@ -531,6 +530,8 @@ export class GhosttyTerminalSurface {
private theme: GhosttyTheme;
private readonly suppressedKeyCodes = new Set<string>();
private pasteShortcutToken = 0;
private copyShortcutToken = 0;
private clearSelectionAfterCopy = false;
private wheelRemainder = 0;
private dprMedia: MediaQueryList | null = null;
// Read live on every blink decision, and watched so that dropping the
Expand Down
Expand Up
@@ -901,9 +902,58 @@ export class GhosttyTerminalSurface {
return;
}
if (isTerminalCopyShortcut(event) && this.hasSelection()) {
event.preventDefault();
// A plain Ctrl+C/Cmd+C fires the browser's native copy event, caught in
// onCopyEvent; not preventing the default keeps that path alive. WebKit
// omits the keyboard copy event without a DOM selection, so race the
// clipboard write against it the same way paste races its read. The
// Shift variant has no native event (Chrome binds Ctrl+Shift+C to
// inspect), so synthesize one with execCommand("copy").
if (event.shiftKey) {
event.preventDefault();
document.execCommand("copy");
} else {
// A plain Ctrl+C is also SIGINT on non-mac: clear the selection once
// it copies so the next Ctrl+C reaches the shell. The Shift chord and
// Cmd+C are copy-only, so they keep the selection; resetting the flag
// up front also drops any clear owed by an earlier gesture that never
// completed.
this.clearSelectionAfterCopy = !event.shiftKey && !isMacPlatform(navigator.platform);
const clipboard = navigator.clipboard;
if (typeof clipboard?.writeText === "function") {
// Defer the write past the default action: the native copy event
// (dispatched synchronously with the default action) claims the
// token first when it fires, and the write covers browsers whose
// shortcut produces no copy event. Skipping a write the native
// event already handled stops a stale resolution from clobbering a
// clipboard the user filled after this copy.
const token = ++this.copyShortcutToken;
const selection = this.getSelection();
void Promise.resolve().then(() => {
if (this.disposed || this.copyShortcutToken !== token) return;
void clipboard.writeText(selection).then(
() => {
// The write may have been superseded while in flight; only
// touch the selection if this gesture still owns the token.
if (this.disposed || this.copyShortcutToken !== token) return;
if (this.clearSelectionAfterCopy) {
this.clearSelectionAfterCopy = false;
this.clearSelection();
}
},
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
() => {
// The write failed and the native event has already had its
// chance, so nothing copied and no clear is owed by this
// gesture; a newer one may have just set the flag, so only
// drop it if this gesture still owns the token.
if (this.copyShortcutToken === token) {
this.clearSelectionAfterCopy = false;
}
},
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
);
});
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
this.suppressedKeyCodes.add(event.code);
this.options.onCopy(this.getSelection());
return;
}
if (isTerminalPasteShortcut(event)) {
Expand Down
Expand Up
@@ -989,6 +1039,18 @@ export class GhosttyTerminalSurface {
this.dprMedia.addEventListener("change", this.onDevicePixelRatioChange);
}
private readonly onCopyEvent = (event: ClipboardEvent) => {
if (!this.hasSelection()) return;
event.preventDefault();
event.clipboardData?.setData("text/plain", this.getSelection());
// The native event beat any deferred write; drop the in-flight fallback.
this.copyShortcutToken += 1;
if (this.clearSelectionAfterCopy) {
this.clearSelectionAfterCopy = false;
this.clearSelection();
}
};
private readonly onPaste = (event: ClipboardEvent) => {
// Always suppress the browser's default insertion: content the textarea
// would receive (for example an html-only clipboard converted to text)
Expand Down
Expand Up
@@ -1384,6 +1446,7 @@ export class GhosttyTerminalSurface {
this.input.addEventListener("blur", this.onBlur);
this.input.addEventListener("input", this.onInput);
this.input.addEventListener("paste", this.onPaste);
this.input.addEventListener("copy", this.onCopyEvent);
this.input.addEventListener("compositionstart", this.onCompositionStart);
this.input.addEventListener("compositionend", this.onCompositionEnd);
this.canvas.addEventListener("pointerdown", this.onPointerDown);
Expand All
@@ -1408,6 +1471,7 @@ export class GhosttyTerminalSurface {
this.input.removeEventListener("blur", this.onBlur);
this.input.removeEventListener("input", this.onInput);
this.input.removeEventListener("paste", this.onPaste);
this.input.removeEventListener("copy", this.onCopyEvent);
this.input.removeEventListener("compositionstart", this.onCompositionStart);
this.input.removeEventListener("compositionend", this.onCompositionEnd);
this.canvas.removeEventListener("pointerdown", this.onPointerDown);
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -1189,6 +1189,7 @@ export interface LocalApi {
items: readonly ContextMenuItem<T>[],
position?: { x: number; y: number },
) => Promise<T | null>;
close: () => Promise<void>;
};
persistence: {
getClientSettings: () => Promise<ClientSettings | null>;
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.