Blocks Design System

Profile settings

An account profile form in three sections separated by Separators. An initials avatar sits beside a “Change photo” Button; Fields hold the name, an @-prefixed username and a Textarea bio with a live character count; a Select picks the time zone. A save bar with Discard and Save appears only while the draft differs from the saved profile, and a toast confirms the save.

Profile

How you appear to teammates across Ledger.

Photo

Shown on your comments and in mentions.

MO

Public profile

Your name and bio appear on your profile card.

Teammates mention you as @maren.

A line about your work.70 characters left

Locale and links

Used for due dates, reminders and your profile link.

Time zone
Source · recipes/profile-settings.tsx
recipes/profile-settings.tsx
'use client'

import {
  BodySmall,
  Button,
  Field,
  Heading,
  Select,
  Separator,
  Stack,
  Text,
  Textarea,
  toastError,
  toastSuccess,
} from '@blocks/design-system'
import { type ChangeEvent, type FormEvent, type ReactNode, useId, useRef, useState } from 'react'
import styles from './profile-settings.module.css'

interface Profile {
  name: string
  username: string
  bio: string
  timeZone: string
  website: string
  photo: string | null
}

type Errors = Partial<Record<'name' | 'username' | 'website', string>>

const initialProfile: Profile = {
  name: 'Maren Okafor',
  username: 'maren',
  bio: 'Product designer on the Payments team. Usually sketching flows or hunting down edge cases.',
  timeZone: 'America/Denver',
  website: 'https://maren.example.com',
  photo: null,
}

const timeZones = [
  { value: 'Pacific/Honolulu', label: 'Hawaii (UTC−10:00)' },
  { value: 'America/Los_Angeles', label: 'Pacific Time (UTC−08:00)' },
  { value: 'America/Denver', label: 'Mountain Time (UTC−07:00)' },
  { value: 'America/Chicago', label: 'Central Time (UTC−06:00)' },
  { value: 'America/New_York', label: 'Eastern Time (UTC−05:00)' },
  { value: 'Europe/London', label: 'London (UTC+00:00)' },
  { value: 'Europe/Berlin', label: 'Berlin (UTC+01:00)' },
  { value: 'Asia/Kolkata', label: 'India (UTC+05:30)' },
  { value: 'Asia/Tokyo', label: 'Tokyo (UTC+09:00)' },
]

const bioLimit = 160

function initials(name: string) {
  const words = name.trim().split(/\s+/).filter(Boolean)
  return words.length === 0 ? '?' : words.map((word) => word[0]).join('').slice(0, 2).toUpperCase()
}

function validate(profile: Profile): Errors {
  const errors: Errors = {}
  if (!profile.name.trim()) errors.name = 'Enter the name teammates know you by.'
  if (!/^[a-z0-9_]{3,20}$/.test(profile.username)) {
    errors.username = 'Use 3–20 lowercase letters, numbers or underscores.'
  }
  if (profile.website && !URL.canParse(profile.website)) errors.website = 'Enter a full address, like https://example.com.'
  return errors
}

// App-owned layout: a heading and a sentence beside each group of fields.
function SettingsSection({ title, description, children }: { title: string; description: string; children: ReactNode }) {
  const headingId = useId()
  return (
    <section className={styles.section} aria-labelledby={headingId}>
      <Stack gap="xs">
        <Heading as="h4" id={headingId} fontSize="md" margin="none">
          {title}
        </Heading>
        <BodySmall color="text-muted" margin="none">
          {description}
        </BodySmall>
      </Stack>
      <Stack gap="lg">{children}</Stack>
    </section>
  )
}

