Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

openPullRequestLink.ts

75 lines2.3 KB

1import type { LocalApi } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import { type MouseEvent, useCallback } from "react";
4​
5import { stackedThreadToast, toastManager } from "../components/ui/toast";
6import { readLocalApi } from "../localApi";
7​
8export class PullRequestLinkOpenError extends Schema.TaggedErrorClass<PullRequestLinkOpenError>()(
9 "PullRequestLinkOpenError",
10 {
11 targetOrigin: Schema.NullOr(Schema.String),
12 cause: Schema.Defect(),
13 },
14) {
15 static fromCause(targetUrl: string, cause: unknown): PullRequestLinkOpenError {
16 let targetOrigin: string | null = null;
17 try {
18 targetOrigin = new URL(targetUrl).origin;
19 } catch {
20 // Keep malformed URLs out of diagnostics while preserving the open failure below.
21 }
22 return new PullRequestLinkOpenError({ targetOrigin, cause });
23 }
24​
25 override get message(): string {
26 return this.targetOrigin === null
27 ? "Unable to open pull request link."
28 : `Unable to open pull request link at ${this.targetOrigin}.`;
29 }
31​
32export async function openPullRequestLink(
33 shell: Pick<LocalApi["shell"], "openExternal">,
34 targetUrl: string,
35): Promise<void> {
36 try {
37 await shell.openExternal(targetUrl);
38 } catch (cause) {
39 throw PullRequestLinkOpenError.fromCause(targetUrl, cause);
40 }
42​
43/**
44 * Returns a click handler that opens a pull request URL in the system browser.
45 *
46 * Stops event propagation/default so activating the link does not also trigger
47 * an enclosing row or trigger (e.g. opening the branch dropdown), and surfaces a
48 * toast when the local API is unavailable or the open fails.
49 */
50export function useOpenPrLink() {
51 return useCallback((event: MouseEvent<HTMLElement>, prUrl: string) => {
52 event.preventDefault();
53 event.stopPropagation();
54​
55 const api = readLocalApi();
56 if (!api) {
57 toastManager.add({
58 type: "error",
59 title: "Link opening is unavailable.",
60 });
61 return;
62 }
63​
64 void openPullRequestLink(api.shell, prUrl).catch((error) => {
65 console.error(error);
66 toastManager.add(
67 stackedThreadToast({
68 type: "error",
69 title: "Unable to open pull request link",
70 description: error instanceof Error ? error.message : "An error occurred.",
71 }),
72 );
73 });
74 }, []);