All files / client/src/components/features serial-monitor.tsx

73.59% Statements 131/178
80% Branches 80/100
75% Functions 18/24
74.7% Lines 127/170

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431                                              3x 3x 3x 3x         35x 35x 35x 35x   35x   35x 35x       35x 2x 2x 10x 3x   7x     2x       35x 1x       35x 1x       35x 2x     35x                     13x 13x 26x   13x   12x 12x   11x       11x                   54x 13x       54x 50x 50x 13x 13x 13x 13x   13x         41x 4x       37x       21x                               1x 2x 1x 1x 1x 1x     1x   1x                   21x 21x   21x 2x 2x     21x 1x 1x     21x 21x       21x 21x 1x     20x                           18x 18x 18x 18x 18x 18x 18x   18x   17x       18x 17x     17x 17x 17x                           18x 18x 18x   18x 21x 21x   21x             21x   21x 20x 20x 19x         18x       18x 18x   18x                                             18x 18x 18x   17x 17x   17x 3x 3x 3x 3x 14x                                               14x 17x 17x 17x 17x 17x 17x         17x 16x 16x         17x                   17x         18x 17x 17x           18x                                   18x                                                                                    
import { useRef, useEffect, useState, useCallback, useMemo, ReactNode } from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { Trash2, Monitor } from "lucide-react";
import type { OutputLine } from "@shared/schema";
 
interface SerialMonitorProps {
  readonly output: OutputLine[];
  readonly isConnected: boolean;
  readonly isSimulationRunning: boolean;
  readonly onSendMessage: (message: string) => void;
  readonly onClear: () => void;
  readonly showMonitor?: boolean;
  readonly autoScrollEnabled?: boolean;
  readonly headerActions?: ReactNode;
  readonly showHeader?: boolean;
}
 
interface ProcessedLine {
  text: string;
  incomplete: boolean;
}
 
const ROW_HEIGHT = 20; // Exact line height in pixels (matches Monaco editor: 14px font + 20px line-height)
const OVERSCAN_COUNT = 10; // Extra lines above/below viewport for smooth scrolling
const ENABLE_VIRTUAL_SCROLL = true; // Feature flag for virtual scrolling
const ENABLE_RAF_BATCHING = typeof process !== 'undefined' && process.env.NODE_ENV !== 'test'; // Disable rAF in tests
 
// Simple ANSI escape code processor
// NOTE: Backspace (\b) is handled separately in applyBackspaceAcrossLines for cross-line support
function processAnsiCodes(text: string): string {
  const ESC = String.fromCodePoint(0x1b);
  const ESC_2J = `${ESC}[2J`;
  const ESC_H = `${ESC}[H`;
  const ESC_K = `${ESC}[K`;
 
  const ANSI_COLOR_RE = new RegExp(String.raw`${ESC}\[[0-9;]*m`, "g");
 
  let processed = text.replaceAll(ESC_2J, "").replaceAll(ESC_H, "");
  processed = processed.replaceAll(ESC_K, "").replaceAll(ANSI_COLOR_RE, "");
 
  // Backspace within the SAME chunk: apply locally
  // (Cross-chunk backspaces are handled in applyBackspaceAcrossLines)
  if (processed.includes("\b")) {
    let out = "";
    for (const ch of processed) {
      if (ch === "\b") {
        out = out.slice(0, -1);
      } else {
        out += ch;
      }
    }
    processed = out;
  }
 
  // Expand tabs to 4 spaces
  if (processed.includes("\t")) {
    processed = processed.replaceAll("\t", "    ");
  }
 
  // Bell character: replace with visible marker (so it's not silently dropped)
  if (processed.includes("\x07")) {
    processed = processed.replaceAll("\x07", "␇");
  }
 
  // Form feed and vertical tab => normalize to newline
  if (processed.includes("\f") || processed.includes("\v")) {
    processed = processed.replaceAll("\f", "\n").replaceAll("\v", "\n");
  }
 
  return processed;
}
 
