Settings panel

An account settings page in labelled sections that sit in two columns on wide screens and stack on small ones. The profile form has a local photo preview, name, email, username, time zone and a bio with a character count; it tracks unsaved changes, validates inline with focus on the first error, and shows saving and saved states. Notification rows use accessible switches (one locked on), and the danger zone deletes only after the workspace name is typed in a focus-trapped confirm dialog. Switch and SettingsSection are exported.

Forms & inputsBlockTailwind v4

Source

"use client";

import * as React from "react";
import { Check, LoaderCircle, TriangleAlert, Upload } from "lucide-react";
import { cn } from "@/lib/utils";

const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card";
const field =
  "h-9 w-full min-w-0 rounded-md border border-input bg-background px-3 text-sm shadow-xs outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 aria-invalid:border-destructive aria-invalid:ring-destructive/20 disabled:opacity-60 dark:[color-scheme:dark]";
const button = "inline-flex h-9 items-center justify-center gap-2 rounded-md px-4 text-sm font-medium transition-colors disabled:pointer-events-none disabled:opacity-50";

/* ---------- Building blocks ---------- */

export function SettingsSection({ title, description, children, id }: { title: string; description?: string; children: React.ReactNode; id?: string }) {
  const headingId = React.useId();
  return (
    <section id={id} aria-labelledby={headingId} className="grid gap-4 md:grid-cols-[minmax(0,15rem)_minmax(0,1fr)] md:gap-10">
      <div>
        <h2 id={headingId} className="font-semibold tracking-tight">
          {title}
        </h2>
        {description && <p className="mt-1 text-sm text-muted-foreground">{description}</p>}
      </div>
      <div className="min-w-0">{children}</div>
    </section>
  );
}

export interface SwitchProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "onChange"> {
  checked: boolean;
  onCheckedChange: (checked: boolean) => void;
}

export function Switch({ checked, onCheckedChange, className, disabled, ...props }: SwitchProps) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      disabled={disabled}
      onClick={() => onCheckedChange(!checked)}
      className={cn(
        "relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-50",
        focusRing,
        checked ? "bg-primary" : "bg-input dark:bg-muted-foreground/30",
        className,
      )}
      {...props}
    >
      <span
        aria-hidden
        className={cn(
          "size-4 rounded-full bg-background shadow-sm motion-safe:transition-transform",
          checked ? "translate-x-[18px]" : "translate-x-0.5",
        )}
      />
    </button>
  );
}

/* ---------- Types ---------- */

export interface ProfileValues {
  name: string;
  email: string;
  username: string;
  timezone: string;
  bio: string;
}

export interface NotificationSetting {
  id: string;
  label: string;
  description?: string;
  enabled: boolean;
  /** Always on and cannot be changed. */
  locked?: boolean;
}

export interface SettingsPanelProps {
  profile: ProfileValues;
  onSaveProfile?: (values: ProfileValues) => void | Promise<void>;
  timezones?: string[];
  notifications: NotificationSetting[];
  onNotificationChange?: (id: string, enabled: boolean) => void;
  /** Name shown in the danger zone and typed to confirm deletion. */
  workspaceName: string;
  onDeleteWorkspace?: () => void | Promise<void>;
  className?: string;
}

const DEFAULT_TIMEZONES = ["Europe/London", "Europe/Stockholm", "America/New_York", "America/Los_Angeles", "Asia/Kolkata", "Asia/Tokyo", "Australia/Sydney"];
const BIO_LIMIT = 160;

function initialsOf(name: string) {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  return ((parts[0]?.[0] || "?") + (parts.length > 1 ? parts[parts.length - 1][0] : "")).toUpperCase();
}

/* ---------- Profile ---------- */

