import * as React from 'react'; import { cloneElement, ReactElement, ReactNode, SVGProps } from 'react'; import last from 'es-toolkit/compat/last'; import { Label, ContentType, Props as LabelProps, LabelPosition, isLabelContentAFunction } from './Label'; import { Layer } from '../container/Layer'; import { findAllByType, filterProps } from '../util/ReactUtils'; import { getValueByDataKey } from '../util/ChartUtils'; import { DataKey, ViewBox } from '../util/types'; import { isNullish } from '../util/DataUtils'; interface Data { value?: number | string | Array; payload?: any; parentViewBox?: ViewBox; } interface LabelListProps { id?: string; // why is data a prop here, shouldn't this only come from chart data? data?: ReadonlyArray; valueAccessor?: (entry: T, index: number) => string | number; clockWise?: boolean; dataKey?: DataKey>; content?: ContentType; textBreakAll?: boolean; position?: LabelPosition; offset?: LabelProps['offset']; angle?: number; formatter?: (label: React.ReactNode) => React.ReactNode; } export type Props = SVGProps & LabelListProps; export type ImplicitLabelListType = | boolean | ReactElement | ((props: any) => ReactElement) | Props; const defaultAccessor = (entry: Data) => (Array.isArray(entry.value) ? last(entry.value) : entry.value); export function LabelList({ valueAccessor = defaultAccessor, ...restProps }: Props) { const { data, dataKey, clockWise, id, textBreakAll, ...others } = restProps; if (!data || !data.length) { return null; } return ( {data.map((entry, index) => { const value = isNullish(dataKey) ? valueAccessor(entry, index) : (getValueByDataKey(entry && entry.payload, dataKey) as string | number); const idProps = isNullish(id) ? {} : { id: `${id}-${index}` }; return ( ); } LabelList.displayName = 'LabelList'; function parseLabelList(label: unknown, data: ReadonlyArray) { if (!label) { return null; } if (label === true) { return ; } if (React.isValidElement(label) || isLabelContentAFunction(label)) { return ; } if (typeof label === 'object') { return ; } return null; } function renderCallByParent( parentProps: { children?: ReactNode; label?: unknown }, data: ReadonlyArray, checkPropsLabel = true, ) { if (!parentProps || (!parentProps.children && checkPropsLabel && !parentProps.label)) { return null; } const { children } = parentProps; const explicitChildren = findAllByType(children, LabelList).map((child, index) => cloneElement(child, { data, // eslint-disable-next-line react/no-array-index-key key: `labelList-${index}`, }), ); if (!checkPropsLabel) { return explicitChildren; } const implicitLabelList = parseLabelList(parentProps.label, data); return [implicitLabelList, ...explicitChildren]; } LabelList.renderCallByParent = renderCallByParent;