Skip to content

Commit 2d156a8

Browse files
authored
feat(shortcuts): copy active thread reference (pingdotgg#8994)
Co-authored-by: maria-rcks <[email protected]>
1 parent b5b6abb commit 2d156a8

20 files changed

Lines changed: 500 additions & 16 deletions
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package expo.modules.t3nativecontrols
2+
3+
import android.content.Context
4+
import android.view.KeyEvent
5+
import expo.modules.kotlin.AppContext
6+
import expo.modules.kotlin.modules.Module
7+
import expo.modules.kotlin.modules.ModuleDefinition
8+
import expo.modules.kotlin.viewevent.EventDispatcher
9+
import expo.modules.kotlin.views.ExpoView
10+
11+
class T3KeyboardCommandsModule : Module() {
12+
override fun definition() = ModuleDefinition {
13+
Name("T3KeyboardCommands")
14+
15+
View(T3KeyboardCommandsView::class) {
16+
Prop("enabledCommands") { view: T3KeyboardCommandsView, commands: List<String> ->
17+
view.enabledCommands = commands.toSet()
18+
}
19+
Events("onCommand")
20+
}
21+
}
22+
}
23+
24+
class T3KeyboardCommandsView(
25+
context: Context,
26+
appContext: AppContext
27+
) : ExpoView(context, appContext) {
28+
private val onCommand by EventDispatcher()
29+
var enabledCommands = emptySet<String>()
30+
31+
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
32+
val copiesThreadReference =
33+
event.action == KeyEvent.ACTION_DOWN &&
34+
event.repeatCount == 0 &&
35+
event.keyCode == KeyEvent.KEYCODE_C &&
36+
event.isCtrlPressed &&
37+
event.isShiftPressed &&
38+
!event.isAltPressed &&
39+
enabledCommands.contains("copyThreadReference")
40+
if (copiesThreadReference) {
41+
onCommand(mapOf("command" to "copyThreadReference"))
42+
return true
43+
}
44+
return super.dispatchKeyEvent(event)
45+
}
46+
}

‎apps/mobile/modules/t3-native-controls/expo-module.config.json‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
"modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
55
},
66
"android": {
7-
"modules": ["expo.modules.t3nativecontrols.T3NativeControlsModule"]
7+
"modules": [
8+
"expo.modules.t3nativecontrols.T3NativeControlsModule",
9+
"expo.modules.t3nativecontrols.T3KeyboardCommandsModule"
10+
]
811
}
912
}

