index.tsx 7.3 KB
Newer Older
1 2 3 4 5 6 7
import {
  defineComponent,
  Ref,
  ref,
  computed,
  watch,
  onMounted,
8 9
  onUnmounted,
  inject,
10 11 12 13 14 15 16 17 18 19
  reactive,
  ExtractPropTypes,
} from 'vue'
import {
  useCustomEvent,
  EmitEvent,
  CustomEventTrigger,
} from '../../helpers/useNVueEvent'
import { getComponentSize } from '../helpers'
import { NVueComponentStyles, createNVueTextVNode } from '../utils'
20
import { uniFormKey, UniFormCtx } from '../../components/form'
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 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 104 105
import { sliderProps } from '../../components/slider'

const slierStyles: NVueComponentStyles = [
  {
    'uni-slider': {
      '': {
        flex: 1,
        flexDirection: 'column',
        marginTop: '12',
        marginRight: 0,
        marginBottom: '12',
        marginLeft: 0,
        paddingTop: 0,
        paddingRight: 0,
        paddingBottom: 0,
        paddingLeft: 0,
      },
    },
    'uni-slider-wrapper': {
      '': {
        flexDirection: 'row',
        alignItems: 'center',
        minHeight: '30',
      },
    },
    'uni-slider-tap-area': {
      '': {
        position: 'relative',
        flex: 1,
        flexDirection: 'column',
        paddingTop: '15',
        paddingRight: 0,
        paddingBottom: '15',
        paddingLeft: 0,
      },
    },
    'uni-slider-handle-wrapper': {
      '': {
        position: 'relative',
        marginTop: 0,
        marginRight: '18',
        marginBottom: 0,
        marginLeft: '18',
        height: '2',
        borderRadius: '5',
        backgroundColor: '#e9e9e9',
        transitionProperty: 'backgroundColor',
        transitionDuration: 300,
        transitionTimingFunction: 'ease',
      },
    },
    'uni-slider-track': {
      '': {
        height: '2',
        borderRadius: '6',
        backgroundColor: '#007aff',
        transitionProperty: 'backgroundColor',
        transitionDuration: 300,
        transitionTimingFunction: 'ease',
      },
    },
    'uni-slider-thumb': {
      '': {
        position: 'absolute',
        width: '28',
        height: '28',
        borderRadius: 50,
        boxShadow: '0 0 4px #ebebeb',
        transitionProperty: 'borderColor',
        transitionDuration: 300,
        transitionTimingFunction: 'ease',
      },
    },
    'uni-slider-step': {
      '': {
        position: 'absolute',
        width: 100,
        height: '2',
        background: 'transparent',
      },
    },
    'uni-slider-value': {
      '': {
        color: '#888888',
        fontSize: '14',
106
        marginLeft: '14',
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
      },
    },
  },
]

type SliderProps = ExtractPropTypes<typeof sliderProps>
type SliderState = ReturnType<typeof useSliderState>

export default defineComponent({
  name: 'USlider',
  props: sliderProps,
  styles: slierStyles,
  setup(props, { emit }) {
    const sliderRef: Ref<HTMLElement | null> = ref(null)
    const sliderTrackRef: Ref<HTMLElement | null> = ref(null)
    const trigger = useCustomEvent<EmitEvent<typeof emit>>(sliderRef, emit)

    const state = useSliderState(props)
    const listeners = useSliderListeners(props, state, trigger)
126
    useSliderInject(props, state)
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

    watch(
      () => props.value,
      (val) => {
        state.sliderValue = Number(val)
      }
    )

    onMounted(() => {
      setTimeout(() => {
        getComponentSize(sliderRef.value!).then(({ width }) => {
          state.sliderWidth = width || 0
          state.sliderValue = Number(props.value)
        })
      }, 100)
    })

    return () => {
      const { showValue } = props
      const { trackStyle, trackActiveStyle, thumbStyle, sliderValue } = state
      return (
        <div class="uni-slider" ref={sliderRef}>
          <div class="uni-slider-wrapper">
            <div class="uni-slider-tap-area" {...listeners}>
              <div
                class="uni-slider-handle-wrapper"
                ref={sliderTrackRef}
                style={trackStyle}
              >
                <div class="uni-slider-track" style={trackActiveStyle}></div>
              </div>
              <div class="uni-slider-thumb" style={thumbStyle}></div>
            </div>
            {showValue
161
              ? createNVueTextVNode(sliderValue + '', {
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
                  class: 'uni-slider-value',
                })
              : null}
          </div>
        </div>
      )
    }
  },
})

