Skip to contentVibraUI
Shared pagesinstalls at /settings/profile

Profile settings

The signed-in person's own details: a picture cropped round in the browser and kept in the tab, name, email and timezone in one saved form, and the account facts the form cannot change beside it.

Open the live page

The page is a server component inside AppShell: it reads the workspace owner's row through db.members and hands it to the form, which is the only client island. Saving goes through a server action that validates the name, the address and the timezone, refuses an address another member already uses, and writes the row back with db.members.update — every refusal naming the field it belongs to so the message renders under that input. Role, join date, teammate count and two-factor state are read off the same row rather than restated. Upload a photo opens the browser's chooser for a PNG, JPEG or WebP — its file field is hidden from sight and from assistive tech, so the button is the one control — and the picture chosen opens in Crop your picture: a round ImageCropper, loaded with a dynamic import, so the page's first load does not carry it. The cropper's code is fetched when Upload a photo is pressed, while the chooser is open, so it is usually there before a picture is; when it arrives after the dialog has opened on its spinner, the focus follows it into the crop area, unless the reader has moved the focus since. Save picture cuts the frame's area to a 256 × 256 WebP in the browser with cropImage — a JPEG where the browser cannot encode WebP, whose PNG could run past the limit — and sends it to saveAvatar, which checks it (at most 200 KB, and a PNG, JPEG or WebP by its leading bytes, never by the type it was sent with) and keeps nothing: the sample store is shared by every visitor of one server instance, so a face kept there would be shown to strangers. The avatar then shows the crop from an object URL, the status line under it says the picture lives in this tab, and a refusal is a danger callout inside the dialog — and so is a crop the browser could not cut, a send that never reached the server ("The picture couldn't be sent. Try again."), and a cropper whose code could not be fetched; each object URL is revoked when another replaces it and when the page goes. In your own app, saveAvatar is where the picture is stored: after its checks, put the file where you keep pictures and write that URL to the member's avatarUrl. The section list beside the page is the nav's own: the leaves of the `/settings` entry in this block's `nav.ts`, in nav order, resolved through the same NAV_ICONS table the sidebar reads. Nothing lists the sections twice, so editing that one file — or letting a template replace it — moves the sidebar and the sub-nav together, and the sub-nav can never offer a section the product has no page for. Composes AppShell, PageHeader, SettingsLayout, SectionHeader, Card, FormRow, Input, Select, Avatar, ImageCropper, Dialog, Callout, AsyncButton, Spinner, DescriptionList and StatusBadge.

Preview

Install

npx shadcn@latest add @vibra/settings-profile

Needs the @vibra registry in your components.json — set it up once.

Source

app/settings/profile/page.tsx
import { REFERENCE_DATE } from "@/lib/sample-data"
import { AppShell } from "@/components/ui/app-shell"
import { PageHeader } from "@/components/ui/page-header"
import { SettingsLayout } from "@/components/ui/settings-layout"

import { signOut } from "./actions"
import { AccountSummary } from "./components/account-summary"
import { ProfileForm } from "./components/profile-form"
import { SETTINGS_SECTIONS } from "./components/settings-sections"
import {
  currentUser,
  DEFAULT_TIMEZONE,
  joinedOn,
  membershipYears,
  profile,
  shellNotifications,
  teammateCount,
  TIMEZONES,
} from "./data"
import { NAV, ROUTE } from "./nav"

/**
 * Your profile. The page is a server component inside the shell: it reads the
 * member row through `db` and hands it to the form, which is the only client
 * island. SettingsLayout draws the settings area's own section list beside it;
 * every section there is a real route, so its links are plain anchors.
 */
