diff --git a/.bb/plugins.json b/.bb/plugins.json index 9c1abef5..770f446b 100644 --- a/.bb/plugins.json +++ b/.bb/plugins.json @@ -9,6 +9,7 @@ { "name": "diff-explorer", "source": "./plugins/diff-explorer" }, { "name": "html-preview", "source": "./plugins/html-preview" }, { "name": "image-copy", "source": "./plugins/image-copy" }, - { "name": "repo-dashboard", "source": "./plugins/repo-dashboard" } + { "name": "repo-dashboard", "source": "./plugins/repo-dashboard" }, + { "name": "pr-inbox", "source": "./plugins/pr-inbox" } ] } diff --git a/.github/workflows/plugins.yaml b/.github/workflows/plugins.yaml index 722012ae..a2f0448a 100644 --- a/.github/workflows/plugins.yaml +++ b/.github/workflows/plugins.yaml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - plugin: [devbox-provider, github-watcher, html-preview, image-copy, kubernetes-provider, stewards, team-setup, thread-briefs, workstreams] + plugin: [devbox-provider, github-watcher, html-preview, image-copy, kubernetes-provider, pr-inbox, stewards, team-setup, thread-briefs, workstreams] defaults: run: working-directory: plugins/${{ matrix.plugin }} diff --git a/README.md b/README.md index 291dd350..3b19aa7a 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ Plugins for [bb](https://getbb.app), maintained by Bit Complete. | [linear](plugins/linear) | Connect Linear once with OAuth; threads then read, search, comment on and move issues through native tools, as you | | [github-watcher](plugins/github-watcher) | Lets a thread watch a GitHub pull request or issue with the server's `gh` login and be woken when reviews, checks, comments or state change | | [stewards](plugins/stewards) | Gives a labelled Linear ticket or GitHub pull request, and every teammate's pull request, a long-lived thread that manages it as you by a playbook in `.bb` | +| [My PRs](plugins/pr-inbox) | Human feedback waiting on your authored PRs, with dismiss and Address comments | | [repo-dashboard](plugins/repo-dashboard) | Shows weekly pull request activity by contributor for Parsley Health, Bit Complete, and Cscc | Install one: diff --git a/plugins/pr-inbox/.gitignore b/plugins/pr-inbox/.gitignore new file mode 100644 index 00000000..1eae0cf6 --- /dev/null +++ b/plugins/pr-inbox/.gitignore @@ -0,0 +1,2 @@ +dist/ +node_modules/ diff --git a/plugins/pr-inbox/PLUGIN_OVERVIEW.md b/plugins/pr-inbox/PLUGIN_OVERVIEW.md new file mode 100644 index 00000000..22c20dd7 --- /dev/null +++ b/plugins/pr-inbox/PLUGIN_OVERVIEW.md @@ -0,0 +1,28 @@ +## Your pull requests waiting on you + +My PRs shows the human feedback on your authored PRs that still needs a +response. Every row says why: an approval note, a change request, a comment, +or an open thread where another person spoke last. Bot feedback alone does +not add a PR. Drafts stay visible when a person is waiting. + +Dismiss a PR until new commits or human feedback arrive. Restore it from the +dismissed list whenever you want. Refresh manually or let the background poll +keep the page current. Failed reads display an error and retain the previous inbox. + +## Address comments + +Start a thread for one PR or select up to 20 and address them together. The +thread finds the relevant checkout, fixes code, runs checks, pushes changes, +and replies to comments. It addresses bot comments too. Its instructions forbid +merging. The plugin starts no work automatically and only reads GitHub itself. +Started PRs keep their thread links after the feedback clears. + +## Requirements + +Use the BB server's authenticated GitHub CLI or configure a secret GitHub token. +Choose a BB project whose default environment has the repository checkouts for +Address threads. Optional provider and model settings override that project's +defaults. Agent work uses the configured provider account. + +My PRs runs independently of Workstreams. Review Watch is its companion for +PRs where someone else needs your review. diff --git a/plugins/pr-inbox/README.md b/plugins/pr-inbox/README.md new file mode 100644 index 00000000..eb0c7088 --- /dev/null +++ b/plugins/pr-inbox/README.md @@ -0,0 +1,123 @@ +# My PRs + +My PRs shows human feedback waiting on your authored pull requests. It is a +standalone sibling of Review Watch, whose Reviews page shows requests for your +review of other people's PRs. My PRs does not require Workstreams. + +## Install and configure + +Install the plugin from the collection: + +```sh +bb plugin install git:https://github.com/bitcomplete/bb-plugins.git@bb/pr-inbox-from-workstreams --plugin pr-inbox --yes +bb plugin config pr-inbox set project +bb plugin reload pr-inbox +bb pr-inbox poll --json +``` + +Open **My PRs** in the sidebar. The first successful refresh shows your open +PRs. By default, the poller uses the BB server's authenticated `gh`. If that +server has no `gh` login, set the secret `githubToken` in the plugin settings. +The token needs read access to the repositories you want to follow. + +The page groups PRs alphabetically by GitHub organization, then by area, using the same compact layout as Reviews. Its +branch icon distinguishes My PRs in the sidebar. Groups come from PR title +scopes, falling back to the repository name. + +The header and navigation badge show the number of PRs on Your turn. The +navigation badge clears when nothing needs your response. This requires a BB +server with Plugin SDK 0.6.53 or newer; reinstalling only the desktop app does +not update a remote server. + +Choose one PR's **Address**, or select several rows and choose **Address N**. +Checkboxes select individual PRs, with one select-all control at the top. +Organization and area headings are labels and counts. Shift-click selects a range. Press **b** to +address the selection or **Esc** to clear it. Address opens a project picker, then starts one thread on the chosen project's +default checkout and machine. Organization mappings preselect the project; the +configured default is a fallback. Override it for an individual PR or batch. +A batch spanning different mapped projects requires a choice. The thread finds checkouts, fixes code, +runs checks, pushes the changes, and replies to review comments. It includes bot comments +in that work. The prompt forbids merging, approving, closing PRs, and automatic +thread resolution. The plugin itself only reads GitHub. + +**Hold…** moves a PR to a faded **On hold** section at the bottom for 1 hour, +until tomorrow at 9 AM in your browser’s timezone, or for 1 week. Held PRs stay +out of Your turn counts and batch selection. Holds survive new feedback and +restarts, expire automatically, and can be ended early with **Resume**. + +**Dismiss** hides feedback until a new commit or new human feedback changes +that PR. Open the dismissed list and choose **Restore** to bring it back. +Started PRs keep a link to their thread, including after the feedback clears. +When an attempt finishes, **Clear attempt** lets you start another. If a start +fails without returning a thread, check your threads before clearing it. + +## Feedback rules + +The policy comes from Workstreams' `your-turn.ts`, `feedback-to-address.ts`, +and `pr-gates.ts`. A PR needs your response when it has any of these: + +- A human's approval note that you have not answered. +- A human's change request with no later push, reply, or re-request. +- An unresolved thread where another human spoke last. +- A human's comment with no later reply from you. + +Drafts count. Bot feedback alone never puts a PR on Your turn. A push answers +a change request, but comments and approval notes require a reply. A bot's +reply does not answer a human's thread. A later standing approval covers that +reviewer's earlier comments. + +My PRs keeps no effort assignments, merge gates, or model +enrichment. Workstreams' existing Your turn view continues to work independently. +Workstreams' local **Confirm handled** records do not transfer to My PRs. + +GitHub search, reviews, conversation comments, review requests, review threads, +and comments inside threads all paginate. The search limit is 1,000 open authored +PRs. An incomplete or failed read keeps the last successful inbox and displays +an error. Address reads only the selected PRs and checks their current heads and +feedback before dispatch. Each PR’s initial feedback connections share one +request; further pages load only when needed. If GitHub rate limits a request, +the plugin keeps the inbox and pauses API reads until the reported reset time, +including across plugin reloads. + +## Settings + +| Setting | Default | Effect | +| --- | --- | --- | +| `project` | Unset | Fallback project for Address threads. The picker can override it. | +| `organizationProjects` | `{}` | JSON mapping of GitHub organization names to BB project IDs; names ignore case. | +| `githubToken` | Unset | Secret GitHub token. Empty uses the server's `gh`. | +| `repoAllowlist` | Empty | Comma-separated `owner/repo` names. Empty includes every repository. | +| `pollMinutes` | 5 | Refresh interval, clamped to 1–60 minutes. | +| `provider` | Unset | Optional provider for Address threads. | +| `model` | Unset | Optional model for Address threads. | + +Token and repository changes clear the old snapshot. Changes apply to the next +refresh. The project picker works even when no default project is configured. + +## CLI + +```sh +bb pr-inbox list --json +bb pr-inbox status --json +bb pr-inbox poll --json +bb pr-inbox dismiss +bb pr-inbox restore +bb pr-inbox address [...] +bb pr-inbox clear +``` + +Use the `id` field from `list`. Address accepts up to 20 distinct PRs. Dismiss, +restore, and clear each take one id. Clearing a link retains its thread in BB. + +## Develop + +```sh +npm ci --legacy-peer-deps +npm run typecheck +npm test +npm run build +``` + +`--legacy-peer-deps` avoids an npm 10 optional-peer resolver error when installing +the frontend test dependencies. Tests cover the feedback rules, pagination, +persistence, stale dispatch, and the page's manual actions using BB's public SDK. diff --git a/plugins/pr-inbox/address-project-dialog.tsx b/plugins/pr-inbox/address-project-dialog.tsx new file mode 100644 index 00000000..450d6da6 --- /dev/null +++ b/plugins/pr-inbox/address-project-dialog.tsx @@ -0,0 +1,80 @@ +import { useEffect, useState } from "react"; +import { useRpc } from "@get-bb/plugin-sdk/app"; +import type { rpcContract } from "./server"; +import type { Selection } from "./types.js"; +import type { z } from "zod"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./components/ui/dialog"; +import { Button } from "./components/ui/button"; + +type Targets = z.infer<(typeof rpcContract)["address_targets"]["output"]>; +type Load = { kind: "loading" } | { kind: "error"; message: string } | { kind: "ready"; targets: Targets }; + +export function AddressProjectDialog({ items, onClose, onStart }: { + items: Selection[]; + onClose: () => void; + onStart: (projectId: string) => Promise; +}) { + const rpc = useRpc(); + const [load, setLoad] = useState({ kind: "loading" }); + const [projectId, setProjectId] = useState(""); + const [starting, setStarting] = useState(false); + const [error, setError] = useState(null); + useEffect(() => { + let active = true; + rpc.call("address_targets", { items: items.map(({ id, activity }) => ({ id, activity })) }).then((targets) => { + if (!active) return; + setLoad({ kind: "ready", targets }); + setProjectId(targets.projectId ?? ""); + }, (cause) => { + if (active) setLoad({ kind: "error", message: cause instanceof Error ? cause.message : String(cause) }); + }); + return () => { active = false; }; + }, [items, rpc]); + + const start = async () => { + if (starting || projectId === "" || load.kind !== "ready") return; + setStarting(true); + setError(null); + try { await onStart(projectId); } + catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); } + finally { setStarting(false); } + }; + + return ( + { if (!open && !starting) onClose(); }}> + + + {items.length === 1 ? "Address feedback" : `Address ${items.length} pull requests`} + Choose the project for this feedback thread. + + {load.kind === "loading" ?

Loading projects…

: null} + {load.kind === "error" ?

{load.message}

: null} + {load.kind === "ready" ? ( +
+ + +

+ {load.targets.projects.length === 0 ? "Add a project checkout in BB to address feedback." + : load.targets.reason === "mixed" ? "These PRs map to different projects. Choose one for this batch." + : load.targets.reason === "organization" ? "Preselected from your organization mappings." + : load.targets.reason === "default" ? "Preselected from your default feedback project." + : "This selection has no available default project."} +

+
+ ) : null} + {error === null ? null :

{error}

} + + + + +
+
+ ); +} diff --git a/plugins/pr-inbox/app.test.tsx b/plugins/pr-inbox/app.test.tsx new file mode 100644 index 00000000..36d34efa --- /dev/null +++ b/plugins/pr-inbox/app.test.tsx @@ -0,0 +1,234 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { fireEvent, screen, waitFor, within } from "@testing-library/react"; +import { loadPluginApp, renderSlot } from "@get-bb/plugin-sdk/testing/app"; +import { rpcContract } from "./server.js"; +import { feedbackOf } from "./feedback.js"; +import { fixture } from "./fixtures.js"; +import type { View } from "./types.js"; + +const cleanups: (() => void)[] = []; +beforeEach(() => { vi.stubGlobal("matchMedia", () => ({ matches: false, addEventListener() {}, removeEventListener() {} })); }); +afterEach(() => { for (const cleanup of cleanups.splice(0)) cleanup(); vi.unstubAllGlobals(); }); +const targets = () => ({ projects: [{ id: "project-test", name: "Default" }, { id: "project-parsley", name: "Parsley" }], projectId: "project-test", reason: "default" }); +async function confirmAddress() { + const dialog = within(await screen.findByRole("dialog")); + await dialog.findByLabelText("Project"); + await waitFor(() => expect(dialog.getByRole("button", { name: "Address feedback" })).toHaveProperty("disabled", false)); + fireEvent.click(dialog.getByRole("button", { name: "Address feedback" })); +} +it("selects feedback and starts one explicit batch, then navigates to its thread", async () => { + const app = await loadPluginApp(() => import("./app.js")); + const panel = app.navPanels[0]; if (!panel) throw new Error("Missing inbox page"); + const prs = [fixture(), fixture(2)].map((data) => feedbackOf({ ...data, requested: [] })); + const view: View = { rows: prs.map((pr) => ({ ...pr, dismissed: false, holdUntil: null, dispatch: { kind: "none" }, threadStatus: null })), + project: "project-test", poll: { at: "2026-10-19T12:00:00Z", lastSuccess: "2026-10-19T12:00:00Z", login: "me", error: null, retryAt: null } }; + const slot = renderSlot(panel, { subPath: "" }, { rpc: { + inbox_get: () => view, + address_targets: targets, + address: () => ({ threadId: "thread-address" }), + } }); + cleanups.push(() => slot.lifecycle.unmount()); + await slot.findByText("Improve the editor 1"); + expect(slot.inspection.rpcCalls.filter((call) => call.method === "address")).toEqual([]); + fireEvent.click(slot.getByRole("checkbox", { name: "Select all actionable PRs" })); + fireEvent.click(await slot.findByRole("button", { name: "Address 2 selected" })); + await confirmAddress(); + await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "toThread", threadId: "thread-address" })); + const calls = slot.inspection.rpcCalls.filter((call) => call.method === "address"); + expect(calls).toHaveLength(1); + expect(JSON.stringify(calls)).toContain(prs[0]?.activity); + expect(JSON.stringify(calls)).toContain(prs[1]?.activity); +}); + +async function renderFeedback(rows: View["rows"]) { + const app = await loadPluginApp(() => import("./app.js")); + const panel = app.navPanels[0]; + if (!panel) throw new Error("Missing feedback page"); + const slot = renderSlot(panel, { subPath: "" }, { rpc: { + inbox_get: () => ({ rows, project: "project-test", poll: null }), + address_targets: targets, + address: () => ({ threadId: "thread-address" }), dismiss: () => ({ ok: true }), clear_dispatch: () => ({ ok: true }), + } }); + cleanups.push(() => slot.lifecycle.unmount()); + await slot.findByRole("heading", { name: "Your turn" }); + return slot; +} +function row(number: number): View["rows"][number] { + return { ...feedbackOf({ ...fixture(number), requested: [] }), dismissed: false, holdUntil: null, dispatch: { kind: "none" }, threadStatus: null }; +} + +it("groups related feedback across repositories and selects only actionable rows", async () => { + const slot = await renderFeedback([ + { ...row(1), title: "fix(catalog): first", repo: "parsleyhealth/store" }, + { ...row(2), title: "feat(catalog): second", repo: "parsleyhealth/api" }, + { ...row(3), title: "fix(schedule): third" }, + { ...row(4), title: "fix(catalog): already started", dispatch: { kind: "linked", threadId: "thread-existing" }, threadStatus: "running" }, + ]); + expect(slot.queryByLabelText("Selection")).toBeNull(); + fireEvent.click(slot.getByLabelText("Select parsleyhealth/store#1")); + fireEvent.click(slot.getByLabelText("Select parsleyhealth/api#2"), { shiftKey: true }); + expect(slot.getByText("2 selected")).toBeTruthy(); + expect(slot.getByRole("checkbox", { name: "Select all actionable PRs" })).toHaveProperty("indeterminate", true); + expect(slot.queryByRole("checkbox", { name: "Select example/editor#4" })).toBeNull(); + fireEvent.click(slot.getByRole("button", { name: "Address 2 selected" })); + await confirmAddress(); + await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "toThread", threadId: "thread-address" })); + const call = JSON.stringify(slot.inspection.rpcCalls.find((call) => call.method === "address")); + expect(call).toContain('"id":"PR_1"'); expect(call).toContain('"id":"PR_2"'); expect(call).not.toContain('"id":"PR_4"'); +}); + +it("supports shift selection, Escape to clear, and b to address without acting while typing", async () => { + const slot = await renderFeedback([row(1), row(2), row(3)]); + fireEvent.click(slot.getByRole("checkbox", { name: "Select example/editor#1" })); + fireEvent.click(slot.getByRole("checkbox", { name: "Select example/editor#3" }), { shiftKey: true }); + expect(slot.getByText("3 selected")).toBeTruthy(); + fireEvent.keyDown(window, { key: "Escape" }); + expect(slot.queryByLabelText("Selection")).toBeNull(); + fireEvent.click(slot.getByRole("checkbox", { name: "Select example/editor#2" })); + const input = document.createElement("input"); document.body.append(input); input.focus(); + fireEvent.keyDown(input, { key: "b" }); + expect(slot.inspection.rpcCalls.filter((call) => call.method === "address")).toHaveLength(0); + input.remove(); fireEvent.keyDown(window, { key: "b" }); + await confirmAddress(); + await waitFor(() => expect(slot.inspection.rpcCalls.filter((call) => call.method === "address")).toHaveLength(1)); + expect(JSON.stringify(slot.inspection.rpcCalls.find((call) => call.method === "address"))).toContain('"id":"PR_2"'); +}); + +it("keeps thread, clear-attempt, dismissal, and restore actions available in compact rows", async () => { + const slot = await renderFeedback([ + { ...row(1), dispatch: { kind: "linked", threadId: "thread-existing" }, threadStatus: "idle" }, + { ...row(2), dismissed: true }, row(3), + ]); + fireEvent.click(slot.getByRole("button", { name: /Open/ })); + expect(slot.inspection.navigateCalls).toContainEqual({ method: "toThread", threadId: "thread-existing" }); + fireEvent.click(slot.getByRole("button", { name: "Clear attempt" })); + await waitFor(() => expect(slot.inspection.rpcCalls.some((call) => call.method === "clear_dispatch")).toBe(true)); + fireEvent.click(slot.getByRole("button", { name: "Dismiss example/editor#3" })); + await waitFor(() => expect(JSON.stringify(slot.inspection.rpcCalls)).toContain('"dismissed":true')); + fireEvent.click(slot.getByText("1 dismissed · show")); + fireEvent.click(slot.getByRole("button", { name: "Restore example/editor#2" })); + await waitFor(() => expect(JSON.stringify(slot.inspection.rpcCalls)).toContain('"dismissed":false')); +}); + +it("registers a sidebar badge that counts actionable feedback and follows realtime updates", async () => { + const app = await loadPluginApp(() => import("./app.js")); + const useBadge = app.navPanels[0]?.experimental_useBadge; + if (!useBadge) throw new Error("Missing My PRs sidebar badge"); + let view: View = { project: "project-test", poll: null, rows: [ + row(1), { ...row(2), dismissed: true }, { ...row(3), turn: null }, { ...row(4), holdUntil: "2099-01-01T12:00:00Z" }, + ] }; + function BadgeProbe() { return {JSON.stringify(useBadge?.())}; } + const slot = renderSlot({ component: BadgeProbe }, {}, { rpc: { inbox_get: () => view } }); + cleanups.push(() => slot.lifecycle.unmount()); + await waitFor(() => expect(JSON.parse(slot.getByLabelText("Navigation badge").textContent ?? "null")).toEqual({ + count: 1, tone: "warning", label: "1 pull request waiting for your response", + })); + view = { ...view, rows: [row(1), row(2), { ...row(3), turn: null }] }; + await slot.behavior.emitRealtime("inbox-changed", {}); + await waitFor(() => expect(JSON.parse(slot.getByLabelText("Navigation badge").textContent ?? "null")).toEqual({ + count: 2, tone: "warning", label: "2 pull requests waiting for your response", + })); + view = { ...view, rows: [] }; + await slot.behavior.emitRealtime("inbox-changed", {}); + await waitFor(() => expect(slot.getByLabelText("Navigation badge").textContent).toBe("null")); + expect(slot.inspection.rpcCalls.every((call) => call.method === "inbox_get")).toBe(true); +}); + +it("keeps the same area in different organizations separate with only row and select-all checkboxes", async () => { + const slot = await renderFeedback([ + { ...row(1), title: "fix(catalog): parsley", repo: "parsleyhealth/store" }, + { ...row(2), title: "fix(catalog): bit", repo: "bitcomplete/store" }, + ]); + const parsley = within(slot.getByRole("region", { name: "parsleyhealth your turn" })); + expect(parsley.getByText("fix(catalog): parsley")).toBeTruthy(); + expect(parsley.queryByText("fix(catalog): bit")).toBeNull(); + expect(slot.getAllByRole("checkbox")).toHaveLength(3); + expect(parsley.getAllByRole("checkbox")).toHaveLength(1); + expect(parsley.queryByLabelText("Select organization parsleyhealth")).toBeNull(); + fireEvent.click(slot.getByLabelText("Select parsleyhealth/store#1")); + expect(slot.getByLabelText("Select parsleyhealth/store#1")).toHaveProperty("checked", true); + expect(slot.getByLabelText("Select bitcomplete/store#2")).toHaveProperty("checked", false); + fireEvent.click(slot.getByRole("button", { name: "Address 1 selected" })); + await confirmAddress(); + await waitFor(() => expect(slot.inspection.rpcCalls.find((call) => call.method === "address")).toMatchObject({ + input: { items: [{ id: "PR_1", activity: row(1).activity }] }, + })); +}); + +it("moves a selected PR to the faded hold section, excludes it from selection, and resumes it", async () => { + const app = await loadPluginApp(() => import("./app.js")); + const panel = app.navPanels[0]; if (!panel) throw new Error("Missing inbox"); + let held: string | null = null; + const slot = renderSlot(panel, { subPath: "" }, { rpc: { + inbox_get: () => ({ rows: [{ ...row(1), holdUntil: held }, row(2)], project: "project-test", poll: null }), + hold: (input) => { held = rpcContract.hold.input.parse(input).until; return { ok: true }; }, + } }); + cleanups.push(() => slot.lifecycle.unmount()); + fireEvent.click(await slot.findByLabelText("Select example/editor#1")); + fireEvent.change(slot.getByLabelText("Hold example/editor#1"), { target: { value: "1" } }); + const section = within(await slot.findByRole("region", { name: "On hold" })); + expect(section.getByText("Improve the editor 1")).toBeTruthy(); + expect(slot.queryByLabelText("Select example/editor#1")).toBeNull(); + expect(slot.queryByLabelText("Selection")).toBeNull(); + fireEvent.click(slot.getByLabelText("Select all actionable PRs")); + expect(slot.getByText("1 selected")).toBeTruthy(); + fireEvent.click(section.getByRole("button", { name: "Resume example/editor#1" })); + await slot.findByLabelText("Select example/editor#1"); + expect(slot.queryByRole("region", { name: "On hold" })).toBeNull(); + expect(slot.inspection.rpcCalls.filter((call) => call.method === "hold")).toMatchObject([ + { input: { id: "PR_1", until: expect.any(String) } }, { input: { id: "PR_1", until: null } }, + ]); +}); + +it("preselects the mapped project and lets a batch choose another project", async () => { + const app = await loadPluginApp(() => import("./app.js")); + const panel = app.navPanels[0]; if (!panel) throw new Error("Missing inbox"); + const slot = renderSlot(panel, { subPath: "" }, { rpc: { + inbox_get: () => ({ rows: [row(1), row(2)], project: "project-test", poll: null }), + address_targets: () => ({ ...targets(), projectId: "project-parsley", reason: "organization" }), + address: () => ({ threadId: "thread-picked" }), + } }); + cleanups.push(() => slot.lifecycle.unmount()); + fireEvent.click(await slot.findByLabelText("Select all actionable PRs")); + fireEvent.click(slot.getByRole("button", { name: "Address 2 selected" })); + const dialog = within(await screen.findByRole("dialog")); + const project = await dialog.findByLabelText("Project"); + expect(project).toHaveProperty("value", "project-parsley"); + expect(slot.inspection.rpcCalls.some((call) => call.method === "address")).toBe(false); + fireEvent.change(project, { target: { value: "project-test" } }); + fireEvent.click(dialog.getByRole("button", { name: "Address feedback" })); + await waitFor(() => expect(slot.inspection.rpcCalls.find((call) => call.method === "address")).toMatchObject({ + input: { projectId: "project-test", items: expect.arrayContaining([{ id: "PR_1", activity: row(1).activity }, { id: "PR_2", activity: row(2).activity }]) }, + })); + await waitFor(() => expect(slot.inspection.navigateCalls).toContainEqual({ method: "toThread", threadId: "thread-picked" })); +}); + +it("requires a choice for mixed projects, preserves selection on failure, and cancels without work", async () => { + const app = await loadPluginApp(() => import("./app.js")); + const panel = app.navPanels[0]; if (!panel) throw new Error("Missing inbox"); + const slot = renderSlot(panel, { subPath: "" }, { rpc: { + inbox_get: () => ({ rows: [row(1), row(2)], project: null, poll: null }), + address_targets: () => ({ ...targets(), projectId: null, reason: "mixed" }), + address: () => { throw new Error("Selected machine is offline"); }, + } }); + cleanups.push(() => slot.lifecycle.unmount()); + fireEvent.click(await slot.findByLabelText("Select all actionable PRs")); + fireEvent.click(slot.getByRole("button", { name: "Address 2 selected" })); + const dialog = within(await screen.findByRole("dialog")); + const project = await dialog.findByLabelText("Project"); + const start = dialog.getByRole("button", { name: "Address feedback" }); + expect(start).toHaveProperty("disabled", true); + fireEvent.change(project, { target: { value: "project-parsley" } }); + fireEvent.click(start); + expect(await dialog.findByRole("alert")).toHaveProperty("textContent", "Selected machine is offline"); + expect(slot.getByText("2 selected")).toBeTruthy(); + fireEvent.click(dialog.getByRole("button", { name: "Cancel" })); + const item = slot.getByLabelText("Select example/editor#1").closest("li"); if (!item) throw new Error("Missing row"); + fireEvent.click(within(item).getByRole("button", { name: "Address comments on example/editor#1" })); + const single = within(await screen.findByRole("dialog", { name: "Address feedback" })); + await single.findByLabelText("Project"); + fireEvent.click(single.getByRole("button", { name: "Cancel" })); + expect(slot.inspection.rpcCalls.filter((call) => call.method === "address")).toHaveLength(1); + expect(slot.inspection.navigateCalls).toHaveLength(0); +}); diff --git a/plugins/pr-inbox/app.tsx b/plugins/pr-inbox/app.tsx new file mode 100644 index 00000000..bcebe624 --- /dev/null +++ b/plugins/pr-inbox/app.tsx @@ -0,0 +1,290 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { definePluginApp, UrlLink, useBbNavigate, useRealtime, useRpc } from "@get-bb/plugin-sdk/app"; +import { AddressProjectDialog } from "./address-project-dialog.js"; +import type { ExperimentalBadge } from "@get-bb/plugin-sdk/app"; +import { groupByOrganization } from "./areas.js"; +import { cn } from "./lib/utils.js"; +import type { rpcContract } from "./server.js"; +import type { Row, View } from "./types.js"; + +const RING = "outline-none focus-visible:ring-2 focus-visible:ring-sky-500"; +const CHIP = "inline-flex h-5 min-w-0 max-w-72 shrink-0 items-center gap-1 rounded px-1.5 text-[11px]"; +const AMBER = "bg-amber-500/10 text-[light-dark(var(--color-amber-800),var(--color-amber-200))]"; +const GRAY = "bg-foreground/[0.05] text-muted-foreground"; +const BUTTON = cn("inline-flex h-6 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md border px-2 text-[12px] disabled:opacity-45", RING); +const GHOST = cn("inline-flex h-6 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md px-2 text-[12px] text-muted-foreground hover:bg-foreground/[0.06] hover:text-foreground", RING); +const COLUMN = "mx-auto w-full max-w-3xl"; +const GROUP_CARD = "min-w-0 rounded-[10px] border border-border/50 bg-foreground/[0.015] px-2 py-1"; +const CHECKBOX = "size-3.5 shrink-0 accent-sky-600 disabled:opacity-20"; +const EMPTY = "py-8 text-center text-[12px] text-muted-foreground"; +const POINTER_CURSORS = "[&_button:not(:disabled)]:cursor-pointer [&_summary]:cursor-pointer [&_a[href]]:cursor-pointer [&_input[type=checkbox]:not(:disabled)]:cursor-pointer"; +type SectionKind = "turn" | "dismissed" | "other" | "held"; + +function age(at: number, now: number) { + const seconds = Math.max(0, Math.floor((now - at) / 1_000)); + return seconds < 60 ? `${seconds}s` : seconds < 3_600 ? `${Math.floor(seconds / 60)}m` : seconds < 86_400 ? `${Math.floor(seconds / 3_600)}h` : `${Math.floor(seconds / 86_400)}d`; +} + +function Spin() { + return ↻; +} + +function Kbd({ children, inverted = false }: { children: string; inverted?: boolean }) { + return {children}; +} + +function ScopeCheckbox({ items, selected, label, disabled, onPick }: { + items: readonly Row[]; selected: ReadonlyMap; label: string; disabled: boolean; + onPick: (items: readonly Row[], select: boolean) => void; +}) { + if (items.length === 0) return ; + const count = items.filter((row) => selected.get(row.id) === row.activity).length; + const full = count === items.length; + return { if (element) element.indeterminate = count > 0 && !full; }} + onChange={() => onPick(items, !full)} className={CHECKBOX} />; +} + +function FeedbackRow({ row, kind, now, pending, selected, onPick, onAddress, onDismiss, onClear, onHold }: { + row: Row; kind: SectionKind; now: number; pending: boolean; selected: boolean; + onPick: (shift: boolean) => void; onAddress: () => void; onDismiss: () => void; onClear: () => void; onHold: (until: string | null) => void; +}) { + const navigate = useBbNavigate(); + const threadId = row.dispatch.kind === "linked" ? row.dispatch.threadId : null; + const clearable = row.dispatch.kind === "uncertain" || (row.dispatch.kind === "linked" && ["idle", "error"].includes(row.threadStatus ?? "")); + const holdLabel = row.holdUntil ? `On hold until ${new Date(row.holdUntil).toLocaleString()}` : null; + const why = row.turn?.why ?? "Waiting on reviewers or checks"; + const updated = `${age(Date.parse(row.updatedAt), now)} ago`; + return
  • +
    + {kind === "turn" && row.dispatch.kind === "none" ? undefined} onClick={(event) => onPick(event.shiftKey)} + className={cn(CHECKBOX, "mt-[3px] opacity-50 group-hover:opacity-100 group-focus-within:opacity-100")} /> : } + + {row.repo.split("/").pop()} + #{row.number} + +
    +

    {row.title}

    +
    + {holdLabel ?? `${why} · ${updated}`} + + {kind === "turn" ? "Your turn" : kind === "dismissed" ? "Dismissed" : kind === "held" ? "On hold" : "Waiting"} + {row.draft ? Draft : null} + {threadId !== null ? : + row.dispatch.kind === "starting" ? Starting… : + kind === "turn" && row.dispatch.kind === "none" ? : null} + {clearable ? : null} + {kind === "held" ? : + kind !== "dismissed" ? : null} + {kind === "turn" || kind === "dismissed" ? : null} + +
    + {row.dispatch.kind === "uncertain" ?

    {row.dispatch.detail}

    : null} +
    +
    +
  • ; +} + +function useInbox() { + const rpc = useRpc(); + const [view, setView] = useState(null); + const [error, setError] = useState(null); + const report = useCallback((cause: unknown) => setError(cause instanceof Error ? cause.message : String(cause)), []); + const refresh = useCallback(() => { void rpc.call("inbox_get").then(setView, report); }, [rpc, report]); + useEffect(refresh, [refresh]); + useEffect(() => { const timer = setInterval(refresh, 15_000); return () => clearInterval(timer); }, [refresh]); + useRealtime("inbox-changed", refresh); + return { rpc, view, error, setError, report, refresh }; +} + +export function InboxPage() { + const { rpc, view, error, setError, report, refresh } = useInbox(); + const navigate = useBbNavigate(); + const rootRef = useRef(null); + const anchor = useRef(null); + const [selected, setSelected] = useState>(new Map()); + const [pending, setPending] = useState(false); + const [addressItems, setAddressItems] = useState(null); + const [polling, setPolling] = useState(false); + const rows = view?.rows ?? []; + const yours = rows.filter((row) => row.turn && !row.dismissed && !row.holdUntil); + const dismissed = rows.filter((row) => row.turn && row.dismissed && !row.holdUntil); + const other = rows.filter((row) => !row.turn && !row.holdUntil); + const held = rows.filter((row) => row.holdUntil); + const organizations = groupByOrganization(yours); + const eligible = organizations.flatMap((organization) => organization.areas.flatMap((area) => area.items.filter((row) => row.dispatch.kind === "none"))); + const chosen = eligible.filter((row) => selected.get(row.id) === row.activity); + const now = Date.now(); + + useEffect(() => { + if (!view) return; + const eligible = new Map(view.rows.filter((row) => row.turn && !row.dismissed && !row.holdUntil && row.dispatch.kind === "none").map((row) => [row.id, row.activity])); + setSelected((current) => new Map([...current].filter(([id, activity]) => eligible.get(id) === activity))); + }, [view]); + + const act = async (operation: () => Promise) => { + if (pending) return; + setPending(true); setError(null); + try { await operation(); refresh(); } + catch (cause) { report(cause); refresh(); } + finally { setPending(false); } + }; + const address = (items: Row[]) => setAddressItems(items); + const startAddress = async (items: Row[], projectId: string) => { + setPending(true); setError(null); + try { + const result = await rpc.call("address", { items: items.map(({ id, activity }) => ({ id, activity })), projectId }); + setSelected(new Map()); setAddressItems(null); refresh(); navigate.toThread(result.threadId); + } catch (cause) { refresh(); throw cause; } + finally { setPending(false); } + }; + const pickScope = (items: readonly Row[], select: boolean) => setSelected((current) => { + const next = new Map(current); + for (const row of items) { if (select) next.set(row.id, row.activity); else next.delete(row.id); } + return next; + }); + const pick = (row: Row, shift: boolean) => { + const from = eligible.findIndex((item) => item.id === anchor.current); + const to = eligible.findIndex((item) => item.id === row.id); + if (shift && from >= 0 && to >= 0) pickScope(eligible.slice(Math.min(from, to), Math.max(from, to) + 1), true); + else pickScope([row], selected.get(row.id) !== row.activity); + anchor.current = row.id; + }; + const poll = async () => { + if (polling) return; + setPolling(true); setError(null); + try { await rpc.call("poll_now"); refresh(); } + catch (cause) { report(cause); } + finally { setPolling(false); } + }; + const shortcuts = useRef({ run: () => {}, clear: () => {}, count: 0, enabled: false }); + shortcuts.current = { run: () => { void address(chosen); }, clear: () => setSelected(new Map()), count: chosen.length, + enabled: !pending && chosen.length <= 20 }; + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + const root = rootRef.current; + const active = document.activeElement; + if (!root || (active && active !== document.body && !root.contains(active))) return; + if (event.metaKey || event.ctrlKey || event.altKey || (event.target instanceof HTMLElement && + (event.target.isContentEditable || event.target.closest("input:not([type=checkbox]):not([type=radio]), textarea, select, [contenteditable]")))) return; + if (shortcuts.current.count === 0) return; + if (event.key === "Escape") { event.preventDefault(); shortcuts.current.clear(); } + else if (event.key === "b" && !event.repeat && shortcuts.current.enabled) { event.preventDefault(); shortcuts.current.run(); } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); + + const renderGroups = (items: Row[], kind: SectionKind) =>
    + {groupByOrganization(items).map((organization) =>
    +

    + {organization.label} + {organization.items.length} +

    +
    + {organization.areas.map((area) =>
    +

    + {area.label}{area.repos.join(", ") === area.label ? null : · {area.repos.join(", ")}} + {area.items.length} +

    +
      + {area.items.map((row) => pick(row, shift)} onAddress={() => { void address([row]); }} + onClear={() => { void act(() => rpc.call("clear_dispatch", { id: row.id })); }} + onHold={(until) => { void act(() => rpc.call("hold", { id: row.id, activity: row.activity, until })); }} + onDismiss={() => { void act(() => rpc.call("dismiss", { id: row.id, activity: row.activity, dismissed: kind !== "dismissed" })); }} />)} +
    +
    )} +
    +
    )} +
    ; + const lastRead = view?.poll?.lastSuccess; + return
    +
    +

    My PRs

    + +
    +
    +
    + {error || view?.poll?.error ?

    {error ?? view?.poll?.error}

    : null} + {view === null ?

    Reading the queue…

    : <> +
    +
    + + +

    Your turn

    + {yours.length} +
    + {yours.length === 0 ?

    Nothing waiting on you.

    : renderGroups(yours, "turn")} +
    + {dismissed.length > 0 ?
    + {dismissed.length} dismissed · show + {renderGroups(dismissed, "dismissed")} +
    : null} + {other.length > 0 ?
    + Other open PRs · {other.length} + {renderGroups(other, "other")} +
    : null} + {held.length > 0 ?
    +

    On hold {held.length}

    + {renderGroups(held, "held")} +
    : null} + } +
    +
    + {chosen.length > 0 ?
    +
    + {chosen.length} selected + + + {chosen.length > 20 ? "Select up to 20 PRs" : "One thread"} + +
    +
    : null} + {addressItems === null ? null : setAddressItems(null)} + onStart={(projectId) => startAddress(addressItems, projectId)} />} +
    ; +} + +function useInboxBadge(): ExperimentalBadge | null { + const { view } = useInbox(); + const count = view?.rows.filter((row) => row.turn && !row.dismissed && !row.holdUntil).length ?? 0; + return count > 0 ? { count, tone: "warning", label: `${count} pull request${count === 1 ? "" : "s"} waiting for your response` } : null; +} + +function InboxCount() { + const { view } = useInbox(); + return {view?.rows.filter((row) => row.turn && !row.dismissed && !row.holdUntil).length ?? 0}; +} + +export default definePluginApp((app) => { + app.slots.navPanel({ id: "inbox", title: "My PRs", icon: "GitBranch", path: "inbox", component: InboxPage, experimental_useBadge: useInboxBadge, headerContent: InboxCount }); +}); diff --git a/plugins/pr-inbox/areas.ts b/plugins/pr-inbox/areas.ts new file mode 100644 index 00000000..0654a295 --- /dev/null +++ b/plugins/pr-inbox/areas.ts @@ -0,0 +1,40 @@ +import type { Row } from "./types.js"; + +export function groupByArea(items: readonly Row[]) { + const groups = new Map(); + for (const item of items) { + const scope = item.title.match(/\b[a-z]+\(([^()]+)\)!?:/i)?.[1]?.trim(); + const token = scope?.toLowerCase().split(/[-_/\s]+/).find(Boolean) ?? ""; + const normalized = /[^s]s$/.test(token) ? token.slice(0, -1) : token; + const key = scope ? `scope:${normalized || scope.toLowerCase()}` : `repo:${item.repo.toLowerCase()}`; + const group = groups.get(key) ?? { items: [], labels: [], latest: 0 }; + group.items.push(item); + group.labels.push(scope || item.repo.split("/").pop() || item.repo); + group.latest = Math.max(group.latest, Date.parse(item.updatedAt)); + groups.set(key, group); + } + return [...groups].map(([key, group]) => { + const counts = new Map(); + for (const label of group.labels) counts.set(label, (counts.get(label) ?? 0) + 1); + const label = [...counts].sort(([a, x], [b, y]) => y - x || a.length - b.length || a.localeCompare(b))[0]?.[0] ?? key; + return { + key, label, latest: group.latest, + repos: [...new Set(group.items.map((item) => item.repo.split("/").pop() || item.repo))].sort(), + items: [...group.items].sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt)), + }; + }).sort((a, b) => b.items.length - a.items.length || b.latest - a.latest || a.key.localeCompare(b.key)); +} + +/** Keep title scopes within their GitHub owner, with owners in alphabetical order. */ +export function groupByOrganization(items: readonly Row[]) { + const groups = new Map(); + for (const item of items) { + const organization = (item.repo.split("/")[0] || item.repo).toLowerCase(); + const group = groups.get(organization) ?? []; + group.push(item); + groups.set(organization, group); + } + return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([label, rows]) => ({ + label, items: rows, areas: groupByArea(rows), + })); +} diff --git a/plugins/pr-inbox/components.json b/plugins/pr-inbox/components.json new file mode 100644 index 00000000..8efbf148 --- /dev/null +++ b/plugins/pr-inbox/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "tsx": true, + "tailwind": { + "config": "", + "css": "app.css", + "baseColor": "neutral", + "cssVariables": true + }, + "aliases": { + "components": "@/components", + "ui": "@/components/ui", + "lib": "@/lib", + "utils": "@/lib/utils", + "hooks": "@/hooks" + }, + "registries": { + "@bb": "https://raw.githubusercontent.com/get-bb/bb/desktop-v0.46.0/packages/plugin-registry/r/{name}.json" + } +} diff --git a/plugins/pr-inbox/components/ui/button.tsx b/plugins/pr-inbox/components/ui/button.tsx new file mode 100644 index 00000000..1d049e67 --- /dev/null +++ b/plugins/pr-inbox/components/ui/button.tsx @@ -0,0 +1,59 @@ +import * as React from "react"; +import { Slot } from "@radix-ui/react-slot"; +import { cva, type VariantProps } from "class-variance-authority"; + +import { cn } from "../../lib/utils"; +import { CONTROL_HOVER_TRANSITION } from "./motion.js"; + +const buttonVariants = cva( + `inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ${CONTROL_HOVER_TRANSITION} focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_[data-icon-root]]:pointer-events-none [&_[data-icon-root]]:size-4 [&_[data-icon-root]]:shrink-0`, + { + variants: { + variant: { + default: "bg-foreground text-background hover:bg-foreground/90", + destructive: + "bg-destructive text-destructive-foreground hover:bg-destructive/90", + outline: + "border border-input bg-transparent hover:bg-state-hover hover:text-foreground", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: + "hover:bg-state-hover hover:text-foreground aria-pressed:bg-state-active aria-pressed:text-foreground aria-pressed:hover:bg-state-active data-[state=open]:bg-state-active data-[state=open]:text-foreground data-[state=open]:hover:bg-state-active", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2", + sm: "h-8 rounded-md px-3 text-xs", + lg: "h-10 rounded-md px-8", + icon: "h-9 w-9", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + }, +); + +export interface ButtonProps + extends + Omit, "title">, + VariantProps { + asChild?: boolean; +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : "button"; + return ( + + ); + }, +); +Button.displayName = "Button"; + +export { Button, buttonVariants }; diff --git a/plugins/pr-inbox/components/ui/dialog.tsx b/plugins/pr-inbox/components/ui/dialog.tsx new file mode 100644 index 00000000..f46751aa --- /dev/null +++ b/plugins/pr-inbox/components/ui/dialog.tsx @@ -0,0 +1,416 @@ +import * as React from "react"; +import * as DialogPrimitive from "@radix-ui/react-dialog"; +import { Slot } from "@radix-ui/react-slot"; + +import { cn } from "../../lib/utils"; +import { usePortalScopeProps } from "../../lib/portal-scope"; +import { useBrowserDimmingModal } from "../../hooks/useBrowserDimmingModal"; +import { + type ResponsiveOverlayContextValue, + useResponsiveRoot, + MobileTrigger, + ResponsiveDrawerShell, + stripRadixContentProps, +} from "./responsive-overlay.js"; +import { + blurActiveKeyboardInputBeforeOverlayOpen, + getOverlayTriggerClassName, + preventOverlayTriggerSelection, +} from "./overlay-trigger.js"; +import { Icon } from "../../components/ui/icon.js"; + +interface ResponsiveDialogContextValue extends ResponsiveOverlayContextValue { + titleId: string; + descriptionId: string; + registerTitleId: (id: string) => () => void; + registerDescriptionId: (id: string) => () => void; +} + +const ResponsiveDialogContext = + React.createContext({ + isCompactViewport: false, + open: false, + onOpenChange: () => {}, + titleId: "", + descriptionId: "", + registerTitleId: () => () => {}, + registerDescriptionId: () => () => {}, + }); + +function useResponsiveDialog() { + return React.useContext(ResponsiveDialogContext); +} + +function Dialog({ + children, + open: controlledOpen, + onOpenChange: controlledOnChange, + ...props +}: React.ComponentProps) { + const responsiveRoot = useResponsiveRoot(controlledOpen, controlledOnChange); + const generatedTitleId = React.useId(); + const generatedDescriptionId = React.useId(); + const [titleId, setTitleId] = React.useState(generatedTitleId); + const [descriptionId, setDescriptionId] = React.useState( + generatedDescriptionId, + ); + const registerTitleId = React.useCallback( + (id: string) => { + setTitleId(id); + return () => setTitleId(generatedTitleId); + }, + [generatedTitleId], + ); + const registerDescriptionId = React.useCallback( + (id: string) => { + setDescriptionId(id); + return () => setDescriptionId(generatedDescriptionId); + }, + [generatedDescriptionId], + ); + const ctx = React.useMemo( + () => ({ + ...responsiveRoot, + titleId, + descriptionId, + registerTitleId, + registerDescriptionId, + }), + [ + descriptionId, + registerDescriptionId, + registerTitleId, + responsiveRoot, + titleId, + ], + ); + + const body = ctx.isCompactViewport ? ( + children + ) : ( + + {children} + + ); + + return ( + + {body} + + ); +} + +const DialogTrigger = React.forwardRef< + HTMLButtonElement, + React.ComponentPropsWithoutRef +>(({ asChild, children, className, ...props }, ref) => { + const { isCompactViewport, open, onOpenChange } = useResponsiveDialog(); + + if (isCompactViewport) { + return ( + + {children} + + ); + } + + return ( + { + if (!open) { + blurActiveKeyboardInputBeforeOverlayOpen(); + } + preventOverlayTriggerSelection(event); + }} + {...props} + > + {children} + + ); +}); +DialogTrigger.displayName = "DialogTrigger"; + +interface DialogCloseProps extends React.ButtonHTMLAttributes { + asChild?: boolean; +} + +const DialogClose = React.forwardRef( + ({ asChild, onClick, children, ...props }, ref) => { + const { isCompactViewport, onOpenChange } = useResponsiveDialog(); + + if (isCompactViewport) { + const Comp = asChild ? Slot : "button"; + const handleClick: React.MouseEventHandler = ( + event, + ) => { + onClick?.(event); + if (!event.defaultPrevented) { + onOpenChange(false); + } + }; + return ( + + {children} + + ); + } + + return ( + + {children} + + ); + }, +); +DialogClose.displayName = "DialogClose"; + +const DialogOverlay = React.forwardRef< + React.ComponentRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogOverlay.displayName = DialogPrimitive.Overlay.displayName; + +type DialogContentProps = React.ComponentPropsWithoutRef< + typeof DialogPrimitive.Content +> & { + onAfterCloseAutoFocus?: () => void; + hideCloseButton?: boolean; +}; + +const DialogContent = React.forwardRef( + ( + { + className, + children, + hideCloseButton = false, + onAfterCloseAutoFocus, + onCloseAutoFocus, + ...props + }, + ref, + ) => { + const { isCompactViewport, open, onOpenChange, titleId, descriptionId } = + useResponsiveDialog(); + useBrowserDimmingModal(open); + const scopeProps = usePortalScopeProps(); + + if (isCompactViewport) { + const domProps = stripRadixContentProps(props); + return ( + +
    + {children} +
    +
    + ); + } + + return ( + + + { + onCloseAutoFocus?.(event); + queueMicrotask(() => onAfterCloseAutoFocus?.()); + }} + className={cn( + "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg grid-cols-[minmax(0,1fr)] translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-sm duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg", + className, + )} + {...props} + > + {children} + {hideCloseButton ? null : ( + + + Close + + )} + + + ); + }, +); +DialogContent.displayName = "DialogContent"; + +const DialogHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
    +); +DialogHeader.displayName = "DialogHeader"; + +const DialogFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
    +); +DialogFooter.displayName = "DialogFooter"; + +const DialogTitle = React.forwardRef< + HTMLHeadingElement, + React.ComponentPropsWithoutRef +>(({ asChild, className, id, children, ...props }, ref) => { + const { isCompactViewport, titleId, registerTitleId } = useResponsiveDialog(); + const resolvedId = id ?? titleId; + React.useLayoutEffect(() => { + if (!isCompactViewport) { + return; + } + return registerTitleId(resolvedId); + }, [isCompactViewport, registerTitleId, resolvedId]); + + if (isCompactViewport) { + const titleProps = { + id: resolvedId, + className: cn( + "text-base font-semibold leading-none tracking-tight", + className, + ), + ...props, + }; + if (asChild) { + return ( + + {children} + + ); + } + return ( +

    + {children} +

    + ); + } + return ( + + {children} + + ); +}); +DialogTitle.displayName = "DialogTitle"; + +const DialogDescription = React.forwardRef< + React.ComponentRef, + React.ComponentPropsWithoutRef +>(({ asChild, className, id, children, ...props }, ref) => { + const { isCompactViewport, descriptionId, registerDescriptionId } = + useResponsiveDialog(); + const resolvedId = id ?? descriptionId; + React.useLayoutEffect(() => { + if (!isCompactViewport) { + return; + } + return registerDescriptionId(resolvedId); + }, [isCompactViewport, registerDescriptionId, resolvedId]); + + if (isCompactViewport) { + const descriptionProps = { + id: resolvedId, + className: cn("text-sm text-muted-foreground", className), + ...props, + }; + if (asChild) { + return ( + + {children} + + ); + } + return ( +

    + {children} +

    + ); + } + return ( + + {children} + + ); +}); +DialogDescription.displayName = DialogPrimitive.Description.displayName; + +export { + Dialog, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +}; diff --git a/plugins/pr-inbox/components/ui/hooks/use-compact-viewport.tsx b/plugins/pr-inbox/components/ui/hooks/use-compact-viewport.tsx new file mode 100644 index 00000000..e2adfaef --- /dev/null +++ b/plugins/pr-inbox/components/ui/hooks/use-compact-viewport.tsx @@ -0,0 +1,37 @@ +import { + createContext, + createElement, + useContext, + type ReactNode, +} from "react"; + +import { useMediaQuery } from "./use-media-query.js"; + +export const COMPACT_VIEWPORT_QUERY = "(max-width: 767px)"; + +const CompactViewportOverrideContext = createContext(null); + +interface CompactViewportOverrideProviderProps { + children: ReactNode; + isCompactViewport: boolean; +} + +export function CompactViewportOverrideProvider({ + children, + isCompactViewport, +}: CompactViewportOverrideProviderProps) { + return createElement( + CompactViewportOverrideContext.Provider, + { value: isCompactViewport }, + children, + ); +} + +export function useIsCompactViewport(): boolean { + const override = useContext(CompactViewportOverrideContext); + const isCompactViewport = useMediaQuery(COMPACT_VIEWPORT_QUERY); + if (override !== null) { + return override; + } + return isCompactViewport; +} diff --git a/plugins/pr-inbox/components/ui/hooks/use-media-query.ts b/plugins/pr-inbox/components/ui/hooks/use-media-query.ts new file mode 100644 index 00000000..076b07ac --- /dev/null +++ b/plugins/pr-inbox/components/ui/hooks/use-media-query.ts @@ -0,0 +1,70 @@ +import { useSyncExternalStore } from "react"; + +export const DARK_COLOR_SCHEME_QUERY = "(prefers-color-scheme: dark)"; +export const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)"; + +type MediaQueryRef = { + mql: MediaQueryList; + subscribe: (notify: () => void) => () => void; +}; + +const mediaQueryCache = new Map(); + +function createMediaQueryRef(query: string): MediaQueryRef | null { + if (typeof window === "undefined" || !window.matchMedia) return null; + + let ref = mediaQueryCache.get(query); + if (ref) return ref; + + const mql = window.matchMedia(query); + const listeners = new Set<() => void>(); + const onChange = () => { + for (const listener of listeners) listener(); + }; + + ref = { + mql, + subscribe(notify) { + const wasEmpty = listeners.size === 0; + listeners.add(notify); + if (wasEmpty) { + mql.addEventListener("change", onChange); + } + return () => { + listeners.delete(notify); + if (listeners.size === 0) { + mql.removeEventListener("change", onChange); + mediaQueryCache.delete(query); + } + }; + }, + }; + mediaQueryCache.set(query, ref); + return ref; +} + +export function subscribeMediaQuery( + query: string, + notify: () => void, +): () => void { + return createMediaQueryRef(query)?.subscribe(notify) ?? (() => {}); +} + +export function getMediaQuerySnapshot(query: string): boolean { + if (typeof window === "undefined" || !window.matchMedia) return false; + return ( + mediaQueryCache.get(query)?.mql.matches ?? window.matchMedia(query).matches + ); +} + +export function useMediaQuery(query: string): boolean { + return useSyncExternalStore( + (notify) => subscribeMediaQuery(query, notify), + () => getMediaQuerySnapshot(query), + () => false, + ); +} + +export function usePrefersReducedMotion(): boolean { + return useMediaQuery(REDUCED_MOTION_QUERY); +} diff --git a/plugins/pr-inbox/components/ui/hooks/use-pointer-coarse.ts b/plugins/pr-inbox/components/ui/hooks/use-pointer-coarse.ts new file mode 100644 index 00000000..7c123c51 --- /dev/null +++ b/plugins/pr-inbox/components/ui/hooks/use-pointer-coarse.ts @@ -0,0 +1,7 @@ +import { useMediaQuery } from "./use-media-query.js"; + +export const POINTER_COARSE_QUERY = "(pointer: coarse)"; + +export function usePointerCoarse(): boolean { + return useMediaQuery(POINTER_COARSE_QUERY); +} diff --git a/plugins/pr-inbox/components/ui/icon.tsx b/plugins/pr-inbox/components/ui/icon.tsx new file mode 100644 index 00000000..63febf6c --- /dev/null +++ b/plugins/pr-inbox/components/ui/icon.tsx @@ -0,0 +1 @@ +export { experimental_Icon as Icon } from "@get-bb/plugin-sdk/app"; diff --git a/plugins/pr-inbox/components/ui/motion.ts b/plugins/pr-inbox/components/ui/motion.ts new file mode 100644 index 00000000..caaa329c --- /dev/null +++ b/plugins/pr-inbox/components/ui/motion.ts @@ -0,0 +1,4 @@ +export const CONTROL_HOVER_TRANSITION = + "transition-colors duration-150 hover:duration-0"; + +export const LIST_HOVER_TRANSITION = "transition-none"; diff --git a/plugins/pr-inbox/components/ui/overlay-trigger.ts b/plugins/pr-inbox/components/ui/overlay-trigger.ts new file mode 100644 index 00000000..cf0bff66 --- /dev/null +++ b/plugins/pr-inbox/components/ui/overlay-trigger.ts @@ -0,0 +1,84 @@ +import type { MouseEvent } from "react"; +import { cn } from "../../lib/utils"; + +const OVERLAY_TRIGGER_CLASS_NAME = "select-none"; + +type OverlayTriggerClassNameResolver = (className?: string) => string; + +const NON_TEXT_INPUT_TYPES = new Set([ + "button", + "checkbox", + "file", + "hidden", + "image", + "radio", + "range", + "reset", + "submit", +]); + +export const getOverlayTriggerClassName: OverlayTriggerClassNameResolver = ( + className, +) => cn(OVERLAY_TRIGGER_CLASS_NAME, className); + +function isKeyboardInputElement(element: Element): element is HTMLElement { + if (element instanceof HTMLTextAreaElement) return true; + if (element instanceof HTMLInputElement) { + return ( + !element.disabled && + !element.readOnly && + !NON_TEXT_INPUT_TYPES.has(element.type) + ); + } + if (!(element instanceof HTMLElement)) return false; + + return ( + element.isContentEditable || + element.closest("[contenteditable='true']") !== null + ); +} + +export function blurActiveKeyboardInputWithin(container: Element | null): void { + if (typeof document === "undefined") return; + + const activeElement = document.activeElement; + if (!activeElement || !isKeyboardInputElement(activeElement)) return; + if (container !== null && !container.contains(activeElement)) return; + + activeElement.blur(); +} + +export function blurActiveKeyboardInputBeforeOverlayOpen(): void { + blurActiveKeyboardInputWithin(null); +} + +export function blurActiveKeyboardInputBeforeOverlayClose(): void { + blurActiveKeyboardInputWithin(null); +} + +export function preventOverlayTriggerSelection(event: MouseEvent): void { + event.preventDefault(); +} + +let lastInputModality: "pointer" | "keyboard" = "pointer"; + +if (typeof document !== "undefined") { + document.addEventListener( + "keydown", + () => { + lastInputModality = "keyboard"; + }, + { capture: true }, + ); + document.addEventListener( + "pointerdown", + () => { + lastInputModality = "pointer"; + }, + { capture: true }, + ); +} + +export function isLastInputKeyboard(): boolean { + return lastInputModality === "keyboard"; +} diff --git a/plugins/pr-inbox/components/ui/responsive-overlay.tsx b/plugins/pr-inbox/components/ui/responsive-overlay.tsx new file mode 100644 index 00000000..a66ced21 --- /dev/null +++ b/plugins/pr-inbox/components/ui/responsive-overlay.tsx @@ -0,0 +1,823 @@ +import * as React from "react"; +import { createPortal } from "react-dom"; +import { Slot } from "@radix-ui/react-slot"; + +import { + blurActiveKeyboardInputBeforeOverlayOpen, + blurActiveKeyboardInputBeforeOverlayClose, + blurActiveKeyboardInputWithin, + getOverlayTriggerClassName, + preventOverlayTriggerSelection, +} from "./overlay-trigger.js"; +import { useIsCompactViewport } from "./hooks/use-compact-viewport.js"; +import { usePointerCoarse } from "./hooks/use-pointer-coarse.js"; +import { usePortalScopeProps } from "../../lib/portal-scope.js"; +import { cn } from "../../lib/utils.js"; + +export interface ResponsiveOverlayContextValue { + isCompactViewport: boolean; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +const RESPONSIVE_DRAWER_REALIZE_FALLBACK_MS = 120; + +export const COMPACT_SHEET_CONTENT_STYLE: React.CSSProperties = { + width: "auto", + minWidth: "auto", + maxWidth: "none", +}; + +const DRAWER_KEYBOARD_INSET_PROPERTY = "--bb-drawer-keyboard-inset"; +const DRAWER_KEYBOARD_MIN_OVERLAP_PX = 80; + +function resetDrawerKeyboardStyles(drawerElement: HTMLElement | null): void { + if (drawerElement === null) return; + + drawerElement.style.height = ""; + drawerElement.style.bottom = ""; + drawerElement.style.removeProperty(DRAWER_KEYBOARD_INSET_PROPERTY); +} + +export function measureDrawerKeyboardOverlap({ + layoutViewportHeight, + visualViewportHeight, + visualViewportOffsetTop, +}: { + layoutViewportHeight: number; + visualViewportHeight: number; + visualViewportOffsetTop: number; +}): number { + const overlap = Math.round( + layoutViewportHeight - (visualViewportHeight + visualViewportOffsetTop), + ); + return overlap >= DRAWER_KEYBOARD_MIN_OVERLAP_PX ? overlap : 0; +} + +function useDrawerKeyboardInset( + panelRef: React.RefObject, + open: boolean, +): void { + React.useEffect(() => { + const panel = panelRef.current; + const visualViewport = window.visualViewport; + if (panel === null || !open || !visualViewport) return; + + let animationFrame: number | null = null; + const applyInset = () => { + animationFrame = null; + if (visualViewport.scale !== 1) { + resetDrawerKeyboardStyles(panel); + return; + } + const overlap = measureDrawerKeyboardOverlap({ + layoutViewportHeight: panel.ownerDocument.documentElement.clientHeight, + visualViewportHeight: visualViewport.height, + visualViewportOffsetTop: visualViewport.offsetTop, + }); + if (overlap === 0) { + panel.style.bottom = ""; + panel.style.removeProperty(DRAWER_KEYBOARD_INSET_PROPERTY); + return; + } + panel.style.bottom = `${overlap}px`; + panel.style.setProperty(DRAWER_KEYBOARD_INSET_PROPERTY, `${overlap}px`); + }; + const scheduleUpdate = () => { + if (animationFrame !== null) { + window.cancelAnimationFrame(animationFrame); + } + animationFrame = window.requestAnimationFrame(applyInset); + }; + + applyInset(); + visualViewport.addEventListener("resize", scheduleUpdate); + visualViewport.addEventListener("scroll", scheduleUpdate); + + return () => { + visualViewport.removeEventListener("resize", scheduleUpdate); + visualViewport.removeEventListener("scroll", scheduleUpdate); + if (animationFrame !== null) { + window.cancelAnimationFrame(animationFrame); + } + resetDrawerKeyboardStyles(panel); + }; + }, [open, panelRef]); +} + +export function useResponsiveOverlayBehavior() { + const presentation = useIsCompactViewport() ? "drawer" : "floating"; + const isPointerCoarse = usePointerCoarse(); + + return { + presentation, + supportsHover: presentation === "floating" && !isPointerCoarse, + }; +} + +export function useResponsiveRoot( + controlledOpen: boolean | undefined, + controlledOnChange: ((open: boolean) => void) | undefined, + defaultOpen: boolean = false, +): ResponsiveOverlayContextValue { + const { presentation } = useResponsiveOverlayBehavior(); + const isCompactViewport = presentation === "drawer"; + const [internalOpen, setInternalOpen] = React.useState(defaultOpen); + const isControlled = controlledOpen !== undefined; + const open = isControlled ? controlledOpen : internalOpen; + + const onOpenChange = React.useCallback( + (next: boolean) => { + if (open && !next && isCompactViewport) { + blurActiveKeyboardInputBeforeOverlayClose(); + } + if (!isControlled) { + setInternalOpen(next); + } + controlledOnChange?.(next); + }, + [isCompactViewport, isControlled, controlledOnChange, open], + ); + + return React.useMemo( + () => ({ isCompactViewport, open, onOpenChange }), + [isCompactViewport, open, onOpenChange], + ); +} + +interface MobileTriggerProps { + asChild?: boolean; + open: boolean; + onOpenChange: (open: boolean) => void; + haspopup: "menu" | "dialog"; + children: React.ReactNode; + onClick?: React.MouseEventHandler; +} + +export const MobileTrigger = React.forwardRef< + HTMLButtonElement, + MobileTriggerProps & + Omit< + React.ButtonHTMLAttributes, + keyof MobileTriggerProps + > +>( + ( + { + asChild, + open, + onOpenChange, + haspopup, + onClick, + children, + className, + ...domProps + }, + ref, + ) => { + const triggerClassName = getOverlayTriggerClassName(className); + const handleClick: React.MouseEventHandler = (e) => { + onClick?.(e); + if (!e.defaultPrevented) { + if (!open) { + blurActiveKeyboardInputBeforeOverlayOpen(); + } + onOpenChange(!open); + } + }; + + const ariaProps = { + "aria-expanded": open, + "aria-haspopup": haspopup, + "data-state": open ? "open" : "closed", + } as const; + + if (asChild) { + return ( + + {children} + + ); + } + + return ( + + ); + }, +); +MobileTrigger.displayName = "MobileTrigger"; + +const RADIX_CONTENT_PROP_NAMES = [ + "side", + "sideOffset", + "align", + "alignOffset", + "collisionPadding", + "collisionBoundary", + "arrowPadding", + "sticky", + "hideWhenDetached", + "avoidCollisions", + "onOpenAutoFocus", + "onCloseAutoFocus", + "onEscapeKeyDown", + "onPointerDownOutside", + "onFocusOutside", + "onInteractOutside", +] as const; + +type RadixContentPropName = (typeof RADIX_CONTENT_PROP_NAMES)[number]; + +const RADIX_CONTENT_KEYS: ReadonlySet = new Set( + RADIX_CONTENT_PROP_NAMES, +); + +export function stripRadixContentProps>( + props: T, +): Omit { + const result = {} as Record; + for (const key of Object.keys(props)) { + if (!RADIX_CONTENT_KEYS.has(key)) { + result[key] = props[key]; + } + } + return result as Omit; +} + +interface ResponsiveDrawerShellProps { + open: boolean; + onOpenChange: (open: boolean) => void; + closeOnBackdropClick?: boolean; + onAfterCloseAutoFocus?: () => void; + srLabel?: string; + labelledBy?: string; + describedBy?: string; + contentClassName?: string; + onContentAnimationEnd?: (open: boolean) => void; + children: React.ReactNode; +} + +export function useResponsiveDrawerRealization({ + open, + enabled = true, +}: { + open: boolean; + enabled?: boolean; +}): { isContentRealized: boolean; realizeContent: () => void } { + const [isContentRealized, setIsContentRealized] = React.useState(false); + const realizeContent = React.useCallback( + () => setIsContentRealized(true), + [], + ); + + React.useEffect(() => { + if (!enabled || !open || isContentRealized) { + return; + } + + let firstFrame: number | null = null; + let secondFrame: number | null = null; + firstFrame = window.requestAnimationFrame(() => { + firstFrame = null; + secondFrame = window.requestAnimationFrame(() => { + secondFrame = null; + realizeContent(); + }); + }); + const fallback = window.setTimeout( + realizeContent, + RESPONSIVE_DRAWER_REALIZE_FALLBACK_MS, + ); + + return () => { + if (firstFrame !== null) { + window.cancelAnimationFrame(firstFrame); + } + if (secondFrame !== null) { + window.cancelAnimationFrame(secondFrame); + } + window.clearTimeout(fallback); + }; + }, [enabled, isContentRealized, open, realizeContent]); + + return { + isContentRealized: enabled && isContentRealized, + realizeContent, + }; +} + +export function ResponsiveDrawerShell({ + open, + onOpenChange, + onAfterCloseAutoFocus, + closeOnBackdropClick = true, + srLabel, + labelledBy, + describedBy, + contentClassName, + onContentAnimationEnd, + children, +}: ResponsiveDrawerShellProps) { + const { isContentRealized } = useResponsiveDrawerRealization({ open }); + + if (!open && !isContentRealized) { + return null; + } + + return ( + + {isContentRealized ? ( + children + ) : ( +