Open History to see the last commit
1import type {
2 PullRequestActor,
3 PullRequestCapabilities,
4 PullRequestFilterOptions,
5 PullRequestReferenceCandidate,
6 PullRequestReferenceSigil,
7} from "@t3tools/contracts";
8
9import { replaceTextRange } from "./composerTrigger.ts";
10
11export type PullRequestComposerTrigger = {
12 readonly query: string;
13 readonly rangeStart: number;
14 readonly rangeEnd: number;
15} & (
16 | { readonly kind: "mention"; readonly sigil: "@" }
17 | { readonly kind: "reference"; readonly sigil: PullRequestReferenceSigil }
18);
19
20// Logins are ASCII, but queries also match display names and reference titles in any script.
21// Combining marks (\p{M}) attach to the letter before them, so they cannot start a query.
22const TOKEN =
23 /^(?:@([\p{L}\p{N}_][\p{L}\p{M}\p{N}_.-]*)?|([#!])([\p{L}\p{N}_-][\p{L}\p{M}\p{N}_-]*)?)$/u;
24
25/** What a pull request's host can complete; absent fields complete nothing. */
26export type PullRequestCompletionSupport = Pick<
27 PullRequestCapabilities,
28 "mentions" | "referenceSigils"
29>;
30
31/**
32 * The `@login`, `#123` or `!123` being typed at the caret, when the caret sits at its end and the
33 * host completes that sigil.
34 */
35export function detectPullRequestComposerTrigger(
36 text: string,
37 cursor: number,
38 support: PullRequestCompletionSupport,
39): PullRequestComposerTrigger | null {
40 const end = Math.max(0, Math.min(text.length, cursor));
41 const next = text[end];
42 if (next !== undefined && !/\s/.test(next)) return null;
43 let start = end;
44 while (start > 0 && !/\s/.test(text[start - 1] ?? "")) start -= 1;
45 const match = TOKEN.exec(text.slice(start, end));
46 if (!match) return null;
47 const sigil = match[2];
48 if (sigil === "#" || sigil === "!") {
49 return support.referenceSigils?.includes(sigil)
50 ? { kind: "reference", sigil, query: match[3] ?? "", rangeStart: start, rangeEnd: end }
51 : null;
52 }
53 return support.mentions === true
54 ? { kind: "mention", sigil: "@", query: match[1] ?? "", rangeStart: start, rangeEnd: end }
55 : null;
56}
57
58/** Replaces the trigger with `token` and leaves the caret past the space after it. */
59export function insertPullRequestCompletion(
60 text: string,
61 trigger: PullRequestComposerTrigger,
62 token: string,
63): { text: string; cursor: number } {
64 const followedBySpace = /[ \t]/.test(text[trigger.rangeEnd] ?? "");
65 if (!followedBySpace) {
66 return replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, `${token} `);
67 }
68 const inserted = replaceTextRange(text, trigger.rangeStart, trigger.rangeEnd, token);
69 return { ...inserted, cursor: inserted.cursor + 1 };
70}
71
72const MAX_COMPLETION_SEARCH_UNITS = 100;
73
74/** The key a debounce delays: the trigger's sigil and its host search, or `null` with no trigger. */
75export function pullRequestCompletionKey(
76 trigger: Pick<PullRequestComposerTrigger, "sigil" | "query"> | null,
77): string | null {
78 if (trigger === null) return null;
79 // Only an oversized query is composed: some hosts route on a short query's UTF-16 length.
80 const query =
81 trigger.query.length > MAX_COMPLETION_SEARCH_UNITS
82 ? trigger.query.normalize("NFC")
83 : trigger.query;
84 let end = MAX_COMPLETION_SEARCH_UNITS;
85 const before = query.charCodeAt(end - 1);
86 const after = query.charCodeAt(end);
87 if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end -= 1;
88 return `${trigger.sigil}${query.slice(0, end)}`;
89}
90
91/**
92 * The search to send for `trigger` given a debounced key. Until a key for this sigil settles, the
93 * host is asked for its unsearched list, which narrows locally, so a burst of typing sends one query.
94 */
95export function debouncedPullRequestCompletionSearch(
96 trigger: Pick<PullRequestComposerTrigger, "sigil">,
97 debouncedKey: string | null,
98): string | undefined {
99 return debouncedKey?.startsWith(trigger.sigil)
100 ? debouncedKey.slice(trigger.sigil.length) || undefined
101 : undefined;
102}
103
104/**
105 * Case-folds completion text into NFC so decomposed accents match precomposed ones; final sigma
106 * "ς" lowercases apart from "σ", so it is merged.
107 */
108export function foldPullRequestCompletionSearch(text: string): string {
109 return text.toLowerCase().normalize("NFC").replace(/ς/g, "σ");
110}
111
112export function narrowPullRequestMentions<A extends { login: string; name: string | null }>(
113 users: ReadonlyArray<A>,
114 typed: string,
115 limit: number,
116): A[] {
117 const needle = foldPullRequestCompletionSearch(typed);
118 return users
119 .filter(
120 (user) =>
121 foldPullRequestCompletionSearch(user.login).includes(needle) ||
122 (user.name !== null && foldPullRequestCompletionSearch(user.name).includes(needle)),
123 )
124 .slice(0, limit);
125}
126
127/** Candidates the typed sigil links, by number prefix or title. */
128export function narrowPullRequestReferences<
129 A extends { reference: string; number: number; title: string },
130>(
131 candidates: ReadonlyArray<A>,
132 trigger: Pick<PullRequestComposerTrigger, "sigil" | "query">,
133 limit: number,
134): A[] {
135 const needle = foldPullRequestCompletionSearch(trigger.query);
136 return candidates
137 .filter(
138 (candidate) =>
139 candidate.reference.startsWith(trigger.sigil) &&
140 (String(candidate.number).startsWith(needle) ||
141 foldPullRequestCompletionSearch(candidate.title).includes(needle)),
142 )
143 .slice(0, limit);
144}
145
146export type PullRequestCompletion =
147 | { readonly kind: "mention"; readonly token: string; readonly actor: PullRequestActor }
148 | {
149 readonly kind: "reference";
150 readonly token: string;
151 readonly candidate: PullRequestReferenceCandidate;
152 };
153
154/** The host's options for `trigger`, narrowed to what is typed now. */
155export function pullRequestCompletions(
156 trigger: PullRequestComposerTrigger | null,
157 options: Pick<PullRequestFilterOptions, "authors" | "references"> | null,
158 limit: number,
159): ReadonlyArray<PullRequestCompletion> {
160 if (trigger === null) return [];
161 return trigger.kind === "mention"
162 ? narrowPullRequestMentions(options?.authors ?? [], trigger.query, limit).map((actor) => ({
163 kind: "mention",
164 token: `@${actor.login}`,
165 actor,
166 }))
167 : narrowPullRequestReferences(options?.references ?? [], trigger, limit).map((candidate) => ({
168 kind: "reference",
169 token: candidate.reference,
170 candidate,
171 }));
172}