From 07159824779670b3867684d9a6589d9e811ddf82 Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 08:50:59 -0500 Subject: [PATCH 1/3] fix(web): apply GitHub's issue and PR search qualifiers, and page past the end The issue and PR search box silently matched nothing for qualifiers it did not know: milestone:, no:milestone, in:title, -label:, draft:, review-requested:, comments: and a quoted phrase all returned zero rows, and author: was dropped (QW-018, QW-020, QW-021, QW-062). The grammar now applies milestone: and no:milestone (with a Milestone filter beside Label), -label:, no:label, in:title/body, comments: ranges, draft:/is:draft and review-requested: on PRs, and matches an author name with no DPNS identity against a trusted mirror's imported login. Free text is matched in titles and bodies as on GitHub, with a quoted phrase as one term, and a mirrored body's provenance quote left out. Every other GitHub qualifier is reported under the box instead of being searched for as text. An out-of-range ?page= no longer shows 'Page 9 of 6' over the empty list's text: it says the page does not exist and offers the last one (QW-068). Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/components/repo/issues-content.tsx | 21 +- forge-web/components/repo/list-controls.tsx | 90 +++++- .../components/repo/pulls-content.test.tsx | 53 +++- forge-web/components/repo/pulls-content.tsx | 22 +- forge-web/components/repo/use-milestones.ts | 21 ++ forge-web/lib/design/contrast.test.ts | 10 +- forge-web/lib/repo/index.ts | 2 + forge-web/lib/repo/issue-index.ts | 119 ++++++-- forge-web/lib/repo/provenance.ts | 14 + forge-web/lib/repo/pull-index.ts | 26 +- forge-web/lib/repo/target-index.ts | 8 +- forge-web/lib/view/issue-query.test.ts | 151 +++++++++- forge-web/lib/view/issue-query.ts | 284 +++++++++++++++--- forge-web/lib/view/pull-query.test.ts | 17 +- forge-web/lib/view/pull-query.ts | 107 +++++-- 15 files changed, 830 insertions(+), 115 deletions(-) create mode 100644 forge-web/components/repo/use-milestones.ts diff --git a/forge-web/components/repo/issues-content.tsx b/forge-web/components/repo/issues-content.tsx index cbf397682..3f18434a3 100644 --- a/forge-web/components/repo/issues-content.tsx +++ b/forge-web/components/repo/issues-content.tsx @@ -2,8 +2,9 @@ /** * IssuesContent — the issue list (`platform-parity-spec.md` §1.2): Open / Closed tabs with exact - * counts, filters for label, author, assignee and "mentions me", sort, a search box with - * GitHub's qualifiers, pages of 50 past the first 100 issues, label chips and assignee avatars. + * counts, filters for label, milestone, author, assignee and "mentions me", sort, a search box + * with GitHub's qualifiers (`lib/view/issue-query`), pages of 50 past the first 100 issues, label + * chips and assignee avatars. * Everything the list shows is in the URL (D-913), so a reload or a shared link shows the same. * * Reads go through the issue index (`lib/repo/issue-index`): one composite for the first 100 @@ -30,6 +31,7 @@ import { issueQueryParams, parseIssueQuery, parseSearchText, + pastLastPage, searchSubmitBase, searchText, unresolvedQualifiers, @@ -37,7 +39,7 @@ import { utf8Length, type IssueListQuery, } from '@/lib/view/issue-query' -import { createIssue, issueFirsts, queryIssues, repoContractIds, repoKey, type IssueListPage, type IssueSelection } from '@/lib/repo' +import { createIssue, issueFirsts, queryIssues, repoContractIds, repoKey, rowFiltersOf, type IssueListPage, type IssueSelection } from '@/lib/repo' import { SupersededWriteError } from '@/lib/sdk' import { useWriteGuard } from '@/hooks/use-write-guard' import { useRepoWriteGeneration } from '@/hooks/use-repo-chrome' @@ -58,11 +60,14 @@ import { MirrorComposeHint, MirrorNote } from '@/components/repo/mirror-note' import { useRepoLinks } from '@/components/repo/target-href' import { AssigneeAvatars, MarkdownEditor } from '@/components/repo/issue-bits' import { + AuthorLoginNote, CommentCount, DroppedNote, LabelChipFilter, LabelFilter, + MilestoneFilter, Pager, + PastLastPage, PersonFilter, RowLink, SearchBox, @@ -75,6 +80,7 @@ import { } from '@/components/repo/list-controls' import { IssueTemplatePicker } from '@/components/repo/issue-templates' import { useRepoTotals } from '@/components/repo/use-repo-totals' +import { useMilestones } from '@/components/repo/use-milestones' import { BodyCounter, SealedLimit, composeCost, privateComposeBlock } from '@/components/repo/private-compose' import type { RepoAddress } from '@/hooks/use-query-param' import { repoHref } from '@/hooks/use-query-param' @@ -91,6 +97,7 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres const generation = useRepoWriteGeneration(home.repo) const trust = useMirrorTrust(home.repo) const totals = useRepoTotals(home.repo) + const milestones = useMilestones(home.repo) // A private repo's issues are sealed on write (`lib/repo/private-writes.ts`); only a member // holding the current key can open one, and non-members see no button (ux-dx-spec §9). const canCompose = privateComposeBlock(home) === null @@ -116,16 +123,18 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres text: query.q, page: query.page, pageSize: ISSUE_PAGE_SIZE, + ...rowFiltersOf(query, trust), } return queryIssues(sdk!, home.repo, selection, totals, network) }, - [ready, repoKey(home.repo), generation, JSON.stringify(query), identity ?? '', totals ?? -1], + [ready, repoKey(home.repo), generation, JSON.stringify(query), identity ?? '', totals ?? -1, query.authorLogin !== null && trust !== null ? [...trust].sort().join(',') : null], { enabled: ready && sdk !== null && (!needsViewer || identity !== null) }, ) const labelDefs = useMemo(() => new Map((data?.labels ?? []).map((l) => [l.name, l])), [data]) const empty = data !== null && data.rows.length === 0 const filtered = hasFilters(query) + const lastPage = empty ? pastLastPage(query.page, data?.matching ?? null, ISSUE_PAGE_SIZE) : null return (
@@ -138,6 +147,7 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres ) : null}
+ @@ -181,6 +191,7 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres
change({ labels })} /> + change(c)} /> ) : error ? (
+ ) : lastPage !== null ? ( + change({ page })} /> ) : empty ? ( pages return (
+ ) +} + +/** What a milestone filter offers: the repo's milestones (open first), or null while they are read. */ +export interface MilestoneChoice { + readonly title: string + readonly closed: boolean +} + +/** The milestone filter (QW-018): any, none, or one of the repo's milestones (open ones first). */ +export function MilestoneFilter({ + milestones, + value, + none, + onChange, +}: { + milestones: readonly MilestoneChoice[] | null + value: string | null + none: boolean + onChange: (c: { milestone: string | null; noMilestone: boolean }) => void +}): JSX.Element { + const known = milestones ?? [] + const open = known.filter((m) => !m.closed) + const closed = known.filter((m) => m.closed) + // A milestone named in the URL that the repo does not define (yet) stays selectable. + const extra = value !== null && !known.some((m) => m.title === value) ? [value] : [] + return ( + + + + + ) +} + +/** + * What `author:login` matched (QW-062): a name with no identity behind it is the login an + * import recorded, so the list shows the items a trusted mirror imported from that author. + */ +export function AuthorLoginNote({ login, notFound }: { login: string | null; notFound: readonly string[] }): JSX.Element | null { + if (login === null) return null + const noName = notFound.some((n) => n.toLowerCase() === login.toLowerCase()) + return ( +

+ author:{login} matches items mirrored from @{login} on the source forge{noName ? ` (no DPNS name ${login}.dash exists)` : ''}. +

+ ) +} + /** "Searched the newest N of M …": a search or comment sort that looked at part of the repo. */ export function SearchedNote({ searchedOf, noun }: { searchedOf: { readonly searched: number; readonly total: number | null } | null | undefined; noun: string }): JSX.Element | null { if (!searchedOf) return null diff --git a/forge-web/components/repo/pulls-content.test.tsx b/forge-web/components/repo/pulls-content.test.tsx index 603796b79..d0588e77d 100644 --- a/forge-web/components/repo/pulls-content.test.tsx +++ b/forge-web/components/repo/pulls-content.test.tsx @@ -232,10 +232,10 @@ describe('PullsContent (L-44)', () => { it('says which qualifiers it could not apply, and why', async () => { await render() - await submit('author:bobby mentions:@me fix') + await submit('author:bobby.dash mentions:@me fix') const note = el.querySelector('[data-testid="pull-search-dropped"]')?.textContent ?? '' - expect(note).toContain('author:bobby') - expect(note).toContain('bobby') + expect(note).toContain('author:bobby.dash') + expect(note).toContain('No DPNS name `bobby.dash` was found.') expect(note).toContain('mentions: is an Issues filter.') expect(replaced.at(-1)).toBe('/repo/pulls/?owner=o&name=n&q=fix') // Clear filters drops the note with the filters. @@ -245,6 +245,53 @@ describe('PullsContent (L-44)', () => { expect(el.querySelector('[data-testid="pull-search-dropped"]')).toBeNull() }) + it('matches a name DPNS does not know as a mirrored author login, and says so (QW-062)', async () => { + await render() + await submit('author:thephez fix') + expect(replaced.at(-1)).toBe('/repo/pulls/?owner=o&name=n&q=author%3Athephez+fix') + expect(el.querySelector('[data-testid="pull-search-dropped"]')).toBeNull() + search = 'owner=o&name=n&q=author%3Athephez+fix' + await render() + expect(asked.at(-1)).toMatchObject({ author: null, authorLogin: 'thephez', text: 'fix' }) + expect(el.querySelector('[data-testid="author-login-note"]')?.textContent).toContain('mirrored from @thephez') + }) + + it('reports review: and a bad draft: value instead of searching for them as text (QW-020)', async () => { + await render() + await submit('review:approved draft:maybe in:comments fix') + const note = el.querySelector('[data-testid="pull-search-dropped"]')?.textContent ?? '' + expect(note).toContain('review:approved') + expect(note).toContain('draft: takes true or false.') + expect(note).toContain('in: takes title or body') + expect(replaced.at(-1)).toBe('/repo/pulls/?owner=o&name=n&q=fix') + }) + + it('applies draft:, review-requested:@me, -label:, milestone: and comments: from the URL', async () => { + search = `owner=o&name=n&q=draft%3Afalse+review-requested%3A${ALICE}+-label%3Awontfix+milestone%3A%22v1+0%22+comments%3A%3E2` + await render() + expect(asked.at(-1)).toMatchObject({ draft: false, reviewRequested: ALICE, notLabels: ['wontfix'], milestone: 'v1 0', comments: { min: 3, max: Infinity } }) + expect((el.querySelector('#pull-search') as HTMLInputElement).value).toBe(`is:open -label:wontfix milestone:"v1 0" comments:>2 draft:false review-requested:${ALICE}`) + // `review-requested:@me` needs a viewer: signed out, nothing is read. + asked.length = 0 + search = 'owner=o&name=n&q=review-requested%3A%40me' + await render() + expect(asked).toEqual([]) + expect(el.textContent).toContain('Sign in to filter by your own pull requests') + }) + + it('says a page past the last one does not exist and offers the last page (QW-068)', async () => { + answer = { ...answer, rows: [], matching: 150, hasNext: false } + search = 'owner=o&name=n&state=merged&page=9' + await render() + const past = el.querySelector('[data-testid="page-past-end"]') + expect(past?.textContent).toContain('There is no page 9') + expect(past?.textContent).toContain('6 pages') + expect(el.textContent).not.toContain('Nothing has been merged yet') + expect(el.querySelector('[data-testid="page-indicator"]')?.textContent).toBe('Page 9') + act(() => button('Go to page 6').click()) + expect(replaced.at(-1)).toBe('/repo/pulls/?owner=o&name=n&state=merged&page=6') + }) + it('a tab change overtaking a slow name lookup stops the spinner, and the lookup is dropped', async () => { let finish!: () => void lookupGate = new Promise((r) => (finish = r)) diff --git a/forge-web/components/repo/pulls-content.tsx b/forge-web/components/repo/pulls-content.tsx index 409c54f0e..d3db31691 100644 --- a/forge-web/components/repo/pulls-content.tsx +++ b/forge-web/components/repo/pulls-content.tsx @@ -38,18 +38,23 @@ import { unresolvedPullQualifiers, type PullListQuery, } from '@/lib/view/pull-query' -import { queryPulls, repoContractIds, repoKey, type PullListPage, type PullRow, type PullSelection } from '@/lib/repo' +import { queryPulls, repoContractIds, repoKey, rowFiltersOf, type PullListPage, type PullRow, type PullSelection } from '@/lib/repo' +import { pastLastPage } from '@/lib/view/issue-query' import { useSdk } from '@/hooks/use-sdk' import { useAsync } from '@/hooks/use-async' import { useAuth } from '@/contexts/auth-context' import { useRepoWriteGeneration } from '@/hooks/use-repo-chrome' import { useRepoTotals } from '@/components/repo/use-repo-totals' +import { useMilestones } from '@/components/repo/use-milestones' import { + AuthorLoginNote, CommentCount, DroppedNote, LabelChipFilter, LabelFilter, + MilestoneFilter, Pager, + PastLastPage, PersonFilter, RowLink, SearchBox, @@ -90,13 +95,14 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress const generation = useRepoWriteGeneration(home.repo) const trust = useMirrorTrust(home.repo) const total = useRepoTotals(home.repo, 'pulls') + const milestones = useMilestones(home.repo) // The list query lives in the URL (a reload or a shared link shows the same list). const { query, search } = useListQuery({ addr, parse: parsePullQuery, toParams: pullQueryParams, grammar: PULL_GRAMMAR, sdk, ready, network }) const change = search.change // `me` needs a signed-in viewer; signed out, a `me` filter shows nothing rather than everything. - const needsViewer = query.author === 'me' || query.assignee === 'me' + const needsViewer = query.author === 'me' || query.assignee === 'me' || query.reviewRequested === 'me' const { data, loading, error, reload } = useAsync( () => { const who = (v: string | null): string | null => (v === 'me' ? identity ?? '' : v) @@ -109,10 +115,13 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress text: query.q, page: query.page, pageSize: PULL_PAGE_SIZE, + draft: query.draft, + reviewRequested: who(query.reviewRequested), + ...rowFiltersOf(query, trust), } return queryPulls(sdk!, home.repo, selection, total, network) }, - [ready, repoKey(home.repo), generation, JSON.stringify(query), identity ?? '', total ?? -1], + [ready, repoKey(home.repo), generation, JSON.stringify(query), identity ?? '', total ?? -1, query.authorLogin !== null && trust !== null ? [...trust].sort().join(',') : null], { enabled: ready && sdk !== null && (!needsViewer || identity !== null) }, ) @@ -122,6 +131,7 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress const heads = useMemo(() => (data?.rows ?? []).map((p) => p.headOid), [data]) const outcomes = useCheckOutcomes(home.repo, heads) const filtered = hasPullFilters(query) + const lastPage = data !== null && data.rows.length === 0 ? pastLastPage(query.page, data.matching, PULL_PAGE_SIZE) : null const counts = data?.counts const settled = counts?.merged != null && counts.closed != null ? counts.merged + counts.closed : null @@ -137,6 +147,7 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress + @@ -168,6 +179,7 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress
change({ labels })} /> + change(c)} /> change({ author })} /> change({ assignee })} /> change({ sort })} /> @@ -175,11 +187,13 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress
{needsViewer && identity === null ? ( -

Sign in to filter by your own pull requests and assignments.

+

Sign in to filter by your own pull requests, assignments and review requests.

) : loading && !data ? ( ) : error ? (
+ ) : lastPage !== null ? ( + change({ page })} /> ) : data !== null && data.rows.length === 0 ? ( { + const { sdk, ready, network } = useSdk(repoContractIds(repo)) + return useAsync( + () => sessionCached(`milestones:${network}:${repoKey(repo)}`, 60_000, () => readMilestones(sdk!, repo)), + [ready, repoKey(repo), network], + { enabled: ready && sdk !== null }, + ) +} diff --git a/forge-web/lib/design/contrast.test.ts b/forge-web/lib/design/contrast.test.ts index ae55cb75f..12f06cfdb 100644 --- a/forge-web/lib/design/contrast.test.ts +++ b/forge-web/lib/design/contrast.test.ts @@ -236,8 +236,12 @@ describe('no component renders text in the raw brand blue', () => { // non-text graphic, which WCAG 1.4.11 asks 3:1 of — the brand value meets that on every // dark surface. const ICON = /<[A-Z]\w*\s+className="[^"]*\btext-dash(?![-\w/])[^"]*"\s+aria-hidden\s*\/>/g - // Class strings that are applied only to an icon wrapper, checked by hand. - const ICON_ONLY = new Set(['components/repo/pulls-content.tsx:81']) + // Class strings that are applied only to an icon wrapper, checked by hand: the file and the + // line's code (not its number, which any edit above it moves). + const ICON_ONLY: readonly { file: string; code: string }[] = [ + { file: 'components/repo/pulls-content.tsx', code: `label: 'Merged', icon: , klass: 'text-dash' }` }, + ] + const iconOnly = (where: string, text: string): boolean => ICON_ONLY.some((o) => where.startsWith(o.file + ':') && text.includes(o.code)) it('uses raw dash blue only on icons', () => { const offenders = ['app', 'components'] @@ -246,7 +250,7 @@ describe('no component renders text in the raw brand blue', () => { readFileSync(file, 'utf8') .split('\n') .map((text, i) => ({ where: `${file.slice(root.length + 1)}:${i + 1}`, text })) - .filter(({ where, text }) => RAW.test(text.replace(ICON, '')) && !ICON_ONLY.has(where)), + .filter(({ where, text }) => RAW.test(text.replace(ICON, '')) && !iconOnly(where, text)), ) .map(({ where }) => where) expect(offenders).toEqual([]) diff --git a/forge-web/lib/repo/index.ts b/forge-web/lib/repo/index.ts index efac719d8..75c5237ae 100644 --- a/forge-web/lib/repo/index.ts +++ b/forge-web/lib/repo/index.ts @@ -168,10 +168,12 @@ export { matchesText, mentions, queryIssues, + rowFiltersOf, rowMatches, type IssueListPage, type IssueRow, type IssueSelection, + type RowFilters, } from './issue-index' export { queryPulls, diff --git a/forge-web/lib/repo/issue-index.ts b/forge-web/lib/repo/issue-index.ts index d5c483099..7a64f7614 100644 --- a/forge-web/lib/repo/issue-index.ts +++ b/forge-web/lib/repo/issue-index.ts @@ -29,7 +29,9 @@ import type { RepoRef } from './contract' import { issueViewOf, type IssueView } from './issues' import { ISSUE_CLOSE } from '../rules/transition' import type { LabelDef } from './labels' -import { pinnedTargets } from '../rules/parity' +import { foldThreadMetaV2, pinnedTargets } from '../rules/parity' +import { searchableBody, trustedOrigin } from './provenance' +import { commentRange, searchTerms, type CountRange, type ExtraFilters, type TextScope } from '../view/issue-query' import type { HiddenCounts } from './private-content' import { authorCandidates, @@ -46,18 +48,24 @@ import { type ListIndex, } from './target-index' -/** An issue row: the folded issue and its comment count (null: not counted). */ +/** An issue row: the folded issue, its comment count (null: not counted) and its milestone. */ export interface IssueRow extends IssueView { readonly comments: number | null + /** The milestone title its member events leave it in (`foldThreadMetaV2`), or null. */ + readonly milestone?: string | null } type IssueIndex = ListIndex /** * The index, loading it on first use (one per repo and network, until a write drops it). An - * issue's view: its state code (the chunk's proved sum) and its labels and assignees from the feed. + * issue's view: its state code (the chunk's proved sum), its labels and assignees, and its + * milestone from the feed. */ -const indexOf = indexCache('issue', async (_sdk, _index, doc, log, code) => issueViewOf(doc, log, code)) +const indexOf = indexCache('issue', async (_sdk, _index, doc, log, code) => ({ + ...issueViewOf(doc, log, code), + milestone: foldThreadMetaV2(log.events).milestone, +})) function sortRowsNewest(a: IssueRow, b: IssueRow): number { return b.createdAt - a.createdAt || (a.id < b.id ? 1 : -1) @@ -67,8 +75,41 @@ function sortRowsNewest(a: IssueRow, b: IssueRow): number { // Queries // --------------------------------------------------------------------------- +/** + * The filters the Issues and Pull requests lists share beyond labels, author and assignee (the + * search box's `ExtraFilters`, resolved: `comments` as a range). Each is optional: absent, it + * does not narrow. + */ +export interface RowFilters { + readonly notLabels?: readonly string[] + readonly noLabel?: boolean + readonly milestone?: string | null + readonly noMilestone?: boolean + /** A source forge's login: an item whose trusted import recorded it as the author. */ + readonly authorLogin?: string | null + /** Who may mirror (`useMirrorTrust`): only their items' recorded author matches `authorLogin`. */ + readonly mirrorTrust?: ReadonlySet | null + /** Where `text` is looked for (default: titles and bodies). */ + readonly scope?: TextScope + readonly comments?: CountRange | null +} + +/** A list query's {@link ExtraFilters} as the {@link RowFilters} a selection carries. */ +export function rowFiltersOf(q: ExtraFilters, mirrorTrust: ReadonlySet | null): RowFilters { + return { + notLabels: q.notLabels, + noLabel: q.noLabel, + milestone: q.milestone, + noMilestone: q.noMilestone, + authorLogin: q.authorLogin, + mirrorTrust, + scope: q.scope, + comments: commentRange(q.comments), + } +} + /** What the list asks for (resolved: `me` is replaced by the viewer's id by the caller). */ -export interface IssueSelection { +export interface IssueSelection extends RowFilters { readonly state: 'open' | 'closed' | 'all' readonly labels: readonly string[] /** An identity id, or null. */ @@ -83,6 +124,23 @@ export interface IssueSelection { readonly pageSize: number } +/** Whether a selection narrows the list beyond its state tab. */ +export function selectionFiltered(q: Omit & { readonly mentions?: IssueSelection['mentions'] }): boolean { + return ( + q.labels.length > 0 || + q.author !== null || + q.assignee !== null || + (q.mentions ?? null) !== null || + q.text.trim() !== '' || + (q.notLabels?.length ?? 0) > 0 || + q.noLabel === true || + (q.milestone ?? null) !== null || + q.noMilestone === true || + (q.authorLogin ?? null) !== null || + (q.comments ?? null) !== null + ) +} + /** The answer for one list page. */ export interface IssueListPage { readonly rows: readonly IssueRow[] @@ -116,14 +174,27 @@ function stateMatches(row: IssueRow, state: IssueSelection['state']): boolean { return state === 'all' || (state === 'open' ? row.state.open : !row.state.open) } +/** What {@link rowMatches} reads of a row: an issue row, or a PR row with its milestone passed in. */ +export type MatchRow = Pick & { + readonly state: { readonly labels: readonly string[]; readonly assignees: readonly string[] } +} + /** Whether a row passes every filter but the state tab. */ -export function rowMatches(row: IssueRow, q: IssueSelection): boolean { - if (q.labels.some((l) => !row.state.labels.includes(l))) return false +export function rowMatches(row: MatchRow, q: Omit): boolean { + const labels = row.state.labels + if (q.labels.some((l) => !labels.includes(l))) return false + if (q.notLabels?.some((l) => labels.includes(l))) return false + if (q.noLabel && labels.length > 0) return false + const milestone = row.milestone ?? null + if (q.milestone != null && milestone !== q.milestone) return false + if (q.noMilestone && milestone !== null) return false if (q.author !== null && row.author !== q.author) return false + if (q.authorLogin != null && trustedOrigin(row.origin, row.author, q.mirrorTrust ?? null)?.author.toLowerCase() !== q.authorLogin.toLowerCase()) return false if (q.assignee === 'none' && row.state.assignees.length > 0) return false if (q.assignee !== null && q.assignee !== 'none' && !row.state.assignees.includes(q.assignee)) return false + if (q.comments != null && (row.comments === null || row.comments < q.comments.min || row.comments > q.comments.max)) return false if (q.mentions !== null && !mentions(row.body, q.mentions.id, q.mentions.name)) return false - return matchesText(q.text, row) + return matchesText(q.text, row, q.scope) } /** @@ -141,23 +212,29 @@ export function mentions(body: string | undefined, id: string, name: string | nu } /** - * Whether `row`'s title holds every word of `text`, case-insensitively; a word that is all - * digits (with or without a leading `#`) also matches the issue number directly (L-43: a title - * substring check alone missed a bare `7512`, even though `#7512` matched by number — a word - * checks both, so neither form of the same search regresses the other). + * Whether `row` holds every term of `text` ({@link searchTerms}: a word, or a `"quoted phrase"` + * as a whole, QW-021), case-insensitively, in its title or body (GitHub's default; `scope` + * `title` / `body` is `in:`). A mirrored body's provenance quote is not searched: it names the + * source repo and author on every row. A word that is all digits (with or without a leading + * `#`) also matches the issue number directly (L-43: a title substring check alone missed a bare + * `7512`, even though `#7512` matched by number — a word checks both, so neither form of the + * same search regresses the other). */ -export function matchesText(text: string, row: { readonly title: string; readonly number: number }): boolean { - const words = text.trim().toLowerCase().split(/\s+/).filter((w) => w !== '') - const title = row.title.toLowerCase() - return words.every((w) => { - // `#n` (review L-43) is a number-only match: it never falls back to a title substring, even +export function matchesText(text: string, row: { readonly title: string; readonly number: number; readonly body?: string }, scope: TextScope = 'any'): boolean { + const terms = searchTerms(text) + if (terms.length === 0) return true + const fields: string[] = [] + if (scope !== 'body') fields.push(row.title.toLowerCase()) + if (scope !== 'title' && row.body) fields.push(searchableBody(row.body).toLowerCase()) + return terms.every((w) => { + // `#n` (review L-43) is a number-only match: it never falls back to a text substring, even // when the digits happen to appear in the title of a different-numbered row. const hash = /^#(\d+)$/.exec(w) if (hash) return Number(hash[1]) === row.number - // A bare number matches the number OR (additively) a title substring. + // A bare number matches the number OR (additively) a text substring. const bare = /^(\d+)$/.exec(w) if (bare && Number(bare[1]) === row.number) return true - return title.includes(w) + return fields.some((f) => f.includes(w)) }) } @@ -196,7 +273,7 @@ export async function queryIssues( network: Network = DEFAULT_NETWORK, ): Promise { const index = await indexOf(sdk, repo, network) - const filtered = q.labels.length > 0 || q.author !== null || q.assignee !== null || q.mentions !== null || q.text.trim() !== '' + const filtered = selectionFiltered(q) const matches = (r: IssueRow): boolean => stateMatches(r, q.state) && rowMatches(r, q) const selected = await selectRows(sdk, index, { candidates: await candidatesFor(sdk, index, q), @@ -205,7 +282,7 @@ export async function queryIssues( direction: q.sort === 'oldest' ? 'asc' : 'desc', want: q.page * q.pageSize, walkAll: q.sort === 'comments', - partial: q.text.trim() !== '' || q.mentions !== null || q.sort === 'comments', + partial: filtered || q.sort === 'comments', }) // Tab counts under the current filters: exact when the whole candidate set is known. diff --git a/forge-web/lib/repo/provenance.ts b/forge-web/lib/repo/provenance.ts index 00679a16a..03fbd940b 100644 --- a/forge-web/lib/repo/provenance.ts +++ b/forge-web/lib/repo/provenance.ts @@ -81,6 +81,20 @@ export function pullOriginOf(body: string): PullOrigin | null { return { baseOid: m[1] ?? '', headLabel: m[2] ?? '' } } +/** + * `body` without the provenance quote an import opens it with (the `> Mirrored from …` line and + * the quote lines right after it, such as a PR's `> Base … · head …`): what a text search looks + * in, since that quote names the source repo and author on every mirrored row. + */ +export function searchableBody(body: string): string { + if (!body.startsWith('> Mirrored from ')) return body + const lines = body.split('\n') + if (!PROVENANCE.test(lines[0] ?? '')) return body + let i = 1 + while (i < lines.length && (lines[i] ?? '').startsWith('>')) i++ + return lines.slice(i).join('\n') +} + /** A review's verdict at the source, from its provenance line (`(review, approved, 2026-…)`). */ export type ImportedVerdict = 'approved' | 'requested changes' | 'commented' diff --git a/forge-web/lib/repo/pull-index.ts b/forge-web/lib/repo/pull-index.ts index a765bf76f..f8a877d0f 100644 --- a/forge-web/lib/repo/pull-index.ts +++ b/forge-web/lib/repo/pull-index.ts @@ -31,7 +31,7 @@ import type { EvoSDK } from '@dashevo/evo-sdk' import { DEFAULT_NETWORK, type Network } from '../constants' import { IncompleteReadError } from '../sdk' import type { RepoRef } from './contract' -import { compareRows, rowMatches } from './issue-index' +import { compareRows, rowMatches, selectionFiltered, type RowFilters } from './issue-index' import { baseRefReaders, incompletePullView, readPull, type BaseRefReaders, type PullView } from './issues' import { PR_CLOSE, PR_DRAFT_CLOSE, PR_MERGE } from '../rules/transition' import type { LabelDef } from './labels' @@ -94,7 +94,7 @@ const indexOf = indexCache('patch', async (sdk, index, doc, log, code) // --------------------------------------------------------------------------- /** What the list asks for (`me` already replaced by the viewer's id). */ -export interface PullSelection { +export interface PullSelection extends RowFilters { readonly state: PullStateFilter readonly labels: readonly string[] /** An identity id, or null. */ @@ -105,6 +105,10 @@ export interface PullSelection { readonly text: string readonly page: number readonly pageSize: number + /** `draft:true` / `draft:false` (`is:draft`): only drafts, or none; null either. */ + readonly draft?: boolean | null + /** `review-requested:x`: an identity with a standing review request. */ + readonly reviewRequested?: string | null } /** Open / Merged / Closed counts (null: not proven). */ @@ -141,9 +145,19 @@ function pullStateMatches(row: Pick, tab: PullStateFilter): b return row.state.open } -/** Whether a row passes every filter but the state tab (labels, author, assignee, title / `#n`): the issue list's rule. */ +/** + * Whether a row passes every filter but the state tab: the issue list's rule (labels, author, + * assignee, milestone, comments, text / `#n`), plus the PR-only draft and review-request filters. + */ function filtersMatch(row: PullRow, q: PullSelection): boolean { - return rowMatches(row, { ...q, state: 'all', mentions: null }) + if (q.draft != null && row.state.draft !== q.draft) return false + if (q.reviewRequested != null && !row.review.requestedReviewers.some((r) => r.identity === q.reviewRequested)) return false + return rowMatches({ ...row, milestone: row.review.milestone }, { ...q, mentions: null }) +} + +/** Whether a selection narrows the list beyond its state tab. */ +function pullFiltered(q: PullSelection): boolean { + return selectionFiltered(q) || q.draft != null || q.reviewRequested != null } /** Open / Merged / Closed of `rows`. */ @@ -200,7 +214,7 @@ export async function queryPulls( network: Network = DEFAULT_NETWORK, ): Promise { const index = await indexOf(sdk, repo, network) - const filtered = q.labels.length > 0 || q.author !== null || q.assignee !== null || q.text.trim() !== '' + const filtered = pullFiltered(q) const selected = await selectRows(sdk, index, { candidates: await candidatesFor(sdk, index, q), matches: (r) => pullStateMatches(r, q.state) && filtersMatch(r, q), @@ -208,7 +222,7 @@ export async function queryPulls( direction: q.sort === 'oldest' ? 'asc' : 'desc', want: q.page * q.pageSize, walkAll: q.sort === 'comments', - partial: q.text.trim() !== '' || q.sort === 'comments', + partial: filtered || q.sort === 'comments', }) let counts = NO_COUNTS diff --git a/forge-web/lib/repo/target-index.ts b/forge-web/lib/repo/target-index.ts index 4917ce50d..5980cbdfa 100644 --- a/forge-web/lib/repo/target-index.ts +++ b/forge-web/lib/repo/target-index.ts @@ -376,17 +376,18 @@ export function transitionTargets(sdk: EvoSDK, index: Lis } /** - * Feed targets whose member events can pass the label and assignee filters, or null when neither + * Feed targets whose member events can pass the label, assignee and milestone filters, or null when none * applies. A loaded row is checked exactly (`loaded`); one not loaded yet is admitted on its * events and filtered once resolved. */ export function metaCandidates( index: ListIndex, - q: { readonly labels: readonly string[]; readonly assignee: string | null }, + q: { readonly labels: readonly string[]; readonly assignee: string | null; readonly milestone?: string | null }, loaded: (row: Row) => boolean, ): Set | null { const assignee = q.assignee !== null && q.assignee !== 'none' ? q.assignee : null - if ((q.labels.length === 0 && assignee === null) || index.feed === null) return null + const milestone = q.milestone ?? null + if ((q.labels.length === 0 && assignee === null && milestone === null) || index.feed === null) return null const out = new Set() for (const [id, log] of index.feed) { if (id === '' || index.notRows.has(id)) continue @@ -397,6 +398,7 @@ export function metaCandidates( } if (q.labels.length > 0 && !log.events.some((e) => e.kind === 'labelAdd')) continue if (assignee !== null && !log.events.some((e) => e.kind === 'assign' && e.value === assignee)) continue + if (milestone !== null && !log.events.some((e) => e.kind === 'milestoneSet' && e.value === milestone)) continue out.add(id) } return out diff --git a/forge-web/lib/view/issue-query.test.ts b/forge-web/lib/view/issue-query.test.ts index 1ee666094..d444feec3 100644 --- a/forge-web/lib/view/issue-query.test.ts +++ b/forge-web/lib/view/issue-query.test.ts @@ -5,10 +5,13 @@ import { dpnsAuthorCandidates, droppedQualifiersReason, emptyIssuesBody, + commentRange, hasFilters, issueQueryParams, parseIssueQuery, parseSearchText, + pastLastPage, + searchTerms, resolveSearchNames, searchSubmitBase, searchText, @@ -16,7 +19,7 @@ import { withQuery, withResolvedNames, } from './issue-query' -import { matchesText } from '../repo/issue-index' +import { matchesText, rowMatches, rowFiltersOf } from '../repo/issue-index' const ID = 'HwhCv9N5BHsbGNLzDR4tnZnqJ6VxtwJSLsM4aUWn2Tnr' const params = (s: string) => new URLSearchParams(s) @@ -29,7 +32,7 @@ describe('issue list URL state', () => { it('round-trips every filter through the URL', () => { const q = parseIssueQuery(params(`state=closed&label=bug&label=good%20first&author=${ID}&assignee=me&mentions=me&sort=comments&q=crash&page=3`)) - expect(q).toEqual({ state: 'closed', labels: ['bug', 'good first'], author: ID, assignee: 'me', mentions: true, sort: 'comments', q: 'crash', page: 3 }) + expect(q).toEqual({ ...DEFAULT_ISSUE_QUERY, state: 'closed', labels: ['bug', 'good first'], author: ID, assignee: 'me', mentions: true, sort: 'comments', q: 'crash', page: 3 }) const back = new URLSearchParams(issueQueryParams(q)) expect(parseIssueQuery(back)).toEqual(q) expect(back.toString()).toBe(`state=closed&label=bug&label=good+first&author=${ID}&assignee=me&mentions=me&sort=comments&q=crash&page=3`) @@ -52,7 +55,7 @@ describe('issue list URL state', () => { // An unknown qualifier stays free text. expect(parseIssueQuery(params('q=foo%3Abar')).q).toBe('foo:bar') // A URL param is never cleared by a qualifier that does not resolve. - expect(parseIssueQuery(params(`author=${ID}&q=author%3Aalice`))).toMatchObject({ author: ID, q: '' }) + expect(parseIssueQuery(params(`author=${ID}&q=author%3Aalice.dash`))).toMatchObject({ author: ID, q: '' }) }) it('dedupes repeated labels', () => { @@ -87,16 +90,16 @@ describe('search-box qualifiers', () => { }) it('keeps unknown keys as free text, and drops (and reports) known ones it cannot resolve', () => { - const q = parseSearchText('author:alice is:merged foo:bar hello') + const q = parseSearchText('author:alice.dash is:merged foo:bar hello') expect(q.author).toBeNull() expect(q.state).toBe('open') expect(q.q).toBe('foo:bar hello') - expect(unresolvedQualifiers('author:alice is:merged foo:bar hello')).toEqual(['author:alice', 'is:merged']) + expect(unresolvedQualifiers('author:alice.dash is:merged foo:bar hello')).toEqual(['author:alice.dash', 'is:merged']) }) it('never overrides a filter with an unresolvable qualifier', () => { const base = { ...DEFAULT_ISSUE_QUERY, author: ID, assignee: 'me', mentions: true, sort: 'comments' as const } - const q = parseSearchText('author:alice assignee:bob mentions:you sort:random', base) + const q = parseSearchText('author:alice.dash assignee:bob mentions:you sort:random', base) expect(q).toMatchObject({ author: ID, assignee: 'me', mentions: true, sort: 'comments', q: '' }) }) @@ -128,6 +131,47 @@ describe('search-box qualifiers', () => { }) }) + it('reads -label:, no:label, milestone:, no:milestone, in: and comments: (QW-018, QW-020)', () => { + const q = parseSearchText('-label:wontfix -label:"needs info" no:label milestone:"v1 0" no:milestone in:title comments:>2 crash') + expect(q).toMatchObject({ notLabels: ['wontfix', 'needs info'], noLabel: true, milestone: 'v1 0', noMilestone: true, scope: 'title', comments: '>2', q: 'crash' }) + expect(parseSearchText('in:body').scope).toBe('body') + expect(parseSearchText('in:title,body').scope).toBe('any') + expect(unresolvedQualifiers('-label:wontfix milestone:v1 in:title comments:1..3')).toEqual([]) + }) + + it('reports the GitHub qualifiers it does not apply rather than searching for them (QW-020)', () => { + const text = 'in:comments comments:lots review:approved review-requested:@me draft:true created:>2024-01-01 -author:bob foo:bar' + expect(unresolvedQualifiers(text)).toEqual(['in:comments', 'comments:lots', 'review:approved', 'review-requested:@me', 'draft:true', 'created:>2024-01-01', '-author:bob']) + // An unknown key is not a GitHub qualifier: it stays free text. + expect(parseSearchText(text).q).toBe('foo:bar') + const reason = droppedQualifiersReason(unresolvedQualifiers(text)) + expect(reason).toContain('in: takes title or body') + expect(reason).toContain('comments: takes a count') + expect(reason).toContain('review: is not a list filter') + expect(reason).toContain('are pull request filters') + expect(reason).toContain('created: is not a filter here.') + expect(reason).toContain('Only -label: can be negated here.') + }) + + it('takes an author name with no identity behind it as a mirrored login (QW-062)', () => { + expect(parseSearchText('author:thephez')).toMatchObject({ author: null, authorLogin: 'thephez', q: '' }) + expect(parseSearchText('author:@thephez')).toMatchObject({ authorLogin: 'thephez' }) + // An id (or a DPNS name rewritten to one) replaces the login, and the reverse. + expect(parseSearchText(`author:thephez author:${ID}`)).toMatchObject({ author: ID, authorLogin: null }) + expect(parseSearchText('author:thephez', { ...DEFAULT_ISSUE_QUERY, author: ID })).toMatchObject({ author: null, authorLogin: 'thephez' }) + // A DPNS-shaped name is never a login: said as not applied. + expect(unresolvedQualifiers('author:alice.dash')).toEqual(['author:alice.dash']) + }) + + it('carries the extra qualifiers in ?q= and reads them back (a reload keeps them)', () => { + const q = { ...DEFAULT_ISSUE_QUERY, notLabels: ['wontfix'], milestone: 'v1 0', authorLogin: 'thephez', scope: 'body' as const, comments: '1..3', q: 'crash' } + const url = new URLSearchParams(issueQueryParams(q)) + expect(url.get('q')).toBe('-label:wontfix milestone:"v1 0" author:thephez in:body comments:1..3 crash') + expect(parseIssueQuery(url)).toEqual(q) + expect(hasFilters({ ...DEFAULT_ISSUE_QUERY, noMilestone: true })).toBe(true) + expect(hasFilters({ ...DEFAULT_ISSUE_QUERY, scope: 'title' })).toBe(false) + }) + it('writes the query back as text that parses to the same query', () => { const q = { ...DEFAULT_ISSUE_QUERY, state: 'all' as const, labels: ['bug', 'two words'], assignee: 'none', sort: 'oldest' as const, q: 'crash' } const text = searchText(q) @@ -136,8 +180,103 @@ describe('search-box qualifiers', () => { }) }) +describe('rowMatches with the extra filters', () => { + const MIRROR = 'MirrorIdentity1111111111111111111111111111' + const base = { labels: [], author: null, assignee: null, mentions: null, text: '' } + const row = { + title: 'Update DIP-2 table', + number: 119, + body: 'The table is out of date.', + author: MIRROR, + origin: { author: 'thephez', createdAt: 0, url: 'https://github.com/dashpay/dips/issues/119', host: 'github.com' }, + comments: 3, + milestone: 'v1.0', + state: { labels: ['bug'], assignees: [] }, + } + const filters = (q: Partial, trust: ReadonlySet | null = new Set([MIRROR])) => + ({ ...base, ...rowFiltersOf({ ...DEFAULT_ISSUE_QUERY, ...q }, trust) }) + + it('filters by milestone and no:milestone (QW-018)', () => { + expect(rowMatches(row, filters({ milestone: 'v1.0' }))).toBe(true) + expect(rowMatches(row, filters({ milestone: 'v2.0' }))).toBe(false) + expect(rowMatches(row, filters({ noMilestone: true }))).toBe(false) + expect(rowMatches({ ...row, milestone: null }, filters({ noMilestone: true }))).toBe(true) + }) + + it('filters by -label: and no:label', () => { + expect(rowMatches(row, filters({ notLabels: ['bug'] }))).toBe(false) + expect(rowMatches(row, filters({ notLabels: ['wontfix'] }))).toBe(true) + expect(rowMatches(row, filters({ noLabel: true }))).toBe(false) + expect(rowMatches({ ...row, state: { labels: [], assignees: [] } }, filters({ noLabel: true }))).toBe(true) + }) + + it('filters by comment count, never counting an uncounted row', () => { + expect(rowMatches(row, filters({ comments: '>2' }))).toBe(true) + expect(rowMatches(row, filters({ comments: '>3' }))).toBe(false) + expect(rowMatches({ ...row, comments: null }, filters({ comments: '>=0' }))).toBe(false) + }) + + it("matches a mirrored author's login only on a trusted mirror's items (QW-062)", () => { + expect(rowMatches(row, filters({ authorLogin: 'THEPHEZ' }))).toBe(true) + expect(rowMatches(row, filters({ authorLogin: 'coolaj86' }))).toBe(false) + // Anyone can write an `imported` author into their own issue: an untrusted signer's never matches. + expect(rowMatches(row, filters({ authorLogin: 'thephez' }, new Set()))).toBe(false) + expect(rowMatches(row, filters({ authorLogin: 'thephez' }, null))).toBe(false) + }) + + it('scopes free text with in:', () => { + expect(rowMatches(row, { ...filters({ scope: 'title' }), text: 'out' })).toBe(false) + expect(rowMatches(row, { ...filters({}), text: 'out' })).toBe(true) + }) +}) + +describe('comment-count ranges (QW-020)', () => { + it("reads GitHub's comments: forms", () => { + expect(commentRange('3')).toEqual({ min: 3, max: 3 }) + expect(commentRange('>2')).toEqual({ min: 3, max: Infinity }) + expect(commentRange('>=2')).toEqual({ min: 2, max: Infinity }) + expect(commentRange('<2')).toEqual({ min: 0, max: 1 }) + expect(commentRange('<=2')).toEqual({ min: 0, max: 2 }) + expect(commentRange('1..3')).toEqual({ min: 1, max: 3 }) + expect(commentRange('2..*')).toEqual({ min: 2, max: Infinity }) + expect(commentRange('*..2')).toEqual({ min: 0, max: 2 }) + for (const bad of ['', '<0', '3..1', '*..*', 'lots', '>', '-1']) expect(commentRange(bad)).toBeNull() + }) +}) + +describe('pastLastPage (QW-068)', () => { + it('names the last page only when the page lies past it', () => { + expect(pastLastPage(9, 140, 25)).toBe(6) + expect(pastLastPage(6, 140, 25)).toBeNull() + expect(pastLastPage(2, 0, 25)).toBe(1) + expect(pastLastPage(9, null, 25)).toBeNull() + expect(pastLastPage(1, 0, 25)).toBeNull() + }) +}) + describe('free-text match', () => { const row = { title: 'Crash when the Config is empty', number: 12 } + it('matches a quoted phrase as a whole, without its quotes (QW-021)', () => { + const dip = { title: 'DIP-15: DashPay', number: 3 } + expect(matchesText('"DIP-15"', dip)).toBe(true) + expect(matchesText('DIP-15', dip)).toBe(true) + expect(matchesText('"the config"', row)).toBe(true) + expect(matchesText('"config the"', row)).toBe(false) + expect(searchTerms('"DIP-15" crash "two words"')).toEqual(['dip-15', 'crash', 'two words']) + }) + it('looks in titles and bodies by default, and in one of them with in: (QW-020)', () => { + const r = { title: 'Crash on start', number: 4, body: 'The HMAC check fails.' } + expect(matchesText('hmac', r)).toBe(true) + expect(matchesText('hmac', r, 'title')).toBe(false) + expect(matchesText('hmac', r, 'body')).toBe(true) + expect(matchesText('crash', r, 'body')).toBe(false) + }) + it("never matches a mirrored body's provenance quote", () => { + const r = { title: 'Update DIP-2', number: 5, body: '> Mirrored from github.com/dashpay/dips#119 by @thephez (issue, 2022-01-01)\n>\n\nThe table is out of date.' } + expect(matchesText('dashpay', r)).toBe(false) + expect(matchesText('thephez', r)).toBe(false) + expect(matchesText('table', r)).toBe(true) + }) it('needs every word, ignoring case', () => { expect(matchesText('crash config', row)).toBe(true) expect(matchesText('crash network', row)).toBe(false) diff --git a/forge-web/lib/view/issue-query.ts b/forge-web/lib/view/issue-query.ts index 25628887b..38aba79b7 100644 --- a/forge-web/lib/view/issue-query.ts +++ b/forge-web/lib/view/issue-query.ts @@ -9,12 +9,18 @@ * assignee= * mentions=me * sort=newest|oldest|comments (default newest) - * q= (matches titles; `#12` matches the number) + * q= (free text, matched in titles and bodies; `#12` matches the + * number and `"a phrase"` matches as a whole. It also carries the + * qualifiers that have no parameter of their own, as GitHub's + * `?q=` does: `-label:`, `no:label`, `milestone:`, + * `no:milestone`, a mirrored `author:` login, `in:`, `comments:`) * page= (1-based, default 1) * - * The search box also takes GitHub's qualifiers (`is:closed label:bug author:@me - * assignee:@me no:assignee mentions:@me sort:comments-desc`), which {@link parseSearchText} - * lifts into the structured query; what is left is the free text. + * The search box also takes GitHub's qualifiers (`is:closed label:bug -label:wontfix + * author:@me assignee:@me no:assignee no:label milestone:"v1.0" no:milestone mentions:@me + * in:title comments:>2 sort:comments-desc`), which {@link parseSearchText} lifts into the + * structured query; what is left is the free text. A qualifier the list cannot apply is reported + * under the box ({@link unresolvedQualifiers}), never searched for as text (QW-020). */ import { displayDpnsName, looksLikeDpnsName } from './dpns' @@ -23,9 +29,35 @@ import { isIdentityId } from '../utils' export type IssueStateFilter = 'open' | 'closed' | 'all' export type IssueSort = 'newest' | 'oldest' | 'comments' +/** Where free text is looked for (`in:`): titles and bodies (GitHub's default), or one of them. */ +export type TextScope = 'any' | 'title' | 'body' + +/** + * The qualifiers with no URL parameter of their own (they travel in `q` as text, as on GitHub), + * shared by the Issues and Pull requests lists. + */ +export interface ExtraFilters { + /** `-label:x`: none of these may be on the row. */ + readonly notLabels: readonly string[] + /** `no:label`: the row has no label. */ + readonly noLabel: boolean + /** `milestone:"v1.0"`: the row's milestone title. */ + readonly milestone: string | null + /** `no:milestone`. */ + readonly noMilestone: boolean + /** + * `author:login` for a name that is not an identity: the source forge's login an import + * recorded (a mirror's `@thephez`), matched only on items a trusted mirror signed (QW-062). + */ + readonly authorLogin: string | null + /** `in:title` / `in:body`. */ + readonly scope: TextScope + /** `comments:>2` and the like, as typed (a value {@link commentRange} reads). */ + readonly comments: string | null +} /** The structured list query. `author` / `assignee` hold an identity id, `me`, or (assignee) `none`. */ -export interface IssueListQuery { +export interface IssueListQuery extends ExtraFilters { readonly state: IssueStateFilter readonly labels: readonly string[] readonly author: string | null @@ -36,6 +68,16 @@ export interface IssueListQuery { readonly page: number } +export const NO_EXTRA_FILTERS: ExtraFilters = { + notLabels: [], + noLabel: false, + milestone: null, + noMilestone: false, + authorLogin: null, + scope: 'any', + comments: null, +} + export const DEFAULT_ISSUE_QUERY: IssueListQuery = { state: 'open', labels: [], @@ -45,6 +87,7 @@ export const DEFAULT_ISSUE_QUERY: IssueListQuery = { sort: 'newest', q: '', page: 1, + ...NO_EXTRA_FILTERS, } /** Rows per displayed page. */ @@ -54,6 +97,10 @@ const STATES: readonly IssueStateFilter[] = ['open', 'closed', 'all'] const SORTS: readonly IssueSort[] = ['newest', 'oldest', 'comments'] /** A label is 1-30 characters (the `label.name` schema); a longer value cannot match one. */ const LABEL_MAX = 30 +/** A milestone title is 1-63 characters (the `milestone.title` schema). */ +const MILESTONE_MAX = 63 +/** A source forge's login (GitHub's shape: letters, digits and inner hyphens, at most 39). */ +const LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/ /** The bytes an issue, PR or comment `body` may hold (the contract's `maxBytes`). */ export const BODY_MAX = 5120 @@ -79,6 +126,7 @@ export function parseIssueQuery(params: { get(name: string): string | null; getA const page = Number.parseInt(params.get('page') ?? '', 10) const labels = [...new Set(params.getAll('label').map((l) => l.trim()).filter((l) => l !== '' && [...l].length <= LABEL_MAX))] const parsed: IssueListQuery = { + ...NO_EXTRA_FILTERS, state: STATES.includes(state as IssueStateFilter) ? (state as IssueStateFilter) : 'open', labels, author: identityParam(params.get('author'), ['me']), @@ -89,7 +137,8 @@ export function parseIssueQuery(params: { get(name: string): string | null; getA page: Number.isInteger(page) && page >= 1 && page <= 10_000 ? page : 1, } // A GitHub link carries its qualifiers inside `q` (`/issues?q=is:closed+label:bug`): lift - // them out. The app writes only free text to `q`, so this leaves its own URLs as they are. + // them out. The app writes to `q` only free text and the qualifiers with no parameter of + // their own ({@link extraQualifiers}), which read back to the same query. return parsed.q.includes(':') ? { ...parseSearchText(parsed.q, parsed), page: parsed.page } : parsed } @@ -102,7 +151,8 @@ export function issueQueryParams(q: IssueListQuery): [string, string][] { if (q.assignee) out.push(['assignee', q.assignee]) if (q.mentions) out.push(['mentions', 'me']) if (q.sort !== 'newest') out.push(['sort', q.sort]) - if (q.q.trim() !== '') out.push(['q', q.q.trim()]) + const text = [...extraQualifiers(q), q.q.trim()].filter((t) => t !== '').join(' ') + if (text !== '') out.push(['q', text]) if (q.page > 1) out.push(['page', String(q.page)]) return out } @@ -130,7 +180,66 @@ export function searchSubmitBase(q: IssueListQuery): IssueListQuery { /** Whether any filter narrows the list beyond the state tab. */ export function hasFilters(q: IssueListQuery): boolean { - return q.labels.length > 0 || q.author !== null || q.assignee !== null || q.mentions || q.q.trim() !== '' + return q.labels.length > 0 || q.author !== null || q.assignee !== null || q.mentions || q.q.trim() !== '' || hasExtraFilters(q) +} + +/** Whether any {@link ExtraFilters} narrows the list (`in:` alone does not: it only scopes free text). */ +export function hasExtraFilters(q: ExtraFilters): boolean { + return q.notLabels.length > 0 || q.noLabel || q.milestone !== null || q.noMilestone || q.authorLogin !== null || q.comments !== null +} + +/** The {@link ExtraFilters} as search-box qualifiers (what `q` carries for them in the URL). */ +export function extraQualifiers(q: ExtraFilters): string[] { + const parts: string[] = [] + for (const l of q.notLabels) parts.push(`-label:${quoted(l)}`) + if (q.noLabel) parts.push('no:label') + if (q.milestone !== null) parts.push(`milestone:${quoted(q.milestone)}`) + if (q.noMilestone) parts.push('no:milestone') + if (q.authorLogin !== null) parts.push(`author:${q.authorLogin}`) + if (q.scope !== 'any') parts.push(`in:${q.scope}`) + if (q.comments !== null) parts.push(`comments:${q.comments}`) + return parts +} + +/** A qualifier value, quoted when it holds whitespace. */ +function quoted(v: string): string { + return /\s/.test(v) ? `"${v}"` : v +} + +/** An inclusive comment-count range, from a `comments:` value. */ +export interface CountRange { + readonly min: number + readonly max: number +} + +/** + * The range a `comments:` value names (GitHub's forms: `5`, `>2`, `>=2`, `<5`, `<=5`, `1..3`, + * `2..*`, `*..3`), or null for anything else. + */ +export function commentRange(v: string | null): CountRange | null { + if (v === null) return null + const int = (s: string): number => Number.parseInt(s, 10) + const single = /^(>=|<=|>|<)?(\d{1,9})$/.exec(v) + if (single) { + const k = int(single[2] ?? '0') + switch (single[1]) { + case '>': + return { min: k + 1, max: Infinity } + case '>=': + return { min: k, max: Infinity } + case '<': + return k === 0 ? null : { min: 0, max: k - 1 } + case '<=': + return { min: 0, max: k } + default: + return { min: k, max: k } + } + } + const range = /^(\d{1,9}|\*)\.\.(\d{1,9}|\*)$/.exec(v) + if (!range || (range[1] === '*' && range[2] === '*')) return null + const min = range[1] === '*' ? 0 : int(range[1] ?? '0') + const max = range[2] === '*' ? Infinity : int(range[2] ?? '0') + return min <= max ? { min, max } : null } /** @@ -146,6 +255,16 @@ export function emptyIssuesBody(filtered: boolean, state: IssueStateFilter, clos return `No issue is open right now; ${plural(closedCount, 'issue')} ${closedCount === 1 ? 'is' : 'are'} closed.` } +/** + * The last page of a list with `matching` rows, when `page` lies past it (a hand-edited or stale + * `?page=`, QW-068); null when the page is in range or the total is not known. + */ +export function pastLastPage(page: number, matching: number | null, pageSize: number): number | null { + if (matching === null || page <= 1) return null + const last = Math.max(1, Math.ceil(matching / pageSize)) + return page > last ? last : null +} + /** Split `text` into tokens, keeping `"quoted phrases"` (and `label:"two words"`) whole. */ function tokens(text: string): string[] { const out: string[] = [] @@ -156,18 +275,40 @@ function tokens(text: string): string[] { const unquote = (s: string): string => s.replace(/"/g, '') -/** A qualifier this parser knows: a known key whose value is (or is not) one it can use. */ -const KNOWN_KEYS = new Set(['is', 'state', 'label', 'author', 'assignee', 'no', 'mentions', 'sort']) +/** + * The qualifiers this parser applies (the rest of GitHub's are known by name below and + * reported, never searched for as text). `-label` is the one negation it applies. + */ +const APPLIED_KEYS = new Set(['is', 'state', 'label', '-label', 'author', 'assignee', 'no', 'mentions', 'sort', 'milestone', 'in', 'comments']) + +/** + * GitHub's issue and PR search qualifiers this list does not apply (QW-020): a token with one of + * these keys (or any negated `-key:`) is reported as not applied rather than kept as free text, + * which could never match and read as "nothing matches". + */ +const OTHER_GITHUB_KEYS = new Set([ + 'archived', 'base', 'closed', 'commenter', 'created', 'draft', 'head', 'interactions', 'involves', 'language', 'linked', 'merged', + 'org', 'project', 'reactions', 'reason', 'repo', 'review', 'review-requested', 'reviewed-by', 'status', 'team', + 'team-review-requested', 'type', 'updated', 'user', 'user-review-requested', +]) + +/** Whether `key` (lowercased, a leading `-` kept) is a qualifier: applied, or one of GitHub's that is reported. */ +function isQualifierKey(key: string): boolean { + if (APPLIED_KEYS.has(key) || OTHER_GITHUB_KEYS.has(key)) return true + return key.startsWith('-') && (APPLIED_KEYS.has(key.slice(1)) || OTHER_GITHUB_KEYS.has(key.slice(1))) +} /** * Lift GitHub-style qualifiers out of search-box text into `base` (the rest of the query is - * kept): `is:open|closed`, `state:…`, `label:x` (repeatable, quotes for spaces), `author:x`, - * `assignee:x`, `no:assignee`, `mentions:@me`, `sort:created-desc|created-asc|comments-desc`. - * `@me` means the viewer. A qualifier with a known key overrides `base` only when its value - * resolves; one that does not (`author:` and `assignee:` only take an identity id, `@me`, or a - * value already rewritten to an id by {@link withResolvedNames} — a DPNS name this function is - * handed as-is does not resolve here) is dropped from the free text and reported by - * {@link unresolvedQualifiers}. An unknown key stays free text. + * kept): `is:open|closed`, `state:…`, `label:x` (repeatable, quotes for spaces), `-label:x`, + * `author:x`, `assignee:x`, `no:assignee|label|milestone`, `milestone:x`, `mentions:@me`, + * `in:title|body`, `comments:>n`, `sort:created-desc|created-asc|comments-desc`. `@me` means + * the viewer. A qualifier with a known key overrides `base` only when its value resolves; one + * that does not (`author:` and `assignee:` take an identity id, `@me`, or a value already + * rewritten to an id by {@link withResolvedNames}; `author:` also takes a source forge's login, + * matched against mirrored items; a DPNS name this function is handed as-is does not resolve + * here) is dropped from the free text and reported by {@link unresolvedQualifiers}, as is any + * other GitHub qualifier. An unknown key stays free text. */ export function parseSearchText(text: string, base: IssueListQuery = DEFAULT_ISSUE_QUERY): IssueListQuery { return liftQualifiers(text, base).query @@ -238,25 +379,47 @@ export async function resolveSearchNames( return { text: resolved.size > 0 ? withResolvedNames(text, resolved) : text, notFound } } -/** An `author:`/`assignee:` token's lowercased key and its value (quotes and a leading `@` stripped); null for any other token. */ +/** The qualifiers whose value names a person (an id, `@me`, or a DPNS name to look up first). */ +const PERSON_KEYS: ReadonlySet = new Set(['author', 'assignee', 'review-requested']) + +/** A person qualifier's lowercased key and its value (quotes and a leading `@` stripped); null for any other token. */ function personQualifier(tok: string): { key: string; value: string } | null { const at = tok.indexOf(':') if (at <= 0) return null const key = tok.slice(0, at).toLowerCase() - if (key !== 'author' && key !== 'assignee') return null + if (!PERSON_KEYS.has(key)) return null return { key, value: unquote(tok.slice(at + 1)).replace(/^@/, '') } } +/** A person qualifier's value as an identity: an id, or `me` (either case, `@` or not); null otherwise. */ +export function personValue(v: string): string | null { + return identityParam(v.replace(/^@/, ''), ['me']) +} + /** Why a known qualifier's value could not be used, by key (see {@link droppedQualifiersReason}). */ const QUALIFIER_REASON: Readonly> = { is: 'is: and state: take open, closed, all or issue.', state: 'is: and state: take open, closed, all or issue.', - author: 'Authors and assignees take an identity id, a DPNS name, or @me.', - assignee: 'Authors and assignees take an identity id, a DPNS name, or @me.', + author: 'Authors and assignees take an identity id, a DPNS name, or @me (an author also a mirrored login).', + assignee: 'Authors and assignees take an identity id, a DPNS name, or @me (an author also a mirrored login).', label: `A label is 1-${LABEL_MAX} characters.`, - no: 'no: only takes assignee.', + '-label': `A label is 1-${LABEL_MAX} characters.`, + no: 'no: takes label, milestone or assignee.', mentions: 'mentions: only takes @me.', sort: 'sort: takes created-desc, created-asc or comments-desc.', + milestone: `milestone: takes a milestone title (1-${MILESTONE_MAX} characters; quote one with spaces).`, + in: 'in: takes title or body (comment text is not searched from the list).', + comments: 'comments: takes a count: 3, >2, >=2, <5, <=5 or 1..3.', + review: "review: is not a list filter: a PR's reviews are read on its page.", + 'reviewed-by': "reviewed-by: is not a list filter: a PR's reviews are read on its page.", + 'review-requested': 'review-requested: and draft: are pull request filters.', + draft: 'review-requested: and draft: are pull request filters.', +} + +/** The key of a qualifier token, lowercased, a leading `-` kept (`''` for a token that is not one). */ +function keyOf(tok: string): string { + const at = tok.indexOf(':') + return at > 0 ? tok.slice(0, at).toLowerCase() : '' } /** @@ -267,11 +430,13 @@ const QUALIFIER_REASON: Readonly> = { * a valid value. An `author:`/`assignee:` value in `notFound` (a {@link resolveSearchNames} * candidate DPNS actually looked up and could not find) names the specific name that was not * found, rather than the generic "take an id, a name, or @me" reason, which would wrongly - * suggest the value's shape (not its non-existence) was the problem. + * suggest the value's shape (not its non-existence) was the problem. A GitHub qualifier the list + * does not apply at all says so by name. */ export function droppedQualifiersReason(dropped: readonly string[], notFound: readonly string[] = []): string { const notFoundLower = new Set(notFound.map((n) => n.toLowerCase())) const reasons = new Set() + const unsupported = new Set() for (const tok of dropped) { if (/^(is|state):pr$/i.test(tok)) { reasons.add('is:pr is not a filter here — open the Pull requests tab to search pull requests.') @@ -282,28 +447,30 @@ export function droppedQualifiersReason(dropped: readonly string[], notFound: re reasons.add(`No DPNS name \`${displayDpnsName(person.value)}\` was found.`) continue } - const key = tok.slice(0, tok.indexOf(':')).toLowerCase() + const key = keyOf(tok) const reason = QUALIFIER_REASON[key] if (reason) reasons.add(reason) + else if (key.startsWith('-')) reasons.add('Only -label: can be negated here.') + else unsupported.add(`${key}:`) } + if (unsupported.size > 0) reasons.add(`${[...unsupported].join(', ')} ${unsupported.size === 1 ? 'is not a filter' : 'are not filters'} here.`) return [...reasons].join(' ') } function liftQualifiers(text: string, base: IssueListQuery): { query: IssueListQuery; unresolved: string[] } { let state = base.state const labels = [...base.labels] - let author = base.author - let assignee = base.assignee - let mentions = base.mentions - let sort = base.sort + const notLabels = [...base.notLabels] + let { author, assignee, mentions, sort, noLabel, milestone, noMilestone, authorLogin, scope, comments } = base const free: string[] = [] const unresolved: string[] = [] // identityParam already matches 'me'/'none' case-insensitively, so stripping a leading `@` // (never mind its case) is all this needs — `@me`, `@ME`, `me` and `ME` all land on 'me'. const who = (v: string, extra: readonly string[] = []): string | null => identityParam(v.replace(/^@/, ''), ['me', ...extra]) + const labelOk = (v: string): boolean => v !== '' && [...v].length <= LABEL_MAX for (const tok of tokens(text)) { const at = tok.indexOf(':') - const key = at > 0 ? tok.slice(0, at).toLowerCase() : '' + const key = keyOf(tok) const value = at > 0 ? unquote(tok.slice(at + 1)) : '' let used = true switch (key) { @@ -313,14 +480,27 @@ function liftQualifiers(text: string, base: IssueListQuery): { query: IssueListQ else if (value !== 'issue') used = false break case 'label': - if (value !== '' && [...value].length <= LABEL_MAX) { + if (labelOk(value)) { if (!labels.includes(value)) labels.push(value) } else used = false break + case '-label': + if (labelOk(value)) { + if (!notLabels.includes(value)) notLabels.push(value) + } else used = false + break case 'author': { const id = who(value) - if (id !== null) author = id - else used = false + const login = value.replace(/^@/, '') + if (id !== null) { + author = id + authorLogin = null + } else if (LOGIN.test(login)) { + // Not an identity (a DPNS name DPNS knows was rewritten to its id before this): the + // login an import recorded, as the mirror shows it (`@thephez on github.com`). + authorLogin = login + author = null + } else used = false break } case 'assignee': { @@ -331,12 +511,29 @@ function liftQualifiers(text: string, base: IssueListQuery): { query: IssueListQ } case 'no': if (value === 'assignee') assignee = 'none' + else if (value === 'label') noLabel = true + else if (value === 'milestone') noMilestone = true + else used = false + break + case 'milestone': + if (value !== '' && [...value].length <= MILESTONE_MAX) milestone = value else used = false break case 'mentions': if (value === '@me' || value === 'me') mentions = true else used = false break + case 'in': { + // `in:title,body` is both (the default), as on GitHub. + const parts = new Set(value.toLowerCase().split(',')) + if ([...parts].some((p) => p !== 'title' && p !== 'body')) used = false + else scope = parts.size === 2 ? 'any' : parts.has('title') ? 'title' : 'body' + break + } + case 'comments': + if (commentRange(value) !== null) comments = value + else used = false + break case 'sort': if (value === 'created-desc') sort = 'newest' else if (value === 'created-asc') sort = 'oldest' @@ -347,22 +544,39 @@ function liftQualifiers(text: string, base: IssueListQuery): { query: IssueListQ used = false } if (used) continue - if (KNOWN_KEYS.has(key)) unresolved.push(tok) + if (isQualifierKey(key)) unresolved.push(tok) else free.push(tok) } - return { query: { ...base, state, labels, author, assignee, mentions, sort, q: free.join(' '), page: 1 }, unresolved } + return { + query: { ...base, state, labels, notLabels, author, assignee, mentions, sort, noLabel, milestone, noMilestone, authorLogin, scope, comments, q: free.join(' '), page: 1 }, + unresolved, + } } /** The query as search-box text, qualifiers first (the inverse of {@link parseSearchText}). */ export function searchText(q: IssueListQuery): string { const parts: string[] = [`is:${q.state}`] - for (const l of q.labels) parts.push(/\s/.test(l) ? `label:"${l}"` : `label:${l}`) + for (const l of q.labels) parts.push(`label:${quoted(l)}`) if (q.author) parts.push(`author:${q.author === 'me' ? '@me' : q.author}`) if (q.assignee === 'none') parts.push('no:assignee') else if (q.assignee) parts.push(`assignee:${q.assignee === 'me' ? '@me' : q.assignee}`) if (q.mentions) parts.push('mentions:@me') + parts.push(...extraQualifiers(q)) if (q.sort === 'oldest') parts.push('sort:created-asc') if (q.sort === 'comments') parts.push('sort:comments-desc') if (q.q.trim() !== '') parts.push(q.q.trim()) return parts.join(' ') } + +/** + * The free text's search terms (QW-021): a `"quoted phrase"` is one term, spaces and all, and + * any other word is one term; lowercased, quotes never part of a term. + */ +export function searchTerms(text: string): string[] { + const out: string[] = [] + for (const m of text.toLowerCase().matchAll(/"([^"]*)"|(\S+)/g)) { + const term = (m[1] ?? m[2] ?? '').replace(/"/g, '').trim() + if (term !== '') out.push(term) + } + return out +} diff --git a/forge-web/lib/view/pull-query.test.ts b/forge-web/lib/view/pull-query.test.ts index ebbd74c8d..7ab79e209 100644 --- a/forge-web/lib/view/pull-query.test.ts +++ b/forge-web/lib/view/pull-query.test.ts @@ -41,14 +41,27 @@ describe('PR list query (L-44)', () => { // Values are exact: `is:MERGED` is not a state, and is said as not applied, with the PR states. expect(parsePullSearch('is:MERGED').state).toBe('open') expect(unresolvedPullQualifiers('is:MERGED')).toEqual(['is:MERGED']) - expect(pullDroppedReason(['is:MERGED'])).toBe('is: and state: take open, closed, merged or all.') + expect(pullDroppedReason(['is:MERGED'])).toBe('is: and state: take open, closed, merged, draft or all.') }) it('reports what it cannot apply: a DPNS author, and mentions (an Issues filter)', () => { - expect(unresolvedPullQualifiers('author:alice mentions:@me')).toEqual(['author:alice', 'mentions:@me']) + expect(unresolvedPullQualifiers('author:alice.dash mentions:@me')).toEqual(['author:alice.dash', 'mentions:@me']) expect(parsePullSearch('mentions:@me fix').q).toBe('fix') }) + it('reads draft:, is:draft and review-requested:, and round-trips them through the URL (QW-020)', () => { + expect(parsePullSearch('is:draft').draft).toBe(true) + expect(parsePullSearch('draft:false').draft).toBe(false) + expect(parsePullSearch('review-requested:@me').reviewRequested).toBe('me') + expect(parsePullSearch(`review-requested:${ID} fix`)).toMatchObject({ reviewRequested: ID, q: 'fix' }) + expect(unresolvedPullQualifiers('draft:maybe review-requested:bob.dash review:approved')).toEqual(['review:approved', 'draft:maybe', 'review-requested:bob.dash']) + expect(pullDroppedReason(['draft:maybe', 'review-requested:bob.dash'], ['bob.dash'])).toBe('draft: takes true or false. No DPNS name `bob.dash` was found.') + const q = { ...DEFAULT_PULL_QUERY, draft: true, reviewRequested: ID, milestone: 'v1', q: 'fix' } + const back = parsePullQuery(new URLSearchParams(pullQueryParams(q))) + expect(back).toEqual(q) + expect(pullSearchText(q)).toBe(`is:open milestone:v1 draft:true review-requested:${ID} fix`) + }) + it('writes the query back as search text, the state first', () => { expect(pullSearchText({ ...DEFAULT_PULL_QUERY, state: 'merged', labels: ['bug'] })).toBe('is:merged label:bug') expect(parsePullSearch(pullSearchText({ ...DEFAULT_PULL_QUERY, state: 'closed', q: 'x' }))).toMatchObject({ state: 'closed', q: 'x' }) diff --git a/forge-web/lib/view/pull-query.ts b/forge-web/lib/view/pull-query.ts index 71e4062b7..b63231d16 100644 --- a/forge-web/lib/view/pull-query.ts +++ b/forge-web/lib/view/pull-query.ts @@ -5,10 +5,13 @@ * * URL parameters (all optional; a default is never written): * state=open|merged|closed|all (default open; closed = closed without merging) - * label, author, assignee, sort, q, page — as on the Issues list + * label, author, assignee, sort, q, page — as on the Issues list; `q` also carries the PR-only + * `draft:` and `review-requested:` qualifiers * - * The search box takes the same qualifiers as the Issues list, plus `is:merged` (and `is:pr`, - * which every PR matches). `mentions:` is not a PR filter here, and is reported as not applied. + * The search box takes the same qualifiers as the Issues list, plus `is:merged`, `is:draft`, + * `draft:true|false` and `review-requested:` (and `is:pr`, which every PR matches). + * `mentions:` is not a PR filter here, and is reported as not applied, as is `review:` (a PR's + * reviews are read on its page, not by the list). */ import type { PullStateFilter } from '../repo' @@ -19,14 +22,22 @@ import { issueQueryParams, parseIssueQuery, parseSearchText, + personValue, searchText, unresolvedQualifiers, type IssueListQuery, } from './issue-query' +import { displayDpnsName } from './dpns' import { plural } from './format' /** The structured PR list query. */ -export type PullListQuery = Omit & { readonly state: PullStateFilter } +export type PullListQuery = Omit & { + readonly state: PullStateFilter + /** `draft:true` / `is:draft` (only drafts), `draft:false` (none), or null. */ + readonly draft: boolean | null + /** `review-requested:`: an identity id or `me`, or null. */ + readonly reviewRequested: string | null +} export const DEFAULT_PULL_QUERY: PullListQuery = toPull(DEFAULT_ISSUE_QUERY, 'open') @@ -40,69 +51,112 @@ export function pullSubmitBase(q: PullListQuery): PullListQuery { const STATES: readonly PullStateFilter[] = ['open', 'merged', 'closed', 'all'] -function toPull(q: IssueListQuery, state: PullStateFilter): PullListQuery { +function toPull(q: IssueListQuery, state: PullStateFilter, pr: Pick = { draft: null, reviewRequested: null }): PullListQuery { const { mentions: _mentions, state: _state, ...rest } = q - return { ...rest, state } + return { ...rest, state, ...pr } } function toIssue(q: PullListQuery): IssueListQuery { - return { ...q, state: 'open', mentions: false } + const { draft: _draft, reviewRequested: _rr, ...rest } = q + return { ...rest, state: 'open', mentions: false } +} + +/** The PR-only filters as qualifiers (what `q` carries for them in the URL). */ +function pullQualifiers(q: Pick): string[] { + const parts: string[] = [] + if (q.draft !== null) parts.push(`draft:${q.draft}`) + if (q.reviewRequested !== null) parts.push(`review-requested:${q.reviewRequested === 'me' ? '@me' : q.reviewRequested}`) + return parts } -/** `is:merged` / `is:pr` (or `state:`), which the Issues grammar does not have: the key in any case, the value exact. */ -const PR_STATE_TOKEN = /(^|\s)(?:[iI][sS]|[sS][tT][aA][tT][eE]):(merged|pr)(?=\s|$)/g +/** `is:merged` / `is:pr` / `is:draft` (or `state:`), which the Issues grammar does not have: the key in any case, the value exact. */ +const PR_STATE_TOKEN = /(^|\s)(?:[iI][sS]|[sS][tT][aA][tT][eE]):(merged|pr|draft)(?=\s|$)/g /** Whether `text` sets a state the Issues grammar knows (its key in any case, its value exactly, as it parses them). */ function setsIssueState(text: string): boolean { return [...text.matchAll(/(?:^|\s)(?:is|state):(\S+)/gi)].some((m) => m[1] === 'open' || m[1] === 'closed' || m[1] === 'all') } /** `mentions:` — an Issues filter, not a PR one. */ const MENTIONS_TOKEN = /(^|\s)(mentions:\S*)/gi +/** `draft:` and `review-requested:`, the PR-only qualifiers with a value. */ +const PR_VALUE_TOKEN = /(^|\s)((draft|review-requested):(\S*))/gi + +interface PullOnly { + readonly rest: string + readonly merged: boolean + readonly draft: boolean | null + readonly reviewRequested: string | null + /** PR-only tokens whose value could not be used, and `mentions:` (an Issues filter). */ + readonly unresolved: readonly string[] +} /** Lift the PR-only qualifiers out of `text`; what is left is Issues grammar. */ -function liftPullOnly(text: string): { rest: string; merged: boolean; mentions: string[] } { +function liftPullOnly(text: string): PullOnly { let merged = false - const mentions: string[] = [] + let draft: boolean | null = null + let reviewRequested: string | null = null + const unresolved: string[] = [] const rest = text .replace(PR_STATE_TOKEN, (_m, lead: string, value: string) => { if (value === 'merged') merged = true + if (value === 'draft') draft = true return lead }) .replace(MENTIONS_TOKEN, (_m, lead: string, token: string) => { - mentions.push(token) + unresolved.push(token) + return lead + }) + .replace(PR_VALUE_TOKEN, (_m, lead: string, token: string, key: string, raw: string) => { + const value = raw.replace(/"/g, '') + if (key.toLowerCase() === 'draft') { + if (value === 'true' || value === 'false') draft = value === 'true' + else unresolved.push(token) + } else { + const who = personValue(value) + if (who !== null) reviewRequested = who + else unresolved.push(token) + } return lead }) .replace(/\s+/g, ' ') .trim() - return { rest, merged, mentions } + return { rest, merged, draft, reviewRequested, unresolved } } /** Lift the search box's qualifiers into `base` (the inverse of {@link pullSearchText}). */ export function parsePullSearch(text: string, base: PullListQuery = DEFAULT_PULL_QUERY): PullListQuery { - const { rest, merged } = liftPullOnly(text) - const parsed = parseSearchText(rest, toIssue(base)) + const only = liftPullOnly(text) + const parsed = parseSearchText(only.rest, toIssue(base)) let state: PullStateFilter = base.state - if (merged) state = 'merged' - else if (setsIssueState(rest)) state = parsed.state - return toPull(parsed, state) + if (only.merged) state = 'merged' + else if (setsIssueState(only.rest)) state = parsed.state + return toPull(parsed, state, { draft: only.draft ?? base.draft, reviewRequested: only.reviewRequested ?? base.reviewRequested }) } /** The qualifiers in `text` that could not be used (for a note under the box). */ export function unresolvedPullQualifiers(text: string): string[] { - const { rest, mentions } = liftPullOnly(text) - return [...unresolvedQualifiers(rest), ...mentions] + const only = liftPullOnly(text) + return [...unresolvedQualifiers(only.rest), ...only.unresolved] } /** * Why each qualifier in `dropped` was not applied, for the note under the box: the Issues list's - * reasons, with the PR states for `is:` / `state:`, and `mentions:` named as an Issues filter. + * reasons, with the PR states for `is:` / `state:`, `mentions:` named as an Issues filter, and + * the PR-only qualifiers' own values. */ export function pullDroppedReason(dropped: readonly string[], notFound: readonly string[] = []): string { const isState = (t: string): boolean => /^(is|state):/i.test(t) const isMentions = (t: string): boolean => /^mentions:/i.test(t) + const isDraft = (t: string): boolean => /^draft:/i.test(t) + const isRequested = (t: string): boolean => /^review-requested:/i.test(t) + const lost = new Set(notFound.map((n) => n.toLowerCase())) + const requested = dropped.filter(isRequested).map((t) => t.slice(t.indexOf(':') + 1).replace(/"/g, '').replace(/^@/, '')) return [ - droppedQualifiersReason(dropped.filter((t) => !isState(t) && !isMentions(t)), notFound), - dropped.some(isState) ? 'is: and state: take open, closed, merged or all.' : '', + droppedQualifiersReason(dropped.filter((t) => !isState(t) && !isMentions(t) && !isDraft(t) && !isRequested(t)), notFound), + dropped.some(isState) ? 'is: and state: take open, closed, merged, draft or all.' : '', dropped.some(isMentions) ? 'mentions: is an Issues filter.' : '', + dropped.some(isDraft) ? 'draft: takes true or false.' : '', + ...requested.filter((v) => lost.has(v.toLowerCase())).map((v) => `No DPNS name \`${displayDpnsName(v)}\` was found.`), + requested.some((v) => !lost.has(v.toLowerCase())) ? 'review-requested: takes an identity id, a DPNS name, or @me.' : '', ] .filter((r) => r !== '') .join(' ') @@ -121,18 +175,19 @@ export function parsePullQuery(params: { get(name: string): string | null; getAl /** The URL params of a query, defaults omitted, in a stable order. */ export function pullQueryParams(q: PullListQuery): [string, string][] { - const rest = issueQueryParams(toIssue(q)) + const rest = issueQueryParams(toIssue({ ...q, q: [...pullQualifiers(q), q.q.trim()].filter((t) => t !== '').join(' ') })) return q.state === 'open' ? rest : [['state', q.state], ...rest] } /** The query as search-box text, qualifiers first. */ export function pullSearchText(q: PullListQuery): string { - return searchText(toIssue(q)).replace(/^is:open/, `is:${q.state}`) + const text = searchText(toIssue({ ...q, q: '' })).replace(/^is:open/, `is:${q.state}`) + return [text, ...pullQualifiers(q), q.q.trim()].filter((t) => t !== '').join(' ') } /** Whether any filter narrows the list beyond the state tab. */ export function hasPullFilters(q: PullListQuery): boolean { - return hasFilters(toIssue(q)) + return hasFilters(toIssue(q)) || q.draft !== null || q.reviewRequested !== null } /** The empty PR list's line: never "open the first one" while some are merged or closed. */ From 2210688a4a2ee3c350844307d00b7b2e1e1bb82b Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 09:01:11 -0500 Subject: [PATCH 2/3] fix(web): address review of the issue and PR search qualifiers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - author: matches only rows a trusted mirror signed, so the list now waits for the mirror trust set instead of walking every chunk to an empty "No issues match" first. - Picking an Author in the dropdown clears a mirrored-login author:, which otherwise stayed on and ANDed with the new author to match nothing. - ?q= now carries the qualifiers with no parameter of their own, so its 200-character cap cut real filter URLs mid-qualifier (-label:wontf…); the cap is a shared 512 (Q_MAX) in the parsers and the linked-q lookup. - A GitHub key with no value ("status: broken", "type: error") stays free text instead of being dropped from the search as an unsupported qualifier. - draft: takes TRUE/False in any case, as GitHub does. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/components/repo/issues-content.tsx | 9 ++++++--- forge-web/components/repo/list-controls.tsx | 4 ++-- .../components/repo/pulls-content.test.tsx | 11 ++++++++++- forge-web/components/repo/pulls-content.tsx | 8 +++++--- forge-web/lib/view/issue-query.test.ts | 17 +++++++++++++++++ forge-web/lib/view/issue-query.ts | 14 ++++++++++++-- forge-web/lib/view/pull-query.test.ts | 1 + forge-web/lib/view/pull-query.ts | 6 ++++-- 8 files changed, 57 insertions(+), 13 deletions(-) diff --git a/forge-web/components/repo/issues-content.tsx b/forge-web/components/repo/issues-content.tsx index 3f18434a3..716e4c399 100644 --- a/forge-web/components/repo/issues-content.tsx +++ b/forge-web/components/repo/issues-content.tsx @@ -109,6 +109,9 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres // `me` needs a signed-in viewer; signed out, a `me` filter shows nothing rather than everything. const needsViewer = query.author === 'me' || query.assignee === 'me' || query.mentions + // `author:` matches only what a trusted mirror signed: until the trust set is read, every + // row would fail it (an empty list, after walking every chunk), so the read waits for it. + const awaitingTrust = query.authorLogin !== null && trust === null const { data, loading, error, reload } = useAsync( async () => { const me = identity ?? '' @@ -128,7 +131,7 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres return queryIssues(sdk!, home.repo, selection, totals, network) }, [ready, repoKey(home.repo), generation, JSON.stringify(query), identity ?? '', totals ?? -1, query.authorLogin !== null && trust !== null ? [...trust].sort().join(',') : null], - { enabled: ready && sdk !== null && (!needsViewer || identity !== null) }, + { enabled: ready && sdk !== null && (!needsViewer || identity !== null) && !awaitingTrust }, ) const labelDefs = useMemo(() => new Map((data?.labels ?? []).map((l) => [l.name, l])), [data]) @@ -196,7 +199,7 @@ export function IssuesContent({ home, addr }: { home: RepoHome; addr: RepoAddres label="Author" value={query.author} signedIn={identity !== null} - onChange={(author) => change({ author })} + onChange={(author) => change({ author, authorLogin: null })} /> Sign in to filter by your own issues, assignments and mentions.

- ) : loading && !data ? ( + ) : (loading || awaitingTrust) && !data ? ( ) : error ? (
diff --git a/forge-web/components/repo/list-controls.tsx b/forge-web/components/repo/list-controls.tsx index 9b0870b8d..615d47158 100644 --- a/forge-web/components/repo/list-controls.tsx +++ b/forge-web/components/repo/list-controls.tsx @@ -15,7 +15,7 @@ import type { EvoSDK } from '@dashevo/evo-sdk' import type { Network } from '@/lib/constants' import type { LabelDef } from '@/lib/repo' import { plural, resolveDpnsId } from '@/lib/view' -import { dpnsAuthorCandidates, resolveSearchNames, withQuery } from '@/lib/view/issue-query' +import { dpnsAuthorCandidates, Q_MAX, resolveSearchNames, withQuery } from '@/lib/view/issue-query' import type { RepoAddress } from '@/hooks/use-query-param' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' @@ -90,7 +90,7 @@ export function useListQuery({ router.replace(`${pathname}?${q.toString()}`, { scroll: false }) } // The linked `?q=`, capped as the query parsers cap it (a crafted link cannot force unbounded DPNS reads). - const linkedQ = params.get('q')?.slice(0, 200) ?? null + const linkedQ = params.get('q')?.slice(0, Q_MAX) ?? null const [search, setSearch] = useState(null) const [dropped, setDropped] = useState(() => grammar.unresolved(linkedQ ?? '')) diff --git a/forge-web/components/repo/pulls-content.test.tsx b/forge-web/components/repo/pulls-content.test.tsx index d0588e77d..3ec43ab96 100644 --- a/forge-web/components/repo/pulls-content.test.tsx +++ b/forge-web/components/repo/pulls-content.test.tsx @@ -24,7 +24,9 @@ vi.mock('next/navigation', () => ({ })) vi.mock('@/hooks/use-sdk', () => ({ useSdk: () => ({ sdk: {}, ready: true, network: 'devnet', status: { phase: 'ready' } }) })) vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ identity: null }) })) -vi.mock('@/hooks/use-mirror-trust', () => ({ useMirrorTrust: () => null })) +/** The mirror trust set the list reads (null: not read yet). */ +let mirrorTrust: ReadonlySet | null = null +vi.mock('@/hooks/use-mirror-trust', () => ({ useMirrorTrust: () => mirrorTrust })) vi.mock('@/hooks/use-repo-chrome', () => ({ useRepoWriteGeneration: () => 0 })) vi.mock('@/components/repo/use-repo-totals', () => ({ useRepoTotals: () => 203 })) vi.mock('@/components/repo/mirror-note', () => ({ MirrorNote: () => null })) @@ -118,6 +120,7 @@ let el: HTMLDivElement beforeEach(() => { ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true search = '' + mirrorTrust = null lookupGate = null dotGate = null dotReads.length = 0 @@ -251,6 +254,12 @@ describe('PullsContent (L-44)', () => { expect(replaced.at(-1)).toBe('/repo/pulls/?owner=o&name=n&q=author%3Athephez+fix') expect(el.querySelector('[data-testid="pull-search-dropped"]')).toBeNull() search = 'owner=o&name=n&q=author%3Athephez+fix' + // Until the mirror trust set is read, no row could match: the list waits rather than read. + asked.length = 0 + await render() + expect(asked).toEqual([]) + expect(el.textContent).toContain('Reading pull requests') + mirrorTrust = new Set(['owner']) await render() expect(asked.at(-1)).toMatchObject({ author: null, authorLogin: 'thephez', text: 'fix' }) expect(el.querySelector('[data-testid="author-login-note"]')?.textContent).toContain('mirrored from @thephez') diff --git a/forge-web/components/repo/pulls-content.tsx b/forge-web/components/repo/pulls-content.tsx index d3db31691..1af75800e 100644 --- a/forge-web/components/repo/pulls-content.tsx +++ b/forge-web/components/repo/pulls-content.tsx @@ -103,6 +103,8 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress // `me` needs a signed-in viewer; signed out, a `me` filter shows nothing rather than everything. const needsViewer = query.author === 'me' || query.assignee === 'me' || query.reviewRequested === 'me' + // `author:` matches only what a trusted mirror signed: the read waits for the trust set. + const awaitingTrust = query.authorLogin !== null && trust === null const { data, loading, error, reload } = useAsync( () => { const who = (v: string | null): string | null => (v === 'me' ? identity ?? '' : v) @@ -122,7 +124,7 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress return queryPulls(sdk!, home.repo, selection, total, network) }, [ready, repoKey(home.repo), generation, JSON.stringify(query), identity ?? '', total ?? -1, query.authorLogin !== null && trust !== null ? [...trust].sort().join(',') : null], - { enabled: ready && sdk !== null && (!needsViewer || identity !== null) }, + { enabled: ready && sdk !== null && (!needsViewer || identity !== null) && !awaitingTrust }, ) const labelDefs = useMemo(() => new Map((data?.labels ?? []).map((l) => [l.name, l])), [data]) @@ -180,7 +182,7 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress
change({ labels })} /> change(c)} /> - change({ author })} /> + change({ author, authorLogin: null })} /> change({ assignee })} /> change({ sort })} />
@@ -188,7 +190,7 @@ export function PullsContent({ home, addr }: { home: RepoHome; addr: RepoAddress {needsViewer && identity === null ? (

Sign in to filter by your own pull requests, assignments and review requests.

- ) : loading && !data ? ( + ) : (loading || awaitingTrust) && !data ? ( ) : error ? (
diff --git a/forge-web/lib/view/issue-query.test.ts b/forge-web/lib/view/issue-query.test.ts index d444feec3..7a492a3dc 100644 --- a/forge-web/lib/view/issue-query.test.ts +++ b/forge-web/lib/view/issue-query.test.ts @@ -153,6 +153,23 @@ describe('search-box qualifiers', () => { expect(reason).toContain('Only -label: can be negated here.') }) + it('keeps a GitHub key with no value as the prose it is ("status: broken")', () => { + expect(unresolvedQualifiers('status: broken type: error')).toEqual([]) + expect(parseSearchText('status: broken type: error').q).toBe('status: broken type: error') + // An applied key with no value is still reported. + expect(unresolvedQualifiers('label: milestone:')).toEqual(['label:', 'milestone:']) + }) + + it('reads back a URL whose q carries long qualifiers, uncut', () => { + const q = parseSearchText( + '-label:"needs more discussion" -label:"blocked upstream" -label:wontfix-maybe milestone:"Release 2026 Q4 stabilisation and hardening sprint" in:title comments:>=10 a longer free text search for the crash on startup', + ) + const text = issueQueryParams(q).find(([k]) => k === 'q')?.[1] ?? '' + expect(text.length).toBeGreaterThan(200) + const back = parseIssueQuery(new URLSearchParams(issueQueryParams(q))) + expect(back).toMatchObject({ notLabels: q.notLabels, milestone: q.milestone, scope: 'title', comments: '>=10', q: q.q }) + }) + it('takes an author name with no identity behind it as a mirrored login (QW-062)', () => { expect(parseSearchText('author:thephez')).toMatchObject({ author: null, authorLogin: 'thephez', q: '' }) expect(parseSearchText('author:@thephez')).toMatchObject({ authorLogin: 'thephez' }) diff --git a/forge-web/lib/view/issue-query.ts b/forge-web/lib/view/issue-query.ts index 38aba79b7..723a8e733 100644 --- a/forge-web/lib/view/issue-query.ts +++ b/forge-web/lib/view/issue-query.ts @@ -102,6 +102,14 @@ const MILESTONE_MAX = 63 /** A source forge's login (GitHub's shape: letters, digits and inner hyphens, at most 39). */ const LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/ +/** + * The longest `?q=` read (a crafted link cannot force unbounded parsing or DPNS reads). `q` also + * carries the qualifiers with no parameter of their own (a 63-character milestone, several + * `-label:`s, `comments:`, `in:`, a PR's `draft:` and `review-requested:`), so this leaves room + * for them beside the free text: a cut mid-qualifier would read back as a different filter. + */ +export const Q_MAX = 512 + /** The bytes an issue, PR or comment `body` may hold (the contract's `maxBytes`). */ export const BODY_MAX = 5120 @@ -133,7 +141,7 @@ export function parseIssueQuery(params: { get(name: string): string | null; getA assignee: identityParam(params.get('assignee'), ['me', 'none']), mentions: params.get('mentions') === 'me', sort: SORTS.includes(sort as IssueSort) ? (sort as IssueSort) : 'newest', - q: (params.get('q') ?? '').slice(0, 200), + q: (params.get('q') ?? '').slice(0, Q_MAX), page: Number.isInteger(page) && page >= 1 && page <= 10_000 ? page : 1, } // A GitHub link carries its qualifiers inside `q` (`/issues?q=is:closed+label:bug`): lift @@ -544,7 +552,9 @@ function liftQualifiers(text: string, base: IssueListQuery): { query: IssueListQ used = false } if (used) continue - if (isQualifierKey(key)) unresolved.push(tok) + // A GitHub key with nothing after its colon (`status: broken`, `type: error`) is prose, not a + // qualifier: it stays free text, as it does on GitHub. An applied key's empty value is reported. + if (isQualifierKey(key) && (value !== '' || APPLIED_KEYS.has(key))) unresolved.push(tok) else free.push(tok) } return { diff --git a/forge-web/lib/view/pull-query.test.ts b/forge-web/lib/view/pull-query.test.ts index 7ab79e209..9ee35bdaf 100644 --- a/forge-web/lib/view/pull-query.test.ts +++ b/forge-web/lib/view/pull-query.test.ts @@ -52,6 +52,7 @@ describe('PR list query (L-44)', () => { it('reads draft:, is:draft and review-requested:, and round-trips them through the URL (QW-020)', () => { expect(parsePullSearch('is:draft').draft).toBe(true) expect(parsePullSearch('draft:false').draft).toBe(false) + expect(parsePullSearch('Draft:TRUE').draft).toBe(true) expect(parsePullSearch('review-requested:@me').reviewRequested).toBe('me') expect(parsePullSearch(`review-requested:${ID} fix`)).toMatchObject({ reviewRequested: ID, q: 'fix' }) expect(unresolvedPullQualifiers('draft:maybe review-requested:bob.dash review:approved')).toEqual(['review:approved', 'draft:maybe', 'review-requested:bob.dash']) diff --git a/forge-web/lib/view/pull-query.ts b/forge-web/lib/view/pull-query.ts index b63231d16..441118dbd 100644 --- a/forge-web/lib/view/pull-query.ts +++ b/forge-web/lib/view/pull-query.ts @@ -23,6 +23,7 @@ import { parseIssueQuery, parseSearchText, personValue, + Q_MAX, searchText, unresolvedQualifiers, type IssueListQuery, @@ -108,7 +109,8 @@ function liftPullOnly(text: string): PullOnly { .replace(PR_VALUE_TOKEN, (_m, lead: string, token: string, key: string, raw: string) => { const value = raw.replace(/"/g, '') if (key.toLowerCase() === 'draft') { - if (value === 'true' || value === 'false') draft = value === 'true' + const flag = value.toLowerCase() + if (flag === 'true' || flag === 'false') draft = flag === 'true' else unresolved.push(token) } else { const who = personValue(value) @@ -166,7 +168,7 @@ export function pullDroppedReason(dropped: readonly string[], notFound: readonly export function parsePullQuery(params: { get(name: string): string | null; getAll(name: string): string[] }): PullListQuery { const raw = params.get('state') const state = STATES.includes(raw as PullStateFilter) ? (raw as PullStateFilter) : 'open' - const q = (params.get('q') ?? '').slice(0, 200) + const q = (params.get('q') ?? '').slice(0, Q_MAX) // The rest as the Issues list reads it; `q`'s qualifiers (a GitHub link) are lifted below. const issue = parseIssueQuery({ get: (n) => (n === 'state' || n === 'q' ? null : params.get(n)), getAll: (n) => params.getAll(n) }) const base = { ...toPull(issue, state), q } From 1eba2745562028a76421a0042863f3c8ada94de8 Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 30 Sep 2026 09:03:55 -0500 Subject: [PATCH 3/3] perf(web): read each body once per text search, and keep a quoted PR qualifier whole A text search walk re-matched every loaded row after each chunk, lowercasing and stripping each body again; the searchable form is now kept per body. A quoted draft: or review-requested: value was cut at its first space, leaking the rest into the free text. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/lib/repo/issue-index.ts | 17 ++++++++++++++++- forge-web/lib/view/pull-query.test.ts | 3 +++ forge-web/lib/view/pull-query.ts | 2 +- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/forge-web/lib/repo/issue-index.ts b/forge-web/lib/repo/issue-index.ts index 7a64f7614..7f1ace9f8 100644 --- a/forge-web/lib/repo/issue-index.ts +++ b/forge-web/lib/repo/issue-index.ts @@ -211,6 +211,21 @@ export function mentions(body: string | undefined, id: string, name: string | nu return new RegExp(`(^|[^\\w@])@${escaped}(?![\\w-])`, 'i').test(body) } +/** + * A body as a text search reads it (lowercased, without a mirrored provenance quote), kept per + * body: a walk re-matches every loaded row after each chunk it reads. + */ +const searchBodies = new Map() +function searchBody(body: string): string { + let hit = searchBodies.get(body) + if (hit === undefined) { + if (searchBodies.size >= 4096) searchBodies.clear() + hit = searchableBody(body).toLowerCase() + searchBodies.set(body, hit) + } + return hit +} + /** * Whether `row` holds every term of `text` ({@link searchTerms}: a word, or a `"quoted phrase"` * as a whole, QW-021), case-insensitively, in its title or body (GitHub's default; `scope` @@ -225,7 +240,7 @@ export function matchesText(text: string, row: { readonly title: string; readonl if (terms.length === 0) return true const fields: string[] = [] if (scope !== 'body') fields.push(row.title.toLowerCase()) - if (scope !== 'title' && row.body) fields.push(searchableBody(row.body).toLowerCase()) + if (scope !== 'title' && row.body) fields.push(searchBody(row.body)) return terms.every((w) => { // `#n` (review L-43) is a number-only match: it never falls back to a text substring, even // when the digits happen to appear in the title of a different-numbered row. diff --git a/forge-web/lib/view/pull-query.test.ts b/forge-web/lib/view/pull-query.test.ts index 9ee35bdaf..cfc8db082 100644 --- a/forge-web/lib/view/pull-query.test.ts +++ b/forge-web/lib/view/pull-query.test.ts @@ -55,6 +55,9 @@ describe('PR list query (L-44)', () => { expect(parsePullSearch('Draft:TRUE').draft).toBe(true) expect(parsePullSearch('review-requested:@me').reviewRequested).toBe('me') expect(parsePullSearch(`review-requested:${ID} fix`)).toMatchObject({ reviewRequested: ID, q: 'fix' }) + // A quoted value is one token: none of it leaks into the free text. + expect(parsePullSearch('review-requested:"a b" fix')).toMatchObject({ reviewRequested: null, q: 'fix' }) + expect(unresolvedPullQualifiers('review-requested:"a b" fix')).toEqual(['review-requested:"a b"']) expect(unresolvedPullQualifiers('draft:maybe review-requested:bob.dash review:approved')).toEqual(['review:approved', 'draft:maybe', 'review-requested:bob.dash']) expect(pullDroppedReason(['draft:maybe', 'review-requested:bob.dash'], ['bob.dash'])).toBe('draft: takes true or false. No DPNS name `bob.dash` was found.') const q = { ...DEFAULT_PULL_QUERY, draft: true, reviewRequested: ID, milestone: 'v1', q: 'fix' } diff --git a/forge-web/lib/view/pull-query.ts b/forge-web/lib/view/pull-query.ts index 441118dbd..d9be33599 100644 --- a/forge-web/lib/view/pull-query.ts +++ b/forge-web/lib/view/pull-query.ts @@ -79,7 +79,7 @@ function setsIssueState(text: string): boolean { /** `mentions:` — an Issues filter, not a PR one. */ const MENTIONS_TOKEN = /(^|\s)(mentions:\S*)/gi /** `draft:` and `review-requested:`, the PR-only qualifiers with a value. */ -const PR_VALUE_TOKEN = /(^|\s)((draft|review-requested):(\S*))/gi +const PR_VALUE_TOKEN = /(^|\s)((draft|review-requested):("[^"]*"|\S*))/gi interface PullOnly { readonly rest: string