import { Button } from 'exchange-elements/v2';
import React from 'react';
import { Observable } from 'rxjs';
import { TrashIcon } from '@components/Icon';
import { LegendModel, Ohlc, ohlcValuesToShowForMainSerie } from '@core/Legend';
import { OHLCConfig } from '../../types';
import { useObservable } from '../../utils';
import styles from './index.module.scss';
export interface LegendProps {
ohlcConfig?: OHLCConfig;
viewModel: Observable<LegendModel>;
}
type LegendItem = LegendModel[number];
type LegendValue = NonNullable<LegendItem['values'][keyof Ohlc]>;
type LegendEntry = [keyof Ohlc, LegendValue];
export const LegendComponent: React.FC<LegendProps> = ({ ohlcConfig, viewModel }) => {
const model = useObservable(viewModel) ?? [];
const showOhlc = ohlcConfig?.show;
const getEntries = (item: LegendItem): LegendEntry[] => {
return Object.entries(item.values) as LegendEntry[];
};
const shouldShowEntry = (item: LegendItem, key: keyof Ohlc): boolean => {
if (item.isIndicator) {
return true;
}
return Boolean(showOhlc && ohlcValuesToShowForMainSerie.includes(key));
};
const renderValue = (item: LegendItem, [key, value]: LegendEntry, index: number) => {
if (!shouldShowEntry(item, key)) {
return null;
}
return (
<div
key={`${item.name}-${String(key)}-${index}`}
className={styles.item}
>
{value.name} <span style={{ color: value.color }}>{value.value}</span>
</div>
);
};
return (
<section className={styles.legend}>
{model.map((item) => (
<div
key={item.name}
className={styles.row}
>
<div className={styles.symbol}>{item.name}</div>
{getEntries(item).map((entry, index) => renderValue(item, entry, index))}
{item.remove && (
<Button
size="sm"
className={styles.button}
onClick={item.remove}
label={<TrashIcon />}
/>
)}
</div>
))}
</section>
);
};