/** * lost-property, in a terminal. The forge runs this on a pty when someone * `ssh`es to the app, with FORGE_APP_DATA pointing at the same data the * web page uses. j/k move, a adds a note, d deletes the one under the * cursor, q leaves. Plain ANSI, no dependencies. */ import { Database } from "bun:sqlite"; import { mkdirSync } from "node:fs"; import { join } from "node:path"; const dataDir = process.env.FORGE_APP_DATA ?? "./data"; mkdirSync(dataDir, { recursive: true }); const db = new Database(join(dataDir, "app.db")); db.exec("PRAGMA journal_mode = WAL"); db.exec( "CREATE TABLE IF NOT EXISTS note (id INTEGER PRIMARY KEY, body TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (datetime('now')))", ); const where = process.env.FORGE_APP_ENV === "preview" ? `preview of #${process.env.FORGE_APP_PULL ?? "?"}` : (process.env.FORGE_APP_ENV ?? "local"); type Note = { id: number; body: string; created_at: string }; const notes = (): Note[] => db.query("SELECT id, body, created_at FROM note ORDER BY id DESC").all(); let cursor = 0; let typing: string | undefined; const out = (s: string): void => { process.stdout.write(s); }; const esc = "\x1b["; function draw(): void { const rows = notes(); const lines: string[] = []; lines.push(`${esc}1mlost-property${esc}0m ${esc}2m${where}${esc}0m`); lines.push(""); if (rows.length === 0) lines.push(`${esc}2mNo notes yet. Press a to add one.${esc}0m`); rows.forEach((n, i) => { const mark = i === cursor ? "▸" : " "; const body = i === cursor ? `${esc}1m${n.body}${esc}0m` : n.body; lines.push(`${mark} ${body} ${esc}2m${n.created_at}${esc}0m`); }); lines.push(""); lines.push(typing === undefined ? `${esc}2mj/k move · a add · d delete · q quit${esc}0m` : `New note: ${typing}${esc}7m ${esc}0m`); out(`${esc}2J${esc}H` + lines.join("\r\n")); } process.stdin.setRawMode?.(true); process.stdin.resume(); process.stdin.setEncoding("utf8"); draw(); process.stdin.on("data", (key: string) => { if (typing !== undefined) { if (key === "\r") { const body = typing.trim(); if (body) db.query("INSERT INTO note (body) VALUES (?1)").run(body.slice(0, 500)); typing = undefined; cursor = 0; } else if (key === "\x1b") typing = undefined; else if (key === "\x7f") typing = typing.slice(0, -1); else if (key >= " ") typing += key; draw(); return; } if (key === "q" || key === "\x03") { out(`${esc}2J${esc}H`); process.exit(0); } const count = notes().length; if (key === "j" || key === "\x1b[B") cursor = Math.min(cursor + 1, Math.max(0, count - 1)); if (key === "k" || key === "\x1b[A") cursor = Math.max(cursor - 1, 0); if (key === "a") typing = ""; if (key === "d") { const n = notes()[cursor]; if (n) db.query("DELETE FROM note WHERE id = ?1").run(n.id); cursor = Math.min(cursor, Math.max(0, notes().length - 1)); } draw(); }); process.stdout.on("resize", draw);