Skip to content
Open
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
27 changes: 27 additions & 0 deletions hub/app/controllers/prototype_authors_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Offers bounded registration-author choices only within an authorized repository.
class PrototypeAuthorsController < ApplicationController
include HasRepositoryWorkspace

rescue_from GithubClient::Error, with: -> { head :service_unavailable }

# @route GET /repositories/:repository_github_id/prototype_authors (repository_prototype_authors)
def index
load_repository_workspace
return if performed?

page = @repository.prototype_listing.authors \
user: Current.user,
query: params[:q],
cursor: params[:cursor]
response.headers["Cache-Control"] = "private, no-store"
render \
json: {
authors: page.fetch(:authors).map do |author|
{ id: author.id.to_s, login: author.login, name: author.name, avatarUrl: author.avatar_url }
end,
nextCursor: page.fetch(:next_cursor)
}
rescue Repository::PrototypeListing::InvalidQuery
head :bad_request
end
end
11 changes: 9 additions & 2 deletions hub/app/controllers/repositories_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,13 @@ def show
load_repository_workspace
return if performed?

@prototypes = @repository.reviewable_prototypes.active.registered
.includes(:author, :current_build).order(registered_at: :desc, id: :desc)
@listing = @repository.prototype_listing.page \
user: Current.user,
query: params[:q],
author: params[:author],
cursor: params[:cursor]
@prototypes = @listing.prototypes
ActiveRecord::Associations::Preloader.new(records: @prototypes, associations: [ :author, :current_build ]).call
prototype_ids = @prototypes.map(&:id)
@latest_builds = @prototypes.filter_map(&:current_build).index_by(&:prototype_id)
missing_prototype_ids = prototype_ids - @latest_builds.keys
Expand All @@ -47,6 +52,8 @@ def show
@candidate_check_failed = true
end
end
rescue Repository::PrototypeListing::InvalidQuery
head :bad_request
end