function ProfileForm({ initial, onSave, timezones }: { initial: ProfileValues; onSave?: SettingsPanelProps["onSaveProfile"]; timezones: string[] }) {
  const [saved, setSaved] = React.useState(initial);
  const [values, setValues] = React.useState(initial);
  const [errors, setErrors] = React.useState<Partial<Record<keyof ProfileValues, string>>>({});
  const [state, setState] = React.useState<"idle" | "saving" | "saved">("idle");
  const [photo, setPhoto] = React.useState<string | null>(null);
  const fileRef = React.useRef<HTMLInputElement>(null);
  const formRef = React.useRef<HTMLFormElement>(null);
  const id = React.useId();
  const dirty = (Object.keys(values) as (keyof ProfileValues)[]).some((key) => values[key] !== saved[key]);

  React.useEffect(() => () => void (photo && URL.revokeObjectURL(photo)), [photo]);

  const set = (key: keyof ProfileValues) => (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    setValues({ ...values, [key]: event.target.value });
    if (errors[key]) setErrors({ ...errors, [key]: undefined });
    if (state === "saved") setState("idle");
  };

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    const next: typeof errors = {};
    if (!values.name.trim()) next.name = "Enter your name.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) next.email = "Enter a valid email address.";
    if (!/^[a-z0-9_.]{3,24}$/i.test(values.username)) next.username = "Use 3–24 letters, numbers, dots or underscores.";
    setErrors(next);
    const first = Object.keys(next)[0];
    if (first) {
      formRef.current?.querySelector<HTMLElement>(`[name="${first}"]`)?.focus();
      return;
    }
    setState("saving");
    try {
      await onSave?.(values);
      setSaved(values);
      setState("saved");
    } catch {
      setState("idle");
    }
  }

  const describe = (key: keyof ProfileValues) => (errors[key] ? `${id}-${key}-error` : undefined);
  const error = (key: keyof ProfileValues) =>
    errors[key] && (
      <p id={`${id}-${key}-error`} className="mt-1.5 text-xs text-destructive">
        {errors[key]}
      </p>
    );

  return (
    <form ref={formRef} onSubmit={submit} noValidate className="rounded-xl border bg-card text-card-foreground shadow-xs">
      <div className="space-y-5 p-5 sm:p-6">
        <div className="flex items-center gap-4">
          <span className="grid size-16 shrink-0 place-items-center overflow-hidden rounded-full bg-muted text-lg font-semibold">
            {photo ? <img src={photo} alt="" className="size-full object-cover" /> : <span aria-hidden>{initialsOf(values.name)}</span>}
          </span>
          <div className="flex flex-wrap gap-2">
            <input
              ref={fileRef}
              type="file"
              accept="image/*"
              className="sr-only"
              tabIndex={-1}
              aria-hidden
              onChange={(event) => {
                const file = event.target.files?.[0];
                if (file) setPhoto(URL.createObjectURL(file));
              }}
            />
            <button type="button" onClick={() => fileRef.current?.click()} className={cn(button, "h-8 border bg-background px-3 hover:bg-accent", focusRing)}>
              <Upload aria-hidden className="size-3.5" />
              Upload photo
            </button>
            {photo && (
              <button type="button" onClick={() => setPhoto(null)} className={cn(button, "h-8 px-3 text-muted-foreground hover:text-foreground", focusRing)}>
                Remove
              </button>
            )}
          </div>
        </div>

        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label htmlFor={`${id}-name`} className="mb-1.5 block text-sm font-medium">
              Name
            </label>
            <input id={`${id}-name`} name="name" autoComplete="name" value={values.name} onChange={set("name")} aria-invalid={!!errors.name} aria-describedby={describe("name")} className={field} />
            {error("name")}
          </div>
          <div>
            <label htmlFor={`${id}-email`} className="mb-1.5 block text-sm font-medium">
              Email
            </label>
            <input id={`${id}-email`} name="email" type="email" autoComplete="email" value={values.email} onChange={set("email")} aria-invalid={!!errors.email} aria-describedby={describe("email")} className={field} />
            {error("email")}
          </div>
          <div>
            <label htmlFor={`${id}-username`} className="mb-1.5 block text-sm font-medium">
              Username
            </label>
            <div className="relative">
              <span aria-hidden className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-sm text-muted-foreground">
                @
              </span>
              <input id={`${id}-username`} name="username" autoComplete="username" value={values.username} onChange={set("username")} aria-invalid={!!errors.username} aria-describedby={describe("username")} className={cn(field, "pl-7")} />
            </div>
            {error("username")}
          </div>
          <div>
            <label htmlFor={`${id}-timezone`} className="mb-1.5 block text-sm font-medium">
              Time zone
            </label>
            <select id={`${id}-timezone`} name="timezone" value={values.timezone} onChange={set("timezone")} className={field}>
              {timezones.map((zone) => (
                <option key={zone} value={zone}>
                  {zone.replace(/_/g, " ").replace("/", " · ")}
                </option>
              ))}
            </select>
          </div>
          <div className="sm:col-span-2">
            <div className="mb-1.5 flex items-baseline justify-between">
              <label htmlFor={`${id}-bio`} className="text-sm font-medium">
                Bio
              </label>
              <span className={cn("text-xs tabular-nums", values.bio.length > BIO_LIMIT - 10 ? "text-amber-600 dark:text-amber-400" : "text-muted-foreground")}>
                {values.bio.length}/{BIO_LIMIT}
              </span>
            </div>
            <textarea
              id={`${id}-bio`}
              name="bio"
              rows={3}
              maxLength={BIO_LIMIT}
              value={values.bio}
              onChange={set("bio")}
              className={cn(field, "h-auto resize-y py-2 leading-relaxed")}
            />
          </div>
        </div>
      </div>

      <div className="flex items-center justify-end gap-2 rounded-b-xl border-t bg-muted/30 px-5 py-3 sm:gap-3 sm:px-6">
        <p aria-live="polite" className="mr-auto min-w-0 truncate text-xs text-muted-foreground sm:text-sm">
          {state === "saved" ? (
            <span className="inline-flex items-center gap-1.5 text-emerald-700 dark:text-emerald-400">
              <Check aria-hidden className="size-4" />
              Saved
            </span>
          ) : dirty ? (
            "Unsaved changes"
          ) : (
            ""
          )}
        </p>
        {dirty && (
          <button
            type="button"
            onClick={() => {
              setValues(saved);
              setErrors({});
            }}
            className={cn(button, "px-3 hover:bg-accent", focusRing)}
          >
            Cancel
          </button>
        )}
        <button type="submit" disabled={!dirty || state === "saving"} className={cn(button, "bg-primary text-primary-foreground hover:bg-primary/90", focusRing)}>
          {state === "saving" && <LoaderCircle aria-hidden className="size-4 motion-safe:animate-spin" />}
          {state === "saving" ? "Saving…" : "Save changes"}
        </button>
      </div>
    </form>
  );
}

