UNPKG

@orca-fe/transformer

Version:
367 lines (364 loc) 18.2 kB
"use strict"; 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 _reactDom = _interopRequireDefault(require("react-dom")); var _tools = require("@orca-fe/tools"); var _utils = require("./utils"); var _TransformerBoxContext = _interopRequireDefault(require("./TransformerBoxContext")); var _TransformerBox = _interopRequireDefault(require("./TransformerBox.style")); var _jsxRuntime = require("react/jsx-runtime"); var _excluded = ["className", "children", "bounds", "onBoundsChange", "defaultBounds", "disabled", "minDragDistance", "onDragBefore", "onChangeEnd", "onChangeStart", "onClickFixed", "checked", "style", "controlledMode", "portal", "limitBounds", "rotateEnabled"]; 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 _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 _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; } var ef = function ef() {}; var roundBy45 = (0, _tools.roundBy)(45); function mod(n, m) { return (n % m + m) % m; } var TransformerBox = function TransformerBox(props) { var _props$className = props.className, className = _props$className === void 0 ? '' : _props$className, children = props.children, nouse = props.bounds, onBoundsChange = props.onBoundsChange, defaultBounds = props.defaultBounds, 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, style = props.style, controlledMode = props.controlledMode, portal = props.portal, limitBounds = props.limitBounds, rotateEnabled = props.rotateEnabled, otherProps = _objectWithoutProperties(props, _excluded); var styles = (0, _TransformerBox.default)(); var cursors = [styles.cursor0, styles.cursor1, styles.cursor2, styles.cursor3]; var _useContext = (0, _react.useContext)(_TransformerBoxContext.default), getPointMapping = _useContext.getPointMapping; var _useState = (0, _react.useState)({ distanceLock: false, // 鼠标按下时的Bounds信息,也用于表达鼠标按下状态 pointerDownBounds: false, // 鼠标按下时的鼠标坐标 pointerDownPosition: { x: 0, y: 0 }, currentPoint: { x: 0, y: 0 }, resizeType: undefined, lastClickTime: 0, ctrlDown: false, shiftDown: false }), _useState2 = _slicedToArray(_useState, 1), _this = _useState2[0]; var _useControllableValue = (0, _ahooks.useControllableValue)(props, { defaultValuePropName: 'defaultBounds', valuePropName: 'bounds', trigger: 'onBoundsChange' }), _useControllableValue2 = _slicedToArray(_useControllableValue, 2), _bounds = _useControllableValue2[0], _setBounds = _useControllableValue2[1]; var _useState3 = (0, _react.useState)(null), _useState4 = _slicedToArray(_useState3, 2), tmpBounds = _useState4[0], setTmpBounds = _useState4[1]; var bounds = tmpBounds || _bounds; var _left = bounds.left, _top = bounds.top, _width = bounds.width, _height = bounds.height; var cursorDirection = roundBy45(bounds.rotate || 0) / 45 % 4; var setBounds = (0, _ahooks.useMemoizedFn)(function (param) { if (controlledMode) { _setBounds(function (bounds) { var newBounds = typeof param === 'function' ? param(bounds) : param; return _objectSpread(_objectSpread({}, bounds), newBounds); }); } else { setTmpBounds(function (tmpBounds) { var bounds = tmpBounds || _bounds; var newBounds = typeof param === 'function' ? param(bounds) : param; return _objectSpread(_objectSpread({}, bounds), newBounds); }); } }); var changeBounds = (0, _ahooks.useMemoizedFn)(function () { if (!(_this.pointerDownBounds && _this.resizeType)) 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; var changedState = (0, _utils.calcBoundsChange)(_this.pointerDownBounds, { x: Math.round(pointOffset.x / 1), y: Math.round(pointOffset.y / 1) }, { resizeType: _this.resizeType, eqRatio: _this.shiftDown, symmetrical: _this.ctrlDown }); setBounds(_objectSpread({}, (0, _utils.calcLimitBounds)(_objectSpread(_objectSpread({}, _bounds), changedState), limitBounds))); } }); var onChangeEnd = (0, _ahooks.useMemoizedFn)(function () { if (!controlledMode && tmpBounds) { _setBounds(tmpBounds); } setTmpBounds(null); _onChangeEnd(tmpBounds || _bounds); }); (0, _ahooks.useEventListener)('keydown', function (e) { if (!_this.ctrlDown && (e.key === 'Control' || e.key === 'Meta')) { _this.ctrlDown = true; changeBounds(); } if (!_this.shiftDown && e.key === 'Shift') { _this.shiftDown = true; changeBounds(); } }); (0, _ahooks.useEventListener)('keyup', function (e) { if (e.key === 'Control' || e.key === 'Meta') { _this.ctrlDown = false; changeBounds(); } if (e.key === 'Shift') { _this.shiftDown = false; changeBounds(); } }); 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; // 兼容 touchEvent var currentPoint = getPointMapping((0, _utils.getPointByEvent)(ev)); if (start) { _this.distanceLock = true; if (target instanceof HTMLDivElement) { var draggable = onDragBefore(ev); if (draggable === false) { return false; } /* 加距离锁 */ _this.pointerDownPosition = currentPoint; _this.currentPoint = _this.pointerDownPosition; _this.pointerDownBounds = _objectSpread({}, bounds); _this.resizeType = (0, _utils.getResizeMode)(Array.from(target.classList)); onChangeStart(ev, _this.resizeType); } else { return false; } } if (finish) { if (_this.pointerDownBounds) { _this.pointerDownBounds = false; _this.resizeType = undefined; onChangeEnd(); } return true; } if (_this.pointerDownBounds && _this.resizeType) { _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 triggerKeyboardChangeEnd = (0, _ahooks.useDebounceFn)(function () { onChangeEnd(); }, { wait: 1000 }); var triggerKeyboardChangeStart = (0, _ahooks.useMemoizedFn)(function (e) { onChangeStart(e, 'keyboard'); triggerKeyboardChangeEnd.run(); }); (0, _ahooks.useEventListener)('keydown', function (e) { if (_this.pointerDownBounds) return; if (checked && !disabled) { var ctrlKey = e.ctrlKey, altKey = e.altKey, metaKey = e.metaKey, shiftKey = e.shiftKey; var isCtrlOnly = !altKey && !shiftKey && (ctrlKey || metaKey); var isShiftOnly = shiftKey && !ctrlKey && !metaKey && !altKey; switch (e.key) { case 'ArrowUp': triggerKeyboardChangeStart(e); if (isCtrlOnly) { // 扩大 setBounds({ top: _top - 1, height: _height + 1 }); } else if (isShiftOnly) { // 缩小 setBounds({ height: _height - 1 }); } else { // 上移 setBounds({ top: _top - 1 }); } break; case 'ArrowDown': triggerKeyboardChangeStart(e); if (isCtrlOnly) { // 扩大 setBounds({ height: _height + 1 }); } else if (isShiftOnly) { // 缩小 setBounds({ top: _top + 1, height: _height - 1 }); } else { // 下移 setBounds({ top: _top + 1 }); } break; case 'ArrowLeft': triggerKeyboardChangeStart(e); if (isCtrlOnly) { // 扩大 setBounds({ left: _left - 1, width: _width + 1 }); } else if (isShiftOnly) { // 缩小 setBounds({ width: _width - 1 }); } else { // 左移 setBounds({ left: _left - 1 }); } break; case 'ArrowRight': triggerKeyboardChangeStart(e); if (isCtrlOnly) { // 扩大 setBounds({ width: _width + 1 }); } else if (isShiftOnly) { // 缩小 setBounds({ left: _left + 1, width: _width - 1 }); } else { // 右移 setBounds({ left: _left + 1 }); } break; } } }); // 获取内容挂载的位置 var contentRoot = portal ? portal() : null; var positionStyle = { 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)"), transform: "rotate(".concat(bounds.rotate || 0, "deg)") }; var content = contentRoot ? ( /*#__PURE__*/_reactDom.default.createPortal( /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.content, _defineProperty(_defineProperty({}, styles.statusChecked, checked && !disabled), styles.statusDisabled, disabled)), style: positionStyle, children: children }), contentRoot)) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: styles.content, children: children }); 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), style: _objectSpread(_objectSpread({}, style), positionStyle) }, otherProps), {}, { children: [content, /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.scaleHandle, styles.scaleHandleTop, cursors[mod(0 + cursorDirection, 4)]) }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.scaleHandle, styles.scaleHandleBottom, cursors[mod(0 + cursorDirection, 4)]) }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.scaleHandle, styles.scaleHandleRight, cursors[mod(2 + cursorDirection, 4)]) }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.scaleHandle, styles.scaleHandleLeft, cursors[mod(2 + cursorDirection, 4)]) }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.scaleHandle, styles.scaleHandleTopLeft, cursors[mod(3 + cursorDirection, 4)]) }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.scaleHandle, styles.scaleHandleTopRight, cursors[mod(1 + cursorDirection, 4)]) }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.scaleHandle, styles.scaleHandleBottomLeft, cursors[mod(1 + cursorDirection, 4)]) }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.scaleHandle, styles.scaleHandleBottomRight, cursors[mod(3 + cursorDirection, 4)]) }), rotateEnabled && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: (0, _classnames.default)(styles.scaleHandle, styles.rotateHandle) })] })); }; var _default = exports.default = TransformerBox;