import * as React from 'react';
import styles from './index.less';
import { IRenderer } from '../../index.data';

const RichTextRenderer: IRenderer<string> = ({ value, style }) => {
  // 取ref_size_sensor高度, 设置为ref的高度(ref_size_sensor总是正确的)
  const ref = React.useRef<HTMLDivElement>(null);
  const ref_size_senser = React.useRef<HTMLDivElement>(null);

  const [height, setHeight] = React.useState<number>(0);

  React.useEffect(() => {
    const newHeight = ref_size_senser.current!.getBoundingClientRect().height;
    if (newHeight > 0) {
      setHeight(newHeight);
    }
  }, [value, JSON.stringify(style)]);

  const newStyle = {
    ...style,
    whiteSpace: 'normal',
    wordBreak: 'break-all',
    height: height > 0 ? height : undefined,
    overflow: 'hidden',
  } as React.CSSProperties;
  return (
    <div ref={ref} className={styles['container']} style={newStyle}>
      <div
        ref={ref_size_senser}
        className={styles['rich']}
        style={style}
        dangerouslySetInnerHTML={{ __html: value || '' }}
      ></div>
    </div>
  );
};

export default RichTextRenderer;
