picker.taro.tsx 8.8 KB
Newer Older
X
xiaoyatong 已提交
1 2 3 4 5 6 7
import React, {
  useState,
  useEffect,
  useRef,
  RefObject,
  ForwardRefRenderFunction,
} from 'react'
8
import { View } from '@tarojs/components'
9
import Popup from '@/packages/popup/index.taro'
10
import PickerSlot from './pickerSlot.taro'
11
import useRefs from '@/utils/use-refs'
O
oasis-cloud 已提交
12
import { useConfig } from '@/packages/configprovider/configprovider.taro'
X
xiaoyatong 已提交
13 14 15 16 17 18 19 20 21
import bem from '@/utils/bem'

export interface PickerOption {
  text: string | number
  value: string | number
  disabled?: string
  children?: PickerOption[]
  className?: string | number
}
22
export interface PickerProps {
H
hanyuxinting 已提交
23
  visible: boolean
X
xiaoyatong 已提交
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
  title?: string
  listData: (PickerOption | PickerOption[])[]
  defaultValueData?: (number | string)[]
  className?: ''
  style?: React.CSSProperties
  threeDimensional?: boolean
  swipeDuration: number | string
  onConfirm?: (
    selectedValue: (string | number)[],
    selectedOptions: PickerOption[]
  ) => void
  onClose?: (
    selectedValue: (string | number)[],
    selectedOptions: PickerOption[]
  ) => void
  onCloseUpdate?: (
    selectedValue: (string | number)[],
    list: PickerOption[],
    pickerRef: RefObject<HTMLDivElement>
  ) => void
  onChange?: (
    index: number,
    value: (string | number)[],
    selectedOptions: PickerOption[]
  ) => void
}

