Files
thrilltrack-explorer/src/lib/cloudflareImageUtils.ts
2025-10-10 14:09:51 +00:00

62 lines
1.6 KiB
TypeScript

/**
* Cloudflare Images variant utilities
* Generates properly formatted URLs for Cloudflare Image variants
*/
export type CloudflareVariant =
| 'avatar'
| 'banner'
| 'bannermobile'
| 'card'
| 'cardthumb'
| 'logo'
| 'public';
const CLOUDFLARE_ACCOUNT_HASH = import.meta.env.VITE_CLOUDFLARE_ACCOUNT_HASH;
/**
* Build a Cloudflare image URL with specified variant
*/
export function getCloudflareImageUrl(
imageId: string | undefined,
variant: CloudflareVariant = 'public'
): string | undefined {
if (!imageId) return undefined;
return `https://imagedelivery.net/${CLOUDFLARE_ACCOUNT_HASH}/${imageId}/${variant}`;
}
/**
* Generate responsive image srcset for card images
* Useful for <img srcset> elements
*/
export function getCloudflareImageSrcSet(imageId: string | undefined): string | undefined {
if (!imageId) return undefined;
return [
`${getCloudflareImageUrl(imageId, 'cardthumb')} 600w`,
`${getCloudflareImageUrl(imageId, 'card')} 1200w`,
`${getCloudflareImageUrl(imageId, 'public')} 1366w`
].join(', ');
}
/**
* Get responsive banner URLs for mobile and desktop
*/
export function getBannerUrls(imageId: string | undefined) {
if (!imageId) return { mobile: undefined, desktop: undefined };
return {
mobile: getCloudflareImageUrl(imageId, 'bannermobile'),
desktop: getCloudflareImageUrl(imageId, 'banner')
};
}
/**
* Extract Cloudflare image ID from various URL formats
*/
export function extractCloudflareImageId(url: string): string | null {
// Match imagedelivery.net URLs
const match = url.match(/imagedelivery\.net\/[^\/]+\/([a-f0-9-]+)\//i);
return match ? match[1] : null;
}