repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Add ui terminal widget rendering

d800cec60bf20503d9912248b26e0495c87f7f5d

Oliver Krylow <o.krylow@isp-insoft.de> ·

unsigned

Browse filesCompare with HEAD

Changed files (3)

extensions/ui/__tests__/terminal-widget.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "vitest";
2 +import { osc8Link, renderUiWidget } from "../terminal-widget";
4 +describe("ui terminal widget", () => {
5 + it("renders OSC 8 links", () => {
6 + expect(osc8Link("http://127.0.0.1:123/open", "open ui")).toBe(
7 + "\u001b]8;;http://127.0.0.1:123/open\u001b\\open ui\u001b]8;;\u001b\\",
8 + );
9 + });
11 + it("renders actionable widget lines", () => {
12 + const lines = renderUiWidget({
13 + url: "http://127.0.0.1:123/?token=abc",
14 + qr: "QR",
15 + state: "connected",
16 + sessionLabel: "ui: pi-ext",
17 + clients: 1,
18 + });
20 + const text = lines.join("\n");
21 + expect(text).toContain("pi ui");
22 + expect(text).toContain("connected");
23 + expect(text).toContain("ui: pi-ext");
24 + expect(text).toContain("press ESC to cancel UI mode");
25 + expect(text).toContain("/ui off");
26 + expect(text).toContain("QR");
27 + });
28 +});

extensions/ui/qr.ts

Added
new file mode 100644
1 +import QRCode from "qrcode";
2 +import { uiError } from "./errors";
4 +export async function renderQr(url: string): Promise<string> {
5 + try {
6 + return await QRCode.toString(url, {
7 + type: "terminal",
8 + small: true,
9 + margin: 1,
10 + });
11 + } catch (cause) {
12 + throw uiError("qr_failed", "Could not render terminal QR code", {
13 + action: "Use the OSC link in the /ui widget instead.",
14 + retryable: true,
15 + cause,
16 + });
17 + }

extensions/ui/terminal-widget.ts

Added
new file mode 100644
1 +import type { UiServerState } from "./server";
3 +export type WidgetState = {
4 + url: string;
5 + qr: string;
6 + state: UiServerState | "starting" | "error";
7 + sessionLabel: string;
8 + clients: number;
9 + lastError?: string;
10 +};
12 +export function osc8Link(url: string, label: string): string {
13 + return `\u001b]8;;${url}\u001b\\${label}\u001b]8;;\u001b\\`;
16 +export function renderUiWidget(state: WidgetState): string[] {
17 + const lines = [
18 + "┏━ pi ui ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
19 + `┃ ${osc8Link(state.url, "open browser ui")}`,
20 + `┃ session: ${state.sessionLabel}`,
21 + `┃ state: ${state.state} · clients: ${state.clients}`,
22 + "┃ press ESC to cancel UI mode · run /ui off to restore terminal UI",
23 + ];
24 + if (state.lastError) lines.push(`┃ error: ${state.lastError}`);
25 + lines.push("┣━ mobile qr ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
26 + for (const line of state.qr.split(/\r?\n/).filter(Boolean)) lines.push(`┃ ${line}`);
27 + lines.push("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
28 + return lines;