Add brewery discovery & detail pages with location-based search (#253)

This commit is contained in:
Aaron Po
2026-08-29 00:44:33 -04:00
committed by GitHub
parent 92a30b11db
commit a580314583
90 changed files with 3874 additions and 187 deletions

View File

@@ -0,0 +1,106 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, within } from 'storybook/test';
import FeaturedBreweryCard from './FeaturedBreweryCard';
import type { Brewery, BreweryLocation } from '../../breweries.server';
const featuredBreweryCardDescription = `Larger "featured brewery" card shown above the fold on the breweries page. These stories cover a brewery with mappable coordinates (the "Show on map" button is present and wired to \`onShowOnMap\`), one with a location but no coordinates, and one with no location at all.`;
const portlandLocation: BreweryLocation = {
breweryPostLocationId: 'loc-1',
breweryPostId: 'brewery-1',
cityId: 'city-1',
cityName: 'Portland',
stateProvinceName: 'Oregon',
stateProvinceCode: 'OR',
countryName: 'United States',
countryCode: 'US',
addressLine1: '123 Hop Street',
addressLine2: null,
postalCode: '97201',
coordinates: { latitude: 45.5152, longitude: -122.6784 },
};
const breweryWithLocation: Brewery = {
breweryPostId: 'brewery-1',
postedById: 'user-1',
breweryName: 'Cascade Hollow Brewing',
description:
'A small-batch brewery known for hazy IPAs and barrel-aged sours, tucked into an old warehouse district.',
createdAt: '2024-03-01T12:00:00.000Z',
updatedAt: null,
location: portlandLocation,
};
const breweryWithoutCoordinates: Brewery = {
...breweryWithLocation,
breweryPostId: 'brewery-2',
breweryName: 'Foggy Bottom Brewhouse',
location: { ...portlandLocation, coordinates: null },
};
const breweryWithoutLocation: Brewery = {
...breweryWithLocation,
breweryPostId: 'brewery-3',
breweryName: 'Unmapped Ales',
location: null,
};
const meta = {
title: 'Breweries/FeaturedBreweryCard',
component: FeaturedBreweryCard,
tags: ['autodocs'],
args: {
onShowOnMap: fn(),
},
parameters: {
layout: 'padded',
docs: {
description: {
component: featuredBreweryCardDescription,
},
},
},
} satisfies Meta<typeof FeaturedBreweryCard>;
export default meta;
type Story = StoryObj<typeof meta>;
export const WithCoordinates: Story = {
args: { brewery: breweryWithLocation },
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
await expect(
canvas.getByRole('heading', { name: 'Cascade Hollow Brewing', level: 3 }),
).toBeInTheDocument();
await expect(canvas.getByText('Founded')).toBeInTheDocument();
await expect(canvas.getByText('2014')).toBeInTheDocument();
await expect(canvas.getByRole('link', { name: /view brewery/i })).toHaveAttribute(
'href',
'/breweries/brewery-1',
);
await userEvent.click(canvas.getByRole('button', { name: /show on map/i }));
await expect(args.onShowOnMap).toHaveBeenCalledOnce();
},
};
export const WithoutCoordinates: Story = {
args: { brewery: breweryWithoutCoordinates },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(
canvas.queryByRole('button', { name: /show on map/i }),
).not.toBeInTheDocument();
},
};
export const WithoutLocation: Story = {
args: { brewery: breweryWithoutLocation },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole('heading', { name: 'Unmapped Ales' })).toBeInTheDocument();
await expect(
canvas.queryByRole('button', { name: /show on map/i }),
).not.toBeInTheDocument();
},
};

View File

