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
34 changes: 34 additions & 0 deletions packages/ui/src/features/editor/components/GithubRefChip.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { GITHUB_REF_URL_ATTR, GithubRefChip } from "./GithubRefChip";

describe("GithubRefChip", () => {
it("exposes its URL as a DOM attribute so the context menu can copy it", () => {
const href = "https://github.com/PostHog/posthog/pull/23985";
const { container } = render(
<GithubRefChip href={href} kind="pr">
PostHog/posthog#23985
</GithubRefChip>,
);

const carrier = container.querySelector(`[${GITHUB_REF_URL_ATTR}]`);
expect(carrier).not.toBeNull();
expect(carrier?.getAttribute(GITHUB_REF_URL_ATTR)).toBe(href);
});

it("lets a nested right-click target resolve the URL via closest()", () => {
const href = "https://github.com/PostHog/posthog/issues/42";
render(
<GithubRefChip href={href} kind="issue">
PostHog/posthog#42
</GithubRefChip>,
);

const label = screen.getByText("PostHog/posthog#42");
expect(
label
.closest(`[${GITHUB_REF_URL_ATTR}]`)
?.getAttribute(GITHUB_REF_URL_ATTR),
).toBe(href);
});
});
8 changes: 8 additions & 0 deletions packages/ui/src/features/editor/components/GithubRefChip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ import { GithubLogoIcon, GitPullRequestIcon } from "@phosphor-icons/react";
import { Chip } from "@posthog/quill";
import type { ReactNode } from "react";

/**
* DOM attribute carrying the chip's GitHub URL. The conversation context menu
* reads it (via `closest()`) so "Copy" can copy the link of a right-clicked
* chip, which is otherwise unreachable from a text selection.
*/
export const GITHUB_REF_URL_ATTR = "data-github-ref-url";