export default function SettingsProfilePage() {
  const me = profile()

  return (
    <AppShell
      nav={NAV}
      activeHref={ROUTE}
      user={currentUser()}
      notifications={shellNotifications()}
      now={REFERENCE_DATE}
      onSignOut={signOut}
    >
      <PageHeader
        title="Profile"
        description="Your name, your address, and how dates are drawn for you."
      />

      {/* The shell's sidebar already lists the six settings sections, so the
          layout's own 220px column would be the same links a second time; the
          page takes the width back and holds the form to a readable measure. */}
      <SettingsLayout nav={SETTINGS_SECTIONS} activeHref={ROUTE} sectionsInSidebar>
        <div className="flex max-w-2xl flex-col gap-6">
          <ProfileForm
            name={me.name}
            email={me.email}
            initials={me.initials}
            avatarUrl={me.avatarUrl}
            timezone={DEFAULT_TIMEZONE}
            timezones={TIMEZONES}
          />
          <AccountSummary
            memberId={me.id}
            role={me.role}
            joinedOn={joinedOn()}
            years={membershipYears()}
            teammates={teammateCount()}
            twoFactor={me.twoFactor}
          />
        </div>
      </SettingsLayout>
    </AppShell>
  )
}
app/settings/profile/nav.ts
import { type NavConfig } from "@/lib/nav-config"

/** The route this page is installed at. AppShell matches the nav against it. */
export const ROUTE = "/settings/profile"

/**
 * This product's navigation, as plain data. AppShell resolves the icon names
 * and works out which item is current from the route, so nothing here is a
 * component and nothing here says "I am the page you are on".
 *
 * Settings is a disclosure with one leaf per settings page, so this page's own
 * route is a leaf: a parent with `items` renders as a button and has no anchor
 * for `aria-current="page"` to land on.
 */
export const NAV: NavConfig = {
  brand: { name: "Northwind", initial: "N", href: "/saas", caption: "Production" },
  groups: [
    {
      label: "Workspace",
      items: [
        { title: "Overview", href: "/saas", icon: "layout-dashboard" },
        { title: "Customers", href: "/ecommerce/customers", icon: "users" },
        { title: "Revenue", href: "/saas/revenue", icon: "credit-card" },
        { title: "Monitoring", href: "/engineering/monitoring", icon: "activity" },
      ],
    },
    {
      label: "Account",
      items: [
        {
          title: "Settings",
          href: "/settings",
          icon: "settings",
          items: [
            // The parent route is a real page (the workspace settings block),
            // so it gets a leaf of its own — a parent with `items` renders as
            // a disclosure button and is never a link.
            { title: "General", href: "/settings", icon: "settings" },
            { title: "Profile", href: "/settings/profile", icon: "user-round" },
            { title: "Security", href: "/settings/security", icon: "shield" },
            { title: "Notifications", href: "/settings/notifications", icon: "bell" },
            { title: "API keys", href: "/settings/api-keys", icon: "key-round" },
            { title: "Integrations", href: "/settings/integrations", icon: "plug" },
          ],
        },
      ],
    },
  ],
  // Pinned under the groups, where the old secondary links sat.
  footer: [{ title: "Support", href: "/support", icon: "life-buoy" }],
}
app/settings/profile/data.ts
/**
 * What this page reads. The person editing it is the workspace owner in
 * `db.members`, so their name, address, role, id and join date all come from
 * that row — and saving the form writes back through the same repository. The
 * one thing no repository records is the display timezone, which is stated
 * here beside the vocabulary the save action validates it against. "Now" is
 * `REFERENCE_DATE`.
 */
import { formatDate, getInitials } from "@/lib/format"
import { db, REFERENCE_DATE, type Member } from "@/lib/sample-data"

export type Profile = {
  id: string
  name: string
  email: string
  role: Member["role"]
  initials: string
  avatarUrl?: string
  joinedAt: Date
  lastActiveAt: Date
  twoFactor: boolean
}

/** The row the whole page is about: whoever owns this workspace. */
function ownerRow(): Member {
  return db.members.all().find((member) => member.role === "owner") ?? db.members.all()[0]
}

