The signed-in account
Signing in, the person at the rail's foot, their profile, signing out
This recipe draws SettingsPage arrangement="mode", the one arrangement Meadow draws: the profile is the reference's profile view, a section of its settings over the whole window, so it is drawn in the frame's place, never inside ScreenFrame. The sign-in stands in the column of the reference's empty home (Empty variant="page"), built from Meadow's parts: the reference's own sign-in is not drawn here.
Copy the file below whole (src/screens/account.tsx) 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 menu at the rail's foot; and the profile (the default export, at /profile). 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, saveProfile 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); an app with no sign-in leaves them out. <SignedIn> shows the sign-in screen while useSession() is null, the screens once someone signs in. 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 code397 lines
- **Sign in**, outside the frame: the title and a line, then Email and Password (PasswordField: its button shows what
was typed, a line says when Caps Lock is on), then the dark Continue. Both fields are required, the email checked
for a full address; Continue on a refused field writes the reason under it (FieldInvalid: marked invalid, read out)
and focuses the first one. Continue shows its spinner while `signIn` runs; a refusal from your auth (throw its words)
shows as a red Alert over the fields.
- **The person at the rail's foot**: `SignedInMenu` in the frame's account place (`<FrameAccount>`, given once by
`<SignedIn>`), the person's avatar in place of the light and dark switch. Enter, Space or ArrowDown opens it; the
arrows move and loop, Escape closes it. Inside: who is signed in, Profile, Settings (there while the frame's pages
hold `/settings`), Appearance (System, Light, Dark: the same choice as the switch it replaces) and Sign out.
- **Profile** (SettingsPage): the grey column of its two sections, Profile and Account, the open one beside it. In
Profile: the photo (AvatarUpload: the initials until a picture is chosen; it stays on this device, nothing is
uploaded), the name, the email and the time zone. Save changes is disabled until a value differs; a refused field
says why under it and takes the focus; a save updates the session, so the menu shows the new name at once, and raises
the theme's toast (`<Toaster />` once in `App.tsx`). In Account: Sign out, in the danger row. The round close and
Escape go back where the profile was opened from.
Light, dark, phone and desktop are the parts' own: add no class for them. An app with both this and
`docs/screen-settings.md` keeps the person's name here and drops the settings recipe's Profile section.
```tsx
// src/screens/account.tsx: signing in, the person's menu at the rail's foot, their profile and signing out
import { type FormEvent, type ReactNode, useState, useSyncExternalStore } from 'react';
import { PageBody } from '@/components/goop/patterns/page-body';
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 { AvatarUpload } from '@/components/ui/goop/avatar';
import { Button } from '@/components/ui/goop/button';
import { DropdownMenuItem } from '@/components/ui/goop/dropdown-menu';
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from '@/components/ui/goop/empty';
import { Field } from '@/components/ui/goop/field';
import { FieldInvalid } from '@/components/ui/goop/field-error';
import {
PageHeader,
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 { Sidebar, SidebarContent } from '@/components/ui/goop/sidebar';
import { SidebarMenu, SidebarMenuItem } from '@/components/ui/goop/sidebar-group';
import { SidebarMenuButton } from '@/components/ui/goop/sidebar-menu-button';
import { TextInput } from '@/components/ui/goop/text-input';
import { toast } from '@/components/ui/goop/toast';
import { TopBar, TopBarGroup, TopBarRow, TopBarTitle } from '@/components/ui/goop/top-bar';
import type { IconName } from '@/lib/goop/meadow/glyph';
import { FrameAccount, hasPage } from './frame';
import { go } from './router';
// ---- the session: wire your auth here
/** The signed-in person, as the screens show them. */
export interface Person {
name: string;
email: string;
timeZone: string;
}
let signedIn: Person | null = null;
const listeners = new Set<() => void>();
function setSignedIn(next: Person | null): void {
signedIn = next;
for (const listener of listeners) listener();
}
function onSessionChange(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/** The sample's wait, as a real call's. */
const wait = (ms: number) => new Promise<void>((done) => setTimeout(done, ms));
/**
* Signs in: your auth's call goes here; a refusal throws its words ("That email and password don't match."). The
* sample accepts any email and password, sends nothing and keeps no password: the name is made from the address.
*/
async function signIn(email: string, _password: string): Promise<void> {
await wait(400);
const name = (email.split('@')[0] ?? '')
.split(/[._-]+/)
.filter(Boolean)
.map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)
.join(' ');
setSignedIn({ name: name || email, email, timeZone: 'Europe/London' });
}
/** Saves the person's profile: your API's call goes here. */
async function saveProfile(change: Partial<Person>): Promise<void> {
await wait(300);
if (signedIn) setSignedIn({ ...signedIn, ...change });
}
/** Signs out: your auth's call goes here. Every screen goes back to the sign-in at once. */
function signOut(): void {
setSignedIn(null);
}
/** The session, in any screen: `const { person, signOut } = useSession();` (`person` is `null` when signed out). */
export function useSession() {
const person = useSyncExternalStore(
onSessionChange,
() => signedIn,
() => null,
);
return { person, signIn, saveProfile, signOut };
}
const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
/** What is wrong with an email, or nothing. */
const emailProblem = (email: string) =>
!email.trim()
? 'Enter your email.'
: EMAIL.test(email.trim())
? undefined
: 'Enter a full address, like you@example.com.';
// ---- signing in
/** The screens, signed in; the sign-in screen until then. Round every screen, once, in App.tsx. */
export function SignedIn({ children }: { children: ReactNode }) {
const { person } = useSession();
if (!person) return <SignInScreen />;
return <FrameAccount account={<SignedInMenu />}>{children}</FrameAccount>;
}
/** The sign-in, outside the frame: the empty home's column in the page's own, its fields and the dark Continue. */
export function SignInScreen() {
const { signIn: start } = useSession();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [tried, setTried] = useState(false);
const [busy, setBusy] = useState(false);
const [refused, setRefused] = useState<string | null>(null);
const emailError = emailProblem(email);
const passwordError = password ? undefined : 'Enter your password.';
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setTried(true);
if (emailError || passwordError) {
// the first refused field takes the focus
const first = event.currentTarget.elements.namedItem(emailError ? 'email' : 'password');
if (first instanceof HTMLElement) first.focus();
return;
}
setBusy(true);
setRefused(null);
try {
await start(email.trim(), password);
} catch (error) {
setRefused(error instanceof Error ? error.message : 'That did not work. Try again.');
setBusy(false);
}
};
return (
<main>
<PageBody variant="column">
<Empty variant="page">
<EmptyHeader>
<EmptyTitle asChild>
<h1>Sign in to Fieldwork</h1>
</EmptyTitle>
<EmptyDescription>Your crew’s notes, calendar and sites, in one place.</EmptyDescription>
</EmptyHeader>
<form noValidate onSubmit={submit} className="flex flex-col gap-3">
{refused ? (
<Alert variant="destructive">
<AlertIcon />
<AlertTitle>Couldn’t sign in</AlertTitle>
<AlertDescription>{refused}</AlertDescription>
</Alert>
) : null}
<Field label="Email" orientation="vertical" className="w-full">
<FieldInvalid error={tried ? emailError : undefined}>
<TextInput
type="email"
name="email"
autoComplete="email"
value={email}
onChange={(event) => setEmail(event.currentTarget.value)}
/>
</FieldInvalid>
</Field>
<Field label="Password" orientation="vertical" className="w-full">
<FieldInvalid error={tried ? passwordError : undefined}>
<PasswordField
name="password"
value={password}
onChange={(event) => setPassword(event.currentTarget.value)}
/>
</FieldInvalid>
</Field>
<Button type="submit" variant="inverse" size="lg" loading={busy}>
Continue
</Button>
</form>
</Empty>
</PageBody>
</main>
);
}
// ---- the person at the rail's foot
/** The signed-in person's menu: who they are, Profile, Settings, the light and dark choice, Sign out. */
export function SignedInMenu() {
const { person, signOut: end } = useSession();
if (!person) return null;
return (
<AccountMenu>
<AccountMenuTrigger variant="avatar" name={person.name} email={person.email} />
<AccountMenuContent>
<AccountMenuHeader />
<DropdownMenuItem icon="tabler-outline:user" onSelect={() => go('/profile')}>
Profile
</DropdownMenuItem>
{hasPage('/settings') ? (
<DropdownMenuItem icon="tabler-outline:settings" onSelect={() => go('/settings')}>
Settings
</DropdownMenuItem>
) : null}
<AccountMenuColorMode />
<AccountMenuSignOut onSelect={end} />
</AccountMenuContent>
</AccountMenu>
);
}
// ---- the profile
type Section = { id: string; words: string; icon: IconName; line: string };
const SECTIONS: readonly Section[] = [
{ id: 'profile', words: 'Profile', icon: 'tabler-outline:user-circle', line: 'How your crew sees you.' },
{ id: 'account', words: 'Account', icon: 'tabler-outline:lock', line: 'Signing in and out of Fieldwork.' },
];
const TIME_ZONES = [
{ value: 'Europe/London', words: 'London' },
{ value: 'Europe/Amsterdam', words: 'Amsterdam' },
{ value: 'America/New_York', words: 'New York' },
];
/** Leaves the profile: back to the page it was opened from, or the app's start when the visit began here. */
const leave = () => (window.history.length > 1 ? window.history.back() : go('/'));
/** The profile, over the whole window (`/profile`); the sign-in screen when no one is signed in. */
export default function AccountScreen() {
const { person } = useSession();
return person ? <Profile person={person} /> : <SignInScreen />;
}
function Profile({ person }: { person: Person }) {
const { saveProfile: save, signOut: end } = useSession();
const [open, setOpen] = useState('profile');
const [name, setName] = useState(person.name);
const [email, setEmail] = useState(person.email);
const [timeZone, setTimeZone] = useState(person.timeZone);
const [tried, setTried] = useState(false);
const [saving, setSaving] = useState(false);
const nameError = name.trim() ? undefined : 'Enter your name.';
const emailError = emailProblem(email);
const changed = name.trim() !== person.name || email.trim() !== person.email || timeZone !== person.timeZone;
const section = SECTIONS.find((one) => one.id === open) ?? (SECTIONS[0] as Section);
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setTried(true);
if (nameError || emailError) {
const first = event.currentTarget.elements.namedItem(nameError ? 'name' : 'email');
if (first instanceof HTMLElement) first.focus();
return;
}
setSaving(true);
await save({ name: name.trim(), email: email.trim(), timeZone });
setSaving(false);
setTried(false);
toast('Profile saved');
};
return (
<SettingsPage
arrangement="mode"
onClose={leave}
closeLabel="Close your account"
header={
<TopBar>
<TopBarRow>
<TopBarGroup align="start">
<TopBarTitle>Your account</TopBarTitle>
</TopBarGroup>
</TopBarRow>
</TopBar>
}
subNav={
<Sidebar variant="settings" aria-label="Your account" shortcut={false}>
<SidebarContent>
<SidebarMenu>
{SECTIONS.map((one) => (
<SidebarMenuItem key={one.id}>
<SidebarMenuButton
size="lg"
icon={one.icon}
isActive={one.id === section.id}
onClick={() => setOpen(one.id)}
>
{one.words}
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarContent>
</Sidebar>
}
heading={
<PageHeader>
<PageHeaderContent>
<PageHeaderTitle asChild>
<h1>{section.words}</h1>
</PageHeaderTitle>
<PageHeaderDescription>{section.line}</PageHeaderDescription>
</PageHeaderContent>
</PageHeader>
}
sections={
section.id === 'profile' ? (
<form noValidate onSubmit={submit} aria-label="Profile" className="flex flex-col gap-10">
<ul>
<Field as="li" label="Photo" description="Beside your notes and plans. It stays on this device.">
<AvatarUpload name={person.name}>{person.name}</AvatarUpload>
</Field>
<Field as="li" label="Name" description="Shown on notes, plans and invitations.">
<FieldInvalid error={tried ? nameError : undefined}>
<TextInput name="name" value={name} onChange={(event) => setName(event.currentTarget.value)} />
</FieldInvalid>
</Field>
<Field as="li" label="Email" description="Where invitations and the weekly digest go.">
<FieldInvalid error={tried ? emailError : undefined}>
<TextInput
type="email"
name="email"
value={email}
onChange={(event) => setEmail(event.currentTarget.value)}
/>
</FieldInvalid>
</Field>
<Field as="li" label="Time zone" description="The calendar's hours and the reminders follow it.">
{(control) => (
<Select value={timeZone} onValueChange={setTimeZone}>
<SelectTrigger {...control}>
<SelectValue />
<SelectIcon />
</SelectTrigger>
<SelectContent searchLabel="Time zone" search={false}>
{TIME_ZONES.map((zone) => (
<SelectItem key={zone.value} value={zone.value}>
{zone.words}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</Field>
</ul>
<div>
<Button type="submit" disabled={!changed} loading={saving}>
Save changes
</Button>
</div>
</form>
) : (
<ul>
<Field
as="li"
tone="danger"
stack="always"
label="Sign out"
description={`Signed in as ${person.email}. Your notes stay as they are.`}
>
<Button variant="destructive" size="page" onClick={end}>
Sign out
</Button>
</Field>
</ul>
)
}
/>
);
}