VehicleForm.tsx 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750
  1. 'use client'
  2. import { useEngineSizeUnit } from '@/components/engine-size-context'
  3. import { engineSizeHint, engineSizePlaceholder, engineSizeToSave } from '@/lib/engine-size'
  4. import { useState, useRef, useEffect, useId } from 'react'
  5. import { useRouter } from 'next/navigation'
  6. import Image from 'next/image'
  7. import { Button } from '@/components/ui/button'
  8. import { Input } from '@/components/ui/input'
  9. import { Label } from '@/components/ui/label'
  10. import { Checkbox } from '@/components/ui/checkbox'
  11. import {
  12. Dialog,
  13. DialogBody,
  14. DialogContent,
  15. DialogDescription,
  16. DialogFooter,
  17. DialogHeader,
  18. DialogTitle,
  19. } from '@/components/ui/dialog'
  20. import { DocsLink } from '@/components/docs-link'
  21. import { toast } from 'sonner'
  22. import { useFieldErrors } from '@/components/field-errors'
  23. import { useGlassModal } from '@/components/glass-modal'
  24. import { useDateSettings } from '@/components/date-settings-context'
  25. import { inspectionDueInput } from '../Lib/inspectionDueInput'
  26. import { VEHICLE_YEAR_MIN, vehicleYearMax } from '../Lib/vehicleYear'
  27. import type { RegistryLookup } from '../Lib/registryLookup'
  28. import { createVehicle, updateVehicle } from '../Actions/vehicleActions'
  29. import type { VehicleDocumentScan } from '../Actions/aiAnalyzeVehicleDocument'
  30. import { ScanDocumentButton } from './ScanDocumentButton'
  31. import { VehicleLookupButton } from './VehicleLookupButton'
  32. import { type BookingVehicle, openBooking, useBookingAccess } from '@/components/booking-launcher'
  33. import type { VehicleLookup } from '@/features/integrations/Actions/vehicleLookupActions'
  34. import { nameSimilarity } from '@/lib/name-similarity'
  35. import { Camera, Check, Loader2, Pencil, Plus, Trash2, X } from 'lucide-react'
  36. import { compressImage } from '@/lib/compress-image'
  37. import { CustomerForm } from '@/features/customers/Components/CustomerForm'
  38. import {
  39. createCustomer,
  40. findOwnerCandidates,
  41. getCustomerOption,
  42. } from '@/features/customers/Actions/customerActions'
  43. import { CustomerCombobox } from '@/features/quotes/Components/CustomerCombobox'
  44. import { useFormatter, useTranslations } from 'next-intl'
  45. import { useFormatDate } from '@/lib/use-format-date'
  46. import { useServiceType } from '@/components/service-type-context'
  47. import type { CreateVehicleInput } from '../Schema/vehicleSchema'
  48. import { clearableInput } from '@/lib/clearable'
  49. import { useTypeKeyEnabled } from '@/components/type-key-context'
  50. import { HSN_PATTERN, normalizeHsn, normalizeTsn, TSN_PATTERN } from '../Lib/typeKey'
  51. import { FLEET_NUMBER_MAX_LENGTH, fleetNumberTooLong } from '../Lib/fleetNumber'
  52. import { useFleetNumberEnabled } from '@/components/fleet-number-context'
  53. import { useHasRecordCustomFields } from '@/components/record-custom-fields-context'
  54. import {
  55. CustomFieldsForm,
  56. type CustomFieldsSave,
  57. } from '@/features/custom-fields/Components/CustomFieldsForm'
  58. import { customFieldsRefusal } from '@/features/custom-fields/Lib/customFieldsRefusal'
  59. import type { CustomFieldError } from '@/features/custom-fields/Lib/customFieldValueRules'
  60. import { handleGated } from '@/components/upgrade-gate'
  61. import { PlateChip } from '@/components/plate-chip'
  62. import { StatusLamp, type LampTone } from '@/components/status-lamp'
  63. import { cn } from '@/lib/utils'
  64. import { PhotoHandoffButton } from './service-page/PhotoHandoffButton'
  65. import { ReadingNotice, useReadingNotice } from './ReadingNotice'
  66. import { ReadingConfirmDialog } from './ReadingConfirmDialog'
  67. import { readingNeedsAnswer } from '../Lib/vehicleReading'
  68. /**
  69. * How alike two names must read before the scanned keeper is offered as an
  70. * existing customer rather than a new one.
  71. */
  72. const OWNER_MATCH_THRESHOLD = 0.9
  73. interface CustomerOption {
  74. id: string
  75. name: string
  76. company: string | null
  77. }
  78. interface OwnerMatch {
  79. customer: CustomerOption
  80. score: number
  81. }
  82. interface VehicleFormProps {
  83. open: boolean
  84. onOpenChange: (open: boolean) => void
  85. vehicle?: {
  86. id: string
  87. make: string
  88. model: string
  89. year: number
  90. vin?: string | null
  91. licensePlate?: string | null
  92. color?: string | null
  93. mileage: number
  94. fuelType?: string | null
  95. transmission?: string | null
  96. engineSize?: string | null
  97. engineCode?: string | null
  98. hsn?: string | null
  99. tsn?: string | null
  100. fleetNumber?: string | null
  101. imageUrl?: string | null
  102. customerId?: string | null
  103. /** The owner, so the selector can name them without loading every customer */
  104. customer?: CustomerOption | null
  105. inspectionStatus?: { dueAt: Date | string | null; source?: string } | null
  106. }
  107. /** Preselects the customer when creating a new vehicle (ignored when editing) */
  108. defaultCustomerId?: string
  109. /** The preselected customer itself, when the caller has it, to name it without a lookup */
  110. defaultCustomer?: CustomerOption | null
  111. /**
  112. * What a registry already said about the plate, for a form opened from the
  113. * plate lookup: filled in as if the search button had been pressed.
  114. */
  115. initialLookup?: VehicleLookup | null
  116. /**
  117. * A plate typed somewhere else, such as a vehicle search that found
  118. * nothing: the new vehicle starts with it in the plate field and the cursor
  119. * there, so Enter asks the registry where one is connected. An empty string
  120. * only puts the cursor there. Nothing is looked up until the person asks.
  121. */
  122. initialPlate?: string
  123. /**
  124. * Offers "Delete vehicle" in the footer, for a page that has its own
  125. * confirmation to hand the delete to. Left out where nothing should be deleted.
  126. */
  127. onDelete?: () => void
  128. /** "km" or "mi", where the caller knows it, shown beside the mileage. */
  129. distanceUnit?: string
  130. /**
  131. * Handed the vehicle just added, for a caller that goes on with it: the
  132. * booking dialog selects it, the work order picker opens its work order.
  133. * Without one, the form itself offers to book the new vehicle in.
  134. */
  135. onCreated?: (vehicle: BookingVehicle) => void
  136. /**
  137. * The owner is the one given and cannot be changed here: a vehicle added
  138. * to a job that already has its customer has to belong to that customer.
  139. */
  140. ownerLocked?: boolean
  141. /**
  142. * The id of the box to put the cursor in when the form opens, for a caller
  143. * that opens it from one detail of the vehicle. Without it the form opens
  144. * as it always has.
  145. */
  146. focusField?: string | null
  147. }
  148. export function VehicleForm({
  149. open,
  150. onOpenChange,
  151. vehicle,
  152. defaultCustomerId,
  153. defaultCustomer,
  154. initialLookup,
  155. initialPlate,
  156. onDelete,
  157. distanceUnit,
  158. onCreated,
  159. ownerLocked = false,
  160. focusField = null,
  161. }: VehicleFormProps) {
  162. const { canBook } = useBookingAccess()
  163. const serviceType = useServiceType()
  164. const isMarine = serviceType === 'marine'
  165. // Only a workshop that switched the type key on sees the two boxes; a hidden
  166. // pair is left out of the save, so what a vehicle already has is kept.
  167. const showTypeKey = useTypeKeyEnabled() && !isMarine
  168. const showFleetNumber = useFleetNumberEnabled()
  169. // The workshop's own fields for a vehicle, when it has defined any. They
  170. // save through their own action: checked before the vehicle is written,
  171. // saved under its id once it has one.
  172. const hasCustomFields = useHasRecordCustomFields('vehicle')
  173. const customFieldsSave = useRef<CustomFieldsSave | null>(null)
  174. // A closed dialog holds no fields: the next one registers its own save.
  175. useEffect(() => {
  176. if (!open) customFieldsSave.current = null
  177. }, [open])
  178. const router = useRouter()
  179. const modal = useGlassModal()
  180. const t = useTranslations('vehicles.form')
  181. const tCustom = useTranslations('settings.customFields')
  182. const tDetail = useTranslations('vehicles.detail')
  183. const { timezone } = useDateSettings()
  184. const tc = useTranslations('common.buttons')
  185. const tCommon = useTranslations('common')
  186. const format = useFormatter()
  187. const { formatDay } = useFormatDate()
  188. const [loading, setLoading] = useState(false)
  189. // What the server refused, said under each field it was about.
  190. const fieldErrors = useFieldErrors()
  191. const { reset: resetFieldErrors } = fieldErrors
  192. useEffect(() => {
  193. if (!open) resetFieldErrors()
  194. }, [open, resetFieldErrors])
  195. const [preview, setPreview] = useState<string | null>(vehicle?.imageUrl ?? null)
  196. const [imageFile, setImageFile] = useState<File | null>(null)
  197. const [selectedCustomerId, setSelectedCustomerId] = useState<string>(
  198. vehicle?.customerId || defaultCustomerId || 'none'
  199. )
  200. const [showCustomerForm, setShowCustomerForm] = useState(false)
  201. // The customer list is searched on the server: a workshop can have tens of
  202. // thousands, and loading them all slowed every page that offers this form.
  203. const initialCustomer =
  204. vehicle?.customer ??
  205. (!vehicle && defaultCustomer?.id === defaultCustomerId ? defaultCustomer : null) ??
  206. null
  207. const [selectedCustomer, setSelectedCustomer] = useState<CustomerOption | null>(initialCustomer)
  208. const [fuelType, setFuelType] = useState(vehicle?.fuelType ?? 'gasoline')
  209. const defaultTransmission = vehicle?.transmission ?? (isMarine ? 'outboard' : 'automatic')
  210. const [transmission, setTransmission] = useState(defaultTransmission)
  211. /** What the registry said about the plate, kept under the field until the dialog closes. */
  212. const [lookupNote, setLookupNote] = useState<VehicleLookup | null>(null)
  213. // The registry lookup made on this form, sent with the save so the answer
  214. // is stored as the registry's, checked now, and not looked up again. The
  215. // server keeps it only while the plate or VIN it was about is still the one saved.
  216. const lookupRef = useRef<RegistryLookup | null>(null)
  217. /** The inspection date the form opened with; a field still holding it was not edited. */
  218. const openedInspectionDue = vehicle?.inspectionStatus?.dueAt
  219. ? inspectionDueInput(vehicle.inspectionStatus.dueAt, vehicle.inspectionStatus.source, timezone)
  220. : ''
  221. const fieldValue = (name: string) =>
  222. (formRef.current?.elements.namedItem(name) as HTMLInputElement | null)?.value ?? ''
  223. /** Keeper read off a scanned document, until it is tied to a customer. */
  224. const [scannedOwner, setScannedOwner] = useState<{ name?: string; address?: string } | null>(null)
  225. const [ownerMatches, setOwnerMatches] = useState<OwnerMatch[]>([])
  226. /** Whether saving should also create the keeper as a customer. */
  227. const [addOwner, setAddOwner] = useState(true)
  228. const [showOwnerMatch, setShowOwnerMatch] = useState(false)
  229. // The keeper is looked up on the server. Saving waits for the answer, or a
  230. // quick save would add them again; a newer scan, another vehicle or closing
  231. // the form makes an answer still on its way stale, and it is dropped.
  232. const [ownerLookupPending, setOwnerLookupPending] = useState(false)
  233. const ownerLookupRef = useRef(0)
  234. const dropOwnerLookup = () => {
  235. ownerLookupRef.current++
  236. setOwnerLookupPending(false)
  237. setShowOwnerMatch(false)
  238. }
  239. const fileRef = useRef<HTMLInputElement>(null)
  240. const formRef = useRef<HTMLFormElement>(null)
  241. // What a few fields hold right now, for the summary at the top, the VIN's
  242. // length and the colour swatch. The fields themselves stay uncontrolled:
  243. // scans and lookups write into them directly, then call readDrafts.
  244. const [mileageDraft, setMileageDraft] = useState(vehicle ? String(vehicle.mileage) : '')
  245. /** A reading far above the saved one, waiting for the person's answer on Save. */
  246. const [readingToConfirm, setReadingToConfirm] = useState<number | null>(null)
  247. /** The reading they said yes to: not asked about again. */
  248. const confirmedReadingRef = useRef<number | null>(null)
  249. // The mileage in the summary can be changed where it is read, without
  250. // going down to the field: a reading is the one thing changed every visit.
  251. const [editingMileage, setEditingMileage] = useState(false)
  252. const mileageBeforeEdit = useRef('')
  253. const [inspectionDraft, setInspectionDraft] = useState(openedInspectionDue)
  254. const [vinDraft, setVinDraft] = useState(vehicle?.vin ?? '')
  255. const [colorDraft, setColorDraft] = useState(vehicle?.color ?? '')
  256. // Mileage is not read back here: both places that edit it set it directly,
  257. // and reading the field during an edit in the header would undo the edit.
  258. const readDrafts = () => {
  259. setInspectionDraft(fieldValue('inspectionDueAt'))
  260. setVinDraft(fieldValue('vin'))
  261. setColorDraft(fieldValue('color'))
  262. }
  263. /** Back to what the vehicle has saved, for a form opened again or on another vehicle. */
  264. const resetDrafts = () => {
  265. setEditingMileage(false)
  266. setMileageDraft(vehicle ? String(vehicle.mileage) : '')
  267. // A yes was for that vehicle and that reading; the next one is asked again.
  268. confirmedReadingRef.current = null
  269. setReadingToConfirm(null)
  270. setInspectionDraft(openedInspectionDue)
  271. setVinDraft(vehicle?.vin ?? '')
  272. setColorDraft(vehicle?.color ?? '')
  273. }
  274. // Sync state when vehicle prop changes (e.g. opening edit for a different vehicle)
  275. useEffect(() => {
  276. setSelectedCustomerId(vehicle?.customerId || defaultCustomerId || 'none')
  277. setSelectedCustomer(
  278. vehicle?.customer ??
  279. (!vehicle && defaultCustomer?.id === defaultCustomerId ? defaultCustomer : null) ??
  280. null
  281. )
  282. setPreview(vehicle?.imageUrl ?? null)
  283. setImageFile(null)
  284. resetDrafts()
  285. setFuelType(vehicle?.fuelType ?? 'gasoline')
  286. setTransmission(vehicle?.transmission ?? (isMarine ? 'outboard' : 'automatic'))
  287. setLookupNote(null)
  288. setScannedOwner(null)
  289. setOwnerMatches([])
  290. setAddOwner(true)
  291. dropOwnerLookup()
  292. // resetDrafts reads the same vehicle fields listed here.
  293. // eslint-disable-next-line react-hooks/exhaustive-deps
  294. }, [
  295. vehicle?.id,
  296. vehicle?.customerId,
  297. vehicle?.fuelType,
  298. vehicle?.transmission,
  299. isMarine,
  300. defaultCustomerId,
  301. defaultCustomer?.id,
  302. vehicle?.customer?.id,
  303. ])
  304. // A new photo saved from elsewhere (the phone, while this form is open) is
  305. // shown without throwing away anything typed here; a photo picked in this
  306. // form and not yet saved wins.
  307. useEffect(() => {
  308. if (!imageFile) setPreview(vehicle?.imageUrl ?? null)
  309. // Only the saved photo moving should move the preview.
  310. // eslint-disable-next-line react-hooks/exhaustive-deps
  311. }, [vehicle?.imageUrl])
  312. // A customer preselected by id alone (a link with ?customerId=) still needs a name
  313. useEffect(() => {
  314. if (!open || selectedCustomerId === 'none' || selectedCustomer?.id === selectedCustomerId)
  315. return
  316. let cancelled = false
  317. getCustomerOption(selectedCustomerId).then((result) => {
  318. if (cancelled || !result.success || !result.data) return
  319. setSelectedCustomer(result.data)
  320. })
  321. return () => {
  322. cancelled = true
  323. }
  324. }, [open, selectedCustomerId, selectedCustomer?.id])
  325. const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
  326. const file = e.target.files?.[0]
  327. if (!file) return
  328. if (file.size > 5 * 1024 * 1024) {
  329. modal.open('error', t('imageTooLarge'), t('maxFileSize'))
  330. return
  331. }
  332. setImageFile(file)
  333. setPreview(URL.createObjectURL(file))
  334. }
  335. const clearImage = () => {
  336. setImageFile(null)
  337. setPreview(null)
  338. if (fileRef.current) fileRef.current.value = ''
  339. }
  340. /** Uploads the photo picked in this form and answers its address. */
  341. const uploadImage = async (file: File): Promise<string> => {
  342. const toastId = toast.loading(t('uploadingImage'))
  343. const compressed = await compressImage(file)
  344. const formData = new FormData()
  345. formData.append('file', compressed)
  346. const res = await fetch('/api/protected/upload', { method: 'POST', body: formData })
  347. if (!res.ok) {
  348. const err = await res.json()
  349. toast.error(err.error || t('uploadFailed'), { id: toastId })
  350. throw new Error(err.error || t('uploadFailed'))
  351. }
  352. const { url } = await res.json()
  353. toast.success(t('imageUploaded'), { id: toastId })
  354. return url
  355. }
  356. const applyScan = (data: VehicleDocumentScan) => {
  357. const form = formRef.current
  358. if (!form) return
  359. const setIfEmpty = (name: string, value: string | undefined) => {
  360. if (!value) return
  361. const input = form.elements.namedItem(name) as HTMLInputElement | null
  362. if (input && !input.value) input.value = value
  363. }
  364. setIfEmpty('make', data.make)
  365. setIfEmpty('model', data.model)
  366. setIfEmpty('year', data.year ? String(data.year) : undefined)
  367. setIfEmpty('vin', data.vin)
  368. setIfEmpty('licensePlate', data.licensePlate)
  369. setIfEmpty('color', data.color)
  370. setIfEmpty('engineSize', data.engineSize)
  371. setIfEmpty('hsn', data.hsn)
  372. setIfEmpty('tsn', data.tsn)
  373. readDrafts()
  374. // A select has no empty state, so only fill it while it still holds the
  375. // value the form opened with.
  376. if (data.fuelType && fuelType === (vehicle?.fuelType ?? 'gasoline')) {
  377. setFuelType(data.fuelType)
  378. }
  379. if (!data.owner?.name || selectedCustomerId !== 'none') return
  380. setScannedOwner(data.owner)
  381. setAddOwner(true)
  382. // Near-identical names are still a judgement call: two brothers at one
  383. // address differ by a first name. Offer the close ones and let the user say.
  384. const ownerName = data.owner.name
  385. const lookup = ++ownerLookupRef.current
  386. setOwnerLookupPending(true)
  387. setOwnerMatches([])
  388. void findOwnerCandidates(ownerName)
  389. .then((result) => {
  390. if (lookup !== ownerLookupRef.current) return
  391. const candidates = (result.success && result.data ? result.data : [])
  392. .map((c) => ({
  393. customer: c,
  394. // Papers naming a business may match the company field rather than the
  395. // contact saved as the customer's name.
  396. score: Math.max(
  397. nameSimilarity(ownerName, c.name),
  398. c.company ? nameSimilarity(ownerName, c.company) : 0
  399. ),
  400. }))
  401. .filter((m) => m.score >= OWNER_MATCH_THRESHOLD)
  402. .sort((a, b) => b.score - a.score)
  403. .slice(0, 5)
  404. setOwnerMatches(candidates)
  405. if (candidates.length > 0) setShowOwnerMatch(true)
  406. })
  407. .finally(() => {
  408. if (lookup === ownerLookupRef.current) setOwnerLookupPending(false)
  409. })
  410. }
  411. /**
  412. * A registry answer fills the same fields as a scanned document, plus the
  413. * gearbox and engine code, which papers rarely state. The select only moves while it still
  414. * holds the value the form opened with.
  415. */
  416. const applyLookup = (data: VehicleLookup, asked: { by: 'plate' | 'vin'; value: string }) => {
  417. applyScan(data)
  418. const engineCode = formRef.current?.elements.namedItem('engineCode') as HTMLInputElement | null
  419. if (data.engineCode && engineCode && !engineCode.value) engineCode.value = data.engineCode
  420. if (data.inspectionDue) {
  421. const input = formRef.current?.elements.namedItem(
  422. 'inspectionDueAt'
  423. ) as HTMLInputElement | null
  424. // The registry's fresh date replaces an empty field, the date the form
  425. // opened with, or the date an earlier lookup wrote; a date the user
  426. // typed since stays.
  427. const earlier = lookupRef.current?.result.inspectionDue?.slice(0, 10)
  428. if (
  429. input &&
  430. (!input.value || input.value === openedInspectionDue || input.value === earlier)
  431. ) {
  432. input.value = data.inspectionDue.slice(0, 10)
  433. }
  434. }
  435. lookupRef.current = {
  436. connectorId: data.connectorId,
  437. by: asked.by,
  438. value: asked.value,
  439. result: data,
  440. }
  441. if (data.transmission && transmission === defaultTransmission) {
  442. setTransmission(data.transmission)
  443. }
  444. setLookupNote(data)
  445. readDrafts()
  446. }
  447. // The fields are uncontrolled, so the registry's answer is written once the
  448. // form has rendered, the same way the lookup button writes it.
  449. const appliedLookupRef = useRef<VehicleLookup | null>(null)
  450. useEffect(() => {
  451. if (!open || vehicle || !initialLookup) return
  452. if (appliedLookupRef.current === initialLookup) return
  453. appliedLookupRef.current = initialLookup
  454. const frame = requestAnimationFrame(() =>
  455. applyLookup(initialLookup, { by: 'plate', value: initialLookup.licensePlate ?? '' })
  456. )
  457. return () => cancelAnimationFrame(frame)
  458. // applyLookup reads the current form and selects; running it again on
  459. // their change would overwrite what the user has since typed.
  460. // eslint-disable-next-line react-hooks/exhaustive-deps
  461. }, [open, vehicle, initialLookup])
  462. useEffect(() => {
  463. if (!open || vehicle || initialPlate === undefined) return
  464. const frame = requestAnimationFrame(() => {
  465. const input = formRef.current?.elements.namedItem('licensePlate') as HTMLInputElement | null
  466. if (!input) return
  467. if (initialPlate && !input.value) input.value = initialPlate
  468. input.focus()
  469. })
  470. return () => cancelAnimationFrame(frame)
  471. }, [open, vehicle, initialPlate])
  472. // Opened from one detail on the vehicle's page: the cursor goes to its box,
  473. // scrolled into view, once the dialog has drawn it. The workshop's own
  474. // fields are fetched after the dialog opens, so theirs is looked for a
  475. // little longer before giving up.
  476. useEffect(() => {
  477. if (!open || !focusField) return
  478. let tries = 0
  479. let frame = 0
  480. const look = () => {
  481. const field = formRef.current?.querySelector<HTMLElement>(`#${CSS.escape(focusField)}`)
  482. if (!field) {
  483. if (++tries < 120) frame = requestAnimationFrame(look)
  484. return
  485. }
  486. // Only the dialog's scrolling body moves: a box at its very end would
  487. // otherwise have the browser scroll the dialog itself to centre it,
  488. // pushing the header out of sight.
  489. const body = field.closest<HTMLElement>('[data-slot="dialog-body"]')
  490. if (body?.scrollTo) {
  491. const offset = field.getBoundingClientRect().top - body.getBoundingClientRect().top
  492. body.scrollTo({
  493. top: body.scrollTop + offset - (body.clientHeight - field.offsetHeight) / 2,
  494. })
  495. } else {
  496. field.scrollIntoView?.({ block: 'center' })
  497. }
  498. // Fuel and gearbox are a row of choices: the cursor goes to the one
  499. // picked (or the first), the stop the keyboard reaches.
  500. const target =
  501. field.getAttribute('role') === 'radiogroup'
  502. ? (field.querySelector<HTMLElement>('[tabindex="0"]') ?? field)
  503. : field
  504. target.focus({ preventScroll: true, focusVisible: true } as FocusOptions)
  505. }
  506. frame = requestAnimationFrame(look)
  507. return () => cancelAnimationFrame(frame)
  508. }, [open, focusField])
  509. useEffect(() => {
  510. if (!open) {
  511. appliedLookupRef.current = null
  512. lookupRef.current = null
  513. dropOwnerLookup()
  514. // Closed without saving: opened again, it shows what is saved, not
  515. // what was picked last time.
  516. resetDrafts()
  517. setFuelType(vehicle?.fuelType ?? 'gasoline')
  518. setTransmission(defaultTransmission)
  519. setLookupNote(null)
  520. setImageFile(null)
  521. setPreview(vehicle?.imageUrl ?? null)
  522. }
  523. // Only closing matters here; the values are read as they are then.
  524. // eslint-disable-next-line react-hooks/exhaustive-deps
  525. }, [open])
  526. const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
  527. e.preventDefault()
  528. // The save shortcut and Enter reach here past the disabled button
  529. if (ownerLookupPending) return
  530. // A changed reading far above the saved one is asked about first; the
  531. // answer Yes saves the form again with it, "Change it" saves nothing.
  532. const typedReading = mileageDraft.trim() === '' ? null : Number(mileageDraft)
  533. if (
  534. vehicle &&
  535. readingNeedsAnswer({
  536. value: typedReading,
  537. saved: vehicle.mileage,
  538. last: vehicle.mileage,
  539. kind: isMarine ? 'hours' : 'distance',
  540. confirmed: confirmedReadingRef.current,
  541. })
  542. ) {
  543. setReadingToConfirm(typedReading)
  544. return
  545. }
  546. const formData = new FormData(e.currentTarget)
  547. // Caught here rather than by the server, which could only answer in English.
  548. if (showTypeKey) {
  549. const hsn = normalizeHsn(String(formData.get('hsn') ?? ''))
  550. const tsn = normalizeTsn(String(formData.get('tsn') ?? ''))
  551. if (hsn && !HSN_PATTERN.test(hsn)) {
  552. toast.error(t('hsnInvalid'))
  553. return
  554. }
  555. if (tsn && !TSN_PATTERN.test(tsn)) {
  556. toast.error(t('tsnInvalid'))
  557. return
  558. }
  559. }
  560. // A fleet number longer than the field takes is refused here and said
  561. // why, never cut: a cut number names another vehicle.
  562. if (showFleetNumber && fleetNumberTooLong(String(formData.get('fleetNumber') ?? ''))) {
  563. toast.error(t('fleetNumberTooLong', { max: FLEET_NUMBER_MAX_LENGTH }))
  564. document.getElementById('fleetNumber')?.focus()
  565. return
  566. }
  567. // The workshop's own fields first: one left empty that must not be stops
  568. // the save here, marked and named on the form. The values then go with
  569. // the vehicle's own save, which checks them again and writes both or
  570. // neither.
  571. let customFields: Record<string, string> | undefined
  572. if (hasCustomFields && customFieldsSave.current) {
  573. const checked = await customFieldsSave.current({ collect: true })
  574. if (!checked.valid) {
  575. toast.error(customFieldsRefusal(checked, tCustom))
  576. return
  577. }
  578. customFields = checked.values
  579. }
  580. setLoading(true)
  581. try {
  582. // The photo is sent only when it was changed here: a new one picked, or
  583. // the saved one removed. Sending back the address the form opened with
  584. // would undo a photo taken on a phone meanwhile, which has already
  585. // replaced it (and let the old file go) on the server.
  586. let imageUrl: string | undefined
  587. try {
  588. if (imageFile) imageUrl = await uploadImage(imageFile)
  589. else if (!preview && vehicle?.imageUrl) imageUrl = ''
  590. } catch (err) {
  591. modal.open(
  592. 'error',
  593. 'Upload Failed',
  594. err instanceof Error ? err.message : 'Could not upload image'
  595. )
  596. setLoading(false)
  597. return
  598. }
  599. // The keeper read off the papers is nobody until a customer row exists,
  600. // and losing them to an unnoticed checkbox is worse than an extra record.
  601. // '' when editing tells the update action to drop the owner.
  602. let customerId = clearableInput(
  603. selectedCustomerId === 'none' ? '' : selectedCustomerId,
  604. Boolean(vehicle)
  605. )
  606. if (!customerId && addOwner && scannedOwner?.name) {
  607. const created = await createCustomer({
  608. name: scannedOwner.name,
  609. address: scannedOwner.address,
  610. })
  611. if (created.success && created.data) {
  612. customerId = (created.data as { id: string }).id
  613. } else if (!handleGated(created)) {
  614. toast.error(created.error || t('ownerSaveFailed'))
  615. }
  616. }
  617. // An emptied field has to reach the server as '' when editing, which
  618. // the update action turns into null; undefined there means "not
  619. // touched" and would bring the old value back. On create, leaving an
  620. // empty field out is the same thing as clearing it.
  621. const optional = (name: string) => clearableInput(formData.get(name), Boolean(vehicle))
  622. const inspectionDue = (formData.get('inspectionDueAt') as string | null) ?? ''
  623. const withUnit = <T,>(value: T) =>
  624. typeof value === 'string' && !isMarine
  625. ? engineSizeToSave(value, vehicle?.engineSize)
  626. : value
  627. const data: CreateVehicleInput & { imageUrl?: string } = {
  628. make: formData.get('make') as string,
  629. model: formData.get('model') as string,
  630. year: Number(formData.get('year')),
  631. vin: optional('vin'),
  632. licensePlate: optional('licensePlate'),
  633. color: optional('color'),
  634. mileage: Number(formData.get('mileage')) || 0,
  635. fuelType: fuelType || undefined,
  636. transmission: transmission || undefined,
  637. // A bare number is saved with its unit, so "649" is kept as "649 cc".
  638. engineSize: withUnit(optional('engineSize')),
  639. engineCode: optional('engineCode'),
  640. hsn: showTypeKey ? optional('hsn') : undefined,
  641. tsn: showTypeKey ? optional('tsn') : undefined,
  642. // Sent only where the box is drawn, and when editing only if the
  643. // vehicle came with its value: a save never clears what it did not show.
  644. fleetNumber:
  645. showFleetNumber && (!vehicle || vehicle.fleetNumber !== undefined)
  646. ? optional('fleetNumber')
  647. : undefined,
  648. // An empty string clears a hand-typed date; undefined leaves the stored
  649. // date alone, so saving another field, or a lookup that brought no
  650. // date, does not turn a registry's date into one typed by hand.
  651. inspectionDueAt:
  652. isMarine || inspectionDue === openedInspectionDue ? undefined : inspectionDue,
  653. registryLookup: isMarine ? undefined : (lookupRef.current ?? undefined),
  654. customerId,
  655. }
  656. const payload = {
  657. ...(imageUrl !== undefined ? { ...data, imageUrl } : data),
  658. ...(customFields ? { customFields } : {}),
  659. }
  660. const result = vehicle
  661. ? await updateVehicle({ ...payload, id: vehicle.id })
  662. : await createVehicle(payload)
  663. // Refused by the workshop's own fields: nothing was saved. The fields
  664. // are marked where they are and the dialog stays open on what was typed.
  665. if (!result.success && result.customFieldErrors && customFieldsSave.current) {
  666. await customFieldsSave.current({ refuse: result.customFieldErrors as CustomFieldError[] })
  667. toast.error(result.error || t('saveError'))
  668. return
  669. }
  670. // Refused by the vehicle's own rules (a year out of range, a reading
  671. // below zero): each is said under its field, the first is focused,
  672. // and everything typed stays where it is.
  673. if (!result.success && result.fieldErrors?.length) {
  674. const unplaced = fieldErrors.report(formRef.current, result.fieldErrors)
  675. toast.error(
  676. unplaced.length > 0
  677. ? unplaced.map((error) => fieldErrors.text(error)).join(' ')
  678. : tCommon('fieldErrors.notSaved')
  679. )
  680. return
  681. }
  682. if (result.success) {
  683. // The vehicle as a picker shows it, with the owner it was saved under:
  684. // the one chosen, or the keeper off the papers just made a customer.
  685. const saved = !vehicle && result.data && 'make' in result.data ? result.data : null
  686. const owner = selectedCustomer
  687. const created: BookingVehicle | null = saved
  688. ? {
  689. id: saved.id,
  690. make: saved.make,
  691. model: saved.model,
  692. year: saved.year,
  693. licensePlate: saved.licensePlate,
  694. customerId: saved.customerId,
  695. customer: saved.customerId
  696. ? {
  697. id: saved.customerId,
  698. name: owner?.id === saved.customerId ? owner.name : (scannedOwner?.name ?? ''),
  699. }
  700. : null,
  701. }
  702. : null
  703. if (created && !onCreated && canBook) {
  704. // Never a dead end: a vehicle added on its own can be booked in
  705. // straight from the confirmation.
  706. toast.success(t('vehicleAdded'), {
  707. action: {
  708. label: t('bookAppointment'),
  709. onClick: () => openBooking({ vehicle: created }),
  710. },
  711. })
  712. } else {
  713. toast.success(vehicle ? t('vehicleUpdated') : t('vehicleAdded'))
  714. }
  715. onOpenChange(false)
  716. setImageFile(null)
  717. // A caller that goes on with the vehicle shows it itself; anywhere
  718. // else the page underneath is read again to list it.
  719. if (created && onCreated) onCreated(created)
  720. else router.refresh()
  721. } else {
  722. modal.open('error', tCommon('errors.error'), result.error || t('saveError'))
  723. }
  724. } finally {
  725. setLoading(false)
  726. }
  727. }
  728. // A label for a stored value: the words for the ones this form offers, the
  729. // value itself for anything a registry or an import wrote.
  730. const optionLabel = (value: string) => {
  731. const key = value === 'two-stroke' ? 'twoStroke' : value
  732. return t.has(key) ? t(key) : value
  733. }
  734. const fuelOptions = withCurrent(
  735. isMarine
  736. ? ['gasoline', 'diesel', 'two-stroke', 'other']
  737. : ['gasoline', 'diesel', 'electric', 'hybrid', 'other'],
  738. fuelType
  739. )
  740. const transmissionOptions = withCurrent(
  741. isMarine ? ['outboard', 'inboard'] : ['automatic', 'manual', 'cvt'],
  742. transmission
  743. )
  744. // "2016 · Diesel · Automatic": the saved vehicle, under its name, when editing
  745. const vehicleSummary = vehicle
  746. ? [
  747. vehicle.year ? String(vehicle.year) : null,
  748. vehicle.fuelType ? optionLabel(vehicle.fuelType) : null,
  749. vehicle.transmission ? optionLabel(vehicle.transmission) : null,
  750. isMarine ? vehicle.licensePlate : null,
  751. ]
  752. .filter(Boolean)
  753. .join(' · ')
  754. : ''
  755. const mileageLabel = isMarine ? t('mileageMarine') : t('mileage')
  756. const unit = distanceUnit
  757. const mileageShown = mileageDraft.trim() === '' ? null : Number(mileageDraft)
  758. const readingNotice = useReadingNotice(mileageDraft, vehicle?.mileage)
  759. const mileageInputRef = useRef<HTMLInputElement>(null)
  760. const inspectionShown = inspectionDraft
  761. ? {
  762. // A date key: the same day everywhere, in the workshop's date format.
  763. text: formatDay(inspectionDraft),
  764. tone: inspectionTone(inspectionDraft),
  765. }
  766. : null
  767. // Only beside a date: "Not set" from the registry says nothing useful.
  768. const fromRegistry =
  769. !!inspectionDraft &&
  770. !!vehicle?.inspectionStatus?.source &&
  771. vehicle.inspectionStatus.source !== 'manual' &&
  772. inspectionDraft === openedInspectionDue
  773. const vinLength = vinDraft.trim().length
  774. const addTitle = isMarine ? t('addTitleMarine') : t('addTitle')
  775. const swatch = cssColor(colorDraft)
  776. return (
  777. <>
  778. <Dialog open={open} onOpenChange={onOpenChange}>
  779. <DialogContent
  780. className="max-h-[90vh] sm:max-w-5xl"
  781. // Escape in the mileage being changed puts the reading back; it must
  782. // not throw the whole form away with it.
  783. onEscapeKeyDown={(e) => {
  784. if (editingMileage) e.preventDefault()
  785. }}
  786. >
  787. <DialogHeader>
  788. {/* The plate and the name say which vehicle is open before any
  789. field does; the docs link sits on the same line, clear of the
  790. close button. On a phone the name takes its own row under the
  791. plate and wraps rather than shrinking to its first letter, and
  792. the docs link goes under it, as in the other dialogs. */}
  793. <div className="flex flex-wrap items-start gap-x-3 gap-y-2 pr-8 text-left">
  794. {vehicle?.licensePlate && !isMarine && (
  795. <PlateChip plate={vehicle.licensePlate} size="md" className="mt-0.5" />
  796. )}
  797. <div className="min-w-0 basis-full space-y-1 sm:flex-[1_1_12rem]">
  798. {/* Three lines at most: the fields scroll under a pinned
  799. header, so an unbounded name could push them out of reach. */}
  800. <DialogTitle
  801. className="line-clamp-3 break-words leading-tight"
  802. title={vehicle ? `${vehicle.make} ${vehicle.model}`.trim() : undefined}
  803. >
  804. {vehicle ? (
  805. <>
  806. <span className="sr-only">{t('editTitle')}: </span>
  807. {`${vehicle.make} ${vehicle.model}`.trim()}
  808. </>
  809. ) : (
  810. addTitle
  811. )}
  812. </DialogTitle>
  813. <DialogDescription className={vehicleSummary ? 'text-[13px]' : 'sr-only'}>
  814. {vehicleSummary || (vehicle ? t('editTitle') : addTitle)}
  815. </DialogDescription>
  816. </div>
  817. <DocsLink href="/docs/features/vehicles" variant="hint" className="mt-1 shrink-0" />
  818. </div>
  819. </DialogHeader>
  820. <ReadingConfirmDialog
  821. entered={readingToConfirm}
  822. last={vehicle?.mileage ?? 0}
  823. unit={unit}
  824. onConfirm={() => {
  825. confirmedReadingRef.current = readingToConfirm
  826. setReadingToConfirm(null)
  827. formRef.current?.requestSubmit()
  828. }}
  829. onChange={() => setReadingToConfirm(null)}
  830. focusField={() => {
  831. mileageInputRef.current?.focus()
  832. mileageInputRef.current?.select()
  833. }}
  834. />
  835. <form
  836. ref={formRef}
  837. onSubmit={handleSubmit}
  838. onInput={readDrafts}
  839. // A refused field's mark goes as soon as it is changed.
  840. onChange={(e) => fieldErrors.clear((e.target as Element).getAttribute('name') ?? '')}
  841. className="flex min-h-0 flex-1 flex-col"
  842. >
  843. <DialogBody className="space-y-4">
  844. {/* At a glance: the photo, who owns it, how far it has gone and
  845. when it is next due, and the papers that can fill the rest. */}
  846. <section className="grid gap-4 rounded-xl border bg-card p-3 sm:grid-cols-[10rem_minmax(0,1fr)] lg:grid-cols-[10rem_minmax(0,1fr)_15rem]">
  847. <div className="w-full max-w-[12rem] space-y-1.5 sm:max-w-none">
  848. <div className="group relative aspect-[4/3] overflow-hidden rounded-lg border bg-muted/40">
  849. {preview ? (
  850. <Image
  851. src={preview}
  852. alt={t('photo')}
  853. fill
  854. unoptimized
  855. className="object-cover"
  856. />
  857. ) : (
  858. <div className="flex h-full flex-col items-center justify-center gap-1.5 text-muted-foreground">
  859. <Camera className="h-6 w-6" aria-hidden />
  860. <span className="text-xs font-medium">{tDetail('addPhoto')}</span>
  861. </div>
  862. )}
  863. <button
  864. type="button"
  865. onClick={() => fileRef.current?.click()}
  866. aria-label={preview ? tDetail('changePhoto') : tDetail('addPhoto')}
  867. title={t('imageFormats')}
  868. className="absolute inset-0 rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring"
  869. />
  870. {preview && (
  871. <>
  872. <span
  873. aria-hidden
  874. className="pointer-events-none absolute inset-x-0 bottom-0 flex items-center gap-1.5 bg-gradient-to-t from-black/75 to-transparent px-2 pt-6 pb-1.5 text-[11.5px] font-medium text-white"
  875. >
  876. <Camera className="h-3.5 w-3.5" />
  877. {tDetail('changePhoto')}
  878. </span>
  879. <button
  880. type="button"
  881. onClick={clearImage}
  882. aria-label={t('removePhoto')}
  883. className="absolute top-1.5 right-1.5 flex h-6 w-6 items-center justify-center rounded-full bg-black/60 text-white opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100"
  884. >
  885. <X className="h-3.5 w-3.5" />
  886. </button>
  887. </>
  888. )}
  889. </div>
  890. {/* A vehicle already saved can take its photo from a phone,
  891. as a work order can. */}
  892. {vehicle && (
  893. <PhotoHandoffButton
  894. vehicleId={vehicle.id}
  895. variant="link"
  896. onVehiclePhoto={(url) => {
  897. setImageFile(null)
  898. setPreview(url)
  899. }}
  900. />
  901. )}
  902. <input
  903. ref={fileRef}
  904. type="file"
  905. accept="image/jpeg,image/png,image/webp,image/avif"
  906. onChange={handleImageSelect}
  907. className="hidden"
  908. aria-label={t('photo')}
  909. tabIndex={-1}
  910. />
  911. </div>
  912. <div className="min-w-0 space-y-4 self-center">
  913. <div className="space-y-1.5">
  914. <Label className="text-[11px] font-semibold uppercase tracking-[0.07em] text-muted-foreground">
  915. {tDetail('owner')}
  916. </Label>
  917. <CustomerCombobox
  918. showAvatar
  919. disabled={ownerLocked}
  920. value={selectedCustomerId === 'none' ? '' : selectedCustomerId}
  921. initialCustomer={selectedCustomer}
  922. // A customer given by id alone is named once the lookup below answers
  923. placeholder={
  924. selectedCustomerId !== 'none' && !selectedCustomer ? '…' : t('noCustomer')
  925. }
  926. searchPlaceholder={t('searchCustomers')}
  927. noneLabel={t('noCustomer')}
  928. emptyLabel={t('noCustomerFound')}
  929. onChange={(id, customer) => {
  930. setSelectedCustomerId(id || 'none')
  931. setSelectedCustomer(customer)
  932. }}
  933. footer={(close) => (
  934. <div className="border-t p-1">
  935. <button
  936. type="button"
  937. className="flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm hover:bg-accent"
  938. onClick={() => {
  939. close()
  940. setShowCustomerForm(true)
  941. }}
  942. >
  943. <Plus className="h-4 w-4" />
  944. {t('addCustomer')}
  945. </button>
  946. </div>
  947. )}
  948. />
  949. </div>
  950. <dl className="flex flex-wrap gap-x-10 gap-y-3">
  951. <div className="space-y-1">
  952. <dt className="text-[11px] font-semibold uppercase tracking-[0.07em] text-muted-foreground">
  953. {mileageLabel}
  954. </dt>
  955. <dd className="flex h-8 items-center">
  956. {editingMileage ? (
  957. <div className="relative w-40">
  958. <Input
  959. // Opened by a click on the figure, to type in straight away.
  960. autoFocus
  961. type="number"
  962. inputMode="numeric"
  963. min={0}
  964. value={mileageDraft}
  965. aria-label={mileageLabel}
  966. onChange={(e) => setMileageDraft(e.target.value)}
  967. onFocus={(e) => e.currentTarget.select()}
  968. onBlur={() => setEditingMileage(false)}
  969. onKeyDown={(e) => {
  970. // Enter keeps the reading and stays in the form
  971. // rather than saving it; Escape puts it back.
  972. if (e.key === 'Enter') {
  973. e.preventDefault()
  974. setEditingMileage(false)
  975. } else if (e.key === 'Escape') {
  976. e.preventDefault()
  977. setMileageDraft(mileageBeforeEdit.current)
  978. setEditingMileage(false)
  979. }
  980. }}
  981. className={cn(
  982. 'h-8 font-display text-lg font-semibold tabular-nums [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none',
  983. unit && 'pr-10'
  984. )}
  985. />
  986. {unit && (
  987. <span
  988. aria-hidden
  989. className="pointer-events-none absolute top-1/2 right-3 -translate-y-1/2 text-sm font-medium text-muted-foreground"
  990. >
  991. {unit}
  992. </span>
  993. )}
  994. </div>
  995. ) : (
  996. <button
  997. type="button"
  998. onClick={() => {
  999. mileageBeforeEdit.current = mileageDraft
  1000. setEditingMileage(true)
  1001. }}
  1002. title={isMarine ? t('editMileageMarine') : t('editMileage')}
  1003. aria-label={`${isMarine ? t('editMileageMarine') : t('editMileage')}: ${
  1004. mileageShown === null || Number.isNaN(mileageShown)
  1005. ? '–'
  1006. : `${format.number(mileageShown)}${unit ? ` ${unit}` : ''}`
  1007. }`}
  1008. className="group/mileage -mx-1.5 inline-flex h-8 items-center gap-1.5 rounded-md px-1.5 font-display text-xl font-semibold tabular-nums transition-colors outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
  1009. >
  1010. {mileageShown === null || Number.isNaN(mileageShown) ? (
  1011. <span className="text-muted-foreground">–</span>
  1012. ) : (
  1013. <span>
  1014. {format.number(mileageShown)}
  1015. {unit && (
  1016. <span className="ml-1 text-sm font-medium text-muted-foreground">
  1017. {unit}
  1018. </span>
  1019. )}
  1020. </span>
  1021. )}
  1022. <Pencil
  1023. aria-hidden
  1024. className="h-3.5 w-3.5 text-muted-foreground opacity-50 transition-opacity group-hover/mileage:opacity-100 group-focus-visible/mileage:opacity-100"
  1025. />
  1026. </button>
  1027. )}
  1028. </dd>
  1029. <ReadingNotice
  1030. entered={mileageDraft}
  1031. last={vehicle?.mileage}
  1032. unit={unit}
  1033. className="max-w-56"
  1034. />
  1035. </div>
  1036. {!isMarine && (
  1037. <div className="space-y-1">
  1038. <dt className="text-[11px] font-semibold uppercase tracking-[0.07em] text-muted-foreground">
  1039. {t('inspectionDue')}
  1040. </dt>
  1041. <dd className="flex flex-wrap items-center gap-x-2 gap-y-1">
  1042. {inspectionShown ? (
  1043. <span className="inline-flex items-center rounded-full border bg-background px-2.5 py-0.5">
  1044. <StatusLamp tone={inspectionShown.tone} className="text-[13px]">
  1045. {inspectionShown.text}
  1046. </StatusLamp>
  1047. </span>
  1048. ) : (
  1049. <span className="inline-flex items-center rounded-full border border-dashed px-2.5 py-0.5 text-[13px] text-muted-foreground">
  1050. {t('notSet')}
  1051. </span>
  1052. )}
  1053. {fromRegistry && (
  1054. <span className="text-xs text-muted-foreground">
  1055. {t('fromRegistry')}
  1056. </span>
  1057. )}
  1058. </dd>
  1059. </div>
  1060. )}
  1061. </dl>
  1062. </div>
  1063. <div className="border-t pt-3 sm:col-span-2 lg:col-span-1 lg:self-center lg:border-t-0 lg:border-l lg:pt-0 lg:pl-4">
  1064. <ScanDocumentButton onScanned={applyScan} stacked />
  1065. </div>
  1066. {/* Keeper read off the papers who matches no customer yet */}
  1067. {scannedOwner?.name && selectedCustomerId === 'none' && (
  1068. <div className="space-y-2 rounded-lg border border-dashed border-border bg-muted/30 p-3 sm:col-span-2 lg:col-span-3">
  1069. <label className="flex cursor-pointer items-start gap-3">
  1070. <Checkbox
  1071. className="mt-0.5"
  1072. checked={addOwner}
  1073. onCheckedChange={(next) => setAddOwner(next === true)}
  1074. />
  1075. <span className="min-w-0">
  1076. <span className="block text-sm">
  1077. {t('addScannedOwner', { name: scannedOwner.name })}
  1078. </span>
  1079. {scannedOwner.address && (
  1080. <span className="block truncate text-xs text-muted-foreground">
  1081. {scannedOwner.address}
  1082. </span>
  1083. )}
  1084. </span>
  1085. </label>
  1086. {ownerMatches.length > 0 && (
  1087. <Button
  1088. type="button"
  1089. size="sm"
  1090. variant="outline"
  1091. className="w-full sm:w-auto"
  1092. onClick={() => setShowOwnerMatch(true)}
  1093. >
  1094. {t('ownerMatchChoose')}
  1095. </Button>
  1096. )}
  1097. </div>
  1098. )}
  1099. </section>
  1100. <div className="grid gap-4 md:grid-cols-2">
  1101. <FormCard title={t('sectionIdentification')}>
  1102. <div className="space-y-2">
  1103. <Label htmlFor="licensePlate">
  1104. {isMarine ? t('licensePlateMarine') : t('licensePlate')}
  1105. </Label>
  1106. {/* Wraps so the lookup's reason, when it is off, sits under the field */}
  1107. <div className="flex flex-wrap gap-2">
  1108. <Input
  1109. id="licensePlate"
  1110. name="licensePlate"
  1111. {...fieldErrors.invalidProps('licensePlate')}
  1112. placeholder="ABC-1234"
  1113. defaultValue={vehicle?.licensePlate ?? ''}
  1114. className="flex-1"
  1115. // Enter in the plate asks the registry, where one is
  1116. // connected, instead of trying to save half a form.
  1117. onKeyDown={(e) => {
  1118. if (e.key !== 'Enter') return
  1119. const lookup = formRef.current?.querySelector<HTMLButtonElement>(
  1120. 'button[data-lookup="plate"]'
  1121. )
  1122. // No registry: Enter is the form's own.
  1123. if (!lookup || (lookup.disabled && !lookup.dataset.busy)) return
  1124. // A second Enter while the registry is still
  1125. // answering must not save the form under it; a
  1126. // click on the busy button does nothing.
  1127. e.preventDefault()
  1128. lookup.click()
  1129. }}
  1130. />
  1131. {!isMarine && (
  1132. <VehicleLookupButton
  1133. by="plate"
  1134. text={t('lookupShort')}
  1135. getValue={() => fieldValue('licensePlate')}
  1136. onFound={(data, asked) =>
  1137. applyLookup(data, { by: 'plate', value: asked })
  1138. }
  1139. vehicleId={vehicle?.id}
  1140. />
  1141. )}
  1142. </div>
  1143. {fieldErrors.message('licensePlate')}
  1144. </div>
  1145. <div className="space-y-2">
  1146. <div className="flex items-baseline justify-between gap-2">
  1147. <Label htmlFor="vin">{isMarine ? t('vinMarine') : t('vin')}</Label>
  1148. {/* A VIN is seventeen characters; counting them catches the
  1149. one missed or typed twice before a lookup is wasted. */}
  1150. {!isMarine && vinLength > 0 && (
  1151. <span
  1152. className={cn(
  1153. 'inline-flex items-center gap-1 font-mono text-[11px] tabular-nums',
  1154. vinLength === VIN_LENGTH
  1155. ? 'text-emerald-700 dark:text-emerald-400'
  1156. : 'text-muted-foreground'
  1157. )}
  1158. title={t('vinLength', { count: vinLength, total: VIN_LENGTH })}
  1159. >
  1160. <span aria-hidden>
  1161. {vinLength} / {VIN_LENGTH}
  1162. </span>
  1163. <span className="sr-only">
  1164. {t('vinLength', { count: vinLength, total: VIN_LENGTH })}
  1165. </span>
  1166. {vinLength === VIN_LENGTH && <Check className="h-3 w-3" aria-hidden />}
  1167. </span>
  1168. )}
  1169. </div>
  1170. <div className="flex gap-2">
  1171. <Input
  1172. id="vin"
  1173. name="vin"
  1174. {...fieldErrors.invalidProps('vin')}
  1175. placeholder="1HGCM82633A004352"
  1176. defaultValue={vehicle?.vin ?? ''}
  1177. autoComplete="off"
  1178. spellCheck={false}
  1179. className="flex-1 font-mono"
  1180. />
  1181. {!isMarine && (
  1182. <VehicleLookupButton
  1183. by="vin"
  1184. text={t('decodeShort')}
  1185. getValue={() => fieldValue('vin')}
  1186. onFound={(data, asked) => applyLookup(data, { by: 'vin', value: asked })}
  1187. vehicleId={vehicle?.id}
  1188. />
  1189. )}
  1190. </div>
  1191. {fieldErrors.message('vin')}
  1192. </div>
  1193. {/* Under both fields, since either button may have answered */}
  1194. {lookupNote && (
  1195. <p className="-mt-2 text-xs text-muted-foreground">
  1196. {lookupNote.inspectionDue
  1197. ? t('lookupInspectionDue', {
  1198. source: lookupNote.source,
  1199. date: formatDay(lookupNote.inspectionDue),
  1200. })
  1201. : t('lookupSource', { source: lookupNote.source })}
  1202. </p>
  1203. )}
  1204. {showTypeKey && (
  1205. <div className="space-y-2">
  1206. <div className="grid grid-cols-2 gap-4">
  1207. <div className="space-y-2">
  1208. <Label htmlFor="hsn">{t('hsn')}</Label>
  1209. <Input
  1210. id="hsn"
  1211. name="hsn"
  1212. {...fieldErrors.invalidProps('hsn')}
  1213. placeholder="0603"
  1214. inputMode="numeric"
  1215. maxLength={6}
  1216. autoComplete="off"
  1217. className="font-mono"
  1218. defaultValue={vehicle?.hsn ?? ''}
  1219. />
  1220. {fieldErrors.message('hsn')}
  1221. </div>
  1222. <div className="space-y-2">
  1223. <Label htmlFor="tsn">{t('tsn')}</Label>
  1224. <Input
  1225. id="tsn"
  1226. name="tsn"
  1227. {...fieldErrors.invalidProps('tsn')}
  1228. placeholder="BFQ"
  1229. maxLength={12}
  1230. autoComplete="off"
  1231. className="font-mono uppercase"
  1232. defaultValue={vehicle?.tsn ?? ''}
  1233. />
  1234. {fieldErrors.message('tsn')}
  1235. </div>
  1236. </div>
  1237. <p className="text-xs text-muted-foreground">{t('typeKeyHint')}</p>
  1238. </div>
  1239. )}
  1240. {showFleetNumber && (
  1241. <div className="space-y-2">
  1242. <Label htmlFor="fleetNumber">{t('fleetNumber')}</Label>
  1243. <Input
  1244. id="fleetNumber"
  1245. name="fleetNumber"
  1246. {...fieldErrors.invalidProps('fleetNumber')}
  1247. placeholder={t('fleetNumberPlaceholder')}
  1248. autoComplete="off"
  1249. className="w-full sm:w-48"
  1250. defaultValue={vehicle?.fleetNumber ?? ''}
  1251. />
  1252. {fieldErrors.message('fleetNumber')}
  1253. </div>
  1254. )}
  1255. {!isMarine && (
  1256. <div className="space-y-2">
  1257. <Label htmlFor="inspectionDueAt">{t('inspectionDue')}</Label>
  1258. <Input
  1259. id="inspectionDueAt"
  1260. name="inspectionDueAt"
  1261. {...fieldErrors.invalidProps('inspectionDueAt')}
  1262. type="date"
  1263. defaultValue={openedInspectionDue}
  1264. className="w-full sm:w-48"
  1265. />
  1266. {fieldErrors.message('inspectionDueAt')}
  1267. <p className="text-xs text-muted-foreground">
  1268. {vehicle?.inspectionStatus?.source &&
  1269. vehicle.inspectionStatus.source !== 'manual'
  1270. ? t('inspectionDueFromRegistry')
  1271. : t('inspectionDueHint')}
  1272. </p>
  1273. </div>
  1274. )}
  1275. </FormCard>
  1276. <FormCard title={isMarine ? t('sectionVehicleMarine') : t('sectionVehicle')}>
  1277. <div className="grid grid-cols-2 gap-4 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_6rem]">
  1278. <div className="space-y-2">
  1279. <Label htmlFor="make">{isMarine ? t('makeMarine') : t('make')}</Label>
  1280. <Input
  1281. id="make"
  1282. name="make"
  1283. {...fieldErrors.invalidProps('make')}
  1284. placeholder={isMarine ? 'Boston Whaler' : 'Toyota'}
  1285. defaultValue={vehicle?.make}
  1286. required
  1287. />
  1288. {fieldErrors.message('make')}
  1289. </div>
  1290. <div className="space-y-2">
  1291. <Label htmlFor="model">{t('model')}</Label>
  1292. <Input
  1293. id="model"
  1294. name="model"
  1295. {...fieldErrors.invalidProps('model')}
  1296. placeholder={isMarine ? 'Montauk 170' : 'Camry'}
  1297. defaultValue={vehicle?.model}
  1298. required
  1299. />
  1300. {fieldErrors.message('model')}
  1301. </div>
  1302. <div className="col-span-2 space-y-2 sm:col-span-1">
  1303. <Label htmlFor="year">{t('year')}</Label>
  1304. <Input
  1305. id="year"
  1306. name="year"
  1307. {...fieldErrors.invalidProps('year')}
  1308. type="number"
  1309. min={VEHICLE_YEAR_MIN}
  1310. max={vehicleYearMax()}
  1311. placeholder="2024"
  1312. defaultValue={vehicle?.year}
  1313. required
  1314. />
  1315. {fieldErrors.message('year')}
  1316. </div>
  1317. </div>
  1318. <Segmented
  1319. id="fuelType"
  1320. label={t('fuelType')}
  1321. value={fuelType}
  1322. onChange={setFuelType}
  1323. options={fuelOptions.map((value) => ({ value, label: optionLabel(value) }))}
  1324. />
  1325. <Segmented
  1326. id="transmission"
  1327. label={isMarine ? t('transmissionMarine') : t('transmission')}
  1328. value={transmission}
  1329. onChange={setTransmission}
  1330. options={transmissionOptions.map((value) => ({
  1331. value,
  1332. label: optionLabel(value),
  1333. }))}
  1334. />
  1335. <div className="grid grid-cols-2 gap-4">
  1336. <div className="space-y-2">
  1337. <Label htmlFor="engineSize">
  1338. {isMarine ? t('engineSizeMarine') : t('engineSize')}
  1339. </Label>
  1340. {isMarine ? (
  1341. <Input
  1342. id="engineSize"
  1343. name="engineSize"
  1344. placeholder="Mercury F 350 XXL Verado V-10 (350 hp)"
  1345. defaultValue={vehicle?.engineSize ?? ''}
  1346. />
  1347. ) : (
  1348. <EngineSizeInput
  1349. key={vehicle?.id ?? 'new'}
  1350. defaultValue={vehicle?.engineSize ?? ''}
  1351. />
  1352. )}
  1353. </div>
  1354. <div className="space-y-2">
  1355. <Label htmlFor="engineCode">{t('engineCode')}</Label>
  1356. <Input
  1357. id="engineCode"
  1358. name="engineCode"
  1359. {...fieldErrors.invalidProps('engineCode')}
  1360. placeholder="2AR-FE"
  1361. defaultValue={vehicle?.engineCode ?? ''}
  1362. />
  1363. {fieldErrors.message('engineCode')}
  1364. </div>
  1365. </div>
  1366. <div className="grid grid-cols-2 gap-4">
  1367. <div className="space-y-2">
  1368. <Label htmlFor="color">{t('color')}</Label>
  1369. <div className="relative">
  1370. {/* The colour itself where the name is one a browser
  1371. knows, an empty ring where it is not. */}
  1372. <span
  1373. aria-hidden
  1374. className={cn(
  1375. 'pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2 rounded-full border',
  1376. swatch
  1377. ? 'border-foreground/20'
  1378. : 'border-dashed border-muted-foreground/50'
  1379. )}
  1380. style={swatch ? { background: swatch } : undefined}
  1381. />
  1382. <Input
  1383. id="color"
  1384. name="color"
  1385. {...fieldErrors.invalidProps('color')}
  1386. placeholder="Silver"
  1387. defaultValue={vehicle?.color ?? ''}
  1388. className="pl-8"
  1389. />
  1390. </div>
  1391. {fieldErrors.message('color')}
  1392. </div>
  1393. <div className="space-y-2">
  1394. <Label htmlFor="mileage">{mileageLabel}</Label>
  1395. <div className="relative">
  1396. <Input
  1397. ref={mileageInputRef}
  1398. id="mileage"
  1399. name="mileage"
  1400. type="number"
  1401. min={0}
  1402. placeholder="0"
  1403. value={mileageDraft}
  1404. onChange={(e) => setMileageDraft(e.target.value)}
  1405. {...fieldErrors.invalidProps(
  1406. 'mileage',
  1407. readingNotice ? 'mileage-notice' : undefined
  1408. )}
  1409. // No spinner: it would sit on top of the unit, and
  1410. // nobody steps an odometer reading one at a time.
  1411. className={cn(
  1412. '[appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none',
  1413. unit && 'pr-10'
  1414. )}
  1415. />
  1416. {unit && (
  1417. <span
  1418. aria-hidden
  1419. className="pointer-events-none absolute top-1/2 right-3 -translate-y-1/2 text-sm text-muted-foreground"
  1420. >
  1421. {unit}
  1422. </span>
  1423. )}
  1424. </div>
  1425. {fieldErrors.message('mileage')}
  1426. <ReadingNotice
  1427. id="mileage-notice"
  1428. entered={mileageDraft}
  1429. last={vehicle?.mileage}
  1430. unit={unit}
  1431. />
  1432. </div>
  1433. </div>
  1434. </FormCard>
  1435. </div>
  1436. {hasCustomFields && open && (
  1437. <CustomFieldsForm
  1438. embedded="card"
  1439. entityType="vehicle"
  1440. entityId={vehicle?.id}
  1441. onValuesReady={(save) => {
  1442. customFieldsSave.current = save
  1443. }}
  1444. />
  1445. )}
  1446. </DialogBody>
  1447. <DialogFooter className="sm:items-center">
  1448. {vehicle && onDelete && (
  1449. <Button
  1450. type="button"
  1451. variant="ghost"
  1452. className="text-destructive hover:bg-destructive/10 hover:text-destructive sm:mr-auto"
  1453. onClick={onDelete}
  1454. >
  1455. <Trash2 className="mr-1.5 h-4 w-4" />
  1456. {isMarine ? t('deleteVehicleMarine') : t('deleteVehicle')}
  1457. </Button>
  1458. )}
  1459. <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
  1460. {tc('cancel')}
  1461. </Button>
  1462. <Button data-save-shortcut type="submit" disabled={loading || ownerLookupPending}>
  1463. {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
  1464. {vehicle ? tc('saveChanges') : addTitle}
  1465. </Button>
  1466. </DialogFooter>
  1467. </form>
  1468. </DialogContent>
  1469. </Dialog>
  1470. {/* Close matches for the keeper on the papers */}
  1471. <Dialog open={showOwnerMatch} onOpenChange={setShowOwnerMatch}>
  1472. <DialogContent className="sm:max-w-md">
  1473. <DialogHeader>
  1474. <DialogTitle>{t('ownerMatchTitle')}</DialogTitle>
  1475. <DialogDescription>
  1476. {t('ownerMatchDescription', { name: scannedOwner?.name ?? '' })}
  1477. </DialogDescription>
  1478. </DialogHeader>
  1479. <div className="space-y-2">
  1480. {ownerMatches.map(({ customer, score }) => (
  1481. <button
  1482. key={customer.id}
  1483. type="button"
  1484. className="flex w-full items-center justify-between gap-3 rounded-lg border border-border p-3 text-left transition-colors hover:bg-accent"
  1485. onClick={() => {
  1486. setSelectedCustomerId(customer.id)
  1487. setSelectedCustomer(customer)
  1488. setScannedOwner(null)
  1489. setShowOwnerMatch(false)
  1490. }}
  1491. >
  1492. <span className="min-w-0">
  1493. <span className="block truncate text-sm font-medium">{customer.name}</span>
  1494. {customer.company && (
  1495. <span className="block truncate text-xs text-muted-foreground">
  1496. {customer.company}
  1497. </span>
  1498. )}
  1499. </span>
  1500. <span className="shrink-0 text-xs text-muted-foreground">
  1501. {t('ownerMatchScore', { percent: Math.round(score * 100) })}
  1502. </span>
  1503. </button>
  1504. ))}
  1505. </div>
  1506. <div className="flex justify-end gap-2">
  1507. <Button type="button" variant="outline" onClick={() => setShowOwnerMatch(false)}>
  1508. {tc('cancel')}
  1509. </Button>
  1510. <Button
  1511. type="button"
  1512. onClick={() => {
  1513. setShowOwnerMatch(false)
  1514. setShowCustomerForm(true)
  1515. }}
  1516. >
  1517. <Plus className="mr-1 h-4 w-4" />
  1518. {t('ownerMatchCreateNew')}
  1519. </Button>
  1520. </div>
  1521. </DialogContent>
  1522. </Dialog>
  1523. <CustomerForm
  1524. open={showCustomerForm}
  1525. onOpenChange={setShowCustomerForm}
  1526. defaults={scannedOwner ?? undefined}
  1527. onCreated={(created) => {
  1528. setSelectedCustomer(created)
  1529. setSelectedCustomerId(created.id)
  1530. setScannedOwner(null)
  1531. }}
  1532. />
  1533. </>
  1534. )
  1535. }
  1536. /**
  1537. * The engine size field. Its placeholder is in the workshop's unit, and a
  1538. * bare number shows the unit it will be saved with, read from its size: 1.6
  1539. * is litres and 649 is cubic centimetres.
  1540. */
  1541. function EngineSizeInput({ defaultValue }: { defaultValue: string }) {
  1542. const t = useTranslations('vehicles.form')
  1543. const unit = useEngineSizeUnit()
  1544. const hintId = useId()
  1545. const [draft, setDraft] = useState(defaultValue)
  1546. const suffix = engineSizeHint(draft, defaultValue)
  1547. return (
  1548. <div className="relative">
  1549. <Input
  1550. id="engineSize"
  1551. name="engineSize"
  1552. placeholder={engineSizePlaceholder(unit)}
  1553. defaultValue={defaultValue}
  1554. onInput={(e) => setDraft(e.currentTarget.value)}
  1555. aria-describedby={hintId}
  1556. className={suffix ? 'pr-10' : undefined}
  1557. />
  1558. {suffix && (
  1559. <span
  1560. aria-hidden="true"
  1561. className="pointer-events-none absolute top-1/2 right-3 -translate-y-1/2 text-sm text-muted-foreground"
  1562. >
  1563. {suffix}
  1564. </span>
  1565. )}
  1566. {/* Always mounted, so a screen reader hears the unit as it changes. */}
  1567. <span id={hintId} className="sr-only" aria-live="polite">
  1568. {suffix ? t('engineSizeSavedAs', { unit: suffix }) : ''}
  1569. </span>
  1570. </div>
  1571. )
  1572. }
  1573. const VIN_LENGTH = 17
  1574. /** The options, and the stored value too when it is none of them, so it still shows as chosen. */
  1575. function withCurrent(options: string[], current: string): string[] {
  1576. return !current || options.includes(current) ? options : [...options, current]
  1577. }
  1578. /** How soon a periodic inspection is due, as the vehicle page colours it. */
  1579. function inspectionTone(dateKey: string): LampTone {
  1580. const left = new Date(`${dateKey}T23:59:59`).getTime() - Date.now()
  1581. if (left < 0) return 'red'
  1582. if (left < 30 * 86_400_000) return 'amber'
  1583. return 'green'
  1584. }
  1585. /** The colour a name stands for, when it is one the browser knows ("silver", "#c0c0c0"). */
  1586. function cssColor(name: string): string | null {
  1587. const value = name.trim().toLowerCase()
  1588. if (!value || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return null
  1589. return CSS.supports('color', value) ? value : null
  1590. }
  1591. /** A titled card holding one group of the form's fields. */
  1592. function FormCard({ title, children }: { title: string; children: React.ReactNode }) {
  1593. return (
  1594. <section className="min-w-0 rounded-xl border bg-card">
  1595. <h3 className="border-b px-4 py-2.5 text-[11px] font-semibold uppercase tracking-[0.07em] text-muted-foreground">
  1596. {title}
  1597. </h3>
  1598. <div className="space-y-4 p-4">{children}</div>
  1599. </section>
  1600. )
  1601. }
  1602. /**
  1603. * A short list of choices as one row of buttons, every option in sight
  1604. * rather than behind a dropdown. Arrow keys move the choice, as in any radio
  1605. * group.
  1606. */
  1607. function Segmented({
  1608. id,
  1609. label,
  1610. value,
  1611. options,
  1612. onChange,
  1613. }: {
  1614. /** The field's name, as the dropdown it replaced had, so its label still names it. */
  1615. id: string
  1616. label: string
  1617. value: string
  1618. options: { value: string; label: string }[]
  1619. onChange: (value: string) => void
  1620. }) {
  1621. const labelId = useId()
  1622. const groupRef = useRef<HTMLDivElement>(null)
  1623. const move = (step: number) => {
  1624. const at = options.findIndex((o) => o.value === value)
  1625. const next = options[(at + step + options.length) % options.length]
  1626. onChange(next.value)
  1627. // Focus follows the choice, so the next arrow press moves on from it.
  1628. requestAnimationFrame(() =>
  1629. groupRef.current
  1630. ?.querySelector<HTMLButtonElement>(`[data-value="${CSS.escape(next.value)}"]`)
  1631. ?.focus()
  1632. )
  1633. }
  1634. return (
  1635. <div className="space-y-2">
  1636. <Label id={labelId} htmlFor={id}>
  1637. {label}
  1638. </Label>
  1639. <div
  1640. ref={groupRef}
  1641. id={id}
  1642. role="radiogroup"
  1643. aria-labelledby={labelId}
  1644. className="flex w-full rounded-lg border bg-muted/50 p-0.5"
  1645. >
  1646. {options.map((option) => {
  1647. const checked = option.value === value
  1648. return (
  1649. <button
  1650. key={option.value}
  1651. type="button"
  1652. role="radio"
  1653. aria-checked={checked}
  1654. data-value={option.value}
  1655. tabIndex={checked || (!value && option === options[0]) ? 0 : -1}
  1656. onClick={() => onChange(option.value)}
  1657. onKeyDown={(e) => {
  1658. if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
  1659. e.preventDefault()
  1660. move(1)
  1661. } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
  1662. e.preventDefault()
  1663. move(-1)
  1664. }
  1665. }}
  1666. className={cn(
  1667. 'min-w-0 flex-1 truncate rounded-md px-2 py-1.5 text-[13px] font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring',
  1668. checked
  1669. ? 'bg-background text-foreground shadow-sm ring-1 ring-border'
  1670. : 'text-muted-foreground hover:text-foreground'
  1671. )}
  1672. >
  1673. {option.label}
  1674. </button>
  1675. )
  1676. })}
  1677. </div>
  1678. </div>
  1679. )
  1680. }