/** The signed-in person, read fresh so a save is visible on the next render. */
export function profile(): Profile {
  const owner = ownerRow()
  return {
    id: owner.id,
    name: owner.name,
    email: owner.email,
    role: owner.role,
    initials: getInitials(owner.name),
    avatarUrl: owner.avatarUrl,
    joinedAt: owner.joinedAt,
    lastActiveAt: owner.lastActiveAt,
    twoFactor: owner.twoFactor,
  }
}

/**
 * The zones the select offers. A timezone is a display preference rather than
 * a row in any repository, so it is stated here — and `saveProfile` rejects
 * anything outside this list, which is why the vocabulary lives beside the
 * action instead of in the component that draws it.
 */
export const TIMEZONES = [
  "Europe/London",
  "Europe/Berlin",
  "Europe/Lisbon",
  "America/New_York",
  "America/Los_Angeles",
  "Asia/Singapore",
  "Australia/Sydney",
] as const

export type Timezone = (typeof TIMEZONES)[number]

/** Where the owner reads their dashboards from; the form's starting value. */
export const DEFAULT_TIMEZONE: Timezone = "Europe/Berlin"

/** "13 June 2023" — the date the owner's row says they joined. */
export function joinedOn(): string {
  return formatDate(ownerRow().joinedAt, "long", { timeZone: "UTC" })
}

/** How long this account has been open, in whole years, against REFERENCE_DATE. */
export function membershipYears(): number {
  const ms = REFERENCE_DATE.getTime() - ownerRow().joinedAt.getTime()
  return Math.floor(ms / (365.25 * 24 * 60 * 60 * 1000))
}

/** How many people share the workspace with them. */
export function teammateCount(): number {
  return db.members.all().length - 1
}

/** The person looking at the page — the same row the form edits. */
export function currentUser() {
  const owner = ownerRow()
  return { name: owner.name, email: owner.email, initials: getInitials(owner.name), avatarUrl: owner.avatarUrl }
}

/** The bell's contents: the newest notifications, unread first in the panel. */
export function shellNotifications() {
  return db.notifications
    .all()
    .sort((a, b) => b.at.getTime() - a.at.getTime())
    .slice(0, 6)
    .map(({ id, title, description, at, read, href }) => ({ id, title, description, at, read, href }))
}
app/settings/profile/actions.ts
"use server"

import { mockAuthAdapter } from "@/lib/auth-adapter"
import { db, invalidInput, isForm, type Result } from "@/lib/sample-data"
import { isEmail } from "@/lib/validation"

import { profile, TIMEZONES, type Timezone } from "./data"

export type SavedProfile = { name: string; email: string; timezone: Timezone }

/** What the form holds between submits: nothing yet, or the last outcome. */
export type ProfileState = Result<SavedProfile> | null

function field(formData: FormData, key: string): string {
  const value = formData.get(key)
  return typeof value === "string" ? value.trim() : ""
}

/** A name as a person would write theirs: long enough for anyone's, short enough for a row. */
const MAX_NAME = 80

/**
 * Writes the form back to the signed-in member's row. Whose row is decided
 * here, from the session — `profile()` — and never read off the form: a hidden
 * id was a suggestion anyone could edit, and a crafted one renamed and
 * re-addressed another member (CONVENTIONS block rule 8). Every refusal names
 * the field it belongs to, so the form can render it under that input rather
 * than as a message the reader has to match up by hand.
 */
