church-website/src/utils/dto/gallery.ts
Benno Tielen 3148231cc8
Some checks failed
Deploy / deploy (push) Has been cancelled
fix: return orignal if size not available
2026-03-20 01:28:34 +01:00

84 lines
1.7 KiB
TypeScript

import { Media } from '@/payload-types'
import { GalleryItem } from '@/components/Gallery/Gallery'
import { StaticImageData } from 'next/image'
type Items = {
photo: string | Media;
id?: string | null;
}[];
export const transformGallery = (items: Items) => {
const galleryItems: GalleryItem[] = []
items.forEach(item => {
if (typeof item === "object" && typeof item.photo === "object" && item.id) {
const thumbnail = getPhoto("gallery", item.photo);
const image = getPhoto("tablet", item.photo);
if (thumbnail && image) {
galleryItems.push({
alt: item.photo.alt,
id: item.id,
thumbnail,
image
})
}
}
})
return galleryItems
}
type Size = "thumbnail" | "banner" | "gallery" | "tablet";
type OptionalMedia = string | null | undefined | Media;
/**
* Get image data from optional media
*
*/
export const getPhoto = (size: Size, data: OptionalMedia): StaticImageData | undefined => {
if (!data) {
return undefined;
}
if (typeof data === "string") {
return undefined;
}
if (!data.sizes) {
return undefined;
}
const sizeData = data.sizes[size]
if (!sizeData) {
// return original
if (data.url && data.width && data.height)
return {
src: data.url,
width: data.width,
height: data.height
};
return undefined;
}
if (sizeData.url && sizeData.width && sizeData.height) {
return {
src: sizeData.url,
width: sizeData.width,
height: sizeData.height
}
}
// return original
if (data.url && data.width && data.height)
return {
src: data.url,
width: data.width,
height: data.height
};
return undefined;
}