51
const InternalPicker: ForwardRefRenderFunction<unknown, Partial<PickerProps>> =
X
xiaoyatong 已提交
52 53 54
  (props, ref) => {
    const { locale } = useConfig()
    const {
H
hanyuxinting 已提交
55
      visible,
X
xiaoyatong 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
      title,
      listData = [],
      defaultValueData,
      onConfirm,
      onClose,
      onCloseUpdate,
      onChange,
      className,
      style,
      threeDimensional,
      swipeDuration,
      ...rest
    } = props

    const [chooseValueData, setchooseValueData] = useState<
      Array<string | number>
    >([]) // 选择的数据的 value 值, 每一条数据的 value 值
    const [columnIndex, setcolumnIndex] = useState<number>(0) // 选中列
    const pickerRef = useRef<any>(null)
75
    const [refs, setRefs] = useRefs()
X
xiaoyatong 已提交
76 77 78
    const [columnsList, setColumnsList] = useState<PickerOption[][]>([]) // 格式化后每一列的数据
    const b = bem('picker')

79
    const isConfirmEvent = useRef(false)
80

X
xiaoyatong 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    // 默认值修改
    useEffect(() => {
      if (
        defaultValueData &&
        defaultValueData.length !== 0 &&
        defaultValueData.toString() !== chooseValueData.toString()
      ) {
        const data = [...defaultValueData]
        setchooseValueData(data)
        setColumnsList(normalListData() as PickerOption[][])
      }
    }, [defaultValueData])

    // 选中值进行修改
    useEffect(() => {
      onChange && onChange(columnIndex, chooseValueData, selectedOptions())
97 98 99 100
      if (isConfirmEvent.current) {
        isConfirmEvent.current = false
        onConfirm && onConfirm(chooseValueData, selectedOptions())
      }
X
xiaoyatong 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114
    }, [chooseValueData])

    // 列表格式修改
    useEffect(() => {
      init()
    }, [listData])

    const closeActionSheet = () => {
      onClose && onClose(chooseValueData, selectedOptions())
      onCloseUpdate &&
        onCloseUpdate(chooseValueData, selectedOptions(), pickerRef)
    }
    // 点击确定
    const confirm = () => {
115 116 117 118 119 120 121 122 123 124 125 126
      let movings = false
      refs.forEach((_ref: any) => {
        if (_ref.moving) movings = true
        _ref.stopMomentum()
      })

      if (movings) {
        isConfirmEvent.current = true
      } else {
        onConfirm && onConfirm(chooseValueData, selectedOptions())
      }

X
xiaoyatong 已提交
127
      onClose && onClose(chooseValueData, selectedOptions())
128 129 130 131

      setTimeout(() => {
        isConfirmEvent.current = false
      }, 0)
X
xiaoyatong 已提交
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
    }

    const selectedOptions = () => {
      const optins: PickerOption[] = []
      columnsList.map((column: PickerOption[], index: number) => {
        let currOptions = []
        currOptions = column.filter(
          (item) => item.value === chooseValueData[index]
        )
        if (currOptions[0]) {
          optins.push(currOptions[0])
        } else {
          column[0] && optins.push(column[0])
        }

        return column
      })

      return optins
    }

    // 选择每一列的数据
    const chooseItem = (option: PickerOption, columnIndex: number) => {
      if (option && Object.keys(option).length) {
        // 是否移动后是否与之前有差异
        if (chooseValueData[columnIndex] !== option.value) {
          if (columnsType() === 'cascade') {
            chooseValueData[columnIndex] = option.value ? option.value : ''
            setchooseValueData([...chooseValueData])

            let index = columnIndex
            let cursor = option
            while (cursor && cursor.children && cursor.children[0]) {
              chooseValueData[index + 1] = cursor.children[0].value
              setchooseValueData([...chooseValueData])
              index++
              const cc = cursor.children[0]
              cursor = cc
            }
            // 当前改变列的下一列 children 值为空
            if (cursor && cursor.children) {
              chooseValueData[index + 1] = ''
              setchooseValueData([...chooseValueData])
            }

            setColumnsList(normalListData() as PickerOption[][])
          } else {
            setchooseValueData((data) => {
              const cdata = [...data]
              cdata[columnIndex] = Object.prototype.hasOwnProperty.call(
                option,
                'value'
              )
                ? option.value
                : ''
              return cdata
            })
          }
          setcolumnIndex(columnIndex)
        }
      }
    }
    // 传入的数据格式化
    const normalListData = () => {
      const type = columnsType()

      switch (type) {
        case 'multiple':
          return listData
        case 'cascade':
          // 级联数据处理
          return formatCascade(listData as PickerOption[], chooseValueData)
        default:
          return [listData]
      }
    }
    // 每一列的类型
    const columnsType = () => {
      const firstColumn: PickerOption | PickerOption[] = listData[0]
      if (firstColumn) {
        if (Array.isArray(firstColumn)) {
          return 'multiple'
        }
        if ('children' in firstColumn) {
          return 'cascade'
        }
      }
      return 'single'
    }

    // 级联数据格式化
    const formatCascade = (
      columns: PickerOption[],
      defaultValues: (number | string)[]
    ) => {
      const formatted: PickerOption[][] = []
      let cursor: PickerOption = {
        text: '',
        value: '',
        children: columns,
      }

      let columnIndex = 0

      while (cursor && cursor.children) {
        const options: PickerOption[] = cursor.children
        const value = defaultValues[columnIndex]
        let index = options.findIndex(
          (columnItem) => columnItem.value === value
        )
        if (index === -1) index = 0
        cursor = cursor.children[index]

        columnIndex++
        formatted.push(options)
      }

      return formatted
    }

    const init = () => {
      const data: (string | number)[] = []

      const normalData: PickerOption[][] = normalListData() as PickerOption[][]

      setColumnsList(normalData)

      normalData.length > 0 &&
        normalData.map((item) => {
          item[0] && data.push(item[0].value)
          return item
        })

      if (!defaultValueData && chooseValueData.length === 0) {
        setchooseValueData([...data])
      }
    }
269 270 271 272 273 274 275 276 277 278 279 280 281 282

    const renderToolbar = () => {
      return (
        <div className={b('control')}>
          <span className={b('cancel-btn')} onClick={() => closeActionSheet()}>
            {locale.cancel}
          </span>
          <div className={b('title')}>{title || ''}</div>
          <span className={b('confirm-btn')} onClick={confirm}>
            {locale.confirm}
          </span>
        </div>
      )
    }
X
xiaoyatong 已提交
283 284
    return (
      <Popup
H
hanyuxinting 已提交
285
        visible={visible}
X
xiaoyatong 已提交
286 287 288 289 290
        position="bottom"
        onClose={() => {
          closeActionSheet()
        }}
      >
291 292 293 294 295 296
        <View
          className={`${b()} ${className || ''}`}
          style={style}
          {...rest}
          catchMove
        >
297
          {renderToolbar()}
X
xiaoyatong 已提交
298 299 300 301
          <div className={b('panel')} ref={pickerRef}>
            {columnsList?.map((item, index) => {
              return (
                <PickerSlot
302
                  ref={setRefs(index)}
X
xiaoyatong 已提交
303 304 305 306 307 308 309 310 311
                  defaultValue={chooseValueData?.[index]}
                  listData={item}
                  threeDimensional={threeDimensional}
                  chooseItem={(value: PickerOption, index: number) =>
                    chooseItem(value, index)
                  }
                  swipeDuration={swipeDuration}
                  key={index}
                  keyIndex={index}
H
hanyuxinting 已提交
312
                  itemShow={visible}
X
xiaoyatong 已提交
313 314 315 316
                />
              )
            })}
          </div>
317
        </View>
X
xiaoyatong 已提交
318 319 320 321
      </Popup>
    )
  }

322
const Picker = React.forwardRef<unknown, Partial<PickerProps>>(InternalPicker)
X
xiaoyatong 已提交
323
export default Picker