export async function saveProfile(
  _previous: ProfileState,
  formData: FormData
): Promise<Result<SavedProfile>> {
  if (!isForm(formData)) return invalidInput("Send your details as the form sends them.")
  const { id } = profile()
  const name = field(formData, "name")
  const email = field(formData, "email")
  const timezone = field(formData, "timezone")

  if (!name) {
    return { ok: false, error: { code: "invalid_input", field: "name", message: "Enter your name." } }
  }
  if (name.length > MAX_NAME) {
    return { ok: false, error: { code: "invalid_input", field: "name", message: `Keep your name under ${MAX_NAME} characters.` } }
  }
  if (!isEmail(email)) {
    return {
      ok: false,
      error: { code: "invalid_input", field: "email", message: "Enter a valid email address." },
    }
  }
  if (!TIMEZONES.includes(timezone as Timezone)) {
    return {
      ok: false,
      error: { code: "invalid_input", field: "timezone", message: "Choose a timezone from the list." },
    }
  }
  // Someone else may already use the address; members share one workspace, so
  // this is a real constraint rather than a formatting rule.
  const taken = db.members.all().some((member) => member.id !== id && member.email === email)
  if (taken) {
    return {
      ok: false,
      error: { code: "email_taken", field: "email", message: "Another member already uses that address." },
    }
  }

  const updated = await db.members.update(id, { name, email })
  if (!updated.ok) return updated

  return { ok: true, data: { name: updated.data.name, email: updated.data.email, timezone: timezone as Timezone } }
}

/** The most a cropped picture may weigh: the 256 × 256 WebP the page sends is a few kilobytes. */
const MAX_AVATAR_BYTES = 200 * 1024

const ascii = (text: string) => Array.from(text, (char) => char.charCodeAt(0))

/** How each picture the page accepts opens: PNG's eight bytes, JPEG's three, and WebP's RIFF container with its mark. */
const SIGNATURES: { at: number; bytes: number[] }[][] = [
  [{ at: 0, bytes: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] }],
  [{ at: 0, bytes: [0xff, 0xd8, 0xff] }],
  [
    { at: 0, bytes: ascii("RIFF") },
    { at: 8, bytes: ascii("WEBP") },
  ],
]

/** Whether the leading bytes are a picture's — never what the type or the name it came with claim. */
function isPicture(head: Uint8Array): boolean {
  return SIGNATURES.some((parts) => parts.every(({ at, bytes }) => bytes.every((byte, index) => head[at + index] === byte)))
}

/**
 * Checks a cropped picture and keeps nothing. The sample store is shared by
 * every visitor of one server instance, so a face written to it would be
 * shown to strangers: the page shows the crop from an object URL in the
 * reader's own tab instead. An installed app stores the file where it keeps
 * pictures and writes that URL to the member's `avatarUrl` — here, after
 * these checks. The type is read off the file's leading bytes, never off what
 * the browser said it was.
 */
export async function saveAvatar(form: FormData): Promise<Result<{ bytes: number }>> {
  if (!isForm(form)) return invalidInput("Send the picture as the form sends it.")
  const file = form.get("avatar")
  if (!file || typeof file === "string") {
    return { ok: false, error: { code: "required", field: "avatar", message: "Choose a picture to save." } }
  }
  if (file.size > MAX_AVATAR_BYTES) {
    return { ok: false, error: { code: "too_large", field: "avatar", message: "Pictures up to 200 KB — crop it smaller." } }
  }
  const head = new Uint8Array(await file.slice(0, 12).arrayBuffer())
  if (!isPicture(head)) {
    return { ok: false, error: { code: "invalid_input", field: "avatar", message: "That file isn't a picture." } }
  }
  return { ok: true, data: { bytes: file.size } }
}

/**
 * The one thing the shell calls. A server action so the page can stay a server
 * component and still hand the shell something to call, and a `Result` so the
 * caller reads the same success-or-error shape every mutation returns.
 */
export async function signOut(): Promise<Result<{ signedOut: true }>> {
  await mockAuthAdapter.signOut()
  return { ok: true, data: { signedOut: true } }
}
app/settings/profile/components/account-summary.tsx
import { DescriptionList } from "@/components/ui/description-list"
import { SectionHeader } from "@/components/ui/section-header"
import { StatusBadge } from "@/components/ui/status-badge"
import { Card, CardContent, CardHeader } from "@/components/ui/card"

export type AccountSummaryProps = {
  memberId: string
  role: string
  joinedOn: string
  years: number
  teammates: number
  twoFactor: boolean
}

