+ {/* The map fades in on top of the poster rather than the poster fading
+ out, so the poster stays painted and remains the LCP element. */}
+
+
+
+ {ready && (
+
+
+
+
+
+ )}
+
+ )
+}
diff --git a/apps/frontend/src/components/ClientVenueMap.tsx b/apps/frontend/src/components/ClientVenueMap.tsx
new file mode 100644
index 0000000..9c3ba4f
--- /dev/null
+++ b/apps/frontend/src/components/ClientVenueMap.tsx
@@ -0,0 +1,52 @@
+import { lazy, Suspense, useEffect, useState } from 'react'
+import type { ComponentProps } from 'react'
+
+import mapPlaceholder from '#/assets/map-placeholder.svg'
+import type VenueMapComponent from './VenueMap'
+
+const venueMapModulePromise = import.meta.env.SSR ? null : import('./VenueMap')
+const LazyVenueMap = venueMapModulePromise
+ ? lazy(() => venueMapModulePromise)
+ : null
+
+type VenueMapProps = ComponentProps
+
+/**
+ * A neutral map skeleton is rendered on the server so this block is painted
+ * immediately instead of waiting for Leaflet and a handful of tiles: the tiles
+ * arrive seconds later and would otherwise win the LCP race on this page. The
+ * live map fades in on top and the skeleton stays painted underneath, which
+ * keeps it a valid LCP candidate.
+ */
+export default function ClientVenueMap(props: VenueMapProps) {
+ const [mounted, setMounted] = useState(false)
+
+ useEffect(() => {
+ setMounted(true)
+ }, [])
+
+ const ready = mounted && LazyVenueMap != null
+
+ return (
+
+
+
+
+ {ready && (
+
+
+
+
+
+ )}
+
+ )
+}
diff --git a/apps/frontend/src/components/Devtools.tsx b/apps/frontend/src/components/Devtools.tsx
new file mode 100644
index 0000000..5060b81
--- /dev/null
+++ b/apps/frontend/src/components/Devtools.tsx
@@ -0,0 +1,26 @@
+import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
+import { TanStackDevtools } from '@tanstack/react-devtools'
+
+import TanStackQueryDevtools from '../integrations/tanstack-query/devtools'
+
+/**
+ * Developer tools are loaded from a separate chunk that is only requested in
+ * development. Keeping them out of the production bundle saves a lot of
+ * JavaScript that would otherwise never run.
+ */
+export default function Devtools() {
+ return (
+ ,
+ },
+ TanStackQueryDevtools,
+ ]}
+ />
+ )
+}
diff --git a/apps/frontend/src/components/Header.tsx b/apps/frontend/src/components/Header.tsx
index 64fa22d..20f12f8 100644
--- a/apps/frontend/src/components/Header.tsx
+++ b/apps/frontend/src/components/Header.tsx
@@ -3,18 +3,19 @@ import ThemeToggle from './ThemeToggle'
export default function Header() {
return (
-
)
diff --git a/apps/frontend/src/components/Map.tsx b/apps/frontend/src/components/Map.tsx
index 16daadf..00f526a 100644
--- a/apps/frontend/src/components/Map.tsx
+++ b/apps/frontend/src/components/Map.tsx
@@ -9,11 +9,14 @@ import {
Tooltip,
useMap,
} from 'react-leaflet'
+import MarkerClusterGroup from 'react-leaflet-cluster'
import L from 'leaflet'
+import 'leaflet/dist/leaflet.css'
import { useNavigate } from '@tanstack/react-router'
import { formatPrice } from '../lib/format-price'
-import { assetUrl } from '#/lib/asset-url'
+import harpIconUrl from '#/assets/harp.svg?url'
+import harpShadowUrl from '#/assets/harp_shadow.svg?url'
import { MOCK_LOCATION_NAME } from '../lib/location'
import type { Coordinates } from '../lib/location'
import type { SearchResult } from '../types/search'
@@ -21,6 +24,11 @@ import type { SearchResult } from '../types/search'
const DEFAULT_CENTER: [number, number] = [63.4305, 10.3951]
const DEFAULT_ZOOM = 15
+// Using the single `tile` host (instead of the a/b/c subdomains) means the
+// browser only needs one connection, and preconnecting to it in the document
+// head pays off for every tile request.
+const TILE_URL = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
+
function FlyToResult({ coordinates }: { coordinates: number[] | undefined }) {
const map = useMap()
@@ -34,8 +42,8 @@ function FlyToResult({ coordinates }: { coordinates: number[] | undefined }) {
}
const harpIcon = new L.Icon({
- iconUrl: assetUrl('harp.svg'),
- shadowUrl: assetUrl('harp_shadow.svg'),
+ iconUrl: harpIconUrl,
+ shadowUrl: harpShadowUrl,
iconSize: [46, 46],
shadowSize: [50, 50],
iconAnchor: [23, 23],
@@ -43,18 +51,45 @@ const harpIcon = new L.Icon({
popupAnchor: [0, -25],
})
+/**
+ * Overlapping pins are merged into a single, larger target. This keeps the map
+ * usable on touch screens: without clustering the pins on top of each other
+ * cannot be tapped individually (WCAG 2.2 target size).
+ */
+function createClusterIcon(cluster: L.MarkerCluster) {
+ const count = cluster.getChildCount()
+
+ return L.divIcon({
+ html: `${count}${count} ${
+ count === 1 ? 'pub' : 'pubs'
+ }, zoom in to see them`,
+ className: 'gspotter-cluster',
+ iconSize: L.point(44, 44, true),
+ iconAnchor: [22, 22],
+ })
+}
+
+export interface MapProps {
+ nearby?: SearchResult[]
+ userLocation?: Coordinates | null
+ flyTo?: number[]
+ isMockLocation?: boolean
+}
+
export default function Map({
nearby = [],
userLocation,
flyTo,
isMockLocation = false,
-}: {
- nearby?: SearchResult[]
- userLocation?: Coordinates | null
- flyTo?: number[]
- isMockLocation?: boolean
-}) {
+}: MapProps) {
const navigate = useNavigate()
+ // Start at the user's position when we already know it. Otherwise Leaflet
+ // first downloads tiles for the default view and immediately replaces them
+ // after flying to the user, wasting both time and bandwidth.
+ const initialCenter: [number, number] = userLocation
+ ? [userLocation.lat, userLocation.lon]
+ : DEFAULT_CENTER
+ const initialZoom = userLocation ? 12 : DEFAULT_ZOOM
const markers = nearby.filter(
(venue, index, all) =>
all.findIndex(
@@ -66,45 +101,54 @@ export default function Map({
)
return (
-
+
- {markers.map((curr) => (
- {
- if (curr.cityId) {
- void navigate({
- to: '/$cityId/venues/$venueId',
- params: { cityId: curr.cityId, venueId: curr.id },
- })
- }
- },
- }}
- >
-
- {curr.name}
- {curr.address && {curr.address}}
- {curr.latestPriceSighting && (
-
- {formatPrice(curr.latestPriceSighting)}
-
- )}
-
-
- ))}
+
+ {markers.map((curr) => (
+ {
+ if (curr.cityId) {
+ void navigate({
+ to: '/$cityId/venues/$venueId',
+ params: { cityId: curr.cityId, venueId: curr.id },
+ })
+ }
+ },
+ }}
+ >
+
+ {curr.name}
+ {curr.address && {curr.address}}
+ {curr.latestPriceSighting && (
+
+ {formatPrice(curr.latestPriceSighting)}
+
+ )}
+
+
+ ))}
+
{userLocation && (
(see __root.tsx and the .mock-location-notice rule in styles.css).
*/
export default function MockLocationNotice() {
return (
-
)
}
diff --git a/apps/frontend/src/components/__tests__/AddReviewDialog.test.tsx b/apps/frontend/src/components/__tests__/AddReviewDialog.test.tsx
index ae3d639..d80db54 100644
--- a/apps/frontend/src/components/__tests__/AddReviewDialog.test.tsx
+++ b/apps/frontend/src/components/__tests__/AddReviewDialog.test.tsx
@@ -38,7 +38,7 @@ async function fillValidReview(
) {
await user.type(screen.getByLabelText('Your name'), 'Kari')
await user.type(screen.getByLabelText('Your review'), 'Great beer')
- await user.click(screen.getByRole('radio', { name: '4 out of 5 stars' }))
+ await user.click(screen.getByRole('radio', { name: '4 out of 5 harps' }))
}
describe('AddReviewDialog', () => {
@@ -87,7 +87,7 @@ describe('AddReviewDialog', () => {
const { user, dialog } = await openDialog()
await user.type(screen.getByLabelText('Your name'), 'Kari')
- await user.click(screen.getByRole('radio', { name: '4 out of 5 stars' }))
+ await user.click(screen.getByRole('radio', { name: '4 out of 5 harps' }))
submitForm(dialog)
expect(await screen.findByRole('alert')).toHaveTextContent(
@@ -109,7 +109,7 @@ describe('AddReviewDialog', () => {
await user.type(screen.getByLabelText('Your name'), ' Kari ')
await user.type(screen.getByLabelText('Your review'), ' Great beer ')
- await user.click(screen.getByRole('radio', { name: '4 out of 5 stars' }))
+ await user.click(screen.getByRole('radio', { name: '4 out of 5 harps' }))
submitForm(dialog)
diff --git a/apps/frontend/src/components/__tests__/Map.test.tsx b/apps/frontend/src/components/__tests__/Map.test.tsx
index 2c4ac7c..e05d54c 100644
--- a/apps/frontend/src/components/__tests__/Map.test.tsx
+++ b/apps/frontend/src/components/__tests__/Map.test.tsx
@@ -57,6 +57,9 @@ vi.mock('react-leaflet', () => ({
Popup: ({ children }: PopupProps) => (
+ ),
+}))
+
describe('Map', () => {
it('renders a map, tile layer and markers for nearby venues', () => {
const venue = makeSearchResult()
@@ -79,7 +88,7 @@ describe('Map', () => {
expect(screen.getByTestId('map')).toHaveAttribute('data-zoom', '15')
expect(screen.getByTestId('tile-layer')).toHaveAttribute(
'data-url',
- 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
+ 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
)
const marker = screen.getByTestId('marker')
diff --git a/apps/frontend/src/graphql/venues.ts b/apps/frontend/src/graphql/venues.ts
index 80a5d8d..1f33d51 100644
--- a/apps/frontend/src/graphql/venues.ts
+++ b/apps/frontend/src/graphql/venues.ts
@@ -1,3 +1,6 @@
+import type { venue } from '#/types/venue'
+import { graphqlFetch } from './client'
+
export const CREATE_REVIEW = `
mutation CreateReview($input: MutationCreateReviewInput!) {
createReview(input: $input) {
@@ -48,3 +51,14 @@ export const GET_VENUE = `
}
}
`
+
+/**
+ * Shared by the city and venue routes. Both render from the same list, so the
+ * options live here to keep the cache key and staleness in sync; the route
+ * loaders prefetch it during SSR so the first paint already has the content.
+ */
+export const venuesQueryOptions = {
+ queryKey: ['venues'],
+ queryFn: () => graphqlFetch<{ venue: venue[] }>(GET_VENUE),
+ staleTime: 5 * 60 * 1000,
+}
diff --git a/apps/frontend/src/lib/asset-url.ts b/apps/frontend/src/lib/asset-url.ts
deleted file mode 100644
index 2b1c108..0000000
--- a/apps/frontend/src/lib/asset-url.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export function assetUrl(path: string): string {
- const base = import.meta.env.BASE_URL.replace(/\/$/, '')
- return `${base}/${path.replace(/^\//, '')}`
-}
diff --git a/apps/frontend/src/routes/$cityId/venues/$venueId.tsx b/apps/frontend/src/routes/$cityId/venues/$venueId.tsx
index 158739c..04fea06 100644
--- a/apps/frontend/src/routes/$cityId/venues/$venueId.tsx
+++ b/apps/frontend/src/routes/$cityId/venues/$venueId.tsx
@@ -1,25 +1,24 @@
import type { ReactNode } from 'react'
-import type { venue } from '#/types/venue'
import { useQuery } from '@tanstack/react-query'
import { Link, createFileRoute } from '@tanstack/react-router'
import Breadcrumbs from '#/components/Breadcrumbs'
import AddReviewDialog from '#/components/AddReviewDialog'
import { venueToSearchResult } from '#/components/VenueCard'
import { ViewVenue } from '#/components/ViewVenue'
-import VenueMap from '#/components/VenueMap'
-import { graphqlFetch } from '#/graphql/client'
-import { GET_VENUE } from '#/graphql/venues'
+import ClientVenueMap from '#/components/ClientVenueMap'
+import { venuesQueryOptions } from '#/graphql/venues'
export const Route = createFileRoute('/$cityId/venues/$venueId')({
+ // Prefetch during SSR: the venue page used to paint a loading shell first, so
+ // the footer moved and the map tiles became the LCP element.
+ loader: ({ context }) =>
+ context.queryClient.prefetchQuery(venuesQueryOptions),
component: VenuePage,
})
function VenuePage() {
const { cityId, venueId } = Route.useParams()
- const { data, isPending, isError } = useQuery({
- queryKey: ['venues'],
- queryFn: () => graphqlFetch<{ venue: venue[] }>(GET_VENUE),
- })
+ const { data, isPending, isError } = useQuery(venuesQueryOptions)
if (isPending) {
return (
@@ -53,7 +52,7 @@ function VenuePage() {
)
return (
-
+
{current.name}
-
+
@@ -118,7 +121,7 @@ function VenuePage() {
function PageShell({ children }: { children: ReactNode }) {
return (
-
+
{children}
diff --git a/apps/frontend/src/routes/$cityId/venues/index.tsx b/apps/frontend/src/routes/$cityId/venues/index.tsx
index d5ea2b0..0424e92 100644
--- a/apps/frontend/src/routes/$cityId/venues/index.tsx
+++ b/apps/frontend/src/routes/$cityId/venues/index.tsx
@@ -1,22 +1,22 @@
import type { ReactNode } from 'react'
-import type { venue } from '#/types/venue'
import { useQuery } from '@tanstack/react-query'
import { Link, createFileRoute } from '@tanstack/react-router'
import Breadcrumbs from '#/components/Breadcrumbs'
import VenueCard from '#/components/VenueCard'
-import { graphqlFetch } from '#/graphql/client'
-import { GET_VENUE } from '#/graphql/venues'
+import { venuesQueryOptions } from '#/graphql/venues'
export const Route = createFileRoute('/$cityId/venues/')({
+ // Prefetch during SSR so the list is in the first paint. Rendering a loading
+ // shell instead makes the page grow once the data lands, which shifts the
+ // footer by a sixth of the viewport.
+ loader: ({ context }) =>
+ context.queryClient.prefetchQuery(venuesQueryOptions),
component: CityVenuesPage,
})
function CityVenuesPage() {
const { cityId } = Route.useParams()
- const { data, isPending, isError } = useQuery({
- queryKey: ['venues'],
- queryFn: () => graphqlFetch<{ venue: venue[] }>(GET_VENUE),
- })
+ const { data, isPending, isError } = useQuery(venuesQueryOptions)
if (isPending) {
return (
@@ -54,7 +54,7 @@ function CityVenuesPage() {
}
return (
-
+
{cityName}
@@ -72,7 +72,7 @@ function CityVenuesPage() {
function PageShell({ children }: { children: ReactNode }) {
return (
-
+
{children}
diff --git a/apps/frontend/src/routes/__root.tsx b/apps/frontend/src/routes/__root.tsx
index 9eada18..1ac9610 100644
--- a/apps/frontend/src/routes/__root.tsx
+++ b/apps/frontend/src/routes/__root.tsx
@@ -1,16 +1,15 @@
+import { lazy, Suspense } from 'react'
import {
HeadContent,
Scripts,
createRootRouteWithContext,
} from '@tanstack/react-router'
-import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
-import { TanStackDevtools } from '@tanstack/react-devtools'
import Footer from '../components/Footer'
import Header from '../components/Header'
-import TanStackQueryDevtools from '../integrations/tanstack-query/devtools'
-
import appCss from '../styles.css?url'
+import loraFont from '../assets/fonts/lora-latin.woff2?url'
+import playfairFont from '../assets/fonts/playfair-display-latin.woff2?url'
import type { QueryClient } from '@tanstack/react-query'
@@ -20,12 +19,23 @@ interface MyRouterContext {
const THEME_INIT_SCRIPT = `(function(){try{var stored=window.localStorage.getItem('theme');var mode=(stored==='light'||stored==='dark')?stored:'dark';var root=document.documentElement;root.classList.remove('light','dark');root.classList.add(mode);root.setAttribute('data-theme',mode);root.style.colorScheme=mode;}catch(e){}})();`
+// The mock-location notice depends on `window.isSecureContext`, which is only
+// known in the browser. Deciding it after hydration would push the whole page
+// down and register as a large layout shift, so the flag is set before the
+// first paint and the notice is toggled with plain CSS instead.
+const MOCK_LOCATION_SCRIPT = `(function(){try{if(!window.isSecureContext){document.documentElement.setAttribute('data-mock-location','');}}catch(e){}})();`
+
// Vite hands us `/project2` (no trailing slash) here, so normalize before
// appending asset names.
const BASE_URL = import.meta.env.BASE_URL.endsWith('/')
? import.meta.env.BASE_URL
: `${import.meta.env.BASE_URL}/`
+// Loaded on demand so React Router/Query devtools never ship in production.
+const Devtools = import.meta.env.DEV
+ ? lazy(() => import('../components/Devtools'))
+ : null
+
export const Route = createRootRouteWithContext()({
head: () => ({
meta: [
@@ -36,9 +46,31 @@ export const Route = createRootRouteWithContext()({
name: 'viewport',
content: 'width=device-width, initial-scale=1',
},
+ {
+ name: 'description',
+ content:
+ 'Find pubs near you, compare Guinness prices, check opening hours and read reviews with G-Spotter.',
+ },
+ {
+ name: 'theme-color',
+ content: '#100b0b',
+ },
{
title: 'G-Spotter',
},
+ {
+ property: 'og:title',
+ content: 'G-Spotter',
+ },
+ {
+ property: 'og:description',
+ content:
+ 'Find pubs near you, compare Guinness prices, check opening hours and read reviews with G-Spotter.',
+ },
+ {
+ property: 'og:type',
+ content: 'website',
+ },
],
links: [
{
@@ -60,31 +92,40 @@ function RootDocument({ children }: { children: React.ReactNode }) {
+
+
+
+
+ Skip to main content
+
{children}
- ,
- },
- TanStackQueryDevtools,
- ]}
- />
+ {Devtools && (
+
+
+
+ )}
diff --git a/apps/frontend/src/routes/index.tsx b/apps/frontend/src/routes/index.tsx
index a9c151f..7b6304c 100644
--- a/apps/frontend/src/routes/index.tsx
+++ b/apps/frontend/src/routes/index.tsx
@@ -2,7 +2,7 @@ import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import Map from '../components/Map'
+import ClientMap from '#/components/ClientMap'
import MockLocationNotice from '#/components/MockLocationNotice'
import NearbyVenues from '#/components/NearbyVenues'
import SearchBox from '#/components/SearchBox'
@@ -204,13 +204,17 @@ function App() {
}, [coordinates])
return (
-
- {usingMockLocation && }
-
+
+
Find pubs near you
+
+ {/* No `rise-in` here: the map poster inside this section must be painted
+ on the first frame, and an animation that starts at opacity: 0 keeps
+ it from being reported as the LCP element. */}
+