overlay-qa-tests.ts 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  1. /**
  2. * Overlay QA Tests - comprehensive overlay positioning and edge case tests
  3. *
  4. * Usage: pi --extension ./examples/extensions/overlay-qa-tests.ts
  5. *
  6. * Commands:
  7. * /overlay-animation - Real-time animation demo (~30 FPS, proves DOOM-like rendering works)
  8. * /overlay-anchors - Cycle through all 9 anchor positions
  9. * /overlay-margins - Test margin and offset options
  10. * /overlay-stack - Test stacked overlays
  11. * /overlay-overflow - Test width overflow with streaming process output
  12. * /overlay-edge - Test overlay positioned at terminal edge
  13. * /overlay-percent - Test percentage-based positioning
  14. * /overlay-maxheight - Test maxHeight truncation
  15. * /overlay-sidepanel - Responsive sidepanel (hides when terminal < 100 cols)
  16. * /overlay-toggle - Toggle visibility demo (demonstrates OverlayHandle.setHidden)
  17. * /overlay-passive - Non-capturing overlay demo (passive info panel alongside active overlay)
  18. * /overlay-focus - Focus cycling, input routing, dismissal, and rendering order with overlays
  19. * /overlay-streaming - Multiple input panels with simulated streaming (Tab to cycle focus)
  20. */
  21. import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
  22. import type { Component, OverlayAnchor, OverlayHandle, OverlayOptions, TUI } from "@earendil-works/pi-tui";
  23. import { Input, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
  24. import { spawn } from "child_process";
  25. // Global handle for toggle demo (in real code, use a more elegant pattern)
  26. let globalToggleHandle: OverlayHandle | null = null;
  27. export default function (pi: ExtensionAPI) {
  28. // Animation demo - proves overlays can handle real-time updates (like pi-doom would need)
  29. pi.registerCommand("overlay-animation", {
  30. description: "Test real-time animation in overlay (~30 FPS)",
  31. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  32. await ctx.ui.custom<void>((tui, theme, _kb, done) => new AnimationDemoComponent(tui, theme, done), {
  33. overlay: true,
  34. overlayOptions: { anchor: "center", width: 50, maxHeight: 20 },
  35. });
  36. },
  37. });
  38. // Test all 9 anchor positions
  39. pi.registerCommand("overlay-anchors", {
  40. description: "Cycle through all anchor positions",
  41. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  42. const anchors: OverlayAnchor[] = [
  43. "top-left",
  44. "top-center",
  45. "top-right",
  46. "left-center",
  47. "center",
  48. "right-center",
  49. "bottom-left",
  50. "bottom-center",
  51. "bottom-right",
  52. ];
  53. let index = 0;
  54. while (true) {
  55. const result = await ctx.ui.custom<"next" | "confirm" | "cancel">(
  56. (_tui, theme, _kb, done) => new AnchorTestComponent(theme, anchors[index]!, done),
  57. {
  58. overlay: true,
  59. overlayOptions: { anchor: anchors[index], width: 40 },
  60. },
  61. );
  62. if (result === "next") {
  63. index = (index + 1) % anchors.length;
  64. continue;
  65. }
  66. if (result === "confirm") {
  67. ctx.ui.notify(`Selected: ${anchors[index]}`, "info");
  68. }
  69. break;
  70. }
  71. },
  72. });
  73. // Test margins and offsets
  74. pi.registerCommand("overlay-margins", {
  75. description: "Test margin and offset options",
  76. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  77. const configs: { name: string; options: OverlayOptions }[] = [
  78. { name: "No margin (top-left)", options: { anchor: "top-left", width: 35 } },
  79. { name: "Margin: 3 all sides", options: { anchor: "top-left", width: 35, margin: 3 } },
  80. {
  81. name: "Margin: top=5, left=10",
  82. options: { anchor: "top-left", width: 35, margin: { top: 5, left: 10 } },
  83. },
  84. { name: "Center + offset (10, -3)", options: { anchor: "center", width: 35, offsetX: 10, offsetY: -3 } },
  85. { name: "Bottom-right, margin: 2", options: { anchor: "bottom-right", width: 35, margin: 2 } },
  86. ];
  87. let index = 0;
  88. while (true) {
  89. const result = await ctx.ui.custom<"next" | "close">(
  90. (_tui, theme, _kb, done) => new MarginTestComponent(theme, configs[index]!, done),
  91. {
  92. overlay: true,
  93. overlayOptions: configs[index]!.options,
  94. },
  95. );
  96. if (result === "next") {
  97. index = (index + 1) % configs.length;
  98. continue;
  99. }
  100. break;
  101. }
  102. },
  103. });
  104. // Test stacked overlays
  105. pi.registerCommand("overlay-stack", {
  106. description: "Test stacked overlays",
  107. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  108. // Three large overlays that overlap in the center area
  109. // Each offset slightly so you can see the stacking
  110. ctx.ui.notify("Showing overlay 1 (back)...", "info");
  111. const p1 = ctx.ui.custom<string>(
  112. (_tui, theme, _kb, done) => new StackOverlayComponent(theme, 1, "back (red border)", done),
  113. {
  114. overlay: true,
  115. overlayOptions: { anchor: "center", width: 50, offsetX: -8, offsetY: -4, maxHeight: 15 },
  116. },
  117. );
  118. await sleep(400);
  119. ctx.ui.notify("Showing overlay 2 (middle)...", "info");
  120. const p2 = ctx.ui.custom<string>(
  121. (_tui, theme, _kb, done) => new StackOverlayComponent(theme, 2, "middle (green border)", done),
  122. {
  123. overlay: true,
  124. overlayOptions: { anchor: "center", width: 50, offsetX: 0, offsetY: 0, maxHeight: 15 },
  125. },
  126. );
  127. await sleep(400);
  128. ctx.ui.notify("Showing overlay 3 (front)...", "info");
  129. const p3 = ctx.ui.custom<string>(
  130. (_tui, theme, _kb, done) => new StackOverlayComponent(theme, 3, "front (blue border)", done),
  131. {
  132. overlay: true,
  133. overlayOptions: { anchor: "center", width: 50, offsetX: 8, offsetY: 4, maxHeight: 15 },
  134. },
  135. );
  136. // Wait for all to close
  137. const results = await Promise.all([p1, p2, p3]);
  138. ctx.ui.notify(`Closed in order: ${results.join(", ")}`, "info");
  139. },
  140. });
  141. // Test width overflow scenarios (original crash case) - streams real process output
  142. pi.registerCommand("overlay-overflow", {
  143. description: "Test width overflow with streaming process output",
  144. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  145. await ctx.ui.custom<void>((tui, theme, _kb, done) => new StreamingOverflowComponent(tui, theme, done), {
  146. overlay: true,
  147. overlayOptions: { anchor: "center", width: 90, maxHeight: 20 },
  148. });
  149. },
  150. });
  151. // Test overlay at terminal edge
  152. pi.registerCommand("overlay-edge", {
  153. description: "Test overlay positioned at terminal edge",
  154. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  155. await ctx.ui.custom<void>((_tui, theme, _kb, done) => new EdgeTestComponent(theme, done), {
  156. overlay: true,
  157. overlayOptions: { anchor: "right-center", width: 40, margin: { right: 0 } },
  158. });
  159. },
  160. });
  161. // Test percentage-based positioning
  162. pi.registerCommand("overlay-percent", {
  163. description: "Test percentage-based positioning",
  164. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  165. const configs = [
  166. { name: "rowPercent: 0 (top)", row: 0, col: 50 },
  167. { name: "rowPercent: 50 (middle)", row: 50, col: 50 },
  168. { name: "rowPercent: 100 (bottom)", row: 100, col: 50 },
  169. { name: "colPercent: 0 (left)", row: 50, col: 0 },
  170. { name: "colPercent: 100 (right)", row: 50, col: 100 },
  171. ];
  172. let index = 0;
  173. while (true) {
  174. const config = configs[index]!;
  175. const result = await ctx.ui.custom<"next" | "close">(
  176. (_tui, theme, _kb, done) => new PercentTestComponent(theme, config, done),
  177. {
  178. overlay: true,
  179. overlayOptions: {
  180. width: 30,
  181. row: `${config.row}%`,
  182. col: `${config.col}%`,
  183. },
  184. },
  185. );
  186. if (result === "next") {
  187. index = (index + 1) % configs.length;
  188. continue;
  189. }
  190. break;
  191. }
  192. },
  193. });
  194. // Test maxHeight
  195. pi.registerCommand("overlay-maxheight", {
  196. description: "Test maxHeight truncation",
  197. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  198. await ctx.ui.custom<void>((_tui, theme, _kb, done) => new MaxHeightTestComponent(theme, done), {
  199. overlay: true,
  200. overlayOptions: { anchor: "center", width: 50, maxHeight: 10 },
  201. });
  202. },
  203. });
  204. // Test responsive sidepanel - only shows when terminal is wide enough
  205. pi.registerCommand("overlay-sidepanel", {
  206. description: "Test responsive sidepanel (hides when terminal < 100 cols)",
  207. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  208. await ctx.ui.custom<void>((tui, theme, _kb, done) => new SidepanelComponent(tui, theme, done), {
  209. overlay: true,
  210. overlayOptions: {
  211. anchor: "right-center",
  212. width: "25%",
  213. minWidth: 30,
  214. margin: { right: 1 },
  215. // Only show when terminal is wide enough
  216. visible: (termWidth) => termWidth >= 100,
  217. },
  218. });
  219. },
  220. });
  221. // Test toggle overlay - demonstrates OverlayHandle.setHidden() via onHandle callback
  222. pi.registerCommand("overlay-toggle", {
  223. description: "Test overlay toggle (press 't' to toggle visibility)",
  224. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  225. await ctx.ui.custom<void>((tui, theme, _kb, done) => new ToggleDemoComponent(tui, theme, done), {
  226. overlay: true,
  227. overlayOptions: { anchor: "center", width: 50 },
  228. // onHandle callback provides access to the OverlayHandle for visibility control
  229. onHandle: (handle) => {
  230. // Store handle globally so component can access it
  231. // (In real code, you'd use a more elegant pattern like a store or event emitter)
  232. globalToggleHandle = handle;
  233. },
  234. });
  235. globalToggleHandle = null;
  236. },
  237. });
  238. // Non-capturing overlay demo - passive info panel that doesn't steal focus
  239. pi.registerCommand("overlay-passive", {
  240. description: "Test non-capturing overlay (passive info panel alongside active overlay)",
  241. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  242. ctx.ui.setEditorText("");
  243. await ctx.ui.custom<void>((tui, theme, _kb, done) => new PassiveDemoController(tui, theme, done), {
  244. overlay: true,
  245. overlayOptions: { anchor: "center", width: 48 },
  246. });
  247. },
  248. });
  249. // Focus cycling demo - demonstrates focus(), input routing, per-panel dismissal, and rendering order
  250. pi.registerCommand("overlay-focus", {
  251. description: "Test focus cycling, input routing, dismissal, and rendering order with overlays",
  252. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  253. ctx.ui.setEditorText("");
  254. await ctx.ui.custom<void>((tui, theme, _kb, done) => new FocusDemoController(tui, theme, done), {
  255. overlay: true,
  256. overlayOptions: { anchor: "bottom-center", width: 55, margin: { bottom: 1 } },
  257. });
  258. },
  259. });
  260. // Test multiple input panels with simulated streaming
  261. pi.registerCommand("overlay-streaming", {
  262. description: "Multiple input panels with simulated streaming (Tab to cycle focus)",
  263. handler: async (_args: string, ctx: ExtensionCommandContext) => {
  264. ctx.ui.setEditorText("");
  265. await ctx.ui.custom<void>((tui, theme, _kb, done) => new StreamingInputController(tui, theme, done), {
  266. overlay: true,
  267. overlayOptions: { anchor: "bottom-center", width: 60, margin: { bottom: 1 } },
  268. });
  269. },
  270. });
  271. }
  272. function sleep(ms: number): Promise<void> {
  273. return new Promise((resolve) => setTimeout(resolve, ms));
  274. }
  275. // Base overlay component with common rendering
  276. abstract class BaseOverlay {
  277. protected theme: Theme;
  278. constructor(theme: Theme) {
  279. this.theme = theme;
  280. }
  281. protected box(lines: string[], width: number, title?: string): string[] {
  282. const th = this.theme;
  283. const innerW = Math.max(1, width - 2);
  284. const result: string[] = [];
  285. const titleStr = title ? truncateToWidth(` ${title} `, innerW) : "";
  286. const titleW = visibleWidth(titleStr);
  287. const topLine = "─".repeat(Math.floor((innerW - titleW) / 2));
  288. const topLine2 = "─".repeat(Math.max(0, innerW - titleW - topLine.length));
  289. result.push(th.fg("border", `╭${topLine}`) + th.fg("accent", titleStr) + th.fg("border", `${topLine2}╮`));
  290. for (const line of lines) {
  291. result.push(th.fg("border", "│") + truncateToWidth(line, innerW, "...", true) + th.fg("border", "│"));
  292. }
  293. result.push(th.fg("border", `╰${"─".repeat(innerW)}╯`));
  294. return result;
  295. }
  296. invalidate(): void {}
  297. dispose(): void {}
  298. }
  299. // Anchor position test
  300. class AnchorTestComponent extends BaseOverlay {
  301. private anchor: OverlayAnchor;
  302. private done: (result: "next" | "confirm" | "cancel") => void;
  303. constructor(theme: Theme, anchor: OverlayAnchor, done: (result: "next" | "confirm" | "cancel") => void) {
  304. super(theme);
  305. this.anchor = anchor;
  306. this.done = done;
  307. }
  308. handleInput(data: string): void {
  309. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  310. this.done("cancel");
  311. } else if (matchesKey(data, "return")) {
  312. this.done("confirm");
  313. } else if (matchesKey(data, "space") || matchesKey(data, "right")) {
  314. this.done("next");
  315. }
  316. }
  317. render(width: number): string[] {
  318. const th = this.theme;
  319. return this.box(
  320. [
  321. "",
  322. ` Current: ${th.fg("accent", this.anchor)}`,
  323. "",
  324. ` ${th.fg("dim", "Space/→ = next anchor")}`,
  325. ` ${th.fg("dim", "Enter = confirm")}`,
  326. ` ${th.fg("dim", "Esc = cancel")}`,
  327. "",
  328. ],
  329. width,
  330. "Anchor Test",
  331. );
  332. }
  333. }
  334. // Margin/offset test
  335. class MarginTestComponent extends BaseOverlay {
  336. private config: { name: string; options: OverlayOptions };
  337. private done: (result: "next" | "close") => void;
  338. constructor(
  339. theme: Theme,
  340. config: { name: string; options: OverlayOptions },
  341. done: (result: "next" | "close") => void,
  342. ) {
  343. super(theme);
  344. this.config = config;
  345. this.done = done;
  346. }
  347. handleInput(data: string): void {
  348. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  349. this.done("close");
  350. } else if (matchesKey(data, "space") || matchesKey(data, "right")) {
  351. this.done("next");
  352. }
  353. }
  354. render(width: number): string[] {
  355. const th = this.theme;
  356. return this.box(
  357. [
  358. "",
  359. ` ${th.fg("accent", this.config.name)}`,
  360. "",
  361. ` ${th.fg("dim", "Space/→ = next config")}`,
  362. ` ${th.fg("dim", "Esc = close")}`,
  363. "",
  364. ],
  365. width,
  366. "Margin Test",
  367. );
  368. }
  369. }
  370. // Stacked overlay test
  371. class StackOverlayComponent extends BaseOverlay {
  372. private num: number;
  373. private position: string;
  374. private done: (result: string) => void;
  375. constructor(theme: Theme, num: number, position: string, done: (result: string) => void) {
  376. super(theme);
  377. this.num = num;
  378. this.position = position;
  379. this.done = done;
  380. }
  381. handleInput(data: string): void {
  382. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || matchesKey(data, "return")) {
  383. this.done(`Overlay ${this.num}`);
  384. }
  385. }
  386. render(width: number): string[] {
  387. const th = this.theme;
  388. // Use different colors for each overlay to show stacking
  389. const colors = ["error", "success", "accent"] as const;
  390. const color = colors[(this.num - 1) % colors.length]!;
  391. const innerW = Math.max(1, width - 2);
  392. const border = (char: string) => th.fg(color, char);
  393. const padLine = (s: string) => truncateToWidth(s, innerW, "...", true);
  394. const lines: string[] = [];
  395. lines.push(border(`╭${"─".repeat(innerW)}╮`));
  396. lines.push(border("│") + padLine(` Overlay ${th.fg("accent", `#${this.num}`)}`) + border("│"));
  397. lines.push(border("│") + padLine(` Layer: ${th.fg(color, this.position)}`) + border("│"));
  398. lines.push(border("│") + padLine("") + border("│"));
  399. // Add extra lines to make it taller
  400. for (let i = 0; i < 5; i++) {
  401. lines.push(border("│") + padLine(` ${"░".repeat(innerW - 2)} `) + border("│"));
  402. }
  403. lines.push(border("│") + padLine("") + border("│"));
  404. lines.push(border("│") + padLine(th.fg("dim", " Press Enter/Esc to close")) + border("│"));
  405. lines.push(border(`╰${"─".repeat(innerW)}╯`));
  406. return lines;
  407. }
  408. }
  409. // Streaming overflow test - spawns real process with colored output (original crash scenario)
  410. class StreamingOverflowComponent extends BaseOverlay {
  411. private tui: TUI;
  412. private lines: string[] = [];
  413. private proc: ReturnType<typeof spawn> | null = null;
  414. private scrollOffset = 0;
  415. private maxVisibleLines = 15;
  416. private finished = false;
  417. private disposed = false;
  418. private done: () => void;
  419. constructor(tui: TUI, theme: Theme, done: () => void) {
  420. super(theme);
  421. this.tui = tui;
  422. this.done = done;
  423. this.startProcess();
  424. }
  425. private startProcess(): void {
  426. // Run a command that produces many lines with ANSI colors
  427. // Using find with -ls produces file listings, or use ls --color
  428. this.proc = spawn("bash", [
  429. "-c",
  430. `
  431. echo "Starting streaming overflow test (30+ seconds)..."
  432. echo "This simulates subagent output with colors, hyperlinks, and long paths"
  433. echo ""
  434. for i in $(seq 1 100); do
  435. # Simulate long file paths with OSC 8 hyperlinks (clickable) - tests width overflow
  436. DIR="/Users/nicobailon/Documents/development/pi-mono/packages/coding-agent/src/modes/interactive"
  437. FILE="\${DIR}/components/very-long-component-name-that-exceeds-width-\${i}.ts"
  438. echo -e "\\033]8;;file://\${FILE}\\007▶ read: \${FILE}\\033]8;;\\007"
  439. # Add some colored status messages with long text
  440. if [ $((i % 5)) -eq 0 ]; then
  441. echo -e " \\033[32m✓ Successfully processed \${i} files in /Users/nicobailon/Documents/development/pi-mono\\033[0m"
  442. fi
  443. if [ $((i % 7)) -eq 0 ]; then
  444. echo -e " \\033[33m⚠ Warning: potential issue detected at line \${i} in very-long-component-name-that-exceeds-width.ts\\033[0m"
  445. fi
  446. if [ $((i % 11)) -eq 0 ]; then
  447. echo -e " \\033[31m✗ Error: file not found /some/really/long/path/that/definitely/exceeds/the/overlay/width/limit/file-\${i}.ts\\033[0m"
  448. fi
  449. sleep 0.3
  450. done
  451. echo ""
  452. echo -e "\\033[32m✓ Complete - 100 files processed in 30 seconds\\033[0m"
  453. echo "Press Esc to close"
  454. `,
  455. ]);
  456. this.proc.stdout?.on("data", (data: Buffer) => {
  457. if (this.disposed) return; // Guard against callbacks after dispose
  458. const text = data.toString();
  459. const newLines = text.split("\n");
  460. for (const line of newLines) {
  461. if (line) this.lines.push(line);
  462. }
  463. // Auto-scroll to bottom
  464. this.scrollOffset = Math.max(0, this.lines.length - this.maxVisibleLines);
  465. this.tui.requestRender();
  466. });
  467. this.proc.stderr?.on("data", (data: Buffer) => {
  468. if (this.disposed) return; // Guard against callbacks after dispose
  469. this.lines.push(this.theme.fg("error", data.toString().trim()));
  470. this.tui.requestRender();
  471. });
  472. this.proc.on("close", () => {
  473. if (this.disposed) return; // Guard against callbacks after dispose
  474. this.finished = true;
  475. this.tui.requestRender();
  476. });
  477. }
  478. handleInput(data: string): void {
  479. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  480. this.proc?.kill();
  481. this.done();
  482. } else if (matchesKey(data, "up")) {
  483. this.scrollOffset = Math.max(0, this.scrollOffset - 1);
  484. this.tui.requestRender(); // Trigger re-render after scroll
  485. } else if (matchesKey(data, "down")) {
  486. this.scrollOffset = Math.min(Math.max(0, this.lines.length - this.maxVisibleLines), this.scrollOffset + 1);
  487. this.tui.requestRender(); // Trigger re-render after scroll
  488. }
  489. }
  490. render(width: number): string[] {
  491. const th = this.theme;
  492. const innerW = Math.max(1, width - 2);
  493. const padLine = (s: string) => truncateToWidth(s, innerW, "...", true);
  494. const border = (c: string) => th.fg("border", c);
  495. const result: string[] = [];
  496. const title = truncateToWidth(` Streaming Output (${this.lines.length} lines) `, innerW);
  497. const titlePad = Math.max(0, innerW - visibleWidth(title));
  498. result.push(border("╭") + th.fg("accent", title) + border(`${"─".repeat(titlePad)}╮`));
  499. // Scroll indicators
  500. const canScrollUp = this.scrollOffset > 0;
  501. const canScrollDown = this.scrollOffset < this.lines.length - this.maxVisibleLines;
  502. const scrollInfo = `↑${this.scrollOffset} | ↓${Math.max(0, this.lines.length - this.maxVisibleLines - this.scrollOffset)}`;
  503. result.push(
  504. border("│") + padLine(canScrollUp || canScrollDown ? th.fg("dim", ` ${scrollInfo}`) : "") + border("│"),
  505. );
  506. // Visible lines - truncate long lines to fit within border
  507. const visibleLines = this.lines.slice(this.scrollOffset, this.scrollOffset + this.maxVisibleLines);
  508. for (const line of visibleLines) {
  509. result.push(border("│") + padLine(` ${line}`) + border("│"));
  510. }
  511. // Pad to maxVisibleLines
  512. for (let i = visibleLines.length; i < this.maxVisibleLines; i++) {
  513. result.push(border("│") + padLine("") + border("│"));
  514. }
  515. const status = this.finished ? th.fg("success", "✓ Done") : th.fg("warning", "● Running");
  516. result.push(border("│") + padLine(` ${status} ${th.fg("dim", "| ↑↓ scroll | Esc close")}`) + border("│"));
  517. result.push(border(`╰${"─".repeat(innerW)}╯`));
  518. return result;
  519. }
  520. dispose(): void {
  521. this.disposed = true;
  522. this.proc?.kill();
  523. }
  524. }
  525. // Edge position test
  526. class EdgeTestComponent extends BaseOverlay {
  527. private done: () => void;
  528. constructor(theme: Theme, done: () => void) {
  529. super(theme);
  530. this.done = done;
  531. }
  532. handleInput(data: string): void {
  533. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  534. this.done();
  535. }
  536. }
  537. render(width: number): string[] {
  538. const th = this.theme;
  539. return this.box(
  540. [
  541. "",
  542. " This overlay is at the",
  543. " right edge of terminal.",
  544. "",
  545. ` ${th.fg("dim", "Verify right border")}`,
  546. ` ${th.fg("dim", "aligns with edge.")}`,
  547. "",
  548. ` ${th.fg("dim", "Press Esc to close")}`,
  549. "",
  550. ],
  551. width,
  552. "Edge Test",
  553. );
  554. }
  555. }
  556. // Percentage positioning test
  557. class PercentTestComponent extends BaseOverlay {
  558. private config: { name: string; row: number; col: number };
  559. private done: (result: "next" | "close") => void;
  560. constructor(
  561. theme: Theme,
  562. config: { name: string; row: number; col: number },
  563. done: (result: "next" | "close") => void,
  564. ) {
  565. super(theme);
  566. this.config = config;
  567. this.done = done;
  568. }
  569. handleInput(data: string): void {
  570. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  571. this.done("close");
  572. } else if (matchesKey(data, "space") || matchesKey(data, "right")) {
  573. this.done("next");
  574. }
  575. }
  576. render(width: number): string[] {
  577. const th = this.theme;
  578. return this.box(
  579. [
  580. "",
  581. ` ${th.fg("accent", this.config.name)}`,
  582. "",
  583. ` ${th.fg("dim", "Space/→ = next")}`,
  584. ` ${th.fg("dim", "Esc = close")}`,
  585. "",
  586. ],
  587. width,
  588. "Percent Test",
  589. );
  590. }
  591. }
  592. // MaxHeight test - renders 20 lines, truncated to 10 by maxHeight
  593. class MaxHeightTestComponent extends BaseOverlay {
  594. private done: () => void;
  595. constructor(theme: Theme, done: () => void) {
  596. super(theme);
  597. this.done = done;
  598. }
  599. handleInput(data: string): void {
  600. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  601. this.done();
  602. }
  603. }
  604. render(width: number): string[] {
  605. const th = this.theme;
  606. // Intentionally render 21 lines - maxHeight: 10 will truncate to first 10
  607. // You should see header + lines 1-6, with bottom border cut off
  608. const contentLines: string[] = [
  609. th.fg("warning", " ⚠ Rendering 21 lines, maxHeight: 10"),
  610. th.fg("dim", " Lines 11-21 truncated (no bottom border)"),
  611. "",
  612. ];
  613. for (let i = 1; i <= 14; i++) {
  614. contentLines.push(` Line ${i} of 14`);
  615. }
  616. contentLines.push("", th.fg("dim", " Press Esc to close"));
  617. return this.box(contentLines, width, "MaxHeight Test");
  618. }
  619. }
  620. // Responsive sidepanel - demonstrates percentage width and visibility callback
  621. class SidepanelComponent extends BaseOverlay {
  622. private tui: TUI;
  623. private items = ["Dashboard", "Messages", "Settings", "Help", "About"];
  624. private selectedIndex = 0;
  625. private done: () => void;
  626. constructor(tui: TUI, theme: Theme, done: () => void) {
  627. super(theme);
  628. this.tui = tui;
  629. this.done = done;
  630. }
  631. handleInput(data: string): void {
  632. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  633. this.done();
  634. } else if (matchesKey(data, "up")) {
  635. this.selectedIndex = Math.max(0, this.selectedIndex - 1);
  636. this.tui.requestRender();
  637. } else if (matchesKey(data, "down")) {
  638. this.selectedIndex = Math.min(this.items.length - 1, this.selectedIndex + 1);
  639. this.tui.requestRender();
  640. } else if (matchesKey(data, "return")) {
  641. // Could trigger an action here
  642. this.tui.requestRender();
  643. }
  644. }
  645. render(width: number): string[] {
  646. const th = this.theme;
  647. const innerW = Math.max(1, width - 2);
  648. const padLine = (s: string) => truncateToWidth(s, innerW, "...", true);
  649. const border = (c: string) => th.fg("border", c);
  650. const lines: string[] = [];
  651. // Header
  652. lines.push(border(`╭${"─".repeat(innerW)}╮`));
  653. lines.push(border("│") + padLine(th.fg("accent", " Responsive Sidepanel")) + border("│"));
  654. lines.push(border("├") + border("─".repeat(innerW)) + border("┤"));
  655. // Menu items
  656. for (let i = 0; i < this.items.length; i++) {
  657. const item = this.items[i]!;
  658. const isSelected = i === this.selectedIndex;
  659. const prefix = isSelected ? th.fg("accent", "→ ") : " ";
  660. const text = isSelected ? th.fg("accent", item) : item;
  661. lines.push(border("│") + padLine(`${prefix}${text}`) + border("│"));
  662. }
  663. // Footer with responsive behavior info
  664. lines.push(border("├") + border("─".repeat(innerW)) + border("┤"));
  665. lines.push(border("│") + padLine(th.fg("warning", " ⚠ Resize terminal < 100 cols")) + border("│"));
  666. lines.push(border("│") + padLine(th.fg("warning", " to see panel auto-hide")) + border("│"));
  667. lines.push(border("│") + padLine(th.fg("dim", " Uses visible: (w) => w >= 100")) + border("│"));
  668. lines.push(border("│") + padLine(th.fg("dim", " ↑↓ navigate | Esc close")) + border("│"));
  669. lines.push(border(`╰${"─".repeat(innerW)}╯`));
  670. return lines;
  671. }
  672. }
  673. // Animation demo - proves overlays can handle real-time updates like pi-doom
  674. class AnimationDemoComponent extends BaseOverlay {
  675. private tui: TUI;
  676. private frame = 0;
  677. private interval: ReturnType<typeof setInterval> | null = null;
  678. private fps = 0;
  679. private lastFpsUpdate = Date.now();
  680. private framesSinceLastFps = 0;
  681. private done: () => void;
  682. constructor(tui: TUI, theme: Theme, done: () => void) {
  683. super(theme);
  684. this.tui = tui;
  685. this.done = done;
  686. this.startAnimation();
  687. }
  688. private startAnimation(): void {
  689. // Run at ~30 FPS (same as DOOM target)
  690. this.interval = setInterval(() => {
  691. this.frame++;
  692. this.framesSinceLastFps++;
  693. // Update FPS counter every second
  694. const now = Date.now();
  695. if (now - this.lastFpsUpdate >= 1000) {
  696. this.fps = this.framesSinceLastFps;
  697. this.framesSinceLastFps = 0;
  698. this.lastFpsUpdate = now;
  699. }
  700. this.tui.requestRender();
  701. }, 1000 / 30);
  702. }
  703. handleInput(data: string): void {
  704. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  705. this.dispose();
  706. this.done();
  707. }
  708. }
  709. render(width: number): string[] {
  710. const th = this.theme;
  711. const innerW = Math.max(1, width - 2);
  712. const padLine = (s: string) => truncateToWidth(s, innerW, "...", true);
  713. const border = (c: string) => th.fg("border", c);
  714. const lines: string[] = [];
  715. lines.push(border(`╭${"─".repeat(innerW)}╮`));
  716. lines.push(border("│") + padLine(th.fg("accent", " Animation Demo (~30 FPS)")) + border("│"));
  717. lines.push(border("│") + padLine(``) + border("│"));
  718. lines.push(border("│") + padLine(` Frame: ${th.fg("accent", String(this.frame))}`) + border("│"));
  719. lines.push(border("│") + padLine(` FPS: ${th.fg("success", String(this.fps))}`) + border("│"));
  720. lines.push(border("│") + padLine(``) + border("│"));
  721. // Animated content - bouncing bar
  722. const barWidth = Math.max(12, innerW - 4); // Ensure enough space for bar
  723. const pos = Math.max(0, Math.floor(((Math.sin(this.frame / 10) + 1) * (barWidth - 10)) / 2));
  724. const bar = " ".repeat(pos) + th.fg("accent", "██████████") + " ".repeat(Math.max(0, barWidth - 10 - pos));
  725. lines.push(border("│") + padLine(` ${bar}`) + border("│"));
  726. // Spinning character
  727. const spinChars = ["◐", "◓", "◑", "◒"];
  728. const spin = spinChars[this.frame % spinChars.length];
  729. lines.push(border("│") + padLine(` Spinner: ${th.fg("warning", spin!)}`) + border("│"));
  730. // Color cycling
  731. const hue = (this.frame * 3) % 360;
  732. const rgb = hslToRgb(hue / 360, 0.8, 0.5);
  733. const colorBlock = `\x1b[48;2;${rgb[0]};${rgb[1]};${rgb[2]}m${" ".repeat(10)}\x1b[0m`;
  734. lines.push(border("│") + padLine(` Color: ${colorBlock}`) + border("│"));
  735. lines.push(border("│") + padLine(``) + border("│"));
  736. lines.push(border("│") + padLine(th.fg("dim", " This proves overlays can handle")) + border("│"));
  737. lines.push(border("│") + padLine(th.fg("dim", " real-time game-like rendering.")) + border("│"));
  738. lines.push(border("│") + padLine(th.fg("dim", " (pi-doom uses same approach)")) + border("│"));
  739. lines.push(border("│") + padLine(``) + border("│"));
  740. lines.push(border("│") + padLine(th.fg("dim", " Press Esc to close")) + border("│"));
  741. lines.push(border(`╰${"─".repeat(innerW)}╯`));
  742. return lines;
  743. }
  744. dispose(): void {
  745. if (this.interval) {
  746. clearInterval(this.interval);
  747. this.interval = null;
  748. }
  749. }
  750. }
  751. // HSL to RGB helper for color cycling animation
  752. function hslToRgb(h: number, s: number, l: number): [number, number, number] {
  753. let r: number, g: number, b: number;
  754. if (s === 0) {
  755. r = g = b = l;
  756. } else {
  757. const hue2rgb = (p: number, q: number, t: number) => {
  758. if (t < 0) t += 1;
  759. if (t > 1) t -= 1;
  760. if (t < 1 / 6) return p + (q - p) * 6 * t;
  761. if (t < 1 / 2) return q;
  762. if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  763. return p;
  764. };
  765. const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  766. const p = 2 * l - q;
  767. r = hue2rgb(p, q, h + 1 / 3);
  768. g = hue2rgb(p, q, h);
  769. b = hue2rgb(p, q, h - 1 / 3);
  770. }
  771. return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
  772. }
  773. // Toggle demo - demonstrates OverlayHandle.setHidden() via onHandle callback
  774. class ToggleDemoComponent extends BaseOverlay {
  775. private tui: TUI;
  776. private toggleCount = 0;
  777. private isToggling = false;
  778. private done: () => void;
  779. constructor(tui: TUI, theme: Theme, done: () => void) {
  780. super(theme);
  781. this.tui = tui;
  782. this.done = done;
  783. }
  784. handleInput(data: string): void {
  785. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  786. this.done();
  787. } else if (matchesKey(data, "t") && globalToggleHandle && !this.isToggling) {
  788. // Demonstrate toggle by hiding for 1 second then showing again
  789. // (In real usage, a global keybinding would control visibility)
  790. this.isToggling = true;
  791. this.toggleCount++;
  792. globalToggleHandle.setHidden(true);
  793. // Auto-restore after 1 second to demonstrate the API
  794. setTimeout(() => {
  795. if (globalToggleHandle) {
  796. globalToggleHandle.setHidden(false);
  797. this.isToggling = false;
  798. this.tui.requestRender();
  799. }
  800. }, 1000);
  801. }
  802. }
  803. render(width: number): string[] {
  804. const th = this.theme;
  805. return this.box(
  806. [
  807. "",
  808. th.fg("accent", " Toggle Demo"),
  809. "",
  810. " This overlay demonstrates the",
  811. " onHandle callback API.",
  812. "",
  813. ` Toggle count: ${th.fg("accent", String(this.toggleCount))}`,
  814. "",
  815. th.fg("dim", " Press 't' to hide for 1 second"),
  816. th.fg("dim", " (demonstrates setHidden API)"),
  817. "",
  818. th.fg("dim", " In real usage, a global keybinding"),
  819. th.fg("dim", " would toggle visibility externally."),
  820. "",
  821. th.fg("dim", " Press Esc to close"),
  822. "",
  823. ],
  824. width,
  825. "Toggle Demo",
  826. );
  827. }
  828. }
  829. // === Non-capturing passive overlay demo ===
  830. class PassiveDemoController extends BaseOverlay {
  831. focused = false;
  832. private tui: TUI;
  833. private typed = "";
  834. private timerComponent: TimerPanel;
  835. private timerHandle: OverlayHandle | null = null;
  836. private interval: ReturnType<typeof setInterval> | null = null;
  837. private inputCount = 0;
  838. private lastInputDebug = "";
  839. private done: () => void;
  840. constructor(tui: TUI, theme: Theme, done: () => void) {
  841. super(theme);
  842. this.tui = tui;
  843. this.done = done;
  844. this.timerComponent = new TimerPanel(theme);
  845. this.timerHandle = this.tui.showOverlay(this.timerComponent, {
  846. nonCapturing: true,
  847. anchor: "top-right",
  848. width: 22,
  849. margin: { top: 1, right: 2 },
  850. });
  851. this.interval = setInterval(() => {
  852. this.timerComponent.tick();
  853. this.tui.requestRender();
  854. }, 1000);
  855. }
  856. handleInput(data: string): void {
  857. this.inputCount++;
  858. this.lastInputDebug = `len=${data.length} c0=${data.charCodeAt(0)}`;
  859. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  860. this.cleanup();
  861. this.done();
  862. } else if (matchesKey(data, "backspace")) {
  863. this.typed = this.typed.slice(0, -1);
  864. } else if (data.length === 1 && data.charCodeAt(0) >= 32) {
  865. this.typed += data;
  866. }
  867. }
  868. render(width: number): string[] {
  869. const th = this.theme;
  870. const display = this.typed.length > 0 ? this.typed : th.fg("dim", "(type here)");
  871. return this.box(
  872. [
  873. "",
  874. ` ${th.fg("dim", `focused=${this.focused} inputs=${this.inputCount}`)}`,
  875. ` ${th.fg("dim", `last: ${this.lastInputDebug || "none"}`)}`,
  876. "",
  877. ` > ${display}`,
  878. "",
  879. th.fg("dim", " Type to prove input goes here."),
  880. th.fg("dim", " Press Esc to close both."),
  881. "",
  882. ],
  883. width,
  884. "Non-Capturing Demo",
  885. );
  886. }
  887. private cleanup(): void {
  888. if (this.interval) {
  889. clearInterval(this.interval);
  890. this.interval = null;
  891. }
  892. this.timerHandle?.hide();
  893. this.timerHandle = null;
  894. }
  895. override dispose(): void {
  896. this.cleanup();
  897. }
  898. }
  899. class TimerPanel extends BaseOverlay {
  900. private seconds = 0;
  901. tick(): void {
  902. this.seconds++;
  903. }
  904. render(width: number): string[] {
  905. const th = this.theme;
  906. const mins = Math.floor(this.seconds / 60);
  907. const secs = this.seconds % 60;
  908. const time = `${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
  909. return this.box([` ${th.fg("accent", time)}`, th.fg("dim", " nonCapturing: true")], width, "Timer");
  910. }
  911. }
  912. // === Focus cycling demo ===
  913. type FocusPanelColor = "error" | "success" | "accent";
  914. type FocusPanelConfig = { label: string; color: FocusPanelColor; options: OverlayOptions };
  915. type FocusPanelEntry = { panel: FocusPanel; handle: OverlayHandle };
  916. const FOCUS_PANEL_CONFIGS = [
  917. { label: "Alpha", color: "error", options: { row: 2, col: 4, width: 34 } },
  918. { label: "Beta", color: "success", options: { row: 5, col: 28, width: 34 } },
  919. { label: "Gamma", color: "accent", options: { row: 8, col: 52, width: 34 } },
  920. ] satisfies FocusPanelConfig[];
  921. class FocusDemoController extends BaseOverlay {
  922. private readonly tui: TUI;
  923. private entries: FocusPanelEntry[] = [];
  924. private readonly done: () => void;
  925. private closed = false;
  926. constructor(tui: TUI, theme: Theme, done: () => void) {
  927. super(theme);
  928. this.tui = tui;
  929. this.done = done;
  930. for (const config of FOCUS_PANEL_CONFIGS) {
  931. const panel = new FocusPanel({ theme, config, controller: this });
  932. const handle = this.tui.showOverlay(panel, { nonCapturing: true, ...config.options });
  933. this.entries.push({ panel, handle });
  934. }
  935. this.focusFirstOpenPanel();
  936. }
  937. focusNext(current: FocusPanel, direction: 1 | -1 = 1): void {
  938. const openEntries = this.openEntries();
  939. const currentOpenPosition = openEntries.findIndex((entry) => entry.panel === current);
  940. if (currentOpenPosition === -1) throw new Error(`Panel ${current.label} is not open`);
  941. const nextOpenPosition = (currentOpenPosition + direction + openEntries.length) % openEntries.length;
  942. this.focusEntryAt(openEntries, nextOpenPosition);
  943. }
  944. dismiss(panel: FocusPanel): void {
  945. const openEntries = this.openEntries();
  946. const currentOpenPosition = openEntries.findIndex((candidate) => candidate.panel === panel);
  947. if (currentOpenPosition === -1) return;
  948. const entry = openEntries[currentOpenPosition];
  949. if (!entry) throw new Error(`Invalid focus panel index ${currentOpenPosition}`);
  950. const remainingEntries = openEntries.filter((candidate) => candidate.panel !== panel);
  951. entry.panel.closed = true;
  952. entry.handle.hide();
  953. if (remainingEntries.length === 0) {
  954. this.close();
  955. return;
  956. }
  957. this.focusEntryAt(remainingEntries, currentOpenPosition % remainingEntries.length);
  958. }
  959. close(): void {
  960. if (this.closed) return;
  961. this.closed = true;
  962. this.hidePanels();
  963. this.done();
  964. }
  965. handleInput(data: string): void {
  966. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  967. this.close();
  968. } else if (matchesKey(data, "tab")) {
  969. this.focusFirstOpenPanel();
  970. }
  971. }
  972. render(width: number): string[] {
  973. const th = this.theme;
  974. const focused = this.entries.find((entry) => entry.handle.isFocused())?.panel.label ?? "Controller";
  975. return this.box(
  976. [
  977. "",
  978. ` Current focus: ${th.fg("accent", focused)}`,
  979. "",
  980. " Three overlapping panels above are",
  981. ` ${th.fg("accent", "nonCapturing")} overlays controlled with`,
  982. " raw OverlayHandle.focus()/hide().",
  983. "",
  984. " Type in the focused panel's input.",
  985. " Focused panel renders on top.",
  986. "",
  987. th.fg("dim", " Tab/Shift+Tab = cycle panels"),
  988. th.fg("dim", " Esc/Ctrl+D = dismiss panel"),
  989. th.fg("dim", " Ctrl+C = close all"),
  990. "",
  991. ],
  992. width,
  993. "Focus + Input Demo",
  994. );
  995. }
  996. override dispose(): void {
  997. if (this.closed) return;
  998. this.closed = true;
  999. this.hidePanels();
  1000. }
  1001. private focusFirstOpenPanel(): void {
  1002. const firstOpen = this.openEntries()[0];
  1003. if (firstOpen) {
  1004. firstOpen.handle.focus();
  1005. this.tui.requestRender();
  1006. }
  1007. }
  1008. private focusEntryAt(entries: FocusPanelEntry[], index: number): void {
  1009. const entry = entries[index];
  1010. if (!entry) throw new Error(`Invalid focus panel index ${index}`);
  1011. entry.handle.focus();
  1012. this.tui.requestRender();
  1013. }
  1014. private hidePanels(): void {
  1015. for (const entry of this.entries) {
  1016. if (!entry.panel.closed) {
  1017. entry.panel.closed = true;
  1018. entry.handle.hide();
  1019. }
  1020. }
  1021. this.entries = [];
  1022. }
  1023. private openEntries(): FocusPanelEntry[] {
  1024. return this.entries.filter((entry) => !entry.panel.closed);
  1025. }
  1026. }
  1027. class FocusPanel extends BaseOverlay {
  1028. focused = false;
  1029. closed = false;
  1030. readonly label: string;
  1031. private readonly color: FocusPanelColor;
  1032. private readonly controller: FocusDemoController;
  1033. private readonly input = new Input();
  1034. private inputs: string[] = [];
  1035. constructor({
  1036. theme,
  1037. config,
  1038. controller,
  1039. }: {
  1040. theme: Theme;
  1041. config: FocusPanelConfig;
  1042. controller: FocusDemoController;
  1043. }) {
  1044. super(theme);
  1045. this.label = config.label;
  1046. this.color = config.color;
  1047. this.controller = controller;
  1048. }
  1049. handleInput(data: string): void {
  1050. if (matchesKey(data, "tab")) {
  1051. this.controller.focusNext(this);
  1052. } else if (matchesKey(data, "shift+tab")) {
  1053. this.controller.focusNext(this, -1);
  1054. } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+d")) {
  1055. this.controller.dismiss(this);
  1056. } else if (matchesKey(data, "ctrl+c")) {
  1057. this.controller.close();
  1058. } else if (matchesKey(data, "return")) {
  1059. this.inputs.push("Enter");
  1060. } else if (matchesKey(data, "up")) {
  1061. this.inputs.push("↑");
  1062. } else if (matchesKey(data, "down")) {
  1063. this.inputs.push("↓");
  1064. } else if (matchesKey(data, "left")) {
  1065. this.input.handleInput(data);
  1066. this.inputs.push("←");
  1067. } else if (matchesKey(data, "right")) {
  1068. this.input.handleInput(data);
  1069. this.inputs.push("→");
  1070. } else if (matchesKey(data, "backspace")) {
  1071. this.input.handleInput(data);
  1072. this.inputs.push("Backspace");
  1073. } else {
  1074. this.input.handleInput(data);
  1075. this.inputs.push(JSON.stringify(data));
  1076. }
  1077. }
  1078. render(width: number): string[] {
  1079. const th = this.theme;
  1080. const innerW = Math.max(1, width - 2);
  1081. const border = (c: string) => th.fg(this.focused ? this.color : "dim", c);
  1082. const padLine = (s: string) => truncateToWidth(s, innerW, "...", true);
  1083. const recent = this.inputs.length === 0 ? "(none)" : this.inputs.slice(-6).join(" ");
  1084. const lines: string[] = [];
  1085. this.input.focused = this.focused;
  1086. const [inputLine = ""] = this.input.render(Math.max(1, innerW - 8));
  1087. lines.push(border(`╭${"─".repeat(innerW)}╮`));
  1088. lines.push(
  1089. border("│") +
  1090. padLine(
  1091. ` ${th.fg(this.color, this.label)} ${this.focused ? th.fg("success", "FOCUSED") : th.fg("dim", "visible")}`,
  1092. ) +
  1093. border("│"),
  1094. );
  1095. lines.push(border("│") + padLine("") + border("│"));
  1096. lines.push(border("│") + padLine(` Input: ${inputLine}`) + border("│"));
  1097. lines.push(border("│") + padLine(` Keys: ${recent}`) + border("│"));
  1098. lines.push(border("│") + padLine(th.fg("dim", " Tab/Shift+Tab focus")) + border("│"));
  1099. lines.push(border("│") + padLine(th.fg("dim", " Esc/Ctrl+D dismiss")) + border("│"));
  1100. lines.push(border(`╰${"─".repeat(innerW)}╯`));
  1101. return lines;
  1102. }
  1103. }
  1104. // === Streaming input panel test (/overlay-streaming) ===
  1105. class StreamingInputController extends BaseOverlay {
  1106. private tui: TUI;
  1107. private panels: StreamingInputPanel[] = [];
  1108. private handles: OverlayHandle[] = [];
  1109. private focusIndex = -1; // -1 = controller focused, 0-2 = panel focused
  1110. private streamLines: string[] = [];
  1111. private streamInterval: ReturnType<typeof setInterval> | null = null;
  1112. private lineCount = 0;
  1113. private done: () => void;
  1114. constructor(tui: TUI, theme: Theme, done: () => void) {
  1115. super(theme);
  1116. this.tui = tui;
  1117. this.done = done;
  1118. // Create 3 input panels as non-capturing overlays
  1119. const colors = ["error", "success", "accent"] as const;
  1120. const labels = ["Panel A", "Panel B", "Panel C"];
  1121. for (let i = 0; i < 3; i++) {
  1122. const panel = new StreamingInputPanel(
  1123. theme,
  1124. labels[i]!,
  1125. colors[i]!,
  1126. () => this.cycleFocus(),
  1127. () => this.close(),
  1128. );
  1129. const handle = this.tui.showOverlay(panel, {
  1130. nonCapturing: true,
  1131. row: 1 + i * 9,
  1132. col: 2,
  1133. width: 35,
  1134. });
  1135. panel.handle = handle;
  1136. this.panels.push(panel);
  1137. this.handles.push(handle);
  1138. }
  1139. // Start with controller focused (focusIndex = -1)
  1140. // Start simulated streaming
  1141. this.streamInterval = setInterval(() => {
  1142. this.lineCount++;
  1143. const timestamp = new Date().toLocaleTimeString();
  1144. this.streamLines.push(`[${timestamp}] Streaming line ${this.lineCount}...`);
  1145. if (this.streamLines.length > 8) {
  1146. this.streamLines.shift();
  1147. }
  1148. this.tui.requestRender();
  1149. }, 500);
  1150. }
  1151. private cycleFocus(): void {
  1152. // Unfocus current panel if any
  1153. if (this.focusIndex >= 0 && this.focusIndex < this.handles.length) {
  1154. this.handles[this.focusIndex]!.unfocus();
  1155. }
  1156. // Cycle: -1 (controller) → 0 → 1 → 2 → -1 ...
  1157. this.focusIndex++;
  1158. if (this.focusIndex >= this.handles.length) {
  1159. this.focusIndex = -1; // Back to controller
  1160. }
  1161. // Focus new panel if any
  1162. if (this.focusIndex >= 0) {
  1163. this.handles[this.focusIndex]!.focus();
  1164. }
  1165. this.tui.requestRender();
  1166. }
  1167. private close(): void {
  1168. if (this.streamInterval) {
  1169. clearInterval(this.streamInterval);
  1170. this.streamInterval = null;
  1171. }
  1172. for (const handle of this.handles) handle.hide();
  1173. this.handles = [];
  1174. this.panels = [];
  1175. this.done();
  1176. }
  1177. handleInput(data: string): void {
  1178. if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  1179. this.close();
  1180. } else if (matchesKey(data, "tab")) {
  1181. this.cycleFocus();
  1182. }
  1183. }
  1184. render(width: number): string[] {
  1185. const th = this.theme;
  1186. const focusedLabel =
  1187. this.focusIndex === -1
  1188. ? th.fg("success", "Controller (this panel)")
  1189. : (this.panels[this.focusIndex]?.label ?? "?");
  1190. const lines = [
  1191. "",
  1192. ` Current focus: ${th.fg("accent", focusedLabel)}`,
  1193. "",
  1194. " Simulated streaming output:",
  1195. th.fg("dim", " ─".repeat((width - 2) / 2)),
  1196. ];
  1197. for (const line of this.streamLines) {
  1198. lines.push(` ${th.fg("dim", line)}`);
  1199. }
  1200. while (lines.length < 12) {
  1201. lines.push("");
  1202. }
  1203. lines.push(th.fg("dim", " ─".repeat((width - 2) / 2)));
  1204. lines.push("");
  1205. lines.push(` Three ${th.fg("accent", "nonCapturing")} input panels on the left.`);
  1206. lines.push(" Tab cycles: Controller → Panel A → B → C → Controller");
  1207. lines.push(" Type in each panel to test input routing.");
  1208. lines.push("");
  1209. lines.push(th.fg("dim", " Tab = cycle focus | Esc = close all"));
  1210. lines.push("");
  1211. return this.box(lines, width, "Streaming + Input Test");
  1212. }
  1213. override dispose(): void {
  1214. this.close();
  1215. }
  1216. }
  1217. class StreamingInputPanel implements Component {
  1218. handle: OverlayHandle | null = null;
  1219. private theme: Theme;
  1220. private typed = "";
  1221. readonly label: string;
  1222. private color: "error" | "success" | "accent";
  1223. private onTab: () => void;
  1224. private onClose: () => void;
  1225. constructor(
  1226. theme: Theme,
  1227. label: string,
  1228. color: "error" | "success" | "accent",
  1229. onTab: () => void,
  1230. onClose: () => void,
  1231. ) {
  1232. this.theme = theme;
  1233. this.label = label;
  1234. this.color = color;
  1235. this.onTab = onTab;
  1236. this.onClose = onClose;
  1237. }
  1238. handleInput(data: string): void {
  1239. if (matchesKey(data, "tab")) {
  1240. this.onTab();
  1241. } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
  1242. this.onClose();
  1243. } else if (matchesKey(data, "backspace")) {
  1244. this.typed = this.typed.slice(0, -1);
  1245. } else if (data.length === 1 && data.charCodeAt(0) >= 32) {
  1246. this.typed += data;
  1247. }
  1248. }
  1249. render(width: number): string[] {
  1250. const th = this.theme;
  1251. const focused = this.handle?.isFocused() ?? false;
  1252. const innerW = Math.max(1, width - 2);
  1253. const border = (c: string) => th.fg(this.color, c);
  1254. const padLine = (s: string) => {
  1255. const w = visibleWidth(s);
  1256. return s + " ".repeat(Math.max(0, innerW - w));
  1257. };
  1258. const inputDisplay = this.typed.length > 0 ? this.typed : th.fg("dim", "(type here)");
  1259. const truncatedInput = truncateToWidth(` > ${inputDisplay}`, innerW, "...", true);
  1260. const lines: string[] = [];
  1261. lines.push(border(`╭${"─".repeat(innerW)}╮`));
  1262. lines.push(border("│") + padLine(` ${th.fg("accent", this.label)}`) + border("│"));
  1263. lines.push(border("│") + padLine("") + border("│"));
  1264. if (focused) {
  1265. lines.push(border("│") + padLine(th.fg("success", " ● FOCUSED")) + border("│"));
  1266. lines.push(border("│") + padLine(th.fg("dim", " (receiving input)")) + border("│"));
  1267. } else {
  1268. lines.push(border("│") + padLine(th.fg("dim", " ○ unfocused")) + border("│"));
  1269. lines.push(border("│") + padLine("") + border("│"));
  1270. }
  1271. lines.push(border("│") + padLine(truncatedInput) + border("│"));
  1272. lines.push(border("│") + padLine("") + border("│"));
  1273. lines.push(border("│") + padLine(th.fg("dim", " Tab | Esc")) + border("│"));
  1274. lines.push(border(`╰${"─".repeat(innerW)}╯`));
  1275. return lines;
  1276. }
  1277. invalidate(): void {}
  1278. }