/**
 * The facts about the account that the form does not edit — every one of them
 * read off the member row rather than restated here.
 */
export function AccountSummary({
  memberId,
  role,
  joinedOn,
  years,
  teammates,
  twoFactor,
}: AccountSummaryProps) {
  return (
    <Card>
      <CardHeader>
        <SectionHeader
          as="h2"
          title="Account"
          description="What the workspace records about this account. Only another owner can change the role."
        />
      </CardHeader>
      <CardContent>
        <DescriptionList
          items={[
            {
              term: "Role",
              description: <StatusBadge status={role} variant="info" dot={false} size="sm" />,
            },
            {
              term: "Member since",
              description: `${joinedOn} · ${years} years`,
            },
            {
              term: "Teammates",
              description: `${teammates} other people in this workspace`,
            },
            {
              term: "Two-factor",
              description: (
                <StatusBadge
                  status={twoFactor ? "on" : "off"}
                  variant={twoFactor ? "success" : "warning"}
                  size="sm"
                  label={twoFactor ? "On" : "Off"}
                />
              ),
            },
            {
              // font-mono earns its place here: this is an identifier a reader
              // copies into a support ticket, not prose.
              term: "Member ID",
              description: <span className="font-mono text-xs">{memberId}</span>,
            },
          ]}
        />
      </CardContent>
    </Card>
  )
}
app/settings/profile/components/avatar-cropper.tsx
"use client"

import { ImageCropper, type CropArea, type Rotation } from "@/components/ui/image-cropper"

// The part of the avatar editor that is fetched once a picture is chosen,
// with import(): the cropper and the function that cuts its area out, so the
// page's first load carries neither.
export { cropImage } from "@/components/ui/image-cropper"
export type { CropArea, Rotation } from "@/components/ui/image-cropper"

export type AvatarCropperProps = {
  /** The chosen picture's object URL. */
  src: string
  rotation: Rotation
  onRotationChange: (rotation: Rotation) => void
  onCropChange: (area: CropArea) => void
}

/** The chosen picture under a round frame: square, as an avatar is cut, and drawn round. */
export function AvatarCropper({ src, rotation, onRotationChange, onCropChange }: AvatarCropperProps) {
  return (
    <ImageCropper
      src={src}
      alt="The picture you chose"
      shape="round"
      aspect={1}
      rotation={rotation}
      onRotationChange={onRotationChange}
      onCropChange={onCropChange}
    />
  )
}
app/settings/profile/components/avatar-editor.tsx
"use client"

import * as React from "react"

import { AsyncButton } from "@/components/ui/async-button"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Callout } from "@/components/ui/callout"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Spinner } from "@/components/ui/spinner"

import { saveAvatar } from "../actions"
import type { CropArea, Rotation } from "./avatar-cropper"

type Cropper = typeof import("./avatar-cropper")

/** The cropper, fetched when it is first wanted rather than with the page: cropping is occasional. */
const loadCropper = (): Promise<Cropper> => import("./avatar-cropper")

const ACCEPT = "image/png,image/jpeg,image/webp"
/** The crop's side, in pixels: the picture is kept square and drawn round. */
const SIZE = 256
const SAVED = "Your picture is shown in this tab only — the demo keeps nothing."

export type AvatarEditorProps = {
  initials: string
  /** The face on file, until the reader crops one of their own. */
  avatarUrl?: string
}

/**
 * The face beside the profile form, and the way to change it. Upload a photo
 * opens the browser's chooser and fetches the cropper meanwhile — not with
 * the page. A picture chosen opens in a round cropper, and Save picture cuts
 * it to a 256 × 256 WebP in the browser, has `saveAvatar` check it, and
 * shows it from an object URL. Nothing is kept on the server, so the picture
 * lives in this tab: the status line says so. Each object URL is let go when
 * another replaces it, and when the editor goes.
 */