/* ---------- Notifications ---------- */

function NotificationList({ initial, onChange }: { initial: NotificationSetting[]; onChange?: SettingsPanelProps["onNotificationChange"] }) {
  const [items, setItems] = React.useState(initial);
  const [message, setMessage] = React.useState("");
  const id = React.useId();
  return (
    <div className="rounded-xl border bg-card text-card-foreground shadow-xs">
      <ul className="divide-y">
        {items.map((item) => (
          <li key={item.id} className="flex items-center justify-between gap-6 px-5 py-4 sm:px-6">
            <div className="min-w-0">
              <p id={`${id}-${item.id}`} className="flex items-center gap-2 text-sm font-medium">
                {item.label}
                {item.locked && <span className="rounded bg-muted px-1.5 py-px text-[11px] font-medium text-muted-foreground">Required</span>}
              </p>
              {item.description && (
                <p id={`${id}-${item.id}-description`} className="mt-0.5 text-sm text-muted-foreground">
                  {item.description}
                </p>
              )}
            </div>
            <Switch
              checked={item.enabled}
              disabled={item.locked}
              aria-labelledby={`${id}-${item.id}`}
              aria-describedby={item.description ? `${id}-${item.id}-description` : undefined}
              onCheckedChange={(enabled) => {
                setItems(items.map((entry) => (entry.id === item.id ? { ...entry, enabled } : entry)));
                onChange?.(item.id, enabled);
                setMessage(`${item.label} ${enabled ? "on" : "off"}.`);
              }}
            />
          </li>
        ))}
      </ul>
      <p aria-live="polite" className="sr-only">
        {message}
      </p>
    </div>
  );
}

/* ---------- Danger zone ---------- */

