import type React from 'react'; import type {YDBDefinitionListItem} from './YDBDefinitionList'; type NameMap = { [key in keyof T]?: string; }; type ContentFormatters = { [key in keyof T]?: (value: T[key]) => React.ReactNode; }; function formatName(key: keyof Shape, map: NameMap) { return map[key] ?? String(key); } function formatContent( key: Key, value: Shape[Key], formatters: ContentFormatters, defaultFormatter?: (value: Shape[Key]) => React.ReactNode, ) { const formatter = formatters[key] || defaultFormatter; return formatter ? formatter(value) : value; } interface CreateDefinitionFormatterOptions { contents?: ContentFormatters; names?: NameMap; defaultContentFormatter?: (value: Shape[keyof Shape]) => React.ReactNode; } export function createDefinitionFormatter>({ contents, names, defaultContentFormatter, }: CreateDefinitionFormatterOptions) { return (key: Key, value: Shape[Key]): YDBDefinitionListItem => { return { name: formatName(key, names || {}), content: formatContent(key, value, contents || {}, defaultContentFormatter), }; }; } export const formatObjectToDefinitionItems = >( formatter: (key: Key, value: Shape[Key]) => YDBDefinitionListItem, obj?: Partial, ): YDBDefinitionListItem[] => { if (!obj) { return []; } return Object.entries(obj) .map(([key, value]) => formatter(key as keyof Shape, value as Shape[keyof Shape])) .filter(({content}) => Boolean(content)); };