export function AvatarEditor({ initials, avatarUrl }: AvatarEditorProps) {
  const hintId = React.useId()
  const inputRef = React.useRef<HTMLInputElement>(null)
  const [cropper, setCropper] = React.useState<Cropper | null>(null)
  const [chosen, setChosen] = React.useState<string | null>(null)
  const [open, setOpen] = React.useState(false)
  const [area, setArea] = React.useState<CropArea | null>(null)
  const [rotation, setRotation] = React.useState<Rotation>(0)
  const [refusal, setRefusal] = React.useState("")
  const [cropped, setCropped] = React.useState<string | null>(null)
  const popupRef = React.useRef<HTMLDivElement>(null)
  // Whether the reader has pressed a key or the pointer in the dialog since it opened.
  const engaged = React.useRef(false)

  React.useEffect(() => (chosen ? () => URL.revokeObjectURL(chosen) : undefined), [chosen])
  React.useEffect(() => (cropped ? () => URL.revokeObjectURL(cropped) : undefined), [cropped])

  // A cropper that arrives after the dialog opened finds the focus on the
  // first thing the dialog could offer without it: Cancel. Unless the reader
  // has moved it since, the focus follows the cropper into its crop area.
  React.useEffect(() => {
    if (!open || !cropper || !chosen || engaged.current) return
    popupRef.current?.querySelector<HTMLElement>('[data-slot="image-cropper-stage"]')?.focus()
  }, [open, cropper, chosen])

  const load = () => {
    if (cropper) return
    loadCropper().then(setCropper, () => setRefusal("The cropper didn't load. Close this and choose the picture again."))
  }

  const choose = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    // Cleared, so choosing the same file again is still a change.
    event.target.value = ""
    if (!file) return
    setChosen(URL.createObjectURL(file))
    setArea(null)
    setRotation(0)
    setRefusal("")
    engaged.current = false
    setOpen(true)
    load()
  }

  async function save() {
    if (!cropper || !chosen || !area) return
    setRefusal("")
    let blob: Blob
    try {
      const size = { rotation, width: SIZE, height: SIZE }
      blob = await cropper.cropImage(chosen, area, { ...size, type: "image/webp" })
      // A browser that cannot encode WebP hands back a PNG, which can run
      // past the limit at this size; a JPEG of the same crop cannot.
      if (blob.type !== "image/webp") blob = await cropper.cropImage(chosen, area, { ...size, type: "image/jpeg", quality: 0.9 })
    } catch {
      setRefusal("This picture couldn't be cropped. Choose another one.")
      return
    }
    const form = new FormData()
    form.set("avatar", blob, `avatar.${blob.type.split("/")[1] || "webp"}`)
    let result: Awaited<ReturnType<typeof saveAvatar>>
    try {
      result = await saveAvatar(form)
    } catch {
      // A dropped connection, or a page older than the server it talks to.
      setRefusal("The picture couldn't be sent. Try again.")
      return
    }
    if (!result.ok) {
      setRefusal(result.error.message)
      return
    }
    setCropped(URL.createObjectURL(blob))
    setOpen(false)
  }

  const shown = cropped ?? avatarUrl

  return (
    <div className="flex flex-col gap-2">
      <div className="flex items-center gap-4">
        <Avatar aria-label="Your picture" className="size-14">
          {shown ? <AvatarImage src={shown} alt="" /> : null}
          <AvatarFallback className="text-base">{initials}</AvatarFallback>
        </Avatar>
        <Button
          type="button"
          variant="outline"
          size="sm"
          aria-describedby={hintId}
          onClick={() => {
            // Fetched while the chooser is open, so it is there when a picture is.
            load()
            inputRef.current?.click()
          }}
        >
          Upload a photo
        </Button>
        {/* Hidden from sight and from assistive tech: the button is the way
            in, and opens it. No name, so the profile form around it never
            sends a photo. */}
        <input ref={inputRef} type="file" accept={ACCEPT} hidden onChange={choose} />
      </div>
      <p id={hintId} className="text-xs text-muted-foreground">
        A PNG, JPEG or WebP picture, framed in a circle before it is used.
      </p>
      <p role="status" aria-live="polite" aria-label="Picture" className="text-xs text-muted-foreground empty:sr-only">
        {cropped ? SAVED : null}
      </p>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent
          ref={popupRef}
          onKeyDown={() => (engaged.current = true)}
          onPointerDown={() => (engaged.current = true)}
          className="sm:max-w-md"
        >
          <DialogHeader>
            <DialogTitle>Crop your picture</DialogTitle>
            <DialogDescription>Drag and zoom it until the circle holds what you want shown.</DialogDescription>
          </DialogHeader>
          {cropper && chosen ? (
            <cropper.AvatarCropper src={chosen} rotation={rotation} onRotationChange={setRotation} onCropChange={setArea} />
          ) : refusal ? null : (
            <div className="grid aspect-[4/3] place-items-center rounded-lg bg-muted">
              <Spinner aria-label="Loading the cropper" className="size-5 text-muted-foreground" />
            </div>
          )}
          {refusal ? (
            <Callout variant="danger" role="alert">
              {refusal}
            </Callout>
          ) : null}
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setOpen(false)}>
              Cancel
            </Button>
            <AsyncButton type="button" disabled={!area} onClick={save}>
              Save picture
            </AsyncButton>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
