add vc-slider v0.1

pull/9/head
wangxueliang 2018-03-23 18:37:32 +08:00
parent 847bed5bca
commit 263dd3a520
8 changed files with 845 additions and 894 deletions

View File

@ -1,74 +1,80 @@
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import addEventListener from 'rc-util/lib/Dom/addEventListener';
export default class Handle extends React.Component { import classNames from 'classnames'
state = { import PropTypes from '../../../_util/vue-types'
import addEventListener from '../../../_util/Dom/addEventListener'
import BaseMixin from '../../../_util/BaseMixin'
export default {
mixins: [BaseMixin],
props: {
prefixCls: PropTypes.string,
vertical: PropTypes.bool,
offset: PropTypes.number,
disabled: PropTypes.bool,
min: PropTypes.number,
max: PropTypes.number,
value: PropTypes.number,
tabIndex: PropTypes.number,
},
data () {
return {
clickFocused: false, clickFocused: false,
} }
},
componentDidMount() { mounted () {
// mouseup won't trigger if mouse moved out of handle, this.$nextTick(() => {
// so we listen on document here. this.onMouseUpListener = addEventListener(document, 'mouseup', this.handleMouseUp)
this.onMouseUpListener = addEventListener(document, 'mouseup', this.handleMouseUp); })
} },
beforeDestroy () {
componentWillUnmount() { this.$nextTick(() => {
if (this.onMouseUpListener) { if (this.onMouseUpListener) {
this.onMouseUpListener.remove(); this.onMouseUpListener.remove()
} }
})
},
methods: {
setClickFocus (focused) {
this.setState({ clickFocused: focused })
},
handleMouseUp () {
if (document.activeElement === this.$refs.handle) {
this.setClickFocus(true)
} }
},
setClickFocus(focused) { handleBlur () {
this.setState({ clickFocused: focused }); this.setClickFocus(false)
} },
handleKeyDown () {
handleMouseUp = () => { this.setClickFocus(false)
if (document.activeElement === this.handle) { },
this.setClickFocus(true); clickFocus () {
} this.setClickFocus(true)
} this.focus()
},
handleBlur = () => { focus () {
this.setClickFocus(false); this.$refs.handle.focus()
} },
blur () {
handleKeyDown = () => { this.$refs.handle.blur()
this.setClickFocus(false); },
} },
render () {
clickFocus() {
this.setClickFocus(true);
this.focus();
}
focus() {
this.handle.focus();
}
blur() {
this.handle.blur();
}
render() {
const { const {
prefixCls, vertical, offset, style, disabled, min, max, value, tabIndex, ...restProps, prefixCls, vertical, offset, disabled, min, max, value, tabIndex, ...restProps
} = this.props; } = this.$props
const className = classNames( const className = classNames(
this.props.className,
{ {
[`${prefixCls}-handle-click-focused`]: this.state.clickFocused, [`${prefixCls}-handle-click-focused`]: this.clickFocused,
} }
); )
const postionStyle = vertical ? { bottom: `${offset}%` } : { left: `${offset}%` }; const postionStyle = vertical ? { bottom: `${offset}%` } : { left: `${offset}%` }
const elStyle = { const elStyle = {
...style,
...postionStyle, ...postionStyle,
}; }
let ariaProps = {}; let ariaProps = {}
if (value !== undefined) { if (value !== undefined) {
ariaProps = { ariaProps = {
...ariaProps, ...ariaProps,
@ -76,34 +82,21 @@ export default class Handle extends React.Component {
'aria-valuemax': max, 'aria-valuemax': max,
'aria-valuenow': value, 'aria-valuenow': value,
'aria-disabled': !!disabled, 'aria-disabled': !!disabled,
}; }
} }
return ( return (
<div <div
ref={node => (this.handle = node)} ref='handle'
role="slider" role='slider'
tabIndex= {disabled ? null : (tabIndex || 0)} tabIndex= {disabled ? null : (tabIndex || 0)}
{...ariaProps} {...ariaProps}
{...restProps} {...restProps}
className={className} class={className}
style={elStyle} style={elStyle}
onBlur={this.handleBlur} onBlur={this.handleBlur}
onKeyDown={this.handleKeyDown} onKeydown={this.handleKeyDown}
/> />
); )
} },
} }
Handle.propTypes = {
prefixCls: PropTypes.string,
className: PropTypes.string,
vertical: PropTypes.bool,
offset: PropTypes.number,
style: PropTypes.object,
disabled: PropTypes.bool,
min: PropTypes.number,
max: PropTypes.number,
value: PropTypes.number,
tabIndex: PropTypes.number,
};

View File