‎apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ public final class T3KeyboardCommandsView: ExpoView {
2929
enabledCommand("files", input: "f", modifiers: [.command, .shift], action: #selector(openFiles), title: "Open Files"),
3030
enabledCommand("terminal", input: "t", modifiers: [.command, .shift], action: #selector(openTerminal), title: "Open Terminal"),
3131
enabledCommand("review", input: "r", modifiers: [.command, .shift], action: #selector(openReview), title: "Open Review"),
32+
enabledCommand(
33+
"copyThreadReference",
34+
input: "c",
35+
modifiers: [.command, .shift],
36+
action: #selector(copyThreadReference),
37+
title: "Copy PR Link or Thread ID"
38+
),
3239
enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"),
3340
].compactMap { $0 }
3441
}
@@ -106,6 +113,7 @@ public final class T3KeyboardCommandsView: ExpoView {
106113
@objc private func openFiles() { emit("files") }
107114
@objc private func openTerminal() { emit("terminal") }
108115
@objc private func openReview() { emit("review") }
116+
@objc private func copyThreadReference() { emit("copyThreadReference") }
109117
@objc private func handleToggleSidebar() { emit("toggleSidebar") }
110118

111119
private func emit(_ command: String) {

‎apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx‎

Lines changed: 124 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,22 @@
11
import { StackActions, useNavigation } from "@react-navigation/native";
2-
import { useCallback, useMemo, useSyncExternalStore, type PropsWithChildren } from "react";
2+
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
3+
import {
4+
useCallback,
5+
useEffect,
6+
useMemo,
7+
useRef,
8+
useState,
9+
useSyncExternalStore,
10+
type PropsWithChildren,
11+
} from "react";
312

13+
import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
414
import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
15+
import { useProject, useThreadShell } from "../../state/entities";
16+
import { useEnvironmentQuery } from "../../state/query";
17+
import type { GitActionProgress } from "../../state/use-vcs-action-state";
18+
import { vcsEnvironment } from "../../state/vcs";
19+
import { GitActionProgressOverlay } from "../threads/GitActionProgressOverlay";
520
import {
621
dispatchHardwareKeyboardCommand,
722
getHardwareKeyboardCommandRegistrationVersion,
@@ -11,11 +26,86 @@ import {
1126
type HardwareKeyboardCommand,
1227
} from "./hardwareKeyboardCommands";
1328

29+
const EMPTY_COPY_FEEDBACK: GitActionProgress = {
30+
phase: "idle",
31+
label: null,
32+
description: null,
33+
};
34+
const COPY_FEEDBACK_DISMISS_MS = 3_000;
35+
1436
export function HardwareKeyboardCommandProvider({
1537
children,
1638
pathname,
1739
}: PropsWithChildren<{ readonly pathname: string }>) {
1840
const navigation = useNavigation();
41+
const activeThreadRef = useMemo(() => parseActiveThreadPath(pathname), [pathname]);
42+
const activeThread = useThreadShell(activeThreadRef);
43+
const activeProjectRef = useMemo(
44+
() =>
45+
activeThread === null
46+
? null
47+
: {
48+
environmentId: activeThread.environmentId,
49+
projectId: activeThread.projectId,
50+
},
51+
[activeThread],
52+
);
53+
const activeProject = useProject(activeProjectRef);
54+
const activeThreadCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot ?? null;
55+
const gitStatus = useEnvironmentQuery(
56+
activeThread !== null &&
57+
activeThread.linkedPullRequest == null &&
58+
activeThread.branch !== null &&
59+
activeThreadCwd !== null
60+
? vcsEnvironment.status({
61+
environmentId: activeThread.environmentId,
62+
input: { cwd: activeThreadCwd },
63+
})
64+
: null,
65+
).data;
66+
const detectedPullRequestUrl =
67+
activeThread?.branch != null && gitStatus?.refName === activeThread.branch
68+
? (gitStatus.pr?.url ?? null)
69+
: null;
70+
const copyTarget = useMemo(
71+
() =>
72+
activeThreadRef === null
73+
? null
74+
: resolveThreadReferenceCopyTarget({
75+
threadId: activeThread?.id ?? activeThreadRef.threadId,
76+
linkedPullRequestUrl: activeThread?.linkedPullRequest?.url ?? null,
77+
detectedPullRequestUrl,
78+
}),
79+
[activeThread, activeThreadRef, detectedPullRequestUrl],
80+
);
81+
const [copyFeedback, setCopyFeedback] = useState<GitActionProgress>(EMPTY_COPY_FEEDBACK);
82+
const copyRequestIdRef = useRef(0);
83+
const copyFeedbackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
84+
const dismissCopyFeedback = useCallback(() => {
85+
if (copyFeedbackTimerRef.current !== null) {
86+
clearTimeout(copyFeedbackTimerRef.current);
87+
copyFeedbackTimerRef.current = null;
88+
}
89+
setCopyFeedback(EMPTY_COPY_FEEDBACK);
90+
}, []);
91+
const showCopyFeedback = useCallback((feedback: GitActionProgress) => {
92+
if (copyFeedbackTimerRef.current !== null) {
93+
clearTimeout(copyFeedbackTimerRef.current);
94+
}
95+
setCopyFeedback(feedback);
96+
copyFeedbackTimerRef.current = setTimeout(() => {
97+
copyFeedbackTimerRef.current = null;
98+
setCopyFeedback(EMPTY_COPY_FEEDBACK);
99+
}, COPY_FEEDBACK_DISMISS_MS);
100+
}, []);
101+
useEffect(
102+
() => () => {
103+
if (copyFeedbackTimerRef.current !== null) {
104+
clearTimeout(copyFeedbackTimerRef.current);
105+
}
106+
},
107+
[],
108+
);
19109
const registrationVersion = useSyncExternalStore(
20110
subscribeToHardwareKeyboardCommandRegistrations,
21111
getHardwareKeyboardCommandRegistrationVersion,
@@ -25,10 +115,11 @@ export function HardwareKeyboardCommandProvider({
25115
const commands = new Set<HardwareKeyboardCommand>(getRegisteredHardwareKeyboardCommands());
26116
commands.add("newTask");
27117
if (pathname !== "/" || navigation.canGoBack()) commands.add("back");
28-
if (parseActiveThreadPath(pathname)) {
118+
if (activeThreadRef !== null) {
29119
commands.add("files");
30120
commands.add("terminal");
31121
commands.add("review");
122+
if (pathname.split("/")[4] !== "terminal") commands.add("copyThreadReference");
32123
}
33124
return [...commands];
34125
}, [pathname, registrationVersion, navigation]);
@@ -37,6 +128,30 @@ export function HardwareKeyboardCommandProvider({
37128
(command: HardwareKeyboardCommand) => {
38129
if (dispatchHardwareKeyboardCommand(command)) return;
39130

131+
if (command === "copyThreadReference") {
132+
if (copyTarget === null) return;
133+
const requestId = ++copyRequestIdRef.current;
134+
void tryCopyTextWithHaptic(copyTarget.value, {
135+
target: copyTarget.clipboardTarget,
136+
}).then((didCopy) => {
137+
if (requestId !== copyRequestIdRef.current) return;
138+
showCopyFeedback(
139+
didCopy
140+
? {
141+
phase: "success",
142+
label: copyTarget.successTitle,
143+
description: copyTarget.value,
144+
}
145+
: {
146+
phase: "error",
147+
label: copyTarget.failureTitle,
148+
description: "Try again.",
149+
},
150+
);
151+
});
152+
return;
153+
}
154+
40155
if (command === "newTask") {
41156
navigation.navigate("NewTaskSheet", { screen: "NewTask" });
42157
return;
@@ -62,12 +177,15 @@ export function HardwareKeyboardCommandProvider({
62177
navigation.navigate("ThreadReview", thread);
63178
}
64179
},
65-
[pathname, navigation],
180+
[copyTarget, navigation, pathname, showCopyFeedback],
66181
);
67182

68183
return (
69-
<T3KeyboardCommands enabledCommands={enabledCommands} onCommand={onCommand}>
70-
{children}
71-
</T3KeyboardCommands>
184+
<>
185+
<T3KeyboardCommands enabledCommands={enabledCommands} onCommand={onCommand}>
186+
{children}
187+
</T3KeyboardCommands>
188+
<GitActionProgressOverlay progress={copyFeedback} onDismiss={dismissCopyFeedback} />
189+
</>
72190
);
73191
}

‎apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export type HardwareKeyboardCommand =
88
| "files"
99
| "terminal"
1010
| "review"
11+
| "copyThreadReference"
1112
| "toggleSidebar";
1213

1314
type CommandHandler = () => boolean | void;

‎apps/mobile/src/lib/copyTextWithHaptic.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
CopyTextClipboardWriteError,
2323
CopyTextHapticFeedbackError,
2424
copyTextWithHaptic,
25+
tryCopyTextWithHaptic,
2526
} from "./copyTextWithHaptic";
2627

2728
describe("copyTextWithHaptic", () => {
@@ -54,6 +55,19 @@ describe("copyTextWithHaptic", () => {
5455
expect(mocks.impactAsync).not.toHaveBeenCalled();
5556
});
5657

58+
it("reports whether the clipboard write succeeded", async () => {
59+
mocks.setStringAsync.mockResolvedValueOnce(undefined);
60+
61+
await expect(tryCopyTextWithHaptic("thread-123")).resolves.toBe(true);
62+
});
63+
64+
it("returns false when the clipboard write fails", async () => {
65+
vi.spyOn(console, "error").mockImplementation(() => undefined);
66+
mocks.setStringAsync.mockRejectedValueOnce(new Error("native clipboard failure"));
67+
68+
await expect(tryCopyTextWithHaptic("thread-123")).resolves.toBe(false);
69+
});
70+
5771
it("reports structured failures without including clipboard contents", async () => {
5872
const clipboardCause = new Error("native clipboard failure");
5973
const hapticCause = new Error("native haptic failure");

‎apps/mobile/src/lib/copyTextWithHaptic.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,26 +27,30 @@ export class CopyTextHapticFeedbackError extends Schema.TaggedErrorClass<CopyTex
2727
}
2828
}
2929

30-
export function copyTextWithHaptic(
30+
interface CopyTextWithHapticOptions {
31+
readonly target?: string;
32+
readonly feedback?: "light-impact" | "selection";
33+
}
34+
35+
export async function tryCopyTextWithHaptic(
3136
value: string,
32-
options: {
33-
readonly target?: string;
34-
readonly feedback?: "light-impact" | "selection";
35-
} = {},
36-
): void {
37+
options: CopyTextWithHapticOptions = {},
38+
): Promise<boolean> {
3739
const target = options.target ?? "text";
3840
const feedback = options.feedback ?? "light-impact";
3941

40-
void (async () => {
42+
const clipboardWrite = (async () => {
4143
try {
4244
await Clipboard.setStringAsync(value);
45+
return true;
4346
} catch (cause) {
4447
console.error(
4548
new CopyTextClipboardWriteError({
4649
target,
4750
cause,
4851
}),
4952
);
53+
return false;
5054
}
5155
})();
5256

@@ -67,4 +71,10 @@ export function copyTextWithHaptic(
6771
);
6872
}
6973
})();
74+
75+
return await clipboardWrite;
76+
}
77+
78+
export function copyTextWithHaptic(value: string, options: CopyTextWithHapticOptions = {}): void {
79+
void tryCopyTextWithHaptic(value, options);
7080
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { requireNativeView } from "expo";
2+
import type { PropsWithChildren } from "react";
3+
import type { NativeSyntheticEvent, ViewProps } from "react-native";
4+
5+
import type { HardwareKeyboardCommand } from "../features/keyboard/hardwareKeyboardCommands";
6+
7+
interface NativeKeyboardCommandsProps extends ViewProps, PropsWithChildren {
8+
readonly enabledCommands: ReadonlyArray<HardwareKeyboardCommand>;
9+
readonly onCommand: (
10+
event: NativeSyntheticEvent<{ readonly command: HardwareKeyboardCommand }>,
11+
) => void;
12+
}
13+
14+
const NativeKeyboardCommands = requireNativeView<NativeKeyboardCommandsProps>("T3KeyboardCommands");
15+
16+
export function T3KeyboardCommands(
17+
props: PropsWithChildren<{
18+
readonly enabledCommands: ReadonlyArray<HardwareKeyboardCommand>;
19+
readonly onCommand: (command: HardwareKeyboardCommand) => void;
20+
}>,
21+
) {
22+
return (
23+
<NativeKeyboardCommands
24+
onCommand={(event) => props.onCommand(event.nativeEvent.command)}
25+
enabledCommands={props.enabledCommands}
26+
style={{ flex: 1 }}
27+
>
28+
{props.children}
29+
</NativeKeyboardCommands>
30+
);
31+
}

‎apps/mobile/src/state/use-thread-selection.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ function threadDetailToShell(
5454
interactionMode: thread.interactionMode,
5555
branch: thread.branch,
5656
worktreePath: thread.worktreePath,
57+
linkedPullRequest: thread.linkedPullRequest ?? null,
5758
latestTurn: thread.latestTurn,
5859
createdAt: thread.createdAt,
5960
updatedAt: thread.updatedAt,

‎apps/server/src/keybindings.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
195195

196196
assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+[");
197197
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
198+
assert.equal(defaultsByCommand.get("thread.copyReference"), "mod+shift+c");
198199
assert.equal(defaultsByCommand.get("thread.settle"), "mod+shift+s");
199200
assert.equal(defaultsByCommand.get("thread.pin"), "mod+shift+p");
200201
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");

0 commit comments

Comments
 (0)