siftlode/frontend/src/components/Welcome.tsx

482 lines
18 KiB
TypeScript
Raw Normal View History

import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
Expand,
Filter,
Inbox,
ListVideo,
Lock,
PlayCircle,
Tags,
X,
type LucideIcon,
} from "lucide-react";
import { api } from "../lib/api";
import { HttpError } from "../lib/api";
import { setLanguage, type LangCode } from "../i18n";
import LanguageSwitcher from "./LanguageSwitcher";
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
const PASSWORD_MIN = 10;
type Mode = "signin" | "register" | "forgot" | "reset";
// Public landing + authentication. One scrollable page: a hero with the auth card (email+
// password, Google, explicit demo) over a short marketing pitch with feature cards. Shown
// whenever the user isn't signed in (see App.tsx). The auth forms talk to /auth/* (see the
// backend); errors are surfaced inline (the api calls use the quiet flag).
export default function Welcome() {
const { t, i18n } = useTranslation();
// Which screenshot (if any) is open in the full-size lightbox.
const [zoomed, setZoomed] = useState<{ src: string; label: string } | null>(null);
const open = (src: string, label: string) => setZoomed({ src, label });
return (
<div className="min-h-screen bg-bg text-fg overflow-y-auto">
<header className="flex items-center justify-between px-5 sm:px-8 py-4">
<div className="text-xl font-bold tracking-tight">
Sift<span className="text-accent">lode</span>
</div>
<LanguageSwitcher value={i18n.language as LangCode} onChange={setLanguage} />
</header>
<main className="max-w-6xl mx-auto px-5 sm:px-8 pb-16">
{/* Hero: pitch + auth card */}
<section className="grid lg:grid-cols-2 gap-10 items-center py-8 lg:py-14">
<div className="max-w-xl">
<h1 className="text-3xl sm:text-4xl font-bold tracking-tight leading-tight">
{t("welcome.hero.title")}
</h1>
<p className="text-muted mt-4 text-lg leading-relaxed">{t("welcome.hero.subtitle")}</p>
<p className="text-sm text-muted mt-4">{t("welcome.hero.trust")}</p>
</div>
<AuthCard />
</section>
{/* App preview */}
<Preview
src="/welcome/feed.png"
label={t("welcome.preview.feed")}
className="aspect-video"
onOpen={open}
/>
{/* Features */}
<section className="mt-14">
<h2 className="text-2xl font-semibold text-center">{t("welcome.features.heading")}</h2>
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-8">
{FEATURES.map((f) => (
<FeatureCard key={f.key} icon={f.icon} k={f.key} />
))}
</div>
</section>
{/* Secondary showcase — smaller thumbnails; click to view full size. */}
<section className="mt-12 flex flex-wrap justify-center gap-4">
<Preview
src="/welcome/channels.png"
label={t("welcome.preview.channels")}
className="w-full sm:w-72 aspect-[4/3]"
onOpen={open}
/>
<Preview
src="/welcome/playlists.png"
label={t("welcome.preview.playlists")}
className="w-full sm:w-72 aspect-[4/3]"
onOpen={open}
/>
</section>
</main>
{zoomed && (
<Lightbox src={zoomed.src} label={zoomed.label} onClose={() => setZoomed(null)} />
)}
<footer className="border-t border-border py-6 text-center text-xs text-muted flex flex-col sm:flex-row gap-3 justify-center items-center">
<span>
Sift<span className="text-accent">lode</span>
</span>
<span className="hidden sm:inline">·</span>
<a href="/privacy" className="hover:text-fg transition">
{t("common.privacyPolicy")}
</a>
<a href="/terms" className="hover:text-fg transition">
{t("common.termsOfService")}
</a>
</footer>
</div>
);
}
const FEATURES: { key: string; icon: LucideIcon }[] = [
{ key: "readable", icon: Filter },
{ key: "neverMiss", icon: Inbox },
{ key: "playlists", icon: ListVideo },
{ key: "player", icon: PlayCircle },
{ key: "channels", icon: Tags },
{ key: "private", icon: Lock },
];
function FeatureCard({ icon: Icon, k }: { icon: LucideIcon; k: string }) {
const { t } = useTranslation();
return (
<div className="glass-card rounded-2xl p-5">
<div className="w-10 h-10 rounded-xl bg-accent/15 text-accent grid place-items-center mb-3">
<Icon className="w-5 h-5" />
</div>
<h3 className="font-semibold">{t(`welcome.features.${k}.title`)}</h3>
<p className="text-sm text-muted leading-relaxed mt-1">{t(`welcome.features.${k}.body`)}</p>
</div>
);
}
// Image with a graceful fallback: if the file isn't present yet, show a tasteful placeholder
// frame instead of a broken image (the demo screenshots drop into frontend/public/welcome/).
// When loaded it's a button that opens the full-size lightbox (onOpen).
function Preview({
src,
label,
className,
onOpen,
}: {
src: string;
label: string;
className?: string;
onOpen?: (src: string, label: string) => void;
}) {
const [failed, setFailed] = useState(false);
if (failed) {
return (
<div className={`glass-card rounded-2xl overflow-hidden ${className ?? ""}`}>
<div className="w-full h-full grid place-items-center bg-gradient-to-br from-accent/10 to-card text-muted text-sm p-6 text-center">
{label}
</div>
</div>
);
}
return (
<button
type="button"
onClick={() => onOpen?.(src, label)}
aria-label={label}
className={`group relative glass-card rounded-2xl overflow-hidden block cursor-zoom-in ${className ?? ""}`}
>
<img
src={src}
alt={label}
loading="lazy"
onError={() => setFailed(true)}
className="w-full h-full object-cover object-top"
/>
<span className="absolute inset-0 grid place-items-center bg-black/0 opacity-0 transition group-hover:bg-black/30 group-hover:opacity-100">
<Expand className="w-6 h-6 text-white drop-shadow-lg" />
</span>
</button>
);
}
// Full-size image viewer: a dimmed, blurred backdrop with the screenshot fit to the viewport
// (aspect ratio preserved via object-contain). Closes on backdrop click, the ✕, or Escape.
function Lightbox({ src, label, onClose }: { src: string; label: string; onClose: () => void }) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden"; // no background scroll while open
return () => {
window.removeEventListener("keydown", onKey);
document.body.style.overflow = prev;
};
}, [onClose]);
return (
<div
className="fixed inset-0 z-[60] grid place-items-center bg-black/80 backdrop-blur-sm p-4 sm:p-8"
onClick={onClose}
role="dialog"
aria-modal="true"
aria-label={label}
>
<button
type="button"
onClick={onClose}
aria-label="Close"
className="absolute top-4 right-4 p-2 rounded-full glass-card glass-hover text-fg"
>
<X className="w-5 h-5" />
</button>
<figure
className="flex max-h-full max-w-full flex-col items-center gap-3"
onClick={(e) => e.stopPropagation()}
>
<img
src={src}
alt={label}
className="max-h-[82vh] max-w-[92vw] w-auto h-auto rounded-xl border border-border object-contain shadow-2xl"
/>
<figcaption className="text-sm text-muted">{label}</figcaption>
</figure>
</div>
);
}
function AuthCard() {
const { t } = useTranslation();
// Snapshot the redirect params ONCE so we can clean them from the address bar below without
// dismissing the banners/reset-mode they drive (those read this stable snapshot, not the URL).
const [params] = useState(() => new URLSearchParams(window.location.search));
const resetToken = params.get("reset");
const bounced = params.get("access"); // Google denied → "requested" | "denied"
const verify = params.get("verify"); // "ok" | "invalid"
const login = params.get("login"); // Google login blocked → "suspended"
const deleted = params.get("deleted"); // self-service account deletion just completed
// Strip the query string so the address bar stays clean (http://host/) after we've captured it.
useEffect(() => {
if (window.location.search) {
window.history.replaceState(null, "", window.location.pathname);
}
}, []);
const [mode, setMode] = useState<Mode>(resetToken ? "reset" : "signin");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
// Whether to offer "Continue with Google" — hidden when the instance has no Google OAuth
// configured. Optimistic (most instances have it); the rare Google-less instance just sees it
// disappear once the config loads.
const [googleEnabled, setGoogleEnabled] = useState(true);
useEffect(() => {
api.authConfig().then((c) => setGoogleEnabled(c.google_enabled)).catch(() => {});
}, []);
const [done, setDone] = useState<string>(""); // success/info message replacing the form
// Explicit demo entry (replaces the old hidden probe): a labelled email field, still gated
// by the demo whitelist server-side.
const [showDemo, setShowDemo] = useState(false);
const [demoEmail, setDemoEmail] = useState("");
const [demoBusy, setDemoBusy] = useState(false);
const [demoError, setDemoError] = useState("");
const reset = () => {
setError("");
setDone("");
};
async function onSubmit(e: React.FormEvent) {
e.preventDefault();
reset();
const mail = email.trim().toLowerCase();
if ((mode === "signin" || mode === "register" || mode === "forgot") && !EMAIL_RE.test(mail)) {
setError(t("welcome.auth.invalidEmail"));
return;
}
if ((mode === "register" || mode === "reset") && password.length < PASSWORD_MIN) {
setError(t("welcome.auth.weakPassword", { min: PASSWORD_MIN }));
return;
}
setBusy(true);
try {
if (mode === "signin") {
await api.passwordLogin(mail, password);
window.location.reload();
return;
}
if (mode === "register") {
await api.register(mail, password);
setDone(t("welcome.auth.registerDone"));
} else if (mode === "forgot") {
await api.requestPasswordReset(mail);
setDone(t("welcome.auth.forgotDone"));
} else if (mode === "reset") {
await api.confirmPasswordReset(resetToken ?? "", password);
setDone(t("welcome.auth.resetDone"));
}
} catch (err) {
setError(err instanceof HttpError && err.detail ? err.detail : t("welcome.auth.genericError"));
} finally {
setBusy(false);
}
}
async function onDemo(e: React.FormEvent) {
e.preventDefault();
setDemoError("");
const mail = demoEmail.trim().toLowerCase();
if (!EMAIL_RE.test(mail)) {
setDemoError(t("welcome.auth.invalidEmail"));
return;
}
setDemoBusy(true);
try {
const r = await api.demoLogin(mail);
if (r.authenticated) window.location.reload();
else setDemoError(t("welcome.auth.demoDenied"));
} catch {
setDemoError(t("welcome.auth.demoDenied"));
} finally {
setDemoBusy(false);
}
}
const inputCls =
"w-full bg-card border border-border rounded-xl px-3 py-2.5 text-sm outline-none focus:border-accent";
const titleKey =
mode === "register"
? "welcome.auth.createTitle"
: mode === "forgot"
? "welcome.auth.forgotTitle"
: mode === "reset"
? "welcome.auth.resetTitle"
: "welcome.auth.signinTitle";
return (
<div className="glass rounded-2xl p-6 sm:p-7 w-full max-w-md lg:justify-self-end">
<h2 className="text-lg font-semibold mb-1">{t(titleKey)}</h2>
{/* One-time status banners from a redirect (Google-denied, email verification). */}
{verify === "ok" && <Banner tone="ok">{t("welcome.auth.verifyOk")}</Banner>}
{verify === "invalid" && <Banner tone="warn">{t("welcome.auth.verifyInvalid")}</Banner>}
{bounced === "requested" && <Banner tone="ok">{t("welcome.auth.accessRequested")}</Banner>}
{bounced === "denied" && <Banner tone="warn">{t("welcome.auth.accessDenied")}</Banner>}
{login === "suspended" && <Banner tone="warn">{t("welcome.auth.suspended")}</Banner>}
{deleted && <Banner tone="ok">{t("welcome.auth.deleted")}</Banner>}
{done ? (
<div className="mt-3">
<p className="text-sm text-fg/80 leading-relaxed">{done}</p>
<button
onClick={() => {
setMode("signin");
setDone("");
}}
className="mt-4 text-sm text-accent hover:underline"
>
{t("welcome.auth.backToSignin")}
</button>
</div>
) : (
<>
<form onSubmit={onSubmit} className="flex flex-col gap-3 mt-3">
{mode !== "reset" && (
<input
type="email"
autoComplete="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t("welcome.auth.email")}
className={inputCls}
/>
)}
{mode !== "forgot" && (
<input
type="password"
autoComplete={mode === "signin" ? "current-password" : "new-password"}
required
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={
mode === "reset" || mode === "register"
? t("welcome.auth.newPassword", { min: PASSWORD_MIN })
: t("welcome.auth.password")
}
className={inputCls}
/>
)}
{error && <p className="text-xs text-red-400">{error}</p>}
<button
type="submit"
disabled={busy}
className="px-4 py-2.5 rounded-xl font-semibold bg-accent text-accent-fg hover:opacity-90 disabled:opacity-50 transition"
>
{busy
? t("welcome.auth.working")
: t(
mode === "register"
? "welcome.auth.createButton"
: mode === "forgot"
? "welcome.auth.forgotButton"
: mode === "reset"
? "welcome.auth.resetButton"
: "welcome.auth.signinButton"
)}
</button>
</form>
{/* Mode switches */}
<div className="flex items-center justify-between mt-3 text-xs">
{mode === "signin" ? (
<>
<button onClick={() => { reset(); setMode("register"); }} className="text-accent hover:underline">
{t("welcome.auth.createLink")}
</button>
<button onClick={() => { reset(); setMode("forgot"); }} className="text-muted hover:text-fg">
{t("welcome.auth.forgotLink")}
</button>
</>
) : (
<button onClick={() => { reset(); setMode("signin"); }} className="text-accent hover:underline">
{t("welcome.auth.backToSignin")}
</button>
)}
</div>
{mode === "signin" && (
<>
<div className="flex items-center gap-3 my-4 text-[11px] uppercase tracking-wide text-muted">
<span className="h-px flex-1 bg-border" />
{t("welcome.auth.or")}
<span className="h-px flex-1 bg-border" />
</div>
{googleEnabled && (
<a
href="/auth/login"
className="block text-center px-4 py-2.5 rounded-xl text-sm font-semibold bg-card border border-border hover:border-accent transition"
>
{t("welcome.auth.google")}
</a>
)}
{!showDemo ? (
<button
onClick={() => setShowDemo(true)}
className="w-full mt-2 px-4 py-2.5 rounded-xl text-sm bg-card border border-border hover:border-accent transition"
>
{t("welcome.auth.tryDemo")}
</button>
) : (
<form onSubmit={onDemo} className="mt-2 flex flex-col gap-2">
<p className="text-[11px] text-muted">{t("welcome.auth.demoHint")}</p>
<div className="flex gap-2">
<input
type="email"
value={demoEmail}
onChange={(e) => setDemoEmail(e.target.value)}
placeholder={t("welcome.auth.demoEmail")}
className={inputCls}
/>
<button
type="submit"
disabled={demoBusy}
className="shrink-0 px-3 py-2.5 rounded-xl text-sm font-semibold bg-card border border-border hover:border-accent disabled:opacity-50 transition"
>
{demoBusy ? t("welcome.auth.working") : t("welcome.auth.demoEnter")}
</button>
</div>
{demoError && <p className="text-xs text-red-400">{demoError}</p>}
</form>
)}
</>
)}
</>
)}
</div>
);
}
function Banner({ tone, children }: { tone: "ok" | "warn"; children: React.ReactNode }) {
const cls = tone === "ok" ? "bg-accent/15 text-fg" : "bg-amber-500/15 text-fg";
return <div className={`rounded-xl px-3 py-2 text-xs leading-relaxed mt-3 ${cls}`}>{children}</div>;
}