/**
 * Strips leading backspace characters from text and removes corresponding
 * characters from the last incomplete line.
 */
function consumeLeadingBackspaces(
  lines: Array<{ text: string; incomplete: boolean }>,
  text: string,
): string {
  let idx = 0;
  while (idx < text.length && text[idx] === "\b") {
    idx++;
  }
  if (idx === 0) return text;
 
  const lastLine = lines.at(-1);
  if (!lastLine?.incomplete) return text;
 
  lastLine.text = lastLine.text.slice(
    0,
    Math.max(0, lastLine.text.length - idx),
  );
  return text.slice(idx);
}
 
// Exported for unit testing and reuse inside the hook
export function applyBackspaceAcrossLines(
  lines: Array<{ text: string; incomplete: boolean }>,
  text: string,
  isComplete: boolean,
): string | null {
  // Handle backspaces at the start of text
  if (text.includes("\b")) {
    text = consumeLeadingBackspaces(lines, text);
  }
 
  // If there's still text to process and we have an incomplete line, append to it
  if (text) {
    const lastLine = lines.at(-1);
    if (lastLine?.incomplete) {
      const cleanText = processAnsiCodes(text);
      Eif (cleanText) {
        lastLine.text += cleanText;
        lastLine.incomplete = !isComplete;
      }
      return null; // already handled
    }
  }
 
  // No text left after backspace processing, or no incomplete line to append to
  if (!text) {
    return null;
  }
 
  // Text remains: caller should handle it (new line or other processing)
  return text;
}
 
function hasControlChars(text: string) {
  return {
    hasClearScreen: text.includes("\x1b[2J") || text.includes("\u001b[2J"),
    hasCursorHome: text.includes("\x1b[H") || text.includes("\u001b[H"),
    hasCarriageReturn: text.includes("\r"),
  };
}
 
/**
 * Handles carriage-return overwrite logic for a single output line.
 * Returns true if the line was fully handled (caller should skip normal processing).
 */
function processCarriageReturnLine(
  lines: ProcessedLine[],
  text: string,
  lineComplete: boolean,
): boolean {
  const parts = text.split("\r");
  const cleanParts = parts.map((p) => processAnsiCodes(p));
  Iif (cleanParts.length <= 1) return false;
  const finalText = cleanParts.at(-1) ?? "";
  const lastLine = lines.at(-1);
  Iif (lastLine?.incomplete) {
    lines[lines.length - 1] = { text: finalText, incomplete: !lineComplete };
  } else {
    lines.push({ text: finalText, incomplete: !lineComplete });
  }
  return true;
}
 
function processLineWithControls(
  lines: ProcessedLine[],
  text: string,
  controls: ReturnType<typeof hasControlChars>,
  shouldClear: boolean,
  lineComplete: boolean,
): { text: string; shouldClear: boolean; handled: boolean } {
  let newShouldClear = shouldClear;
  let newText = text;
 
  if (controls.hasClearScreen) {
    newShouldClear = true;
    lines.length = 0;
  }
 
  if (controls.hasCursorHome && newShouldClear) {
    lines.length = 0;
    newShouldClear = false;
  }
 
  const backspaceResult = applyBackspaceAcrossLines(lines, newText, lineComplete);
  Iif (backspaceResult === null) {
    return { text: "", shouldClear: newShouldClear, handled: true };
  }
 
  newText = backspaceResult;
  if (controls.hasCarriageReturn && processCarriageReturnLine(lines, newText, lineComplete)) {
    return { text: "", shouldClear: newShouldClear, handled: true };
  }
 
  return { text: newText, shouldClear: newShouldClear, handled: false };
}
 
