~james/core

core/web/src/lib/ticketQuery.ts -rw-r--r-- 10.9 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import { normalizeHandle } from "#lib/handle.ts";

export type TicketState = "open" | "closed" | "completed";

export interface QueryValue {
	text: string;
	quoted: boolean;
	start: number;
	end: number;
}

interface TokenBase {
	negated: boolean;
	/** the full token with the minus sign */
	start: number;
	end: number;
}

export type QueryToken =
	| (TokenBase & { kind: "word"; text: string })
	| (TokenBase & { kind: "phrase"; text: string })
	| (TokenBase & {
			kind: "qualifier";
			key: string;
			/** the end of the key and the colon */
			keyEnd: number;
			values: QueryValue[];
			known: boolean;
	  });

export const QUALIFIERS = ["is", "label", "author", "sort"] as const;
export type QualifierKey = (typeof QUALIFIERS)[number];

const isSpace = (ch: string | undefined) => ch !== undefined && /\s/.test(ch);

/** a phrase without a closing quote goes to the end */
const scanPhrase = (input: string, at: number): { text: string; end: number } => {
	let i = at + 1;
	let text = "";
	while (i < input.length) {
		const ch = input[i];
		if (ch === "\\") {
			if (i + 1 < input.length) {
				text += input[i + 1];
				i += 2;
			} else {
				text += ch;
				i += 1;
			}
			continue;
		}
		if (ch === '"') return { text, end: i + 1 };
		text += ch;
		i += 1;
	}
	return { text, end: i };
};

const scanValues = (input: string, at: number): { values: QueryValue[]; end: number } => {
	const values: QueryValue[] = [];
	let i = at;
	for (;;) {
		if (input[i] === '"') {
			const phrase = scanPhrase(input, i);
			values.push({ text: phrase.text, quoted: true, start: i, end: phrase.end });
			i = phrase.end;
		} else {
			let j = i;
			while (j < input.length && !isSpace(input[j]) && input[j] !== ",") j += 1;
			values.push({ text: input.slice(i, j), quoted: false, start: i, end: j });
			i = j;
		}
		if (input[i] !== ",") return { values, end: i };
		i += 1;
	}
};

const KEY = /^[A-Za-z_]+:/;

export const tokenize = (
	input: string,
	qualifiers: readonly string[] = QUALIFIERS
): QueryToken[] => {
	const tokens: QueryToken[] = [];
	let i = 0;
	while (i < input.length) {
		if (isSpace(input[i])) {
			i += 1;
			continue;
		}
		const start = i;
		const negated = input[i] === "-" && i + 1 < input.length && !isSpace(input[i + 1]);
		const body = negated ? i + 1 : i;
		if (input[body] === '"') {
			const phrase = scanPhrase(input, body);
			tokens.push({ kind: "phrase", negated, start, end: phrase.end, text: phrase.text });
			i = phrase.end;
			continue;
		}
		const key = KEY.exec(input.slice(body))?.[0];
		if (key) {
			const name = key.slice(0, -1).toLowerCase();
			const { values, end } = scanValues(input, body + key.length);
			tokens.push({
				kind: "qualifier",
				negated,
				start,
				end,
				key: name,
				keyEnd: body + key.length,
				values,
				known: qualifiers.includes(name)
			});
			i = end;
			continue;
		}
		let end = body;
		while (end < input.length && !isSpace(input[end])) end += 1;
		tokens.push({ kind: "word", negated, start, end, text: input.slice(body, end) });
		i = end;
	}
	return tokens;
};

const STATE_VALUES: Record<string, TicketState> = {
	open: "open",
	closed: "closed",
	completed: "completed",
	merged: "completed"
};
export const SORT_VALUES = new Set([
	"relevance",
	"best-match",
	"created-desc",
	"created",
	"newest",
	"created-asc",
	"oldest"
]);
/** the problem with a value or null if the value is valid */
export const valueProblem = (key: QualifierKey, value: string): string | null => {
	const v = value.trim().toLowerCase();
	if (v === "") return `\`${key}:\` needs a value`;
	const ok = (() => {
		switch (key) {
			case "is":
				return v in STATE_VALUES;
			case "sort":
				return SORT_VALUES.has(v);
			case "label":
			case "author":
				return true;
		}
	})();
	return ok ? null : `\`${key}:${value}\` is not valid`;
};