// Account profile settings. The form compares a draft with the saved profile;
// the save bar only appears while they differ.
export default function ProfileSettings() {
  const titleId = useId()
  const title = useRef<HTMLHeadingElement>(null)
  const photoInput = useRef<HTMLInputElement>(null)
  const [savedProfile, setSavedProfile] = useState(initialProfile)
  const [draft, setDraft] = useState(initialProfile)
  // Errors appear on Save, then follow the fields as they're fixed.
  const [showErrors, setShowErrors] = useState(false)
  const errors = showErrors ? validate(draft) : {}

  const dirty = (Object.keys(draft) as (keyof Profile)[]).some((key) => draft[key] !== savedProfile[key])

  function update<Key extends keyof Profile>(key: Key, value: Profile[Key]) {
    setDraft((current) => ({ ...current, [key]: value }))
  }

  function choosePhoto(event: ChangeEvent<HTMLInputElement>) {
    const file = event.currentTarget.files?.[0]
    event.currentTarget.value = ''
    if (!file) return
    if (!file.type.startsWith('image/') || file.size > 2_000_000) {
      toastError('Choose a JPG, PNG or GIF under 2 MB.')
      return
    }
    const reader = new FileReader()
    reader.addEventListener('load', () => update('photo', String(reader.result)))
    reader.readAsDataURL(file)
  }

  // The save bar holds focus when it disappears, so hand focus back to the form.
  function finish(next: Profile) {
    setDraft(next)
    setShowErrors(false)
    title.current?.focus()
  }

  function save(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const firstInvalid = Object.keys(validate(draft))[0]
    if (firstInvalid) {
      setShowErrors(true)
      event.currentTarget.querySelector<HTMLElement>(`[name="${firstInvalid}"]`)?.focus()
      return
    }
    setSavedProfile(draft)
    finish(draft)
    toastSuccess('Profile saved')
  }

  return (
    <form className={styles.settings} noValidate onSubmit={save} aria-labelledby={titleId}>
      <Stack gap="xs">
        <Heading as="h3" id={titleId} ref={title} tabIndex={-1} fontSize="xl" margin="none">
          Profile
        </Heading>
        <BodySmall color="text-muted" margin="none">
          How you appear to teammates across Ledger.
        </BodySmall>
      </Stack>

      <SettingsSection title="Photo" description="Shown on your comments and in mentions.">
        <Stack direction="row" align="center" gap="lg" wrap="wrap">
          {/* A chosen photo is a local data URL, painted as the avatar's background. */}
          <span
            className={styles.avatar}
            role="img"
            aria-label={draft.photo ? 'Your chosen photo' : `Initials ${initials(draft.name)}`}
            style={draft.photo ? { backgroundImage: `url("${draft.photo}")` } : undefined}
          >
            {draft.photo ? null : initials(draft.name)}
          </span>
          <Stack direction="row" gap="sm" wrap="wrap">
            <Button type="button" onClick={() => photoInput.current?.click()}>
              Change photo
            </Button>
            {draft.photo && (
              <Button type="button" variant="ghost" onClick={() => update('photo', null)}>
                Remove
              </Button>
            )}
          </Stack>
          {/* The Button is the accessible control; this input only opens the picker. */}
          <input ref={photoInput} type="file" accept="image/*" hidden onChange={choosePhoto} />
        </Stack>
      </SettingsSection>

      <Separator />

      <SettingsSection title="Public profile" description="Your name and bio appear on your profile card.">
        <Field name="name" invalid={Boolean(errors.name)}>
          <Field.Label>Name</Field.Label>
          <Field.Control autoComplete="name" value={draft.name} onValueChange={(value) => update('name', value)} />
          {errors.name && <Field.Error match>{errors.name}</Field.Error>}
        </Field>

        <Field name="username" invalid={Boolean(errors.username)}>
          <Field.Label>Username</Field.Label>
          <div className={styles.prefixed}>
            <span className={styles.prefix} aria-hidden>
              @
            </span>
            <Field.Control
              autoComplete="username"
              spellCheck={false}
              value={draft.username}
              onValueChange={(value) => update('username', value.toLowerCase())}
              dangerouslySetClassName={styles.prefixedInput}
            />
          </div>
          <Field.Description>Teammates mention you as @{draft.username || 'username'}.</Field.Description>
          {errors.username && <Field.Error match>{errors.username}</Field.Error>}
        </Field>

        <Field name="bio">
          <Field.Label>Bio</Field.Label>
          <Field.Control
            render={<Textarea rows={3} />}
            maxLength={bioLimit}
            value={draft.bio}
            onValueChange={(value) => update('bio', value)}
          />
          <Field.Description render={<div className={styles.hint} />}>
            <span>A line about your work.</span>
            <span>{bioLimit - draft.bio.length} characters left</span>
          </Field.Description>
        </Field>
      </SettingsSection>

      <Separator />

      <SettingsSection title="Locale and links" description="Used for due dates, reminders and your profile link.">
        <Select items={timeZones} value={draft.timeZone} onValueChange={(value) => value && update('timeZone', value)}>
          <Select.Label>Time zone</Select.Label>
          <Select.Trigger />
          <Select.Content>
            {timeZones.map((zone) => (
              <Select.Item key={zone.value} value={zone.value}>
                {zone.label}
              </Select.Item>
            ))}
          </Select.Content>
        </Select>

        <Field name="website" invalid={Boolean(errors.website)}>
          <Field.Label>Website</Field.Label>
          <Field.Control
            type="url"
            inputMode="url"
            placeholder="https://"
            value={draft.website}
            onValueChange={(value) => update('website', value.trim())}
          />
          {errors.website && <Field.Error match>{errors.website}</Field.Error>}
        </Field>
      </SettingsSection>

      {dirty && (
        <section className={styles.saveBar} aria-label="Unsaved changes">
          <Text fontSize="sm" fontWeight="medium" role="status">
            You have unsaved changes
          </Text>
          <Stack direction="row" gap="sm">
            <Button type="button" variant="ghost" onClick={() => finish(savedProfile)}>
              Discard
            </Button>
            <Button type="submit" variant="primary">
              Save changes
            </Button>
          </Stack>
        </section>
      )}
    </form>
  )
}
Profile

