infiniteloading.tsx 7.3 KB
Newer Older
L
liuyijun 已提交
1 2 3
import React, { useState, useEffect, useRef, FunctionComponent } from 'react'
import bem from '@/utils/bem'
import classNames from 'classnames'
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import Icon from '@/packages/icon'
import './infiniteloading.scss'

export interface InfiniteloadingProps {
  hasMore: boolean
  threshold: number
  containerId: string
  useWindow: boolean
  useCapture: boolean
  isOpenRefresh: boolean
  pullIcon: string
  pullTxt: string
  loadIcon: string
  loadTxt: string
  loadMoreTxt: string
L
liuyijun 已提交
19 20
  className: string
  style: React.CSSProperties
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
  refresh: (param: () => void) => void
  loadMore: (param: () => void) => void
  scrollChange: (param: number) => void
}

declare var window: Window & { webkitRequestAnimationFrame: any }
const defaultProps = {
  hasMore: true,
  threshold: 200,
  containerId: '',
  useWindow: true,
  useCapture: false,
  isOpenRefresh: false,
  pullIcon:
    'https://img10.360buyimg.com/imagetools/jfs/t1/169863/6/4565/6306/60125948E7e92774e/40b3a0cf42852bcb.png',
  pullTxt: '松开刷新',
  loadIcon:
    'https://img10.360buyimg.com/imagetools/jfs/t1/169863/6/4565/6306/60125948E7e92774e/40b3a0cf42852bcb.png',
  loadTxt: '加载中···',
  loadMoreTxt: '哎呀,这里是底部了啦',
} as InfiniteloadingProps

export const Infiniteloading: FunctionComponent<
  Partial<InfiniteloadingProps> & React.HTMLAttributes<HTMLDivElement>