@ -1,15 +1,12 @@
/* eslint-disable react/prop-types */ import classNames from 'classnames'
import React from 'react'; import PropTypes from '../../../_util/vue-types'
import PropTypes from 'prop-types'; import BaseMixin from '../../../_util/BaseMixin'
import classNames from 'classnames'; import { initDefaultProps, hasProp } from '../../../_util/props-util'
import shallowEqual from 'shallowequal'; import Track from './common/Track'
import Track from './common/Track'; import createSlider from './common/createSlider'
import createSlider from './common/createSlider'; import * as utils from './utils'
import * as utils from './utils';
class Range extends React.Component { const rangeProps = {
static displayName = 'Range';
static propTypes = {
defaultValue: PropTypes.arrayOf(PropTypes.number), defaultValue: PropTypes.arrayOf(PropTypes.number),
value: PropTypes.arrayOf(PropTypes.number), value: PropTypes.arrayOf(PropTypes.number),
count: PropTypes.number, count: PropTypes.number,
@ -20,308 +17,292 @@ class Range extends React.Component {
allowCross: PropTypes.bool, allowCross: PropTypes.bool,
disabled: PropTypes.bool, disabled: PropTypes.bool,
tabIndex: PropTypes.arrayOf(PropTypes.number), tabIndex: PropTypes.arrayOf(PropTypes.number),
}; }
const Range = {
static defaultProps = { displayName: 'Range',
mixins: [BaseMixin],
props: initDefaultProps(rangeProps, {
count: 1, count: 1,
allowCross: true, allowCross: true,
pushable: false, pushable: false,
tabIndex: [], tabIndex: [],
}; }),
data () {
constructor(props) { const { count, min, max } = this
super(props);
const { count, min, max } = props;
const initialValue = Array.apply(null, Array(count + 1)) const initialValue = Array.apply(null, Array(count + 1))
.map(() => min); .map(() => min)
const defaultValue = 'defaultValue' in props ? const defaultValue = hasProp(this, 'defaultValue') ? this.defaultValue : initialValue
props.defaultValue : initialValue; let { value } = this
const value = props.value !== undefined ? if (value === undefined) {
props.value : defaultValue; value = defaultValue
const bounds = value.map((v, i) => this.trimAlignValue(v, i)); }
const recent = bounds[0] === max ? 0 : bounds.length - 1; const bounds = value.map((v, i) => this.trimAlignValue(v, i))
const recent = bounds[0] === max ? 0 : bounds.length - 1
this.state = { return {
handle: null, handle: null,
recent, recent,
bounds, bounds,
};
} }
},
componentWillReceiveProps(nextProps) { watch: {
if (!('value' in nextProps || 'min' in nextProps || 'max' in nextProps)) return; value: {
if (this.props.min === nextProps.min && handler (val) {
this.props.max === nextProps.max && const { min, max } = this
shallowEqual(this.props.value, nextProps.value)) { this.setChangeValue(val, min, max)
return; },
deep: true,
},
min (val) {
const { bounds, max } = this
this.setChangeValue(bounds, val, max)
},
max (val) {
const { bounds, min } = this
this.setChangeValue(bounds, min, val)
},
},
methods: {
setChangeValue (value, min, max) {
const { bounds } = this
const newValue = value || bounds
const minAmaxProps = {
min,
max,
} }
const nextBounds = newValue.map((v, i) => this.trimAlignValue(v, i, minAmaxProps))
if (nextBounds.length === bounds.length && nextBounds.every((v, i) => v === bounds[i])) return
const { bounds } = this.state; this.setState({ bounds: nextBounds })
const value = nextProps.value || bounds;
const nextBounds = value.map((v, i) => this.trimAlignValue(v, i, nextProps));
if (nextBounds.length === bounds.length && nextBounds.every((v, i) => v === bounds[i])) return;
this.setState({ bounds: nextBounds }); if (bounds.some(v => utils.isValueOutOfRange(v, minAmaxProps))) {
const newValues = newValue.map((v) => {
if (bounds.some(v => utils.isValueOutOfRange(v, nextProps))) { return utils.ensureValueInRange(v, minAmaxProps)
const newValues = value.map((v) => { })
return utils.ensureValueInRange(v, nextProps); this.$emit('change', newValues)
});
this.props.onChange(newValues);
} }
} },
onChange (state) {
onChange(state) { const isNotControlled = !hasProp(this, 'value')
const props = this.props;
const isNotControlled = !('value' in props);
if (isNotControlled) { if (isNotControlled) {
this.setState(state); this.setState(state)
} else if (state.handle !== undefined) { } else if (state.handle !== undefined) {
this.setState({ handle: state.handle }); this.setState({ handle: state.handle })
} }
const data = { ...this.state, ...state }; const data = { ...this.$data, ...state }
const changedValue = data.bounds; const changedValue = data.bounds
props.onChange(changedValue); this.$emit('change', changedValue)
} },
onStart (position) {
const { bounds } = this
this.$emit('beforeChange', bounds)
onStart(position) { const value = this.calcValueByPos(position)
const props = this.props;
const state = this.state;
const bounds = this.getValue();
props.onBeforeChange(bounds);
const value = this.calcValueByPos(position); const closestBound = this.getClosestBound(value)
this.startValue = value; this.prevMovedHandleIndex = this.getBoundNeedMoving(value, closestBound)
this.startPosition = position;
const closestBound = this.getClosestBound(value);
this.prevMovedHandleIndex = this.getBoundNeedMoving(value, closestBound);
this.setState({ this.setState({
handle: this.prevMovedHandleIndex, handle: this.prevMovedHandleIndex,
recent: this.prevMovedHandleIndex, recent: this.prevMovedHandleIndex,
}); })
const prevValue = bounds[this.prevMovedHandleIndex]; const prevValue = bounds[this.prevMovedHandleIndex]
if (value === prevValue) return; if (value === prevValue) return
const nextBounds = [...state.bounds]; const nextBounds = [...bounds]
nextBounds[this.prevMovedHandleIndex] = value; nextBounds[this.prevMovedHandleIndex] = value
this.onChange({ bounds: nextBounds }); this.$emit('change', { bounds: nextBounds })
} },
onEnd () {
this.removeDocumentEvents()
this.$emit('afterChange', this.bounds)
},
onMove (e, position) {
utils.pauseEvent(e)
const { bounds, handle } = this
const value = this.calcValueByPos(position)
const oldValue = bounds[handle]
if (value === oldValue) return
onEnd = () => { this.moveTo(value)
this.removeDocumentEvents(); },
this.props.onAfterChange(this.getValue()); onKeyboard (e) {
} const valueMutator = utils.getKeyboardValueMutator(e)
onMove(e, position) {
utils.pauseEvent(e);
const state = this.state;
const value = this.calcValueByPos(position);
const oldValue = state.bounds[state.handle];
if (value === oldValue) return;
this.moveTo(value);
}
onKeyboard(e) {
const valueMutator = utils.getKeyboardValueMutator(e);
if (valueMutator) { if (valueMutator) {
utils.pauseEvent(e); utils.pauseEvent(e)
const { state, props } = this; const { bounds, handle } = this
const { bounds, handle } = state; const oldValue = bounds[handle]
const oldValue = bounds[handle]; const mutatedValue = valueMutator(oldValue, this.$props)
const mutatedValue = valueMutator(oldValue, props); const value = this.trimAlignValue(mutatedValue)
const value = this.trimAlignValue(mutatedValue); if (value === oldValue) return
if (value === oldValue) return; const isFromKeyboardEvent = true
const isFromKeyboardEvent = true; this.moveTo(value, isFromKeyboardEvent)
this.moveTo(value, isFromKeyboardEvent);
} }
} },
getClosestBound (value) {
getValue() { const { bounds } = this
return this.state.bounds; let closestBound = 0
}
getClosestBound(value) {
const { bounds } = this.state;
let closestBound = 0;
for (let i = 1; i < bounds.length - 1; ++i) { for (let i = 1; i < bounds.length - 1; ++i) {
if (value > bounds[i]) { closestBound = i; } if (value > bounds[i]) { closestBound = i }
} }
if (Math.abs(bounds[closestBound + 1] - value) < Math.abs(bounds[closestBound] - value)) { if (Math.abs(bounds[closestBound + 1] - value) < Math.abs(bounds[closestBound] - value)) {
closestBound = closestBound + 1; closestBound = closestBound + 1
} }
return closestBound; return closestBound
} },
getBoundNeedMoving (value, closestBound) {
getBoundNeedMoving(value, closestBound) { const { bounds, recent } = this
const { bounds, recent } = this.state; let boundNeedMoving = closestBound
let boundNeedMoving = closestBound; const isAtTheSamePoint = (bounds[closestBound + 1] === bounds[closestBound])
const isAtTheSamePoint = (bounds[closestBound + 1] === bounds[closestBound]);
if (isAtTheSamePoint && bounds[recent] === bounds[closestBound]) { if (isAtTheSamePoint && bounds[recent] === bounds[closestBound]) {
boundNeedMoving = recent; boundNeedMoving = recent
} }
if (isAtTheSamePoint && (value !== bounds[closestBound + 1])) { if (isAtTheSamePoint && (value !== bounds[closestBound + 1])) {
boundNeedMoving = value < bounds[closestBound + 1] ? closestBound : closestBound + 1; boundNeedMoving = value < bounds[closestBound + 1] ? closestBound : closestBound + 1
} }
return boundNeedMoving; return boundNeedMoving
} },
getLowerBound () {
getLowerBound() { return this.bounds[0]
return this.state.bounds[0]; },
} getUpperBound () {
const { bounds } = this
getUpperBound() { return bounds[bounds.length - 1]
const { bounds } = this.state; },
return bounds[bounds.length - 1];
}
/** /**
* Returns an array of possible slider points, taking into account both * Returns an array of possible slider points, taking into account both
* `marks` and `step`. The result is cached. * `marks` and `step`. The result is cached.
*/ */
getPoints() { getPoints () {
const { marks, step, min, max } = this.props; const { marks, step, min, max } = this
const cache = this._getPointsCache; const cache = this._getPointsCache
if (!cache || cache.marks !== marks || cache.step !== step) { if (!cache || cache.marks !== marks || cache.step !== step) {
const pointsObject = { ...marks }; const pointsObject = { ...marks }
if (step !== null) { if (step !== null) {
for (let point = min; point <= max; point += step) { for (let point = min; point <= max; point += step) {
pointsObject[point] = point; pointsObject[point] = point
} }
} }
const points = Object.keys(pointsObject).map(parseFloat); const points = Object.keys(pointsObject).map(parseFloat)
points.sort((a, b) => a - b); points.sort((a, b) => a - b)
this._getPointsCache = { marks, step, points }; this._getPointsCache = { marks, step, points }
} }
return this._getPointsCache.points; return this._getPointsCache.points
},
moveTo (value, isFromKeyboardEvent) {
const { bounds, handle } = this
const nextBounds = [...bounds]
nextBounds[handle] = value
let nextHandle = handle
if (this.pushable !== false) {
this.pushSurroundingHandles(nextBounds, nextHandle)
} else if (this.allowCross) {
nextBounds.sort((a, b) => a - b)
nextHandle = nextBounds.indexOf(value)
} }
this.$emit('change', {
moveTo(value, isFromKeyboardEvent) {
const { state, props } = this;
const nextBounds = [...state.bounds];
nextBounds[state.handle] = value;
let nextHandle = state.handle;
if (props.pushable !== false) {
this.pushSurroundingHandles(nextBounds, nextHandle);
} else if (props.allowCross) {
nextBounds.sort((a, b) => a - b);
nextHandle = nextBounds.indexOf(value);
}
this.onChange({
handle: nextHandle, handle: nextHandle,
bounds: nextBounds, bounds: nextBounds,
}); })
if (isFromKeyboardEvent) { if (isFromKeyboardEvent) {
// known problem: because setState is async, // known problem: because setState is async,
// so trigger focus will invoke handler's onEnd and another handler's onStart too early, // so trigger focus will invoke handler's onEnd and another handler's onStart too early,
// cause onBeforeChange and onAfterChange receive wrong value. // cause onBeforeChange and onAfterChange receive wrong value.
// here use setState callback to hackbut not elegant // here use setState callback to hackbut not elegant
this.setState({}, () => { this.setState({}, () => {
this.handlesRefs[nextHandle].focus(); this.handlesRefs[nextHandle].focus()
}); })
}
} }
},
pushSurroundingHandles (bounds, handle) {
const value = bounds[handle]
let { pushable: threshold } = this
threshold = Number(threshold)
pushSurroundingHandles(bounds, handle) { let direction = 0
const value = bounds[handle];
let { pushable: threshold } = this.props;
threshold = Number(threshold);
let direction = 0;
if (bounds[handle + 1] - value < threshold) { if (bounds[handle + 1] - value < threshold) {
direction = +1; // push to right direction = +1 // push to right
} }
if (value - bounds[handle - 1] < threshold) { if (value - bounds[handle - 1] < threshold) {
direction = -1; // push to left direction = -1 // push to left
} }
if (direction === 0) { return; } if (direction === 0) { return }
const nextHandle = handle + direction; const nextHandle = handle + direction
const diffToNext = direction * (bounds[nextHandle] - value); const diffToNext = direction * (bounds[nextHandle] - value)
if (!this.pushHandle(bounds, nextHandle, direction, threshold - diffToNext)) { if (!this.pushHandle(bounds, nextHandle, direction, threshold - diffToNext)) {
// revert to original value if pushing is impossible // revert to original value if pushing is impossible
bounds[handle] = bounds[nextHandle] - (direction * threshold); bounds[handle] = bounds[nextHandle] - (direction * threshold)
} }
} },
pushHandle (bounds, handle, direction, amount) {
pushHandle(bounds, handle, direction, amount) { const originalValue = bounds[handle]
const originalValue = bounds[handle]; let currentValue = bounds[handle]
let currentValue = bounds[handle];
while (direction * (currentValue - originalValue) < amount) { while (direction * (currentValue - originalValue) < amount) {
if (!this.pushHandleOnePoint(bounds, handle, direction)) { if (!this.pushHandleOnePoint(bounds, handle, direction)) {
// can't push handle enough to create the needed `amount` gap, so we // can't push handle enough to create the needed `amount` gap, so we
// revert its position to the original value // revert its position to the original value
bounds[handle] = originalValue; bounds[handle] = originalValue
return false; return false
} }
currentValue = bounds[handle]; currentValue = bounds[handle]
} }
// the handle was pushed enough to create the needed `amount` gap // the handle was pushed enough to create the needed `amount` gap
return true; return true
} },
pushHandleOnePoint (bounds, handle, direction) {
pushHandleOnePoint(bounds, handle, direction) { const points = this.getPoints()
const points = this.getPoints(); const pointIndex = points.indexOf(bounds[handle])
const pointIndex = points.indexOf(bounds[handle]); const nextPointIndex = pointIndex + direction
const nextPointIndex = pointIndex + direction;
if (nextPointIndex >= points.length || nextPointIndex < 0) { if (nextPointIndex >= points.length || nextPointIndex < 0) {
// reached the minimum or maximum available point, can't push anymore // reached the minimum or maximum available point, can't push anymore
return false; return false
} }
const nextHandle = handle + direction; const nextHandle = handle + direction
const nextValue = points[nextPointIndex]; const nextValue = points[nextPointIndex]
const { pushable: threshold } = this.props; const { pushable: threshold } = this
const diffToNext = direction * (bounds[nextHandle] - nextValue); const diffToNext = direction * (bounds[nextHandle] - nextValue)
if (!this.pushHandle(bounds, nextHandle, direction, threshold - diffToNext)) { if (!this.pushHandle(bounds, nextHandle, direction, threshold - diffToNext)) {
// couldn't push next handle, so we won't push this one either // couldn't push next handle, so we won't push this one either
return false; return false
} }
// push the handle // push the handle
bounds[handle] = nextValue; bounds[handle] = nextValue
return true; return true
} },
trimAlignValue (v, handle, nextProps = {}) {
trimAlignValue(v, handle, nextProps = {}) { const mergedProps = { ...this, ...nextProps }
const mergedProps = { ...this.props, ...nextProps }; const valInRange = utils.ensureValueInRange(v, mergedProps)
const valInRange = utils.ensureValueInRange(v, mergedProps); const valNotConflict = this.ensureValueNotConflict(handle, valInRange, mergedProps)
const valNotConflict = this.ensureValueNotConflict(handle, valInRange, mergedProps); return utils.ensureValuePrecision(valNotConflict, mergedProps)
return utils.ensureValuePrecision(valNotConflict, mergedProps); },
} ensureValueNotConflict (handle, val, { allowCross, pushable: thershold }) {
const state = this.$data || {}
ensureValueNotConflict(handle, val, { allowCross, pushable: thershold }) { const { bounds } = state
const state = this.state || {}; handle = handle === undefined ? state.handle : handle
const { bounds } = state; thershold = Number(thershold)
handle = handle === undefined ? state.handle : handle;
thershold = Number(thershold);
/* eslint-disable eqeqeq */ /* eslint-disable eqeqeq */
if (!allowCross && handle != null && bounds !== undefined) { if (!allowCross && handle != null && bounds !== undefined) {
if (handle > 0 && val <= (bounds[handle - 1] + thershold)) { if (handle > 0 && val <= (bounds[handle - 1] + thershold)) {
return bounds[handle - 1] + thershold; return bounds[handle - 1] + thershold
} }
if (handle < bounds.length - 1 && val >= (bounds[handle + 1] - thershold)) { if (handle < bounds.length - 1 && val >= (bounds[handle + 1] - thershold)) {
return bounds[handle + 1] - thershold; return bounds[handle + 1] - thershold
} }
} }
/* eslint-enable eqeqeq */ /* eslint-enable eqeqeq */
return val; return val
} },
},
render() { render () {
const { const {
handle, handle,
bounds, bounds,
} = this.state;
const {
prefixCls, prefixCls,
vertical, vertical,
included, included,
@ -332,11 +313,11 @@ class Range extends React.Component {
trackStyle, trackStyle,
handleStyle, handleStyle,
tabIndex, tabIndex,
} = this.props; } = this
const offsets = bounds.map(v => this.calcOffset(v)); const offsets = bounds.map(v => this.calcOffset(v))
const handleClassName = `${prefixCls}-handle`; const handleClassName = `${prefixCls}-handle`
const handles = bounds.map((v, i) => handleGenerator({ const handles = bounds.map((v, i) => handleGenerator({
className: classNames({ className: classNames({
[handleClassName]: true, [handleClassName]: true,
@ -354,14 +335,14 @@ class Range extends React.Component {
disabled, disabled,
style: handleStyle[i], style: handleStyle[i],
ref: h => this.saveHandle(i, h), ref: h => this.saveHandle(i, h),
})); }))
const tracks = bounds.slice(0, -1).map((_, index) => { const tracks = bounds.slice(0, -1).map((_, index) => {
const i = index + 1; const i = index + 1
const trackClassName = classNames({ const trackClassName = classNames({
[`${prefixCls}-track`]: true, [`${prefixCls}-track`]: true,
[`${prefixCls}-track-${i}`]: true, [`${prefixCls}-track-${i}`]: true,
}); })
return ( return (
<Track <Track
className={trackClassName} className={trackClassName}
@ -372,11 +353,11 @@ class Range extends React.Component {
style={trackStyle[index]} style={trackStyle[index]}
key={i} key={i}
/> />
); )
}); })
return { tracks, handles }; return { tracks, handles }
} },
} }
export default createSlider(Range); export default createSlider(Range)

View File

@ -1,142 +1,142 @@
/* eslint-disable react/prop-types */ import PropTypes from '../../../_util/vue-types'
import React from 'react' import warning from '../../../_util/warning'
import PropTypes from 'prop-types' import BaseMixin from '../../../_util/BaseMixin'
import warning from 'warning' import { hasProp } from '../../../_util/props-util'
import Track from './common/Track' import Track from './common/Track'
import createSlider from './common/createSlider' import createSlider from './common/createSlider'
import * as utils from './utils' import * as utils from './utils'
class Slider extends React.Component { const Slider = {
static propTypes = { mixins: [BaseMixin],
props: {
defaultValue: PropTypes.number, defaultValue: PropTypes.number,
value: PropTypes.number, value: PropTypes.number,
disabled: PropTypes.bool, disabled: PropTypes.bool,
autoFocus: PropTypes.bool, autoFocus: PropTypes.bool,
tabIndex: PropTypes.number, tabIndex: PropTypes.number,
}; },
data () {
const defaultValue = this.defaultValue !== undefined
? this.defaultValue : this.min
const value = this.value !== undefined
? this.value : defaultValue
constructor (props) {
super(props)
const defaultValue = props.defaultValue !== undefined
? props.defaultValue : props.min
const value = props.value !== undefined
? props.value : defaultValue
this.state = {
value: this.trimAlignValue(value),
dragging: false,
}
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
warning( warning(
!('minimumTrackStyle' in props), !hasProp(this, 'minimumTrackStyle'),
'minimumTrackStyle will be deprecate, please use trackStyle instead.' 'minimumTrackStyle will be deprecate, please use trackStyle instead.'
) )
warning( warning(
!('maximumTrackStyle' in props), !hasProp(this, 'maximumTrackStyle'),
'maximumTrackStyle will be deprecate, please use railStyle instead.' 'maximumTrackStyle will be deprecate, please use railStyle instead.'
) )
} }
return {
sValue: this.trimAlignValue(value),
dragging: false,
} }
},
componentDidMount () { mounted () {
const { autoFocus, disabled } = this.props this.$nextTick(() => {
const { autoFocus, disabled } = this
if (autoFocus && !disabled) { if (autoFocus && !disabled) {
this.focus() this.focus()
} }
})
},
watch: {
value: {
handler (val) {
const { min, max } = this
this.setChangeValue(val, min, max)
},
deep: true,
},
min (val) {
const { sValue, max } = this
this.setChangeValue(sValue, val, max)
},
max (val) {
const { sValue, min } = this
this.setChangeValue(sValue, min, val)
},
},
methods: {
setChangeValue (value, min, max) {
const minAmaxProps = {
min,
max,
} }
const newValue = value !== undefined
? value : this.sValue
const nextValue = this.trimAlignValue(newValue, minAmaxProps)
if (nextValue === this.sValue) return
componentWillReceiveProps (nextProps) { this.setState({ sValue: nextValue })
if (!('value' in nextProps || 'min' in nextProps || 'max' in nextProps)) return if (utils.isValueOutOfRange(newValue, minAmaxProps)) {
this.$emit('change', nextValue)
const prevValue = this.state.value
const value = nextProps.value !== undefined
? nextProps.value : prevValue
const nextValue = this.trimAlignValue(value, nextProps)
if (nextValue === prevValue) return
this.setState({ value: nextValue })
if (utils.isValueOutOfRange(value, nextProps)) {
this.props.onChange(nextValue)
} }
} },
onChange (state) { onChange (state) {
const props = this.props const isNotControlled = !hasProp(this, 'value')
const isNotControlled = !('value' in props)
if (isNotControlled) { if (isNotControlled) {
this.setState(state) this.setState(state)
} }
const changedValue = state.value const changedValue = state.sValue
props.onChange(changedValue) this.$emit('change', changedValue)
} },
onStart (position) { onStart (position) {
this.setState({ dragging: true }) this.setState({ dragging: true })
const props = this.props const { sValue } = this
const prevValue = this.getValue() this.$emit('beforeChange', sValue)
props.onBeforeChange(prevValue)
const value = this.calcValueByPos(position) const value = this.calcValueByPos(position)
this.startValue = value
this.startPosition = position
if (value === prevValue) return if (value === sValue) return
this.prevMovedHandleIndex = 0 this.prevMovedHandleIndex = 0
this.onChange({ value }) this.onChange({ sValue: value })
} },
onEnd () {
onEnd = () => {
this.setState({ dragging: false }) this.setState({ dragging: false })
this.removeDocumentEvents() this.removeDocumentEvents()
this.props.onAfterChange(this.getValue()) this.$emit('afterChange', this.sValue)
} },
onMove (e, position) { onMove (e, position) {
utils.pauseEvent(e) utils.pauseEvent(e)
const { value: oldValue } = this.state const { sValue } = this
const value = this.calcValueByPos(position) const value = this.calcValueByPos(position)
if (value === oldValue) return if (value === sValue) return
this.onChange({ value })
}
this.onChange({ sValue: value })
},
onKeyboard (e) { onKeyboard (e) {
const valueMutator = utils.getKeyboardValueMutator(e) const valueMutator = utils.getKeyboardValueMutator(e)
if (valueMutator) { if (valueMutator) {
utils.pauseEvent(e) utils.pauseEvent(e)
const state = this.state const { sValue } = this
const oldValue = state.value const mutatedValue = valueMutator(sValue, this.$props)
const mutatedValue = valueMutator(oldValue, this.props)
const value = this.trimAlignValue(mutatedValue) const value = this.trimAlignValue(mutatedValue)
if (value === oldValue) return if (value === sValue) return
this.onChange({ value }) this.onChange({ sValue: value })
} }
} },
getValue () {
return this.state.value
}
getLowerBound () { getLowerBound () {
return this.props.min return this.min
} },
getUpperBound () { getUpperBound () {
return this.state.value return this.sValue
} },
trimAlignValue (v, nextProps = {}) { trimAlignValue (v, nextProps = {}) {
const mergedProps = { ...this.props, ...nextProps } const mergedProps = { ...this.$props, ...nextProps }
const val = utils.ensureValueInRange(v, mergedProps) const val = utils.ensureValueInRange(v, mergedProps)
return utils.ensureValuePrecision(val, mergedProps) return utils.ensureValuePrecision(val, mergedProps)
} },
},
render () { render () {
const { const {
prefixCls, prefixCls,
@ -150,7 +150,7 @@ class Slider extends React.Component {
min, min,
max, max,
handle: handleGenerator, handle: handleGenerator,
} = this.props } = this
const { value, dragging } = this.state const { value, dragging } = this.state
const offset = this.calcOffset(value) const offset = this.calcOffset(value)
const handle = handleGenerator({ const handle = handleGenerator({
@ -183,9 +183,8 @@ class Slider extends React.Component {
}} }}
/> />
) )
return { tracks: track, handles: handle } return { tracks: track, handles: handle }
} },
} }
export default createSlider(Slider) export default createSlider(Slider)

View File

@ -1,7 +1,9 @@
import React from 'react'
import classNames from 'classnames' import classNames from 'classnames'
const Marks = ({ const Marks = {
functional: true,
render (createElement, context) {
const {
className, className,
vertical, vertical,
marks, marks,
@ -9,8 +11,8 @@ const Marks = ({
upperBound, upperBound,
lowerBound, lowerBound,
max, min, max, min,
onClickLabel, } = context.props
}) => { const { clickLabel } = context.listeners
const marksKeys = Object.keys(marks) const marksKeys = Object.keys(marks)
const marksCount = marksKeys.length const marksCount = marksKeys.length
const unit = marksCount > 1 ? 100 / (marksCount - 1) : 100 const unit = marksCount > 1 ? 100 / (marksCount - 1) : 100
@ -19,8 +21,10 @@ const Marks = ({
const range = max - min const range = max - min
const elements = marksKeys.map(parseFloat).sort((a, b) => a - b).map(point => { const elements = marksKeys.map(parseFloat).sort((a, b) => a - b).map(point => {
const markPoint = marks[point] const markPoint = marks[point]
const markPointIsObject = typeof markPoint === 'object' && // todo
!React.isValidElement(markPoint) // const markPointIsObject = typeof markPoint === 'object' &&
// !React.isValidElement(markPoint)
const markPointIsObject = typeof markPoint === 'object'
const markLabel = markPointIsObject ? markPoint.label : markPoint const markLabel = markPointIsObject ? markPoint.label : markPoint
if (!markLabel && markLabel !== 0) { if (!markLabel && markLabel !== 0) {
return null return null
@ -49,18 +53,19 @@ const Marks = ({
? { ...style, ...markPoint.style } : style ? { ...style, ...markPoint.style } : style
return ( return (
<span <span
className={markClassName} class={markClassName}
style={markStyle} style={markStyle}
key={point} key={point}
onMouseDown={(e) => onClickLabel(e, point)} onMouseDown={(e) => clickLabel(e, point)}
onTouchStart={(e) => onClickLabel(e, point)} onTouchStart={(e) => clickLabel(e, point)}
> >
{markLabel} {markLabel}
</span> </span>
) )
}) })
return <div className={className}>{elements}</div> return <div class={className}>{elements}</div>
}; },
}
export default Marks export default Marks

View File

@ -1,6 +1,5 @@
import React from 'react'
import classNames from 'classnames' import classNames from 'classnames'
import warning from 'warning' import warning from '../../../_util/warning'
const calcPoints = (vertical, marks, dots, step, min, max) => { const calcPoints = (vertical, marks, dots, step, min, max) => {
warning( warning(
@ -17,8 +16,11 @@ const calcPoints = (vertical, marks, dots, step, min, max) => {
return points return points
} }
const Steps = ({ prefixCls, vertical, marks, dots, step, included, const Steps = {
lowerBound, upperBound, max, min, dotStyle, activeDotStyle }) => { functional: true,
render (createElement, context) {
const { prefixCls, vertical, marks, dots, step, included,
lowerBound, upperBound, max, min, dotStyle, activeDotStyle } = context.data
const range = max - min const range = max - min
const elements = calcPoints(vertical, marks, dots, step, min, max).map((point) => { const elements = calcPoints(vertical, marks, dots, step, min, max).map((point) => {
const offset = `${Math.abs(point - min) / range * 100}%` const offset = `${Math.abs(point - min) / range * 100}%`
@ -39,6 +41,7 @@ const Steps = ({ prefixCls, vertical, marks, dots, step, included,
}) })
return <div className={`${prefixCls}-step`}>{elements}</div> return <div className={`${prefixCls}-step`}>{elements}</div>
},
} }
export default Steps export default Steps

View File

@ -1,8 +1,8 @@
import React from 'react'
import PropTypes from 'prop-types'
import addEventListener from 'rc-util/lib/Dom/addEventListener'
import classNames from 'classnames' import classNames from 'classnames'
import warning from 'warning' import PropTypes from '../../../_util/vue-types'
import addEventListener from '../../../_util/Dom/addEventListener'
import warning from '../../../_util/warning'
import { initDefaultProps } from '../../../_util/props-util'
import Steps from './Steps' import Steps from './Steps'
import Marks from './Marks' import Marks from './Marks'
import Handle from '../Handle' import Handle from '../Handle'
@ -11,26 +11,19 @@ import * as utils from '../utils'
function noop () {} function noop () {}
export default function createSlider (Component) { export default function createSlider (Component) {
return class ComponentEnhancer extends Component { // const displayName = `ComponentEnhancer(${Component.displayName})`
static displayName = `ComponentEnhancer(${Component.displayName})`; const propTypes = {
static propTypes = {
...Component.propTypes, ...Component.propTypes,
min: PropTypes.number, min: PropTypes.number,
max: PropTypes.number, max: PropTypes.number,
step: PropTypes.number, step: PropTypes.number,
marks: PropTypes.object, marks: PropTypes.object,
included: PropTypes.bool, included: PropTypes.bool,
className: PropTypes.string,
prefixCls: PropTypes.string, prefixCls: PropTypes.string,
disabled: PropTypes.bool, disabled: PropTypes.bool,
children: PropTypes.any,
onBeforeChange: PropTypes.func,
onChange: PropTypes.func,
onAfterChange: PropTypes.func,
handle: PropTypes.func, handle: PropTypes.func,
dots: PropTypes.bool, dots: PropTypes.bool,
vertical: PropTypes.bool, vertical: PropTypes.bool,
style: PropTypes.object,
minimumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate minimumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate
maximumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate maximumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate
handleStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]), handleStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]),
@ -39,14 +32,11 @@ export default function createSlider (Component) {
dotStyle: PropTypes.object, dotStyle: PropTypes.object,
activeDotStyle: PropTypes.object, activeDotStyle: PropTypes.object,
autoFocus: PropTypes.bool, autoFocus: PropTypes.bool,
onFocus: PropTypes.func, }
onBlur: PropTypes.func, return {
}; props: initDefaultProps(propTypes, {
static defaultProps = {
...Component.defaultProps, ...Component.defaultProps,
prefixCls: 'rc-slider', prefixCls: 'rc-slider',
className: '',
min: 0, min: 0,
max: 100, max: 100,
step: 1, step: 1,
@ -55,9 +45,6 @@ export default function createSlider (Component) {
delete restProps.dragging delete restProps.dragging
return <Handle {...restProps} key={index} /> return <Handle {...restProps} key={index} />
}, },
onBeforeChange: noop,
onChange: noop,
onAfterChange: noop,
included: true, included: true,
disabled: false, disabled: false,
dots: false, dots: false,
@ -67,13 +54,10 @@ export default function createSlider (Component) {
railStyle: {}, railStyle: {},
dotStyle: {}, dotStyle: {},
activeDotStyle: {}, activeDotStyle: {},
}; }),
data () {
constructor (props) {
super(props)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const { step, max, min } = props const { step, max, min } = this
warning( warning(
step && Math.floor(step) === step ? (max - min) % step === 0 : true, step && Math.floor(step) === step ? (max - min) % step === 0 : true,
'Slider[max] - Slider[min] (%s) should be a multiple of Slider[step] (%s)', 'Slider[max] - Slider[min] (%s) should be a multiple of Slider[step] (%s)',
@ -82,22 +66,24 @@ export default function createSlider (Component) {
) )
} }
this.handlesRefs = {} this.handlesRefs = {}
} return {}
},
componentWillUnmount () { beforeDestroy () {
if (super.componentWillUnmount) super.componentWillUnmount() this.$nextTick(() => {
// if (super.componentWillUnmount) super.componentWillUnmount()
this.removeDocumentEvents() this.removeDocumentEvents()
} })
},
componentDidMount () { mounted () {
this.$nextTick(() => {
// Snapshot testing cannot handle refs, so be sure to null-check this. // Snapshot testing cannot handle refs, so be sure to null-check this.
this.document = this.sliderRef && this.sliderRef.ownerDocument this.document = this.$refs.sliderRef && this.$refs.sliderRef.ownerDocument
} })
},
onMouseDown = (e) => { methods: {
onMouseDown (e) {
if (e.button !== 0) { return } if (e.button !== 0) { return }
const isVertical = this.vertical
const isVertical = this.props.vertical
let position = utils.getMousePosition(isVertical, e) let position = utils.getMousePosition(isVertical, e)
if (!utils.isEventFromHandle(e, this.handlesRefs)) { if (!utils.isEventFromHandle(e, this.handlesRefs)) {
this.dragOffset = 0 this.dragOffset = 0
@ -109,12 +95,11 @@ export default function createSlider (Component) {
this.removeDocumentEvents() this.removeDocumentEvents()
this.onStart(position) this.onStart(position)
this.addDocumentMouseEvents() this.addDocumentMouseEvents()
} },
onTouchStart (e) {
onTouchStart = (e) => {
if (utils.isNotTouchEvent(e)) return if (utils.isNotTouchEvent(e)) return
const isVertical = this.props.vertical const isVertical = this.vertical
let position = utils.getTouchPosition(isVertical, e) let position = utils.getTouchPosition(isVertical, e)
if (!utils.isEventFromHandle(e, this.handlesRefs)) { if (!utils.isEventFromHandle(e, this.handlesRefs)) {
this.dragOffset = 0 this.dragOffset = 0
@ -126,40 +111,30 @@ export default function createSlider (Component) {
this.onStart(position) this.onStart(position)
this.addDocumentTouchEvents() this.addDocumentTouchEvents()
utils.pauseEvent(e) utils.pauseEvent(e)
} },
onFocus (e) {
onFocus = (e) => { const { vertical } = this
const { onFocus, vertical } = this.props
if (utils.isEventFromHandle(e, this.handlesRefs)) { if (utils.isEventFromHandle(e, this.handlesRefs)) {
const handlePosition = utils.getHandleCenterPosition(vertical, e.target) const handlePosition = utils.getHandleCenterPosition(vertical, e.target)
this.dragOffset = 0 this.dragOffset = 0
this.onStart(handlePosition) this.onStart(handlePosition)
utils.pauseEvent(e) utils.pauseEvent(e)
if (onFocus) { this.$emit('focus', e)
onFocus(e)
} }
} },
} onBlur (e) {
onBlur = (e) => {
const { onBlur } = this.props
this.onEnd(e) this.onEnd(e)
if (onBlur) { this.$emit('blur', e)
onBlur(e) },
}
};
addDocumentTouchEvents () { addDocumentTouchEvents () {
// just work for Chrome iOS Safari and Android Browser // just work for Chrome iOS Safari and Android Browser
this.onTouchMoveListener = addEventListener(this.document, 'touchmove', this.onTouchMove) this.onTouchMoveListener = addEventListener(this.document, 'touchmove', this.onTouchMove)
this.onTouchUpListener = addEventListener(this.document, 'touchend', this.onEnd) this.onTouchUpListener = addEventListener(this.document, 'touchend', this.onEnd)
} },
addDocumentMouseEvents () { addDocumentMouseEvents () {
this.onMouseMoveListener = addEventListener(this.document, 'mousemove', this.onMouseMove) this.onMouseMoveListener = addEventListener(this.document, 'mousemove', this.onMouseMove)
this.onMouseUpListener = addEventListener(this.document, 'mouseup', this.onEnd) this.onMouseUpListener = addEventListener(this.document, 'mouseup', this.onEnd)
} },
removeDocumentEvents () { removeDocumentEvents () {
/* eslint-disable no-unused-expressions */ /* eslint-disable no-unused-expressions */
this.onTouchMoveListener && this.onTouchMoveListener.remove() this.onTouchMoveListener && this.onTouchMoveListener.remove()
@ -168,104 +143,86 @@ export default function createSlider (Component) {
this.onMouseMoveListener && this.onMouseMoveListener.remove() this.onMouseMoveListener && this.onMouseMoveListener.remove()
this.onMouseUpListener && this.onMouseUpListener.remove() this.onMouseUpListener && this.onMouseUpListener.remove()
/* eslint-enable no-unused-expressions */ /* eslint-enable no-unused-expressions */
} },
onMouseUp () {
onMouseUp = () => {
if (this.handlesRefs[this.prevMovedHandleIndex]) { if (this.handlesRefs[this.prevMovedHandleIndex]) {
this.handlesRefs[this.prevMovedHandleIndex].clickFocus() this.handlesRefs[this.prevMovedHandleIndex].clickFocus()
} }
} },
onMouseMove (e) {
onMouseMove = (e) => { if (!this.$refs.sliderRef) {
if (!this.sliderRef) {
this.onEnd() this.onEnd()
return; return
} }
const position = utils.getMousePosition(this.props.vertical, e) const position = utils.getMousePosition(this.vertical, e)
this.onMove(e, position - this.dragOffset) this.onMove(e, position - this.dragOffset)
} },
onTouchMove (e) {
onTouchMove = (e) => { if (utils.isNotTouchEvent(e) || !this.$refs.sliderRef) {
if (utils.isNotTouchEvent(e) || !this.sliderRef) {
this.onEnd() this.onEnd()
return; return
} }
const position = utils.getTouchPosition(this.props.vertical, e) const position = utils.getTouchPosition(this.vertical, e)
this.onMove(e, position - this.dragOffset) this.onMove(e, position - this.dragOffset)
} },
onKeyDown (e) {
onKeyDown = (e) => { if (this.$refs.sliderRef && utils.isEventFromHandle(e, this.handlesRefs)) {
if (this.sliderRef && utils.isEventFromHandle(e, this.handlesRefs)) {
this.onKeyboard(e) this.onKeyboard(e)
} }
} },
focus () { focus () {
if (!this.props.disabled) { if (!this.disabled) {
this.handlesRefs[0].focus() this.handlesRefs[0].focus()
} }
} },
blur () { blur () {
if (!this.props.disabled) { if (!this.disabled) {
this.handlesRefs[0].blur() this.handlesRefs[0].blur()
} }
} },
getSliderStart () { getSliderStart () {
const slider = this.sliderRef const slider = this.$refs.sliderRef
const rect = slider.getBoundingClientRect() const rect = slider.getBoundingClientRect()
return this.props.vertical ? rect.top : rect.left return this.vertical ? rect.top : rect.left
} },
getSliderLength () { getSliderLength () {
const slider = this.sliderRef const slider = this.$refs.sliderRef
if (!slider) { if (!slider) {
return 0 return 0
} }
const coords = slider.getBoundingClientRect() const coords = slider.getBoundingClientRect()
return this.props.vertical ? coords.height : coords.width return this.vertical ? coords.height : coords.width
} },
calcValue (offset) { calcValue (offset) {
const { vertical, min, max } = this.props const { vertical, min, max } = this
const ratio = Math.abs(Math.max(offset, 0) / this.getSliderLength()) const ratio = Math.abs(Math.max(offset, 0) / this.getSliderLength())
const value = vertical ? (1 - ratio) * (max - min) + min : ratio * (max - min) + min const value = vertical ? (1 - ratio) * (max - min) + min : ratio * (max - min) + min
return value return value
} },
calcValueByPos (position) { calcValueByPos (position) {
const pixelOffset = position - this.getSliderStart() const pixelOffset = position - this.getSliderStart()
const nextValue = this.trimAlignValue(this.calcValue(pixelOffset)) const nextValue = this.trimAlignValue(this.calcValue(pixelOffset))
return nextValue return nextValue
} },
calcOffset (value) { calcOffset (value) {
const { min, max } = this.props const { min, max } = this.props
const ratio = (value - min) / (max - min) const ratio = (value - min) / (max - min)
return ratio * 100 return ratio * 100
} },
saveSlider = (slider) => {
this.sliderRef = slider
}
saveHandle (index, handle) { saveHandle (index, handle) {
this.handlesRefs[index] = handle this.handlesRefs[index] = handle
} },
onClickMarkLabel (e, value) {
onClickMarkLabel = (e, value) => {
e.stopPropagation() e.stopPropagation()
this.onChange({ value }) this.$emit('change', { value })
} },
},
render () { render () {
const { const {
prefixCls, prefixCls,
className,
marks, marks,
dots, dots,
step, step,
@ -274,35 +231,46 @@ export default function createSlider (Component) {
vertical, vertical,
min, min,
max, max,
children,
maximumTrackStyle, maximumTrackStyle,
style,
railStyle, railStyle,
dotStyle, dotStyle,
activeDotStyle, activeDotStyle,
} = this.props } = this
const { tracks, handles } = super.render() const { tracks, handles } = super.render()
const sliderClassName = classNames(prefixCls, { const sliderClassName = classNames(prefixCls, {
[`${prefixCls}-with-marks`]: Object.keys(marks).length, [`${prefixCls}-with-marks`]: Object.keys(marks).length,
[`${prefixCls}-disabled`]: disabled, [`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-vertical`]: vertical, [`${prefixCls}-vertical`]: vertical,
[className]: className,
}) })
const markProps = {
props: {
vertical,
marks,
included,
lowerBound: this.getLowerBound(),
upperBound: this.getUpperBound(),
max,
min,
className: `${prefixCls}-mark`,
},
on: {
clickLabel: disabled ? noop : this.onClickMarkLabel,
},
}
return ( return (
<div <div
ref={this.saveSlider} ref='sliderRef'
className={sliderClassName} class={sliderClassName}
onTouchStart={disabled ? noop : this.onTouchStart} onTouchStart={disabled ? noop : this.onTouchStart}
onMouseDown={disabled ? noop : this.onMouseDown} onMouseDown={disabled ? noop : this.onMouseDown}
onMouseUp={disabled ? noop : this.onMouseUp} onMouseUp={disabled ? noop : this.onMouseUp}
onKeyDown={disabled ? noop : this.onKeyDown} onKeyDown={disabled ? noop : this.onKeyDown}
onFocus={disabled ? noop : this.onFocus} onFocus={disabled ? noop : this.onFocus}
onBlur={disabled ? noop : this.onBlur} onBlur={disabled ? noop : this.onBlur}
style={style}
> >
<div <div
className={`${prefixCls}-rail`} class={`${prefixCls}-rail`}
style={{ style={{
...maximumTrackStyle, ...maximumTrackStyle,
...railStyle, ...railStyle,
@ -325,19 +293,11 @@ export default function createSlider (Component) {
/> />
{handles} {handles}
<Marks <Marks
className={`${prefixCls}-mark`} {...markProps}
onClickLabel={disabled ? noop : this.onClickMarkLabel}
vertical={vertical}
marks={marks}
included={included}
lowerBound={this.getLowerBound()}
upperBound={this.getUpperBound()}
max={max}
min={min}
/> />
{children} {this.$slots.default}
</div> </div>
) )
} },
} }
} }

View File

@ -1,80 +1,91 @@
import React from 'react'; import PropTypes from '../../../_util/vue-types'
import PropTypes from 'prop-types'; import BaseMixin from '../../../_util/BaseMixin'
import Tooltip from 'rc-tooltip'; import Tooltip from '../../vc-tooltip'
import Handle from './Handle'; import Handle from './Handle'
export default function createSliderWithTooltip(Component) { export default function createSliderWithTooltip (Component) {
return class ComponentWrapper extends React.Component { return {
static propTypes = { mixins: [BaseMixin],
tipFormatter: PropTypes.func, props: {
handleStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]), tipFormatter: PropTypes.func.def((value) => { return value }),
tipProps: PropTypes.object, handleStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]).def([{}]),
}; tipProps: PropTypes.object.def({}),
static defaultProps = { },
tipFormatter(value) { return value; }, data () {
handleStyle: [{}], return {
tipProps: {}, visibles: {},
};
constructor(props) {
super(props);
this.state = { visibles: {} };
} }
handleTooltipVisibleChange = (index, visible) => { },
methods: {
handleTooltipVisibleChange (index, visible) {
this.setState((prevState) => { this.setState((prevState) => {
return { return {
visibles: { visibles: {
...prevState.visibles, ...prevState.visibles,
[index]: visible, [index]: visible,
}, },
};
});
} }
handleWithTooltip = ({ value, dragging, index, disabled, ...restProps }) => { })
},
handleWithTooltip ({ value, dragging, index, disabled, ...restProps }) {
const { const {
tipFormatter, tipFormatter,
tipProps, tipProps,
handleStyle, handleStyle,
} = this.props; } = this.$props
const { const {
prefixCls = 'rc-slider-tooltip', prefixCls = 'rc-slider-tooltip',
overlay = tipFormatter(value), overlay = tipFormatter(value),
placement = 'top', placement = 'top',
visible = visible || false, visible = visible || false,
...restTooltipProps, ...restTooltipProps } = tipProps
} = tipProps;
let handleStyleWithIndex; let handleStyleWithIndex
if (Array.isArray(handleStyle)) { if (Array.isArray(handleStyle)) {
handleStyleWithIndex = handleStyle[index] || handleStyle[0]; handleStyleWithIndex = handleStyle[index] || handleStyle[0]
} else { } else {
handleStyleWithIndex = handleStyle; handleStyleWithIndex = handleStyle
}
const tooltipProps = {
props: {
prefixCls,
overlay,
placement,
visible: (!disabled && (this.visibles[index] || dragging)) || visible,
...restTooltipProps,
},
key: index,
}
const handleProps = {
props: {
value,
...restProps,
},
on: {
mouseenter: () => this.handleTooltipVisibleChange(index, true),
mouseleave: () => this.handleTooltipVisibleChange(index, false),
},
style: {
...handleStyleWithIndex,
},
} }
return ( return (
<Tooltip <Tooltip
{...restTooltipProps} {...tooltipProps}
prefixCls={prefixCls}
overlay={overlay}
placement={placement}
visible={(!disabled && (this.state.visibles[index] || dragging)) || visible}
key={index}
> >
<Handle <Handle
{...restProps} {...handleProps}
style={{
...handleStyleWithIndex,
}}
value={value}
onMouseEnter={() => this.handleTooltipVisibleChange(index, true)}
onMouseLeave={() => this.handleTooltipVisibleChange(index, false)}
/> />
</Tooltip> </Tooltip>
); )
},
},
render () {
return <Component {...this.$props} handle={this.handleWithTooltip} />
},
} }
render() {
return <Component {...this.props} handle={this.handleWithTooltip} />;
}
};
} }

View File

@ -1,9 +1,8 @@
import { findDOMNode } from 'react-dom'
import keyCode from '../../_util/KeyCode' import keyCode from '../../_util/KeyCode'
export function isEventFromHandle (e, handles) { export function isEventFromHandle (e, handles) {
return Object.keys(handles) return Object.keys(handles)
.some(key => e.target === findDOMNode(handles[key])) .some(key => e.target === handles[key])
} }
export function isValueOutOfRange (value, { min, max }) { export function isValueOutOfRange (value, { min, max }) {