peppa/apps/web/components/OpenBotButton.tsx
Асель 60fa861303 PEP-100: popups blocked — a new-tab link instead of leaving Peppa
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:25:12 +05:00

60 lines
2.4 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { pairingLinkAction } from "@/app/(app)/actions";
/**
* PEP-100: opens the user's bot (with the pairing code) in a new tab / the Telegram app and keeps
* Peppa open — a plain redirect used to take the page away mid-steps. While the user presses
* Start, the page refreshes itself so the step turns done.
*/
export function OpenBotButton({ label, variant = "default", size = "sm" }: { label: string; variant?: "default" | "ghost" | "outline"; size?: "sm" | "xs" }) {
const router = useRouter();
const [waiting, setWaiting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [link, setLink] = useState<string | null>(null);
useEffect(() => {
if (!waiting) return;
const t = setInterval(() => router.refresh(), 3000);
const stop = setTimeout(() => setWaiting(false), 3 * 60_000);
return () => {
clearInterval(t);
clearTimeout(stop);
};
}, [waiting, router]);
async function open() {
setError(null);
// Opened synchronously in the click, so the browser doesn't block it as a popup.
const tab = window.open("about:blank", "_blank");
const r = await pairingLinkAction();
if (!r.url) {
tab?.close();
setError(r.error ?? "Не получилось открыть бота");
return;
}
// Popups blocked: never take Peppa away — show a link that opens in a new tab instead.
if (tab) tab.location.href = r.url;
else setLink(r.url);
setWaiting(true);
}
return (
<span className="inline-flex flex-col items-start gap-1">
<Button type="button" variant={variant} size={size} onClick={() => void open()}>
{label}
</Button>
{link && (
<a href={link} target="_blank" rel="noreferrer" className="text-sm font-medium text-primary underline-offset-2 hover:underline">
Браузер не открыл новую вкладку — нажмите здесь, чтобы открыть бота
</a>
)}
{waiting && <span className="text-xs text-muted-foreground">Нажмите Start в Telegram и вернитесь сюда — шаг отметится сам.</span>}
{error && <span className="text-xs text-destructive">{error}</span>}
</span>
);
}