/
This commit is contained in:
+66
-5
@@ -2,7 +2,9 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import { api, clearToken, getToken } from "./lib/api.ts";
|
||||
import { featureEnabled, THINKING_SYSTEM_PROMPT } from "./lib/features.ts";
|
||||
import type { Attachment, ChatMessage, Conversation, DriverModel, FilePreview, User } from "./lib/types.ts";
|
||||
import { navigate, normalizePath, useRoute } from "./lib/route.ts";
|
||||
import { Login } from "./components/Login.tsx";
|
||||
import { RegisterPage } from "./components/RegisterPage.tsx";
|
||||
import { Sidebar } from "./components/Sidebar.tsx";
|
||||
import { Chat } from "./components/Chat.tsx";
|
||||
import { ConvEditDialog, FilePreviewModal, SettingsModal, ShareModal } from "./components/dialogs.tsx";
|
||||
@@ -48,7 +50,18 @@ function applyTheme(theme: string) {
|
||||
|
||||
export function App() {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [checking, setChecking] = useState(!SHARE_ID && !RESET_TOKEN && !REVIEW_ID && !IS_ADMIN_PAGE);
|
||||
// Boot splash ONLY on the platform routes (/ and /chat, with a token).
|
||||
// /login and /register never show it — they render instantly.
|
||||
const [checking, setChecking] = useState(() => {
|
||||
if (SHARE_ID || RESET_TOKEN || REVIEW_ID || IS_ADMIN_PAGE) return false;
|
||||
const p = normalizePath(window.location.pathname);
|
||||
if (p === "/login" || p === "/register") return false;
|
||||
return !!getToken();
|
||||
});
|
||||
// True once we know whether there is a session (no token = instant).
|
||||
const [authReady, setAuthReady] = useState(() => !getToken());
|
||||
const rawRoute = useRoute();
|
||||
const path = normalizePath(rawRoute);
|
||||
const [models, setModels] = useState<DriverModel[]>([]);
|
||||
const [model, setModel] = useState("");
|
||||
const [convs, setConvs] = useState<Conversation[]>([]);
|
||||
@@ -98,7 +111,7 @@ export function App() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Session restore (boot splash stays at least MIN_SPLASH_MS)
|
||||
// Session restore (boot splash stays at least MIN_SPLASH_MS on / and /chat)
|
||||
useEffect(() => {
|
||||
const t0 = Date.now();
|
||||
const done = () => {
|
||||
@@ -106,7 +119,8 @@ export function App() {
|
||||
window.setTimeout(() => setChecking(false), wait);
|
||||
};
|
||||
if (!getToken()) {
|
||||
done();
|
||||
setAuthReady(true);
|
||||
setChecking(false);
|
||||
return;
|
||||
}
|
||||
api.verify()
|
||||
@@ -125,9 +139,35 @@ export function App() {
|
||||
if (c.conversations.length > 0) setActiveId(c.conversations[0]!.id);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(done);
|
||||
.finally(() => {
|
||||
setAuthReady(true);
|
||||
done();
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Route guard: / redirects by session, /chat needs auth, /login and
|
||||
// /register bounce logged-in users to /chat. Public routes return above.
|
||||
useEffect(() => {
|
||||
if (SHARE_ID || RESET_TOKEN || REVIEW_ID || IS_ADMIN_PAGE) return;
|
||||
const noToken = !getToken();
|
||||
if (path === "/") {
|
||||
if (noToken) navigate("/login", true);
|
||||
else if (authReady) navigate(user ? "/chat" : "/login", true);
|
||||
return;
|
||||
}
|
||||
if (path === "/login" || path === "/register") {
|
||||
if (user) navigate("/chat", true);
|
||||
return;
|
||||
}
|
||||
if (path === "/chat") {
|
||||
if (noToken || (authReady && !user)) navigate("/login", true);
|
||||
return;
|
||||
}
|
||||
// Unknown path: land on the platform or the login page.
|
||||
if (noToken) navigate("/login", true);
|
||||
else if (authReady) navigate(user ? "/chat" : "/login", true);
|
||||
}, [path, user, authReady]);
|
||||
|
||||
// Load messages for active conversation
|
||||
useEffect(() => {
|
||||
if (!activeId) {
|
||||
@@ -148,7 +188,10 @@ export function App() {
|
||||
|
||||
function handleLogin(u: User) {
|
||||
setUser(u);
|
||||
setAuthReady(true);
|
||||
setChecking(false);
|
||||
applyTheme(u.theme);
|
||||
navigate("/chat", true);
|
||||
api.models().then((m) => {
|
||||
setModels(m.models);
|
||||
if (m.models.length > 0) setModel(m.models[0]!.id);
|
||||
@@ -161,12 +204,15 @@ export function App() {
|
||||
api.logout().finally(() => {});
|
||||
clearToken();
|
||||
setUser(null);
|
||||
setAuthReady(true);
|
||||
setChecking(false);
|
||||
setConvs([]);
|
||||
setMessages([]);
|
||||
setActiveId(null);
|
||||
setArchivedConv(null);
|
||||
setAttachments([]);
|
||||
setFilePreview(null);
|
||||
navigate("/login", true);
|
||||
}
|
||||
|
||||
async function newChat() {
|
||||
@@ -334,12 +380,27 @@ export function App() {
|
||||
await refreshConvs();
|
||||
}
|
||||
|
||||
// Auth pages render instantly (no splash); the platform boots behind one.
|
||||
if (path === "/login") {
|
||||
if (user) return null; // bounce to /chat imminent
|
||||
return <Login onLogin={handleLogin} />;
|
||||
}
|
||||
if (path === "/register") {
|
||||
if (user) return null; // bounce to /chat imminent
|
||||
return <RegisterPage />;
|
||||
}
|
||||
|
||||
if (checking) {
|
||||
return <LoadingScreen />;
|
||||
}
|
||||
|
||||
// / (or unknown paths) while the guard above redirects.
|
||||
if (path !== "/chat") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Login onLogin={handleLogin} />;
|
||||
return null; // bounce to /login imminent (no splash flash)
|
||||
}
|
||||
|
||||
const active = convs.find((c) => c.id === activeId) ?? archivedConv;
|
||||
|
||||
@@ -3,8 +3,9 @@ import { ArrowRight, KeyRound, MessageSquareText, ShieldCheck, User, UserPlus, Z
|
||||
import { api, setToken } from "../lib/api.ts";
|
||||
import { useT } from "../lib/i18n.ts";
|
||||
import type { User as UserType } from "../lib/types.ts";
|
||||
import { navigate } from "../lib/route.ts";
|
||||
import { Button, FlowerMark, Input, LangPicker, Spinner } from "./ui.tsx";
|
||||
import { RecoverDialog, RegisterDialog } from "./dialogs.tsx";
|
||||
import { RecoverDialog } from "./dialogs.tsx";
|
||||
import { AccessRequestModal } from "./ReviewPage.tsx";
|
||||
|
||||
export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
|
||||
@@ -16,7 +17,6 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
|
||||
const [recoverOpen, setRecoverOpen] = useState(false);
|
||||
const [recoveryOn, setRecoveryOn] = useState(false);
|
||||
const [recoveryFrom, setRecoveryFrom] = useState<string | undefined>(undefined);
|
||||
const [registerOpen, setRegisterOpen] = useState(false);
|
||||
const [registrationOn, setRegistrationOn] = useState(false);
|
||||
const [requestOpen, setRequestOpen] = useState(false);
|
||||
const [requestOn, setRequestOn] = useState(false);
|
||||
@@ -37,6 +37,19 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
|
||||
setRegistrationOn(m.registration);
|
||||
setRequestOn(m.accessRequest);
|
||||
}).catch(() => {});
|
||||
// Fresh registration hands the new key over via sessionStorage so the
|
||||
// login form comes prefilled (cleared immediately after reading).
|
||||
try {
|
||||
const raw = sessionStorage.getItem("ka_login_prefill");
|
||||
if (raw) {
|
||||
const p = JSON.parse(raw) as { username?: string; key?: string };
|
||||
if (p.username) setUsername(p.username);
|
||||
if (p.key) setKey(p.key);
|
||||
sessionStorage.removeItem("ka_login_prefill");
|
||||
}
|
||||
} catch {
|
||||
// ignore (private mode, malformed payload)
|
||||
}
|
||||
}, []);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
@@ -171,16 +184,11 @@ export function Login({ onLogin }: { onLogin: (user: UserType) => void }) {
|
||||
className="mt-3 w-full"
|
||||
disabled={!registrationOn}
|
||||
title={registrationOn ? t("login.regTipOn") : t("login.regTipOff")}
|
||||
onClick={() => setRegisterOpen(true)}
|
||||
onClick={() => navigate("/register")}
|
||||
>
|
||||
<UserPlus size={16} />
|
||||
{t("login.register")}
|
||||
</Button>
|
||||
<RegisterDialog
|
||||
open={registerOpen}
|
||||
onClose={() => setRegisterOpen(false)}
|
||||
onDone={(u, k) => { setUsername(u); setKey(k); }}
|
||||
/>
|
||||
{/* Wishlist path: only when open registration is off AND the admin
|
||||
enabled access requests. They are mutually exclusive server-side. */}
|
||||
{!registrationOn && requestOn && (
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { ArrowLeft, ArrowRight, UserPlus } from "lucide-react";
|
||||
import { api } from "../lib/api.ts";
|
||||
import { useT } from "../lib/i18n.ts";
|
||||
import { navigate } from "../lib/route.ts";
|
||||
import { Button, CopyButton, Field, FlowerMark, Input, LangPicker, Spinner } from "./ui.tsx";
|
||||
|
||||
const PREFILL_KEY = "ka_login_prefill";
|
||||
|
||||
/** Full-page self-registration (/register). No boot splash on this route. */
|
||||
export function RegisterPage() {
|
||||
const { t } = useT();
|
||||
const [username, setUsername] = useState("");
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [key, setKey] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [registrationOn, setRegistrationOn] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
api.methods().then((m) => setRegistrationOn(m.registration)).catch(() => {});
|
||||
}, []);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const res = await api.register({
|
||||
username: username.trim().toLowerCase(),
|
||||
displayName: displayName.trim() || undefined,
|
||||
email: email.trim() || undefined,
|
||||
});
|
||||
setKey(res.key);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t("dlg.regFailed"));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function goLogin() {
|
||||
const u = username.trim().toLowerCase();
|
||||
if (key && u) {
|
||||
try {
|
||||
sessionStorage.setItem(PREFILL_KEY, JSON.stringify({ username: u, key }));
|
||||
} catch {
|
||||
// private mode — the login form just stays empty
|
||||
}
|
||||
}
|
||||
navigate("/login");
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid min-h-full place-items-center overflow-y-auto bg-gradient-to-br from-stone-100 via-stone-50 to-accent-100/60 p-6 dark:from-zinc-950 dark:via-zinc-950 dark:to-accent-950/40">
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="rounded-[2rem] border border-white/60 bg-white/80 p-8 shadow-2xl shadow-accent-900/5 backdrop-blur-xl dark:border-zinc-700/60 dark:bg-zinc-900/80">
|
||||
<div className="mb-2 flex flex-col items-center text-center">
|
||||
<FlowerMark size={68} dynamic={false} className="mb-4 drop-shadow-lg" />
|
||||
<h1 className="text-2xl font-bold tracking-tight">{t("dlg.registerTitle")}</h1>
|
||||
</div>
|
||||
|
||||
{key ? (
|
||||
<div className="mt-6 space-y-4">
|
||||
<p className="text-center text-sm opacity-80">
|
||||
{t("dlg.regWelcome", { user: username.trim().toLowerCase() })}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="min-w-0 flex-1 truncate rounded-2xl bg-stone-100 px-3 py-2.5 text-sm dark:bg-zinc-800">{key}</code>
|
||||
<CopyButton text={key} />
|
||||
</div>
|
||||
<Button variant="gradient" size="lg" className="w-full" onClick={goLogin}>
|
||||
{t("dlg.regContinue")} <ArrowRight size={17} />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={submit} className="mt-6 space-y-3">
|
||||
<Field label={t("common.username")}>
|
||||
<Input
|
||||
variant="soft"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="alice"
|
||||
maxLength={32}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("common.displayName")}>
|
||||
<Input
|
||||
variant="soft"
|
||||
value={displayName}
|
||||
onChange={(e) => setDisplayName(e.target.value)}
|
||||
placeholder="Alice"
|
||||
maxLength={60}
|
||||
autoComplete="nickname"
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("dlg.emailOpt")}>
|
||||
<Input
|
||||
variant="soft"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="[email protected]"
|
||||
inputMode="email"
|
||||
autoComplete="email"
|
||||
/>
|
||||
</Field>
|
||||
{error && (
|
||||
<p className="rounded-full bg-red-500/10 px-5 py-2.5 text-center text-sm text-red-600 dark:text-red-400" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="gradient"
|
||||
size="lg"
|
||||
className="w-full"
|
||||
disabled={busy || !registrationOn}
|
||||
title={registrationOn ? undefined : t("login.regTipOff")}
|
||||
>
|
||||
{busy ? <Spinner /> : (<><UserPlus size={16} /> {t("login.register")}</>)}
|
||||
</Button>
|
||||
{!registrationOn && (
|
||||
<p className="text-center text-sm opacity-60">{t("login.regTipOff")}</p>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => navigate("/login")}
|
||||
className="mt-4 inline-flex w-full items-center justify-center gap-1.5 text-center text-sm opacity-60 transition hover:opacity-100 hover:underline"
|
||||
>
|
||||
<ArrowLeft size={15} />
|
||||
{t("common.backToLogin")}
|
||||
</button>
|
||||
|
||||
<div className="mt-4 flex justify-center">
|
||||
<LangPicker />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Archive, ArchiveRestore, Eye, Fingerprint, Globe, FileText, ImagePlus, KeyRound, Link2, Mail, Palette, Pencil, ScanText, Search, Settings2, ShieldCheck, Sparkles, Tag, Trash2, Unplug, User as UserIcon, UserPlus, X } from "lucide-react";
|
||||
import { Archive, ArchiveRestore, Eye, Fingerprint, Globe, FileText, ImagePlus, KeyRound, Link2, Mail, Palette, Pencil, ScanText, Search, Settings2, ShieldCheck, Sparkles, Tag, Trash2, Unplug, User as UserIcon, X } from "lucide-react";
|
||||
import { api } from "../lib/api.ts";
|
||||
import { cn } from "../lib/cn.ts";
|
||||
import { ACCENT_PRESETS, applyAccent, currentAccent, previewAccent, type AccentState } from "../lib/accent.ts";
|
||||
@@ -204,91 +204,6 @@ export function FilePreviewModal({
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Self-registration ---------- */
|
||||
|
||||
export function RegisterDialog({
|
||||
open,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onDone: (username: string, key: string) => void;
|
||||
}) {
|
||||
const { t } = useT();
|
||||
const [username, setUsername] = useState("");
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [key, setKey] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setUsername("");
|
||||
setDisplayName("");
|
||||
setEmail("");
|
||||
setKey(null);
|
||||
setError("");
|
||||
}
|
||||
}, [open ]);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const res = await api.register({
|
||||
username: username.trim().toLowerCase(),
|
||||
displayName: displayName.trim() || undefined,
|
||||
email: email.trim() || undefined,
|
||||
});
|
||||
setKey(res.key);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t("dlg.regFailed"));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title={t("dlg.registerTitle")} icon={UserPlus}>
|
||||
{key ? (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm opacity-80">
|
||||
{t("dlg.regWelcome", { user: username.trim().toLowerCase() })}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="min-w-0 flex-1 truncate rounded-2xl bg-stone-100 px-3 py-2.5 text-sm dark:bg-zinc-800">{key}</code>
|
||||
<CopyButton text={key} />
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button size="sm" onClick={() => { onDone(username.trim().toLowerCase(), key); onClose(); }}>{t("dlg.regContinue")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<Field label={t("common.username")}>
|
||||
<Input value={username} onChange={(e) => setUsername(e.target.value)} placeholder="alice" maxLength={32} required />
|
||||
</Field>
|
||||
<Field label={t("common.displayName")}>
|
||||
<Input value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder="Alice" maxLength={60} />
|
||||
</Field>
|
||||
<Field label={t("dlg.emailOpt")}>
|
||||
<Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" inputMode="email" />
|
||||
</Field>
|
||||
{error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="secondary" size="sm" type="button" onClick={onClose}>{t("common.cancel")}</Button>
|
||||
<Button size="sm" type="submit" disabled={busy}>{busy ? <Spinner size={15} /> : t("login.register")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Share ---------- */
|
||||
|
||||
export function ShareModal({ conv, onClose }: { conv: Conversation | null; onClose: () => void }) {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
/** Tiny pathname router (no dependency): /login, /register, /chat, /. */
|
||||
|
||||
export function normalizePath(p: string): string {
|
||||
if (p.length > 1 && p.endsWith("/")) return p.slice(0, -1);
|
||||
return p || "/";
|
||||
}
|
||||
|
||||
export function getPath(): string {
|
||||
return normalizePath(window.location.pathname);
|
||||
}
|
||||
|
||||
/** Client-side navigation without reload (same-origin path only). */
|
||||
export function navigate(to: string, replace = false): void {
|
||||
const dest = normalizePath(to);
|
||||
if (getPath() === dest) return;
|
||||
if (replace) window.history.replaceState(null, "", dest);
|
||||
else window.history.pushState(null, "", dest);
|
||||
window.dispatchEvent(new PopStateEvent("popstate"));
|
||||
}
|
||||
|
||||
export function useRoute(): string {
|
||||
const [route, setRoute] = useState(getPath);
|
||||
useEffect(() => {
|
||||
const h = () => setRoute(getPath());
|
||||
window.addEventListener("popstate", h);
|
||||
return () => window.removeEventListener("popstate", h);
|
||||
}, []);
|
||||
return route;
|
||||
}
|
||||
Reference in New Issue
Block a user