@@ -0,0 +1,59 @@
import { Link } from 'react-router';
import type { Brewery } from '../../breweries.server';
import { formatBreweryAddress } from '../../utils/format-address';
interface FeaturedBreweryCardProps {
brewery: Brewery;
onShowOnMap: () => void;
}
// see BREWERY_HANDOFF.md
const FILLER_STATS = [
{ label: 'Founded', value: '2014' },
{ label: 'Beers listed', value: '18' },
{ label: 'House style', value: 'Seasonal ale' },
];
const FeaturedBreweryCard = ({ brewery, onShowOnMap }: FeaturedBreweryCardProps) => (
<div className="card bg-base-100 shadow-md rounded-box">
<div className="card-body gap-3.5 p-8 md:grid md:grid-cols-[1.35fr_1fr] md:gap-10 md:items-start">
<div className="flex flex-col gap-3.5">
{brewery.location && (
<div className="text-sm font-semibold text-base-content/60">
{brewery.location.cityName}, {brewery.location.stateProvinceCode}
</div>
)}
<h3 className="font-serif text-4xl leading-tight m-0">{brewery.breweryName}</h3>
<p className="text-lg leading-snug text-pretty m-0">{brewery.description}</p>
{brewery.location && (
<p className="text-sm text-base-content/60 m-0">
{formatBreweryAddress(brewery.location)}
</p>
)}
<div className="flex gap-3 pt-2">
<Link to={`/breweries/${brewery.breweryPostId}`} className="btn btn-primary">
View brewery
</Link>
{brewery.location?.coordinates && (
<button type="button" onClick={onShowOnMap} className="btn btn-outline">
Show on map
</button>
)}
</div>
</div>
<div className="stats stats-vertical shadow w-full mt-6 md:mt-0">
{FILLER_STATS.map((stat) => (
<div key={stat.label} className="stat">
<div className="stat-title text-xs font-bold uppercase tracking-widest">
{stat.label}
</div>
<div className="stat-value font-serif text-2xl">{stat.value}</div>
</div>
))}
</div>
</div>
</div>
);
export default FeaturedBreweryCard;

View File

@@ -0,0 +1,93 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, within } from 'storybook/test';
import RecentBreweries from './RecentBreweries';
import type { Brewery, BreweryLocation } from '../../breweries.server';
const recentBreweriesDescription = `Grid of recently-added breweries shown on the breweries index page. Renders nothing when the list is empty.`;
const portlandLocation: BreweryLocation = {
breweryPostLocationId: 'loc-1',
breweryPostId: 'brewery-1',
cityId: 'city-1',
cityName: 'Portland',
stateProvinceName: 'Oregon',
stateProvinceCode: 'OR',
countryName: 'United States',
countryCode: 'US',
addressLine1: '123 Hop Street',
addressLine2: null,
postalCode: '97201',
coordinates: { latitude: 45.5152, longitude: -122.6784 },
};
const cascadeHollow: Brewery = {
breweryPostId: 'brewery-1',
postedById: 'user-1',
breweryName: 'Cascade Hollow Brewing',
description: 'A small-batch brewery known for hazy IPAs and barrel-aged sours.',
createdAt: '2024-03-01T12:00:00.000Z',
updatedAt: null,
location: portlandLocation,
};
const midrangeMalts: Brewery = {
breweryPostId: 'brewery-2',
postedById: 'user-2',
breweryName: 'Midrange Malts',
description: 'A neighborhood taproom pouring approachable session ales year-round.',
createdAt: '2024-04-15T09:30:00.000Z',
updatedAt: null,
location: { ...portlandLocation, breweryPostId: 'brewery-2', cityName: 'Salem' },
};
const unmappedAles: Brewery = {
breweryPostId: 'brewery-3',
postedById: 'user-3',
breweryName: 'Unmapped Ales',
description: 'A pop-up brewery that hasn’t added a storefront location yet.',
createdAt: '2024-05-02T18:00:00.000Z',
updatedAt: null,
location: null,
};
const meta = {
title: 'Breweries/RecentBreweries',
component: RecentBreweries,
tags: ['autodocs'],
parameters: {
layout: 'padded',
docs: {
description: {
component: recentBreweriesDescription,
},
},
},
} satisfies Meta<typeof RecentBreweries>;
export default meta;
type Story = StoryObj<typeof meta>;
export const WithBreweries: Story = {
args: { breweries: [cascadeHollow, midrangeMalts, unmappedAles] },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole('heading', { name: 'Recently added' })).toBeInTheDocument();
await expect(
canvas.getByRole('heading', { name: 'Cascade Hollow Brewing' }),
).toBeInTheDocument();
const links = canvas.getAllByRole('link', { name: /view brewery/i });
await expect(links).toHaveLength(3);
await expect(links[0]).toHaveAttribute('href', '/breweries/brewery-1');
},
};
export const Empty: Story = {
args: { breweries: [] },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(
canvas.queryByRole('heading', { name: 'Recently added' }),
).not.toBeInTheDocument();
},
};

View File

