import { useContext, useState, type ReactNode } from "react"; import { useLocation } from "react-router-dom"; import { findRoute, resolveParent } from "@/routes"; import { BackContext, type BackTarget } from "@/lib/back"; import { useAuth } from "@/store/auth"; import { BackButton } from "@/components/BackButton"; /** * Родитель текущего экрана — один раз по таблице маршрутов, для всех: кнопки * над экраном (BackBar) и выходов внутри страниц (useRouteBack). Здесь же живёт * цель, которую страница может задать сама (useBackOverride). */ export function BackProvider({ children }: { children: ReactNode }) { const loc = useLocation(); const signedIn = useAuth((s) => !!s.token); const [override, setOverride] = useState(null); const hit = findRoute(loc.pathname); const parent = hit && hit.route.parent !== null ? { to: resolveParent(hit.route.parent, { params: hit.params, search: new URLSearchParams(loc.search), signedIn, }), mode: hit.route.back, } : null; return {children}; } /** * Строка «Назад» над экраном. Стоит в App над маршрутами, а не в страницах: * так она есть в любом состоянии экрана — загрузка, ошибка, пустота, редирект * охраны, — и новый раздел получает её сам, стоит завести его в таблице * маршрутов с родителем. У главной и входа родителя нет — строки тоже. */ export function BackBar() { const { parent, override } = useContext(BackContext); if (!parent) return null; const target = override ?? parent; return ; }