@legendapp/motion
Version:
83 lines (76 loc) • 2.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useTransformOrigin = void 0;
var _tools = require("@legendapp/tools");
var _react = require("@legendapp/tools/react");
var _react2 = require("react");
/* eslint-disable react-hooks/rules-of-hooks */
function computeOrigin(val, size) {
const isStr = (0, _tools.isString)(val);
const isPerc = isStr && val.endsWith('%');
// Chop off a % or px
let num = isStr ? +val.replace(/%|px/, '') : val;
// Divide by 100 for percent or by view size if pixels
const perc = isPerc ? +num / 100 : +num / size;
// Offset by half of the size
if (!isNaN(perc)) {
num = (perc - 0.5) * size;
} else {
// Fallback to no origin
num = 0;
}
return num;
}
const useTransformOrigin = exports.useTransformOrigin = function useTransformOrigin(transformOrigin, transform, onLayoutProp) {
let onLayout = onLayoutProp;
let needsLayoutX = false;
let needsLayoutY = false;
// Compute whether x and y need layout based on input
if (transformOrigin) {
let {
x,
y
} = transformOrigin;
needsLayoutX = x !== undefined && x !== '50%';
needsLayoutY = y !== undefined && y !== '50%';
}
// Compute whether we ever needed layout so we don't remove a hook if the origin is removed
const everDidLayout = (0, _react.useEverHadValue)(!!transformOrigin, true);
if (everDidLayout) {
const [size, setSize] = (0, _react2.useState)({
width: 0,
height: 0
});
onLayout = (0, _react2.useCallback)(e => {
setSize(e.nativeEvent.layout);
onLayoutProp === null || onLayoutProp === void 0 || onLayoutProp(e);
}, [onLayoutProp]);
if (transformOrigin && transform) {
let {
x,
y
} = transformOrigin;
// Compute x and y origins
x = needsLayoutX ? computeOrigin(x, size.width) : 0;
y = needsLayoutY ? computeOrigin(y, size.height) : 0;
// First move the center of the view to the origin
transform.splice(0, 0, {
translateY: y
});
transform.splice(0, 0, {
translateX: x
});
// Restore it back the the original position after transforming
transform.push({
translateX: -x
});
transform.push({
translateY: -y
});
}
}
return onLayout;
};
//# sourceMappingURL=useTransformOrigin.js.map