function DeleteWorkspace({ name, onDelete }: { name: string; onDelete?: SettingsPanelProps["onDeleteWorkspace"] }) {
  const [open, setOpen] = React.useState(false);
  const [confirm, setConfirm] = React.useState("");
  const [state, setState] = React.useState<"idle" | "deleting" | "deleted">("idle");
  const triggerRef = React.useRef<HTMLButtonElement>(null);
  const dialogRef = React.useRef<HTMLDivElement>(null);
  const inputRef = React.useRef<HTMLInputElement>(null);
  const id = React.useId();
  const matches = confirm.trim() === name;

  const close = React.useCallback(() => {
    setOpen(false);
    setConfirm("");
    triggerRef.current?.focus();
  }, []);

  React.useEffect(() => {
    if (!open) return;
    inputRef.current?.focus();
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        close();
      } else if (event.key === "Tab" && dialogRef.current) {
        const list = Array.from(dialogRef.current.querySelectorAll<HTMLElement>("input, button:not([disabled])"));
        const first = list[0];
        const last = list[list.length - 1];
        if (event.shiftKey && document.activeElement === first) {
          event.preventDefault();
          last.focus();
        } else if (!event.shiftKey && document.activeElement === last) {
          event.preventDefault();
          first.focus();
        }
      }
    };
    const overflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = overflow;
    };
  }, [open, close]);

  async function remove(event: React.FormEvent) {
    event.preventDefault();
    if (!matches) return;
    setState("deleting");
    try {
      await onDelete?.();
      setState("deleted");
      setOpen(false);
    } catch {
      setState("idle");
    }
  }

  return (
    <div className="rounded-xl border border-destructive/30 bg-card text-card-foreground shadow-xs">
      <div className="flex flex-col gap-4 p-5 sm:flex-row sm:items-center sm:justify-between sm:p-6">
        <div>
          <p className="text-sm font-medium">Delete workspace</p>
          <p className="mt-0.5 text-sm text-muted-foreground">
            Permanently removes <span className="font-medium text-foreground">{name}</span>, its projects and members.
          </p>
        </div>
        {state === "deleted" ? (
          <p role="status" className="text-sm font-medium text-muted-foreground">
            Workspace deleted
          </p>
        ) : (
          <button
            ref={triggerRef}
            type="button"
            onClick={() => setOpen(true)}
            className={cn(button, "shrink-0 border border-destructive/40 text-destructive hover:bg-destructive/10", focusRing)}
          >
            Delete workspace
          </button>
        )}
      </div>

      {open && (
        <div className="fixed inset-0 z-50 grid place-items-center p-4">
          <div aria-hidden onClick={close} className="absolute inset-0 bg-black/40 motion-safe:transition-opacity starting:opacity-0 dark:bg-black/60" />
          <div
            ref={dialogRef}
            role="alertdialog"
            aria-modal="true"
            aria-labelledby={`${id}-title`}
            aria-describedby={`${id}-description`}
            className="relative w-full max-w-md rounded-xl border bg-background p-6 text-foreground shadow-2xl motion-safe:transition-[opacity,scale] starting:scale-95 starting:opacity-0"
          >
            <span className="grid size-10 place-items-center rounded-full bg-destructive/10 text-destructive">
              <TriangleAlert aria-hidden className="size-5" />
            </span>
            <h3 id={`${id}-title`} className="mt-4 text-lg font-semibold tracking-tight">
              Delete {name}?
            </h3>
            <p id={`${id}-description`} className="mt-1.5 text-sm text-muted-foreground">
              This cannot be undone. Type <span className="font-mono font-medium text-foreground">{name}</span> to confirm.
            </p>
            <form onSubmit={remove} className="mt-5">
              <label htmlFor={`${id}-confirm`} className="sr-only">
                Workspace name
              </label>
              <input
                ref={inputRef}
                id={`${id}-confirm`}
                value={confirm}
                onChange={(event) => setConfirm(event.target.value)}
                autoComplete="off"
                spellCheck={false}
                className={field}
              />
              <div className="mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
                <button type="button" onClick={close} className={cn(button, "border bg-background hover:bg-accent", focusRing)}>
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={!matches || state === "deleting"}
                  className={cn(button, "bg-destructive text-white hover:bg-destructive/90", focusRing)}
                >
                  {state === "deleting" && <LoaderCircle aria-hidden className="size-4 motion-safe:animate-spin" />}
                  Delete workspace
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- Panel ---------- */

export function SettingsPanel({
  profile,
  onSaveProfile,
  timezones = DEFAULT_TIMEZONES,
  notifications,
  onNotificationChange,
  workspaceName,
  onDeleteWorkspace,
  className,
}: SettingsPanelProps) {
  return (
    <div className={cn("space-y-10", className)}>
      <SettingsSection title="Profile" description="Shown on your comments and in the member list.">
        <ProfileForm initial={profile} onSave={onSaveProfile} timezones={timezones} />
      </SettingsSection>
      <div className="h-px bg-border" />
      <SettingsSection title="Notifications" description="Email updates for this workspace.">
        <NotificationList initial={notifications} onChange={onNotificationChange} />
      </SettingsSection>
      <div className="h-px bg-border" />
      <SettingsSection title="Danger zone">
        <DeleteWorkspace name={workspaceName} onDelete={onDeleteWorkspace} />
      </SettingsSection>
    </div>
  );
}