/** the positive states in the query or null if there are none */
export const statesOf = (query: string): TicketState[] | null => {
	const states = new Set<TicketState>();
	for (const token of tokenize(query)) {
		if (token.kind !== "qualifier" || token.negated) continue;
		if (token.key !== "is") continue;
		for (const value of token.values) {
			const state = STATE_VALUES[value.text.trim().toLowerCase()];
			if (state) states.add(state);
		}
	}
	return states.size > 0 ? [...states] : null;
};

/** the active tab state if the query has one state only */
export const activeState = (query: string): TicketState | null => {
	const states = statesOf(query);
	return states?.length === 1 ? states[0] : null;
};

const isStateClause = (token: QueryToken) =>
	token.kind === "qualifier" &&
	token.key === "is" &&
	token.values.some((value) => value.text.trim().toLowerCase() in STATE_VALUES);

const join = (parts: string[]) => parts.filter(Boolean).join(" ");

/** removes all state clauses and keeps the remaining text */
export const withoutStates = (query: string): string => {
	let out = "";
	let cursor = 0;
	for (const token of tokenize(query)) {
		if (!isStateClause(token)) continue;
		out += query.slice(cursor, token.start);
		cursor = token.end;
	}
	return (out + query.slice(cursor)).replace(/\s+/g, " ").trim();
};

/** the query for a state tab */
export const withState = (query: string, state: TicketState, isPull = false): string =>
	join([`is:${state === "completed" && isPull ? "merged" : state}`, withoutStates(query)]);

