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,
D
DCloud_LXH 已提交
12 13 14 15 16 17 18 19 20 21 22 23
} 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>
24
type RefreshState = 'refreshing' | 'restore' | 'pulling' | 'refresherabort' | ''
D
DCloud_LXH 已提交
25
type Direction = 'x' | 'y'
D
DCloud_LXH 已提交
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
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 已提交
103 104 105 106 107 108 109 110
  emits: [
    'scroll',
    'scrolltoupper',
    'scrolltolower',
    'refresherrefresh',
    'refresherrestore',
    'refresherpulling',
    'refresherabort',
D
DCloud_LXH 已提交
111
    'update:refresherTriggered',
D
DCloud_LXH 已提交
112
  ],
D
DCloud_LXH 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
  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 已提交
132 133
      content,
      emit as SetupContext['emit']
D
DCloud_LXH 已提交
134 135
    )

D
DCloud_LXH 已提交
136 137 138 139 140 141 142 143 144 145 146
    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 已提交
147
    return () => {
D
DCloud_LXH 已提交
148 149
      const { refresherEnabled, refresherBackground, refresherDefaultStyle } =
        props
D
DCloud_LXH 已提交
150 151 152 153 154
      const { refresherHeight, refreshState, refreshRotate } = state

      return (
        <uni-scroll-view ref={rootRef}>
          <div ref={wrap} class="uni-scroll-view">
D
DCloud_LXH 已提交
155
            <div ref={main} style={mainStyle.value} class="uni-scroll-view">
D
DCloud_LXH 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
              <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
171
                              key="refresh__icon"
D
DCloud_LXH 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
                              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
187
                              key="refresh__spinner"
D
DCloud_LXH 已提交
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
                              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 已提交
254 255
  content: HTMLRef,
  emit: SetupContext['emit']
D
DCloud_LXH 已提交
256
) {
D
DCloud_LXH 已提交
257 258 259 260 261 262
  let _innerSetScrollTop: boolean = false
  let _innerSetScrollLeft: boolean = false
  let beforeRefreshing: boolean = false
  let toUpperNumber: number = 0 // 容器触顶时,此时鼠标Y轴位置
  let triggerAbort: boolean = false

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

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

D
DCloud_LXH 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  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 已提交
292

D
DCloud_LXH 已提交
293 294 295 296 297 298 299 300 301 302 303
    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 已提交
304
    }
D
DCloud_LXH 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    _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 已提交
320 321
  }
  function _handleScroll($event: MouseEvent) {
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    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 已提交
341
      }
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
      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 已提交
375 376
      }
    }
377 378
    state.lastScrollTop = target.scrollTop
    state.lastScrollLeft = target.scrollLeft
D
DCloud_LXH 已提交
379 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
  }
  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
      }
412
      let element = rootRef.value!.querySelector('#' + val)
D
DCloud_LXH 已提交
413
      if (element) {
414 415
        let mainRect = main.value!.getBoundingClientRect()
        let elRect = element.getBoundingClientRect()
D
DCloud_LXH 已提交
416
        if (props.scrollX) {
417 418 419
          let left = elRect.left - mainRect.left
          let scrollLeft = main.value!.scrollLeft
          let x = scrollLeft + left
D
DCloud_LXH 已提交
420 421 422 423 424 425 426
          if (props.scrollWithAnimation) {
            scrollTo(x, 'x')
          } else {
            main.value!.scrollLeft = x
          }
        }
        if (props.scrollY) {
427 428 429
          let top = elRect.top - mainRect.top
          let scrollTop = main.value!.scrollTop
          let y = scrollTop + top
D
DCloud_LXH 已提交
430 431 432 433 434 435 436 437 438
          if (props.scrollWithAnimation) {
            scrollTo(y, 'y')
          } else {
            main.value!.scrollTop = y
          }
        }
      }
    }
  }
