@orca-fe/transformer
Version:
Transformer Container
264 lines (262 loc) • 15.5 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); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _ahooks = require("ahooks");
var _hooks = require("@orca-fe/hooks");
var _tools = require("@orca-fe/tools");
var _TransformerLine = _interopRequireWildcard(require("./TransformerLine.style"));
var _utils = require("../TransformerBox/utils");
var _TransformerBoxContext = _interopRequireDefault(require("../TransformerBox/TransformerBoxContext"));
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["className", "children", "points", "onPointsChange", "defaultPoints", "disabled", "minDragDistance", "onDragBefore", "onChangeEnd", "onChangeStart", "onClickFixed", "checked", "controlledMode", "portal"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
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); }
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 _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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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 _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 _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 _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; }
var ef = function ef() {};
var eArr = [];
function getBounds(points) {
var xArr = points.map(function (p) {
return p.x;
});
var yArr = points.map(function (p) {
return p.y;
});
return {
left: Math.min.apply(Math, _toConsumableArray(xArr)),
top: Math.min.apply(Math, _toConsumableArray(yArr)),
width: Math.max.apply(Math, _toConsumableArray(xArr)) - Math.min.apply(Math, _toConsumableArray(xArr)),
height: Math.max.apply(Math, _toConsumableArray(yArr)) - Math.min.apply(Math, _toConsumableArray(yArr))
};
}
var TransformerLine = function TransformerLine(props) {
var _props$className = props.className,
className = _props$className === void 0 ? '' : _props$className,
children = props.children,
nouse1 = props.points,
nouse2 = props.onPointsChange,
defaultPoints = props.defaultPoints,
disabled = props.disabled,
_props$minDragDistanc = props.minDragDistance,
minDragDistance = _props$minDragDistanc === void 0 ? 4 : _props$minDragDistanc,
_props$onDragBefore = props.onDragBefore,
onDragBefore = _props$onDragBefore === void 0 ? ef : _props$onDragBefore,
_props$onChangeEnd = props.onChangeEnd,
_onChangeEnd = _props$onChangeEnd === void 0 ? ef : _props$onChangeEnd,
_props$onChangeStart = props.onChangeStart,
onChangeStart = _props$onChangeStart === void 0 ? ef : _props$onChangeStart,
_props$onClickFixed = props.onClickFixed,
onClickFixed = _props$onClickFixed === void 0 ? ef : _props$onClickFixed,
checked = props.checked,
_props$controlledMode = props.controlledMode,
controlledMode = _props$controlledMode === void 0 ? true : _props$controlledMode,
portal = props.portal,
otherProps = _objectWithoutProperties(props, _excluded);
var styles = (0, _TransformerLine.default)();
var _useContext = (0, _react.useContext)(_TransformerBoxContext.default),
getPointMapping = _useContext.getPointMapping;
var _useState = (0, _react.useState)({
distanceLock: false,
pointerDownIndex: -1,
// 鼠标按下时的Bounds信息,也用于表达鼠标按下状态
pointerDownPoints: false,
// 鼠标按下时的鼠标坐标
pointerDownPosition: {
x: 0,
y: 0
},
currentPoint: {
x: 0,
y: 0
},
lastClickTime: 0,
ctrlDown: false,
shiftDown: false
}),
_useState2 = _slicedToArray(_useState, 1),
_this = _useState2[0];
var _useControllableValue = (0, _ahooks.useControllableValue)(props, {
defaultValuePropName: 'defaultPoints',
valuePropName: 'points',
trigger: 'onPointsChange'
}),
_useControllableValue2 = _slicedToArray(_useControllableValue, 2),
_useControllableValue3 = _useControllableValue2[0],
_points = _useControllableValue3 === void 0 ? eArr : _useControllableValue3,
_setPoints = _useControllableValue2[1];
var _useState3 = (0, _react.useState)(null),
_useState4 = _slicedToArray(_useState3, 2),
tmpPoints = _useState4[0],
setTmpPoints = _useState4[1];
var points = tmpPoints || _points;
var setPoints = (0, _ahooks.useMemoizedFn)(function (param) {
if (controlledMode) {
_setPoints(param);
} else {
setTmpPoints(function (tmpBounds) {
var bounds = tmpBounds || _points;
var newPoints = typeof param === 'function' ? param(bounds) : param;
return newPoints;
});
}
});
var changeBounds = (0, _ahooks.useMemoizedFn)(function () {
var points = _this.pointerDownPoints;
if (!points) return;
var pointOffset = (0, _utils.getPointOffset)(_this.pointerDownPosition, _this.currentPoint);
if (!_this.distanceLock || Math.pow(minDragDistance, 2) < Math.pow(pointOffset.x, 2) + Math.pow(pointOffset.y, 2)) {
/* 解锁距离锁 */
_this.distanceLock = false;
if (_this.pointerDownIndex === -2) {
// 全量点移动
setPoints(points.map(function (point) {
return {
x: point.x + pointOffset.x,
y: point.y + pointOffset.y
};
}));
} else {
setPoints((0, _tools.changeArr)(points, _this.pointerDownIndex, {
x: points[_this.pointerDownIndex].x + pointOffset.x,
y: points[_this.pointerDownIndex].y + pointOffset.y
}));
}
}
});
var onChangeEnd = (0, _ahooks.useMemoizedFn)(function () {
if (!controlledMode && tmpPoints) {
_setPoints(tmpPoints);
}
setTmpPoints(null);
_onChangeEnd(tmpPoints || _points);
});
var rootRef = (0, _react.useRef)(null);
(0, _hooks.usePan)(function (_ref) {
var target = _ref.target,
start = _ref.start,
startPosition = _ref.startPosition,
ev = _ref.ev,
offset = _ref.offset,
finish = _ref.finish;
var currentPoint = getPointMapping((0, _utils.getPointByEvent)(ev));
if (start) {
_this.distanceLock = true;
if (target instanceof HTMLDivElement) {
var isPointHandle = target.classList.contains("".concat(_TransformerLine.prefix, "-point-handle"));
var isMoveHandle = target.classList.contains("".concat(_TransformerLine.prefix, "-move-handle"));
if (!isPointHandle && !isMoveHandle) {
return false;
}
var draggable = onDragBefore(ev);
if (draggable === false) {
return false;
}
/* 加距离锁 */
_this.pointerDownPosition = currentPoint;
_this.currentPoint = _this.pointerDownPosition;
_this.pointerDownPoints = points;
if (isPointHandle) {
var _Number, _target$attributes$ge;
_this.pointerDownIndex = (_Number = Number((_target$attributes$ge = target.attributes.getNamedItem('data-index')) === null || _target$attributes$ge === void 0 ? void 0 : _target$attributes$ge.value)) !== null && _Number !== void 0 ? _Number : -1;
} else {
_this.pointerDownIndex = -2;
}
onChangeStart(ev);
} else {
return false;
}
}
if (finish) {
if (_this.pointerDownPoints) {
_this.pointerDownPoints = false;
onChangeEnd();
}
return true;
}
if (_this.pointerDownPoints && _this.pointerDownIndex !== -1) {
_this.currentPoint = currentPoint;
changeBounds();
}
return true;
}, rootRef);
(0, _ahooks.useEventListener)('dragstart', function (event) {
event.preventDefault();
}, {
target: rootRef
});
(0, _ahooks.useEventListener)('mouseup', function (event) {
var diff = Date.now() - _this.lastClickTime;
_this.lastClickTime = Date.now();
if (_this.distanceLock && event.button === 0 && diff < 200) {
onClickFixed(event);
}
}, {
target: rootRef
});
var bounds = (0, _react.useMemo)(function () {
return getBounds(points);
}, [points]);
return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", _objectSpread(_objectSpread({
ref: rootRef,
className: (0, _classnames.default)(styles.root, _defineProperty(_defineProperty({}, styles.statusChecked, checked && !disabled), styles.statusDisabled, disabled), className)
}, otherProps), {}, {
children: [points.slice(0, points.length - 1).map(function (point, index) {
// 计算两点的角度
var nextPoint = points[index + 1];
var angle = Math.atan2(nextPoint.y - point.y, nextPoint.x - point.x) * 180 / Math.PI;
// 计算两点的距离
var distance = Math.sqrt(Math.pow(nextPoint.x - point.x, 2) + Math.pow(nextPoint.y - point.y, 2));
return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
className: (0, _classnames.default)(styles.moveHandle),
"data-index": index,
style: {
left: "calc(var(--transformer-box-scale) * ".concat(Math.round(point.x), "px)"),
top: "calc(var(--transformer-box-scale) * ".concat(Math.round(point.y), "px)"),
width: "calc(var(--transformer-box-scale) * ".concat(Math.round(distance), "px)"),
transformOrigin: 'left center',
transform: "translateY(-50%) rotate(".concat(angle, "deg)")
}
}, index);
}), points.map(function (point, index) {
return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
className: (0, _classnames.default)(styles.pointHandle),
"data-index": index,
style: {
left: "calc(var(--transformer-box-scale) * ".concat(Math.round(point.x), "px)"),
top: "calc(var(--transformer-box-scale) * ".concat(Math.round(point.y), "px)")
}
}, index);
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
className: (0, _classnames.default)(styles.content),
style: {
left: "calc(var(--transformer-box-scale) * ".concat(Math.round(bounds.left), "px)"),
top: "calc(var(--transformer-box-scale) * ".concat(Math.round(bounds.top), "px)"),
width: "calc(var(--transformer-box-scale) * ".concat(Math.round(bounds.width), "px)"),
height: "calc(var(--transformer-box-scale) * ".concat(Math.round(bounds.height), "px)")
},
children: children
})]
}));
};
var _default = exports.default = TransformerLine;