I am trying to write a function to check bowser's compatibility
export const FEATURE_WEBP = 'FEATURE_WEBP';
export type FeatureWebp = typeof FEATURE_WEBP;
export type FeatureWebpOptions = {
lossy?: boolean;
lossyless?: boolean;
alpha?: boolean;
animation?: boolean;
};
export type FeatureWebpCheckResult = FeatureWebpOptions;
export type Features = typeof features[number];
export type Options<T extends Features> = {
persist?: boolean;
} & T extends FeatureWebp
? FeatureWebpOptions
: never;
export type Result<T extends Features> = T extends FeatureWebp
? FeatureWebpOptions
: never;
export const features = [FEATURE_WEBP] as const;
export async function checkFeature<T extends Features>(
feature: T,
options?: Options<T>,
): Promise<Result<T> | null> {
switch (feature) {
case FEATURE_WEBP: {
return await checkWebp(options);
}
default:
return null;
}
}
export async function checkWebp(
options: FeatureWebpOptions = {},
): Promise<FeatureWebpCheckResult> {
const result: FeatureWebpCheckResult = {};
const testImages = {
lossy: '',
lossless: '',
alpha: "",
animation: "",
} as const;
const testImageRender = (data: string): Promise<boolean> => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = function () {
const result = img.width > 0 && img.height > 0;
resolve(result);
};
img.onerror = function (error) {
reject(error);
};
img.src = `data:image/webp;base64,${data}`;
});
};
switch (true) {
case options.lossy: {
result.lossy = await testImageRender(testImages.lossless);
}
case options.alpha: {
result.alpha = await testImageRender(testImages.alpha);
}
default:
break;
}
return result;
}