attempt to prevent thread blocking from fac

This commit is contained in:
jeffvli
2025-11-26 03:35:02 -08:00
parent 94a7829882
commit 948f428546
+31 -4
View File
@@ -14,14 +14,24 @@ export const getFastAverageColor = async (args: {
algorithm?: 'dominant' | 'simple' | 'sqrt'; algorithm?: 'dominant' | 'simple' | 'sqrt';
src: string; src: string;
}) => { }) => {
return new Promise<string>((resolve, reject) => {
setTimeout(() => {
const fac = new FastAverageColor(); const fac = new FastAverageColor();
const background = await fac.getColorAsync(args.src, { fac.getColorAsync(args.src, {
algorithm: args.algorithm || 'dominant', algorithm: args.algorithm || 'dominant',
ignoredColor: ignoredColors, ignoredColor: ignoredColors,
mode: 'speed', mode: 'speed',
})
.then((background) => {
resolve(background.rgb);
fac.destroy();
})
.catch((error) => {
fac.destroy();
reject(error);
});
});
}); });
return background.rgb;
}; };
export const useFastAverageColor = (args: { export const useFastAverageColor = (args: {
@@ -48,10 +58,15 @@ export const useFastAverageColor = (args: {
useEffect(() => { useEffect(() => {
let isMounted = true; let isMounted = true;
const fac = new FastAverageColor(); let fac: FastAverageColor | null = null;
if (src && srcLoaded) { if (src && srcLoaded) {
setIsLoading(true); setIsLoading(true);
setTimeout(() => {
if (!isMounted) return;
fac = new FastAverageColor();
fac.getColorAsync(src, { fac.getColorAsync(src, {
algorithm: algorithm || 'dominant', algorithm: algorithm || 'dominant',
ignoredColor: ignoredColors, ignoredColor: ignoredColors,
@@ -67,6 +82,10 @@ export const useFastAverageColor = (args: {
}); });
setIsLoading(false); setIsLoading(false);
} }
if (fac) {
fac.destroy();
fac = null;
}
}) })
.catch((e) => { .catch((e) => {
if (isMounted) { if (isMounted) {
@@ -79,6 +98,11 @@ export const useFastAverageColor = (args: {
}); });
setIsLoading(false); setIsLoading(false);
} }
if (fac) {
fac.destroy();
fac = null;
}
});
}); });
} else if (srcLoaded) { } else if (srcLoaded) {
if (isMounted) { if (isMounted) {
@@ -93,7 +117,10 @@ export const useFastAverageColor = (args: {
return () => { return () => {
isMounted = false; isMounted = false;
if (fac) {
fac.destroy(); fac.destroy();
fac = null;
}
}; };
}, [algorithm, srcLoaded, src, id]); }, [algorithm, srcLoaded, src, id]);