@@ -7,11 +7,8 @@ import {
77 staticText ,
88 type TextItem ,
99} from "@david/console-static-text" ;
10- import { isOutputTty } from "../utils.ts" ;
11- import { humanDownloadSize } from "./format.ts" ;
12- import { logger , LoggerRefreshItemKind } from "../logger.ts" ;
13-
14- const progressBars : RenderIntervalProgressBar [ ] = [ ] ;
10+ import { isOutputTty } from "./utils.ts" ;
11+ import { logger , LoggerRefreshItemKind } from "./logger.ts" ;
1512
1613/** Options for showing progress. */
1714export interface ProgressOptions {
@@ -32,7 +29,7 @@ export interface ProgressOptions {
3229/** A progress bar instance created via `$.progress(...)`. */
3330export class ProgressBar {
3431 #state: RenderState ;
35- #pb: RenderIntervalProgressBar ;
32+ #pb: DeferredItem ;
3633 #withCount = 0 ;
3734 #onLog: ( ...data : any [ ] ) => void ;
3835 #noClear: boolean ;
@@ -252,20 +249,15 @@ export function renderProgressBar(state: RenderState, size: ConsoleSize | undefi
252249 }
253250}
254251
255- export interface RenderIntervalProgressBar {
256- render ( size : ConsoleSize | undefined ) : TextItem [ ] ;
257- }
252+ const progressBars : DeferredItem [ ] = [ ] ;
258253
259- function addProgressBar ( render : ( size : ConsoleSize ) => TextItem [ ] ) : RenderIntervalProgressBar {
260- const pb = {
261- render,
262- } ;
263- progressBars . push ( pb ) ;
254+ function addProgressBar ( render : DeferredItem ) : DeferredItem {
255+ progressBars . push ( render ) ;
264256 refresh ( ) ;
265- return pb ;
257+ return render ;
266258}
267259
268- function removeProgressBar ( pb : RenderIntervalProgressBar ) {
260+ function removeProgressBar ( pb : DeferredItem ) {
269261 const index = progressBars . indexOf ( pb ) ;
270262 if ( index === - 1 ) {
271263 return false ;
@@ -278,15 +270,20 @@ function removeProgressBar(pb: RenderIntervalProgressBar) {
278270function refresh ( ) {
279271 logger . setItems (
280272 LoggerRefreshItemKind . ProgressBars ,
281- progressBars . map ( ( p ) => {
282- const item : DeferredItem = ( consoleSize ) => {
283- return p . render ( consoleSize ) ;
284- } ;
285- return item ;
286- } ) ,
273+ progressBars ,
287274 ) ;
288275}
289276
290277export function isShowingProgressBars ( ) {
291278 return isOutputTty && progressBars . length > 0 ;
292279}
280+
281+ const units = [ "B" , "KiB" , "MiB" , "GiB" , "TiB" , "PiB" , "EiB" , "ZiB" , "YiB" ] ;
282+
283+ export function humanDownloadSize ( byteCount : number , totalBytes ?: number ) {
284+ const exponentBasis = totalBytes ?? byteCount ;
285+ const exponent = Math . min ( units . length - 1 , Math . floor ( Math . log ( exponentBasis ) / Math . log ( 1024 ) ) ) ;
286+ const unit = units [ exponent ] ;
287+ const prettyBytes = ( Math . floor ( byteCount / Math . pow ( 1024 , exponent ) * 100 ) / 100 ) . toFixed ( exponent === 0 ? 0 : 2 ) ;
288+ return `${ prettyBytes } ${ unit } ` ;
289+ }
0 commit comments