export function SerialMonitor({
  output,
  isConnected: _isConnected,
  isSimulationRunning: _isSimulationRunning = false,
  onSendMessage: _onSendMessage,
  onClear: _onClear,
  showMonitor = true,
  autoScrollEnabled = true,
  headerActions,
  showHeader = true,
}: SerialMonitorProps) {
  const outputRef = useRef<HTMLDivElement | null>(null);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const shouldAutoScrollRef = useRef(true);
  const lastScrollTopRef = useRef(0);
  const [scrollTop, setScrollTop] = useState(0);
  const [containerHeight, setContainerHeight] = useState(600); // Default height
  const rafIdRef = useRef<number | null>(null);
 
  useEffect(() => {
    // enable/disable autoscroll according to parent prop
    shouldAutoScrollRef.current = !!autoScrollEnabled;
  }, [autoScrollEnabled]);
 
  // Measure container height for virtual scrolling
  useEffect(() => {
    Iif (!containerRef.current) return;
    
    // Check if ResizeObserver is available (not available in some test environments)
    Eif (globalThis.ResizeObserver === undefined) {
      setContainerHeight(600); // Fallback height for tests
      return;
    }
    
    const observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        setContainerHeight(entry.contentRect.height);
      }
    });
    
    observer.observe(containerRef.current);
    return () => observer.disconnect();
  }, []);
 
  // Process output lines with rAF batching
  const processedLines = useMemo(() => {
    const lines: ProcessedLine[] = [];
    let shouldClear = false;
 
    output.forEach((line) => {
      let text = line.text;
      const controls = hasControlChars(text);
 
      const { text: processedText, shouldClear: newShouldClear, handled } = processLineWithControls(
        lines,
        text,
        controls,
        shouldClear,
        line.complete ?? true,
      );
      shouldClear = newShouldClear;
 
      if (!handled && processedText) {
        const cleanText = processAnsiCodes(processedText);
        if (cleanText) {
          lines.push({ text: cleanText, incomplete: !line.complete });
        }
      }
    });
 
    return lines;
  }, [output]);
 
  // Calculate visible range for virtual scrolling
  const { visibleLines, visibleStart, totalHeight, offsetY } = useMemo(() => {
    Eif (!ENABLE_VIRTUAL_SCROLL || processedLines.length < 100) {
      // Don't virtualize for small lists
      return {
        visibleLines: processedLines,
        visibleStart: 0,
        totalHeight: processedLines.length * ROW_HEIGHT,
        offsetY: 0,
      };
    }
 
    const visibleStart = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - OVERSCAN_COUNT);
    const visibleEnd = Math.min(
      processedLines.length,
      Math.ceil((scrollTop + containerHeight) / ROW_HEIGHT) + OVERSCAN_COUNT
    );
 
    return {
      visibleLines: processedLines.slice(visibleStart, visibleEnd),
      visibleStart,
      totalHeight: processedLines.length * ROW_HEIGHT,
      offsetY: visibleStart * ROW_HEIGHT,
    };
  }, [processedLines, scrollTop, containerHeight]);
 
  // Render visible lines with rAF batching (disabled in tests for synchronous rendering)
  useEffect(() => {
    const el = outputRef.current;
    if (!el) return;
 
    const renderContent = () => {
      el.innerHTML = "";
 
      if (processedLines.length === 0) {
        const placeholder = document.createElement("div");
        placeholder.className = "text-muted-foreground italic";
        placeholder.textContent = "Serial output will appear here...";
        el.appendChild(placeholder);
      I} else if (ENABLE_VIRTUAL_SCROLL && processedLines.length >= 100) {
        // Virtual scrolling mode (only for large outputs)
        const viewport = document.createElement("div");
        viewport.style.height = `${totalHeight}px`;
        viewport.style.position = "relative";
 
        const content = document.createElement("div");
        content.style.transform = `translateY(${offsetY}px)`;
        content.style.willChange = "transform";
 
        visibleLines.forEach((ln) => {
          const div = document.createElement("div");
          div.className = "text-foreground whitespace-pre-wrap break-words";
          div.style.height = `${ROW_HEIGHT}px`;
          div.style.lineHeight = `${ROW_HEIGHT}px`;
          div.style.fontSize = "var(--fs-code-base)"; // Scales with global --ui-font-scale
          div.textContent = ln.text;
          content.appendChild(div);
        });
 
        viewport.appendChild(content);
        el.appendChild(viewport);
      } else {
        // Standard rendering mode (for small outputs or when virtualization disabled)
        processedLines.forEach((ln) => {
          const div = document.createElement("div");
          div.className = "text-foreground whitespace-pre-wrap break-words";
          div.style.fontSize = "var(--fs-code-base)"; // Scales with global --ui-font-scale
          div.style.lineHeight = "var(--lh-code-base)"; // Scales with global --ui-font-scale
          div.textContent = ln.text;
          el.appendChild(div);
        });
      }
 
      // Auto-scroll to bottom if enabled
      if (shouldAutoScrollRef.current && el) {
        el.scrollTop = el.scrollHeight;
        lastScrollTopRef.current = el.scrollTop;
      }
    };
 
    // Use rAF batching in production, immediate rendering in tests
    Iif (ENABLE_RAF_BATCHING) {
      if (rafIdRef.current) {
        cancelAnimationFrame(rafIdRef.current);
      }
 
      rafIdRef.current = requestAnimationFrame(() => {
        renderContent();
        rafIdRef.current = null;
      });
    } else {
      renderContent();
    }
  }, [visibleLines, visibleStart, totalHeight, offsetY, processedLines]);
 
  // Cleanup rAF on unmount
  useEffect(() => {
    return () => {
      Iif (rafIdRef.current) {
        cancelAnimationFrame(rafIdRef.current);
      }
    };
  }, []);
 
  const handleScroll = useCallback(() => {
    const el = outputRef.current;
    if (!el) return;
 
    const currentScrollTop = el.scrollTop;
    setScrollTop(currentScrollTop); // Update scroll position for virtual scrolling
 
    const maxScrollTop = el.scrollHeight - el.clientHeight;
 
    if (currentScrollTop < lastScrollTopRef.current - 5) {
      shouldAutoScrollRef.current = false;
    }
    if (maxScrollTop - currentScrollTop < 20) {
      shouldAutoScrollRef.current = true;
    }
    lastScrollTopRef.current = currentScrollTop;
  }, []);
 
  return (
    <div className="h-full flex flex-col" data-testid="serial-monitor" ref={containerRef}>
      {/* Header - Consistent with other panel headers */}
      {showHeader && (
        <div className="flex items-center justify-between px-[var(--header-padding-x)] h-[var(--ui-header-height)] bg-muted border-b border-border flex-shrink-0">
          <div className="flex items-center gap-2">
            <Monitor className="h-4 w-4 text-muted-foreground mr-1" strokeWidth={1.5} />
            <span className="font-semibold tracking-wide uppercase text-muted-foreground/80" style={{ fontSize: "var(--fs-body-xs)" }}>Serial Monitor</span>
          </div>
          <div className="flex items-center gap-1">
            {headerActions}
            <Button
              variant="ghost"
              size="sm"
              className="h-[var(--ui-button-height)] w-[var(--ui-button-height)] p-0 flex items-center justify-center"
              onClick={() => _onClear()}
              title="Clear serial output"
            >
              <Trash2 size={16} />
            </Button>
          </div>
        </div>
      )}
 
      {/* Content area - flex-1 for remaining space */}
      <div className="flex-1 min-h-0">
        {showMonitor ? (
          <ScrollArea
            className="h-full"
            viewportRef={outputRef}
            viewportTestId="serial-output"
            viewportProps={{ onScroll: handleScroll }}
            viewportClassName="p-3 font-mono"
            thumbClassName="bg-status-success"
          />
        ) : (
          <div className="h-full" />
        )}
      </div>
    </div>
  );
}