Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions apps/backend/src/schema/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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({
Expand Down
1 change: 1 addition & 0 deletions apps/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions apps/frontend/public/harp.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions apps/frontend/public/harp_shadow.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
98 changes: 73 additions & 25 deletions apps/frontend/src/components/Map.tsx
Original file line number Diff line number Diff line change
@@ -1,40 +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',
iconSize: [46, 46],
shadowSize: [50, 50],
iconAnchor: [23, 23],
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<SearchResult | null>(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 (
<section id="map" className="relative">
<SearchBox onSelect={handleSelect} />
<MapContainer
center={DEFAULT_CENTER}
zoom={DEFAULT_ZOOM}
Expand All @@ -45,21 +74,40 @@ export default function Map({
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<FlyToResult result={selected} />
{selected && (
<Marker position={[selected.lat, selected.lon]}>
<FlyToResult coordinates={flyTo} />
{markers.map((curr) => (
<Marker
key={`${curr.type}-${curr.name}-${curr.lat}-${curr.lon}`}
icon={harpIcon}
position={[curr.lat, curr.lon]}
>
<Popup>
<strong>{selected.name}</strong>
{selected.address && (
<span className="block">{selected.address}</span>
)}
{selected.latestPriceSighting && (
<strong>{curr.name}</strong>
{curr.address && <span className="block">{curr.address}</span>}
{curr.latestPriceSighting && (
<span className="block">
{formatPrice(selected.latestPriceSighting)}
{formatPrice(curr.latestPriceSighting)}
</span>
)}
</Popup>
</Marker>
))}
{userLocation && (
<CircleMarker
center={[userLocation.lat, userLocation.lon]}
radius={8}
pathOptions={{
color: '#328f97',
fillColor: '#4fb8b2',
fillOpacity: 0.85,
}}
>
<Popup>
{isMockLocation
? `Mock location: ${MOCK_LOCATION_NAME}`
: 'Your location'}
</Popup>
</CircleMarker>
)}
</MapContainer>
</section>
Expand Down
30 changes: 30 additions & 0 deletions apps/frontend/src/components/MockLocationNotice.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<aside className="demo-alert rise-in mb-6">
<p className="island-kicker">Mock position</p>
<h2 className="mt-1 text-base font-extrabold">
We are showing a mock position instead of your real one
</h2>
<p className="mt-1 text-sm text-[var(--sea-ink-soft)]">
Browsers only share your location over HTTPS or on localhost, and this
site is served over plain HTTP. Pubs are therefore sorted by distance
from {MOCK_LOCATION_NAME} rather than from where you actually are.
</p>
<p className="mt-2 text-sm text-[var(--sea-ink-soft)]">
For the full experience, check out{' '}
<a href={REPOSITORY_URL} target="_blank" rel="noreferrer">
the repository
</a>{' '}
and run the website on localhost.
</p>
</aside>
)
}
146 changes: 146 additions & 0 deletions apps/frontend/src/components/NearbyVenues.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<>
<span className="flex items-baseline justify-between gap-3">
<span className="font-semibold">{venue.name}</span>
{venue.averageRating != null && (
<span
title={`Average rating ${venue.averageRating.toFixed(1)} out of 5 from ${
venue.reviewCount ?? 0
} ${(venue.reviewCount ?? 0) === 1 ? 'review' : 'reviews'}`}
className="inline-flex shrink-0 items-center gap-1 rounded-full border border-[var(--chip-line)] bg-[var(--chip-bg)] px-2 py-0.5 text-xs font-bold text-[var(--sea-ink)]"
>
<span aria-hidden="true" className="text-amber-500">
★
</span>
<span>{venue.averageRating.toFixed(1)}</span>
<span className="font-normal text-[var(--sea-ink-soft)]">
({venue.reviewCount ?? 0})
</span>
</span>
)}
</span>
{venue.address && (
<span className="mt-0.5 block text-xs text-[var(--sea-ink-soft)]">
{venue.address}
</span>
)}
{venue.openingHours && venue.openingHours.length > 0 && (
<span className="mt-0.5 block text-xs text-[var(--sea-ink-soft)]">
{formatOpeningHours(venue.openingHours)}
</span>
)}
{venue.latestPriceSighting && (
<span className="mt-0.5 block text-xs text-[var(--sea-ink-soft)]">
{formatPrice(venue.latestPriceSighting)}
</span>
)}
</>
)
}

export default function NearbyVenues({
venues,
hasLocation,
locating,
locationError,
isLoading,
isError,
onRefresh,
}: NearbyVenuesProps) {
return (
<section className="island-shell rise-in rounded-2xl p-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<p className="island-kicker">Nearby pubs</p>
<h2 className="mt-1 text-xl font-extrabold">Within 10 km</h2>
</div>
<button
type="button"
onClick={onRefresh}
disabled={locating}
className="rounded-full border border-[var(--chip-line)] bg-[var(--chip-bg)] px-3 py-1.5 text-sm font-semibold text-[var(--sea-ink)] transition hover:-translate-y-0.5 disabled:cursor-wait disabled:opacity-60 disabled:hover:translate-y-0"
>
{locating ? 'Finding location…' : 'Refresh location'}
</button>
</div>

{locationError && (
<p className="mt-3 text-sm text-[var(--sea-ink-soft)]">
{locationError}
</p>
)}

{!locationError && !hasLocation && (
<p className="mt-3 text-sm text-[var(--sea-ink-soft)]">
{locating
? 'Finding your location…'
: 'Allow location access to see pubs near you.'}
</p>
)}

{hasLocation && isError && (
<p className="mt-3 text-sm text-[var(--sea-ink-soft)]">
Nearby pubs are unavailable right now.
</p>
)}

{hasLocation && !isError && isLoading && venues.length === 0 && (
<p className="mt-3 text-sm text-[var(--sea-ink-soft)]">
Loading nearby pubs…
</p>
)}

{hasLocation &&
!isError &&
!isLoading &&
venues.length === 0 &&
!locationError && (
<p className="mt-3 text-sm text-[var(--sea-ink-soft)]">
No pubs within 10 km of your location.
</p>
)}

{hasLocation && venues.length > 0 && (
<ul className="mt-3">
{venues.map((venue) => (
<li key={venue.id}>
{venue.cityId ? (
<Link
to="/$cityId/venues/$venueId"
params={{ cityId: venue.cityId, venueId: venue.id }}
className={rowClassName}
>
<VenueRow venue={venue} />
</Link>
) : (
<div className={rowClassName}>
<VenueRow venue={venue} />
</div>
)}
</li>
))}
</ul>
)}
</section>
)
}
Loading