diff --git a/Makefile.data b/Makefile.data index a1cf3e4..0e12cd4 100644 --- a/Makefile.data +++ b/Makefile.data @@ -42,6 +42,8 @@ INSPIRE_DIR := $(DATA_DIR)/inspire OA_BOUNDARIES := $(DATA_DIR)/oa_boundaries.gpkg UPRN_LOOKUP := $(DATA_DIR)/uprn_lookup.parquet PC_BOUNDARIES := $(MANUAL_DATA)/postcode_boundaries +TRANSIT_DIR := $(DATA_DIR)/transit +TRANSIT_STAMP := $(TRANSIT_DIR)/.done # Sentinel files for directory targets (Make doesn't track directories well) GEOSURE_STAMP := $(GEOSURE_DIR)/.done @@ -55,7 +57,7 @@ PMTILES_VERSION := 1.22.3 download-arcgis download-price-paid download-deprivation download-ethnicity \ download-naptan download-pois download-ofsted download-broadband \ download-postcodes download-geosure download-noise download-inspire \ - download-oa-boundaries download-uprn-lookup \ + download-oa-boundaries download-uprn-lookup download-transit-network \ transform-pois transform-epc-pp transform-crime transform-poi-proximity \ transform-school-proximity transform-geosure transform-postcode-boundaries \ generate-postcode-boundaries \ @@ -78,6 +80,7 @@ download-noise: $(NOISE) download-inspire: $(INSPIRE_STAMP) download-oa-boundaries: $(OA_BOUNDARIES) download-uprn-lookup: $(UPRN_LOOKUP) +download-transit-network: $(TRANSIT_STAMP) transform-pois: $(POIS_FILTERED) transform-epc-pp: $(EPC_PP) transform-crime: $(CRIME) @@ -152,6 +155,10 @@ $(OA_BOUNDARIES): $(UPRN_LOOKUP): uv run python -m pipeline.download.uprn_lookup --output $@ +$(TRANSIT_STAMP): + uv run python -m pipeline.download.transit_network --output $(TRANSIT_DIR) + @touch $@ + # ── Journey times (requires TFL_API_KEY) ────────────────────────────────────── $(JT_BANK): diff --git a/Taskfile.yml b/Taskfile.yml index 18834bf..b02d9ba 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -16,6 +16,11 @@ tasks: cmds: - uv run python -m pipeline.download.map_assets --output frontend/public/assets + download:greenspace: + desc: Extract park/water polygons from OSM PBF for postcode boundary trimming + cmds: + - uv run python -m pipeline.download.greenspace_water --output data/greenspace_water.parquet {{.CLI_ARGS}} + test: desc: Run all tests (Python and Rust) cmds: @@ -27,6 +32,7 @@ tasks: - uv run -m pipeline.utils.test_fuzzy_join - uv run pytest pipeline/utils/test_haversine.py - uv run pytest pipeline/utils/test_poi_counts.py + - uv run pytest pipeline/transform/postcode_boundaries/test_postcode_boundaries.py test:server: desc: Run Rust backend tests diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 11b4bd7..4564ee9 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,6 +1,5 @@ import { useState, useEffect, useCallback, useMemo } from 'react'; import MapPage, { type ExportState } from './components/map/MapPage'; -import LearnPage from './components/learn/LearnPage'; import PricingPage from './components/pricing/PricingPage'; import HomePage from './components/home/HomePage'; import SavedSearchesPage from './components/saved-searches/SavedSearchesPage'; @@ -26,9 +25,7 @@ function pageToPath(page: Page): string { switch (page) { case 'dashboard': return '/dashboard'; - case 'learn': - return '/learn'; - case 'saved-searches': +case 'saved-searches': return '/saved'; case 'pricing': return '/pricing'; @@ -39,8 +36,7 @@ function pageToPath(page: Page): string { function pathToPage(pathname: string): Page | null { if (pathname === '/dashboard') return 'dashboard'; - if (pathname === '/learn') return 'learn'; - if (pathname === '/saved') return 'saved-searches'; +if (pathname === '/saved') return 'saved-searches'; if (pathname === '/pricing') return 'pricing'; if (pathname === '/') return 'home'; return null; @@ -81,7 +77,7 @@ export default function App() { // Backward compat: dashboard params on unknown path const params = new URLSearchParams(window.location.search); - if (params.has('lat') || params.has('filter') || params.has('poi') || params.has('tab') || params.has('v') || params.has('f')) { + if (params.has('lat') || params.has('filter') || params.has('poi') || params.has('tab') || params.has('v') || params.has('f') || params.has('dest')) { // Rewrite URL to /dashboard keeping query params window.history.replaceState({ page: 'dashboard' }, '', `/dashboard${window.location.search}`); return 'dashboard'; @@ -207,6 +203,7 @@ export default function App() { onNavigateTo={() => {}} screenshotMode ogMode={isOgMode} + initialTravelTime={urlState.travelTime} /> ); } @@ -236,8 +233,6 @@ export default function App() { /> {activePage === 'home' ? ( navigateTo('dashboard')} onOpenPricing={() => navigateTo('pricing')} theme={theme} features={features} /> - ) : activePage === 'learn' ? ( - ) : activePage === 'pricing' ? ( navigateTo('dashboard')} /> ) : activePage === 'saved-searches' ? ( @@ -264,6 +259,7 @@ export default function App() { onNavigateTo={navigateTo} onExportStateChange={setExportState} isMobile={isMobile} + initialTravelTime={urlState.travelTime} /> )} {showAuthModal && ( diff --git a/frontend/src/components/data-sources/DataSourcesPage.tsx b/frontend/src/components/data-sources/DataSourcesPage.tsx index 1e1ac70..650656c 100644 --- a/frontend/src/components/data-sources/DataSourcesPage.tsx +++ b/frontend/src/components/data-sources/DataSourcesPage.tsx @@ -165,7 +165,7 @@ export default function DataSourcesPage() {

{source.name}

