Skip to content
Closed
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
50 changes: 50 additions & 0 deletions apps/web/src/browser/browserLinkTarget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,54 @@ describe("resolveLinkTarget", () => {
);
}
});

it("resolves to app when preference is app, in-app opening is available, and url is web url", () => {
expect(
resolveLinkTarget({
url: "https://github.com/owner/repo/pull/1",
event: click,
preference: "app",
canOpenInApp: true,
}),
).toBe("app");
});

it("resolves to system when preference is system", () => {
expect(
resolveLinkTarget({
url: "https://github.com/owner/repo/pull/1",
event: click,
preference: "system",
canOpenInApp: true,
}),
).toBe("system");
});

it("resolves to system when modified with meta or ctrl or middle-clicked", () => {
for (const event of [
{ metaKey: true, ctrlKey: false },
{ metaKey: false, ctrlKey: true },
{ metaKey: false, ctrlKey: false, button: 1 },
]) {
expect(
resolveLinkTarget({
url: "https://github.com/owner/repo/pull/1",
event,
preference: "app",
canOpenInApp: true,
}),
).toBe("system");
}
});

it("resolves to system when in-app opening is unavailable", () => {
expect(
resolveLinkTarget({
url: "https://github.com/owner/repo/pull/1",
event: click,
preference: "app",
canOpenInApp: false,
}),
).toBe("system");
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import "~/index.css";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { Cause } from "effect";
Expand All @@ -9,6 +10,7 @@ const mocks = vi.hoisted(() => ({
update:
vi.fn<(input: unknown) => Promise<{ _tag: "Success" } | { _tag: "Failure"; cause: unknown }>>(),
notify: vi.fn(),
openLink: vi.fn<(url: string, options?: unknown) => Promise<void>>(),
}));
vi.mock(
import("~/state/pullRequests"),
Expand All @@ -20,9 +22,14 @@ vi.mock(
);

vi.mock(import("../ui/toast"), () => ({ toastManager: { add: mocks.notify } }) as never);
vi.mock(import("~/state/server"), async () => {
vi.mock(import("~/browser/useOpenLink"), () => ({
useOpenLink: (threadRef: unknown) => (url: string, options?: unknown) =>
mocks.openLink(url, { ...(options as object | undefined), threadRef }),
}));
vi.mock(import("~/state/server"), async (original) => {
const actual = await original();
const { Atom } = await import("effect/reactivity");
return { primaryServerKeybindingsAtom: Atom.make([]) } as never;
return { ...actual, primaryServerKeybindingsAtom: Atom.make([]) } as never;
});
vi.mock(import("./PullRequestThreadLinks"), () => ({ PullRequestThreadLinks: () => null }));
vi.mock(
Expand Down Expand Up @@ -68,13 +75,15 @@ const openDetail: Detail = {
function setup() {
mocks.update.mockReset().mockResolvedValue({ _tag: "Success" });
mocks.notify.mockReset();
return (detail: Detail = openDetail) => (
mocks.openLink.mockReset().mockResolvedValue(undefined);
return (detail: Detail = openDetail, threadRef: ScopedThreadRef | null = null) => (
<PullRequestActionsMenu
environmentId={environmentId}
reference={reference}
pullRequestKey="owner/repo/7"
detail={detail}
terminology={sourceControlClients.get("github").changeRequest}
threadRef={threadRef}
linkThreadRef={null}
onThreadPickerOpenChange={() => {}}
refreshing={false}
Expand Down Expand Up @@ -210,3 +219,28 @@ it.each<[string, Detail]>([
await expect.element(page.getByRole("menuitem", { name: "Open on GitHub" })).toBeVisible();
expect(document.querySelector('[role="menuitemcheckbox"]')).toBeNull();
});

it("opens on host through openLink when Open on GitHub is clicked", async () => {
const control = setup();
await using screen = await render(control());
await screen.getByRole("button", { name: "More pull request actions" }).click();
const openOnHost = page.getByRole("menuitem", { name: "Open on GitHub" });
await openOnHost.click();
expect(mocks.openLink).toHaveBeenCalledWith(
openDetail.url,
expect.objectContaining({ threadRef: null }),
);
});

it("passes threadRef to openLink when Open on GitHub is clicked", async () => {
const threadRef = { environmentId, threadId: "thread-1" as never };
const control = setup();
await using screen = await render(control(openDetail, threadRef));
await screen.getByRole("button", { name: "More pull request actions" }).click();
const openOnHost = page.getByRole("menuitem", { name: "Open on GitHub" });
await openOnHost.click();
expect(mocks.openLink).toHaveBeenCalledWith(
openDetail.url,
expect.objectContaining({ threadRef }),
);
});
17 changes: 15 additions & 2 deletions apps/web/src/components/pullRequest/PullRequestActionsMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import { useId, useState } from "react";
import { m } from "~/i18n/messages";

import { shortcutLabelForCommand } from "~/keybindings";
import { readLocalApi } from "~/localApi";
import { useOpenLink } from "~/browser/useOpenLink";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { primaryServerKeybindingsAtom } from "~/state/server";
import { useAtomCommand } from "~/state/use-atom-command";
Expand Down Expand Up @@ -71,6 +71,7 @@ export function PullRequestActionsMenu({
pullRequestKey,
detail,
terminology,
threadRef = null,
linkThreadRef,
onThreadPickerOpenChange,
refreshing,
Expand Down Expand Up @@ -123,6 +124,7 @@ export function PullRequestActionsMenu({
| "observedAt"
>;
terminology: ChangeRequestTerminology;
threadRef?: ScopedThreadRef | null | undefined;
linkThreadRef: ScopedThreadRef | null;
onThreadPickerOpenChange: (open: boolean) => void;
refreshing: boolean;
Expand Down Expand Up @@ -162,6 +164,7 @@ export function PullRequestActionsMenu({
}) {
const gt = useGT();
const resolve = useMessages();
const openLink = useOpenLink(threadRef);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const inlineConfirm = useInlineActionConfirm(pullRequestKey);
const actionPending = pendingAction !== null;
Expand Down Expand Up @@ -434,7 +437,17 @@ export function PullRequestActionsMenu({
) : null}
</>
) : null}
<MenuItem onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}>
<MenuItem
onClick={(event) => {
void openLink(detail.url, { event }).catch((error: unknown) => {
console.error(error);
toastManager.add({
type: "error",
title: m(msg("Could not open the link")),
});
});
}}
>
<ArrowUpRightIcon className="size-3.5" />
{openOnHostText}
</MenuItem>
Expand Down
43 changes: 38 additions & 5 deletions apps/web/src/components/pullRequest/PullRequestDetailCrumbs.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import type { ScopedThreadRef } from "@t3tools/contracts";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { T, useGT } from "gt-react";
import { msg, T, useGT } from "gt-react";
import { ArrowLeftIcon, ExternalLinkIcon } from "lucide-react";
import type { MouseEvent as ReactMouseEvent } from "react";

import { useOpenLink } from "~/browser/useOpenLink";
import { m } from "~/i18n/messages";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import { Button } from "../ui/button";
import { toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { openOnHostLabel, showPullRequestLinkContextMenu } from "./pullRequestLinkContextMenu";

Expand Down Expand Up @@ -62,23 +65,35 @@ function NumberLink({
toneClassName,
openOnHostText,
focusable,
threadRef = null,
}: {
detail: CrumbsPullRequest;
toneClassName: string;
openOnHostText: string;
focusable: boolean;
threadRef?: ScopedThreadRef | null | undefined;
}) {
const gt = useGT();
const openLink = useOpenLink(threadRef);
const handleOpen = (event: ReactMouseEvent<HTMLElement>) => {
void openLink(detail.url, { event }).catch((error: unknown) => {
console.error(error);
toastManager.add({
type: "error",
title: m(msg("Could not open the link")),
});
});
};
return (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
{...(focusable ? {} : { tabIndex: -1 })}
onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}
onClick={(event) => handleOpen(event)}
onAuxClick={(event) => {
if (event.button === 1) void readLocalApi()?.shell.openExternal(detail.url);
if (event.button === 1) handleOpen(event);
}}
onContextMenu={(event) => openNumberContextMenu(event, detail)}
className={cn(
Expand Down Expand Up @@ -116,15 +131,28 @@ export function PullRequestDetailCrumbs({
repositoryUrl,
openOnHostText,
onBack,
threadRef = null,
}: {
detail: CrumbsPullRequest | null;
toneClassName: string | null;
condensed: boolean;
repositoryUrl: string | null;
openOnHostText: string;
onBack: (() => void) | undefined;
threadRef?: ScopedThreadRef | null | undefined;
}) {
const gt = useGT();
const openLink = useOpenLink(threadRef);
const handleOpenRepository = (event: ReactMouseEvent<HTMLElement>) => {
if (!repositoryUrl) return;
void openLink(repositoryUrl, { event }).catch((error: unknown) => {
console.error(error);
toastManager.add({
type: "error",
title: m(msg("Could not open the link")),
});
});
};
const ready = detail !== null && toneClassName !== null;
return (
<div className="pl-4 grid h-7 min-w-0 items-center overflow-hidden">
Expand All @@ -148,7 +176,10 @@ export function PullRequestDetailCrumbs({
repositoryUrl ? (
<button
type="button"
onClick={() => void readLocalApi()?.shell.openExternal(repositoryUrl)}
onClick={(event) => handleOpenRepository(event)}
onAuxClick={(event) => {
if (event.button === 1) handleOpenRepository(event);
}}
className="min-w-0 cursor-pointer truncate text-left font-medium text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
>
{detail.repository}
Expand All @@ -171,6 +202,7 @@ export function PullRequestDetailCrumbs({
toneClassName={toneClassName}
openOnHostText={openOnHostText}
focusable
threadRef={threadRef}
/>
</>
) : null}
Expand All @@ -194,6 +226,7 @@ export function PullRequestDetailCrumbs({
toneClassName={toneClassName}
openOnHostText={openOnHostText}
focusable={condensed}
threadRef={threadRef}
/>
<Tooltip>
<TooltipTrigger
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,26 @@ import {
AuthSourceControlWriteScope,
EnvironmentId,
ProjectId,
type ScopedThreadRef,
SourceControlProviderKind,
type PullRequestDetailView,
} from "@t3tools/contracts";
import { expect, it, vi } from "vite-plus/test";
import { userEvent } from "vite-plus/test/browser";
import { page, userEvent } from "vite-plus/test/browser";
import appCss from "~/index.css?inline";
import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { act, fakeTimers, render } from "../../../test/render";

const { permissions, reads, shown } = vi.hoisted(() => ({
const { permissions, reads, shown, openLink } = vi.hoisted(() => ({
permissions: { checkout: true, operate: true },
reads: { diff: [] as unknown[] },
shown: { detail: null as PullRequestDetailView | null },
openLink: vi.fn<(url: string, options?: unknown) => Promise<void>>(),
}));

vi.mock(import("~/browser/useOpenLink"), () => ({
useOpenLink: (threadRef: unknown) => (url: string, options?: unknown) =>
openLink(url, { ...(options as object | undefined), threadRef }),
}));

vi.mock(import("~/state/session"), async (original) => ({
Expand Down Expand Up @@ -130,10 +137,11 @@ const detail: PullRequestDetailView = {

const environmentId = EnvironmentId.make("environment");
const draftId = DraftId.make("conflicts-draft");
const panel = (attach = false, reference = detail) => (
const panel = (attach = false, reference = detail, threadRef: ScopedThreadRef | null = null) => (
<PullRequestDetailPanel
environmentId={environmentId}
reference={reference}
threadRef={threadRef}
context="page"
shortcutsEnabled={false}
getShortcutContext={() => ({
Expand All @@ -153,6 +161,7 @@ function setup() {
permissions.operate = true;
reads.diff = [];
shown.detail = detail;
openLink.mockReset().mockResolvedValue(undefined);
useComposerDraftStore.setState({ draftsByThreadKey: {} });
}

Expand Down Expand Up @@ -238,3 +247,22 @@ it("keeps a screen reader's place when scrolling the description condenses the h
// A programmatic focus() pulls the screen reader's browse cursor back to the header.
expect(moves).not.toHaveBeenCalled();
});

it("opens pull request on host using openLink with threadRef when the number link is clicked", async () => {
setup();
const threadRef = { environmentId, threadId: "thread-1" as never };
await using screen = await render(panel(false, detail, threadRef));
const openOnHost = screen.getByRole("button", { name: "Open pull request #1 on host" });
await openOnHost.click();
expect(openLink).toHaveBeenCalledWith(detail.url, expect.objectContaining({ threadRef }));
});

it("opens pull request on host using openLink with threadRef when Open on GitHub action is clicked", async () => {
setup();
const threadRef = { environmentId, threadId: "thread-1" as never };
await using screen = await render(panel(false, detail, threadRef));
await screen.getByRole("button", { name: "More pull request actions" }).click();
const openOnHost = page.getByRole("menuitem", { name: "Open on GitHub" });
await openOnHost.click();
expect(openLink).toHaveBeenCalledWith(detail.url, expect.objectContaining({ threadRef }));
});
Original file line number Diff line number Diff line change
Expand Up @@ -1529,6 +1529,7 @@ export function PullRequestDetailPanel({
number={reference.number}
tabs={visibleTabs}
activeTab={tab}
threadRef={threadRef}
{...(onBack ? { onBack } : {})}
{...(onClose ? { onClose } : {})}
actions={
Expand Down Expand Up @@ -1572,6 +1573,7 @@ export function PullRequestDetailPanel({
repositoryUrl={repositoryUrl}
openOnHostText={openOnHostText}
onBack={onBack}
threadRef={threadRef}
/>
<div className="mr-4 flex h-7 shrink-0 select-none items-center justify-end gap-1">
{detail ? (
Expand Down Expand Up @@ -1631,6 +1633,7 @@ export function PullRequestDetailPanel({
pullRequestKey={pullRequestKey}
detail={detail}
terminology={terminology}
threadRef={threadRef}
linkThreadRef={
threadRef ??
(typeof composerDraftTarget === "object" ? composerDraftTarget : null)
Expand Down
Loading
Loading