peppa/apps/web/components/OpenBotButton.tsx
Асель bb7b1b4158 PEP-100: opening the bot keeps Peppa open — new tab, the page refreshes until Start is pressed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:25:12 +05:00

53 lines
1.9 KiB
TypeScript
Raw 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);
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;
}
if (tab) tab.location.href = r.url;
else window.location.href = 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>
{waiting && <span className="text-xs text-muted-foreground">Нажмите Start в Telegram и вернитесь сюда — шаг отметится сам.</span>}
{error && <span className="text-xs text-destructive">{error}</span>}
</span>
);
}