index.tsx 19.0 KB
Newer Older
D
DCloud_LXH 已提交
1 2 3 4 5 6 7 8 9 10
import {
  Ref,
  ref,
  ExtractPropTypes,
  computed,
  reactive,
  onMounted,
  onBeforeUnmount,
  onActivated,
  watch,
D
DCloud_LXH 已提交
11
  SetupContext,
12
  nextTick,
D
DCloud_LXH 已提交
13 14 15 16 17 18 19 20 21 22 23 24
} from 'vue'
import { passive } from '@dcloudio/uni-shared'
import { initScrollBounce, disableScrollBounce } from '../../helpers/scroll'
import {
  useCustomEvent,
  CustomEventTrigger,
  EmitEvent,
} from '../../helpers/useEvent'
import { defineBuiltInComponent } from '@dcloudio/uni-components'

type HTMLRef = Ref<HTMLElement | null>
type Props = ExtractPropTypes<typeof props>
25
type RefreshState = 'refreshing' | 'restore' | 'pulling' | 'refresherabort' | ''
D
DCloud_LXH 已提交
26
type Direction = 'x' | 'y'
D
DCloud_LXH 已提交
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
interface State {
  lastScrollTop: number
  lastScrollLeft: number
  lastScrollToUpperTime: number
  lastScrollToLowerTime: number
  refresherHeight: number
  refreshRotate: number
  refreshState: RefreshState
}

const passiveOptions = passive(true)

const props = {
  scrollX: {
    type: [Boolean, String],
    default: false,
  },
  scrollY: {
    type: [Boolean, String],
    default: false,
  },
  upperThreshold: {
    type: [Number, String],
    default: 50,
  },
  lowerThreshold: {
    type: [Number, String],
    default: 50,
  },
  scrollTop: {
    type: [Number, String],
    default: 0,
  },
  scrollLeft: {
    type: [Number, String],
    default: 0,
  },
  scrollIntoView: {
    type: String,
    default: '',
  },
  scrollWithAnimation: {
    type: [Boolean, String],
    default: false,
  },
  enableBackToTop: {
    type: [Boolean, String],
    default: false,
  },
  refresherEnabled: {
    type: [Boolean, String],
    default: false,
  },
  refresherThreshold: {
    type: Number,
    default: 45,
  },
  refresherDefaultStyle: {
    type: String,
    default: 'back',
  },
  refresherBackground: {
    type: String,
    default: '#fff',
  },
  refresherTriggered: {
    type: [Boolean, String],
    default: false,
  },
}

