zapishis-client/apps/web/hooks/telegram/use-back-button.ts
2025-10-09 12:01:06 +03:00

41 lines
880 B
TypeScript

'use client';
import { backButton } from '@telegram-apps/sdk-react';
import { usePathname, useRouter } from 'next/navigation';
import { useCallback, useEffect } from 'react';
const exclude = ['/pro'];
export function useBackButton() {
const { back } = useRouter();
const pathname = usePathname();
const onBackClick = useCallback(() => {
if (pathname !== '/') {
back();
}
}, [pathname, back]);
useEffect(() => {
const off = backButton.onClick(onBackClick);
return off;
}, [onBackClick]);
useEffect(() => {
if (backButton.isMounted()) {
if (isRootLevelPage(pathname)) {
backButton.hide();
} else {
backButton.show();
}
}
}, [pathname]);
}
function isRootLevelPage(pathname: string) {
if (exclude.includes(pathname)) return false;
return pathname.split('/').filter(Boolean).length === 1;
}