- + {source.license} diff --git a/frontend/src/components/faq/FAQPage.tsx b/frontend/src/components/faq/FAQPage.tsx index 34b67de..90ac142 100644 --- a/frontend/src/components/faq/FAQPage.tsx +++ b/frontend/src/components/faq/FAQPage.tsx @@ -10,7 +10,7 @@ const FAQ_ITEMS: FAQItem[] = [ { question: 'What is this application?', answer: - 'Perfect Postcodes is an interactive map that visualises property-level data across England and Wales. It combines Land Registry sale prices, EPC energy certificates, TfL journey times, deprivation indices, crime statistics, broadband speeds, school ratings, road noise levels, ethnicity demographics, and OpenStreetMap points of interest into a single explorable view.', + 'Perfect Postcode is an interactive map that visualises property-level data across England and Wales. It combines Land Registry sale prices, EPC energy certificates, TfL journey times, deprivation indices, crime statistics, broadband speeds, school ratings, road noise levels, ethnicity demographics, and OpenStreetMap points of interest into a single explorable view.', }, { question: 'Where does the data come from?', @@ -101,7 +101,7 @@ export default function FAQPage() { Frequently Asked Questions

- Common questions about how Perfect Postcodes works, where the data comes from, and how to use the + Common questions about how Perfect Postcode works, where the data comes from, and how to use the map.

diff --git a/frontend/src/components/learn/LearnPage.tsx b/frontend/src/components/learn/LearnPage.tsx new file mode 100644 index 0000000..c04ccd4 --- /dev/null +++ b/frontend/src/components/learn/LearnPage.tsx @@ -0,0 +1,399 @@ +import { useEffect, useState, useRef } from 'react'; +import { ChevronIcon } from '../ui/icons/ChevronIcon'; + +type LearnTab = 'data-sources' | 'faq'; + +const DATA_SOURCES = [ + { + id: 'price-paid', + name: 'Price Paid Data', + origin: 'HM Land Registry', + use: 'Complete historical property sale prices for England and Wales. Used for the last known sale price of each property.', + url: 'https://www.gov.uk/government/statistical-data-sets/price-paid-data-downloads', + license: 'Open Government Licence v3.0', + }, + { + id: 'epc', + name: 'Energy Performance Certificates (EPC)', + origin: 'Ministry of Housing, Communities & Local Government', + use: 'Domestic Energy Performance Certificates providing floor area, number of rooms, construction age, energy ratings, property type, and built form. Fuzzy-joined with Price Paid records by address within postcode buckets. Property owners can opt out of public disclosure.', + optOutUrl: 'https://www.gov.uk/guidance/energy-performance-certificates-opt-out-of-public-disclosure', + url: 'https://epc.opendatacommunities.org/downloads/domestic', + license: 'Open Government Licence v3.0', + }, + { + id: 'nspl', + name: 'National Statistics Postcode Lookup (NSPL)', + origin: 'ONS / ArcGIS', + use: 'Maps postcodes to latitude/longitude, LSOA, and Output Area codes for geolocation and joining area-level datasets.', + url: 'https://www.arcgis.com/sharing/rest/content/items/077631e063eb4e1ab43575d01381ec33/data', + license: 'Open Government Licence v3.0', + }, + { + id: 'iod', + name: 'English Indices of Deprivation 2025', + origin: 'Ministry of Housing, Communities & Local Government', + use: 'Relative deprivation scores for 33,755 LSOAs across domains: Income, Employment, Education, Health, Crime, Living Environment, and sub-domains. Joined to properties via LSOA code.', + url: 'https://www.gov.uk/government/statistics/english-indices-of-deprivation-2025', + license: 'Open Government Licence v3.0', + }, + { + id: 'ethnicity', + name: 'Population by Ethnicity (2021 Census)', + origin: 'ONS', + use: 'Population percentages by ethnic group (Asian, Black, Mixed, White, Other) per Local Authority. Joined via Local Authority District code.', + url: 'https://www.ethnicity-facts-figures.service.gov.uk/uk-population-by-ethnicity/national-and-regional-populations/regional-ethnic-diversity/latest/#download-the-data', + license: 'Open Government Licence v3.0', + }, + { + id: 'crime', + name: 'Street-level Crime Data', + origin: 'data.police.uk', + use: 'Street-level crime data from 2023 to 2025, aggregated into yearly averages by LSOA and crime type (violence, burglary, anti-social behaviour, drugs, vehicle crime, etc.).', + url: 'https://data.police.uk/data/', + license: 'Open Government Licence v3.0', + }, + { + id: 'tfl-journey-times', + name: 'TfL Journey Times', + origin: 'Transport for London', + use: "Journey time calculations from postcodes to central London destinations (Bank, Waterloo, King's Cross, etc.) via public transport and cycling.", + url: 'https://api-portal.tfl.gov.uk/', + license: 'Powered by TfL Open Data', + }, + { + id: 'osm-pois', + name: 'OpenStreetMap POIs', + origin: 'OpenStreetMap contributors / Geofabrik', + use: 'Points of interest extracted from the Great Britain PBF extract. Covers amenities, shops, healthcare, leisure, tourism, and more. Filtered and remapped to friendly category names.', + url: 'https://download.geofabrik.de/europe/great-britain-latest.osm.pbf', + license: 'Open Data Commons Open Database License (ODbL)', + }, + { + id: 'naptan', + name: 'NaPTAN (Public Transport Stops)', + origin: 'Department for Transport', + use: 'National Public Transport Access Nodes providing station and stop locations (rail, bus, metro/tram, ferry, airport), merged into the POI dataset.', + url: 'https://naptan.dft.gov.uk/naptan/schema/2.4/doc/NaPTANSchemaGuide-2.4-v0.57.pdf', + license: 'Open Government Licence v3.0', + }, + { + id: 'noise', + name: 'Defra Noise Mapping', + origin: 'Defra / Environment Agency', + use: 'Strategic noise mapping Round 4 (2022) for road, rail, and airport sources. Lden (day-evening-night 24h weighted average) at 10m grid resolution, modelled at 4m above ground. Sampled at postcode centroids via WCS GeoTIFF tiles.', + url: 'https://environment.data.gov.uk/spatialdata/road-noise-all-metrics-england-round-4/wcs', + license: 'Open Government Licence v3.0', + }, + { + id: 'ofsted', + name: 'Ofsted School Inspections', + origin: 'Ofsted', + use: 'Latest inspection outcomes for state-funded schools (as at April 2025). Averaged per postcode to give a local school quality score (1=Outstanding to 4=Inadequate).', + url: 'https://www.gov.uk/government/statistical-data-sets/monthly-management-information-ofsteds-school-inspections-outcomes', + license: 'Open Government Licence v3.0', + }, + { + id: 'broadband', + name: 'Ofcom Broadband Performance', + origin: 'Ofcom', + use: 'Fixed broadband coverage and speeds by Output Area from Connected Nations 2025. Includes max download/upload speeds across different speed tiers.', + url: 'https://www.ofcom.org.uk/phones-and-broadband/coverage-and-speeds/connected-nations-20252/data-downloads-2025', + license: 'Open Government Licence v3.0', + }, + { + id: 'geosure', + name: 'GeoSure Ground Stability', + origin: 'Ordnance Survey', + use: 'Ground stability hazard ratings on a 5km hex grid covering Great Britain. Six risk categories (collapsible deposits, compressible ground, landslides, running sand, shrink-swell, and soluble rocks) rated Low, Moderate, or Significant. Spatial-joined to postcodes via centroid intersection.', + url: 'https://osdatahub.os.uk/downloads/open/GeoSure', + license: 'Open Government Licence v3.0', + }, + { + id: 'council-tax', + name: 'Council Tax Levels 2025-26', + origin: 'Ministry of Housing, Communities & Local Government', + use: 'Annual council tax rates for Bands A-H for all 296 billing authorities in England, for a dwelling occupied by two adults. Joined to properties via local authority district code from the NSPL postcode lookup.', + url: 'https://www.gov.uk/government/statistics/council-tax-levels-set-by-local-authorities-in-england-2025-to-2026', + license: 'Open Government Licence v3.0', + }, +]; + +interface FAQItem { + question: string; + answer: string; +} + +const FAQ_ITEMS: FAQItem[] = [ + { + question: 'What is this application?', + answer: + 'Perfect Postcode is an interactive map that visualises property-level data across England and Wales. It combines Land Registry sale prices, EPC energy certificates, TfL journey times, deprivation indices, crime statistics, broadband speeds, school ratings, road noise levels, ethnicity demographics, and OpenStreetMap points of interest into a single explorable view.', + }, + { + question: 'Where does the data come from?', + answer: + 'All data comes from open government and community sources. Property prices are from HM Land Registry, energy certificates from MHCLG, transport times from TfL, deprivation scores from the English Indices of Deprivation 2025, crime data from data.police.uk, school ratings from Ofsted, broadband from Ofcom, noise from Defra, ethnicity from the 2021 Census, and points of interest from OpenStreetMap. See the Data Sources tab for full details and links.', + }, + { + question: 'What are the coloured hexagons on the map?', + answer: + 'The map uses H3 hexagons to aggregate property data at different zoom levels. Each hexagon summarises the properties within it. The colour represents the value of whichever feature you have pinned or are actively filtering — for example, average price or energy rating. Zoom in to see smaller, more detailed hexagons; zoom out for a broader overview.', + }, + { + question: 'How do filters work?', + answer: + 'Use the Filters panel on the left to narrow down properties. Add a filter by clicking a feature name, then drag the range slider to set minimum and maximum values. For categorical features like property type, select or deselect individual values. Only hexagons containing properties that match all active filters are shown. Filters are combined with AND logic — every property must satisfy every filter.', + }, + { + question: 'What does the eye icon do on a filter?', + answer: + "The eye icon pins a feature as the colour source for the hexagon layer. When pinned, hexagons are coloured by that feature's value range even when you are not actively dragging its slider. This lets you visualise one feature while filtering on others. Click the eye icon again to unpin.", + }, + { + question: 'How fresh is the data?', + answer: + 'Property prices cover all Land Registry transactions up to the most recent quarterly release. EPC data includes certificates issued up to the latest available download. Crime data spans 2023–2025 as yearly averages. TfL journey times are computed from current timetables. Deprivation indices are from the 2025 release. School ratings reflect the latest Ofsted inspections as at April 2025. Broadband data is from Ofcom Connected Nations 2025.', + }, + { + question: 'How are EPC records matched to Land Registry sales?', + answer: + "EPC and Land Registry records don't share a common identifier, so they are fuzzy-joined by address within each postcode bucket. The pipeline uses token-sorted string similarity with special handling for numeric tokens (house numbers, flat numbers). Matches are assigned greedily from highest similarity score downward so each record is used at most once.", + }, + { + question: 'What are Points of Interest (POIs)?', + answer: + 'POIs are places like cafes, schools, supermarkets, GP surgeries, parks, and train stations extracted from OpenStreetMap and the NaPTAN public transport dataset. Use the POI panel on the right to toggle categories on and off. POIs appear as markers on the map when you are zoomed in far enough.', + }, + { + question: 'Can I share a specific view with someone?', + answer: + 'Yes. The URL updates automatically as you pan, zoom, and change filters. Click the Share button in the header to copy the current URL to your clipboard. Anyone who opens that link will see the same view, filters, and active POI categories.', + }, + { + question: 'How do I see individual properties?', + answer: + 'Click on a hexagon to open the Properties panel on the right. It lists all matching properties within that hexagon, showing address, price, and key features. Use "Load more" at the bottom to paginate through large hexagons.', + }, + { + question: 'Why are some hexagons grey?', + answer: + 'Grey hexagons contain properties that have data but fall outside the range of your currently pinned or active feature. This gives you a sense of where properties exist even when their values are outside your selected range.', + }, + { + question: 'Does this work on mobile?', + answer: + 'Yes. On mobile, the dashboard uses a vertical split layout with the map on top and a tabbed panel below for filters, area stats, properties, and POIs. Tapping a hexagon opens a full-screen drawer with the details. The full desktop experience with side-by-side panels is available on screens 768px and wider.', + }, +]; + +function FAQItemCard({ item }: { item: FAQItem }) { + const [open, setOpen] = useState(false); + + return ( +
+ + {open && ( +
+

{item.answer}

+
+ )} +
+ ); +} + +export default function LearnPage() { + const [tab, setTab] = useState('data-sources'); + const [highlightedId, setHighlightedId] = useState(null); + const cardRefs = useRef>({}); + const scrollContainerRef = useRef(null); + + useEffect(() => { + function handleHash() { + const hash = window.location.hash.replace('#', ''); + if (hash === 'faq') { + setTab('faq'); + setHighlightedId(null); + } else if (hash && DATA_SOURCES.some((s) => s.id === hash)) { + setTab('data-sources'); + setHighlightedId(hash); + setTimeout(() => { + cardRefs.current[hash]?.scrollIntoView({ behavior: 'smooth', block: 'center' }); + }, 100); + } else { + setHighlightedId(null); + } + } + handleHash(); + window.addEventListener('hashchange', handleHash); + return () => window.removeEventListener('hashchange', handleHash); + }, []); + + // Scroll to top when switching tabs + useEffect(() => { + scrollContainerRef.current?.scrollTo(0, 0); + }, [tab]); + + const tabClass = (t: LearnTab) => + `px-4 py-2 text-sm font-medium rounded-t border-b-2 ${ + tab === t + ? 'border-teal-500 text-teal-700 dark:text-teal-400' + : 'border-transparent text-warm-500 dark:text-warm-400 hover:text-warm-700 dark:hover:text-warm-300' + }`; + + return ( +
+ {/* Tab bar */} +
+
+ + +
+
+ + {/* Content */} +
+ {tab === 'data-sources' ? ( + <> +
+
+

+ Data Sources +

+

+ This application combines {DATA_SOURCES.length} open datasets covering property + prices, energy performance, transport, demographics, crime, environment, and more. +

+
+ {DATA_SOURCES.map((source) => ( +
{ + cardRefs.current[source.id] = el; + }} + className={`bg-white dark:bg-navy-800 rounded-lg border p-5 ${ + highlightedId === source.id + ? 'border-teal-400 ring-2 ring-teal-400' + : 'border-warm-200 dark:border-navy-700' + }`} + > +
+

+ {source.name} +

+ + {source.license} + +
+

+ Source: {source.origin} +

+

{source.use}

+ + {source.url} + + {'optOutUrl' in source && source.optOutUrl && ( + + )} +
+ ))} +
+
+
+ + + + ) : ( +
+

+ Frequently Asked Questions +

+

+ Common questions about how Perfect Postcode works, where the data comes from, and how + to use the map. +

+
+ {FAQ_ITEMS.map((item, index) => ( + + ))} +
+
+ )} +
+
+ ); +} diff --git a/frontend/src/components/map/FeatureBrowser.tsx b/frontend/src/components/map/FeatureBrowser.tsx index 1367b69..0a9858e 100644 --- a/frontend/src/components/map/FeatureBrowser.tsx +++ b/frontend/src/components/map/FeatureBrowser.tsx @@ -9,6 +9,8 @@ import { groupFeaturesByCategory } from '../../lib/features'; import { FeatureInfoPopup } from '../ui/FeatureInfoPopup'; import { FeatureActions } from '../ui/FeatureIcons'; import { FeatureLabel } from '../ui/FeatureLabel'; +import { RouteIcon, PlusIcon } from '../ui/icons'; +import { IconButton } from '../ui/IconButton'; interface FeatureBrowserProps { availableFeatures: FeatureMeta[]; @@ -19,6 +21,8 @@ interface FeatureBrowserProps { onNavigateToSource?: (slug: string, featureName: string) => void; openInfoFeature?: string | null; onClearOpenInfoFeature?: () => void; + travelTimeEnabled?: boolean; + onEnableTravelTime?: () => void; } export default function FeatureBrowser({ @@ -30,6 +34,8 @@ export default function FeatureBrowser({ onNavigateToSource, openInfoFeature, onClearOpenInfoFeature, + travelTimeEnabled, + onEnableTravelTime, }: FeatureBrowserProps) { const [search, setSearch] = useState(''); const [infoFeature, setInfoFeature] = useState(null); @@ -60,6 +66,26 @@ export default function FeatureBrowser({
+ {!travelTimeEnabled && onEnableTravelTime && (!search || 'travel time journey commute'.includes(search.toLowerCase())) && ( +
+
+
+ +
+ + Travel Time + + + Color by journey time to a destination + +
+
+ onEnableTravelTime()} title="Add travel time"> + + +
+
+ )} {grouped.map((group) => { const isExpanded = isSearching || expandedGroups.has(group.name); return ( diff --git a/frontend/src/components/map/Filters.tsx b/frontend/src/components/map/Filters.tsx index a2c9e78..ec7280e 100644 --- a/frontend/src/components/map/Filters.tsx +++ b/frontend/src/components/map/Filters.tsx @@ -1,14 +1,51 @@ -import { memo, useState } from 'react'; +import { memo, useState, useMemo } from 'react'; import { Slider } from '../ui/Slider'; import { FilterIcon, LightbulbIcon } from '../ui/icons'; import { EmptyState } from '../ui/EmptyState'; +import { CollapsibleGroupHeader } from '../ui/CollapsibleGroupHeader'; +import { PillToggle } from '../ui/PillToggle'; +import { PillGroup } from '../ui/PillGroup'; import type { FeatureMeta, FeatureFilters } from '../../types'; import { formatFilterValue } from '../../lib/format'; +import { groupFeaturesByCategory } from '../../lib/features'; +import { useCollapsibleGroups } from '../../hooks/useCollapsibleGroups'; import InfoPopup from '../ui/InfoPopup'; import { FeatureInfoPopup } from '../ui/FeatureInfoPopup'; import { FeatureActions } from '../ui/FeatureIcons'; import { FeatureLabel } from '../ui/FeatureLabel'; import FeatureBrowser from './FeatureBrowser'; +import { TravelTimeCard } from './TravelTimeCard'; +import type { TransportMode } from '../../hooks/useTravelTime'; + +function SliderLabels({ + min, + max, + value, +}: { + min: number; + max: number; + value: [number, number]; +}) { + const range = max - min || 1; + const leftPct = ((value[0] - min) / range) * 100; + const rightPct = ((value[1] - min) / range) * 100; + return ( +
+ + {formatFilterValue(value[0])} + + + {formatFilterValue(value[1])} + +
+ ); +} interface FiltersProps { features: FeatureMeta[]; @@ -22,15 +59,23 @@ interface FiltersProps { onDragStart: (name: string) => void; onDragChange: (value: [number, number]) => void; onDragEnd: () => void; - zoom: number; - itemCount: number; - usePostcodeView: boolean; pinnedFeature: string | null; onTogglePin: (name: string) => void; onCancelPin: () => void; onNavigateToSource?: (slug: string, featureName: string) => void; openInfoFeature?: string | null; onClearOpenInfoFeature?: () => void; + travelTimeEnabled: boolean; + travelTimeDestination: [number, number] | null; + travelTimeDestinationLabel: string; + travelTimeMode: TransportMode; + travelTimeRange: [number, number] | null; + travelTimeDataRange: [number, number] | null; + onTravelTimeEnable: () => void; + onTravelTimeDisable: () => void; + onTravelTimeSetDestination: (lat: number, lon: number, label: string) => void; + onTravelTimeModeChange: (mode: TransportMode) => void; + onTravelTimeRangeChange: (range: [number, number]) => void; } export default memo(function Filters({ @@ -45,21 +90,34 @@ export default memo(function Filters({ onDragStart, onDragChange, onDragEnd, - zoom, - itemCount, - usePostcodeView, pinnedFeature, onTogglePin, onCancelPin: _onCancelPin, onNavigateToSource, openInfoFeature, onClearOpenInfoFeature, + travelTimeEnabled, + travelTimeDestination, + travelTimeDestinationLabel, + travelTimeMode, + travelTimeRange, + travelTimeDataRange, + onTravelTimeEnable, + onTravelTimeDisable, + onTravelTimeSetDestination, + onTravelTimeModeChange, + onTravelTimeRangeChange, }: FiltersProps) { const availableFeatures = features.filter((f) => !enabledFeatures.has(f.name)); const enabledFeatureList = features.filter((f) => enabledFeatures.has(f.name)); const [showPhilosophy, setShowPhilosophy] = useState(false); const [activeInfoFeature, setActiveInfoFeature] = useState(null); + const [collapsedGroups, toggleGroup] = useCollapsibleGroups(); + const enabledGroups = useMemo( + () => groupFeaturesByCategory(enabledFeatureList), + [enabledFeatureList] + ); return (
@@ -72,118 +130,146 @@ export default memo(function Filters({ Finding the Perfect Postcode
-
+
Active Filters - {enabledFeatureList.length > 0 && ( + {(enabledFeatureList.length > 0 || travelTimeEnabled) && ( - {enabledFeatureList.length} + {enabledFeatureList.length + (travelTimeEnabled ? 1 : 0)} )}
- - {itemCount.toLocaleString()} {usePostcodeView ? 'postcodes' : 'hexagons'} · z - {zoom.toFixed(1)} -
-
- {enabledFeatureList.length === 0 && ( +
+ {travelTimeEnabled && ( +
+ +
+ )} + + {enabledFeatureList.length === 0 && !travelTimeEnabled && ( } title="No active filters" description="Browse features below and click + to add a filter" + className="px-3 py-4" /> )} - {enabledFeatureList.map((feature) => { - if (feature.type === 'enum') { - const selectedValues = (filters[feature.name] as string[]) || []; - const allValues = feature.values || []; - return ( -
-
- - -
- -
- {allValues.map((val) => ( - - ))} -
-
- ); - } - - const isActive = activeFeature === feature.name; - const isPinned = pinnedFeature === feature.name; - const displayValue = - isActive && dragValue - ? dragValue - : (filters[feature.name] as [number, number]) || [feature.min!, feature.max!]; - const step = feature.step ?? (feature.max! - feature.min!) / 100; - + {enabledGroups.map((group) => { + const isExpanded = !collapsedGroups.has(group.name); return ( -
- -
- - {formatFilterValue(displayValue[0])} - {formatFilterValue(displayValue[1])} +
+ toggleGroup(group.name)} + className="px-3 py-1.5 text-xs font-bold text-warm-500 bg-warm-50 dark:bg-navy-950 dark:text-warm-400 sticky top-0 hover:bg-warm-100 dark:hover:bg-warm-800" + > + + {group.features.length} - -
- onDragChange([min, max])} - onPointerDown={() => onDragStart(feature.name)} - onPointerUp={() => onDragEnd()} - /> + + {isExpanded && ( +
+ {group.features.map((feature) => { + if (feature.type === 'enum') { + const selectedValues = (filters[feature.name] as string[]) || []; + const allValues = feature.values || []; + return ( +
+
+ + +
+ + {allValues.map((val) => ( + { + const next = selectedValues.includes(val) + ? selectedValues.filter((v) => v !== val) + : [...selectedValues, val]; + onFilterChange(feature.name, next); + }} + size="xs" + /> + ))} + +
+ ); + } + + const isActive = activeFeature === feature.name; + const isPinned = pinnedFeature === feature.name; + const displayValue = + isActive && dragValue + ? dragValue + : (filters[feature.name] as [number, number]) || [feature.min!, feature.max!]; + const step = feature.step ?? (feature.max! - feature.min!) / 100; + + return ( +
+
+ + +
+
+ onDragChange([min, max])} + onPointerDown={() => onDragStart(feature.name)} + onPointerUp={() => onDragEnd()} + /> + +
+
+ ); + })} +
+ )}
); })}
-
+
Add Filter
@@ -197,6 +283,8 @@ export default memo(function Filters({ onNavigateToSource={onNavigateToSource} openInfoFeature={openInfoFeature} onClearOpenInfoFeature={onClearOpenInfoFeature} + travelTimeEnabled={travelTimeEnabled} + onEnableTravelTime={onTravelTimeEnable} />
diff --git a/frontend/src/components/map/Map.tsx b/frontend/src/components/map/Map.tsx index e785ee8..e1d2449 100644 --- a/frontend/src/components/map/Map.tsx +++ b/frontend/src/components/map/Map.tsx @@ -46,6 +46,10 @@ interface MapProps { onPostcodeSearched?: (postcode: SearchedPostcode | null) => void; bounds?: Bounds | null; hideLegend?: boolean; + travelTimeEnabled?: boolean; + travelTimeDestination?: [number, number] | null; + travelTimeColorRange?: [number, number] | null; + travelTimeRange?: [number, number] | null; } interface Dimensions { @@ -98,6 +102,10 @@ export default memo(function Map({ onPostcodeSearched, bounds: viewportBounds, hideLegend = false, + travelTimeEnabled = false, + travelTimeDestination, + travelTimeColorRange, + travelTimeRange, }: MapProps) { const containerRef = useRef(null); const [viewState, setViewState] = useState(initialViewState || INITIAL_VIEW_STATE); @@ -176,6 +184,10 @@ export default memo(function Map({ theme, searchedPostcode, bounds: viewportBounds, + travelTimeEnabled, + travelTimeDestination, + travelTimeColorRange, + travelTimeRange, }); return ( @@ -204,7 +216,7 @@ export default memo(function Map({ className="text-5xl font-bold text-white drop-shadow-lg" style={{ textShadow: '0 2px 8px rgba(0,0,0,0.6)' }} > - Your perfect postcodes + Your perfect postcode
) : null @@ -212,7 +224,17 @@ export default memo(function Map({ <> {!hideLegend && - (viewFeature && colorRange && colorFeatureMeta ? ( + (travelTimeEnabled && travelTimeDestination && travelTimeColorRange ? ( + + ) : viewFeature && colorRange && colorFeatureMeta ? ( ) : ( <> - - + + )}
diff --git a/frontend/src/components/map/MapPage.tsx b/frontend/src/components/map/MapPage.tsx index bfb019b..99c0e87 100644 --- a/frontend/src/components/map/MapPage.tsx +++ b/frontend/src/components/map/MapPage.tsx @@ -8,7 +8,6 @@ import POIPane from './POIPane'; import { PropertiesPane } from './PropertiesPane'; import AreaPane from './AreaPane'; import MobileDrawer from './MobileDrawer'; -import DataSources from '../data-sources/DataSources'; import MapLegend from './MapLegend'; import { TabButton } from '../ui/TabButton'; import { useMapData } from '../../hooks/useMapData'; @@ -18,6 +17,7 @@ import { useHexagonSelection } from '../../hooks/useHexagonSelection'; import { usePaneResize } from '../../hooks/usePaneResize'; import { useAreaSummary } from '../../hooks/useAreaSummary'; import { useUrlSync } from '../../hooks/useUrlSync'; +import { useTravelTime, type TravelTimeInitial } from '../../hooks/useTravelTime'; import { apiUrl, buildFilterString } from '../../lib/api'; import { SpinnerIcon } from '../ui/icons/SpinnerIcon'; @@ -44,6 +44,7 @@ interface MapPageProps { screenshotMode?: boolean; ogMode?: boolean; isMobile?: boolean; + initialTravelTime?: TravelTimeInitial; } export default function MapPage({ @@ -62,6 +63,7 @@ export default function MapPage({ screenshotMode, ogMode, isMobile = false, + initialTravelTime, }: MapPageProps) { const [searchedPostcode, setSearchedPostcode] = useState(null); const [selectedPOICategories, setSelectedPOICategories] = @@ -99,6 +101,9 @@ export default function MapPage({ features, }); + // Travel time hook + const travelTime = useTravelTime(initialTravelTime); + // Map data hook const mapData = useMapData({ filters, @@ -107,6 +112,9 @@ export default function MapPage({ activeFeature, dragValue, dragData, + travelTimeEnabled: travelTime.enabled, + travelTimeDestination: travelTime.destination, + travelTimeMode: travelTime.mode, }); // Keep filter bounds in sync with map data @@ -124,8 +132,21 @@ export default function MapPage({ // POI data const pois = usePOIData(mapData.bounds, selectedPOICategories); + // Compute data range for travel time slider + const travelTimeDataRange = useMemo((): [number, number] | null => { + if (!travelTime.enabled || !travelTime.destination) return null; + const vals: number[] = []; + for (const item of mapData.data) { + const val = item.travel_time; + if (typeof val === 'number' && !isNaN(val)) vals.push(val); + } + if (vals.length === 0) return null; + vals.sort((a, b) => a - b); + return [vals[0], vals[vals.length - 1]]; + }, [travelTime.enabled, travelTime.destination, mapData.data]); + // Sync current state to URL - useUrlSync(mapData.currentView, filters, features, selectedPOICategories, selection.rightPaneTab); + useUrlSync(mapData.currentView, filters, features, selectedPOICategories, selection.rightPaneTab, travelTime); // Set initial view and tab from URL state useEffect(() => { @@ -201,7 +222,7 @@ export default function MapPage({ .then((blob) => { const link = document.createElement('a'); link.href = URL.createObjectURL(blob); - link.download = 'perfect-postcodes-export.xlsx'; + link.download = 'perfect-postcode-export.xlsx'; link.click(); URL.revokeObjectURL(link.href); }) @@ -292,7 +313,6 @@ export default function MapPage({ onClose={selection.handleCloseSelection} hexagonLocation={hexagonLocation} filters={filters} - onNavigateToSource={(slug, featureName) => onNavigateTo('data-sources', slug, featureName)} aiSummary={aiSummary.summary} aiSummaryLoading={aiSummary.loading} aiSummaryError={aiSummary.error} @@ -307,7 +327,6 @@ export default function MapPage({ hexagonId={selection.selectedHexagon?.id || null} onLoadMore={selection.handleLoadMoreProperties} onClose={selection.handleCloseSelection} - onNavigateToSource={(slug) => onNavigateTo('data-sources', slug)} /> ); @@ -317,7 +336,6 @@ export default function MapPage({ selectedCategories={selectedPOICategories} onCategoriesChange={setSelectedPOICategories} poiCount={pois.length} - onNavigateToSource={(slug) => onNavigateTo('data-sources', slug)} /> ); @@ -334,15 +352,22 @@ export default function MapPage({ onDragStart={handleDragStart} onDragChange={handleDragChange} onDragEnd={handleDragEnd} - zoom={mapData.zoom} - itemCount={mapData.usePostcodeView ? mapData.postcodeData.length : mapData.data.length} - usePostcodeView={mapData.usePostcodeView} pinnedFeature={pinnedFeature} onTogglePin={handleTogglePin} onCancelPin={handleCancelPin} - onNavigateToSource={(slug, featureName) => onNavigateTo('data-sources', slug, featureName)} openInfoFeature={pendingInfoFeature} onClearOpenInfoFeature={onClearPendingInfoFeature} + travelTimeEnabled={travelTime.enabled} + travelTimeDestination={travelTime.destination} + travelTimeDestinationLabel={travelTime.destinationLabel} + travelTimeMode={travelTime.mode} + travelTimeRange={travelTime.timeRange} + travelTimeDataRange={travelTimeDataRange} + onTravelTimeEnable={travelTime.handleEnable} + onTravelTimeDisable={travelTime.handleDisable} + onTravelTimeSetDestination={travelTime.handleSetDestination} + onTravelTimeModeChange={travelTime.handleModeChange} + onTravelTimeRangeChange={travelTime.handleTimeRangeChange} /> ); @@ -386,13 +411,16 @@ export default function MapPage({ onPostcodeSearched={setSearchedPostcode} bounds={mapData.bounds} hideLegend + travelTimeEnabled={travelTime.enabled} + travelTimeDestination={travelTime.destination} + travelTimeColorRange={mapData.travelTimeColorRange} + travelTimeRange={travelTime.timeRange} /> {mapData.loading && (
Loading...
)} - onNavigateTo('data-sources')} />
{/* Bottom panel — 55% */} @@ -401,7 +429,18 @@ export default function MapPage({ style={{ flex: '55 0 0' }} > {/* Legend */} - {viewFeature && mapData.colorRange && mobileLegendMeta ? ( + {travelTime.enabled && travelTime.destination && mapData.travelTimeColorRange ? ( + + ) : viewFeature && mapData.colorRange && mobileLegendMeta ? ( {mapData.loading && (
Loading...
)} - onNavigateTo('data-sources')} />
{/* Right Pane */} diff --git a/frontend/src/components/map/POIPane.tsx b/frontend/src/components/map/POIPane.tsx index f35ee93..dc7f9e3 100644 --- a/frontend/src/components/map/POIPane.tsx +++ b/frontend/src/components/map/POIPane.tsx @@ -3,6 +3,8 @@ import { useCollapsibleGroups } from '../../hooks/useCollapsibleGroups'; import type { POICategoryGroup } from '../../types'; import InfoPopup from '../ui/InfoPopup'; import { SearchInput } from '../ui/SearchInput'; +import { PillToggle } from '../ui/PillToggle'; +import { PillGroup } from '../ui/PillGroup'; import { InfoIcon, ChevronIcon } from '../ui/icons'; import { IconButton } from '../ui/IconButton'; @@ -162,39 +164,32 @@ export default function POIPane({ > - - + toggleGroup(group.name)} + size="xs" + /> + {groupSelected}/{group.categories.length} - {!isCollapsed && - group.categories.map((category) => ( - - ))} + {!isCollapsed && ( +
+ + {group.categories.map((category) => ( + toggleCategory(category)} + size="xs" + /> + ))} + +
+ )} ); })} diff --git a/frontend/src/components/map/PropertiesPane.tsx b/frontend/src/components/map/PropertiesPane.tsx index 23d898d..7368672 100644 --- a/frontend/src/components/map/PropertiesPane.tsx +++ b/frontend/src/components/map/PropertiesPane.tsx @@ -1,6 +1,6 @@ import React, { useMemo, useState } from 'react'; import { Property } from '../../types'; -import { formatDuration, formatAge, formatNumber } from '../../lib/format'; +import { formatDuration, formatAge, formatNumber, formatTransactionDate } from '../../lib/format'; import { getNum } from '../../lib/property-fields'; import InfoPopup from '../ui/InfoPopup'; import { SearchInput } from '../ui/SearchInput'; @@ -145,6 +145,7 @@ function PropertyCard({ property }: { property: Property }) { const price = getNum(property, 'Last known price', 'latest_price'); const estimatedPrice = getNum(property, 'Estimated current price'); const pricePerSqm = getNum(property, 'Price per sqm', 'price_per_sqm'); + const estPricePerSqm = getNum(property, 'Est. price per sqm'); const floorArea = getNum(property, 'Total floor area (sqm)', 'total_floor_area'); const rooms = getNum( property, @@ -152,6 +153,7 @@ function PropertyCard({ property }: { property: Property }) { 'number_habitable_rooms' ); const age = getNum(property, 'Approximate construction age', 'construction_age_band'); + const transactionDate = getNum(property, 'Date of last transaction', 'date_of_transfer'); const councilTax = getNum(property, 'Council tax (£/yr)'); const councilTaxD = getNum(property, 'Council tax Band D (£/yr)'); @@ -165,10 +167,16 @@ function PropertyCard({ property }: { property: Property }) { {price !== undefined && (
£{formatNumber(price)} + {transactionDate !== undefined && ( + + {' '} + ({formatTransactionDate(transactionDate)}) + + )} {pricePerSqm !== undefined && ( {' '} - (£{formatNumber(pricePerSqm)}/m²) + £{formatNumber(pricePerSqm)}/m² )}
@@ -179,6 +187,9 @@ function PropertyCard({ property }: { property: Property }) { £{formatNumber(estimatedPrice)} + {estPricePerSqm !== undefined && ( + (£{formatNumber(estPricePerSqm)}/m²) + )} )} diff --git a/frontend/src/components/map/TravelTimeCard.tsx b/frontend/src/components/map/TravelTimeCard.tsx new file mode 100644 index 0000000..e9cb57c --- /dev/null +++ b/frontend/src/components/map/TravelTimeCard.tsx @@ -0,0 +1,172 @@ +import { useState, useCallback } from 'react'; +import { Slider } from '../ui/Slider'; +import { PillToggle } from '../ui/PillToggle'; +import { PillGroup } from '../ui/PillGroup'; +import { IconButton } from '../ui/IconButton'; +import { CloseIcon } from '../ui/icons/CloseIcon'; +import { MapPinIcon } from '../ui/icons/MapPinIcon'; +import { RouteIcon } from '../ui/icons/RouteIcon'; +import { formatFilterValue } from '../../lib/format'; +import { authHeaders } from '../../lib/api'; +import type { TransportMode } from '../../hooks/useTravelTime'; + +const MODES: { value: TransportMode; label: string }[] = [ + { value: 'transit', label: 'Transit' }, + { value: 'car', label: 'Car' }, + { value: 'bicycle', label: 'Bicycle' }, +]; + +interface TravelTimeCardProps { + destination: [number, number] | null; + destinationLabel: string; + mode: TransportMode; + timeRange: [number, number] | null; + dataRange: [number, number] | null; + onSetDestination: (lat: number, lon: number, label: string) => void; + onModeChange: (mode: TransportMode) => void; + onTimeRangeChange: (range: [number, number]) => void; + onRemove: () => void; +} + +export function TravelTimeCard({ + destination, + destinationLabel, + mode, + timeRange, + dataRange, + onSetDestination, + onModeChange, + onTimeRangeChange, + onRemove, +}: TravelTimeCardProps) { + const [query, setQuery] = useState(''); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + const handleSearch = useCallback( + async (e: React.FormEvent) => { + e.preventDefault(); + const trimmed = query.trim(); + if (!trimmed) return; + + setError(null); + setLoading(true); + try { + const res = await fetch( + `/api/postcode/${encodeURIComponent(trimmed)}`, + authHeaders() + ); + if (!res.ok) { + setError('Postcode not found'); + return; + } + const json: { postcode: string; latitude: number; longitude: number } = + await res.json(); + onSetDestination(json.latitude, json.longitude, json.postcode); + setQuery(''); + } catch { + setError('Lookup failed'); + } finally { + setLoading(false); + } + }, + [query, onSetDestination] + ); + + const sliderMin = dataRange ? Math.floor(dataRange[0]) : 0; + const sliderMax = dataRange ? Math.ceil(dataRange[1]) : 120; + const displayRange = timeRange ?? [sliderMin, sliderMax]; + + return ( +
+ {/* Header */} +
+
+ + + Travel Time + +
+ onRemove()} title="Remove travel time"> + + +
+ + {/* Destination search */} +
+
+ { + setQuery(e.target.value); + setError(null); + }} + placeholder={destination ? 'Change destination...' : 'Enter postcode...'} + className="flex-1 min-w-0 px-2 py-1 text-xs rounded border border-warm-200 dark:border-warm-600 bg-white dark:bg-warm-800 text-navy-950 dark:text-warm-200 placeholder-warm-400 dark:placeholder-warm-500 outline-none focus:ring-1 focus:ring-teal-400" + /> + +
+ {error && ( +

{error}

+ )} + {destination && destinationLabel && ( +
+ + + {destinationLabel} + +
+ )} +
+ + {/* Mode selector */} +
+ + Mode + + + {MODES.map((m) => ( + onModeChange(m.value)} + size="xs" + /> + ))} + +
+ + {/* Time range slider — only show when we have data */} + {destination && dataRange && ( +
+ + Max time + + onTimeRangeChange([min, max])} + /> +
+ + {formatFilterValue(displayRange[0])} min + + + {formatFilterValue(displayRange[1])} min + +
+
+ )} +
+ ); +} diff --git a/frontend/src/components/saved-searches/SavedSearchesPage.tsx b/frontend/src/components/saved-searches/SavedSearchesPage.tsx index 8a2e374..97a679f 100644 --- a/frontend/src/components/saved-searches/SavedSearchesPage.tsx +++ b/frontend/src/components/saved-searches/SavedSearchesPage.tsx @@ -1,5 +1,6 @@ import { useState, useCallback } from 'react'; import type { SavedSearch } from '../../hooks/useSavedSearches'; +import { shortenUrl } from '../../lib/api'; import { BookmarkIcon } from '../ui/icons/BookmarkIcon'; import { TrashIcon } from '../ui/icons/TrashIcon'; import { SpinnerIcon } from '../ui/icons/SpinnerIcon'; @@ -20,6 +21,7 @@ export default function SavedSearchesPage({ }) { const [deleteConfirmId, setDeleteConfirmId] = useState(null); const [copiedId, setCopiedId] = useState(null); + const [sharingId, setSharingId] = useState(null); const handleDeleteConfirm = useCallback(async () => { if (!deleteConfirmId) return; @@ -27,17 +29,16 @@ export default function SavedSearchesPage({ setDeleteConfirmId(null); }, [deleteConfirmId, onDelete]); - const handleShare = useCallback((params: string, id: string) => { - const url = `${window.location.origin}/?${params}`; + const copyToClipboard = useCallback((text: string, id: string) => { const onSuccess = () => { setCopiedId(id); setTimeout(() => setCopiedId(null), 2000); }; if (navigator.clipboard?.writeText) { - navigator.clipboard.writeText(url).then(onSuccess); + navigator.clipboard.writeText(text).then(onSuccess); } else { const ta = document.createElement('textarea'); - ta.value = url; + ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta); @@ -48,6 +49,18 @@ export default function SavedSearchesPage({ } }, []); + const handleShare = useCallback(async (params: string, id: string) => { + setSharingId(id); + try { + const shortUrl = await shortenUrl(params); + copyToClipboard(shortUrl, id); + } catch { + copyToClipboard(`${window.location.origin}/?${params}`, id); + } finally { + setSharingId(null); + } + }, [copyToClipboard]); + return (
@@ -106,9 +119,12 @@ export default function SavedSearchesPage({