export default /*#__PURE__*/ defineBuiltInComponent({
  name: 'ScrollView',
  compatConfig: {
    MODE: 3,
  },
  props,
D
DCloud_LXH 已提交
104 105 106 107 108 109 110 111
  emits: [
    'scroll',
    'scrolltoupper',
    'scrolltolower',
    'refresherrefresh',
    'refresherrestore',
    'refresherpulling',
    'refresherabort',
D
DCloud_LXH 已提交
112
    'update:refresherTriggered',
D
DCloud_LXH 已提交
113
  ],
D
DCloud_LXH 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  setup(props, { emit, slots }) {
    const rootRef: HTMLRef = ref(null)
    const main: HTMLRef = ref(null)
    const wrap: HTMLRef = ref(null)
    const content: HTMLRef = ref(null)
    const refresherinner: HTMLRef = ref(null)

    const trigger = useCustomEvent<EmitEvent<typeof emit>>(rootRef, emit)

    const { state, scrollTopNumber, scrollLeftNumber } =
      useScrollViewState(props)
    useScrollViewLoader(
      props,
      state,
      scrollTopNumber,
      scrollLeftNumber,
      trigger,
      rootRef,
      main,
D
DCloud_LXH 已提交
133 134
      content,
      emit as SetupContext['emit']
D
DCloud_LXH 已提交
135 136
    )

D
DCloud_LXH 已提交
137 138 139 140 141 142 143 144 145 146 147
    const mainStyle = computed(() => {
      let style = ''
      props.scrollX
        ? (style += 'overflow-x:auto;')
        : (style += 'overflow-x:hidden;')
      props.scrollY
        ? (style += 'overflow-y:auto;')
        : (style += 'overflow-y:hidden;')
      return style
    })

D
DCloud_LXH 已提交
148
    return () => {
D
DCloud_LXH 已提交
149 150
      const { refresherEnabled, refresherBackground, refresherDefaultStyle } =
        props
D
DCloud_LXH 已提交
151 152 153 154 155
      const { refresherHeight, refreshState, refreshRotate } = state

      return (
        <uni-scroll-view ref={rootRef}>
          <div ref={wrap} class="uni-scroll-view">
D
DCloud_LXH 已提交
156
            <div ref={main} style={mainStyle.value} class="uni-scroll-view">
D
DCloud_LXH 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
              <div ref={content} class="uni-scroll-view-content">
                {refresherEnabled ? (
                  <div
                    ref={refresherinner}
                    style={{
                      backgroundColor: refresherBackground,
                      height: refresherHeight + 'px',
                    }}
                    class="uni-scroll-view-refresher"
                  >
                    {refresherDefaultStyle !== 'none' ? (
                      <div class="uni-scroll-view-refresh">
                        <div class="uni-scroll-view-refresh-inner">
                          {refreshState == 'pulling' ? (
                            <svg
172
                              key="refresh__icon"
D
DCloud_LXH 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
                              style={{
                                transform: 'rotate(' + refreshRotate + 'deg)',
                              }}
                              fill="#2BD009"
                              class="uni-scroll-view-refresh__icon"
                              width="24"
                              height="24"
                              viewBox="0 0 24 24"
                            >
                              <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />
                              <path d="M0 0h24v24H0z" fill="none" />
                            </svg>
                          ) : null}
                          {refreshState == 'refreshing' ? (
                            <svg
188
                              key="refresh__spinner"
D
DCloud_LXH 已提交
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
                              class="uni-scroll-view-refresh__spinner"
                              width="24"
                              height="24"
                              viewBox="25 25 50 50"
                            >
                              <circle
                                cx="50"
                                cy="50"
                                r="20"
                                fill="none"
                                style="color: #2bd009"
                                stroke-width="3"
                              />
                            </svg>
                          ) : null}
                        </div>
                      </div>
                    ) : null}
                    {refresherDefaultStyle == 'none'
                      ? slots.refresher && slots.refresher()
                      : null}
                  </div>
                ) : null}
                {slots.default && slots.default()}
              </div>
            </div>
          </div>
        </uni-scroll-view>
      )
    }
  },
})

function useScrollViewState(props: Props) {
  const scrollTopNumber = computed(() => {
    return Number(props.scrollTop) || 0
  })
  const scrollLeftNumber = computed(() => {
    return Number(props.scrollLeft) || 0
  })

  const state: State = reactive({
    lastScrollTop: scrollTopNumber.value,
    lastScrollLeft: scrollLeftNumber.value,
    lastScrollToUpperTime: 0,
    lastScrollToLowerTime: 0,
    refresherHeight: 0,
    refreshRotate: 0,
    refreshState: '',
  })

  return {
    state,
    scrollTopNumber,
    scrollLeftNumber,
  }
}

