index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import baseComponent from '../helpers/baseComponent'
  2. import classNames from '../helpers/libs/classNames'
  3. import eventsMixin from '../helpers/mixins/eventsMixin'
  4. import styleToCssString from '../helpers/libs/styleToCssString'
  5. import { getTouchPoints, getPointsNumber } from '../helpers/shared/gestures'
  6. import { useRect } from '../helpers/hooks/useDOM'
  7. /**
  8. * 获取小数位数
  9. */
  10. const getPrecision = (step) => {
  11. const stepString = step.toString()
  12. return stepString.indexOf('.') >= 0 ? stepString.length - stepString.indexOf('.') - 1 : 0
  13. }
  14. /**
  15. * 返回精度正确的值
  16. */
  17. const checkValuePrecision = (val, step, min) => {
  18. const closestStep = Math.round((val - min) / step) * step + min
  19. const precision = getPrecision(step)
  20. return parseFloat(closestStep.toFixed(precision))
  21. }
  22. /**
  23. * 获取样式
  24. */
  25. const getStyles = (value) => {
  26. return Array.isArray(value) ? value.map((n) => styleToCssString(n)) : styleToCssString(value)
  27. }
  28. const defaultEvents = {
  29. onChange() {},
  30. onAfterChange() {},
  31. }
  32. baseComponent({
  33. behaviors: [eventsMixin({ defaultEvents })],
  34. relations: {
  35. '../field/index': {
  36. type: 'ancestor',
  37. },
  38. },
  39. properties: {
  40. prefixCls: {
  41. type: String,
  42. value: 'wux-slider',
  43. },
  44. min: {
  45. type: Number,
  46. value: 0,
  47. observer: 'getMarks',
  48. },
  49. max: {
  50. type: Number,
  51. value: 100,
  52. observer: 'getMarks',
  53. },
  54. step: {
  55. type: Number,
  56. value: 1,
  57. observer: 'getMarks',
  58. },
  59. defaultValue: {
  60. type: Array,
  61. value: [0],
  62. },
  63. value: {
  64. type: Array,
  65. value: [0],
  66. observer(newVal) {
  67. if (this.data.controlled) {
  68. this.updated(newVal)
  69. }
  70. },
  71. },
  72. controlled: {
  73. type: Boolean,
  74. value: false,
  75. },
  76. disabled: {
  77. type: Boolean,
  78. value: false,
  79. },
  80. showMark: {
  81. type: Boolean,
  82. value: false,
  83. },
  84. showValue: {
  85. type: [Boolean, Object],
  86. value: false,
  87. },
  88. tipFormatter: {
  89. type: String,
  90. value: '{d}',
  91. },
  92. markStyle: {
  93. type: [String, Object, Array],
  94. value: '',
  95. observer(newVal) {
  96. this.setData({
  97. extMarkStyle: getStyles(newVal),
  98. })
  99. },
  100. },
  101. handleStyle: {
  102. type: [String, Object, Array],
  103. value: '',
  104. observer(newVal) {
  105. this.setData({
  106. extHandleStyle: getStyles(newVal),
  107. })
  108. },
  109. },
  110. trackStyle: {
  111. type: [String, Object, Array],
  112. value: '',
  113. observer(newVal) {
  114. this.setData({
  115. extTrackStyle: getStyles(newVal),
  116. })
  117. },
  118. },
  119. railStyle: {
  120. type: [String, Object],
  121. value: '',
  122. observer(newVal) {
  123. this.setData({
  124. extRailStyle: styleToCssString(newVal),
  125. })
  126. },
  127. },
  128. wrapStyle: {
  129. type: [String, Object],
  130. value: '',
  131. observer(newVal) {
  132. this.setData({
  133. extWrapStyle: styleToCssString(newVal),
  134. })
  135. },
  136. },
  137. },
  138. data: {
  139. offsets: [],
  140. inputValue: [],
  141. extMarkStyle: '',
  142. extHandleStyle: '',
  143. extTrackStyle: '',
  144. extRailStyle: '',
  145. extWrapStyle: '',
  146. isTouched: false,
  147. swiping: false,
  148. },
  149. computed: {
  150. classes: ['prefixCls, disabled, tipFormatter', function(prefixCls, disabled, tipFormatter) {
  151. const wrap = classNames(prefixCls, {
  152. [`${prefixCls}--disabled`]: disabled,
  153. [`${prefixCls}--has-tip`]: !!tipFormatter,
  154. })
  155. const min = `${prefixCls}__min`
  156. const railWrap = `${prefixCls}__rail-wrap`
  157. const rail = `${prefixCls}__rail`
  158. const mark = `${prefixCls}__mark`
  159. const track = `${prefixCls}__track`
  160. const handle = `${prefixCls}__handle`
  161. const max = `${prefixCls}__max`
  162. return {
  163. wrap,
  164. min,
  165. railWrap,
  166. rail,
  167. mark,
  168. track,
  169. handle,
  170. max,
  171. }
  172. }],
  173. },
  174. observers: {
  175. inputValue(newVal) {
  176. const offsets = newVal.map((value) => this.calcOffset(this.checkValue(value)))
  177. this.setData({ offsets })
  178. },
  179. },
  180. methods: {
  181. /**
  182. * 更新选中值及偏移量
  183. */
  184. updated(inputValue) {
  185. if (this.hasFieldDecorator) return
  186. if (this.data.inputValue !== inputValue) {
  187. this.setData({ inputValue })
  188. }
  189. },
  190. /**
  191. * 手指触摸动作开始
  192. */
  193. onTouchStart(e) {
  194. if (this.data.disabled || getPointsNumber(e) > 1) return
  195. const { index } = e.currentTarget.dataset
  196. this.isMoved = false
  197. this.startX = getTouchPoints(e).x
  198. this.moveX = 0
  199. // 记录选中值发生改变时的初始偏移量
  200. this.startPos = this.data.offsets[index] || 0
  201. // 记录最后一次选中项
  202. this.setData({ last: index, isTouched: true, isMoved: false })
  203. },
  204. /**
  205. * 手指触摸后移动
  206. */
  207. onTouchMove(e) {
  208. if (this.data.disabled || getPointsNumber(e) > 1) return
  209. const { index } = e.currentTarget.dataset
  210. const { prefixCls } = this.data
  211. this.isMoved = true
  212. this.setData({ isMoved: true })
  213. this.moveX = getTouchPoints(e).x
  214. useRect(`.${prefixCls}__rail`, this).then((rect) => {
  215. if (!rect || !this.isMoved) return
  216. const diffX = (this.moveX - this.startX) / rect.width * 100
  217. const nextOffsets = [...this.data.offsets]
  218. const offset = this.checkValue(this.startPos + diffX, 0, 100)
  219. const { inputValue } = this.data
  220. const currentValue = this.calcValue(offset)
  221. const prevValue = inputValue[index - 1]
  222. const nextValue = inputValue[index + 1]
  223. // 通过合法的当前值反算偏移量
  224. nextOffsets[index] = this.calcOffset(currentValue)
  225. // 判断当前值是否小于前一值,是则重新计算偏移量
  226. if (prevValue && prevValue > currentValue) {
  227. nextOffsets[index] = this.calcOffset(prevValue)
  228. }
  229. // 判断当前值是否大于后一值,是则重新计算偏移量
  230. if (nextValue && nextValue < currentValue) {
  231. nextOffsets[index] = this.calcOffset(nextValue)
  232. }
  233. // 判断当前值是否发生变化,是则触发 change 事件
  234. if (inputValue[index] !== currentValue) {
  235. const value = this.getValue(nextOffsets)
  236. if (!this.data.controlled) {
  237. this.updated(value)
  238. }
  239. this.triggerEvent('change', { offsets: nextOffsets, value })
  240. }
  241. })
  242. },
  243. /**
  244. * 手指触摸动作结束
  245. */
  246. onTouchEnd(e) {
  247. if (this.data.disabled || getPointsNumber(e) > 1 || !this.isMoved) return
  248. this.isMoved = false
  249. this.setData({ isTouched: false, isMoved: false })
  250. const { offsets } = this.data
  251. const value = this.getValue(offsets)
  252. this.triggerEvent('afterChange', { offsets, value })
  253. },
  254. /**
  255. * 计算选中值
  256. */
  257. calcValue(ratio) {
  258. const { min, max } = this.data
  259. return this.trimValue(ratio * (max - min) / 100 + min)
  260. },
  261. /**
  262. * 计算偏移量
  263. */
  264. calcOffset(value) {
  265. const { min, max } = this.data
  266. const ratio = (value - min) / (max - min)
  267. return ratio * 100
  268. },
  269. /**
  270. * 判断元素是否在指定的范围内
  271. */
  272. checkValue(val, min = this.data.min, max = this.data.max) {
  273. if (val <= min) {
  274. return min
  275. }
  276. if (val >= max) {
  277. return max
  278. }
  279. return val
  280. },
  281. /**
  282. * 验证选中值
  283. */
  284. trimValue(val) {
  285. return checkValuePrecision(this.checkValue(val), this.data.step, this.data.min)
  286. },
  287. /**
  288. * 获取选中值
  289. */
  290. getValue(offsets = this.data.offsets) {
  291. return offsets.map((offset) => this.calcValue(offset))
  292. },
  293. /**
  294. * 获取间断点位置
  295. */
  296. getMarks() {
  297. if (!this.data.showMark) return
  298. const {min, max, step } = this.data
  299. const count = (max - min) / step
  300. const marks = []
  301. const offset = 100 * step / (max - min)
  302. for (let i = 1; i < count; i++) {
  303. marks.push(i * offset)
  304. }
  305. this.setData({ marks })
  306. },
  307. noop() {},
  308. getValueByPosition(position) {
  309. const { min, max, step } = this.data
  310. const newPosition = position < min ? min : position > max ? max : position
  311. let value = min
  312. const lengthPerStep = 100 / ((max - min) / step)
  313. const steps = Math.round(newPosition / lengthPerStep)
  314. value = steps * lengthPerStep * (max - min) * 0.01 + min
  315. return value
  316. },
  317. onRailClick(e) {
  318. if (this.data.disabled || getPointsNumber(e) > 1) return
  319. const { prefixCls, min, max, inputValue: sliderValue } = this.data
  320. useRect(`.${prefixCls}__rail-wrap`, this).then((rect) => {
  321. const position = ((getTouchPoints(e).x - rect.left) / Math.ceil(rect.width)) * (max - min) + min
  322. const targetValue = this.getValueByPosition(position)
  323. const indexLength = sliderValue.length - 1
  324. const range = indexLength > 0
  325. const nextOffsets = [...this.data.offsets]
  326. let nextSliderValue = [...sliderValue]
  327. let currentIndex = 0
  328. if (range) {
  329. let prevIndex = 0
  330. let nextIndex = null
  331. for (let i = indexLength; i >= 0; i--) {
  332. if (sliderValue[i] <= targetValue) {
  333. prevIndex = i
  334. break
  335. }
  336. }
  337. if (prevIndex === indexLength) {
  338. nextIndex = prevIndex
  339. prevIndex = nextIndex - 1
  340. } else {
  341. nextIndex = prevIndex + 1
  342. }
  343. // 移动的滑块采用就近原则
  344. if (
  345. Math.abs(targetValue - sliderValue[prevIndex]) >
  346. Math.abs(targetValue - sliderValue[nextIndex])
  347. ) {
  348. currentIndex = nextIndex
  349. nextSliderValue[nextIndex] = targetValue
  350. } else {
  351. currentIndex = prevIndex
  352. nextSliderValue[prevIndex] = targetValue
  353. }
  354. } else {
  355. nextSliderValue = [targetValue]
  356. }
  357. nextOffsets[currentIndex] = this.calcOffset(targetValue)
  358. if (sliderValue[currentIndex] !== targetValue) {
  359. if (!this.data.controlled) {
  360. this.updated(nextSliderValue)
  361. }
  362. this.triggerEvent('change', { offsets: nextOffsets, value: nextSliderValue })
  363. this.triggerEvent('afterChange', { offsets: nextOffsets, value: nextSliderValue })
  364. }
  365. })
  366. },
  367. },
  368. attached() {
  369. const { defaultValue, value, controlled } = this.data
  370. const inputValue = controlled ? value : defaultValue
  371. this.getMarks()
  372. this.updated(inputValue)
  373. },
  374. })