noticebar.tsx 8.5 KB
Newer Older
V
vickyYe 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
import React, {
  useState,
  useEffect,
  useRef,
  FunctionComponent,
  useImperativeHandle,
  MouseEvent,
  CSSProperties,
} from 'react'
import './noticebar.scss'
import { number } from 'prop-types'
import Icon from '../icon'
import bem from '@/utils/bem'
import classNames from 'classnames'

export interface NoticeBarProps {
  // 滚动方向  across 横向 vertical 纵向
  direction: string
  className?: string
  style?: CSSProperties
  list: any
  standTime: number
  complexAm: boolean
  height: number
  text: string
  closeMode: boolean
  wrapable: boolean
  leftIcon: string
  color: string
  background: string
  delay: string | number
  scrollable: boolean
  speed: number
  rightIcon?: HTMLElement | any
  close?: (list?: any) => void
  click?: (item?: any) => void
}
const defaultProps = {
  // 滚动方向  across 横向 vertical 纵向
  direction: 'across',
  list: [],
  standTime: 1000,
  complexAm: false,
  height: 40,
  text: '',
  closeMode: false,
  wrapable: false,
  leftIcon: '',
  color: '',
  background: '',
  delay: 1,
  scrollable: true,
  speed: 50,
} as NoticeBarProps
export const NoticeBar: FunctionComponent<
  Partial<NoticeBarProps> & React.HTMLAttributes<HTMLDivElement>