function useScrollViewLoader(
  props: Props,
  state: State,
  scrollTopNumber: Ref<number>,
  scrollLeftNumber: Ref<number>,
  trigger: CustomEventTrigger,
  rootRef: HTMLRef,
  main: HTMLRef,
D
DCloud_LXH 已提交
255 256
  content: HTMLRef,
  emit: SetupContext['emit']
D
DCloud_LXH 已提交
257
) {
D
DCloud_LXH 已提交
258 259 260 261 262 263
  let _innerSetScrollTop: boolean = false
  let _innerSetScrollLeft: boolean = false
  let beforeRefreshing: boolean = false
  let toUpperNumber: number = 0 // 容器触顶时,此时鼠标Y轴位置
  let triggerAbort: boolean = false

D
DCloud_LXH 已提交
264
  let __transitionEnd = () => {}
D
DCloud_LXH 已提交
265

D
DCloud_LXH 已提交
266
  const upperThresholdNumber = computed(() => {
267
    let val = Number(props.upperThreshold)
D
DCloud_LXH 已提交
268 269 270
    return isNaN(val) ? 50 : val
  })
  const lowerThresholdNumber = computed(() => {
271
    let val = Number(props.lowerThreshold)
D
DCloud_LXH 已提交
272 273 274
    return isNaN(val) ? 50 : val
  })

D
DCloud_LXH 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
  function scrollTo(scrollToValue: number, direction: Direction) {
    const container = main.value!
    let transformValue = 0
    let transform = ''

    scrollToValue < 0
      ? (scrollToValue = 0)
      : direction === 'x' &&
        scrollToValue > container.scrollWidth - container.offsetWidth
      ? (scrollToValue = container.scrollWidth - container.offsetWidth)
      : direction === 'y' &&
        scrollToValue > container.scrollHeight - container.offsetHeight &&
        (scrollToValue = container.scrollHeight - container.offsetHeight)

    direction === 'x'
      ? (transformValue = container.scrollLeft - scrollToValue)
      : direction === 'y' &&
        (transformValue = container.scrollTop - scrollToValue)
D
DCloud_LXH 已提交
293

D
DCloud_LXH 已提交
294 295 296 297 298 299 300 301 302 303 304
    if (transformValue === 0) return

    let _content = content.value!

    _content.style.transition = 'transform .3s ease-out'
    _content.style.webkitTransition = '-webkit-transform .3s ease-out'
    if (direction === 'x') {
      transform = 'translateX(' + transformValue + 'px) translateZ(0)'
    } else {
      direction === 'y' &&
        (transform = 'translateY(' + transformValue + 'px) translateZ(0)')
D
DCloud_LXH 已提交
305
    }
D
DCloud_LXH 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    _content.removeEventListener('transitionend', __transitionEnd)
    _content.removeEventListener('webkitTransitionEnd', __transitionEnd)
    __transitionEnd = () => _transitionEnd(scrollToValue, direction)
    _content.addEventListener('transitionend', __transitionEnd)
    _content.addEventListener('webkitTransitionEnd', __transitionEnd)
    if (direction === 'x') {
      // if (e !== 'ios') {
      container.style.overflowX = 'hidden'
      // }
    } else if (direction === 'y') {
      container.style.overflowY = 'hidden'
    }

    _content.style.transform = transform
    _content.style.webkitTransform = transform
D
DCloud_LXH 已提交
321 322
  }
  function _handleScroll($event: MouseEvent) {
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    const target = $event.target as HTMLElement
    trigger('scroll', $event, {
      scrollLeft: target.scrollLeft,
      scrollTop: target.scrollTop,
      scrollHeight: target.scrollHeight,
      scrollWidth: target.scrollWidth,
      deltaX: state.lastScrollLeft - target.scrollLeft,
      deltaY: state.lastScrollTop - target.scrollTop,
    })
    if (props.scrollY) {
      if (
        target.scrollTop <= upperThresholdNumber.value &&
        state.lastScrollTop - target.scrollTop > 0 &&
        $event.timeStamp - state.lastScrollToUpperTime > 200
      ) {
        trigger('scrolltoupper', $event, {
          direction: 'top',
        })
        state.lastScrollToUpperTime = $event.timeStamp
D
DCloud_LXH 已提交
342
      }
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
      if (
        target.scrollTop + target.offsetHeight + lowerThresholdNumber.value >=
          target.scrollHeight &&
        state.lastScrollTop - target.scrollTop < 0 &&
        $event.timeStamp - state.lastScrollToLowerTime > 200
      ) {
        trigger('scrolltolower', $event, {
          direction: 'bottom',
        })
        state.lastScrollToLowerTime = $event.timeStamp
      }
    }
    if (props.scrollX) {
      if (
        target.scrollLeft <= upperThresholdNumber.value &&
        state.lastScrollLeft - target.scrollLeft > 0 &&
        $event.timeStamp - state.lastScrollToUpperTime > 200
      ) {
        trigger('scrolltoupper', $event, {
          direction: 'left',
        })
        state.lastScrollToUpperTime = $event.timeStamp
      }
      if (
        target.scrollLeft + target.offsetWidth + lowerThresholdNumber.value >=
          target.scrollWidth &&
        state.lastScrollLeft - target.scrollLeft < 0 &&
        $event.timeStamp - state.lastScrollToLowerTime > 200
      ) {
        trigger('scrolltolower', $event, {
          direction: 'right',
        })
        state.lastScrollToLowerTime = $event.timeStamp
D
DCloud_LXH 已提交
376 377
      }
    }
378 379
    state.lastScrollTop = target.scrollTop
    state.lastScrollLeft = target.scrollLeft
D
DCloud_LXH 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  }
  function _scrollTopChanged(val: number) {
    if (props.scrollY) {
      if (_innerSetScrollTop) {
        _innerSetScrollTop = false
      } else {
        if (props.scrollWithAnimation) {
          scrollTo(val, 'y')
        } else {
          main.value!.scrollTop = val
        }
      }
    }
  }
  function _scrollLeftChanged(val: number) {
    if (props.scrollX) {
      if (_innerSetScrollLeft) {
        _innerSetScrollLeft = false
      } else {
        if (props.scrollWithAnimation) {
          scrollTo(val, 'x')
        } else {
          main.value!.scrollLeft = val
        }
      }
    }
  }
  function _scrollIntoViewChanged(val: string) {
    if (val) {
      if (!/^[_a-zA-Z][-_a-zA-Z0-9:]*$/.test(val)) {
        console.error(`id error: scroll-into-view=${val}`)
        return
      }
413
      let element = rootRef.value!.querySelector('#' + val)
D
DCloud_LXH 已提交
414
      if (element) {
415 416
        let mainRect = main.value!.getBoundingClientRect()
        let elRect = element.getBoundingClientRect()
D
DCloud_LXH 已提交
417
        if (props.scrollX) {
418 419 420
          let left = elRect.left - mainRect.left
          let scrollLeft = main.value!.scrollLeft
          let x = scrollLeft + left
D
DCloud_LXH 已提交
421 422 423 424 425 426 427
          if (props.scrollWithAnimation) {
            scrollTo(x, 'x')
          } else {
            main.value!.scrollLeft = x
          }
        }
        if (props.scrollY) {
428 429 430
          let top = elRect.top - mainRect.top
          let scrollTop = main.value!.scrollTop
          let y = scrollTop + top
D
DCloud_LXH 已提交
431 432 433 434 435 436 437 438 439
          if (props.scrollWithAnimation) {
            scrollTo(y, 'y')
          } else {
            main.value!.scrollTop = y
          }
        }
      }
    }
  }
D
DCloud_LXH 已提交
440
  function _transitionEnd(val: number, direction: Direction) {
D
DCloud_LXH 已提交
441 442 443 444 445
    content.value!.style.transition = ''
    content.value!.style.webkitTransition = ''
    content.value!.style.transform = ''
    content.value!.style.webkitTransform = ''
    let _main = main.value!
D
DCloud_LXH 已提交
446
    if (direction === 'x') {
D
DCloud_LXH 已提交
447 448
      _main.style.overflowX = props.scrollX ? 'auto' : 'hidden'
      _main.scrollLeft = val
D
DCloud_LXH 已提交
449
    } else if (direction === 'y') {
D
DCloud_LXH 已提交
450 451 452 453 454 455 456 457 458 459
      _main.style.overflowY = props.scrollY ? 'auto' : 'hidden'
      _main.scrollTop = val
    }
    content.value!.removeEventListener('transitionend', __transitionEnd)
    content.value!.removeEventListener('webkitTransitionEnd', __transitionEnd)
  }
  function _setRefreshState(_state: RefreshState) {
    switch (_state) {
      case 'refreshing':
        state.refresherHeight = props.refresherThreshold
D
DCloud_LXH 已提交
460 461 462 463 464 465
        // 之前是刷新状态则不再触发刷新
        if (!beforeRefreshing) {
          beforeRefreshing = true
          trigger('refresherrefresh', {} as Event, {})
          emit('update:refresherTriggered', true)
        }
D
DCloud_LXH 已提交
466 467
        break
      case 'restore':
D
DCloud_LXH 已提交
468 469 470 471 472 473 474 475 476 477 478
      case 'refresherabort':
        beforeRefreshing = false
        state.refresherHeight = toUpperNumber = 0
        if (_state === 'restore') {
          triggerAbort = false
          trigger('refresherrestore', {} as Event, {})
        }
        if (_state === 'refresherabort' && triggerAbort) {
          triggerAbort = false
          trigger('refresherabort', {} as Event, {})
        }
D
DCloud_LXH 已提交
479 480 481 482 483 484
        break
    }
    state.refreshState = _state
  }

  onMounted(() => {
485 486 487 488
    nextTick(() => {
      _scrollTopChanged(scrollTopNumber.value)
      _scrollLeftChanged(scrollLeftNumber.value)
    })
D
DCloud_LXH 已提交
489 490
    _scrollIntoViewChanged(props.scrollIntoView)
    let __handleScroll = function (event: Event) {
D
DCloud_LXH 已提交
491
      event.preventDefault()
D
DCloud_LXH 已提交
492 493 494 495 496 497 498 499 500 501
      event.stopPropagation()
      _handleScroll(event as MouseEvent)
    }
    let touchStart: {
      x: number
      y: number
    } = {
      x: 0,
      y: 0,
    }
502
    let needStop: boolean | null = null
503

D
DCloud_LXH 已提交
504
    let __handleTouchMove = function (event: TouchEvent) {
505 506 507 508 509 510
      let x = event.touches[0].pageX
      let y = event.touches[0].pageY
      let _main = main.value!

      if (Math.abs(x - touchStart.x) > Math.abs(y - touchStart.y)) {
        // 横向滑动
511
        if (props.scrollX) {
512 513 514 515 516 517 518
          if (_main.scrollLeft === 0 && x > touchStart.x) {
            needStop = false
            return
          } else if (
            _main.scrollWidth === _main.offsetWidth + _main.scrollLeft &&
            x < touchStart.x
          ) {
D
DCloud_LXH 已提交
519
            needStop = false
520
            return
D
DCloud_LXH 已提交
521
          }
522
          needStop = true
D
DCloud_LXH 已提交
523
        } else {
524 525 526 527
          needStop = false
        }
      } else {
        // 纵向滑动
528 529 530
        if (props.scrollY) {
          if (_main.scrollTop === 0 && y > touchStart.y) {
            needStop = false
531
            // 刷新时,阻止页面滚动
532 533
            if (props.refresherEnabled && event.cancelable !== false)
              event.preventDefault()
534 535 536 537
          } else if (
            _main.scrollHeight === _main.offsetHeight + _main.scrollTop &&
            y < touchStart.y
          ) {
D
DCloud_LXH 已提交
538
            needStop = false
539
            return
540 541
          } else {
            needStop = true
D
DCloud_LXH 已提交
542
          }
543 544
        } else {
          needStop = false
D
DCloud_LXH 已提交
545 546
        }
      }
547

D
DCloud_LXH 已提交
548 549 550 551
      if (needStop) {
        event.stopPropagation()
      }

552 553 554 555 556
      if (_main.scrollTop === 0 && event.touches.length === 1) {
        // 如果容器滑动到达顶端,则进入下拉状态
        state.refreshState = 'pulling'
      }

D
DCloud_LXH 已提交
557 558 559
      if (props.refresherEnabled && state.refreshState === 'pulling') {
        const dy = y - touchStart.y

560 561 562 563 564 565 566 567 568 569 570 571 572
        if (toUpperNumber === 0) {
          toUpperNumber = y
        }

        if (!beforeRefreshing) {
          state.refresherHeight = y - toUpperNumber
          // 之前为刷新状态则不再触发pulling
          if (state.refresherHeight > 0) {
            triggerAbort = true
            trigger('refresherpulling', event, {
              deltaY: dy,
            })
          }
D
DCloud_LXH 已提交
573
        } else {
574 575 576
          state.refresherHeight = dy + props.refresherThreshold
          // 如果之前在刷新状态,则不触发刷新中断
          triggerAbort = false
D
DCloud_LXH 已提交
577 578
        }

579 580
        const route = state.refresherHeight / props.refresherThreshold
        state.refreshRotate = (route > 1 ? 1 : route) * 360
D
DCloud_LXH 已提交
581 582
      }
    }
D
DCloud_LXH 已提交
583
    let __handleTouchStart = function (event: TouchEvent) {
D
DCloud_LXH 已提交
584 585 586 587 588 589 590 591 592 593
      if (event.touches.length === 1) {
        disableScrollBounce({
          disable: true,
        })
        touchStart = {
          x: event.touches[0].pageX,
          y: event.touches[0].pageY,
        }
      }
    }
D
DCloud_LXH 已提交
594
    let __handleTouchEnd = function (event: TouchEvent) {
D
DCloud_LXH 已提交
595 596 597 598 599 600 601 602 603 604
      touchStart = {
        x: 0,
        y: 0,
      }
      disableScrollBounce({
        disable: false,
      })
      if (state.refresherHeight >= props.refresherThreshold) {
        _setRefreshState('refreshing')
      } else {
D
DCloud_LXH 已提交
605
        _setRefreshState('refresherabort')
D
DCloud_LXH 已提交
606 607 608 609 610 611 612
      }
    }
    main.value!.addEventListener(
      'touchstart',
      __handleTouchStart,
      passiveOptions
    )
D
DCloud_LXH 已提交
613 614
    main.value!.addEventListener('touchmove', __handleTouchMove, passive(false))
    main.value!.addEventListener('scroll', __handleScroll, passive(false))
D
DCloud_LXH 已提交
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    main.value!.addEventListener('touchend', __handleTouchEnd, passiveOptions)
    initScrollBounce()

    onBeforeUnmount(() => {
      main.value!.removeEventListener('touchstart', __handleTouchStart)
      main.value!.removeEventListener('touchmove', __handleTouchMove)
      main.value!.removeEventListener('scroll', __handleScroll)
      main.value!.removeEventListener('touchend', __handleTouchEnd)
    })
  })

  onActivated(() => {
    // 还原 scroll-view 滚动位置
    props.scrollY && (main.value!.scrollTop = state.lastScrollTop)
    props.scrollX && (main.value!.scrollLeft = state.lastScrollLeft)
  })

  watch(scrollTopNumber, (val) => {
    _scrollTopChanged(val)
  })
  watch(scrollLeftNumber, (val) => {
    _scrollLeftChanged(val)
  })
  watch(
    () => props.scrollIntoView,
    (val) => {
      _scrollIntoViewChanged(val)
    }
  )
  watch(
    () => props.refresherTriggered,
    (val) => {
      // TODO
      if (val === true) {
        _setRefreshState('refreshing')
      } else if (val === false) {
        _setRefreshState('restore')
      }
    }
  )
}