63 lines
2.6 KiB
TypeScript
63 lines
2.6 KiB
TypeScript
"use client";
|
||
|
||
import { useEffect, useState } from "react";
|
||
import { useRouter } from "next/navigation";
|
||
import { useLive } from "@/lib/live";
|
||
import { Button } from "@/components/ui/button";
|
||
import { pairingLinkAction } from "@/app/(app)/actions";
|
||
import { useT } from "@/components/I18n";
|
||
|
||
/**
|
||
* 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 live channel tells the page, and it re-renders so the step turns done.
|
||
*/
|
||
export function OpenBotButton({ label, variant = "default", size = "sm" }: { label: string; variant?: "default" | "ghost" | "outline"; size?: "sm" | "xs" }) {
|
||
const t = useT();
|
||
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 stop = setTimeout(() => setWaiting(false), 3 * 60_000);
|
||
return () => clearTimeout(stop);
|
||
}, [waiting]);
|
||
// PEP-225: the binding (`me`) changes when the user presses Start in the bot — re-render then.
|
||
useLive(waiting ? "me" : null, (e) => {
|
||
if (e.type === "change") router.refresh();
|
||
});
|
||
|
||
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 ? t.text(r.error) : t("Не получилось открыть бота"));
|
||
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">
|
||
{t("Браузер не открыл новую вкладку — нажмите здесь, чтобы открыть бота")}
|
||
</a>
|
||
)}
|
||
{waiting && <span className="text-xs text-muted-foreground">{t("Нажмите Start в Telegram и вернитесь сюда — шаг отметится сам.")}</span>}
|
||
{error && <span className="text-xs text-destructive">{error}</span>}
|
||
</span>
|
||
);
|
||
}
|