| 20 | } |
| 21 | |
| 22 | export function createShimmerProgress(): ShimmerProgress { |
| 23 | let lastPhase = ''; |
| 24 | |
| 25 | const workerPath = path.join(__dirname, 'shimmer-worker.js'); |
| 26 | const worker = new Worker(workerPath, { |
| 27 | workerData: { startTime: Date.now() }, |
| 28 | }); |
| 29 | |
| 30 | return { |
| 31 | onProgress(progress: IndexProgress) { |
| 32 | const phaseName = PHASE_NAMES[progress.phase] || progress.phase; |
| 33 | |
| 34 | if (progress.phase !== lastPhase && lastPhase) { |
| 35 | worker.postMessage({ type: 'finish-phase' }); |
| 36 | } |
| 37 | lastPhase = progress.phase; |
| 38 | |
| 39 | let percent = -1; |
| 40 | let count = 0; |
| 41 | if (progress.total > 0) { |
| 42 | percent = Math.round((progress.current / progress.total) * 100); |
| 43 | } else if (progress.current > 0) { |
| 44 | count = progress.current; |
| 45 | } |
| 46 | |
| 47 | worker.postMessage({ |
| 48 | type: 'update', |
| 49 | phase: progress.phase, |
| 50 | phaseName, |
| 51 | percent, |
| 52 | count, |
| 53 | }); |
| 54 | }, |
| 55 | |
| 56 | stop() { |
| 57 | return new Promise<void>((resolve) => { |
| 58 | const timeout = setTimeout(() => { |
| 59 | worker.terminate().then(() => resolve()); |
| 60 | }, 2000); |
| 61 | |
| 62 | worker.on('message', (msg: { type: string }) => { |
| 63 | if (msg.type === 'stopped') { |
| 64 | clearTimeout(timeout); |
| 65 | worker.terminate().then(() => resolve()); |
| 66 | } |
| 67 | }); |
| 68 | |
| 69 | worker.postMessage({ type: 'stop' }); |
| 70 | }); |
| 71 | }, |
| 72 | }; |
| 73 | } |