UNPKG

@sky-mavis/tanto-widget

Version:
85 lines 3.21 kB
import {jsx}from'@emotion/react/jsx-runtime';import {useCallback,useState,useEffect,useMemo}from'react';import {useAccount}from'wagmi';import {analytic}from'../../analytic.mjs';import {viewConfigs}from'../../configs/viewConfigs.mjs';import {VISIBILITY_TRANSITION_DURATION}from'../../constants/index.mjs';import {useTantoConfig}from'../../hooks/useTantoConfig.mjs';import {useUnmount}from'../../hooks/useUnmount.mjs';import {Route,authenticatedRoutes,publicRoutes,internalRoutes}from'../../types/route.mjs';import {WidgetRouterContext}from'./WidgetRouterContext.mjs';const WidgetRouterProvider = ({ children }) => { const { disableProfile } = useTantoConfig(); const { isConnected } = useAccount(); const getInitialView = useCallback(route => { if (route) return viewConfigs[route]; return isConnected && !disableProfile ? viewConfigs[Route.PROFILE] : viewConfigs[Route.WALLETS]; }, [isConnected, disableProfile]); const [routerState, setRouterState] = useState(() => { const initialView = getInitialView(); return { view: initialView, history: [initialView] }; }); const reset = useCallback(route => { const initialView = getInitialView(route); setRouterState({ view: initialView, history: [initialView] }); }, [getInitialView]); const goTo = useCallback((nextRoute, options) => { if (!isConnected && authenticatedRoutes.includes(nextRoute)) return; setRouterState(({ view: currentView, history }) => { const isSameView = nextRoute === currentView.route; const newView = { route: nextRoute, title: options?.title ?? currentView.title, content: options?.content ?? viewConfigs[nextRoute].content, showBackButton: options?.showBackButton ?? (!isSameView && history.length > 0), ...options }; return { view: newView, history: isSameView ? history : [...history, newView] }; }); }, [isConnected]); const goBack = useCallback(() => { setRouterState(prevRouterState => { const { history } = prevRouterState; if (history.length <= 1) return prevRouterState; const newHistory = history.slice(0, -1); return { view: newHistory[newHistory.length - 1], history: newHistory }; }); }, []); useEffect(() => { const { route } = routerState.view; const shouldReset = isConnected && !disableProfile && publicRoutes.includes(route) || !isConnected && authenticatedRoutes.includes(route); if (shouldReset) reset(); }, [isConnected, disableProfile, routerState.view.route, reset]); useUnmount(() => { if (internalRoutes.includes(routerState.view.route)) setTimeout(reset, VISIBILITY_TRANSITION_DURATION); }); useEffect(() => { analytic.sendScreen(routerState.view.route); }, [routerState.view.route]); const contextValue = useMemo(() => ({ view: routerState.view, history: routerState.history, goTo, goBack, reset }), [routerState, goTo, goBack, reset]); return jsx(WidgetRouterContext.Provider, { value: contextValue, children: children }); };export{WidgetRouterProvider};