Files
pansy/web/src/lib/gardens.ts
T
steveandClaude Opus 4.8 3f61f07034
Build image / build-and-push (push) Successful in 7s
Address Gadfly review on #8: modal focus/close, dim validation, dedup
Fixes from the PR #27 adversarial review (considered; not graded).

Correctness / error-handling
- Modal: focus once on mount and attach the keydown listener once (latest
  onClose/busy via refs), so a parent re-render (e.g. a background refetch)
  no longer re-fires focus() and steals it from the input being typed in.
- Modal takes a `busy` prop; while a save/delete is in flight, Escape and
  backdrop clicks don't dismiss it (form/delete modals pass busy=pending),
  so an action can't be interrupted mid-flight and lose its error.
- Form validates the *converted* centimeter values against the server's
  [1cm, 100m] bounds, so sub-cm / over-100m sizes fail client-side with a
  clear message instead of a generic server error.
- displayFromCm rounds imperial to 0.1 ft so an 8 ft garden (244 cm)
  prefills as "8", not "8.01".

Maintainability
- Extracted ui/field.ts (useFieldId + fieldControlClass) shared by
  TextField/TextArea/Select. Added a `danger` Button variant, used by the
  delete modal; card edit/delete buttons gained focus-visible rings.
- useUpdateGarden takes the id in its mutation variables (no dummy 0 during
  create). GardensPage shares a close handler; dropped a redundant zod
  annotation; 409 rebase reuses dimString; renamed `del` -> `deletion`.

Verified in a browser: 8 ft round-trips to a prefilled "8"; a sub-cm value
is rejected client-side with the modal staying open. tsc clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
2026-07-18 19:03:49 -04:00

89 lines
2.6 KiB
TypeScript

// Gardens data layer: zod-validated shapes for /api/v1/gardens plus the
// react-query hooks the /gardens page uses.
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { z } from 'zod'
import { ApiError, api } from './api'
import type { UnitPref } from './units'
const unitPrefSchema = z.enum(['metric', 'imperial'])
export const gardenSchema = z.object({
id: z.number(),
ownerId: z.number(),
name: z.string(),
widthCm: z.number(),
heightCm: z.number(),
unitPref: unitPrefSchema,
notes: z.string(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
})
export type Garden = z.infer<typeof gardenSchema>
const gardensKey = ['gardens'] as const
export const gardensQueryOptions = queryOptions({
queryKey: gardensKey,
queryFn: async (): Promise<Garden[]> => z.array(gardenSchema).parse(await api.get('/gardens')),
})
export function useGardens() {
return useQuery(gardensQueryOptions)
}
export interface GardenInput {
name: string
widthCm: number
heightCm: number
unitPref: UnitPref
notes: string
}
export function useCreateGarden() {
const qc = useQueryClient()
return useMutation({
mutationFn: async (input: GardenInput): Promise<Garden> =>
gardenSchema.parse(await api.post('/gardens', input)),
onSuccess: () => qc.invalidateQueries({ queryKey: gardensKey }),
})
}
export interface GardenUpdate extends GardenInput {
id: number
version: number
}
export function useUpdateGarden() {
const qc = useQueryClient()
return useMutation({
// id travels with the mutation variables (not the hook) so callers don't need
// a placeholder id before a garden is chosen.
mutationFn: async ({ id, ...input }: GardenUpdate): Promise<Garden> =>
gardenSchema.parse(await api.patch(`/gardens/${id}`, input)),
onSuccess: () => qc.invalidateQueries({ queryKey: gardensKey }),
})
}
export function useDeleteGarden() {
const qc = useQueryClient()
return useMutation({
mutationFn: (id: number) => api.delete(`/gardens/${id}`),
onSuccess: () => qc.invalidateQueries({ queryKey: gardensKey }),
})
}
/**
* If err is a 409 version conflict, return the fresh server row it carries
* (under `current`), so a form can rebase onto it; otherwise null.
*/
export function conflictGarden(err: unknown): Garden | null {
if (err instanceof ApiError && err.isConflict && err.body && typeof err.body === 'object') {
const current = (err.body as { current?: unknown }).current
const parsed = gardenSchema.safeParse(current)
if (parsed.success) return parsed.data
}
return null
}