okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221apps/host: the owner's UI and the Node App Host0b3299a01

main
4.1 KiB110 linesraw
1/**
2 * Subsequence matching for the command palette.
3 *
4 * Prefix matching was the wrong tool: `mtx` should find *Monitor*, and `stg`
5 * should find *Settings*, because that is what every other launcher does and
6 * what a keyboard user's fingers already assume.
7 *
8 * Returns the matched character indices so the caller can highlight them — a
9 * fuzzy result you cannot explain is worse than no result, because the user
10 * cannot tell whether the thing they wanted was ranked low or is missing.
11 */
12
13export interface FuzzyResult {
14  /** Character indices in the haystack that the query matched. */
15  indices: number[];
16  /** Higher is better. Consecutive matches and word starts score highest. */
17  score: number;
18}
19
20const WORD_START = /[\s\-_/.]/;
21
22export function fuzzyMatch(query: string, text: string): FuzzyResult | null {
23  const q = query.toLowerCase();
24  const t = text.toLowerCase();
25  if (!q) return { indices: [], score: 0 };
26
27  let qi = 0;
28  let score = 0;
29  let lastMatch = -2;
30  const indices: number[] = [];
31
32  for (let ti = 0; ti < t.length && qi < q.length; ti += 1) {
33    if (t[ti] !== q[qi]) continue;
34
35    indices.push(ti);
36    // Consecutive characters are what make a match feel intentional.
37    if (ti === lastMatch + 1) score += 6;
38    // Starting a word is the next strongest signal.
39    if (ti === 0 || WORD_START.test(t[ti - 1])) score += 4;
40    // Earlier matches beat later ones, so the ranking follows the reading order.
41    score += Math.max(0, 3 - Math.floor(ti / 8));
42
43    lastMatch = ti;
44    qi += 1;
45  }
46
47  if (qi < q.length) return null;
48
49  // A short haystack containing the match is more likely to be the target than
50  // a long one that merely contains the same letters.
51  score += Math.max(0, 12 - Math.floor(t.length / 4));
52  return { indices, score };
53}
54
55/**
56 * Ranks a list, dropping non-matches and sorting best first.
57 *
58 * `text` returns the strings to try, best first. A label match wins outright;
59 * aliases are tried after it, so "tune" finds *Engine tuning* without the label
60 * having to be renamed to something worse. Only a label match yields highlight
61 * indices — highlighting a word the user cannot see would be confusing.
62 */
63export function rank<T>(query: string, items: T[], text: (item: T) => string[]): { item: T; indices: number[] }[] {
64  if (!query.trim()) return items.map((item) => ({ item, indices: [] }));
65  const q = query.trim();
66  const out: { item: T; indices: number[]; score: number }[] = [];
67  for (const item of items) {
68    const candidates = text(item);
69    for (let i = 0; i < candidates.length; i += 1) {
70      const hit = fuzzyMatch(q, candidates[i]);
71      if (!hit) continue;
72      // A label hit always outranks an alias hit, and later aliases rank lower.
73      const penalty = i * 40;
74      out.push({ item, indices: i === 0 ? hit.indices : [], score: hit.score - penalty });
75      break;
76    }
77  }
78  return out.sort((a, b) => b.score - a.score).map(({ item, indices }) => ({ item, indices }));
79}
80
81/**
82 * Splits a query into its scope prefix and the rest.
83 *
84 * `>` scopes to commands, `#` to conversations, `@` to workspaces — three
85 * prefixes covering everything the palette can reach, so the user does not have
86 * to read a mixed list to find the kind of thing they already know they want.
87 */
88export type Scope = 'all' | 'command' | 'session' | 'workspace';
89
90export function parseScope(raw: string): { scope: Scope; term: string } {
91  const c = raw[0];
92  if (c === '>') return { scope: 'command', term: raw.slice(1) };
93  if (c === '#') return { scope: 'session', term: raw.slice(1) };
94  if (c === '@') return { scope: 'workspace', term: raw.slice(1) };
95  return { scope: 'all', term: raw };
96}
97
98/** Renders a label with its matched characters emphasised. */
99export function highlight(label: string, indices: number[]): { text: string; hit: boolean }[] {
100  if (!indices.length) return [{ text: label, hit: false }];
101  const set = new Set(indices);
102  const parts: { text: string; hit: boolean }[] = [];
103  for (let i = 0; i < label.length; i += 1) {
104    const hit = set.has(i);
105    const last = parts[parts.length - 1];
106    if (last && last.hit === hit) last.text += label[i];
107    else parts.push({ text: label[i], hit });
108  }
109  return parts;
110}