repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/runtime.ts

Raw
File outline
import { chooseLanAddress } from "./network";
import { openBrowser } from "./open";
import { renderQr } from "./qr";
import { startUiServer, type UiServer, type UiServerState } from "./server";
import { renderUiWidget } from "./terminal-widget";

export type UiRuntimeStatus = {
	active: boolean;
	url?: string;
	state: UiServerState | "starting" | "stopped" | "error";
	clients: number;
	lastError?: string;
};

export type UiRuntime = {
	status(): UiRuntimeStatus;
	widgetLines(): string[];
	redrawQr(): Promise<void>;
	open(): Promise<void>;
	stop(reason: string): Promise<void>;
};

export type CreateUiRuntimeOptions = {
	sessionLabel: string;
	address?: string;
	preferredPort?: number;
	openBrowser?: boolean;
	onChange?: () => void;
};

export async function createUiRuntime(
	options: CreateUiRuntimeOptions,
): Promise<UiRuntime> {
	let state: UiRuntimeStatus = { active: false, state: "starting", clients: 0 };
	let qr = "";
	let server: UiServer | undefined;

	const address = options.address ?? chooseLanAddress();
	server = await startUiServer({
		address,
		preferredPort: options.preferredPort,
		onClientState: () => {
			state = currentStatus();
			options.onChange?.();
		},
	});
	qr = await renderQr(server.publicUrl);
	state = currentStatus();
	if (options.openBrowser !== false) await openBrowser(server.publicUrl);

	function currentStatus(): UiRuntimeStatus {
		if (!server) return { active: false, state: "stopped", clients: 0 };
		return {
			active: server.state() !== "stopped",
			url: server.publicUrl,
			state: server.state(),
			clients: server.clients(),
		};
	}

	return {
		status: () => state,
		widgetLines: () => {
			if (!server || !state.url) return [];
			return renderUiWidget({
				url: state.url,
				qr,
				state: state.state,
				sessionLabel: options.sessionLabel,
				clients: state.clients,
				lastError: state.lastError,
			});
		},
		async redrawQr() {
			if (!server) return;
			qr = await renderQr(server.publicUrl);
			state = currentStatus();
			options.onChange?.();
		},
		async open() {
			if (!server) return;
			await openBrowser(server.publicUrl);
		},
		async stop(reason: string) {
			const current = server;
			server = undefined;
			state = { active: false, state: "stopped", clients: 0 };
			options.onChange?.();
			if (current) await current.close(reason);
		},
	};
}