repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ui/terminal-widget.ts
RawFile outline
import path from "node:path";
import type { UiServerState } from "./server";
export type WidgetState = {
url: string;
qr: string;
state: UiServerState | "starting" | "error";
sessionLabel: string;
clients: number;
rpcState?: string;
sessionPath?: string;
lastError?: string;
};
const WIDTH = 64;
const CONTENT_WIDTH = WIDTH - 4;
const OSC8_RE = /\u001b]8;;.*?\u001b\\|\u001b]8;;\u001b\\/g;
export function osc8Link(url: string, label: string): string {
return `\u001b]8;;${url}\u001b\\${label}\u001b]8;;\u001b\\`;
}
export function renderUiWidget(state: WidgetState): string[] {
const session = state.sessionPath
? path.basename(state.sessionPath)
: "pending";
const rows = [
"pi ui",
osc8Link(state.url, "open browser ui"),
`url: ${urlWithoutParams(state.url)}`,
`session: ${state.sessionLabel}`,
`state: ${state.state} · clients: ${state.clients} · rpc: ${state.rpcState ?? "not-started"}`,
`file: ${session}`,
"press ESC to stop · /ui off · mobile QR: /ui qr",
];
if (state.lastError) rows.push(`error: ${state.lastError}`);
return [top(), ...rows.flatMap(row), bottom()];
}
function top(): string {
return `┏${"━".repeat(WIDTH - 2)}┓`;
}
function bottom(): string {
return `┗${"━".repeat(WIDTH - 2)}┛`;
}
function row(content: string): string[] {
return wrap(content).map(
(part) =>
`┃ ${part}${" ".repeat(Math.max(0, CONTENT_WIDTH - visibleLength(part)))} ┃`,
);
}
function wrap(content: string): string[] {
if (visibleLength(content) <= CONTENT_WIDTH) return [content];
const parts: string[] = [];
let rest = content;
while (visibleLength(rest) > CONTENT_WIDTH) {
parts.push(rest.slice(0, CONTENT_WIDTH));
rest = rest.slice(CONTENT_WIDTH);
}
if (rest) parts.push(rest);
return parts;
}
function visibleLength(content: string): number {
return content.replace(OSC8_RE, "").length;
}
function urlWithoutParams(value: string): string {
const url = new URL(value);
url.search = "";
url.hash = "";
return url.toString();
}