feat: add QR code and command to deeplink auth fallback, fix polling on tab return

This commit is contained in:
Fringg
2026-03-22 05:16:56 +03:00
parent 58b1f96852
commit 76c9d6448a
3 changed files with 144 additions and 68 deletions

View File

@@ -2,11 +2,13 @@ import { useEffect, useRef, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import { isAxiosError } from 'axios';
import { QRCodeSVG } from 'qrcode.react';
import { brandingApi, type TelegramWidgetConfig } from '../api/branding';
import { authApi } from '../api/auth';
import { useAuthStore } from '../store/auth';
import { useNavigate } from 'react-router';
import { consumeCampaignSlug } from '../utils/campaign';
import { copyToClipboard } from '../utils/clipboard';
interface TelegramLoginButtonProps {
referralCode?: string;
@@ -30,8 +32,10 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
const [deepLinkBotUsername, setDeepLinkBotUsername] = useState<string>('');
const [deepLinkPolling, setDeepLinkPolling] = useState(false);
const [deepLinkError, setDeepLinkError] = useState('');
const [copied, setCopied] = useState(false);
const pollTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
const expireTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
const copiedTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
const loginWithDeepLink = useAuthStore((s) => s.loginWithDeepLink);
@@ -61,15 +65,12 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
};
}, []);
// Cleanup polling and expire timeout on unmount
// Cleanup all timeouts on unmount
useEffect(() => {
return () => {
if (pollTimeoutRef.current) {
clearTimeout(pollTimeoutRef.current);
}
if (expireTimeoutRef.current) {
clearTimeout(expireTimeoutRef.current);
}
if (pollTimeoutRef.current) clearTimeout(pollTimeoutRef.current);
if (expireTimeoutRef.current) clearTimeout(expireTimeoutRef.current);
if (copiedTimeoutRef.current) clearTimeout(copiedTimeoutRef.current);
};
}, []);
@@ -335,6 +336,64 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
}
}, [scriptFailed, deepLinkToken, deepLinkPolling, startDeepLinkAuth]);
// Resume polling immediately when user returns to the page (e.g. after confirming in Telegram)
// Browsers throttle setTimeout in background tabs, so polling may have stalled.
useEffect(() => {
if (!deepLinkPolling || !deepLinkToken) return;
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible' && mountedRef.current) {
// Clear any pending throttled timer and trigger an immediate poll
if (pollTimeoutRef.current) {
clearTimeout(pollTimeoutRef.current);
pollTimeoutRef.current = null;
}
const capturedCampaign = capturedCampaignRef.current;
const immediatePoll = async () => {
if (!mountedRef.current) return;
try {
await loginWithDeepLink(deepLinkToken, capturedCampaign);
if (expireTimeoutRef.current) {
clearTimeout(expireTimeoutRef.current);
expireTimeoutRef.current = null;
}
if (mountedRef.current) {
setDeepLinkPolling(false);
navigate('/');
}
} catch (err: unknown) {
if (!mountedRef.current) return;
if (isAxiosError(err)) {
if (err.response?.status === 202) {
pollTimeoutRef.current = setTimeout(immediatePoll, DEEPLINK_POLL_INTERVAL_MS);
return;
}
if (err.response?.status === 410) {
setDeepLinkPolling(false);
setDeepLinkToken(null);
setDeepLinkError(t('auth.deepLinkExpired'));
return;
}
}
setDeepLinkPolling(false);
setDeepLinkError(t('common.error'));
}
};
immediatePoll();
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
// Sever any in-flight recursive immediatePoll chain from this effect cycle
if (pollTimeoutRef.current) {
clearTimeout(pollTimeoutRef.current);
pollTimeoutRef.current = null;
}
};
}, [deepLinkPolling, deepLinkToken, loginWithDeepLink, navigate, t]);
if (!botUsername || botUsername === 'your_bot') {
return (
<div className="py-4 text-center text-sm text-gray-500">
@@ -345,79 +404,90 @@ export default function TelegramLoginButton({ referralCode }: TelegramLoginButto
// Deep link fallback UI
if (scriptFailed) {
const resolvedBotUsername = deepLinkBotUsername || botUsername;
const deepLinkUrl = deepLinkToken
? `https://t.me/${deepLinkBotUsername || botUsername}?start=webauth_${deepLinkToken}`
? `https://t.me/${resolvedBotUsername}?start=webauth_${deepLinkToken}`
: '';
const startCommand = deepLinkToken ? `/start webauth_${deepLinkToken}` : '';
return (
<div className="flex flex-col items-center space-y-4">
<div className="flex flex-col items-center space-y-3">
{/* Info message */}
<p className="max-w-xs text-center text-xs text-dark-400">
{t('auth.telegramWidgetBlocked')}
</p>
<div className="flex flex-col items-center space-y-5">
{/* Info message */}
<p className="max-w-xs text-center text-xs text-dark-400">
{t('auth.telegramWidgetBlocked')}
</p>
{deepLinkToken && deepLinkUrl ? (
<>
{/* Deep link button */}
<a
href={deepLinkUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 rounded-lg bg-[#54a9eb] px-6 py-3 text-sm font-medium text-white shadow-sm transition-colors hover:bg-[#4a96d2]"
>
<svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
</svg>
{t('auth.openBotToLogin')}
</a>
{/* Polling status */}
{deepLinkPolling && (
<div className="flex items-center gap-2 text-xs text-dark-400">
<span className="h-3 w-3 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
{t('auth.waitingForConfirmation')}
</div>
)}
</>
) : deepLinkError ? (
{deepLinkToken && deepLinkUrl ? (
<>
{/* QR Code */}
<div className="flex flex-col items-center space-y-2">
<p className="text-xs text-red-500">{deepLinkError}</p>
<div className="rounded-2xl bg-white p-4">
<QRCodeSVG value={deepLinkUrl} size={180} level="M" includeMargin={false} />
</div>
<p className="text-[11px] text-dark-500">{t('auth.scanQrToLogin')}</p>
</div>
{/* Open bot button */}
<a
href={deepLinkUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 rounded-lg bg-[#54a9eb] px-6 py-3 text-sm font-medium text-white shadow-sm transition-colors hover:bg-[#4a96d2]"
>
<svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
</svg>
{t('auth.openBotToLogin')}
</a>
{/* Manual command */}
<div className="flex w-full max-w-xs flex-col items-center space-y-1.5">
<p className="text-[11px] text-dark-500">{t('auth.orSendCommand')}</p>
<button
type="button"
onClick={startDeepLinkAuth}
className="text-sm text-accent-400 transition-colors hover:text-accent-300"
onClick={() => {
copyToClipboard(startCommand)
.then(() => {
setCopied(true);
if (copiedTimeoutRef.current) clearTimeout(copiedTimeoutRef.current);
copiedTimeoutRef.current = setTimeout(() => setCopied(false), 2000);
})
.catch(() => {});
}}
className="group flex w-full items-center justify-between rounded-lg border border-dark-700 bg-dark-800/50 px-3 py-2 transition-colors hover:border-dark-600"
>
{t('auth.tryAgain')}
<code className="truncate text-xs text-dark-300">{startCommand}</code>
<span className="ml-2 flex-shrink-0 text-[10px] text-dark-500 transition-colors group-hover:text-dark-300">
{copied ? t('auth.commandCopied') : t('common.copy')}
</span>
</button>
</div>
) : (
<div className="flex items-center gap-2 text-xs text-dark-400">
<span className="h-3 w-3 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
{t('common.loading')}
</div>
)}
</div>
{/* Bot link fallback */}
<div className="text-center">
<p className="mb-2 text-xs text-dark-500">{t('auth.orOpenInApp')}</p>
<a
href={
referralCode
? `https://t.me/${botUsername}?start=${encodeURIComponent(referralCode)}`
: `https://t.me/${botUsername}`
}
target="_blank"
rel="noopener noreferrer"
className="text-telegram-blue inline-flex items-center text-sm hover:underline"
>
<svg className="mr-1 h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
</svg>
@{botUsername}
</a>
</div>
{/* Polling status */}
{deepLinkPolling && (
<div className="flex items-center gap-2 text-xs text-dark-400">
<span className="h-3 w-3 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
{t('auth.waitingForConfirmation')}
</div>
)}
</>
) : deepLinkError ? (
<div className="flex flex-col items-center space-y-2">
<p className="text-xs text-red-500">{deepLinkError}</p>
<button
type="button"
onClick={startDeepLinkAuth}
className="text-sm text-accent-400 transition-colors hover:text-accent-300"
>
{t('auth.tryAgain')}
</button>
</div>
) : (
<div className="flex items-center gap-2 text-xs text-dark-400">
<span className="h-3 w-3 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
{t('common.loading')}
</div>
)}
</div>
);
}

View File

@@ -180,6 +180,9 @@
"waitingForConfirmation": "Waiting for confirmation...",
"deepLinkExpired": "Link expired. Please try again.",
"tryAgain": "Try Again",
"scanQrToLogin": "Scan QR code with your phone camera",
"orSendCommand": "Or send the bot this command:",
"commandCopied": "Command copied",
"welcomeBack": "Welcome back!",
"loginTitle": "Login to Cabinet",
"loginSubtitle": "Sign in with Telegram or use your email",

View File

@@ -183,6 +183,9 @@
"waitingForConfirmation": "Ожидание подтверждения...",
"deepLinkExpired": "Ссылка истекла. Попробуйте снова.",
"tryAgain": "Попробовать снова",
"scanQrToLogin": "Отсканируйте QR-код камерой телефона",
"orSendCommand": "Или отправьте боту команду:",
"commandCopied": "Команда скопирована",
"welcomeBack": "Добро пожаловать!",
"loginTitle": "Вход в личный кабинет",
"loginSubtitle": "Войдите через Telegram или используйте email",