UNPKG

2.4 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.useTransformOrigin = void 0;
7var _tools = require("@legendapp/tools");
8var _react = require("@legendapp/tools/react");
9var _react2 = require("react");
10/* eslint-disable react-hooks/rules-of-hooks */
11
12function computeOrigin(val, size) {
13 const isStr = (0, _tools.isString)(val);
14 const isPerc = isStr && val.endsWith('%');
15 // Chop off a % or px
16 let num = isStr ? +val.replace(/%|px/, '') : val;
17 // Divide by 100 for percent or by view size if pixels
18 const perc = isPerc ? +num / 100 : +num / size;
19 // Offset by half of the size
20 if (!isNaN(perc)) {
21 num = (perc - 0.5) * size;
22 } else {
23 // Fallback to no origin
24 num = 0;
25 }
26 return num;
27}
28const useTransformOrigin = function useTransformOrigin(transformOrigin, transform, onLayoutProp) {
29 let onLayout = onLayoutProp;
30 let needsLayoutX = false;
31 let needsLayoutY = false;
32
33 // Compute whether x and y need layout based on input
34 if (transformOrigin) {
35 let {
36 x,
37 y
38 } = transformOrigin;
39 needsLayoutX = x !== undefined && x !== '50%';
40 needsLayoutY = y !== undefined && y !== '50%';
41 }
42
43 // Compute whether we ever needed layout so we don't remove a hook if the origin is removed
44 const everDidLayout = (0, _react.useEverHadValue)(!!transformOrigin, true);
45 if (everDidLayout) {
46 const [size, setSize] = (0, _react2.useState)({
47 width: 0,
48 height: 0
49 });
50 onLayout = (0, _react2.useCallback)(e => {
51 setSize(e.nativeEvent.layout);
52 onLayoutProp === null || onLayoutProp === void 0 ? void 0 : onLayoutProp(e);
53 }, [onLayoutProp]);
54 if (transformOrigin && transform) {
55 let {
56 x,
57 y
58 } = transformOrigin;
59
60 // Compute x and y origins
61 x = needsLayoutX ? computeOrigin(x, size.width) : 0;
62 y = needsLayoutY ? computeOrigin(y, size.height) : 0;
63
64 // First move the center of the view to the origin
65 transform.splice(0, 0, {
66 translateY: y
67 });
68 transform.splice(0, 0, {
69 translateX: x
70 });
71
72 // Restore it back the the original position after transforming
73 transform.push({
74 translateX: -x
75 });
76 transform.push({
77 translateY: -y
78 });
79 }
80 }
81 return onLayout;
82};
83exports.useTransformOrigin = useTransformOrigin;
84//# sourceMappingURL=useTransformOrigin.js.map
\No newline at end of file