From 8aaa7f6931d057bff027db690d07bac90585de9f Mon Sep 17 00:00:00 2001 From: mitchell Date: Wed, 15 Apr 2026 16:32:03 -0400 Subject: [PATCH] refactor: move containment logic into function --- src/render/index.ts | 67 +++++++++++++++++++++------------------------ 1 file changed, 31 insertions(+), 36 deletions(-) diff --git a/src/render/index.ts b/src/render/index.ts index 24cc67b..e8ce000 100644 --- a/src/render/index.ts +++ b/src/render/index.ts @@ -5,63 +5,58 @@ const moveCursor = (x: number, y: number) => const clearScreenDown = () => new Promise((resolve) => process.stdout.clearScreenDown(resolve)); +let lineCount = 0; +let charsSinceNL = 0; + +function resetCounts() { + lineCount = 0; + charsSinceNL = 0; +} + export async function renderStream( stream: AsyncIterableStream>, ) { - let lineCount = 0; - let charsSinceNL = 0; const [numColumns, numRows] = process.stdout.getWindowSize(); + resetCounts(); for await (const part of stream) { if (part.type === "reasoning-start") { process.stdout.write("\u001b[2m\n"); } else if (part.type === "reasoning-delta") { process.stdout.write(part.text); - - charsSinceNL += part.text.length; - if (part.text.includes("\n")) { - lineCount += part.text.match(/\n/g)?.length ?? 1; - charsSinceNL = 0; - } else if (charsSinceNL >= numColumns) { - lineCount++; - charsSinceNL = charsSinceNL - numColumns; - } - - if (lineCount >= numRows / 2) { - await moveCursor(0, -lineCount); - await clearScreenDown(); - lineCount = 0; - charsSinceNL = 0; - } + await checkContainment(part.text, numColumns, numRows); } else if (part.type === "reasoning-end") { process.stdout.write("\n\u001b[22m"); await moveCursor(0, -lineCount - 2); await clearScreenDown(); - lineCount = 0; - charsSinceNL = 0; + resetCounts(); } else if (part.type === "text-start") { process.stdout.write("\n"); } else if (part.type === "text-delta") { process.stdout.write(part.text); - - charsSinceNL += part.text.length; - if (part.text.includes("\n")) { - lineCount += part.text.match(/\n/g)?.length ?? 1; - charsSinceNL = 0; - } else if (charsSinceNL >= numColumns) { - lineCount++; - charsSinceNL = charsSinceNL - numColumns; - } - - if (lineCount >= numRows / 2) { - await moveCursor(0, -lineCount); - await clearScreenDown(); - lineCount = 0; - charsSinceNL = 0; - } + await checkContainment(part.text, numColumns, numRows); } else if (part.type === "text-end") { await moveCursor(0, -lineCount - 1); await clearScreenDown(); + resetCounts(); } } } + +async function checkContainment(text: string, columns: number, rows: number) { + charsSinceNL += text.length; + if (text.includes("\n")) { + lineCount += text.match(/\n/g)?.length ?? 1; + charsSinceNL = 0; + } else if (charsSinceNL >= columns) { + lineCount++; + charsSinceNL = charsSinceNL - columns; + } + + if (lineCount >= rows / 2) { + await moveCursor(0, -lineCount); + await clearScreenDown(); + lineCount = 0; + charsSinceNL = 0; + } +}