function useSliderState(props: SliderProps) {
  const sliderWidth = ref<number>(0)
  const sliderValue = ref<number>(0)

  const _getBgColor = () => {
    return props.backgroundColor !== '#e9e9e9'
      ? props.backgroundColor
      : props.color !== '#007aff'
      ? props.color
      : '#007aff'
  }
  const _getActiveColor = () => {
    return props.activeColor !== '#007aff'
      ? props.activeColor
      : props.selectedColor !== '#e9e9e9'
      ? props.selectedColor
      : '#e9e9e9'
  }
  const _getValueWidth = () => {
    const max = Number(props.max)
    const min = Number(props.min)
193
    return ((sliderValue.value - min) / (max - min)) * sliderWidth.value
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 269 270 271 272 273 274 275 276 277 278 279
  }

  const state = reactive({
    sliderWidth,
    sliderValue,
    trackStyle: computed(() => ({ backgroundColor: _getBgColor() })),
    trackActiveStyle: computed(() => ({
      backgroundColor: _getActiveColor(),
      width: _getValueWidth(),
    })),
    thumbStyle: computed(() => ({
      width: props.blockSize,
      height: props.blockSize,
      marginTop: -props.blockSize / 2,
      left: _getValueWidth(),
      backgroundColor: props.blockColor,
    })),
  })

  return state
}

function useSliderListeners(
  props: SliderProps,
  state: SliderState,
  trigger: CustomEventTrigger
) {
  let eventOld: any = null

  function onTrack(action: string, x: number) {
    if (!props.disabled) {
      if (action === 'move') {
        changedValue(x)
        trigger('changing', {
          value: state.sliderValue,
        })
      } else if (action === 'end') {
        changedValue(x)
        trigger('change', {
          value: state.sliderValue,
        })
      }
    }
  }

  function changedValue(x: number) {
    if (x < 0) {
      x = 0
    }
    if (x > state.sliderWidth) {
      x = state.sliderWidth
    }

    const max = Number(props.max)
    const min = Number(props.min)
    const step = Number(props.step)
    let value: number = (x / state.sliderWidth) * max - min
    if (step > 0 && value > step && (value % step) / step !== 0) {
      value -= value % step
    }

    state.sliderValue = value + min
  }

  const listeners = {
    onTouchstart(e: TouchEvent) {
      if (e.changedTouches.length === 1 && !eventOld) {
        eventOld = e
        onTrack('start', e.changedTouches[0].pageX)
      }
    },
    onTouchmove(e: TouchEvent) {
      if (e.changedTouches.length === 1 && eventOld) {
        onTrack('move', e.changedTouches[0].pageX)
      }
    },
    onTouchend(e: TouchEvent) {
      if (e.changedTouches.length === 1 && eventOld) {
        eventOld = null
        onTrack('end', e.changedTouches[0].pageX)
      }
    },
  }

  return listeners
}
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

function useSliderInject(props: SliderProps, state: SliderState) {
  const uniForm = inject<UniFormCtx>(uniFormKey, false as unknown as UniFormCtx)

  const formField = {
    submit: () => {
      const data: [string, any] = ['', null]
      if (props.name) {
        data[0] = props.name
        data[1] = state.sliderValue
      }
      return data
    },
    reset: () => {
      state.sliderValue = Number(props.value)
    },
  }

  if (!!uniForm) {
    uniForm.addField(formField)
    onUnmounted(() => {
      uniForm.removeField(formField)
    })
  }
}