Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pullRequestComposerTrigger.ts

176 lines6.2 KB

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;
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 };
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)}`;
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;
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, and the dot lowercasing "İ" adds is dropped.
107 */
108export function foldPullRequestCompletionSearch(text: string): string {
109 return text
110 .toLowerCase()
111 .replace(/(?<=i)\u0307/g, "")
112 .normalize("NFC")
113 .replace(/ς/g, "σ");
115​
116export function narrowPullRequestMentions<A extends { login: string; name: string | null }>(
117 users: ReadonlyArray<A>,
118 typed: string,
119 limit: number,
120): A[] {
121 const needle = foldPullRequestCompletionSearch(typed);
122 return users
123 .filter(
124 (user) =>
125 foldPullRequestCompletionSearch(user.login).includes(needle) ||
126 (user.name !== null && foldPullRequestCompletionSearch(user.name).includes(needle)),
127 )
128 .slice(0, limit);
130​
131/** Candidates the typed sigil links, by number prefix or title. */
132export function narrowPullRequestReferences<
133 A extends { reference: string; number: number; title: string },
134>(
135 candidates: ReadonlyArray<A>,
136 trigger: Pick<PullRequestComposerTrigger, "sigil" | "query">,
137 limit: number,
138): A[] {
139 const needle = foldPullRequestCompletionSearch(trigger.query);
140 return candidates
141 .filter(
142 (candidate) =>
143 candidate.reference.startsWith(trigger.sigil) &&
144 (String(candidate.number).startsWith(needle) ||
145 foldPullRequestCompletionSearch(candidate.title).includes(needle)),
146 )
147 .slice(0, limit);
149​
150export type PullRequestCompletion =
151 | { readonly kind: "mention"; readonly token: string; readonly actor: PullRequestActor }
152 | {
153 readonly kind: "reference";
154 readonly token: string;
155 readonly candidate: PullRequestReferenceCandidate;
156 };
157​
158/** The host's options for `trigger`, narrowed to what is typed now. */
159export function pullRequestCompletions(
160 trigger: PullRequestComposerTrigger | null,
161 options: Pick<PullRequestFilterOptions, "authors" | "references"> | null,
162 limit: number,
163): ReadonlyArray<PullRequestCompletion> {
164 if (trigger === null) return [];
165 return trigger.kind === "mention"
166 ? narrowPullRequestMentions(options?.authors ?? [], trigger.query, limit).map((actor) => ({
167 kind: "mention",
168 token: `@${actor.login}`,
169 actor,
170 }))
171 : narrowPullRequestReferences(options?.references ?? [], trigger, limit).map((candidate) => ({
172 kind: "reference",
173 token: candidate.reference,
174 candidate,
175 }));