How it works

  • Draft against saved. The form keeps a draft and the last saved profile; comparing them decides whether the save bar shows. Discard restores the saved copy, and both Save and Discard move focus to the form’s heading, because the bar that held focus disappears.
  • The avatar follows the name. Its initials update as you type. “Change photo” opens a hidden file input, reads the image as a data URL and paints it as the avatar’s background, so nothing loads from the network.
  • Prefix and count are decoration plus text. The “@” is drawn inside the input and hidden from screen readers; the description says how teammates mention you. The remaining character count is part of the bio’s Field.Description.
  • Sections reflow with their container. A container query sets each section’s heading beside its fields when there is room and above them on a phone.

App-owned CSS

The section layout, the avatar, the username prefix and the floating save bar.

recipes/profile-settings.module.css
/* Settings layout: label column beside fields when there's room, a floating save bar. */

.settings {
  container-type: inline-size;
  display: grid;
  gap: var(--ds-space-xl);
}

.section {
  display: grid;
  gap: var(--ds-space-lg);
}

@container (min-width: 34rem) {
  .section {
    grid-template-columns: 11rem minmax(0, 1fr);
    gap: var(--ds-space-xl);
  }
}

.avatar {
  display: grid;
  place-items: center;
  flex: none;
  width: calc(var(--ds-space-xl) * 2);
  height: calc(var(--ds-space-xl) * 2);
  overflow: hidden;
  font: var(--ds-font-weight-semibold) var(--ds-font-size-lg) / 1 var(--ds-font-heading);
  color: var(--ds-color-accent-text);
  background: var(--ds-color-accent-subtle);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-circle);
  background-size: cover;
  background-position: center;
}

/* An "@" inside the username input's border. */
.prefixed {
  position: relative;
}

.prefix {
  position: absolute;
  inset-block: 0;
  left: var(--ds-space-md);
  display: grid;
  place-items: center;
  font-size: var(--ds-font-size-sm);
  color: var(--ds-color-text-muted);
  pointer-events: none;
}

.prefixed .prefixedInput {
  padding-left: calc(var(--ds-space-md) + var(--ds-space-lg));
}

.hint {
  display: flex;
  justify-content: space-between;
  gap: var(--ds-space-md);

  /* The count keeps its place on the hint's line, right-aligned. */
  & span:last-child {
    flex: none;
    font-variant-numeric: tabular-nums;
  }
}

.saveBar {
  position: sticky;
  bottom: var(--ds-space-lg);
  z-index: var(--ds-z-sticky);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: var(--ds-space-md);
  padding: var(--ds-space-md) var(--ds-space-md) var(--ds-space-md) var(--ds-space-lg);
  background: var(--ds-color-surface);
  border: var(--ds-border-width-sm) solid var(--ds-color-border);
  border-radius: var(--ds-border-radius-xl);
  box-shadow: var(--ds-shadow-lg);
  animation: rise var(--ds-duration-normal) var(--ds-easing-emphasized);
}

@keyframes rise {
  from {
    opacity: 0;
    translate: 0 var(--ds-space-md);
  }
}

@media (prefers-reduced-motion: reduce) {
  .saveBar {
    animation: none;
  }
}