Files
planet/frontend/src/utils/phaseProgress.ts
T

62 lines
2.0 KiB
TypeScript

export type PhaseProgressLike = {
phase?: string | null
phase_progress?: number | null
phase_message?: string | null
phase_current?: number | null
phase_total?: number | null
phase_unit?: string | null
}
const BYTE_UNIT_BASE = 1024
const BYTE_UNITS = ['B', 'KB', 'MB', 'GB'] as const
export function formatBytes(value: number): string {
if (!Number.isFinite(value) || value <= 0) return '0 B'
let size = value
let unitIndex = 0
while (size >= BYTE_UNIT_BASE && unitIndex < BYTE_UNITS.length - 1) {
size /= BYTE_UNIT_BASE
unitIndex += 1
}
const digits = unitIndex === 0 ? 0 : size >= 10 ? 1 : 2
return `${size.toFixed(digits)} ${BYTE_UNITS[unitIndex]}`
}
export function formatPhaseMetric(source: Pick<PhaseProgressLike, 'phase_current' | 'phase_total' | 'phase_unit'>): string | null {
const current = source.phase_current
const total = source.phase_total
if (typeof current !== 'number') return null
if (source.phase_unit === 'bytes') {
return typeof total === 'number' && total > 0
? `${formatBytes(current)} / ${formatBytes(total)}`
: formatBytes(current)
}
if (typeof total === 'number' && total > 0) {
return `${current} / ${total}${source.phase_unit ? ` ${source.phase_unit}` : ''}`
}
return `${current}${source.phase_unit ? ` ${source.phase_unit}` : ''}`
}
export function getPhaseDisplay(source: PhaseProgressLike, fallback = 'running'): string {
const phase = source.phase || fallback
const parts = [phase]
if (typeof source.phase_progress === 'number') {
parts.push(`${Math.round(source.phase_progress)}%`)
}
if (source.phase_message) {
parts.push(source.phase_message)
}
const metric = formatPhaseMetric(source)
if (metric) {
parts.push(metric)
}
return parts.join(' · ')
}
export function getPhaseSummary(source: PhaseProgressLike, fallback = 'running'): string {
const phase = source.phase || fallback
return typeof source.phase_progress === 'number'
? `${phase} ${Math.round(source.phase_progress)}%`
: phase
}