Исправлена блокировка потока при вставке изображений, оптимизирован код и ответственность

This commit is contained in:
RoyceDa
2026-02-19 21:43:27 +02:00
parent a38a331cd1
commit 53535d68e0
7 changed files with 147 additions and 54 deletions

View File

@@ -0,0 +1,39 @@
// ...existing code...
const worker = new Worker(new URL('./image.worker.ts', import.meta.url), { type: 'module' });
type WorkerReq =
| { id: number; type: 'blurhashToBase64Image'; payload: { blurhash: string; width: number; height: number } }
| { id: number; type: 'base64ImageToBlurhash'; payload: { base64Image: string } };
type WorkerRes =
| { id: number; ok: true; data: string }
| { id: number; ok: false; error: string };
let seq = 0;
const pending = new Map<number, (res: WorkerRes) => void>();
worker.onmessage = (e: MessageEvent<WorkerRes>) => {
const res = e.data;
const cb = pending.get(res.id);
if (cb) {
pending.delete(res.id);
cb(res);
}
};
function callWorker(req: Omit<WorkerReq, 'id'>): Promise<string> {
return new Promise((resolve, reject) => {
const id = ++seq;
pending.set(id, (res) => (res.ok ? resolve(res.data) : reject(res.error)));
worker.postMessage({ ...req, id });
});
}
export function blurhashToBase64Image(blurhash: string, width: number, height: number): Promise<string> {
return callWorker({ type: 'blurhashToBase64Image', payload: { blurhash, width, height } });
}
export function base64ImageToBlurhash(base64Image: string): Promise<string> {
return callWorker({ type: 'base64ImageToBlurhash', payload: { base64Image } });
}
// ...existing code...