@alifd/meet-react
Version:
Fusion Mobile React UI System Component
275 lines • 12 kB
JavaScript
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { __rest } from "tslib";
import classNames from 'classnames';
import React, { createElement, forwardRef, useEffect, useMemo, useState } from "react";
import { isFunction, isUndef } from '../utils';
import { useGuid } from '../utils/hooks';
import View from '../view';
import Thumb from './thumb';
import Track from './track';
import { getClosestThumbIndex, getNodeRect, getPrecision, getTouchPosition, noop, pauseEvent } from './utils';
var Mode;
(function (Mode) {
Mode["Single"] = "single";
Mode["Double"] = "double";
})(Mode || (Mode = {}));
function getInitialRatio(max, min, value, defaultValue) {
var ratio = min;
if (!isUndef(value)) {
ratio = value;
} else if (!isUndef(defaultValue)) {
ratio = defaultValue;
}
if (!Array.isArray(ratio)) {
ratio = [ratio];
}
return ratio.map(function (item) {
if (item > max) {
return max;
}
if (item < min) {
return min;
}
return item;
}).reduce(function (prev, curr, index) {
return Object.assign(Object.assign({}, prev), _defineProperty({}, index, (curr - min) / (max - min)));
}, {});
}
var Range = function Range(props, ref) {
var _props$size = props.size,
size = _props$size === void 0 ? 'medium' : _props$size,
_props$min = props.min,
min = _props$min === void 0 ? 0 : _props$min,
_props$prefix = props.prefix,
prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
_props$max = props.max,
max = _props$max === void 0 ? 100 : _props$max,
_props$mode = props.mode,
mode = _props$mode === void 0 ? 'single' : _props$mode,
value = props.value,
defaultValue = props.defaultValue,
_props$step = props.step,
step = _props$step === void 0 ? 1 : _props$step,
_props$disabled = props.disabled,
disabled = _props$disabled === void 0 ? false : _props$disabled,
_props$marks = props.marks,
marks = _props$marks === void 0 ? false : _props$marks,
_props$marksPosition = props.marksPosition,
marksPosition = _props$marksPosition === void 0 ? 'below' : _props$marksPosition,
_props$previewed = props.previewed,
previewed = _props$previewed === void 0 ? false : _props$previewed,
className = props.className,
tooltipVisible = props.tooltipVisible,
_props$onChange = props.onChange,
onChange = _props$onChange === void 0 ? noop : _props$onChange,
_props$onProcess = props.onProcess,
onProcess = _props$onProcess === void 0 ? noop : _props$onProcess,
others = __rest(props, ["size", "min", "prefix", "max", "mode", "value", "defaultValue", "step", "disabled", "marks", "marksPosition", "previewed", "className", "tooltipVisible", "onChange", "onProcess"]);
var _useState = useState(getInitialRatio(max, min, value, defaultValue)),
_useState2 = _slicedToArray(_useState, 2),
ratio = _useState2[0],
setRatio = _useState2[1];
var _useState3 = useState(null),
_useState4 = _slicedToArray(_useState3, 2),
active = _useState4[0],
setActive = _useState4[1];
var _useState5 = useState(false),
_useState6 = _slicedToArray(_useState5, 2),
dragging = _useState6[0],
setDragging = _useState6[1];
var _useState7 = useState(0),
_useState8 = _slicedToArray(_useState7, 2),
rangeWidth = _useState8[0],
setRangeWidth = _useState8[1];
var id = useGuid('range-');
var thumbId1 = useGuid('range-thumb-');
var thumbId2 = useGuid('range-thumb-');
var isControlled = ('value' in props);
var handles = mode === Mode.Double ? {
0: thumbId1,
1: thumbId2
} : {
0: thumbId1
};
function getRatioValue(val) {
return parseFloat((val * (max - min) + min).toFixed(getPrecision(step)));
}
var points = useMemo(function () {
var data = {};
var dealPoints = function dealPoints() {
if (step) {
for (var point = min; point <= max; point += step) {
var current = Number(point.toFixed(1));
data[current] = current;
}
}
};
if (marks instanceof Array) {
marks.reduce(function (prev, current) {
prev[current] = current;
return prev;
}, data);
} else if (marks instanceof Object) {
data = Object.assign({}, marks);
}
dealPoints();
return Object.keys(data).map(parseFloat).sort(function (a, b) {
return a - b;
});
}, [marks, step, min, max]);
function getClosestStep(val) {
var diffs = points.map(function (point) {
return Math.abs(point - val - min);
});
return points[diffs.indexOf(Math.min.apply(Math, _toConsumableArray(diffs)))];
}
function getValue(newRatio) {
var result = Object.keys(newRatio).map(function (key) {
return getRatioValue(newRatio[key]);
}).sort(function (a, b) {
return a - b;
});
if (result.length === 1) {
return result[0];
}
return result;
}
function updatePositionByTouch(e, activeIndex) {
var position = getTouchPosition(e);
return getNodeRect(id).then(function (rect) {
var diff = position - rect.left;
var offset = Math.max(Math.min(diff, rect.width), 0);
var closestValue = getClosestStep(offset / rect.width * (max - min));
var newRatio = Object.assign({}, ratio);
if (!isUndef(activeIndex)) {
newRatio[activeIndex] = (closestValue - min) / (max - min);
}
if (!isControlled) {
setRatio(newRatio);
}
return newRatio;
});
}
function handleTouchStart(e) {
var _a;
if (disabled || previewed || dragging) {
return;
}
(_a = e.persist) === null || _a === void 0 ? void 0 : _a.call(e);
var position = getTouchPosition(e);
getClosestThumbIndex(position, handles).then(function (activeIndex) {
setDragging(true);
setActive(activeIndex);
updatePositionByTouch(e, activeIndex).then(function (newRatio) {
if (isFunction(onChange)) {
onChange(getValue(newRatio), e);
}
});
pauseEvent(e);
});
}
function handleTouchMove(e) {
var _a;
if (!dragging) {
return;
}
(_a = e.persist) === null || _a === void 0 ? void 0 : _a.call(e);
updatePositionByTouch(e, active).then(function (newRatio) {
if (isFunction(onProcess)) {
onProcess(getValue(newRatio), e);
}
if (isFunction(onChange)) {
onChange(getValue(newRatio), e);
}
});
pauseEvent(e);
}
function handleTouchEnd(e) {
var _a;
if (!dragging) {
return;
}
(_a = e.persist) === null || _a === void 0 ? void 0 : _a.call(e);
setDragging(false);
setActive(null);
updatePositionByTouch(e, active).then(function (newRatio) {
if (isFunction(onChange)) {
onChange(getValue(newRatio), e);
}
});
pauseEvent(e);
}
function adjustRatio() {
var data = {};
Object.keys(ratio).forEach(function (key) {
return data[key] = (getClosestStep(ratio[key] * (max - min)) - min) / (max - min);
});
setRatio(data);
}
useEffect(function () {
adjustRatio();
setTimeout(function () {
getNodeRect(id).then(function (rect) {
setRangeWidth(rect.width);
});
}, 100);
}, []);
useEffect(function () {
if (isControlled) {
setRatio(getInitialRatio(max, min, value, defaultValue));
}
}, [value, defaultValue, max, min]);
var ratioValue = Object.values(ratio).sort(function (a, b) {
return a - b;
});
return /*#__PURE__*/React.createElement(View, _extends({}, others, {
id: id,
withoutTouch: false,
className: classNames("".concat(prefix, "range"), className),
onMouseDown: handleTouchStart,
onMouseMove: handleTouchMove,
onMouseUp: handleTouchEnd,
onTouchStart: handleTouchStart,
onTouchMove: handleTouchMove,
onTouchEnd: handleTouchEnd
}), /*#__PURE__*/React.createElement(Track, {
prefix: prefix,
size: size,
min: min,
max: max,
marks: marks,
marksPosition: marksPosition,
disabled: disabled,
ratio: ratioValue,
rangeWidth: rangeWidth
}), Object.keys(handles).map(function (key) {
var isActive = "".concat(active) === "".concat(key);
return /*#__PURE__*/React.createElement(Thumb, {
prefix: prefix,
key: key,
size: size,
id: handles[key],
disabled: disabled,
isActive: isActive,
tooltipVisible: tooltipVisible,
offset: ratio[key] * rangeWidth,
value: getRatioValue(ratio[key])
});
}));
};
Range.displayName = 'Range';
export default /*#__PURE__*/forwardRef(Range);