index.tsx 8.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
import {
  defineComponent,
  inject,
  ref,
  Ref,
  watch,
  VNode,
  computed,
  getCurrentInstance,
  onMounted,
11 12
  ExtractPropTypes,
  WritableComputedRef,
13
} from 'vue'
14
import { extend, isString } from '@vue/shared'
15 16 17 18 19 20 21 22 23 24
import { Props, GetPickerViewColumn } from '../picker-view'
import { parseStyleText, getComponentSize } from '../helpers'

type ScrollOptions = {
  showScrollbar: boolean
  scrollToBegin: boolean
  decelerationRate: number
  scrollY: boolean
  scrollTop?: number
}
25
type PickerColumnProps = ExtractPropTypes<typeof props>
26 27 28 29

const dom = weex.requireModule('dom')
const isAndroid = weex.config.env.platform.toLowerCase() === 'android'
function getStyle(val: string) {
30
  return extend({}, isString(val) ? parseStyleText(val) : val)
31 32
}

33 34 35 36 37 38 39
const props = {
  length: {
    type: [Number, String],
    default: 0,
  },
}

40 41
export default defineComponent({
  name: 'PickerViewColumn',
42
  props,
43 44 45 46 47 48 49 50 51 52 53 54
  data: () => ({
    _isMounted: false,
  }),
  setup(props, { slots }) {
    const instance = getCurrentInstance()!

    const rootRef: Ref<HTMLElement | null> = ref(null)
    const contentRef: Ref<HTMLElement | null> = ref(null)
    const scrollViewItemRef: Ref<HTMLElement | null> = ref(null)
    const indicatorRef: Ref<HTMLElement | null> = ref(null)

    const pickerViewProps = inject<Props>('pickerViewProps')!
55 56 57
    const getPickerViewColumn = inject(
      'getPickerViewColumn'
    ) as GetPickerViewColumn
58 59 60 61 62 63

    const current = getPickerViewColumn(instance)
    const indicatorStyle = computed(() =>
      getStyle(pickerViewProps.indicatorStyle)
    )
    const maskStyle = computed(() => getStyle(pickerViewProps.maskStyle))
64 65 66 67
    let indicatorHeight = ref(0)
    indicatorHeight.value = getHeight(indicatorStyle.value)
    let pickerViewHeight = ref(0)
    pickerViewHeight.value = parseFloat(pickerViewProps.height as string)
68

69 70 71 72 73
    const { setCurrent, onScrollend } = usePickerColumnScroll(
      props,
      current,
      contentRef,
      indicatorHeight
74 75 76 77 78 79 80 81
    )

    const checkMounted = () => {
      let height_: number
      let indicatorHeight_: number
      setTimeout(() => {
        Promise.all([
          getComponentSize(rootRef.value!).then(({ height }) => {
82
            height_ = pickerViewHeight.value = height
83 84 85
          }),
          isAndroid && props.length
            ? getComponentSize(scrollViewItemRef.value!).then(({ height }) => {
86
                indicatorHeight_ = indicatorHeight.value =
87 88 89
                  height / parseFloat(props.length as string)
              })
            : getComponentSize(indicatorRef.value!).then(({ height }) => {
90
                indicatorHeight_ = indicatorHeight.value = height
91 92 93 94 95 96
              }),
        ]).then(() => {
          if (height_ && indicatorHeight_) {
            // 初始化时iOS直接滚动经常出错
            setTimeout(() => {
              instance.data._isMounted = true
D
DCloud_LXH 已提交
97
              setCurrent(current.value, false, true)
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
            }, 50)
          } else {
            checkMounted()
          }
        })
      }, 50)
    }

    onMounted(checkMounted)

    const createScrollViewChild = (item?: VNode[]) => {
      if (!item) return null
      return isAndroid ? (
        <div ref={scrollViewItemRef} style="flex-direction:column;">
          {item}
        </div>
      ) : (
        item
      )
    }

    return () => {
      const children = slots.default && slots.default()
121 122
      let padding = (pickerViewHeight.value - indicatorHeight.value) / 2
      const maskPosition = `${pickerViewHeight.value - padding}px`
123 124 125 126 127 128 129
      const scrollOptions: ScrollOptions = {
        showScrollbar: false,
        scrollToBegin: false,
        decelerationRate: 0.3,
        scrollY: true,
      }
      if (!isAndroid) {
130
        scrollOptions.scrollTop = current.value * indicatorHeight.value
131 132 133
      }

      return (
D
DCloud_LXH 已提交
134
        <view ref={rootRef} class="uni-picker-view-column">
135 136 137 138 139 140
          <scroll-view
            class="uni-picker-view-group"
            style="flex-direction:column;"
            onScrollend={onScrollend}
            {...scrollOptions}
          >
D
DCloud_LXH 已提交
141
            <view
142 143 144 145 146 147 148 149
              ref={contentRef}
              class="uni-picker-view-content"
              style={{
                paddingTop: `${padding}px`,
                paddingBottom: `${padding}px`,
              }}
            >
              {createScrollViewChild(children)}
D
DCloud_LXH 已提交
150
            </view>
151
          </scroll-view>
152
          <u-scalable class="uni-picker-view-mask" style={maskStyle.value}>
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
            <u-scalable
              class="uni-picker-view-mask uni-picker-view-mask-top"
              style={{
                bottom: maskPosition,
              }}
            ></u-scalable>
            <u-scalable
              class="uni-picker-view-mask uni-picker-view-mask-bottom"
              style={{
                top: maskPosition,
              }}
            ></u-scalable>
          </u-scalable>
          <u-scalable
            ref={indicatorRef}
            class="uni-picker-view-indicator"
            style={extend({}, indicatorStyle.value, {
              top: `${padding}px`,
            })}
          ></u-scalable>
D
DCloud_LXH 已提交
173
        </view>
174 175 176 177 178 179
      )
    }
  },
  styles: [
    {
      'uni-picker-view-column': {
180 181 182 183 184 185
        '': {
          flex: 1,
          position: 'relative',
          alignItems: 'stretch',
          overflow: 'hidden',
        },
186 187
      },
      'uni-picker-view-mask': {
188 189 190 191 192 193 194 195
        '': {
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          pointerEvents: 'none',
        },
196 197
      },
      'uni-picker-view-mask-top': {
198 199 200 201 202
        '': {
          bottom: 0,
          backgroundImage:
            'linear-gradient(to bottom,rgba(255, 255, 255, 0.95),rgba(255, 255, 255, 0.6))',
        },
203 204
      },
      'uni-picker-view-mask-bottom': {
205 206 207 208 209
        '': {
          top: 0,
          backgroundImage:
            'linear-gradient(to top,rgba(255, 255, 255, 0.95),rgba(255, 255, 255, 0.6))',
        },
210 211
      },
      'uni-picker-view-group': {
212
        '': { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 },
213 214
      },
      'uni-picker-view-content': {
215
        '': {
D
DCloud_LXH 已提交
216
          flexDirection: 'column',
217 218 219 220 221
          paddingTop: 0,
          paddingRight: 0,
          paddingBottom: 0,
          paddingLeft: 0,
        },
222 223
      },
      'uni-picker-view-indicator': {
224 225 226 227 228 229 230 231 232 233 234
        '': {
          position: 'absolute',
          left: 0,
          right: 0,
          top: 0,
          height: '34px',
          pointerEvents: 'none',
          borderColor: '#e5e5e5',
          borderTopWidth: '1px',
          borderBottomWidth: '1px',
        },
235 236 237 238 239 240 241 242 243 244 245 246 247 248
      },
    },
  ],
})

