The best way to control Claude Code, Codex and more from any computer or phone
fix(prs): typed qualifiers filter mobile PR search and sync the draft menu (#19934)
Mobile now parses GitHub-style qualifiers (draft:, label:, author:, review:, status:, namespaced labels) out of PR search through the shared client-runtime parser, and Filters → Draft on web and mobile reflects and replaces a typed draft: qualifier. Co-authored-by: Bil0000 <bilal.bakr.elsherif@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Bilal Bakr committed
Oct 17, 2026 at 04:48 UTC
9f70fcc7b584f74049e643dc6ae3104df197f4ca
9 files changed
+404
-275
apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
+21
-12
@@ -1,8 +1,11 @@
1
+import {
2
+ applyPullRequestDraftFilterChange,
3
+ parsePullRequestQuery,
4
+} from "@t3tools/client-runtime/pull-request-query";
5
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6
import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
7
import { useNavigation } from "@react-navigation/native";
8
import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
5
-import { ProjectId } from "@t3tools/contracts";
9
import { useAtomValue } from "@effect/atom-react";
10
import {
11
Keyboard,
@@ -30,10 +33,10 @@ import { usePullRequestListActions } from "./usePullRequestListActions";
33
import {
34
filterPullRequestList,
35
pullRequestListFacets,
36
+ pullRequestListInput,
37
pullRequestListRowsAreEqual,
38
scopedPullRequestListKey as pullRequestKey,
39
type EnvironmentPullRequestListEntry,
36
- PR_LIST_PAGE_SIZE,
40
withoutScratchProjectScope,
41
} from "./pullRequestList";
42
import { useDebouncedValue } from "../../state/queries";
@@ -79,6 +82,8 @@ export function PullRequestsScreen(
82
);
83
const debouncedQuery = useDebouncedValue(tab.query.trim(), 180);
84
const query = tab.searchMode === "resting" ? "" : debouncedQuery;
85
+ const typedQuery = tab.searchMode === "resting" ? "" : tab.query;
86
+ const typedDraft = parsePullRequestQuery(typedQuery).filters.draft;
87
const listControls = usePullRequestListControls();
88
const selectedEnvironmentId = listControls.environmentId;
89
const environmentId = environments.some((item) => item.environmentId === selectedEnvironmentId)
@@ -121,14 +126,7 @@ export function PullRequestsScreen(
126
.sort((left, right) => left.environmentId.localeCompare(right.environmentId))
127
.map((environment) => ({
128
environmentId: environment.environmentId,
124
- input: {
125
- state: controls.state,
126
- involvement: controls.involvement,
127
- filters: controls.filters,
128
- limit: PR_LIST_PAGE_SIZE,
129
- ...(controls.projectId ? { projectId: ProjectId.make(controls.projectId) } : {}),
130
- ...(query ? { query } : {}),
131
- },
129
+ input: pullRequestListInput(controls, query),
130
})),
131
[environments, environmentId, configs, controls, query],
132
);
@@ -281,9 +279,20 @@ export function PullRequestsScreen(
279
}))}
280
environmentId={environmentId}
281
onEnvironmentChange={listControls.setEnvironmentId}
284
- value={controls}
282
+ value={
283
+ typedDraft
284
+ ? { ...controls, filters: { ...controls.filters, draft: typedDraft } }
285
+ : controls
286
+ }
287
onChange={(next) => {
286
- listControls.setControls(environmentId, next);
288
+ const update = applyPullRequestDraftFilterChange(
289
+ typedQuery,
290
+ controls.filters,
291
+ next.filters,
292
+ );
293
+ listControls.setControls(environmentId, { ...next, filters: update.filters });
294
+ if (update.query !== typedQuery)
295
+ workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query });
296
void listRef.current?.scrollToOffset({
297
offset: Platform.OS === "ios" ? -insets.top : 0,
298
animated: false,
apps/mobile/src/features/pull-requests/pullRequestList.test.ts
+30
@@ -12,8 +12,10 @@ import {
12
mergePullRequestListEntries,
13
mergeEnvironmentPullRequestPages,
14
nextPullRequestListInput,
15
+ PR_LIST_PAGE_SIZE,
16
pullRequestListFacets,
17
pullRequestListHead,
18
+ pullRequestListInput,
19
pullRequestListReviewStatus,
20
pullRequestLabelColor,
21
scopedPullRequestListKey,
@@ -289,6 +291,11 @@ describe("mobile PR scan and filters", () => {
291
new Set(),
292
).map((row) => row.number),
293
).toEqual([1]);
294
+ expect(
295
+ filterPullRequestList(rows, DEFAULT_PR_LIST_CONTROLS, viewers, "author:@me", new Set()).map(
296
+ (row) => row.number,
297
+ ),
298
+ ).toEqual([1]);
299
});
300
it("combines label groups, exclusions, draft and review filters", () => {
301
const rows = [
@@ -314,6 +321,29 @@ describe("mobile PR scan and filters", () => {
321
),
322
).toEqual([1]);
323
});
324
+ it("reads a typed draft qualifier as a filter and searches only the text left over", () => {
325
+ expect(pullRequestListInput(DEFAULT_PR_LIST_CONTROLS, "draft:false fix")).toEqual({
326
+ state: "open",
327
+ involvement: "all",
328
+ filters: { draft: "hide" },
329
+ limit: PR_LIST_PAGE_SIZE,
330
+ query: "fix",
331
+ });
332
+ const rows = [
333
+ entry(1, { title: "Fix parser" }),
334
+ entry(2, { title: "Fix drafts", isDraft: true }),
335
+ entry(3),
336
+ ];
337
+ expect(
338
+ filterPullRequestList(
339
+ rows,
340
+ DEFAULT_PR_LIST_CONTROLS,
341
+ {},
342
+ "draft:false fix",
343
+ new Set(["github.com"]),
344
+ ).map((row) => row.number),
345
+ ).toEqual([1]);
346
+ });
347
it("does not label unsupported review summaries as reviewed or match text locally on host-search results", () => {
348
expect(
349
filterPullRequestList(
apps/mobile/src/features/pull-requests/pullRequestList.ts
+28
-9
@@ -1,8 +1,11 @@
1
-import type {
2
- EnvironmentId,
3
- PullRequestListEntry,
4
- PullRequestListInput,
5
- PullRequestListResult,
1
+import { parsePullRequestQuery } from "@t3tools/client-runtime/pull-request-query";
2
+import {
3
+ ProjectId,
4
+ resolvePullRequestAuthorFilter,
5
+ type EnvironmentId,
6
+ type PullRequestListEntry,
7
+ type PullRequestListInput,
8
+ type PullRequestListResult,
9
} from "@t3tools/contracts";
10
import type { PullRequestListControls } from "../../persistence/mobile-preferences";
11
@@ -138,6 +141,21 @@ export function pullRequestListHead(
141
};
142
}
143
144
+export function pullRequestListInput(
145
+ controls: PullRequestListControls,
146
+ query: string,
147
+): PullRequestListInput {
148
+ const parsed = parsePullRequestQuery(query);
149
+ return {
150
+ state: controls.state,
151
+ involvement: controls.involvement,
152
+ filters: { ...controls.filters, ...parsed.filters },
153
+ limit: PR_LIST_PAGE_SIZE,
154
+ ...(controls.projectId ? { projectId: ProjectId.make(controls.projectId) } : {}),
155
+ ...(parsed.text ? { query: parsed.text } : {}),
156
+ };
157
+}
158
+
159
export function nextPullRequestListInput(
160
pages: PullRequestListPages,
161
input: PullRequestListInput,
@@ -186,8 +204,9 @@ export function filterPullRequestList<
204
connectedEnvironmentIds?: ReadonlySet<string>,
205
) {
206
const normalize = (value: string) => value.toLowerCase();
189
- const words = query.toLowerCase().split(/\s+/).filter(Boolean);
190
- const { filters } = controls;
207
+ const parsed = parsePullRequestQuery(query);
208
+ const words = parsed.text.toLowerCase().split(/\s+/).filter(Boolean);
209
+ const filters = { ...controls.filters, ...parsed.filters };
210
const filtered = entries.filter((entry) => {
211
if (controls.state !== "all" && entry.state !== controls.state) return false;
212
if (controls.projectId && entry.projectId !== controls.projectId) return false;
@@ -204,8 +223,8 @@ export function filterPullRequestList<
223
if ((filters.draft === "only" && !entry.isDraft) || (filters.draft === "hide" && entry.isDraft))
224
return false;
225
if (filters.author) {
207
- const author = filters.author === "me" ? viewer : filters.author;
208
- if (!author || normalize(entry.author?.login ?? "") !== normalize(author)) return false;
226
+ const author = resolvePullRequestAuthorFilter(filters.author, viewer);
227
+ if (normalize(entry.author?.login ?? "") !== normalize(author)) return false;
228
}
229
if (filters.review && entry.reviewDecision && entry.reviewDecision !== filters.review)
230
return false;
apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
-131
@@ -19,7 +19,6 @@ import {
19
groupPullRequestsByInvolvement,
20
matchesPullRequestFilters,
21
matchesPullRequestQuery,
22
- parsePullRequestQuery,
22
pullRequestStatsBatches,
23
pullRequestStatsKeysToRequest,
24
pullRequestStatsRefreshBatches,
@@ -557,84 +556,6 @@ describe("narrowing rows by the filters a host may not have applied", () => {
556
});
557
});
558
560
-describe("reading qualifiers out of a typed query", () => {
561
- it("keeps quoted values whole and separates negation", () => {
562
- expect(parsePullRequestQuery('label:"needs design" -label:wip Fix the parser')).toEqual({
563
- text: "Fix the parser",
564
- filters: { labels: [["needs design"]], excludedLabels: ["wip"] },
565
- });
566
- });
567
-
568
- it("reads a comma-separated list as one group either name satisfies", () => {
569
- expect(parsePullRequestQuery("label:size:S,size:XS").filters.labels).toEqual([
570
- ["size:S", "size:XS"],
571
- ]);
572
- });
573
-
574
- it("keeps the spaces in a quoted name of a list, and drops an empty part", () => {
575
- expect(parsePullRequestQuery('label:"needs design","wip"').filters.labels).toEqual([
576
- ["needs design", "wip"],
577
- ]);
578
- expect(parsePullRequestQuery("label:a,,b").filters.labels).toEqual([["a", "b"]]);
579
- });
580
-
581
- it("excludes every name of a negated list", () => {
582
- expect(parsePullRequestQuery("-label:a,b").filters).toEqual({ excludedLabels: ["a", "b"] });
583
- });
584
-
585
- it("makes each label qualifier its own group, so the groups are an AND", () => {
586
- expect(parsePullRequestQuery("label:bug label:a,b").filters.labels).toEqual([
587
- ["bug"],
588
- ["a", "b"],
589
- ]);
590
- });
591
-
592
- it("reads the scalar qualifiers in GitHub's own spelling", () => {
593
- expect(
594
- parsePullRequestQuery("author:octocat DRAFT:false review:changes_requested status:failure")
595
- .filters,
596
- ).toEqual({
597
- author: "octocat",
598
- draft: "hide",
599
- review: "changes-requested",
600
- checks: "failing",
601
- });
602
- });
603
-
604
- it("leaves an unknown value and a stray colon as text, and reads an unknown key as a label", () => {
605
- const parsed = parsePullRequestQuery("milestone:v2 draft:maybe status: parser");
606
- expect(parsed.filters).toEqual({ labels: [["milestone:v2"]] });
607
- expect(parsed.text).toBe("draft:maybe status: parser");
608
- });
609
-
610
- it("reads a quoted name holding a comma as the one label it is", () => {
611
- expect(parsePullRequestQuery('label:"needs,triage"').filters.labels).toEqual([
612
- ["needs,triage"],
613
- ]);
614
- expect(parsePullRequestQuery('-label:"needs,triage"').filters.excludedLabels).toEqual([
615
- "needs,triage",
616
- ]);
617
- });
618
-
619
- it("cuts a typed query back to what the contract carries", () => {
620
- const many = Array.from({ length: 14 }, (_, index) => `l${index}`).join(",");
621
- const long = "x".repeat(240);
622
- const parsed = parsePullRequestQuery(`label:${many} label:${long} author:${long}`);
623
- expect(parsed.filters.labels?.[0]).toHaveLength(10);
624
- expect(parsed.filters.labels?.[1]).toEqual(["x".repeat(200)]);
625
- expect(parsed.filters.author).toBe("x".repeat(200));
626
- });
627
-
628
- it("cuts a namespaced label after its key is prefixed on", () => {
629
- const parsed = parsePullRequestQuery(`size:${"x".repeat(240)}`);
630
- expect(parsed.filters.labels).toEqual([[`size:${"x".repeat(240)}`.slice(0, 200)]]);
631
- });
632
-
633
- it("answers an empty query with an empty everything", () => {
634
- expect(parsePullRequestQuery(" ")).toEqual({ text: "", filters: {} });
635
- });
636
-});
637
-
559
describe("resolveProjectScope", () => {
560
const projects = [{ id: "p1" }, { id: "p2" }];
561
@@ -1508,58 +1429,6 @@ describe("the server a saved selection names", () => {
1429
});
1430
});
1431
1511
-describe("colon-namespaced labels typed as a search", () => {
1512
- it("reads an unknown key as the label it almost always is", () => {
1513
- expect(parsePullRequestQuery("size:XXL").filters.labels).toEqual([["size:XXL"]]);
1514
- expect(parsePullRequestQuery("vouch:trusted").filters.labels).toEqual([["vouch:trusted"]]);
1515
- expect(parsePullRequestQuery("size:XXL").text).toBe("");
1516
- });
1517
-
1518
- it("reads the key as the namespace of every bare name in its list", () => {
1519
- expect(parsePullRequestQuery("size:S,XS").filters.labels).toEqual([["size:S", "size:XS"]]);
1520
- });
1521
-
1522
- it("leaves a name that already carries its own namespace alone", () => {
1523
- expect(parsePullRequestQuery("size:S,size:XS").filters.labels).toEqual([["size:S", "size:XS"]]);
1524
- });
1525
-
1526
- it("excludes one the same way", () => {
1527
- expect(parsePullRequestQuery("-size:XXL").filters.excludedLabels).toEqual(["size:XXL"]);
1528
- expect(parsePullRequestQuery("-size:S,XS").filters.excludedLabels).toEqual([
1529
- "size:S",
1530
- "size:XS",
1531
- ]);
1532
- });
1533
-
1534
- it("keeps a quoted token as text, which is the way back to a literal search", () => {
1535
- const parsed = parsePullRequestQuery('"size:XXL"');
1536
- expect(parsed.filters.labels).toBeUndefined();
1537
- expect(parsed.text).toBe('"size:XXL"');
1538
- });
1539
-
1540
- it("reads a hyphenated namespace as a label too", () => {
1541
- expect(parsePullRequestQuery("priority-1:high").filters.labels).toEqual([["priority-1:high"]]);
1542
- expect(parsePullRequestQuery("priority-1:high").text).toBe("");
1543
- });
1544
-
1545
- it("leaves a pasted link alone rather than naming a label after its scheme", () => {
1546
- const parsed = parsePullRequestQuery("https://github.com/pingdotgg/t3code/pull/1");
1547
- expect(parsed.filters.labels).toBeUndefined();
1548
- expect(parsed.text).toBe("https://github.com/pingdotgg/t3code/pull/1");
1549
- });
1550
-
1551
- it("mixes with the keys it does know, and with plain words", () => {
1552
- const parsed = parsePullRequestQuery("area:web draft:true wizard label:bug");
1553
- expect(parsed.filters).toEqual({ labels: [["area:web"], ["bug"]], draft: "only" });
1554
- expect(parsed.text).toBe("wizard");
1555
- });
1556
-
1557
- it("shares the ceiling with the labels typed as labels", () => {
1558
- const many = Array.from({ length: 12 }, (_, index) => `area:${index}`).join(" ");
1559
- expect(parsePullRequestQuery(many).filters.labels).toHaveLength(10);
1560
- });
1561
-});
1562
-
1432
describe("the priority groups against a paginated feed", () => {
1433
const authoredRow = (number: number, updatedAt: string) =>
1434
entry({ number, updatedAt, author: { login: "Bilal", name: null, avatarUrl: null } });
apps/web/src/components/pullRequest/pullRequestList.logic.ts
-117
@@ -136,123 +136,6 @@ function isAuthoredByViewer(entry: ScopedEntry, viewers: PullRequestViewers): bo
136
return viewer !== null && normalize(entry.author?.login) === viewer;
137
}
138
139
-const REVIEW_VALUES: Record<string, PullRequestListFilters["review"]> = {
140
- approved: "approved",
141
- changes_requested: "changes-requested",
142
- "changes-requested": "changes-requested",
143
- required: "review-required",
144
- "review-required": "review-required",
145
- none: "none",
146
-};
147
-const CHECKS_VALUES: Record<string, PullRequestListFilters["checks"]> = {
148
- success: "passing",
149
- passing: "passing",
150
- failure: "failing",
151
- failing: "failing",
152
-};
153
-
154
-const QUERY_TOKEN = /(?:[^\s"]|"[^"]*")+/g;
155
-const MAX_QUALIFIER_VALUES = 10;
156
-const MAX_QUALIFIER_LENGTH = 200;
157
-
158
-function qualifierValue(raw: string): string {
159
- return raw.replaceAll('"', "").trim();
160
-}
161
-
162
-function splitQualifierList(raw: string): string[] {
163
- if (/^\s*"[^"]*"\s*$/.test(raw)) {
164
- const whole = qualifierValue(raw);
165
- return whole.length === 0 ? [] : [whole];
166
- }
167
- return raw
168
- .split(",")
169
- .map((part) => qualifierValue(part))
170
- .filter((part) => part.length > 0);
171
-}
172
-
173
-function boundedNames(names: ReadonlyArray<string>): string[] {
174
- return names
175
- .slice(0, MAX_QUALIFIER_VALUES)
176
- .map((name) => name.slice(0, MAX_QUALIFIER_LENGTH).trim())
177
- .filter((name) => name.length > 0);
178
-}
179
-
180
-export function parsePullRequestQuery(raw: string): {
181
- readonly text: string;
182
- readonly filters: PullRequestListFilters;
183
-} {
184
- const text: string[] = [];
185
- const labels: string[][] = [];
186
- const excludedLabels: string[] = [];
187
- let author: string | undefined;
188
- let draft: PullRequestListFilters["draft"];
189
- let review: PullRequestListFilters["review"];
190
- let checks: PullRequestListFilters["checks"];
191
- for (const [token] of raw.matchAll(QUERY_TOKEN)) {
192
- const qualifier = /^(-?)([A-Za-z][A-Za-z0-9_-]*):(.*)$/.exec(token);
193
- const value = qualifier === null ? "" : qualifierValue(qualifier[3] ?? "");
194
- const negated = qualifier?.[1] === "-";
195
- switch (value.length === 0 ? "" : (qualifier?.[2]?.toLowerCase() ?? "")) {
196
- case "label": {
197
- const names = boundedNames(splitQualifierList(qualifier?.[3] ?? ""));
198
- if (names.length === 0) break;
199
- if (negated) excludedLabels.push(...names);
200
- else labels.push(names);
201
- continue;
202
- }
203
- case "author":
204
- if (negated) break;
205
- author = value.slice(0, MAX_QUALIFIER_LENGTH).trim();
206
- continue;
207
- case "draft":
208
- if (negated || (value.toLowerCase() !== "true" && value.toLowerCase() !== "false")) break;
209
- draft = value.toLowerCase() === "true" ? "only" : "hide";
210
- continue;
211
- case "review": {
212
- const decision = negated ? undefined : REVIEW_VALUES[value.toLowerCase()];
213
- if (decision === undefined) break;
214
- review = decision;
215
- continue;
216
- }
217
- case "status":
218
- case "checks": {
219
- const state = negated ? undefined : CHECKS_VALUES[value.toLowerCase()];
220
- if (state === undefined) break;
221
- checks = state;
222
- continue;
223
- }
224
- case "":
225
- break;
226
- default:
227
- if (!value.startsWith("/")) {
228
- const names = boundedNames(
229
- splitQualifierList(qualifier?.[3] ?? "").map((name) =>
230
- name.includes(":") ? name : `${qualifier?.[2] ?? ""}:${name}`,
231
- ),
232
- );
233
- if (names.length === 0) break;
234
- if (negated) excludedLabels.push(...names);
235
- else labels.push(names);
236
- continue;
237
- }
238
- }
239
- text.push(token);
240
- }
241
- return {
242
- text: text.join(" "),
243
- filters: {
244
- ...(labels.length === 0 ? {} : { labels: labels.slice(0, MAX_QUALIFIER_VALUES) }),
245
- ...(excludedLabels.length === 0
246
- ? {}
247
- : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }),
248
- ...(author === undefined ? {} : { author }),
249
- ...(draft === undefined ? {} : { draft }),
250
- ...(review === undefined ? {} : { review }),
251
- ...(checks === undefined ? {} : { checks }),
252
- },
253
- };
254
-}
255
-
139
export function matchesPullRequestQuery(entry: PullRequestListEntry, query: string): boolean {
140
const normalizedQuery = query.trim().toLowerCase();
141
if (normalizedQuery.length === 0) return true;
apps/web/src/routes/_chat.pull-requests.tsx
+21
-6
@@ -1,3 +1,7 @@
1
+import {
2
+ applyPullRequestDraftFilterChange,
3
+ parsePullRequestQuery,
4
+} from "@t3tools/client-runtime/pull-request-query";
5
import { RefreshIcon } from "~/components/ui/refresh-icon";
6
import { Spinner } from "~/components/ui/spinner";
7
import { useShortcutModifierState } from "~/shortcutModifierState";
@@ -58,7 +62,6 @@ import {
62
groupPullRequestsByInvolvement,
63
matchesPullRequestFilters,
64
matchesPullRequestQuery,
61
- parsePullRequestQuery,
65
narrowPullRequestsToFilters,
66
mergePullRequestDiffStats,
67
partitionPullRequestsWithPriority,
@@ -1631,7 +1634,9 @@ function PullRequestsRouteView() {
1634
</div>
1635
);
1636
const carriedToNothing =
1634
- showingCarried && listQuery.isPending && shownCount === 0 && typedQuery.length === 0;
1637
+ shownCount === 0 &&
1638
+ typedQuery.length === 0 &&
1639
+ (!querySettled || (showingCarried && listQuery.isPending));
1640
const listBody = (
1641
<>
1642
{!capabilityKnown ? (
@@ -1788,16 +1793,26 @@ function PullRequestsRouteView() {
1793
involvement={search.involvement}
1794
involvementOptions={INVOLVEMENT_TABS}
1795
onInvolvement={(involvement) => updateListScope({ involvement })}
1791
- filters={menuFilters}
1792
- onFilters={(next) =>
1796
+ filters={
1797
+ typedParsed.filters.draft
1798
+ ? { ...menuFilters, draft: typedParsed.filters.draft }
1799
+ : menuFilters
1800
+ }
1801
+ onFilters={(value) => {
1802
+ const { query, filters: next } = applyPullRequestDraftFilterChange(
1803
+ typedQuery,
1804
+ menuFilters,
1805
+ value,
1806
+ );
1807
updateListScope({
1808
+ ...(query === typedQuery ? {} : { q: query || undefined }),
1809
draft: next.draft,
1810
review: next.review,
1811
checks: next.checks,
1812
author: next.author,
1813
labels: next.labels?.flatMap((group) => group),
1799
- })
1800
- }
1814
+ });
1815
+ }}
1816
authorOptions={facets.authors}
1817
labelOptions={facets.labels}
1818
host={search.host}
packages/client-runtime/package.json
+4
@@ -422,6 +422,10 @@
422
"./pull-request-markdown": {
423
"types": "./src/pullRequestMarkdown.ts",
424
"default": "./src/pullRequestMarkdown.ts"
425
+ },
426
+ "./pull-request-query": {
427
+ "types": "./src/pullRequestQuery.ts",
428
+ "default": "./src/pullRequestQuery.ts"
429
}
430
},
431
"scripts": {
packages/client-runtime/src/pullRequestQuery.test.ts
new
+163
@@ -0,0 +1,163 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+import { applyPullRequestDraftFilterChange, parsePullRequestQuery } from "./pullRequestQuery.ts";
3
+
4
+describe("reading qualifiers out of a typed query", () => {
5
+ it("keeps quoted values whole and separates negation", () => {
6
+ expect(parsePullRequestQuery('label:"needs design" -label:wip Fix the parser')).toEqual({
7
+ text: "Fix the parser",
8
+ filters: { labels: [["needs design"]], excludedLabels: ["wip"] },
9
+ });
10
+ });
11
+
12
+ it("reads a comma-separated list as one group either name satisfies", () => {
13
+ expect(parsePullRequestQuery("label:size:S,size:XS").filters.labels).toEqual([
14
+ ["size:S", "size:XS"],
15
+ ]);
16
+ });
17
+
18
+ it("keeps the spaces in a quoted name of a list, and drops an empty part", () => {
19
+ expect(parsePullRequestQuery('label:"needs design","wip"').filters.labels).toEqual([
20
+ ["needs design", "wip"],
21
+ ]);
22
+ expect(parsePullRequestQuery("label:a,,b").filters.labels).toEqual([["a", "b"]]);
23
+ });
24
+
25
+ it("excludes every name of a negated list", () => {
26
+ expect(parsePullRequestQuery("-label:a,b").filters).toEqual({ excludedLabels: ["a", "b"] });
27
+ });
28
+
29
+ it("makes each label qualifier its own group, so the groups are an AND", () => {
30
+ expect(parsePullRequestQuery("label:bug label:a,b").filters.labels).toEqual([
31
+ ["bug"],
32
+ ["a", "b"],
33
+ ]);
34
+ });
35
+
36
+ it("reads the scalar qualifiers in GitHub's own spelling", () => {
37
+ expect(
38
+ parsePullRequestQuery("author:octocat DRAFT:false review:changes_requested status:failure")
39
+ .filters,
40
+ ).toEqual({
41
+ author: "octocat",
42
+ draft: "hide",
43
+ review: "changes-requested",
44
+ checks: "failing",
45
+ });
46
+ });
47
+
48
+ it("leaves an unknown value and a stray colon as text, and reads an unknown key as a label", () => {
49
+ const parsed = parsePullRequestQuery("milestone:v2 draft:maybe status: parser");
50
+ expect(parsed.filters).toEqual({ labels: [["milestone:v2"]] });
51
+ expect(parsed.text).toBe("draft:maybe status: parser");
52
+ });
53
+
54
+ it("reads a quoted name holding a comma as the one label it is", () => {
55
+ expect(parsePullRequestQuery('label:"needs,triage"').filters.labels).toEqual([
56
+ ["needs,triage"],
57
+ ]);
58
+ expect(parsePullRequestQuery('label:"needs,triage",wip').filters.labels).toEqual([
59
+ ["needs,triage", "wip"],
60
+ ]);
61
+ expect(parsePullRequestQuery('-label:"needs,triage"').filters.excludedLabels).toEqual([
62
+ "needs,triage",
63
+ ]);
64
+ });
65
+
66
+ it("cuts a typed query back to what the contract carries", () => {
67
+ const many = Array.from({ length: 14 }, (_, index) => `l${index}`).join(",");
68
+ const long = "x".repeat(240);
69
+ const parsed = parsePullRequestQuery(`label:${many} label:${long} author:${long}`);
70
+ expect(parsed.filters.labels?.[0]).toHaveLength(10);
71
+ expect(parsed.filters.labels?.[1]).toEqual(["x".repeat(200)]);
72
+ expect(parsed.filters.author).toBe("x".repeat(200));
73
+ });
74
+
75
+ it("cuts a namespaced label after its key is prefixed on", () => {
76
+ const parsed = parsePullRequestQuery(`size:${"x".repeat(240)}`);
77
+ expect(parsed.filters.labels).toEqual([[`size:${"x".repeat(240)}`.slice(0, 200)]]);
78
+ });
79
+
80
+ it("answers an empty query with an empty everything", () => {
81
+ expect(parsePullRequestQuery(" ")).toEqual({ text: "", filters: {} });
82
+ });
83
+});
84
+
85
+describe("colon-namespaced labels typed as a search", () => {
86
+ it("reads an unknown key as the label it almost always is", () => {
87
+ expect(parsePullRequestQuery("size:XXL").filters.labels).toEqual([["size:XXL"]]);
88
+ expect(parsePullRequestQuery("vouch:trusted").filters.labels).toEqual([["vouch:trusted"]]);
89
+ expect(parsePullRequestQuery("size:XXL").text).toBe("");
90
+ });
91
+
92
+ it("reads the key as the namespace of every bare name in its list", () => {
93
+ expect(parsePullRequestQuery("size:S,XS").filters.labels).toEqual([["size:S", "size:XS"]]);
94
+ });
95
+
96
+ it("leaves a name that already carries its own namespace alone", () => {
97
+ expect(parsePullRequestQuery("size:S,size:XS").filters.labels).toEqual([["size:S", "size:XS"]]);
98
+ });
99
+
100
+ it("excludes one the same way", () => {
101
+ expect(parsePullRequestQuery("-size:XXL").filters.excludedLabels).toEqual(["size:XXL"]);
102
+ expect(parsePullRequestQuery("-size:S,XS").filters.excludedLabels).toEqual([
103
+ "size:S",
104
+ "size:XS",
105
+ ]);
106
+ });
107
+
108
+ it("keeps a quoted token as text, which is the way back to a literal search", () => {
109
+ const parsed = parsePullRequestQuery('"size:XXL"');
110
+ expect(parsed.filters.labels).toBeUndefined();
111
+ expect(parsed.text).toBe('"size:XXL"');
112
+ });
113
+
114
+ it("reads a hyphenated namespace as a label too", () => {
115
+ expect(parsePullRequestQuery("priority-1:high").filters.labels).toEqual([["priority-1:high"]]);
116
+ expect(parsePullRequestQuery("priority-1:high").text).toBe("");
117
+ });
118
+
119
+ it("leaves a pasted link alone rather than naming a label after its scheme", () => {
120
+ const parsed = parsePullRequestQuery("https://github.com/pingdotgg/t3code/pull/1");
121
+ expect(parsed.filters.labels).toBeUndefined();
122
+ expect(parsed.text).toBe("https://github.com/pingdotgg/t3code/pull/1");
123
+ });
124
+
125
+ it("mixes with the keys it does know, and with plain words", () => {
126
+ const parsed = parsePullRequestQuery("area:web draft:true wizard label:bug");
127
+ expect(parsed.filters).toEqual({ labels: [["area:web"], ["bug"]], draft: "only" });
128
+ expect(parsed.text).toBe("wizard");
129
+ });
130
+
131
+ it("shares the ceiling with the labels typed as labels", () => {
132
+ const many = Array.from({ length: 12 }, (_, index) => `area:${index}`).join(" ");
133
+ expect(parsePullRequestQuery(many).filters.labels).toHaveLength(10);
134
+ });
135
+});
136
+
137
+describe("changing the draft menu after typing a qualifier", () => {
138
+ it("replaces or clears a typed draft qualifier and keeps the rest of the query", () => {
139
+ expect(
140
+ applyPullRequestDraftFilterChange(
141
+ 'draft:false fix label:"needs design"',
142
+ {},
143
+ { draft: "only" },
144
+ ),
145
+ ).toEqual({ query: 'fix label:"needs design"', filters: { draft: "only" } });
146
+ expect(
147
+ applyPullRequestDraftFilterChange('draft:true "draft:false" fix', { draft: "only" }, {}),
148
+ ).toEqual({
149
+ query: '"draft:false" fix',
150
+ filters: {},
151
+ });
152
+ });
153
+
154
+ it("keeps the typed query and the stored menu draft when another filter changes", () => {
155
+ expect(
156
+ applyPullRequestDraftFilterChange(
157
+ "draft:false fix",
158
+ { draft: "only" },
159
+ { draft: "hide", checks: "passing" },
160
+ ),
161
+ ).toEqual({ query: "draft:false fix", filters: { draft: "only", checks: "passing" } });
162
+ });
163
+});
packages/client-runtime/src/pullRequestQuery.ts
new
+137
@@ -0,0 +1,137 @@
1
+import type { PullRequestListFilters } from "@t3tools/contracts";
2
+
3
+const REVIEW_VALUES: Record<string, PullRequestListFilters["review"]> = {
4
+ approved: "approved",
5
+ changes_requested: "changes-requested",
6
+ "changes-requested": "changes-requested",
7
+ required: "review-required",
8
+ "review-required": "review-required",
9
+ none: "none",
10
+};
11
+const CHECKS_VALUES: Record<string, PullRequestListFilters["checks"]> = {
12
+ success: "passing",
13
+ passing: "passing",
14
+ failure: "failing",
15
+ failing: "failing",
16
+};
17
+
18
+const QUERY_TOKEN = /(?:[^\s"]|"[^"]*")+/g;
19
+const MAX_QUALIFIER_VALUES = 10;
20
+const MAX_QUALIFIER_LENGTH = 200;
21
+
22
+function qualifierValue(raw: string): string {
23
+ return raw.replaceAll('"', "").trim();
24
+}
25
+
26
+function splitQualifierList(raw: string): string[] {
27
+ return (raw.match(/(?:[^,"]|"[^"]*")+/g) ?? [])
28
+ .map((part) => qualifierValue(part))
29
+ .filter((part) => part.length > 0);
30
+}
31
+
32
+function boundedNames(names: ReadonlyArray<string>): string[] {
33
+ return names
34
+ .slice(0, MAX_QUALIFIER_VALUES)
35
+ .map((name) => name.slice(0, MAX_QUALIFIER_LENGTH).trim())
36
+ .filter((name) => name.length > 0);
37
+}
38
+
39
+export function parsePullRequestQuery(raw: string): {
40
+ readonly text: string;
41
+ readonly filters: PullRequestListFilters;
42
+} {
43
+ const text: string[] = [];
44
+ const labels: string[][] = [];
45
+ const excludedLabels: string[] = [];
46
+ let author: string | undefined;
47
+ let draft: PullRequestListFilters["draft"];
48
+ let review: PullRequestListFilters["review"];
49
+ let checks: PullRequestListFilters["checks"];
50
+ for (const [token] of raw.matchAll(QUERY_TOKEN)) {
51
+ const qualifier = /^(-?)([A-Za-z][A-Za-z0-9_-]*):(.*)$/.exec(token);
52
+ const value = qualifier === null ? "" : qualifierValue(qualifier[3] ?? "");
53
+ const negated = qualifier?.[1] === "-";
54
+ switch (value.length === 0 ? "" : (qualifier?.[2]?.toLowerCase() ?? "")) {
55
+ case "label": {
56
+ const names = boundedNames(splitQualifierList(qualifier?.[3] ?? ""));
57
+ if (names.length === 0) break;
58
+ if (negated) excludedLabels.push(...names);
59
+ else labels.push(names);
60
+ continue;
61
+ }
62
+ case "author":
63
+ if (negated) break;
64
+ author = value.slice(0, MAX_QUALIFIER_LENGTH).trim();
65
+ continue;
66
+ case "draft":
67
+ if (negated || (value.toLowerCase() !== "true" && value.toLowerCase() !== "false")) break;
68
+ draft = value.toLowerCase() === "true" ? "only" : "hide";
69
+ continue;
70
+ case "review": {
71
+ const decision = negated ? undefined : REVIEW_VALUES[value.toLowerCase()];
72
+ if (decision === undefined) break;
73
+ review = decision;
74
+ continue;
75
+ }
76
+ case "status":
77
+ case "checks": {
78
+ const state = negated ? undefined : CHECKS_VALUES[value.toLowerCase()];
79
+ if (state === undefined) break;
80
+ checks = state;
81
+ continue;
82
+ }
83
+ case "":
84
+ break;
85
+ default:
86
+ if (!value.startsWith("/")) {
87
+ const names = boundedNames(
88
+ splitQualifierList(qualifier?.[3] ?? "").map((name) =>
89
+ name.includes(":") ? name : `${qualifier?.[2] ?? ""}:${name}`,
90
+ ),
91
+ );
92
+ if (names.length === 0) break;
93
+ if (negated) excludedLabels.push(...names);
94
+ else labels.push(names);
95
+ continue;
96
+ }
97
+ }
98
+ text.push(token);
99
+ }
100
+ return {
101
+ text: text.join(" "),
102
+ filters: {
103
+ ...(labels.length === 0 ? {} : { labels: labels.slice(0, MAX_QUALIFIER_VALUES) }),
104
+ ...(excludedLabels.length === 0
105
+ ? {}
106
+ : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }),
107
+ ...(author === undefined ? {} : { author }),
108
+ ...(draft === undefined ? {} : { draft }),
109
+ ...(review === undefined ? {} : { review }),
110
+ ...(checks === undefined ? {} : { checks }),
111
+ },
112
+ };
113
+}
114
+
115
+/**
116
+ * The Draft menu shows a typed `draft:` qualifier, so picking another value has to take the
117
+ * qualifier out of the query: left in, it would keep outranking whatever the menu stores.
118
+ */
119
+export function applyPullRequestDraftFilterChange(
120
+ query: string,
121
+ menuFilters: PullRequestListFilters,
122
+ next: PullRequestListFilters,
123
+) {
124
+ const typedDraft = parsePullRequestQuery(query).filters.draft;
125
+ if (next.draft === (typedDraft ?? menuFilters.draft))
126
+ return { query, filters: { ...next, draft: menuFilters.draft } };
127
+ return {
128
+ query:
129
+ typedDraft === undefined
130
+ ? query
131
+ : [...query.matchAll(QUERY_TOKEN)]
132
+ .map(([token]) => token)
133
+ .filter((token) => parsePullRequestQuery(token).filters.draft === undefined)
134
+ .join(" "),
135
+ filters: next,
136
+ };
137
+}