UNPKG

@orca-fe/transformer

Version:
365 lines (363 loc) 15.9 kB
var _excluded = ["className", "children", "bounds", "onBoundsChange", "defaultBounds", "disabled", "minDragDistance", "onDragBefore", "onChangeEnd", "onChangeStart", "onClickFixed", "checked", "style", "controlledMode", "portal", "limitBounds", "rotateEnabled"]; 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; } import React, { useContext, useRef, useState } from 'react'; import cn from 'classnames'; import { useControllableValue, useDebounceFn, useEventListener, useMemoizedFn } from 'ahooks'; import { usePan } from '@orca-fe/hooks'; import ReactDOM from 'react-dom'; import { roundBy } from '@orca-fe/tools'; import { calcBoundsChange, calcLimitBounds, getPointByEvent, getPointOffset, getResizeMode } from "./utils"; import TransformerBoxContext from "./TransformerBoxContext"; import useStyles from "./TransformerBox.style"; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; var ef = () => {}; var roundBy45 = roundBy(45); function mod(n, m) { return (n % m + m) % m; } var 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 = useStyles(); var cursors = [styles.cursor0, styles.cursor1, styles.cursor2, styles.cursor3]; var _useContext = useContext(TransformerBoxContext), getPointMapping = _useContext.getPointMapping; var _useState = 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 = useControllableValue(props, { defaultValuePropName: 'defaultBounds', valuePropName: 'bounds', trigger: 'onBoundsChange' }), _useControllableValue2 = _slicedToArray(_useControllableValue, 2), _bounds = _useControllableValue2[0], _setBounds = _useControllableValue2[1]; var _useState3 = 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 = useMemoizedFn(param => { if (controlledMode) { _setBounds(bounds => { var newBounds = typeof param === 'function' ? param(bounds) : param; return _objectSpread(_objectSpread({}, bounds), newBounds); }); } else { setTmpBounds(tmpBounds => { var bounds = tmpBounds || _bounds; var newBounds = typeof param === 'function' ? param(bounds) : param; return _objectSpread(_objectSpread({}, bounds), newBounds); }); } }); var changeBounds = useMemoizedFn(() => { if (!(_this.pointerDownBounds && _this.resizeType)) return; var pointOffset = 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 = 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({}, calcLimitBounds(_objectSpread(_objectSpread({}, _bounds), changedState), limitBounds))); } }); var onChangeEnd = useMemoizedFn(() => { if (!controlledMode && tmpBounds) { _setBounds(tmpBounds); } setTmpBounds(null); _onChangeEnd(tmpBounds || _bounds); }); useEventListener('keydown', e => { if (!_this.ctrlDown && (e.key === 'Control' || e.key === 'Meta')) { _this.ctrlDown = true; changeBounds(); } if (!_this.shiftDown && e.key === 'Shift') { _this.shiftDown = true; changeBounds(); } }); useEventListener('keyup', e => { if (e.key === 'Control' || e.key === 'Meta') { _this.ctrlDown = false; changeBounds(); } if (e.key === 'Shift') { _this.shiftDown = false; changeBounds(); } }); var rootRef = useRef(null); usePan(({ target, start, startPosition, ev, offset, finish }) => { // 兼容 touchEvent var currentPoint = getPointMapping(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 = 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); useEventListener('dragstart', event => { event.preventDefault(); }, { target: rootRef }); useEventListener('mouseup', 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 = useDebounceFn(() => { onChangeEnd(); }, { wait: 1000 }); var triggerKeyboardChangeStart = useMemoizedFn(e => { onChangeStart(e, 'keyboard'); triggerKeyboardChangeEnd.run(); }); useEventListener('keydown', 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) * ${Math.round(bounds.left)}px)`, top: `calc(var(--transformer-box-scale) * ${Math.round(bounds.top)}px)`, width: `calc(var(--transformer-box-scale) * ${Math.round(bounds.width)}px)`, height: `calc(var(--transformer-box-scale) * ${Math.round(bounds.height)}px)`, transform: `rotate(${bounds.rotate || 0}deg)` }; var content = contentRoot ? ( /*#__PURE__*/ReactDOM.createPortal( /*#__PURE__*/_jsx("div", { className: cn(styles.content, { [styles.statusChecked]: checked && !disabled, [styles.statusDisabled]: disabled }), style: positionStyle, children: children }), contentRoot)) : /*#__PURE__*/_jsx("div", { className: styles.content, children: children }); return /*#__PURE__*/_jsxs("div", _objectSpread(_objectSpread({ ref: rootRef, className: cn(styles.root, { [styles.statusChecked]: checked && !disabled, [styles.statusDisabled]: disabled }, className), style: _objectSpread(_objectSpread({}, style), positionStyle) }, otherProps), {}, { children: [content, /*#__PURE__*/_jsx("div", { className: cn(styles.scaleHandle, styles.scaleHandleTop, cursors[mod(0 + cursorDirection, 4)]) }), /*#__PURE__*/_jsx("div", { className: cn(styles.scaleHandle, styles.scaleHandleBottom, cursors[mod(0 + cursorDirection, 4)]) }), /*#__PURE__*/_jsx("div", { className: cn(styles.scaleHandle, styles.scaleHandleRight, cursors[mod(2 + cursorDirection, 4)]) }), /*#__PURE__*/_jsx("div", { className: cn(styles.scaleHandle, styles.scaleHandleLeft, cursors[mod(2 + cursorDirection, 4)]) }), /*#__PURE__*/_jsx("div", { className: cn(styles.scaleHandle, styles.scaleHandleTopLeft, cursors[mod(3 + cursorDirection, 4)]) }), /*#__PURE__*/_jsx("div", { className: cn(styles.scaleHandle, styles.scaleHandleTopRight, cursors[mod(1 + cursorDirection, 4)]) }), /*#__PURE__*/_jsx("div", { className: cn(styles.scaleHandle, styles.scaleHandleBottomLeft, cursors[mod(1 + cursorDirection, 4)]) }), /*#__PURE__*/_jsx("div", { className: cn(styles.scaleHandle, styles.scaleHandleBottomRight, cursors[mod(3 + cursorDirection, 4)]) }), rotateEnabled && /*#__PURE__*/_jsx("div", { className: cn(styles.scaleHandle, styles.rotateHandle) })] })); }; export default TransformerBox;