@@ -0,0 +1,42 @@
import { Link } from 'react-router';
import type { Brewery } from '../../breweries.server';
interface RecentBreweriesProps {
breweries: Brewery[];
}
const RecentBreweries = ({ breweries }: RecentBreweriesProps) => {
if (breweries.length === 0) return null;
return (
<section className="max-w-7xl mx-auto px-5 pt-11">
<h2 className="font-serif text-2xl mb-3.5">Recently added</h2>
<div className="grid gap-5 grid-cols-[repeat(auto-fit,minmax(15rem,1fr))]">
{breweries.map((brewery) => (
<div key={brewery.breweryPostId} className="card bg-base-100 shadow">
<div className="card-body gap-1.5">
<h3 className="card-title font-serif text-xl">{brewery.breweryName}</h3>
{brewery.location && (
<div className="text-sm text-base-content/60">
{brewery.location.cityName},{' '}
{brewery.location.stateProvinceCode}
</div>
)}
<p className="text-sm leading-snug mt-1 line-clamp-2">
{brewery.description}
</p>
<Link
to={`/breweries/${brewery.breweryPostId}`}
className="link link-hover text-sm font-semibold text-secondary hover:text-primary mt-2"
>
View brewery &rarr;
</Link>
</div>
</div>
))}
</div>
</section>
);
};
export default RecentBreweries;

View File