> = (props) => {
  const {
    children,
    hasMore,
    threshold,
    containerId,
    useWindow,
    useCapture,
    isOpenRefresh,
    pullIcon,
    pullTxt,
    loadIcon,
    loadTxt,
    loadMoreTxt,
L
liuyijun 已提交
59
    className,
60 61 62
    refresh,
    loadMore,
    scrollChange,
L
liuyijun 已提交
63
    ...restProps
64 65 66 67 68 69 70 71 72 73 74 75 76 77
  } = {
    ...defaultProps,
    ...props,
  }
  const [isInfiniting, setIsInfiniting] = useState(false)
  const scroller = useRef<HTMLDivElement>(null)
  const refreshTop = useRef<HTMLDivElement>(null)
  const scrollEl = useRef<Window | HTMLElement | (Node & ParentNode)>(window)
  const isTouching = useRef(false)
  const beforeScrollTop = useRef(0)
  const refreshMaxH = useRef(0)
  const y = useRef(0)
  const distance = useRef(0)

L
liuyijun 已提交
78 79 80
  const b = bem('infiniteloading')
  const classes = classNames(className, b())

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
  useEffect(() => {
    const parentElement = getParentElement(scroller.current as HTMLDivElement) as Node & ParentNode
    scrollEl.current = useWindow ? window : parentElement
    scrollEl.current.addEventListener('scroll', handleScroll, useCapture)

    return () => {
      scrollEl.current.removeEventListener('scroll', handleScroll, useCapture)
    }
  }, [hasMore, isInfiniting])

  useEffect(() => {
    const element = scroller.current as HTMLDivElement
    element.addEventListener('touchmove', preventDefault, { passive: false })

    return () => {
      element.removeEventListener('touchmove', preventDefault, {
        passive: false,
      } as EventListenerOptions)
    }
  }, [])

  const preventDefault = (event: TouchEvent) => {
    event.preventDefault()
  }

  const getStyle = () => {
    return {
      height: distance.current < 0 ? `0px` : `${distance.current}px`,
      transition: isTouching.current
        ? `height 0s cubic-bezier(0.25,0.1,0.25,1)`
        : `height 0.2s cubic-bezier(0.25,0.1,0.25,1)`,
    }
  }

  const getParentElement = (el: HTMLElement) => {
    return !!containerId ? document.querySelector(`#${containerId}`) : el && el.parentNode
  }

  const handleScroll = () => {
    requestAniFrame()(() => {
      if (!isScrollAtBottom() || !hasMore || isInfiniting) {
        return false
      } else {
        setIsInfiniting(true)
        loadMore && loadMore(infiniteDone)
      }
    })
  }

  const infiniteDone = () => {
    setIsInfiniting(false)
  }

  const refreshDone = () => {
    distance.current = 0
    ;(refreshTop.current as HTMLDivElement).style.height = `${distance.current}px`
    isTouching.current = false
  }

  const touchStart = (event: React.TouchEvent<HTMLDivElement>) => {
    if (beforeScrollTop.current === 0 && !isTouching.current && isOpenRefresh) {
      y.current = event.touches[0].pageY
      isTouching.current = true
      const childHeight = ((refreshTop.current as HTMLDivElement).firstElementChild as HTMLElement)
        .offsetHeight
      refreshMaxH.current = Math.floor(childHeight * 1 + 10)
    }
  }

  const touchMove = (event: React.TouchEvent<HTMLDivElement>) => {
    distance.current = event.touches[0].pageY - y.current
    if (distance.current > 0 && isTouching.current) {
      if (distance.current >= refreshMaxH.current) {
        distance.current = refreshMaxH.current
        ;(refreshTop.current as HTMLDivElement).style.height = `${distance.current}px`
      } else {
        ;(refreshTop.current as HTMLDivElement).style.height = `${distance.current}px`
      }
    } else {
      distance.current = 0
      isTouching.current = false
    }
  }

  const touchEnd = () => {
    if (distance.current < refreshMaxH.current) {
      distance.current = 0
    } else {
      refresh && refresh(refreshDone)
    }
  }

  const requestAniFrame = () => {
    return (
      window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      function (callback) {
        window.setTimeout(callback, 1000 / 60)
      }
    )
  }

  const getWindowScrollTop = () => {
    return window.pageYOffset !== undefined
      ? window.pageYOffset
      : (document.documentElement || document.body.parentNode || document.body).scrollTop
  }

  const calculateTopPosition = (el: HTMLElement): number => {
    return !el ? 0 : el.offsetTop + calculateTopPosition(el.offsetParent as HTMLElement)
  }

  const isScrollAtBottom = () => {
    let offsetDistance = 0
    let resScrollTop = 0
    let direction = 'down'
    const windowScrollTop = getWindowScrollTop()
    if (useWindow) {
      if (scroller.current) {
        offsetDistance =
          calculateTopPosition(scroller.current) +
          scroller.current.offsetHeight -
          windowScrollTop -
          window.innerHeight
      }
      resScrollTop = windowScrollTop
    } else {
      const { scrollHeight, clientHeight, scrollTop } = scrollEl.current as HTMLElement
      offsetDistance = scrollHeight - clientHeight - scrollTop
      resScrollTop = scrollTop
    }
    if (beforeScrollTop.current > resScrollTop) {
      direction = 'up'
    } else {
      direction = 'down'
    }
    beforeScrollTop.current = resScrollTop
    scrollChange && scrollChange(resScrollTop)
    return offsetDistance <= threshold && direction == 'down'
  }

  return (
    <div
L
liuyijun 已提交
224
      className={classes}
225 226 227 228
      ref={scroller}
      onTouchStart={(event) => touchStart(event)}
      onTouchMove={(event) => touchMove(event)}
      onTouchEnd={() => touchEnd()}
L
liuyijun 已提交
229
      {...restProps}
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    >
      <div className="nut-infinite-top" ref={refreshTop} style={getStyle()}>
        <div className="top-box">
          <Icon className="top-img" name={pullIcon} />
          <span className="top-text">{pullTxt}</span>
        </div>
      </div>
      <div className="nut-infinite-container">{children}</div>
      <div className="nut-infinite-bottom">
        {isInfiniting ? (
          <div className="bottom-box">
            <Icon className="bottom-img" name={loadIcon} />
            <div className="bottom-text">{loadTxt}</div>
          </div>
        ) : (
          !hasMore && <div className="tips">{loadMoreTxt}</div>
        )}
      </div>
    </div>
  )
}

Infiniteloading.defaultProps = defaultProps
Infiniteloading.displayName = 'NutInfiniteloading'