app/settings/profile/components/profile-form.tsx
"use client"

import * as React from "react"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card"
import { FormRow } from "@/components/ui/form-section"
import { Input } from "@/components/ui/input"
import { SectionHeader } from "@/components/ui/section-header"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

import { saveProfile, type ProfileState } from "../actions"
import { AvatarEditor } from "./avatar-editor"

export type ProfileFormProps = {
  name: string
  email: string
  initials: string
  /** The face on file, beside the initials it falls back to. */
  avatarUrl?: string
  timezone: string
  timezones: readonly string[]
}

/**
 * The one form on this page. Both text inputs are controlled: React resets an
 * uncontrolled form once its action settles, which would wipe what was typed
 * on every rejected submit. The timezone rides along in a hidden input so the
 * action reads it out of FormData like every other field. Whose row the save
 * writes is the action's to know, not the form's: no id travels with it.
 */
export function ProfileForm({ name, email, initials, avatarUrl, timezone, timezones }: ProfileFormProps) {
  const [state, formAction, pending] = React.useActionState<ProfileState, FormData>(
    saveProfile,
    null
  )
  const [nameValue, setNameValue] = React.useState(name)
  const [emailValue, setEmailValue] = React.useState(email)
  const [zone, setZone] = React.useState(timezone)

  const error = state && !state.ok ? state.error : undefined
  const errorFor = (field: string) => (error?.field === field ? error.message : undefined)
  // A refusal with no field is nobody's input in particular, so it goes above
  // the buttons as a form-level alert rather than under an arbitrary control.
  const formError = error && !error.field ? error.message : undefined

  return (
    <Card>
      <CardHeader>
        <SectionHeader
          as="h2"
          title="Your details"
          description="How you appear to everyone else in this workspace."
        />
      </CardHeader>

      <form action={formAction}>
        {/* A measure, not the card's full width: a name and an address are
            short, and a 900px input invites neither. */}
        <CardContent className="flex max-w-md flex-col gap-5">
          <input type="hidden" name="timezone" value={zone} />

          {/* The picture saves on its own, never with the form: its file
              field has no name. */}
          <AvatarEditor initials={initials} avatarUrl={avatarUrl} />

          <FormRow label="Full name" htmlFor="profile-name" required error={errorFor("name")}>
            <Input
              id="profile-name"
              name="name"
              autoComplete="name"
              value={nameValue}
              onChange={(event) => setNameValue(event.target.value)}
            />
          </FormRow>

          <FormRow
            label="Email"
            htmlFor="profile-email"
            required
            description="Sign-in address, and where every notification is sent."
            error={errorFor("email")}
          >
            <Input
              id="profile-email"
              name="email"
              type="email"
              autoComplete="email"
              value={emailValue}
              onChange={(event) => setEmailValue(event.target.value)}
            />
          </FormRow>

          <FormRow
            label="Timezone"
            htmlFor="profile-timezone"
            description="Dates and charts are drawn in this zone."
            error={errorFor("timezone")}
          >
            {/* The wiring goes on the trigger, not on Select's root: the root
                is a context provider and renders no element of its own, so
                aria-describedby handed to it would go nowhere. */}
            {(field) => (
              <Select value={zone} onValueChange={(next) => setZone(String(next))}>
                <SelectTrigger
                  id={field.id}
                  aria-describedby={field["aria-describedby"]}
                  aria-invalid={field["aria-invalid"]}
                  className="w-full sm:w-72"
                >
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {timezones.map((option) => (
                    <SelectItem key={option} value={option}>
                      {option.replace("_", " ")}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          </FormRow>

          {formError ? (
            <p role="alert" className="text-sm text-danger">
              {formError}
            </p>
          ) : null}
        </CardContent>

        <CardFooter className="mt-4 justify-between gap-3">
          <p role="status" className="text-sm text-muted-foreground">
            {state?.ok ? `Profile saved. You are ${state.data.name}.` : null}
          </p>
          <Button type="submit" disabled={pending} aria-busy={pending || undefined}>
            {pending ? "Saving…" : "Save changes"}
          </Button>
        </CardFooter>
      </form>
    </Card>
  )
}
app/settings/profile/components/settings-sections.tsx
import { flattenNav, type NavConfig } from "@/lib/nav-config"
import { navIcon } from "@/components/ui/app-shell/icons"
import { type SettingsNavItem } from "@/components/ui/settings-layout"

import { NAV } from "../nav"

// Not `SETTINGS_HREF`: this is the entry to look up, not a link. The template
// generator reads any *href constant holding an absolute path as a route a
// page links to, and would stub "/settings" for a product that has no page
// there — the same reason a page nav's own ROUTE is not called a href.
/** The route the settings area is rooted at. */
const SETTINGS_ROOT = "/settings"

/**
 * The settings area's own sections, as SettingsLayout wants them: the leaves of
 * the nav's `/settings` entry, in nav order. Read from the nav rather than
 * written out a second time, because a template replaces `nav.ts` with its own
 * — a hand-listed set would then offer sections that product has no page for,
 * and the sub-nav beside the page would disagree with the sidebar above it.
 *
 * `findNavItem` is not the lookup: these navs give `/settings` a leaf of its
 * own (General, the area's front page), and that leaf ties with its parent on
 * href length, so the entry that owns the list has to be asked for directly.
 * An entry with no leaves is its own only section.
 *
 * Each section is a real route, so these stay plain anchors — no `onNavigate`,
 * no client state — and SettingsLayout marks the one matching `activeHref` as
 * the current page.
 */
export function settingsSections(nav: NavConfig = NAV): SettingsNavItem[] {
  const entries = flattenNav(nav).filter((item) => item.href === SETTINGS_ROOT)
  // The parent wins over its own General leaf, which shares its href: the one
  // that carries the list is the one being asked for. `findNavItem` would hand
  // back the leaf instead, since equal href lengths go to the later item.
  const settings = entries.find((item) => item.items?.length) ?? entries[0]
  if (!settings) return []
  const leaves = settings.items?.length ? settings.items : [settings]

  return leaves.map((leaf) => {
    // A NavConfig names its icons rather than holding them; this is the table
    // the sidebar resolves them through, so the two cannot drift.
    const Icon = navIcon(leaf.icon)
    return { title: leaf.title, href: leaf.href, icon: Icon ? <Icon /> : undefined }
  })
}

/** This block's own sections: the nav it ships with, resolved once. */
export const SETTINGS_SECTIONS: SettingsNavItem[] = settingsSections()