UNPKG

@embrace-io/react-native-navigation

Version:

A React Native wrapper for the OTel Navigation instrumentation library that creates telemetry data representing Navigation changes

56 lines (55 loc) 2.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = require("react"); const spanFactory_1 = require("../utils/spanFactory"); const useSpanRef_1 = require("../utils/hooks/useSpanRef"); const useConsole_1 = require("../utils/hooks/useConsole"); const useAppStateListener_1 = require("./useAppStateListener"); const useNavigationTracker = (ref, tracer, config) => { const navigationElRef = (0, react_1.useMemo)(() => { const isMutableRef = ref !== null && typeof ref !== "function"; return isMutableRef ? ref === null || ref === void 0 ? void 0 : ref.current : undefined; }, [ref]); const { attributes: customAttributes, debug } = config !== null && config !== void 0 ? config : {}; const console = (0, react_1.useRef)((0, useConsole_1.default)(!!debug)); const span = (0, useSpanRef_1.default)(); const view = (0, react_1.useRef)(null); /** * Native Navigation Span Factory */ const initNavigationSpan = (0, react_1.useMemo)(() => (0, spanFactory_1.spanCreator)(tracer, span, view, console.current, customAttributes), [customAttributes, span, tracer]); /** * Registering the Navigation 'state' Listener * to start and end spans depending on the navigation lifecycle */ (0, react_1.useEffect)(() => { if (!navigationElRef) { console.current.warn("[Embrace] Navigation ref is not available. Make sure this is properly configured."); return; } if (navigationElRef) { navigationElRef.addListener("state", () => { var _a; const { name: routeName } = (_a = navigationElRef.getCurrentRoute()) !== null && _a !== void 0 ? _a : {}; if (!routeName) { console.current.warn("[Embrace] Navigation route name is not available. Make sure this is properly configured."); // do nothing in case for some reason there is no route return; } initNavigationSpan(routeName); }); } }, [navigationElRef, initNavigationSpan]); /** * Start and end spans depending on the app state changes */ (0, useAppStateListener_1.default)(tracer, span, view, customAttributes); /** * Ending the final span depending on the app lifecycle */ (0, react_1.useEffect)(() => () => { // making sure the final span is ended when the app is unmounted (0, spanFactory_1.spanEnd)(span, undefined, true); }, [span]); }; exports.default = useNavigationTracker;