feat: small refactors

This commit is contained in:
Brooklyn Nicholson 2026-04-06 18:38:13 -05:00
parent e2b3b1c5e4
commit afd670a36f
12 changed files with 2780 additions and 68 deletions

View file

@ -7,14 +7,72 @@ export const stripAnsi = (s: string) => s.replace(ANSI_RE, '')
export const hasAnsi = (s: string) => s.includes('\x1b[')
const renderEstimateLine = (line: string) => {
const trimmed = line.trim()
if (trimmed.startsWith('|')) {
return trimmed
.split('|')
.filter(Boolean)
.map(cell => cell.trim())
.join(' ')
}
return line
.replace(/\[(.+?)\]\((https?:\/\/[^\s)]+)\)/g, '$1')
.replace(/`([^`]+)`/g, '$1')
.replace(/\*\*(.+?)\*\*/g, '$1')
.replace(/\*(.+?)\*/g, '$1')
.replace(/^#{1,3}\s+/, '')
.replace(/^\s*[-*]\s+/, '• ')
.replace(/^\s*(\d+)\.\s+/, '$1. ')
.replace(/^>\s?/, '│ ')
}
export const compactPreview = (s: string, max: number) => {
const one = s.replace(/\s+/g, ' ').trim()
return !one ? '' : one.length > max ? one.slice(0, max - 1) + '…' : one
}
export const estimateRows = (text: string, w: number) =>
text.split('\n').reduce((sum, line) => sum + Math.ceil((stripAnsi(line).length || 1) / w), 0)
export const estimateRows = (text: string, w: number, compact = false) => {
let inCode = false
let rows = 0
for (const raw of text.split('\n')) {
const line = stripAnsi(raw)
if (line.startsWith('```')) {
if (!inCode) {
const lang = line.slice(3).trim()
if (lang) {
rows += Math.ceil((`${lang}`.length || 1) / w)
}
}
inCode = !inCode
continue
}
const trimmed = line.trim()
if (!inCode && trimmed.startsWith('|') && /^[|\s:-]+$/.test(trimmed)) {
continue
}
const rendered = inCode ? line : renderEstimateLine(line)
if (compact && !rendered.trim()) {
continue
}
rows += Math.ceil((rendered.length || 1) / w)
}
return Math.max(1, rows)
}
export const flat = (r: Record<string, string[]>) => Object.values(r).flat()