opencode-gh-search 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +109 -2
- package/dist/gui-experimental.cjs +67 -0
- package/package.json +45 -4
- package/src/gui.tsx +325 -0
- package/src/index.ts +498 -0
- package/src/rpc.ts +387 -0
- package/src/search.ts +162 -0
- package/src/tui.tsx +186 -0
package/src/rpc.ts
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { Rpc } from "@opencode/plugin/rpc"
|
|
2
|
+
|
|
3
|
+
export type Kind = "pr" | "issue"
|
|
4
|
+
|
|
5
|
+
/** Everything that differs between pull requests and issues. The UIs and the server read it from here. */
|
|
6
|
+
export const KINDS: Record<
|
|
7
|
+
Kind,
|
|
8
|
+
{
|
|
9
|
+
/** Slash command name. */
|
|
10
|
+
command: string
|
|
11
|
+
title: string
|
|
12
|
+
noun: string
|
|
13
|
+
plural: string
|
|
14
|
+
/** Display labels for each state, in sort order. */
|
|
15
|
+
states: Record<string, string>
|
|
16
|
+
}
|
|
17
|
+
> = {
|
|
18
|
+
pr: {
|
|
19
|
+
command: "pr",
|
|
20
|
+
title: "Pull requests",
|
|
21
|
+
noun: "pull request",
|
|
22
|
+
plural: "pull requests",
|
|
23
|
+
states: { open: "Open", draft: "Draft", merged: "Merged", closed: "Closed" },
|
|
24
|
+
},
|
|
25
|
+
issue: {
|
|
26
|
+
command: "issue",
|
|
27
|
+
title: "Issues",
|
|
28
|
+
noun: "issue",
|
|
29
|
+
plural: "issues",
|
|
30
|
+
states: { open: "Open", closed: "Closed" },
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface Repo {
|
|
35
|
+
name: string
|
|
36
|
+
dir: string
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface Resolved {
|
|
40
|
+
/** The repos to search: the session's repo, the repos matching `@short`, or every repo in the folder. */
|
|
41
|
+
repos: Repo[]
|
|
42
|
+
/** The search query left after `@short`. */
|
|
43
|
+
query: string
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A pull request or an issue. */
|
|
47
|
+
export interface Item {
|
|
48
|
+
kind: Kind
|
|
49
|
+
number: number
|
|
50
|
+
title: string
|
|
51
|
+
state: string
|
|
52
|
+
/** owner/name */
|
|
53
|
+
repo: string
|
|
54
|
+
author: string
|
|
55
|
+
url: string
|
|
56
|
+
labels: string[]
|
|
57
|
+
assignees: string[]
|
|
58
|
+
/** ISO dates. */
|
|
59
|
+
createdAt: string
|
|
60
|
+
mergedAt?: string
|
|
61
|
+
closedAt?: string
|
|
62
|
+
/** Pull requests only: the source and target branch. */
|
|
63
|
+
branch?: string
|
|
64
|
+
base?: string
|
|
65
|
+
/** Pull requests only: GitHub's review decision, and who a review is still requested from (users or team slugs). */
|
|
66
|
+
review?: "approved" | "changes_requested" | "review_required" | "none"
|
|
67
|
+
reviewers?: string[]
|
|
68
|
+
/** Pull requests only: each reviewer's latest review state (`approved`, `changes_requested`, `commented`…). */
|
|
69
|
+
reviews?: Record<string, string>
|
|
70
|
+
/** Pull requests only: which of the reviewers in `reviews` are bot accounts. */
|
|
71
|
+
bots?: string[]
|
|
72
|
+
/** Pull requests only: GitHub reported it as mergeable (`CLEAN`). Often unknown until someone opens the PR. */
|
|
73
|
+
mergeable?: boolean
|
|
74
|
+
/** Pull requests only: set when part of a stack of open PRs: position from the bottom, and the stack's size. */
|
|
75
|
+
stack?: { position: number; size: number; parent?: number }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Where the next batch starts in the sorted local results. */
|
|
79
|
+
export interface Cursor {
|
|
80
|
+
offset: number
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface Page {
|
|
84
|
+
/** owner/name of every repo searched. */
|
|
85
|
+
repos: string[]
|
|
86
|
+
items: Item[]
|
|
87
|
+
/** Matches in the local index, across all batches. */
|
|
88
|
+
total: number
|
|
89
|
+
/** A repo's index is still being synced, so results may grow. */
|
|
90
|
+
indexing: boolean
|
|
91
|
+
/** The signed-in user; an empty login if unknown. */
|
|
92
|
+
viewer: Viewer
|
|
93
|
+
/** Why a repo's index couldn't be synced. */
|
|
94
|
+
error?: string
|
|
95
|
+
next?: Cursor
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const has = (value: string | undefined, part: string) => !!value && value.toLowerCase().includes(part)
|
|
99
|
+
const same = (a: string | undefined, b: string) => !!a && a.toLowerCase() === b.toLowerCase()
|
|
100
|
+
|
|
101
|
+
/** The signed-in user, and their teams as `org/slug`. */
|
|
102
|
+
export interface Viewer {
|
|
103
|
+
login: string
|
|
104
|
+
teams: string[]
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A login filter value: `@me` is exactly you, anything else a partial login. */
|
|
108
|
+
const person = (login: string | undefined, value: string, viewer: Viewer) =>
|
|
109
|
+
value === "@me" ? same(login, viewer.login) : has(login, value)
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Whether a review is requested from you directly, or only from a team you are on. Like GitHub, a team request
|
|
113
|
+
* counts as yours until the team (or its auto-assignment) hands it to specific members.
|
|
114
|
+
*/
|
|
115
|
+
export function requested(item: Item, viewer: Viewer): "you" | "team" | "" {
|
|
116
|
+
if (!viewer.login || !item.reviewers) return ""
|
|
117
|
+
if (item.reviewers.some((r) => same(r, viewer.login))) return "you"
|
|
118
|
+
const org = item.repo.split("/")[0]
|
|
119
|
+
if (item.reviewers.some((r) => viewer.teams.some((team) => same(team, `${org}/${r}`)))) return "team"
|
|
120
|
+
return ""
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The GitHub-style `key:value` filters: which kinds they apply to, how they match, and the example shown in
|
|
125
|
+
* the search box. The single source for parsing, matching and the placeholder text.
|
|
126
|
+
*/
|
|
127
|
+
const FILTERS: Record<string, { kinds: Kind[]; example: string; test: (item: Item, value: string, viewer: Viewer) => boolean }> = {
|
|
128
|
+
author: { kinds: ["pr", "issue"], example: "author:tom", test: (item, value, viewer) => person(item.author, value, viewer) },
|
|
129
|
+
is: {
|
|
130
|
+
kinds: ["pr", "issue"],
|
|
131
|
+
example: "is:open",
|
|
132
|
+
// A prefix is enough (`is:merg`). As on GitHub, drafts are open.
|
|
133
|
+
test: (item, value) => ("open".startsWith(value) && item.state === "draft") || item.state.startsWith(value),
|
|
134
|
+
},
|
|
135
|
+
label: { kinds: ["pr", "issue"], example: "label:bug", test: (item, value) => item.labels.some((l) => has(l, value)) },
|
|
136
|
+
assignee: {
|
|
137
|
+
kinds: ["pr", "issue"],
|
|
138
|
+
example: "assignee:tom",
|
|
139
|
+
test: (item, value, viewer) => item.assignees.some((login) => person(login, value, viewer)),
|
|
140
|
+
},
|
|
141
|
+
base: { kinds: ["pr"], example: "base:main", test: (item, value) => has(item.base, value) },
|
|
142
|
+
head: { kinds: ["pr"], example: "head:feat", test: (item, value) => has(item.branch, value) },
|
|
143
|
+
// GitHub's values (`approved`, `changes_requested`, `required`, `none`), by prefix: `review:changes`.
|
|
144
|
+
review: {
|
|
145
|
+
kinds: ["pr"],
|
|
146
|
+
example: "review:approved",
|
|
147
|
+
test: (item, value) => !!item.review && (item.review.startsWith(value) || item.review.startsWith(`review_${value}`)),
|
|
148
|
+
},
|
|
149
|
+
"review-requested": {
|
|
150
|
+
kinds: ["pr"],
|
|
151
|
+
example: "review-requested:tom",
|
|
152
|
+
test: (item, value, viewer) =>
|
|
153
|
+
value === "@me" ? !!requested(item, viewer) : !!item.reviewers?.some((login) => has(login, value)),
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const ALIASES: Record<string, string> = { state: "is" }
|
|
158
|
+
|
|
159
|
+
/** The search box hint: the syntax by example. */
|
|
160
|
+
export function placeholder(kind: Kind): string {
|
|
161
|
+
const filters = Object.values(FILTERS).filter((filter) => filter.kinds.includes(kind))
|
|
162
|
+
return ["@repo", "text", "#12", ...filters.map((filter) => filter.example), "-exclude"].join(" ")
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** A search term: free text, or a `key:value` filter. A leading `-` negates it. */
|
|
166
|
+
interface Term {
|
|
167
|
+
key: string
|
|
168
|
+
value: string
|
|
169
|
+
negate: boolean
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Filters that don't apply to `kind`, and unknown ones, are searched as text. */
|
|
173
|
+
export function parseQuery(query: string, kind: Kind): Term[] {
|
|
174
|
+
return query
|
|
175
|
+
.toLowerCase()
|
|
176
|
+
.split(/\s+/)
|
|
177
|
+
.filter(Boolean)
|
|
178
|
+
.map((raw): Term => {
|
|
179
|
+
const negate = raw.length > 1 && raw.startsWith("-")
|
|
180
|
+
const word = negate ? raw.slice(1) : raw
|
|
181
|
+
const [name, ...rest] = word.split(":")
|
|
182
|
+
const key = ALIASES[name] ?? name
|
|
183
|
+
const value = rest.join(":")
|
|
184
|
+
if (value && FILTERS[key]?.kinds.includes(kind)) return { key, value, negate }
|
|
185
|
+
return { key: "text", value: word, negate }
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function test(item: Item, term: Term, viewer: Viewer): boolean {
|
|
190
|
+
if (term.key !== "text") return FILTERS[term.key].test(item, term.value, viewer)
|
|
191
|
+
const number = String(item.number)
|
|
192
|
+
if (term.value.startsWith("#")) return number.includes(term.value.slice(1))
|
|
193
|
+
return has(item.title, term.value) || (/^\d+$/.test(term.value) && number.includes(term.value))
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* How many text terms match exactly rather than partially: the whole number (`#700`, `700`), or a whole word
|
|
198
|
+
* of the title. Results with more exact matches come first, so `#700` lists #700 before #5700.
|
|
199
|
+
*/
|
|
200
|
+
export function exactness(item: Item, terms: Term[]): number {
|
|
201
|
+
const words = new Set(item.title.toLowerCase().split(/[^\p{L}\p{N}]+/u))
|
|
202
|
+
const number = String(item.number)
|
|
203
|
+
return terms.filter((term) => {
|
|
204
|
+
if (term.key !== "text" || term.negate) return false
|
|
205
|
+
const value = term.value.startsWith("#") ? term.value.slice(1) : term.value
|
|
206
|
+
return value === number || (!term.value.startsWith("#") && words.has(value))
|
|
207
|
+
}).length
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Text terms must appear in the title or number (partial matches count; `#74` only matches numbers).
|
|
212
|
+
* Repeated qualifiers of one kind are alternatives (`is:open is:draft`); different kinds must all hold.
|
|
213
|
+
* Negated terms must not match.
|
|
214
|
+
*/
|
|
215
|
+
export function matches(item: Item, terms: Term[], viewer: Viewer): boolean {
|
|
216
|
+
const any = new Map<string, boolean>()
|
|
217
|
+
for (const term of terms) {
|
|
218
|
+
const hit = test(item, term, viewer)
|
|
219
|
+
if (term.negate) {
|
|
220
|
+
if (hit) return false
|
|
221
|
+
} else if (term.key === "text") {
|
|
222
|
+
if (!hit) return false
|
|
223
|
+
} else {
|
|
224
|
+
any.set(term.key, (any.get(term.key) ?? false) || hit)
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return [...any.values()].every(Boolean)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Splits `title` into parts, marking where the query's text terms match, so the UIs can highlight them. Uses the
|
|
232
|
+
* same rules as matching: free-text words, case-insensitive, partial; filters, `#numbers` and `-excludes` aren't
|
|
233
|
+
* highlighted. A leading `@repo` is skipped.
|
|
234
|
+
*/
|
|
235
|
+
export function highlight(title: string, query: string, kind: Kind): { text: string; hit: boolean }[] {
|
|
236
|
+
const words = parseQuery(query.trim().replace(/^@\S*\s*/, ""), kind)
|
|
237
|
+
.filter((term) => term.key === "text" && !term.negate && !term.value.startsWith("#"))
|
|
238
|
+
.map((term) => term.value)
|
|
239
|
+
const lower = title.toLowerCase()
|
|
240
|
+
const marked = new Array<boolean>(title.length).fill(false)
|
|
241
|
+
for (const word of words)
|
|
242
|
+
for (let at = lower.indexOf(word); at !== -1; at = lower.indexOf(word, at + word.length))
|
|
243
|
+
marked.fill(true, at, at + word.length)
|
|
244
|
+
const parts: { text: string; hit: boolean }[] = []
|
|
245
|
+
for (let i = 0; i < title.length; i++) {
|
|
246
|
+
const last = parts[parts.length - 1]
|
|
247
|
+
if (last && last.hit === marked[i]) last.text += title[i]
|
|
248
|
+
else parts.push({ text: title[i], hit: marked[i] })
|
|
249
|
+
}
|
|
250
|
+
return parts
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Exact name, then `*-<short>`, then substring. The first tier with matches wins. */
|
|
254
|
+
export function matchRepos<T>(repos: T[], name: (repo: T) => string, short: string): T[] {
|
|
255
|
+
const s = short.toLowerCase()
|
|
256
|
+
const tiers = [
|
|
257
|
+
(n: string) => n === s,
|
|
258
|
+
(n: string) => n.endsWith(`-${s}`),
|
|
259
|
+
(n: string) => n.includes(s),
|
|
260
|
+
]
|
|
261
|
+
for (const tier of tiers) {
|
|
262
|
+
const hits = repos.filter((repo) => tier(name(repo).toLowerCase()))
|
|
263
|
+
if (hits.length > 0) return hits
|
|
264
|
+
}
|
|
265
|
+
return []
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const relative = new Intl.RelativeTimeFormat(undefined, { numeric: "auto" })
|
|
269
|
+
const units: [Intl.RelativeTimeFormatUnit, number][] = [
|
|
270
|
+
["year", 365 * 24 * 3600],
|
|
271
|
+
["month", 30 * 24 * 3600],
|
|
272
|
+
["week", 7 * 24 * 3600],
|
|
273
|
+
["day", 24 * 3600],
|
|
274
|
+
["hour", 3600],
|
|
275
|
+
["minute", 60],
|
|
276
|
+
]
|
|
277
|
+
|
|
278
|
+
/** "yesterday", "5 days ago", like GitHub. */
|
|
279
|
+
export function ago(iso: string): string {
|
|
280
|
+
const seconds = (Date.parse(iso) - Date.now()) / 1000
|
|
281
|
+
for (const [unit, size] of units) {
|
|
282
|
+
if (Math.abs(seconds) >= size) return relative.format(Math.round(seconds / size), unit)
|
|
283
|
+
}
|
|
284
|
+
return "just now"
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** GitHub's wording: what last happened to the item, and when. */
|
|
288
|
+
export function when(item: Item): string {
|
|
289
|
+
if (item.mergedAt) return `merged ${ago(item.mergedAt)}`
|
|
290
|
+
if (item.closedAt) return `closed ${ago(item.closedAt)}`
|
|
291
|
+
return item.createdAt ? `opened ${ago(item.createdAt)}` : ""
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** You opened it. */
|
|
295
|
+
export function mine(item: Item, viewer: Viewer): boolean {
|
|
296
|
+
return same(item.author, viewer.login)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* An open PR's review status, in GitHub's words, from your point of view; the first that applies wins. Only direct
|
|
301
|
+
* requests count as yours: team requests are left out, since team auto-assignment hands them to specific members.
|
|
302
|
+
* `attention` is waiting on you; `danger` is GitHub's red for changes requested; `success` needs nothing more from
|
|
303
|
+
* reviews. Ignored reviewers (bots, by default) are already left out of `reviews` by the server.
|
|
304
|
+
*/
|
|
305
|
+
export function status(item: Item, viewer: Viewer): { label: string; tone: "attention" | "danger" | "success" | "" } | undefined {
|
|
306
|
+
if (item.state !== "open" && item.state !== "draft") return undefined
|
|
307
|
+
const reviews = Object.entries(item.reviews ?? {})
|
|
308
|
+
const own = reviews.find(([login]) => same(login, viewer.login))?.[1]
|
|
309
|
+
const yours = mine(item, viewer)
|
|
310
|
+
if (requested(item, viewer) === "you") return { label: "Review requested", tone: "attention" }
|
|
311
|
+
if (item.review === "changes_requested") return { label: "Changes requested", tone: "danger" }
|
|
312
|
+
if (item.mergeable) return { label: "Ready to merge", tone: "success" }
|
|
313
|
+
if (own === "approved") return { label: "You approved", tone: "success" }
|
|
314
|
+
if (item.review === "approved") return { label: "Approved", tone: "success" }
|
|
315
|
+
// On your own PR, your comment-only "reviews" are replies; what matters is someone else commenting.
|
|
316
|
+
if (yours && reviews.some(([login, state]) => !same(login, viewer.login) && state === "commented"))
|
|
317
|
+
return { label: "Reviewed", tone: "attention" }
|
|
318
|
+
if (!yours && own === "commented") return { label: "You reviewed", tone: "" }
|
|
319
|
+
return undefined
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* The second row line: `#number · repo · author when`, e.g. `#818 · benmezger opened last week`, with the repo only
|
|
324
|
+
* when several are searched; the UIs append the stack position. Split around the author so it can be highlighted.
|
|
325
|
+
*/
|
|
326
|
+
export function meta(item: Item, many: boolean): { before: string; author: string; after: string } {
|
|
327
|
+
const join = (parts: string[]) => parts.filter(Boolean).join(" · ")
|
|
328
|
+
const before = join([`#${item.number}`, many ? item.repo.split("/").pop() ?? "" : ""])
|
|
329
|
+
const after = when(item)
|
|
330
|
+
if (!item.author) return { before: join([before, after]), author: "", after: "" }
|
|
331
|
+
return { before: `${before} · `, author: item.author, after: after ? ` ${after}` : "" }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** The empty list's message. "Searching…" only while a query is in flight; an unfinished index still says so. */
|
|
335
|
+
export function empty(plural: string, state: { error: string; searching: boolean; indexing: boolean }): string {
|
|
336
|
+
if (state.error) return state.error
|
|
337
|
+
if (state.searching) return "Searching…"
|
|
338
|
+
return state.indexing ? `No ${plural} yet, still indexing…` : `No ${plural}`
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** The header's scope line. */
|
|
342
|
+
export function scope(repos: string[], error: string): string {
|
|
343
|
+
if (repos.length === 1) return repos[0]
|
|
344
|
+
if (repos.length > 1) return `${repos.length} repositories`
|
|
345
|
+
return error ? "No repositories" : "Searching…"
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const str = { type: "string" }
|
|
349
|
+
|
|
350
|
+
export const GhSearch = Rpc.define({
|
|
351
|
+
id: "gh-search",
|
|
352
|
+
methods: {
|
|
353
|
+
resolve: {
|
|
354
|
+
input: {
|
|
355
|
+
type: "object",
|
|
356
|
+
properties: { directory: str, input: str },
|
|
357
|
+
required: ["directory", "input"],
|
|
358
|
+
additionalProperties: false,
|
|
359
|
+
},
|
|
360
|
+
output: { type: "object" },
|
|
361
|
+
},
|
|
362
|
+
search: {
|
|
363
|
+
input: {
|
|
364
|
+
type: "object",
|
|
365
|
+
properties: {
|
|
366
|
+
kind: { type: "string", enum: ["pr", "issue"] },
|
|
367
|
+
dirs: { type: "array", items: str },
|
|
368
|
+
query: str,
|
|
369
|
+
size: { type: "integer", minimum: 1, maximum: 100 },
|
|
370
|
+
cursor: { type: "object" },
|
|
371
|
+
},
|
|
372
|
+
required: ["kind", "dirs", "query", "size"],
|
|
373
|
+
additionalProperties: false,
|
|
374
|
+
},
|
|
375
|
+
output: { type: "object" },
|
|
376
|
+
errors: {
|
|
377
|
+
gh_failed: {
|
|
378
|
+
type: "object",
|
|
379
|
+
properties: { message: str },
|
|
380
|
+
required: ["message"],
|
|
381
|
+
additionalProperties: false,
|
|
382
|
+
},
|
|
383
|
+
},
|
|
384
|
+
},
|
|
385
|
+
},
|
|
386
|
+
events: {},
|
|
387
|
+
})
|
package/src/search.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import type { createSignal as CreateSignal, onCleanup as OnCleanup } from "solid-js"
|
|
2
|
+
import { GhSearch, type Cursor, type Item, type Kind, type Page, type Resolved, type Viewer } from "./rpc.js"
|
|
3
|
+
|
|
4
|
+
const DEBOUNCE_MS = 150
|
|
5
|
+
const INDEX_POLL_MS = 1500
|
|
6
|
+
|
|
7
|
+
type Client = { rpc: (contract: typeof GhSearch) => any }
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The search dialog's state, shared by the Desktop and terminal UIs: resolves `@repo`, loads batches,
|
|
11
|
+
* pages on demand and re-reads results while a repo's index is still syncing. Call inside a Solid component.
|
|
12
|
+
*
|
|
13
|
+
* Takes Solid's primitives from the caller: a TUI plugin must use the host's Solid instance, and a plain `.ts`
|
|
14
|
+
* import of `solid-js` here can resolve to a different copy whose signals the host never sees.
|
|
15
|
+
*/
|
|
16
|
+
export function createSearch(options: {
|
|
17
|
+
solid: { createSignal: typeof CreateSignal; onCleanup: typeof OnCleanup }
|
|
18
|
+
client: Client
|
|
19
|
+
kind: Kind
|
|
20
|
+
directory: string
|
|
21
|
+
initial: string
|
|
22
|
+
batch: number
|
|
23
|
+
/** Called after a new query's first batch has replaced the rows. */
|
|
24
|
+
onReset?: () => void
|
|
25
|
+
/** Called after more rows were appended. */
|
|
26
|
+
onMore?: () => void
|
|
27
|
+
}) {
|
|
28
|
+
const { createSignal, onCleanup } = options.solid
|
|
29
|
+
const gh = options.client.rpc(GhSearch)
|
|
30
|
+
const [text, setText] = createSignal(options.initial)
|
|
31
|
+
const [rows, setRows] = createSignal<Item[]>([])
|
|
32
|
+
const [repos, setRepos] = createSignal<string[]>([])
|
|
33
|
+
const [selected, setSelected] = createSignal(0)
|
|
34
|
+
const [searching, setSearching] = createSignal(false)
|
|
35
|
+
const [loadingMore, setLoadingMore] = createSignal(false)
|
|
36
|
+
const [indexing, setIndexing] = createSignal(false)
|
|
37
|
+
const [error, setError] = createSignal("")
|
|
38
|
+
const [viewer, setViewer] = createSignal<Viewer>({ login: "", teams: [] })
|
|
39
|
+
let target: { dirs: string[]; query: string } | undefined
|
|
40
|
+
let next: Cursor | undefined
|
|
41
|
+
let seq = 0
|
|
42
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
43
|
+
let poll: ReturnType<typeof setTimeout> | undefined
|
|
44
|
+
onCleanup(() => {
|
|
45
|
+
clearTimeout(timer)
|
|
46
|
+
clearTimeout(poll)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
const fetch = (size: number, cursor?: Cursor) =>
|
|
50
|
+
gh.search({ kind: options.kind, ...target!, size, ...(cursor ? { cursor } : {}) }) as Promise<Page>
|
|
51
|
+
|
|
52
|
+
async function run(value: string) {
|
|
53
|
+
const id = ++seq
|
|
54
|
+
setSearching(true)
|
|
55
|
+
setLoadingMore(false)
|
|
56
|
+
setError("")
|
|
57
|
+
try {
|
|
58
|
+
const resolved = (await gh.resolve({ directory: options.directory, input: value })) as Resolved
|
|
59
|
+
if (id !== seq) return
|
|
60
|
+
next = undefined
|
|
61
|
+
target = { dirs: resolved.repos.map((repo) => repo.dir), query: resolved.query }
|
|
62
|
+
if (resolved.repos.length === 0) {
|
|
63
|
+
setRepos([])
|
|
64
|
+
setRows([])
|
|
65
|
+
setIndexing(false)
|
|
66
|
+
setError(`No repository matches ${value.trim().split(/\s+/)[0]}`)
|
|
67
|
+
return
|
|
68
|
+
}
|
|
69
|
+
const page = await fetch(options.batch)
|
|
70
|
+
if (id !== seq) return
|
|
71
|
+
next = page.next
|
|
72
|
+
setRepos(page.repos)
|
|
73
|
+
setRows(page.items)
|
|
74
|
+
setIndexing(page.indexing)
|
|
75
|
+
setViewer(page.viewer)
|
|
76
|
+
setError(page.error ?? "")
|
|
77
|
+
setSelected(0)
|
|
78
|
+
watchIndex(id)
|
|
79
|
+
options.onReset?.()
|
|
80
|
+
} catch (e) {
|
|
81
|
+
if (id !== seq) return
|
|
82
|
+
setRows([])
|
|
83
|
+
setError(e instanceof Error ? e.message : String(e))
|
|
84
|
+
} finally {
|
|
85
|
+
if (id === seq) setSearching(false)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function more() {
|
|
90
|
+
if (!target || !next || loadingMore()) return
|
|
91
|
+
const id = seq
|
|
92
|
+
setLoadingMore(true)
|
|
93
|
+
try {
|
|
94
|
+
const page = await fetch(options.batch, next)
|
|
95
|
+
if (id !== seq) return
|
|
96
|
+
next = page.next
|
|
97
|
+
setRows((list) => [...list, ...page.items])
|
|
98
|
+
setIndexing(page.indexing)
|
|
99
|
+
setError(page.error ?? "")
|
|
100
|
+
} catch (e) {
|
|
101
|
+
if (id === seq) setError(e instanceof Error ? e.message : String(e))
|
|
102
|
+
} finally {
|
|
103
|
+
if (id === seq) setLoadingMore(false)
|
|
104
|
+
}
|
|
105
|
+
if (id === seq) options.onMore?.()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// While a repo's index is still syncing, re-read the rows already shown so newly indexed items appear.
|
|
109
|
+
function watchIndex(id: number) {
|
|
110
|
+
clearTimeout(poll)
|
|
111
|
+
if (!indexing()) return
|
|
112
|
+
poll = setTimeout(async () => {
|
|
113
|
+
if (id !== seq || !target) return
|
|
114
|
+
try {
|
|
115
|
+
const page = await fetch(Math.max(rows().length, options.batch))
|
|
116
|
+
if (id !== seq) return
|
|
117
|
+
next = page.next
|
|
118
|
+
setRows(page.items)
|
|
119
|
+
setIndexing(page.indexing)
|
|
120
|
+
setError(page.error ?? "")
|
|
121
|
+
setSelected((i) => Math.min(i, Math.max(page.items.length - 1, 0)))
|
|
122
|
+
} catch {}
|
|
123
|
+
watchIndex(id)
|
|
124
|
+
}, INDEX_POLL_MS)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function input(value: string) {
|
|
128
|
+
setText(value)
|
|
129
|
+
clearTimeout(timer)
|
|
130
|
+
timer = setTimeout(() => void run(value), DEBOUNCE_MS)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Moves the selection by `delta` rows, loading more when it nears the end. */
|
|
134
|
+
function move(delta: number, lookahead: number) {
|
|
135
|
+
const count = rows().length
|
|
136
|
+
if (!count) return
|
|
137
|
+
const index = Math.max(0, Math.min(selected() + delta, count - 1))
|
|
138
|
+
setSelected(index)
|
|
139
|
+
if (index >= count - lookahead) void more()
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
void run(options.initial)
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
text,
|
|
146
|
+
input,
|
|
147
|
+
rows,
|
|
148
|
+
repos,
|
|
149
|
+
selected,
|
|
150
|
+
setSelected,
|
|
151
|
+
move,
|
|
152
|
+
more,
|
|
153
|
+
searching,
|
|
154
|
+
loadingMore,
|
|
155
|
+
indexing,
|
|
156
|
+
error,
|
|
157
|
+
viewer,
|
|
158
|
+
hasMore: () => !!next,
|
|
159
|
+
many: () => repos().length > 1,
|
|
160
|
+
current: () => rows()[selected()] as Item | undefined,
|
|
161
|
+
}
|
|
162
|
+
}
|