function getHeight(style: Record<string, any>) {
  const height = style.height || style.lineHeight || ''
  const res = height.match(/(-?[\d\.]+)px/)
  let value = 0
  if (res) {
    value = parseFloat(res[1])
  }
  return value
}
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

function usePickerColumnScroll(
  props: PickerColumnProps,
  current: WritableComputedRef<number>,
  contentRef: Ref<HTMLElement | null>,
  indicatorHeight: Ref<number>
) {
  let scrollToElementTime: number

  watch(
    () => props.length,
    () => {
      setTimeout(() => {
        setCurrent(current.value, true, true)
      }, 150)
    }
  )
  watch(
    () => current.value,
    (_current) => {
      dom.scrollToElement(contentRef.value, {
        offset: _current * indicatorHeight.value,
        animated: true,
      })
      scrollToElementTime = Date.now()
    }
  )

  const setCurrent = (_current: number, animated = true, force: Boolean) => {
    if (current.value === _current && !force) {
      return
    }
    dom.scrollToElement(contentRef.value, {
      offset: _current * indicatorHeight.value,
      animated,
    })
    current.value = _current
    if (animated) {
      scrollToElementTime = Date.now()
    }
  }
  const onScrollend = (event: {
    detail: {
      contentOffset: { x: number; y: number }
    }
  }) => {
    if (Date.now() - scrollToElementTime < 340) {
      return
    }
    const y = event.detail.contentOffset.y
    const _current = Math.round(y / indicatorHeight.value)
    if (y % indicatorHeight.value) {
      setCurrent(_current, true, true)
    } else {
      current.value = _current
    }
  }

  return { setCurrent, onScrollend }
}