import './style.less' import classnames from 'classnames' import React, { PureComponent } from 'react' import Avatar, { genderList } from '../avatar/index' interface RightText { num: number text: string } interface TextItem { name: string text: string gender: genderList } export interface Props { textList: Array rightText: RightText background: string duration: number className?: string isPad?: boolean watchVisible?: boolean watchCheckDuration?: number } export default class Subtitle extends PureComponent { public static defaultProps = { background: '#9468D9', duration: 1000, watchCheckDuration: 100 } public state = { transiting: false, currentIndex: 0 } public timeoutToken: NodeJS.Timeout | null = null public intervalToekn: number | null = null public el: HTMLDivElement | null = null public visible = true public scheduleNextTransition() { this.timeoutToken = setTimeout(() => { this.setState({ transiting: true }) }, this.props.duration) } public componentDidMount() { if (this.props.watchVisible) { this.intervalToekn = setInterval(() => { const { width } = (this.el as HTMLDivElement).getBoundingClientRect() if (width && !this.visible) { this.visible = true this.terminateCurrentTransition() } if (!width && this.visible) { this.visible = false } }, this.props.watchCheckDuration) } this.scheduleNextTransition() } public getNextIndex() { const { currentIndex: index } = this.state const nextIndex = index + 1 return nextIndex === this.props.textList.length ? 0 : nextIndex } public terminateCurrentTransition = () => { this.setState({ transiting: false, currentIndex: this.getNextIndex() }) this.scheduleNextTransition() } public componentWillUnmount() { if (this.timeoutToken) clearTimeout(this.timeoutToken) if (this.props.watchVisible) clearInterval(this.intervalToekn as number) } public render() { const { rightText, background, textList, isPad, className } = this.props const { transiting, currentIndex } = this.state const { num, text } = rightText const list = textList.slice(currentIndex, currentIndex + 2) if (list.length === 1) list.push(textList[0]) return (
(this.el = el)} style={{ background }} >
{list.map(({ name, text, gender }, index) => (
{name}
{text}
))}
{num} {text}
) } }