@visactor/react-vrender-utils
Version:
## Description
55 lines (50 loc) • 3.16 kB
JavaScript
var __rest = this && this.__rest || function(s, e) {
var t = {};
for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0 && (t[p] = s[p]);
if (null != s && "function" == typeof Object.getOwnPropertySymbols) {
var i = 0;
for (p = Object.getOwnPropertySymbols(s); i < p.length; i++) e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]) && (t[p[i]] = s[p[i]]);
}
return t;
};
import React from "react";
import * as ReactDOM from "react-dom";
import { ShadowRoot } from "@visactor/react-vrender";
const needForceStyle = el => {
const pos = window.getComputedStyle(el).position;
return !("absolute" === pos || "relative" === pos);
};
export const Html = ({children: children, divProps: divProps, transform: transform, transformFunc: transformFunc}) => {
const groupRef = React.useRef(null), [div] = React.useState((() => document.createElement("div"))), root = React.useMemo((() => ReactDOM.createRoot(div)), [ div ]), shouldTransform = null == transform || transform, handleGroupRerender = () => {
if (shouldTransform && groupRef.current) {
if (!groupRef.current.shouldUpdateGlobalMatrix()) return;
let attrs = groupRef.current.globalTransMatrix.toTransformAttrs();
transformFunc && (attrs = transformFunc(attrs)), div.style.position = "absolute",
div.style.zIndex = "10", div.style.top = "0px", div.style.left = "0px", div.style.transform = `translate(${attrs.x}px, ${attrs.y}px) rotate(${attrs.rotateDeg}deg) scaleX(${attrs.scaleX}) scaleY(${attrs.scaleY})`,
div.style.transformOrigin = "top left";
} else div.style.position = "", div.style.zIndex = "", div.style.top = "", div.style.left = "",
div.style.transform = "", div.style.transformOrigin = "";
const _a = divProps || {}, {style: style} = _a, restProps = __rest(_a, [ "style" ]);
Object.assign(div.style, style), Object.assign(div, restProps);
};
return React.useEffect((() => {
var _a, _b;
const group = groupRef.current;
if (!(null == group ? void 0 : group.stage)) return;
const stage = group.stage, htmlContainer = null === (_b = null === (_a = stage.window) || void 0 === _a ? void 0 : _a.getContainer) || void 0 === _b ? void 0 : _b.call(_a);
return htmlContainer ? (htmlContainer.appendChild(div), shouldTransform && needForceStyle(htmlContainer) && (htmlContainer.style.position = "relative"),
stage.hooks.beforeRender.tap(`${group._uid}-render`, handleGroupRerender), handleGroupRerender(),
() => {
var _a;
stage.hooks.beforeRender.unTap(`${group._uid}-render`, handleGroupRerender), null === (_a = div.parentNode) || void 0 === _a || _a.removeChild(div);
}) : void 0;
}), [ shouldTransform ]), React.useLayoutEffect((() => {
handleGroupRerender();
}), [ divProps ]), React.useLayoutEffect((() => {
root.render(children);
})), React.useLayoutEffect((() => () => {
root.unmount();
}), []), React.createElement(ShadowRoot, {
ref: groupRef
});
};