Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fa49164143 | ||
|
|
cf3c773f86 | ||
|
|
4b54c25943 | ||
|
|
e7645d1ba5 | ||
|
|
29b5f85952 | ||
|
|
c077c27720 | ||
|
|
e2fc7a8f15 | ||
|
|
355a5a841c | ||
|
|
96deab7d58 | ||
|
|
e9886361d2 | ||
|
|
8ebe461435 | ||
|
|
2002529137 | ||
|
|
bd7c8593d9 | ||
|
|
0c414680fd | ||
|
|
e211e1376d | ||
|
|
74418ca6b9 | ||
|
|
5df8c93420 | ||
|
|
ebf9c12446 | ||
|
|
ca4ddd2b12 | ||
|
|
dff3e210ab | ||
|
|
37bbda1da1 |
No files matched your search
+6
-4
@@ -736,7 +736,7 @@ async def get_schools(
|
||||
None, description="Filter by local authority", max_length=100
|
||||
),
|
||||
school_type: Optional[str] = Query(None, description="Filter by school type", max_length=100),
|
||||
phase: Optional[str] = Query(None, description="Filter by phase: primary, secondary, all-through", max_length=50),
|
||||
phase: Optional[str] = Query(None, description="Filter by phase: primary or secondary (grouped), or any GIAS phase name (exact)", max_length=50),
|
||||
postcode: Optional[str] = Query(None, description="Search near postcode", max_length=10),
|
||||
radius: float = Query(5.0, ge=0.1, le=5, description="Search radius in miles"),
|
||||
page: int = Query(1, ge=1, le=1000, description="Page number"),
|
||||
@@ -771,11 +771,13 @@ async def get_schools(
|
||||
|
||||
# Phase filter — uses PHASE_GROUPS so all-through/middle schools appear
|
||||
# in the correct phase(s) rather than being invisible to both filters.
|
||||
# Any other GIAS phase (nursery, 16 plus, middle deemed ...) is an exact
|
||||
# match. It must never fall through to no filter: the search page offers
|
||||
# every phase, and "Nursery" used to return the whole result set.
|
||||
if phase:
|
||||
phase_lower = phase.lower().replace("_", "-")
|
||||
allowed = PHASE_GROUPS.get(phase_lower)
|
||||
if allowed:
|
||||
df_latest = df_latest[df_latest["phase"].str.lower().isin(allowed)]
|
||||
allowed = PHASE_GROUPS.get(phase_lower, {phase_lower})
|
||||
df_latest = df_latest[df_latest["phase"].fillna("").str.lower().isin(allowed)]
|
||||
|
||||
# Secondary-specific filters (after phase filter)
|
||||
if gender:
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""The /api/schools phase filter.
|
||||
|
||||
The search page offers every GIAS phase, but the filter only knew the three
|
||||
grouped ones (primary, secondary, all-through). Anything else — nursery,
|
||||
16 plus, the middle-deemed phases — fell through to no filter at all, so
|
||||
"Nursery" returned the whole result set, mostly primaries.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
PHASES = {
|
||||
100001: "Nursery",
|
||||
100002: "Primary",
|
||||
100003: "Middle deemed primary",
|
||||
100004: "Secondary",
|
||||
100005: "Middle deemed secondary",
|
||||
100006: "16 plus",
|
||||
100007: "All-through",
|
||||
}
|
||||
|
||||
|
||||
def _schools_df() -> pd.DataFrame:
|
||||
base = {
|
||||
"local_authority": "Testshire",
|
||||
"school_type": "Academy",
|
||||
"address": "1 Test Street",
|
||||
"town": "Testtown",
|
||||
"postcode": "TS1 1AA",
|
||||
"religious_denomination": None,
|
||||
"age_range": "4-11",
|
||||
"has_sixth_form": None,
|
||||
"gender": "Mixed",
|
||||
"admissions_policy": None,
|
||||
"ofsted_grade": np.nan,
|
||||
"ofsted_date": None,
|
||||
"ofsted_framework": None,
|
||||
"latitude": 51.5,
|
||||
"longitude": -0.1,
|
||||
"year": 202425,
|
||||
"total_pupils": 300,
|
||||
"rwm_expected_pct": np.nan,
|
||||
"attainment_8_score": np.nan,
|
||||
}
|
||||
return pd.DataFrame([
|
||||
{**base, "urn": urn, "school_name": f"{phase} School", "phase": phase}
|
||||
for urn, phase in PHASES.items()
|
||||
])
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
from backend import app as app_module
|
||||
|
||||
monkeypatch.setattr(app_module, "load_latest_school_data", _schools_df)
|
||||
monkeypatch.setattr(app_module, "load_school_data", _schools_df)
|
||||
return TestClient(app_module.app, raise_server_exceptions=False)
|
||||
|
||||
|
||||
def _urns(client, phase):
|
||||
resp = client.get("/api/schools", params={"phase": phase})
|
||||
assert resp.status_code == 200, resp.text
|
||||
return sorted(s["urn"] for s in resp.json()["schools"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase, urn", [
|
||||
("nursery", 100001),
|
||||
("16 plus", 100006),
|
||||
("middle deemed primary", 100003),
|
||||
("middle deemed secondary", 100005),
|
||||
])
|
||||
def test_an_ungrouped_phase_matches_exactly(client, phase, urn):
|
||||
assert _urns(client, phase) == [urn]
|
||||
|
||||
|
||||
def test_grouped_phases_still_take_in_their_related_phases(client):
|
||||
assert _urns(client, "primary") == [100002, 100003, 100007]
|
||||
assert _urns(client, "secondary") == [100004, 100005, 100006, 100007]
|
||||
|
||||
|
||||
def test_an_unknown_phase_returns_nothing_rather_than_everything(client):
|
||||
assert _urns(client, "kindergarten") == []
|
||||
+165
-5
@@ -270,6 +270,34 @@ test('searching by name returns school results', async ({ page }) => {
|
||||
test('searching by postcode returns nearby schools', async ({ page }) => {
|
||||
await searchByName(page, 'B1 1BB');
|
||||
await expect(schoolLinks(page).first()).toBeVisible({ timeout: 15_000 });
|
||||
// A new postcode search starts at half a mile.
|
||||
await expect(page).toHaveURL(/[?&]radius=0\.5(&|$)/);
|
||||
await expect(page.getByRole('combobox', { name: 'Distance' })).toHaveValue('0.5');
|
||||
});
|
||||
|
||||
test('the phase filter switches straight from secondary to primary', async ({ page }) => {
|
||||
// The phase options once came from the result set, which the phase filter
|
||||
// had already narrowed — so with secondary chosen, primary was not offered.
|
||||
await page.goto('/?search=school&phase=secondary');
|
||||
const phase = page.getByRole('combobox', { name: 'Phase' });
|
||||
await expect(phase).toHaveValue('secondary', { timeout: 15_000 });
|
||||
await phase.selectOption('primary');
|
||||
await expect(page).toHaveURL(/[?&]phase=primary(&|$)/);
|
||||
await expect(phase).toHaveValue('primary');
|
||||
});
|
||||
|
||||
test('a phase outside primary/secondary filters to that phase, not to everything', async ({ page }) => {
|
||||
// The search page offers every GIAS phase, but the API only knew the grouped
|
||||
// ones and silently dropped the rest — so "Nursery" returned primaries.
|
||||
for (const phase of ['Nursery', '16 plus']) {
|
||||
const res = await page.request.get(
|
||||
`/api/schools?phase=${encodeURIComponent(phase.toLowerCase())}&page_size=50`);
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const phases = new Set(
|
||||
((await res.json()).schools ?? []).map((s: { phase?: string }) => s.phase));
|
||||
expect([...phases], `phase=${phase} returned other phases`)
|
||||
.toEqual(phases.size ? [phase] : []);
|
||||
}
|
||||
});
|
||||
|
||||
test('a report-card school shows a Report Card badge in search results, not its old grade', async ({ page }) => {
|
||||
@@ -513,6 +541,13 @@ test('results map fullscreen falls back to an overlay on iOS', async ({ page })
|
||||
await expect(openFs).toBeVisible();
|
||||
});
|
||||
|
||||
/*
|
||||
* A postcode search with a list long enough to scroll. The default half mile
|
||||
* finds two schools around B1 1BB, so the page ends before the toolbar has
|
||||
* anything to stay pinned over; the scroll tests ask for a mile.
|
||||
*/
|
||||
const LONG_LIST = '/?postcode=B1%201BB&radius=1';
|
||||
|
||||
/*
|
||||
* The results toolbar: search, filters and the List/Map switch pinned under
|
||||
* the header, so none of them scroll away with the results.
|
||||
@@ -523,7 +558,7 @@ test('results map fullscreen falls back to an overlay on iOS', async ({ page })
|
||||
*/
|
||||
test('the results toolbar stays pinned with its List/Map switch', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await searchByName(page, 'B1 1BB');
|
||||
await page.goto(LONG_LIST);
|
||||
await expect(schoolLinks(page).first()).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
const view = page.getByRole('group', { name: 'Results view' });
|
||||
@@ -547,6 +582,38 @@ test('the results toolbar stays pinned with its List/Map switch', async ({ page
|
||||
.toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
/*
|
||||
* The toolbar's line count is set by the screen width, never by the results.
|
||||
* It once wrapped wherever it ran out of room, and the List/Map switch only
|
||||
* appears when there are results — so the same search took two lines with
|
||||
* results and one without.
|
||||
*/
|
||||
test('the results toolbar keeps its line count whether or not there are results', async ({ page }) => {
|
||||
const withResults = LONG_LIST;
|
||||
// No school type matches this, so the same search returns nothing.
|
||||
const without = `${withResults}&school_type=no-such-type`;
|
||||
|
||||
const lines = async (url: string) => {
|
||||
await page.goto(url);
|
||||
// By label: the input is a combobox when autosuggest is on.
|
||||
const input = page.getByLabel('School name or postcode', { exact: true });
|
||||
const filters = page.getByRole('group', { name: 'Filters' });
|
||||
await expect(filters).toBeVisible({ timeout: 15_000 });
|
||||
const a = (await input.boundingBox())!;
|
||||
const b = (await filters.boundingBox())!;
|
||||
return b.y >= a.y + a.height ? 2 : 1;
|
||||
};
|
||||
const view = page.getByRole('group', { name: 'Results view' });
|
||||
|
||||
for (const [width, expected] of [[1400, 1], [1100, 2]] as const) {
|
||||
await page.setViewportSize({ width, height: 800 });
|
||||
expect(await lines(withResults), `${width}px with results`).toBe(expected);
|
||||
await expect(view).toBeVisible();
|
||||
expect(await lines(without), `${width}px without results`).toBe(expected);
|
||||
await expect(view).toHaveCount(0);
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* Desktop opens a postcode search on the map (mockup B): the list in a pane on
|
||||
* the left, the map filling the rest of the screen, and a card on the map for
|
||||
@@ -561,8 +628,18 @@ test('a desktop postcode search opens on the map with the list beside it', async
|
||||
const pane = page.locator('[class*="mapListPane"]');
|
||||
const card = pane.locator('[data-urn]').first();
|
||||
await expect(card).toBeVisible({ timeout: 15_000 });
|
||||
// The list view's own row, not a cut-down card: it carries the same View
|
||||
// link and Compare button.
|
||||
await expect(card.getByRole('link', { name: 'View', exact: true })).toBeVisible();
|
||||
await expect(card.getByRole('button', { name: /Compar/ })).toBeVisible();
|
||||
await expect(page.locator('.sc-pin').first()).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// The count and the sort share one line at the top of the list.
|
||||
const heading = await pane.getByRole('heading', { level: 2 }).boundingBox();
|
||||
const sort = await pane.getByRole('combobox').boundingBox();
|
||||
expect(Math.abs((heading!.y + heading!.height / 2) - (sort!.y + sort!.height / 2)))
|
||||
.toBeLessThan(8);
|
||||
|
||||
// The split runs to the bottom of the screen rather than stopping short.
|
||||
const split = await page.locator('[class*="mapViewContainer"]').boundingBox();
|
||||
expect(split!.y + split!.height).toBeGreaterThan(800 - 40);
|
||||
@@ -573,14 +650,34 @@ test('a desktop postcode search opens on the map with the list beside it', async
|
||||
const name = (await card.locator('a').first().innerText()).trim();
|
||||
await card.click({ position: { x: 6, y: 6 } });
|
||||
await expect(page.locator('.sc-pin--selected')).toHaveCount(1);
|
||||
// Leaflet crossfades popups for 200ms, so two exist until the old one goes.
|
||||
await expect(page.locator('.sc-popup')).toHaveCount(1);
|
||||
await expect(page.locator('.sc-popup')).toContainText(name);
|
||||
// The card's View link is drawn like the list's, not in Leaflet's link blue.
|
||||
// Polled, because .btn transitions its colour.
|
||||
const colour = (l: Locator) => l.evaluate(el => getComputedStyle(el).color);
|
||||
const listViewColour = await colour(card.getByRole('link', { name: 'View', exact: true }));
|
||||
await expect.poll(() => colour(page.locator('.sc-popup').getByRole('link', { name: 'View', exact: true })))
|
||||
.toBe(listViewColour);
|
||||
|
||||
// And from the keyboard: each row has a "Show … on the map" button that
|
||||
// appears on focus.
|
||||
const second = pane.locator('[data-urn]').nth(1);
|
||||
const secondName = (await second.locator('a').first().innerText()).trim();
|
||||
const show = second.getByRole('button', { name: `Show ${secondName} on the map` });
|
||||
await show.focus();
|
||||
await expect(show).toBeVisible();
|
||||
await page.keyboard.press('Enter');
|
||||
await expect(show).toHaveAttribute('aria-pressed', 'true');
|
||||
await expect(page.locator('.sc-popup')).toHaveCount(1);
|
||||
await expect(page.locator('.sc-popup')).toContainText(secondName);
|
||||
});
|
||||
|
||||
// 402 is the iPhone 17, where the toolbar overflowed (see below).
|
||||
for (const width of [360, 390, 402, 430]) {
|
||||
test(`a phone opens on the map, with the list a tap away, at ${width}px`, async ({ page }) => {
|
||||
await page.setViewportSize({ width, height: 800 });
|
||||
await searchByName(page, 'B1 1BB');
|
||||
await page.goto(LONG_LIST);
|
||||
|
||||
// On the map, with the floating button offering the list, clear of the
|
||||
// bottom tab bar.
|
||||
@@ -615,12 +712,13 @@ for (const width of [360, 390, 402, 430]) {
|
||||
// scrollWidth alone cannot see this page's overflow: .main clips on x, so
|
||||
// the search summary ran 40px off an iPhone 17 screen with scrollWidth
|
||||
// still equal to the viewport. Measure the toolbar's own edges instead;
|
||||
// the controls row scrolls by design, so only its box is held to the edge.
|
||||
// the applied-filter chips scroll by design, so only their line's box is
|
||||
// held to the edge.
|
||||
const offscreen = await page.evaluate(() => {
|
||||
const toolbar = document.querySelector('[class*="resultsToolbar"]');
|
||||
return [...(toolbar?.querySelectorAll('*') ?? [])]
|
||||
.filter((el) => (el as HTMLElement).offsetParent
|
||||
&& !el.parentElement?.closest('[class*="controlsRow"]'))
|
||||
&& !el.parentElement?.closest('[class*="chipsLine"]'))
|
||||
.map((el) => ({ el: (el.className?.toString() || el.tagName).slice(0, 40),
|
||||
right: Math.round(el.getBoundingClientRect().right) }))
|
||||
.filter((o) => o.right > window.innerWidth);
|
||||
@@ -629,7 +727,8 @@ for (const width of [360, 390, 402, 430]) {
|
||||
const small = await page.evaluate(() => {
|
||||
const toolbar = document.querySelector('[class*="resultsToolbar"]');
|
||||
const fabEl = document.querySelector('[class*="viewFab"]');
|
||||
return [...(toolbar?.querySelectorAll('a, button, input, select') ?? []), fabEl]
|
||||
const closeEl = document.querySelector('[class*="closeSheetBtn"]');
|
||||
return [...(toolbar?.querySelectorAll('a, button, input, select') ?? []), fabEl, closeEl]
|
||||
.filter((el): el is HTMLElement => !!el && !!(el as HTMLElement).offsetParent)
|
||||
.map((el) => ({ t: el.innerText?.trim().slice(0, 24) || el.getAttribute('aria-label'),
|
||||
w: el.getBoundingClientRect().width, h: el.getBoundingClientRect().height }))
|
||||
@@ -651,6 +750,67 @@ for (const width of [360, 390, 402, 430]) {
|
||||
});
|
||||
}
|
||||
|
||||
/*
|
||||
* Phones filter through one Filters button and a sheet with every filter in
|
||||
* it. The row it replaced scrolled sideways with "More filters" first, so
|
||||
* phase showed only in part, school type not at all, and the panel "More
|
||||
* filters" opened held neither.
|
||||
*/
|
||||
test('a phone filters through one sheet, and sees what it applied as chips', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goto(LONG_LIST);
|
||||
const trigger = page.getByRole('button', { name: 'Filters', exact: true });
|
||||
await expect(trigger).toBeInViewport({ timeout: 15_000 });
|
||||
// The desktop row is gone at this width: no phase select until the sheet.
|
||||
await expect(page.getByRole('combobox', { name: 'Phase', exact: true })).toHaveCount(0);
|
||||
|
||||
await trigger.click();
|
||||
const sheet = page.getByRole('dialog', { name: 'Filters' });
|
||||
await expect(sheet).toBeVisible();
|
||||
await expect(sheet.getByRole('radio', { name: 'Within 1 mile' })).toBeChecked();
|
||||
for (const name of ['Phase', 'School type', 'Local authority']) {
|
||||
await expect(sheet.getByRole('combobox', { name, exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
// A change applies at once, and the sheet stays open for the next one.
|
||||
await sheet.getByRole('combobox', { name: 'Phase', exact: true }).selectOption('primary');
|
||||
await page.waitForURL(/[?&]phase=primary(&|$)/);
|
||||
await expect(sheet).toBeVisible();
|
||||
const show = sheet.getByRole('button', { name: /^(Show [\d,]+ schools?|No schools match)$/ });
|
||||
await expect(show).toBeVisible();
|
||||
|
||||
// MOBILE.md: the sheet clears the bottom tab bar, and its targets are 44px.
|
||||
// It slides up over 0.3s, so poll for where it comes to rest.
|
||||
await expect.poll(async () => {
|
||||
const box = (await show.boundingBox())!;
|
||||
return Math.round(box.y + box.height);
|
||||
}).toBeLessThanOrEqual(844);
|
||||
const small = await sheet.evaluate((el) =>
|
||||
[...el.querySelectorAll('button, select, label:has(input)')]
|
||||
.filter((n): n is HTMLElement => !!(n as HTMLElement).offsetParent)
|
||||
.map((n) => ({ t: n.innerText?.trim().slice(0, 24) || n.getAttribute('aria-label'),
|
||||
w: n.getBoundingClientRect().width, h: n.getBoundingClientRect().height }))
|
||||
.filter((o) => o.w < 44 || o.h < 44));
|
||||
expect(small).toEqual([]);
|
||||
|
||||
await show.click();
|
||||
await expect(sheet).toBeHidden();
|
||||
|
||||
// What was applied shows under the search, counted on the button, and comes
|
||||
// off with a tap, keeping the search.
|
||||
await expect(page.getByRole('button', { name: 'Filters, 1 applied' })).toBeInViewport();
|
||||
const chip = page.getByRole('group', { name: 'Applied filters' })
|
||||
.getByRole('button', { name: 'Remove filter: Primary' });
|
||||
await expect(chip).toBeInViewport();
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth))
|
||||
.toBe(0);
|
||||
await chip.click();
|
||||
await expect(page).not.toHaveURL(/[?&]phase=/);
|
||||
await expect(page).toHaveURL(/[?&]postcode=B1(%20|\+)1BB/);
|
||||
await expect(page.getByRole('group', { name: 'Applied filters' })).toHaveCount(0);
|
||||
await expect(trigger).toBeInViewport();
|
||||
});
|
||||
|
||||
test('comparing two schools shows the parent-first sections side by side', async ({ page }) => {
|
||||
// Two same-phase (pure primary) schools so both stay on one tab.
|
||||
const [urn0, urn1] = await twoPrimaryUrns(page);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { render, screen, within } from '@testing-library/react';
|
||||
import { FilterBar } from '@/components/FilterBar';
|
||||
|
||||
let searchParams = new URLSearchParams();
|
||||
jest.mock('next/navigation', () => ({
|
||||
useRouter: () => ({ push: jest.fn(), replace: jest.fn(), prefetch: jest.fn() }),
|
||||
usePathname: () => '/',
|
||||
useSearchParams: () => searchParams,
|
||||
}));
|
||||
|
||||
const FILTERS = {
|
||||
local_authorities: [], school_types: [], years: [],
|
||||
phases: ['Primary', 'Secondary', 'All-through'],
|
||||
genders: [], admissions_policies: [],
|
||||
};
|
||||
|
||||
/**
|
||||
* The phase options must not come from the result set. The backend scopes its
|
||||
* result filters to the schools it returns, and it applies the phase filter
|
||||
* first — so with "secondary" chosen the scoped list holds only secondary-ish
|
||||
* phases, and switching to primary meant going back to "Any phase" first.
|
||||
*/
|
||||
describe('FilterBar phase options', () => {
|
||||
it('offers every phase while a phase filter narrows the results', () => {
|
||||
searchParams = new URLSearchParams('search=hampton&phase=secondary');
|
||||
render(
|
||||
<FilterBar
|
||||
filters={FILTERS}
|
||||
resultFilters={{
|
||||
local_authorities: [], school_types: [],
|
||||
phases: ['Secondary', 'All-through'],
|
||||
genders: [], admissions_policies: [],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
const phase = screen.getByRole('combobox', { name: 'Phase' });
|
||||
expect(within(phase).getByRole('option', { name: 'Primary' })).toBeInTheDocument();
|
||||
expect(phase).toHaveValue('secondary');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { FilterBar } from '@/components/FilterBar';
|
||||
|
||||
const push = jest.fn();
|
||||
let searchParams = new URLSearchParams();
|
||||
jest.mock('next/navigation', () => ({
|
||||
useRouter: () => ({ push, replace: jest.fn(), prefetch: jest.fn() }),
|
||||
usePathname: () => '/',
|
||||
useSearchParams: () => searchParams,
|
||||
}));
|
||||
|
||||
const FILTERS = {
|
||||
local_authorities: [], school_types: [], years: [], phases: [],
|
||||
genders: [], admissions_policies: [],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
push.mockClear();
|
||||
searchParams = new URLSearchParams();
|
||||
});
|
||||
|
||||
describe('FilterBar default distance', () => {
|
||||
it('searches a new postcode within half a mile', async () => {
|
||||
render(<FilterBar filters={FILTERS} />);
|
||||
await userEvent.type(screen.getByPlaceholderText(/School name or postcode/i), 'SW19 6AR{Enter}');
|
||||
await waitFor(() => expect(push).toHaveBeenCalledWith(expect.stringContaining('radius=0.5')));
|
||||
});
|
||||
|
||||
it('shows half a mile when the URL carries a postcode but no radius', () => {
|
||||
searchParams = new URLSearchParams('postcode=SW196AR');
|
||||
render(<FilterBar filters={FILTERS} />);
|
||||
expect(screen.getByRole('combobox', { name: 'Distance' })).toHaveValue('0.5');
|
||||
});
|
||||
|
||||
it('keeps a distance the user already chose', async () => {
|
||||
searchParams = new URLSearchParams('postcode=SW196AR&radius=3');
|
||||
render(<FilterBar filters={FILTERS} />);
|
||||
expect(screen.getByRole('combobox', { name: 'Distance' })).toHaveValue('3');
|
||||
});
|
||||
});
|
||||
|
||||
describe('FilterBar distance options', () => {
|
||||
it('offers a quarter mile without making it the default', () => {
|
||||
searchParams = new URLSearchParams('postcode=SW196AR');
|
||||
render(<FilterBar filters={FILTERS} />);
|
||||
const distance = screen.getByRole('combobox', { name: 'Distance' });
|
||||
expect([...(distance as HTMLSelectElement).options].map(o => o.value)).toEqual(['0.25', '0.5', '1', '3', '5']);
|
||||
expect(distance).toHaveValue('0.5');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import { FilterBar } from '@/components/FilterBar';
|
||||
|
||||
/*
|
||||
* Phones filter through one "Filters" button and a bottom sheet holding every
|
||||
* filter, rather than a sideways-scrolling row whose later chips (phase, type)
|
||||
* sat off-screen beside a "More filters" panel that did not contain them.
|
||||
* Which markup shows at which width is CSS and invisible to jsdom; these pin
|
||||
* the behaviour and the accessible names.
|
||||
*/
|
||||
|
||||
let params = new URLSearchParams('postcode=SW196AR&radius=1');
|
||||
const push = jest.fn();
|
||||
jest.mock('next/navigation', () => ({
|
||||
useSearchParams: () => params,
|
||||
usePathname: () => '/',
|
||||
useRouter: () => ({ push, replace: jest.fn(), prefetch: jest.fn() }),
|
||||
}));
|
||||
jest.mock('@/lib/analytics', () => ({ track: jest.fn() }));
|
||||
|
||||
const filters = {
|
||||
local_authorities: ['Wandsworth', 'Merton'], school_types: ['Community school'], years: [],
|
||||
phases: ['Primary', 'Secondary'], genders: ['Girls', 'Mixed'], admissions_policies: [],
|
||||
};
|
||||
|
||||
const pushedParams = () => new URLSearchParams(push.mock.calls.at(-1)![0].split('?')[1]);
|
||||
|
||||
beforeEach(() => {
|
||||
params = new URLSearchParams('postcode=SW196AR&radius=1');
|
||||
push.mockClear();
|
||||
});
|
||||
|
||||
describe('the phone Filters button', () => {
|
||||
it('sits beside the folded search summary', () => {
|
||||
render(<FilterBar filters={filters} />);
|
||||
const summary = screen.getByRole('button', { name: /Edit search/ });
|
||||
expect(summary.parentElement).toContainElement(screen.getByRole('button', { name: 'Filters' }));
|
||||
});
|
||||
|
||||
it('counts every applied filter, phase and type included', () => {
|
||||
params = new URLSearchParams('postcode=SW196AR&radius=1&phase=primary&school_type=Community+school');
|
||||
render(<FilterBar filters={filters} />);
|
||||
expect(screen.getByRole('button', { name: 'Filters, 2 applied' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is still offered before anything has been searched', () => {
|
||||
params = new URLSearchParams('local_authority=Wandsworth');
|
||||
render(<FilterBar filters={filters} />);
|
||||
expect(screen.getByRole('button', { name: 'Filters, 1 applied' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('stays out of the hero', () => {
|
||||
render(<FilterBar filters={filters} isHero />);
|
||||
expect(screen.queryByRole('button', { name: /^Filters/ })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the filter sheet', () => {
|
||||
const openSheet = () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Filters/ }));
|
||||
return screen.getByRole('dialog', { name: 'Filters' });
|
||||
};
|
||||
|
||||
it('holds every filter in one place', () => {
|
||||
render(<FilterBar filters={filters} />);
|
||||
const sheet = openSheet();
|
||||
expect(within(sheet).getByRole('radiogroup', { name: 'Distance' })).toBeInTheDocument();
|
||||
for (const name of ['Phase', 'School type', 'Local authority']) {
|
||||
expect(within(sheet).getByRole('combobox', { name })).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows the secondary-only filters once they apply', () => {
|
||||
params = new URLSearchParams('postcode=SW196AR&radius=1&phase=secondary');
|
||||
render(<FilterBar filters={filters} />);
|
||||
const sheet = openSheet();
|
||||
for (const name of ['Gender', 'Sixth form']) {
|
||||
expect(within(sheet).getByRole('combobox', { name })).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it('offers distance only for a postcode search', () => {
|
||||
params = new URLSearchParams('search=southmead');
|
||||
render(<FilterBar filters={filters} />);
|
||||
expect(within(openSheet()).queryByRole('radiogroup', { name: 'Distance' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('changes the distance', () => {
|
||||
render(<FilterBar filters={filters} />);
|
||||
const distance = within(openSheet()).getByRole('radiogroup', { name: 'Distance' });
|
||||
expect(within(distance).getByRole('radio', { name: 'Within 1 mile' })).toBeChecked();
|
||||
fireEvent.click(within(distance).getByRole('radio', { name: 'Within 3 miles' }));
|
||||
expect(pushedParams().get('radius')).toBe('3');
|
||||
});
|
||||
|
||||
it('applies a change straight away and stays open for the next one', () => {
|
||||
render(<FilterBar filters={filters} />);
|
||||
const sheet = openSheet();
|
||||
fireEvent.change(within(sheet).getByRole('combobox', { name: 'Phase' }), { target: { value: 'primary' } });
|
||||
expect(pushedParams().get('phase')).toBe('primary');
|
||||
expect(screen.getByRole('dialog', { name: 'Filters' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('closes on the results button, which gives the count', () => {
|
||||
render(<FilterBar filters={filters} resultCount={12} />);
|
||||
fireEvent.click(within(openSheet()).getByRole('button', { name: 'Show 12 schools' }));
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('says so when nothing matches', () => {
|
||||
render(<FilterBar filters={filters} resultCount={0} />);
|
||||
expect(within(openSheet()).getByRole('button', { name: 'No schools match' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clears the filters but keeps the search', () => {
|
||||
params = new URLSearchParams('postcode=SW196AR&radius=1&phase=primary&local_authority=Wandsworth');
|
||||
render(<FilterBar filters={filters} />);
|
||||
fireEvent.click(within(openSheet()).getByRole('button', { name: 'Clear all' }));
|
||||
const next = pushedParams();
|
||||
expect(next.get('phase')).toBeNull();
|
||||
expect(next.get('local_authority')).toBeNull();
|
||||
expect(next.get('postcode')).toBe('SW196AR');
|
||||
expect(next.get('radius')).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the applied-filter chips', () => {
|
||||
it('appear only when something is applied', () => {
|
||||
render(<FilterBar filters={filters} />);
|
||||
expect(screen.queryByRole('group', { name: 'Applied filters' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('name each filter by its label and remove it on tap', () => {
|
||||
params = new URLSearchParams('postcode=SW196AR&radius=1&phase=primary&gender=girls&has_sixth_form=no');
|
||||
render(<FilterBar filters={filters} />);
|
||||
const chips = screen.getByRole('group', { name: 'Applied filters' });
|
||||
for (const label of ['Primary', 'Girls', 'Without sixth form']) {
|
||||
expect(within(chips).getByRole('button', { name: `Remove filter: ${label}` })).toBeInTheDocument();
|
||||
}
|
||||
fireEvent.click(within(chips).getByRole('button', { name: 'Remove filter: Primary' }));
|
||||
const next = pushedParams();
|
||||
expect(next.get('phase')).toBeNull();
|
||||
expect(next.get('gender')).toBe('girls');
|
||||
expect(next.get('postcode')).toBe('SW196AR');
|
||||
});
|
||||
|
||||
it('carry a Clear all that keeps the search', () => {
|
||||
params = new URLSearchParams('search=southmead&school_type=Community+school');
|
||||
render(<FilterBar filters={filters} />);
|
||||
fireEvent.click(within(screen.getByRole('group', { name: 'Applied filters' }))
|
||||
.getByRole('button', { name: 'Clear all' }));
|
||||
const next = pushedParams();
|
||||
expect(next.get('school_type')).toBeNull();
|
||||
expect(next.get('search')).toBe('southmead');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { act, fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import { FilterBar } from '@/components/FilterBar';
|
||||
|
||||
/*
|
||||
* While a filter change is navigating, the sheet's controls stay enabled: a
|
||||
* control disabled under the user's focus drops it to <body>, and a keyboard or
|
||||
* screen-reader user is thrown out of the sheet after every change. A second
|
||||
* change made before the first lands must build on the first, not on the URL
|
||||
* useSearchParams still reports.
|
||||
*/
|
||||
|
||||
// Every transition stays pending, as a slow server render would.
|
||||
jest.mock('react', () => ({
|
||||
...jest.requireActual('react'),
|
||||
useTransition: () => [true, (fn: () => void) => fn()],
|
||||
}));
|
||||
|
||||
const params = new URLSearchParams('postcode=SW196AR&radius=1');
|
||||
const push = jest.fn();
|
||||
jest.mock('next/navigation', () => ({
|
||||
useSearchParams: () => params,
|
||||
usePathname: () => '/',
|
||||
useRouter: () => ({ push, replace: jest.fn(), prefetch: jest.fn() }),
|
||||
}));
|
||||
jest.mock('@/lib/analytics', () => ({ track: jest.fn() }));
|
||||
|
||||
const filters = {
|
||||
local_authorities: ['Wandsworth'], school_types: ['Community school'], years: [],
|
||||
phases: ['Primary', 'Secondary'], genders: [], admissions_policies: [],
|
||||
};
|
||||
|
||||
const pushedParams = () => new URLSearchParams(push.mock.calls.at(-1)![0].split('?')[1]);
|
||||
|
||||
const openSheet = () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Filters/ }));
|
||||
return screen.getByRole('dialog', { name: 'Filters' });
|
||||
};
|
||||
|
||||
beforeEach(() => push.mockClear());
|
||||
|
||||
it('keeps the sheet usable, and says it is busy, while a change lands', () => {
|
||||
render(<FilterBar filters={filters} />);
|
||||
const sheet = openSheet();
|
||||
for (const name of ['Phase', 'School type', 'Local authority']) {
|
||||
expect(within(sheet).getByRole('combobox', { name })).toBeEnabled();
|
||||
}
|
||||
expect(within(sheet).getByRole('radio', { name: 'Within 3 miles' })).toBeEnabled();
|
||||
expect(sheet.querySelector('[aria-busy="true"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('builds a second change on the first, not on the URL it has not reached', () => {
|
||||
render(<FilterBar filters={filters} />);
|
||||
const sheet = openSheet();
|
||||
fireEvent.change(within(sheet).getByRole('combobox', { name: 'Phase' }), { target: { value: 'primary' } });
|
||||
fireEvent.change(within(sheet).getByRole('combobox', { name: 'School type' }),
|
||||
{ target: { value: 'Community school' } });
|
||||
const next = pushedParams();
|
||||
expect(next.get('phase')).toBe('primary');
|
||||
expect(next.get('school_type')).toBe('Community school');
|
||||
expect(next.get('postcode')).toBe('SW196AR');
|
||||
});
|
||||
|
||||
describe('a screen that widens past phone width', () => {
|
||||
let listeners: ((e: { matches: boolean }) => void)[] = [];
|
||||
beforeEach(() => {
|
||||
listeners = [];
|
||||
window.matchMedia = jest.fn().mockImplementation((query: string) => ({
|
||||
matches: true, media: query,
|
||||
addEventListener: (_: string, l: (e: { matches: boolean }) => void) => listeners.push(l),
|
||||
removeEventListener: jest.fn(),
|
||||
}));
|
||||
});
|
||||
|
||||
it('closes the sheet, leaving the desktop row as the only filters', () => {
|
||||
render(<FilterBar filters={filters} />);
|
||||
openSheet();
|
||||
act(() => listeners.forEach((l) => l({ matches: false })));
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,10 @@ jest.mock('@/lib/api', () => ({
|
||||
fetchNationalAverages: jest.fn(async () => ({})),
|
||||
fetchLAaverages: jest.fn(async () => ({ secondary: { attainment_8_by_la: {} } })),
|
||||
}));
|
||||
jest.mock('@/components/FilterBar', () => ({ FilterBar: () => null }));
|
||||
// Renders only the List/Map switch HomeView hands it, which lives in its row.
|
||||
jest.mock('@/components/FilterBar', () => ({
|
||||
FilterBar: ({ viewSwitch }: { viewSwitch?: unknown }) => viewSwitch || null,
|
||||
}));
|
||||
jest.mock('@/components/SchoolRow', () => ({ SchoolRow: ({ school }: {school: School}) => <div>{school.school_name}</div> }));
|
||||
jest.mock('@/components/SchoolMap', () => ({ SchoolMap: ({ schools }: {schools: School[]}) => <div data-testid="map">{schools.map(s => s.school_name).join(',')}</div> }));
|
||||
|
||||
|
||||
@@ -24,7 +24,10 @@ jest.mock('@/lib/api', () => ({
|
||||
fetchNationalAverages: jest.fn(),
|
||||
fetchLAaverages: jest.fn(async () => ({ secondary: { attainment_8_by_la: {} } })),
|
||||
}));
|
||||
jest.mock('@/components/FilterBar', () => ({ FilterBar: () => null }));
|
||||
// Renders only the List/Map switch HomeView hands it, which lives in its row.
|
||||
jest.mock('@/components/FilterBar', () => ({
|
||||
FilterBar: ({ viewSwitch }: { viewSwitch?: unknown }) => viewSwitch || null,
|
||||
}));
|
||||
jest.mock('@/components/SchoolMap', () => ({
|
||||
SchoolMap: ({ selectedUrn, radiusMiles, onMarkerClick, schools }: {
|
||||
selectedUrn: number | null; radiusMiles?: number;
|
||||
@@ -94,7 +97,8 @@ it('lists a name search, which has no map', async () => {
|
||||
|
||||
it('puts the count and the sort in the list beside the map, once', async () => {
|
||||
await renderMap();
|
||||
expect(screen.getAllByRole('heading', { name: /3 schools within 1.0 miles of SW196AR/ })).toHaveLength(1);
|
||||
// Short beside the map, so it shares one line with the sort.
|
||||
expect(screen.getAllByRole('heading', { name: '3 schools within 1 mile' })).toHaveLength(1);
|
||||
expect(screen.getAllByRole('combobox')).toHaveLength(1);
|
||||
});
|
||||
|
||||
@@ -104,11 +108,11 @@ it('selects the pin from the card, and the card from the pin', async () => {
|
||||
|
||||
fireEvent.click(within(card(1)).getByText(/pupils/));
|
||||
expect(screen.getByTestId('map')).toHaveAttribute('data-selected', '1');
|
||||
expect(card(1).className).toMatch(/compactItemSelected/);
|
||||
expect(card(1).className).toMatch(/mapRowSelected/);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'pin' }));
|
||||
expect(card(2).className).toMatch(/compactItemSelected/);
|
||||
expect(card(1).className).not.toMatch(/compactItemSelected/);
|
||||
expect(card(2).className).toMatch(/mapRowSelected/);
|
||||
expect(card(1).className).not.toMatch(/mapRowSelected/);
|
||||
});
|
||||
|
||||
it('clicking a card\'s link or button does not also select it', async () => {
|
||||
@@ -121,8 +125,9 @@ it('clicking a card\'s link or button does not also select it', async () => {
|
||||
it('shows the England comparison for mainstream schools only, and never a placeholder 0%', async () => {
|
||||
const { container } = await renderMap();
|
||||
const card = (urn: number) => container.querySelector(`[data-urn="${urn}"]`) as HTMLElement;
|
||||
expect(card(2)).toHaveTextContent('52% RWM -10 pts · 269 pupils');
|
||||
expect(card(3)).toHaveTextContent('62 pupils');
|
||||
expect(card(2)).toHaveTextContent('52%Reading, Writing & Maths-10 pts vs national');
|
||||
expect(card(2)).toHaveTextContent('269pupils');
|
||||
expect(card(3)).toHaveTextContent('62pupils');
|
||||
expect(card(3)).not.toHaveTextContent(/%|pts/);
|
||||
});
|
||||
|
||||
@@ -152,3 +157,39 @@ it('builds no list cards on a phone, where the pane is hidden', async () => {
|
||||
// The count stays: it is the pane's heading, shown above the map.
|
||||
expect(screen.getByRole('heading', { name: /3 schools within/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('draws the list view\'s own row beside the map, with the same content', async () => {
|
||||
const { container } = await renderMap();
|
||||
const beside = container.querySelector('[data-urn="2"] > [class~="row"]')!.textContent;
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'List' }));
|
||||
const row = screen.getByRole('link', { name: 'Southmead Primary School' }).closest('[class~="row"]')!;
|
||||
expect(row.parentElement?.className).toMatch(/schoolList/);
|
||||
expect(row.textContent).toBe(beside);
|
||||
});
|
||||
|
||||
it('lets a keyboard pick a pin from the list, with a real button', async () => {
|
||||
await renderMap();
|
||||
const show = screen.getByRole('button', { name: 'Show Southmead Primary School on the map' });
|
||||
expect(show).toHaveAttribute('aria-pressed', 'false');
|
||||
fireEvent.click(show);
|
||||
expect(screen.getByTestId('map')).toHaveAttribute('data-selected', '2');
|
||||
expect(show).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
it('keeps the postcode in the heading in list view, where there is room', async () => {
|
||||
await renderMap();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'List' }));
|
||||
expect(screen.getByRole('heading', { name: '3 schools within 1 mile of SW196AR' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('draws and names a quarter-mile search as 0.25, not rounded to 0.3', async () => {
|
||||
params = new URLSearchParams('postcode=SW196AR&radius=0.25');
|
||||
const quarter = { ...results(), location_info: { postcode: 'SW196AR', radius: 0.25 * 1.60934, coordinates: [51.42, -0.21] } } as SchoolsResponse;
|
||||
render(<HomeView initialSchools={quarter} filters={filters} />);
|
||||
await act(async () => {});
|
||||
expect(screen.getByTestId('map')).toHaveAttribute('data-radius', '0.25');
|
||||
expect(screen.getByRole('heading', { name: '3 schools within 0.25 miles' })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'List' }));
|
||||
expect(screen.getByRole('heading', { name: '3 schools within 0.25 miles of SW196AR' })).toBeInTheDocument();
|
||||
});
|
||||
@@ -105,11 +105,21 @@ describe('the toolbar filters', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('the phone filter row', () => {
|
||||
describe('the phone chips line', () => {
|
||||
it('drops its "more this way" fade when nothing is left to scroll', () => {
|
||||
params = new URLSearchParams('postcode=SW196AR&radius=1&phase=primary');
|
||||
render(<FilterBar filters={filters} />);
|
||||
// jsdom lays nothing out, so the row reads as not overflowing at all.
|
||||
expect(screen.getByRole('group', { name: 'Filters' }).className).toMatch(/controlsAtEnd/);
|
||||
// jsdom lays nothing out, so the line reads as not overflowing at all.
|
||||
const line = screen.getByRole('group', { name: 'Applied filters' }).parentElement!;
|
||||
expect(line.className).toMatch(/controlsAtEnd/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the phone filter sheet', () => {
|
||||
it('offers the results total', () => {
|
||||
render(<HomeView initialSchools={results()} filters={filters} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Filters' }));
|
||||
expect(screen.getByRole('button', { name: 'Show 1 school' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
/*
|
||||
* SchoolRow and SecondarySchoolRow switch to their narrow layout with a
|
||||
* container query on a `results` container, not a media query, because the
|
||||
* same row fills the phone list and the narrow list beside the desktop map.
|
||||
* Outside a `results` container the query never matches and the row keeps its
|
||||
* wide layout on a phone, a silent regression rather than an error.
|
||||
*
|
||||
* HomeView provides the container on every list it renders the rows into.
|
||||
* Anything else that starts rendering them must do the same; this fails so
|
||||
* that the person adding it reads this first.
|
||||
*/
|
||||
|
||||
const ROOT = path.join(__dirname, '..', '..');
|
||||
const DIRS = ['app', 'components', 'lib'];
|
||||
const ROW_IMPORT = /from\s+['"][^'"]*\/(SchoolRow|SecondarySchoolRow)['"]/;
|
||||
|
||||
function sources(dir: string): string[] {
|
||||
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) return entry.name === 'node_modules' ? [] : sources(full);
|
||||
return /\.tsx?$/.test(entry.name) ? [full] : [];
|
||||
});
|
||||
}
|
||||
|
||||
it('renders the results rows only where a `results` container is provided', () => {
|
||||
const importers = DIRS.flatMap((d) => sources(path.join(ROOT, d)))
|
||||
.filter((file) => ROW_IMPORT.test(fs.readFileSync(file, 'utf8')))
|
||||
.map((file) => path.relative(ROOT, file));
|
||||
expect(importers).toEqual(['components/HomeView.tsx']);
|
||||
});
|
||||
|
||||
it('gives each of HomeView\'s row lists the `results` container', () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, 'components', 'HomeView.module.css'), 'utf8');
|
||||
for (const list of ['.schoolList', '.compactList', '.bottomSheet']) {
|
||||
const rule = new RegExp(`\\${list}\\s*\\{[^}]*container:\\s*results\\s*/\\s*inline-size`);
|
||||
expect({ list, provided: rule.test(css) }).toEqual({ list, provided: true });
|
||||
}
|
||||
});
|
||||
@@ -645,6 +645,13 @@ html .leaflet-container a.leaflet-popup-close-button:focus {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* The popup card's View link is a .btn-tertiary, which leaflet.css's
|
||||
`.leaflet-container a` (0,1,1) paints #0078A8 over its 0,1,0. Its hover
|
||||
rule, at 0,3,0, still wins over this. */
|
||||
html .leaflet-container a.btn-tertiary {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* Main content column */
|
||||
.main {
|
||||
max-width: 1400px;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { absoluteUrl } from '@/lib/site';
|
||||
import type { Metadata } from 'next';
|
||||
import { fetchSchools, fetchFilters, fetchDataInfo } from '@/lib/api';
|
||||
import { formatAcademicYear } from '@/lib/utils';
|
||||
import { DEFAULT_RADIUS_MILES, formatAcademicYear } from '@/lib/utils';
|
||||
import { HomeView } from '@/components/HomeView';
|
||||
import { getFlags } from '@/lib/flags';
|
||||
import { HowItWorksSection } from '@/components/HowItWorksSection';
|
||||
@@ -71,7 +71,9 @@ export default async function HomePage({ searchParams }: HomePageProps) {
|
||||
|
||||
// Parse search params
|
||||
const page = parseInt(params.page || '1');
|
||||
const radius = params.radius ? parseFloat(params.radius) : undefined;
|
||||
// Without this the API applies its own 5-mile default while the Distance
|
||||
// control shows DEFAULT_RADIUS_MILES.
|
||||
const radius = params.radius ? parseFloat(params.radius) : DEFAULT_RADIUS_MILES;
|
||||
|
||||
// Check if user has performed a search
|
||||
const hasSearchParams = !!(
|
||||
|
||||
@@ -40,8 +40,19 @@
|
||||
margin: 0 auto 1.5rem;
|
||||
}
|
||||
|
||||
/* One row where it fits: the search takes what the controls leave, and the
|
||||
"More filters" panel breaks onto its own line below both. */
|
||||
/*
|
||||
* One row on wide screens, two below 1340px — decided by the width alone,
|
||||
* never by what the search returned.
|
||||
*
|
||||
* The row once wrapped wherever it ran out of room, and its contents change
|
||||
* with the results: the List/Map switch beside it, the distance chip and Clear
|
||||
* all come and go. So the same search folded onto two lines when it had
|
||||
* results and sat on one when it had none. Now the controls never wrap away
|
||||
* from the search on a wide screen; the search box takes what they leave, and
|
||||
* 1340px is where the fullest toolbar (distance, phase, type, More filters,
|
||||
* Clear and the switch) still leaves it 12rem. The "More filters" panel breaks
|
||||
* onto its own line below both.
|
||||
*/
|
||||
.filterBar:not(.heroMode) {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -56,12 +67,38 @@
|
||||
}
|
||||
|
||||
.filterBar:not(.heroMode) .searchSection {
|
||||
flex: 1 1 320px;
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* Only phones fold the form away; see the 640px block. */
|
||||
.searchSummary {
|
||||
.filterBar:not(.heroMode) .controlsRow {
|
||||
flex: 0 0 auto;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
/* The List/Map switch closes the line; the "More filters" panel follows it. */
|
||||
.viewSwitchSlot {
|
||||
flex: 0 0 auto;
|
||||
order: 1;
|
||||
}
|
||||
|
||||
/* Below that, the switch stays up beside the search and the controls always
|
||||
take a full-width line of their own, results or not. */
|
||||
@media (min-width: 641px) and (max-width: 1339px) {
|
||||
.viewSwitchSlot {
|
||||
order: 0;
|
||||
}
|
||||
|
||||
.filterBar:not(.heroMode) .controlsRow {
|
||||
flex-basis: 100%;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
|
||||
/* Only phones fold the form away and filter through the sheet; see the
|
||||
640px block. */
|
||||
.summaryRow,
|
||||
.chipsLine {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -313,6 +350,11 @@
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* In the phone sheet a select is a full-width field and a whole touch target. */
|
||||
.sheetSelect {
|
||||
min-height: 2.75rem;
|
||||
}
|
||||
|
||||
/* A pill, 44px tall: these are the page's main controls now, not fine print,
|
||||
and a phone needs the full touch target. */
|
||||
.controlSelect {
|
||||
@@ -324,8 +366,9 @@
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
/* A select is as wide as its longest option, and a school type can run to
|
||||
"Academy special sponsor led". Cap it; the chosen value truncates. */
|
||||
max-width: 14rem;
|
||||
"Academy special sponsor led". Cap it; the chosen value truncates. The cap
|
||||
is part of the one-line budget above. */
|
||||
max-width: 11rem;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
@@ -363,6 +406,7 @@
|
||||
pushing the results off a short screen. The 3px gutter keeps the selects'
|
||||
focus rings clear of the scroll clip. */
|
||||
.filters {
|
||||
order: 2;
|
||||
flex-basis: 100%;
|
||||
display: flex;
|
||||
gap: 0.625rem;
|
||||
@@ -516,16 +560,16 @@
|
||||
/*
|
||||
* Phones: the results toolbar is pinned, so it is held to two short lines.
|
||||
*
|
||||
* After a search the form folds into a one-line summary ("SW196AR · within
|
||||
* 1 mile Edit") and the controls become a single row that scrolls sideways.
|
||||
* "More filters" leads the row there: it is the one control that opens
|
||||
* everything else, so it must never be the chip scrolled out of sight.
|
||||
* After a search the form folds into a one-line summary ("SW196AR · 1 mi
|
||||
* Edit") with the Filters button beside it, and every filter lives in
|
||||
* the sheet that button opens. A second line, of the applied filters as
|
||||
* chips, appears only once something is applied.
|
||||
*/
|
||||
@media (max-width: 640px) {
|
||||
/*
|
||||
* nowrap matters as much as column. The desktop rule wraps, and in a
|
||||
* wrapping flex container each line is as wide as its widest item's content,
|
||||
* not the container: the search summary ("SW196AR · within 1 mile Edit",
|
||||
* not the container: the search summary (then "SW196AR · within 1 mile Edit",
|
||||
* about 410px) stretched the line, and the controls row with it, 40px past a
|
||||
* 402px iPhone 17 screen. Single-line, stretch means the container's width.
|
||||
*/
|
||||
@@ -579,13 +623,79 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Phones switch views with the floating button (HomeView, .mobileDock). An
|
||||
empty slot would still take a gap in this column. */
|
||||
.viewSwitchSlot {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* The desktop row and its panel give way to the Filters button, the
|
||||
applied-filter chips and the sheet. */
|
||||
.filterBar:not(.heroMode) .controlsRow,
|
||||
.filterBar:not(.heroMode) .filters {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.summaryRow {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.summaryRow .searchSummary {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.sheetTrigger {
|
||||
flex: 0 0 auto;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
min-height: 2.75rem;
|
||||
padding: 0 0.875rem;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--text-secondary);
|
||||
border-radius: var(--radius-md);
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--step--1);
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The same brand chip as "More filters" on desktop: the list is narrowed. */
|
||||
.sheetTriggerActive {
|
||||
border-color: var(--brand);
|
||||
background: var(--brand-bg);
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.sheetTriggerCount {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
padding: 0 0.3rem;
|
||||
border-radius: 999px;
|
||||
background: var(--brand);
|
||||
color: var(--bg-card);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* Bleeds to the screen edge so a chip scrolls out from under it, rather than
|
||||
being cut off at the toolbar's padding. The toolbar's inline padding is
|
||||
1rem at this width (HomeView.module.css, .resultsToolbar). The 4px of
|
||||
block padding is room for focus rings, which the scroll clip would
|
||||
otherwise cut off above and below the chips. */
|
||||
.controlsRow {
|
||||
flex-wrap: nowrap;
|
||||
.chipsLine {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
overflow-x: auto;
|
||||
margin: -4px -1rem;
|
||||
padding: 4px 1rem;
|
||||
@@ -597,15 +707,50 @@
|
||||
mask-image: none;
|
||||
}
|
||||
|
||||
.controlsRow::-webkit-scrollbar {
|
||||
.chipsLine::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.controlsRow > * {
|
||||
.chipsLine > *,
|
||||
.chips > * {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.controlsRow .advancedToggle {
|
||||
order: -1;
|
||||
.chips {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
min-height: 2.75rem;
|
||||
padding: 0 0.75rem 0 1rem;
|
||||
background: rgba(var(--sage-rgb), 0.38);
|
||||
border: 1px solid var(--brand);
|
||||
border-radius: 999px;
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--step--1);
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
color: var(--brand-strong);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* A school type can run to "Academy special sponsor led". */
|
||||
.chipLabel {
|
||||
max-width: 11rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.chipsClear {
|
||||
min-height: 2.75rem;
|
||||
padding: 0 0.75rem;
|
||||
font-size: var(--step--1);
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
+371
-149
@@ -3,10 +3,11 @@
|
||||
import { useState, useCallback, useTransition, useRef, useEffect } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||
import { isValidPostcode, schoolUrl } from "@/lib/utils";
|
||||
import { DEFAULT_RADIUS_MILES, isValidPostcode, schoolUrl } from "@/lib/utils";
|
||||
import { track } from "@/lib/analytics";
|
||||
import { useSchoolSuggest } from "@/hooks/useSchoolSuggest";
|
||||
import { SuggestList, suggestOptionId } from "./SuggestList";
|
||||
import { FilterSheet, SheetField, RADIUS_OPTIONS, radiusLabel as milesLabel } from "./FilterSheet";
|
||||
import type { Suggestion } from "@/lib/suggest";
|
||||
import type { Filters, ResultFilters } from "@/lib/types";
|
||||
import styles from "./FilterBar.module.css";
|
||||
@@ -22,6 +23,14 @@ interface FilterBarProps {
|
||||
geoError?: string | null;
|
||||
/** Server-read feature flag. Off means no listener, no fetch, no markup. */
|
||||
autosuggest?: boolean;
|
||||
/**
|
||||
* The results page's List/Map switch. It sits in this bar's own row rather
|
||||
* than beside it, so that when the bar takes two lines the filters' line
|
||||
* runs the full width instead of stopping short of the switch.
|
||||
*/
|
||||
viewSwitch?: ReactNode;
|
||||
/** The results' total, for the phone filter sheet's "Show N schools". */
|
||||
resultCount?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,6 +55,37 @@ function SelectShell({
|
||||
);
|
||||
}
|
||||
|
||||
/** The filters a phone sees as chips and counts on its Filters button. */
|
||||
const FILTER_KEYS = [
|
||||
"phase",
|
||||
"school_type",
|
||||
"local_authority",
|
||||
"gender",
|
||||
"has_sixth_form",
|
||||
"admissions_policy",
|
||||
] as const;
|
||||
type FilterKey = (typeof FILTER_KEYS)[number];
|
||||
|
||||
function SlidersIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M4 6h10M18 6h2M4 12h4M12 12h8M4 18h12" />
|
||||
<circle cx="16" cy="6" r="2" />
|
||||
<circle cx="10" cy="12" r="2" />
|
||||
<circle cx="18" cy="18" r="2" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function FilterBar({
|
||||
filters,
|
||||
isHero,
|
||||
@@ -54,6 +94,8 @@ export function FilterBar({
|
||||
geoState = "idle",
|
||||
geoError,
|
||||
autosuggest = false,
|
||||
viewSwitch,
|
||||
resultCount,
|
||||
}: FilterBarProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
@@ -63,7 +105,7 @@ export function FilterBar({
|
||||
|
||||
const currentSearch = searchParams.get("search") || "";
|
||||
const currentPostcode = searchParams.get("postcode") || "";
|
||||
const currentRadius = searchParams.get("radius") || "1";
|
||||
const currentRadius = searchParams.get("radius") || String(DEFAULT_RADIUS_MILES);
|
||||
const initialOmniValue = currentPostcode || currentSearch;
|
||||
|
||||
const [omniValue, setOmniValue] = useState(initialOmniValue);
|
||||
@@ -165,9 +207,9 @@ export function FilterBar({
|
||||
setOmniValue(currentQuery);
|
||||
}
|
||||
|
||||
// The phone row's right-edge fade says "more this way"; once there is no
|
||||
// more, it only dims the last chip. Same rule as the school page's section
|
||||
// nav (MOBILE.md, "Right-edge scroll-fade").
|
||||
// The phone chips line's right-edge fade says "more this way"; once there is
|
||||
// no more, it only dims the last chip. Same rule as the school page's
|
||||
// section nav (MOBILE.md, "Right-edge scroll-fade").
|
||||
const controlsRowRef = useRef<HTMLDivElement>(null);
|
||||
const [controlsAtEnd, setControlsAtEnd] = useState(false);
|
||||
const updateControlsAtEnd = useCallback(() => {
|
||||
@@ -180,8 +222,8 @@ export function FilterBar({
|
||||
window.addEventListener("resize", updateControlsAtEnd);
|
||||
return () => window.removeEventListener("resize", updateControlsAtEnd);
|
||||
}, [updateControlsAtEnd]);
|
||||
// Chips come and go with the search (distance, Clear), so re-measure after
|
||||
// every render rather than only on resize.
|
||||
// Chips come and go with the filters, so re-measure after every render
|
||||
// rather than only on resize.
|
||||
useEffect(updateControlsAtEnd);
|
||||
const openSearch = () => {
|
||||
setSearchOpen(true);
|
||||
@@ -205,9 +247,21 @@ export function FilterBar({
|
||||
return () => document.removeEventListener("keydown", handleKeyDown);
|
||||
}, []);
|
||||
|
||||
/*
|
||||
* Where the navigation in flight is headed. useSearchParams only catches up
|
||||
* once a navigation lands, so a second change made before then (the phone
|
||||
* sheet stays usable while one lands) would otherwise be built on the old
|
||||
* URL and undo the first. Dropped once nothing is pending, when
|
||||
* searchParams is current again.
|
||||
*/
|
||||
const pendingQueryRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!isPending) pendingQueryRef.current = null;
|
||||
}, [isPending]);
|
||||
|
||||
const updateURL = useCallback(
|
||||
(updates: Record<string, string>) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
const params = new URLSearchParams(pendingQueryRef.current ?? searchParams);
|
||||
|
||||
Object.entries(updates).forEach(([key, value]) => {
|
||||
if (value && value !== "") {
|
||||
@@ -218,6 +272,7 @@ export function FilterBar({
|
||||
});
|
||||
|
||||
params.delete("page");
|
||||
pendingQueryRef.current = params.toString();
|
||||
|
||||
startTransition(() => {
|
||||
router.push(`${pathname}?${params.toString()}`);
|
||||
@@ -262,7 +317,7 @@ export function FilterBar({
|
||||
if (isPostcode) {
|
||||
updateURL({
|
||||
postcode: cleaned.toUpperCase(),
|
||||
radius: currentRadius || "1",
|
||||
radius: currentRadius,
|
||||
search: "",
|
||||
});
|
||||
} else {
|
||||
@@ -274,8 +329,15 @@ export function FilterBar({
|
||||
updateURL({ [key]: value });
|
||||
};
|
||||
|
||||
// Every filter at once, keeping the search and its distance: what "Clear
|
||||
// all" means beside the applied filters, where the search is not one of them.
|
||||
const handleClearFilterValues = () => {
|
||||
updateURL(Object.fromEntries(FILTER_KEYS.map((k) => [k, ""])));
|
||||
};
|
||||
|
||||
const handleClearFilters = () => {
|
||||
setOmniValue("");
|
||||
pendingQueryRef.current = "";
|
||||
startTransition(() => {
|
||||
router.push(pathname);
|
||||
});
|
||||
@@ -295,7 +357,10 @@ export function FilterBar({
|
||||
const laOptions =
|
||||
resultFilters?.local_authorities ?? filters.local_authorities;
|
||||
const typeOptions = resultFilters?.school_types ?? filters.school_types;
|
||||
const phaseOptions = resultFilters?.phases ?? filters.phases ?? [];
|
||||
// Phase is the exception: always the full list. The result set has already
|
||||
// been narrowed by the phase filter, so scoping to it would leave only the
|
||||
// chosen phase on offer and switching phase would need "Any phase" first.
|
||||
const phaseOptions = filters.phases ?? [];
|
||||
const genderOptions = resultFilters?.genders ?? filters.genders ?? [];
|
||||
const admissionsPolicyOptions =
|
||||
resultFilters?.admissions_policies ?? filters.admissions_policies ?? [];
|
||||
@@ -307,13 +372,208 @@ export function FilterBar({
|
||||
// only ever additive, so the control's behaviour is untouched.
|
||||
const activeIf = (value: string) => (value ? ` ${styles.selectActive}` : "");
|
||||
|
||||
const radiusLabel = `${currentRadius} mile${currentRadius === "1" ? "" : "s"}`;
|
||||
const radiusLabel = milesLabel(currentRadius);
|
||||
|
||||
/*
|
||||
* Phones filter through one button and a sheet holding every filter. The
|
||||
* desktop row's phone version scrolled sideways with "More filters" first,
|
||||
* so phase showed only in part and school type not at all, and the panel
|
||||
* "More filters" opened did not contain either of them.
|
||||
*/
|
||||
const [sheetOpen, setSheetOpen] = useState(false);
|
||||
// The sheet is phone furniture: if the screen widens past phone width while
|
||||
// it is open (rotation, a resized window), close it, or its selects and the
|
||||
// desktop row's would both be showing.
|
||||
useEffect(() => {
|
||||
if (!sheetOpen || typeof window.matchMedia !== "function") return;
|
||||
const phone = window.matchMedia("(max-width: 640px)");
|
||||
const onChange = (e: { matches: boolean }) => {
|
||||
if (!e.matches) setSheetOpen(false);
|
||||
};
|
||||
phone.addEventListener("change", onChange);
|
||||
return () => phone.removeEventListener("change", onChange);
|
||||
}, [sheetOpen]);
|
||||
const values: Record<FilterKey, string> = {
|
||||
phase: currentPhase,
|
||||
school_type: currentType,
|
||||
local_authority: currentLA,
|
||||
gender: currentGender,
|
||||
has_sixth_form: currentHasSixthForm,
|
||||
admissions_policy: currentAdmissionsPolicy,
|
||||
};
|
||||
const labelFor = (key: FilterKey, value: string) => {
|
||||
if (key === "has_sixth_form") {
|
||||
return value === "yes" ? "With sixth form" : "Without sixth form";
|
||||
}
|
||||
// Phase, gender and admissions values are lowercased option names; the
|
||||
// rest are the names themselves.
|
||||
const named: Partial<Record<FilterKey, string[]>> = {
|
||||
phase: phaseOptions,
|
||||
gender: [...genderOptions, ...(filters.genders ?? [])],
|
||||
admissions_policy: [
|
||||
...admissionsPolicyOptions,
|
||||
...(filters.admissions_policies ?? []),
|
||||
],
|
||||
};
|
||||
return (named[key] ?? []).find((o) => o.toLowerCase() === value.toLowerCase()) ?? value;
|
||||
};
|
||||
const applied = FILTER_KEYS.filter((k) => values[k]).map((key) => ({
|
||||
key,
|
||||
label: labelFor(key, values[key]),
|
||||
}));
|
||||
const appliedCount = applied.length;
|
||||
|
||||
/*
|
||||
* Each select is built here once and drawn twice: as a pill in the desktop
|
||||
* row or panel, and as a full-width labelled field in the phone sheet. Only
|
||||
* one copy is ever showing; the sheet's is mounted only while it is open.
|
||||
* The sheet's stay enabled while a change lands: disabling the control
|
||||
* under the user's focus would drop focus to <body>, out of the dialog.
|
||||
*/
|
||||
type Look = "pill" | "panel" | "sheet";
|
||||
const selectClass = (look: Look, value: string) =>
|
||||
`${look === "pill" ? styles.controlSelect : styles.filterSelect}${look === "sheet" ? ` ${styles.sheetSelect}` : ""}${activeIf(value)}`;
|
||||
|
||||
const phaseSelect = (look: Look) => (
|
||||
<SelectShell wide={look !== "pill"}>
|
||||
<select
|
||||
value={currentPhase}
|
||||
onChange={(e) => handleFilterChange("phase", e.target.value)}
|
||||
className={selectClass(look, currentPhase)}
|
||||
aria-label="Phase"
|
||||
disabled={isPending && look !== "sheet"}
|
||||
>
|
||||
<option value="">Any phase</option>
|
||||
{phaseOptions.map((p) => (
|
||||
<option key={p} value={p.toLowerCase()}>
|
||||
{p}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
);
|
||||
|
||||
const typeSelect = (look: Look) => (
|
||||
<SelectShell wide={look !== "pill"}>
|
||||
<select
|
||||
value={currentType}
|
||||
onChange={(e) => handleFilterChange("school_type", e.target.value)}
|
||||
className={selectClass(look, currentType)}
|
||||
aria-label="School type"
|
||||
disabled={isPending && look !== "sheet"}
|
||||
>
|
||||
<option value="">Any school type</option>
|
||||
{typeOptions.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
);
|
||||
|
||||
const laSelect = (look: Look) => (
|
||||
<SelectShell wide>
|
||||
<select
|
||||
value={currentLA}
|
||||
onChange={(e) => handleFilterChange("local_authority", e.target.value)}
|
||||
className={selectClass(look, currentLA)}
|
||||
aria-label="Local authority"
|
||||
disabled={isPending && look !== "sheet"}
|
||||
>
|
||||
<option value="">All Local Authorities</option>
|
||||
{laOptions.map((la) => (
|
||||
<option key={la} value={la}>
|
||||
{la}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
);
|
||||
|
||||
const genderSelect = (look: Look) => (
|
||||
<SelectShell wide>
|
||||
<select
|
||||
value={currentGender}
|
||||
onChange={(e) => handleFilterChange("gender", e.target.value)}
|
||||
className={selectClass(look, currentGender)}
|
||||
aria-label="Gender"
|
||||
disabled={isPending && look !== "sheet"}
|
||||
>
|
||||
<option value="">Boys, Girls & Mixed</option>
|
||||
{genderOptions.map((g) => (
|
||||
<option key={g} value={g.toLowerCase()}>
|
||||
{g}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
);
|
||||
|
||||
const sixthFormSelect = (look: Look) => (
|
||||
<SelectShell wide>
|
||||
<select
|
||||
value={currentHasSixthForm}
|
||||
onChange={(e) => handleFilterChange("has_sixth_form", e.target.value)}
|
||||
className={selectClass(look, currentHasSixthForm)}
|
||||
aria-label="Sixth form"
|
||||
disabled={isPending && look !== "sheet"}
|
||||
>
|
||||
<option value="">With or without sixth form</option>
|
||||
<option value="yes">With sixth form</option>
|
||||
<option value="no">Without sixth form</option>
|
||||
</select>
|
||||
</SelectShell>
|
||||
);
|
||||
|
||||
const admissionsSelect = (look: Look) => (
|
||||
<SelectShell wide>
|
||||
<select
|
||||
value={currentAdmissionsPolicy}
|
||||
onChange={(e) => handleFilterChange("admissions_policy", e.target.value)}
|
||||
className={selectClass(look, currentAdmissionsPolicy)}
|
||||
aria-label="Admissions"
|
||||
disabled={isPending && look !== "sheet"}
|
||||
>
|
||||
<option value="">All admissions types</option>
|
||||
{admissionsPolicyOptions.map((p) => (
|
||||
<option key={p} value={p.toLowerCase()}>
|
||||
{p}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
);
|
||||
|
||||
const sheetTrigger = (
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.sheetTrigger}${appliedCount ? ` ${styles.sheetTriggerActive}` : ""}`}
|
||||
onClick={() => setSheetOpen(true)}
|
||||
aria-haspopup="dialog"
|
||||
aria-label={appliedCount ? `Filters, ${appliedCount} applied` : "Filters"}
|
||||
>
|
||||
<SlidersIcon />
|
||||
Filters
|
||||
{appliedCount > 0 && (
|
||||
<span className={styles.sheetTriggerCount} aria-hidden="true">
|
||||
{appliedCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
// Beside the folded search summary; on the chips line when there is no
|
||||
// summary to sit beside. While the search is being edited it steps aside,
|
||||
// and comes back when the form folds.
|
||||
const triggerBesideSummary = canFold && !searchOpen;
|
||||
const triggerOnChipsLine = !canFold;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${styles.filterBar} ${isPending ? styles.isLoading : ""} ${isHero ? styles.heroMode : ""}`}
|
||||
>
|
||||
{canFold && !searchOpen && (
|
||||
{triggerBesideSummary && (
|
||||
<div className={styles.summaryRow}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.searchSummary}
|
||||
@@ -335,10 +595,14 @@ export function FilterBar({
|
||||
</svg>
|
||||
<span className={styles.summaryText}>
|
||||
<strong>{currentQuery}</strong>
|
||||
{currentPostcode && <span> · within {radiusLabel}</span>}
|
||||
{/* Short, so the distance survives beside the Filters button on a
|
||||
360px screen; the button's name carries the long form. */}
|
||||
{currentPostcode && <span> · {currentRadius} mi</span>}
|
||||
</span>
|
||||
<span className={styles.summaryEdit} aria-hidden="true">Edit</span>
|
||||
</button>
|
||||
{sheetTrigger}
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
onSubmit={handleSearchSubmit}
|
||||
@@ -449,16 +713,13 @@ export function FilterBar({
|
||||
|
||||
{!isHero && (
|
||||
<>
|
||||
{/* Every control here is a real <select> or <button>, drawn as a
|
||||
pill. On phones the row scrolls sideways rather than wrapping, so
|
||||
the pinned toolbar stays two lines tall. */}
|
||||
<div
|
||||
ref={controlsRowRef}
|
||||
className={`${styles.controlsRow}${controlsAtEnd ? ` ${styles.controlsAtEnd}` : ""}`}
|
||||
role="group"
|
||||
aria-label="Filters"
|
||||
onScroll={updateControlsAtEnd}
|
||||
>
|
||||
{viewSwitch && (
|
||||
<div className={styles.viewSwitchSlot}>{viewSwitch}</div>
|
||||
)}
|
||||
{/* Desktop and tablet. Every control here is a real <select> or
|
||||
<button>, drawn as a pill. Phones hide the row and use the
|
||||
Filters button and sheet instead. */}
|
||||
<div className={styles.controlsRow} role="group" aria-label="Filters">
|
||||
{currentPostcode && (
|
||||
<SelectShell>
|
||||
<select
|
||||
@@ -468,51 +729,18 @@ export function FilterBar({
|
||||
aria-label="Distance"
|
||||
disabled={isPending}
|
||||
>
|
||||
<option value="0.5">Within 0.5 miles</option>
|
||||
<option value="1">Within 1 mile</option>
|
||||
<option value="3">Within 3 miles</option>
|
||||
<option value="5">Within 5 miles</option>
|
||||
</select>
|
||||
</SelectShell>
|
||||
)}
|
||||
|
||||
{phaseOptions.length > 0 && (
|
||||
<SelectShell>
|
||||
<select
|
||||
value={currentPhase}
|
||||
onChange={(e) => handleFilterChange("phase", e.target.value)}
|
||||
className={`${styles.controlSelect}${activeIf(currentPhase)}`}
|
||||
aria-label="Phase"
|
||||
disabled={isPending}
|
||||
>
|
||||
<option value="">Any phase</option>
|
||||
{phaseOptions.map((p) => (
|
||||
<option key={p} value={p.toLowerCase()}>
|
||||
{p}
|
||||
{RADIUS_OPTIONS.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
Within {milesLabel(r)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
)}
|
||||
|
||||
<SelectShell>
|
||||
<select
|
||||
value={currentType}
|
||||
onChange={(e) =>
|
||||
handleFilterChange("school_type", e.target.value)
|
||||
}
|
||||
className={`${styles.controlSelect}${activeIf(currentType)}`}
|
||||
aria-label="School type"
|
||||
disabled={isPending}
|
||||
>
|
||||
<option value="">Any school type</option>
|
||||
{typeOptions.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
{phaseOptions.length > 0 && phaseSelect("pill")}
|
||||
|
||||
{typeSelect("pill")}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
@@ -520,21 +748,7 @@ export function FilterBar({
|
||||
onClick={() => setFiltersOpen((v) => !v)}
|
||||
aria-expanded={filtersOpen}
|
||||
>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M4 6h10M18 6h2M4 12h4M12 12h8M4 18h12" />
|
||||
<circle cx="16" cy="6" r="2" />
|
||||
<circle cx="10" cy="12" r="2" />
|
||||
<circle cx="18" cy="18" r="2" />
|
||||
</svg>
|
||||
<SlidersIcon />
|
||||
More filters
|
||||
{hasActiveDropdownFilters
|
||||
? ` (${activeDropdownFilters.length})`
|
||||
@@ -558,85 +772,93 @@ export function FilterBar({
|
||||
|
||||
{filtersOpen && (
|
||||
<div className={styles.filters}>
|
||||
<SelectShell wide>
|
||||
<select
|
||||
value={currentLA}
|
||||
onChange={(e) =>
|
||||
handleFilterChange("local_authority", e.target.value)
|
||||
}
|
||||
className={`${styles.filterSelect}${activeIf(currentLA)}`}
|
||||
aria-label="Local authority"
|
||||
disabled={isPending}
|
||||
>
|
||||
<option value="">All Local Authorities</option>
|
||||
{laOptions.map((la) => (
|
||||
<option key={la} value={la}>
|
||||
{la}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
{laSelect("panel")}
|
||||
|
||||
{isSecondaryMode && (
|
||||
<>
|
||||
{genderOptions.length > 0 && (
|
||||
<SelectShell wide>
|
||||
<select
|
||||
value={currentGender}
|
||||
onChange={(e) =>
|
||||
handleFilterChange("gender", e.target.value)
|
||||
}
|
||||
className={`${styles.filterSelect}${activeIf(currentGender)}`}
|
||||
disabled={isPending}
|
||||
>
|
||||
<option value="">Boys, Girls & Mixed</option>
|
||||
{genderOptions.map((g) => (
|
||||
<option key={g} value={g.toLowerCase()}>
|
||||
{g}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
)}
|
||||
|
||||
<SelectShell wide>
|
||||
<select
|
||||
value={currentHasSixthForm}
|
||||
onChange={(e) =>
|
||||
handleFilterChange("has_sixth_form", e.target.value)
|
||||
}
|
||||
className={`${styles.filterSelect}${activeIf(currentHasSixthForm)}`}
|
||||
disabled={isPending}
|
||||
>
|
||||
<option value="">With or without sixth form</option>
|
||||
<option value="yes">With sixth form</option>
|
||||
<option value="no">Without sixth form</option>
|
||||
</select>
|
||||
</SelectShell>
|
||||
|
||||
{admissionsPolicyOptions.length > 0 && (
|
||||
<SelectShell wide>
|
||||
<select
|
||||
value={currentAdmissionsPolicy}
|
||||
onChange={(e) =>
|
||||
handleFilterChange("admissions_policy", e.target.value)
|
||||
}
|
||||
className={`${styles.filterSelect}${activeIf(currentAdmissionsPolicy)}`}
|
||||
disabled={isPending}
|
||||
>
|
||||
<option value="">All admissions types</option>
|
||||
{admissionsPolicyOptions.map((p) => (
|
||||
<option key={p} value={p.toLowerCase()}>
|
||||
{p}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectShell>
|
||||
)}
|
||||
{genderOptions.length > 0 && genderSelect("panel")}
|
||||
{sixthFormSelect("panel")}
|
||||
{admissionsPolicyOptions.length > 0 && admissionsSelect("panel")}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Phones: what is applied, each removable with a tap. The line
|
||||
scrolls sideways if it overflows, under the same right-edge fade
|
||||
as the school page's section nav. */}
|
||||
{(appliedCount > 0 || triggerOnChipsLine) && (
|
||||
<div
|
||||
ref={controlsRowRef}
|
||||
className={`${styles.chipsLine}${controlsAtEnd ? ` ${styles.controlsAtEnd}` : ""}`}
|
||||
onScroll={updateControlsAtEnd}
|
||||
>
|
||||
{triggerOnChipsLine && sheetTrigger}
|
||||
{appliedCount > 0 && (
|
||||
<div className={styles.chips} role="group" aria-label="Applied filters">
|
||||
{applied.map(({ key, label }) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
className={styles.chip}
|
||||
onClick={() => handleFilterChange(key, "")}
|
||||
aria-label={`Remove filter: ${label}`}
|
||||
disabled={isPending}
|
||||
>
|
||||
<span className={styles.chipLabel}>{label}</span>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2.5"
|
||||
strokeLinecap="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M18 6 6 18M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-tertiary ${styles.chipsClear}`}
|
||||
onClick={handleClearFilterValues}
|
||||
disabled={isPending}
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FilterSheet
|
||||
open={sheetOpen}
|
||||
onClose={() => setSheetOpen(false)}
|
||||
radius={currentPostcode ? currentRadius : null}
|
||||
onRadiusChange={(r) => updateURL({ radius: r })}
|
||||
onClearAll={appliedCount > 0 ? handleClearFilterValues : undefined}
|
||||
resultCount={resultCount}
|
||||
isPending={isPending}
|
||||
>
|
||||
{phaseOptions.length > 0 && (
|
||||
<SheetField label="Phase">{phaseSelect("sheet")}</SheetField>
|
||||
)}
|
||||
<SheetField label="School type">{typeSelect("sheet")}</SheetField>
|
||||
<SheetField label="Local authority">{laSelect("sheet")}</SheetField>
|
||||
{isSecondaryMode && (
|
||||
<>
|
||||
{genderOptions.length > 0 && (
|
||||
<SheetField label="Gender">{genderSelect("sheet")}</SheetField>
|
||||
)}
|
||||
<SheetField label="Sixth form">{sixthFormSelect("sheet")}</SheetField>
|
||||
{admissionsPolicyOptions.length > 0 && (
|
||||
<SheetField label="Admissions">{admissionsSelect("sheet")}</SheetField>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</FilterSheet>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/* ── Phone filter sheet ───────────────────────────────────────────── */
|
||||
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.fieldLabel {
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--step--1);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* Distance: five joined segments, a full-width row. At 360px each is about
|
||||
65px wide, clear of the 44px minimum. */
|
||||
.segments {
|
||||
display: flex;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.segment {
|
||||
position: relative;
|
||||
flex: 1 1 0;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.segment + .segment {
|
||||
border-left: 1px solid var(--border);
|
||||
}
|
||||
|
||||
/* The real radio stays in the tree for keyboard and screen readers; the span
|
||||
is what is drawn. */
|
||||
.segment input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
margin: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.segment span {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 2.75rem;
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--step--1);
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-card);
|
||||
white-space: nowrap;
|
||||
transition: background-color var(--transition), color var(--transition);
|
||||
}
|
||||
|
||||
.segment input:checked + span {
|
||||
background: rgba(var(--sage-rgb), 0.38);
|
||||
color: var(--brand-strong);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.segment input:focus-visible + span {
|
||||
box-shadow: inset 0 0 0 2px var(--brand);
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.clearAll {
|
||||
min-height: 2.75rem;
|
||||
padding: 0 1rem;
|
||||
}
|
||||
|
||||
.show {
|
||||
flex: 1;
|
||||
min-height: 2.75rem;
|
||||
justify-content: center;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import { useId } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { Modal } from "./Modal";
|
||||
import styles from "./FilterSheet.module.css";
|
||||
|
||||
export const RADIUS_OPTIONS = ["0.25", "0.5", "1", "3", "5"] as const;
|
||||
|
||||
export const radiusLabel = (r: string) => `${r} mile${r === "1" ? "" : "s"}`;
|
||||
|
||||
interface FilterSheetProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
/** The current distance, or null when the search is not by postcode. */
|
||||
radius: string | null;
|
||||
onRadiusChange: (radius: string) => void;
|
||||
/** The filter selects, each already labelled; FilterBar owns their state. */
|
||||
children: ReactNode;
|
||||
/** Shown only when something is applied. */
|
||||
onClearAll?: () => void;
|
||||
resultCount?: number;
|
||||
isPending: boolean;
|
||||
}
|
||||
|
||||
/*
|
||||
* Every filter in one place, for phones. A change applies at once, as it does
|
||||
* in the desktop toolbar, so the results behind the sheet are already the
|
||||
* filtered ones and the footer button only has to close it.
|
||||
*/
|
||||
export function FilterSheet({
|
||||
open,
|
||||
onClose,
|
||||
radius,
|
||||
onRadiusChange,
|
||||
children,
|
||||
onClearAll,
|
||||
resultCount,
|
||||
isPending,
|
||||
}: FilterSheetProps) {
|
||||
const distanceId = useId();
|
||||
|
||||
const showLabel = isPending
|
||||
? "Updating…"
|
||||
: resultCount === undefined
|
||||
? "Show schools"
|
||||
: resultCount === 0
|
||||
? "No schools match"
|
||||
: `Show ${resultCount.toLocaleString()} school${resultCount === 1 ? "" : "s"}`;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={open}
|
||||
onClose={onClose}
|
||||
title="Filters"
|
||||
size="small"
|
||||
footer={
|
||||
<div className={styles.footer}>
|
||||
{onClearAll && (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-tertiary ${styles.clearAll}`}
|
||||
onClick={onClearAll}
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-action ${styles.show}`}
|
||||
onClick={onClose}
|
||||
>
|
||||
{showLabel}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{/* Controls stay enabled while a change lands, so focus is never
|
||||
dropped out of the dialog; aria-busy says the results are updating. */}
|
||||
<div className={styles.body} aria-busy={isPending}>
|
||||
{radius !== null && (
|
||||
<div className={styles.field}>
|
||||
<span id={distanceId} className={styles.fieldLabel}>
|
||||
Distance
|
||||
</span>
|
||||
<div
|
||||
className={styles.segments}
|
||||
role="radiogroup"
|
||||
aria-labelledby={distanceId}
|
||||
>
|
||||
{RADIUS_OPTIONS.map((r) => (
|
||||
<label key={r} className={styles.segment}>
|
||||
<input
|
||||
type="radio"
|
||||
name={`${distanceId}-radius`}
|
||||
value={r}
|
||||
checked={r === radius}
|
||||
onChange={() => onRadiusChange(r)}
|
||||
aria-label={`Within ${radiusLabel(r)}`}
|
||||
/>
|
||||
<span>{r} mi</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/** One labelled row of the sheet. */
|
||||
export function SheetField({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<label className={styles.field}>
|
||||
<span className={styles.fieldLabel}>{label}</span>
|
||||
{children}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -591,7 +591,7 @@
|
||||
|
||||
.mapViewContainer {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(340px, 420px) minmax(0, 1fr);
|
||||
grid-template-columns: minmax(360px, 460px) minmax(0, 1fr);
|
||||
height: calc(100dvh - var(--map-top) - var(--map-bottom));
|
||||
min-height: 480px;
|
||||
background: var(--bg-card);
|
||||
@@ -608,13 +608,32 @@
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
|
||||
/* One line: the count takes what the sort leaves, and truncates rather than
|
||||
wrap if a narrow pane cannot fit both. */
|
||||
.mapListPane .resultsHeader {
|
||||
gap: 0.5rem;
|
||||
flex-wrap: nowrap;
|
||||
gap: 0.75rem;
|
||||
padding: 0.875rem 1rem 0.75rem;
|
||||
}
|
||||
|
||||
.mapListPane .resultsHeader h2 {
|
||||
font-size: var(--step-1);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: var(--step-0);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.mapListPane .resultsHeaderActions {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* A select is as wide as its longest option ("Highest Reading, Writing &
|
||||
Maths %", 281px), more than half the pane. Cap it; a long choice truncates. */
|
||||
.mapListPane .sortSelect {
|
||||
max-width: 11rem;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.mapContainer {
|
||||
@@ -631,117 +650,53 @@
|
||||
overflow-y: auto;
|
||||
padding: 0.125rem 1rem 1rem;
|
||||
scrollbar-width: thin;
|
||||
/* The rows lay themselves out by this list's width (SchoolRow.module.css),
|
||||
which here is always narrow, whatever the screen. */
|
||||
container: results / inline-size;
|
||||
}
|
||||
|
||||
/* Compact School Item: the list pane's card, and the phone's bottom sheet. */
|
||||
.compactItem {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4375rem;
|
||||
padding: 0.75rem 0.875rem;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
/* A row in the list beside the map: clicking it picks its pin. */
|
||||
.mapRow {
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
transition: border-color var(--transition), box-shadow var(--transition);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.compactItem:hover {
|
||||
border-color: var(--border-strong);
|
||||
.mapRowSelected > :last-child {
|
||||
outline: 2px solid var(--brand);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.compactItemSelected,
|
||||
.compactItemSelected:hover {
|
||||
border-color: var(--brand);
|
||||
box-shadow: 0 0 0 2px rgba(var(--brand-rgb), 0.28);
|
||||
/* Visually hidden until focused, then a pill over the row's top edge. */
|
||||
.showOnMap {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.compactItemHeader {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 0.625rem;
|
||||
}
|
||||
|
||||
.compactItemName {
|
||||
font-family: var(--font-display);
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
color: var(--text-primary);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.compactItemName:hover {
|
||||
color: var(--brand-strong);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.distanceBadge {
|
||||
flex-shrink: 0;
|
||||
padding: 0.125rem 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
.showOnMap:focus-visible {
|
||||
top: -0.5rem;
|
||||
right: 0.75rem;
|
||||
z-index: 1;
|
||||
width: auto;
|
||||
height: auto;
|
||||
padding: 0.375rem 0.75rem;
|
||||
overflow: visible;
|
||||
clip-path: none;
|
||||
background: var(--brand);
|
||||
color: var(--brand-on);
|
||||
border-radius: 4px;
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--step--1);
|
||||
font-weight: 700;
|
||||
outline: 2px solid var(--text-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.compactItemTags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.compactBadge,
|
||||
.compactTag {
|
||||
padding: 0.125rem 0.4375rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.compactTag {
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-secondary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.ofsted1,
|
||||
.ofsted2 { background: var(--status-above-bg); color: var(--status-above); }
|
||||
.ofsted3 { background: var(--status-below-bg); color: var(--status-below); }
|
||||
.ofsted4 { background: var(--status-below); color: var(--text-inverse); }
|
||||
.ofstedRc { background: var(--phase-secondary-text); color: var(--text-inverse); }
|
||||
.ofstedInspected { background: var(--phase-primary-bg); color: var(--phase-primary-text); }
|
||||
.ofstedPending { background: var(--border); color: var(--text-muted); }
|
||||
|
||||
.compactItemFooter {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.compactStat {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.compactStat strong {
|
||||
font-size: 0.9375rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.deltaUp { color: var(--status-above); font-weight: 600; }
|
||||
.deltaDown { color: var(--status-below); font-weight: 600; }
|
||||
|
||||
.compactItemActions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
|
||||
.sectionHeader {
|
||||
@@ -779,6 +734,8 @@
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1.25rem;
|
||||
/* The rows lay themselves out by this list's width (SchoolRow.module.css). */
|
||||
container: results / inline-size;
|
||||
}
|
||||
|
||||
/* Staggered fade-in for rows */
|
||||
@@ -881,33 +838,37 @@
|
||||
animation: slideUpSheet 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
|
||||
}
|
||||
|
||||
.bottomSheet .compactItem {
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
background: transparent;
|
||||
padding: 1rem;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* A 30px circle, drawn by ::before, inside a 44px target (MOBILE.md). */
|
||||
.closeSheetBtn {
|
||||
position: absolute;
|
||||
top: -12px;
|
||||
right: -12px;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 50%;
|
||||
top: -19px;
|
||||
right: -15px;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
background: none;
|
||||
border: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.25rem;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
box-shadow: 0 2px 8px rgba(var(--shadow-rgb), 0.1);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.closeSheetBtn::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 7px;
|
||||
z-index: -1;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 2px 8px rgba(var(--shadow-rgb), 0.1);
|
||||
}
|
||||
|
||||
@keyframes slideUpSheet {
|
||||
from {
|
||||
transform: translateY(120%);
|
||||
@@ -935,6 +896,13 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* The sheet holds one results row, which is the card itself. It is not
|
||||
inside a `results` container, so give it one: a phone-width sheet takes
|
||||
the row's narrow layout. */
|
||||
.bottomSheet {
|
||||
container: results / inline-size;
|
||||
}
|
||||
|
||||
.mapListPane .resultsHeader {
|
||||
padding: 0.625rem 0.875rem;
|
||||
}
|
||||
|
||||
@@ -16,8 +16,8 @@ import { HeroIllustration } from './Illustration';
|
||||
import { useComparisonContext } from '@/context/ComparisonContext';
|
||||
import { fetchSchools, fetchLAaverages, fetchNationalAverages } from '@/lib/api';
|
||||
import type { SchoolsResponse, Filters, School } from '@/lib/types';
|
||||
import { schoolUrl, buildOfstedListBadge, isSpecialSchool, listRwmValue } from '@/lib/utils';
|
||||
import { track } from '@/lib/analytics';
|
||||
import { DEFAULT_RADIUS_MILES } from '@/lib/utils';
|
||||
import styles from './HomeView.module.css';
|
||||
|
||||
interface HomeViewProps {
|
||||
@@ -341,6 +341,7 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
setIsLoadingMap(true);
|
||||
const params: Record<string, any> = {};
|
||||
searchParams.forEach((value, key) => { params[key] = value; });
|
||||
params.radius ??= DEFAULT_RADIUS_MILES;
|
||||
params.page = 1;
|
||||
params.page_size = 500;
|
||||
fetchSchools(params, { cache: 'no-store', signal: controller.signal })
|
||||
@@ -420,7 +421,7 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
setGeoState('idle');
|
||||
track('near_me_used', { outcome: 'granted' });
|
||||
track('search_submitted', { query: postcode, via: 'near_me', has_postcode: true, filters_active: '', filters_count: 0 });
|
||||
router.push(`/?postcode=${encodeURIComponent(postcode)}&radius=1`);
|
||||
router.push(`/?postcode=${encodeURIComponent(postcode)}&radius=${DEFAULT_RADIUS_MILES}`);
|
||||
} else {
|
||||
track('near_me_used', { outcome: 'no_postcode' });
|
||||
setGeoState('error');
|
||||
@@ -460,8 +461,9 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
// open card); only the list beside it is sorted.
|
||||
const mapResultSchools = mapSchools.length > 0 ? mapSchools : initialSchools.schools;
|
||||
const mapListSchools = sortSchools(mapResultSchools);
|
||||
// Two places, so a 0.25-mile search is not drawn or labelled as 0.3.
|
||||
const radiusMiles = initialSchools.location_info
|
||||
? Number((initialSchools.location_info.radius / 1.60934).toFixed(1))
|
||||
? Number((initialSchools.location_info.radius / 1.60934).toFixed(2))
|
||||
: undefined;
|
||||
|
||||
// Empty-results sentinel: track when a search returns nothing.
|
||||
@@ -558,14 +560,46 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
|
||||
const isMapView = initialSchools.schools.length > 0 && resultsView === 'map' && isLocationSearch;
|
||||
|
||||
// One school as a results row: the list view, the list beside the map and
|
||||
// the phone's bottom sheet all draw the same thing.
|
||||
const renderRow = (school: School) => (
|
||||
school.attainment_8_score != null ? (
|
||||
<SecondarySchoolRow
|
||||
key={school.urn}
|
||||
school={school}
|
||||
isLocationSearch={isLocationSearch}
|
||||
onAddToCompare={addSchoolFromSearch}
|
||||
onRemoveFromCompare={removeSchool}
|
||||
isInCompare={compareUrns.includes(school.urn)}
|
||||
laAvgAttainment8={school.local_authority ? laAverages[school.local_authority] ?? null : null}
|
||||
/>
|
||||
) : (
|
||||
<SchoolRow
|
||||
key={school.urn}
|
||||
school={school}
|
||||
isLocationSearch={isLocationSearch}
|
||||
onAddToCompare={addSchoolFromSearch}
|
||||
onRemoveFromCompare={removeSchool}
|
||||
isInCompare={compareUrns.includes(school.urn)}
|
||||
nationalAvgRwm={nationalAvgRwm}
|
||||
/>
|
||||
)
|
||||
);
|
||||
|
||||
const schoolCount = `${initialSchools.total.toLocaleString()} school${initialSchools.total !== 1 ? 's' : ''}`;
|
||||
|
||||
// The count and the sort. Above the list in list view; at the top of the
|
||||
// list pane, beside the map, in map view.
|
||||
const resultsHeader = (
|
||||
<div className={styles.resultsHeader}>
|
||||
<h2 aria-live="polite" aria-atomic="true">
|
||||
{isLocationSearch && initialSchools.location_info
|
||||
? `${initialSchools.total.toLocaleString()} school${initialSchools.total !== 1 ? 's' : ''} within ${(initialSchools.location_info.radius / 1.60934).toFixed(1)} miles of ${initialSchools.location_info.postcode}`
|
||||
: `${initialSchools.total.toLocaleString()} school${initialSchools.total !== 1 ? 's' : ''} found`
|
||||
{/* Beside the map the heading shares one line with the sort, so it
|
||||
drops the postcode, which the search box just above already shows. */}
|
||||
{isMapView && radiusMiles != null
|
||||
? `${schoolCount} within ${radiusMiles} mile${radiusMiles === 1 ? '' : 's'}`
|
||||
: isLocationSearch && radiusMiles != null && initialSchools.location_info
|
||||
? `${schoolCount} within ${radiusMiles} mile${radiusMiles === 1 ? '' : 's'} of ${initialSchools.location_info.postcode}`
|
||||
: `${schoolCount} found`
|
||||
}
|
||||
</h2>
|
||||
<div className={styles.resultsHeaderActions}>
|
||||
@@ -678,33 +712,34 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
filters={filters}
|
||||
isHero={false}
|
||||
resultFilters={initialSchools.result_filters}
|
||||
resultCount={initialSchools.total}
|
||||
onNearMe={handleNearMe}
|
||||
geoState={geoState}
|
||||
geoError={geoError}
|
||||
autosuggest={autosuggest}
|
||||
viewSwitch={hasViewSwitch && (
|
||||
<div className={styles.viewSwitch} role="group" aria-label="Results view">
|
||||
<button
|
||||
type="button"
|
||||
className={styles.viewSwitchBtn}
|
||||
aria-pressed={resultsView === 'list'}
|
||||
onClick={() => changeView('list', 'toolbar')}
|
||||
>
|
||||
<ListIcon />
|
||||
List
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.viewSwitchBtn}
|
||||
aria-pressed={resultsView === 'map'}
|
||||
onClick={() => changeView('map', 'toolbar')}
|
||||
>
|
||||
<MapIcon />
|
||||
Map
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{hasViewSwitch && (
|
||||
<div className={styles.viewSwitch} role="group" aria-label="Results view">
|
||||
<button
|
||||
type="button"
|
||||
className={styles.viewSwitchBtn}
|
||||
aria-pressed={resultsView === 'list'}
|
||||
onClick={() => changeView('list', 'toolbar')}
|
||||
>
|
||||
<ListIcon />
|
||||
List
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.viewSwitchBtn}
|
||||
aria-pressed={resultsView === 'map'}
|
||||
onClick={() => changeView('map', 'toolbar')}
|
||||
>
|
||||
<MapIcon />
|
||||
Map
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -797,17 +832,32 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
<div className={styles.mapListPane}>
|
||||
{resultsHeader}
|
||||
<div ref={mapListRef} className={styles.compactList}>
|
||||
{/* The list view's own rows, so both views show the same thing.
|
||||
Clicking a row (not its links or buttons) picks its pin. */}
|
||||
{listPaneShown && mapListSchools.map((school) => (
|
||||
<CompactSchoolItem
|
||||
<div
|
||||
key={school.urn}
|
||||
school={school}
|
||||
onAddToCompare={addSchoolFromSearch}
|
||||
isInCompare={compareUrns.includes(school.urn)}
|
||||
nationalAvgRwm={nationalAvgRwm}
|
||||
laAverages={laAverages}
|
||||
isSelected={selectedMapSchool?.urn === school.urn}
|
||||
onSelect={setSelectedMapSchool}
|
||||
/>
|
||||
data-urn={school.urn}
|
||||
className={`${styles.mapRow} ${selectedMapSchool?.urn === school.urn ? styles.mapRowSelected : ''}`}
|
||||
onClick={(e) => {
|
||||
if ((e.target as HTMLElement).closest('a, button')) return;
|
||||
setSelectedMapSchool(school);
|
||||
}}
|
||||
>
|
||||
{/* The keyboard's way to pick the pin: hidden until it has
|
||||
focus, since a pointer just clicks the row. The row
|
||||
itself cannot be the button, as it holds links and
|
||||
buttons of its own. */}
|
||||
<button
|
||||
type="button"
|
||||
className={styles.showOnMap}
|
||||
aria-pressed={selectedMapSchool?.urn === school.urn}
|
||||
onClick={() => setSelectedMapSchool(school)}
|
||||
>
|
||||
Show {school.school_name} on the map
|
||||
</button>
|
||||
{renderRow(school)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -831,29 +881,7 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
/* List View Layout */
|
||||
<>
|
||||
<div className={styles.schoolList}>
|
||||
{sortedSchools.map((school) => (
|
||||
school.attainment_8_score != null ? (
|
||||
<SecondarySchoolRow
|
||||
key={school.urn}
|
||||
school={school}
|
||||
isLocationSearch={isLocationSearch}
|
||||
onAddToCompare={addSchoolFromSearch}
|
||||
onRemoveFromCompare={removeSchool}
|
||||
isInCompare={selectedSchools.some(s => s.urn === school.urn)}
|
||||
laAvgAttainment8={school.local_authority ? laAverages[school.local_authority] ?? null : null}
|
||||
/>
|
||||
) : (
|
||||
<SchoolRow
|
||||
key={school.urn}
|
||||
school={school}
|
||||
isLocationSearch={isLocationSearch}
|
||||
onAddToCompare={addSchoolFromSearch}
|
||||
onRemoveFromCompare={removeSchool}
|
||||
isInCompare={selectedSchools.some(s => s.urn === school.urn)}
|
||||
nationalAvgRwm={nationalAvgRwm}
|
||||
/>
|
||||
)
|
||||
))}
|
||||
{sortedSchools.map(renderRow)}
|
||||
</div>
|
||||
|
||||
{(hasMore || allSchools.length < initialSchools.total) && (
|
||||
@@ -899,14 +927,7 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<CompactSchoolItem
|
||||
school={selectedMapSchool}
|
||||
onAddToCompare={addSchoolFromSearch}
|
||||
isInCompare={compareUrns.includes(selectedMapSchool.urn)}
|
||||
nationalAvgRwm={nationalAvgRwm}
|
||||
laAverages={laAverages}
|
||||
showView
|
||||
/>
|
||||
{renderRow(selectedMapSchool)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -914,106 +935,3 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* Compact School Item: a card in the map view's list, and the phone's bottom sheet. */
|
||||
interface CompactSchoolItemProps {
|
||||
school: School;
|
||||
onAddToCompare: (school: School) => void;
|
||||
isInCompare: boolean;
|
||||
nationalAvgRwm?: number | null;
|
||||
laAverages?: Record<string, number>;
|
||||
isSelected?: boolean;
|
||||
/** Clicking the card (not its link or button) picks its pin on the map. */
|
||||
onSelect?: (school: School) => void;
|
||||
/** The bottom sheet has no list around it, so it carries its own View. */
|
||||
showView?: boolean;
|
||||
}
|
||||
|
||||
function CompactSchoolItem({
|
||||
school, onAddToCompare, isInCompare, nationalAvgRwm, laAverages, isSelected, onSelect, showView,
|
||||
}: CompactSchoolItemProps) {
|
||||
const ofstedBadge = buildOfstedListBadge(school);
|
||||
const special = isSpecialSchool(school);
|
||||
const href = schoolUrl(school.urn, school.school_name);
|
||||
|
||||
/*
|
||||
* The headline figure, then its comparison. Same rules as the list rows:
|
||||
* no placeholder all-zero RWM, and no mainstream benchmark for special
|
||||
* schools, PRUs or AP.
|
||||
*/
|
||||
let figure: React.ReactNode = null;
|
||||
if (school.attainment_8_score != null) {
|
||||
const laAvg = school.local_authority ? laAverages?.[school.local_authority] : undefined;
|
||||
const diff = !special && laAvg != null
|
||||
? Math.round((school.attainment_8_score - laAvg) * 10) / 10 : null;
|
||||
figure = (
|
||||
<>
|
||||
<strong>{school.attainment_8_score.toFixed(1)}</strong> Att 8
|
||||
{diff != null && (
|
||||
<span className={diff >= 0.5 ? styles.deltaUp : diff <= -0.5 ? styles.deltaDown : undefined}>
|
||||
{' '}{diff >= 0 ? '+' : ''}{diff} vs LA
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
const rwm = listRwmValue(school);
|
||||
if (rwm != null) {
|
||||
const diff = !special && nationalAvgRwm != null ? Math.round(rwm - nationalAvgRwm) : null;
|
||||
figure = (
|
||||
<>
|
||||
<strong>{rwm}%</strong> RWM
|
||||
{diff != null && (
|
||||
<span className={diff >= 2 ? styles.deltaUp : diff <= -2 ? styles.deltaDown : undefined}>
|
||||
{' '}{diff >= 2 ? `+${diff} pts` : diff <= -2 ? `${diff} pts` : '≈ national'}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const handleClick = (e: React.MouseEvent) => {
|
||||
if ((e.target as HTMLElement).closest('a, button')) return;
|
||||
onSelect?.(school);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
data-urn={school.urn}
|
||||
className={`${styles.compactItem} ${isSelected ? styles.compactItemSelected : ''}`}
|
||||
onClick={onSelect ? handleClick : undefined}
|
||||
>
|
||||
<div className={styles.compactItemHeader}>
|
||||
<a href={href} className={styles.compactItemName}>{school.school_name}</a>
|
||||
{school.distance != null && (
|
||||
<span className={styles.distanceBadge}>{school.distance.toFixed(1)} mi</span>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.compactItemTags}>
|
||||
<span className={`${styles.compactBadge} ${styles[ofstedBadge.cssClass] ?? ''}`}>
|
||||
{ofstedBadge.label}
|
||||
</span>
|
||||
{school.school_type && <span className={styles.compactTag}>{school.school_type}</span>}
|
||||
</div>
|
||||
<div className={styles.compactItemFooter}>
|
||||
<span className={styles.compactStat}>
|
||||
{figure}
|
||||
{school.total_pupils != null && (
|
||||
<>{figure ? ' · ' : ''}{school.total_pupils.toLocaleString('en-GB')} pupils</>
|
||||
)}
|
||||
</span>
|
||||
<div className={styles.compactItemActions}>
|
||||
{showView && <a href={href} className="btn btn-tertiary btn-sm">View</a>}
|
||||
<button
|
||||
type="button"
|
||||
className={isInCompare ? 'btn btn-active btn-sm' : 'btn btn-secondary btn-sm'}
|
||||
onClick={() => onAddToCompare(school)}
|
||||
>
|
||||
{isInCompare ? '✓ Comparing' : '+ Compare'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,9 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
/* Above the pinned results toolbar (1001), the floating List/Map button
|
||||
(1002) and the comparison toast (2000): a modal covers the page. */
|
||||
z-index: 2100;
|
||||
padding: 1rem;
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
@@ -31,6 +33,10 @@
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.modal:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateY(-20px);
|
||||
@@ -96,6 +102,14 @@
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Clears the iPhone home indicator when the modal is a bottom sheet. */
|
||||
.footer {
|
||||
flex-shrink: 0;
|
||||
padding: 0.75rem 1rem calc(0.75rem + env(safe-area-inset-bottom, 0px));
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg-card);
|
||||
}
|
||||
|
||||
/* Scrollbar styles */
|
||||
.content::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
'use client';
|
||||
|
||||
import { useEffect, useCallback, useRef } from 'react';
|
||||
import { useEffect, useCallback, useId, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import styles from './Modal.module.css';
|
||||
|
||||
@@ -15,10 +15,14 @@ interface ModalProps {
|
||||
children: React.ReactNode;
|
||||
title?: string;
|
||||
size?: 'small' | 'medium' | 'large';
|
||||
/** Pinned below the scrolling content, so its actions stay in reach. */
|
||||
footer?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function Modal({ isOpen, onClose, children, title, size = 'medium' }: ModalProps) {
|
||||
export function Modal({ isOpen, onClose, children, title, size = 'medium', footer }: ModalProps) {
|
||||
const overlayRef = useRef<HTMLDivElement>(null);
|
||||
const dialogRef = useRef<HTMLDivElement>(null);
|
||||
const titleId = useId();
|
||||
|
||||
const handleEscape = useCallback((e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
@@ -41,6 +45,17 @@ export function Modal({ isOpen, onClose, children, title, size = 'medium' }: Mod
|
||||
};
|
||||
}, [isOpen, handleEscape]);
|
||||
|
||||
// Focus moves into the dialog when it opens and back to whatever opened it
|
||||
// when it closes. A child that has already taken focus (an autoFocus input)
|
||||
// keeps it: children's effects run before this one.
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
const opener = document.activeElement as HTMLElement | null;
|
||||
const dialog = dialogRef.current;
|
||||
if (dialog && !dialog.contains(document.activeElement)) dialog.focus();
|
||||
return () => opener?.focus?.();
|
||||
}, [isOpen]);
|
||||
|
||||
// Pin the overlay to the VISUAL viewport, not the layout viewport. On mobile
|
||||
// the on-screen keyboard shrinks the visual viewport but not the layout one,
|
||||
// so a `position: fixed; inset: 0` overlay keeps full height — leaving the
|
||||
@@ -77,9 +92,16 @@ export function Modal({ isOpen, onClose, children, title, size = 'medium' }: Mod
|
||||
|
||||
return createPortal(
|
||||
<div ref={overlayRef} className={styles.overlay} onClick={handleOverlayClick}>
|
||||
<div className={`${styles.modal} ${styles[size]}`}>
|
||||
<div
|
||||
ref={dialogRef}
|
||||
className={`${styles.modal} ${styles[size]}`}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={title ? titleId : undefined}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div className={styles.header}>
|
||||
{title && <h2 className={styles.title}>{title}</h2>}
|
||||
{title && <h2 id={titleId} className={styles.title}>{title}</h2>}
|
||||
<button
|
||||
className={styles.closeButton}
|
||||
onClick={onClose}
|
||||
@@ -103,6 +125,7 @@ export function Modal({ isOpen, onClose, children, title, size = 'medium' }: Mod
|
||||
<div className={styles.content}>
|
||||
{children}
|
||||
</div>
|
||||
{footer && <div className={styles.footer}>{footer}</div>}
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
|
||||
@@ -220,7 +220,16 @@
|
||||
.vsNationalFlat { font-size: 0.7rem; color: var(--text-muted); }
|
||||
|
||||
/* ── Mobile ──────────────────────────────────────────── */
|
||||
@media (max-width: 640px) {
|
||||
/*
|
||||
* Narrow: content full width, actions in a row beneath. Keyed to the list the
|
||||
* row sits in, not the screen, because the same row fills the phone list and
|
||||
* the ~430px list beside the map on desktop. HomeView makes its lists a
|
||||
* `results` container; outside one, the row keeps its wide layout, which is
|
||||
* why rowContainerGuard.test.ts fails if anything else renders this row.
|
||||
* 608px is exact: below 769px the page pads 1rem each side, so a 640px screen
|
||||
* gives a 608px list, matching the old max-width: 640px media query.
|
||||
*/
|
||||
@container results (max-width: 608px) {
|
||||
.row {
|
||||
flex-wrap: wrap;
|
||||
padding: 0.875rem;
|
||||
|
||||
@@ -232,7 +232,16 @@
|
||||
}
|
||||
|
||||
/* ── Mobile ──────────────────────────────────────────── */
|
||||
@media (max-width: 640px) {
|
||||
/*
|
||||
* Narrow: content full width, actions in a row beneath. Keyed to the list the
|
||||
* row sits in, not the screen, because the same row fills the phone list and
|
||||
* the ~430px list beside the map on desktop. HomeView makes its lists a
|
||||
* `results` container; outside one, the row keeps its wide layout, which is
|
||||
* why rowContainerGuard.test.ts fails if anything else renders this row.
|
||||
* 608px is exact: below 769px the page pads 1rem each side, so a 640px screen
|
||||
* gives a 608px list, matching the old max-width: 640px media query.
|
||||
*/
|
||||
@container results (max-width: 608px) {
|
||||
.row {
|
||||
flex-wrap: wrap;
|
||||
padding: 0.875rem;
|
||||
|
||||
@@ -235,6 +235,9 @@ export function getVariabilityLabel(stdDev: number | null): string {
|
||||
// Validation
|
||||
// ============================================================================
|
||||
|
||||
/** Radius a postcode search uses until the user picks another. */
|
||||
export const DEFAULT_RADIUS_MILES = 0.5;
|
||||
|
||||
/**
|
||||
* Validate UK postcode format
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user