repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/q/wizard-ui.ts

Raw
File outline
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
import {
	type Component,
	type Focusable,
	Input,
	Key,
	matchesKey,
	truncateToWidth,
	visibleWidth,
	wrapTextWithAnsi,
} from "@earendil-works/pi-tui";
import { MIN_WRAP_WIDTH, WIZARD_OVERLAY } from "./constants.js";
import type { WizardResult, WizardState } from "./types.js";

type ThemeLike = {
	fg(color: "accent" | "dim", text: string): string;
	bg(color: "selectedBg", text: string): string;
};

const HORIZONTAL_PADDING = 2;
const SECTION_RULE_WIDTH = 36;

type Choice =
	| { type: "answer"; label: string; value: string }
	| { type: "custom"; label: string }
	| { type: "fork"; label: string };

export async function runWizard(
	ctx: ExtensionCommandContext,
	state: WizardState,
): Promise<WizardResult> {
	return ctx.ui.custom<WizardResult>(
		(tui, theme, _kb, done) =>
			new WizardComponent(state, theme, done, () => tui.requestRender()),
		WIZARD_OVERLAY,
	);
}

class WizardComponent implements Component, Focusable {
	private selected = 0;
	private mode: "select" | "custom" = "select";
	private input = new Input();
	private cachedWidth?: number;
	private cachedLines?: string[];
	private _focused = false;

	constructor(
		private state: WizardState,
		private theme: ThemeLike,
		private done: (result: WizardResult) => void,
		private requestRender: () => void,
	) {
		this.input.onSubmit = (value) => this.accept(value.trim());
		this.input.onEscape = () => this.setMode("select");
	}

	get focused(): boolean {
		return this._focused;
	}
	set focused(value: boolean) {
		this._focused = value;
		this.input.focused = value && this.mode === "custom";
	}

	handleInput(data: string): void {
		if (this.mode === "custom") {
			this.input.handleInput(data);
			this.invalidateAndRender();
			return;
		}
		this.handleSelectionInput(data);
	}

	render(width: number): string[] {
		if (this.cachedWidth === width && this.cachedLines) return this.cachedLines;
		const contentWidth = innerWidth(width);
		const lines = [
			"",
			...this.renderQuestion(contentWidth),
			"",
			...this.renderAnswerArea(contentWidth),
			"",
			inset(
				this.theme.fg("dim", "↑↓ select • enter confirm • esc cancel"),
				width,
			),
			"",
		];
		this.cachedWidth = width;
		this.cachedLines = lines.map((line) => truncateToWidth(line, width));
		return this.cachedLines;
	}

	invalidate(): void {
		this.cachedWidth = undefined;
		this.cachedLines = undefined;
		this.input.invalidate();
	}

	private handleSelectionInput(data: string): void {
		if (matchesKey(data, Key.escape)) return this.done({ type: "cancel" });
		if (matchesKey(data, Key.up)) return this.move(-1);
		if (matchesKey(data, Key.down)) return this.move(1);
		if (matchesKey(data, Key.enter)) return this.choose();
	}

	private move(delta: number): void {
		this.selected = clamp(this.selected + delta, 0, this.choices().length - 1);
		this.invalidateAndRender();
	}

	private choose(): void {
		const choice = this.choices()[this.selected];
		if (!choice) return;
		if (choice.type === "answer") return this.accept(choice.value);
		if (choice.type === "fork")
			return this.done({ type: "fork", state: this.state });
		this.setMode("custom");
	}

	private setMode(mode: "select" | "custom"): void {
		this.mode = mode;
		this.input.setValue("");
		this.input.focused = this.focused && mode === "custom";
		this.invalidateAndRender();
	}

	private accept(answer: string): void {
		if (!answer) return;
		this.state.answers[this.state.index] = answer;
		this.state.index++;
		this.selected = 0;
		this.mode = "select";
		this.input.setValue("");
		if (this.state.index >= this.state.questions.length)
			this.done({ type: "complete", state: this.state });
		else this.invalidateAndRender();
	}

	private renderQuestion(width: number): string[] {
		const question = this.state.questions[this.state.index]?.question ?? "";
		return [
			inset(
				this.theme.fg(
					"accent",
					`Question ${this.state.index + 1}/${this.state.questions.length}`,
				),
				width,
			),
			inset(this.theme.fg("dim", rule(width)), width),
			...wrapTextWithAnsi(question, Math.max(MIN_WRAP_WIDTH, width)).map(
				(line) => inset(line, width),
			),
		];
	}

	private renderAnswerArea(width: number): string[] {
		return this.mode === "custom"
			? this.renderCustomInput(width)
			: this.renderChoices(width);
	}

	private renderCustomInput(width: number): string[] {
		return [
			inset(this.theme.fg("accent", "Answer"), width),
			inset(this.theme.fg("dim", rule(width)), width),
			...this.input.render(width).map((line) => inset(line, width)),
			inset(
				this.theme.fg(
					"dim",
					"type answer inline • enter accepts • esc returns",
				),
				width,
			),
		];
	}

	private renderChoices(width: number): string[] {
		return [
			inset(this.theme.fg("accent", "Answers"), width),
			inset(this.theme.fg("dim", rule(width)), width),
			...this.choices().map((choice, i) => this.renderChoice(choice, i, width)),
		];
	}

	private renderChoice(choice: Choice, index: number, width: number): string {
		const prefix = index === this.selected ? "› " : "  ";
		const icon =
			choice.type === "fork" ? "↪ " : choice.type === "custom" ? "✎ " : "";
		const line = truncateToWidth(prefix + icon + choice.label, width);
		const padded =
			index === this.selected
				? this.theme.bg("selectedBg", padVisible(line, width))
				: line;
		return inset(padded, width);
	}

	private choices(): Choice[] {
		const suggestions =
			this.state.questions[this.state.index]?.suggestions ?? [];
		return [
			...suggestions.map((s) => ({
				type: "answer" as const,
				label: s,
				value: s,
			})),
			{ type: "custom" as const, label: "custom answer" },
			{ type: "fork" as const, label: "discuss answer in fork" },
		];
	}

	private invalidateAndRender(): void {
		this.invalidate();
		this.requestRender();
	}
}

function clamp(value: number, min: number, max: number): number {
	return Math.min(max, Math.max(min, value));
}

function innerWidth(width: number): number {
	return Math.max(MIN_WRAP_WIDTH, width - HORIZONTAL_PADDING * 2);
}

function inset(text: string, width: number): string {
	return (
		" ".repeat(HORIZONTAL_PADDING) +
		truncateToWidth(text, width - HORIZONTAL_PADDING)
	);
}

function rule(width: number): string {
	return "─".repeat(Math.min(SECTION_RULE_WIDTH, width));
}

function padVisible(text: string, width: number): string {
	return text + " ".repeat(Math.max(0, width - visibleWidth(text)));
}