TypeScript
fix(prs): typed qualifiers filter mobile PR search and sync the draft menu (#19934)
Bilal Bakr9f70fcc7b584
diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsxindex 35c48d29d49..226d13cd40d 100644--- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx@@ -1,8 +1,11 @@+import {+ applyPullRequestDraftFilterChange,+ parsePullRequestQuery,+} from "@t3tools/client-runtime/pull-request-query";import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";import { LegendList, type LegendListRef } from "@legendapp/list/react-native";import { useNavigation } from "@react-navigation/native";import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";-import { ProjectId } from "@t3tools/contracts";import { useAtomValue } from "@effect/atom-react";import {Keyboard,@@ -30,10 +33,10 @@ import { usePullRequestListActions } from "./usePullRequestListActions";import {filterPullRequestList,pullRequestListFacets,+ pullRequestListInput,pullRequestListRowsAreEqual,scopedPullRequestListKey as pullRequestKey,type EnvironmentPullRequestListEntry,- PR_LIST_PAGE_SIZE,withoutScratchProjectScope,} from "./pullRequestList";import { useDebouncedValue } from "../../state/queries";@@ -79,6 +82,8 @@ export function PullRequestsScreen();const debouncedQuery = useDebouncedValue(tab.query.trim(), 180);const query = tab.searchMode === "resting" ? "" : debouncedQuery;+ const typedQuery = tab.searchMode === "resting" ? "" : tab.query;+ const typedDraft = parsePullRequestQuery(typedQuery).filters.draft;const listControls = usePullRequestListControls();const selectedEnvironmentId = listControls.environmentId;const environmentId = environments.some((item) => item.environmentId === selectedEnvironmentId)@@ -121,14 +126,7 @@ export function PullRequestsScreen(.sort((left, right) => left.environmentId.localeCompare(right.environmentId)).map((environment) => ({environmentId: environment.environmentId,- input: {- state: controls.state,- involvement: controls.involvement,- filters: controls.filters,- limit: PR_LIST_PAGE_SIZE,- ...(controls.projectId ? { projectId: ProjectId.make(controls.projectId) } : {}),- ...(query ? { query } : {}),- },+ input: pullRequestListInput(controls, query),})),[environments, environmentId, configs, controls, query],);@@ -281,9 +279,20 @@ export function PullRequestsScreen(}))}environmentId={environmentId}onEnvironmentChange={listControls.setEnvironmentId}- value={controls}+ value={+ typedDraft+ ? { ...controls, filters: { ...controls.filters, draft: typedDraft } }+ : controls+ }onChange={(next) => {- listControls.setControls(environmentId, next);+ const update = applyPullRequestDraftFilterChange(+ typedQuery,+ controls.filters,+ next.filters,+ );+ listControls.setControls(environmentId, { ...next, filters: update.filters });+ if (update.query !== typedQuery)+ workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query });void listRef.current?.scrollToOffset({offset: Platform.OS === "ios" ? -insets.top : 0,animated: false,diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.test.ts b/apps/mobile/src/features/pull-requests/pullRequestList.test.tsindex de5dd166ff1..f5d6755190b 100644--- a/apps/mobile/src/features/pull-requests/pullRequestList.test.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestList.test.ts@@ -12,8 +12,10 @@ import {mergePullRequestListEntries,mergeEnvironmentPullRequestPages,nextPullRequestListInput,+ PR_LIST_PAGE_SIZE,pullRequestListFacets,pullRequestListHead,+ pullRequestListInput,pullRequestListReviewStatus,pullRequestLabelColor,scopedPullRequestListKey,@@ -289,6 +291,11 @@ describe("mobile PR scan and filters", () => {new Set(),).map((row) => row.number),).toEqual([1]);+ expect(+ filterPullRequestList(rows, DEFAULT_PR_LIST_CONTROLS, viewers, "author:@me", new Set()).map(+ (row) => row.number,+ ),+ ).toEqual([1]);});it("combines label groups, exclusions, draft and review filters", () => {const rows = [@@ -314,6 +321,29 @@ describe("mobile PR scan and filters", () => {),).toEqual([1]);});+ it("reads a typed draft qualifier as a filter and searches only the text left over", () => {+ expect(pullRequestListInput(DEFAULT_PR_LIST_CONTROLS, "draft:false fix")).toEqual({+ state: "open",+ involvement: "all",+ filters: { draft: "hide" },+ limit: PR_LIST_PAGE_SIZE,+ query: "fix",+ });+ const rows = [+ entry(1, { title: "Fix parser" }),+ entry(2, { title: "Fix drafts", isDraft: true }),+ entry(3),+ ];+ expect(+ filterPullRequestList(+ rows,+ DEFAULT_PR_LIST_CONTROLS,+ {},+ "draft:false fix",+ new Set(["github.com"]),+ ).map((row) => row.number),+ ).toEqual([1]);+ });it("does not label unsupported review summaries as reviewed or match text locally on host-search results", () => {expect(filterPullRequestList(diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.tsindex 2b6e1552bd6..7577c81fa5b 100644--- a/apps/mobile/src/features/pull-requests/pullRequestList.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts@@ -1,8 +1,11 @@-import type {- EnvironmentId,- PullRequestListEntry,- PullRequestListInput,- PullRequestListResult,+import { parsePullRequestQuery } from "@t3tools/client-runtime/pull-request-query";+import {+ ProjectId,+ resolvePullRequestAuthorFilter,+ type EnvironmentId,+ type PullRequestListEntry,+ type PullRequestListInput,+ type PullRequestListResult,} from "@t3tools/contracts";import type { PullRequestListControls } from "../../persistence/mobile-preferences";@@ -138,6 +141,21 @@ export function pullRequestListHead(};}+export function pullRequestListInput(+ controls: PullRequestListControls,+ query: string,+): PullRequestListInput {+ const parsed = parsePullRequestQuery(query);+ return {+ state: controls.state,+ involvement: controls.involvement,+ filters: { ...controls.filters, ...parsed.filters },+ limit: PR_LIST_PAGE_SIZE,+ ...(controls.projectId ? { projectId: ProjectId.make(controls.projectId) } : {}),+ ...(parsed.text ? { query: parsed.text } : {}),+ };+}+export function nextPullRequestListInput(pages: PullRequestListPages,input: PullRequestListInput,@@ -186,8 +204,9 @@ export function filterPullRequestList<connectedEnvironmentIds?: ReadonlySet<string>,) {const normalize = (value: string) => value.toLowerCase();- const words = query.toLowerCase().split(/\s+/).filter(Boolean);- const { filters } = controls;+ const parsed = parsePullRequestQuery(query);+ const words = parsed.text.toLowerCase().split(/\s+/).filter(Boolean);+ const filters = { ...controls.filters, ...parsed.filters };const filtered = entries.filter((entry) => {if (controls.state !== "all" && entry.state !== controls.state) return false;if (controls.projectId && entry.projectId !== controls.projectId) return false;@@ -204,8 +223,8 @@ export function filterPullRequestList<if ((filters.draft === "only" && !entry.isDraft) || (filters.draft === "hide" && entry.isDraft))return false;if (filters.author) {- const author = filters.author === "me" ? viewer : filters.author;- if (!author || normalize(entry.author?.login ?? "") !== normalize(author)) return false;+ const author = resolvePullRequestAuthorFilter(filters.author, viewer);+ if (normalize(entry.author?.login ?? "") !== normalize(author)) return false;}if (filters.review && entry.reviewDecision && entry.reviewDecision !== filters.review)return false;diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.tsindex 56c94d7cc23..172e64062f8 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts@@ -19,7 +19,6 @@ import {groupPullRequestsByInvolvement,matchesPullRequestFilters,matchesPullRequestQuery,- parsePullRequestQuery,pullRequestStatsBatches,pullRequestStatsKeysToRequest,pullRequestStatsRefreshBatches,@@ -557,84 +556,6 @@ describe("narrowing rows by the filters a host may not have applied", () => {});});-describe("reading qualifiers out of a typed query", () => {- it("keeps quoted values whole and separates negation", () => {- expect(parsePullRequestQuery('label:"needs design" -label:wip Fix the parser')).toEqual({- text: "Fix the parser",- filters: { labels: [["needs design"]], excludedLabels: ["wip"] },- });- });-- it("reads a comma-separated list as one group either name satisfies", () => {- expect(parsePullRequestQuery("label:size:S,size:XS").filters.labels).toEqual([- ["size:S", "size:XS"],- ]);- });-- it("keeps the spaces in a quoted name of a list, and drops an empty part", () => {- expect(parsePullRequestQuery('label:"needs design","wip"').filters.labels).toEqual([- ["needs design", "wip"],- ]);- expect(parsePullRequestQuery("label:a,,b").filters.labels).toEqual([["a", "b"]]);- });-- it("excludes every name of a negated list", () => {- expect(parsePullRequestQuery("-label:a,b").filters).toEqual({ excludedLabels: ["a", "b"] });- });-- it("makes each label qualifier its own group, so the groups are an AND", () => {- expect(parsePullRequestQuery("label:bug label:a,b").filters.labels).toEqual([- ["bug"],- ["a", "b"],- ]);- });-- it("reads the scalar qualifiers in GitHub's own spelling", () => {- expect(- parsePullRequestQuery("author:octocat DRAFT:false review:changes_requested status:failure")- .filters,- ).toEqual({- author: "octocat",- draft: "hide",- review: "changes-requested",- checks: "failing",- });- });-- it("leaves an unknown value and a stray colon as text, and reads an unknown key as a label", () => {- const parsed = parsePullRequestQuery("milestone:v2 draft:maybe status: parser");- expect(parsed.filters).toEqual({ labels: [["milestone:v2"]] });- expect(parsed.text).toBe("draft:maybe status: parser");- });-- it("reads a quoted name holding a comma as the one label it is", () => {- expect(parsePullRequestQuery('label:"needs,triage"').filters.labels).toEqual([- ["needs,triage"],- ]);- expect(parsePullRequestQuery('-label:"needs,triage"').filters.excludedLabels).toEqual([- "needs,triage",- ]);- });-- it("cuts a typed query back to what the contract carries", () => {- const many = Array.from({ length: 14 }, (_, index) => `l${index}`).join(",");- const long = "x".repeat(240);- const parsed = parsePullRequestQuery(`label:${many} label:${long} author:${long}`);- expect(parsed.filters.labels?.[0]).toHaveLength(10);- expect(parsed.filters.labels?.[1]).toEqual(["x".repeat(200)]);- expect(parsed.filters.author).toBe("x".repeat(200));- });-- it("cuts a namespaced label after its key is prefixed on", () => {- const parsed = parsePullRequestQuery(`size:${"x".repeat(240)}`);- expect(parsed.filters.labels).toEqual([[`size:${"x".repeat(240)}`.slice(0, 200)]]);- });-- it("answers an empty query with an empty everything", () => {- expect(parsePullRequestQuery(" ")).toEqual({ text: "", filters: {} });- });-});-describe("resolveProjectScope", () => {const projects = [{ id: "p1" }, { id: "p2" }];@@ -1508,58 +1429,6 @@ describe("the server a saved selection names", () => {});});-describe("colon-namespaced labels typed as a search", () => {- it("reads an unknown key as the label it almost always is", () => {- expect(parsePullRequestQuery("size:XXL").filters.labels).toEqual([["size:XXL"]]);- expect(parsePullRequestQuery("vouch:trusted").filters.labels).toEqual([["vouch:trusted"]]);- expect(parsePullRequestQuery("size:XXL").text).toBe("");- });-- it("reads the key as the namespace of every bare name in its list", () => {- expect(parsePullRequestQuery("size:S,XS").filters.labels).toEqual([["size:S", "size:XS"]]);- });-- it("leaves a name that already carries its own namespace alone", () => {- expect(parsePullRequestQuery("size:S,size:XS").filters.labels).toEqual([["size:S", "size:XS"]]);- });-- it("excludes one the same way", () => {- expect(parsePullRequestQuery("-size:XXL").filters.excludedLabels).toEqual(["size:XXL"]);- expect(parsePullRequestQuery("-size:S,XS").filters.excludedLabels).toEqual([- "size:S",- "size:XS",- ]);- });-- it("keeps a quoted token as text, which is the way back to a literal search", () => {- const parsed = parsePullRequestQuery('"size:XXL"');- expect(parsed.filters.labels).toBeUndefined();- expect(parsed.text).toBe('"size:XXL"');- });-- it("reads a hyphenated namespace as a label too", () => {- expect(parsePullRequestQuery("priority-1:high").filters.labels).toEqual([["priority-1:high"]]);- expect(parsePullRequestQuery("priority-1:high").text).toBe("");- });-- it("leaves a pasted link alone rather than naming a label after its scheme", () => {- const parsed = parsePullRequestQuery("https://github.com/pingdotgg/t3code/pull/1");- expect(parsed.filters.labels).toBeUndefined();- expect(parsed.text).toBe("https://github.com/pingdotgg/t3code/pull/1");- });-- it("mixes with the keys it does know, and with plain words", () => {- const parsed = parsePullRequestQuery("area:web draft:true wizard label:bug");- expect(parsed.filters).toEqual({ labels: [["area:web"], ["bug"]], draft: "only" });- expect(parsed.text).toBe("wizard");- });-- it("shares the ceiling with the labels typed as labels", () => {- const many = Array.from({ length: 12 }, (_, index) => `area:${index}`).join(" ");- expect(parsePullRequestQuery(many).filters.labels).toHaveLength(10);- });-});-describe("the priority groups against a paginated feed", () => {const authoredRow = (number: number, updatedAt: string) =>entry({ number, updatedAt, author: { login: "Bilal", name: null, avatarUrl: null } });diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.tsindex 9f8a5809216..c64254d58f0 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts@@ -136,123 +136,6 @@ function isAuthoredByViewer(entry: ScopedEntry, viewers: PullRequestViewers): boreturn viewer !== null && normalize(entry.author?.login) === viewer;}-const REVIEW_VALUES: Record<string, PullRequestListFilters["review"]> = {- approved: "approved",- changes_requested: "changes-requested",- "changes-requested": "changes-requested",- required: "review-required",- "review-required": "review-required",- none: "none",-};-const CHECKS_VALUES: Record<string, PullRequestListFilters["checks"]> = {- success: "passing",- passing: "passing",- failure: "failing",- failing: "failing",-};--const QUERY_TOKEN = /(?:[^\s"]|"[^"]*")+/g;-const MAX_QUALIFIER_VALUES = 10;-const MAX_QUALIFIER_LENGTH = 200;--function qualifierValue(raw: string): string {- return raw.replaceAll('"', "").trim();-}--function splitQualifierList(raw: string): string[] {- if (/^\s*"[^"]*"\s*$/.test(raw)) {- const whole = qualifierValue(raw);- return whole.length === 0 ? [] : [whole];- }- return raw- .split(",")- .map((part) => qualifierValue(part))- .filter((part) => part.length > 0);-}--function boundedNames(names: ReadonlyArray<string>): string[] {- return names- .slice(0, MAX_QUALIFIER_VALUES)- .map((name) => name.slice(0, MAX_QUALIFIER_LENGTH).trim())- .filter((name) => name.length > 0);-}--export function parsePullRequestQuery(raw: string): {- readonly text: string;- readonly filters: PullRequestListFilters;-} {- const text: string[] = [];- const labels: string[][] = [];- const excludedLabels: string[] = [];- let author: string | undefined;- let draft: PullRequestListFilters["draft"];- let review: PullRequestListFilters["review"];- let checks: PullRequestListFilters["checks"];- for (const [token] of raw.matchAll(QUERY_TOKEN)) {- const qualifier = /^(-?)([A-Za-z][A-Za-z0-9_-]*):(.*)$/.exec(token);- const value = qualifier === null ? "" : qualifierValue(qualifier[3] ?? "");- const negated = qualifier?.[1] === "-";- switch (value.length === 0 ? "" : (qualifier?.[2]?.toLowerCase() ?? "")) {- case "label": {- const names = boundedNames(splitQualifierList(qualifier?.[3] ?? ""));- if (names.length === 0) break;- if (negated) excludedLabels.push(...names);- else labels.push(names);- continue;- }- case "author":- if (negated) break;- author = value.slice(0, MAX_QUALIFIER_LENGTH).trim();- continue;- case "draft":- if (negated || (value.toLowerCase() !== "true" && value.toLowerCase() !== "false")) break;- draft = value.toLowerCase() === "true" ? "only" : "hide";- continue;- case "review": {- const decision = negated ? undefined : REVIEW_VALUES[value.toLowerCase()];- if (decision === undefined) break;- review = decision;- continue;- }- case "status":- case "checks": {- const state = negated ? undefined : CHECKS_VALUES[value.toLowerCase()];- if (state === undefined) break;- checks = state;- continue;- }- case "":- break;- default:- if (!value.startsWith("/")) {- const names = boundedNames(- splitQualifierList(qualifier?.[3] ?? "").map((name) =>- name.includes(":") ? name : `${qualifier?.[2] ?? ""}:${name}`,- ),- );- if (names.length === 0) break;- if (negated) excludedLabels.push(...names);- else labels.push(names);- continue;- }- }- text.push(token);- }- return {- text: text.join(" "),- filters: {- ...(labels.length === 0 ? {} : { labels: labels.slice(0, MAX_QUALIFIER_VALUES) }),- ...(excludedLabels.length === 0- ? {}- : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }),- ...(author === undefined ? {} : { author }),- ...(draft === undefined ? {} : { draft }),- ...(review === undefined ? {} : { review }),- ...(checks === undefined ? {} : { checks }),- },- };-}-export function matchesPullRequestQuery(entry: PullRequestListEntry, query: string): boolean {const normalizedQuery = query.trim().toLowerCase();if (normalizedQuery.length === 0) return true;diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsxindex 2faa7f04aa1..85617acbfac 100644--- a/apps/web/src/routes/_chat.pull-requests.tsx+++ b/apps/web/src/routes/_chat.pull-requests.tsx@@ -1,3 +1,7 @@+import {+ applyPullRequestDraftFilterChange,+ parsePullRequestQuery,+} from "@t3tools/client-runtime/pull-request-query";import { RefreshIcon } from "~/components/ui/refresh-icon";import { Spinner } from "~/components/ui/spinner";import { useShortcutModifierState } from "~/shortcutModifierState";@@ -58,7 +62,6 @@ import {groupPullRequestsByInvolvement,matchesPullRequestFilters,matchesPullRequestQuery,- parsePullRequestQuery,narrowPullRequestsToFilters,mergePullRequestDiffStats,partitionPullRequestsWithPriority,@@ -1631,7 +1634,9 @@ function PullRequestsRouteView() {</div>);const carriedToNothing =- showingCarried && listQuery.isPending && shownCount === 0 && typedQuery.length === 0;+ shownCount === 0 &&+ typedQuery.length === 0 &&+ (!querySettled || (showingCarried && listQuery.isPending));const listBody = (<>{!capabilityKnown ? (@@ -1788,16 +1793,26 @@ function PullRequestsRouteView() {involvement={search.involvement}involvementOptions={INVOLVEMENT_TABS}onInvolvement={(involvement) => updateListScope({ involvement })}- filters={menuFilters}- onFilters={(next) =>+ filters={+ typedParsed.filters.draft+ ? { ...menuFilters, draft: typedParsed.filters.draft }+ : menuFilters+ }+ onFilters={(value) => {+ const { query, filters: next } = applyPullRequestDraftFilterChange(+ typedQuery,+ menuFilters,+ value,+ );updateListScope({+ ...(query === typedQuery ? {} : { q: query || undefined }),draft: next.draft,review: next.review,checks: next.checks,author: next.author,labels: next.labels?.flatMap((group) => group),- })- }+ });+ }}authorOptions={facets.authors}labelOptions={facets.labels}host={search.host}diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex 80462970d59..771843e2ae7 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -422,6 +422,10 @@"./pull-request-markdown": {"types": "./src/pullRequestMarkdown.ts","default": "./src/pullRequestMarkdown.ts"+ },+ "./pull-request-query": {+ "types": "./src/pullRequestQuery.ts",+ "default": "./src/pullRequestQuery.ts"}},"scripts": {diff --git a/packages/client-runtime/src/pullRequestQuery.test.ts b/packages/client-runtime/src/pullRequestQuery.test.tsnew file mode 100644index 00000000000..3a4d2f9b6bb--- /dev/null+++ b/packages/client-runtime/src/pullRequestQuery.test.ts@@ -0,0 +1,163 @@+import { describe, expect, it } from "vite-plus/test";+import { applyPullRequestDraftFilterChange, parsePullRequestQuery } from "./pullRequestQuery.ts";++describe("reading qualifiers out of a typed query", () => {+ it("keeps quoted values whole and separates negation", () => {+ expect(parsePullRequestQuery('label:"needs design" -label:wip Fix the parser')).toEqual({+ text: "Fix the parser",+ filters: { labels: [["needs design"]], excludedLabels: ["wip"] },+ });+ });++ it("reads a comma-separated list as one group either name satisfies", () => {+ expect(parsePullRequestQuery("label:size:S,size:XS").filters.labels).toEqual([+ ["size:S", "size:XS"],+ ]);+ });++ it("keeps the spaces in a quoted name of a list, and drops an empty part", () => {+ expect(parsePullRequestQuery('label:"needs design","wip"').filters.labels).toEqual([+ ["needs design", "wip"],+ ]);+ expect(parsePullRequestQuery("label:a,,b").filters.labels).toEqual([["a", "b"]]);+ });++ it("excludes every name of a negated list", () => {+ expect(parsePullRequestQuery("-label:a,b").filters).toEqual({ excludedLabels: ["a", "b"] });+ });++ it("makes each label qualifier its own group, so the groups are an AND", () => {+ expect(parsePullRequestQuery("label:bug label:a,b").filters.labels).toEqual([+ ["bug"],+ ["a", "b"],+ ]);+ });++ it("reads the scalar qualifiers in GitHub's own spelling", () => {+ expect(+ parsePullRequestQuery("author:octocat DRAFT:false review:changes_requested status:failure")+ .filters,+ ).toEqual({+ author: "octocat",+ draft: "hide",+ review: "changes-requested",+ checks: "failing",+ });+ });++ it("leaves an unknown value and a stray colon as text, and reads an unknown key as a label", () => {+ const parsed = parsePullRequestQuery("milestone:v2 draft:maybe status: parser");+ expect(parsed.filters).toEqual({ labels: [["milestone:v2"]] });+ expect(parsed.text).toBe("draft:maybe status: parser");+ });++ it("reads a quoted name holding a comma as the one label it is", () => {+ expect(parsePullRequestQuery('label:"needs,triage"').filters.labels).toEqual([+ ["needs,triage"],+ ]);+ expect(parsePullRequestQuery('label:"needs,triage",wip').filters.labels).toEqual([+ ["needs,triage", "wip"],+ ]);+ expect(parsePullRequestQuery('-label:"needs,triage"').filters.excludedLabels).toEqual([+ "needs,triage",+ ]);+ });++ it("cuts a typed query back to what the contract carries", () => {+ const many = Array.from({ length: 14 }, (_, index) => `l${index}`).join(",");+ const long = "x".repeat(240);+ const parsed = parsePullRequestQuery(`label:${many} label:${long} author:${long}`);+ expect(parsed.filters.labels?.[0]).toHaveLength(10);+ expect(parsed.filters.labels?.[1]).toEqual(["x".repeat(200)]);+ expect(parsed.filters.author).toBe("x".repeat(200));+ });++ it("cuts a namespaced label after its key is prefixed on", () => {+ const parsed = parsePullRequestQuery(`size:${"x".repeat(240)}`);+ expect(parsed.filters.labels).toEqual([[`size:${"x".repeat(240)}`.slice(0, 200)]]);+ });++ it("answers an empty query with an empty everything", () => {+ expect(parsePullRequestQuery(" ")).toEqual({ text: "", filters: {} });+ });+});++describe("colon-namespaced labels typed as a search", () => {+ it("reads an unknown key as the label it almost always is", () => {+ expect(parsePullRequestQuery("size:XXL").filters.labels).toEqual([["size:XXL"]]);+ expect(parsePullRequestQuery("vouch:trusted").filters.labels).toEqual([["vouch:trusted"]]);+ expect(parsePullRequestQuery("size:XXL").text).toBe("");+ });++ it("reads the key as the namespace of every bare name in its list", () => {+ expect(parsePullRequestQuery("size:S,XS").filters.labels).toEqual([["size:S", "size:XS"]]);+ });++ it("leaves a name that already carries its own namespace alone", () => {+ expect(parsePullRequestQuery("size:S,size:XS").filters.labels).toEqual([["size:S", "size:XS"]]);+ });++ it("excludes one the same way", () => {+ expect(parsePullRequestQuery("-size:XXL").filters.excludedLabels).toEqual(["size:XXL"]);+ expect(parsePullRequestQuery("-size:S,XS").filters.excludedLabels).toEqual([+ "size:S",+ "size:XS",+ ]);+ });++ it("keeps a quoted token as text, which is the way back to a literal search", () => {+ const parsed = parsePullRequestQuery('"size:XXL"');+ expect(parsed.filters.labels).toBeUndefined();+ expect(parsed.text).toBe('"size:XXL"');+ });++ it("reads a hyphenated namespace as a label too", () => {+ expect(parsePullRequestQuery("priority-1:high").filters.labels).toEqual([["priority-1:high"]]);+ expect(parsePullRequestQuery("priority-1:high").text).toBe("");+ });++ it("leaves a pasted link alone rather than naming a label after its scheme", () => {+ const parsed = parsePullRequestQuery("https://github.com/pingdotgg/t3code/pull/1");+ expect(parsed.filters.labels).toBeUndefined();+ expect(parsed.text).toBe("https://github.com/pingdotgg/t3code/pull/1");+ });++ it("mixes with the keys it does know, and with plain words", () => {+ const parsed = parsePullRequestQuery("area:web draft:true wizard label:bug");+ expect(parsed.filters).toEqual({ labels: [["area:web"], ["bug"]], draft: "only" });+ expect(parsed.text).toBe("wizard");+ });++ it("shares the ceiling with the labels typed as labels", () => {+ const many = Array.from({ length: 12 }, (_, index) => `area:${index}`).join(" ");+ expect(parsePullRequestQuery(many).filters.labels).toHaveLength(10);+ });+});++describe("changing the draft menu after typing a qualifier", () => {+ it("replaces or clears a typed draft qualifier and keeps the rest of the query", () => {+ expect(+ applyPullRequestDraftFilterChange(+ 'draft:false fix label:"needs design"',+ {},+ { draft: "only" },+ ),+ ).toEqual({ query: 'fix label:"needs design"', filters: { draft: "only" } });+ expect(+ applyPullRequestDraftFilterChange('draft:true "draft:false" fix', { draft: "only" }, {}),+ ).toEqual({+ query: '"draft:false" fix',+ filters: {},+ });+ });++ it("keeps the typed query and the stored menu draft when another filter changes", () => {+ expect(+ applyPullRequestDraftFilterChange(+ "draft:false fix",+ { draft: "only" },+ { draft: "hide", checks: "passing" },+ ),+ ).toEqual({ query: "draft:false fix", filters: { draft: "only", checks: "passing" } });+ });+});diff --git a/packages/client-runtime/src/pullRequestQuery.ts b/packages/client-runtime/src/pullRequestQuery.tsnew file mode 100644index 00000000000..9b333972d0f--- /dev/null+++ b/packages/client-runtime/src/pullRequestQuery.ts@@ -0,0 +1,137 @@+import type { PullRequestListFilters } from "@t3tools/contracts";++const REVIEW_VALUES: Record<string, PullRequestListFilters["review"]> = {+ approved: "approved",+ changes_requested: "changes-requested",+ "changes-requested": "changes-requested",+ required: "review-required",+ "review-required": "review-required",+ none: "none",+};+const CHECKS_VALUES: Record<string, PullRequestListFilters["checks"]> = {+ success: "passing",+ passing: "passing",+ failure: "failing",+ failing: "failing",+};++const QUERY_TOKEN = /(?:[^\s"]|"[^"]*")+/g;+const MAX_QUALIFIER_VALUES = 10;+const MAX_QUALIFIER_LENGTH = 200;++function qualifierValue(raw: string): string {+ return raw.replaceAll('"', "").trim();+}++function splitQualifierList(raw: string): string[] {+ return (raw.match(/(?:[^,"]|"[^"]*")+/g) ?? [])+ .map((part) => qualifierValue(part))+ .filter((part) => part.length > 0);+}++function boundedNames(names: ReadonlyArray<string>): string[] {+ return names+ .slice(0, MAX_QUALIFIER_VALUES)+ .map((name) => name.slice(0, MAX_QUALIFIER_LENGTH).trim())+ .filter((name) => name.length > 0);+}++export function parsePullRequestQuery(raw: string): {+ readonly text: string;+ readonly filters: PullRequestListFilters;+} {+ const text: string[] = [];+ const labels: string[][] = [];+ const excludedLabels: string[] = [];+ let author: string | undefined;+ let draft: PullRequestListFilters["draft"];+ let review: PullRequestListFilters["review"];+ let checks: PullRequestListFilters["checks"];+ for (const [token] of raw.matchAll(QUERY_TOKEN)) {+ const qualifier = /^(-?)([A-Za-z][A-Za-z0-9_-]*):(.*)$/.exec(token);+ const value = qualifier === null ? "" : qualifierValue(qualifier[3] ?? "");+ const negated = qualifier?.[1] === "-";+ switch (value.length === 0 ? "" : (qualifier?.[2]?.toLowerCase() ?? "")) {+ case "label": {+ const names = boundedNames(splitQualifierList(qualifier?.[3] ?? ""));+ if (names.length === 0) break;+ if (negated) excludedLabels.push(...names);+ else labels.push(names);+ continue;+ }+ case "author":+ if (negated) break;+ author = value.slice(0, MAX_QUALIFIER_LENGTH).trim();+ continue;+ case "draft":+ if (negated || (value.toLowerCase() !== "true" && value.toLowerCase() !== "false")) break;+ draft = value.toLowerCase() === "true" ? "only" : "hide";+ continue;+ case "review": {+ const decision = negated ? undefined : REVIEW_VALUES[value.toLowerCase()];+ if (decision === undefined) break;+ review = decision;+ continue;+ }+ case "status":+ case "checks": {+ const state = negated ? undefined : CHECKS_VALUES[value.toLowerCase()];+ if (state === undefined) break;+ checks = state;+ continue;+ }+ case "":+ break;+ default:+ if (!value.startsWith("/")) {+ const names = boundedNames(+ splitQualifierList(qualifier?.[3] ?? "").map((name) =>+ name.includes(":") ? name : `${qualifier?.[2] ?? ""}:${name}`,+ ),+ );+ if (names.length === 0) break;+ if (negated) excludedLabels.push(...names);+ else labels.push(names);+ continue;+ }+ }+ text.push(token);+ }+ return {+ text: text.join(" "),+ filters: {+ ...(labels.length === 0 ? {} : { labels: labels.slice(0, MAX_QUALIFIER_VALUES) }),+ ...(excludedLabels.length === 0+ ? {}+ : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }),+ ...(author === undefined ? {} : { author }),+ ...(draft === undefined ? {} : { draft }),+ ...(review === undefined ? {} : { review }),+ ...(checks === undefined ? {} : { checks }),+ },+ };+}++/**+ * The Draft menu shows a typed `draft:` qualifier, so picking another value has to take the+ * qualifier out of the query: left in, it would keep outranking whatever the menu stores.+ */+export function applyPullRequestDraftFilterChange(+ query: string,+ menuFilters: PullRequestListFilters,+ next: PullRequestListFilters,+) {+ const typedDraft = parsePullRequestQuery(query).filters.draft;+ if (next.draft === (typedDraft ?? menuFilters.draft))+ return { query, filters: { ...next, draft: menuFilters.draft } };+ return {+ query:+ typedDraft === undefined+ ? query+ : [...query.matchAll(QUERY_TOKEN)]+ .map(([token]) => token)+ .filter((token) => parsePullRequestQuery(token).filters.draft === undefined)+ .join(" "),+ filters: next,+ };+}