| 20 | } |
| 21 | |
| 22 | export function progress({ |
| 23 | style = 'heavy', |
| 24 | max: userMax = 100, |
| 25 | size: userSize = 40, |
| 26 | ...spinnerOptions |
| 27 | }: ProgressOptions = {}): ProgressResult { |
| 28 | const spin = spinner(spinnerOptions); |
| 29 | let value = 0; |
| 30 | let previousMessage = ''; |
| 31 | |
| 32 | const max = Math.max(1, userMax); |
| 33 | const size = Math.max(1, userSize); |
| 34 | |
| 35 | const activeStyle = (state: State) => { |
| 36 | switch (state) { |
| 37 | case 'initial': |
| 38 | case 'active': |
| 39 | return (text: string) => styleText('magenta', text); |
| 40 | case 'error': |
| 41 | case 'cancel': |
| 42 | return (text: string) => styleText('red', text); |
| 43 | case 'submit': |
| 44 | return (text: string) => styleText('green', text); |
| 45 | default: |
| 46 | return (text: string) => styleText('magenta', text); |
| 47 | } |
| 48 | }; |
| 49 | const drawProgress = (state: State, msg: string) => { |
| 50 | const active = Math.floor((value / max) * size); |
| 51 | return `${activeStyle(state)(S_PROGRESS_CHAR[style].repeat(active))}${styleText('dim', S_PROGRESS_CHAR[style].repeat(size - active))} ${msg}`; |
| 52 | }; |
| 53 | |
| 54 | const start = (msg = '') => { |
| 55 | previousMessage = msg; |
| 56 | spin.start(drawProgress('initial', msg)); |
| 57 | }; |
| 58 | const advance = (step = 1, msg?: string): void => { |
| 59 | value = Math.min(max, step + value); |
| 60 | spin.message(drawProgress('active', msg ?? previousMessage)); |
| 61 | previousMessage = msg ?? previousMessage; |
| 62 | }; |
| 63 | return { |
| 64 | start, |
| 65 | stop: spin.stop, |
| 66 | cancel: spin.cancel, |
| 67 | error: spin.error, |
| 68 | clear: spin.clear, |
| 69 | advance, |
| 70 | isCancelled: spin.isCancelled, |
| 71 | message: (msg: string) => advance(0, msg), |
| 72 | }; |
| 73 | } |