# Recipe card

A recipe in the other sense: lemon ricotta pancakes with a servings stepper that rescales every quantity into kitchen fractions, an ingredient checklist, and a method you advance one step at a time, with a timer on the steps that need one. `Card`, `Heading`, `Badge`, `Button`, `Checkbox` and `toastInfo` compose it.

**Example: Lemon ricotta pancakes** (`examples/recipes/recipe-card.tsx`)

```tsx
'use client'

import { Badge, Body, Button, Card, Checkbox, Heading, Stack, Text, toastInfo } from '@blocks/design-system'
import { ChefHat, Clock, Flame, Minus, Pause, Play, Plus, RotateCcw, Timer } from 'lucide-react'
import { useEffect, useId, useState } from 'react'
import styles from './recipe-card.module.css'

const baseServings = 4

interface Ingredient {
  id: string
  amount: number
  unit?: [string, string]
  item: string | [string, string]
  note?: string
  /** Count things you can't halve, like eggs. */
  whole?: boolean
}

const ingredients: Ingredient[] = [
  { id: 'flour', amount: 1.5, unit: ['cup', 'cups'], item: 'all-purpose flour' },
  { id: 'sugar', amount: 2, unit: ['tbsp', 'tbsp'], item: 'sugar' },
  { id: 'baking-powder', amount: 2, unit: ['tsp', 'tsp'], item: 'baking powder' },
  { id: 'salt', amount: 0.25, unit: ['tsp', 'tsp'], item: 'fine salt' },
  { id: 'ricotta', amount: 1, unit: ['cup', 'cups'], item: 'whole-milk ricotta' },
  { id: 'milk', amount: 0.75, unit: ['cup', 'cups'], item: 'milk' },
  { id: 'eggs', amount: 3, item: ['egg', 'eggs'], whole: true },
  { id: 'lemon', amount: 1, item: ['lemon', 'lemons'], note: 'zested and juiced' },
  { id: 'butter', amount: 2, unit: ['tbsp', 'tbsp'], item: 'butter', note: 'for the pan' },
]

const steps = [
  { text: 'Whisk the flour, sugar, baking powder and salt in a large bowl.' },
  { text: 'In a second bowl, beat the ricotta, milk, eggs, lemon zest and half the juice until smooth.' },
  { text: 'Fold the wet mix into the dry until just combined. A few lumps are fine. Let it rest.', minutes: 5 },
  { text: 'Heat a skillet over medium-low and brush it with butter. Pour in ¼-cup scoops of batter.' },
  { text: 'Cook until bubbles set at the edges, then flip and cook the other side.', minutes: 3 },
  { text: 'Serve warm, with the rest of the lemon juice and a spoon of ricotta on top.' },
]

const fractions: [number, string][] = [
  [0, ''],
  [1 / 8, '⅛'],
  [1 / 4, '¼'],
  [1 / 3, '⅓'],
  [1 / 2, '½'],
  [2 / 3, '⅔'],
  [3 / 4, '¾'],
  [1, ''],
]

// 0.375 → "⅜" isn't on a measuring spoon, so snap to the nearest kitchen fraction.
function formatAmount(value: number) {
  const whole = Math.floor(value)
  const [fraction, glyph] = fractions.reduce((best, candidate) =>
    Math.abs(candidate[0] - (value - whole)) < Math.abs(best[0] - (value - whole)) ? candidate : best,
  )
  const wholePart = whole + (fraction === 1 ? 1 : 0)
  if (wholePart === 0 && !glyph) return null
  return `${wholePart || ''}${glyph}`
}

function scaleIngredient(ingredient: Ingredient, servings: number) {
  const scaled = (ingredient.amount * servings) / baseServings
  const amount = ingredient.whole ? Math.max(1, Math.round(scaled)) : scaled
  const formatted = formatAmount(amount)
  const plural = amount > 1
  const item = typeof ingredient.item === 'string' ? ingredient.item : ingredient.item[plural ? 1 : 0]
  const quantity = formatted
    ? [formatted, ingredient.unit?.[plural ? 1 : 0]].filter(Boolean).join(' ')
    : 'A pinch of'
  return { quantity, item }
}

function formatClock(seconds: number) {
  return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
}

// A recipe you cook from: scale it, tick off what's on the counter, and work
// through the method one step at a time with a timer where a step needs one.
export default function RecipeCard() {
  const [servings, setServings] = useState(baseServings)
  const [gathered, setGathered] = useState<string[]>([])
  const [current, setCurrent] = useState(0)
  const [timer, setTimer] = useState<{ step: number; remaining: number; running: boolean } | null>(null)
  const id = useId()

  const running = timer?.running ?? false
  useEffect(() => {
    if (!running) return
    const interval = window.setInterval(() => {
      setTimer((previous) => (previous ? { ...previous, remaining: previous.remaining - 1 } : previous))
    }, 1000)
    return () => window.clearInterval(interval)
  }, [running])

  useEffect(() => {
    if (timer?.running && timer.remaining <= 0) {
      setTimer(null)
      toastInfo(`Step ${timer.step + 1} timer is done`, { description: steps[timer.step]?.text })
    }
  }, [timer])

  function toggleGathered(ingredientId: string, checked: boolean) {
    setGathered(checked ? [...gathered, ingredientId] : gathered.filter((other) => other !== ingredientId))
  }

  return (
    <Card as="article" aria-labelledby={`${id}-title`} padding="none" dangerouslySetClassName={styles.card}>
      <header className={styles.hero}>
        <span className={styles.mark} aria-hidden>
          <ChefHat size={28} />
        </span>
        <Stack gap="xs">
          <Text fontSize="xs" fontWeight="semibold" color="accent-text" dangerouslySetClassName={styles.kicker}>
            Weekend brunch
          </Text>
          <Heading as="h3" id={`${id}-title`} fontSize="xl">
            Lemon ricotta pancakes
          </Heading>
          <Body margin="none" color="text-muted">
            Tall, tender and bright with zest. The ricotta keeps them custardy in the middle.
          </Body>
        </Stack>
        <dl className={styles.meta}>
          <div>
            <dt>
              <Clock aria-hidden size={14} /> Prep
            </dt>
            <dd>10 min</dd>
          </div>
          <div>
            <dt>
              <Flame aria-hidden size={14} /> Cook
            </dt>
            <dd>20 min</dd>
          </div>
          <div>
            <dt>Difficulty</dt>
            <dd>
              <Badge tone="success">Easy</Badge>
            </dd>
          </div>
        </dl>
      </header>

      <div className={styles.body}>
        <section aria-labelledby={`${id}-ingredients`} className={styles.ingredients}>
          <Stack direction="row" justify="space-between" align="center" gap="sm" wrap="wrap">
            <Heading as="h4" id={`${id}-ingredients`} fontSize="md">
              Ingredients
            </Heading>
            <fieldset className={styles.stepper}>
              <legend className={styles.visuallyHidden}>Servings</legend>
              <Button
                type="button"
                size="sm"
                variant="ghost"
                aria-label="Fewer servings"
                disabled={servings <= 1}
                onClick={() => setServings(servings - 1)}
              >
                <Minus aria-hidden size={14} />
              </Button>
              <output aria-live="polite" className={styles.servings}>
                {servings} {servings === 1 ? 'serving' : 'servings'}
              </output>
              <Button
                type="button"
                size="sm"
                variant="ghost"
                aria-label="More servings"
                disabled={servings >= 12}
                onClick={() => setServings(servings + 1)}
              >
                <Plus aria-hidden size={14} />
              </Button>
            </fieldset>
          </Stack>
          <Text as="p" fontSize="sm" color="text-muted" margin="none">
            {gathered.length} of {ingredients.length} on the counter
          </Text>
          <ul className={styles.list}>
            {ingredients.map((ingredient) => {
              const { quantity, item } = scaleIngredient(ingredient, servings)
              return (
                <li key={ingredient.id}>
                  <Checkbox
                    checked={gathered.includes(ingredient.id)}
                    onCheckedChange={(checked) => toggleGathered(ingredient.id, checked)}
                  >
                    <span className={styles.ingredient}>
                      <strong>{quantity}</strong> {item}
                      {ingredient.note && <span className={styles.note}>, {ingredient.note}</span>}
                    </span>
                  </Checkbox>
                </li>
              )
            })}
          </ul>
        </section>

        <section aria-labelledby={`${id}-method`} className={styles.method}>
          <Stack direction="row" justify="space-between" align="center" gap="sm">
            <Heading as="h4" id={`${id}-method`} fontSize="md">
              Method
            </Heading>
            <Text fontSize="xs" color="text-muted" role="status">
              Step {current + 1} of {steps.length}
            </Text>
          </Stack>
          <ol className={styles.steps}>
            {steps.map((step, index) => {
              const isCurrent = index === current
              const stepTimer = timer?.step === index ? timer : null
              return (
                <li
                  key={step.text}
                  aria-current={isCurrent ? 'step' : undefined}
                  data-state={index < current ? 'done' : isCurrent ? 'current' : 'upcoming'}
                  className={styles.step}
                >
                  <span className={styles.number} aria-hidden>
                    {index + 1}
                  </span>
                  <Stack gap="sm" align="start">
                    <Text as="p" margin="none">
                      {step.text}
                    </Text>
                    {step.minutes && (
                      <Stack direction="row" gap="sm" align="center">
                        <Button
                          type="button"
                          size="sm"
                          variant={isCurrent ? 'primary' : 'ghost'}
                          onClick={() =>
                            setTimer(
                              stepTimer
                                ? { ...stepTimer, running: !stepTimer.running }
                                : { step: index, remaining: step.minutes * 60, running: true },
                            )
                          }
                        >
                          {stepTimer?.running ? <Pause aria-hidden size={14} /> : stepTimer ? <Play aria-hidden size={14} /> : <Timer aria-hidden size={14} />}
                          {stepTimer ? (stepTimer.running ? 'Pause' : 'Resume') : `Start ${step.minutes}-minute timer`}
                        </Button>
                        {stepTimer && (
                          <>
                            <span role="timer" aria-label={`Step ${index + 1} timer`} className={styles.clock}>
                              {formatClock(stepTimer.remaining)}
                            </span>
                            <Button type="button" size="sm" variant="ghost" aria-label="Reset timer" onClick={() => setTimer(null)}>
                              <RotateCcw aria-hidden size={14} />
                            </Button>
                          </>
                        )}
                      </Stack>
                    )}
                  </Stack>
                </li>
              )
            })}
          </ol>
          <Stack direction="row" justify="space-between" gap="sm">
            <Button type="button" variant="ghost" disabled={current === 0} onClick={() => setCurrent(current - 1)}>
              Previous step
            </Button>
            <Button
              type="button"
              variant="primary"
              disabled={current === steps.length - 1}
              onClick={() => setCurrent(current + 1)}
            >
              Next step
            </Button>
          </Stack>
        </section>
      </div>
    </Card>
  )
}
```

