SearchCommand.tsx 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. 'use client'
  2. import { useGuardedPush } from '@/hooks/use-guarded-push'
  3. import { Fragment, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
  4. import { useTranslations } from 'next-intl'
  5. import {
  6. Bell,
  7. Car,
  8. ClipboardCheck,
  9. CornerDownLeft,
  10. Disc3,
  11. FileText,
  12. type LucideIcon,
  13. Package,
  14. Plug,
  15. Keyboard,
  16. ScanLine,
  17. Search,
  18. Users,
  19. Wrench,
  20. } from 'lucide-react'
  21. import {
  22. CommandDialog,
  23. CommandGroup,
  24. CommandInput,
  25. CommandItem,
  26. CommandList,
  27. } from '@/components/ui/command'
  28. import { formatQuantity } from '@/lib/format-quantity'
  29. import { cn } from '@/lib/utils'
  30. import { globalSearch, getRecentCustomers } from '@/features/search/Actions/searchActions'
  31. import { formatTypeKey } from '@/features/vehicles/Lib/typeKey'
  32. import { useTypeKeyEnabled } from '@/components/type-key-context'
  33. import { openPlateLookup, usePlateLookupAccess } from '@/components/plate-lookup-context'
  34. import { requestSpotlight } from '@/features/settings/Components/SettingsSpotlight'
  35. import { CRUMB, useSettingsSearchItems } from '@/features/search/Lib/settingsItems'
  36. import {
  37. type CommandContext,
  38. visibleActionCommands,
  39. visiblePageCommands,
  40. } from '@/features/search/Lib/commands'
  41. import {
  42. type PreparedItem,
  43. type Range,
  44. prepareItem,
  45. prepareQuery,
  46. rank,
  47. splitByRanges,
  48. } from '@/features/search/Lib/matcher'
  49. import { pushRecent, readRecent, type RecentPick } from '@/features/search/Lib/recent'
  50. import { SEARCH_OPEN_EVENT } from '@/features/search/Lib/open'
  51. import { useShortcut, useShortcuts } from '@/features/shortcuts/Components/ShortcutsProvider'
  52. import { ShortcutKeys } from '@/features/shortcuts/Components/ShortcutKeys'
  53. import { SHORTCUTS_HELP_COMMAND, shortcutForCommand } from '@/features/shortcuts/Lib/registry'
  54. import { searchFaultCodes } from '@/features/fault-codes/Actions/searchFaultCodes'
  55. import {
  56. isManufacturerCode,
  57. looksLikeFaultCode,
  58. looksLikeOemCode,
  59. normalizeFaultCode,
  60. } from '@/features/fault-codes/Lib/codes'
  61. import type { OemSearchHit } from '@/features/fault-codes/Lib/types'
  62. type Vehicle = {
  63. id: string
  64. make: string
  65. model: string
  66. year: number
  67. licensePlate: string | null
  68. hsn?: string | null
  69. tsn?: string | null
  70. }
  71. interface SearchResult {
  72. vehicles: Vehicle[]
  73. customers: {
  74. id: string
  75. name: string
  76. email: string | null
  77. phone: string | null
  78. company: string | null
  79. vehicles: Vehicle[]
  80. }[]
  81. services: {
  82. id: string
  83. title: string
  84. invoiceNumber: string | null
  85. vehicle: Vehicle | null
  86. }[]
  87. parts: {
  88. id: string
  89. name: string
  90. partNumber: string | null
  91. quantity: number
  92. /** False for a fee or consumable that is charged but never counted. */
  93. trackStock?: boolean
  94. unit: string | null
  95. }[]
  96. quotes: {
  97. id: string
  98. title: string
  99. quoteNumber: string | null
  100. status: string
  101. }[]
  102. reminders: {
  103. id: string
  104. title: string
  105. dueDate: Date | null
  106. isCompleted: boolean
  107. customer: { id: string; name: string } | null
  108. vehicle: Vehicle | null
  109. }[]
  110. inspections: {
  111. id: string
  112. status: string
  113. createdAt: Date
  114. template: { name: string }
  115. vehicle: Vehicle
  116. }[]
  117. tireSets: {
  118. id: string
  119. reference: string | null
  120. season: string
  121. size: string | null
  122. quantity: number
  123. status: string
  124. location: { code: string } | null
  125. customer: { id: string; name: string } | null
  126. vehicle: Vehicle | null
  127. }[]
  128. }
  129. /** The palette's fault code groups, asked for on their own beside the normal search. */
  130. interface FaultCodeResult {
  131. query: string
  132. /** The code service answered. */
  133. available: boolean
  134. codes: { code: string; title: string }[]
  135. /** A make's own code typed in full (BMW's 283700), from each make that has it. */
  136. oem: OemSearchHit[]
  137. jobs: {
  138. findingId: string
  139. serviceRecordId: string | null
  140. title: string | null
  141. vehicleId: string
  142. vehicle: string
  143. licensePlate: string | null
  144. }[]
  145. }
  146. const NO_FAULT_CODES: FaultCodeResult = {
  147. query: '',
  148. available: false,
  149. codes: [],
  150. oem: [],
  151. jobs: [],
  152. }
  153. const EMPTY: SearchResult = {
  154. vehicles: [],
  155. customers: [],
  156. services: [],
  157. parts: [],
  158. quotes: [],
  159. reminders: [],
  160. inspections: [],
  161. tireSets: [],
  162. }
  163. type RecentCustomer = {
  164. id: string
  165. name: string
  166. email: string | null
  167. phone: string | null
  168. company: string | null
  169. }
  170. /** A connector the catalog offers, trimmed to what the palette shows. */
  171. export type SearchConnector = { id: string; name: string; category: string; logo: string }
  172. export type SearchCommandProps = CommandContext & {
  173. isCloud?: boolean
  174. supportEnabled?: boolean
  175. isMarine?: boolean
  176. connectors?: SearchConnector[]
  177. }
  178. /**
  179. * Anything the palette knows without asking the server: a settings page or
  180. * a setting on it, a connector, a page of the app, or something to start.
  181. */
  182. type LocalItem = {
  183. kind: 'setting' | 'settingsPage' | 'connector' | 'page' | 'action'
  184. id: string
  185. href: string
  186. title: string
  187. subtitle?: string
  188. icon?: LucideIcon
  189. logo?: string
  190. locked?: boolean
  191. anchor?: string
  192. run?: () => void
  193. }
  194. type PreparedLocal = { item: LocalItem; prepared: PreparedItem }
  195. /** How many to show per group when searching. Everything else is a scroll away in the app itself. */
  196. const LIMITS: Record<LocalItem['kind'], number> = {
  197. setting: 8,
  198. settingsPage: 8,
  199. connector: 4,
  200. page: 5,
  201. action: 4,
  202. }
  203. /** Enough recent customers to be useful before typing, few enough that the actions stay in view. */
  204. const RECENT_CUSTOMERS_SHOWN = 8
  205. /** Wait this long after the last keystroke before asking the server. Local matches never wait. */
  206. const REMOTE_DEBOUNCE_MS = 150
  207. function Highlight({ text, ranges }: { text: string; ranges: Range[] }) {
  208. return (
  209. <>
  210. {splitByRanges(text, ranges).map((part, i) =>
  211. part.hit ? (
  212. <mark key={i} className="bg-transparent font-semibold text-primary">
  213. {part.text}
  214. </mark>
  215. ) : (
  216. <Fragment key={i}>{part.text}</Fragment>
  217. )
  218. )}
  219. </>
  220. )
  221. }
  222. /** The shortcut for a page or an action, on the right of its row. */
  223. function LocalShortcut({ id }: { id: string }) {
  224. const shortcut = shortcutForCommand(id)
  225. return shortcut ? <ShortcutKeys id={shortcut.id} /> : null
  226. }
  227. function Kbd({ children }: { children: ReactNode }) {
  228. return (
  229. <kbd className="pointer-events-none inline-flex h-5 min-w-5 items-center justify-center rounded border bg-muted px-1 font-mono text-[10px] font-medium text-muted-foreground">
  230. {children}
  231. </kbd>
  232. )
  233. }
  234. function Chip({ icon: Icon, logo }: { icon?: LucideIcon; logo?: string }) {
  235. return (
  236. <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground ring-1 ring-inset ring-foreground/5 group-data-[selected=true]/row:bg-primary/10 group-data-[selected=true]/row:text-primary group-data-[selected=true]/row:ring-primary/20">
  237. {logo ? (
  238. <img src={logo} alt="" className="h-4 w-4 object-contain" />
  239. ) : Icon ? (
  240. <Icon className="h-4! w-4!" />
  241. ) : null}
  242. </span>
  243. )
  244. }
  245. /**
  246. * One row. The chip lights up in the theme colour on the selected row, and
  247. * the return-key hint appears there and nowhere else, so the eye always
  248. * knows which row Enter will open.
  249. */
  250. function Row({
  251. value,
  252. onSelect,
  253. icon,
  254. logo,
  255. title,
  256. subtitle,
  257. trailing,
  258. locked,
  259. className,
  260. proLabel,
  261. }: {
  262. value: string
  263. onSelect: () => void
  264. icon?: LucideIcon
  265. logo?: string
  266. title: ReactNode
  267. subtitle?: ReactNode
  268. /** A mono tag on the right: a plate, a shelf code, an invoice number. */
  269. trailing?: ReactNode
  270. locked?: boolean
  271. className?: string
  272. proLabel?: string
  273. }) {
  274. return (
  275. <CommandItem
  276. value={value}
  277. onSelect={onSelect}
  278. className={cn('group/row cursor-pointer gap-3 rounded-lg', className)}
  279. >
  280. <Chip icon={icon} logo={logo} />
  281. <div className="min-w-0 flex-1">
  282. <div className="flex items-center gap-2">
  283. <span className="truncate text-sm">{title}</span>
  284. {locked && proLabel && (
  285. <span className="shrink-0 rounded bg-amber-500/15 px-1.5 py-px text-[10px] font-semibold text-amber-600">
  286. {proLabel}
  287. </span>
  288. )}
  289. </div>
  290. {subtitle && <div className="truncate text-xs text-muted-foreground">{subtitle}</div>}
  291. </div>
  292. {trailing && (
  293. <span className="hidden shrink-0 font-mono text-xs text-muted-foreground sm:inline">
  294. {trailing}
  295. </span>
  296. )}
  297. <span className="hidden shrink-0 items-center gap-1 text-[11px] text-muted-foreground opacity-0 transition-opacity group-data-[selected=true]/row:opacity-100 sm:flex">
  298. <CornerDownLeft className="h-3! w-3!" />
  299. </span>
  300. </CommandItem>
  301. )
  302. }
  303. function vehicleLine(v: Vehicle) {
  304. return `${v.year} ${v.make} ${v.model}`
  305. }
  306. function iconForHref(href: string): LucideIcon {
  307. if (href.startsWith('/customers')) return Users
  308. if (href.startsWith('/vehicles')) return Car
  309. if (href.startsWith('/quotes')) return FileText
  310. if (href.startsWith('/inventory')) return Package
  311. if (href.startsWith('/tire-hotel')) return Disc3
  312. if (href.startsWith('/inspections')) return ClipboardCheck
  313. if (href.startsWith('/reminders')) return Bell
  314. if (href.startsWith('/settings')) return Search
  315. return Wrench
  316. }
  317. export function SearchCommand({
  318. visibleSubjects,
  319. features,
  320. tireHotelEnabled,
  321. aiEnabled,
  322. isAdminOrOwner,
  323. isCloud,
  324. supportEnabled,
  325. isMarine,
  326. connectors = [],
  327. faultCodesEnabled,
  328. }: SearchCommandProps) {
  329. const go = useGuardedPush()
  330. const t = useTranslations('search')
  331. const tNav = useTranslations('navigation.sidebar')
  332. const tSettings = useTranslations('settings')
  333. const tIntegrations = useTranslations('integrations')
  334. const tTire = useTranslations('tireHotel')
  335. const tPlate = useTranslations('vehicles.plateLookup')
  336. const tShortcuts = useTranslations('settings.shortcuts')
  337. const { openHelp: openShortcutsHelp } = useShortcuts()
  338. const tFault = useTranslations('faultCodes.search')
  339. const tCodes = useTranslations('faultCodes')
  340. const typeKeyEnabled = useTypeKeyEnabled()
  341. const plateLookup = usePlateLookupAccess()
  342. const [open, setOpen] = useState(false)
  343. const [query, setQuery] = useState('')
  344. const [results, setResults] = useState<SearchResult>(EMPTY)
  345. const [loading, setLoading] = useState(false)
  346. const [recentCustomers, setRecentCustomers] = useState<RecentCustomer[]>([])
  347. const [recent, setRecent] = useState<RecentPick[]>([])
  348. const cacheRef = useRef(new Map<string, SearchResult>())
  349. const seqRef = useRef(0)
  350. const [faultResults, setFaultResults] = useState<FaultCodeResult>(NO_FAULT_CODES)
  351. const faultCacheRef = useRef(new Map<string, FaultCodeResult>())
  352. const faultSeqRef = useRef(0)
  353. const canSettings = !visibleSubjects || visibleSubjects.includes('settings')
  354. const ctx: CommandContext = useMemo(
  355. () => ({
  356. visibleSubjects,
  357. features,
  358. tireHotelEnabled,
  359. aiEnabled,
  360. isAdminOrOwner,
  361. faultCodesEnabled,
  362. }),
  363. [visibleSubjects, features, tireHotelEnabled, aiEnabled, isAdminOrOwner, faultCodesEnabled]
  364. )
  365. const settingsItems = useSettingsSearchItems({ isCloud, supportEnabled, features })
  366. // Everything searchable without the server, titled in the workshop's
  367. // language and prepared once; typing only ranks it.
  368. const localItems = useMemo<PreparedLocal[]>(() => {
  369. const out: PreparedLocal[] = []
  370. const settingsWord = tNav('settings')
  371. for (const page of visiblePageCommands(ctx)) {
  372. const title = tNav(isMarine && page.marineTitleKey ? page.marineTitleKey : page.titleKey)
  373. const item: LocalItem = {
  374. kind: 'page',
  375. id: page.id,
  376. href: page.href,
  377. title,
  378. icon: isMarine && page.marineIcon ? page.marineIcon : page.icon,
  379. }
  380. out.push({ item, prepared: prepareItem({ title, keywords: page.keywords }) })
  381. }
  382. for (const action of visibleActionCommands(ctx)) {
  383. const title = t(`actions.${action.titleKey}`)
  384. const item: LocalItem = {
  385. kind: 'action',
  386. id: action.id,
  387. href: action.href,
  388. title,
  389. icon: action.icon,
  390. }
  391. out.push({ item, prepared: prepareItem({ title, keywords: action.keywords }) })
  392. }
  393. if (plateLookup.available) {
  394. const title = tPlate('open')
  395. out.push({
  396. item: {
  397. kind: 'action',
  398. id: 'action:plate-lookup',
  399. href: '#',
  400. title,
  401. subtitle: plateLookup.registryName ?? undefined,
  402. icon: ScanLine,
  403. run: () => openPlateLookup(),
  404. },
  405. prepared: prepareItem({
  406. title,
  407. keywords: ['plate', 'registry', 'lookup', 'license plate', 'vin', 'registration'],
  408. }),
  409. })
  410. }
  411. {
  412. const title = tShortcuts('help.title')
  413. out.push({
  414. item: {
  415. kind: 'action',
  416. id: SHORTCUTS_HELP_COMMAND,
  417. href: '#',
  418. title,
  419. icon: Keyboard,
  420. run: openShortcutsHelp,
  421. },
  422. prepared: prepareItem({
  423. title,
  424. keywords: ['hotkeys', 'keys', 'shortcut', 'keyboard', 'key bindings', 'cheat sheet'],
  425. }),
  426. })
  427. }
  428. if (canSettings) {
  429. for (const { item, prepared } of settingsItems) {
  430. const subtitle = item.description
  431. ? `${item.breadcrumb} · ${item.description}`
  432. : item.breadcrumb
  433. out.push({
  434. item: {
  435. kind: item.kind,
  436. id: item.id,
  437. href: item.href,
  438. title: item.title,
  439. subtitle: `${settingsWord}${CRUMB}${subtitle}`,
  440. icon: item.icon,
  441. locked: item.locked,
  442. anchor: item.anchor,
  443. },
  444. prepared,
  445. })
  446. }
  447. const integrationsWord = tSettings('nav.items.integrations.title')
  448. for (const c of connectors) {
  449. const category = tIntegrations(`categories.${c.category}`)
  450. out.push({
  451. item: {
  452. kind: 'connector',
  453. id: `connector:${c.id}`,
  454. href: `/settings/integrations/${c.id}`,
  455. title: c.name,
  456. subtitle: `${settingsWord}${CRUMB}${integrationsWord}${CRUMB}${category}`,
  457. icon: Plug,
  458. logo: c.logo,
  459. },
  460. prepared: prepareItem({
  461. title: c.name,
  462. keywords: [c.id, c.category, 'integration', 'connect', 'connector'],
  463. context: category,
  464. }),
  465. })
  466. }
  467. }
  468. return out
  469. }, [
  470. ctx,
  471. isMarine,
  472. canSettings,
  473. settingsItems,
  474. connectors,
  475. plateLookup.available,
  476. plateLookup.registryName,
  477. t,
  478. tNav,
  479. tSettings,
  480. tIntegrations,
  481. tPlate,
  482. tShortcuts,
  483. openShortcutsHelp,
  484. ])
  485. const preparedQuery = useMemo(() => prepareQuery(query), [query])
  486. const hasQuery = preparedQuery.tokens.length > 0
  487. const ranked = useMemo(
  488. () => (hasQuery ? rank(preparedQuery, localItems) : []),
  489. [hasQuery, preparedQuery, localItems]
  490. )
  491. // Direct hits go above the workshop's records; loose ones only show when
  492. // nothing else does, so "ola" never buries a customer under Localization.
  493. const { strongGroups, weakGroups } = useMemo(() => {
  494. type Group = { kind: LocalItem['kind']; rows: typeof ranked; best: number }
  495. const build = (rows: typeof ranked) => {
  496. const byKind = new Map<LocalItem['kind'], Group>()
  497. for (const row of rows) {
  498. const kind = row.item.kind
  499. let group = byKind.get(kind)
  500. if (!group) {
  501. group = { kind, rows: [], best: row.match.score }
  502. byKind.set(kind, group)
  503. }
  504. if (group.rows.length < LIMITS[kind]) group.rows.push(row)
  505. }
  506. return [...byKind.values()].sort((a, b) => b.best - a.best)
  507. }
  508. return {
  509. strongGroups: build(ranked.filter((r) => r.match.strong)),
  510. weakGroups: build(ranked.filter((r) => !r.match.strong)),
  511. }
  512. }, [ranked])
  513. // Opened by its shortcut, and by the header's search box, which has no
  514. // other way to reach this component.
  515. useShortcut('general.search', () => setOpen((prev) => !prev))
  516. useEffect(() => {
  517. const onOpen = () => setOpen(true)
  518. document.addEventListener(SEARCH_OPEN_EVENT, onOpen)
  519. return () => document.removeEventListener(SEARCH_OPEN_EVENT, onOpen)
  520. }, [])
  521. // On opening: forget what the server said last time (records change), read
  522. // what this person opened lately, and fetch the customers worked on last.
  523. useEffect(() => {
  524. if (!open) return
  525. cacheRef.current.clear()
  526. faultCacheRef.current.clear()
  527. // eslint-disable-next-line react-hooks/set-state-in-effect -- reading the store on open is the point
  528. setRecent(readRecent())
  529. let cancelled = false
  530. getRecentCustomers().then((res) => {
  531. if (!cancelled && res.success && res.data) setRecentCustomers(res.data)
  532. })
  533. return () => {
  534. cancelled = true
  535. }
  536. }, [open])
  537. // The server search: debounced a little, cached for the life of the
  538. // dialog, and never allowed to overwrite a newer answer with an older one.
  539. // Previous results stay on screen while the next ones load, so the list
  540. // never blinks empty between keystrokes.
  541. useEffect(() => {
  542. const term = query.trim()
  543. // Every change of query, cached or not, makes any answer still on its way stale.
  544. const seq = ++seqRef.current
  545. if (term.length < 2) {
  546. // eslint-disable-next-line react-hooks/set-state-in-effect -- clearing results on a short query is intentional
  547. setResults(EMPTY)
  548. setLoading(false)
  549. return
  550. }
  551. const key = term.toLowerCase()
  552. const cached = cacheRef.current.get(key)
  553. if (cached) {
  554. setResults(cached)
  555. setLoading(false)
  556. return
  557. }
  558. setLoading(true)
  559. const timer = setTimeout(() => {
  560. globalSearch(term).then((res) => {
  561. if (seq !== seqRef.current) return
  562. if (res.success && res.data) {
  563. cacheRef.current.set(key, res.data)
  564. setResults(res.data)
  565. }
  566. setLoading(false)
  567. })
  568. }, REMOTE_DEBOUNCE_MS)
  569. return () => clearTimeout(timer)
  570. }, [query])
  571. // Fault codes, asked for on their own so the code service can never hold
  572. // up vehicles, customers or jobs. Only a query that looks like a code goes
  573. // out; the jobs where a whole code was read come back with or without the
  574. // service, since they are the workshop's own.
  575. useEffect(() => {
  576. const term = query.trim()
  577. const seq = ++faultSeqRef.current
  578. if (!looksLikeFaultCode(term) && !looksLikeOemCode(term)) {
  579. // eslint-disable-next-line react-hooks/set-state-in-effect -- clearing results on a query that is not a code is intentional
  580. setFaultResults(NO_FAULT_CODES)
  581. return
  582. }
  583. const key = term.toUpperCase()
  584. const cached = faultCacheRef.current.get(key)
  585. if (cached) {
  586. setFaultResults(cached)
  587. return
  588. }
  589. const timer = setTimeout(() => {
  590. searchFaultCodes(term).then((res) => {
  591. if (seq !== faultSeqRef.current) return
  592. if (res.success && res.data) {
  593. const next = {
  594. query: key,
  595. available: res.data.available,
  596. codes: res.data.codes,
  597. oem: res.data.oem,
  598. jobs: res.data.jobs,
  599. }
  600. faultCacheRef.current.set(key, next)
  601. setFaultResults(next)
  602. }
  603. })
  604. }, REMOTE_DEBOUNCE_MS)
  605. return () => clearTimeout(timer)
  606. }, [query])
  607. const close = useCallback(() => {
  608. setOpen(false)
  609. setQuery('')
  610. }, [])
  611. const pickLocal = useCallback(
  612. (item: LocalItem) => {
  613. close()
  614. pushRecent({
  615. id: item.id,
  616. href: item.href,
  617. title: item.title,
  618. subtitle: item.subtitle,
  619. kind: 'local',
  620. })
  621. if (item.run) {
  622. item.run()
  623. return
  624. }
  625. go(item.href)
  626. if (item.anchor) requestSpotlight(item.anchor)
  627. },
  628. [close, go]
  629. )
  630. const pickRecord = useCallback(
  631. (href: string, title: string, subtitle?: string) => {
  632. close()
  633. pushRecent({ id: href, href, title, subtitle, kind: 'record' })
  634. go(href)
  635. },
  636. [close, go]
  637. )
  638. const hasRecords =
  639. results.vehicles.length > 0 ||
  640. results.customers.length > 0 ||
  641. results.services.length > 0 ||
  642. results.parts.length > 0 ||
  643. results.quotes.length > 0 ||
  644. results.reminders.length > 0 ||
  645. results.inspections.length > 0 ||
  646. results.tireSets.length > 0
  647. // The palette's fault code rows: the service's codes for what was typed, and
  648. // the whole code itself when the service has nothing for it, so Enter still
  649. // opens its page.
  650. const faultQuery = query.trim().toUpperCase()
  651. const faultCurrent = faultResults.query === faultQuery ? faultResults : NO_FAULT_CODES
  652. const typedCode = normalizeFaultCode(faultQuery)
  653. const faultCodeRows = faultCodesEnabled
  654. ? typedCode && !faultCurrent.codes.some((c) => c.code === typedCode)
  655. ? [{ code: typedCode, title: '' }, ...faultCurrent.codes]
  656. : faultCurrent.codes
  657. : []
  658. const faultJobs = faultCurrent.jobs
  659. const searchFaultWords =
  660. faultCodesEnabled && !looksLikeFaultCode(query) && query.trim().length >= 3
  661. const faultOemRows = faultCodesEnabled ? faultCurrent.oem : []
  662. const hasFaultRows = faultCodeRows.length > 0 || faultOemRows.length > 0 || faultJobs.length > 0
  663. const showWeak = !hasRecords && !hasFaultRows && strongGroups.length === 0
  664. const nothing =
  665. hasQuery &&
  666. !loading &&
  667. !hasRecords &&
  668. !hasFaultRows &&
  669. strongGroups.length === 0 &&
  670. weakGroups.length === 0
  671. const groupHeading = (kind: LocalItem['kind']) => {
  672. switch (kind) {
  673. case 'setting':
  674. case 'settingsPage':
  675. return t('groups.settings')
  676. case 'connector':
  677. return t('groups.integrations')
  678. case 'page':
  679. return t('groups.pages')
  680. case 'action':
  681. return t('groups.actions')
  682. }
  683. }
  684. // Settings pages and settings share a heading; cmdk needs one group per
  685. // heading or it draws it twice, so the two kinds are merged here.
  686. const mergeSettings = (groups: typeof strongGroups) => {
  687. const merged: typeof strongGroups = []
  688. for (const g of groups) {
  689. const heading = groupHeading(g.kind)
  690. const existing = merged.find((m) => groupHeading(m.kind) === heading)
  691. if (existing) {
  692. existing.rows = [...existing.rows, ...g.rows]
  693. .sort((a, b) => b.match.score - a.match.score)
  694. .slice(0, LIMITS.setting)
  695. existing.best = Math.max(existing.best, g.best)
  696. } else merged.push({ ...g, rows: [...g.rows] })
  697. }
  698. return merged.sort((a, b) => b.best - a.best)
  699. }
  700. const renderLocalGroups = (groups: typeof strongGroups) =>
  701. mergeSettings(groups).map((group) => (
  702. <CommandGroup key={group.kind} heading={groupHeading(group.kind)}>
  703. {group.rows.map(({ item, match }) => (
  704. <Row
  705. key={item.id}
  706. value={item.id}
  707. onSelect={() => pickLocal(item)}
  708. icon={item.icon}
  709. logo={item.logo}
  710. title={<Highlight text={item.title} ranges={match.ranges} />}
  711. subtitle={item.subtitle}
  712. locked={item.locked}
  713. proLabel={t('pro')}
  714. trailing={<LocalShortcut id={item.id} />}
  715. />
  716. ))}
  717. </CommandGroup>
  718. ))
  719. // Recent picks: local ones are looked up again so a renamed page reads
  720. // right and a vanished one drops out; records keep the words they had.
  721. const recentRows = useMemo(() => {
  722. const byId = new Map(localItems.map(({ item }) => [item.id, item]))
  723. return recent
  724. .map((pick) => {
  725. if (pick.kind === 'local') {
  726. const item = byId.get(pick.id)
  727. return item ? { pick, item } : null
  728. }
  729. return { pick, item: null }
  730. })
  731. .filter((r): r is { pick: RecentPick; item: LocalItem | null } => r !== null)
  732. .slice(0, 6)
  733. }, [recent, localItems])
  734. return (
  735. <CommandDialog
  736. open={open}
  737. onOpenChange={(next) => (next ? setOpen(true) : close())}
  738. title={t('title')}
  739. description={t('description')}
  740. className="top-[6vh] translate-y-0 gap-0 rounded-xl border-border/60 shadow-2xl sm:top-[12vh] sm:max-w-2xl"
  741. showCloseButton={false}
  742. shouldFilter={false}
  743. >
  744. <div className="relative">
  745. <CommandInput
  746. placeholder={t('placeholder')}
  747. value={query}
  748. onValueChange={setQuery}
  749. autoFocus
  750. />
  751. {loading && <div className="search-progress" aria-hidden />}
  752. </div>
  753. <CommandList className="max-h-[min(62vh,560px)] min-h-[220px] scroll-py-2">
  754. {nothing && (
  755. <div className="flex flex-col items-center gap-1 px-6 py-12 text-center">
  756. <Search className="mb-2 h-5 w-5 text-muted-foreground/60" />
  757. <p className="text-sm font-medium">{t('noResultsFor', { query: query.trim() })}</p>
  758. <p className="text-xs text-muted-foreground">{t('noResultsHint')}</p>
  759. </div>
  760. )}
  761. {!hasQuery && recentRows.length > 0 && (
  762. <CommandGroup heading={t('groups.recent')}>
  763. {recentRows.map(({ pick, item }) =>
  764. item ? (
  765. <Row
  766. key={pick.id}
  767. value={`recent:${pick.id}`}
  768. onSelect={() => pickLocal(item)}
  769. icon={item.icon}
  770. logo={item.logo}
  771. title={item.title}
  772. subtitle={item.subtitle}
  773. locked={item.locked}
  774. proLabel={t('pro')}
  775. trailing={<LocalShortcut id={item.id} />}
  776. />
  777. ) : (
  778. <Row
  779. key={pick.id}
  780. value={`recent:${pick.id}`}
  781. onSelect={() => pickRecord(pick.href, pick.title, pick.subtitle)}
  782. icon={iconForHref(pick.href)}
  783. title={pick.title}
  784. subtitle={pick.subtitle}
  785. />
  786. )
  787. )}
  788. </CommandGroup>
  789. )}
  790. {!hasQuery && recentCustomers.length > 0 && (
  791. <CommandGroup heading={t('recentCustomers')}>
  792. {recentCustomers.slice(0, RECENT_CUSTOMERS_SHOWN).map((c) => (
  793. <Row
  794. key={c.id}
  795. value={`recent-customer:${c.id}`}
  796. onSelect={() =>
  797. pickRecord(
  798. `/customers/${c.id}`,
  799. c.name,
  800. [c.company, c.email, c.phone].filter(Boolean).join(' · ') || undefined
  801. )
  802. }
  803. icon={Users}
  804. title={c.name}
  805. subtitle={[c.company, c.email, c.phone].filter(Boolean).join(' · ')}
  806. />
  807. ))}
  808. </CommandGroup>
  809. )}
  810. {!hasQuery && (
  811. <CommandGroup heading={t('groups.actions')}>
  812. {localItems
  813. .filter(({ item }) => item.kind === 'action')
  814. .map(({ item }) => (
  815. <Row
  816. key={item.id}
  817. value={item.id}
  818. onSelect={() => pickLocal(item)}
  819. icon={item.icon}
  820. title={item.title}
  821. subtitle={item.subtitle}
  822. trailing={<LocalShortcut id={item.id} />}
  823. />
  824. ))}
  825. </CommandGroup>
  826. )}
  827. {hasQuery && (faultCodeRows.length > 0 || faultOemRows.length > 0) && (
  828. <CommandGroup heading={tFault('group')}>
  829. {faultOemRows.map((c) => (
  830. <Row
  831. key={`${c.make}:${c.code}`}
  832. value={`fault-oem:${c.make}:${c.code}`}
  833. onSelect={() =>
  834. pickRecord(`/fault-codes/oem/${c.make}/${c.code}`, c.code, c.title || undefined)
  835. }
  836. icon={ScanLine}
  837. title={
  838. <>
  839. <span className="mr-2 font-mono font-semibold">{c.code}</span>
  840. <span className="mr-2 rounded-full border border-primary/30 bg-primary/10 px-1.5 py-px text-[10px] font-medium text-primary">
  841. {tCodes('oem.badge', { make: c.makeName })}
  842. </span>
  843. {c.title}
  844. </>
  845. }
  846. subtitle={
  847. c.meanings > 1
  848. ? tCodes('oem.otherMeanings', { count: c.meanings - 1 })
  849. : undefined
  850. }
  851. />
  852. ))}
  853. {faultCodeRows.map((c) => (
  854. <Row
  855. key={c.code}
  856. value={`fault-code:${c.code}`}
  857. onSelect={() => pickRecord(`/fault-codes/${c.code}`, c.code, c.title || undefined)}
  858. icon={ScanLine}
  859. title={
  860. <>
  861. <span className="mr-2 font-mono font-semibold">{c.code}</span>
  862. {c.title}
  863. </>
  864. }
  865. subtitle={
  866. // A whole code the service has no meaning for: say why, when we know.
  867. c.title
  868. ? undefined
  869. : isManufacturerCode(c.code)
  870. ? tCodes('manufacturerUnknown')
  871. : faultCurrent.available && faultCurrent.query === c.code
  872. ? tCodes('noMeaning')
  873. : undefined
  874. }
  875. />
  876. ))}
  877. </CommandGroup>
  878. )}
  879. {hasQuery && faultJobs.length > 0 && (
  880. <CommandGroup heading={tFault('jobsWith', { code: faultCurrent.query })}>
  881. {faultJobs.map((job) => {
  882. const href = job.serviceRecordId
  883. ? `/vehicles/${job.vehicleId}/service/${job.serviceRecordId}`
  884. : `/vehicles/${job.vehicleId}`
  885. const title = job.title ?? job.vehicle
  886. const subtitle = [job.title ? job.vehicle : null, job.licensePlate]
  887. .filter(Boolean)
  888. .join(' · ')
  889. return (
  890. <Row
  891. key={job.findingId}
  892. value={`fault-job:${job.findingId}`}
  893. onSelect={() => pickRecord(href, title, subtitle || undefined)}
  894. icon={Wrench}
  895. title={title}
  896. subtitle={subtitle}
  897. trailing={job.licensePlate}
  898. />
  899. )
  900. })}
  901. </CommandGroup>
  902. )}
  903. {hasQuery && renderLocalGroups(strongGroups)}
  904. {hasQuery && results.customers.length > 0 && (
  905. <CommandGroup heading={tNav('customers')}>
  906. {results.customers.map((c) => (
  907. <Fragment key={c.id}>
  908. <Row
  909. value={`customer:${c.id}`}
  910. onSelect={() =>
  911. pickRecord(
  912. `/customers/${c.id}`,
  913. c.name,
  914. [c.company, c.email, c.phone].filter(Boolean).join(' · ') || undefined
  915. )
  916. }
  917. icon={Users}
  918. title={c.name}
  919. subtitle={[c.company, c.email, c.phone].filter(Boolean).join(' · ')}
  920. />
  921. {c.vehicles.map((v) => (
  922. <Row
  923. key={v.id}
  924. value={`customer-vehicle:${v.id}`}
  925. onSelect={() => pickRecord(`/vehicles/${v.id}`, vehicleLine(v), c.name)}
  926. icon={Car}
  927. title={vehicleLine(v)}
  928. subtitle={c.name}
  929. trailing={v.licensePlate}
  930. className="ml-10"
  931. />
  932. ))}
  933. </Fragment>
  934. ))}
  935. </CommandGroup>
  936. )}
  937. {hasQuery && results.vehicles.length > 0 && (
  938. <CommandGroup heading={tNav(isMarine ? 'vessels' : 'vehicles')}>
  939. {results.vehicles.map((v) => (
  940. <Row
  941. key={v.id}
  942. value={`vehicle:${v.id}`}
  943. onSelect={() =>
  944. pickRecord(`/vehicles/${v.id}`, vehicleLine(v), v.licensePlate ?? undefined)
  945. }
  946. icon={Car}
  947. title={vehicleLine(v)}
  948. subtitle={
  949. typeKeyEnabled && (v.hsn || v.tsn) ? formatTypeKey(v.hsn, v.tsn) : undefined
  950. }
  951. trailing={v.licensePlate}
  952. />
  953. ))}
  954. </CommandGroup>
  955. )}
  956. {hasQuery && results.services.length > 0 && (
  957. <CommandGroup heading={t('services')}>
  958. {results.services.map((s) => {
  959. const href = s.vehicle
  960. ? `/vehicles/${s.vehicle.id}/service/${s.id}`
  961. : `/sales/${s.id}`
  962. const subtitle = [s.vehicle ? vehicleLine(s.vehicle) : null, s.vehicle?.licensePlate]
  963. .filter(Boolean)
  964. .join(' · ')
  965. return (
  966. <Row
  967. key={s.id}
  968. value={`service:${s.id}`}
  969. onSelect={() => pickRecord(href, s.title, subtitle || undefined)}
  970. icon={Wrench}
  971. title={s.title}
  972. subtitle={subtitle}
  973. trailing={s.invoiceNumber}
  974. />
  975. )
  976. })}
  977. </CommandGroup>
  978. )}
  979. {hasQuery && results.quotes.length > 0 && (
  980. <CommandGroup heading={tNav('quotes')}>
  981. {results.quotes.map((q) => (
  982. <Row
  983. key={q.id}
  984. value={`quote:${q.id}`}
  985. onSelect={() => pickRecord(`/quotes/${q.id}`, q.title, q.quoteNumber ?? undefined)}
  986. icon={FileText}
  987. title={q.title}
  988. subtitle={q.status}
  989. trailing={q.quoteNumber}
  990. />
  991. ))}
  992. </CommandGroup>
  993. )}
  994. {hasQuery && results.parts.length > 0 && (
  995. <CommandGroup heading={tNav('inventory')}>
  996. {results.parts.map((p) => (
  997. <Row
  998. key={p.id}
  999. value={`part:${p.id}`}
  1000. onSelect={() => pickRecord('/inventory', p.name, p.partNumber ?? undefined)}
  1001. icon={Package}
  1002. title={p.name}
  1003. subtitle={
  1004. p.trackStock === false
  1005. ? undefined
  1006. : `${formatQuantity(p.quantity, p.unit)} in stock`
  1007. }
  1008. trailing={p.partNumber}
  1009. />
  1010. ))}
  1011. </CommandGroup>
  1012. )}
  1013. {hasQuery && results.reminders.length > 0 && (
  1014. <CommandGroup heading={tNav('reminders')}>
  1015. {results.reminders.map((r) => {
  1016. const href = r.vehicle ? `/vehicles/${r.vehicle.id}?tab=reminders` : '/reminders'
  1017. const subtitle = r.vehicle
  1018. ? `${vehicleLine(r.vehicle)}${r.vehicle.licensePlate ? ` · ${r.vehicle.licensePlate}` : ''}`
  1019. : (r.customer?.name ?? '')
  1020. return (
  1021. <Row
  1022. key={r.id}
  1023. value={`reminder:${r.id}`}
  1024. onSelect={() => pickRecord(href, r.title, subtitle || undefined)}
  1025. icon={Bell}
  1026. title={
  1027. <span className={cn(r.isCompleted && 'text-muted-foreground line-through')}>
  1028. {r.title}
  1029. </span>
  1030. }
  1031. subtitle={subtitle}
  1032. />
  1033. )
  1034. })}
  1035. </CommandGroup>
  1036. )}
  1037. {/* Shelf code leads: the desk asks "where are these tires", and the
  1038. code is the answer they are about to read out loud. */}
  1039. {hasQuery && results.tireSets.length > 0 && (
  1040. <CommandGroup heading={tNav('tireHotel')}>
  1041. {results.tireSets.map((set) => {
  1042. const title = set.location?.code ?? tTire(`statuses.${set.status}`)
  1043. const subtitle = [
  1044. set.customer?.name,
  1045. set.vehicle ? `${set.vehicle.make} ${set.vehicle.model}` : null,
  1046. set.size,
  1047. tTire('list.tireCount', { count: set.quantity }),
  1048. ]
  1049. .filter(Boolean)
  1050. .join(' · ')
  1051. return (
  1052. <Row
  1053. key={set.id}
  1054. value={`tire:${set.id}`}
  1055. onSelect={() => pickRecord(`/tire-hotel/${set.id}`, title, subtitle)}
  1056. icon={Disc3}
  1057. title={<span className={cn(set.location?.code && 'font-mono')}>{title}</span>}
  1058. subtitle={subtitle}
  1059. trailing={set.vehicle?.licensePlate}
  1060. />
  1061. )
  1062. })}
  1063. </CommandGroup>
  1064. )}
  1065. {hasQuery && results.inspections.length > 0 && (
  1066. <CommandGroup heading={tNav('inspections')}>
  1067. {results.inspections.map((insp) => (
  1068. <Row
  1069. key={insp.id}
  1070. value={`inspection:${insp.id}`}
  1071. onSelect={() =>
  1072. pickRecord(
  1073. `/inspections/${insp.id}`,
  1074. insp.template.name,
  1075. vehicleLine(insp.vehicle)
  1076. )
  1077. }
  1078. icon={ClipboardCheck}
  1079. title={insp.template.name}
  1080. subtitle={`${vehicleLine(insp.vehicle)} · ${insp.status}`}
  1081. trailing={insp.vehicle.licensePlate}
  1082. />
  1083. ))}
  1084. </CommandGroup>
  1085. )}
  1086. {hasQuery && showWeak && renderLocalGroups(weakGroups)}
  1087. {searchFaultWords && (
  1088. <CommandGroup heading={tFault('group')}>
  1089. <Row
  1090. value="fault-code-words"
  1091. onSelect={() =>
  1092. pickRecord(
  1093. `/fault-codes?q=${encodeURIComponent(query.trim())}`,
  1094. tFault('searchFor', { query: query.trim() })
  1095. )
  1096. }
  1097. icon={ScanLine}
  1098. title={tFault('searchFor', { query: query.trim() })}
  1099. />
  1100. </CommandGroup>
  1101. )}
  1102. </CommandList>
  1103. <div className="flex items-center justify-between gap-4 border-t px-3 py-2 text-[11px] text-muted-foreground">
  1104. <div className="hidden items-center gap-3 sm:flex">
  1105. <span className="flex items-center gap-1">
  1106. <Kbd>↑</Kbd>
  1107. <Kbd>↓</Kbd>
  1108. <span className="ml-1">{t('hints.navigate')}</span>
  1109. </span>
  1110. <span className="flex items-center gap-1">
  1111. <Kbd>↵</Kbd>
  1112. <span className="ml-1">{t('hints.open')}</span>
  1113. </span>
  1114. <span className="flex items-center gap-1">
  1115. <Kbd>esc</Kbd>
  1116. <span className="ml-1">{t('hints.close')}</span>
  1117. </span>
  1118. </div>
  1119. <div className="min-w-0 truncate">
  1120. {loading ? t('hints.searching') : !hasQuery ? t('hints.start') : null}
  1121. </div>
  1122. </div>
  1123. </CommandDialog>
  1124. )
  1125. }