Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(app): rebuild sign-in in the Activepieces layout with email codes

spacesdriveca0aedfbf340
diff --git a/frontend/src/components/GoogleSignInButton.tsx b/frontend/src/components/GoogleSignInButton.tsx
index 6140f80..8d65936 100644
--- a/frontend/src/components/GoogleSignInButton.tsx
+++ b/frontend/src/components/GoogleSignInButton.tsx
@@ -1,7 +1,6 @@
import { useEffect, useRef, useState } from 'react';
-import { useTheme } from 'next-themes';
import { Skeleton } from '@/components/ui/skeleton';
-import { GOOGLE_CLIENT_ID, createNonce, loadGoogleIdentity } from '@/lib/googleIdentity';
+import { GOOGLE_CLIENT_ID, createNonce, googleButtonLabel, loadGoogleIdentity } from '@/lib/googleIdentity';
import type { GoogleButtonConfiguration } from '@/lib/googleIdentity';
// Google renders its own button inside an iframe; its width is capped at 400px by Google.
@@ -13,10 +12,12 @@ export interface GoogleSignInButtonProps {
text?: GoogleButtonConfiguration['text'];
}
+// Google's own button cannot take the app's style (in dark mode it puts the G on a white square), so the app draws
+// an outline button and lays Google's real button over it, nearly transparent: clicks, keyboard focus and the
+// sign-in itself stay Google's, and hover and focus show on the button underneath
export default function GoogleSignInButton({ onCredential, onError, text = 'continue_with' }: GoogleSignInButtonProps) {
const containerRef = useRef<HTMLDivElement>(null);
const handlers = useRef({ onCredential, onError });
- const { resolvedTheme } = useTheme();
const [ready, setReady] = useState(false);
useEffect(() => {
@@ -40,7 +41,7 @@ export default function GoogleSignInButton({ onCredential, onError, text = 'cont
containerRef.current.replaceChildren();
gsi.renderButton(containerRef.current, {
type: 'standard',
- theme: resolvedTheme === 'dark' ? 'filled_black' : 'outline',
+ theme: 'outline',
size: 'large',
shape: 'rectangular',
text,
@@ -54,14 +55,21 @@ export default function GoogleSignInButton({ onCredential, onError, text = 'cont
})();
return () => { cancelled = true; };
- }, [resolvedTheme, text]);
+ }, [text]);
if (!GOOGLE_CLIENT_ID) return null;
return (
- <div className="relative min-h-10 w-full">
- {!ready && <Skeleton className="absolute inset-0 h-10 rounded-control" />}
- <div ref={containerRef} className="flex w-full justify-center [color-scheme:normal]" />
+ <div className="group relative h-(--control-h-lg) w-full">
+ <span
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-0 flex items-center justify-center gap-2.5 rounded-control border border-line-control bg-surface-raised text-sm font-medium text-ink shadow-sm transition-colors duration-(--duration-base) group-hover:bg-surface-hover group-has-[iframe:focus]:ring-3 group-has-[iframe:focus]:ring-ring/50"
+ >
+ <img src="/icons/google-g.svg" alt="" className="size-4.5" draggable={false} />
+ {googleButtonLabel(text)}
+ </span>
+ {!ready && <Skeleton className="absolute inset-0 rounded-control" />}
+ <div ref={containerRef} className="absolute inset-0 flex justify-center overflow-hidden opacity-[0.01] [color-scheme:normal]" />
</div>
);
}
diff --git a/frontend/src/context/AuthContext.tsx b/frontend/src/context/AuthContext.tsx
index c98bd66..e28e692 100644
--- a/frontend/src/context/AuthContext.tsx
+++ b/frontend/src/context/AuthContext.tsx
@@ -12,6 +12,8 @@ export interface AuthContextValue {
signUp: (email: string, password: string) => ReturnType<Auth['signUp']>;
verifySignUpCode: (email: string, code: string) => ReturnType<Auth['verifyOtp']>;
resendSignUpCode: (email: string) => ReturnType<Auth['resend']>;
+ sendSignInCode: (email: string) => ReturnType<Auth['signInWithOtp']>;
+ verifySignInCode: (email: string, code: string) => ReturnType<Auth['verifyOtp']>;
sendPasswordReset: (email: string) => ReturnType<Auth['resetPasswordForEmail']>;
verifyPasswordResetCode: (email: string, code: string) => ReturnType<Auth['verifyOtp']>;
updatePassword: (password: string) => ReturnType<Auth['updateUser']>;
@@ -35,16 +37,24 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const signIn = (email: string, password: string) =>
supabase.auth.signInWithPassword({ email, password });
+ // a password account, for instances that do not email sign-in codes; with Confirm email on, a code confirms it
const signUp = (email: string, password: string) =>
supabase.auth.signUp({ email, password });
- // the code from the confirmation email; a correct one confirms the address and signs the user in
const verifySignUpCode = (email: string, code: string) =>
supabase.auth.verifyOtp({ email, token: code, type: 'signup' });
const resendSignUpCode = (email: string) =>
supabase.auth.resend({ type: 'signup', email });
+ // emails a 6-digit code that signs the user in, creating the account the first time an address is used
+ const sendSignInCode = (email: string) =>
+ supabase.auth.signInWithOtp({ email, options: { shouldCreateUser: true } });
+
+ // a correct code also confirms an address that signed up with a password and never confirmed it
+ const verifySignInCode = (email: string, code: string) =>
+ supabase.auth.verifyOtp({ email, token: code, type: 'email' });
+
// the email's link signs the user in on Settings, where the Password section sets the new password
const sendPasswordReset = (email: string) =>
supabase.auth.resetPasswordForEmail(email, { redirectTo: `${window.location.origin}/settings` });
@@ -63,7 +73,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const signOut = () => supabase.auth.signOut();
return (
- <AuthContext.Provider value={{ session, user: session?.user ?? null, signIn, signUp, verifySignUpCode, resendSignUpCode, sendPasswordReset, verifyPasswordResetCode, updatePassword, signInWithGoogle, signOut }}>
+ <AuthContext.Provider value={{ session, user: session?.user ?? null, signIn, signUp, verifySignUpCode, resendSignUpCode, sendSignInCode, verifySignInCode, sendPasswordReset, verifyPasswordResetCode, updatePassword, signInWithGoogle, signOut }}>
{children}
</AuthContext.Provider>
);
diff --git a/frontend/src/lib/authErrors.ts b/frontend/src/lib/authErrors.ts
index 8aed3df..a307cea 100644
--- a/frontend/src/lib/authErrors.ts
+++ b/frontend/src/lib/authErrors.ts
@@ -7,15 +7,15 @@ export interface AuthErrorLike {
export interface EmailErrorNotice {
message: string;
- // true when no more codes can be emailed today, so Google sign-in is the way in
+ // true when no more codes can be emailed today, so Google or a password is the way in
emailLimitReached: boolean;
}
const WAIT_SECONDS = /\d+\s+seconds?/i;
-const LIMIT_WITH_GOOGLE = 'Twiligent has sent all the verification emails it can today. Sign in with Google instead, or try again tomorrow.';
+const LIMIT_WITH_GOOGLE = 'Twiligent has sent all the codes it can email today. Continue with Google or use your password instead, or try again tomorrow.';
const WRONG_CODE = 'The code is wrong or has expired. Check it, or send a new one.';
-const LIMIT_WITHOUT_GOOGLE = 'Twiligent has sent all the verification emails it can today. Try again tomorrow.';
+const LIMIT_WITHOUT_GOOGLE = 'Twiligent has sent all the codes it can email today. Use your password instead, or try again tomorrow.';
// Supabase's own email limit and the Worker's daily cap both answer 429; the per-address cap and the short wait between codes do too,
// but those messages already say what to do and Google would not help
diff --git a/frontend/src/lib/emailAddress.ts b/frontend/src/lib/emailAddress.ts
new file mode 100644
index 0000000..71cc02d
--- /dev/null
+++ b/frontend/src/lib/emailAddress.ts
@@ -0,0 +1,6 @@
+// enough of a check to enable the Continue button: something, an @, a dot in the domain; Supabase checks the rest
+const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
+
+export function looksLikeEmail(value: string): boolean {
+ return EMAIL_SHAPE.test(value.trim());
+}
diff --git a/frontend/src/lib/googleIdentity.ts b/frontend/src/lib/googleIdentity.ts
index 92856c9..6dfcb6d 100644
--- a/frontend/src/lib/googleIdentity.ts
+++ b/frontend/src/lib/googleIdentity.ts
@@ -14,6 +14,18 @@ export interface GoogleIdConfiguration {
export type GoogleButtonText = 'signin_with' | 'signup_with' | 'continue_with' | 'signin';
+const BUTTON_LABELS: Record<GoogleButtonText, string> = {
+ signin_with: 'Sign in with Google',
+ signup_with: 'Sign up with Google',
+ continue_with: 'Continue with Google',
+ signin: 'Sign in',
+};
+
+// the words Google's own button shows for each text option, for the button drawn in the app's style over it
+export function googleButtonLabel(text: GoogleButtonText): string {
+ return BUTTON_LABELS[text];
+}
+
export interface GoogleButtonConfiguration {
type?: 'standard' | 'icon';
theme?: 'outline' | 'filled_blue' | 'filled_black';
diff --git a/frontend/src/pages/Login.tsx b/frontend/src/pages/Login.tsx
index 1914465..6358ddc 100644
--- a/frontend/src/pages/Login.tsx
+++ b/frontend/src/pages/Login.tsx
@@ -1,100 +1,130 @@
-import { useState } from 'react';
+import { Suspense, lazy, useState } from 'react';
import type { FormEvent } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';
-import { BookOpen, MailWarning } from 'lucide-react';
+import { ArrowLeft, MailWarning } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
-import { Button } from '@/components/ui/button';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Logo } from '@/components/brand/Logo';
import GoogleSignInButton from '@/components/GoogleSignInButton';
-import type { GoogleButtonText } from '@/lib/googleIdentity';
import { GOOGLE_CLIENT_ID } from '@/lib/googleIdentity';
import { emailErrorNotice, isExistingAccount, passwordErrorMessage } from '@/lib/authErrors';
+import type { AuthErrorLike } from '@/lib/authErrors';
import { PASSWORD_MIN_LENGTH, newPasswordProblem } from '@/lib/passwords';
import { FieldRow } from '@/components/DetailPanel';
import { useCountdown } from './useCountdown';
-import type { AuthErrorLike } from '@/lib/authErrors';
-import LoginBrandPanel from './LoginBrandPanel';
-import LoginForm from './LoginForm';
+import LoginEmailStart from './LoginEmailStart';
+import LoginPasswordForm from './LoginPasswordForm';
import LoginCodeForm from './LoginCodeForm';
import LoginEmailForm from './LoginEmailForm';
import PasswordInput from './PasswordInput';
-import { LOGIN_COPY, PRIVACY_URL } from './loginCopy';
-import type { LoginMode } from './loginCopy';
-import { docsUrl } from '@/lib/docs';
-
-interface GoogleOptionProps {
- text: GoogleButtonText;
- onCredential: (idToken: string, nonce: string) => void;
-}
+import { LOGIN_COPY, PRIVACY_URL, SIGN_UP_TITLE } from './loginCopy';
+import type { LoginView } from './loginCopy';
-function GoogleOption({ text, onCredential }: GoogleOptionProps) {
- return (
- <div className="flex flex-col gap-6">
- <GoogleSignInButton
- text={text}
- onCredential={onCredential}
- onError={err => toast.error(err.message)}
- />
- <div className="flex items-center gap-3 text-caption font-medium tracking-[0.08em] text-ink-faint uppercase" role="separator" aria-label="or continue with email">
- <span className="h-px flex-1 bg-divider" />
- or
- <span className="h-px flex-1 bg-divider" />
- </div>
- </div>
- );
-}
+// the dashboard picture behind the card is decoration, so it loads after the card and never delays signing in
+const LoginBackdrop = lazy(() => import('./LoginBackdrop'));
// Supabase allows one email code a minute per address, so the resend button waits as long after each send
const RESEND_WAIT_SECONDS = 60;
-const FAILURE_PREFIX: Record<LoginMode, string> = {
- login: "Couldn't sign in.",
+const FAILURE_PREFIX: Record<LoginView, string> = {
+ start: "Couldn't send the code.",
+ code: "Couldn't sign in.",
+ password: "Couldn't sign in.",
signup: "Couldn't create the account.",
verify: "Couldn't confirm the email.",
forgot: "Couldn't send the code.",
reset: "Couldn't reset the password.",
};
+// where Back goes from each view
+const BACK_TO: Partial<Record<LoginView, LoginView>> = {
+ code: 'start',
+ password: 'start',
+ signup: 'start',
+ verify: 'start',
+ forgot: 'password',
+ reset: 'password',
+};
+
+function OrDivider() {
+ return (
+ <div className="my-4 flex items-center gap-3 text-sm text-ink-muted" role="separator" aria-label="or continue with email">
+ <span className="h-px flex-1 bg-line-strong/60" />
+ or
+ <span className="h-px flex-1 bg-line-strong/60" />
+ </div>
+ );
+}
+
+const QUIET_LINK =
+ 'rounded-sm text-caption text-ink-muted transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring';
+
+// the Activepieces sign-in in Twiligent's brand: one card over a blurred picture of the app, Google first,
+// then an email that receives a sign-in code, with the password behind a quiet link
export default function Login() {
const {
- signIn, signUp, verifySignUpCode, resendSignUpCode, sendPasswordReset, verifyPasswordResetCode, updatePassword, signInWithGoogle,
+ signIn, signUp, verifySignUpCode, resendSignUpCode, sendSignInCode, verifySignInCode, sendPasswordReset, verifyPasswordResetCode,
+ updatePassword, signInWithGoogle,
} = useAuth();
const navigate = useNavigate();
- // the public site's Get started buttons open /login?mode=signup
const [params] = useSearchParams();
- const [mode, setMode] = useState<LoginMode>(params.get('mode') === 'signup' ? 'signup' : 'login');
+ const signingUp = params.get('mode') === 'signup';
+ const [view, setView] = useState<LoginView>('start');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [code, setCode] = useState('');
- // kept here, above the keyed panel, so only the mode switch link resets it
const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false);
const [resending, setResending] = useState(false);
const [resendIn, startResendWait] = useCountdown();
const [emailLimitMessage, setEmailLimitMessage] = useState<string | null>(null);
- const isLogin = mode === 'login';
- const copy = LOGIN_COPY[mode];
+ const copy = LOGIN_COPY[view];
+ const title = view === 'start' && signingUp ? SIGN_UP_TITLE : copy.title;
+ const back = BACK_TO[view];
+
+ function showView(next: LoginView) {
+ setView(next);
+ setShowPassword(false);
+ }
- function openCodeStep(nextMode: 'verify' | 'reset', justSent: boolean) {
+ function openCodeStep(next: 'code' | 'verify' | 'reset') {
setCode('');
- startResendWait(justSent ? RESEND_WAIT_SECONDS : 0);
- setMode(nextMode);
+ startResendWait(RESEND_WAIT_SECONDS);
+ showView(next);
}
function showEmailError(prefix: string, err: unknown) {
const notice = emailErrorNotice(err as AuthErrorLike, !!GOOGLE_CLIENT_ID);
- // the warning above the Google button says it already
- if (notice.emailLimitReached) setEmailLimitMessage(notice.message);
- else toast.error(`${prefix} ${notice.message}`);
+ // the warning on the first view says it already, next to the ways in that still work
+ if (notice.emailLimitReached) {
+ setEmailLimitMessage(notice.message);
+ showView('start');
+ } else {
+ toast.error(`${prefix} ${notice.message}`);
+ }
+ }
+
+ async function submitStart() {
+ const { error } = await sendSignInCode(email.trim());
+ if (error) throw error;
+ openCodeStep('code');
}
- async function submitLogin() {
- const { error } = await signIn(email, password);
+ async function submitCode() {
+ const { error } = await verifySignInCode(email.trim(), code);
+ if (error) throw error;
+ navigate('/');
+ }
+
+ async function submitPassword() {
+ const { error } = await signIn(email.trim(), password);
+ // an address that signed up with a password and never confirmed it is confirmed by a sign-in code
if (error?.code === 'email_not_confirmed') {
- openCodeStep('verify', false);
- toast.info('Confirm your email to sign in. Enter the code from your sign-up email, or send a new one.');
+ const { error: sendError } = await sendSignInCode(email.trim());
+ if (sendError) throw sendError;
+ openCodeStep('code');
+ toast.info('Confirm your email to sign in. Enter the code we just sent.');
return;
}
if (error) throw error;
@@ -102,23 +132,23 @@ export default function Login() {
}
async function submitSignUp() {
- const { data, error } = await signUp(email, password);
+ const { data, error } = await signUp(email.trim(), password);
if (error) throw error;
- // email confirmation is off in Supabase, so the account is ready
+ // with Confirm email off the account is ready at once
if (data.session) {
navigate('/');
return;
}
if (isExistingAccount(data.user)) {
toast.error('This email already has an account. Sign in instead.');
- setMode('login');
+ showView('password');
return;
}
- openCodeStep('verify', true);
+ openCodeStep('verify');
}
async function submitSignUpCode() {
- const { error } = await verifySignUpCode(email, code);
+ const { error } = await verifySignUpCode(email.trim(), code);
if (error) throw error;
toast.success('Email confirmed');
navigate('/');
@@ -126,17 +156,17 @@ export default function Login() {
// Supabase answers the same whether or not the address has an account, so the message cannot say which
async function submitForgot() {
- const { error } = await sendPasswordReset(email);
+ const { error } = await sendPasswordReset(email.trim());
if (error) throw error;
setPassword('');
- openCodeStep('reset', true);
- toast.success(`If an account uses ${email}, a code is on its way.`);
+ openCodeStep('reset');
+ toast.success(`If an account uses ${email.trim()}, a code is on its way.`);
}
async function submitReset() {
const problem = newPasswordProblem(password, password);
if (problem) throw new Error(problem);
- const { error } = await verifyPasswordResetCode(email, code);
+ const { error } = await verifyPasswordResetCode(email.trim(), code);
if (error) throw error;
// the code has signed the user in, so a refused password is fixed from Settings instead of a new code
const { error: passwordError } = await updatePassword(password);
@@ -149,17 +179,23 @@ export default function Login() {
navigate('/');
}
- const SUBMIT: Record<LoginMode, () => Promise<void>> = {
- login: submitLogin, signup: submitSignUp, verify: submitSignUpCode, forgot: submitForgot, reset: submitReset,
+ const SUBMIT: Record<LoginView, () => Promise<void>> = {
+ start: submitStart,
+ code: submitCode,
+ password: submitPassword,
+ signup: submitSignUp,
+ verify: submitSignUpCode,
+ forgot: submitForgot,
+ reset: submitReset,
};
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
try {
- await SUBMIT[mode]();
+ await SUBMIT[view]();
} catch (err) {
- showEmailError(FAILURE_PREFIX[mode], err);
+ showEmailError(FAILURE_PREFIX[view], err);
} finally {
setLoading(false);
}
@@ -168,7 +204,13 @@ export default function Login() {
async function handleResend() {
setResending(true);
try {
- const { error } = mode === 'reset' ? await sendPasswordReset(email) : await resendSignUpCode(email);
+ const address = email.trim();
+ const { error } =
+ view === 'reset'
+ ? await sendPasswordReset(address)
+ : view === 'verify'
+ ? await resendSignUpCode(address)
+ : await sendSignInCode(address);
if (error) throw error;
startResendWait(RESEND_WAIT_SECONDS);
toast.success('New code sent');
@@ -179,11 +221,6 @@ export default function Login() {
}
}
- function switchMode(next: LoginMode) {
- setMode(next);
- setShowPassword(false);
- }
-
async function handleGoogleCredential(idToken: string, nonce: string) {
setLoading(true);
try {
@@ -198,36 +235,67 @@ export default function Login() {
}
return (
- <div className="grid min-h-svh bg-surface lg:grid-cols-[minmax(0,1fr)_minmax(0,1.05fr)]">
- <div className="flex min-h-svh flex-col px-6 py-6 sm:px-10">
- <header className="flex items-center justify-between">
- <Logo className="h-7" />
- <Button variant="ghost" size="sm" render={<a href={docsUrl()} />}>
- <BookOpen data-icon="inline-start" />
- Docs
- </Button>
- </header>
-
- <main className="flex flex-1 items-center justify-center py-12">
- <div key={mode} className="flex w-full max-w-[22.5rem] animate-fold-in flex-col gap-7">
- <div className="flex flex-col gap-2 text-center">
- <h1 className="font-heading text-[2rem] leading-tight font-semibold tracking-[-0.025em] text-ink">{copy.title}</h1>
- <p className="text-sm text-ink-muted">{copy.lead}</p>
- </div>
-
- {emailLimitMessage && !isLogin && (
- <Alert variant="warning">
- <MailWarning />
- <AlertTitle>Email codes are paused until tomorrow</AlertTitle>
- <AlertDescription>{emailLimitMessage}</AlertDescription>
- </Alert>
+ <div className="relative min-h-svh bg-surface">
+ <Suspense fallback={null}>
+ <LoginBackdrop />
+ </Suspense>
+ <div aria-hidden="true" className="fixed inset-0 bg-surface/70 backdrop-blur-[3px]" />
+ <main className="relative flex min-h-svh items-center justify-center p-4">
+ <section
+ aria-labelledby="login-title"
+ className="w-full max-w-[26rem] animate-in rounded-dialog border border-line bg-popover p-8 text-popover-foreground shadow-lg duration-(--duration-overlay) fade-in zoom-in-95 sm:p-9"
+ >
+ <div key={view} className="flex animate-in flex-col duration-200 fade-in">
+ <Logo className="mx-auto h-7" />
+ {back && (
+ <button type="button" onClick={() => showView(back)} className={`mx-auto mt-5 flex items-center gap-1 ${QUIET_LINK}`}>
+ <ArrowLeft className="size-3.5" />
+ Back
+ </button>
)}
+ <h1
+ id="login-title"
+ className="mt-6 mb-6 text-center font-heading text-[1.375rem] leading-snug font-semibold tracking-[-0.02em] text-balance text-ink"
+ >
+ {title}
+ </h1>
- {GOOGLE_CLIENT_ID && (mode === 'login' || mode === 'signup' || emailLimitMessage) && <GoogleOption text={copy.google} onCredential={handleGoogleCredential} />}
+ {view === 'start' && (
+ <>
+ {emailLimitMessage && (
+ <Alert variant="warning" className="mb-5">
+ <MailWarning />
+ <AlertTitle>Email codes are paused until tomorrow</AlertTitle>
+ <AlertDescription>{emailLimitMessage}</AlertDescription>
+ </Alert>
+ )}
+ {GOOGLE_CLIENT_ID && (
+ <>
+ <GoogleSignInButton
+ text={signingUp ? 'signup_with' : 'continue_with'}
+ onCredential={handleGoogleCredential}
+ onError={err => toast.error(err.message)}
+ />
+ <OrDivider />
+ </>
+ )}
+ <LoginEmailStart email={email} onEmailChange={setEmail} loading={loading} onSubmit={handleSubmit} />
+ <button type="button" onClick={() => showView('password')} className={`mx-auto mt-5 ${QUIET_LINK}`}>
+ Use password
+ </button>
+ <p className="mt-8 border-t border-line-strong/60 pt-5 text-center text-[0.6875rem] leading-relaxed text-ink-muted">
+ By continuing, you agree to the{' '}
+ <a href={PRIVACY_URL} target="_blank" rel="noopener noreferrer" className="underline underline-offset-4 hover:text-ink">
+ privacy policy
+ </a>
+ .
+ </p>
+ </>
+ )}
- {mode === 'login' || mode === 'signup' ? (
- <LoginForm
- isLogin={isLogin}
+ {(view === 'password' || view === 'signup') && (
+ <LoginPasswordForm
+ isSignUp={view === 'signup'}
copy={copy}
email={email}
password={password}
@@ -237,14 +305,19 @@ export default function Login() {
onTogglePassword={() => setShowPassword(visible => !visible)}
loading={loading}
onSubmit={handleSubmit}
- onForgotPassword={isLogin ? () => switchMode('forgot') : undefined}
+ onForgotPassword={() => showView('forgot')}
+ onSwitch={() => showView(view === 'signup' ? 'password' : 'signup')}
/>
- ) : mode === 'forgot' ? (
+ )}
+
+ {view === 'forgot' && (
<LoginEmailForm copy={copy} email={email} onEmailChange={setEmail} loading={loading} onSubmit={handleSubmit} />
- ) : (
+ )}
+
+ {(view === 'code' || view === 'verify' || view === 'reset') && (
<LoginCodeForm
copy={copy}
- email={email}
+ email={email.trim()}
code={code}
onCodeChange={setCode}
loading={loading}
@@ -252,9 +325,9 @@ export default function Login() {
resendIn={resendIn}
resending={resending}
onResend={handleResend}
- ready={mode === 'verify' || password.length >= PASSWORD_MIN_LENGTH}
+ ready={view !== 'reset' || password.length >= PASSWORD_MIN_LENGTH}
>
- {mode === 'reset' && (
+ {view === 'reset' && (
<FieldRow label="New password" htmlFor="password">
<PasswordInput
id="password"
@@ -269,30 +342,9 @@ export default function Login() {
)}
</LoginCodeForm>
)}
-
- <p className="text-center text-sm text-ink-muted">
- {copy.switchPrompt}{' '}
- <button
- type="button"
- onClick={() => switchMode(copy.switchTo)}
- className="rounded-sm font-medium text-brand-text underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
- >
- {copy.switchAction}
- </button>
- </p>
</div>
- </main>
-
- <footer className="flex flex-col items-center gap-2 text-center text-caption text-ink-faint sm:flex-row sm:justify-between sm:text-left">
- <p>
- By continuing you agree to the{' '}
- <a href={PRIVACY_URL} target="_blank" rel="noopener noreferrer" className="underline underline-offset-4 hover:text-ink-muted">privacy policy</a>.
- </p>
- <p>&copy; {new Date().getFullYear()} Twiligent</p>
- </footer>
- </div>
-
- <LoginBrandPanel />
+ </section>
+ </main>
</div>
);
}
diff --git a/frontend/src/pages/LoginBackdrop.tsx b/frontend/src/pages/LoginBackdrop.tsx
new file mode 100644
index 0000000..0ae2c7b
--- /dev/null
+++ b/frontend/src/pages/LoginBackdrop.tsx
@@ -0,0 +1,110 @@
+import { Eye, Heart, MessageCircle, Users } from 'lucide-react';
+import { Logo } from '@/components/brand/Logo';
+import PageHeader from '@/components/PageHeader';
+import MetricBox from '@/components/MetricBox';
+import SurfaceBox from '@/components/SurfaceBox';
+import ListRow, { RankNumber } from '@/components/ListRow';
+import MetricAreaChart from '@/components/MetricAreaChart';
+import { PlatformIcon } from '@/components/platform';
+import { NAV_GROUPS } from '@/layout/navigation';
+import { cn } from '@/lib/utils';
+
+// sample figures for a picture of the Overview; nothing here is read from an account
+const METRICS = [
+ { label: 'Audience', value: '151,265', trend: 3.1, icon: <Users />, highlight: true },
+ { label: 'Views', value: '1.9M', trend: 12.6, icon: <Eye /> },
+ { label: 'Likes', value: '84.7K', trend: 5.4, icon: <Heart /> },
+ { label: 'Comments', value: '6,213', trend: 2.2, icon: <MessageCircle /> },
+];
+const ACCOUNTS = [
+ { platform: 'youtube', name: 'Northwind Kitchen', value: '84,213' },
+ { platform: 'instagram', name: '@northwind.kitchen', value: '31,702' },
+ { platform: 'youtube', name: 'Northwind Shorts', value: '22,940' },
+ { platform: 'reddit', name: 'u/northwind_cooks', value: '12,410' },
+];
+const WEEKS = [128, 130, 131, 134, 137, 138, 141, 144, 145, 148, 150, 151].map((value, i) => ({
+ name: `W${i + 1}`,
+ value: value * 1000,
+}));
+
+// the dashboard behind the sign-in card, built from the app's own components with sample figures, the way
+// Activepieces shows its app behind its sign-in; hidden from assistive technology and the pointer, loaded after the card
+export default function LoginBackdrop() {
+ return (
+ <div
+ aria-hidden="true"
+ className="pointer-events-none fixed inset-0 flex animate-in overflow-hidden duration-500 select-none fade-in"
+ >
+ <aside className="hidden w-(--sidebar-w) shrink-0 flex-col gap-5 border-r border-sidebar-border bg-sidebar px-3 py-4 md:flex">
+ <Logo className="ml-2 h-6" />
+ {NAV_GROUPS.map(group => (
+ <div key={group.label} className="flex flex-col gap-0.5">
+ <p className="px-2 pb-1 text-caption font-medium text-ink-faint">{group.label}</p>
+ {group.items.map((item, i) => {
+ const Icon = item.icon;
+ const active = group === NAV_GROUPS[0] && i === 0;
+ return (
+ <span
+ key={item.path}
+ className={cn(
+ 'flex h-(--nav-row-h) items-center gap-2.5 rounded-row px-2 text-sm',
+ active ? 'bg-sidebar-accent font-medium text-ink' : 'text-ink-muted',
+ )}
+ >
+ <Icon className="size-[18px]" strokeWidth={1.75} />
+ {item.label}
+ </span>
+ );
+ })}
+ </div>
+ ))}
+ </aside>
+
+ <div className="flex min-w-0 flex-1 flex-col bg-surface">
+ <div className="flex h-(--topbar-h) shrink-0 items-center border-b border-line px-6 text-sm font-medium text-ink">
+ Overview
+ </div>
+ <main className="flex flex-col gap-6 p-8">
+ <PageHeader
+ size="display"
+ title="Good morning, Asha"
+ description="4 accounts across YouTube, Instagram and Reddit"
+ />
+ <div className="grid grid-cols-2 gap-4 xl:grid-cols-4">
+ {METRICS.map(metric => (
+ <MetricBox
+ key={metric.label}
+ icon={metric.icon}
+ label={metric.label}
+ value={metric.value}
+ trend={metric.trend}
+ trendLabel="this month"
+ highlight={metric.highlight}
+ />
+ ))}
+ </div>
+ <div className="grid gap-4 lg:grid-cols-[1fr_22rem]">
+ <SurfaceBox title="Audience" subheader="Last 12 weeks">
+ <MetricAreaChart data={WEEKS} dataKey="value" label="Audience" height={260} />
+ </SurfaceBox>
+ <SurfaceBox title="Top accounts" subheader="By audience" className="hidden lg:flex">
+ {ACCOUNTS.map((account, i) => (
+ <ListRow
+ key={account.name}
+ leading={<RankNumber rank={i + 1} />}
+ title={
+ <span className="flex items-center gap-2">
+ <PlatformIcon platform={account.platform} />
+ {account.name}
+ </span>
+ }
+ trailing={<span className="font-mono text-small text-ink-muted">{account.value}</span>}
+ />
+ ))}
+ </SurfaceBox>
+ </div>
+ </main>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/pages/LoginCodeForm.tsx b/frontend/src/pages/LoginCodeForm.tsx
index a525b50..e55255a 100644
--- a/frontend/src/pages/LoginCodeForm.tsx
+++ b/frontend/src/pages/LoginCodeForm.tsx
@@ -1,5 +1,5 @@
import type { FormEvent, ReactNode } from 'react';
-import { ArrowRight, RotateCw } from 'lucide-react';
+import { RotateCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
@@ -52,7 +52,6 @@ export default function LoginCodeForm({
<Button type="submit" size="lg" className="mt-2 w-full" disabled={loading || !ready || code.length !== CODE_LENGTH}>
{loading && <Spinner className="size-4" />}
{loading ? copy.busy : copy.submit}
- {!loading && <ArrowRight data-icon="inline-end" />}
</Button>
<Button type="button" variant="ghost" size="sm" className="self-center" onClick={onResend} disabled={resending || resendIn > 0}>
{resending ? <Spinner className="size-4" /> : <RotateCw data-icon="inline-start" />}
diff --git a/frontend/src/pages/LoginEmailForm.tsx b/frontend/src/pages/LoginEmailForm.tsx
index 7cb99b3..fc5d95d 100644
--- a/frontend/src/pages/LoginEmailForm.tsx
+++ b/frontend/src/pages/LoginEmailForm.tsx
@@ -1,5 +1,4 @@
import type { FormEvent } from 'react';
-import { ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
@@ -33,7 +32,6 @@ export default function LoginEmailForm({ copy, email, onEmailChange, loading, on
<Button type="submit" size="lg" className="mt-2 w-full" disabled={loading}>
{loading && <Spinner className="size-4" />}
{loading ? copy.busy : copy.submit}
- {!loading && <ArrowRight data-icon="inline-end" />}
</Button>
</form>
);
diff --git a/frontend/src/pages/LoginEmailStart.tsx b/frontend/src/pages/LoginEmailStart.tsx
new file mode 100644
index 0000000..bc907e8
--- /dev/null
+++ b/frontend/src/pages/LoginEmailStart.tsx
@@ -0,0 +1,51 @@
+import type { FormEvent } from 'react';
+import { ArrowRight, Mail } from 'lucide-react';
+import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
+import { Spinner } from '@/components/ui/spinner';
+import { looksLikeEmail } from '@/lib/emailAddress';
+
+export interface LoginEmailStartProps {
+ email: string;
+ onEmailChange: (value: string) => void;
+ loading: boolean;
+ onSubmit: (e: FormEvent<HTMLFormElement>) => void;
+}
+
+// one field for the address with the Continue arrow inside it; the arrow wakes up once the address looks complete
+export default function LoginEmailStart({ email, onEmailChange, loading, onSubmit }: LoginEmailStartProps) {
+ return (
+ <form onSubmit={onSubmit}>
+ {/* the group dims itself when anything in it is disabled, and only the arrow should; its focus is one red border
+ with a faint halo instead of the default wide ring */}
+ <InputGroup className="h-12 rounded-field bg-surface-raised has-disabled:bg-surface-raised has-disabled:opacity-100 dark:has-disabled:bg-surface-raised has-[[data-slot=input-group-control]:focus-visible]:ring-2 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/15">
+ <InputGroupAddon>
+ <Mail className="ml-1.5 text-ink-faint" />
+ </InputGroupAddon>
+ <InputGroupInput
+ id="email"
+ type="email"
+ aria-label="Email"
+ placeholder="[email protected]"
+ value={email}
+ onChange={e => onEmailChange(e.target.value)}
+ required
+ autoComplete="email"
+ autoFocus
+ className="focus-visible:outline-none"
+ />
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ type="submit"
+ variant="default"
+ size="icon-sm"
+ className="mr-1.5 size-9 rounded-control"
+ aria-label="Continue with email"
+ disabled={loading || !looksLikeEmail(email)}
+ >
+ {loading ? <Spinner className="size-4" /> : <ArrowRight />}
+ </InputGroupButton>
+ </InputGroupAddon>
+ </InputGroup>
+ </form>
+ );
+}
diff --git a/frontend/src/pages/LoginPasswordForm.tsx b/frontend/src/pages/LoginPasswordForm.tsx
new file mode 100644
index 0000000..4b7f3af
--- /dev/null
+++ b/frontend/src/pages/LoginPasswordForm.tsx
@@ -0,0 +1,91 @@
+import type { FormEvent } from 'react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Spinner } from '@/components/ui/spinner';
+import { FieldRow } from '@/components/DetailPanel';
+import { PASSWORD_MIN_LENGTH } from '@/lib/passwords';
+import PasswordInput from './PasswordInput';
+import type { LoginCopy } from './loginCopy';
+
+export interface LoginPasswordFormProps {
+ // false signs in, true creates a password account
+ isSignUp: boolean;
+ copy: LoginCopy;
+ email: string;
+ password: string;
+ onEmailChange: (value: string) => void;
+ onPasswordChange: (value: string) => void;
+ showPassword: boolean;
+ onTogglePassword: () => void;
+ loading: boolean;
+ onSubmit: (e: FormEvent<HTMLFormElement>) => void;
+ onForgotPassword: () => void;
+ // between signing in and creating an account
+ onSwitch: () => void;
+}
+
+export default function LoginPasswordForm({
+ isSignUp,
+ copy,
+ email,
+ password,
+ onEmailChange,
+ onPasswordChange,
+ showPassword,
+ onTogglePassword,
+ loading,
+ onSubmit,
+ onForgotPassword,
+ onSwitch,
+}: LoginPasswordFormProps) {
+ const quietLink =
+ 'rounded-sm text-caption text-ink-muted transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring';
+ return (
+ <form onSubmit={onSubmit} className="flex flex-col gap-4">
+ <FieldRow label="Email" htmlFor="email">
+ <Input
+ id="email"
+ type="email"
+ className="h-(--control-h-lg)"
+ placeholder="[email protected]"
+ value={email}
+ onChange={e => onEmailChange(e.target.value)}
+ required
+ autoComplete="email"
+ autoFocus={!email}
+ />
+ </FieldRow>
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <label htmlFor="password" className="text-sm font-medium text-ink">
+ Password
+ </label>
+ {!isSignUp && (
+ <button type="button" onClick={onForgotPassword} className={quietLink}>
+ Forgot your password?
+ </button>
+ )}
+ </div>
+ <PasswordInput
+ id="password"
+ value={password}
+ onChange={onPasswordChange}
+ placeholder={isSignUp ? `At least ${PASSWORD_MIN_LENGTH} characters` : 'Your password'}
+ autoComplete={isSignUp ? 'new-password' : 'current-password'}
+ showPassword={showPassword}
+ onTogglePassword={onTogglePassword}
+ />
+ </div>
+ <Button type="submit" size="lg" className="mt-1 w-full" disabled={loading}>
+ {loading && <Spinner className="size-4" />}
+ {loading ? copy.busy : copy.submit}
+ </Button>
+ <p className="text-center text-caption text-ink-muted">
+ {isSignUp ? 'Already have an account?' : 'No account yet?'}{' '}
+ <button type="button" onClick={onSwitch} className={`font-medium text-ink ${quietLink}`}>
+ {isSignUp ? 'Sign in' : 'Create one with a password'}
+ </button>
+ </p>
+ </form>
+ );
+}
diff --git a/frontend/src/pages/loginCopy.ts b/frontend/src/pages/loginCopy.ts
index dc86c37..8a5ccbb 100644
--- a/frontend/src/pages/loginCopy.ts
+++ b/frontend/src/pages/loginCopy.ts
@@ -1,72 +1,25 @@
-import type { GoogleButtonText } from '@/lib/googleIdentity';
-
export const PRIVACY_URL = 'https://blog.ujjwal.fyi/privacy/';
-// verify is the code step after sign-up, or after signing in with an email that is not confirmed yet;
+// start takes an email for a sign-in code, code checks that code, password is the email and password sign-in;
+// signup makes a password account and verify takes the code that confirms it, for instances without sign-in codes;
// forgot asks for the email of a forgotten password, and reset takes the emailed code and the new password
-export type LoginMode = 'login' | 'signup' | 'verify' | 'forgot' | 'reset';
+export type LoginView = 'start' | 'code' | 'password' | 'signup' | 'verify' | 'forgot' | 'reset';
export interface LoginCopy {
title: string;
- lead: string;
submit: string;
busy: string;
- switchPrompt: string;
- switchAction: string;
- // where the link under the form goes
- switchTo: LoginMode;
- google: GoogleButtonText;
}
-export const LOGIN_COPY: Record<LoginMode, LoginCopy> = {
- login: {
- title: 'Welcome back',
- lead: 'Sign in to see every channel in one place.',
- submit: 'Sign in',
- busy: 'Signing in',
- switchPrompt: 'New to Twiligent?',
- switchAction: 'Create an account',
- switchTo: 'signup',
- google: 'continue_with',
- },
- signup: {
- title: 'Create your account',
- lead: 'Start with Google, or use an email and a password of at least 6 characters.',
- submit: 'Create account',
- busy: 'Creating account',
- switchPrompt: 'Already have an account?',
- switchAction: 'Sign in',
- switchTo: 'login',
- google: 'signup_with',
- },
- verify: {
- title: 'Check your email',
- lead: 'Enter the 6-digit code we emailed you to confirm your address.',
- submit: 'Confirm email',
- busy: 'Confirming',
- switchPrompt: 'Wrong address?',
- switchAction: 'Start again',
- switchTo: 'signup',
- google: 'continue_with',
- },
- forgot: {
- title: 'Reset your password',
- lead: 'Enter the email you sign in with. We will email you a 6-digit code.',
- submit: 'Send code',
- busy: 'Sending',
- switchPrompt: 'Remembered it?',
- switchAction: 'Back to sign in',
- switchTo: 'login',
- google: 'continue_with',
- },
- reset: {
- title: 'Choose a new password',
- lead: 'Enter the code we emailed you and the password you want to use from now on.',
- submit: 'Save password and sign in',
- busy: 'Saving',
- switchPrompt: 'Remembered it?',
- switchAction: 'Back to sign in',
- switchTo: 'login',
- google: 'continue_with',
- },
+export const LOGIN_COPY: Record<LoginView, LoginCopy> = {
+ start: { title: 'Every channel, folded into one clear picture.', submit: 'Continue', busy: 'Sending code' },
+ code: { title: 'Check your email', submit: 'Continue', busy: 'Checking' },
+ password: { title: 'Sign in with password', submit: 'Sign in', busy: 'Signing in' },
+ signup: { title: 'Create an account with a password', submit: 'Create account', busy: 'Creating account' },
+ verify: { title: 'Confirm your email', submit: 'Confirm email', busy: 'Confirming' },
+ forgot: { title: 'Reset your password', submit: 'Send code', busy: 'Sending' },
+ reset: { title: 'Choose a new password', submit: 'Save password and sign in', busy: 'Saving' },
};
+
+// the public site's Get started buttons open /login?mode=signup; the same code creates the account
+export const SIGN_UP_TITLE = 'Create your Twiligent account';
diff --git a/frontend/tests/lib/authErrors.test.ts b/frontend/tests/lib/authErrors.test.ts
index f8aec5c..d72c683 100644
--- a/frontend/tests/lib/authErrors.test.ts
+++ b/frontend/tests/lib/authErrors.test.ts
@@ -2,19 +2,21 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { cleanCode, emailErrorNotice, isExistingAccount, passwordErrorMessage } from '../../src/lib/authErrors.ts';
+// the Worker's daily cap message, which the page replaces with its own
const WORKER_LIMIT = 'Twiligent has sent all the verification emails it can today. Sign in with Google instead, or try again tomorrow.';
+const WITH_GOOGLE = 'Twiligent has sent all the codes it can email today. Continue with Google or use your password instead, or try again tomorrow.';
-test('the daily cap points to Google when the Google button is on the page', () => {
- assert.deepEqual(emailErrorNotice({ message: WORKER_LIMIT, status: 429 }, true), { message: WORKER_LIMIT, emailLimitReached: true });
+test('the daily cap points to Google and the password when the Google button is on the page', () => {
+ assert.deepEqual(emailErrorNotice({ message: WORKER_LIMIT, status: 429 }, true), { message: WITH_GOOGLE, emailLimitReached: true });
assert.deepEqual(emailErrorNotice({ message: WORKER_LIMIT, status: 429 }, false), {
- message: 'Twiligent has sent all the verification emails it can today. Try again tomorrow.',
+ message: 'Twiligent has sent all the codes it can email today. Use your password instead, or try again tomorrow.',
emailLimitReached: true,
});
});
test('Supabase\'s own email limit reads the same way', () => {
const notice = emailErrorNotice({ message: 'email rate limit exceeded', status: 429, code: 'over_email_send_rate_limit' }, true);
- assert.deepEqual(notice, { message: WORKER_LIMIT, emailLimitReached: true });
+ assert.deepEqual(notice, { message: WITH_GOOGLE, emailLimitReached: true });
});
test('a short wait between codes and the per-address cap keep their own messages', () => {
diff --git a/frontend/tests/lib/emailAddress.test.ts b/frontend/tests/lib/emailAddress.test.ts
new file mode 100644
index 0000000..6a2d614
--- /dev/null
+++ b/frontend/tests/lib/emailAddress.test.ts
@@ -0,0 +1,14 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { looksLikeEmail } from '../../src/lib/emailAddress.ts';
+
+test('an address with a name, an @ and a domain with a dot is ready to continue', () => {
+ assert.equal(looksLikeEmail('[email protected]'), true);
+ assert.equal(looksLikeEmail(' [email protected] '), true);
+});
+
+test('a half-typed address is not', () => {
+ for (const value of ['', 'asha', 'asha@', 'asha@northwind', '[email protected]', 'a [email protected]']) {
+ assert.equal(looksLikeEmail(value), false, value);
+ }
+});
diff --git a/frontend/tests/lib/googleIdentity.test.ts b/frontend/tests/lib/googleIdentity.test.ts
index 70de8c3..10558e6 100644
--- a/frontend/tests/lib/googleIdentity.test.ts
+++ b/frontend/tests/lib/googleIdentity.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { createNonce, sha256Hex } from '../../src/lib/googleIdentity.ts';
+import { createNonce, googleButtonLabel, sha256Hex } from '../../src/lib/googleIdentity.ts';
test('sha256Hex matches the known digest', async () => {
assert.equal(await sha256Hex('abc'), 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
@@ -17,3 +17,8 @@ test('each nonce is different', async () => {
const [first, second] = await Promise.all([createNonce(), createNonce()]);
assert.notEqual(first.raw, second.raw);
});
+
+test('the drawn Google button says what the Google button would say', () => {
+ assert.equal(googleButtonLabel('continue_with'), 'Continue with Google');
+ assert.equal(googleButtonLabel('signup_with'), 'Sign up with Google');
+});