Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
refactor(tui): share the cell and pane primitives instead of growing a second copy (#186)
Abdurrahman Fakhrul5b45314c5161
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex b9c19fa5..98944697 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -10,6 +10,10 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh- `agent` show the todo checklist in the TUI and in the status row (#179)+**Changed**++- `tui` share the cell and pane primitives instead of growing a second copy+**Tests**- `perf,api` prove the gate catches regressions, and restore the rationale the refactor droppeddiff --git a/scripts/integrations-tui/layout.mjs b/scripts/integrations-tui/layout.mjsindex d14f76b9..0c776e61 100644--- a/scripts/integrations-tui/layout.mjs+++ b/scripts/integrations-tui/layout.mjs@@ -1,67 +1,20 @@-export function stripAnsi(value) {- return String(value ?? "").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");-}-export function clean(value) {- return stripAnsi(value).replace(/[\r\n\t]+/g, " ").replace(/[\u0000-\u001f\u007f]/g, "").trim();-}-function isWide(cp) {- return cp >= 0x1100 && (cp <= 0x115f || cp === 0x2329 || cp === 0x232a ||- (cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) || (cp >= 0xac00 && cp <= 0xd7a3) ||- (cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0xfe10 && cp <= 0xfe19) ||- (cp >= 0xfe30 && cp <= 0xfe6f) || (cp >= 0xff00 && cp <= 0xff60) ||- (cp >= 0xffe0 && cp <= 0xffe6) || (cp >= 0x1f300 && cp <= 0x1faff) ||- (cp >= 0x20000 && cp <= 0x3fffd));-}-export function cellWidth(value) {- let total = 0;- for (const ch of stripAnsi(value)) {- const cp = ch.codePointAt(0) ?? 0;- if (cp === 0x200d || (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0x300 && cp <= 0x36f)) continue;- total += isWide(cp) ? 2 : 1;- }- return total;-}-export function fitCells(value, width, { pad = true } = {}) {- const text = clean(value);- if (width <= 0) return "";- let out = "", used = 0;- for (const ch of text) {- const w = cellWidth(ch);- if (used + w > width) break;- out += ch; used += w;- }- if (used < cellWidth(text) && width > 0) {- while (out && cellWidth(out) > Math.max(0, width - 1)) out = out.slice(0, -1);- out += "…"; used = cellWidth(out);- }- return pad ? out + " ".repeat(Math.max(0, width - used)) : out;-}+export {+ stripAnsi,+ clean,+ cellWidth,+ fitCells,+ paneWidths,+ border,+ paneRow,+ compose,+ windowFor,+} from "../tui/cells.mjs";+export function maxPaneCount(cols) {return cols >= 132 ? 4 : cols >= 92 ? 3 : cols >= 68 ? 2 : 1;}+export function visibleColumns(columns, cols) {const count = Math.max(1, Math.min(maxPaneCount(cols), columns.length));return columns.slice(-count);}-export function paneWidths(totalWidth, count) {- const inner = Math.max(count * 10, totalWidth - (count + 1));- const base = Math.floor(inner / count), extra = inner % count;- return Array.from({ length: count }, (_, i) => base + (i < extra ? 1 : 0));-}-export function border(widths, kind = "top") {- const chars = kind === "top" ? ["┌", "┬", "┐"] : kind === "mid" ? ["├", "┼", "┤"] : ["└", "┴", "┘"];- return chars[0] + widths.map((w) => "─".repeat(w)).join(chars[1]) + chars[2];-}-export function paneRow(cells, widths) {- return "│" + widths.map((w, i) => fitCells(cells[i] ?? "", w)).join("│") + "│";-}-export function compose(left, right, width) {- const l = clean(left), r = clean(right), gap = Math.max(1, width - cellWidth(l) - cellWidth(r));- return fitCells(`${l}${" ".repeat(gap)}${r}`, width);-}-export function windowFor(items, selected, height) {- if (items.length <= height) return { start: 0, end: items.length };- let start = Math.max(0, selected - Math.floor(height / 2));- start = Math.min(start, Math.max(0, items.length - height));- return { start, end: Math.min(items.length, start + height) };-}diff --git a/scripts/tui/cells.mjs b/scripts/tui/cells.mjsnew file mode 100644index 00000000..35909416--- /dev/null+++ b/scripts/tui/cells.mjs@@ -0,0 +1,73 @@+export function stripAnsi(value) {+ return String(value ?? "").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");+}++export function clean(value) {+ return stripAnsi(value).replace(/[\r\n\t]+/g, " ").replace(/[\u0000-\u001f\u007f]/g, "").trim();+}++function isWide(cp) {+ return cp >= 0x1100 && (cp <= 0x115f || cp === 0x2329 || cp === 0x232a ||+ (cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) || (cp >= 0xac00 && cp <= 0xd7a3) ||+ (cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0xfe10 && cp <= 0xfe19) ||+ (cp >= 0xfe30 && cp <= 0xfe6f) || (cp >= 0xff00 && cp <= 0xff60) ||+ (cp >= 0xffe0 && cp <= 0xffe6) || (cp >= 0x1f300 && cp <= 0x1faff) ||+ (cp >= 0x20000 && cp <= 0x3fffd));+}++export function cellWidth(value) {+ let total = 0;+ for (const ch of stripAnsi(value)) {+ const cp = ch.codePointAt(0) ?? 0;+ if (cp === 0x200d || (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0x300 && cp <= 0x36f)) continue;+ total += isWide(cp) ? 2 : 1;+ }+ return total;+}++export function fitCells(value, width, { pad = true } = {}) {+ const text = clean(value);+ if (width <= 0) return "";+ let out = "", used = 0;+ for (const ch of text) {+ const w = cellWidth(ch);+ if (used + w > width) break;+ out += ch; used += w;+ }+ if (used < cellWidth(text) && width > 0) {+ while (out && cellWidth(out) > Math.max(0, width - 1)) {+ // Slicing by UTF-16 code units would split surrogate pairs and leave orphaned surrogates.+ // Array.from peels by Unicode code points to preserve character integrity.+ out = Array.from(out).slice(0, -1).join("");+ }+ out += "…"; used = cellWidth(out);+ }+ return pad ? out + " ".repeat(Math.max(0, width - used)) : out;+}++export function paneWidths(totalWidth, count) {+ const inner = Math.max(count * 10, totalWidth - (count + 1));+ const base = Math.floor(inner / count), extra = inner % count;+ return Array.from({ length: count }, (_, i) => base + (i < extra ? 1 : 0));+}++export function border(widths, kind = "top") {+ const chars = kind === "top" ? ["┌", "┬", "┐"] : kind === "mid" ? ["├", "┼", "┤"] : ["└", "┴", "┘"];+ return chars[0] + widths.map((w) => "─".repeat(w)).join(chars[1]) + chars[2];+}++export function paneRow(cells, widths) {+ return "│" + widths.map((w, i) => fitCells(cells[i] ?? "", w)).join("│") + "│";+}++export function compose(left, right, width) {+ const l = clean(left), r = clean(right), gap = Math.max(1, width - cellWidth(l) - cellWidth(r));+ return fitCells(`${l}${" ".repeat(gap)}${r}`, width);+}++export function windowFor(items, selected, height) {+ if (items.length <= height) return { start: 0, end: items.length };+ let start = Math.max(0, selected - Math.floor(height / 2));+ start = Math.min(start, Math.max(0, items.length - height));+ return { start, end: Math.min(items.length, start + height) };+}diff --git a/scripts/tui/cells.test.ts b/scripts/tui/cells.test.tsnew file mode 100644index 00000000..39887325--- /dev/null+++ b/scripts/tui/cells.test.ts@@ -0,0 +1,135 @@+import { describe, expect, it } from "vitest";+import {+ border,+ cellWidth,+ clean,+ compose,+ fitCells,+ paneRow,+ paneWidths,+ stripAnsi,+ windowFor,+} from "./cells.mjs";++describe("TUI cell and pane primitives", () => {+ it("measures plain ASCII string widths", () => {+ expect(cellWidth("")).toBe(0);+ expect(cellWidth("hello")).toBe(5);+ expect(cellWidth("hello world")).toBe(11);+ expect(cellWidth(" ")).toBe(3);+ });++ it("ignores ANSI escape sequences when measuring width", () => {+ expect(cellWidth("\x1b[31mred\x1b[0m")).toBe(3);+ expect(cellWidth("\x1b[1;32mbold green\x1b[0m")).toBe(10);+ expect(cellWidth("\x1b[38;5;208morange 256\x1b[0m")).toBe(10);+ expect(cellWidth("\x1b[38;2;255;128;0mtruecolor\x1b[0m")).toBe(9);+ expect(cellWidth("\x1b[2K\x1b[?25hvisible")).toBe(7);+ expect(stripAnsi("\x1b[34mtest\x1b[0m")).toBe("test");+ });++ it("measures East Asian wide characters and zero-width codepoints accurately", () => {+ expect(cellWidth("你好世界")).toBe(8);+ expect(cellWidth("コンニチハ")).toBe(10);+ expect(cellWidth("안녕하세요")).toBe(10);+ expect(cellWidth("全角!")).toBe(6);+ expect(cellWidth("🌸")).toBe(2);+ expect(cellWidth("😀")).toBe(2);+ // Zero-width joiner, variation selectors, and combining diacritics+ expect(cellWidth("e\u0301")).toBe(1);+ expect(cellWidth("test\u200d")).toBe(4);+ expect(cellWidth("a\ufe0f")).toBe(1);+ });++ it("truncates with an ellipsis and pads to target width", () => {+ expect(fitCells("hello", 10)).toBe("hello ");+ expect(fitCells("hello", 10, { pad: false })).toBe("hello");+ expect(fitCells("hello world", 8)).toBe("hello w…");+ expect(fitCells("hello world", 5)).toBe("hell…");+ expect(fitCells("hello", 1)).toBe("…");+ expect(fitCells("hello", 0)).toBe("");+ expect(fitCells("hello", -2)).toBe("");+ });++ it("preserves surrogate pairs without splitting high/low surrogates on truncation", () => {+ // Demonstration of surrogate preservation: slicing by UTF-16 code units would+ // leave an orphaned high surrogate \ud83c. Array.from avoids splitting pairs.+ const result = fitCells("🌸🌸🌸", 4);+ expect(result).toBe("🌸… ");+ expect(cellWidth(result)).toBe(4);+ const codeUnits = Array.from({ length: result.length }, (_, i) => result.charCodeAt(i));+ const loneSurrogate = codeUnits.some((cu, i) => {+ if (cu >= 0xd800 && cu <= 0xdbff) {+ const next = codeUnits[i + 1] ?? 0;+ return next < 0xdc00 || next > 0xdfff;+ }+ if (cu >= 0xdc00 && cu <= 0xdfff) {+ const prev = codeUnits[i - 1] ?? 0;+ return prev < 0xd800 || prev > 0xdbff;+ }+ return false;+ });+ expect(loneSurrogate).toBe(false);+ });++ it("computes pane widths summing to available width without overflow", () => {+ for (const total of [60, 80, 100, 120, 160]) {+ for (const count of [1, 2, 3, 4]) {+ const widths = paneWidths(total, count);+ expect(widths).toHaveLength(count);+ const inner = widths.reduce((sum, w) => sum + w, 0);+ const expectedInner = Math.max(count * 10, total - (count + 1));+ expect(inner).toBe(expectedInner);+ if (total >= count * 10 + count + 1) {+ const totalBorderWidth = inner + (count + 1);+ expect(totalBorderWidth).toBe(total);+ }+ }+ }+ });++ it("composes border and paneRow lines of exactly equal visible width", () => {+ const cases = [+ { total: 80, count: 3, cells: ["Short", "Medium cell text", "Third column"] },+ { total: 95, count: 2, cells: ["\x1b[32mActive status\x1b[0m", "CJK 你好世界 column"] },+ { total: 60, count: 1, cells: ["Single full-width pane"] },+ { total: 120, count: 4, cells: ["A", "B", "C", "D"] },+ ];+ for (const { total, count, cells } of cases) {+ const widths = paneWidths(total, count);+ const top = border(widths, "top");+ const mid = border(widths, "mid");+ const bottom = border(widths, "bottom");+ const row = paneRow(cells, widths);++ const topW = cellWidth(top);+ const midW = cellWidth(mid);+ const bottomW = cellWidth(bottom);+ const rowW = cellWidth(row);++ expect(topW).toBe(rowW);+ expect(midW).toBe(rowW);+ expect(bottomW).toBe(rowW);+ }+ });++ it("composes left and right text within a target width", () => {+ const res = compose("Left", "Right", 20);+ expect(cellWidth(res)).toBe(20);+ expect(res.startsWith("Left")).toBe(true);+ expect(res.endsWith("Right")).toBe(true);+ });++ it("computes window slices for scrolling lists", () => {+ const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];+ expect(windowFor(items, 0, 5)).toEqual({ start: 0, end: 5 });+ expect(windowFor(items, 5, 5)).toEqual({ start: 3, end: 8 });+ expect(windowFor(items, 9, 5)).toEqual({ start: 5, end: 10 });+ expect(windowFor([1, 2], 0, 5)).toEqual({ start: 0, end: 2 });+ });++ it("cleans control characters and trims text", () => {+ expect(clean(" hello\tworld\r\n ")).toBe("hello world");+ expect(clean("\x1b[31m colored \x1b[0m")).toBe("colored");+ });+});