Official
palette
Built-in command palette (⌘⇧P) and chat search (⌘P).
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/palette@0.2.5
Permissions in 0.2.5
Files
model.ts7.4 KB
// The palette's model: the order of what it lists, by the shared fuzzy
// matcher, and where the selection sits. Pure functions over plain
// objects, so the tests run them in Node.
import type { Chat, CommandInfo, PaletteProviderInfo, Workspace } from "divergence";
import { fuzzy } from "../sdk/ui/fuzzy.ts";
export type Command = Pick<CommandInfo, "id" | "title" | "category"> &
Partial<Pick<CommandInfo, "enabled" | "registered">>;
export type ChatEntry = Pick<Chat, "id" | "workspaceId"> & Partial<Pick<Chat, "title" | "updatedAt" | "archived">>;
export type Provider = Pick<PaletteProviderInfo, "plugin" | "id"> & Partial<Pick<PaletteProviderInfo, "prefix">>;
export type Mode<P> = { mode: "commands" | "chats"; query: string } | { mode: "provider"; provider: P; query: string };
/// How many rows the palette draws at once, and how many chats: a chat's row is two lines tall.
export const VISIBLE = 12;
export const VISIBLE_CHATS = 8;
/// How long the chat search keeps what was typed in it after it closes.
export const KEEP_FOR_MS = 30_000;
/// How many commands the palette remembers as recently run.
export const RECENT_LIMIT = 20;
/// The text a command is searched and shown by: `Category: Title`.
export function commandLabel(command: Pick<CommandInfo, "title" | "category">) {
return command.category ? `${command.category}: ${command.title}` : command.title;
}
/// The commands the palette lists for `query`: those whose `when` holds and
/// whose plugin runs, fuzzy over the title and the category; with no
/// query, recently run first, then by label.
export function rankCommands<C extends Command>(
commands: readonly C[],
query: unknown,
recent: readonly string[] = [],
) {
const shown = commands.filter((command) => command.enabled !== false && command.registered !== false);
const recency = (command: C) => {
const at = recent.indexOf(command.id);
return at < 0 ? Infinity : at;
};
if (!String(query ?? "").trim()) {
return shown
.map((command) => ({ command, positions: [] }))
.sort(
(a, b) =>
recency(a.command) - recency(b.command) || commandLabel(a.command).localeCompare(commandLabel(b.command)),
);
}
return shown
.map((command) => {
const label = commandLabel(command);
// The row shows the label, so a match in the title alone is marked
// where the title starts in it.
const inLabel = fuzzy(query, label);
const inTitle = inLabel ? null : fuzzy(query, command.title);
const offset = label.length - command.title.length;
const match = inLabel ?? (inTitle && { ...inTitle, positions: inTitle.positions.map((at) => at + offset) });
return match
? { command, positions: match.positions, score: match.score + (recency(command) < Infinity ? 3 : 0) }
: null;
})
.filter((candidate) => candidate !== null)
.sort((a, b) => b.score - a.score || recency(a.command) - recency(b.command));
}
/// The chats the palette lists for `query`, by title and workspace name:
/// first those that start with the query, then those holding each of its
/// words whole at word starts, then whole anywhere, each kind recently
/// active first; then those holding only its letters, the best matches
/// first.
export function rankChats<C extends ChatEntry>(
chats: readonly C[],
workspaces: Readonly<Record<string, Pick<Workspace, "name">>>,
query: unknown,
) {
const open = chats.filter((chat) => !chat.archived);
const name = (chat: C) => workspaces[chat.workspaceId]?.name ?? "";
const newest = (a: C, b: C) => String(b.updatedAt ?? "").localeCompare(String(a.updatedAt ?? ""));
if (!String(query ?? "").trim())
return open
.slice()
.sort(newest)
.map((chat) => ({ chat, positions: [] }));
return open
.map((chat) => {
// A longer title is no worse a match: equally good matches tie, and the newer chat comes first.
const title = fuzzy(query, chat.title ?? "", false);
const workspace = fuzzy(query, name(chat), false);
const both = fuzzy(query, `${name(chat)} ${chat.title ?? ""}`, false);
// A title that starts with the words typed is no more relevant than
// one that says them further on, so both rank as words found whole.
const best = [
title,
workspace && { ...workspace, score: workspace.score - 2, positions: [] },
both && { ...both, score: both.score - 4, positions: [] },
]
.filter((candidate) => candidate !== null)
.map((candidate) => ({ ...candidate, tier: Math.min(candidate.tier, 2) }))
.sort((a, b) => b.tier - a.tier || b.score - a.score)[0];
return best ? { chat, positions: best.positions, score: best.score, tier: best.tier } : null;
})
.filter((candidate) => candidate !== null)
// A chat holding the words typed is as relevant as another that does,
// so the newer one comes first; letters found apart are told apart by
// how well they match.
.sort((a, b) => b.tier - a.tier || (a.tier === 0 ? b.score - a.score : 0) || newest(a.chat, b.chat));
}
/// `make`, made again only when one of the values `from` reads is not the one it read last time.
export function keptWhileSame<T>(from: () => readonly unknown[], make: () => T): () => T {
let kept: { from: readonly unknown[]; value: T } | null = null;
return () => {
const now = from();
if (!kept || now.some((value, i) => value !== kept!.from[i])) kept = { from: now, value: make() };
return kept.value;
};
}
/// `recent` with `id` first, at most RECENT_LIMIT long.
export function remember(recent: readonly string[], id: string) {
return [id, ...recent.filter((known) => known !== id)].slice(0, RECENT_LIMIT);
}
/// The mode a query asks for in the chat palette (⌘P): `>` switches to
/// commands, a provider's prefix to that provider, anything else searches
/// chats. Returns `{ mode, provider?, query }` with the prefix taken off.
export function modeOf<P extends Provider>(query: unknown, providers: readonly P[] = []): Mode<P> {
const text = String(query ?? "");
if (text.startsWith(">")) return { mode: "commands", query: text.slice(1).trimStart() };
const provider = providers
.filter((p): p is P & { prefix: string } => !!p.prefix && text.startsWith(p.prefix))
.sort((a, b) => b.prefix.length - a.prefix.length)[0];
if (provider) return { mode: "provider", provider, query: text.slice(provider.prefix.length).trimStart() };
return { mode: "chats", query: text };
}
/// Moves the selection by `delta` rows, wrapping around.
export function move(selected: number, count: number, delta: number) {
if (!count) return 0;
return (((selected + delta) % count) + count) % count;
}
/// Rows the palette sends on each side of the list's top and of the
/// selection. It is more than the 150 rows the kernel lets the top come
/// near a row left out before it says where the top is (`onRange`), so the
/// kernel asks again only once the rows sent must move, and the rows come
/// before they are scrolled onto the screen.
export const SIDE = 160;
/// The rows `[lo, hi)` of `count` the palette sends: a short list whole,
/// a long one around the row at its top (`top`, from the kernel) and around
/// the selection, so the arrow keys can bring any row into view.
export function shownRows(count: number, top: number, selected: number, screen: number): [number, number] {
if (count <= 2 * SIDE + screen) return [0, count];
return [Math.max(0, Math.min(top, selected) - SIDE), Math.min(count, Math.max(top + screen, selected + 1) + SIDE)];
}
No comments yet.