From 9e736f9cc7ec191b8c19e67227aa180a2efabab2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henry=20Gr=C3=A6sberg?= Date: Wed, 28 Oct 2026 00:31:04 +0100 Subject: [PATCH 1/4] Make map marker icon the guinnes harp --- apps/frontend/package.json | 1 + apps/frontend/public/harp.svg | 1 + apps/frontend/public/harp_shadow.svg | 1 + apps/frontend/src/components/Map.tsx | 13 ++++++++++++- pnpm-lock.yaml | 3 +++ 5 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 apps/frontend/public/harp.svg create mode 100644 apps/frontend/public/harp_shadow.svg diff --git a/apps/frontend/package.json b/apps/frontend/package.json index e97a6ce..4171bf1 100644 --- a/apps/frontend/package.json +++ b/apps/frontend/package.json @@ -21,6 +21,7 @@ "@tanstack/react-router-devtools": "latest", "@tanstack/react-router-ssr-query": "latest", "@tanstack/react-start": "latest", + "leaflet": "^1.9.4", "nitro": "3.0.260610-beta", "react": "^19.3.0", "react-dom": "^19.3.0", diff --git a/apps/frontend/public/harp.svg b/apps/frontend/public/harp.svg new file mode 100644 index 0000000..b03c7ae --- /dev/null +++ b/apps/frontend/public/harp.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/frontend/public/harp_shadow.svg b/apps/frontend/public/harp_shadow.svg new file mode 100644 index 0000000..1bc1a62 --- /dev/null +++ b/apps/frontend/public/harp_shadow.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/frontend/src/components/Map.tsx b/apps/frontend/src/components/Map.tsx index 42b14e0..b44d256 100644 --- a/apps/frontend/src/components/Map.tsx +++ b/apps/frontend/src/components/Map.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react' import { MapContainer, Marker, Popup, TileLayer, useMap } from 'react-leaflet' +import L from 'leaflet' import { formatPrice } from '../lib/format-price' import type { SearchResult } from '../types/search' @@ -20,6 +21,16 @@ function FlyToResult({ result }: { result: SearchResult | null }) { return null } +const harpIcon = new L.Icon({ + iconUrl: "harp.svg", + shadowUrl: "harp_shadow.svg", + iconSize: [46, 46], + shadowSize: [48, 48], + iconAnchor: [23, 23], + shadowAnchor: [24, 24], + popupAnchor: [0, -47.5], +}) + export default function Map({ onSelect, }: { @@ -47,7 +58,7 @@ export default function Map({ /> {selected && ( - + {selected.name} {selected.address && ( diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6d549c9..ed7c188 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -81,6 +81,9 @@ importers: '@tanstack/react-start': specifier: latest version: 1.169.4(esbuild@0.28.2)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(rolldown@1.2.13)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) + leaflet: + specifier: ^1.9.4 + version: 1.9.4 nitro: specifier: 3.0.260610-beta version: 3.0.260610-beta(@electric-sql/pglite@0.4.3)(chokidar@5.0.0)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(lru-cache@11.5.3)(mysql2@3.15.3)(vite@8.3.4(@types/node@22.20.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) From 62850f7115bdd551d8189d94bc3c30d16b76c679 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henry=20Gr=C3=A6sberg?= Date: Wed, 28 Oct 2026 00:41:32 +0100 Subject: [PATCH 2/4] Delete tanstack start demo routes --- apps/frontend/src/routeTree.gen.ts | 60 +------ apps/frontend/src/routes/about.tsx | 16 -- .../src/routes/demo/tanstack-query.tsx | 37 ---- apps/frontend/src/routes/demo/todos.tsx | 159 ------------------ 4 files changed, 3 insertions(+), 269 deletions(-) delete mode 100644 apps/frontend/src/routes/about.tsx delete mode 100644 apps/frontend/src/routes/demo/tanstack-query.tsx delete mode 100644 apps/frontend/src/routes/demo/todos.tsx diff --git a/apps/frontend/src/routeTree.gen.ts b/apps/frontend/src/routeTree.gen.ts index e0e641a..dceedff 100644 --- a/apps/frontend/src/routeTree.gen.ts +++ b/apps/frontend/src/routeTree.gen.ts @@ -10,63 +10,33 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as AboutRouteImport } from './routes/about' -import { Route as DemoTanstackQueryRouteImport } from './routes/demo/tanstack-query' -import { Route as DemoTodosRouteImport } from './routes/demo/todos' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const DemoTanstackQueryRoute = DemoTanstackQueryRouteImport.update({ - id: '/demo/tanstack-query', - path: '/demo/tanstack-query', - getParentRoute: () => rootRouteImport, -} as any) -const DemoTodosRoute = DemoTodosRouteImport.update({ - id: '/demo/todos', - path: '/demo/todos', - getParentRoute: () => rootRouteImport, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/about': typeof AboutRoute - '/demo/tanstack-query': typeof DemoTanstackQueryRoute - '/demo/todos': typeof DemoTodosRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/about': typeof AboutRoute - '/demo/tanstack-query': typeof DemoTanstackQueryRoute - '/demo/todos': typeof DemoTodosRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/about': typeof AboutRoute - '/demo/tanstack-query': typeof DemoTanstackQueryRoute - '/demo/todos': typeof DemoTodosRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/about' | '/demo/tanstack-query' | '/demo/todos' + fullPaths: '/' fileRoutesByTo: FileRoutesByTo - to: '/' | '/about' | '/demo/tanstack-query' | '/demo/todos' - id: '__root__' | '/' | '/about' | '/demo/tanstack-query' | '/demo/todos' + to: '/' + id: '__root__' | '/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute - DemoTanstackQueryRoute: typeof DemoTanstackQueryRoute - DemoTodosRoute: typeof DemoTodosRoute } declare module '@tanstack/react-router' { @@ -78,35 +48,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/demo/tanstack-query': { - id: '/demo/tanstack-query' - path: '/demo/tanstack-query' - fullPath: '/demo/tanstack-query' - preLoaderRoute: typeof DemoTanstackQueryRouteImport - parentRoute: typeof rootRouteImport - } - '/demo/todos': { - id: '/demo/todos' - path: '/demo/todos' - fullPath: '/demo/todos' - preLoaderRoute: typeof DemoTodosRouteImport - parentRoute: typeof rootRouteImport - } } } const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, - AboutRoute: AboutRoute, - DemoTanstackQueryRoute: DemoTanstackQueryRoute, - DemoTodosRoute: DemoTodosRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/frontend/src/routes/about.tsx b/apps/frontend/src/routes/about.tsx deleted file mode 100644 index 8659896..0000000 --- a/apps/frontend/src/routes/about.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import Map from '../components/Map' -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/about')({ - component: About, -}) - -function About() { - return ( -
-
- -
-
- ) -} diff --git a/apps/frontend/src/routes/demo/tanstack-query.tsx b/apps/frontend/src/routes/demo/tanstack-query.tsx deleted file mode 100644 index 30d4a40..0000000 --- a/apps/frontend/src/routes/demo/tanstack-query.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { useQuery } from '@tanstack/react-query' - -export const Route = createFileRoute('/demo/tanstack-query')({ - component: TanStackQueryDemo, -}) - -function TanStackQueryDemo() { - const { data } = useQuery({ - queryKey: ['todos'], - queryFn: () => - Promise.resolve([ - { id: 1, name: 'Alice' }, - { id: 2, name: 'Bob' }, - { id: 3, name: 'Charlie' }, - ]), - initialData: [], - }) - - return ( -
-
-

TanStack Query

-

- TanStack Query Simple Promise Handling -

-
    - {data.map((todo) => ( -
  • - {todo.name} -
  • - ))} -
-
-
- ) -} diff --git a/apps/frontend/src/routes/demo/todos.tsx b/apps/frontend/src/routes/demo/todos.tsx deleted file mode 100644 index 695468d..0000000 --- a/apps/frontend/src/routes/demo/todos.tsx +++ /dev/null @@ -1,159 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' - -import { graphqlFetch } from '#/graphql/client' - -interface Todo { - id: number - title: string - createdAt: string -} - -const GET_TODOS_QUERY = ` - query GetTodos { - todos { - id - title - createdAt - } - } -` - -const CREATE_TODO_MUTATION = ` - mutation CreateTodo($title: String!) { - createTodo(title: $title) { - id - title - } - } -` - -export const Route = createFileRoute('/demo/todos')({ - component: DemoTodos, -}) - -function DemoTodos() { - const queryClient = useQueryClient() - - const { data, isPending, isError, error } = useQuery({ - queryKey: ['todos'], - queryFn: () => graphqlFetch<{ todos: Todo[] }>(GET_TODOS_QUERY), - }) - - const createTodo = useMutation({ - mutationFn: (title: string) => - graphqlFetch<{ createTodo: Todo }>(CREATE_TODO_MUTATION, { title }), - onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), - }) - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault() - const form = e.currentTarget - const title = new FormData(form).get('title') - - if (typeof title !== 'string' || !title) return - - try { - await createTodo.mutateAsync(title) - form.reset() - } catch (mutationError) { - console.error('Failed to create todo:', mutationError) - } - } - - const todos = data?.todos ?? [] - - return ( -
-
-
- - Prisma Logo - -
-

