@roderickhsiao/react-i13n
Version:
[Experiment] React I13n provides a performant and scalable solution to application instrumentation.
104 lines (94 loc) • 2.83 kB
JavaScript
/**
* Copyright 2015 - Present, Yahoo Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import { cloneElement, useContext, useEffect, useState, useRef } from 'react';
import { listen } from 'subscribe-ui-event';
import clickHandler from '../../libs/clickHandler';
import useDebugDashboard from '../../hooks/useDebugDashboard';
import useScanLinks from '../../hooks/useScanLinks';
import useViewportDetect from '../../hooks/useViewportDetect';
import I13nContext from './I13nContext';
var CoreComponent = props => {
var {
bindClickEvent,
componentIsFunction,
children,
follow,
i13nModel,
scanLinks = {},
shouldFollowLink,
viewport
} = props;
var {
executeEvent,
i13nNode,
i13nInstance,
parentI13nNode
} = useContext(I13nContext);
var domRef = useRef();
var [DOMNode, setDOMNode] = useState();
var {
enable: scanLinksEnabled,
tags
} = scanLinks; // create event
useEffect(() => {
executeEvent === null || executeEvent === void 0 ? void 0 : executeEvent('created', {});
}, []); // auto bind click event
useEffect(() => {
var clickEventListener;
if (bindClickEvent && DOMNode) {
var handleClick = e => {
clickHandler(e, {
executeEvent,
i13nNode,
props: {
follow
}
});
};
clickEventListener = listen(DOMNode, 'click', handleClick);
}
return () => {
var _clickEventListener;
(_clickEventListener = clickEventListener) === null || _clickEventListener === void 0 ? void 0 : _clickEventListener.remove();
};
}, [bindClickEvent, i13nNode, executeEvent, DOMNode]); // update modal if changes
useEffect(() => {
i13nNode === null || i13nNode === void 0 ? void 0 : i13nNode.updateModel(i13nModel);
}, [i13nNode, i13nModel]);
useScanLinks({
enabled: scanLinksEnabled,
executeEvent,
i13nInstance,
i13nNode,
node: i13nNode === null || i13nNode === void 0 ? void 0 : i13nNode.getDOMNode(),
shouldFollowLink,
tags
});
var ref = (i13nInstance === null || i13nInstance === void 0 ? void 0 : i13nInstance.isViewportEnabled()) ? domRef : {};
useViewportDetect({
viewport,
executeEvent,
ref,
node: i13nNode
});
useDebugDashboard({
node: i13nNode
}); // clean up
useEffect(() => () => {
if (parentI13nNode) {
parentI13nNode.removeChildNode(i13nNode);
}
}, [parentI13nNode, i13nNode]);
return /*#__PURE__*/cloneElement(children, {
[componentIsFunction ? 'innerRef' : 'ref']: node => {
if (node) {
i13nNode === null || i13nNode === void 0 ? void 0 : i13nNode.setDOMNode(node);
domRef.current = node;
setDOMNode(node);
}
}
});
};
export default CoreComponent;