## How it works

- Quantities are stored as numbers for four servings and formatted at render: scaled, snapped to the nearest measuring-cup fraction (½, ⅓, ¾…), pluralized, and rounded to whole eggs. Too little salt to measure reads “A pinch of”.
- The stepper is a labelled group of two icon buttons around an `<output>` that announces the new serving count. The buttons disable at 1 and 12.
- Checking an ingredient strikes it through with `:has([data-checked])` on the Checkbox’s label, and the count above the list keeps the same fact in text.
- The current step carries `aria-current="step"` as well as its highlight. One timer runs at a time; it is a `role="timer"` (so it doesn’t announce every second) and a toast says when it finishes.
- The layout splits into two columns with a container query, so it reads as a card on a phone and a spread on a wide column.

## App-owned CSS

`examples/recipes/recipe-card.module.css`:

```css
.card {
  container-type: inline-size;
  overflow: hidden;
  background-color: var(--ds-color-bg);
}

.hero {
  display: grid;
  gap: var(--ds-space-lg);
  padding: var(--ds-space-xl) var(--ds-space-lg) var(--ds-space-lg);
  background:
    radial-gradient(circle at 100% 0%, color-mix(in srgb, var(--ds-color-accent) 14%, transparent), transparent 55%),
    var(--ds-color-bg-subtle);
  border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}

.mark {
  display: grid;
  place-items: center;
  width: calc(var(--ds-space-xl) + var(--ds-space-lg));
  aspect-ratio: 1;
  color: var(--ds-color-accent-text);
  background-color: var(--ds-color-bg);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-circle);
  box-shadow: var(--ds-shadow-sm);
}

.kicker {
  text-transform: uppercase;
}

.meta {
  display: flex;
  flex-wrap: wrap;
  gap: var(--ds-space-lg) var(--ds-space-xl);
  margin: 0;

  & dt {
    display: flex;
    align-items: center;
    gap: var(--ds-space-sm);
    font-size: var(--ds-font-size-xs);
    color: var(--ds-color-text-muted);
  }

  & dd {
    margin: var(--ds-space-xs) 0 0;
    font-weight: var(--ds-font-weight-semibold);
  }
}

.body {
  display: grid;
}

.ingredients,
.method {
  display: flex;
  flex-direction: column;
  gap: var(--ds-space-md);
  padding: var(--ds-space-lg);
}

.method {
  border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}

@container (min-width: 36rem) {
  .hero {
    grid-template-columns: auto 1fr;
    padding-inline: var(--ds-space-xl);
  }

  .meta {
    grid-column: 2;
  }

  .body {
    grid-template-columns: minmax(0, 5fr) minmax(0, 7fr);
  }

  .ingredients,
  .method {
    padding: var(--ds-space-xl);
  }

  .ingredients {
    background-color: var(--ds-color-bg-subtle);
  }

  .method {
    border-top: none;
    border-left: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  }
}

/* Servings stepper */
.stepper {
  display: inline-flex;
  align-items: center;
  gap: var(--ds-space-sm);
  min-width: 0;
  margin: 0;
  padding: 0;
  border: none;
}

.servings {
  min-width: calc(var(--ds-space-xxl) + var(--ds-space-lg));
  font-size: var(--ds-font-size-sm);
  font-weight: var(--ds-font-weight-semibold);
  font-variant-numeric: tabular-nums;
  text-align: center;
}

/* Ingredient checklist */
.list {
  display: flex;
  flex-direction: column;
  gap: var(--ds-space-md);
  margin: 0;
  padding: 0;
  list-style: none;
}

.ingredient {
  transition: color var(--ds-duration-fast) var(--ds-easing-standard);

  & strong {
    font-weight: var(--ds-font-weight-semibold);
    font-variant-numeric: tabular-nums;
  }
}

label:has([data-checked]) .ingredient {
  color: var(--ds-color-text-muted);
  text-decoration: line-through;
  text-decoration-color: var(--ds-color-border-strong);
}

.note {
  color: var(--ds-color-text-muted);
}

/* Method */
.steps {
  display: flex;
  flex-direction: column;
  gap: var(--ds-space-xs);
  margin: 0;
  padding: 0;
  list-style: none;
}

.step {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: var(--ds-space-md);
  padding: var(--ds-space-md);
  border-radius: var(--ds-border-radius-md);
  transition: background-color var(--ds-duration-normal) var(--ds-easing-standard);

  &[data-state="current"] {
    background-color: var(--ds-color-accent-subtle);
    box-shadow: inset var(--ds-border-width-lg) 0 0 var(--ds-color-accent);
  }

  &[data-state="done"] {
    color: var(--ds-color-text-muted);
  }
}

.number {
  display: grid;
  place-items: center;
  width: var(--ds-control-height-sm);
  aspect-ratio: 1;
  font-size: var(--ds-font-size-xs);
  font-weight: var(--ds-font-weight-bold);
  color: var(--ds-color-text-muted);
  border: var(--ds-border-width-sm) solid var(--ds-color-border);
  border-radius: var(--ds-border-radius-circle);

  [data-state="current"] > & {
    color: var(--ds-color-accent-fg);
    background-color: var(--ds-color-accent);
    border-color: var(--ds-color-accent);
  }

  [data-state="done"] > & {
    background-color: var(--ds-color-surface);
    border-color: var(--ds-color-surface);
  }
}

.clock {
  font-family: var(--ds-font-monospace);
  font-size: var(--ds-font-size-sm);
  font-weight: var(--ds-font-weight-semibold);
  font-variant-numeric: tabular-nums;
}

.visuallyHidden {
  position: absolute;
  width: var(--ds-space-xxs);
  height: var(--ds-space-xxs);
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

@media (prefers-reduced-motion: reduce) {
  .ingredient,
  .step {
    transition: none;
  }
}
```
