Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/ephemlets/src/look.ts

Raw
import type { Theme } from "@earendil-works/pi-coding-agent";
import {
	type Color,
	mixColors,
	rgbColor,
	type TUI,
} from "@earendil-works/pi-tui";

export type IconSet = "nerd" | "unicode";
export const ICON_SETS = ["nerd", "unicode"] as const;

type IconName =
	| "checkOn"
	| "checkOff"
	| "radioOn"
	| "radioOff"
	| "unread"
	| "sent"
	| "read"
	| "save"
	| "delete"
	| "bell"
	| "now"
	| "next"
	| "edit"
	| "waiting";

/** Verified Nerd Font Material Design code points; Unicode fallbacks stay one cell wide. */
const ICONS: Record<IconSet, Record<IconName, string>> = {
	nerd: {
		checkOn: "\u{f0132}", // nf-md-checkbox_marked
		checkOff: "\u{f0131}", // nf-md-checkbox_blank_outline
		radioOn: "\u{f043e}", // nf-md-radiobox_marked
		radioOff: "\u{f043d}", // nf-md-radiobox_blank
		unread: "\u{f0150}", // nf-md-clock_outline
		sent: "\u{f012c}", // nf-md-check
		read: "\u{f012d}", // nf-md-check_all
		save: "\u{f0818}", // nf-md-content_save_outline
		delete: "\u{f09e7}", // nf-md-delete_outline
		bell: "\u{f009e}", // nf-md-bell_ring
		now: "\u{f0241}", // nf-md-flash
		next: "\u{f1164}", // nf-md-send_clock_outline
		edit: "\u{f0cb6}", // nf-md-pencil_outline
		waiting: "\u{f051f}", // nf-md-timer_sand
	},
	unicode: {
		checkOn: "☑",
		checkOff: "☐",
		radioOn: "◉",
		radioOff: "○",
		unread: "◷",
		sent: "✓",
		read: "✔",
		save: "⤓",
		delete: "✕",
		bell: "●",
		now: "↯",
		next: "⇢",
		edit: "✎",
		waiting: "⧗",
	},
};

export function icon(set: IconSet, name: IconName): string {
	return ICONS[set][name];
}

const QUERY_TIMEOUT_MS = 500;
const OSC4_REPLY =
	/^\x1b\]4;(\d+);rgb:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})(?:\x07|\x1b\\)$/i;

/** Parses one OSC 4 palette reply; channels may use 1 to 4 hex digits. */
export function parsePaletteReply(
	data: string,
): { index: number; color: Color } | undefined {
	const match = OSC4_REPLY.exec(data);
	if (!match) return undefined;
	const channel = (hex: string) =>
		Math.round((Number.parseInt(hex, 16) / (16 ** hex.length - 1)) * 255);
	return {
		index: Number(match[1]),
		color: rgbColor(
			channel(match[2] ?? "0"),
			channel(match[3] ?? "0"),
			channel(match[4] ?? "0"),
		),
	};
}
const MAX_ATTEMPTS = 3;

/**
 * Themes may name palette indices, which render with the terminal's own colors.
 * Blending needs their RGB, so ask the terminal (OSC 4) once per index.
 * Pi's TUI swallows replies while its own color query runs; unanswered indices retry later.
 */
export class Palette {
	private readonly known = new Map<number, Color>();
	private readonly attempts = new Map<number, number>();
	private readonly pending = new Set<number>();
	private stopListening: (() => void) | undefined;
	private timer: ReturnType<typeof setTimeout> | undefined;
	private readonly stopSchemeWatch: () => void;

	constructor(
		private readonly tui: TUI,
		private readonly changed: () => void,
	) {
		// A light/dark switch may change the terminal palette.
		this.stopSchemeWatch =
			tui.onTerminalColorSchemeChange?.(() => {
				this.known.clear();
				this.attempts.clear();
				this.changed();
			}) ?? (() => {});
	}

