recipes/recipe-card.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
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 , '' ],
]
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' )} `
}
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 >
)
}