import { ReactNode } from 'react'; import { isObject, isFunction, isArray } from 'lodash'; import { VevProps } from '@vev/utils'; import { flattenObject } from './generate-title'; export const generateImage = ( data: VevProps | VevProps[] | string, schema?: VevProps | VevProps[] | string, ): string | ReactNode | undefined => { let image: string | ReactNode | undefined; if (Array.isArray(schema)) schema = schema.find((s) => s.preview) || schema[0]; if (isObject(schema) && schema?.preview) { if (isFunction(schema.preview)) { ({ image } = schema.preview(data as VevProps)); } else { image = schema?.preview?.image; } } if (!image) { const values = !isArray(data) ? flattenObject(data) : data || []; for (const value of values) { const data: string[] = Object.values(value || {}) as string[]; const imageInArr = data.find( (child: string) => typeof child === 'string' && child.includes('cdn-cgi/image'), ); if (imageInArr) { image = imageInArr; } } } if (image && typeof image === 'object' && 'url' in (image as any)) { image = (image as any).url; } return image; }; /** * Finds the first image field in the schema and returns its URL from the item data, * or `true` if the field exists but has no value (to signal a fallback icon). */ export const getImageFieldUrl = ( data: Record, schema?: VevProps | VevProps[] | string, ): string | true | undefined => { if (!isObject(schema) || !('fields' in schema)) return undefined; const imageField = (schema.fields as VevProps[])?.find((f) => f.type === 'image'); if (!imageField?.name) return undefined; const imageValue = data[imageField.name]; if (imageValue?.url) return imageValue.url; return true; // field exists but no image set };