diff --git a/.github/workflows/preview-pr.yml b/.github/workflows/preview-pr.yml index 6d80a398..8bb402cc 100644 --- a/.github/workflows/preview-pr.yml +++ b/.github/workflows/preview-pr.yml @@ -86,7 +86,7 @@ jobs: VERCEL_PROJECT_ID: ${{ env.VERCEL_PROJECT_ID }} - name: Cypress test - uses: cypress-io/github-action@v6 + uses: cypress-io/github-action@v7 with: start: yarn e2e:setup command: yarn e2e:run diff --git a/external_types/DatabaseCatalogAPI.yaml b/external_types/DatabaseCatalogAPI.yaml index 7112ec84..093d79e0 100644 --- a/external_types/DatabaseCatalogAPI.yaml +++ b/external_types/DatabaseCatalogAPI.yaml @@ -53,6 +53,8 @@ paths: - $ref: "#/components/parameters/status" - $ref: "#/components/parameters/provider" - $ref: "#/components/parameters/producer_url" + - $ref: "#/components/parameters/created_after" + - $ref: "#/components/parameters/created_before" - $ref: "#/components/parameters/is_official_query_param" security: @@ -98,6 +100,8 @@ paths: - $ref: "#/components/parameters/offset" - $ref: "#/components/parameters/provider" - $ref: "#/components/parameters/producer_url" + - $ref: "#/components/parameters/created_after" + - $ref: "#/components/parameters/created_before" - $ref: "#/components/parameters/country_code" - $ref: "#/components/parameters/subdivision_name" - $ref: "#/components/parameters/municipality" @@ -127,6 +131,8 @@ paths: - $ref: "#/components/parameters/offset" - $ref: "#/components/parameters/provider" - $ref: "#/components/parameters/producer_url" + - $ref: "#/components/parameters/created_after" + - $ref: "#/components/parameters/created_before" - $ref: "#/components/parameters/entity_types" - $ref: "#/components/parameters/country_code" - $ref: "#/components/parameters/subdivision_name" @@ -153,6 +159,8 @@ paths: - $ref: "#/components/parameters/offset" - $ref: "#/components/parameters/provider" - $ref: "#/components/parameters/producer_url" + - $ref: "#/components/parameters/created_after" + - $ref: "#/components/parameters/created_before" - $ref: "#/components/parameters/country_code" - $ref: "#/components/parameters/subdivision_name" - $ref: "#/components/parameters/municipality" @@ -452,6 +460,16 @@ paths: Query: New York Transit
Search Executed: 'new' & york & 'transit' +