Database

-

Todos Demo

-
-
- -

Todos

- - {isPending && ( -

Loading todos...

- )} - - {isError && ( -

- Failed to load todos: {error.message}. Is the GraphQL backend - running on http://localhost:3001? -

- )} - - {!isPending && !isError && ( -
    - {todos.map((todo) => ( -
  • -
    - {todo.title} - #{todo.id} -
    -
  • - ))} - {todos.length === 0 && ( -
  • - No todos yet. Create one below! -
  • - )} -
- )} - -
- - -
- -
-

- Powered by GraphQL + Apollo Server -

-

- The frontend queries the GraphQL backend on port 3001, which uses - Prisma to talk to PostgreSQL -

-
-

Setup Instructions:

-
    -
  1. - Configure DATABASE_URL in{' '} - packages/db/.env and apps/backend/.env -
  2. -
  3. - Run: pnpm install -
  4. -
  5. - Run: pnpm db:generate && pnpm db:push -
  6. -
  7. - Optional: pnpm db:seed -
  8. -
  9. - Run: pnpm dev (starts frontend and backend - together) -
  10. -
-
-
-
-
- ) -} From 2c1467b79861494964324057397dfa14588922dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henry=20Gr=C3=A6sberg?= Date: Thu, 29 Oct 2026 14:23:48 +0100 Subject: [PATCH 3/4] Add mock location and nearby pub details --- apps/backend/src/schema/schema.ts | 19 ++ apps/frontend/public/harp_shadow.svg | 2 +- apps/frontend/src/components/Map.tsx | 95 ++++++--- .../src/components/MockLocationNotice.tsx | 30 +++ apps/frontend/src/components/NearbyVenues.tsx | 146 +++++++++++++ apps/frontend/src/components/SearchBox.tsx | 21 +- apps/frontend/src/components/ViewVenue.tsx | 34 +-- apps/frontend/src/lib/format-opening-hours.ts | 20 ++ apps/frontend/src/lib/location.ts | 186 +++++++++++++++++ apps/frontend/src/routes/index.tsx | 195 +++++++++++++++++- apps/frontend/src/types/venue.ts | 12 ++ 11 files changed, 691 insertions(+), 69 deletions(-) create mode 100644 apps/frontend/src/components/MockLocationNotice.tsx create mode 100644 apps/frontend/src/components/NearbyVenues.tsx create mode 100644 apps/frontend/src/lib/location.ts diff --git a/apps/backend/src/schema/schema.ts b/apps/backend/src/schema/schema.ts index 8708bd6..3224e61 100644 --- a/apps/backend/src/schema/schema.ts +++ b/apps/backend/src/schema/schema.ts @@ -120,6 +120,14 @@ builder.queryType({ args: { lat: t.arg.float(), lon: t.arg.float(), + limit: t.arg.int({ + description: + 'Return at most this many venues. Omit to return every venue.', + }), + maxDistanceKm: t.arg.float({ + description: + 'Only return venues within this distance in kilometres of lat/lon.', + }), }, resolve: async (query, _parent, args) => { if (args.lat == null || args.lon == null) { @@ -130,9 +138,20 @@ builder.queryType({ return venues } + // haversine_distance returns metres. A null radius/limit means "no + // restriction"; Postgres treats LIMIT NULL as no limit. + const maxDistanceMeters = + args.maxDistanceKm == null + ? null + : Math.max(0, args.maxDistanceKm) * 1000 + const limit = args.limit == null ? null : Math.max(0, args.limit) + const nearest = await prisma.$queryRaw<{ id: string }[]>` SELECT id FROM venue + WHERE ${maxDistanceMeters}::double precision IS NULL + OR haversine_distance(${args.lat}, ${args.lon}, lat, lon) <= ${maxDistanceMeters}::double precision ORDER BY haversine_distance(${args.lat}, ${args.lon}, lat, lon), name + LIMIT ${limit}::integer ` const venues = await prisma.venue.findMany({ diff --git a/apps/frontend/public/harp_shadow.svg b/apps/frontend/public/harp_shadow.svg index 1bc1a62..bd5af57 100644 --- a/apps/frontend/public/harp_shadow.svg +++ b/apps/frontend/public/harp_shadow.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/apps/frontend/src/components/Map.tsx b/apps/frontend/src/components/Map.tsx index b44d256..ab28da3 100644 --- a/apps/frontend/src/components/Map.tsx +++ b/apps/frontend/src/components/Map.tsx @@ -1,51 +1,69 @@ -import { useEffect, useState } from 'react' -import { MapContainer, Marker, Popup, TileLayer, useMap } from 'react-leaflet' +'use client' + +import { useEffect } from 'react' +import { + CircleMarker, + MapContainer, + Marker, + Popup, + TileLayer, + useMap, +} from 'react-leaflet' import L from 'leaflet' import { formatPrice } from '../lib/format-price' +import { MOCK_LOCATION_NAME } from '../lib/location' +import type { Coordinates } from '../lib/location' 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 }) { +function FlyToResult({ coordinates }: { coordinates: number[] | undefined }) { const map = useMap() useEffect(() => { - if (result) { - map.flyTo([result.lat, result.lon], result.type === 'city' ? 12 : 16) + if (coordinates && coordinates.length == 2) { + map.flyTo([coordinates[0], coordinates[1]], 12) } - }, [result, map]) + }, [coordinates, map]) return null } const harpIcon = new L.Icon({ - iconUrl: "harp.svg", - shadowUrl: "harp_shadow.svg", + iconUrl: 'harp.svg', + shadowUrl: 'harp_shadow.svg', iconSize: [46, 46], - shadowSize: [48, 48], + shadowSize: [50, 50], iconAnchor: [23, 23], - shadowAnchor: [24, 24], + shadowAnchor: [25, 25], popupAnchor: [0, -47.5], }) export default function Map({ - onSelect, + nearby = [], + userLocation, + flyTo, + isMockLocation = false, }: { - onSelect?: (result: SearchResult) => void + nearby?: SearchResult[] + userLocation?: Coordinates | null + flyTo?: number[] + isMockLocation?: boolean }) { - const [selected, setSelected] = useState(null) - - function handleSelect(result: SearchResult) { - setSelected(result) - onSelect?.(result) - } + const markers = nearby.filter( + (venue, index, all) => + all.findIndex( + (other) => + other.name === venue.name && + other.lat === venue.lat && + other.lon === venue.lon, + ) === index, + ) return (
- - - {selected && ( - + + {markers.map((curr) => ( + - {selected.name} - {selected.address && ( - {selected.address} - )} - {selected.latestPriceSighting && ( + {curr.name} + {curr.address && {curr.address}} + {curr.latestPriceSighting && ( - {formatPrice(selected.latestPriceSighting)} + {formatPrice(curr.latestPriceSighting)} )} + ))} + {userLocation && ( + + + {isMockLocation + ? `Mock location: ${MOCK_LOCATION_NAME}` + : 'Your location'} + + )}
diff --git a/apps/frontend/src/components/MockLocationNotice.tsx b/apps/frontend/src/components/MockLocationNotice.tsx new file mode 100644 index 0000000..5ee36fc --- /dev/null +++ b/apps/frontend/src/components/MockLocationNotice.tsx @@ -0,0 +1,30 @@ +import { MOCK_LOCATION_NAME } from '#/lib/location' + +const REPOSITORY_URL = 'https://git.ntnu.no/IT2810-H26/T09-Project-2' + +/** + * Shown when the app fell back to MOCK_LOCATION because the browser refused to + * share a real position over a non-secure origin. + */ +export default function MockLocationNotice() { + return ( + + ) +} diff --git a/apps/frontend/src/components/NearbyVenues.tsx b/apps/frontend/src/components/NearbyVenues.tsx new file mode 100644 index 0000000..43642f7 --- /dev/null +++ b/apps/frontend/src/components/NearbyVenues.tsx @@ -0,0 +1,146 @@ +import { Link } from '@tanstack/react-router' + +import { formatOpeningHours } from '#/lib/format-opening-hours' +import { formatPrice } from '#/lib/format-price' +import type { SearchResult } from '#/types/search' + +interface NearbyVenuesProps { + venues: SearchResult[] + hasLocation: boolean + locating: boolean + locationError: string | null + isLoading: boolean + isError: boolean + onRefresh: () => void +} + +const rowClassName = + 'block w-full border-t border-[var(--line)] px-1 py-3 text-left text-sm text-[var(--sea-ink)] transition hover:bg-[var(--chip-bg)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--lagoon-deep)' + +function VenueRow({ venue }: { venue: SearchResult }) { + return ( + <> + + {venue.name} + {venue.averageRating != null && ( + + + {venue.averageRating.toFixed(1)} + + ({venue.reviewCount ?? 0}) + + + )} + + {venue.address && ( + + {venue.address} + + )} + {venue.openingHours && venue.openingHours.length > 0 && ( + + {formatOpeningHours(venue.openingHours)} + + )} + {venue.latestPriceSighting && ( + + {formatPrice(venue.latestPriceSighting)} + + )} + + ) +} + +export default function NearbyVenues({ + venues, + hasLocation, + locating, + locationError, + isLoading, + isError, + onRefresh, +}: NearbyVenuesProps) { + return ( +
+
+
+

Nearby pubs

+

Within 10 km

+
+ +
+ + {locationError && ( +

+ {locationError} +

+ )} + + {!locationError && !hasLocation && ( +

+ {locating + ? 'Finding your location…' + : 'Allow location access to see pubs near you.'} +

+ )} + + {hasLocation && isError && ( +

+ Nearby pubs are unavailable right now. +

+ )} + + {hasLocation && !isError && isLoading && venues.length === 0 && ( +

+ Loading nearby pubs… +

+ )} + + {hasLocation && + !isError && + !isLoading && + venues.length === 0 && + !locationError && ( +

+ No pubs within 10 km of your location. +

+ )} + + {hasLocation && venues.length > 0 && ( +
    + {venues.map((venue) => ( +
  • + {venue.cityId ? ( + + + + ) : ( +
    + +
    + )} +
  • + ))} +
+ )} +
+ ) +} diff --git a/apps/frontend/src/components/SearchBox.tsx b/apps/frontend/src/components/SearchBox.tsx index a5025da..3cb800b 100644 --- a/apps/frontend/src/components/SearchBox.tsx +++ b/apps/frontend/src/components/SearchBox.tsx @@ -1,4 +1,5 @@ import { keepPreviousData, useQuery } from '@tanstack/react-query' +import { useNavigate } from '@tanstack/react-router' import { useEffect, useId, useMemo, useState } from 'react' import type { FormEvent, KeyboardEvent } from 'react' @@ -65,11 +66,8 @@ function SearchIcon() { ) } -export function SearchBox({ - onSelect, -}: { - onSelect: (result: SearchResult) => void -}) { +export function SearchBox() { + const navigate = useNavigate() const inputId = useId() const listId = useId() @@ -128,7 +126,18 @@ export function SearchBox({ setOpen(false) setShowAll(false) setActiveIndex(-1) - onSelect(result) + + if (result.type === 'city') { + void navigate({ + to: '/$cityId/venues', + params: { cityId: result.id }, + }) + } else if (result.cityId) { + void navigate({ + to: '/$cityId/venues/$venueId', + params: { cityId: result.cityId, venueId: result.id }, + }) + } } function handleSubmit(event: FormEvent) { diff --git a/apps/frontend/src/components/ViewVenue.tsx b/apps/frontend/src/components/ViewVenue.tsx index d5d0382..0d3ff8d 100644 --- a/apps/frontend/src/components/ViewVenue.tsx +++ b/apps/frontend/src/components/ViewVenue.tsx @@ -1,13 +1,10 @@ -import { Link } from '@tanstack/react-router' - -import { formatOpeningDays } from '#/lib/format-opening-hours' +import { + formatOpeningDays, + formatOpeningTime, +} from '#/lib/format-opening-hours' import { formatPrice } from '#/lib/format-price' import type { SearchResult } from '#/types/search' -function formatTime(iso: string) { - return iso.slice(11, 16) -} - export function ViewVenue({ venue, kicker = 'Selected pub', @@ -60,8 +57,8 @@ export function ViewVenue({ {formatOpeningDays(openingHours.days)} - {formatTime(openingHours.opening)} -{' '} - {formatTime(openingHours.closing)} + {formatOpeningTime(openingHours.opening)} -{' '} + {formatOpeningTime(openingHours.closing)} ))} @@ -74,22 +71,3 @@ export function ViewVenue({ ) } - -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 - - const card = - - if (!venue.cityId) return card - - return ( - - {card} - - ) -} diff --git a/apps/frontend/src/lib/format-opening-hours.ts b/apps/frontend/src/lib/format-opening-hours.ts index d3e9739..32aca67 100644 --- a/apps/frontend/src/lib/format-opening-hours.ts +++ b/apps/frontend/src/lib/format-opening-hours.ts @@ -38,6 +38,26 @@ function formatRun(run: Day[]): string { // consecutive days into ranges and naming whole weekdays/weekends. // Examples: MON–FRI → "Weekdays", SAT–SUN → "Weekends", // MON–WED → "Monday–Wednesday", MON/WED/FRI → "Monday, Wednesday and Friday". +export function formatOpeningTime(iso: string): string { + return iso.slice(11, 16) +} + +export interface OpeningHoursEntry { + days: string[] + opening: string + closing: string +} + +/** Compact one-line summary, e.g. "Weekdays 14:00–02:00 · Weekends 12:00–03:00". */ +export function formatOpeningHours(entries: OpeningHoursEntry[]): string { + return entries + .map( + (entry) => + `${formatOpeningDays(entry.days)} ${formatOpeningTime(entry.opening)}–${formatOpeningTime(entry.closing)}`, + ) + .join(' · ') +} + export function formatOpeningDays(days: string[]): string { const sorted = [...new Set(days.map((day) => day.toUpperCase()))] .filter(isDay) diff --git a/apps/frontend/src/lib/location.ts b/apps/frontend/src/lib/location.ts new file mode 100644 index 0000000..8cfd0f6 --- /dev/null +++ b/apps/frontend/src/lib/location.ts @@ -0,0 +1,186 @@ +export interface Coordinates { + lat: number + lon: number +} + +const LOCATION_STORAGE_KEY = 'g-spotter:location' +const LOCATION_TTL_MS = 24 * 60 * 60 * 1000 + +/** + * Fallback position used when the browser cannot share the user's real one. + * Geolocation only works in secure contexts, and the deployed site is served + * over plain HTTP on the NTNU network, so it always falls back to this. + * NTNU Realfagsbygget, Gløshaugen, Trondheim. + */ +export const MOCK_LOCATION: Coordinates = { + lat: 63.415458, + lon: 10.406021, +} + +export const MOCK_LOCATION_NAME = 'NTNU Realfagsbygget' + +/** + * True when the page runs in a non-secure context, i.e. plain HTTP on a host + * other than localhost. `window.isSecureContext` is true for HTTPS as well as + * for localhost and 127.0.0.1, which are exactly the origins that allow + * geolocation. + */ +export function usesMockLocation(): boolean { + if (typeof window === 'undefined') return false + + return !window.isSecureContext +} + +interface StoredLocation extends Coordinates { + savedAt: number +} + +export type LocationErrorCode = + 'denied' | 'unavailable' | 'timeout' | 'unsupported' + +export class LocationError extends Error { + code: LocationErrorCode + + constructor(code: LocationErrorCode, message: string) { + super(message) + this.name = 'LocationError' + this.code = code + } +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) +} + +function clearStoredLocation() { + try { + window.localStorage.removeItem(LOCATION_STORAGE_KEY) + } catch { + // Ignore storage failures (for example in private browsing modes). + } +} + +/** + * Reads the cached coordinates if they are younger than one day. + * Expired or malformed entries are removed so the next visit asks again. + */ +export function readStoredLocation(now = Date.now()): Coordinates | null { + if (typeof window === 'undefined') return null + + let raw: string | null + try { + raw = window.localStorage.getItem(LOCATION_STORAGE_KEY) + } catch { + return null + } + + if (!raw) return null + + try { + const stored = JSON.parse(raw) as Partial + + if ( + !isFiniteNumber(stored.lat) || + !isFiniteNumber(stored.lon) || + !isFiniteNumber(stored.savedAt) || + now - stored.savedAt >= LOCATION_TTL_MS + ) { + clearStoredLocation() + return null + } + + return { lat: stored.lat, lon: stored.lon } + } catch { + clearStoredLocation() + return null + } +} + +export function writeStoredLocation(coordinates: Coordinates) { + if (typeof window === 'undefined') return + + const stored: StoredLocation = { ...coordinates, savedAt: Date.now() } + + try { + window.localStorage.setItem(LOCATION_STORAGE_KEY, JSON.stringify(stored)) + } catch { + // The app still works without a cache, it will just ask again next reload. + } +} + +export function requestBrowserLocation(): Promise { + return new Promise((resolve, reject) => { + // Browsers only expose geolocation on secure origins (HTTPS or localhost). + if (usesMockLocation()) { + reject( + new LocationError( + 'unsupported', + 'Location needs a secure (HTTPS) connection to work.', + ), + ) + return + } + + // Some embedded browsers and older webviews do not expose geolocation. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (typeof navigator === 'undefined' || !navigator.geolocation) { + reject( + new LocationError( + 'unsupported', + 'Your browser does not support location services.', + ), + ) + return + } + + navigator.geolocation.getCurrentPosition( + (position) => + resolve({ + lat: position.coords.latitude, + lon: position.coords.longitude, + }), + (error) => { + if (error.code === error.PERMISSION_DENIED) { + reject( + new LocationError( + 'denied', + 'Location permission was denied. Allow it to see pubs near you.', + ), + ) + } else if (error.code === error.TIMEOUT) { + reject( + new LocationError( + 'timeout', + 'Finding your location took too long. Try again.', + ), + ) + } else { + reject( + new LocationError( + 'unavailable', + 'Your location is unavailable right now. Try again.', + ), + ) + } + }, + { + enableHighAccuracy: true, + timeout: 10_000, + maximumAge: 0, + }, + ) + }) +} + +/** Requests a fresh position and stores it for the next 24 hours. */ +export async function requestAndStoreLocation(): Promise { + const coordinates = await requestBrowserLocation() + writeStoredLocation(coordinates) + return coordinates +} + +export function describeLocationError(error: unknown): string { + if (error instanceof LocationError) return error.message + + return 'Could not get your location.' +} diff --git a/apps/frontend/src/routes/index.tsx b/apps/frontend/src/routes/index.tsx index a9808bf..6754b0d 100644 --- a/apps/frontend/src/routes/index.tsx +++ b/apps/frontend/src/routes/index.tsx @@ -1,21 +1,206 @@ +import { useQuery } from '@tanstack/react-query' import { createFileRoute } from '@tanstack/react-router' -import { useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import Map from '../components/Map' -import VenueLoader from '#/components/ViewVenue' +import MockLocationNotice from '#/components/MockLocationNotice' +import NearbyVenues from '#/components/NearbyVenues' import type { SearchResult } from '#/types/search' +import type { NearbyVenue, VenuePriceSighting } from '#/types/venue' +import SearchBox from '#/components/SearchBox' +import { graphqlFetch } from '#/graphql/client' +import { + MOCK_LOCATION, + describeLocationError, + readStoredLocation, + requestAndStoreLocation, + usesMockLocation, +} from '#/lib/location' +import type { Coordinates } from '#/lib/location' export const Route = createFileRoute('/')({ component: App }) +const NEARBY_LIMIT = 5 +const NEARBY_MAX_DISTANCE_KM = 10 + +const NEARBY_QUERY = ` + query NearbyVenues( + $lat: Float! + $lon: Float! + $limit: Int! + $maxDistanceKm: Float! + ) { + venue( + lat: $lat + lon: $lon + limit: $limit + maxDistanceKm: $maxDistanceKm + ) { + id + name + address + lat + lon + city { + id + } + openingHours { + days + opening + closing + } + pricesSighted { + price + size + sizeMl + Limitations + timeStart + timeEnd + timeSighted + } + reviews { + rating + } + } + } +` + +function averageRating(reviews: { rating: number }[]) { + if (reviews.length === 0) return null + + return ( + reviews.reduce((total, review) => total + review.rating, 0) / reviews.length + ) +} + +function latestPriceSighting(sightings: VenuePriceSighting[]) { + return sightings.reduce((latest, sighting) => { + if ( + latest === null || + new Date(sighting.timeSighted) > new Date(latest.timeSighted) + ) { + return sighting + } + + return latest + }, null) +} + +function toSearchResult(venue: NearbyVenue): SearchResult { + return { + id: venue.id, + cityId: venue.city.id, + type: 'venue', + name: venue.name, + lat: venue.lat, + lon: venue.lon, + address: venue.address, + openingHours: venue.openingHours, + latestPriceSighting: latestPriceSighting(venue.pricesSighted), + averageRating: averageRating(venue.reviews), + reviewCount: venue.reviews.length, + } +} + function App() { - const [selected, setSelected] = useState(null) + const [coordinates, setCoordinates] = useState(null) + const [locating, setLocating] = useState(true) + const [locationError, setLocationError] = useState(null) + const [usingMockLocation, setUsingMockLocation] = useState(false) + const initialized = useRef(false) + + const refreshLocation = useCallback(async () => { + setLocationError(null) + + // Browsers block geolocation outside secure contexts, so on plain HTTP the + // only option is a fixed, clearly announced mock position. + if (usesMockLocation()) { + setUsingMockLocation(true) + setCoordinates(MOCK_LOCATION) + setLocating(false) + return + } + + setLocating(true) + + try { + setCoordinates(await requestAndStoreLocation()) + } catch (error) { + setLocationError(describeLocationError(error)) + } finally { + setLocating(false) + } + }, []) + + // Reuse the location from the last 24 hours, otherwise ask the browser once. + useEffect(() => { + if (initialized.current) return + initialized.current = true + + if (usesMockLocation()) { + void refreshLocation() + return + } + + const stored = readStoredLocation() + + if (stored) { + setCoordinates(stored) + setLocating(false) + return + } + + void refreshLocation() + }, [refreshLocation]) + + const { data, isFetching, isError } = useQuery({ + queryKey: ['nearbyVenues', coordinates?.lat, coordinates?.lon], + queryFn: () => + graphqlFetch<{ venue: NearbyVenue[] }>(NEARBY_QUERY, { + lat: coordinates!.lat, + lon: coordinates!.lon, + limit: NEARBY_LIMIT, + maxDistanceKm: NEARBY_MAX_DISTANCE_KM, + }), + enabled: coordinates != null, + staleTime: 5 * 60 * 1000, + retry: 1, + }) + + const nearbyVenues = useMemo( + () => (data?.venue ?? []).map(toSearchResult), + [data], + ) + + const flyTo = useMemo(() => { + if (coordinates) return [coordinates.lat, coordinates.lon] + + return undefined + }, [coordinates]) return (
+ {usingMockLocation && }
- + +
- +
+ +
) } diff --git a/apps/frontend/src/types/venue.ts b/apps/frontend/src/types/venue.ts index 77b3679..155e1e5 100644 --- a/apps/frontend/src/types/venue.ts +++ b/apps/frontend/src/types/venue.ts @@ -40,3 +40,15 @@ export interface venue { pricesSighted?: VenuePriceSighting[] reviews: VenueReview[] } + +export interface NearbyVenue { + id: string + name: string + address: string + lat: number + lon: number + city: { id: string } + openingHours: VenueOpeningHours[] + pricesSighted: VenuePriceSighting[] + reviews: { rating: number }[] +} From 162c16767e0a5604c18844669c4c512eb28fb4d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henry=20Gr=C3=A6sberg?= Date: Thu, 29 Oct 2026 14:28:31 +0100 Subject: [PATCH 4/4] Add disclaimer about geolocation not working on http sites to readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 189d0d1..5cec5bb 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ ### Site deployed to [http://it2810-09.idi.ntnu.no/project2](http://it2810-09.idi.ntnu.no/project2), backend deployed to [http://it2810-09.idi.ntnu.no:3001](http://it2810-09.idi.ntnu.no:3001) +> #### !NB: We use location services in our app to use the users location to find nearby pubs. The JS geolocation API is blocked on most browsers if the site is not encrypted (https) or a loopback (localhost), so to see the full capabilities of our site, please clone the repo and check out the site on `localhost:3000/project2` + Our inital spec, written for the first deliverable, and what we are basing the development on, is outlined in [./docs/inital-plan.md](./docs/initial-plan.md) ## Index