hermes-agent/ui-tui/packages/hermes-ink/src/ink/line-width-cache.ts
Brooklyn Nicholson b1c49d5e73 chore(tui): /clean recent perf work — KISS/DRY pass
24 files, -319 LoC. Behaviour preserved, 369/369 tests green.

- hermes-ink caches: shared lruEvict helper for the four parallel LRU
  caches (stringWidth, wrapText, sliceAnsi, lineWidth); touch-on-read
  stays inlined per cache; tightened output.ts skip-slice fast path.
- wheelAccel: trimmed provenance header, collapsed env parsing, ternary
  dispatch in computeWheelStep.
- perfPane: folded ensureLogDir into once-flag, spread-with-overrides
  for fastPath/phases instead of full rebuilds.
- env: extracted truthy() (used 4×).
- virtualHeights: collapsed user/diff/slash height bumps; trail+todos
  estimate.
- useInputHandlers: scrollIdleTimer cleanup on unmount, ?? undefined
  shorthand.
- useMainApp: dropped dead liveTailVisible IIFE and liveProgress
  indirection.
- appLayout, markdown, messageLine, entry: vertical rhythm, dropped
  narration comments, inlined one-shot vars.
- fix: empty catch blocks → /* best-effort */ for no-empty lint.
2026-04-26 20:38:47 -05:00

38 lines
874 B
TypeScript

import { lruEvict } from './lru.js'
import { stringWidth } from './stringWidth.js'
// During streaming, text grows but completed lines are immutable.
// Caching stringWidth per-line avoids re-measuring hundreds of
// unchanged lines on every token (~50x reduction in stringWidth calls).
const cache = new Map<string, number>()
const MAX_CACHE_SIZE = 4096
export function lineWidth(line: string): number {
const cached = cache.get(line)
if (cached !== undefined) {
cache.delete(line)
cache.set(line, cached)
return cached
}
const width = stringWidth(line)
if (cache.size >= MAX_CACHE_SIZE) {
cache.delete(cache.keys().next().value!)
}
cache.set(line, width)
return width
}
export function lineWidthCacheSize(): number {
return cache.size
}
export function evictLineWidthCache(keepRatio = 0): void {
lruEvict(cache, keepRatio)
}