# @route POST /repositories/:github_id/poll (poll_repository)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ const state = vi.hoisted(() => ({
vi.mock("@hooks/use-page-data", () => ({
usePageData: () => state.data,
}))
vi.mock("@hooks/use-prototype-listing", () => ({
usePrototypeListing: () => ({}),
}))
vi.mock("@pages/repositories-show-page", () => ({
RepositoriesShowPage: ({ managingPrototypes }: { managingPrototypes: boolean }) => (
<output>{managingPrototypes ? "Managing prototypes" : "Idle"}</output>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"
import { describe, expect, it, vi } from "vitest"

import { prototypeListing } from "@/storybook/fixtures/prototype-listing"
import type { PrototypeListingControls } from "@utils/prototype-listing/types"

import { PrototypeAuthorFilter } from "."

describe("PrototypeAuthorFilter()", () => {
it("pins Me first and supports selecting and clearing an author with the keyboard", () => {
const onChange = vi.fn()
const onSearch = vi.fn(() => Promise.resolve({ authors: [], nextCursor: null }))
const { rerender } = render(
<PrototypeAuthorFilter listing={prototypeListing} onChange={onChange} onSearch={onSearch} />,
)
const trigger = screen.getByRole("button", { name: "Author: All authors" })
fireEvent.click(trigger)
const menu = screen.getByRole("menu", { name: "Author" })
expect(within(menu).getAllByRole("menuitemradio")[0]).toHaveTextContent("Me")
expect(within(menu).getByRole("searchbox")).toHaveFocus()
expect(
within(menu).getByRole("menuitemradio", { name: "All authors", checked: true }),
).toBeInTheDocument()
fireEvent.keyDown(within(menu).getByRole("searchbox"), { key: "ArrowDown" })
const me = within(menu).getByRole("menuitemradio", { name: "Me" })
expect(me).toHaveFocus()
fireEvent.keyDown(me, { key: " " })
expect(onChange).toHaveBeenCalledExactlyOnceWith("me")
expect(screen.queryByRole("menu")).not.toBeInTheDocument()
expect(trigger).toHaveFocus()
rerender(
<PrototypeAuthorFilter
listing={{ ...prototypeListing, author: "me", authorLabel: "Me" }}
onChange={onChange}
onSearch={onSearch}
/>,
)
fireEvent.click(screen.getByRole("button", { name: "Author: Me" }))
const all = screen.getByRole("menuitemradio", { name: "All authors", checked: false })
all.focus()
fireEvent.keyDown(all, { key: "Enter" })
expect(onChange).toHaveBeenCalledTimes(2)
expect(onChange).toHaveBeenLastCalledWith("")
expect(screen.queryByRole("menu")).not.toBeInTheDocument()
expect(trigger).toHaveFocus()
})

it("replaces author option pages and cancels stale searches when the query changes", async () => {
const onSearch = vi
.fn<PrototypeListingControls["loadAuthors"]>(() =>
Promise.resolve({
authors: [{ id: "2", login: "mona", name: null, avatarUrl: null }],
nextCursor: "next",
}),
)
.mockResolvedValueOnce({
authors: [{ id: "1", login: "octocat", name: null, avatarUrl: null }],
nextCursor: "next",
})
render(
<PrototypeAuthorFilter listing={prototypeListing} onChange={vi.fn()} onSearch={onSearch} />,
)
fireEvent.click(screen.getByRole("button", { name: "Author: All authors" }))
expect(await screen.findByRole("menuitemradio", { name: "@octocat" })).toBeInTheDocument()
const firstSignal = onSearch.mock.calls[0]?.[2]
fireEvent.click(screen.getByRole("button", { name: "Next authors" }))
expect(await screen.findByRole("menuitemradio", { name: "@mona" })).toBeInTheDocument()
expect(screen.queryByRole("menuitemradio", { name: "@octocat" })).not.toBeInTheDocument()
expect(firstSignal?.aborted).toBe(true)
fireEvent.change(screen.getByRole("searchbox"), { target: { value: "mona" } })
await waitFor(() =>
expect(onSearch).toHaveBeenLastCalledWith("mona", null, expect.any(AbortSignal)),
)
fireEvent.keyDown(screen.getByRole("searchbox"), { key: "Escape" })
expect(screen.queryByRole("menu")).not.toBeInTheDocument()
expect(onSearch.mock.calls.at(-1)?.[2].aborted).toBe(true)
})

it("reports lookup failures and retries without losing the pinned Me option", async () => {
const onSearch = vi
.fn(() => Promise.resolve({ authors: [], nextCursor: null }))
.mockRejectedValueOnce(new Error("Unavailable"))
render(
<PrototypeAuthorFilter listing={prototypeListing} onChange={vi.fn()} onSearch={onSearch} />,
)
fireEvent.click(screen.getByRole("button", { name: "Author: All authors" }))
expect(await screen.findByRole("alert")).toHaveTextContent(prototypeListing.copy.authorsFailed)
expect(screen.getByRole("menuitemradio", { name: "Me" })).toBeInTheDocument()
fireEvent.click(screen.getByRole("button", { name: "Retry" }))
expect(await screen.findByRole("status")).toHaveTextContent(prototypeListing.copy.loading)
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("No matching authors"))
})
})
37 changes: 37 additions & 0 deletions hub/app/javascript/features/prototype-author-filter/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { ActionMenu } from "@primer/react-brand"

import type { PrototypeAuthorResults, PrototypeListing } from "@utils/prototype-listing/types"

import { PrototypeAuthorOptions } from "./options"

import "./styles.css"

/** Offers a searchable, single-selection menu of saved registration authors. */
export function PrototypeAuthorFilter({
listing,
onChange,
onSearch,
}: {
listing: PrototypeListing
onChange: (author: string) => void
onSearch: (
query: string,
cursor: string | null,
signal: AbortSignal,
) => Promise<PrototypeAuthorResults>
}) {
const label = `${listing.copy.author}: ${listing.authorLabel}`

return (
<div className="prototype-author-filter">
<ActionMenu size="small" selectionVariant="single" menuAlignment="start" onSelect={onChange}>
<ActionMenu.Button aria-label={label} variant="secondary">
{label}
</ActionMenu.Button>
<ActionMenu.Overlay aria-label={listing.copy.author}>
<PrototypeAuthorOptions listing={listing} onSearch={onSearch} />
</ActionMenu.Overlay>
</ActionMenu>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { useEffect, useRef, useState } from "react"
import type { KeyboardEvent } from "react"

import { ActionMenu, Button, TextInput } from "@primer/react-brand"

import type { PrototypeAuthorResults, PrototypeListing } from "@utils/prototype-listing/types"

/** Loads author choices only while the menu is mounted and cancels stale searches. */
export function PrototypeAuthorOptions({
listing,
onSearch,
handler,
}: {
listing: PrototypeListing
onSearch: (
query: string,
cursor: string | null,
signal: AbortSignal,
) => Promise<PrototypeAuthorResults>
handler?: (author: string) => void
}) {
const [query, setQuery] = useState("")
const [cursor, setCursor] = useState<string | null>(null)
const [results, setResults] = useState<PrototypeAuthorResults | null>(null)
const [failed, setFailed] = useState(false)
const [retry, setRetry] = useState(0)
const input = useRef<HTMLInputElement>(null)
const copy = listing.copy

useEffect(() => {
input.current?.focus()
}, [])

useEffect(() => {
const controller = new AbortController()
const timer = setTimeout(() => {
onSearch(query, cursor, controller.signal).then(
(value) => {
if (!controller.signal.aborted) setResults(value)
},
() => {
if (!controller.signal.aborted) setFailed(true)
},
)
}, 200)
return () => {
clearTimeout(timer)
controller.abort()
}
}, [query, cursor, retry, onSearch])

function selectOnKeyDown(event: KeyboardEvent<HTMLLIElement>) {
if (event.key !== " " && event.key !== "Enter") return

event.preventDefault()
event.stopPropagation()
event.currentTarget.click()
}

const choiceProps = { handler, type: "single" as const, onKeyDownCapture: selectOnKeyDown }

return (
<>
<li
role="presentation"
tabIndex={-1}
className="prototype-author-filter__search"
onFocus={(event) => {
if (event.target === event.currentTarget) input.current?.focus()
}}
>
<TextInput
ref={input}
fullWidth
type="search"
aria-label={copy.searchAuthors}
placeholder={copy.searchAuthors}
value={query}
maxLength={200}
onKeyDownCapture={(event) => {
if (event.key === "Enter" || event.key === " ") event.stopPropagation()
if (event.key === "ArrowDown") {
event.preventDefault()
event.stopPropagation()
event.currentTarget
.closest('[role="menu"]')
?.querySelector<HTMLElement>('[role="menuitemradio"]')
?.focus()
}
}}
onChange={(event) => {
setQuery(event.target.value)
setCursor(null)
setResults(null)
setFailed(false)
}}
/>
</li>

<ActionMenu.Item {...choiceProps} value="me" selected={listing.author === "me"}>
{copy.me}
</ActionMenu.Item>
<ActionMenu.Item {...choiceProps} value="" selected={!listing.author}>
{copy.allAuthors}
</ActionMenu.Item>

{failed ? (
<li role="presentation" className="prototype-author-filter__status">
<div role="alert">
<p>{copy.authorsFailed}</p>
<Button
size="small"
variant="subtle"
onClick={() => {
setFailed(false)
setRetry((value) => value + 1)
input.current?.focus()
}}
>
{copy.retry}
</Button>
</div>
</li>
) : !results || !results.authors.length ? (
<li role="presentation" className="prototype-author-filter__status">
<p role="status">{results ? copy.noAuthors : copy.loading}</p>
</li>
) : (
results.authors.map((author) => (
<ActionMenu.Item
{...choiceProps}
key={author.id}
value={author.id}
selected={listing.author === author.id}
>
@{author.login}
{author.name ? ` (${author.name})` : ""}
</ActionMenu.Item>
))
)}

{results?.nextCursor || cursor ? (
<li role="presentation" className="prototype-author-filter__paging">
{results?.nextCursor ? (
<Button
variant="subtle"
size="small"
onClick={() => {
setCursor(results.nextCursor)
setResults(null)
input.current?.focus()
}}
>
{copy.moreAuthors}
</Button>
) : null}
{cursor ? (
<Button
variant="subtle"
size="small"
onClick={() => {
setCursor(null)
setResults(null)
setFailed(false)
input.current?.focus()
}}
>
{copy.firstAuthors}
</Button>
) : null}
</li>
) : null}
</>
)
}
Loading
Loading