	/** RGB-capable color, or undefined while the terminal has not reported it. */
	resolve(color: Color): Color | undefined {
		if (color.kind !== "indexed") return color;
		const known = this.known.get(color.index);
		if (!known) this.ask(color.index);
		return known;
	}

	private ask(index: number): void {
		const attempts = this.attempts.get(index) ?? 0;
		if (this.pending.has(index) || attempts >= MAX_ATTEMPTS) return;
		if (!this.tui.addInputListener) return;
		this.attempts.set(index, attempts + 1);
		this.pending.add(index);
		this.stopListening ??= this.tui.addInputListener((data) => {
			const reply = parsePaletteReply(data);
			if (!reply || !this.pending.has(reply.index)) return undefined;
			this.pending.delete(reply.index);
			this.known.set(reply.index, reply.color);
			if (!this.pending.size) this.stop();
			this.changed();
			return { consume: true };
		});
		// Queries are sent after the current render, never inside its output.
		queueMicrotask(() => this.tui.terminal.write(`\x1b]4;${index};?\x1b\\`));
		clearTimeout(this.timer);
		this.timer = setTimeout(() => {
			this.pending.clear();
			this.stop();
		}, QUERY_TIMEOUT_MS);
	}

	private stop(): void {
		clearTimeout(this.timer);
		this.timer = undefined;
		this.stopListening?.();
		this.stopListening = undefined;
	}

	dispose(): void {
		this.stop();
		this.stopSchemeWatch();
	}
}

type Style = { bold?: boolean; strikethrough?: boolean };
export type Paint = (text: string, fg?: Color, style?: Style) => string;

/**
 * Semantic colors for one render: surfaces are theme backgrounds; tints blend in OKLCH
 * when both colors are known, and otherwise fall back to plain theme tokens.
 */
export class Look {
	readonly surface: Color;
	readonly band: Color;
	/** Band of fields whose answers interrupt the agent immediately. */
	readonly urgentBand: Color;
	readonly focus: Color;
	readonly focusText: Color | undefined;
	readonly hover: Color | undefined;
	readonly pill: Color;
	readonly track: Color;
	readonly text: Color;
	readonly muted: Color;
	readonly accent: Color;
	readonly onAccent: Color;
	readonly ok: Color;
	readonly warn: Color;

	constructor(
		private readonly theme: Theme,
		palette: Palette | undefined,
		readonly icons: IconSet,
	) {
		const c = theme.colors;
		this.surface = c.customMessageBg;
		this.text = c.customMessageText;
		this.muted = c.muted;
		this.accent = c.accent;
		this.ok = c.success;
		this.warn = c.warning;
		// Text on filled accents uses the surface, which contrasts in either appearance.
		this.onAccent = this.surface;
		const known = (color: Color) =>
			palette
				? palette.resolve(color)
				: color.kind === "indexed"
					? undefined
					: color;
		const blend = (a: Color, b: Color, amount: number) => {
			const x = known(a);
			const y = known(b);
			return x && y ? mixColors(x, y, amount) : undefined;
		};
		this.band = blend(this.surface, this.text, 0.06) ?? this.surface;
		this.urgentBand = blend(this.surface, this.warn, 0.16) ?? this.band;
		const focus = blend(this.surface, this.accent, 0.25);
		this.focus = focus ?? c.selectedBg;
		this.focusText = focus ? undefined : this.surface;
		this.hover = blend(this.surface, this.text, 0.08);
		this.pill = blend(this.surface, this.text, 0.1) ?? this.muted;
		this.track = blend(this.band, this.text, 0.12) ?? this.muted;
	}

	/** Paints text over a background; every segment carries its own background. */
	on(bg: Color): Paint {
		return (text, fg = this.text, style = {}) =>
			this.theme.style(text, { fg, bg, ...style });
	}

	icon(name: IconName): string {
		return icon(this.icons, name);
	}
}