diff --git a/apps/frontend/src/components/Map.tsx b/apps/frontend/src/components/Map.tsx index 8137d86..42b14e0 100644 --- a/apps/frontend/src/components/Map.tsx +++ b/apps/frontend/src/components/Map.tsx @@ -1,11 +1,43 @@ -import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet' +import { useEffect, useState } from 'react' +import { MapContainer, Marker, Popup, TileLayer, useMap } from 'react-leaflet' + +import { formatPrice } from '../lib/format-price' +import type { SearchResult } from '../types/search' +import { SearchBox } from './SearchBox' + +const DEFAULT_CENTER: [number, number] = [63.4305, 10.3951] +const DEFAULT_ZOOM = 15 + +function FlyToResult({ result }: { result: SearchResult | null }) { + const map = useMap() + + useEffect(() => { + if (result) { + map.flyTo([result.lat, result.lon], result.type === 'city' ? 12 : 16) + } + }, [result, map]) + + return null +} + +export default function Map({ + onSelect, +}: { + onSelect?: (result: SearchResult) => void +}) { + const [selected, setSelected] = useState(null) + + function handleSelect(result: SearchResult) { + setSelected(result) + onSelect?.(result) + } -export default function Map() { return ( -
+
+ @@ -13,11 +45,22 @@ export default function Map() { attribution='© OpenStreetMap contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> - - - Guinness!!! - - + + {selected && ( + + + {selected.name} + {selected.address && ( + {selected.address} + )} + {selected.latestPriceSighting && ( + + {formatPrice(selected.latestPriceSighting)} + + )} + + + )}
) diff --git a/apps/frontend/src/components/SearchBox.tsx b/apps/frontend/src/components/SearchBox.tsx new file mode 100644 index 0000000..5085820 --- /dev/null +++ b/apps/frontend/src/components/SearchBox.tsx @@ -0,0 +1,293 @@ +import { keepPreviousData, useQuery } from '@tanstack/react-query' +import { useEffect, useId, useMemo, useState } from 'react' +import type { FormEvent, KeyboardEvent } from 'react' + +import { graphqlFetch } from '../graphql/client' +import { formatPrice } from '../lib/format-price' +import type { SearchResult } from '../types/search' + +const DEBOUNCE_MS = 300 +const COLLAPSED_RESULT_COUNT = 3 + +// Search runs in the database (see apps/backend/src/schema/schema.ts). Results +// mix cities and venues; `type` tells them apart. +const SEARCH_QUERY = ` + query Search($term: String!) { + search(term: $term) { + type + name + lat + lon + address + openingHours { + days + opening + closing + } + latestPriceSighting { + price + size + sizeMl + Limitations + timeStart + timeEnd + timeSighted + } + } + } +` + +function typeRank(result: SearchResult) { + // Cities are the most useful thing to jump to, so list them first. + return result.type === 'city' ? 0 : 1 +} + +function typeLabel(result: SearchResult) { + return result.type === 'city' ? 'City' : 'Pub' +} + +function SearchIcon() { + return ( + + ) +} + +export function SearchBox({ + onSelect, +}: { + onSelect: (result: SearchResult) => void +}) { + const inputId = useId() + const listId = useId() + + const [term, setTerm] = useState('') + const [debouncedTerm, setDebouncedTerm] = useState('') + const [open, setOpen] = useState(false) + const [showAll, setShowAll] = useState(false) + const [activeIndex, setActiveIndex] = useState(-1) + + // Debounce the term so we do not hit the server on every keystroke. + useEffect(() => { + const timeout = setTimeout(() => { + setDebouncedTerm(term.trim()) + }, DEBOUNCE_MS) + + return () => clearTimeout(timeout) + }, [term]) + + // Collapse the list again whenever the term changes (the plan wants the full + // list only after the user presses Enter). + useEffect(() => { + setShowAll(false) + setActiveIndex(-1) + }, [term]) + + const { data, isFetching, isError } = useQuery({ + queryKey: ['search', debouncedTerm], + queryFn: () => + graphqlFetch<{ search: SearchResult[] }>(SEARCH_QUERY, { + term: debouncedTerm, + }), + enabled: debouncedTerm.length > 0, + placeholderData: keepPreviousData, + retry: 1, + }) + + const results = useMemo(() => { + const all = data?.search ?? [] + + return [...all].sort((a, b) => typeRank(a) - typeRank(b)) + }, [data]) + + const visibleResults = showAll + ? results + : results.slice(0, COLLAPSED_RESULT_COUNT) + const hiddenCount = results.length - visibleResults.length + const activeOption = + activeIndex >= 0 && activeIndex < visibleResults.length ? activeIndex : -1 + + const waitingForDebounce = term.trim() !== debouncedTerm + const showPanel = open && term.trim().length > 0 + + function select(result: SearchResult) { + setTerm(result.name) + setDebouncedTerm(result.name) + setOpen(false) + setShowAll(false) + setActiveIndex(-1) + onSelect(result) + } + + function handleSubmit(event: FormEvent) { + event.preventDefault() + + const active = activeIndex >= 0 ? visibleResults[activeIndex] : undefined + + if (active) { + select(active) + return + } + + // Enter (or the search button) reveals the full result list. + setOpen(true) + setShowAll(true) + } + + function handleKeyDown(event: KeyboardEvent) { + if (event.key === 'ArrowDown') { + event.preventDefault() + setOpen(true) + setActiveIndex((index) => Math.min(index + 1, visibleResults.length - 1)) + } else if (event.key === 'ArrowUp') { + event.preventDefault() + setActiveIndex((index) => Math.max(index - 1, -1)) + } else if (event.key === 'Escape') { + setOpen(false) + setActiveIndex(-1) + } + } + + return ( +
+
+ +
+ + { + setTerm(event.target.value) + setOpen(true) + }} + onFocus={() => setOpen(true)} + onBlur={() => setOpen(false)} + onKeyDown={handleKeyDown} + placeholder="Search for a pub or city…" + autoComplete="off" + role="combobox" + aria-controls={listId} + aria-expanded={showPanel} + aria-autocomplete="list" + aria-activedescendant={ + activeOption >= 0 ? `${listId}-option-${activeOption}` : undefined + } + className="w-full bg-transparent text-sm text-[var(--sea-ink)] outline-none placeholder:text-[var(--sea-ink-soft)] [&::-webkit-search-cancel-button]:appearance-none" + /> + {term.length > 0 && ( + + )} +
+
+ + {showPanel && ( +
+ {isError && ( +

+ Search is unavailable right now. +

+ )} + + {!isError && (waitingForDebounce || isFetching) && ( +

+ Searching… +

+ )} + + {!isError && + !waitingForDebounce && + !isFetching && + results.length === 0 && ( +

+ No matches for “{debouncedTerm}”. +

+ )} + + {!isError && visibleResults.length > 0 && ( +
    + {visibleResults.map((result, index) => ( +
  • + +
  • + ))} +
+ )} + + {!isError && hiddenCount > 0 && ( + + )} +
+ )} +
+ ) +} + +export default SearchBox diff --git a/apps/frontend/src/components/ViewVenue.tsx b/apps/frontend/src/components/ViewVenue.tsx index fb67c63..6c55f87 100644 --- a/apps/frontend/src/components/ViewVenue.tsx +++ b/apps/frontend/src/components/ViewVenue.tsx @@ -1,64 +1,52 @@ -import type { venue } from '#/types/venue' -import { useQuery } from '@tanstack/react-query' -import { graphqlFetch } from '#/graphql/client' +import { formatPrice } from '#/lib/format-price' +import type { SearchResult } from '#/types/search' -const GET_VENUE = ` - query GetVenues { - venue { - id - name - address - city { - id - name - } - openingHours { - days - opening - closing - } - } - } -` - -export function ViewVenue(Current: venue) { - const fmt = (iso: string) => iso.slice(11, 16) +function formatTime(iso: string) { + return iso.slice(11, 16) +} +export function ViewVenue({ venue }: { venue: SearchResult }) { return ( -
-

- {Current.city.name} -

-

{Current.name}

-

{Current.address}

+
+

Selected pub

+

{venue.name}

+

{venue.address}

+ {venue.latestPriceSighting && ( +

+ Latest price:{' '} + {formatPrice(venue.latestPriceSighting)} +

+ )}

Opening hours

-
    - {Current.openingHours.map((oh, i) => ( -
  • - {oh.days.join(', ')} - - {fmt(oh.opening)} - {fmt(oh.closing)} - -
  • - ))} -
+ {venue.openingHours && venue.openingHours.length > 0 ? ( +
    + {venue.openingHours.map((openingHours, index) => ( +
  • + + {openingHours.days.join(', ')} + + + {formatTime(openingHours.opening)} -{' '} + {formatTime(openingHours.closing)} + +
  • + ))} +
+ ) : ( +

+ No opening hours listed. +

+ )}
) } -export default function VenueLoader() { - const { data, isPending, isError } = useQuery({ - queryKey: ['venues'], - queryFn: () => graphqlFetch<{ venue: venue[] }>(GET_VENUE), - }) +export default function VenueLoader({ venue }: { venue: SearchResult | null }) { + // Only venues have a card; a selected city just moves the map. + if (!venue || venue.type !== 'venue') return null - if (isPending) return

Loading venue…

- if (isError) return
error
- // Hardcoded: show first venue for now - if (data.venue.length == 0) return
No venues found
- const first = data.venue[0] - return + return } diff --git a/apps/frontend/src/lib/format-price.ts b/apps/frontend/src/lib/format-price.ts new file mode 100644 index 0000000..46e16a1 --- /dev/null +++ b/apps/frontend/src/lib/format-price.ts @@ -0,0 +1,11 @@ +import type { SearchPriceSighting } from '../types/search' + +function formatSize(sighting: SearchPriceSighting) { + if (sighting.sizeMl != null) return `${Math.round(sighting.sizeMl)} ml` + + return sighting.size.toLowerCase().replaceAll('_', ' ') +} + +export function formatPrice(sighting: SearchPriceSighting) { + return `NOK ${sighting.price} · ${formatSize(sighting)}` +} diff --git a/apps/frontend/src/routes/index.tsx b/apps/frontend/src/routes/index.tsx index 7425db3..a9808bf 100644 --- a/apps/frontend/src/routes/index.tsx +++ b/apps/frontend/src/routes/index.tsx @@ -1,16 +1,21 @@ import { createFileRoute } from '@tanstack/react-router' +import { useState } from 'react' + import Map from '../components/Map' import VenueLoader from '#/components/ViewVenue' +import type { SearchResult } from '#/types/search' export const Route = createFileRoute('/')({ component: App }) function App() { + const [selected, setSelected] = useState(null) + return (
- +
- +
) } diff --git a/apps/frontend/src/types/search.ts b/apps/frontend/src/types/search.ts new file mode 100644 index 0000000..edea19f --- /dev/null +++ b/apps/frontend/src/types/search.ts @@ -0,0 +1,25 @@ +export interface SearchOpeningHours { + days: string[] + opening: string + closing: string +} + +export interface SearchPriceSighting { + price: number + size: string + sizeMl: number | null + Limitations: string[] + timeStart: string | null + timeEnd: string | null + timeSighted: string +} + +export interface SearchResult { + type: 'venue' | 'city' + name: string + lat: number + lon: number + address: string | null + openingHours: SearchOpeningHours[] | null + latestPriceSighting: SearchPriceSighting | null +}