The signed-in account
Signing in, the person in the frame, their profile, signing out
This recipe draws SettingsPage arrangement="column"; the others (agent/layout-chooser.md) take the same slots. Your page fits another? Change the one prop:
sections(sections: many):subNava link to each section;sectionsmany.mode(sections: app-wide; Trail draws it assections):subNavevery settings area.tabs(sections: few):subNavtwo to five tabs.
Copy the file below whole (src/screens/account.tsx, say) beside frame.tsx (docs/screen-frame.md) and keep the parts and their props. It holds four things: the session, useSession() (the signed-in person, or null), with signIn, saveProfile and signOut; the sign-in screen; SignedInMenu, the person's account menu; and the profile screen. The session is the one piece you replace: the sample sign-in accepts any email and password, sends nothing, fetches nothing and keeps no password (the person's name is made from the address). A real app wires its own auth into signIn and signOut and reads its person in useSession; this file uses no auth library and no network.
In the app (docs/screen-app.md), this screen is one step: its three lines below go into App.tsx (the import beside the other screens', the route after the last route, and <SignedIn> round the screens), and an app with no sign-in leaves them out. <SignedIn> shows SignInScreen while useSession() is null, the screens once someone signs in; /profile is the default export. On its own, the default export is the same gate with the profile as its one screen. Signing out sets the session to null, so every screen goes back to the sign-in screen at once.
tsx app // src/App.tsx: the sign-in's three lines in the app recipe's App.tsx (start.mjs adds them with account`) import AccountScreen, { SignedIn } from './screens/account'; if (page === 'profile') return <AccountScreen />; <SignedIn>{screenFor(route)}</SignedIn>
Show the code443 lines
- **Sign in** stands outside the app frame (AuthPage: a centred card, no sidebar). Email and password are required,
each with its own error line under it, the email checked for a full address ("Enter your email.", "Enter a full
address, like you@example.com."); the first refused field takes the focus. Continue shows its spinner while
`signIn` runs; a refusal from your auth ("That email and password don't match.") shows as an alert over the fields.
The password field's button shows what was typed; a line says when Caps Lock is on. "Forgot your password?" goes to
your app's own page for it.
- **The person in the frame**: `SignedInMenu` in ScreenFrame's `account` (at the sidebar's foot, under the pages), a
row with the person's avatar, name and email. Enter, Space or ArrowDown opens it on its first row, ArrowUp on its
last; the arrows move and loop, Escape closes it. Inside: who is signed in, Profile, Settings
(`docs/screen-settings.md`, the settings screen itself; there while the frame's pages list `/settings`), Appearance
(System, Light, Dark: the same store as the top bar's switch) and Sign out; its links are routes of your router
(`hrefOf` from `./router`, `docs/screen-frame.md`).
`<SignedIn>` gives it to every screen's frame once (`<FrameAccount account={<SignedInMenu />}>`);
a screen on its own passes `account={<SignedInMenu />}`.
- **Profile** (SettingsPage): the photo (the avatar shows the person's initials until a picture is chosen; it stays
in this tab, nothing is uploaded), the name, the email and the time zone. Save changes is disabled until a value
differs; a refused field shows its error line and takes the focus; a save updates the session, so the account
menu shows the new name at once, and raises the theme's toast (`<Toaster />` once in `App.tsx`, as the frame
recipe says).
Light, dark, phone and desktop are the parts' own: add no class for them.
```tsx
// src/screens/account.tsx: signing in, the person’s menu and their profile
import { type ChangeEvent, type FormEvent, type ReactNode, useRef, useState, useSyncExternalStore } from 'react';
import { AuthPage } from '@/components/goop/patterns/auth-page';
import { SettingsPage } from '@/components/goop/patterns/settings-page';
import {
AccountMenu,
AccountMenuColorMode,
AccountMenuContent,
AccountMenuHeader,
AccountMenuSignOut,
AccountMenuTrigger,
} from '@/components/ui/goop/account-menu';
import { Alert, AlertDescription, AlertIcon, AlertTitle } from '@/components/ui/goop/alert';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/goop/avatar';
import { Button } from '@/components/ui/goop/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/goop/card';
import { DropdownMenuItem } from '@/components/ui/goop/dropdown-menu';
import { Field } from '@/components/ui/goop/field';
import { FieldInvalid } from '@/components/ui/goop/field-error';
import { Link } from '@/components/ui/goop/link';
import {
PageHeader,
PageHeaderActions,
PageHeaderContent,
PageHeaderDescription,
PageHeaderTitle,
} from '@/components/ui/goop/page-header';
import { PasswordField } from '@/components/ui/goop/password-field';
import {
Select,
SelectContent,
SelectIcon,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/goop/select';
import { TextInput } from '@/components/ui/goop/text-input';
import { ToastIndicator, toast } from '@/components/ui/goop/toast';
import { SAMPLE_BRAND } from '@/lib/goop/trail/sample-brand';
import { FrameAccount, hasPage, ScreenFrame, ScreenTopBar } from './frame';
import { hrefOf } from './router';
// ---- the session: the one piece you replace with your auth (move it to src/session.ts once a second file reads it)
/** The signed-in person: who the account menu and the profile show. */
type Person = { name: string; email: string; zone: string; photo: string | null };
let signedIn: Person | null = null;
const listeners = new Set<() => void>();
function setSession(next: Person | null) {
signedIn = next;
for (const listener of listeners) listener();
}
function subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/** The signed-in person, or null: every screen reads it. Your auth's own hook (its session) takes its place. */
export function useSession(): Person | null {
return useSyncExternalStore(subscribe, () => signedIn);
}
/** The sample's name for an address: "teodora.valk@fieldwork.test" signs in as Teodora Valk. */
function nameFrom(email: string): string {
const words = (email.split('@')[0] ?? '').split(/[._-]+/).filter(Boolean);
return words.map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(' ');
}
/**
* The SAMPLE sign-in: it accepts any email and password, sends nothing and keeps no password. Your app calls its own
* auth here and returns the refusal's words ("That email and password don't match.") or null once signed in.
*/
export async function signIn({ email }: { email: string; password: string }): Promise<string | null> {
setSession({ name: nameFrom(email), email, zone: 'Amsterdam (UTC+1)', photo: null });
return null;
}
/** Keeps the person's new details: your app sends them to its own service first. */
export function saveProfile(person: Person) {
setSession(person);
}
/** Signs the person out: every screen goes back to the sign-in screen. Your app ends its own session here too. */
export function signOut() {
setSession(null);
}
// ---- the sample data: swap it for yours
const ROUTES = { profile: '/profile', settings: '/settings', forgot: '/forgot-password' } as const;
const TIME_ZONES = [
'London (UTC+0)',
'Amsterdam (UTC+1)',
'Nairobi (UTC+3)',
'Singapore (UTC+8)',
'New York (UTC−5)',
] as const;
/** What each refused field says: what is wrong and how to put it right. */
const ERRORS = {
emailEmpty: 'Enter your email.',
emailFormat: 'Enter a full address, like you@example.com.',
passwordEmpty: 'Enter your password.',
nameEmpty: 'Enter your name: your team sees it beside everything you do.',
} as const;
/** A full address: something, one @, a name with a dot in it — the form's check, never the auth's. */
const FULL_ADDRESS = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function emailError(email: string): string | undefined {
const value = email.trim();
if (value === '') return ERRORS.emailEmpty;
return FULL_ADDRESS.test(value) ? undefined : ERRORS.emailFormat;
}
/** The profile, behind the sign-in screen while no one is signed in: App.tsx's `/profile`. */
export default function AccountScreens() {
const person = useSession();
return person ? <ProfileScreen person={person} /> : <SignInScreen />;
}
/** App.tsx's gate round the screens: signed out, the sign-in screen; signed in, every frame shows the person. */
export function SignedIn({ children }: { children: ReactNode }) {
const person = useSession();
if (!person) return <SignInScreen />;
return <FrameAccount account={<SignedInMenu />}>{children}</FrameAccount>;
}
/** The sign-in screen, outside the frame: App.tsx shows it while no one is signed in. */
export function SignInScreen() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
/** Errors show once a person has tried to sign in, and then follow what they type. */
const [tried, setTried] = useState(false);
const [busy, setBusy] = useState(false);
const [refusal, setRefusal] = useState<string | null>(null);
const emailRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
const refusals = () => ({ email: emailError(email), password: password === '' ? ERRORS.passwordEmpty : undefined });
const errors = tried ? refusals() : { email: undefined, password: undefined };
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setTried(true);
setRefusal(null);
const refused = refusals();
if (refused.email || refused.password) {
// the first refused field takes the focus, so it is read with its error
(refused.email ? emailRef : passwordRef).current?.focus();
return;
}
setBusy(true);
const said = await signIn({ email: email.trim(), password });
// signed in: the gate shows the app, and this screen (and what was typed) is gone
if (said === null) return;
setBusy(false);
setPassword('');
setRefusal(said);
passwordRef.current?.focus();
}
return (
<AuthPage>
<Card asChild variant="outline">
<form noValidate aria-labelledby="sign-in-title" onSubmit={submit}>
<CardHeader>
<div className="flex min-w-0 flex-col gap-1">
<CardTitle asChild>
<h1 id="sign-in-title">{`Sign in to ${SAMPLE_BRAND.name}`}</h1>
</CardTitle>
<CardDescription>Use your work email and password.</CardDescription>
</div>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{refusal ? (
<Alert variant="destructive">
<AlertIcon />
<AlertTitle>You are not signed in</AlertTitle>
<AlertDescription>{refusal}</AlertDescription>
</Alert>
) : null}
<Field label="Email" orientation="vertical" className="w-full">
{(control) => (
<FieldInvalid error={errors.email} className="grow">
<TextInput
{...control}
ref={emailRef}
type="email"
name="email"
autoComplete="email"
placeholder="you@example.com"
value={email}
onChange={(event) => setEmail(event.currentTarget.value)}
/>
</FieldInvalid>
)}
</Field>
<Field label="Password" orientation="vertical" className="w-full">
{(control) => (
<FieldInvalid error={errors.password} className="grow">
<PasswordField
{...control}
ref={passwordRef}
name="password"
purpose="current"
placeholder="Your password"
value={password}
onChange={(event) => setPassword(event.currentTarget.value)}
/>
</FieldInvalid>
)}
</Field>
<div className="flex justify-end text-base">
{/* A link standing alone in its row, not in a sentence: on a touch screen its box is the touch size high. */}
<Link
variant="primary"
href={hrefOf(ROUTES.forgot)}
className="touch:inline-flex touch:min-h-control-touch touch:items-center"
>
Forgot your password?
</Link>
</div>
<Button type="submit" size="lg" className="w-full" loading={busy} loadingLabel="Signing in">
Continue
</Button>
</CardContent>
</form>
</Card>
</AuthPage>
);
}
/** The signed-in person's menu, for ScreenFrame's `account` on every signed-in screen: the sidebar's foot. */
export function SignedInMenu() {
const person = useSession();
if (!person) return null;
return (
<AccountMenu>
<AccountMenuTrigger name={person.name} email={person.email} {...(person.photo ? { image: person.photo } : {})} />
<AccountMenuContent>
<AccountMenuHeader />
<DropdownMenuItem icon="user" asChild>
<a href={hrefOf(ROUTES.profile)}>Profile</a>
</DropdownMenuItem>
{hasPage(ROUTES.settings) ? (
<DropdownMenuItem icon="settings" asChild>
<a href={hrefOf(ROUTES.settings)}>Settings</a>
</DropdownMenuItem>
) : null}
<AccountMenuColorMode />
<AccountMenuSignOut onSelect={signOut} />
</AccountMenuContent>
</AccountMenu>
);
}
const same = (a: Person, b: Person) =>
a.name === b.name && a.email === b.email && a.zone === b.zone && a.photo === b.photo;
function ProfileScreen({ person }: { person: Person }) {
const [draft, setDraft] = useState<Person>(person);
/** Errors show once a person has tried to save, and then follow what they type. */
const [tried, setTried] = useState(false);
const nameRef = useRef<HTMLInputElement>(null);
const emailRef = useRef<HTMLInputElement>(null);
const chooser = useRef<HTMLInputElement>(null);
const refusals = (next: Person) => ({
name: next.name.trim() === '' ? ERRORS.nameEmpty : undefined,
email: emailError(next.email),
});
const errors = tried ? refusals(draft) : { name: undefined, email: undefined };
const change = (next: Partial<Person>) => setDraft((was) => ({ ...was, ...next }));
function choose(event: ChangeEvent<HTMLInputElement>) {
const file = event.currentTarget.files?.[0];
// the same file chosen twice still reads as a choice
event.currentTarget.value = '';
// the picture stays in this tab: your app uploads the file and keeps its address
if (file) change({ photo: URL.createObjectURL(file) });
}
function save() {
const refused = refusals(draft);
if (refused.name || refused.email) {
setTried(true);
(refused.name ? nameRef : emailRef).current?.focus();
return;
}
const kept = { ...draft, name: draft.name.trim(), email: draft.email.trim() };
saveProfile(kept);
setDraft(kept);
setTried(false);
toast({
title: 'Profile saved',
description: 'Your team sees the new details from now on.',
mark: <ToastIndicator icon="circle-check" />,
});
}
return (
<ScreenFrame current={ROUTES.profile} account={<SignedInMenu />}>
<SettingsPage
arrangement="column"
header={<ScreenTopBar title="Profile" />}
heading={
<PageHeader>
<PageHeaderContent>
<PageHeaderTitle asChild>
<h1>Your profile</h1>
</PageHeaderTitle>
<PageHeaderDescription>How you appear to everyone in the workspace.</PageHeaderDescription>
</PageHeaderContent>
<PageHeaderActions>
<Button size="lg" disabled={same(draft, person)} onClick={save}>
Save changes
</Button>
</PageHeaderActions>
</PageHeader>
}
sections={
<>
<section aria-labelledby="photo-title">
<PageHeader>
<PageHeaderContent>
<PageHeaderTitle asChild>
<h2 id="photo-title">Photo</h2>
</PageHeaderTitle>
<PageHeaderDescription>Shown beside your name in lists, comments and notices.</PageHeaderDescription>
</PageHeaderContent>
</PageHeader>
<Card variant="outline" asChild>
<ul>
<Field as="li" label="Your photo" description="A square picture works best">
{(control) => (
<div className="flex items-center gap-2">
<Avatar {...control} variant="solid" size="lg" name={draft.name || person.name}>
{draft.photo ? <AvatarImage src={draft.photo} alt="" /> : null}
<AvatarFallback>{draft.name || person.name}</AvatarFallback>
</Avatar>
<input
ref={chooser}
type="file"
accept="image/*"
aria-label="Your photo"
tabIndex={-1}
className="sr-only"
onChange={choose}
/>
<Button variant="outline" onClick={() => chooser.current?.click()}>
Upload photo
</Button>
<Button variant="ghost" disabled={draft.photo === null} onClick={() => change({ photo: null })}>
Remove photo
</Button>
</div>
)}
</Field>
</ul>
</Card>
</section>
<section aria-labelledby="details-title">
<PageHeader>
<PageHeaderContent>
<PageHeaderTitle asChild>
<h2 id="details-title">Details</h2>
</PageHeaderTitle>
<PageHeaderDescription>Your name, where your notices go and your clock.</PageHeaderDescription>
</PageHeaderContent>
</PageHeader>
<Card variant="outline" asChild>
<ul>
<Field as="li" label="Full name">
<FieldInvalid error={errors.name} className="grow">
<TextInput
ref={nameRef}
name="name"
autoComplete="name"
value={draft.name}
onChange={(event) => change({ name: event.currentTarget.value })}
/>
</FieldInvalid>
</Field>
<Field as="li" label="Email" description="Where your notices are sent">
<FieldInvalid error={errors.email} className="grow">
<TextInput
ref={emailRef}
type="email"
name="email"
autoComplete="email"
value={draft.email}
onChange={(event) => change({ email: event.currentTarget.value })}
/>
</FieldInvalid>
</Field>
<Field as="li" label="Time zone" description="Due dates and reminders follow this clock">
{(control) => (
<Select value={draft.zone} onValueChange={(zone) => change({ zone })}>
<SelectTrigger {...control}>
<SelectValue />
<SelectIcon />
</SelectTrigger>
<SelectContent aria-label="Time zone" search={false}>
{TIME_ZONES.map((zone) => (
<SelectItem key={zone} value={zone}>
{zone}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</Field>
</ul>
</Card>
</section>
</>
}
/>
</ScreenFrame>
);
}