Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
355a5a841c | ||
|
|
96deab7d58 | ||
|
|
e9886361d2 | ||
|
|
8ebe461435 | ||
|
|
2002529137 | ||
|
|
bd7c8593d9 | ||
|
|
0c414680fd | ||
|
|
e211e1376d | ||
|
|
74418ca6b9 |
No files matched your search
+6
-4
@@ -736,7 +736,7 @@ async def get_schools(
|
|||||||
None, description="Filter by local authority", max_length=100
|
None, description="Filter by local authority", max_length=100
|
||||||
),
|
),
|
||||||
school_type: Optional[str] = Query(None, description="Filter by school type", 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),
|
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"),
|
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"),
|
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
|
# Phase filter — uses PHASE_GROUPS so all-through/middle schools appear
|
||||||
# in the correct phase(s) rather than being invisible to both filters.
|
# 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:
|
if phase:
|
||||||
phase_lower = phase.lower().replace("_", "-")
|
phase_lower = phase.lower().replace("_", "-")
|
||||||
allowed = PHASE_GROUPS.get(phase_lower)
|
allowed = PHASE_GROUPS.get(phase_lower, {phase_lower})
|
||||||
if allowed:
|
df_latest = df_latest[df_latest["phase"].fillna("").str.lower().isin(allowed)]
|
||||||
df_latest = df_latest[df_latest["phase"].str.lower().isin(allowed)]
|
|
||||||
|
|
||||||
# Secondary-specific filters (after phase filter)
|
# Secondary-specific filters (after phase filter)
|
||||||
if gender:
|
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") == []
|
||||||
@@ -270,6 +270,34 @@ test('searching by name returns school results', async ({ page }) => {
|
|||||||
test('searching by postcode returns nearby schools', async ({ page }) => {
|
test('searching by postcode returns nearby schools', async ({ page }) => {
|
||||||
await searchByName(page, 'B1 1BB');
|
await searchByName(page, 'B1 1BB');
|
||||||
await expect(schoolLinks(page).first()).toBeVisible({ timeout: 15_000 });
|
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 }) => {
|
test('a report-card school shows a Report Card badge in search results, not its old grade', async ({ page }) => {
|
||||||
@@ -547,6 +575,38 @@ test('the results toolbar stays pinned with its List/Map switch', async ({ page
|
|||||||
.toHaveAttribute('aria-pressed', 'true');
|
.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 = '/?postcode=B1%201BB&radius=1';
|
||||||
|
// 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
|
* 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
|
* the left, the map filling the rest of the screen, and a card on the map for
|
||||||
|
|||||||
@@ -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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -18,7 +18,10 @@ jest.mock('@/lib/api', () => ({
|
|||||||
fetchNationalAverages: jest.fn(async () => ({})),
|
fetchNationalAverages: jest.fn(async () => ({})),
|
||||||
fetchLAaverages: jest.fn(async () => ({ secondary: { attainment_8_by_la: {} } })),
|
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/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> }));
|
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(),
|
fetchNationalAverages: jest.fn(),
|
||||||
fetchLAaverages: jest.fn(async () => ({ secondary: { attainment_8_by_la: {} } })),
|
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', () => ({
|
jest.mock('@/components/SchoolMap', () => ({
|
||||||
SchoolMap: ({ selectedUrn, radiusMiles, onMarkerClick, schools }: {
|
SchoolMap: ({ selectedUrn, radiusMiles, onMarkerClick, schools }: {
|
||||||
selectedUrn: number | null; radiusMiles?: number;
|
selectedUrn: number | null; radiusMiles?: number;
|
||||||
@@ -177,5 +180,16 @@ it('lets a keyboard pick a pin from the list, with a real button', async () => {
|
|||||||
it('keeps the postcode in the heading in list view, where there is room', async () => {
|
it('keeps the postcode in the heading in list view, where there is room', async () => {
|
||||||
await renderMap();
|
await renderMap();
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'List' }));
|
fireEvent.click(screen.getByRole('button', { name: 'List' }));
|
||||||
expect(screen.getByRole('heading', { name: '3 schools within 1.0 miles of SW196AR' })).toBeInTheDocument();
|
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();
|
||||||
});
|
});
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
import { absoluteUrl } from '@/lib/site';
|
import { absoluteUrl } from '@/lib/site';
|
||||||
import type { Metadata } from 'next';
|
import type { Metadata } from 'next';
|
||||||
import { fetchSchools, fetchFilters, fetchDataInfo } from '@/lib/api';
|
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 { HomeView } from '@/components/HomeView';
|
||||||
import { getFlags } from '@/lib/flags';
|
import { getFlags } from '@/lib/flags';
|
||||||
import { HowItWorksSection } from '@/components/HowItWorksSection';
|
import { HowItWorksSection } from '@/components/HowItWorksSection';
|
||||||
@@ -71,7 +71,9 @@ export default async function HomePage({ searchParams }: HomePageProps) {
|
|||||||
|
|
||||||
// Parse search params
|
// Parse search params
|
||||||
const page = parseInt(params.page || '1');
|
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
|
// Check if user has performed a search
|
||||||
const hasSearchParams = !!(
|
const hasSearchParams = !!(
|
||||||
|
|||||||
@@ -40,8 +40,19 @@
|
|||||||
margin: 0 auto 1.5rem;
|
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) {
|
.filterBar:not(.heroMode) {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
@@ -56,10 +67,34 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.filterBar:not(.heroMode) .searchSection {
|
.filterBar:not(.heroMode) .searchSection {
|
||||||
flex: 1 1 320px;
|
flex: 1 1 0;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.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; see the 640px block. */
|
/* Only phones fold the form away; see the 640px block. */
|
||||||
.searchSummary {
|
.searchSummary {
|
||||||
display: none;
|
display: none;
|
||||||
@@ -324,8 +359,9 @@
|
|||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
/* A select is as wide as its longest option, and a school type can run to
|
/* 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. */
|
"Academy special sponsor led". Cap it; the chosen value truncates. The cap
|
||||||
max-width: 14rem;
|
is part of the one-line budget above. */
|
||||||
|
max-width: 11rem;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -363,6 +399,7 @@
|
|||||||
pushing the results off a short screen. The 3px gutter keeps the selects'
|
pushing the results off a short screen. The 3px gutter keeps the selects'
|
||||||
focus rings clear of the scroll clip. */
|
focus rings clear of the scroll clip. */
|
||||||
.filters {
|
.filters {
|
||||||
|
order: 2;
|
||||||
flex-basis: 100%;
|
flex-basis: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 0.625rem;
|
gap: 0.625rem;
|
||||||
@@ -579,6 +616,12 @@
|
|||||||
display: none;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
/* Bleeds to the screen edge so a chip scrolls out from under it, rather than
|
/* 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
|
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
|
1rem at this width (HomeView.module.css, .resultsToolbar). The 4px of
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import { useState, useCallback, useTransition, useRef, useEffect } from "react";
|
import { useState, useCallback, useTransition, useRef, useEffect } from "react";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
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 { track } from "@/lib/analytics";
|
||||||
import { useSchoolSuggest } from "@/hooks/useSchoolSuggest";
|
import { useSchoolSuggest } from "@/hooks/useSchoolSuggest";
|
||||||
import { SuggestList, suggestOptionId } from "./SuggestList";
|
import { SuggestList, suggestOptionId } from "./SuggestList";
|
||||||
@@ -22,6 +22,12 @@ interface FilterBarProps {
|
|||||||
geoError?: string | null;
|
geoError?: string | null;
|
||||||
/** Server-read feature flag. Off means no listener, no fetch, no markup. */
|
/** Server-read feature flag. Off means no listener, no fetch, no markup. */
|
||||||
autosuggest?: boolean;
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -54,6 +60,7 @@ export function FilterBar({
|
|||||||
geoState = "idle",
|
geoState = "idle",
|
||||||
geoError,
|
geoError,
|
||||||
autosuggest = false,
|
autosuggest = false,
|
||||||
|
viewSwitch,
|
||||||
}: FilterBarProps) {
|
}: FilterBarProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
@@ -63,7 +70,7 @@ export function FilterBar({
|
|||||||
|
|
||||||
const currentSearch = searchParams.get("search") || "";
|
const currentSearch = searchParams.get("search") || "";
|
||||||
const currentPostcode = searchParams.get("postcode") || "";
|
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 initialOmniValue = currentPostcode || currentSearch;
|
||||||
|
|
||||||
const [omniValue, setOmniValue] = useState(initialOmniValue);
|
const [omniValue, setOmniValue] = useState(initialOmniValue);
|
||||||
@@ -262,7 +269,7 @@ export function FilterBar({
|
|||||||
if (isPostcode) {
|
if (isPostcode) {
|
||||||
updateURL({
|
updateURL({
|
||||||
postcode: cleaned.toUpperCase(),
|
postcode: cleaned.toUpperCase(),
|
||||||
radius: currentRadius || "1",
|
radius: currentRadius,
|
||||||
search: "",
|
search: "",
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -295,7 +302,10 @@ export function FilterBar({
|
|||||||
const laOptions =
|
const laOptions =
|
||||||
resultFilters?.local_authorities ?? filters.local_authorities;
|
resultFilters?.local_authorities ?? filters.local_authorities;
|
||||||
const typeOptions = resultFilters?.school_types ?? filters.school_types;
|
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 genderOptions = resultFilters?.genders ?? filters.genders ?? [];
|
||||||
const admissionsPolicyOptions =
|
const admissionsPolicyOptions =
|
||||||
resultFilters?.admissions_policies ?? filters.admissions_policies ?? [];
|
resultFilters?.admissions_policies ?? filters.admissions_policies ?? [];
|
||||||
@@ -449,6 +459,9 @@ export function FilterBar({
|
|||||||
|
|
||||||
{!isHero && (
|
{!isHero && (
|
||||||
<>
|
<>
|
||||||
|
{viewSwitch && (
|
||||||
|
<div className={styles.viewSwitchSlot}>{viewSwitch}</div>
|
||||||
|
)}
|
||||||
{/* Every control here is a real <select> or <button>, drawn as a
|
{/* Every control here is a real <select> or <button>, drawn as a
|
||||||
pill. On phones the row scrolls sideways rather than wrapping, so
|
pill. On phones the row scrolls sideways rather than wrapping, so
|
||||||
the pinned toolbar stays two lines tall. */}
|
the pinned toolbar stays two lines tall. */}
|
||||||
@@ -468,6 +481,7 @@ export function FilterBar({
|
|||||||
aria-label="Distance"
|
aria-label="Distance"
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
>
|
>
|
||||||
|
<option value="0.25">Within 0.25 miles</option>
|
||||||
<option value="0.5">Within 0.5 miles</option>
|
<option value="0.5">Within 0.5 miles</option>
|
||||||
<option value="1">Within 1 mile</option>
|
<option value="1">Within 1 mile</option>
|
||||||
<option value="3">Within 3 miles</option>
|
<option value="3">Within 3 miles</option>
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { useComparisonContext } from '@/context/ComparisonContext';
|
|||||||
import { fetchSchools, fetchLAaverages, fetchNationalAverages } from '@/lib/api';
|
import { fetchSchools, fetchLAaverages, fetchNationalAverages } from '@/lib/api';
|
||||||
import type { SchoolsResponse, Filters, School } from '@/lib/types';
|
import type { SchoolsResponse, Filters, School } from '@/lib/types';
|
||||||
import { track } from '@/lib/analytics';
|
import { track } from '@/lib/analytics';
|
||||||
|
import { DEFAULT_RADIUS_MILES } from '@/lib/utils';
|
||||||
import styles from './HomeView.module.css';
|
import styles from './HomeView.module.css';
|
||||||
|
|
||||||
interface HomeViewProps {
|
interface HomeViewProps {
|
||||||
@@ -340,6 +341,7 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
|||||||
setIsLoadingMap(true);
|
setIsLoadingMap(true);
|
||||||
const params: Record<string, any> = {};
|
const params: Record<string, any> = {};
|
||||||
searchParams.forEach((value, key) => { params[key] = value; });
|
searchParams.forEach((value, key) => { params[key] = value; });
|
||||||
|
params.radius ??= DEFAULT_RADIUS_MILES;
|
||||||
params.page = 1;
|
params.page = 1;
|
||||||
params.page_size = 500;
|
params.page_size = 500;
|
||||||
fetchSchools(params, { cache: 'no-store', signal: controller.signal })
|
fetchSchools(params, { cache: 'no-store', signal: controller.signal })
|
||||||
@@ -419,7 +421,7 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
|||||||
setGeoState('idle');
|
setGeoState('idle');
|
||||||
track('near_me_used', { outcome: 'granted' });
|
track('near_me_used', { outcome: 'granted' });
|
||||||
track('search_submitted', { query: postcode, via: 'near_me', has_postcode: true, filters_active: '', filters_count: 0 });
|
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 {
|
} else {
|
||||||
track('near_me_used', { outcome: 'no_postcode' });
|
track('near_me_used', { outcome: 'no_postcode' });
|
||||||
setGeoState('error');
|
setGeoState('error');
|
||||||
@@ -459,8 +461,9 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
|||||||
// open card); only the list beside it is sorted.
|
// open card); only the list beside it is sorted.
|
||||||
const mapResultSchools = mapSchools.length > 0 ? mapSchools : initialSchools.schools;
|
const mapResultSchools = mapSchools.length > 0 ? mapSchools : initialSchools.schools;
|
||||||
const mapListSchools = sortSchools(mapResultSchools);
|
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
|
const radiusMiles = initialSchools.location_info
|
||||||
? Number((initialSchools.location_info.radius / 1.60934).toFixed(1))
|
? Number((initialSchools.location_info.radius / 1.60934).toFixed(2))
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
// Empty-results sentinel: track when a search returns nothing.
|
// Empty-results sentinel: track when a search returns nothing.
|
||||||
@@ -594,8 +597,8 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
|||||||
drops the postcode, which the search box just above already shows. */}
|
drops the postcode, which the search box just above already shows. */}
|
||||||
{isMapView && radiusMiles != null
|
{isMapView && radiusMiles != null
|
||||||
? `${schoolCount} within ${radiusMiles} mile${radiusMiles === 1 ? '' : 's'}`
|
? `${schoolCount} within ${radiusMiles} mile${radiusMiles === 1 ? '' : 's'}`
|
||||||
: isLocationSearch && initialSchools.location_info
|
: isLocationSearch && radiusMiles != null && initialSchools.location_info
|
||||||
? `${schoolCount} within ${(initialSchools.location_info.radius / 1.60934).toFixed(1)} miles of ${initialSchools.location_info.postcode}`
|
? `${schoolCount} within ${radiusMiles} mile${radiusMiles === 1 ? '' : 's'} of ${initialSchools.location_info.postcode}`
|
||||||
: `${schoolCount} found`
|
: `${schoolCount} found`
|
||||||
}
|
}
|
||||||
</h2>
|
</h2>
|
||||||
@@ -713,29 +716,29 @@ export function HomeView({ initialSchools, filters, totalSchools, howItWorks, ed
|
|||||||
geoState={geoState}
|
geoState={geoState}
|
||||||
geoError={geoError}
|
geoError={geoError}
|
||||||
autosuggest={autosuggest}
|
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>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -235,6 +235,9 @@ export function getVariabilityLabel(stdDev: number | null): string {
|
|||||||
// Validation
|
// Validation
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
|
/** Radius a postcode search uses until the user picks another. */
|
||||||
|
export const DEFAULT_RADIUS_MILES = 0.5;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate UK postcode format
|
* Validate UK postcode format
|
||||||
*/
|
*/
|
||||||
|
|||||||
Reference in new issue
Block a user