/** adds quotes to a value that contains spaces or commas */
export const quoteValue = (value: string): string =>
	value === "" || /[\s,"\\]/.test(value) ? `"${value.replace(/["\\]/g, "\\$&")}"` : value;

export const DEFAULT_QUERY = "is:open";

/** replaces author handles with dids and returns the handles that did not resolve */
export const resolveAuthors = async (
	query: string,
	resolve: (handle: string) => Promise<string | undefined>
): Promise<{ query: string; unresolved: string[] }> => {
	const handles = tokenize(query)
		.flatMap((token) =>
			token.kind === "qualifier" && token.key === "author" ? token.values : []
		)
		.map((value) => ({ value, handle: normalizeHandle(value.text) }))
		.filter(({ handle }) => handle !== "" && !handle.startsWith("did:"));
	const dids = await Promise.all(handles.map(({ handle }) => resolve(handle)));
	const unresolved: string[] = [];
	let out = "";
	let cursor = 0;
	handles.forEach(({ value, handle }, index) => {
		const did = dids[index];
		if (!did) {
			unresolved.push(handle);
			return;
		}
		out += query.slice(cursor, value.start) + did;
		cursor = value.end;
	});
	return { query: out + query.slice(cursor), unresolved };
};

/** reads the query from q or from the old state and label params */
export const queryFromUrl = (url: URL): string => {
	const q = url.searchParams.get("q");
	if (q !== null) return q.trim();
	const parts: string[] = [];
	const state = url.searchParams.get("state");
	parts.push(state && state in STATE_VALUES ? `is:${state}` : DEFAULT_QUERY);
	for (const label of url.searchParams.getAll("label")) parts.push(`label:${quoteValue(label)}`);
	return join(parts);
};

export const labelQuery = (name: string): string =>
	join([DEFAULT_QUERY, `label:${quoteValue(name)}`]);

/** the list link for a label */
export const labelHref = (listHref: string, name: string): string =>
	`${listHref}?q=${encodeURIComponent(labelQuery(name))}`;

export interface Suggestion {
	/** the text in the list */
	label: string;
	/** the text that replaces the range */
	insert: string;
	hint?: string;
	/** a key keeps the caret after the colon */
	kind: "key" | "value";
}

export interface Suggestions {
	from: number;
	to: number;
	items: Suggestion[];
}

export interface ValueOption {
	value: string;
	hint?: string;
}

export interface QueryDialect<K extends string = string> {
	qualifiers: readonly K[];
	hints: Readonly<Record<K, string>>;
	values(key: K, ctx: SuggestContext): ValueOption[];
	problem(key: K, value: string): string | null;
}

const KEY_HINTS: Record<QualifierKey, string> = {
	is: "state",
	label: "label name",
	author: "handle or did",
	sort: "order"
};

export interface SuggestContext {
	labels?: readonly string[];
	isPull?: boolean;
}

export const SORT_OPTIONS: ValueOption[] = [
	{ value: "newest", hint: "created, newest first" },
	{ value: "oldest", hint: "created, oldest first" },
	{ value: "relevance", hint: "best match first" }
];

const valuesFor = (key: QualifierKey, ctx: SuggestContext): ValueOption[] => {
	const states = ctx.isPull
		? [{ value: "open" }, { value: "merged" }, { value: "closed" }]
		: [{ value: "open" }, { value: "closed" }];
	switch (key) {
		case "is":
			return states;
		case "label":
			return (ctx.labels ?? []).map((value) => ({ value }));
		case "sort":
			return SORT_OPTIONS;
		case "author":
			return [];
	}
};

const MAX_SUGGESTIONS = 8;

export const TICKET_DIALECT: QueryDialect<QualifierKey> = {
	qualifiers: QUALIFIERS,
	hints: KEY_HINTS,
	values: valuesFor,
	problem: valueProblem
};

/** the suggestions for the token at the caret */
export const suggest = (
	query: string,
	caret: number,
	ctx: SuggestContext = {},
	dialect: QueryDialect = TICKET_DIALECT
): Suggestions | null => {
	const keyItem = (key: string): Suggestion => ({
		label: `${key}:`,
		insert: `${key}:`,
		hint: dialect.hints[key],
		kind: "key"
	});
	const token = tokenize(query, dialect.qualifiers).find(
		(t) => t.start <= caret && caret <= t.end
	);
	if (!token || token.kind === "phrase") {
		if (token) return null;
		return { from: caret, to: caret, items: dialect.qualifiers.map(keyItem) };
	}
	const body = token.negated ? token.start + 1 : token.start;
	if (token.kind === "word") {
		const prefix = query.slice(body, caret).toLowerCase();
		if (prefix === "" || !/^[a-z_]+$/.test(prefix)) return null;
		const items = dialect.qualifiers.filter((key) => key.startsWith(prefix)).map(keyItem);
		return items.length > 0 ? { from: body, to: token.end, items } : null;
	}
	if (!token.known || caret < token.keyEnd) return null;
	const value = token.values.find((v) => v.start <= caret && caret <= v.end);
	if (!value || value.quoted) return null;
	const prefix = query.slice(value.start, caret).toLowerCase();
	const taken = new Set(token.values.filter((v) => v !== value).map((v) => v.text.toLowerCase()));
	const items = dialect
		.values(token.key, ctx)
		.filter(
			({ value: v }) =>
				v.toLowerCase().startsWith(prefix) &&
				v.toLowerCase() !== prefix &&
				!taken.has(v.toLowerCase())
		)
		.slice(0, MAX_SUGGESTIONS)
		.map(({ value: v, hint }) => ({
			label: v,
			insert: quoteValue(v),
			hint,
			kind: "value" as const
		}));
	return items.length > 0 ? { from: value.start, to: value.end, items } : null;
};

/** applies a suggestion and returns the new text and caret */
export const accept = (
	query: string,
	suggestions: Suggestions,
	item: Suggestion
): { query: string; caret: number } => {
	const before = query.slice(0, suggestions.from);
	let after = query.slice(suggestions.to);
	let insert = item.insert;
	if (item.kind === "value") {
		if (after === "") insert += " ";
		else if (!/^[\s,]/.test(after)) after = ` ${after}`;
	}
	return { query: before + insert + after, caret: before.length + insert.length };
};