Seed shelf UI: source links, lots, and what's left (#51) (#68)
Build image / build-and-push (push) Successful in 11s

Co-authored-by: Steve Dudenhoeffer <[email protected]>
This commit was merged in pull request #68.
This commit is contained in:
2026-07-21 06:03:12 +00:00
committed by steve
parent 7f8b5254d0
commit 5d9b10d7c7
15 changed files with 1067 additions and 11 deletions
@@ -0,0 +1,50 @@
import { useState } from 'react'
import { Alert } from '@/components/ui/Alert'
import { Button } from '@/components/ui/Button'
import { Modal } from '@/components/ui/Modal'
import { errorMessage } from '@/lib/api'
import { formatQuantity, useDeleteSeedLot, type SeedLot } from '@/lib/seedLots'
/**
* Retire a lot. Worth confirming because it's the one place cost and germination
* data lives — and worth saying plainly that the plantings survive it, since
* "will this wipe my garden" is the reasonable fear.
*/
export function DeleteSeedLotModal({ lot, onClose }: { lot: SeedLot; onClose: () => void }) {
const del = useDeleteSeedLot()
const [error, setError] = useState<string | null>(null)
return (
<Modal title="Retire this seed lot?" onClose={onClose} busy={del.isPending}>
<div className="flex flex-col gap-3">
<p className="text-sm text-fg">
{formatQuantity(lot.quantity)} {lot.unit}
{lot.vendor ? ` from ${lot.vendor}` : ''}
{lot.packedForYear != null ? `, packed for ${lot.packedForYear}` : ''}.
</p>
<p className="text-sm text-muted">
Anything planted from it stays exactly where it is it just stops being attributed to this purchase.
</p>
{error && <Alert>{error}</Alert>}
<div className="mt-1 flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={onClose} disabled={del.isPending}>
Cancel
</Button>
<Button
type="button"
variant="danger"
disabled={del.isPending}
onClick={() =>
del.mutate(lot.id, {
onSuccess: onClose,
onError: (err) => setError(errorMessage(err, 'Could not retire the lot.')),
})
}
>
{del.isPending ? 'Retiring…' : 'Retire lot'}
</Button>
</div>
</div>
</Modal>
)
}
+51 -1
View File
@@ -1,6 +1,10 @@
import { useState } from 'react'
import { PlantIcon } from './PlantIcon'
import { LotStateChip, SeedLotList } from './SeedLotList'
import { SourceLink } from './SourceLink'
import { cardActionClass, cardDangerClass } from '@/components/ui/cardActions'
import { CATEGORY_LABELS, isBuiltin, type Plant } from '@/lib/plants'
import { formatQuantity, summarizeLots, type SeedLot } from '@/lib/seedLots'
import { formatSpacing, type UnitPref } from '@/lib/units'
/**
@@ -11,17 +15,30 @@ import { formatSpacing, type UnitPref } from '@/lib/units'
export function PlantCard({
plant,
unit,
lots,
onEdit,
onDelete,
onDuplicate,
onAddLot,
onEditLot,
onDeleteLot,
}: {
plant: Plant
unit: UnitPref
/** This plant's purchases. A lot may reference a built-in, so even a built-in
* card can carry seed. */
lots: SeedLot[]
onEdit: () => void
onDelete: () => void
onDuplicate: () => void
onAddLot: () => void
onEditLot: (lot: SeedLot) => void
onDeleteLot: (lot: SeedLot) => void
}) {
const builtin = isBuiltin(plant)
const [showLots, setShowLots] = useState(false)
const summary = summarizeLots(lots)
return (
<div className="flex flex-col rounded-xl border border-border bg-surface">
<div className="flex items-start gap-3 p-4">
@@ -38,6 +55,12 @@ export function PlantCard({
<p className="mt-0.5 text-sm text-muted">
{CATEGORY_LABELS[plant.category]} · {formatSpacing(plant.spacingCm, unit)} spacing
</p>
{(plant.vendor || plant.sourceUrl) && (
<p className="mt-0.5 flex flex-wrap items-center gap-1.5 text-xs text-muted">
{plant.vendor && <span>{plant.vendor}</span>}
<SourceLink url={plant.sourceUrl} />
</p>
)}
{plant.notes && <p className="mt-1 line-clamp-2 text-xs text-muted">{plant.notes}</p>}
</div>
<span
@@ -46,7 +69,34 @@ export function PlantCard({
title={plant.color}
/>
</div>
<div className="flex justify-end gap-1 border-t border-border px-2 py-1.5">
{showLots && (
<div className="border-t border-border px-3 py-2">
<SeedLotList lots={lots} canEdit onAdd={onAddLot} onEdit={onEditLot} onDelete={onDeleteLot} />
</div>
)}
<div className="flex items-center justify-end gap-1 border-t border-border px-2 py-1.5">
{/* The seed count sits with the actions rather than in the body: it's
what you scan for down a list of twenty packets, so it wants a fixed
place on the card. */}
<button
type="button"
onClick={() => setShowLots((v) => !v)}
className={`${cardActionClass} mr-auto flex items-center gap-1.5`}
aria-expanded={showLots}
>
{lots.length === 0 ? (
<span className="text-muted">No seed</span>
) : (
<>
<span className="tabular-nums">
{formatQuantity(summary.remaining)}
{summary.unit ? ` ${summary.unit}` : ''} left
</span>
<LotStateChip state={summary.state} />
</>
)}
</button>
<button type="button" onClick={onDuplicate} className={cardActionClass}>
Duplicate
</button>
@@ -16,6 +16,7 @@ import {
type PlantCategory,
type PlantInput,
} from '@/lib/plants'
import { safeExternalUrl } from '@/lib/seedLots'
import { cmFromSpacing, spacingFromCm, spacingUnitLabel, type UnitPref } from '@/lib/units'
const DEFAULT_COLOR = '#4a7c3f'
@@ -61,6 +62,8 @@ export function PlantFormModal({
const [color, setColor] = useState(expandHex(source?.color ?? DEFAULT_COLOR))
const [icon, setIcon] = useState(source?.icon ?? DEFAULT_ICON)
const [days, setDays] = useState(source?.daysToMaturity != null ? String(source.daysToMaturity) : '')
const [sourceUrl, setSourceUrl] = useState(source?.sourceUrl ?? '')
const [vendor, setVendor] = useState(source?.vendor ?? '')
const [notes, setNotes] = useState(source?.notes ?? '')
const [version, setVersion] = useState(plant?.version ?? 0)
const [conflict, setConflict] = useState<string | null>(null)
@@ -96,6 +99,14 @@ export function PlantFormModal({
daysToMaturity = d
}
// The server refuses anything that isn't http(s) with a host, but say so here
// rather than letting a paste of "johnnyseeds.com" come back as a generic
// error with no hint about which field or why.
if (sourceUrl.trim() && !safeExternalUrl(sourceUrl.trim())) {
setFormError('The source link needs to be a full http:// or https:// address.')
return
}
const input: PlantInput = {
name: name.trim(),
category,
@@ -103,6 +114,8 @@ export function PlantFormModal({
color,
icon: icon.trim(),
daysToMaturity,
sourceUrl: sourceUrl.trim(),
vendor: vendor.trim(),
notes: notes.trim(),
}
@@ -194,6 +207,27 @@ export function PlantFormModal({
onChange={(e) => setDays(e.target.value)}
/>
{/* Provenance for the variety itself. What you bought and what's left
of it is a seed lot, added from the plant card. */}
<div className="grid grid-cols-2 gap-3">
<TextField
label="Vendor"
name="vendor"
placeholder="Johnny's Selected Seeds"
value={vendor}
onChange={(e) => setVendor(e.target.value)}
/>
<TextField
label="Source link"
name="sourceUrl"
type="url"
inputMode="url"
placeholder="https://…"
value={sourceUrl}
onChange={(e) => setSourceUrl(e.target.value)}
/>
</div>
<TextArea label="Notes" name="notes" rows={2} value={notes} onChange={(e) => setNotes(e.target.value)} />
{formError && <Alert>{formError}</Alert>}
+161
View File
@@ -0,0 +1,161 @@
import { Button } from '@/components/ui/Button'
import { cn } from '@/lib/cn'
import { SourceLink } from './SourceLink'
import {
formatCost,
formatQuantity,
formatUnitCost,
lotState,
type LotState,
type SeedLot,
} from '@/lib/seedLots'
const STATE_LABEL: Record<LotState, string> = {
over: 'over-planted',
empty: 'empty',
low: 'low',
ok: 'in stock',
unknown: 'no count',
}
// Encoded in colour AND words, because this is the thing you skim down a list of
// twenty packets deciding what to order — a bare number doesn't survive that.
const STATE_CLASS: Record<LotState, string> = {
// "over" is a discrepancy to look at rather than a shortage to act on, so it
// reads as a distinct warning rather than sharing "low"'s styling.
over: 'bg-orange-500/25 text-orange-900 dark:text-orange-200',
empty: 'bg-red-500/15 text-red-800 dark:text-red-300',
low: 'bg-amber-500/20 text-amber-800 dark:text-amber-300',
ok: 'bg-accent/20 text-accent-strong',
unknown: 'bg-border/60 text-muted',
}
export function LotStateChip({ state, className }: { state: LotState; className?: string }) {
return (
<span
className={cn(
'shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide',
STATE_CLASS[state],
className,
)}
>
{STATE_LABEL[state]}
</span>
)
}
/** A proportional bar for how much of a lot is left, so the state reads before
* any of the text does. Omitted when there's no quantity to be a fraction of. */
function RemainingBar({ lot }: { lot: SeedLot }) {
if (lot.quantity <= 0) return null
const pct = Math.max(0, Math.min(100, (lot.remaining / lot.quantity) * 100))
const state = lotState(lot)
return (
<div className="mt-1 h-1 w-full overflow-hidden rounded-full bg-border/60">
<div
className={cn(
'h-full rounded-full',
state === 'ok' ? 'bg-accent' : state === 'low' ? 'bg-amber-500' : 'bg-red-500',
)}
style={{ width: `${pct}%` }}
/>
</div>
)
}
/**
* A plant's purchases: what came from where, and what's left of each.
*
* Two lots of the same variety are two separate rows with independent counts,
* which is the whole reason inventory lives on the purchase rather than on the
* plant (#50).
*/
export function SeedLotList({
lots,
canEdit,
onAdd,
onEdit,
onDelete,
}: {
lots: SeedLot[]
canEdit: boolean
onAdd: () => void
onEdit: (lot: SeedLot) => void
onDelete: (lot: SeedLot) => void
}) {
return (
<div className="flex flex-col gap-2">
{lots.length === 0 && (
<p className="text-xs text-muted">
No seed recorded. Add a lot to track what you bought and how much is left.
</p>
)}
{lots.map((lot) => (
<LotRow key={lot.id} lot={lot} canEdit={canEdit} onEdit={() => onEdit(lot)} onDelete={() => onDelete(lot)} />
))}
{canEdit && (
<Button variant="ghost" className="self-start px-2 py-1 text-xs" onClick={onAdd}>
+ Add seed lot
</Button>
)}
</div>
)
}
function LotRow({
lot,
canEdit,
onEdit,
onDelete,
}: {
lot: SeedLot
canEdit: boolean
onEdit: () => void
onDelete: () => void
}) {
const cost = formatCost(lot.costCents)
const unitCost = formatUnitCost(lot)
return (
<div className="rounded-lg border border-border px-2 py-1.5">
<div className="flex items-start gap-2">
<div className="min-w-0 flex-1">
<p className="flex flex-wrap items-center gap-1.5 text-sm text-fg">
<span className="font-medium tabular-nums">
{formatQuantity(lot.remaining)} / {formatQuantity(lot.quantity)} {lot.unit}
</span>
<LotStateChip state={lotState(lot)} />
</p>
<p className="mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs text-muted">
{lot.vendor && <span>{lot.vendor}</span>}
{lot.packedForYear != null && <span>packed for {lot.packedForYear}</span>}
{lot.purchasedAt && <span>bought {lot.purchasedAt}</span>}
{lot.germinationPct != null && <span>{lot.germinationPct}% germ.</span>}
{cost && <span>{unitCost ? `${cost} (${unitCost})` : cost}</span>}
<SourceLink url={lot.sourceUrl} />
</p>
<RemainingBar lot={lot} />
</div>
{canEdit && (
<div className="flex shrink-0 flex-col items-end">
<button
type="button"
onClick={onEdit}
className="rounded px-1.5 py-0.5 text-xs text-muted outline-none hover:text-fg focus-visible:ring-2 focus-visible:ring-accent/40"
>
Edit
</button>
<button
type="button"
onClick={onDelete}
className="rounded px-1.5 py-0.5 text-xs text-red-700 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-accent/40 dark:text-red-400"
>
Retire
</button>
</div>
)}
</div>
{lot.notes && <p className="mt-1 text-xs text-muted">{lot.notes}</p>}
</div>
)
}
+248
View File
@@ -0,0 +1,248 @@
import { useState, type FormEvent } from 'react'
import { Alert } from '@/components/ui/Alert'
import { Button } from '@/components/ui/Button'
import { Modal } from '@/components/ui/Modal'
import { Select } from '@/components/ui/Select'
import { TextArea } from '@/components/ui/TextArea'
import { TextField } from '@/components/ui/TextField'
import { errorMessage } from '@/lib/api'
import {
conflictSeedLot,
LOT_UNITS,
safeExternalUrl,
useCreateSeedLot,
useUpdateSeedLot,
type LotUnit,
type SeedLot,
} from '@/lib/seedLots'
import type { Plant } from '@/lib/plants'
/**
* Record a purchase, or correct one. Everything except quantity and unit is
* optional — the point is to make writing it down cheap enough to bother with,
* and a form that demands a SKU and a lot code gets skipped.
*/
export function SeedLotModal({
plant,
lot,
onClose,
}: {
plant: Plant
/** Editing an existing lot, or undefined to record a new one. */
lot?: SeedLot
onClose: () => void
}) {
const isEdit = !!lot
const create = useCreateSeedLot()
const update = useUpdateSeedLot()
const pending = create.isPending || update.isPending
// A new lot inherits the plant's vendor and source link, since the usual case
// is buying the variety you already recorded from the place you recorded it.
const [vendor, setVendor] = useState(lot?.vendor ?? plant.vendor ?? '')
const [sourceUrl, setSourceUrl] = useState(lot?.sourceUrl ?? plant.sourceUrl ?? '')
const [quantity, setQuantity] = useState(lot ? String(lot.quantity) : '')
const [unit, setUnit] = useState<LotUnit>(lot?.unit ?? 'seeds')
const [purchasedAt, setPurchasedAt] = useState(lot?.purchasedAt ?? '')
const [packedForYear, setPackedForYear] = useState(lot?.packedForYear != null ? String(lot.packedForYear) : '')
const [cost, setCost] = useState(lot?.costCents != null ? (lot.costCents / 100).toFixed(2) : '')
const [germination, setGermination] = useState(lot?.germinationPct != null ? String(lot.germinationPct) : '')
const [sku, setSku] = useState(lot?.sku ?? '')
const [lotCode, setLotCode] = useState(lot?.lotCode ?? '')
const [notes, setNotes] = useState(lot?.notes ?? '')
const [version, setVersion] = useState(lot?.version ?? 0)
const [conflict, setConflict] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
async function onSubmit(e: FormEvent) {
e.preventDefault()
setError(null)
setConflict(null)
const qty = quantity.trim() === '' ? 0 : Number(quantity)
if (!Number.isFinite(qty) || qty < 0) {
setError('Quantity must be a number, or left blank.')
return
}
if (sourceUrl.trim() && !safeExternalUrl(sourceUrl.trim())) {
setError('The source link needs to be a full http:// or https:// address.')
return
}
let year: number | null = null
if (packedForYear.trim()) {
const y = Number(packedForYear)
if (!Number.isInteger(y) || y < 1900 || y > 2200) {
setError('Packed-for year should be a four-digit year.')
return
}
year = y
}
let costCents: number | null = null
if (cost.trim()) {
const c = Number(cost)
if (!Number.isFinite(c) || c < 0) {
setError('Cost must be an amount, or left blank.')
return
}
costCents = Math.round(c * 100)
}
let germinationPct: number | null = null
if (germination.trim()) {
const g = Number(germination)
if (!Number.isFinite(g) || g < 0 || g > 100) {
setError('Germination is a percentage between 0 and 100.')
return
}
germinationPct = g
}
const input = {
plantId: plant.id,
vendor: vendor.trim(),
sourceUrl: sourceUrl.trim(),
sku: sku.trim(),
lotCode: lotCode.trim(),
purchasedAt: purchasedAt.trim() === '' ? null : purchasedAt.trim(),
packedForYear: year,
quantity: qty,
unit,
costCents,
germinationPct,
notes: notes.trim(),
}
try {
if (isEdit) {
await update.mutateAsync({ id: lot.id, version, ...input })
} else {
await create.mutateAsync(input)
}
onClose()
} catch (err) {
const current = conflictSeedLot(err)
if (current) {
// Someone edited this lot elsewhere. Rebase onto the fresh row so a
// re-save applies, rather than making them retype everything — the same
// contract every other version-guarded form here honours.
setVersion(current.version)
setVendor(current.vendor)
setSourceUrl(current.sourceUrl)
setQuantity(String(current.quantity))
setUnit(current.unit)
setPurchasedAt(current.purchasedAt ?? '')
setPackedForYear(current.packedForYear != null ? String(current.packedForYear) : '')
setCost(current.costCents != null ? (current.costCents / 100).toFixed(2) : '')
setGermination(current.germinationPct != null ? String(current.germinationPct) : '')
setSku(current.sku)
setLotCode(current.lotCode)
setNotes(current.notes)
setConflict('This lot changed elsewhere. The latest values are shown — review and save again.')
return
}
setError(errorMessage(err, isEdit ? 'Could not save the lot.' : 'Could not record the lot.'))
}
}
return (
<Modal title={isEdit ? 'Edit seed lot' : `Seed lot — ${plant.name}`} onClose={onClose} busy={pending}>
<form onSubmit={onSubmit} className="flex flex-col gap-3">
{conflict && <Alert tone="info">{conflict}</Alert>}
<div className="grid grid-cols-2 gap-3">
<TextField
label="Quantity"
name="quantity"
type="number"
inputMode="decimal"
step="any"
min="0"
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
/>
<Select
label="Unit"
name="unit"
value={unit}
onChange={(e) => setUnit(e.target.value as LotUnit)}
options={LOT_UNITS.map((u) => ({ value: u.value, label: u.label }))}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<TextField label="Vendor" name="vendor" value={vendor} onChange={(e) => setVendor(e.target.value)} />
<TextField
label="Source link"
name="sourceUrl"
type="url"
inputMode="url"
placeholder="https://…"
value={sourceUrl}
onChange={(e) => setSourceUrl(e.target.value)}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<TextField
label="Purchased"
name="purchasedAt"
type="date"
value={purchasedAt}
onChange={(e) => setPurchasedAt(e.target.value)}
/>
<TextField
label="Packed for"
name="packedForYear"
type="number"
inputMode="numeric"
placeholder="2026"
value={packedForYear}
onChange={(e) => setPackedForYear(e.target.value)}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<TextField
label="Cost"
name="cost"
type="number"
inputMode="decimal"
step="0.01"
min="0"
placeholder="4.99"
value={cost}
onChange={(e) => setCost(e.target.value)}
/>
<TextField
label="Germination %"
name="germination"
type="number"
inputMode="decimal"
step="any"
min="0"
max="100"
value={germination}
onChange={(e) => setGermination(e.target.value)}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<TextField label="SKU" name="sku" value={sku} onChange={(e) => setSku(e.target.value)} />
<TextField label="Lot code" name="lotCode" value={lotCode} onChange={(e) => setLotCode(e.target.value)} />
</div>
<TextArea label="Notes" name="lotNotes" rows={2} value={notes} onChange={(e) => setNotes(e.target.value)} />
{error && <Alert>{error}</Alert>}
<div className="mt-1 flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={onClose} disabled={pending}>
Cancel
</Button>
<Button type="submit" disabled={pending}>
{pending ? 'Saving…' : isEdit ? 'Save' : 'Record lot'}
</Button>
</div>
</form>
</Modal>
)
}
+27
View File
@@ -0,0 +1,27 @@
import { safeExternalUrl } from '@/lib/seedLots'
/**
* A link out to where seed came from.
*
* The href is a URL somebody pasted, so it is re-checked here before rendering
* and carries rel="noopener noreferrer" — the server scheme-checks it too (#50),
* but a link is rendered from whatever the client was handed, and "the backend
* validated it" is not a reason to hand javascript: to an anchor tag.
*
* Renders nothing at all when the URL is absent or unsafe, so callers don't each
* have to remember to guard.
*/
export function SourceLink({ url, label = 'source' }: { url: string; label?: string }) {
const safe = safeExternalUrl(url)
if (!safe) return null
return (
<a
href={safe}
target="_blank"
rel="noopener noreferrer"
className="underline decoration-dotted underline-offset-2 hover:text-fg"
>
{label}
</a>
)
}