D
DCloud_LXH 已提交
439
  function _transitionEnd(val: number, direction: Direction) {
D
DCloud_LXH 已提交
440 441 442 443 444
    content.value!.style.transition = ''
    content.value!.style.webkitTransition = ''
    content.value!.style.transform = ''
    content.value!.style.webkitTransform = ''
    let _main = main.value!
D
DCloud_LXH 已提交
445
    if (direction === 'x') {
D
DCloud_LXH 已提交
446 447
      _main.style.overflowX = props.scrollX ? 'auto' : 'hidden'
      _main.scrollLeft = val
D
DCloud_LXH 已提交
448
    } else if (direction === 'y') {
D
DCloud_LXH 已提交
449 450 451 452 453 454 455 456 457 458
      _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 已提交
459 460 461 462 463 464
        // 之前是刷新状态则不再触发刷新
        if (!beforeRefreshing) {
          beforeRefreshing = true
          trigger('refresherrefresh', {} as Event, {})
          emit('update:refresherTriggered', true)
        }
D
DCloud_LXH 已提交
465 466
        break
      case 'restore':
D
DCloud_LXH 已提交
467 468 469 470 471 472 473 474 475 476 477
      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 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        break
    }
    state.refreshState = _state
  }

  onMounted(() => {
    _scrollTopChanged(scrollTopNumber.value)
    _scrollLeftChanged(scrollLeftNumber.value)
    _scrollIntoViewChanged(props.scrollIntoView)
    let __handleScroll = function (event: Event) {
      // Unable to preventDefault inside passive event listener invocation.
      // event.preventDefault();
      event.stopPropagation()
      _handleScroll(event as MouseEvent)
    }
    let touchStart: {
      x: number
      y: number
    } = {
      x: 0,
      y: 0,
    }
500
    let needStop: boolean | null = null
501

D
DCloud_LXH 已提交
502
    let __handleTouchMove = function (event: TouchEvent) {
503 504 505 506 507 508
      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)) {
        // 横向滑动
509
        if (props.scrollX) {
510 511 512 513 514 515 516
          if (_main.scrollLeft === 0 && x > touchStart.x) {
            needStop = false
            return
          } else if (
            _main.scrollWidth === _main.offsetWidth + _main.scrollLeft &&
            x < touchStart.x
          ) {
D
DCloud_LXH 已提交
517
            needStop = false
518
            return
D
DCloud_LXH 已提交
519
          }
520
          needStop = true
D
DCloud_LXH 已提交
521
        } else {
522 523 524 525
          needStop = false
        }
      } else {
        // 纵向滑动
526 527 528
        if (props.scrollY) {
          if (_main.scrollTop === 0 && y > touchStart.y) {
            needStop = false
529
            // 刷新时,阻止页面滚动
530 531
            if (props.refresherEnabled && event.cancelable !== false)
              event.preventDefault()
532 533 534 535
          } else if (
            _main.scrollHeight === _main.offsetHeight + _main.scrollTop &&
            y < touchStart.y
          ) {
D
DCloud_LXH 已提交
536
            needStop = false
537
            return
538 539
          } else {
            needStop = true
D
DCloud_LXH 已提交
540
          }
541 542
        } else {
          needStop = false
D
DCloud_LXH 已提交
543 544
        }
      }
545

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

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

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

558 559 560 561 562 563 564 565 566 567 568 569 570
        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 已提交
571
        } else {
572 573 574
          state.refresherHeight = dy + props.refresherThreshold
          // 如果之前在刷新状态,则不触发刷新中断
          triggerAbort = false
D
DCloud_LXH 已提交
575 576
        }

577 578
        const route = state.refresherHeight / props.refresherThreshold
        state.refreshRotate = (route > 1 ? 1 : route) * 360
D
DCloud_LXH 已提交
579 580
      }
    }
D
DCloud_LXH 已提交
581
    let __handleTouchStart = function (event: TouchEvent) {
D
DCloud_LXH 已提交
582 583 584 585 586 587 588 589 590 591
      if (event.touches.length === 1) {
        disableScrollBounce({
          disable: true,
        })
        touchStart = {
          x: event.touches[0].pageX,
          y: event.touches[0].pageY,
        }
      }
    }
D
DCloud_LXH 已提交
592
    let __handleTouchEnd = function (event: TouchEvent) {
D
DCloud_LXH 已提交
593 594 595 596 597 598 599 600 601 602
      touchStart = {
        x: 0,
        y: 0,
      }
      disableScrollBounce({
        disable: false,
      })
      if (state.refresherHeight >= props.refresherThreshold) {
        _setRefreshState('refreshing')
      } else {
D
DCloud_LXH 已提交
603
        _setRefreshState('refresherabort')
D
DCloud_LXH 已提交
604 605 606 607 608 609 610
      }
    }
    main.value!.addEventListener(
      'touchstart',
      __handleTouchStart,
      passiveOptions
    )
611
    main.value!.addEventListener('touchmove', __handleTouchMove)
D
DCloud_LXH 已提交
612 613 614 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
    main.value!.addEventListener('scroll', __handleScroll, passiveOptions)
    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')
      }
    }
  )
}