@@ -0,0 +1,180 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { useState } from 'react';
import { createMemoryRouter, RouterProvider } from 'react-router';
import { expect, fireEvent, waitFor, within } from 'storybook/test';
import NearbyBreweriesSection from './NearbyBreweriesSection';
import type { BreweryLocation, SimplifiedBrewery } from '../../../breweries.server';
const nearbyBreweriesSectionDescription = `Requests geolocation (falling back to \`fallbackCenter\` when it's unavailable or denied, as it reliably is in headless browser tests), then loads nearby breweries via \`useFetcher().load()\` against the \`/breweries/nearby\` route, re-fetching whenever the debounced search radius changes. This harness runs the real component behind a \`createMemoryRouter\` with a fake loader for that route, keyed by the requested radius, so the \`Default\` story's play function can prove both the initial load and that rapid radius changes are debounced into a single re-fetch rather than one per step. The lazily-loaded Leaflet map mounts for real here (Storybook's client-only render means \`ClientOnly\` reports "mounted" immediately) and will issue real tile requests - the play function doesn't assert anything about it.`;
const portlandLocation: BreweryLocation = {
breweryPostLocationId: 'loc-close',
breweryPostId: 'brewery-close',
cityId: 'city-1',
cityName: 'Portland',
stateProvinceName: 'Oregon',
stateProvinceCode: 'OR',
countryName: 'United States',
countryCode: 'US',
addressLine1: '123 Hop Street',
addressLine2: null,
postalCode: '97201',
coordinates: { latitude: 45.52, longitude: -122.68 },
};
const closeQuarters: SimplifiedBrewery = {
breweryPostId: 'brewery-close',
breweryName: 'Close Quarters Brewing',
location: portlandLocation,
distanceMetres: 4800,
};
const midrangeMalts: SimplifiedBrewery = {
breweryPostId: 'brewery-mid',
breweryName: 'Midrange Malts',
location: {
...portlandLocation,
breweryPostLocationId: 'loc-mid',
breweryPostId: 'brewery-mid',
cityName: 'Salem',
coordinates: { latitude: 44.94, longitude: -123.03 },
},
distanceMetres: 52000,
};
const farFlungFermentery: SimplifiedBrewery = {
breweryPostId: 'brewery-far',
breweryName: 'Far Flung Fermentery',
location: {
...portlandLocation,
breweryPostLocationId: 'loc-far',
breweryPostId: 'brewery-far',
cityName: 'Bend',
coordinates: { latitude: 44.06, longitude: -121.31 },
},
distanceMetres: 138000,
};
const FALLBACK_CENTER = { latitude: 45.5152, longitude: -122.6784, label: 'Portland, OR' };
// Keyed by rangeInMetres so the play function can prove the radius slider
// drives refetches. DEFAULT_RADIUS_KM=120 -> 120000; MAX_RADIUS_KM=150 -> 150000.
const NEARBY_FIXTURES: Record<number, SimplifiedBrewery[]> = {
30000: [closeQuarters],
60000: [closeQuarters],
90000: [closeQuarters, midrangeMalts],
120000: [closeQuarters, midrangeMalts],
150000: [closeQuarters, midrangeMalts, farFlungFermentery],
};
let fetchedRanges: number[] = [];
const NearbyBreweriesRoute = () => {
const [selectedId, setSelectedId] = useState<string | null>(null);
return (
<NearbyBreweriesSection
featured={null}
fallbackCenter={FALLBACK_CENTER}
selectedId={selectedId}
onSelect={setSelectedId}
/>
);
};
const NearbyBreweriesHarness = () => {
const [router] = useState(() => {
fetchedRanges = [];
return createMemoryRouter([
{ path: '/', element: <NearbyBreweriesRoute /> },
{
path: '/breweries/nearby',
loader: async ({ request }) => {
const rangeInMetres = Number(
new URL(request.url).searchParams.get('rangeInMetres'),
);
fetchedRanges.push(rangeInMetres);
return { breweries: NEARBY_FIXTURES[rangeInMetres] ?? [] };
},
},
]);
});
return <RouterProvider router={router} />;
};
const NearbyBreweriesEmptyHarness = () => {
const [router] = useState(() =>
createMemoryRouter([
{ path: '/', element: <NearbyBreweriesRoute /> },
{
path: '/breweries/nearby',
loader: async () => ({ breweries: [] as SimplifiedBrewery[] }),
},
]),
);
return <RouterProvider router={router} />;
};
const meta = {
title: 'Breweries/NearbyBreweriesSection',
component: NearbyBreweriesHarness,
tags: ['autodocs'],
parameters: {
layout: 'fullscreen',
usesDataRouter: true,
docs: {
description: {
component: nearbyBreweriesSectionDescription,
},
},
},
} satisfies Meta<typeof NearbyBreweriesHarness>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
// Initial (undebounced) fetch at the default radius (120km -> 120000m).
await waitFor(
() => expect(canvas.getByText('Close Quarters Brewing')).toBeInTheDocument(),
{ timeout: 3000 },
);
await expect(canvas.getByText('Midrange Malts')).toBeInTheDocument();
await expect(fetchedRanges).toEqual([120000]);
// Simulate a fast drag through several intermediate values with no
// waits in between.
const radiusSlider = canvas.getByRole('slider', { name: /search radius/i });
fireEvent.change(radiusSlider, { target: { value: '30' } });
fireEvent.change(radiusSlider, { target: { value: '60' } });
fireEvent.change(radiusSlider, { target: { value: '90' } });
fireEvent.change(radiusSlider, { target: { value: '150' } });
// The radius label updates immediately (it isn't debounced)...
await expect(canvas.getByText('150 km')).toBeInTheDocument();
// ...but no new fetch has fired yet - the 300ms debounce window hasn't elapsed.
await expect(fetchedRanges).toEqual([120000]);
// After the debounce window, exactly one more fetch happens, for the
// final radius only - not one per intermediate step.
await waitFor(() => expect(canvas.getByText('Far Flung Fermentery')).toBeInTheDocument(), {
timeout: 3000,
});
await expect(fetchedRanges).toEqual([120000, 150000]);
},
};
export const NoBreweriesWithinRadius: Story = {
render: () => <NearbyBreweriesEmptyHarness />,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await waitFor(
() => expect(canvas.getByText(/no partner breweries within/i)).toBeInTheDocument(),
{ timeout: 3000 },
);
},
};

View File