export function GithubRefChip({
href,
kind,
Expand All @@ -14,6 +21,7 @@ export function GithubRefChip({
const Icon = kind === "pr" ? GitPullRequestIcon : GithubLogoIcon;
return (
<Chip
{...{ [GITHUB_REF_URL_ATTR]: href }}
size="xs"
onClick={() => window.open(href, "_blank")}
className="cli-file-mention mx-0.5 max-w-full cursor-pointer! whitespace-nowrap pl-1 align-middle active:translate-y-0"
Expand Down
20 changes: 17 additions & 3 deletions packages/ui/src/features/sessions/components/SessionView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import { resolveAndAttachDroppedFiles } from "@posthog/ui/features/message-edito
import { PermissionSelector } from "@posthog/ui/features/permissions/PermissionSelector";
import { CloudInitializingView } from "@posthog/ui/features/sessions/components/CloudInitializingView";
import { ConversationView } from "@posthog/ui/features/sessions/components/ConversationView";
import {
copyFromContextMenu,
getGithubRefUrlFromEventTarget,
} from "@posthog/ui/features/sessions/components/copyContextTarget";
import { DropZoneOverlay } from "@posthog/ui/features/sessions/components/DropZoneOverlay";
import { ModelSelector } from "@posthog/ui/features/sessions/components/ModelSelector";
import { PendingChatView } from "@posthog/ui/features/sessions/components/PendingChatView";
Expand Down Expand Up @@ -250,6 +254,9 @@ export function SessionView({
const [isDraggingFile, setIsDraggingFile] = useState(false);
const editorRef = useRef<PromptInputHandle>(null);
const dragCounterRef = useRef(0);
// URL of the GitHub chip the context menu was opened on, captured on
// right-click so the "Copy" item can copy the link (selections can't reach it).
const copyTargetUrlRef = useRef<string | null>(null);

const firstPendingPermission = useMemo(() => {
const entries = Array.from(pendingPermissions.entries());
Expand Down Expand Up @@ -368,7 +375,9 @@ export function SessionView({
target.closest('input, textarea, [contenteditable="true"], .ProseMirror')
) {
e.stopPropagation();
return;
}
copyTargetUrlRef.current = getGithubRefUrlFromEventTarget(e.target);
}, []);

return (
Expand Down Expand Up @@ -642,10 +651,15 @@ export function SessionView({
<ContextMenu.Content size="1">
<ContextMenu.Item
onSelect={() => {
const text = window.getSelection()?.toString();
if (text) {
navigator.clipboard.writeText(text);
const url = copyTargetUrlRef.current;
const text = url ?? window.getSelection()?.toString();
if (!text) {
return;
}
copyFromContextMenu(text, {
onSuccess: () => toast.success(url ? "Link copied" : "Copied"),
onError: () => toast.error("Couldn't copy"),
});
}}
>
Copy
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { GithubRefChip } from "@posthog/ui/features/editor/components/GithubRefChip";
import {
copyFromContextMenu,
getGithubRefUrlFromEventTarget,
} from "@posthog/ui/features/sessions/components/copyContextTarget";
import { ContextMenu, Theme } from "@radix-ui/themes";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useRef } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";

const PR_URL = "https://github.com/PostHog/posthog/pull/63995";

// Radix's menu content mounts a scroll-area that observes resizes; jsdom lacks it.
if (typeof globalThis.ResizeObserver === "undefined") {
globalThis.ResizeObserver = class {
observe() {}
unobserve() {}
disconnect() {}
} as unknown as typeof ResizeObserver;
}

/**
* Mirrors the exact context-menu wiring in SessionView: a ContextMenu.Trigger
* whose child captures the right-clicked URL in a ref, and a "Copy" item that
* copies the captured URL (falling back to the text selection).
*/
function Harness() {
const copyTargetUrlRef = useRef<string | null>(null);
const handleContextMenu = (e: React.MouseEvent) => {
copyTargetUrlRef.current = getGithubRefUrlFromEventTarget(e.target);
};
return (
<Theme>
<ContextMenu.Root>
<ContextMenu.Trigger>
{/** biome-ignore lint/a11y/noStaticElementInteractions: test harness */}
<div onContextMenu={handleContextMenu}>
<span>The draft PR is up: </span>
<GithubRefChip href={PR_URL} kind="pr">
PostHog/posthog#63995
</GithubRefChip>
</div>
</ContextMenu.Trigger>
<ContextMenu.Content>
<ContextMenu.Item
onSelect={() => {
const url = copyTargetUrlRef.current;
const text = url ?? window.getSelection()?.toString();
if (!text) {
return;
}
copyFromContextMenu(text);
}}
>
Copy
</ContextMenu.Item>
</ContextMenu.Content>
</ContextMenu.Root>
</Theme>
);
}

describe("conversation context-menu copy (integration)", () => {
afterEach(() => {
vi.restoreAllMocks();
});

it("copies the PR URL when right-clicking the chip and choosing Copy", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
Object.assign(navigator, { clipboard: { writeText } });

render(<Harness />);

// Right-click the chip label, exactly as a user would.
const label = screen.getByText("PostHog/posthog#63995");
fireEvent.contextMenu(label);

const copyItem = await screen.findByText("Copy");
await userEvent.click(copyItem);

// The write is deferred until after the menu closes (focus race), so wait.
await waitFor(() => expect(writeText).toHaveBeenCalledWith(PR_URL));
});

it("falls back to the text selection when the right-click misses a chip", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
Object.assign(navigator, { clipboard: { writeText } });
vi.spyOn(window, "getSelection").mockReturnValue({
toString: () => "some selected prose",
} as Selection);

render(<Harness />);

fireEvent.contextMenu(screen.getByText(/The draft PR is up/));
await userEvent.click(await screen.findByText("Copy"));

await waitFor(() =>
expect(writeText).toHaveBeenCalledWith("some selected prose"),
);
});

it("copies nothing when there is neither a chip URL nor a selection", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
Object.assign(navigator, { clipboard: { writeText } });
vi.spyOn(window, "getSelection").mockReturnValue({
toString: () => "",
} as Selection);

render(<Harness />);

fireEvent.contextMenu(screen.getByText(/The draft PR is up/));
await userEvent.click(await screen.findByText("Copy"));

// Flush the deferred-write tick so a wrongful copy would have fired by now.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(writeText).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { GITHUB_REF_URL_ATTR } from "@posthog/ui/features/editor/components/GithubRefChip";
import { describe, expect, it, vi } from "vitest";
import {
copyFromContextMenu,
getGithubRefUrlFromEventTarget,
} from "./copyContextTarget";

function buildDom(): {
icon: HTMLElement;
label: HTMLElement;
chip: HTMLElement;
outside: HTMLElement;
} {
document.body.innerHTML = `
<div id="conversation">
<span ${GITHUB_REF_URL_ATTR}="https://github.com/PostHog/posthog/pull/23985">
<button id="chip"><svg id="icon"></svg><span id="label">PostHog/posthog#23985</span></button>
</span>
<p id="outside">just some prose</p>
</div>`;
return {
icon: document.getElementById("icon") as HTMLElement,
label: document.getElementById("label") as HTMLElement,
chip: document.getElementById("chip") as HTMLElement,
outside: document.getElementById("outside") as HTMLElement,
};
}

const CHIP_URL = "https://github.com/PostHog/posthog/pull/23985";

describe("getGithubRefUrlFromEventTarget", () => {
it.each<{
name: string;
pick: (dom: ReturnType<typeof buildDom>) => EventTarget | null;
expected: string | null;
}>([
{ name: "a nested icon", pick: (dom) => dom.icon, expected: CHIP_URL },
{ name: "the label", pick: (dom) => dom.label, expected: CHIP_URL },
{ name: "the chip button", pick: (dom) => dom.chip, expected: CHIP_URL },
{ name: "non-chip prose", pick: (dom) => dom.outside, expected: null },
{ name: "a non-element target", pick: () => null, expected: null },
])("resolves $expected when the target is $name", ({ pick, expected }) => {
expect(getGithubRefUrlFromEventTarget(pick(buildDom()))).toBe(expected);
});
});

describe("copyFromContextMenu", () => {
it("defers the clipboard write until after the current task (focus race)", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
Object.assign(navigator, { clipboard: { writeText } });

copyFromContextMenu("https://github.com/PostHog/posthog/pull/1");

// Not written synchronously while the menu is still dismissing.
expect(writeText).not.toHaveBeenCalled();
await vi.waitFor(() =>
expect(writeText).toHaveBeenCalledWith(
"https://github.com/PostHog/posthog/pull/1",
),
);
});

it("invokes onSuccess after the deferred write resolves", async () => {
Object.assign(navigator, {
clipboard: { writeText: vi.fn().mockResolvedValue(undefined) },
});
const onSuccess = vi.fn();
const onError = vi.fn();

copyFromContextMenu("text", { onSuccess, onError });

await vi.waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1));
expect(onError).not.toHaveBeenCalled();
});

it("invokes onError when the deferred write rejects", async () => {
Object.assign(navigator, {
clipboard: {
writeText: vi
.fn()
.mockRejectedValue(new Error("Document is not focused")),
},
});
const onSuccess = vi.fn();
const onError = vi.fn();

copyFromContextMenu("text", { onSuccess, onError });

await vi.waitFor(() => expect(onError).toHaveBeenCalledTimes(1));
expect(onSuccess).not.toHaveBeenCalled();
});
});
41 changes: 41 additions & 0 deletions packages/ui/src/features/sessions/components/copyContextTarget.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { GITHUB_REF_URL_ATTR } from "@posthog/ui/features/editor/components/GithubRefChip";

/**
* Resolve the GitHub PR/issue URL the context menu was opened on, if the
* right-click landed inside a {@link GithubRefChip}. Returns `null` for any
* other target (prose, file chips, empty space, non-elements).
*/
export function getGithubRefUrlFromEventTarget(
target: EventTarget | null,
): string | null {
// `Element`, not `HTMLElement`: the chip icon renders as an <svg>, whose
// right-click target is an SVGElement that still supports `closest()`.
if (!(target instanceof Element)) return null;
return (
target
.closest(`[${GITHUB_REF_URL_ATTR}]`)
?.getAttribute(GITHUB_REF_URL_ATTR) ?? null
);
}

/**
* Copy text to the clipboard from a context-menu selection.
*
* The write is deferred to a later task on purpose. When a Radix
* `ContextMenu.Item` is selected, the menu's focus scope is being torn down and
* the document is momentarily not focused — calling `navigator.clipboard.writeText`
* synchronously there rejects with "Document is not focused" in Electron/Chromium,
* so the clipboard is left unchanged. Deferring lets the menu finish closing and
* focus return to the document before we write.
*/
export function copyFromContextMenu(
text: string,
callbacks: { onSuccess?: () => void; onError?: () => void } = {},
): void {
setTimeout(() => {
navigator.clipboard
.writeText(text)
.then(() => callbacks.onSuccess?.())
.catch(() => callbacks.onError?.());
}, 0);
}
Loading