| 1 | import speedometer from './speedometer.js';
|
|---|
| 2 | import throttle from './throttle.js';
|
|---|
| 3 | import utils from '../utils.js';
|
|---|
| 4 |
|
|---|
| 5 | export const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
|
|---|
| 6 | let bytesNotified = 0;
|
|---|
| 7 | const _speedometer = speedometer(50, 250);
|
|---|
| 8 |
|
|---|
| 9 | return throttle((e) => {
|
|---|
| 10 | if (!e || typeof e.loaded !== 'number') {
|
|---|
| 11 | return;
|
|---|
| 12 | }
|
|---|
| 13 | const rawLoaded = e.loaded;
|
|---|
| 14 | const total = e.lengthComputable ? e.total : undefined;
|
|---|
| 15 | const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
|
|---|
| 16 | const progressBytes = Math.max(0, loaded - bytesNotified);
|
|---|
| 17 | const rate = _speedometer(progressBytes);
|
|---|
| 18 |
|
|---|
| 19 | bytesNotified = Math.max(bytesNotified, loaded);
|
|---|
| 20 |
|
|---|
| 21 | const data = {
|
|---|
| 22 | loaded,
|
|---|
| 23 | total,
|
|---|
| 24 | progress: total ? loaded / total : undefined,
|
|---|
| 25 | bytes: progressBytes,
|
|---|
| 26 | rate: rate ? rate : undefined,
|
|---|
| 27 | estimated: rate && total ? (total - loaded) / rate : undefined,
|
|---|
| 28 | event: e,
|
|---|
| 29 | lengthComputable: total != null,
|
|---|
| 30 | [isDownloadStream ? 'download' : 'upload']: true,
|
|---|
| 31 | };
|
|---|
| 32 |
|
|---|
| 33 | listener(data);
|
|---|
| 34 | }, freq);
|
|---|
| 35 | };
|
|---|
| 36 |
|
|---|
| 37 | export const progressEventDecorator = (total, throttled) => {
|
|---|
| 38 | const lengthComputable = total != null;
|
|---|
| 39 |
|
|---|
| 40 | return [
|
|---|
| 41 | (loaded) =>
|
|---|
| 42 | throttled[0]({
|
|---|
| 43 | lengthComputable,
|
|---|
| 44 | total,
|
|---|
| 45 | loaded,
|
|---|
| 46 | }),
|
|---|
| 47 | throttled[1],
|
|---|
| 48 | ];
|
|---|
| 49 | };
|
|---|
| 50 |
|
|---|
| 51 | export const asyncDecorator =
|
|---|
| 52 | (fn) =>
|
|---|
| 53 | (...args) =>
|
|---|
| 54 | utils.asap(() => fn(...args));
|
|---|