@@ -0,0 +1,173 @@
import { lazy, Suspense, useEffect, useState } from 'react';
import { useFetcher } from 'react-router';
import type { LatLngTuple } from 'leaflet';
import useDebouncedValue from '../../../../../hooks/useDebouncedValue';
import type { SimplifiedBrewery } from '../../../breweries.server';
import type { loader as nearbyLoader } from '../../../routes/resources/breweries-nearby';
import type { DistanceUnit } from '../../../utils/distance';
import ChangeLocationButton from './controls/ChangeLocationButton';
import RadiusUnitControls from './controls/RadiusUnitControls';
import NearbyBreweriesHeader from './header/NearbyBreweriesHeader';
import NearbyBreweryList from './list/NearbyBreweryList';
import ClientOnlyMap, { MAP_PLACEHOLDER_CLASS } from './map/ClientOnlyMap';
import type { NearbyMapPin } from './map/NearbyBreweryMap';
const NearbyBreweryMap = lazy(() => import('./map/NearbyBreweryMap'));
const DEFAULT_RADIUS_KM = 120;
const RADIUS_DEBOUNCE_MS = 300;
export interface FeaturedPin {
id: string;
name: string;
latitude: number;
longitude: number;
}
interface FallbackCenter {
latitude: number;
longitude: number;
label: string;
}
interface NearbyBreweriesSectionProps {
featured: FeaturedPin | null;
fallbackCenter: FallbackCenter | null;
selectedId: string | null;
onSelect: (id: string) => void;
}
const NearbyBreweriesSection = ({
featured,
fallbackCenter,
selectedId,
onSelect,
}: NearbyBreweriesSectionProps) => {
const [userLocation, setUserLocation] = useState<LatLngTuple | null>(null);
const [locationLabel, setLocationLabel] = useState('your location');
const [geoAttempted, setGeoAttempted] = useState(false);
const [radiusKm, setRadiusKm] = useState(DEFAULT_RADIUS_KM);
const debouncedRadiusKm = useDebouncedValue(radiusKm, RADIUS_DEBOUNCE_MS);
const [unit, setUnit] = useState<DistanceUnit>('km');
const fetcher = useFetcher<typeof nearbyLoader>();
const requestGeolocation = () => {
if (!navigator.geolocation) {
Promise.resolve().then(() => setGeoAttempted(true));
return;
}
navigator.geolocation.getCurrentPosition(
(pos) => {
setUserLocation([pos.coords.latitude, pos.coords.longitude]);
setLocationLabel('your location');
setGeoAttempted(true);
},
() => setGeoAttempted(true),
{ enableHighAccuracy: true },
);
};
useEffect(() => {
requestGeolocation();
}, []);
const center: LatLngTuple | null =
userLocation ??
(geoAttempted && fallbackCenter
? [fallbackCenter.latitude, fallbackCenter.longitude]
: null);
const centerLabel = userLocation ? locationLabel : (fallbackCenter?.label ?? locationLabel);
useEffect(() => {
if (!center) return;
fetcher.load(
`/breweries/nearby?latitude=${center[0]}&longitude=${center[1]}&rangeInMetres=${debouncedRadiusKm * 1000}`,
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [center?.[0], center?.[1], debouncedRadiusKm]);
const nearby: SimplifiedBrewery[] = fetcher.data?.breweries ?? [];
const withDistance = center
? nearby
.filter((b) => b.location?.coordinates && b.distanceMetres !== null)
.map((b) => ({
brewery: b,
distanceMetres: b.distanceMetres as number,
}))
.sort((a, b) => a.distanceMetres - b.distanceMetres)
: [];
const pins: NearbyMapPin[] = withDistance.map(({ brewery }) => ({
id: brewery.breweryPostId,
name: brewery.breweryName,
cityLabel: brewery.location
? `${brewery.location.cityName}, ${brewery.location.stateProvinceCode}`
: null,
latitude: brewery.location!.coordinates!.latitude,
longitude: brewery.location!.coordinates!.longitude,
}));
if (featured && !pins.some((p) => p.id === featured.id)) {
pins.push({
id: featured.id,
name: featured.name,
cityLabel: null,
latitude: featured.latitude,
longitude: featured.longitude,
});
}
return (
<section id="breweries-near-you" className="max-w-7xl mx-auto px-5 pt-11">
<NearbyBreweriesHeader
center={center}
withDistance={withDistance}
radiusKm={radiusKm}
unit={unit}
centerLabel={centerLabel}
/>
<div className="grid gap-5 items-stretch md:grid-cols-[22rem_1fr]">
<div className="flex flex-col gap-3 order-2 md:order-1">
<RadiusUnitControls
radiusKm={radiusKm}
unit={unit}
onRadiusChange={(e) => setRadiusKm(Number(e.target.value))}
onSelectKm={() => setUnit('km')}
onSelectMi={() => setUnit('mi')}
/>
<NearbyBreweryList
withDistance={withDistance}
center={center}
radiusKm={radiusKm}
unit={unit}
selectedId={selectedId}
onSelect={onSelect}
/>
<ChangeLocationButton onClick={requestGeolocation} />
</div>
<div className="order-1 md:order-2">
<ClientOnlyMap
render={() =>
center ? (
<Suspense fallback={<div className={MAP_PLACEHOLDER_CLASS} />}>
<NearbyBreweryMap
pins={pins}
selectedId={selectedId}
onSelect={onSelect}
userLocation={userLocation}
userLocationLabel={centerLabel}
/>
</Suspense>
) : (
<div className={MAP_PLACEHOLDER_CLASS} />
)
}
/>
</div>
</div>
</section>
);
};
export default NearbyBreweriesSection;

View File

@@ -0,0 +1,15 @@
interface ChangeLocationButtonProps {
onClick: () => void;
}
const ChangeLocationButton = ({ onClick }: ChangeLocationButtonProps) => {
return (
<div className="pt-1">
<button type="button" onClick={onClick} className="btn btn-ghost btn-sm">
Change location
</button>
</div>
);
};
export default ChangeLocationButton;

View File

@@ -0,0 +1,59 @@
import { formatDistance, type DistanceUnit } from '../../../../utils/distance';
const MIN_RADIUS_KM = 10;
const MAX_RADIUS_KM = 300;
const RADIUS_STEP_KM = 10;
interface RadiusUnitControlsProps {
radiusKm: number;
unit: DistanceUnit;
onRadiusChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
onSelectKm: () => void;
onSelectMi: () => void;
}
const RadiusUnitControls = ({
radiusKm,
unit,
onRadiusChange,
onSelectKm,
onSelectMi,
}: RadiusUnitControlsProps) => {
return (
<div className="flex items-center justify-between gap-3">
<label className="flex-1 flex flex-col gap-1 text-sm text-base-content/70">
<span className="flex justify-between">
<span>Search radius</span>
<span className="font-semibold">{formatDistance(radiusKm * 1000, unit)}</span>
</span>
<input
type="range"
min={MIN_RADIUS_KM}
max={MAX_RADIUS_KM}
step={RADIUS_STEP_KM}
value={radiusKm}
onChange={onRadiusChange}
className="range range-primary range-sm"
/>
</label>
<div className="join self-end">
<button
type="button"
onClick={onSelectKm}
className={`btn btn-xs join-item ${unit === 'km' ? 'btn-active' : ''}`}
>
km
</button>
<button
type="button"
onClick={onSelectMi}
className={`btn btn-xs join-item ${unit === 'mi' ? 'btn-active' : ''}`}
>
mi
</button>
</div>
</div>
);
};
export default RadiusUnitControls;

View File

@@ -0,0 +1,32 @@
import type { LatLngTuple } from 'leaflet';
import { formatDistance, type DistanceUnit } from '../../../../utils/distance';
import type { BreweryWithDistance } from '../types';
interface NearbyBreweriesHeaderProps {
center: LatLngTuple | null;
withDistance: BreweryWithDistance[];
radiusKm: number;
unit: DistanceUnit;
centerLabel: string;
}
const NearbyBreweriesHeader = ({
center,
centerLabel,
radiusKm,
unit,
withDistance,
}: NearbyBreweriesHeaderProps) => {
return (
<div className="flex items-baseline justify-between gap-4 flex-wrap mb-3.5">
<h2 className="font-serif text-2xl m-0">Breweries near you</h2>
<span className="text-sm text-base-content/60">
{center
? `${withDistance.length} within ${formatDistance(radiusKm * 1000, unit)} of ${centerLabel}`
: 'Finding breweries near you…'}
</span>
</div>
);
};
export default NearbyBreweriesHeader;

View File

@@ -0,0 +1,44 @@
import type { LatLngTuple } from 'leaflet';
import { formatDistance, type DistanceUnit } from '../../../../utils/distance';
import type { BreweryWithDistance } from '../types';
import NearbyBreweryListItem from './NearbyBreweryListItem';
interface NearbyBreweryListProps {
withDistance: BreweryWithDistance[];
center: LatLngTuple | null;
radiusKm: number;
unit: DistanceUnit;
selectedId: string | null;
onSelect: (id: string) => void;
}
const NearbyBreweryList = ({
withDistance,
center,
radiusKm,
unit,
selectedId,
onSelect,
}: NearbyBreweryListProps) => {
return (
<>
{withDistance.length === 0 && center && (
<p className="text-sm text-base-content/60">
No partner breweries within {formatDistance(radiusKm * 1000, unit)}.
</p>
)}
{withDistance.map(({ brewery, distanceMetres }) => (
<NearbyBreweryListItem
key={brewery.breweryPostId}
brewery={brewery}
distanceMetres={distanceMetres}
unit={unit}
selected={selectedId === brewery.breweryPostId}
onSelect={onSelect}
/>
))}
</>
);
};
export default NearbyBreweryList;

View File

@@ -0,0 +1,49 @@
import type { SimplifiedBrewery } from '../../../../breweries.server';
import { formatDistance, type DistanceUnit } from '../../../../utils/distance';
// Notes aren't tracked on brewery locations yet - see BREWERY_HANDOFF.md.
const FILLER_NOTE = 'A stop worth the detour.';
const cardClassName = (selected: boolean) =>
`card card-sm card-border bg-base-100 text-left shadow transition-shadow hover:shadow-lg ${
selected ? 'border-2 border-primary' : ''
}`;
interface NearbyBreweryListItemProps {
brewery: SimplifiedBrewery;
distanceMetres: number;
unit: DistanceUnit;
selected: boolean;
onSelect: (id: string) => void;
}
const NearbyBreweryListItem = ({
brewery,
distanceMetres,
unit,
selected,
onSelect,
}: NearbyBreweryListItemProps) => (
<button
type="button"
onClick={() => onSelect(brewery.breweryPostId)}
className={cardClassName(selected)}
>
<div className="card-body">
<div className="flex justify-between items-baseline gap-3">
<h3 className="card-title font-serif text-lg">{brewery.breweryName}</h3>
<span className="text-sm font-semibold text-primary whitespace-nowrap">
{formatDistance(distanceMetres, unit)}
</span>
</div>
{brewery.location && (
<div className="text-sm text-base-content/60">
{brewery.location.cityName}, {brewery.location.stateProvinceCode}
</div>
)}
<div className="text-sm mt-2">{FILLER_NOTE}</div>
</div>
</button>
);
export default NearbyBreweryListItem;

View File

@@ -0,0 +1,14 @@
import ClientOnly from '../../../../../../components/ClientOnly';
const MAP_PLACEHOLDER_CLASS = 'skeleton min-h-[30rem] h-full w-full rounded-box';
interface ClientOnlyMapProps {
render: () => React.JSX.Element;
}
const ClientOnlyMap = ({ render }: ClientOnlyMapProps) => {
return <ClientOnly fallback={<div className={MAP_PLACEHOLDER_CLASS} />}>{render}</ClientOnly>;
};
export default ClientOnlyMap;
export { MAP_PLACEHOLDER_CLASS };

View File

@@ -0,0 +1,64 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import NearbyBreweryMap, { type NearbyMapPin } from './NearbyBreweryMap';
const nearbyBreweryMapDescription = `Leaflet map of nearby-brewery pins used inside NearbyBreweriesSection. Smoke-render only - this hits the real OpenStreetMap tile server in the browser test run. Wrapped in a fixed-height container here since its \`h-full\` class normally relies on a CSS grid ancestor that this story doesn't provide.`;
const pins: NearbyMapPin[] = [
{
id: 'brewery-close',
name: 'Close Quarters Brewing',
cityLabel: 'Portland, OR',
latitude: 45.52,
longitude: -122.68,
},
{
id: 'brewery-mid',
name: 'Midrange Malts',
cityLabel: 'Salem, OR',
latitude: 44.94,
longitude: -123.03,
},
];
const meta = {
title: 'Breweries/NearbyBreweryMap',
component: NearbyBreweryMap,
decorators: [
(Story) => (
<div className="h-[32rem]">
<Story />
</div>
),
],
parameters: {
layout: 'padded',
docs: {
description: {
component: nearbyBreweryMapDescription,
},
},
},
} satisfies Meta<typeof NearbyBreweryMap>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {
args: {
pins,
selectedId: null,
onSelect: () => undefined,
userLocation: [45.5152, -122.6784],
userLocationLabel: 'your location',
},
};
export const WithoutUserLocation: Story = {
args: {
pins,
selectedId: null,
onSelect: () => undefined,
userLocation: null,
userLocationLabel: 'your location',
},
};

View File

@@ -0,0 +1,159 @@
import { useEffect, useRef } from 'react';
import { MapContainer, TileLayer, Marker, Popup, CircleMarker, useMap } from 'react-leaflet';
import L, { type LatLngTuple } from 'leaflet';
import 'leaflet/dist/leaflet.css';
const DEFAULT_ZOOM = 11;
const MIN_ZOOM = 8;
export interface NearbyMapPin {
id: string;
name: string;
cityLabel: string | null;
latitude: number;
longitude: number;
}
interface NearbyBreweryMapProps {
pins: NearbyMapPin[];
selectedId: string | null;
onSelect: (id: string) => void;
userLocation: LatLngTuple | null;
userLocationLabel: string;
}
// Leaflet paints markers as SVG attributes, which can't reference CSS custom
// properties the way class names can - resolve the current theme's colors instead.
const resolveThemeColor = (variable: string, fallback: string) => {
if (typeof document === 'undefined') return fallback;
const value = getComputedStyle(document.documentElement).getPropertyValue(variable).trim();
return value || fallback;
};
const pinIcon = (active: boolean) =>
L.divIcon({
className: '',
html: `<span class="block h-[18px] w-[18px] rounded-full border-[3px] border-base-100 shadow-[0_1px_4px_rgba(0,0,0,.35)] ${
active ? 'bg-secondary scale-125' : 'bg-primary'
}"></span>`,
iconSize: [18, 18],
iconAnchor: [9, 9],
});
const FitAndFocus = ({
pins,
userLocation,
selectedId,
}: {
pins: NearbyMapPin[];
userLocation: LatLngTuple | null;
selectedId: string | null;
}) => {
const map = useMap();
const didInitialFit = useRef(false);
useEffect(() => {
if (didInitialFit.current) return;
const focus: LatLngTuple | null =
userLocation ?? (pins[0] ? [pins[0].latitude, pins[0].longitude] : null);
if (focus) {
map.setView(focus, DEFAULT_ZOOM, { animate: false });
didInitialFit.current = true;
}
const timeout = setTimeout(() => map.invalidateSize(), 200);
return () => clearTimeout(timeout);
}, [map, pins, userLocation]);
useEffect(() => {
if (!didInitialFit.current || !selectedId) return;
const pin = pins.find((p) => p.id === selectedId);
if (!pin) return;
map.flyTo([pin.latitude, pin.longitude], Math.max(map.getZoom(), 11), { duration: 0.8 });
}, [map, pins, selectedId]);
return null;
};
const RecenterButton = ({ userLocation }: { userLocation: LatLngTuple | null }) => {
const map = useMap();
if (!userLocation) return null;
return (
<button
type="button"
onClick={() => map.setView(userLocation, DEFAULT_ZOOM, { animate: true })}
className="btn btn-circle btn-sm bg-base-100 absolute top-2.5 right-2.5 z-[1000] shadow"
aria-label="Recenter on your location"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="h-4 w-4"
>
<circle cx="12" cy="12" r="3" />
<path d="M12 2v3M12 19v3M2 12h3M19 12h3" />
</svg>
</button>
);
};
const NearbyBreweryMap = ({
pins,
selectedId,
onSelect,
userLocation,
userLocationLabel,
}: NearbyBreweryMapProps) => (
<MapContainer
center={userLocation ?? [pins[0]?.latitude ?? 20, pins[0]?.longitude ?? 0]}
zoom={DEFAULT_ZOOM}
minZoom={MIN_ZOOM}
scrollWheelZoom={false}
className="min-h-[30rem] h-full w-full rounded-box relative z-0"
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<FitAndFocus pins={pins} userLocation={userLocation} selectedId={selectedId} />
<RecenterButton userLocation={userLocation} />
{userLocation && (
<CircleMarker
center={userLocation}
radius={6}
pathOptions={{
color: resolveThemeColor('--color-base-100', '#fff'),
weight: 2,
fillColor: resolveThemeColor('--color-primary', '#2b6cb0'),
fillOpacity: 1,
}}
>
<Popup>You are here &mdash; {userLocationLabel}</Popup>
</CircleMarker>
)}
{pins.map((pin) => (
<Marker
key={pin.id}
position={[pin.latitude, pin.longitude]}
icon={pinIcon(pin.id === selectedId)}
eventHandlers={{ click: () => onSelect(pin.id) }}
>
<Popup>
<p className="font-semibold font-serif">{pin.name}</p>
{pin.cityLabel && (
<p className="text-sm text-base-content/70">{pin.cityLabel}</p>
)}
<a href={`/breweries/${pin.id}`} className="link link-primary text-sm">
View brewery &rarr;
</a>
</Popup>
</Marker>
))}
</MapContainer>
);
export default NearbyBreweryMap;

View File

@@ -0,0 +1,6 @@
import type { SimplifiedBrewery } from '../../../breweries.server';
export interface BreweryWithDistance {
brewery: SimplifiedBrewery;
distanceMetres: number;
}