+ Location filters: +
+ - `location_id` (a `location_id` of `/v1/locations`) or `continent` restricts the results to feeds with stops + in that location or continent, sub-areas included. Feeds are matched through their reverse-geolocated stops, + so a feed that was never reverse-geolocated matches no location. Unknown values return no feed. Pass one of + the two, not both. + - To list the same feeds as a location's `feed_counts`, also pass `status=active,inactive,development,future`. + - `sort=location` orders the results by the share of each feed's stops inside the requested location or + continent instead of by creation date.
operationId: searchFeeds @@ -471,9 +489,16 @@ paths: - $ref: "#/components/parameters/license_ids" - $ref: "#/components/parameters/license_is_spdx" - $ref: "#/components/parameters/license_tags" + - $ref: "#/components/parameters/location_id_query_param" + - $ref: "#/components/parameters/search_continent" + - $ref: "#/components/parameters/search_sort" security: - Authentication: [] responses: + 400: + description: > + `sort=location` was requested without `location_id` or `continent`, both `location_id` and `continent` + were given, or `sort` has an unsupported value. 403: description: Filtering by Seal of Reliability status is not available to this caller. 200: @@ -494,10 +519,29 @@ paths: /v1/locations: get: description: > - Search locations (countries, subdivisions and municipalities). - Results can be filtered by a free-text query and narrowed to a specific country, - subdivision or location type. Matches are ordered from the broadest area to the - most specific, and by relevance within each level. + Search and filter locations: continents, countries, subdivisions and municipalities. Results can be + filtered by a free-text query, a location id, a parent location, a continent, a country, a subdivision or a + location type. Matches are ordered from the broadest area to the most specific, and by relevance within each + level, unless `sort=feed_count` is given. +
+ Navigate the hierarchy with filters: `location_type=continent` lists the continents, + `location_type=country&continent=` the countries of a continent, `parent_location_id=` the + direct children of a location and `location_id=` one location. To list a location's feeds, call + `/v1/search` with its `location_id` (or, for a continent, `continent`), + `status=active,inactive,development,future` and `sort=location`. +
+ Countries, subdivisions and municipalities are OpenStreetMap administrative areas: their `location_id` is + the OSM id. Continents come from a fixed country-to-continent classification: they have no `location_id` + and are identified by their `continent_code`. Every location's `continent_code` is the continent of its + country. +
+ Feed counts (`include=feed_counts`, `has_feeds`, `sort=feed_count`) count distinct feeds with a + status of `active`, `inactive`, `development` or `future` that have reverse-geolocated stops in + the location, sub-areas included. A feed that was never reverse-geolocated is counted in no location, so a + count is not the number of all the feeds serving a place. A continent counts each feed once, even when it + has stops in several of its countries. Work-in-progress feeds are counted only for callers allowed to see + them, as in `/v1/search`. Counts are precomputed and refreshed after feeds are processed, so they can lag + behind a feed's latest changes. operationId: getLocations tags: - "locations" @@ -514,10 +558,13 @@ paths: schema: type: string example: montreal + - $ref: "#/components/parameters/location_id_filter" + - $ref: "#/components/parameters/parent_location_id_query_param" + - $ref: "#/components/parameters/location_continent" - name: country_code in: query description: > - Limit results to locations contained within this country, given as its + Limit results to locations contained within this country, the country included, given as its ISO 3166-1 alpha-2 code. Case-insensitive. schema: type: string @@ -525,7 +572,7 @@ paths: - name: subdivision_code in: query description: > - Limit results to locations contained within this subdivision, given as its + Limit results to locations contained within this subdivision, the subdivision included, given as its ISO 3166-2 code. Case-insensitive. schema: type: string @@ -534,16 +581,21 @@ paths: in: query description: > Filter by the type of location: + * `continent` - a continent, from a fixed country-to-continent classification. * `country` - a sovereign country, identified by an ISO 3166-1 code. * `subdivision` - a first-level subdivision (e.g. state or province), identified by an ISO 3166-2 code. * `municipality` - a locality below the subdivision level (e.g. a city or town). schema: type: string enum: + - continent - country - subdivision - municipality example: municipality + - $ref: "#/components/parameters/has_feeds_query_param" + - $ref: "#/components/parameters/locations_include" + - $ref: "#/components/parameters/locations_sort" security: - Authentication: [] responses: @@ -553,6 +605,8 @@ paths: application/json: schema: $ref: "#/components/schemas/LocationSearchResponse" + 400: + description: "`sort` or `include` has an unsupported value." /v1/licenses: get: @@ -1858,8 +1912,29 @@ components: type: string example: Los Angeles + LocationFeedCounts: + type: object + description: Number of distinct feeds per data type with stops in a location, sub-areas included. + properties: + gtfs: + type: integer + example: 42 + gtfs_rt: + type: integer + example: 18 + gbfs: + type: integer + example: 7 + total: + type: integer + description: Number of distinct feeds of any data type. + example: 67 + LocationSearchResponse: type: object + required: + - total + - results properties: total: type: integer @@ -1872,15 +1947,27 @@ components: LocationSearchResult: type: object + required: + - location_id + - location_type + - slug + - path + - path_slugs + - path_names properties: location_id: type: integer - description: Stable location identifier. + nullable: true + description: > + Stable location identifier: the OpenStreetMap id of the area. Null for a continent, identified by its + `continent_code`. example: 175905 parent_location_id: type: integer nullable: true - description: Stable identifier of the nearest containing location. + description: > + Identifier of the nearest containing location. Null for continents and countries: a country's continent + is its `continent_code`. example: 161950 name: type: string @@ -1895,13 +1982,45 @@ components: location_type: type: string description: > - The type of location: `country` (has an ISO 3166-1 code), `subdivision` + The type of location: `continent`, `country` (has an ISO 3166-1 code), `subdivision` (has an ISO 3166-2 code) or `municipality` (a locality below the subdivision level). enum: + - continent - country - subdivision - municipality example: municipality + continent_code: + type: string + nullable: true + description: > + Code of the continent of this location's country, or of the continent itself (`AF`, `AN`, `AS`, `EU`, + `NA`, `OC`, `SA`). Null when the country has no continent in the classification. + example: NA + slug: + type: string + description: > + URL segment of the location. A continent's slug is fixed (`north-america`) and a country's is its + ISO 3166-1 code, lowercased (`ca`). Any other location's slug is its `location_id` followed by its name, + lowercased, without accents, with every run of non-alphanumeric characters replaced by a hyphen + (`175905-montreal`); a name without any ASCII letter or digit leaves the `location_id` alone (`1234`). + The `location_id` identifies the location: the name part follows OpenStreetMap and can change. + example: 175905-montreal + path_slugs: + type: array + description: > + The slugs of the locations in `path_names`, in the same order, from the country down. Prefix them with the + continent's slug to build a directory URL. + items: + type: string + example: + - ca + - 61549-quebec + - 8508277-montreal-region + - 175905-montreal + feed_counts: + # Null unless `include` contains `feed_counts`. + $ref: "#/components/schemas/LocationFeedCounts" country_name: type: string nullable: true @@ -1924,7 +2043,9 @@ components: example: CA-QC path_names: type: array - description: The ordered list of location names from the broadest containing area down to this location. + description: > + The ordered list of location names from the country down to this location. A continent's is its own + name. items: type: string example: @@ -1935,7 +2056,9 @@ components: display_name: type: string nullable: true - description: A human-readable representation of the full location hierarchy, joined from the broadest area to this location. + description: > + A human-readable representation of the location hierarchy, joined from the country (or, for a + continent, the continent itself) down to this location. example: Canada, Quebec, Montréal (region), Montréal # Have to put the enum inline because of a bug in openapi-generator @@ -2516,6 +2639,26 @@ components: schema: type: string example: Los Angeles + created_after: + name: created_after + in: query + description: Filter feeds added to the database at or after this timestamp. Date should be in ISO 8601 date-time format. + required: False + schema: + type: string + format: date-time + example: "2026-01-01T00:00:00Z" + + created_before: + name: created_before + in: query + description: Filter feeds added to the database at or before this timestamp. Date should be in ISO 8601 date-time format. + required: False + schema: + type: string + format: date-time + example: "2026-08-01T00:00:00Z" + downloaded_after: name: downloaded_after in: query @@ -2606,6 +2749,103 @@ components: type: boolean default: null + location_continent: + name: continent + in: query + description: > + Limit results to locations in this continent, the continent included, given as its slug (`africa`, + `antarctica`, `asia`, `europe`, `north-america`, `oceania`, `south-america`) or code (`AF`, `AN`, `AS`, + `EU`, `NA`, `OC`, `SA`). Case-insensitive. + required: False + schema: + type: string + example: north-america + + location_id_query_param: + name: location_id + in: query + description: > + A `location_id` from `/v1/locations`: only feeds with reverse-geolocated stops in that location, sub-areas + included. + required: False + schema: + type: integer + example: 61549 + + search_continent: + name: continent + in: query + description: > + A continent, given as its slug (`africa`, `antarctica`, `asia`, `europe`, `north-america`, `oceania`, + `south-america`) or code (`AF`, `AN`, `AS`, `EU`, `NA`, `OC`, `SA`): only feeds with reverse-geolocated stops + in one of its countries. Case-insensitive. + required: False + schema: + type: string + example: europe + + location_id_filter: + name: location_id + in: query + description: Limit results to the location with this `location_id`. + required: False + schema: + type: integer + example: 61549 + + parent_location_id_query_param: + name: parent_location_id + in: query + description: > + Limit results to the direct children of the location with this `location_id`: the subdivisions of a + country, the areas one level down from a subdivision, and so on. Depth varies by country, so the children of + a subdivision can be regions or municipalities. The countries of a continent are listed with + `location_type=country` and `continent`. + required: False + schema: + type: integer + example: 61549 + + has_feeds_query_param: + name: has_feeds + in: query + required: False + description: When true, only return locations with at least one feed (see the feed count rules of `/v1/locations`). + schema: + type: boolean + default: false + + locations_include: + name: include + in: query + required: False + description: > + Optional data to add to each location: `feed_counts`, the location's feed counts per data type. + style: form + explode: false + schema: + type: array + items: + type: string + enum: + - feed_counts + + locations_sort: + name: sort + in: query + description: > + Sort order of the results. + `admin_level` (default): from the broadest area to the most specific, then by relevance to `search_query` + when one is given, then by display name. + `feed_count`: most feeds first, then by display name. + required: False + schema: + type: string + enum: + - admin_level + - feed_count + default: admin_level + limit_query_param_locations_endpoint: name: limit in: query @@ -2721,6 +2961,24 @@ components: schema: type: string + search_sort: + name: sort + in: query + description: > + Sort order of the results. + `created_at` (default): newest feeds first, then by relevance to `search_query` when one is given. + `location`: by relevance to the requested location, which requires `location_id` or `continent`. Feeds + with the largest share of their reverse-geolocated stops inside the location come first (on Montréal, a + city bus feed with all its stops in Montréal ranks above a regional train with a fifth of them there); + ties are broken by provider, feed name and feed id. + required: False + schema: + type: string + enum: + - created_at + - location + default: created_at + version_query_param: name: version in: query diff --git a/messages/en.json b/messages/en.json index 8990e62d..244eaa43 100644 --- a/messages/en.json +++ b/messages/en.json @@ -125,7 +125,9 @@ "metricsAdminOnly": "Metrics - Admin Only", "languageSelect": "Language select", "transitFeedsRedirectTitle": "You've been redirected from TransitFeeds", - "transitFeedsRedirectBody": "This page now lives on MobilityDatabase.org, where you'll find the most up-to-date transit data." + "transitFeedsRedirectBody": "This page now lives on MobilityDatabase.org, where you'll find the most up-to-date transit data.", + "locations": "Locations", + "feedsMenu": "Feeds menu" }, "emailVerification": { "loadingTitle": "Verifying your email", @@ -1254,7 +1256,8 @@ "contactUs": "Contact Us", "shareFeedback": "Share Feedback", "privacyPolicy": "Privacy Policy", - "termsAndConditions": "Terms and Conditions" + "termsAndConditions": "Terms and Conditions", + "locations": "Locations" }, "aria": { "github": "GitHub", @@ -1262,5 +1265,44 @@ "linkedin": "LinkedIn", "logo": "Mobility Database logo" } + }, + "locations": { + "root": "Locations", + "title": "Feeds by Location", + "rootIntro": "Browse open GTFS Schedule, GTFS Realtime and GBFS feeds by location, from continents down to specific places.", + "nodeIntro": "{total, plural, =0 {No feeds are} one {# feed is} other {# feeds are}} located in {place}.", + "feedCountsAria": "Feed counts by data type", + "shortLabels": { + "gtfs": "GTFS", + "gtfs_rt": "GTFS-RT", + "gbfs": "GBFS" + }, + "childrenHeading": { + "continents": "Continents", + "countries": "Countries", + "places": "Places" + }, + "childFeedTotal": "{count, plural, one {# feed} other {# feeds}}", + "childrenSearchPlaceholder": { + "continents": "Search continents", + "countries": "Search countries", + "places": "Search places" + }, + "childrenSearchAria": "Filter the locations below by name", + "childLoadingAria": "Loading {name}", + "childrenSearchResults": "{count, plural, =0 {No matching locations} one {# matching location} other {# matching locations}}", + "childrenSearchEmpty": "No location matches “{query}”.", + "feedsHeading": "Feeds in {place}", + "allFeedsHeading": "All feeds", + "resultsRange": "Showing {start}–{end} of {total} feeds", + "noFeeds": "No feeds are listed for this location yet.", + "paginationAria": "Feed list pages", + "meta": { + "rootTitle": "Transit Feeds by Location | Mobility Database", + "rootDescription": "Browse open GTFS Schedule, GTFS Realtime and GBFS transit and mobility feeds by location, from continents down to specific places.", + "nodeTitle": "{place} Transit Feeds | Mobility Database", + "nodeTitlePaged": "{place} Transit Feeds, Page {page} | Mobility Database", + "nodeDescription": "Browse {total} open transit and mobility feeds located in {place}: {gtfs} GTFS Schedule, {gtfs_rt} GTFS Realtime and {gbfs} GBFS." + } } } diff --git a/messages/fr.json b/messages/fr.json index 81336666..f496cb4d 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -125,7 +125,9 @@ "metricsAdminOnly": "Métriques - Admin uniquement", "languageSelect": "Sélection de la langue", "transitFeedsRedirectTitle": "Vous avez été redirigé depuis TransitFeeds", - "transitFeedsRedirectBody": "Cette page se trouve désormais sur MobilityDatabase.org, où vous trouverez les données de transit les plus récentes." + "transitFeedsRedirectBody": "Cette page se trouve désormais sur MobilityDatabase.org, où vous trouverez les données de transit les plus récentes.", + "locations": "Lieux", + "feedsMenu": "Menu des flux" }, "emailVerification": { "loadingTitle": "Vérification de votre e-mail", @@ -1254,7 +1256,8 @@ "contactUs": "Contactez-nous", "shareFeedback": "Donner un avis", "privacyPolicy": "Politique de confidentialité", - "termsAndConditions": "Conditions d'utilisation" + "termsAndConditions": "Conditions d'utilisation", + "locations": "Lieux" }, "aria": { "github": "GitHub", @@ -1262,5 +1265,44 @@ "linkedin": "LinkedIn", "logo": "Logo Mobility Database" } + }, + "locations": { + "root": "Lieux", + "title": "Flux par lieu", + "rootIntro": "Parcourez les flux ouverts GTFS Schedule, GTFS Realtime et GBFS par lieu, des continents jusqu’aux villes.", + "nodeIntro": "{total, plural, =0 {Aucun flux n’est situé} one {# flux est situé} other {# flux sont situés}} dans : {place}.", + "feedCountsAria": "Nombre de flux par type de données", + "shortLabels": { + "gtfs": "GTFS", + "gtfs_rt": "GTFS-RT", + "gbfs": "GBFS" + }, + "childrenHeading": { + "continents": "Continents", + "countries": "Pays", + "places": "Lieux" + }, + "childFeedTotal": "{count, plural, one {# flux} other {# flux}}", + "childrenSearchPlaceholder": { + "continents": "Rechercher un continent", + "countries": "Rechercher un pays", + "places": "Rechercher un lieu" + }, + "childrenSearchAria": "Filtrer les lieux ci-dessous par nom", + "childLoadingAria": "Chargement de {name}", + "childrenSearchResults": "{count, plural, =0 {Aucun lieu correspondant} one {# lieu correspondant} other {# lieux correspondants}}", + "childrenSearchEmpty": "Aucun lieu ne correspond à « {query} ».", + "feedsHeading": "Flux dans : {place}", + "allFeedsHeading": "Tous les flux", + "resultsRange": "{start}–{end} sur {total} flux", + "noFeeds": "Aucun flux n’est encore répertorié pour ce lieu.", + "paginationAria": "Pages de la liste des flux", + "meta": { + "rootTitle": "Flux de transport par lieu | Mobility Database", + "rootDescription": "Parcourez les flux ouverts de transport et de mobilité GTFS Schedule, GTFS Realtime et GBFS par lieu, des continents jusqu’aux villes.", + "nodeTitle": "Flux de transport : {place} | Mobility Database", + "nodeTitlePaged": "Flux de transport : {place}, page {page} | Mobility Database", + "nodeDescription": "Parcourez {total} flux ouverts de transport et de mobilité situés dans : {place}. {gtfs} GTFS Schedule, {gtfs_rt} GTFS Realtime et {gbfs} GBFS." + } } } diff --git a/src/app/[locale]/locations/[[...location]]/loading.tsx b/src/app/[locale]/locations/[[...location]]/loading.tsx new file mode 100644 index 00000000..4f26a04e --- /dev/null +++ b/src/app/[locale]/locations/[[...location]]/loading.tsx @@ -0,0 +1,99 @@ +import { type ReactElement } from 'react'; +import { Box, Container, Skeleton } from '@mui/material'; +import SectionContainer from '../../../components/SectionContainer'; + +const CARD_COUNT = 8; +const ROW_COUNT = 8; + +/** + * Shown while a location page streams in, e.g. after clicking a child + * location; same layout as page.tsx so nothing jumps when it resolves. + * ref: https://nextjs.org/docs/app/api-reference/file-conventions/loading + */ +export default function Loading(): ReactElement { + return ( + + + {/* Back button and breadcrumb */} + + {/* Title and intro */} + + + {/* Feed count chips */} + + {[150, 140, 100].map((width) => ( + + ))} + + + {/* Child locations */} + + + {Array.from({ length: CARD_COUNT }, (_, index) => ( + + ))} + + + {/* Feeds table */} + + {Array.from({ length: ROW_COUNT }, (_, index) => ( + + ))} + + + ); +} diff --git a/src/app/[locale]/locations/[[...location]]/page.tsx b/src/app/[locale]/locations/[[...location]]/page.tsx new file mode 100644 index 00000000..656730c9 --- /dev/null +++ b/src/app/[locale]/locations/[[...location]]/page.tsx @@ -0,0 +1,286 @@ +import { type ReactElement } from 'react'; +import { type Metadata } from 'next'; +import { notFound, permanentRedirect } from 'next/navigation'; +import { Box, Container, Typography } from '@mui/material'; +import { getTranslations, setRequestLocale } from 'next-intl/server'; +import BreadcrumbNavigation, { + type Crumb, +} from '../../../components/BreadcrumbNavigation'; +import SectionContainer from '../../../components/SectionContainer'; +import { getPathname } from '../../../../i18n/navigation'; +import FeedCountSummary from '../components/FeedCountSummary'; +import LocationChildrenGrid from '../components/LocationChildrenGrid'; +import LocationFeedsList from '../components/LocationFeedsList'; +import { + buildBreadcrumbSteps, + buildLocationHref, + buildPlaceName, + FEEDS_SECTION_ID, + getChildrenKind, + getLocationName, + getPageCount, + getLocationSegments, + getTotalFeedCount, + isSameSegments, + parseLocationRequest, + parsePageParam, + type LocationRequest, +} from '../lib/location-directory'; +import { + fetchLocationPage, + requestKey, + type LocationPageData, +} from '../lib/location-directory-data'; + +const SITE_URL = 'https://mobilitydatabase.org'; + +interface PageProps { + params: Promise<{ locale: string; location?: string[] }>; + searchParams: Promise>; +} + +interface ParsedRequest { + locale: string; + location: LocationRequest; + page: number; +} + +/** The request, or null when the URL or the page number is malformed. */ +async function parseRequest({ + params, + searchParams, +}: PageProps): Promise { + const [{ locale, location: segments }, { page: rawPage }] = await Promise.all( + [params, searchParams], + ); + const location = parseLocationRequest(segments); + const page = parsePageParam(rawPage); + if (location === null || page === null) return null; + return { locale, location, page }; +} + +/** + * The page data, or null when the location does not exist or the page is + * past the last one. Deduped by React cache() between generateMetadata and + * the page. + */ +async function fetchPageData({ + location, + page, +}: ParsedRequest): Promise { + const data = await fetchLocationPage( + page, + location.kind, + requestKey(location), + ); + if (data === null || page > getPageCount(data.feeds.total ?? 0)) { + return null; + } + return data; +} + +/** The canonical URL segments of the page's location; empty at the root. */ +function canonicalSegments({ location, continents }: LocationPageData) { + return location === null ? [] : getLocationSegments(location, continents); +} + +/** The page's URL in the request's locale (`/fr/...` in French). */ +function localizedHref( + segments: readonly string[], + page: number, + locale: string, +): string { + const [pathname, query] = buildLocationHref(segments, page).split('?'); + const localizedPathname = getPathname({ href: pathname, locale }); + return `${localizedPathname}${query !== undefined ? `?${query}` : ''}`; +} + +/** + * The page's data, or a 404 when the location does not exist, or a permanent + * redirect when the URL is not the location's canonical URL: only the last + * segment identifies the location, so any other URL of it (an outdated name, + * another continent) moves to the canonical one. + * + * The page streams (loading.tsx), so the 404 and the redirect reach the + * browser inside a 200 response, as a not-found page and a client-side + * redirect. The metadata of a non-canonical URL still points crawlers to the + * canonical one. + */ +async function resolvePage(request: ParsedRequest): Promise { + const data = await fetchPageData(request); + if (data === null) notFound(); + const segments = canonicalSegments(data); + if (!isSameSegments(request.location.segments, segments)) { + permanentRedirect(localizedHref(segments, request.page, request.locale)); + } + return data; +} + +export async function generateMetadata(props: PageProps): Promise { + const request = await parseRequest(props); + if (request === null) return {}; + const [data, t] = await Promise.all([ + fetchPageData(request), + getTranslations({ locale: request.locale, namespace: 'locations.meta' }), + ]); + if (data === null) return {}; + + const { location } = data; + const { page } = request; + const place = buildPlaceName(location); + const counts = location?.feed_counts; + const title = + location === null + ? t('rootTitle') + : page > 1 + ? t('nodeTitlePaged', { place, page }) + : t('nodeTitle', { place }); + const description = + location === null + ? t('rootDescription') + : t('nodeDescription', { + place, + total: getTotalFeedCount(counts), + gtfs: counts?.gtfs ?? 0, + gtfs_rt: counts?.gtfs_rt ?? 0, + gbfs: counts?.gbfs ?? 0, + }); + const url = `${SITE_URL}${localizedHref(canonicalSegments(data), page, request.locale)}`; + + return { + title, + description, + alternates: { canonical: url }, + openGraph: { + title, + description, + url, + siteName: 'Mobility Database', + type: 'website', + }, + }; +} + +export default async function LocationsPage( + props: PageProps, +): Promise { + const request = await parseRequest(props); + if (request === null) notFound(); + const { locale, page } = request; + setRequestLocale(locale); + + const [data, t, tCommon] = await Promise.all([ + resolvePage(request), + getTranslations('locations'), + getTranslations('common'), + ]); + const segments = canonicalSegments(data); + + const { location, children, feeds, continents } = data; + const isRoot = location === null; + const total = feeds.total ?? 0; + const pageCount = getPageCount(total); + const place = buildPlaceName(location); + const steps = buildBreadcrumbSteps(location, continents); + + const crumbs: Crumb[] = [ + { label: tCommon('feeds'), href: '/feeds' }, + { label: t('root'), href: isRoot ? undefined : buildLocationHref([]) }, + ...steps.map((step, index) => ({ + label: step.label, + href: + index === steps.length - 1 + ? undefined + : buildLocationHref(step.segments), + })), + ]; + // Without history to pop, back goes one level up the directory. + const backFallbackHref = isRoot + ? '/feeds' + : buildLocationHref(segments.slice(0, -1)); + const childrenKind = getChildrenKind(location); + + return ( + + + + + {isRoot ? t('title') : getLocationName(location)} + + + {isRoot + ? t('rootIntro') + : t('nodeIntro', { + total: getTotalFeedCount(location.feed_counts), + place, + })} + + + {/* No catalog-wide counts by data type at the root. */} + {isRoot ? null : ( + + )} + + {children.length > 0 ? ( + + + {t(`childrenHeading.${childrenKind}`)}{' '} + + ({children.length}) + + + + + ) : null} + + + + {isRoot ? t('allFeedsHeading') : t('feedsHeading', { place })} + + + + + + ); +} diff --git a/src/app/[locale]/locations/components/FeedCountChips.tsx b/src/app/[locale]/locations/components/FeedCountChips.tsx new file mode 100644 index 00000000..9e673cd7 --- /dev/null +++ b/src/app/[locale]/locations/components/FeedCountChips.tsx @@ -0,0 +1,46 @@ +import { type ReactElement } from 'react'; +import { Box, Chip } from '@mui/material'; +import { type FeedCountDataType } from '../lib/location-directory'; + +export interface FeedCountChip { + dataType: FeedCountDataType; + count: number; + /** Already formatted, e.g. "42 GTFS Schedule". */ + label: string; +} + +interface Props { + chips: FeedCountChip[]; + size?: 'small' | 'medium'; + ariaLabel?: string; +} + +/** + * GTFS / GTFS-RT / GBFS counts as outlined chips. Hook-free, so it renders in + * both server and client components. + */ +export default function FeedCountChips({ + chips, + size = 'medium', + ariaLabel, +}: Props): ReactElement { + return ( + + {chips.map(({ dataType, count, label }) => ( + 0 ? 'primary' : 'default'} + sx={count > 0 ? { fontWeight: 700 } : { color: 'text.disabled' }} + /> + ))} + + ); +} diff --git a/src/app/[locale]/locations/components/FeedCountSummary.tsx b/src/app/[locale]/locations/components/FeedCountSummary.tsx new file mode 100644 index 00000000..55b90eab --- /dev/null +++ b/src/app/[locale]/locations/components/FeedCountSummary.tsx @@ -0,0 +1,44 @@ +import { type ReactElement } from 'react'; +import { getTranslations } from 'next-intl/server'; +import FeedCountChips from './FeedCountChips'; +import { + formatCount, + getFeedCountEntries, + type FeedCountDataType, + type LocationFeedCounts, +} from '../lib/location-directory'; + +interface Props { + counts: LocationFeedCounts | undefined; + locale: string; +} + +const LABEL_KEYS: Record = { + gtfs: 'gtfsSchedule', + gtfs_rt: 'gtfsRealtime', + gbfs: 'gbfs', +}; + +/** The node's feed totals split by GTFS Schedule / GTFS Realtime / GBFS. */ +export default async function FeedCountSummary({ + counts, + locale, +}: Props): Promise { + const [tCommon, t] = await Promise.all([ + getTranslations('common'), + getTranslations('locations'), + ]); + + return ( +
+ ({ + dataType, + count, + label: `${formatCount(count, locale)} ${tCommon(LABEL_KEYS[dataType])}`, + }))} + /> +
+ ); +} diff --git a/src/app/[locale]/locations/components/LinkPendingIndicator.tsx b/src/app/[locale]/locations/components/LinkPendingIndicator.tsx new file mode 100644 index 00000000..f1df17e4 --- /dev/null +++ b/src/app/[locale]/locations/components/LinkPendingIndicator.tsx @@ -0,0 +1,42 @@ +'use client'; + +import { type ReactElement } from 'react'; +import { LinearProgress } from '@mui/material'; +import { keyframes } from '@mui/material/styles'; +// useLinkStatus is not re-exported by i18n/navigation; it reads the status of +// the nearest enclosing Link, which next-intl's Link renders under the hood. +import { useLinkStatus } from 'next/link'; + +// Fast navigations finish before the bar shows, so it never flashes. +const appearAfterDelay = keyframes` + to { opacity: 1; } +`; + +interface Props { + ariaLabel: string; +} + +/** + * Thin bar along the bottom of the enclosing Link while its navigation is + * pending. Must render inside a Link; the Link needs `position: relative`. + */ +export default function LinkPendingIndicator({ + ariaLabel, +}: Props): ReactElement | null { + const { pending } = useLinkStatus(); + if (!pending) return null; + return ( + + ); +} diff --git a/src/app/[locale]/locations/components/LocationChildrenGrid.tsx b/src/app/[locale]/locations/components/LocationChildrenGrid.tsx new file mode 100644 index 00000000..4f0ccd45 --- /dev/null +++ b/src/app/[locale]/locations/components/LocationChildrenGrid.tsx @@ -0,0 +1,80 @@ +import { type ReactElement } from 'react'; +import { getTranslations } from 'next-intl/server'; +import { getEmojiFlag, type TCountryCode } from 'countries-list'; +import LocationChildrenList, { + type LocationChildItem, +} from './LocationChildrenList'; +import { + buildLocationHref, + formatCount, + getFeedCountEntries, + getLocationName, + getLocationSegments, + getTotalFeedCount, + sortByFeedCount, + type ChildrenKind, + type ContinentInfo, + type LocationResult, +} from '../lib/location-directory'; + +interface Props { + locations: LocationResult[]; + /** To link each location through its continent. */ + continents: ContinentInfo[]; + kind: ChildrenKind; + locale: string; +} + +function getFlag(location: LocationResult): string | undefined { + if ( + location.location_type !== 'country' || + location.country_code == undefined + ) + return undefined; + const flag = getEmojiFlag( + location.country_code.toUpperCase() as TCountryCode, + ); + return flag !== '' ? flag : undefined; +} + +/** + * Child locations, most feeds first. Everything that needs the server + * (flags, translations, number formatting, links) is resolved here so the + * client list only filters plain data. + */ +export default async function LocationChildrenGrid({ + locations, + continents, + kind, + locale, +}: Props): Promise { + const t = await getTranslations('locations'); + + const items: LocationChildItem[] = sortByFeedCount( + locations.map((location) => ({ + location, + name: getLocationName(location), + counts: location.feed_counts, + })), + ).map(({ location, name, counts }) => { + const href = buildLocationHref(getLocationSegments(location, continents)); + return { + key: href, + name, + flag: getFlag(location), + href, + totalLabel: t.rich('childFeedTotal', { + count: getTotalFeedCount(counts), + b: (chunks) => {chunks}, + }), + counts: getFeedCountEntries(counts).map(({ dataType, count }) => ({ + dataType, + count, + formattedCount: formatCount(count, locale), + typeLabel: t(`shortLabels.${dataType}`), + })), + }; + }); + + return ; +} diff --git a/src/app/[locale]/locations/components/LocationChildrenList.tsx b/src/app/[locale]/locations/components/LocationChildrenList.tsx new file mode 100644 index 00000000..6fda078f --- /dev/null +++ b/src/app/[locale]/locations/components/LocationChildrenList.tsx @@ -0,0 +1,224 @@ +'use client'; + +import { useMemo, useState, type ReactElement, type ReactNode } from 'react'; +import { + Box, + Card, + CardActionArea, + InputAdornment, + TextField, + Typography, +} from '@mui/material'; +import SearchIcon from '@mui/icons-material/Search'; +import { useTranslations } from 'next-intl'; +import { Link } from '../../../../i18n/navigation'; +import LinkPendingIndicator from './LinkPendingIndicator'; +import { + filterByName, + type ChildrenKind, + type FeedCountDataType, +} from '../lib/location-directory'; + +export interface LocationChildCount { + dataType: FeedCountDataType; + count: number; + /** Locale-formatted, rendered bold. */ + formattedCount: string; + /** e.g. "GTFS-RT". */ + typeLabel: string; +} + +export interface LocationChildItem { + /** Unique among siblings (the href). */ + key: string; + name: string; + /** Emoji flag, countries only. */ + flag?: string; + href: string; + /** e.g. "8 feeds", with the number in a . */ + totalLabel: ReactNode; + /** Plain-text counts; chips are kept for the page summary. */ + counts: LocationChildCount[]; +} + +// Bold, primary-colored numbers stand out from their secondary-colored labels. +const countNumberSx = { + '& strong': { fontWeight: 700, color: 'text.primary' }, +} as const; + +interface Props { + /** Already sorted, most feeds first. */ + items: LocationChildItem[]; + /** Names the search box after the level it filters. */ + kind: ChildrenKind; +} + +/** Searchable, scrollable grid of child locations. */ +export default function LocationChildrenList({ + items, + kind, +}: Props): ReactElement { + const t = useTranslations('locations'); + const [query, setQuery] = useState(''); + const visibleItems = useMemo( + () => filterByName(items, query), + [items, query], + ); + + return ( + <> + { + setQuery(event.target.value); + }} + placeholder={t(`childrenSearchPlaceholder.${kind}`)} + slotProps={{ + htmlInput: { + 'aria-label': t('childrenSearchAria'), + 'aria-controls': 'location-children', + 'data-testid': 'location-children-search', + }, + input: { + startAdornment: ( + + + + ), + }, + }} + sx={{ + mb: 1, + maxWidth: { md: 480 }, + // White in light mode, like the cards below; the section is paper. + '& .MuiInputBase-root': { bgcolor: 'background.default' }, + }} + /> + + {query.trim() !== '' + ? t('childrenSearchResults', { count: visibleItems.length }) + : null} + + + {visibleItems.length > 0 ? ( + + {visibleItems.map((item) => ( +
  • + + + + + {item.flag != undefined + ? `${item.flag} ${item.name}` + : item.name} + + + {item.totalLabel} + + + + {item.counts.map( + ({ dataType, count, formattedCount, typeLabel }) => ( + 0 ? 'text.secondary' : 'text.disabled' + } + // Zero counts stay fully disabled. + sx={count > 0 ? countNumberSx : undefined} + > + {formattedCount} {typeLabel} + + ), + )} + + + + +
  • + ))} +
    + ) : ( + + {t('childrenSearchEmpty', { query: query.trim() })} + + )} +
    + + ); +} diff --git a/src/app/[locale]/locations/components/LocationFeedsList.tsx b/src/app/[locale]/locations/components/LocationFeedsList.tsx new file mode 100644 index 00000000..ae28dd48 --- /dev/null +++ b/src/app/[locale]/locations/components/LocationFeedsList.tsx @@ -0,0 +1,87 @@ +'use client'; + +import { type ReactElement } from 'react'; +import { Box, Pagination, PaginationItem, Typography } from '@mui/material'; +import { useTranslations } from 'next-intl'; +import SearchTable from '../../../screens/Feeds/SearchTable'; +import { useSealOfReliabilityFilterAccess } from '../../../hooks/useSealOfReliabilityFilterAccess'; +import { type SearchFeedItem } from '../../../services/feeds/utils'; +import { Link } from '../../../../i18n/navigation'; +import { + buildLocationHref, + FEEDS_SECTION_ID, + getPageOffset, + LOCATION_FEEDS_PAGE_SIZE, +} from '../lib/location-directory'; + +interface Props { + feeds: SearchFeedItem[]; + total: number; + page: number; + pageCount: number; + /** URL segments of the current location, used to build the page links. */ + segments: string[]; +} + +/** + * The feeds of a directory location in the same compact table as the /feeds + * search (simple view), paginated with real links so every page is + * crawlable and reflected in the URL. + */ +export default function LocationFeedsList({ + feeds, + total, + page, + pageCount, + segments, +}: Props): ReactElement { + const t = useTranslations('locations'); + // Same flag the /feeds search uses to show the seal badge on rows. + const { isFeatureLive: isSealEnabled } = useSealOfReliabilityFilterAccess(); + + if (feeds.length === 0) { + return {t('noFeeds')}; + } + + const start = getPageOffset(page) + 1; + const end = Math.min(start + LOCATION_FEEDS_PAGE_SIZE - 1, total); + + return ( + <> + + {t('resultsRange', { start, end, total })} + + + + + {pageCount > 1 ? ( + ( + + )} + /> + ) : null} + + ); +} diff --git a/src/app/[locale]/locations/lib/location-directory-data.spec.ts b/src/app/[locale]/locations/lib/location-directory-data.spec.ts new file mode 100644 index 00000000..3d86839c --- /dev/null +++ b/src/app/[locale]/locations/lib/location-directory-data.spec.ts @@ -0,0 +1,341 @@ +/** + * @jest-environment node + */ + +import { ApiError } from '../../../services/feeds'; +import { fetchLocationPage } from './location-directory-data'; + +jest.mock('server-only', () => ({})); + +jest.mock('react', () => ({ + ...jest.requireActual('react'), + cache: (fn: unknown) => fn, +})); + +// Behaves like unstable_cache: a resolved value is stored per key parts and +// arguments, a thrown error is not. Tests reset the store between them. +const mockCacheStore = new Map(); +jest.mock('next/cache', () => ({ + unstable_cache: ( + fn: (...args: A) => Promise, + keyParts: string[], + ): ((...args: A) => Promise) => { + return async (...args: A): Promise => { + const key = JSON.stringify([keyParts, args]); + if (mockCacheStore.has(key)) return mockCacheStore.get(key) as R; + const value = await fn(...args); + mockCacheStore.set(key, value); + return value; + }; + }, +})); + +const mockGetLocations = jest.fn(); +const mockSearchFeeds = jest.fn(); + +jest.mock('../../../services/feeds', () => ({ + ApiError: class ApiError extends Error { + readonly status: number; + constructor(message: string, status: number) { + super(message); + this.status = status; + } + }, + getLocations: (...args: unknown[]) => mockGetLocations(...args), + searchFeeds: (...args: unknown[]) => mockSearchFeeds(...args), +})); + +jest.mock('../../../utils/auth-server', () => ({ + getGuestGcipIdToken: async () => 'guest-token', +})); + +const STATUSES = ['active', 'inactive', 'development', 'future']; + +const northAmerica = { + location_id: null, + location_type: 'continent', + continent_code: 'NA', + name: 'North America', + slug: 'north-america', + path_slugs: ['north-america'], + feed_counts: { total: 30 }, +}; +const antarctica = { + ...northAmerica, + continent_code: 'AN', + name: 'Antarctica', + slug: 'antarctica', + path_slugs: ['antarctica'], + feed_counts: { total: 0 }, +}; +const canada = { + location_id: 1428125, + location_type: 'country', + continent_code: 'NA', + name: 'Canada', + slug: 'ca', + path_slugs: ['ca'], + feed_counts: { total: 25 }, +}; +const montreal = { + location_id: 175905, + location_type: 'municipality', + continent_code: 'NA', + name: 'Montréal', + slug: '175905-montreal', + path_slugs: ['ca', '61549-quebec', '175905-montreal'], + feed_counts: { total: 22 }, +}; +const CONTINENT_INFO = [ + { code: 'NA', slug: 'north-america', name: 'North America' }, + { code: 'AN', slug: 'antarctica', name: 'Antarctica' }, +]; +const feeds = { total: 22, results: [{ id: 'mdb-1' }] }; +const emptyFeeds = { total: 0, results: [] }; + +type Params = Record; + +/** Answers /v1/locations like the API, from its filters. */ +function locationsApi({ + children = [montreal], + places = [canada, montreal], +}: { children?: unknown[]; places?: Array } = {}) { + return async (params: Params) => { + const page = (rows: unknown[]) => { + const offset = Number(params.offset ?? 0); + const limit = Number(params.limit ?? 100); + return { + total: rows.length, + results: rows.slice(offset, offset + limit), + }; + }; + if (params.location_type === 'continent') { + const continents = [northAmerica, antarctica]; + return page( + params.continent === undefined + ? continents + : continents.filter(({ slug }) => slug === params.continent), + ); + } + if (params.location_type === 'country' && params.continent !== undefined) { + return page([canada]); + } + if (params.country_code !== undefined) { + return page( + places.filter( + ({ location_type, slug }) => + location_type === 'country' && slug === params.country_code, + ), + ); + } + if (params.parent_location_id !== undefined) return page(children); + if (params.location_id !== undefined) { + return page( + places.filter(({ location_id }) => location_id === params.location_id), + ); + } + throw new Error(`unexpected query ${JSON.stringify(params)}`); + }; +} + +function locationQueries(): Params[] { + return mockGetLocations.mock.calls.map(([params]) => params as Params); +} + +function searchQueries(): Params[] { + return mockSearchFeeds.mock.calls.map( + ([params]) => (params as { query: Params }).query, + ); +} + +describe('fetchLocationPage', () => { + beforeEach(() => { + mockCacheStore.clear(); + mockGetLocations.mockReset(); + mockGetLocations.mockImplementation(locationsApi()); + mockSearchFeeds.mockReset(); + mockSearchFeeds.mockResolvedValue(feeds); + }); + + it('lists the continents with feeds and the newest feeds at the root', async () => { + const data = await fetchLocationPage(2, 'root', ''); + + expect(data).toEqual({ + location: null, + children: [northAmerica], + feeds, + continents: CONTINENT_INFO, + }); + expect(locationQueries()).toEqual([ + { + location_type: 'continent', + include: ['feed_counts'], + sort: 'feed_count', + limit: 100, + offset: 0, + }, + ]); + expect(searchQueries()).toEqual([ + { status: STATUSES, limit: 20, offset: 20 }, + ]); + }); + + it('lists a continent with its countries and feeds, in parallel', async () => { + const data = await fetchLocationPage(1, 'continent', 'north-america'); + + expect(data).toEqual({ + location: northAmerica, + children: [canada], + feeds, + continents: CONTINENT_INFO, + }); + expect(locationQueries()).toContainEqual({ + has_feeds: true, + include: ['feed_counts'], + sort: 'feed_count', + location_type: 'country', + continent: 'north-america', + limit: 100, + offset: 0, + }); + expect(searchQueries()).toEqual([ + { + continent: 'north-america', + sort: 'location', + status: STATUSES, + limit: 20, + offset: 0, + }, + ]); + }); + + it('is null for an unknown continent', async () => { + expect(await fetchLocationPage(1, 'continent', 'atlantis')).toBeNull(); + }); + + it('resolves a country from its code, then its children and feeds', async () => { + const data = await fetchLocationPage(1, 'country', 'ca'); + + expect(data?.location).toEqual(canada); + expect(data?.children).toEqual([montreal]); + expect(locationQueries()).toContainEqual({ + location_type: 'country', + country_code: 'ca', + include: ['feed_counts'], + limit: 1, + }); + expect(locationQueries()).toContainEqual({ + has_feeds: true, + include: ['feed_counts'], + sort: 'feed_count', + parent_location_id: canada.location_id, + limit: 100, + offset: 0, + }); + expect(searchQueries()).toEqual([ + { + location_id: canada.location_id, + sort: 'location', + status: STATUSES, + limit: 20, + offset: 0, + }, + ]); + }); + + it('fetches a place, its children and its feeds from its id', async () => { + const data = await fetchLocationPage(2, 'place', '175905'); + + expect(data).toEqual({ + location: montreal, + children: [montreal], + feeds, + continents: CONTINENT_INFO, + }); + expect(locationQueries()).toContainEqual({ + location_id: 175905, + include: ['feed_counts'], + limit: 1, + }); + expect(searchQueries()).toEqual([ + { + location_id: 175905, + sort: 'location', + status: STATUSES, + limit: 20, + offset: 20, + }, + ]); + }); + + it('is null for an unknown place or country', async () => { + mockSearchFeeds.mockResolvedValue(emptyFeeds); + expect(await fetchLocationPage(1, 'place', '42')).toBeNull(); + expect(await fetchLocationPage(1, 'country', 'zz')).toBeNull(); + }); + + it('is null when the API rejects the request', async () => { + mockGetLocations.mockRejectedValue(new ApiError('Bad request', 400)); + expect(await fetchLocationPage(1, 'place', '175905')).toBeNull(); + }); + + it('rethrows other API errors', async () => { + mockGetLocations.mockRejectedValue(new ApiError('Unavailable', 503)); + await expect(fetchLocationPage(1, 'place', '175905')).rejects.toThrow( + 'Unavailable', + ); + }); + + it('fetches every page of children', async () => { + const children = Array.from({ length: 150 }, (_, index) => ({ + ...montreal, + location_id: index + 1, + })); + mockGetLocations.mockImplementation(locationsApi({ children })); + + const data = await fetchLocationPage(1, 'place', '175905'); + + expect(data?.children).toHaveLength(150); + expect( + locationQueries() + .filter((params) => params.parent_location_id !== undefined) + .map(({ offset }) => offset), + ).toEqual([0, 100]); + }); + + it('caches the empty feed page of a location without feeds', async () => { + mockSearchFeeds.mockResolvedValue(emptyFeeds); + + await fetchLocationPage(1, 'place', '175905'); + await fetchLocationPage(1, 'place', '175905'); + + expect(mockSearchFeeds).toHaveBeenCalledTimes(1); + }); + + it('never caches a later page of a location without feeds', async () => { + mockSearchFeeds.mockResolvedValue(emptyFeeds); + + await fetchLocationPage(3, 'place', '175905'); + await fetchLocationPage(3, 'place', '175905'); + + expect(mockSearchFeeds).toHaveBeenCalledTimes(2); + }); + + it('never caches a page past the last one', async () => { + mockSearchFeeds.mockResolvedValue({ total: 22, results: [] }); + + await fetchLocationPage(9, 'place', '175905'); + await fetchLocationPage(9, 'place', '175905'); + + expect(mockSearchFeeds).toHaveBeenCalledTimes(2); + }); + + it('never caches the empty feed page of an unknown location', async () => { + mockSearchFeeds.mockResolvedValue(emptyFeeds); + + await fetchLocationPage(1, 'place', '42'); + await fetchLocationPage(1, 'place', '42'); + + expect(mockSearchFeeds).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/app/[locale]/locations/lib/location-directory-data.ts b/src/app/[locale]/locations/lib/location-directory-data.ts new file mode 100644 index 00000000..cf920c47 --- /dev/null +++ b/src/app/[locale]/locations/lib/location-directory-data.ts @@ -0,0 +1,436 @@ +/** + * Cacheable data fetching for the /locations directory. + * + * The directory is public, catalog-wide data, so these functions use the + * shared guest token and must NOT call cookies() or headers() directly or + * indirectly (same rule as the guest feed pages, see guest-feed-data.ts). + */ +import 'server-only'; +import { cache } from 'react'; +import { unstable_cache } from 'next/cache'; +import { getGuestGcipIdToken } from '../../../utils/auth-server'; +import { + ApiError, + getLocations, + searchFeeds, + type LocationsParams, + type SearchFeedsResponse, +} from '../../../services/feeds'; +import { + fetchAllPages, + getPageOffset, + LOCATION_FEEDS_PAGE_SIZE, + toContinentInfo, + type ContinentInfo, + type LocationRequest, + type LocationResult, +} from './location-directory'; + +/** 6 hours; also flushed on demand with the existing `guest-feeds` tag. */ +export const LOCATION_DIRECTORY_REVALIDATE_SECONDS = 21600; +const CACHE_TAGS = ['location-directory', 'guest-feeds']; +const CACHE_OPTIONS = { + tags: CACHE_TAGS, + revalidate: LOCATION_DIRECTORY_REVALIDATE_SECONDS, +}; + +/** The statuses `feed_counts` counts, so a location lists as many feeds. */ +const DIRECTORY_FEED_STATUSES: Array< + 'active' | 'inactive' | 'development' | 'future' +> = ['active', 'inactive', 'development', 'future']; + +/** + * A URL that does not exist: no location matches it, or the API rejects it + * (400). Thrown inside the cached functions because unstable_cache never + * stores a thrown error: caching the miss would keep a location missing for + * hours after it starts to exist. + */ +class LocationNotFoundError extends Error {} + +async function requireData( + request: () => Promise, +): Promise { + try { + const data = await request(); + if (data == undefined) { + throw new Error('Empty response from the locations API'); + } + return data; + } catch (error) { + if ( + error instanceof ApiError && + (error.status === 400 || error.status === 404) + ) { + throw new LocationNotFoundError(error.message); + } + throw error; + } +} + +/** Resolves a missing location to null so the page can call notFound(). */ +async function nullWhenMissing( + request: () => Promise, +): Promise { + try { + return await request(); + } catch (error) { + if (error instanceof LocationNotFoundError) return null; + throw error; + } +} + +/** Locations with feeds, most feeds first, with their counts. */ +const WITH_FEEDS: Pick = { + has_feeds: true, + include: ['feed_counts'], + sort: 'feed_count', +}; + +/** Every location matching the filters (every page). */ +async function fetchLocations( + filters: LocationsParams, +): Promise { + const accessToken = await getGuestGcipIdToken(); + return await fetchAllPages( + async (offset, limit) => + await requireData( + async () => + await getLocations({ ...filters, limit, offset }, accessToken), + ), + ); +} + +/** The only location matching the filters; throws when there is none. */ +async function fetchLocation( + filters: LocationsParams, +): Promise { + const accessToken = await getGuestGcipIdToken(); + const { results } = await requireData( + async () => + await getLocations( + { ...filters, include: ['feed_counts'], limit: 1 }, + accessToken, + ), + ); + const location = results[0]; + if (location === undefined) throw new LocationNotFoundError('No location'); + return location; +} + +// unstable_cache keys on the key parts plus the call arguments, so the +// arguments are kept primitive. + +/** The seven continents with their counts, most feeds first. */ +const cachedContinents = unstable_cache( + async (): Promise => + await fetchLocations({ + location_type: 'continent', + include: ['feed_counts'], + sort: 'feed_count', + }), + ['location-directory-continents'], + CACHE_OPTIONS, +); + +/** The countries of a continent (slug) that have feeds. */ +const cachedContinentCountries = unstable_cache( + async (continentSlug: string): Promise => + await fetchLocations({ + ...WITH_FEEDS, + location_type: 'country', + continent: continentSlug, + }), + ['location-directory-continent-countries'], + CACHE_OPTIONS, +); + +/** The country with this ISO 3166-1 code; throws when there is none. */ +const cachedCountry = unstable_cache( + async (countryCode: string): Promise => + await fetchLocation({ + location_type: 'country', + country_code: countryCode, + }), + ['location-directory-country'], + CACHE_OPTIONS, +); + +/** The location with this id; throws when there is none. */ +const cachedPlace = unstable_cache( + async (locationId: number): Promise => + await fetchLocation({ location_id: locationId }), + ['location-directory-place'], + CACHE_OPTIONS, +); + +/** The direct children with feeds of a location. */ +const cachedChildren = unstable_cache( + async (parentLocationId: number): Promise => + await fetchLocations({ + ...WITH_FEEDS, + parent_location_id: parentLocationId, + }), + ['location-directory-children'], + CACHE_OPTIONS, +); + +/** Whose feeds a page lists: every feed, a continent's or a location's. */ +type FeedScope = + | { kind: 'all' } + | { kind: 'continent'; continentSlug: string } + | { kind: 'location'; locationId: number }; + +/** + * Carries a feed page without results out of unstable_cache without storing + * it: an unknown location or a page past the last one, including any page + * after the first of a location without feeds. The feeds are fetched in + * parallel with the location, so caching those would let any URL add entries + * to the data cache. The first, empty page of an existing location is stored, + * so that it replaces a page that had feeds: a refresh that throws keeps the + * old entry. + */ +class UncachedFeedsPage extends Error { + readonly feeds: SearchFeedsResponse; + + constructor(feeds: SearchFeedsResponse) { + super('Empty feed page'); + this.feeds = feeds; + } +} + +/** Whether the scope's location exists; only asked when its page is empty. */ +async function scopeExists( + scope: FeedScope, + accessToken: string, +): Promise { + if (scope.kind === 'all') return true; + const filters: LocationsParams = + scope.kind === 'continent' + ? { location_type: 'continent', continent: scope.continentSlug } + : { location_id: scope.locationId }; + try { + const locations = await getLocations({ ...filters, limit: 1 }, accessToken); + return (locations?.total ?? 0) > 0; + } catch (error) { + if (error instanceof ApiError && error.status === 400) return false; + throw error; + } +} + +function scopeQuery( + scope: FeedScope, +): + | { location_id: number; sort: 'location' } + | { continent: string; sort: 'location' } + | Record { + if (scope.kind === 'continent') { + return { continent: scope.continentSlug, sort: 'location' }; + } + if (scope.kind === 'location') { + return { location_id: scope.locationId, sort: 'location' }; + } + return {}; +} + +/** + * One page of feeds: newest first for every feed, otherwise most relevant to + * the continent or location first. The scope is passed as primitives, for the + * cache key. + */ +const cachedFeeds = unstable_cache( + async ( + offset: number, + scopeKind: FeedScope['kind'], + scopeValue: string | number | null, + ): Promise => { + const scope: FeedScope = + scopeKind === 'continent' + ? { kind: 'continent', continentSlug: String(scopeValue) } + : scopeKind === 'location' + ? { kind: 'location', locationId: Number(scopeValue) } + : { kind: 'all' }; + const accessToken = await getGuestGcipIdToken(); + const feeds = await requireData( + async () => + await searchFeeds( + { + query: { + ...scopeQuery(scope), + status: DIRECTORY_FEED_STATUSES, + limit: LOCATION_FEEDS_PAGE_SIZE, + offset, + }, + }, + accessToken, + ), + ); + // An empty page is stored only when it is the first page of an existing + // location: any other empty page (an unknown location, a page past the + // last one, any page number of a location without feeds) would let a URL + // add cache entries. + if ( + (feeds.results ?? []).length === 0 && + ((feeds.total ?? 0) > 0 || + offset > 0 || + scope.kind === 'all' || + !(await scopeExists(scope, accessToken))) + ) { + throw new UncachedFeedsPage(feeds); + } + return feeds; + }, + ['location-directory-feeds'], + CACHE_OPTIONS, +); + +async function fetchFeeds( + offset: number, + scope: FeedScope, +): Promise { + const scopeValue = + scope.kind === 'continent' + ? scope.continentSlug + : scope.kind === 'location' + ? scope.locationId + : null; + try { + return await cachedFeeds(offset, scope.kind, scopeValue); + } catch (error) { + if (error instanceof UncachedFeedsPage) return error.feeds; + throw error; + } +} + +export interface LocationPageData { + /** The current location; null at the root. */ + location: LocationResult | null; + /** Continents with feeds at the root, otherwise the children with feeds. */ + children: LocationResult[]; + /** The requested page of feeds located there. */ + feeds: SearchFeedsResponse; + /** The seven continents, to name and link every location's continent. */ + continents: ContinentInfo[]; +} + +/** + * The location, its children and the feed page. A continent or a place is + * fetched in parallel with its children and feeds, from the URL alone; a + * country's id is first resolved from its code (cached). + */ +async function loadLocationPage( + page: number, + request: LocationRequest, +): Promise { + const offset = getPageOffset(page); + + if (request.kind === 'root') { + const [continents, feeds] = await Promise.all([ + cachedContinents(), + fetchFeeds(offset, { kind: 'all' }), + ]); + return { + location: null, + children: continents.filter( + (continent) => (continent.feed_counts?.total ?? 0) > 0, + ), + feeds, + continents: toContinentInfo(continents), + }; + } + + if (request.kind === 'continent') { + const { continentSlug } = request; + const [continents, children, feeds] = await Promise.all([ + cachedContinents(), + cachedContinentCountries(continentSlug), + fetchFeeds(offset, { kind: 'continent', continentSlug }), + ]); + const location = continents.find(({ slug }) => slug === continentSlug); + if (location === undefined) throw new LocationNotFoundError(continentSlug); + return { + location, + children, + feeds, + continents: toContinentInfo(continents), + }; + } + + if (request.kind === 'country') { + const [continents, location] = await Promise.all([ + cachedContinents(), + cachedCountry(request.countryCode), + ]); + const locationId = location.location_id as number; + const [children, feeds] = await Promise.all([ + cachedChildren(locationId), + fetchFeeds(offset, { kind: 'location', locationId }), + ]); + return { + location, + children, + feeds, + continents: toContinentInfo(continents), + }; + } + + const { locationId } = request; + const [continents, location, children, feeds] = await Promise.all([ + cachedContinents(), + cachedPlace(locationId), + cachedChildren(locationId), + fetchFeeds(offset, { kind: 'location', locationId }), + ]); + return { + location, + children, + feeds, + continents: toContinentInfo(continents), + }; +} + +/** + * Everything a directory page shows, or null when the location does not + * exist. React cache() dedupes the generateMetadata and page calls within + * one request; it compares arguments by identity, hence primitives: the + * request is passed as its URL segments. + */ +export const fetchLocationPage = cache( + async ( + page: number, + kind: LocationRequest['kind'], + key: string, + ): Promise => + await nullWhenMissing( + async () => await loadLocationPage(page, toRequest(kind, key)), + ), +); + +/** The cache() key of a request: its kind and what identifies it. */ +export function requestKey(request: LocationRequest): string { + switch (request.kind) { + case 'root': + return ''; + case 'continent': + return request.continentSlug; + case 'country': + return request.countryCode; + case 'place': + return String(request.locationId); + } +} + +function toRequest( + kind: LocationRequest['kind'], + key: string, +): LocationRequest { + switch (kind) { + case 'root': + return { kind, segments: [] }; + case 'continent': + return { kind, segments: [], continentSlug: key }; + case 'country': + return { kind, segments: [], countryCode: key }; + case 'place': + return { kind, segments: [], locationId: Number(key) }; + } +} diff --git a/src/app/[locale]/locations/lib/location-directory.spec.ts b/src/app/[locale]/locations/lib/location-directory.spec.ts new file mode 100644 index 00000000..f57f89a7 --- /dev/null +++ b/src/app/[locale]/locations/lib/location-directory.spec.ts @@ -0,0 +1,519 @@ +import { + buildBreadcrumbSteps, + buildLocationHref, + buildPlaceName, + type ContinentInfo, + fetchAllPages, + fetchRemainingPages, + filterByName, + formatCount, + getChildrenKind, + getFeedCountEntries, + getLocationName, + getLocationSegments, + getPageCount, + getPageOffset, + getTotalFeedCount, + isSameSegments, + type LocationResult, + normalizeLocationName, + parseLocationRequest, + parsePageParam, + sortByFeedCount, + toContinentInfo, +} from './location-directory'; + +const northAmerica: LocationResult = { + location_id: null, + parent_location_id: null, + location_type: 'continent', + continent_code: 'NA', + name: 'North America', + slug: 'north-america', + path_slugs: ['north-america'], + path_names: ['North America'], +}; + +const CONTINENTS: ContinentInfo[] = [ + { code: 'EU', slug: 'europe', name: 'Europe' }, + { code: 'NA', slug: 'north-america', name: 'North America' }, +]; + +// Variable depth: Montréal sits under an intermediate region. +const montreal: LocationResult = { + location_id: 175905, + parent_location_id: 161950, + location_type: 'municipality', + continent_code: 'NA', + name: 'Montréal', + slug: '175905-montreal', + path_slugs: [ + 'ca', + '61549-quebec', + '161950-montreal-region', + '175905-montreal', + ], + path_names: ['Canada', 'Québec', 'Montréal (region)', 'Montréal'], +}; + +const canada: LocationResult = { + location_id: 1428125, + parent_location_id: null, + location_type: 'country', + continent_code: 'NA', + name: 'Canada', + slug: 'ca', + path_slugs: ['ca'], + path_names: ['Canada'], +}; + +// A country without continent in the classification. +const clipperton: LocationResult = { + location_id: 2, + parent_location_id: null, + location_type: 'country', + continent_code: null, + name: 'Clipperton', + slug: 'cp', + path_slugs: ['cp'], + path_names: ['Clipperton'], +}; + +describe('parseLocationRequest', () => { + it('is the root without segments', () => { + expect(parseLocationRequest(undefined)).toEqual({ + kind: 'root', + segments: [], + }); + expect(parseLocationRequest([])).toEqual({ kind: 'root', segments: [] }); + }); + + it('reads a continent from its slug', () => { + expect(parseLocationRequest(['north-america'])).toEqual({ + kind: 'continent', + segments: ['north-america'], + continentSlug: 'north-america', + }); + }); + + it('reads a country from its code, with or without continent', () => { + expect(parseLocationRequest(['north-america', 'ca'])).toEqual({ + kind: 'country', + segments: ['north-america', 'ca'], + countryCode: 'ca', + }); + expect(parseLocationRequest(['cp'])).toEqual({ + kind: 'country', + segments: ['cp'], + countryCode: 'cp', + }); + }); + + it('reads a place from the id of its last segment, at any depth', () => { + const segments = [ + 'north-america', + 'ca', + '61549-quebec', + '161950-montreal-region', + '175905-montreal', + ]; + expect(parseLocationRequest(segments)).toEqual({ + kind: 'place', + segments, + locationId: 175905, + }); + // The name part is only there to be read. + expect( + parseLocationRequest(['north-america', 'ca', '61549-old-name']), + ).toMatchObject({ kind: 'place', locationId: 61549 }); + expect(parseLocationRequest(['asia', 'jp', '1234'])).toMatchObject({ + kind: 'place', + locationId: 1234, + }); + }); + + it('decodes percent-encoded segments', () => { + expect( + parseLocationRequest([ + 'asia', + 'jp', + `1234-${encodeURIComponent('東京')}`, + ]), + ).toMatchObject({ kind: 'place', locationId: 1234 }); + }); + + it.each([ + [['north-america', '']], + [['north-america', ' ']], + [['North-America']], + [['north-america', 'CA']], + [['north-america', 'canada']], + [['north-america', 'ca', 'quebec']], + [['north-america', 'ca', 'quebec', '175905-montreal']], + [['north-america', 'ca', '0-nowhere']], + [['north-america', 'ca', 'can ada']], + [['north-america', 'ca', '61549-quebec.json']], + [['north-america', 'ca', '%E0%A4%A']], + ])('rejects malformed segments %p', (segments) => { + expect(parseLocationRequest(segments)).toBeNull(); + }); +}); + +describe('parsePageParam', () => { + it('defaults to page 1 when absent', () => { + expect(parsePageParam(undefined)).toBe(1); + }); + + it('accepts positive integers', () => { + expect(parsePageParam('1')).toBe(1); + expect(parsePageParam('2')).toBe(2); + expect(parsePageParam('120')).toBe(120); + }); + + it.each(['', '0', '-1', '+2', '01', '1.5', '1e3', 'abc', ' 2', '2 '])( + 'rejects %p', + (raw) => { + expect(parsePageParam(raw)).toBeNull(); + }, + ); + + it('rejects repeated params and unsafe integers', () => { + expect(parsePageParam(['1', '2'])).toBeNull(); + expect(parsePageParam('99999999999999999999')).toBeNull(); + }); +}); + +describe('pagination math', () => { + it('computes the page count with a floor of 1', () => { + expect(getPageCount(0)).toBe(1); + expect(getPageCount(1)).toBe(1); + expect(getPageCount(20)).toBe(1); + expect(getPageCount(21)).toBe(2); + expect(getPageCount(45, 10)).toBe(5); + }); + + it('computes the API offset of a 1-based page', () => { + expect(getPageOffset(1)).toBe(0); + expect(getPageOffset(2)).toBe(20); + expect(getPageOffset(3, 10)).toBe(20); + }); +}); + +describe('buildLocationHref', () => { + it('builds the root and nested paths', () => { + expect(buildLocationHref([])).toBe('/locations'); + expect(buildLocationHref(['north-america', 'ca', '61549-quebec'])).toBe( + '/locations/north-america/ca/61549-quebec', + ); + }); + + it('adds ?page only after the first page', () => { + expect(buildLocationHref(['europe'], 1)).toBe('/locations/europe'); + expect(buildLocationHref(['europe'], 2)).toBe('/locations/europe?page=2'); + expect(buildLocationHref([], 3)).toBe('/locations?page=3'); + }); + + it('encodes unsafe characters in segments', () => { + expect(buildLocationHref(['a b', 'c/d'])).toBe('/locations/a%20b/c%2Fd'); + }); +}); + +describe('location segments and names', () => { + it('reads the continents of the API results', () => { + expect(toContinentInfo([northAmerica, canada])).toEqual([ + { code: 'NA', slug: 'north-america', name: 'North America' }, + ]); + }); + + it('links a location through its continent and path slugs', () => { + expect(getLocationSegments(montreal, CONTINENTS)).toEqual([ + 'north-america', + 'ca', + '61549-quebec', + '161950-montreal-region', + '175905-montreal', + ]); + expect(buildLocationHref(getLocationSegments(canada, CONTINENTS))).toBe( + '/locations/north-america/ca', + ); + expect( + buildLocationHref(getLocationSegments(northAmerica, CONTINENTS)), + ).toBe('/locations/north-america'); + expect(buildLocationHref(getLocationSegments(clipperton, CONTINENTS))).toBe( + '/locations/cp', + ); + }); + + it('round-trips with URL parsing', () => { + const segments = getLocationSegments(montreal, CONTINENTS); + const href = buildLocationHref(segments, 2); + expect(href).toBe( + '/locations/north-america/ca/61549-quebec/161950-montreal-region/175905-montreal?page=2', + ); + const parsed = parseLocationRequest(href.split('?')[0].split('/').slice(2)); + expect(parsed).toMatchObject({ kind: 'place', locationId: 175905 }); + expect(isSameSegments(parsed?.segments ?? [], segments)).toBe(true); + }); + + it('compares segment lists', () => { + expect(isSameSegments(['europe', 'fr'], ['europe', 'fr'])).toBe(true); + expect(isSameSegments(['asia', 'fr'], ['europe', 'fr'])).toBe(false); + expect(isSameSegments(['europe'], ['europe', 'fr'])).toBe(false); + }); + + it('names a location, falling back to its slug', () => { + expect(getLocationName(montreal)).toBe('Montréal'); + expect(getLocationName({ ...montreal, name: null })).toBe( + '175905-montreal', + ); + expect(getLocationName(northAmerica)).toBe('North America'); + }); +}); + +describe('buildBreadcrumbSteps', () => { + it('is empty at the root', () => { + expect(buildBreadcrumbSteps(null, CONTINENTS)).toEqual([]); + }); + + it('has a single step on a continent', () => { + expect(buildBreadcrumbSteps(northAmerica, CONTINENTS)).toEqual([ + { label: 'North America', segments: ['north-america'] }, + ]); + }); + + it('starts with the continent, then one step per path name', () => { + expect(buildBreadcrumbSteps(montreal, CONTINENTS)).toEqual([ + { label: 'North America', segments: ['north-america'] }, + { label: 'Canada', segments: ['north-america', 'ca'] }, + { + label: 'Québec', + segments: ['north-america', 'ca', '61549-quebec'], + }, + { + label: 'Montréal (region)', + segments: [ + 'north-america', + 'ca', + '61549-quebec', + '161950-montreal-region', + ], + }, + { + label: 'Montréal', + segments: [ + 'north-america', + 'ca', + '61549-quebec', + '161950-montreal-region', + '175905-montreal', + ], + }, + ]); + }); + + it('starts at the country without continent', () => { + expect(buildBreadcrumbSteps(clipperton, CONTINENTS)).toEqual([ + { label: 'Clipperton', segments: ['cp'] }, + ]); + }); + + it('ignores unaligned names', () => { + const steps = buildBreadcrumbSteps( + { ...canada, path_names: ['Canada', 'Extra'] }, + CONTINENTS, + ); + expect(steps.map((step) => step.label)).toEqual([ + 'North America', + 'Canada', + ]); + }); +}); + +describe('buildPlaceName', () => { + it('is empty at the root', () => { + expect(buildPlaceName(null)).toBe(''); + }); + + it('names a continent on its own', () => { + expect(buildPlaceName(northAmerica)).toBe('North America'); + }); + + it('lists the most specific place first, without the continent', () => { + expect(buildPlaceName(canada)).toBe('Canada'); + expect(buildPlaceName(montreal)).toBe( + 'Montréal, Montréal (region), Québec, Canada', + ); + }); + + it('keeps the country of a location without continent', () => { + expect(buildPlaceName(clipperton)).toBe('Clipperton'); + }); + + it('falls back to the name without path names', () => { + expect(buildPlaceName({ ...canada, path_names: [] })).toBe('Canada'); + }); +}); + +describe('getChildrenKind', () => { + it('lists continents at the root', () => { + expect(getChildrenKind(null)).toBe('continents'); + }); + + it('lists countries in a continent', () => { + expect(getChildrenKind(northAmerica)).toBe('countries'); + }); + + it('lists places below a country', () => { + expect(getChildrenKind(canada)).toBe('places'); + expect(getChildrenKind(montreal)).toBe('places'); + }); +}); + +describe('fetchAllPages', () => { + const pageOf = ( + total: number, + offset: number, + limit: number, + ): { total: number; results: number[] } => ({ + total, + results: Array.from( + { length: Math.max(0, Math.min(limit, total - offset)) }, + (_, index) => offset + index, + ), + }); + + it('stops after the first page when it holds everything', async () => { + const fetchPage = jest.fn(async (offset: number, limit: number) => + pageOf(42, offset, limit), + ); + await expect(fetchAllPages(fetchPage)).resolves.toHaveLength(42); + expect(fetchPage).toHaveBeenCalledTimes(1); + expect(fetchPage).toHaveBeenCalledWith(0, 100); + }); + + it('fetches the remaining pages in order', async () => { + const fetchPage = jest.fn(async (offset: number, limit: number) => + pageOf(250, offset, limit), + ); + const results = await fetchAllPages(fetchPage); + expect(results).toEqual(Array.from({ length: 250 }, (_, index) => index)); + expect(fetchPage.mock.calls).toEqual([ + [0, 100], + [100, 100], + [200, 100], + ]); + }); + + it('follows a server that returns fewer results than asked', async () => { + const fetchPage = jest.fn(async (offset: number) => pageOf(25, offset, 10)); + await expect(fetchAllPages(fetchPage)).resolves.toHaveLength(25); + expect(fetchPage.mock.calls.map(([offset]) => offset)).toEqual([0, 10, 20]); + }); + + it('completes a first page fetched elsewhere', async () => { + const fetchPage = jest.fn(async (offset: number, limit: number) => + pageOf(230, offset, limit), + ); + const results = await fetchRemainingPages(pageOf(230, 0, 100), fetchPage); + expect(results).toEqual(Array.from({ length: 230 }, (_, index) => index)); + expect(fetchPage.mock.calls).toEqual([ + [100, 100], + [200, 100], + ]); + await expect( + fetchRemainingPages(pageOf(42, 0, 100), fetchPage), + ).resolves.toHaveLength(42); + expect(fetchPage).toHaveBeenCalledTimes(2); + }); + + it('handles empty and total-less responses', async () => { + await expect( + fetchAllPages(async () => ({ total: 0, results: [] })), + ).resolves.toEqual([]); + await expect(fetchAllPages(async () => ({}))).resolves.toEqual([]); + await expect( + fetchAllPages(async () => ({ results: [1, 2] })), + ).resolves.toEqual([1, 2]); + }); +}); + +describe('feed counts', () => { + it('lists GTFS, GTFS-RT and GBFS in order, defaulting to 0', () => { + expect(getFeedCountEntries({ gtfs: 4, gbfs: 1 })).toEqual([ + { dataType: 'gtfs', count: 4 }, + { dataType: 'gtfs_rt', count: 0 }, + { dataType: 'gbfs', count: 1 }, + ]); + expect(getFeedCountEntries(undefined).map((e) => e.count)).toEqual([ + 0, 0, 0, + ]); + }); + + it('prefers the distinct total over the per-type sum', () => { + expect(getTotalFeedCount({ gtfs: 2, gtfs_rt: 2, gbfs: 1, total: 4 })).toBe( + 4, + ); + expect(getTotalFeedCount({ gtfs: 2, gtfs_rt: 2, gbfs: 1 })).toBe(5); + expect(getTotalFeedCount(undefined)).toBe(0); + }); + + it('formats counts for the locale', () => { + expect(formatCount(1234, 'en')).toBe('1,234'); + expect(formatCount(undefined, 'en')).toBe('0'); + // fr groups with a narrow no-break space + expect(formatCount(1234, 'fr').replace(/\s/g, ' ')).toBe('1 234'); + }); +}); + +describe('normalizeLocationName', () => { + it('drops accents and case', () => { + expect(normalizeLocationName(' Québec ')).toBe('quebec'); + expect(normalizeLocationName('São Paulo')).toBe('sao paulo'); + }); +}); + +describe('sortByFeedCount', () => { + const item = ( + name: string, + total: number, + ): { name: string; counts: { total: number } } => ({ + name, + counts: { total }, + }); + + it('puts the most feeds first, then sorts by name', () => { + const sorted = sortByFeedCount([ + item('Laval', 3), + item('Montréal', 22), + item('Québec', 3), + item('Gatineau', 1), + item('Lévis', 3), + ]); + expect(sorted.map(({ name }) => name)).toEqual([ + 'Montréal', + 'Laval', + 'Lévis', + 'Québec', + 'Gatineau', + ]); + }); + + it('does not mutate its input', () => { + const items = [item('B', 1), item('A', 2)]; + sortByFeedCount(items); + expect(items.map(({ name }) => name)).toEqual(['B', 'A']); + }); +}); + +describe('filterByName', () => { + const items = [{ name: 'Montréal' }, { name: 'Québec' }, { name: 'Laval' }]; + + it('matches anywhere in the name, ignoring accents and case', () => { + expect(filterByName(items, 'MONTRE')).toEqual([{ name: 'Montréal' }]); + expect(filterByName(items, 'bec')).toEqual([{ name: 'Québec' }]); + }); + + it('returns every item for a blank query', () => { + expect(filterByName(items, ' ')).toEqual(items); + }); +}); diff --git a/src/app/[locale]/locations/lib/location-directory.ts b/src/app/[locale]/locations/lib/location-directory.ts new file mode 100644 index 00000000..4a160348 --- /dev/null +++ b/src/app/[locale]/locations/lib/location-directory.ts @@ -0,0 +1,374 @@ +/** + * Pure helpers for the /locations directory: URL segment and page parsing, + * URL and breadcrumb building, paging and count formatting. Safe to import + * from server and client components; holds no data fetching. + */ +import type { components } from '../../../services/feeds/types'; + +export type LocationResult = components['schemas']['LocationSearchResult']; +export type LocationFeedCounts = components['schemas']['LocationFeedCounts']; + +export const LOCATIONS_BASE_PATH = '/locations'; +export const LOCATION_FEEDS_PAGE_SIZE = 20; +/** Maximum `limit` of the `/v1/locations` endpoints. */ +export const LOCATIONS_API_PAGE_SIZE = 100; +/** Anchor of the feed list; pagination links jump back to it. */ +export const FEEDS_SECTION_ID = 'feeds'; + +// URL segments: lowercase letters (any script), digits and hyphens, e.g. +// `north-america`, `ca`, `175905-montreal`. +const SLUG_PATTERN = /^[\p{Ll}\p{Lo}\p{M}\p{Nd}-]+$/u; +// A country's segment is its ISO 3166-1 alpha-2 code, lowercased. +const COUNTRY_SEGMENT_PATTERN = /^[a-z]{2}$/; +// Below the country, a segment starts with the location id; the rest is the +// name, only there to be read. +const PLACE_SEGMENT_PATTERN = /^(\d+)(?:-|$)/; + +function decodeSegment(segment: string): string | null { + if (!segment.includes('%')) return segment; + try { + return decodeURIComponent(segment); + } catch { + return null; + } +} + +/** The location id at the start of a place segment (`175905-montreal`). */ +function placeIdOf(segment: string): number | null { + const match = PLACE_SEGMENT_PATTERN.exec(segment); + if (match === null) return null; + const id = Number(match[1]); + return Number.isSafeInteger(id) && id > 0 ? id : null; +} + +/** + * The location a directory URL asks for. `segments` are the URL segments as + * requested, to compare with the location's canonical segments. + */ +export type LocationRequest = + | { kind: 'root'; segments: string[] } + | { kind: 'continent'; segments: string[]; continentSlug: string } + | { kind: 'country'; segments: string[]; countryCode: string } + | { kind: 'place'; segments: string[]; locationId: number }; + +/** + * Parses the optional catch-all segments of `/locations/...`: + * `//-/...`, as deep as the location. A + * country without continent starts at its code. Only the last segment + * identifies the location (continent slug, country code or location id); + * the others are checked against its canonical URL by the page. + * + * @returns null when a segment is malformed: empty, uppercase, spaces, + * punctuation other than `-`, or a place segment without its id. + */ +export function parseLocationRequest( + rawSegments: readonly string[] | undefined, +): LocationRequest | null { + const segments: string[] = []; + for (const rawSegment of rawSegments ?? []) { + const segment = decodeSegment(rawSegment); + if (segment === null || !SLUG_PATTERN.test(segment)) return null; + segments.push(segment); + } + if (segments.length === 0) return { kind: 'root', segments }; + // Continent slugs are never two letters long, unlike country codes. + const startsWithContinent = !COUNTRY_SEGMENT_PATTERN.test(segments[0]); + const fromCountry = startsWithContinent ? segments.slice(1) : segments; + if (fromCountry.length === 0) { + return { kind: 'continent', segments, continentSlug: segments[0] }; + } + if (!COUNTRY_SEGMENT_PATTERN.test(fromCountry[0])) return null; + if (fromCountry.length === 1) { + return { kind: 'country', segments, countryCode: fromCountry[0] }; + } + const placeIds = fromCountry.slice(1).map(placeIdOf); + const locationId = placeIds[placeIds.length - 1]; + if (placeIds.includes(null) || locationId == null) return null; + return { kind: 'place', segments, locationId }; +} + +const PAGE_PATTERN = /^[1-9]\d*$/; + +/** + * Parses the 1-based `?page=` search param. + * + * @returns 1 when absent, the page number when it is a positive integer + * written without leading zeros or signs, otherwise null. + */ +export function parsePageParam( + raw: string | string[] | undefined, +): number | null { + if (raw == undefined) return 1; + if (typeof raw !== 'string' || !PAGE_PATTERN.test(raw)) return null; + const page = Number(raw); + return Number.isSafeInteger(page) ? page : null; +} + +/** Number of pages needed for `total` items; never less than 1. */ +export function getPageCount( + total: number, + pageSize: number = LOCATION_FEEDS_PAGE_SIZE, +): number { + if (total <= 0) return 1; + return Math.ceil(total / pageSize); +} + +/** API offset of the first item of a 1-based page. */ +export function getPageOffset( + page: number, + pageSize: number = LOCATION_FEEDS_PAGE_SIZE, +): number { + return (page - 1) * pageSize; +} + +/** + * Locale-less path to a directory location, e.g. + * `/locations/north-america/ca/61549-quebec?page=2`. Page 1 has no query + * string so that it stays the canonical URL of the location. Pass the result + * to the next-intl `Link`, which adds the locale prefix. + */ +export function buildLocationHref( + segments: readonly string[], + page: number = 1, +): string { + const path = [LOCATIONS_BASE_PATH, ...segments.map(encodeURIComponent)].join( + '/', + ); + return page > 1 ? `${path}?page=${page}` : path; +} + +/** Display name of a location, falling back to its slug. */ +export function getLocationName(location: LocationResult): string { + return location.name ?? location.slug ?? ''; +} + +/** A continent, as the directory names and links it. */ +export interface ContinentInfo { + code: string; + slug: string; + name: string; +} + +/** The continents of the `/v1/locations` results, by code. */ +export function toContinentInfo( + continents: readonly LocationResult[], +): ContinentInfo[] { + return continents.flatMap((continent) => + continent.location_type === 'continent' && + continent.continent_code != undefined + ? [ + { + code: continent.continent_code, + slug: continent.slug, + name: getLocationName(continent), + }, + ] + : [], + ); +} + +function continentOf( + location: LocationResult, + continents: readonly ContinentInfo[], +): ContinentInfo | undefined { + return continents.find(({ code }) => code === location.continent_code); +} + +/** + * Canonical URL segments of a location: a continent's slug, then for any + * other location its continent's slug and its `path_slugs`, from the country + * down (`['north-america', 'ca', '61549-quebec']`). A country without + * continent starts at its code. + */ +export function getLocationSegments( + location: LocationResult, + continents: readonly ContinentInfo[], +): string[] { + if (location.location_type === 'continent') return [location.slug]; + const continent = continentOf(location, continents); + return continent !== undefined + ? [continent.slug, ...location.path_slugs] + : [...location.path_slugs]; +} + +/** Whether two segment lists are the same URL path. */ +export function isSameSegments( + a: readonly string[], + b: readonly string[], +): boolean { + return a.length === b.length && a.every((segment, i) => segment === b[i]); +} + +/** What the children of a directory page are, for their heading and search. */ +export type ChildrenKind = 'continents' | 'countries' | 'places'; + +/** Continents at the root, countries in a continent, places below. */ +export function getChildrenKind(location: LocationResult | null): ChildrenKind { + if (location === null) return 'continents'; + return location.location_type === 'continent' ? 'countries' : 'places'; +} + +export interface BreadcrumbStep { + label: string; + /** URL segments of this step, continent first. */ + segments: string[]; +} + +/** + * One step per level of the location, continent first: its continent, then + * one per `path_names` entry, each linked through the matching prefix of + * `path_slugs`. Empty at the root. + */ +export function buildBreadcrumbSteps( + location: LocationResult | null, + continents: readonly ContinentInfo[], +): BreadcrumbStep[] { + if (location === null) return []; + if (location.location_type === 'continent') { + return [{ label: getLocationName(location), segments: [location.slug] }]; + } + const continent = continentOf(location, continents); + const prefix = continent !== undefined ? [continent.slug] : []; + const steps: BreadcrumbStep[] = + continent !== undefined + ? [{ label: continent.name, segments: prefix }] + : []; + const names = location.path_names; + const slugs = location.path_slugs; + const depth = Math.min(names.length, slugs.length); + for (let index = 0; index < depth; index++) { + steps.push({ + label: names[index], + segments: [...prefix, ...slugs.slice(0, index + 1)], + }); + } + return steps; +} + +/** + * Human-readable place for titles, most specific first: `Montréal, Québec, + * Canada`. A continent is named on its own; empty at the root. + */ +export function buildPlaceName(location: LocationResult | null): string { + if (location === null) return ''; + if (location.location_type === 'continent') return getLocationName(location); + // `path_names` runs from the country down. + const names = location.path_names; + if (names.length === 0) return getLocationName(location); + return [...names].reverse().join(', '); +} + +export interface ResultsPage { + total?: number; + results?: T[]; +} + +export type PageFetcher = ( + offset: number, + limit: number, +) => Promise>; + +/** + * Completes the first page of an offset-paginated endpoint: it tells the + * total and the effective page size, the remaining pages are then fetched + * in parallel. + */ +export async function fetchRemainingPages( + first: ResultsPage, + fetchPage: PageFetcher, + pageSize: number = LOCATIONS_API_PAGE_SIZE, +): Promise { + const results = [...(first.results ?? [])]; + const total = first.total ?? results.length; + // A server that caps `limit` lower than asked still pages consistently. + const step = results.length; + if (step === 0 || step >= total) return results; + const offsets: number[] = []; + for (let offset = step; offset < total; offset += step) { + offsets.push(offset); + } + const rest = await Promise.all( + offsets.map(async (offset) => await fetchPage(offset, pageSize)), + ); + for (const page of rest) results.push(...(page.results ?? [])); + return results; +} + +/** Every result of an offset-paginated endpoint; see fetchRemainingPages. */ +export async function fetchAllPages( + fetchPage: PageFetcher, + pageSize: number = LOCATIONS_API_PAGE_SIZE, +): Promise { + const first = await fetchPage(0, pageSize); + return await fetchRemainingPages(first, fetchPage, pageSize); +} + +export const FEED_COUNT_DATA_TYPES = ['gtfs', 'gtfs_rt', 'gbfs'] as const; +export type FeedCountDataType = (typeof FEED_COUNT_DATA_TYPES)[number]; + +export interface FeedCountEntry { + dataType: FeedCountDataType; + count: number; +} + +/** GTFS, GTFS-RT and GBFS counts in display order; missing counts are 0. */ +export function getFeedCountEntries( + counts: LocationFeedCounts | undefined, +): FeedCountEntry[] { + return FEED_COUNT_DATA_TYPES.map((dataType) => ({ + dataType, + count: counts?.[dataType] ?? 0, + })); +} + +/** Total distinct feeds of a location, falling back to the sum by type. */ +export function getTotalFeedCount( + counts: LocationFeedCounts | undefined, +): number { + if (counts?.total != undefined) return counts.total; + return getFeedCountEntries(counts).reduce( + (sum, entry) => sum + entry.count, + 0, + ); +} + +/** Lowercased and without accents, so "Québec" matches "quebec". */ +export function normalizeLocationName(name: string): string { + return name + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') + .toLowerCase() + .trim(); +} + +/** Most feeds first; ties by name, ignoring accents and case. */ +export function sortByFeedCount< + T extends { name: string; counts: LocationFeedCounts | undefined }, +>(items: readonly T[]): T[] { + return [...items].sort( + (a, b) => + getTotalFeedCount(b.counts) - getTotalFeedCount(a.counts) || + normalizeLocationName(a.name).localeCompare( + normalizeLocationName(b.name), + ), + ); +} + +/** Items whose name contains the query, ignoring accents and case. */ +export function filterByName( + items: readonly T[], + query: string, +): T[] { + const normalizedQuery = normalizeLocationName(query); + if (normalizedQuery === '') return [...items]; + return items.filter((item) => + normalizeLocationName(item.name).includes(normalizedQuery), + ); +} + +/** Locale-aware integer formatting, e.g. 1234 -> "1,234" (en). */ +export function formatCount(value: number | undefined, locale: string): string { + return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format( + value ?? 0, + ); +} diff --git a/src/app/components/Footer.tsx b/src/app/components/Footer.tsx index 35606b1e..5846b895 100644 --- a/src/app/components/Footer.tsx +++ b/src/app/components/Footer.tsx @@ -73,6 +73,7 @@ const Footer: React.FC = () => { {t('columns.platform')} {t('links.feeds')} + {t('links.locations')} {t('links.addFeed')} = ({ const theme = useTheme(); return ( - {navigationItems.map((item) => ( - - - - ))} + + + ), + )} (null); + const [openedByKeyboard, setOpenedByKeyboard] = React.useState(false); + const closeTimer = React.useRef>(undefined); + + React.useEffect(() => { + return () => { + clearTimeout(closeTimer.current); + }; + }, []); + + const handleOpen = (e: React.MouseEvent): void => { + clearTimeout(closeTimer.current); + setOpenedByKeyboard(false); + setAnchorEl(e.currentTarget); + }; + + const handleClose = (): void => { + closeTimer.current = setTimeout(() => { + setAnchorEl(null); + }, 80); + }; + + const closeNow = (): void => { + clearTimeout(closeTimer.current); + setAnchorEl(null); + }; + + return ( + + + { + clearTimeout(closeTimer.current); + }, + onMouseLeave: handleClose, + sx: { pointerEvents: 'auto', minWidth: 200 }, + }, + }} + > + + {feedsMenuItems.map((item) => ( + + {t(item.titleKey)} + + ))} + + + + ); +} diff --git a/src/app/components/HeaderMobileDrawer.tsx b/src/app/components/HeaderMobileDrawer.tsx index 962f3dbe..f0e3984f 100644 --- a/src/app/components/HeaderMobileDrawer.tsx +++ b/src/app/components/HeaderMobileDrawer.tsx @@ -21,6 +21,7 @@ import { useColorScheme } from '@mui/material/styles'; import { useRouter } from 'next/navigation'; import { ACCOUNT_TARGET, + feedsMenuItems, gbfsMetricsNavItems, gtfsMetricsNavItems, SIGN_IN_TARGET, @@ -140,20 +141,56 @@ export default function DrawerContent({ - {navigationItems.map((item) => ( - - ))} + {navigationItems.map((item) => + item.target === 'feeds' ? ( + + } + aria-controls='feeds-content' + id='feeds-header' + data-cy='drawer-feeds' + > + + {item.title} + + + + {feedsMenuItems.map((subItem) => ( + + ))} + + + ) : ( + + ), + )} diff --git a/src/app/constants/Navigation.ts b/src/app/constants/Navigation.ts index 77d4454e..c3c65a48 100644 --- a/src/app/constants/Navigation.ts +++ b/src/app/constants/Navigation.ts @@ -15,6 +15,22 @@ export const MOBILITY_DATA_LINKS = { github: 'https://github.com/MobilityData/mobility-database-catalogs', }; +export const FEEDS_TARGET = '/feeds'; +export const LOCATIONS_TARGET = '/locations'; + +/** + * Sub-items of the "Feeds" header menu (desktop dropdown and mobile drawer). + * `titleKey` is a key of the `common` messages namespace. + */ +export const feedsMenuItems = [ + { titleKey: 'search', target: FEEDS_TARGET, dataCy: 'header-feeds-search' }, + { + titleKey: 'locations', + target: LOCATIONS_TARGET, + dataCy: 'header-feeds-locations', + }, +] as const; + export const WEB_VALIDATOR_LINK = 'https://gtfs-validator.mobilitydata.org'; export const GTFS_ORG_LINK = 'https://gtfs.org'; export const GBFS_LINK = 'https://github.com/MobilityData/gbfs'; diff --git a/src/app/screens/Feeds/SearchTable.tsx b/src/app/screens/Feeds/SearchTable.tsx index 2e990d4b..130b9fad 100644 --- a/src/app/screens/Feeds/SearchTable.tsx +++ b/src/app/screens/Feeds/SearchTable.tsx @@ -39,35 +39,37 @@ const HeaderTableCell = styled(TableCell)(() => ({ border: 'none', })); +const DATA_TYPE_LABEL_KEYS = { + gtfs: 'gtfsSchedule', + gtfs_rt: 'gtfsRealtime', + gbfs: 'gbfs', +} as const; + +function DataTypeElement({ + dataType, +}: { + dataType: 'gtfs' | 'gtfs_rt' | 'gbfs'; +}): React.ReactElement { + const tCommon = useTranslations('common'); + return ( + + {tCommon(DATA_TYPE_LABEL_KEYS[dataType])} + + ); +} + +// The translation hook lives in DataTypeElement, not here: this is called once +// per row, and a hook called in a loop breaks when the row count changes +// between renders of the same table (e.g. paging to a partial last page). export const getDataTypeElement = ( dataType: 'gtfs' | 'gtfs_rt' | 'gbfs', -): React.ReactElement => { - const tCommon = useTranslations('common'); - const DataTypeHolder = ({ - children, - }: { - children: React.ReactNode; - }): React.ReactElement => { - return ( - - {children} - - ); - }; - if (dataType === 'gtfs') { - return {tCommon('gtfsSchedule')}; - } else if (dataType === 'gtfs_rt') { - return {tCommon('gtfsRealtime')}; - } else { - return {tCommon('gbfs')}; - } -}; +): React.ReactElement => ; export default function SearchTable({ feedsData, diff --git a/src/app/services/feeds/index.ts b/src/app/services/feeds/index.ts index 50b726c2..63aafe11 100644 --- a/src/app/services/feeds/index.ts +++ b/src/app/services/feeds/index.ts @@ -17,6 +17,21 @@ const client = createClient({ }, }); +/** + * Error thrown for any API response with a status >= 400. Extends `Error` + * with the same message as before, adding the HTTP status so callers can + * tell a 404 apart from a server failure. + */ +export class ApiError extends Error { + readonly status: number; + + constructor(message: string, status: number) { + super(message); + this.name = 'ApiError'; + this.status = status; + } +} + const throwOnError: Middleware = { async onResponse(res) { if (res.status >= 400) { @@ -26,7 +41,7 @@ const throwOnError: Middleware = { } const errorMessage = typeof body === 'string' ? body : JSON.stringify(body); - throw new Error(errorMessage); + throw new ApiError(errorMessage, res.status); } return undefined; }, @@ -333,14 +348,18 @@ export const getMetadata = async (): Promise< }); }; +export type SearchFeedsResponse = + paths['/v1/search']['get']['responses'][200]['content']['application/json']; + +/** + * Also lists the feeds of a location directory page, with `location_id` (or + * `continent`) and `sort: 'location'`. + */ export const searchFeeds = async ( params: AllFeedsParams, accessToken: string, userContextJwt?: string, -): Promise< - | paths['/v1/search']['get']['responses'][200]['content']['application/json'] - | undefined -> => { +): Promise => { const authMiddleware = generateAuthMiddlewareWithToken( accessToken, userContextJwt, @@ -351,6 +370,38 @@ export const searchFeeds = async ( }); }; +export type LocationsParams = NonNullable< + paths['/v1/locations']['get']['parameters']['query'] +>; + +export type LocationsResponse = + paths['/v1/locations']['get']['responses'][200]['content']['application/json']; + +/** + * Searches and filters locations (continents, countries, subdivisions, + * municipalities): one location with `location_id`, its children with + * `parent_location_id`, a continent's countries with `location_type` and + * `continent`. Returns at most 100 results per call: page with `limit` and + * `offset`. Throws an `ApiError` with status 400 on an unsupported `sort` or + * `include`. + */ +export const getLocations = async ( + params: LocationsParams, + accessToken: string, + userContextJwt?: string, +): Promise => { + const authMiddleware = generateAuthMiddlewareWithToken( + accessToken, + userContextJwt, + ); + return await withAuthMiddleware(authMiddleware, async () => { + const response = await client.GET('/v1/locations', { + params: { query: params }, + }); + return response.data; + }); +}; + export const getLicense = async ( id: string, accessToken: string, diff --git a/src/app/services/feeds/types.ts b/src/app/services/feeds/types.ts index c3be5015..188c8fee 100644 --- a/src/app/services/feeds/types.ts +++ b/src/app/services/feeds/types.ts @@ -331,6 +331,16 @@ export interface paths { * Query: New York Transit *
    * Search Executed: 'new' & york & 'transit' + *

    + * Location filters: + *
    + * - `location_id` (a `location_id` of `/v1/locations`) or `continent` restricts the results to feeds with stops + * in that location or continent, sub-areas included. Feeds are matched through their reverse-geolocated stops, + * so a feed that was never reverse-geolocated matches no location. Unknown values return no feed. Pass one of + * the two, not both. + * - To list the same feeds as a location's `feed_counts`, also pass `status=active,inactive,development,future`. + * - `sort=location` orders the results by the share of each feed's stops inside the requested location or + * continent instead of by creation date. *
    */ get: operations['searchFeeds']; @@ -349,7 +359,7 @@ export interface paths { path?: never; cookie?: never; }; - /** @description Search locations (countries, subdivisions and municipalities). Results can be filtered by a free-text query and narrowed to a specific country, subdivision or location type. Matches are ordered from the broadest area to the most specific, and by relevance within each level. */ + /** @description Search and filter locations: continents, countries, subdivisions and municipalities. Results can be filtered by a free-text query, a location id, a parent location, a continent, a country, a subdivision or a location type. Matches are ordered from the broadest area to the most specific, and by relevance within each level, unless `sort=feed_count` is given.
    Navigate the hierarchy with filters: `location_type=continent` lists the continents, `location_type=country&continent=` the countries of a continent, `parent_location_id=` the direct children of a location and `location_id=` one location. To list a location's feeds, call `/v1/search` with its `location_id` (or, for a continent, `continent`), `status=active,inactive,development,future` and `sort=location`.
    Countries, subdivisions and municipalities are OpenStreetMap administrative areas: their `location_id` is the OSM id. Continents come from a fixed country-to-continent classification: they have no `location_id` and are identified by their `continent_code`. Every location's `continent_code` is the continent of its country.
    Feed counts (`include=feed_counts`, `has_feeds`, `sort=feed_count`) count distinct feeds with a status of `active`, `inactive`, `development` or `future` that have reverse-geolocated stops in the location, sub-areas included. A feed that was never reverse-geolocated is counted in no location, so a count is not the number of all the feeds serving a place. A continent counts each feed once, even when it has stops in several of its countries. Work-in-progress feeds are counted only for callers allowed to see them, as in `/v1/search`. Counts are precomputed and refreshed after feeds are processed, so they can lag behind a feed's latest changes. */ get: operations['getLocations']; put?: never; post?: never; @@ -1308,20 +1318,34 @@ export interface components { */ municipality?: string; }; + /** @description Number of distinct feeds per data type with stops in a location, sub-areas included. */ + LocationFeedCounts: { + /** @example 42 */ + gtfs?: number; + /** @example 18 */ + gtfs_rt?: number; + /** @example 7 */ + gbfs?: number; + /** + * @description Number of distinct feeds of any data type. + * @example 67 + */ + total?: number; + }; LocationSearchResponse: { /** @description The total number of matching locations regardless of limit and offset. */ - total?: number; + total: number; /** @description The page of matching locations, ordered from the broadest area to the most specific and by relevance within each level. */ - results?: components['schemas']['LocationSearchResult'][]; + results: components['schemas']['LocationSearchResult'][]; }; LocationSearchResult: { /** - * @description Stable location identifier. + * @description Stable location identifier: the OpenStreetMap id of the area. Null for a continent, identified by its `continent_code`. * @example 175905 */ - location_id?: number; + location_id: number | null; /** - * @description Stable identifier of the nearest containing location. + * @description Identifier of the nearest containing location. Null for continents and countries: a country's continent is its `continent_code`. * @example 161950 */ parent_location_id?: number | null; @@ -1336,11 +1360,32 @@ export interface components { */ alt_name?: string | null; /** - * @description The type of location: `country` (has an ISO 3166-1 code), `subdivision` (has an ISO 3166-2 code) or `municipality` (a locality below the subdivision level). + * @description The type of location: `continent`, `country` (has an ISO 3166-1 code), `subdivision` (has an ISO 3166-2 code) or `municipality` (a locality below the subdivision level). * @example municipality * @enum {string} */ - location_type?: 'country' | 'subdivision' | 'municipality'; + location_type: 'continent' | 'country' | 'subdivision' | 'municipality'; + /** + * @description Code of the continent of this location's country, or of the continent itself (`AF`, `AN`, `AS`, `EU`, `NA`, `OC`, `SA`). Null when the country has no continent in the classification. + * @example NA + */ + continent_code?: string | null; + /** + * @description URL segment of the location. A continent's slug is fixed (`north-america`) and a country's is its ISO 3166-1 code, lowercased (`ca`). Any other location's slug is its `location_id` followed by its name, lowercased, without accents, with every run of non-alphanumeric characters replaced by a hyphen (`175905-montreal`); a name without any ASCII letter or digit leaves the `location_id` alone (`1234`). The `location_id` identifies the location: the name part follows OpenStreetMap and can change. + * @example 175905-montreal + */ + slug: string; + /** + * @description The slugs of the locations in `path_names`, in the same order, from the country down. Prefix them with the continent's slug to build a directory URL. + * @example [ + * "ca", + * "61549-quebec", + * "8508277-montreal-region", + * "175905-montreal" + * ] + */ + path_slugs: string[]; + feed_counts?: components['schemas']['LocationFeedCounts']; /** * @description The name of the country that contains this location. * @example Canada @@ -1362,7 +1407,7 @@ export interface components { */ subdivision_code?: string | null; /** - * @description The ordered list of location names from the broadest containing area down to this location. + * @description The ordered list of location names from the country down to this location. A continent's is its own name. * @example [ * "Canada", * "Quebec", @@ -1370,9 +1415,9 @@ export interface components { * "Montréal" * ] */ - path_names?: string[]; + path_names: string[]; /** - * @description A human-readable representation of the full location hierarchy, joined from the broadest area to this location. + * @description A human-readable representation of the location hierarchy, joined from the country (or, for a continent, the continent itself) down to this location. * @example Canada, Quebec, Montréal (region), Montréal */ display_name?: string | null; @@ -1793,6 +1838,10 @@ export interface components { subdivision_name: string; /** @description List only feeds with the specified value. Can be a partial match. Case insensitive. */ municipality: string; + /** @description Filter feeds added to the database at or after this timestamp. Date should be in ISO 8601 date-time format. */ + created_after: string; + /** @description Filter feeds added to the database at or before this timestamp. Date should be in ISO 8601 date-time format. */ + created_before: string; /** @description Filter feed datasets with downloaded date greater or equal to given date. Date should be in ISO 8601 date-time format. */ downloaded_after: string; /** @description Filter feed datasets with downloaded date less or equal to given date. Date should be in ISO 8601 date-time format. */ @@ -1822,6 +1871,22 @@ export interface components { is_official_query_param: boolean; /** @description If true, only return feeds that currently hold the Seal of Reliability; if false, only feeds without it. Viewing a feed's seal is public, but filtering the catalogue by it is granted per user and requires the `isSealFilterEnabled` feature flag - other callers receive a 403. To request access or learn more, contact us at api@mobilitydata.org. */ has_seal_query_param: boolean; + /** @description Limit results to locations in this continent, the continent included, given as its slug (`africa`, `antarctica`, `asia`, `europe`, `north-america`, `oceania`, `south-america`) or code (`AF`, `AN`, `AS`, `EU`, `NA`, `OC`, `SA`). Case-insensitive. */ + location_continent: string; + /** @description A `location_id` from `/v1/locations`: only feeds with reverse-geolocated stops in that location, sub-areas included. */ + location_id_query_param: number; + /** @description A continent, given as its slug (`africa`, `antarctica`, `asia`, `europe`, `north-america`, `oceania`, `south-america`) or code (`AF`, `AN`, `AS`, `EU`, `NA`, `OC`, `SA`): only feeds with reverse-geolocated stops in one of its countries. Case-insensitive. */ + search_continent: string; + /** @description Limit results to the location with this `location_id`. */ + location_id_filter: number; + /** @description Limit results to the direct children of the location with this `location_id`: the subdivisions of a country, the areas one level down from a subdivision, and so on. Depth varies by country, so the children of a subdivision can be regions or municipalities. The countries of a continent are listed with `location_type=country` and `continent`. */ + parent_location_id_query_param: number; + /** @description When true, only return locations with at least one feed (see the feed count rules of `/v1/locations`). */ + has_feeds_query_param: boolean; + /** @description Optional data to add to each location: `feed_counts`, the location's feed counts per data type. */ + locations_include: 'feed_counts'[]; + /** @description Sort order of the results. `admin_level` (default): from the broadest area to the most specific, then by relevance to `search_query` when one is given, then by display name. `feed_count`: most feeds first, then by display name. */ + locations_sort: 'admin_level' | 'feed_count'; /** @description The number of items to be returned. */ limit_query_param_locations_endpoint: number; /** @description The number of items to be returned. */ @@ -1842,6 +1907,8 @@ export interface components { offset: number; /** @description General search query to match against transit provider, location, and feed name. */ search_text_query_param: string; + /** @description Sort order of the results. `created_at` (default): newest feeds first, then by relevance to `search_query` when one is given. `location`: by relevance to the requested location, which requires `location_id` or `continent`. Feeds with the largest share of their reverse-geolocated stops inside the location come first (on Montréal, a city bus feed with all its stops in Montréal ranks above a regional train with a fifth of them there); ties are broken by provider, feed name and feed id. */ + search_sort: 'created_at' | 'location'; /** @description Comma separated list of GBFS versions to filter by. */ version_query_param: string; /** @description Comma separated list of data types to filter by. Valid values are gtfs, gtfs_rt and gbfs. */ @@ -1911,6 +1978,10 @@ export interface operations { provider?: components['parameters']['provider']; /** @description List only feeds with the specified value. Can be a partial match. Case insensitive. */ producer_url?: components['parameters']['producer_url']; + /** @description Filter feeds added to the database at or after this timestamp. Date should be in ISO 8601 date-time format. */ + created_after?: components['parameters']['created_after']; + /** @description Filter feeds added to the database at or before this timestamp. Date should be in ISO 8601 date-time format. */ + created_before?: components['parameters']['created_before']; /** @description If true, only return official feeds. */ is_official?: components['parameters']['is_official_query_param']; }; @@ -1965,6 +2036,10 @@ export interface operations { provider?: components['parameters']['provider']; /** @description List only feeds with the specified value. Can be a partial match. Case insensitive. */ producer_url?: components['parameters']['producer_url']; + /** @description Filter feeds added to the database at or after this timestamp. Date should be in ISO 8601 date-time format. */ + created_after?: components['parameters']['created_after']; + /** @description Filter feeds added to the database at or before this timestamp. Date should be in ISO 8601 date-time format. */ + created_before?: components['parameters']['created_before']; /** @description Filter feeds by their exact country code. */ country_code?: components['parameters']['country_code']; /** @description List only feeds with the specified value. Can be a partial match. Case insensitive. */ @@ -2018,6 +2093,10 @@ export interface operations { provider?: components['parameters']['provider']; /** @description List only feeds with the specified value. Can be a partial match. Case insensitive. */ producer_url?: components['parameters']['producer_url']; + /** @description Filter feeds added to the database at or after this timestamp. Date should be in ISO 8601 date-time format. */ + created_after?: components['parameters']['created_after']; + /** @description Filter feeds added to the database at or before this timestamp. Date should be in ISO 8601 date-time format. */ + created_before?: components['parameters']['created_before']; /** @description Filter feeds by their entity type. Expects a comma separated list of all types to fetch. */ entity_types?: components['parameters']['entity_types']; /** @description Filter feeds by their exact country code. */ @@ -2057,6 +2136,10 @@ export interface operations { provider?: components['parameters']['provider']; /** @description List only feeds with the specified value. Can be a partial match. Case insensitive. */ producer_url?: components['parameters']['producer_url']; + /** @description Filter feeds added to the database at or after this timestamp. Date should be in ISO 8601 date-time format. */ + created_after?: components['parameters']['created_after']; + /** @description Filter feeds added to the database at or before this timestamp. Date should be in ISO 8601 date-time format. */ + created_before?: components['parameters']['created_before']; /** @description Filter feeds by their exact country code. */ country_code?: components['parameters']['country_code']; /** @description List only feeds with the specified value. Can be a partial match. Case insensitive. */ @@ -2492,6 +2575,12 @@ export interface operations { license_is_spdx?: components['parameters']['license_is_spdx']; /** @description Comma separated list of tags to filter feeds by their license tags. */ license_tags?: components['parameters']['license_tags']; + /** @description A `location_id` from `/v1/locations`: only feeds with reverse-geolocated stops in that location, sub-areas included. */ + location_id?: components['parameters']['location_id_query_param']; + /** @description A continent, given as its slug (`africa`, `antarctica`, `asia`, `europe`, `north-america`, `oceania`, `south-america`) or code (`AF`, `AN`, `AS`, `EU`, `NA`, `OC`, `SA`): only feeds with reverse-geolocated stops in one of its countries. Case-insensitive. */ + continent?: components['parameters']['search_continent']; + /** @description Sort order of the results. `created_at` (default): newest feeds first, then by relevance to `search_query` when one is given. `location`: by relevance to the requested location, which requires `location_id` or `continent`. Feeds with the largest share of their reverse-geolocated stops inside the location come first (on Montréal, a city bus feed with all its stops in Montréal ranks above a regional train with a fifth of them there); ties are broken by provider, feed name and feed id. */ + sort?: components['parameters']['search_sort']; }; header?: never; path?: never; @@ -2512,6 +2601,13 @@ export interface operations { }; }; }; + /** @description `sort=location` was requested without `location_id` or `continent`, both `location_id` and `continent` were given, or `sort` has an unsupported value. */ + 400: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; /** @description Filtering by Seal of Reliability status is not available to this caller. */ 403: { headers: { @@ -2530,17 +2626,34 @@ export interface operations { offset?: components['parameters']['offset']; /** @description Free-text search matched against the location name, alternate name and its full hierarchy (e.g. "Canada, Quebec, Montréal"). Matching is accent-insensitive and supports typeahead-style prefix matching, so "mon" matches "Montréal". When several words are provided, all of them must match. */ search_query?: string; - /** @description Limit results to locations contained within this country, given as its ISO 3166-1 alpha-2 code. Case-insensitive. */ + /** @description Limit results to the location with this `location_id`. */ + location_id?: components['parameters']['location_id_filter']; + /** @description Limit results to the direct children of the location with this `location_id`: the subdivisions of a country, the areas one level down from a subdivision, and so on. Depth varies by country, so the children of a subdivision can be regions or municipalities. The countries of a continent are listed with `location_type=country` and `continent`. */ + parent_location_id?: components['parameters']['parent_location_id_query_param']; + /** @description Limit results to locations in this continent, the continent included, given as its slug (`africa`, `antarctica`, `asia`, `europe`, `north-america`, `oceania`, `south-america`) or code (`AF`, `AN`, `AS`, `EU`, `NA`, `OC`, `SA`). Case-insensitive. */ + continent?: components['parameters']['location_continent']; + /** @description Limit results to locations contained within this country, the country included, given as its ISO 3166-1 alpha-2 code. Case-insensitive. */ country_code?: string; - /** @description Limit results to locations contained within this subdivision, given as its ISO 3166-2 code. Case-insensitive. */ + /** @description Limit results to locations contained within this subdivision, the subdivision included, given as its ISO 3166-2 code. Case-insensitive. */ subdivision_code?: string; /** * @description Filter by the type of location: + * * `continent` - a continent, from a fixed country-to-continent classification. * * `country` - a sovereign country, identified by an ISO 3166-1 code. * * `subdivision` - a first-level subdivision (e.g. state or province), identified by an ISO 3166-2 code. * * `municipality` - a locality below the subdivision level (e.g. a city or town). */ - location_type?: 'country' | 'subdivision' | 'municipality'; + location_type?: + | 'continent' + | 'country' + | 'subdivision' + | 'municipality'; + /** @description When true, only return locations with at least one feed (see the feed count rules of `/v1/locations`). */ + has_feeds?: components['parameters']['has_feeds_query_param']; + /** @description Optional data to add to each location: `feed_counts`, the location's feed counts per data type. */ + include?: components['parameters']['locations_include']; + /** @description Sort order of the results. `admin_level` (default): from the broadest area to the most specific, then by relevance to `search_query` when one is given, then by display name. `feed_count`: most feeds first, then by display name. */ + sort?: components['parameters']['locations_sort']; }; header?: never; path?: never; @@ -2557,6 +2670,13 @@ export interface operations { 'application/json': components['schemas']['LocationSearchResponse']; }; }; + /** @description `sort` or `include` has an unsupported value. */ + 400: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; }; }; getLicenses: { diff --git a/src/app/utils/proxy-helpers.spec.ts b/src/app/utils/proxy-helpers.spec.ts index 72defd43..1d346ac6 100644 --- a/src/app/utils/proxy-helpers.spec.ts +++ b/src/app/utils/proxy-helpers.spec.ts @@ -1,4 +1,5 @@ import { + getLowercaseLocationPathname, isFeedDetailPage, rewriteFeedRequest, hasLocaleInPathname, @@ -293,3 +294,40 @@ describe('proxy-helpers', () => { }); }); }); + +describe('getLowercaseLocationPathname', () => { + it('lowercases location paths with uppercase letters', () => { + expect( + getLowercaseLocationPathname('/locations/north-america/canada/Ontario'), + ).toBe('/locations/north-america/canada/ontario'); + expect(getLowercaseLocationPathname('/fr/locations/North-America')).toBe( + '/fr/locations/north-america', + ); + expect(getLowercaseLocationPathname('/Locations/Europe')).toBe( + '/locations/europe', + ); + expect(getLowercaseLocationPathname('/FR/locations/europe')).toBe( + '/fr/locations/europe', + ); + }); + + it('keeps encoded characters encoded', () => { + expect(getLowercaseLocationPathname('/locations/%C3%89TATS')).toBe( + '/locations/%C3%A9tats', + ); + }); + + it('ignores lowercase paths and other routes', () => { + expect( + getLowercaseLocationPathname('/locations/north-america/canada/ontario'), + ).toBeNull(); + expect(getLowercaseLocationPathname('/locations')).toBeNull(); + expect(getLowercaseLocationPathname('/fr/locations')).toBeNull(); + expect(getLowercaseLocationPathname('/feeds/gtfs/MDB-1')).toBeNull(); + expect(getLowercaseLocationPathname('/locationsX/Foo')).toBeNull(); + }); + + it('ignores malformed encodings', () => { + expect(getLowercaseLocationPathname('/locations/%E0%A4%A')).toBeNull(); + }); +}); diff --git a/src/app/utils/proxy-helpers.ts b/src/app/utils/proxy-helpers.ts index afbfcd98..66e44d65 100644 --- a/src/app/utils/proxy-helpers.ts +++ b/src/app/utils/proxy-helpers.ts @@ -47,6 +47,41 @@ export function isFeedDetailPage(pathname: string): FeedDetailPageInfo { }; } +// ============================================================================ +// Location Directory +// ============================================================================ + +const LOCATION_PATH_REGEX = /^(\/(?:en|fr))?(\/locations(?:\/.*)?)$/i; + +/** + * The lowercase form of a location directory path, or null when the path is + * not under /locations or is already lowercase. + * + * Location slugs are lowercase, so `/locations/north-america/canada/Ontario` + * would otherwise render the not-found page; it is redirected to + * `/locations/north-america/canada/ontario` instead, keeping one URL per place. + */ +export function getLowercaseLocationPathname(pathname: string): string | null { + const match = pathname.match(LOCATION_PATH_REGEX); + if (match == null) return null; + const localePrefix = (match[1] ?? '').toLowerCase(); + let decodedPath: string; + try { + decodedPath = decodeURIComponent(match[2]); + } catch { + return null; + } + const lowercasePath = decodedPath.toLowerCase(); + if (lowercasePath === decodedPath && localePrefix === (match[1] ?? '')) { + return null; + } + const encodedPath = lowercasePath + .split('/') + .map((segment) => encodeURIComponent(segment)) + .join('/'); + return `${localePrefix}${encodedPath}`; +} + // ============================================================================ // Auth State Detection // ============================================================================ diff --git a/src/mocks/handlers.ts b/src/mocks/handlers.ts index 0f826fe3..f4ddb0eb 100644 --- a/src/mocks/handlers.ts +++ b/src/mocks/handlers.ts @@ -7,10 +7,28 @@ import datasetsFeedJson from '../../cypress/fixtures/feed_datasets_test-516.json import feed2947 from '../../cypress/fixtures/feed_mdb-2947.json'; import gtfsFeed2947 from '../../cypress/fixtures/gtfs_feed_mdb-2947.json'; import datasets2947 from '../../cypress/fixtures/feed_datasets_mdb-2947.json'; +import { + getMockLocationFeeds, + getMockLocations, + isLocationSearch, +} from './locationDirectory'; export const handlers = [ - // Mock search endpoint: return a list including test-516 and mdb-2947 - http.get(`*/v1/search`, () => { + // Locations: search and filters, with feed counts + http.get(`*/v1/locations`, ({ request }) => { + const params = new URL(request.url).searchParams; + const { status, body } = getMockLocations(params); + return HttpResponse.json(body, { status }); + }), + // Mock search endpoint. With `location_id` or `continent` (location + // directory pages): the feeds located there, paginated and sorted. + // Otherwise: a list including test-516 and mdb-2947. + http.get(`*/v1/search`, ({ request }) => { + const params = new URL(request.url).searchParams; + if (isLocationSearch(params)) { + const { status, body } = getMockLocationFeeds(params); + return HttpResponse.json(body, { status }); + } return HttpResponse.json({ total: 2, results: [ diff --git a/src/mocks/locationDirectory.spec.ts b/src/mocks/locationDirectory.spec.ts new file mode 100644 index 00000000..efb2cd71 --- /dev/null +++ b/src/mocks/locationDirectory.spec.ts @@ -0,0 +1,180 @@ +import { + getMockLocationFeeds, + getMockLocations, + isLocationSearch, + slugify, +} from './locationDirectory'; + +type Locations = ReturnType; +type Feeds = ReturnType; + +function ok(result: { status: number; body: unknown }, label: string): T { + if (result.status !== 200) throw new Error(`expected 200 for ${label}`); + return result.body as T; +} + +type LocationsBody = Extract['body']; +type FeedsBody = Extract['body']; + +function locations(query: string): LocationsBody { + return ok(getMockLocations(new URLSearchParams(query)), query); +} + +function location(id: number, query: string = '') { + const { results } = locations(`location_id=${id}&${query}`); + expect(results).toHaveLength(1); + return results[0]; +} + +function feeds(query: string): FeedsBody { + return ok(getMockLocationFeeds(new URLSearchParams(query)), query); +} + +describe('location directory mocks', () => { + it('slugifies names like the API', () => { + expect(slugify('Québec')).toBe('quebec'); + expect(slugify('Saint-Jean-sur-Richelieu')).toBe( + 'saint-jean-sur-richelieu', + ); + expect(slugify('Île-de-France')).toBe('ile-de-france'); + expect(slugify('Montréal (région)')).toBe('montreal-region'); + }); + + it('lists the continents, without location id, most feeds first', () => { + const all = locations('location_type=continent&include=feed_counts'); + expect(all.total).toBe(7); + const antarctica = all.results.find((row) => row.slug === 'antarctica'); + expect(antarctica).toMatchObject({ + location_id: null, + parent_location_id: null, + continent_code: 'AN', + path_slugs: ['antarctica'], + path_names: ['Antarctica'], + feed_counts: { total: 0 }, + }); + + const { results } = locations( + 'location_type=continent&has_feeds=true&include=feed_counts&sort=feed_count', + ); + expect(results.map((row) => row.slug)).toEqual([ + 'north-america', + 'europe', + 'oceania', + 'africa', + ]); + }); + + it('starts every path at the country, with id-name slugs below it', () => { + expect(location(110)).toMatchObject({ + parent_location_id: 100, + continent_code: 'NA', + slug: '110-quebec', + path_slugs: ['ca', '110-quebec'], + path_names: ['Canada', 'Québec'], + display_name: 'Canada, Québec', + }); + // A country has no parent: its continent is its continent_code. + expect(location(100)).toMatchObject({ + parent_location_id: null, + continent_code: 'NA', + slug: 'ca', + path_slugs: ['ca'], + }); + expect(location(700)).toMatchObject({ + continent_code: null, + path_slugs: ['cp'], + }); + }); + + it('lists children with parent_location_id and rolls counts up', () => { + expect(location(111, 'include=feed_counts').feed_counts?.total).toBe(22); + + const quebec = location(110, 'include=feed_counts'); + expect(quebec.feed_counts?.total).toBeGreaterThan(22); + const children = locations( + 'parent_location_id=110&include=feed_counts&has_feeds=true&sort=feed_count&limit=2', + ); + expect(children.total).toBe(4); + // Laval and Québec tie on 2 feeds: by display name. + expect(children.results.map((row) => row.slug)).toEqual([ + '111-montreal', + '112-laval', + ]); + expect(children.results[0].feed_counts?.total).toBe(22); + }); + + it('matches nothing for unknown ids', () => { + expect(locations('location_id=42').total).toBe(0); + expect(locations('parent_location_id=42').total).toBe(0); + expect(locations('location_id=abc').total).toBe(0); + }); + + it('has a variable depth, and ids tell same-named siblings apart', () => { + expect(location(212).path_names).toHaveLength(4); + expect(location(214).path_slugs).toEqual([ + 'us', + '210-california', + '214-san-francisco', + ]); + expect( + locations('parent_location_id=230&has_feeds=true').results.map( + (row) => row.slug, + ), + ).toEqual(['123456-washington-township', '123457-washington-township']); + }); + + it('pages results and rejects unsupported parameters', () => { + const all = locations('parent_location_id=110'); + const second = locations('parent_location_id=110&limit=2&offset=2'); + expect(second.total).toBe(all.total); + expect(second.results).toEqual(all.results.slice(2, 4)); + expect(all.results[0].feed_counts).toBeUndefined(); + expect(getMockLocations(new URLSearchParams('sort=name')).status).toBe(400); + expect(getMockLocations(new URLSearchParams('limit=101')).status).toBe(400); + expect( + getMockLocations(new URLSearchParams('include=children')).status, + ).toBe(400); + }); + + it('filters by continent, slug or code', () => { + const bySlug = locations('continent=europe&location_type=country'); + const byCode = locations('continent=EU&location_type=country'); + expect(bySlug.results.map((row) => row.slug)).toEqual(['fr', 'de']); + expect(byCode).toEqual(bySlug); + }); + + it('routes location searches only', () => { + expect(isLocationSearch(new URLSearchParams('location_id=1'))).toBe(true); + expect(isLocationSearch(new URLSearchParams('continent=europe'))).toBe( + true, + ); + expect(isLocationSearch(new URLSearchParams('status=active'))).toBe(false); + }); + + it('paginates the feeds of a location, most relevant first', () => { + const query = 'location_id=111&sort=location&limit=20'; + const first = feeds(query); + const second = feeds(`${query}&offset=20`); + expect(first.total).toBe(22); + expect(first.results).toHaveLength(20); + expect(second.results).toHaveLength(2); + // The commuter train also serves Laval and Longueuil: least relevant. + expect(second.results[1].feed_name).toBe('Commuter trains'); + }); + + it('lists the feeds of a continent by slug or code', () => { + expect(feeds('continent=europe&sort=location').total).toBe(3); + expect(feeds('continent=EU&sort=location').total).toBe(3); + expect(feeds('continent=asia').total).toBe(0); + expect(feeds('continent=atlantis').total).toBe(0); + // Continents have no location id. + expect(feeds('location_id=-4').total).toBe(0); + }); + + it('rejects sort=location alone and both location parameters', () => { + const status = (query: string): number => + getMockLocationFeeds(new URLSearchParams(query)).status; + expect(status('sort=location')).toBe(400); + expect(status('location_id=110&continent=europe')).toBe(400); + }); +}); diff --git a/src/mocks/locationDirectory.ts b/src/mocks/locationDirectory.ts new file mode 100644 index 00000000..cbe3270e --- /dev/null +++ b/src/mocks/locationDirectory.ts @@ -0,0 +1,569 @@ +/** + * Mock data and logic for the location directory endpoints: + * GET /v1/locations (search and filters: `location_id`, + * `parent_location_id`, `continent`, `location_type`, ...) + * GET /v1/search with `location_id` / `continent` (a location's feeds) + * + * Locations form a tree of variable depth under the continents (Los Angeles + * sits under a county, San Francisco directly under California). Here the + * continents have negative ids to hold the tree; like the API, results give + * them no `location_id` and give countries no parent. Feed counts, + * `has_feeds` and the `sort=location` relevance are derived from MOCK_FEEDS' + * stop locations, so the mock behaves like the API: a feed counts once per + * location, sub-areas included. + * Location ids, feed ids, URLs and names are fictional mock data. + */ +import type { components } from '../app/services/feeds/types'; + +type Feed = components['schemas']['SearchFeedItemResult']; +type LocationResult = components['schemas']['LocationSearchResult']; +type FeedCounts = components['schemas']['LocationFeedCounts']; +type LocationsResponse = components['schemas']['LocationSearchResponse']; +interface FeedsResponse { + total: number; + results: Feed[]; +} + +type PlaceType = 'continent' | 'country' | 'subdivision' | 'municipality'; + +interface Place { + id: number; + parent: number | null; + type: PlaceType; + name: string; + /** + * Continent code, ISO 3166-1 (countries) or ISO 3166-2 (subdivisions) + * code. + */ + code?: string; +} + +/** Mock-only ids; Asia and South America have no feeds here. */ +const continent = (id: number, name: string, code: string): Place => ({ + id, + parent: null, + type: 'continent', + name, + code, +}); +const AFRICA = -1; +const EUROPE = -4; +const NORTH_AMERICA = -5; +const OCEANIA = -6; + +const country = ( + id: number, + name: string, + code: string, + continentId: number | null, +): Place => ({ id, parent: continentId, type: 'country', name, code }); +const subdivision = ( + id: number, + parent: number, + name: string, + code: string, +): Place => ({ id, parent, type: 'subdivision', name, code }); +const municipality = (id: number, parent: number, name: string): Place => ({ + id, + parent, + type: 'municipality', + name, +}); + +export const MOCK_PLACES: Place[] = [ + continent(AFRICA, 'Africa', 'AF'), + continent(-2, 'Antarctica', 'AN'), + continent(-3, 'Asia', 'AS'), + continent(EUROPE, 'Europe', 'EU'), + continent(NORTH_AMERICA, 'North America', 'NA'), + continent(OCEANIA, 'Oceania', 'OC'), + continent(-7, 'South America', 'SA'), + country(100, 'Canada', 'CA', NORTH_AMERICA), + subdivision(110, 100, 'Québec', 'CA-QC'), + municipality(111, 110, 'Montréal'), + municipality(112, 110, 'Laval'), + municipality(113, 110, 'Longueuil'), + municipality(114, 110, 'Québec'), + subdivision(120, 100, 'Ontario', 'CA-ON'), + municipality(121, 120, 'Toronto'), + subdivision(130, 100, 'British Columbia', 'CA-BC'), + municipality(131, 130, 'Vancouver'), + country(200, 'United States', 'US', NORTH_AMERICA), + subdivision(210, 200, 'California', 'US-CA'), + // Extra intermediate level: county > city. + municipality(211, 210, 'Los Angeles County'), + municipality(212, 211, 'Los Angeles'), + municipality(213, 211, 'Pasadena'), + municipality(214, 210, 'San Francisco'), + subdivision(220, 200, 'New York', 'US-NY'), + municipality(221, 220, 'New York'), + subdivision(230, 200, 'Ohio', 'US-OH'), + // Siblings sharing a name: their ids tell their slugs apart. + municipality(123456, 230, 'Washington Township'), + municipality(123457, 230, 'Washington Township'), + country(300, 'France', 'FR', EUROPE), + subdivision(310, 300, 'Île-de-France', 'FR-IDF'), + municipality(311, 310, 'Paris'), + country(400, 'Germany', 'DE', EUROPE), + subdivision(410, 400, 'Berlin', 'DE-BE'), + municipality(411, 410, 'Berlin'), + country(500, 'Australia', 'AU', OCEANIA), + subdivision(510, 500, 'New South Wales', 'AU-NSW'), + municipality(511, 510, 'Sydney'), + country(600, 'South Africa', 'ZA', AFRICA), + subdivision(610, 600, 'Western Cape', 'ZA-WC'), + municipality(611, 610, 'Cape Town'), + // No continent in the classification: its path starts at the country. + country(700, 'Clipperton', 'CP', null), +]; + +const PLACES_BY_ID = new Map(MOCK_PLACES.map((place) => [place.id, place])); + +/** Same name rule as the API: `Montréal (région)` -> `montreal-region`. */ +export function slugify(name: string): string { + return name + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); +} + +/** + * Same slug rule as the API: a continent's name, a country's lowercased + * code, otherwise the location id followed by the name. + */ +function slugOf(place: Place): string { + if (place.type === 'continent') return slugify(place.name); + if (place.type === 'country') return (place.code as string).toLowerCase(); + const name = slugify(place.name); + return name === '' ? String(place.id) : `${place.id}-${name}`; +} + +/** The place and its ancestors, from the continent down. */ +function chainOf(place: Place): Place[] { + const chain: Place[] = []; + let current: Place | undefined = place; + while (current != undefined) { + chain.unshift(current); + current = + current.parent === null ? undefined : PLACES_BY_ID.get(current.parent); + } + return chain; +} + +function ancestorOfType(place: Place, type: PlaceType): Place | undefined { + return chainOf(place).find((ancestor) => ancestor.type === type); +} + +function isWithin(placeId: number, ancestorId: number): boolean { + const place = PLACES_BY_ID.get(placeId); + return ( + place != undefined && chainOf(place).some(({ id }) => id === ancestorId) + ); +} + +type FeedSeed = [ + dataType: Feed['data_type'], + provider: string, + feedName: string, + /** One entry per group of stops, all of equal weight. */ + stopPlaces: number[], +]; + +const MONTREAL = 111; +const EXO_SECTORS = [ + 'Chambly-Richelieu-Carignan', + 'Haut-Saint-Laurent', + 'Laurentides', + 'Le Richelain', + 'Roussillon', + 'Sorel-Varennes', + 'Sud-Ouest', + 'Terrebonne-Mascouche', + 'Vallée du Richelieu', + 'La Presqu’Île', + 'L’Assomption', + 'Deux-Montagnes', +]; + +const FEED_SEEDS: FeedSeed[] = [ + // Canada-wide + ['gtfs', 'Example Intercity Rail', 'National rail network', [110, 120, 130]], + // Québec, stops not geolocated to a municipality + ['gtfs', 'Example Coach Lines', 'Intercity coaches', [110]], + ['gtfs_rt', 'Example Coach Lines', 'Trip updates', [110]], + // Montréal: 22 feeds, more than one page + ['gtfs', 'Société de transport de Montréal', 'Bus and metro', [MONTREAL]], + ['gtfs_rt', 'Société de transport de Montréal', 'Trip updates', [MONTREAL]], + ['gtfs_rt', 'Société de transport de Montréal', 'Alerts', [MONTREAL]], + ['gtfs', 'Réseau express métropolitain', 'REM light metro', [MONTREAL]], + ['gtfs', 'exo', 'Commuter trains', [MONTREAL, 112, 113]], + ['gtfs_rt', 'exo', 'Commuter trains - trip updates', [MONTREAL]], + ...EXO_SECTORS.map( + (sector): FeedSeed => ['gtfs', 'exo', `Buses - ${sector}`, [MONTREAL]], + ), + ['gbfs', 'BIXI Montréal', 'Bike share', [MONTREAL]], + ['gbfs', 'Example Scooters', 'Montréal e-scooters', [MONTREAL]], + ['gbfs', 'Example Car Share', 'Montréal car share', [MONTREAL]], + ['gtfs_rt', 'exo', 'Commuter trains - vehicle positions', [MONTREAL]], + // Elsewhere in Québec + ['gtfs', 'Société de transport de Laval', 'Buses', [112]], + ['gtfs', 'Réseau de transport de Longueuil', 'Buses', [113]], + ['gtfs', 'Réseau de transport de la Capitale', 'Buses', [114]], + ['gtfs_rt', 'Réseau de transport de la Capitale', 'Vehicle positions', [114]], + // Ontario and British Columbia + ['gtfs', 'Example Regional Transit', 'Regional rail and buses', [120, 121]], + ['gtfs', 'Toronto Transit Commission', 'Surface and subway', [121]], + ['gtfs_rt', 'Toronto Transit Commission', 'Trip updates', [121]], + ['gbfs', 'Bike Share Toronto', 'Bike share', [121]], + ['gtfs', 'Example Coast Transit', 'Buses and SkyTrain', [131]], + // United States + ['gtfs', 'Example Metro Los Angeles', 'Bus', [212, 213]], + ['gtfs_rt', 'Example Metro Los Angeles', 'Trip updates', [212]], + ['gtfs', 'Example County Transit', 'County buses', [211]], + ['gtfs', 'Example Bay Area Rail', 'Rapid transit', [214]], + ['gbfs', 'Example Bikes SF', 'Bike share', [214]], + ['gtfs', 'Example Metropolitan Transit', 'Subway', [221]], + ['gtfs_rt', 'Example Metropolitan Transit', 'Subway trip updates', [221]], + ['gtfs', 'Example Township Shuttle', 'Shuttle', [123456]], + ['gtfs', 'Example Township Dial-a-Ride', 'Dial-a-ride', [123457]], + // Europe + ['gtfs', 'Example Île-de-France Mobilités', 'Regional network', [311]], + ['gbfs', 'Example Vélo Paris', 'Bike share', [311]], + ['gtfs', 'Example Verkehrsverbund Berlin', 'Regional network', [411]], + // Oceania + ['gtfs', 'Example Transport NSW', 'Sydney network', [511]], + ['gtfs_rt', 'Example Transport NSW', 'Trip updates', [511]], + // Africa + ['gtfs', 'Example Cape Town Bus', 'Bus rapid transit', [611]], + // No continent + ['gtfs', 'Example Island Boats', 'Supply boats', [700]], +]; + +interface MockFeed { + feed: Feed; + stopPlaces: number[]; +} + +function declaredLocation( + placeId: number, +): NonNullable[number] { + const place = PLACES_BY_ID.get(placeId) as Place; + const chain = chainOf(place); + const placeCountry = ancestorOfType(place, 'country'); + const municipalities = chain.filter(({ type }) => type === 'municipality'); + return { + country_code: placeCountry?.code, + country: placeCountry?.name, + subdivision_name: ancestorOfType(place, 'subdivision')?.name, + municipality: municipalities[municipalities.length - 1]?.name, + }; +} + +function toMockFeed( + [dataType, provider, feedName, stopPlaces]: FeedSeed, + index: number, +): MockFeed { + const id = `mock-loc-${String(index + 1).padStart(3, '0')}`; + return { + stopPlaces, + feed: { + id, + data_type: dataType, + status: 'active', + official: index % 3 === 0, + seasonal: false, + provider, + feed_name: feedName, + external_ids: [{ external_id: id, source: 'mdb' }], + source_info: { + producer_url: `https://example.com/${id}/${dataType}`, + authentication_type: 0, + }, + locations: stopPlaces.map(declaredLocation), + entity_types: dataType === 'gtfs_rt' ? ['tu', 'vp'] : undefined, + versions: dataType === 'gbfs' ? ['2.3'] : undefined, + }, + }; +} + +const MOCK_FEEDS: MockFeed[] = FEED_SEEDS.map(toMockFeed); + +/** Share of a feed's stop groups inside the location, 0 when outside. */ +function shareIn({ stopPlaces }: MockFeed, locationId: number): number { + const inside = stopPlaces.filter((placeId) => isWithin(placeId, locationId)); + return inside.length / stopPlaces.length; +} + +function feedsIn(locationId: number): MockFeed[] { + return MOCK_FEEDS.filter((feed) => shareIn(feed, locationId) > 0); +} + +function countFeeds(feeds: MockFeed[]): FeedCounts { + const count = (dataType: Feed['data_type']): number => + feeds.filter(({ feed }) => feed.data_type === dataType).length; + return { + gtfs: count('gtfs'), + gtfs_rt: count('gtfs_rt'), + gbfs: count('gbfs'), + total: feeds.length, + }; +} + +interface Row { + result: LocationResult; + /** The mock place id, negative for a continent. */ + id: number; + depth: number; + counts: FeedCounts; +} + +function toRow(place: Place): Row { + const chain = chainOf(place); + const placeContinent = ancestorOfType(place, 'continent'); + const placeCountry = ancestorOfType(place, 'country'); + const placeSubdivision = ancestorOfType(place, 'subdivision'); + // From the country down, or the continent itself. + const pathChain = + place.type === 'continent' + ? chain + : chain.filter(({ type }) => type !== 'continent'); + const isContinent = place.type === 'continent'; + return { + depth: chain.length, + counts: countFeeds(feedsIn(place.id)), + id: place.id, + result: { + // Continents have no id, and countries no parent, in the API. + location_id: isContinent ? null : place.id, + parent_location_id: + isContinent || place.type === 'country' ? null : place.parent, + name: place.name, + alt_name: null, + location_type: place.type, + continent_code: placeContinent?.code ?? null, + slug: slugOf(place), + path_slugs: pathChain.map(slugOf), + path_names: pathChain.map(({ name }) => name), + country_name: placeCountry?.name ?? null, + country_code: placeCountry?.code ?? null, + subdivision_name: placeSubdivision?.name ?? null, + subdivision_code: placeSubdivision?.code ?? null, + display_name: pathChain.map(({ name }) => name).join(', '), + }, + }; +} + +const ROWS: Row[] = MOCK_PLACES.map(toRow); +const ROWS_BY_ID = new Map(ROWS.map((row) => [row.id, row])); + +export type MockResult = + | { status: 200; body: T } + | { status: 400; body: { detail: string } }; + +const badRequest = (detail: string): MockResult => ({ + status: 400, + body: { detail }, +}); + +function readPaging( + params: URLSearchParams, + maxLimit: number, +): { limit: number; offset: number } | null { + const limit = Number(params.get('limit') ?? String(maxLimit)); + const offset = Number(params.get('offset') ?? '0'); + if (!Number.isInteger(limit) || limit < 0 || limit > maxLimit) return null; + if (!Number.isInteger(offset) || offset < 0) return null; + return { limit, offset }; +} + +/** The comma-separated `include` values, or null when one is unsupported. */ +function readInclude( + params: URLSearchParams, + allowed: readonly string[], +): Set | null { + const values = (params.get('include') ?? '') + .split(',') + .filter((value) => value !== ''); + if (values.some((value) => !allowed.includes(value))) return null; + return new Set(values); +} + +function readSort( + params: URLSearchParams, +): 'admin_level' | 'feed_count' | null { + const sort = params.get('sort') ?? 'admin_level'; + return sort === 'admin_level' || sort === 'feed_count' ? sort : null; +} + +/** The mock id of the `continent` parameter (slug or code), NaN if unknown. */ +function readContinent(params: URLSearchParams): number | undefined { + const value = params.get('continent')?.toLowerCase(); + if (value == undefined || value === '') return undefined; + // Slug or code, case-insensitive; unknown values match nothing. + return ( + ROWS.find( + ({ result }) => + result.location_type === 'continent' && + [result.slug, result.continent_code?.toLowerCase()].includes(value), + )?.id ?? Number.NaN + ); +} + +function readId(params: URLSearchParams, name: string): number | undefined { + const raw = params.get(name); + if (raw == undefined || raw === '') return undefined; + const id = Number(raw); + // Invalid values match nothing. + return Number.isInteger(id) ? id : Number.NaN; +} + +const normalize = (text: string): string => + text + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') + .toLowerCase(); + +function sortRows(rows: Row[], sort: 'admin_level' | 'feed_count'): Row[] { + return [...rows].sort( + (a, b) => + (sort === 'feed_count' + ? (b.counts.total ?? 0) - (a.counts.total ?? 0) + : a.depth - b.depth) || + (a.result.display_name ?? '').localeCompare(b.result.display_name ?? ''), + ); +} + +/** + * Filters, sorts and pages rows like the list endpoints; `include` adds the + * feed counts. + */ +function listRows( + rows: Row[], + params: URLSearchParams, + include: Set, +): MockResult { + const sort = readSort(params); + if (sort === null) return badRequest('Unsupported sort.'); + const paging = readPaging(params, 100); + if (paging === null) return badRequest('Invalid limit or offset.'); + const hasFeeds = params.get('has_feeds') === 'true'; + const matching = sortRows( + rows.filter(({ counts }) => !hasFeeds || (counts.total ?? 0) > 0), + sort, + ); + return { + status: 200, + body: { + total: matching.length, + results: matching + .slice(paging.offset, paging.offset + paging.limit) + .map(({ result, counts }) => + include.has('feed_counts') + ? { ...result, feed_counts: counts } + : result, + ), + }, + }; +} + +/** GET /v1/locations */ +export function getMockLocations( + params: URLSearchParams, +): MockResult { + const include = readInclude(params, ['feed_counts']); + if (include === null) return badRequest('Unsupported include.'); + const locationType = params.get('location_type'); + const locationId = readId(params, 'location_id'); + const parentLocationId = readId(params, 'parent_location_id'); + const continentId = readContinent(params); + const countryCode = params.get('country_code')?.toUpperCase(); + const subdivisionCode = params.get('subdivision_code')?.toUpperCase(); + const words = normalize(params.get('search_query') ?? '') + .split(/\s+/) + .filter((word) => word !== ''); + + const rows = ROWS.filter(({ result, id }) => { + if (locationType != null && result.location_type !== locationType) + return false; + if (locationId != undefined && result.location_id !== locationId) + return false; + if ( + parentLocationId != undefined && + result.parent_location_id !== parentLocationId + ) + return false; + if (continentId != undefined && !isWithin(id, continentId)) return false; + if (countryCode != undefined && result.country_code !== countryCode) + return false; + if ( + subdivisionCode != undefined && + result.subdivision_code !== subdivisionCode + ) + return false; + const haystack = normalize(result.display_name ?? ''); + return words.every((word) => haystack.includes(word)); + }); + return listRows(rows, params, include); +} + +/** True when a /v1/search request targets a location. */ +export function isLocationSearch(params: URLSearchParams): boolean { + return ( + params.has('location_id') || + params.has('continent') || + params.get('sort') === 'location' + ); +} + +/** GET /v1/search with `location_id` or `continent`. */ +export function getMockLocationFeeds( + params: URLSearchParams, +): MockResult { + const sort = params.get('sort') ?? 'created_at'; + const rawLocationId = params.get('location_id'); + const continentId = readContinent(params); + if (rawLocationId != null && continentId != undefined) { + return badRequest('Pass location_id or continent, not both.'); + } + let scopeId: number | undefined = continentId; + if (rawLocationId != null) { + scopeId = Number(rawLocationId); + if (!Number.isInteger(scopeId)) return badRequest('Invalid location_id.'); + } + if (sort !== 'created_at' && sort !== 'location') { + return badRequest('Unsupported sort.'); + } + if (sort === 'location' && scopeId == undefined) { + return badRequest('sort=location requires location_id or continent.'); + } + const paging = readPaging(params, 3500); + if (paging === null) return badRequest('Invalid limit or offset.'); + + // A location id is never a continent's; unknown values return no feed. + const known = + scopeId != undefined && + ROWS_BY_ID.has(scopeId) && + (rawLocationId == null || scopeId > 0); + const scoped = + scopeId == undefined ? MOCK_FEEDS : known ? feedsIn(scopeId) : []; + const sorted = [...scoped].sort((a, b) => + sort === 'location' && scopeId != undefined + ? shareIn(b, scopeId) - shareIn(a, scopeId) || + (a.feed.provider ?? '').localeCompare(b.feed.provider ?? '') || + (a.feed.feed_name ?? '').localeCompare(b.feed.feed_name ?? '') || + a.feed.id.localeCompare(b.feed.id) + : // Newest first: the mock ids grow with the creation order. + b.feed.id.localeCompare(a.feed.id), + ); + return { + status: 200, + body: { + total: sorted.length, + results: sorted + .slice(paging.offset, paging.offset + paging.limit) + .map(({ feed }) => feed), + }, + }; +} diff --git a/src/proxy.ts b/src/proxy.ts index 2bfbf3c7..9b4ff162 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -1,5 +1,6 @@ import { NextResponse, type NextRequest } from 'next/server'; import { + getLowercaseLocationPathname, isFeedDetailPage, isAuthenticatedNotGuest, rewriteFeedRequest, @@ -19,8 +20,9 @@ import { * 2. Direct access to /static/ routes without proxy header → returns 404 * 3. Feed detail pages with auth session → rewrite to /authed route (dynamic, non-cached) * 4. Feed detail pages without auth → rewrite to /static route (dynamic, ISR-cacheable) - * 5. If supported locale exists in pathname → pass through unchanged - * 6. Otherwise → internally rewrite to include default locale + * 5. Location directory paths with uppercase letters → 308 redirect to the lowercase path + * 6. If supported locale exists in pathname → pass through unchanged + * 7. Otherwise → internally rewrite to include default locale * * See src/app/utils/proxy-helpers.ts for routing helper functions. */ @@ -85,6 +87,15 @@ export default function proxy(request: NextRequest): NextResponse { }); } + // === Location directory: one lowercase URL per place === + + const lowercaseLocationPathname = getLowercaseLocationPathname(pathname); + if (lowercaseLocationPathname !== null) { + const url = request.nextUrl.clone(); + url.pathname = lowercaseLocationPathname; + return NextResponse.redirect(url, 308); + } + // === Locale routing === // If locale already in path, continue as-is