> = (props) => {
  const {
    children,
    className,
    style,
    direction,
    list,
    standTime,
    complexAm,
    height,
    text,
    closeMode,
    wrapable,
    leftIcon,
    color,
    background,
    delay,
    scrollable,
    speed,
    rightIcon,
    close,
    click,
  } = { ...defaultProps, ...props }

  const wrap = useRef<HTMLDivElement>(null)
  const content = useRef<HTMLDivElement>(null)
  // const [scrollList,SetScrollList] = useState([])
  const [showNoticeBar, SetShowNoticeBar] = useState(true)
  let scrollList: any = useRef([])
  const [wrapWidth, SetWrapWidth] = useState(0)
  const [firstRound, SetFirstRound] = useState(true)
  const [duration, SetDuration] = useState(0)
  const [offsetWidth, SetOffsetW] = useState(0)
  const [animationClass, SetAnimationClass] = useState('')
  const [animate, SetAnimate] = useState(false)
  const [distance, SetDistance] = useState(0)
  const [timer, SetTimer] = useState(0)

  const [index, setIndex] = useState<number>(0)

  useEffect(() => {
    if (direction == 'vertical') {
      if (children) {
        let arr: any = []
        React.Children.map(children, (child) => {
          arr.push((child as any).props.children)
        })
        // SetScrollList([].concat(arr))
        scrollList.current = [].concat(arr)
      } else {
        // SetScrollList([].concat(list))
        scrollList.current = [].concat(list)
      }
      setTimeout(() => {
        complexAm ? startRoll() : startRollEasy()
      }, Number(standTime))
    } else {
      initScrollWrap(text)
    }
    return () => {
      clearInterval(timer)
    }
  }, [])

  const cloneChild = (listItem: any, listIndex: any) => {
    return React.Children.map(children, function (child: any, index) {
      if (child && index == listIndex) {
        return React.cloneElement(child, {
          key: listIndex,
          children: listItem,
        })
      }
    })
  }

  useEffect(() => {
    initScrollWrap(text)
  }, [text])

  useEffect(() => {
    if (list && list.length) {
      scrollList.current = [].concat(list)
    }
  }, [list])

  const initScrollWrap = (value: string) => {
    if (showNoticeBar == false) {
      return
    }
    setTimeout(() => {
      if (!wrap.current || !content.current) {
        return
      }
      const wrapW = wrap.current.getBoundingClientRect().width
      const offsetW = content.current.getBoundingClientRect().width

      if (scrollable && offsetW > wrapW) {
        SetWrapWidth(wrapW)
        SetOffsetW(offsetW)
        SetDuration(offsetW / speed)
        SetAnimationClass('play')
      } else {
        SetAnimationClass('')
      }
    })
  }
  const handleClick = (event: MouseEvent) => {
    click && click(event)
  }

  const onClickIcon = (event: MouseEvent) => {
    event.stopPropagation()
    SetShowNoticeBar(!closeMode)
    close && close(event)
  }

  const onAnimationEnd = () => {
    SetFirstRound(false)
    setTimeout(() => {
      SetDuration((offsetWidth + wrapWidth) / speed)
      SetAnimationClass('play-infinite')
    }, 0)
  }

  /**
   * 利益点滚动方式一
   */
  const startRollEasy = () => {
    showhorseLamp()
    let timerCurr = window.setInterval(
      showhorseLamp,
      ~~(height / speed / 4) * 1000 + Number(standTime)
    )
    SetTimer(timerCurr)
  }
  const showhorseLamp = () => {
    SetAnimate(true)
    setTimeout(() => {
      scrollList.current.push(scrollList.current[0])
      scrollList.current.shift()
      SetAnimate(false)
    }, ~~(height / speed / 4) * 1000)
  }

  const startRoll = () => {
    let timerCurr = setInterval(() => {
      let chunk = 100
      for (let i = 0; i < chunk; i++) {
        scroll(i, i < chunk - 1 ? false : true)
      }
    }, Number(standTime) + 100 * speed)
    SetTimer(timerCurr)
  }
  const scroll = (n: number, last: boolean) => {
    SetAnimate(true)
    setTimeout(() => {
      let long = distance
      long -= height / 100
      SetDistance(long)
      if (last) {
        scrollList.current.push(scrollList.current[0])
        scrollList.current.shift()
        SetDistance(0)
        SetAnimate(false)
      }
    }, n * speed)
  }
  /**
   * 点击滚动单元
   */
  const go = (item: any) => {
    click && click(item)
  }

  const handleClickIcon = () => {
    close && close(scrollList[0])
  }

  const iconShow = () => {
    if (leftIcon == 'close') {
      return false
    } else {
      return true
    }
  }

  const contentStyle = {
    paddingLeft: firstRound ? 0 : wrapWidth + 'px',
    animationDelay: (firstRound ? props.delay : 0) + 's',
    animationDuration: duration + 's',
  }

  const barStyle = {
    color: color,
    background: background,
    height: direction == 'vertical' ? `${height}px` : '',
  }

  const horseLampStyle = {
    transform: complexAm ? `translateY(${distance}px)` : '',
    transition: animate ? `all ${~~(height / speed / 4)}s` : '',
    marginTop: animate ? `-${height}px` : '',
  }

  const b = bem('noticebar')
  const noticebarClass = classNames({
    'nut-noticebar-page': true,
    withicon: closeMode,
    close: closeMode,
    wrapable: wrapable,
  })

  return (
    <div className={`${b()} ${className ? className : ''}`} style={style}>
      {showNoticeBar && direction == 'across' ? (
        <div className={noticebarClass} style={barStyle} onClick={handleClick}>
          <div
            className="left-icon"
            style={{ backgroundImage: `url(${leftIcon ? leftIcon : ''})` }}
          >
            {!leftIcon ? <Icon name={'notice'} size="16" color={color} /> : null}
          </div>
          <div ref={wrap} className="wrap">
            <div
              ref={content}
              className={`content ${animationClass} ${!scrollable && !wrapable && 'nut-ellipsis'}`}
              style={contentStyle}
              onAnimationEnd={onAnimationEnd}
            >
              {children}
              {text}
            </div>
          </div>
          {closeMode ? (
            <div className="right-icon" onClick={onClickIcon}>
              <Icon name={'close'} color={color} />
            </div>
          ) : null}
        </div>
      ) : scrollList.current.length > 0 && direction == 'vertical' ? (
        <div className="nut-noticebar-vertical" style={barStyle}>
          {children ? (
            <div className="horseLamp_list" style={horseLampStyle}>
               
              {scrollList.current.map((item: any, index: any) => {
                return cloneChild(item, index)
              })}
            </div>
          ) : (
            <ul className="horseLamp_list" style={horseLampStyle}>
              {scrollList.current.map((item: any, index: any) => {
                return (
                  <li
                    className="horseLamp_list_item"
                    style={{ height: height }}
                    key={index}
                    onClick={() => {
                      go(item)
                    }}
                  >
                    {item}
                  </li>
                )
              })}
            </ul>
          )}
          <div
            className="go"
            onClick={() => {
              handleClickIcon()
            }}
          >
            {rightIcon ? (
              rightIcon
            ) : closeMode ? (
              <Icon name="cross" color={color} size="11px" />
            ) : null}
          </div>
        </div>
      ) : null}
    </div>
  )
}

NoticeBar.defaultProps = defaultProps
NoticeBar.displayName = 'NutNoticeBar'