import { isObject, capitalize, isFunction } from 'lodash'; import { VevProps } from '@vev/utils'; export const generateTitle = ( data: { [key: string]: any } | { [key: string]: any }[] | string, schema?: VevProps | VevProps[] | string, ): string | undefined => { if (Array.isArray(schema)) schema = schema.find((s) => s.preview) || schema[0]; let title: string | undefined; if (isObject(schema) && schema?.preview) { if (isFunction(schema.preview)) { ({ title } = schema.preview(data as VevProps)); } else { title = schema?.preview?.title; } } if (!title) { if (typeof data === 'string' || typeof data === 'number') return data.toString(); const values = isObject(data) ? flattenObject(data) : data || []; const haveString = values.some( (val: string | number) => typeof val === 'string' || (typeof val === 'number' && val), ); const stringArr = haveString ? values : values.map((val: string | number | { [key: string]: any }) => typeof val === 'string' || typeof val === 'number' ? val : val?.key, ); const titleObj = stringArr .filter(Boolean) .find((v) => (typeof v === 'string' || typeof v === 'number') && v) as string; title = titleObj?.toString() || capitalize((isObject(data) && Object.keys(data)[0]) || 'Unknown') || JSON.stringify(data) || 'Unknown'; } return title.length >= 34 ? `${title.slice(0, 34)}...` : title; }; export const flattenObject = (data: any): any[] => { let values = Object.values(data); for (const value of values) { if (isObject(value)) { values = [...values, ...flattenObject(value)]; } } return values; };