diff --git a/bun.lock b/bun.lock index 621925e..d45e2dd 100644 --- a/bun.lock +++ b/bun.lock @@ -10,6 +10,7 @@ "@gorhom/bottom-sheet": "5.2.14", "@maplibre/maplibre-react-native": "11.5.0", "@react-native-async-storage/async-storage": "2.2.0", + "@react-native-community/datetimepicker": "8.4.7", "expo": "54.0.37", "expo-asset": "12.0.14", "expo-clipboard": "~8.0.8", @@ -402,6 +403,8 @@ "@react-native-async-storage/async-storage": ["@react-native-async-storage/async-storage@2.2.0", "", { "dependencies": { "merge-options": "^3.0.4" }, "peerDependencies": { "react-native": "^0.0.0-0 || >=0.65 <1.0" } }, "sha512-gvRvjR5JAaUZF8tv2Kcq/Gbt3JHwbKFYfmb445rhOj6NUMx3qPLixmDx5pZAyb9at1bYvJ4/eTUipU5aki45xw=="], + "@react-native-community/datetimepicker": ["@react-native-community/datetimepicker@8.4.7", "", { "dependencies": { "invariant": "^2.2.4" }, "peerDependencies": { "expo": ">=52.0.0", "react": "*", "react-native": "*", "react-native-windows": "*" }, "optionalPeers": ["expo", "react-native-windows"] }, "sha512-E70/YTUKHRfK2HZKniE9e68aVg1+ScGZ7nqsgu43FjeCFyKk7//B4pPUenWJAXgTVZHB1G0aU1PAfJx/irXUqQ=="], + "@react-native/assets-registry": ["@react-native/assets-registry@0.81.5", "", {}, "sha512-705B6x/5Kxm1RKRvSv0ADYWm5JOnoiQ1ufW7h8uu2E6G9Of/eE6hP/Ivw3U5jI16ERqZxiKQwk34VJbB0niX9w=="], "@react-native/babel-plugin-codegen": ["@react-native/babel-plugin-codegen@0.81.5", "", { "dependencies": { "@babel/traverse": "^7.25.3", "@react-native/codegen": "0.81.5" } }, "sha512-oF71cIH6je3fSLi6VPjjC3Sgyyn57JLHXs+mHWc9MoCiJJcM4nqsS5J38zv1XQ8d3zOW2JtHro+LF0tagj2bfQ=="], diff --git a/docs/development/android.md b/docs/development/android.md index a01ae0f..96a6a22 100644 --- a/docs/development/android.md +++ b/docs/development/android.md @@ -72,8 +72,6 @@ The initial SDK 54 lockfile was checked with `npm audit` and compatible fixes ap Brand assets add two Expo modules and enable one existing module's config plugin: `expo-font` (already a dependency; its config plugin now embeds the bundled Geist and Mona Sans TTFs as Android XML font families), `expo-splash-screen` (black splash with the brand mark; AndroidX `core-splashscreen`), and `expo-asset` (resolves the bundled font URLs that `src/theme/fonts.web.ts` declares with `@font-face` on the web). Their Android dependencies are AndroidX and React Native only; none pulls Google Play services. `@resvg/resvg-js` is a development-only renderer for `scripts/render-brand-assets.mjs` and is not part of the app. After changing the mark, run the script and commit the PNGs; `node scripts/render-brand-assets.mjs --check` fails when they are stale. Fonts and their OFL-1.1 texts are listed in [`assets/fonts/README.md`](../../assets/fonts/README.md). -The task sheet uses `@gorhom/bottom-sheet` 5.2.14, a JavaScript library (with `@gorhom/portal`) on the pinned Reanimated 4.1.1, react-native-worklets 0.5.1 and Gesture Handler 2.28. Its v5.2.8 example app pins the same SDK 54 / React Native 0.81.5 new-architecture stack. It adds no native module, permission or Google dependency. Gesture, keyboard and TalkBack behaviour still require a device check after each upgrade. +The planner's time chip uses `@react-native-community/datetimepicker` 8.4.7 (SDK 54 core has no date/time dialog and `@expo/ui` is beta). SDK 54 lists exactly 8.4.4, but its Kotlin sources call `getCurrentActivity()`, which the Kotlin 2.2.20 pinned by the navigation plugin rejects (`MaterialDatePickerModule.kt`/`MaterialTimePickerModule.kt`: "Function invocation 'getCurrentActivity()' expected"); 8.4.5 and later use `reactApplicationContext.currentActivity`. The package is therefore listed in `expo.install.exclude` so `bun run doctor` accepts the exact 8.4.7 pin; revisit when the SDK's expected version catches up. Only the imperative `DateTimePickerAndroid.open` API is used, with `timeZoneName: 'Europe/Rome'`; it shows the platform `DatePickerDialog`/`TimePickerDialog`. Its Android library depends on AndroidX `core-ktx` and `com.google.android.material:material` 1.12.0 (Material Components, Apache-2.0, a UI library with no Google Play services, location or network use). No config plugin is needed for the default dialogs, so none is added. It requires a rebuilt APK; verify the merged dependency graph and manifest stay free of `com.google.android.gms` and add no permission. The web preview uses the browser's date/time input instead. -## Browser preview - -MapLibre GL JS 6 ships ESM workers separately. `bun install --frozen-lockfile` runs `scripts/prepare-web-assets.mjs` to copy the pinned worker into `public/vendor`, while the web map supplies its same-origin URL. The Expo Babel import-meta transform permits Metro's non-module bundle output. Keep these together when upgrading the browser renderer; an exported web bundle alone does not prove workers started. This browser dependency is separate from native MapLibre and is excluded from Android's platform-resolved bundle. +**Apri in un’altra app** calls `Linking.openURL` with a `geo:` URI. It needs no `` entry because the app never asks which handlers exist; with no map app installed the failure is reported in Italian. diff --git a/docs/development/tooling.md b/docs/development/tooling.md index c65938f..fb21883 100644 --- a/docs/development/tooling.md +++ b/docs/development/tooling.md @@ -6,7 +6,7 @@ Bun is the package manager and the typecheck/test runner. Its version is pinned Use `bun run verify` before handing off code. It runs the native typecheck, ESLint with zero warnings permitted, and all fixture tests through Bun's native test runner. The package scripts also expose each check separately, a TypeScript compiler comparison and live service probes. Generated datasets, native output and research archives are excluded from linting. -Run `bun run doctor` after Expo dependency/configuration changes. It runs the SDK compatibility check without an interactive fix prompt, then the pinned Expo Doctor. Use Expo’s installer with Bun for intentional dependency updates. +Run `bun run doctor` after Expo dependency/configuration changes. It runs the SDK compatibility check without an interactive fix prompt, then the pinned Expo Doctor. Check every new or updated native module with an Android build, not only typecheck and doctor: the Kotlin 2.2.20 pin from the navigation plugin can reject Kotlin sources written for older compilers. Use Expo’s installer with Bun for intentional dependency updates. The Bun suite also invokes the Python standard-library place- and GTT-package regressions. fflate is a pure-JavaScript dependency (no native module) used to inflate ranged GTT ZIP members. Timetable store tests run the production SQL against Bun's built-in `bun:sqlite` through a small driver adapter (`src/transit-data/test-support`); on device the same SQL runs through expo-sqlite. Bun's own type package is not installed, so a minimal ambient declaration covers `bun:sqlite`. Python 3 prepares data and renders extraction SQL; executing the Overture extract needs DuckDB with its `httpfs` extension. See [data preparation](data.md) for pinned inputs, independent place/GTT refreshes and package validation. diff --git a/docs/development/ux.md b/docs/development/ux.md index 46c5485..c157ca0 100644 --- a/docs/development/ux.md +++ b/docs/development/ux.md @@ -16,7 +16,12 @@ The map is the starting point. Search, discovery, transport and saved places are - An empty search has no selected category or automatic discovery results. Put category shortcuts inside the search interaction. Category selection, typed search, transport and saved places reveal their own results and pins. - Clearing or closing a search returns to the unselected map. Map movement alone does not begin discovery; searching a changed area is explicit. - Submitting a search or choosing a category frames its leading nearby results once, above the sheet. Panning before they arrive keeps the user's view; typing alone never moves the map. +- Typed search matches every word somewhere in a place: its name (exact and prefix names rank first, one typo at most), its address including house numbers (exact), an Italian category word (`farmacia`, `bar`) or a neighbourhood from the bundled OpenStreetMap gazetteer (`Eataly Lingotto`, `bar San Salvario`). Linking words (`in`, `a`, `di`) are optional. A neighbourhood alone returns the neighbourhood, not every business inside it; its reading area is an approximate radius around the OSM node, never a boundary. Results say what they are: venue, address (**Indirizzo**), street (**Via**), area (**Quartiere**), GTT stop or line. A typed stop code (`472`, `fermata 472`) leads the list, a line name (`15`, `M1`, `linea 4`) offers its three stops nearest the searched area, and stops found by name follow the places unless the query starts with `fermata`. Stops and lines come from the bundled GTT catalog and appear in either search policy. - Route planning starts from a fresh position or a deliberately chosen origin. Cancelling origin selection returns to the destination; a fallback viewport never silently becomes the departure point. +- The planner shows **Da** and **A** as two editable fields with a swap button. Each opens a search inside the planner (the same local, stop and, when allowed, Photon search, plus saved places); the origin editor also offers **La tua posizione** (a fresh fix) and **Scegli sulla mappa**. Back closes the editor before the planner. Swapping needs a settled origin; a device origin swapped into the destination is that fixed position, not a live one. Changing either endpoint keeps the planning session and frames the new route once. +- Transit time is one chip (**Partenza adesso**, **Partenza 17:45 · domani**, **Arrivo entro 09:00 · gio 15 ott**). It opens Partenza/Arrivo, **Adesso** and Android's own date and time dialogs, all in Europe/Rome whatever the device zone; each choice plans again. Nonexistent and ambiguous minutes at daylight-saving changes are refused with a message. +- **Apri in un’altra app** on a place and on the planner destination sends `geo:lat,lon?q=lat,lon(Nome)` to Android, which lets the user pick Organic Maps or another map app. The app itself sends nothing anywhere for this; the chosen map app receives the place and handles it under its own privacy terms. Organic Maps' geo URL parser reads the coordinates and the percent-encoded label from `q` (its `geo_url_tests.cpp`, `GeoURL_GeoLabel`, checked on 2026-11-02 at upstream commit fb0ea2c); parentheses in a name are replaced because they would end the label. +- Place details keep **Indicazioni** and **Salva** as the primary pair, then website (shown without scheme), phone and the hand-off. **Fonti e dettagli** lists every contributing source record with the field it supplied, its licence and its own date, Overture's existence estimate (never "open now"), and states that no used source supplies opening hours. - Give one task the sheet at a time: results, place, stop, route planning or settings. Keep the map usable alongside it and provide a clear return to the map. Sheet titles and actions take precedence over explanatory text. Keep transport and saved shortcuts on the neutral map; task cards replace that chrome. Empty search uses a horizontal shortcut row. - List distances are measured from the device when its fix is under five minutes old; otherwise they are measured from the centre the map currently shows and say **dal centro mappa**. A selected stop or place shows a distance only from the device. Show OpenStreetMap and Overture categories with Italian labels and a generic fallback, never a raw tag. - Show coverage boundaries, result limits and data warnings with the results they explain. Keep mandatory map attribution accessible. Preserve place provenance, source timestamps, and live, scheduled, stale and unavailable distinctions in their relevant detail views. diff --git a/docs/research/online-services.md b/docs/research/online-services.md index 3d2b906..3e38b4c 100644 --- a/docs/research/online-services.md +++ b/docs/research/online-services.md @@ -18,6 +18,8 @@ The [official README](https://github.com/komoot/photon) documents multilingual O The README permits use in projects while request volume remains reasonable, reserves throttling/banning for extensive use, and disclaims availability or change guarantees. This is more appropriate for bounded request volumes than assuming an unlimited hosted service. Debounce, cancel obsolete queries, cap results, cache appropriately and make the provider replaceable. A private instance is possible but adds substantial data/hosting work; it is not the proposed starting point. +**How the app uses it.** Only names and addresses go to Photon, with the map centre as location bias, one request per second, cancelled when superseded and cached for five minutes per text and rounded bias. Category words, neighbourhood words alone, stop codes and line names (`472`, `M1`, `fermata 472`, `linea 4`) are answered on the device. Photon, like the local index, needs every word to match: on 2026-11-02 `Eataly Lingotto` returned nothing while `Eataly` biased to the Lingotto node returned the Via Nizza 224 store 1.7 km from that node. So when the full query returns nothing and it names a neighbourhood from the bundled OSM gazetteer (`src/data/localities.json`, built by `scripts/localities.mjs` from one Overpass export), one more request sends the remaining words biased to that neighbourhood's public node instead of the map centre, and answers outside its approximate radius (2 km for suburbs, 900 m for quarters) are dropped. This adds at most one request per such search and discloses a public neighbourhood point rather than the user's map view. Results are labelled as venue, address, street or area from Photon's `osm_key`, `osm_value` and `type`. + A single bounded synthetic query returned HTTP 200 and matching OSM objects. This demonstrates technical access, not comprehensive business discovery. Photon cannot retrieve businesses absent from the data it indexes. ## FOSSGIS public routing: car, bike and foot diff --git a/package.json b/package.json index 1517819..47d189c 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "@gorhom/bottom-sheet": "5.2.14", "@maplibre/maplibre-react-native": "11.5.0", "@react-native-async-storage/async-storage": "2.2.0", + "@react-native-community/datetimepicker": "8.4.7", "expo": "54.0.37", "expo-asset": "12.0.14", "expo-clipboard": "~8.0.8", @@ -74,6 +75,11 @@ }, "packageManager": "bun@1.4.3", "expo": { + "install": { + "exclude": [ + "@react-native-community/datetimepicker" + ] + }, "autolinking": { "android": { "exclude": [ diff --git a/scripts/localities.mjs b/scripts/localities.mjs new file mode 100644 index 0000000..b134fb1 --- /dev/null +++ b/scripts/localities.mjs @@ -0,0 +1,47 @@ +#!/usr/bin/env node +/** + * Builds src/data/localities.json, the small neighbourhood gazetteer used to read area words in + * search ("Eataly Lingotto", "bar San Salvario"). Input: an Overpass JSON export of OSM place nodes + * within the place-package rectangle, retrieved with + * + * [out:json][timeout:80];(node["place"~"^(suburb|quarter|neighbourhood)$"](44.98,7.57,45.15,7.78););out body; + * + * Usage: node scripts/localities.mjs [retrievedAt YYYY-MM-DD] + * + * Selection: every place=suburb, plus quarter/neighbourhood nodes with multi-word names (single + * words such as "Rossi" or "Crimea" are too often part of business names). "Centro" is excluded as + * generic. A parenthetical suffix is dropped and the first node of a repeated name wins. Radii are + * approximate reading areas around the OSM node, not boundaries. + */ +import { readFileSync, writeFileSync } from 'node:fs'; + +const [input, retrievedAt = new Date().toISOString().slice(0, 10)] = process.argv.slice(2); +if (!input) { console.error('usage: node scripts/localities.mjs [YYYY-MM-DD]'); process.exit(2); } +const data = JSON.parse(readFileSync(input, 'utf8')); +const RADIUS = { suburb: 2000, quarter: 900, neighbourhood: 900 }; +const key = name => name.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim(); +const seen = new Set(); +const localities = []; +const order = { suburb: 0, quarter: 1, neighbourhood: 2 }; +for (const element of [...data.elements].sort((a, b) => order[a.tags.place] - order[b.tags.place] || a.id - b.id)) { + const kind = element.tags.place; + const name = (element.tags.name ?? '').replace(/\s*\(.*\)\s*$/, '').trim(); + if (!name || key(name) === 'centro' || seen.has(key(name))) continue; + if (kind !== 'suburb' && key(name).split(' ').length < 2) continue; + seen.add(key(name)); + localities.push({ id: `osm:node:${element.id}`, name, kind, latitude: Number(element.lat.toFixed(5)), longitude: Number(element.lon.toFixed(5)), radiusMeters: RADIUS[kind] }); +} +localities.sort((a, b) => a.name.localeCompare(b.name, 'it')); +const output = { + schemaVersion: 1, + source: 'OpenStreetMap place nodes via Overpass API', + license: 'ODbL-1.0', + attribution: '© OpenStreetMap contributors · ODbL', + osmBase: data.osm3s?.timestamp_osm_base ?? null, + retrievedAt, + query: '[out:json];(node["place"~"^(suburb|quarter|neighbourhood)$"](44.98,7.57,45.15,7.78););out body;', + selection: 'place=suburb, plus multi-word quarter/neighbourhood names; "Centro" excluded; radii are approximate.', + localities, +}; +writeFileSync(new URL('../src/data/localities.json', import.meta.url), `${JSON.stringify(output, null, 1)}\n`); +console.log(`${localities.length} localities`); diff --git a/src/data/localities.json b/src/data/localities.json new file mode 100644 index 0000000..5f9a802 --- /dev/null +++ b/src/data/localities.json @@ -0,0 +1,644 @@ +{ + "schemaVersion": 1, + "source": "OpenStreetMap place nodes via Overpass API", + "license": "ODbL-1.0", + "attribution": "© OpenStreetMap contributors · ODbL", + "osmBase": "2026-11-01T23:31:51Z", + "retrievedAt": "2026-11-02", + "query": "[out:json];(node[\"place\"~\"^(suburb|quarter|neighbourhood)$\"](44.98,7.57,45.15,7.78););out body;", + "selection": "place=suburb, plus multi-word quarter/neighbourhood names; \"Centro\" excluded; radii are approximate.", + "localities": [ + { + "id": "osm:node:6182638641", + "name": "Alta Parella", + "kind": "neighbourhood", + "latitude": 45.0821, + "longitude": 7.62059, + "radiusMeters": 900 + }, + { + "id": "osm:node:6196526153", + "name": "Altessano", + "kind": "suburb", + "latitude": 45.12783, + "longitude": 7.64035, + "radiusMeters": 2000 + }, + { + "id": "osm:node:2036078189", + "name": "Aurora", + "kind": "suburb", + "latitude": 45.08257, + "longitude": 7.68601, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6180793734", + "name": "Barca", + "kind": "suburb", + "latitude": 45.10178, + "longitude": 7.72788, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6176880988", + "name": "Barriera di Lanzo", + "kind": "suburb", + "latitude": 45.11354, + "longitude": 7.65744, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6180847263", + "name": "Barriera di Milano", + "kind": "suburb", + "latitude": 45.09239, + "longitude": 7.69532, + "radiusMeters": 2000 + }, + { + "id": "osm:node:4553870468", + "name": "Basse di Mirafiori", + "kind": "neighbourhood", + "latitude": 45.01269, + "longitude": 7.65493, + "radiusMeters": 900 + }, + { + "id": "osm:node:6182638639", + "name": "Basso San Donato", + "kind": "neighbourhood", + "latitude": 45.08457, + "longitude": 7.66481, + "radiusMeters": 900 + }, + { + "id": "osm:node:6182638637", + "name": "Borgata Ceronda", + "kind": "neighbourhood", + "latitude": 45.09123, + "longitude": 7.65625, + "radiusMeters": 900 + }, + { + "id": "osm:node:6182621428", + "name": "Borgata Frassati", + "kind": "neighbourhood", + "latitude": 45.09552, + "longitude": 7.6325, + "radiusMeters": 900 + }, + { + "id": "osm:node:6184439824", + "name": "Borgata Lesna", + "kind": "neighbourhood", + "latitude": 45.0625, + "longitude": 7.62005, + "radiusMeters": 900 + }, + { + "id": "osm:node:1223076192", + "name": "Borgata Mirafiori", + "kind": "neighbourhood", + "latitude": 45.01393, + "longitude": 7.62855, + "radiusMeters": 900 + }, + { + "id": "osm:node:6184718081", + "name": "Borgata Paradiso", + "kind": "suburb", + "latitude": 45.07446, + "longitude": 7.59807, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6221831572", + "name": "Borgata Quaglia", + "kind": "neighbourhood", + "latitude": 45.06361, + "longitude": 7.60654, + "radiusMeters": 900 + }, + { + "id": "osm:node:6184536794", + "name": "Borgata Rosa", + "kind": "neighbourhood", + "latitude": 45.08702, + "longitude": 7.73303, + "radiusMeters": 900 + }, + { + "id": "osm:node:6182621430", + "name": "Borgata Tesso", + "kind": "neighbourhood", + "latitude": 45.09246, + "longitude": 7.67404, + "radiusMeters": 900 + }, + { + "id": "osm:node:1931793949", + "name": "Borgo Cina", + "kind": "neighbourhood", + "latitude": 45.03359, + "longitude": 7.6376, + "radiusMeters": 900 + }, + { + "id": "osm:node:6184474135", + "name": "Borgo Dora", + "kind": "neighbourhood", + "latitude": 45.08127, + "longitude": 7.68341, + "radiusMeters": 900 + }, + { + "id": "osm:node:13328827517", + "name": "Borgo Mercato", + "kind": "quarter", + "latitude": 45.0008, + "longitude": 7.6729, + "radiusMeters": 900 + }, + { + "id": "osm:node:13328827516", + "name": "Borgo Navile", + "kind": "quarter", + "latitude": 44.99933, + "longitude": 7.6803, + "radiusMeters": 900 + }, + { + "id": "osm:node:6184474132", + "name": "Borgo Nuovo", + "kind": "neighbourhood", + "latitude": 45.0636, + "longitude": 7.68834, + "radiusMeters": 900 + }, + { + "id": "osm:node:6174580830", + "name": "Borgo Po", + "kind": "suburb", + "latitude": 45.06067, + "longitude": 7.69913, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6173273410", + "name": "Borgo San Paolo", + "kind": "suburb", + "latitude": 45.06146, + "longitude": 7.64584, + "radiusMeters": 2000 + }, + { + "id": "osm:node:13328827518", + "name": "Borgo San Pietro", + "kind": "quarter", + "latitude": 45.01219, + "longitude": 7.6634, + "radiusMeters": 900 + }, + { + "id": "osm:node:6176940554", + "name": "Borgo Vittoria", + "kind": "suburb", + "latitude": 45.0973, + "longitude": 7.67806, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6172501669", + "name": "Campidoglio", + "kind": "suburb", + "latitude": 45.07935, + "longitude": 7.653, + "radiusMeters": 2000 + }, + { + "id": "osm:node:7976096773", + "name": "Cascina del Mulino", + "kind": "suburb", + "latitude": 45.11009, + "longitude": 7.76076, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6173226735", + "name": "Cenisia", + "kind": "suburb", + "latitude": 45.06971, + "longitude": 7.64988, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6184456731", + "name": "Centro Europa", + "kind": "neighbourhood", + "latitude": 45.03892, + "longitude": 7.62069, + "radiusMeters": 900 + }, + { + "id": "osm:node:4553863660", + "name": "Cime Bianche", + "kind": "neighbourhood", + "latitude": 45.01737, + "longitude": 7.61788, + "radiusMeters": 900 + }, + { + "id": "osm:node:6173226734", + "name": "Cit Turin", + "kind": "suburb", + "latitude": 45.07343, + "longitude": 7.66153, + "radiusMeters": 2000 + }, + { + "id": "osm:node:4553693050", + "name": "Città Giardino", + "kind": "neighbourhood", + "latitude": 45.04988, + "longitude": 7.62695, + "radiusMeters": 900 + }, + { + "id": "osm:node:6173628343", + "name": "Crocetta", + "kind": "suburb", + "latitude": 45.05792, + "longitude": 7.66497, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6177198087", + "name": "Falchera", + "kind": "suburb", + "latitude": 45.12836, + "longitude": 7.70936, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6182601507", + "name": "Falchera Nuova", + "kind": "neighbourhood", + "latitude": 45.13057, + "longitude": 7.71094, + "radiusMeters": 900 + }, + { + "id": "osm:node:6182601508", + "name": "Falchera Vecchia", + "kind": "neighbourhood", + "latitude": 45.12578, + "longitude": 7.70967, + "radiusMeters": 900 + }, + { + "id": "osm:node:6181637678", + "name": "Filadelfia", + "kind": "suburb", + "latitude": 45.03705, + "longitude": 7.65706, + "radiusMeters": 2000 + }, + { + "id": "osm:node:11506831794", + "name": "Gallo Praile", + "kind": "neighbourhood", + "latitude": 45.11597, + "longitude": 7.64085, + "radiusMeters": 900 + }, + { + "id": "osm:node:4553863661", + "name": "Il Villaggio", + "kind": "neighbourhood", + "latitude": 45.02004, + "longitude": 7.623, + "radiusMeters": 900 + }, + { + "id": "osm:node:6184484978", + "name": "Italia '61", + "kind": "neighbourhood", + "latitude": 45.02089, + "longitude": 7.66587, + "radiusMeters": 900 + }, + { + "id": "osm:node:6181683958", + "name": "Lingotto", + "kind": "suburb", + "latitude": 45.02615, + "longitude": 7.64989, + "radiusMeters": 2000 + }, + { + "id": "osm:node:1935302960", + "name": "Lucento", + "kind": "suburb", + "latitude": 45.09859, + "longitude": 7.648, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6174604885", + "name": "Madonna del Pilone", + "kind": "suburb", + "latitude": 45.06829, + "longitude": 7.72019, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6176928212", + "name": "Madonna di Campagna", + "kind": "suburb", + "latitude": 45.10082, + "longitude": 7.66845, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6181549636", + "name": "Mirafiori Nord", + "kind": "suburb", + "latitude": 45.04035, + "longitude": 7.62842, + "radiusMeters": 2000 + }, + { + "id": "osm:node:2036078230", + "name": "Mirafiori Sud", + "kind": "suburb", + "latitude": 45.01783, + "longitude": 7.63285, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6182614496", + "name": "Monte Bianco", + "kind": "neighbourhood", + "latitude": 45.09171, + "longitude": 7.68767, + "radiusMeters": 900 + }, + { + "id": "osm:node:7707020146", + "name": "Monte Rosa", + "kind": "neighbourhood", + "latitude": 45.08913, + "longitude": 7.69502, + "radiusMeters": 900 + }, + { + "id": "osm:node:6181694730", + "name": "Nizza Millefonti", + "kind": "suburb", + "latitude": 45.03017, + "longitude": 7.66785, + "radiusMeters": 2000 + }, + { + "id": "osm:node:7976096770", + "name": "Oltrepo", + "kind": "suburb", + "latitude": 45.10629, + "longitude": 7.75488, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6182638640", + "name": "Parco Dora", + "kind": "neighbourhood", + "latitude": 45.08932, + "longitude": 7.67071, + "radiusMeters": 900 + }, + { + "id": "osm:node:6171509496", + "name": "Parella", + "kind": "suburb", + "latitude": 45.07968, + "longitude": 7.63256, + "radiusMeters": 2000 + }, + { + "id": "osm:node:7976096771", + "name": "Pescarito", + "kind": "suburb", + "latitude": 45.1157, + "longitude": 7.74663, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6182601509", + "name": "Pietra Alta", + "kind": "neighbourhood", + "latitude": 45.1157, + "longitude": 7.7051, + "radiusMeters": 900 + }, + { + "id": "osm:node:6184439826", + "name": "Polo Nord", + "kind": "neighbourhood", + "latitude": 45.05557, + "longitude": 7.64932, + "radiusMeters": 900 + }, + { + "id": "osm:node:6184474134", + "name": "Porta Palazzo", + "kind": "neighbourhood", + "latitude": 45.07713, + "longitude": 7.68336, + "radiusMeters": 900 + }, + { + "id": "osm:node:6172500307", + "name": "Pozzo Strada", + "kind": "suburb", + "latitude": 45.06834, + "longitude": 7.62639, + "radiusMeters": 2000 + }, + { + "id": "osm:node:2038200594", + "name": "Quadrilatero Romano", + "kind": "neighbourhood", + "latitude": 45.07533, + "longitude": 7.67973, + "radiusMeters": 900 + }, + { + "id": "osm:node:6180874733", + "name": "Rebaudengo", + "kind": "suburb", + "latitude": 45.10426, + "longitude": 7.6993, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6184718082", + "name": "Regina Margherita", + "kind": "neighbourhood", + "latitude": 45.0735, + "longitude": 7.57944, + "radiusMeters": 900 + }, + { + "id": "osm:node:6180987596", + "name": "Regio Parco", + "kind": "suburb", + "latitude": 45.09305, + "longitude": 7.71495, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6184439825", + "name": "Rione Lancia", + "kind": "neighbourhood", + "latitude": 45.06033, + "longitude": 7.64022, + "radiusMeters": 900 + }, + { + "id": "osm:node:11506831800", + "name": "Salvo D'Acquisto", + "kind": "neighbourhood", + "latitude": 45.12132, + "longitude": 7.62811, + "radiusMeters": 900 + }, + { + "id": "osm:node:7976096772", + "name": "Sambuy", + "kind": "suburb", + "latitude": 45.11292, + "longitude": 7.7796, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6173288380", + "name": "San Donato", + "kind": "suburb", + "latitude": 45.08236, + "longitude": 7.66179, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6173683209", + "name": "San Salvario", + "kind": "suburb", + "latitude": 45.05495, + "longitude": 7.68015, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6184474133", + "name": "San Secondo", + "kind": "neighbourhood", + "latitude": 45.05928, + "longitude": 7.67284, + "radiusMeters": 900 + }, + { + "id": "osm:node:7976096774", + "name": "Sant'Anna", + "kind": "suburb", + "latitude": 45.09323, + "longitude": 7.75027, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6181575722", + "name": "Santa Rita", + "kind": "suburb", + "latitude": 45.04566, + "longitude": 7.64553, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6182601512", + "name": "Spina 4", + "kind": "neighbourhood", + "latitude": 45.09305, + "longitude": 7.68519, + "radiusMeters": 900 + }, + { + "id": "osm:node:1935302964", + "name": "Vallette", + "kind": "suburb", + "latitude": 45.10438, + "longitude": 7.6323, + "radiusMeters": 2000 + }, + { + "id": "osm:node:2036078250", + "name": "Vanchiglia", + "kind": "suburb", + "latitude": 45.07044, + "longitude": 7.69847, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6174637817", + "name": "Vanchiglietta", + "kind": "suburb", + "latitude": 45.07278, + "longitude": 7.71655, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6184439823", + "name": "Venchi Unica", + "kind": "neighbourhood", + "latitude": 45.07291, + "longitude": 7.61685, + "radiusMeters": 900 + }, + { + "id": "osm:node:2566661473", + "name": "Vigne - Lavatoio", + "kind": "neighbourhood", + "latitude": 45.01764, + "longitude": 7.75723, + "radiusMeters": 900 + }, + { + "id": "osm:node:6184718080", + "name": "Villaggio Dora", + "kind": "neighbourhood", + "latitude": 45.09008, + "longitude": 7.57017, + "radiusMeters": 900 + }, + { + "id": "osm:node:9532904692", + "name": "Villaggio Olimpia", + "kind": "suburb", + "latitude": 45.12446, + "longitude": 7.73085, + "radiusMeters": 2000 + }, + { + "id": "osm:node:6182621429", + "name": "Villaggio Santa Caterina", + "kind": "neighbourhood", + "latitude": 45.10197, + "longitude": 7.64391, + "radiusMeters": 900 + }, + { + "id": "osm:node:2036078254", + "name": "Villaretto", + "kind": "suburb", + "latitude": 45.13131, + "longitude": 7.68506, + "radiusMeters": 2000 + } + ] +} diff --git a/src/domain/types.ts b/src/domain/types.ts index 3dff2c9..d5a9b3d 100644 --- a/src/domain/types.ts +++ b/src/domain/types.ts @@ -4,11 +4,17 @@ export type TransitTime = { kind: 'now' } | { kind: 'depart-at' | 'arrive-by'; d export interface PlaceFieldCorrection { field: 'phone'; originalValue: string; value: string; url: string; checkedAt: string; reason: string; } +/** What a search result names: a venue, a civic address, a street, or an area such as a neighbourhood. */ +export type PlaceKind = 'place' | 'address' | 'street' | 'area'; export interface Place { + /** Absent means a venue. */ + kind?: PlaceKind; id: string; name: string; coordinate: Coordinate; category?: string | null; address?: string | null; website?: string | null; phone?: string | null; source: string; attributions: string[]; dataUpdatedAt?: string; confidence?: number | null; operatingStatus?: string | null; distanceMeters?: number; fieldCorrections?: PlaceFieldCorrection[]; + /** Per-source records from the local package (dataset, licence, update_time, confidence), when known. */ + provenance?: Record[]; } export type SavedPlace = Place; export interface RouteStep { instruction: string; distanceMeters: number; coordinate?: Coordinate } diff --git a/src/features/app/AppMap.tsx b/src/features/app/AppMap.tsx index 8f28f64..8b41280 100644 --- a/src/features/app/AppMap.tsx +++ b/src/features/app/AppMap.tsx @@ -5,6 +5,7 @@ import { toCoordinate, toMapCoordinate } from "../map/coordinates"; import MapCanvas from "../map/MapCanvas"; import { placeMarker, stopMarker, taskMarkers } from "../map/map-layers"; import { resultFrameBounds } from "../map/map-presentation"; +import { searchMapStops } from "../search/search-rows"; import { useMapContext } from "../map/useMapModel"; import { useNavigationContext } from "../navigation/useNavigation"; import { usePlacesContext } from "../places/usePlaces"; @@ -37,16 +38,21 @@ export function AppMap({ height, padding, attributionLeft, attributionTop }: { const searchPlaces = search.result.places; const shownPlaces = useMemo(() => tab === "saved" ? places.saved : search.hasSearch ? searchPlaces : [], [tab, places.saved, search.hasSearch, searchPlaces]); const nearbyStops = transit.nearbyStops; + // A typed stop code or line leads the results; its stops are pinned and framed. + const searchStops = useMemo(() => tab === "explore" && search.hasSearch + ? searchMapStops(search.transit, searchPlaces.length) : { pinned: [], framed: [] }, [tab, search.hasSearch, search.transit, searchPlaces.length]); + const leadStops = searchStops.pinned; const markers = useMemo(() => taskMarkers( - tab === "transit" ? nearbyStops.map(stopMarker) : shownPlaces.map(placeMarker), selected, board, - ), [tab, nearbyStops, shownPlaces, selected, board]); + tab === "transit" ? nearbyStops.map(stopMarker) : [...leadStops.map(stopMarker), ...shownPlaces.map(placeMarker)], selected, board, + ), [tab, nearbyStops, leadStops, shownPlaces, selected, board]); // Submitted searches and category choices frame their settled results once (see MapCanvas). const frame = search.frame; const resultFrame = useMemo(() => { if (tab !== "explore" || !search.hasSearch || !frame) return undefined; - const ready = frame.settled && !selected && !board && searchPlaces.length > 0; - return { key: frame.key, ready, bounds: ready ? resultFrameBounds(searchPlaces.map(place => place.coordinate), camera.searchCenter) : null }; - }, [tab, search.hasSearch, frame, selected, board, searchPlaces, camera.searchCenter]); + const coordinates = searchStops.framed.length ? searchStops.framed.map(stop => stop.coordinate) : searchPlaces.map(place => place.coordinate); + const ready = frame.settled && !selected && !board && coordinates.length > 0; + return { key: frame.key, ready, bounds: ready ? resultFrameBounds(coordinates, camera.searchCenter) : null }; + }, [tab, search.hasSearch, frame, selected, board, searchPlaces, searchStops, camera.searchCenter]); const route = planner.routes.route; const routeGeometry = useMemo( () => route && route.geometry.length > 1 ? { type: "LineString", coordinates: route.geometry.map(toMapCoordinate) } : null, @@ -92,6 +98,8 @@ export function AppMap({ height, padding, attributionLeft, attributionTop }: { const next = nearbyStops.find((item) => item.id === id); if (next) transit.openStop(next); } else { + const stop = leadStops.find((item) => item.id === id); + if (stop) { transit.openStop(stop); return; } const next = shownPlaces.find((item) => item.id === id); if (next) places.openPlace(next); } diff --git a/src/features/app/TaskSheet.tsx b/src/features/app/TaskSheet.tsx index 539dce4..7684a00 100644 --- a/src/features/app/TaskSheet.tsx +++ b/src/features/app/TaskSheet.tsx @@ -21,7 +21,7 @@ function taskTitle(task: Task, search: Search): string { switch (task.kind) { case "settings": return "Privacy e fonti"; case "journeyStop": case "stop": return task.stop.name; - case "planner": return "Percorso"; + case "planner": return task.editing === "origin" ? "Scegli la partenza" : task.editing === "destination" ? "Scegli la destinazione" : "Percorso"; case "place": return task.place.name; case "transit": return "Trasporti"; case "saved": return "Salvati"; @@ -61,13 +61,13 @@ export function TaskSheet({ snap, resting, heights, now }: { snap: SheetSnap; re closeLabel="Chiudi e torna alla mappa" actions={ sheet.request(expandTo)} /> + label={expands ? "Espandi scheda" : "Riduci scheda"} onPress={() => sheet.request(expandTo, { explicit: true })} /> } /> ); return ( : undefined} footerHeight={top.kind === "planner" ? ROUTE_ACTIONS_HEIGHT : 0}> + footer={top.kind === "planner" && !top.editing ? : undefined} footerHeight={top.kind === "planner" && !top.editing ? ROUTE_ACTIONS_HEIGHT : 0}> diff --git a/src/features/app/external-link.test.ts b/src/features/app/external-link.test.ts index abd9626..9602f48 100644 --- a/src/features/app/external-link.test.ts +++ b/src/features/app/external-link.test.ts @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { LINK_FAILURE, openExternalLink } from './external-link'; +import { GEO_HANDOFF_FAILURE, geoUri, LINK_FAILURE, openExternalLink, openInOtherApp } from './external-link'; async function attempt(url: string, open: (url: string) => Promise = async () => {}) { const opened: string[] = []; const reported: string[] = []; @@ -25,3 +25,15 @@ test('scheme-less place websites open over https', async () => { assert.deepEqual(await attempt(' example.it/menu?x=1 '), { opened: ['https://example.it/menu?x=1'], reported: [] }); assert.deepEqual(await attempt('mailto:a@example.it'), { opened: [], reported: [LINK_FAILURE] }, 'explicit non-web schemes stay rejected'); }); + +test('another app receives a geo: URI with coordinates and the Organic Maps label form', async () => { + const place = { name: 'Eataly Lingotto', coordinate: { latitude: 45.03535, longitude: 7.667453 } }; + assert.equal(geoUri(place), 'geo:45.035350,7.667453?q=45.035350,7.667453(Eataly%20Lingotto)'); + assert.equal(geoUri({ ...place, name: 'Caffè (Piazza) & Co' }), 'geo:45.035350,7.667453?q=45.035350,7.667453(Caff%C3%A8%20Piazza%20%26%20Co)'); + assert.equal(geoUri({ ...place, name: ' ' }), 'geo:45.035350,7.667453?q=45.035350,7.667453'); + const opened: string[] = []; const reported: string[] = []; + await openInOtherApp(place, async url => { opened.push(url); }, message => reported.push(message)); + await openInOtherApp(place, async () => { throw new Error('No Activity found'); }, message => reported.push(message)); + assert.deepEqual(opened, [geoUri(place)]); + assert.deepEqual(reported, [GEO_HANDOFF_FAILURE]); +}); diff --git a/src/features/app/external-link.ts b/src/features/app/external-link.ts index 8248519..57b2f3e 100644 --- a/src/features/app/external-link.ts +++ b/src/features/app/external-link.ts @@ -17,3 +17,26 @@ export async function openExternalLink(rawUrl: string, open: (url: string) => Pr report(LINK_FAILURE); } } + +export const GEO_HANDOFF_FAILURE = 'Nessuna app sul dispositivo può aprire questo luogo.'; + +/** + * An Android `geo:` URI for the system chooser: `geo:lat,lon?q=lat,lon(Name)`. Organic Maps reads the + * coordinates and the percent-encoded label from `q` (its geo URL parser tests cover this form); other + * map apps read at least the coordinates. Parentheses in the name would end the label, so they become spaces. + */ +export function geoUri(place: { name: string; coordinate: { latitude: number; longitude: number } }): string { + const lat = place.coordinate.latitude.toFixed(6); + const lon = place.coordinate.longitude.toFixed(6); + const label = encodeURIComponent(place.name.replace(/[()]/g, ' ').replace(/\s+/g, ' ').trim()); + return `geo:${lat},${lon}?q=${lat},${lon}${label ? `(${label})` : ''}`; +} + +/** Hands one place to another app on this device; nothing is sent to any service by this app. */ +export async function openInOtherApp(place: Parameters[0], open: (url: string) => Promise, report: (message: string) => void) { + try { + await open(geoUri(place)); + } catch { + report(GEO_HANDOFF_FAILURE); + } +} diff --git a/src/features/app/feedback.ts b/src/features/app/feedback.ts index f7e0206..116dba1 100644 --- a/src/features/app/feedback.ts +++ b/src/features/app/feedback.ts @@ -1,6 +1,7 @@ import { useCallback, useState } from 'react'; import { Linking } from 'react-native'; -import { openExternalLink } from './external-link'; +import { openExternalLink, openInOtherApp } from './external-link'; +import type { Place } from '../../domain/types'; import { createFeatureContext } from './feature-context'; export interface AppFeedback { @@ -10,13 +11,16 @@ export interface AppFeedback { dismiss(): void; /** Opens web and telephone links only, reporting failures in Italian. */ openLink(url: string): Promise; + /** Offers a place to the other map apps on the device through Android's geo: intent. */ + openInOtherApp(place: Pick): Promise; } export function useAppFeedback(): AppFeedback { const [message, setMessage] = useState(''); const dismiss = useCallback(() => setMessage(''), []); const openLink = useCallback((url: string) => openExternalLink(url, target => Linking.openURL(target), setMessage), []); - return { message, report: setMessage, dismiss, openLink }; + const handOff = useCallback((place: Pick) => openInOtherApp(place, target => Linking.openURL(target), setMessage), []); + return { message, report: setMessage, dismiss, openLink, openInOtherApp: handOff }; } export const [FeedbackProvider, useFeedback] = createFeatureContext('Feedback'); diff --git a/src/features/app/sheet-model.test.ts b/src/features/app/sheet-model.test.ts index fee2385..012d96e 100644 --- a/src/features/app/sheet-model.test.ts +++ b/src/features/app/sheet-model.test.ts @@ -1,7 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import type { Place, Stop } from '../../domain/types'; -import { defaultSnap, nextSnapDown, nextSnapUp, peekContentHeight, sheetBackStep, sheetHeaderNavigation, sheetHeights, SHEET_TOP_RESERVE, toggledSnap } from './sheet-model'; +import { defaultSnap, dismissesKeyboard, nextSnapDown, nextSnapUp, peekContentHeight, sheetBackStep, sheetHeaderNavigation, sheetHeights, SHEET_TOP_RESERVE, toggledSnap } from './sheet-model'; import { initialTaskState, taskReducer, type TaskAction, type TaskState } from './task-model'; const place: Place = { id: 'p', name: 'Mole Antonelliana', coordinate: { latitude: 45.069, longitude: 7.693 }, source: 'Test', attributions: [] }; @@ -74,3 +74,12 @@ test('a short window with shared heights keeps logical snaps, camera padding and assert.equal(toggledSnap('full', 'half', tall), 'peek', 'from the top, the control always moves the sheet'); assert.equal(sheetBackStep(run({ type: 'openTab', tab: 'transit' }, { type: 'openStop', stop }), 'full', 'half', tall), 'task', 'Back does not "collapse" to an identical height'); }); + +test('only the explicit expand control dismisses the keyboard; library-reported heights never do', () => { + assert.equal(dismissesKeyboard('half', 'full', true), true); + assert.equal(dismissesKeyboard(null, 'full', true), true); + // The keyboard opening over a results sheet makes the library report its highest snap. + assert.equal(dismissesKeyboard('half', 'full', false), false); + assert.equal(dismissesKeyboard('full', 'full', true), false); + assert.equal(dismissesKeyboard('full', 'half', true), false); +}); diff --git a/src/features/app/sheet-model.ts b/src/features/app/sheet-model.ts index 7a753ce..3173958 100644 --- a/src/features/app/sheet-model.ts +++ b/src/features/app/sheet-model.ts @@ -34,6 +34,8 @@ export function defaultSnap(tasks: TaskState, hasSearch: boolean): SheetSnap { case 'place': return 'peek'; case 'search': return hasSearch ? 'half' : 'peek'; case 'browse': return 'peek'; + // Searching for an endpoint needs room for results above the keyboard. + case 'planner': return top.editing ? 'full' : 'half'; default: return 'half'; } } @@ -80,3 +82,12 @@ export function sheetHeaderNavigation(tasks: TaskState): { back: boolean; close: const beneath = taskReducer(tasks, { type: 'closeTopTask' }); return { back: hasTaskAboveRoot(tasks) && sheetVisible(beneath), close: true }; } + +/** + * Expanding to full with the header control dismisses the keyboard so the whole sheet shows. A + * height the sheet library reports never does: when the keyboard opens over a sheet it reports its + * highest snap, and dismissing then blurred the search field the user had just tapped. + */ +export function dismissesKeyboard(current: SheetSnap | null, next: SheetSnap, explicit: boolean): boolean { + return explicit && next === 'full' && current !== 'full'; +} diff --git a/src/features/app/sheet.ts b/src/features/app/sheet.ts index eda3f1f..407d185 100644 --- a/src/features/app/sheet.ts +++ b/src/features/app/sheet.ts @@ -1,13 +1,16 @@ import { useCallback, useEffect, useRef, useState, type RefObject } from 'react'; import { Keyboard } from 'react-native'; import { createFeatureContext } from './feature-context'; -import type { SheetHeights, SheetSnap } from './sheet-model'; +import { dismissesKeyboard, type SheetHeights, type SheetSnap } from './sheet-model'; export interface SheetState { /** A height the user chose by dragging or the expand control; null rests at the task's default. */ requested: SheetSnap | null; - /** Records a height reached by gesture or chosen with the explicit controls. */ - request(snap: SheetSnap): void; + /** + * Records a height reached by gesture or chosen with the explicit controls. Only `explicit` + * requests (the header control) dismiss the keyboard when expanding to full. + */ + request(snap: SheetSnap, options?: { explicit?: boolean }): void; /** Returns to the task's resting height. */ collapse(): void; /** The heights currently laid out (set by the shell), for Back decisions outside rendering. */ @@ -21,9 +24,9 @@ export function useSheetState(contentKey: string): SheetState { const collapse = useCallback(() => setRequested(null), []); const current = useRef(null); current.current = requested; - const request = useCallback((snap: SheetSnap) => { + const request = useCallback((snap: SheetSnap, options?: { explicit?: boolean }) => { // Side effect outside the updater: React may run updaters during render, or twice in StrictMode. - if (current.current !== snap && snap === 'full') Keyboard.dismiss(); + if (dismissesKeyboard(current.current, snap, options?.explicit ?? false)) Keyboard.dismiss(); current.current = snap; setRequested(snap); }, []); diff --git a/src/features/app/task-model.test.ts b/src/features/app/task-model.test.ts index ed11946..5c493e2 100644 --- a/src/features/app/task-model.test.ts +++ b/src/features/app/task-model.test.ts @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import type { Coordinate, Place, Stop } from '../../domain/types'; +import { sheetHeaderNavigation } from './sheet-model'; import { boardInFront, boardStop, detailKey, hasTaskAboveRoot, initialTaskState, isValidTaskState, journeyStop, ORIGIN_LABELS, plannerInFront, plannerTask, selectedPlace, sheetVisible, taskReducer, topTask, type TaskAction, type TaskState, @@ -231,3 +232,55 @@ test('every reachable action sequence keeps a valid task stack', () => { for (let step = 0; step < 6; step++) state = taskReducer(state, { type: 'back' }); assert.deepEqual(kinds(state), ['browse'], 'Back always reaches the map'); }); + +test('planner endpoints: search either field, choose places, swap, and Back closes the editor first', () => { + let state = run({ type: 'openPlace', place: cafe }, { type: 'beginRoute', viewport, locating: true }, { type: 'originLocated', coordinate: here }, { type: 'editEndpoint', endpoint: 'destination' }); + assert.equal(plannerTask(state)!.editing, 'destination'); + assert.equal(detailKey(state), 'route:cafe:destination', 'The editor is its own sheet content'); + assert.deepEqual(kinds(taskReducer(state, { type: 'back' })), ['browse', 'place', 'planner'], 'Back closes the editor, not the planner'); + assert.equal(plannerTask(taskReducer(state, { type: 'back' }))!.editing, undefined); + // The sheet header's Back arrow does the same, keeping the planning session. + const arrow = taskReducer(state, { type: 'closeTopTask' }); + assert.deepEqual(kinds(arrow), ['browse', 'place', 'planner']); + assert.equal(plannerTask(arrow)!.editing, undefined); + assert.equal(plannerTask(arrow)!.session, plannerTask(state)!.session); + assert.equal(sheetHeaderNavigation(state).back, true, 'The arrow is shown while editing'); + + const session = plannerTask(state)!.session; + state = taskReducer(state, { type: 'setDestination', place: museum }); + assert.equal(plannerTask(state)!.session, session, 'The same planning session continues'); + assert.equal(plannerTask(state)!.destination.id, 'museum'); + assert.equal(plannerTask(state)!.editing, undefined); + assert.equal(plannerTask(state)!.origin.label, ORIGIN_LABELS.device, 'Changing the destination keeps the origin'); + assert.equal(selectedPlace(state)?.id, 'museum', 'The map marks the new destination'); + + // Swapping a device origin makes that fixed position the destination, labelled as such. + const swapped = taskReducer(state, { type: 'swapEndpoints' }); + assert.equal(plannerTask(swapped)!.origin.label, 'Museo'); + assert.equal(plannerTask(swapped)!.origin.place?.id, 'museum'); + assert.equal(plannerTask(swapped)!.destination.name, ORIGIN_LABELS.device); + assert.deepEqual(plannerTask(swapped)!.destination.coordinate, here); + // Swapping back restores the searched place's identity. + const twice = taskReducer(swapped, { type: 'swapEndpoints' }); + assert.equal(plannerTask(twice)!.destination.id, 'museum'); + assert.deepEqual(plannerTask(twice)!.origin.coordinate, here); + + state = run({ type: 'openPlace', place: cafe }, { type: 'beginRoute', viewport, locating: true }, { type: 'editEndpoint', endpoint: 'origin' }); + assert.equal(plannerTask(state)!.originStep, 'idle', 'Searching the origin replaces a pending fix'); + assert.equal(plannerTask(taskReducer(state, { type: 'originLocated', coordinate: here }))!.origin.ready, false, 'A late fix cannot override the search'); + assert.equal(taskReducer(state, { type: 'swapEndpoints' }), state, 'No swap without a settled origin'); + state = taskReducer(state, { type: 'setOriginPlace', place: museum }); + assert.deepEqual(plannerTask(state)!.origin, { coordinate: museum.coordinate, label: 'Museo', ready: true, place: museum }); + assert.equal(plannerInFront(state), true); + // Map picking and "La tua posizione" remain explicit choices from the origin editor. + const picking = run({ type: 'openPlace', place: cafe }, { type: 'beginRoute', viewport, locating: true }, { type: 'editEndpoint', endpoint: 'origin' }, { type: 'pickOrigin' }); + assert.equal(plannerTask(picking)!.originStep, 'picking'); + assert.equal(plannerTask(picking)!.editing, undefined); + const locating = taskReducer(taskReducer(picking, { type: 'editEndpoint', endpoint: 'origin' }), { type: 'locateOrigin' }); + assert.equal(plannerTask(locating)!.originStep, 'locating'); + assert.equal(plannerTask(locating)!.editing, undefined); + // Endpoint edits apply only to the planner in front. + const behind = run({ type: 'openPlace', place: cafe }, { type: 'beginRoute', viewport, locating: true }, { type: 'originLocated', coordinate: here }, { type: 'openJourneyStop', stop: porta }); + assert.equal(taskReducer(behind, { type: 'setDestination', place: museum }), behind); + assert.equal(taskReducer(behind, { type: 'editEndpoint', endpoint: 'origin' }), behind); +}); diff --git a/src/features/app/task-model.ts b/src/features/app/task-model.ts index c22464a..820e538 100644 --- a/src/features/app/task-model.ts +++ b/src/features/app/task-model.ts @@ -15,7 +15,9 @@ export type RootTab = 'browse' | 'transit' | 'saved'; /** idle: origin settled or unset; locating: awaiting a fresh fix; picking: awaiting a map tap. */ export type OriginStep = 'idle' | 'locating' | 'picking'; -export interface PlannerOrigin { coordinate: Coordinate; label: string; ready: boolean } +/** `place` is set when the origin was chosen from search or saved places (or swapped from the destination). */ +export interface PlannerOrigin { coordinate: Coordinate; label: string; ready: boolean; place?: Place } +export type PlannerEndpoint = 'origin' | 'destination'; export interface PlannerTask { kind: 'planner'; /** Changes whenever a different planning session replaces this one. */ @@ -23,6 +25,8 @@ export interface PlannerTask { destination: Place; origin: PlannerOrigin; originStep: OriginStep; + /** The origin or destination field being searched; absent while neither is edited. */ + editing?: PlannerEndpoint; } export interface PlaceTask { kind: 'place'; place: Place } export interface StopTask { kind: 'stop'; stop: Stop } @@ -75,6 +79,15 @@ export type TaskAction = | { type: 'pickOrigin' } | { type: 'setOrigin'; coordinate: Coordinate } | { type: 'cancelOriginPicking' } + /** Opens the search field for the planner's origin or destination. */ + | { type: 'editEndpoint'; endpoint: PlannerEndpoint } + | { type: 'closeEndpointEditor' } + /** A searched or saved place becomes the origin. */ + | { type: 'setOriginPlace'; place: Place } + /** A searched or saved place becomes the destination, keeping the origin. */ + | { type: 'setDestination'; place: Place } + /** Exchanges a settled origin and the destination. */ + | { type: 'swapEndpoints' } | { type: 'setTravelMode'; mode: TravelMode } | { type: 'setTransitTime'; transitTime: TransitTime } | { type: 'openJourneyStop'; stop: Stop } @@ -115,12 +128,34 @@ function sameCoordinate(a: Coordinate, b: Coordinate) { } function closeTop(state: TaskState): TaskState { if (state.settings) return { ...state, settings: false }; + // An open endpoint editor is the top step: closing it returns to the plan, for Back and the sheet arrow alike. + const top = last(state.details); + if (top?.kind === 'planner' && top.editing) return updatePlanner(state, withoutEditor); if (state.details.length) return { ...state, details: state.details.slice(0, -1) }; return state.root.kind === 'browse' ? state : { ...state, root: browse }; } function cancelPicking(planner: PlannerTask): PlannerTask | null { return planner.origin.ready ? { ...planner, originStep: 'idle' } : null; } +function withoutEditor(planner: PlannerTask): PlannerTask { + if (!planner.editing) return planner; + const next = { ...planner }; + delete next.editing; + return next; +} +/** Endpoint edits apply only while the planner is the task in front. */ +function updateFrontPlanner(state: TaskState, update: (planner: PlannerTask) => PlannerTask): TaskState { + return topTask(state).kind === 'planner' ? updatePlanner(state, update) : state; +} +/** The origin as a destination: a chosen place keeps its identity; a position or map point gets a stable id. */ +function originAsPlace(origin: PlannerOrigin): Place { + if (origin.place) return origin.place; + const { latitude, longitude } = origin.coordinate; + return { + id: `point:${latitude.toFixed(6)},${longitude.toFixed(6)}`, name: origin.label, coordinate: { ...origin.coordinate }, + source: origin.label === ORIGIN_LABELS.device ? 'Posizione del dispositivo al momento dell’inversione' : 'Punto scelto sulla mappa', attributions: [], + }; +} export function taskReducer(state: TaskState, action: TaskAction): TaskState { switch (action.type) { @@ -169,7 +204,7 @@ export function taskReducer(state: TaskState, action: TaskAction): TaskState { const index = state.details.findIndex(task => task.kind === 'planner'); if (index < 0) return state; const trimmed = { ...state, details: state.details.slice(0, index + 1) }; - return updatePlanner(trimmed, planner => ({ ...planner, origin: { ...planner.origin, ready: false }, originStep: 'locating' })); + return updatePlanner(trimmed, planner => ({ ...withoutEditor(planner), origin: { ...planner.origin, ready: false }, originStep: 'locating' })); } case 'originLocated': return updatePlanner(state, planner => planner.originStep !== 'locating' ? planner @@ -179,12 +214,32 @@ export function taskReducer(state: TaskState, action: TaskAction): TaskState { case 'locationRequestCancelled': return updatePlanner(state, planner => planner.originStep === 'locating' ? { ...planner, originStep: 'idle' } : planner); case 'pickOrigin': - return updatePlanner(state, planner => planner.originStep === 'picking' ? planner : { ...planner, originStep: 'picking' }); + return updatePlanner(state, planner => planner.originStep === 'picking' && !planner.editing ? planner : { ...withoutEditor(planner), originStep: 'picking' }); case 'setOrigin': return updatePlanner(state, planner => planner.originStep !== 'picking' ? planner : { ...planner, origin: { coordinate: action.coordinate, label: ORIGIN_LABELS.map, ready: true }, originStep: 'idle' }); case 'cancelOriginPicking': return updatePlanner(state, planner => planner.originStep === 'picking' ? cancelPicking(planner) : planner); + case 'editEndpoint': + return updateFrontPlanner(state, planner => planner.editing === action.endpoint ? planner : { + ...planner, editing: action.endpoint, + // Searching for an origin replaces a pending fix or map tap; the current origin stays until one is chosen. + originStep: action.endpoint === 'origin' ? 'idle' : planner.originStep, + }); + case 'closeEndpointEditor': + return updatePlanner(state, withoutEditor); + case 'setOriginPlace': + return updateFrontPlanner(state, planner => ({ + ...withoutEditor(planner), originStep: 'idle', + origin: { coordinate: { ...action.place.coordinate }, label: action.place.name, ready: true, place: action.place }, + })); + case 'setDestination': + return updateFrontPlanner(state, planner => ({ ...withoutEditor(planner), destination: action.place })); + case 'swapEndpoints': + return updateFrontPlanner(state, planner => !planner.origin.ready || planner.originStep !== 'idle' ? planner : { + ...withoutEditor(planner), destination: originAsPlace(planner.origin), + origin: { coordinate: { ...planner.destination.coordinate }, label: planner.destination.name, ready: true, place: planner.destination }, + }); case 'setTravelMode': return state.travel.mode === action.mode ? state : { ...state, travel: { ...state.travel, mode: action.mode } }; case 'setTransitTime': @@ -200,7 +255,7 @@ export function taskReducer(state: TaskState, action: TaskAction): TaskState { return closeTop(state); case 'back': { const top = topTask(state); - if (top.kind === 'planner' && top.originStep === 'picking') return updatePlanner(state, cancelPicking); + if (top.kind === 'planner' && top.originStep === 'picking' && !top.editing) return updatePlanner(state, cancelPicking); return closeTop(state); } } @@ -257,7 +312,8 @@ export function detailKey(state: TaskState): string { switch (top.kind) { case 'settings': return 'privacy'; case 'journeyStop': return `journey-stop:${top.stop.id}`; - case 'planner': return `route:${top.destination.id}`; + // The endpoint editor is its own content: it opens raised for typing and returns to the plan. + case 'planner': return `route:${top.destination.id}${top.editing ? `:${top.editing}` : ''}`; case 'stop': return `stop:${top.stop.id}`; case 'place': return `place:${top.place.id}`; case 'transit': case 'saved': return `list:${top.kind}`; diff --git a/src/features/app/useAndroidBack.ts b/src/features/app/useAndroidBack.ts index dba28b0..56a738c 100644 --- a/src/features/app/useAndroidBack.ts +++ b/src/features/app/useAndroidBack.ts @@ -32,7 +32,7 @@ export function useAndroidBack(dependencies: { if (step === 'exit') return false; if (hasTaskAboveRoot(state)) { const top = topTask(state); - if (top.kind === 'planner' && top.originStep !== 'picking') location.cancel(); + if (top.kind === 'planner' && top.originStep !== 'picking' && !top.editing) location.cancel(); tasks.dispatch({ type: 'back' }); return true; } diff --git a/src/features/app/useShellActions.ts b/src/features/app/useShellActions.ts index ffbcdb8..2feeca0 100644 --- a/src/features/app/useShellActions.ts +++ b/src/features/app/useShellActions.ts @@ -38,7 +38,9 @@ export function useShellController({ tasks, camera, location, sheet, search }: { const closeTopTask = useCallback(() => { const state = getState(); if (!hasTaskAboveRoot(state)) { closeTask(); return; } - if (topTask(state).kind === 'planner') location.cancel(); + const top = topTask(state); + // Closing the endpoint editor keeps the planner and any pending origin fix. + if (top.kind === 'planner' && !top.editing) location.cancel(); dispatch({ type: 'closeTopTask' }); }, [getState, closeTask, location, dispatch]); const toggleSettings = useCallback(() => { diff --git a/src/features/map/MapCanvas.native.tsx b/src/features/map/MapCanvas.native.tsx index 2a9bf9d..d37b716 100644 --- a/src/features/map/MapCanvas.native.tsx +++ b/src/features/map/MapCanvas.native.tsx @@ -6,7 +6,7 @@ import type { FeatureCollection, Point } from 'geojson'; import { useTheme } from '../../theme'; import { diagnostics } from '../../services/diagnostics'; import type { MapCanvasProps } from './MapCanvas.types'; -import { createOnceFraming, createRouteFraming } from './map-presentation'; +import { createOnceFraming, createRouteFraming, frameCamera } from './map-presentation'; import { lineLayout, markerLabelLayout, overlayPaint } from './map-overlay-style'; /** @@ -24,6 +24,7 @@ export default function MapCanvas({ center, zoom = 14.5, cameraRevision, routeFi const commands = useRef(0); const padding = useRef(cameraPadding); padding.current = cameraPadding; const camera = useRef(null); + const size = useRef({ width: 412, height: 800 }); const [mapError, setMapError] = useState(false); const [longitude, latitude] = center; const coverage = useMemo(() => { @@ -51,7 +52,10 @@ export default function MapCanvas({ center, zoom = 14.5, cameraRevision, routeFi useEffect(() => { if (!loaded || !resultFraming.current.claim(frameKey, !!frameBounds) || !frameBounds) return; commands.current += 1; - camera.current?.fitBounds(frameBounds, { padding: padding.current ?? { top: 50, right: 50, bottom: 50, left: 50 }, duration: 500 }); + // fitBounds has no zoom cap here, and padding taller than the map zoomed to the maximum (a blank + // building interior for two results 30 m apart): ease to a computed, capped camera instead. + const inset = padding.current ?? { top: 50, right: 50, bottom: 50, left: 50 }; + camera.current?.easeTo({ ...frameCamera(frameBounds, size.current, inset), padding: inset, duration: 500 }); }, [loaded, frameKey, frameBounds]); useEffect(() => { if (followLocation !== false) { commands.current += 1; camera.current?.easeTo({ center: [longitude, latitude], zoom, padding: padding.current, duration: 450 }); } }, [longitude, latitude, zoom, followLocation, cameraRevision]); useEffect(() => { @@ -60,7 +64,7 @@ export default function MapCanvas({ center, zoom = 14.5, cameraRevision, routeFi commands.current += 1; camera.current?.fitBounds([Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)], { padding: padding.current ?? { top: 50, right: 50, bottom: 50, left: 50 }, duration: 500 }); }, [route, routeFitKey, followLocation]); - return + return { size.current = event.nativeEvent.layout; }}> onMapPress?.(event.nativeEvent.lngLat)} // A user gesture outranks a pending padding re-centre (see `commands`). diff --git a/src/features/map/MapCanvas.web.tsx b/src/features/map/MapCanvas.web.tsx index 8ec614f..57ea3ea 100644 --- a/src/features/map/MapCanvas.web.tsx +++ b/src/features/map/MapCanvas.web.tsx @@ -5,7 +5,7 @@ import 'maplibre-gl/dist/maplibre-gl.css'; import { useTheme, type MapColors } from '../../theme'; import { diagnostics } from '../../services/diagnostics'; import type { MapCanvasProps } from './MapCanvas.types'; -import { createOnceFraming, createRouteFraming } from './map-presentation'; +import { createOnceFraming, createRouteFraming, RESULT_MAX_ZOOM } from './map-presentation'; import { lineLayout, markerLabelLayout, overlayPaint } from './map-overlay-style'; const APP_SOURCES = ['local-coverage', 'journey', 'places', 'position'] as const; @@ -53,11 +53,11 @@ export default function MapCanvas(props: MapCanvasProps) { * GL JS adds fitBounds padding to the map's own padding, which the effect below keeps equal to the * camera padding. Apply the current padding first, then fit with a small margin inside it. */ - const fitWithinPadding = useCallback((instance: WebMap | null, bounds: [number, number, number, number]) => { + const fitWithinPadding = useCallback((instance: WebMap | null, bounds: [number, number, number, number], maxZoom?: number) => { if (!instance) return; const padding = latest.current.cameraPadding; if (padding) instance.setPadding(padding); - instance.fitBounds(bounds, { padding: padding ? 24 : 50, duration: 500 }); + instance.fitBounds(bounds, { padding: padding ? 24 : 50, duration: 500, ...(maxZoom === undefined ? {} : { maxZoom }) }); }, []); const syncData = useCallback(() => { const instance = map.current; @@ -122,7 +122,7 @@ export default function MapCanvas(props: MapCanvasProps) { const frameBounds = props.resultFrame?.ready ? props.resultFrame.bounds : null; useEffect(() => { if (!loaded || !resultFraming.current.claim(frameKey, !!frameBounds) || !frameBounds) return; - fitWithinPadding(map.current, frameBounds); + fitWithinPadding(map.current, frameBounds, RESULT_MAX_ZOOM); }, [loaded, frameKey, frameBounds, fitWithinPadding]); useEffect(() => { if (loaded && followLocation !== false) map.current?.easeTo({ center: [longitude, latitude], zoom, padding: latest.current.cameraPadding, duration: 450 }); }, [loaded, longitude, latitude, zoom, followLocation, cameraRevision]); useEffect(() => { if (loaded) syncData(); }, [loaded, syncData, props.coverageBounds, props.markers, props.selectedMarkerId, props.userLocation, props.route]); diff --git a/src/features/map/map-presentation.test.ts b/src/features/map/map-presentation.test.ts index 174788c..283a739 100644 --- a/src/features/map/map-presentation.test.ts +++ b/src/features/map/map-presentation.test.ts @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { createRouteFraming, mapCameraPadding } from './map-presentation'; +import { createRouteFraming, frameCamera, mapCameraPadding, RESULT_MAX_ZOOM, resultFrameBounds } from './map-presentation'; test('refreshes and late responses respect manual map browsing; an explicit frame still works', () => { const camera = createRouteFraming(); @@ -51,3 +51,19 @@ test('result frames fire once per submitted search and survive leaving and retur assert.equal(frames.claim('results:2', true), false, 'a pan before results arrive keeps the user view'); assert.equal(frames.claim('results:3', true), true); }); + +test('results metres apart frame a readable street area, never the maximum zoom', () => { + // Eataly and Eataly Green Pea, Via Nizza 224/230, about 30 m apart. + const bounds = resultFrameBounds([{ latitude: 45.03535, longitude: 7.667453 }, { latitude: 45.035464, longitude: 7.6666 }], { latitude: 45.07, longitude: 7.68 })!; + assert.ok(bounds[2] - bounds[0] >= 0.004 && bounds[3] - bounds[1] >= 0.004, 'a minimum span around near-identical results'); + const view = { width: 412, height: 915 }; + const open = frameCamera(bounds, view, { top: 120, bottom: 420, left: 0, right: 0 }); + assert.ok(open.zoom <= RESULT_MAX_ZOOM && open.zoom > 14, `zoom ${open.zoom}`); + assert.ok(Math.abs(open.center[0] - 7.6670265) < 1e-6 && Math.abs(open.center[1] - 45.035407) < 1e-4); + // A full sheet plus keyboard can pad more than the map's height: the fit still stays capped. + const crushed = frameCamera(bounds, view, { top: 136, bottom: 900 }); + assert.ok(Number.isFinite(crushed.zoom) && crushed.zoom <= RESULT_MAX_ZOOM); + assert.equal(frameCamera([7.6666, 45.0354, 7.6667, 45.0355], view).zoom, RESULT_MAX_ZOOM, 'a tiny box is capped'); + // A wide box still fits rather than being capped. + assert.ok(frameCamera([7.6, 45.0, 7.77, 45.14], view).zoom < 12); +}); diff --git a/src/features/map/map-presentation.ts b/src/features/map/map-presentation.ts index b9842ff..49ff0a4 100644 --- a/src/features/map/map-presentation.ts +++ b/src/features/map/map-presentation.ts @@ -47,6 +47,27 @@ export function resultFrameBounds(points: readonly { latitude: number; longitude return [west - padLongitude, south - padLatitude, east + padLongitude, north + padLatitude]; } +/** Closest zoom a result frame may reach: streets and labels stay readable around one or near-identical results. */ +export const RESULT_MAX_ZOOM = 17; +const MIN_FIT_PIXELS = 96; +const mercatorY = (latitude: number) => Math.log(Math.tan(Math.PI / 4 + (latitude * Math.PI) / 360)); +const latitudeOf = (y: number) => (360 / Math.PI) * Math.atan(Math.exp(y)) - 90; + +/** + * The camera that fits `bounds` inside the padded viewport (MapLibre 512 px tiles), capped at + * `maxZoom`. The fitted area never shrinks below a minimum, so a sheet or keyboard padding larger + * than the map cannot drive the zoom to the maximum. + */ +export function frameCamera(bounds: Bounds, size: { width: number; height: number }, padding: { top?: number; right?: number; bottom?: number; left?: number } = {}, maxZoom = RESULT_MAX_ZOOM): { center: [number, number]; zoom: number } { + const [west, south, east, north] = bounds; + const width = Math.max(MIN_FIT_PIXELS, size.width - (padding.left ?? 0) - (padding.right ?? 0)); + const height = Math.max(MIN_FIT_PIXELS, size.height - (padding.top ?? 0) - (padding.bottom ?? 0)); + const spanX = Math.max(1e-9, (east - west) / 360); + const spanY = Math.max(1e-9, (mercatorY(north) - mercatorY(south)) / (2 * Math.PI)); + const zoom = Math.min(maxZoom, Math.log2(Math.min(width / (spanX * 512), height / (spanY * 512)))); + return { center: [(west + east) / 2, latitudeOf((mercatorY(north) + mercatorY(south)) / 2)], zoom: Math.max(0, zoom) }; +} + /** * One-shot framing for keys that only grow (submitted searches). Unlike route framing, an absent key * does not reset it: leaving and returning to a search the user already framed (or panned) never diff --git a/src/features/places/PlaceDetail.tsx b/src/features/places/PlaceDetail.tsx index ee76528..9ff6672 100644 --- a/src/features/places/PlaceDetail.tsx +++ b/src/features/places/PlaceDetail.tsx @@ -7,20 +7,24 @@ import { useDistanceReference } from "../map/useDistanceReference"; import { useFeedback } from "../app/feedback"; import { usePlannerContext } from "../planner/usePlanner"; import { placeCategoryLabel } from "./category-label"; +import { confidenceLabel, freshnessLabel, sourceLines, websiteLabel } from "./place-detail-model"; import { usePlacesContext } from "./usePlaces"; export function PlaceDetail({ place }: { place: Place }) { const { isSaved, toggleSaved } = usePlacesContext(); const { beginRoute } = usePlannerContext(); - const { openLink } = useFeedback(); + const { openLink, openInOtherApp } = useFeedback(); const saved = isSaved(place.id); // A selected place shows a distance only from a fresh device fix (see distance-reference.ts). const distance = detailDistance(useDistanceReference(), place.coordinate); + const category = placeCategoryLabel(place.category); + const confidence = confidenceLabel(place); return ( - {placeCategoryLabel(place.category)}{distance ? <> · {distance.value} : null} + {category}{distance ? <> · {distance.value} : null} {place.address ? {place.address} : null} + {place.kind === "area" ? Posizione indicativa del quartiere, non un confine. : null} @@ -29,17 +33,21 @@ export function PlaceDetail({ place }: { place: Place }) { - {place.website ? openLink(place.website!)} /> : null} + {place.website ? openLink(place.website!)} /> : null} {place.phone ? openLink(`tel:${place.phone}`)} /> : null} + { void openInOtherApp(place); }} /> - - Orari non disponibili - - Fonte: {place.source} - {place.dataUpdatedAt ? `\nDati del ${place.dataUpdatedAt}` : ""} - {place.attributions.length ? `\n${place.attributions.join("\n")}` : ""} - + + {/* No bundled or online source supplies opening hours; unknown stays unknown. */} + Orari di apertura non disponibili nelle fonti usate. + {confidence ? {confidence} : null} + {freshnessLabel(place)} + + Fonte: {place.source} + {sourceLines(place).map((line, index) => {line})} + diff --git a/src/features/places/PlaceRow.tsx b/src/features/places/PlaceRow.tsx index f4a79ff..9cd4edd 100644 --- a/src/features/places/PlaceRow.tsx +++ b/src/features/places/PlaceRow.tsx @@ -5,7 +5,11 @@ import { Icon, ListRow, type IconName } from "../../ui"; import { distanceFrom, type DistanceReference } from "../map/distance-reference"; import { placeCategoryLabel } from "./category-label"; -function placeIcon(place: Place): IconName { +export function placeIcon(place: Place): IconName { + if (place.kind === "address") return "home-outline"; + if (place.kind === "street") return "trail-sign-outline"; + if (place.kind === "area") return "map-outline"; + if (place.category === "Fermata GTT") return "bus-outline"; const label = `${place.name} ${place.category ?? ""}`.toLowerCase(); return /bar|caff|caf|coffee/.test(label) ? "cafe-outline" : /shop|nego|cloth|abbigl/.test(label) ? "bag-handle-outline" diff --git a/src/features/places/place-detail-model.test.ts b/src/features/places/place-detail-model.test.ts new file mode 100644 index 0000000..2ef5220 --- /dev/null +++ b/src/features/places/place-detail-model.test.ts @@ -0,0 +1,42 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { confidenceLabel, freshnessLabel, sourceDate, sourceLines, websiteLabel } from './place-detail-model'; + +test('websites read without scheme, www or trailing slash', () => { + assert.equal(websiteLabel('https://www.eataly.net/it_it/negozi/torino-lagrange'), 'eataly.net/it_it/negozi/torino-lagrange'); + assert.equal(websiteLabel('http://example.it/'), 'example.it'); + assert.equal(websiteLabel('example.it/menu'), 'example.it/menu'); +}); + +test('source dates keep the upstream date part, with or without a timezone', () => { + assert.equal(sourceDate('2026-09-17T22:52:12Z'), '17/09/2026'); + assert.equal(sourceDate('2022-02-03T08:09:10'), '03/02/2022'); + assert.equal(sourceDate(''), null); + assert.equal(sourceDate(null), null); + assert.equal(freshnessLabel({ dataUpdatedAt: '' }), 'Data di aggiornamento non indicata dalla fonte'); + assert.equal(freshnessLabel({ dataUpdatedAt: '2026-09-17T22:52:12Z' }), 'Ultimo aggiornamento indicato dalle fonti: 17/09/2026'); +}); + +test('each contributing record is listed with the field it supplied, its licence and its date', () => { + const lines = sourceLines({ + provenance: [ + { dataset: 'meta', license: 'CDLA-Permissive-2.0', property: '', update_time: '2026-09-14T00:00:00.000Z' }, + { dataset: 'Overture', license: 'CDLA-Permissive-2.0', property: '/properties/confidence', update_time: '2026-09-17T22:52:12Z' }, + { dataset: 'Foursquare', license: 'Apache-2.0', property: '/properties/phones/0', update_time: null }, + ], + attributions: ['meta · CDLA-Permissive-2.0', 'Overture · CDLA-Permissive-2.0', 'Foursquare · Apache-2.0', 'Telefono corretto da sito ufficiale · https://example.it/ · 2026-10-11'], + }); + assert.deepEqual(lines, [ + 'meta · CDLA-Permissive-2.0 · aggiornato il 14/09/2026', + 'Overture (affidabilità) · CDLA-Permissive-2.0 · aggiornato il 17/09/2026', + 'Foursquare (telefono) · Apache-2.0 · data non indicata', + 'Telefono corretto da sito ufficiale · https://example.it/ · 2026-10-11', + ]); + assert.deepEqual(sourceLines({ attributions: ['© OpenStreetMap contributors · ODbL'] }), ['© OpenStreetMap contributors · ODbL']); +}); + +test('confidence is an existence estimate for Overture records only', () => { + assert.equal(confidenceLabel({ confidence: 0.7602, source: 'Overture Places' }), 'Esistenza stimata da Overture: 76% (non indica se è aperto ora)'); + assert.equal(confidenceLabel({ confidence: 0.9, source: 'Photon / OpenStreetMap' }), null); + assert.equal(confidenceLabel({ confidence: null, source: 'Overture Places' }), null); +}); diff --git a/src/features/places/place-detail-model.ts b/src/features/places/place-detail-model.ts new file mode 100644 index 0000000..5d76a81 --- /dev/null +++ b/src/features/places/place-detail-model.ts @@ -0,0 +1,46 @@ +import type { Place } from '../../domain/types'; + +/** A website as people read it: no scheme, "www." or trailing slash. */ +export function websiteLabel(url: string): string { + return url.trim().replace(/^https?:\/\//i, '').replace(/^www\./i, '').replace(/\/$/, ''); +} + +/** An upstream date shown as written (dd/mm/yyyy of its date part); no timezone conversion is implied. */ +export function sourceDate(value: unknown): string | null { + const match = typeof value === 'string' ? /^(\d{4})-(\d{2})-(\d{2})/.exec(value) : null; + return match ? `${match[3]}/${match[2]}/${match[1]}` : null; +} + +const FIELD_LABELS: Record = { + confidence: 'affidabilità', websites: 'sito web', phones: 'telefono', addresses: 'indirizzo', names: 'nome', + categories: 'categoria', taxonomy: 'categoria', brand: 'marchio', emails: 'email', socials: 'profili social', operating_status: 'stato', +}; +const text = (value: unknown) => typeof value === 'string' && value.trim() ? value.trim() : null; + +/** One line per contributing source record, with the field it supplied, its licence and its own date. */ +export function sourceLines(place: Pick): string[] { + if (!place.provenance?.length) return [...place.attributions]; + const lines = place.provenance.map(source => { + const property = text(source.property)?.replace(/^\/properties\//, '').split('/')[0]; + const date = sourceDate(source.update_time); + return [ + `${text(source.dataset) ?? 'Fonte'}${property ? ` (${FIELD_LABELS[property] ?? property})` : ''}`, + text(source.license), date ? `aggiornato il ${date}` : 'data non indicata', + ].filter(Boolean).join(' · '); + }); + // Notices that are not source records (such as a checked phone correction) stay listed too. + const datasets = new Set(place.provenance.map(source => `${text(source.dataset)} · ${text(source.license)}`)); + return [...new Set([...lines, ...place.attributions.filter(notice => !datasets.has(notice))])]; +} + +/** The freshest date any source states for the record, or an explicit absence. */ +export function freshnessLabel(place: Pick): string { + const date = sourceDate(place.dataUpdatedAt); + return date ? `Ultimo aggiornamento indicato dalle fonti: ${date}` : 'Data di aggiornamento non indicata dalla fonte'; +} + +/** Overture's confidence estimates that the place exists; it never means "open now". */ +export function confidenceLabel(place: Pick): string | null { + if (typeof place.confidence !== 'number' || !Number.isFinite(place.confidence) || !place.source.startsWith('Overture')) return null; + return `Esistenza stimata da Overture: ${Math.round(place.confidence * 100)}% (non indica se è aperto ora)`; +} diff --git a/src/features/planner/EndpointEditor.tsx b/src/features/planner/EndpointEditor.tsx new file mode 100644 index 0000000..a75f2b8 --- /dev/null +++ b/src/features/planner/EndpointEditor.tsx @@ -0,0 +1,87 @@ +import { useState } from 'react'; +import { ActivityIndicator, TextInput, View } from 'react-native'; +import type { Place } from '../../domain/types'; +import { useThemeColors } from '../../theme'; +import { Icon, IconButton, ListRow, Notice, SectionHeader, useHairlines } from '../../ui'; +import { Text } from '../../ui/Text'; +import type { PlannerEndpoint } from '../app/task-model'; +import { useDistanceReference } from '../map/useDistanceReference'; +import { useMapContext } from '../map/useMapModel'; +import { PlaceRow } from '../places/PlaceRow'; +import { usePlacesContext } from '../places/usePlaces'; +import { usePlaceLookup } from '../search/usePlaceLookup'; +import { usePlannerContext } from './usePlanner'; + +/** + * Searching for the origin or destination inside the planner: the same local, Photon (when allowed) + * and stop search as the main field, plus saved places; for the origin also the device position and + * a tap on the map. + */ +export function EndpointEditor({ endpoint, current }: { endpoint: PlannerEndpoint; current: Place | null }) { + const colors = useThemeColors(); + const hairlines = useHairlines(); + const planner = usePlannerContext(); + const { locate, camera } = useMapContext(); + const { saved, isSaved } = usePlacesContext(); + const reference = useDistanceReference(); + const [query, setQuery] = useState(''); + const lookup = usePlaceLookup(query, camera.searchCenter, true); + const origin = endpoint === 'origin'; + // A one-character stop code or line ("4") already yields stops. + const typed = query.trim().length >= 2 || lookup.places.length > 0; + const choose = (place: Place) => planner.chooseEndpoint(place); + const suggestions = saved.filter(place => place.id !== current?.id).slice(0, 6); + return ( + + + {/* Editable fields need a 3:1 boundary (WCAG 1.4.11); the decorative hairline is about 1.2:1. */} + + + { if (lookup.places[0]) choose(lookup.places[0]); }} + /> + {lookup.searching ? : null} + {query ? setQuery('')} /> : null} + + + {!typed ? ( + + {origin ? <> + { void locate(); }} /> + + : null} + {suggestions.length ? <> + + {suggestions.map(place => choose(place)} />)} + : null} + + {lookup.policy === 'local-only' ? 'Solo ricerca locale: il testo resta sul dispositivo.' : 'Luoghi e fermate locali; nomi e indirizzi anche con Photon / OpenStreetMap.'} + + + ) : ( + + {lookup.error ? : null} + {lookup.places.map(place => choose(place)} />)} + {!lookup.places.length && !lookup.searching ? ( + + + {lookup.policy === 'local-only' ? 'Nessuna corrispondenza locale. La ricerca online è disattivata.' : 'Nessuna corrispondenza. I dati possono essere incompleti.'} + + ) : null} + {lookup.policy === 'local-only' ? Solo ricerca locale : null} + + )} + + ); +} diff --git a/src/features/planner/JourneyPlanner.tsx b/src/features/planner/JourneyPlanner.tsx index 3516a00..c9b8643 100644 --- a/src/features/planner/JourneyPlanner.tsx +++ b/src/features/planner/JourneyPlanner.tsx @@ -1,93 +1,13 @@ -import { useReducer, useState } from 'react'; -import { Keyboard, Pressable, TextInput, View } from 'react-native'; +import { Pressable, View } from 'react-native'; import { Text } from '../../ui/Text'; import type { RouteLeg, RoutePlan, RouteStop, Stop, TransitTime } from '../../domain/types'; import { useThemeColors } from '../../theme'; -import { Button, Chip, Disclosure, Icon, Notice, Num, SegmentedControl, TransitLineBadge, transitModeFromLeg, useHairlines } from '../../ui'; +import { Button, Disclosure, Icon, Notice, Num, TransitLineBadge, transitModeFromLeg, useHairlines } from '../../ui'; import { matchJourneyStop } from '../../services/transit-stop-matching'; import { - createTransitTimeDraft, draftTransitTime, italianDate, journeyDate, journeyDistance, journeyDuration, - journeyTime, journeyTimingLabel, nextRomeDate, savedJourneyTimeLabel, transitTimeDraftReducer, transitTimeLabel, waitBefore, + journeyDate, journeyDistance, journeyDuration, journeyTime, journeyTimingLabel, savedJourneyTimeLabel, transitTimeLabel, waitBefore, } from './journey-presentation'; -const timeModes: { kind: TransitTime['kind']; label: string }[] = [ - { kind: 'now', label: 'Adesso' }, { kind: 'depart-at', label: 'Parti alle' }, { kind: 'arrive-by', label: 'Arriva entro' }, -]; - -export function TransitTimeForm({ value, onSubmit, disabled }: { - value: TransitTime; onSubmit: (value: TransitTime) => void; disabled: boolean; -}) { - const [{ kind, date, time }, updateDraft] = useReducer(transitTimeDraftReducer, value, createTransitTimeDraft); - const [error, setError] = useState(''); - const colors = useThemeColors(); - // Editable fields need a 3:1 boundary (WCAG 1.4.11); the decorative hairline is about 1.2:1. - const inputBorder = { borderWidth: 1, borderColor: colors.textSecondary }; - function submit() { - try { - const next = draftTransitTime(kind, date.trim(), time.trim()); - updateDraft({ type: 'submitted', value: next, now: new Date() }); - setError(''); - Keyboard.dismiss(); - onSubmit(next); - } catch (failure) { - setError(failure instanceof Error ? failure.message : 'Controlla data e orario.'); - } - } - return ( - - ({ value: item.kind, label: item.label }))} value={kind} - onChange={next => { updateDraft({ type: 'kind', kind: next, now: new Date() }); setError(''); }} /> - {kind !== 'now' ? ( - <> - - {[{ label: 'Oggi', days: 0 }, { label: 'Domani', days: 1 }].map(item => ( - { updateDraft({ type: 'date', value: italianDate(nextRomeDate(item.days)) }); setError(''); }} /> - ))} - - - - Data (gg/mm/aaaa) - { updateDraft({ type: 'date', value: text }); setError(''); }} - placeholder="gg/mm/aaaa" - autoCorrect={false} - inputMode="text" - maxLength={10} - placeholderTextColor={colors.textSecondary} - style={inputBorder} - className="min-h-12 min-w-0 rounded-xl px-3 py-2 font-mono text-base text-primary" - /> - - - Ora (HH:mm) - { updateDraft({ type: 'time', value: text }); setError(''); }} - placeholder="HH:mm" - autoCorrect={false} - inputMode="text" - maxLength={5} - returnKeyType="search" - onSubmitEditing={disabled ? undefined : submit} - placeholderTextColor={colors.textSecondary} - style={inputBorder} - className="min-h-12 min-w-0 rounded-xl px-3 py-2 font-mono text-base text-primary" - /> - - - - ) : null} - Ora italiana - {error ? : null} - - - ); -} - function stopLabel(stop: RouteStop | undefined, fallback: string) { return `${stop?.name ?? fallback}${stop?.code ? ` · fermata ${stop.code}` : ''}${stop?.platformCode ? ` · banchina ${stop.platformCode}` : ''}`; } diff --git a/src/features/planner/PlannerEndpoints.tsx b/src/features/planner/PlannerEndpoints.tsx new file mode 100644 index 0000000..efe7633 --- /dev/null +++ b/src/features/planner/PlannerEndpoints.tsx @@ -0,0 +1,49 @@ +import { View } from 'react-native'; +import { useThemeColors } from '../../theme'; +import { IconButton, useHairlines } from '../../ui'; +import { PressableSurface } from '../../ui/PressableSurface'; +import { Text } from '../../ui/Text'; +import { ORIGIN_LABELS, type PlannerEndpoint, type PlannerTask } from '../app/task-model'; +import { usePlannerContext } from './usePlanner'; + +/** Origin and destination as two editable fields, with the swap between them. */ +export function PlannerEndpoints({ task }: { task: PlannerTask }) { + const planner = usePlannerContext(); + const hairlines = useHairlines(); + const colors = useThemeColors(); + const origin = task.originStep === 'locating' ? 'Cerco la tua posizione…' + : task.originStep === 'picking' ? 'Tocca la mappa per la partenza' + : task.origin.ready ? task.origin.label : ORIGIN_LABELS.unset; + const canSwap = task.origin.ready && task.originStep === 'idle'; + return ( + // The two fields are editable controls: a 3:1 outline (WCAG 1.4.11), a hairline between them. + + + planner.editEndpoint('origin')} /> + + planner.editEndpoint('destination')} /> + + + + ); +} + +function EndpointField({ endpoint, label, value, pending, onPress }: { endpoint: PlannerEndpoint; label: string; value: string; pending: boolean; onPress: () => void }) { + const colors = useThemeColors(); + const name = endpoint === 'origin' ? 'Partenza' : 'Destinazione'; + return ( + + + {/* A ring for where the trip starts, a filled dot for where it ends (shape, not colour). */} + + + + {label} + {value} + + + ); +} diff --git a/src/features/planner/PlannerSheet.tsx b/src/features/planner/PlannerSheet.tsx index c601d4a..6a43d00 100644 --- a/src/features/planner/PlannerSheet.tsx +++ b/src/features/planner/PlannerSheet.tsx @@ -1,23 +1,31 @@ import { Linking, View } from "react-native"; import { Text } from "../../ui/Text"; import { useThemeColors } from "../../theme"; -import { Button, Disclosure, Display, Icon, IconButton, Notice, Num, SegmentedControl, useHairlines } from "../../ui"; +import { Button, Disclosure, Icon, ListRow, Notice, Num, SegmentedControl, useHairlines } from "../../ui"; import { formatDistance } from "../../ui/format"; import type { PlannerTask } from "../app/task-model"; -import { useMapContext } from "../map/useMapModel"; import { useNavigationContext } from "../navigation/useNavigation"; import { useTransitContext } from "../transit/useTransit"; -import { JourneyResults, TransitTimeForm } from "./JourneyPlanner"; +import { useFeedback } from "../app/feedback"; +import { EndpointEditor } from "./EndpointEditor"; +import { JourneyResults } from "./JourneyPlanner"; +import { PlannerEndpoints } from "./PlannerEndpoints"; +import { TransitTimeControl } from "./TransitTimeControl"; import { journeyDate, journeyTime } from "./journey-presentation"; import { TRAVEL_MODES } from "./travel-modes"; import { usePlannerContext } from "./usePlanner"; /** Route planning preview: origin, mode, time, alternatives and saving. */ export function PlannerSheet({ task, now }: { task: PlannerTask; now: number }) { + if (task.editing) return ; + return ; +} + +function PlannerPreview({ task, now }: { task: PlannerTask; now: number }) { const colors = useThemeColors(); const hairlines = useHairlines(); const planner = usePlannerContext(); - const { location, locate } = useMapContext(); + const { openInOtherApp } = useFeedback(); const navigation = useNavigationContext(); const { openJourneyStop } = useTransitContext(); const { route, plans, error, loading: routing, refresh, retainedSelection } = planner.routes; @@ -28,17 +36,10 @@ export function PlannerSheet({ task, now }: { task: PlannerTask; now: number }) return ( {navigation.error ? { void Linking.openSettings(); }} /> : null} - - - Da: {task.origin.label} - {task.destination.name} - - - - + ({ value: item.id, label: item.label, icon: item.icon }))} value={mode} onChange={planner.setMode} /> {mode === "transit" ? ( - + ) : null} {pickingOrigin ? null : mode === "transit" && route ? ( ) : null} + {pickingOrigin ? null : ( + + { void openInOtherApp(task.destination); }} /> + + )} ); } diff --git a/src/features/planner/TransitTimeControl.tsx b/src/features/planner/TransitTimeControl.tsx new file mode 100644 index 0000000..7f120c1 --- /dev/null +++ b/src/features/planner/TransitTimeControl.tsx @@ -0,0 +1,51 @@ +import { useState } from 'react'; +import { View } from 'react-native'; +import type { TransitTime } from '../../domain/types'; +import { Chip, Notice, SegmentedControl } from '../../ui'; +import { Text } from '../../ui/Text'; +import { openCivilPicker } from './civil-picker'; +import { pickedCivil, pickerValue, romeDayLabel, timeChipLabel, timeDirection, withCivilChange, withDirection, type TimeDirection } from './transit-time-control'; + +const directions: { value: TimeDirection; label: string }[] = [{ value: 'depart', label: 'Partenza' }, { value: 'arrive', label: 'Arrivo' }]; + +/** + * One chip naming the journey time ("Partenza adesso"). It opens Partenza/Arrivo and Android's own + * date and time dialogs, read in Europe/Rome; each choice plans again at once. + */ +export function TransitTimeControl({ value, onChange, disabled }: { value: TransitTime; onChange: (value: TransitTime) => void; disabled: boolean }) { + const [open, setOpen] = useState(false); + const [error, setError] = useState(''); + const now = new Date(); + const label = timeChipLabel(value, now); + const civil = value.kind === 'now' ? pickedCivil(now) : { date: value.date, time: value.time.slice(0, 5) }; + function apply(next: () => TransitTime) { + try { onChange(next()); setError(''); } + catch (failure) { setError(failure instanceof Error ? failure.message : 'Controlla data e orario.'); } + } + async function pick(mode: 'date' | 'time') { + const chosen = await openCivilPicker(mode, pickerValue(value, new Date())); + // Validated as chosen: a nonexistent or ambiguous DST minute shows an error and keeps the current time. + if (chosen) apply(() => withCivilChange(value, chosen, timeDirection(value), new Date())); + } + return ( + + + { if (!disabled || open) setOpen(!open); }} /> + + {open ? ( + + apply(() => withDirection(value, direction, new Date()))} /> + + apply(() => ({ kind: 'now' }))} /> + { void pick('date'); }} /> + { void pick('time'); }} /> + + Ora italiana + {error ? : null} + + ) : null} + + ); +} diff --git a/src/features/planner/civil-picker.native.ts b/src/features/planner/civil-picker.native.ts new file mode 100644 index 0000000..e88e5da --- /dev/null +++ b/src/features/planner/civil-picker.native.ts @@ -0,0 +1,19 @@ +import { DateTimePickerAndroid } from '@react-native-community/datetimepicker'; +import { pickedCivil, type CivilChoice } from './transit-time-control'; + +/** + * Android's own date or time dialog, shown and read in Europe/Rome whatever the device zone. + * Resolves the chosen Rome civil date or minute, or null when dismissed. + */ +export function openCivilPicker(mode: 'date' | 'time', value: Date): Promise { + return new Promise(resolve => { + DateTimePickerAndroid.open({ + value, mode, is24Hour: true, timeZoneName: 'Europe/Rome', + onChange: (event, date) => { + if (event.type !== 'set' || !date) { resolve(null); return; } + const civil = pickedCivil(date); + resolve(mode === 'date' ? { date: civil.date } : { time: civil.time }); + }, + }); + }); +} diff --git a/src/features/planner/civil-picker.ts b/src/features/planner/civil-picker.ts new file mode 100644 index 0000000..b8820d6 --- /dev/null +++ b/src/features/planner/civil-picker.ts @@ -0,0 +1,24 @@ +import { browserCivil, pickedCivil, type CivilChoice } from './transit-time-control'; + +/** + * Browser fallback for the web preview: the browser's own date/time input. Its value is already a + * Rome civil date or minute, returned as typed so validation can refuse nonexistent or ambiguous + * daylight-saving minutes. Android uses the platform dialogs (civil-picker.native.ts). + */ +export function openCivilPicker(mode: 'date' | 'time', value: Date): Promise { + const doc = (globalThis as { document?: Document }).document; + if (!doc) return Promise.resolve(null); + const current = pickedCivil(value); + return new Promise(resolve => { + const input = doc.createElement('input'); + input.type = mode; + input.value = mode === 'date' ? current.date : current.time; + Object.assign(input.style, { position: 'fixed', opacity: '0', pointerEvents: 'none', bottom: '0', left: '0' }); + let settled = false; + const finish = (result: CivilChoice | null) => { if (settled) return; settled = true; input.remove(); resolve(result); }; + input.addEventListener('change', () => finish(browserCivil(mode, input.value))); + input.addEventListener('blur', () => setTimeout(() => finish(null), 300)); + doc.body.appendChild(input); + try { input.showPicker(); } catch { input.focus(); } + }); +} diff --git a/src/features/planner/transit-time-control.test.ts b/src/features/planner/transit-time-control.test.ts new file mode 100644 index 0000000..3a16275 --- /dev/null +++ b/src/features/planner/transit-time-control.test.ts @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { browserCivil, pickedCivil, pickerValue, romeDayLabel, romeInstant, timeChipLabel, withCivilChange, withDirection } from './transit-time-control'; + +const evening = new Date('2026-10-11T21:58:00Z'); // 23:58 in Rome + +test('the chip names the choice in Rome time: adesso, today, tomorrow or a date', () => { + assert.equal(timeChipLabel({ kind: 'now' }, evening), 'Partenza adesso'); + assert.equal(timeChipLabel({ kind: 'depart-at', date: '2026-10-11', time: '23:59' }, evening), 'Partenza 23:59'); + assert.equal(timeChipLabel({ kind: 'depart-at', date: '2026-10-12', time: '07:05' }, evening), 'Partenza 07:05 · domani'); + assert.equal(timeChipLabel({ kind: 'arrive-by', date: '2026-10-15', time: '09:00' }, evening), 'Arrivo entro 09:00 · gio 15 ott'); + // After Rome midnight (still the 11th in UTC), "oggi" is already the 12th. + assert.equal(romeDayLabel('2026-10-12', new Date('2026-10-11T22:30:00Z')), 'oggi'); +}); + +test('Partenza/Arrivo keeps the chosen minute; from adesso it starts at the current Rome minute', () => { + assert.deepEqual(withDirection({ kind: 'now' }, 'arrive', evening), { kind: 'arrive-by', date: '2026-10-11', time: '23:58' }); + assert.deepEqual(withDirection({ kind: 'now' }, 'depart', evening), { kind: 'depart-at', date: '2026-10-11', time: '23:58' }); + const chosen = { kind: 'depart-at', date: '2026-10-14', time: '17:45' } as const; + assert.deepEqual(withDirection(chosen, 'arrive', evening), { kind: 'arrive-by', date: '2026-10-14', time: '17:45' }); + assert.equal(withDirection(chosen, 'depart', evening), chosen); +}); + +test('picked dates and times change one part; nonexistent and ambiguous DST minutes are refused', () => { + const chosen = { kind: 'arrive-by', date: '2026-10-14', time: '17:45' } as const; + assert.deepEqual(withCivilChange(chosen, { time: '08:15' }), { kind: 'arrive-by', date: '2026-10-14', time: '08:15' }); + assert.deepEqual(withCivilChange(chosen, { date: '2026-10-20' }), { kind: 'arrive-by', date: '2026-10-20', time: '17:45' }); + assert.deepEqual(withCivilChange({ kind: 'now' }, { time: '06:30' }, 'depart', evening), { kind: 'depart-at', date: '2026-10-11', time: '06:30' }); + assert.throws(() => withCivilChange(chosen, { date: '2026-10-25', time: '02:30' }), /ambiguo/); + assert.throws(() => withCivilChange(chosen, { date: '2026-03-29', time: '02:30' }), /inesistente/); +}); + +test('native pickers open and read in Europe/Rome independent of the device zone', () => { + assert.equal(romeInstant('2026-10-14', '17:45').toISOString(), '2026-10-14T15:45:00.000Z'); + assert.equal(romeInstant('2026-01-14', '17:45').toISOString(), '2026-01-14T16:45:00.000Z'); + assert.deepEqual(pickedCivil(new Date('2026-10-11T22:07:00Z')), { date: '2026-10-12', time: '00:07' }); + assert.equal(pickerValue({ kind: 'now' }, evening), evening); + assert.deepEqual(pickedCivil(pickerValue({ kind: 'depart-at', date: '2026-03-29', time: '03:30' })), { date: '2026-03-29', time: '03:30' }); +}); + +test('a browser-picked spring-forward minute is validated as chosen, not shifted to a valid instant', () => { + const chosen = { kind: 'depart-at', date: '2027-03-28', time: '01:30' } as const; + const picked = browserCivil('time', '02:30'); + assert.deepEqual(picked, { time: '02:30' }); + assert.throws(() => withCivilChange(chosen, picked!), /inesistente/); + assert.deepEqual(browserCivil('date', '2027-03-28'), { date: '2027-03-28' }); + assert.equal(browserCivil('time', ''), null); + assert.equal(browserCivil('date', '28/03/2027'), null); +}); diff --git a/src/features/planner/transit-time-control.ts b/src/features/planner/transit-time-control.ts new file mode 100644 index 0000000..2429dae --- /dev/null +++ b/src/features/planner/transit-time-control.ts @@ -0,0 +1,73 @@ +import type { TransitTime } from '../../domain/types'; +import { romeDateTime } from '../../services/transit-time'; +import { draftTransitTime, italianDate, nextRomeDate } from './journey-presentation'; + +/** Partenza or Arrivo; "now" is a departure. */ +export type TimeDirection = 'depart' | 'arrive'; +export const timeDirection = (value: TransitTime): TimeDirection => value.kind === 'arrive-by' ? 'arrive' : 'depart'; + +const DAY_LABELS = ['oggi', 'domani']; +/** "oggi", "domani" or a short Italian date such as "gio 14 ott", always for the Rome civil date. */ +export function romeDayLabel(isoDate: string, now = new Date()): string { + const index = [0, 1].findIndex(days => nextRomeDate(days, now) === isoDate); + if (index >= 0) return DAY_LABELS[index]!; + return new Date(`${isoDate}T12:00:00Z`).toLocaleDateString('it-IT', { timeZone: 'UTC', weekday: 'short', day: 'numeric', month: 'short' }); +} + +/** The chip: "Partenza adesso", "Partenza 17:45 · domani", "Arrivo entro 09:00 · gio 14 ott". */ +export function timeChipLabel(value: TransitTime, now = new Date()): string { + if (value.kind === 'now') return 'Partenza adesso'; + const day = romeDayLabel(value.date, now); + return `${value.kind === 'arrive-by' ? 'Arrivo entro' : 'Partenza'} ${value.time.slice(0, 5)}${day === 'oggi' ? '' : ` · ${day}`}`; +} + +/** The civil date and minute a choice starts from: the chosen one, or the current Rome minute. */ +function civil(value: TransitTime, now: Date): { date: string; time: string } { + if (value.kind !== 'now') return { date: value.date, time: value.time.slice(0, 5) }; + const current = romeDateTime(now); + return { date: current.date, time: current.time.slice(0, 5) }; +} +const build = (kind: 'depart-at' | 'arrive-by', date: string, time: string) => draftTransitTime(kind, italianDate(date), time); + +/** Switches between Partenza and Arrivo, keeping the chosen date and time (from "now", the current minute). */ +export function withDirection(value: TransitTime, direction: TimeDirection, now = new Date()): TransitTime { + if (timeDirection(value) === direction && value.kind !== 'now') return value; + const { date, time } = civil(value, now); + return build(direction === 'arrive' ? 'arrive-by' : 'depart-at', date, time); +} + +/** What a picker chose: one Rome civil part, unnormalized. */ +export type CivilChoice = { date: string; time?: undefined } | { time: string; date?: undefined }; + +/** A picked Rome date or time replaces that part; validation rejects nonexistent or ambiguous DST minutes. */ +export function withCivilChange(value: TransitTime, change: { date?: string; time?: string }, direction = timeDirection(value), now = new Date()): TransitTime { + const current = civil(value, now); + return build(direction === 'arrive' ? 'arrive-by' : 'depart-at', change.date ?? current.date, change.time ?? current.time); +} + +/** The instant whose Rome civil time is `date time` (the earlier one in a fold, the shifted one in a gap). */ +export function romeInstant(date: string, time: string): Date { + const utc = new Date(`${date}T${time.slice(0, 5)}:00Z`).getTime(); + for (const offset of [60, 120]) { + const candidate = new Date(utc - offset * 60_000); + const local = romeDateTime(candidate); + if (local.date === date && local.time.slice(0, 5) === time.slice(0, 5)) return candidate; + } + return new Date(utc - 60 * 60_000); +} +/** The instant the native pickers open on. */ +export function pickerValue(value: TransitTime, now = new Date()): Date { + if (value.kind === 'now') return now; + return romeInstant(value.date, value.time); +} +/** What a native picker returned, read as a Rome civil date and minute. */ +export function pickedCivil(picked: Date): { date: string; time: string } { + const local = romeDateTime(picked); + return { date: local.date, time: local.time.slice(0, 5) }; +} + +/** A browser date/time input value as the one civil part it chose; empty or malformed input is no choice. */ +export function browserCivil(mode: 'date' | 'time', raw: string): CivilChoice | null { + if (mode === 'date') return /^\d{4}-\d{2}-\d{2}$/.test(raw) ? { date: raw } : null; + return /^\d{2}:\d{2}/.test(raw) ? { time: raw.slice(0, 5) } : null; +} diff --git a/src/features/planner/usePlanner.ts b/src/features/planner/usePlanner.ts index 8b7e464..fd3212f 100644 --- a/src/features/planner/usePlanner.ts +++ b/src/features/planner/usePlanner.ts @@ -5,7 +5,7 @@ import { navigationLocationForReplan } from '../../domain/navigation'; import { savedTravel, type SavedJourney, type SavedTravelSnapshot } from '../../services/saved-travel'; import { createFeatureContext } from '../app/feature-context'; import type { SheetState } from '../app/sheet'; -import { plannerInFront, plannerTask, type PlannerTask, type TaskState } from '../app/task-model'; +import { plannerInFront, plannerTask, type PlannerEndpoint, type PlannerTask, type TaskState } from '../app/task-model'; import { useTaskTransitions, type TaskModel } from '../app/useTaskModel'; import { INITIAL_MAP } from '../map/coordinates'; import type { DeviceLocation } from '../map/useDeviceLocation'; @@ -34,6 +34,13 @@ export interface Planner { /** Uses a map tap as origin while picking. */ chooseOrigin(coordinate: Coordinate): void; cancelOriginPicking(): void; + /** Opens the search for the origin or the destination. */ + editEndpoint(endpoint: PlannerEndpoint): void; + closeEndpointEditor(): void; + /** Uses a searched or saved place for the endpoint being edited. */ + chooseEndpoint(place: Place): void; + /** Exchanges origin and destination once the origin is settled. */ + swapEndpoints(): void; setMode(mode: TravelMode): void; submitTransitTime(value: TransitTime): void; selectJourney(id: string): void; @@ -145,6 +152,20 @@ export function usePlanner({ tasks, camera, location, places, navigation, sheet, dispatch({ type: 'setOrigin', coordinate }); }, [location, getState, dispatch]); const cancelOriginPicking = useCallback(() => dispatch({ type: 'cancelOriginPicking' }), [dispatch]); + const editEndpoint = useCallback((endpoint: PlannerEndpoint) => { + // A pending fix must not replace the origin the user is about to search for. + if (endpoint === 'origin') location.cancel(); + dispatch({ type: 'editEndpoint', endpoint }); + }, [location, dispatch]); + const closeEndpointEditor = useCallback(() => { Keyboard.dismiss(); dispatch({ type: 'closeEndpointEditor' }); }, [dispatch]); + const chooseEndpoint = useCallback((place: Place) => { + const editing = plannerTask(getState())?.editing; + if (!editing) return; + Keyboard.dismiss(); + if (editing === 'origin') { location.cancel(); dispatch({ type: 'setOriginPlace', place }); } + else dispatch({ type: 'setDestination', place }); + }, [getState, location, dispatch]); + const swapEndpoints = useCallback(() => dispatch({ type: 'swapEndpoints' }), [dispatch]); const setMode = useCallback((next: TravelMode) => dispatch({ type: 'setTravelMode', mode: next }), [dispatch]); const submitTransitTime = useCallback((value: TransitTime) => { if (JSON.stringify(value) === JSON.stringify(getState().travel.transitTime)) refresh(); @@ -202,7 +223,7 @@ export function usePlanner({ tasks, camera, location, places, navigation, sheet, return { task, mode, transitTime, routes, savedJourneyVisible, journeyBusy, journeySaveError: savedTravelFailureMessage(travel.journeyFailure), savedTravel: travel, fitKey, - beginRoute, pickOriginOnMap, chooseOrigin, cancelOriginPicking, setMode, submitTransitTime, selectJourney, + beginRoute, pickOriginOnMap, chooseOrigin, cancelOriginPicking, editEndpoint, closeEndpointEditor, chooseEndpoint, swapEndpoints, setMode, submitTransitTime, selectJourney, saveJourney, clearJourney, restoreJourney, startGuidance, replanFromNavigation, suspend, }; } diff --git a/src/features/search/SearchField.tsx b/src/features/search/SearchField.tsx index 1703a22..de90a6d 100644 --- a/src/features/search/SearchField.tsx +++ b/src/features/search/SearchField.tsx @@ -17,9 +17,9 @@ export function SearchField() { searchRows(result.places, transit), [result.places, transit]); + const count = searchRowCount(rows); const header = (<> {searching ? : null} - {searching ? "Aggiorno i risultati…" : <>{places.length} risultati{result.truncated ? <> · primi {result.resultLimit} : null}{policy === "local-only" ? " · solo locali" : ""}} + {searching ? "Aggiorno i risultati…" : <>{count} {count === 1 ? "risultato" : "risultati"}{result.truncated ? <> · primi {result.resultLimit} luoghi : null}{policy === "local-only" ? " · solo locali" : ""}} - {error && places.length ? : null} + {error && count ? : null} ); const empty = searching ? : error ? @@ -36,15 +43,17 @@ export function SearchResults() { ? `Raggio ${formatDistance(result.coverage.radiusMeters)} · ${result.coverage.extent === "outside" ? "fuori dal pacchetto locale" : result.coverage.extent === "partial" ? "copertura locale parziale" : "nel pacchetto locale"}` : `Nomi nel pacchetto locale${result.coverage.centerInside ? "" : " · centro fuori copertura"}${policy === "local-and-online" ? "; Photon online" : ""}`} {result.warnings.map((warning, index) => )} - Luoghi da OpenStreetMap e Overture. Le informazioni possono essere incomplete. + Luoghi da OpenStreetMap e Overture; quartieri approssimati da OpenStreetMap. Fermate e linee dagli orari GTT inclusi nell’app. Le informazioni possono essere incomplete. ); return ( place.id} - renderItem={({ item }) => openPlace(item)} />} + data={rows} + keyExtractor={row => row.key} + renderItem={({ item }) => item.kind === "section" ? + : item.kind === "stop" ? openStop(item.stop)} /> + : openPlace(item.place)} />} extraData={reference} ListHeaderComponent={header} ListEmptyComponent={empty} diff --git a/src/features/search/search-rows.ts b/src/features/search/search-rows.ts new file mode 100644 index 0000000..d17582f --- /dev/null +++ b/src/features/search/search-rows.ts @@ -0,0 +1,53 @@ +import type { Place, Stop } from '../../domain/types'; +import type { TransitSearch } from '../../services/transit-search'; + +/** One row of the search list: a group heading, a place (venue, address, street, area) or a GTT stop. */ +export type SearchRow = + | { kind: 'section'; key: string; title: string } + | { kind: 'place'; key: string; place: Place } + | { kind: 'stop'; key: string; stop: Stop; line?: string }; + +/** + * Orders the list: a typed stop code first, then a typed line's nearby stops, then places; stops + * found by name follow the places unless the query asked for a stop ("fermata …"). Groups get a + * heading only when more than one kind is shown. + */ +export function searchRows(places: readonly Place[], transit: TransitSearch): SearchRow[] { + const lead: SearchRow[] = []; + if (transit.code) lead.push({ kind: 'stop', key: `code:${transit.code.id}`, stop: transit.code }); + const line: SearchRow[] = transit.line?.stops.length ? [ + { kind: 'section', key: `line:${transit.line.name}`, title: `Linea ${transit.line.name} · fermate vicine` }, + ...transit.line.stops.map(stop => ({ kind: 'stop' as const, key: `line:${transit.line!.name}:${stop.id}`, stop, line: transit.line!.name })), + ] : []; + const named: SearchRow[] = transit.named.map(stop => ({ kind: 'stop', key: `named:${stop.id}`, stop })); + const placeRows: SearchRow[] = places.map(place => ({ kind: 'place', key: `place:${place.id}`, place })); + const kinds = [lead.length || line.length || named.length, placeRows.length].filter(Boolean).length; + const heading = (key: string, title: string, rows: SearchRow[]): SearchRow[] => + rows.length && kinds > 1 ? [{ kind: 'section', key, title }, ...rows] : rows; + const stopsFirst = transit.explicit; + return [ + ...(lead.length ? heading('section:code', 'Fermata', lead) : []), + ...line, + ...(stopsFirst ? heading('section:stops', 'Fermate', named) : []), + ...heading('section:places', 'Luoghi e indirizzi', placeRows), + ...(stopsFirst ? [] : heading('section:stops', 'Fermate', named)), + ]; +} + +/** Results that a user can open (headings excluded). */ +export const searchRowCount = (rows: readonly SearchRow[]) => rows.filter(row => row.kind !== 'section').length; + +/** Two characters start a search; a one-character stop code or line ("4", "9") also does. */ +export const showsSearch = (term: string, transit: TransitSearch) => term.length >= 2 || !!transit.code || !!transit.line; + +/** + * Stops the map pins for a search (every listed stop) and the ones a submitted search frames: the + * stops that lead the list (code, line, or names after "fermata"), else name matches when no place matched. + */ +export function searchMapStops(transit: TransitSearch, placeCount: number): { pinned: Stop[]; framed: Stop[] } { + const unique = (stops: Stop[]) => stops.filter((stop, index) => stops.findIndex(other => other.id === stop.id) === index); + const lead = unique([...(transit.code ? [transit.code] : []), ...(transit.line?.stops ?? [])]); + const pinned = unique([...lead, ...transit.named]); + const framed = lead.length ? lead : transit.explicit || !placeCount ? transit.named : []; + return { pinned, framed }; +} diff --git a/src/features/search/usePlaceLookup.ts b/src/features/search/usePlaceLookup.ts new file mode 100644 index 0000000..06ac92c --- /dev/null +++ b/src/features/search/usePlaceLookup.ts @@ -0,0 +1,55 @@ +import { useEffect, useMemo, useState, useSyncExternalStore } from 'react'; +import type { Coordinate, Place, SearchPolicy } from '../../domain/types'; +import { searchLocalResult, searchPlaces } from '../../services'; +import { searchPreferences } from '../../services/search-preferences'; +import { endpointStops, searchTransit, stopAsPlace } from '../../services/transit-search'; +import { catalogVersion, subscribeCatalog } from '../../transit-data/stop-catalog'; + +export interface PlaceLookup { + places: Place[]; + policy: SearchPolicy; + searching: boolean; + error: string; +} +const LIMIT = 10; +const catalogHash = () => catalogVersion().packageHash; + +/** + * The search used to choose a route endpoint: a typed stop code or stop name first, then local + * places at once and Photon after a pause when online search is allowed. "Solo ricerca locale" + * (or an unread preference) never sends the text anywhere. + */ +export function usePlaceLookup(query: string, center: Coordinate, active: boolean): PlaceLookup { + const preference = useSyncExternalStore(searchPreferences.subscribe, searchPreferences.getSnapshot, searchPreferences.getSnapshot); + const policy: SearchPolicy = preference.ready && preference.preferenceKnown ? preference.policy : 'local-only'; + const text = query.trim(); + const catalog = useSyncExternalStore(subscribeCatalog, catalogHash, catalogHash); + const stops = useMemo(() => { + void catalog; + return text ? endpointStops(searchTransit(text, center)).map(stopAsPlace) : []; + }, [text, center, catalog]); + const local = useMemo(() => text.length >= 2 ? searchLocalResult(text, center).places : [], [text, center]); + const [online, setOnline] = useState<{ key: string; places: Place[] } | null>(null); + const [searching, setSearching] = useState(false); + const [error, setError] = useState(''); + const key = `${policy}:${text}:${center.latitude}:${center.longitude}`; + useEffect(() => { + setError(''); + if (!active || text.length < 2 || policy === 'local-only') { setSearching(false); return; } + const controller = new AbortController(); + const unsubscribe = searchPreferences.subscribe(() => { + const current = searchPreferences.getSnapshot(); + if (!current.ready || !current.preferenceKnown || current.policy !== policy) controller.abort(); + }); + setSearching(true); + const timer = setTimeout(() => { + searchPlaces(text, { center, policy, signal: controller.signal }) + .then(result => { if (!controller.signal.aborted) setOnline({ key, places: result.places }); }) + .catch(failure => { if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : 'Ricerca non disponibile.'); }) + .finally(() => { if (!controller.signal.aborted) setSearching(false); }); + }, 450); + return () => { clearTimeout(timer); controller.abort(); unsubscribe(); }; + }, [active, text, center, policy, key]); + const places = online?.key === key ? online.places : local; + return { places: useMemo(() => [...stops, ...places].slice(0, LIMIT), [stops, places]), policy, searching, error }; +} diff --git a/src/features/search/useSearch.ts b/src/features/search/useSearch.ts index 7616637..0293cbd 100644 --- a/src/features/search/useSearch.ts +++ b/src/features/search/useSearch.ts @@ -3,6 +3,8 @@ import { Keyboard, type TextInput } from 'react-native'; import type { SearchPolicy, SearchResult } from '../../domain/types'; import { searchLocalResult, searchPlaces } from '../../services'; import { searchPreferences } from '../../services/search-preferences'; +import { EMPTY_TRANSIT_SEARCH, searchTransit, type TransitSearch } from '../../services/transit-search'; +import { catalogVersion, subscribeCatalog } from '../../transit-data/stop-catalog'; import { createFeatureContext } from '../app/feature-context'; import type { SheetState } from '../app/sheet'; import { rootTab, searchRoot } from '../app/task-model'; @@ -10,6 +12,7 @@ import type { TaskModel } from '../app/useTaskModel'; import type { DeviceLocation } from '../map/useDeviceLocation'; import type { MapCamera } from '../map/useMapCamera'; import { initialSearchFrame, searchFrameReducer } from './search-frame'; +import { showsSearch } from './search-rows'; export interface Search { inputRef: RefObject; @@ -21,6 +24,8 @@ export interface Search { /** The term is long enough to show results. */ hasSearch: boolean; result: SearchResult; + /** GTT stops and lines named by the typed text (bundled catalog, never sent anywhere). */ + transit: TransitSearch; policy: SearchPolicy; searching: boolean; error: string; @@ -38,6 +43,8 @@ export interface Search { clear(): void; } +const catalogHash = () => catalogVersion().packageHash; + /** Local results immediately, then online results when the search policy allows them. */ export function useSearch({ tasks, camera, location, sheet, appActive, navigationVisible }: { tasks: TaskModel; camera: MapCamera; location: DeviceLocation; sheet: SheetState; appActive: boolean; navigationVisible: boolean; @@ -47,10 +54,13 @@ export function useSearch({ tasks, camera, location, sheet, appActive, navigatio const category = searchRoot(tasks.state)?.category ?? ''; const explore = rootTab(tasks.state) === 'explore'; const term = query.trim() || category; - const hasSearch = term.length >= 2; const searchCenter = camera.searchCenter; const preference = useSyncExternalStore(searchPreferences.subscribe, searchPreferences.getSnapshot, searchPreferences.getSnapshot); const policy: SearchPolicy = preference.ready && preference.preferenceKnown ? preference.policy : 'local-only'; + const catalog = useSyncExternalStore(subscribeCatalog, catalogHash, catalogHash); + // Typed text only: a category shortcut never lists stops. Line stops are nearest the searched area. + const transit = useMemo(() => { void catalog; return query.trim().length ? searchTransit(query, searchCenter) : EMPTY_TRANSIT_SEARCH; }, [query, searchCenter, catalog]); + const hasSearch = showsSearch(term, transit); const localResult = useMemo(() => searchLocalResult(query.trim() || category, searchCenter), [query, category, searchCenter]); const [completed, setCompleted] = useState<{ result: SearchResult; policy: SearchPolicy; local: SearchResult } | null>(null); const result = completed?.policy === policy && completed.local === localResult ? completed.result : localResult; @@ -143,7 +153,7 @@ export function useSearch({ tasks, camera, location, sheet, appActive, navigatio }, [retry, location]); const clear = useCallback(() => { setQuery(''); dispatchFrame({ type: 'cancel' }); }, []); const frame = useMemo(() => frameState.pending ? { key: `results:${frameState.pending.revision}`, settled: frameState.pending.settled } : null, [frameState.pending]); - return { inputRef, query, category, term, hasSearch, result, policy, searching, error, frame, focus, changeQuery, chooseCategory, submit, retry, clear }; + return { inputRef, query, category, term, hasSearch, result, transit, policy, searching, error, frame, focus, changeQuery, chooseCategory, submit, retry, clear }; } export const [SearchProvider, useSearchContext] = createFeatureContext('Search'); diff --git a/src/features/transit/StopRow.tsx b/src/features/transit/StopRow.tsx new file mode 100644 index 0000000..8c1f8d1 --- /dev/null +++ b/src/features/transit/StopRow.tsx @@ -0,0 +1,25 @@ +import { View } from "react-native"; +import type { Stop } from "../../domain/types"; +import { useThemeColors } from "../../theme"; +import { Icon, ListRow, TransitLineBadge, transitModeFromLineName } from "../../ui"; +import { distanceFrom, type DistanceReference } from "../map/distance-reference"; + +/** A GTT stop in a list; `line` leads with that line's badge when the row answers a line search. */ +export function StopRow({ stop, line, reference, onPress }: { stop: Stop; line?: string; reference: DistanceReference; onPress: () => void }) { + const colors = useThemeColors(); + const distance = distanceFrom(reference, stop.coordinate); + const lines = stop.lines.slice(0, 6).join(", ") || "GTT"; + return ( + + : } + onPress={onPress} + /> + ); +} diff --git a/src/services/notices.ts b/src/services/notices.ts index cd268e1..ff990d8 100644 --- a/src/services/notices.ts +++ b/src/services/notices.ts @@ -1,4 +1,5 @@ import licenses from '../data/licenses.json'; +import localities from '../data/localities.json'; import manifest from '../data/manifest.json'; import { mirrorHosts } from '../transit-data/config'; import { STOP_LIVE_DISCLOSURE, STOP_LIVE_SETTING } from '../transit-data/stop-live'; @@ -7,7 +8,8 @@ export const DATA_MANIFEST = manifest; export const PROVIDER_NOTICES = [ { name: 'Mappe', text: 'OpenFreeMap · OpenMapTiles · © OpenStreetMap contributors', url: 'https://www.openstreetmap.org/copyright' }, { name: 'Luoghi', text: `Overture Maps Foundation. Pacchetto di ${manifest.places.count.toLocaleString('it-IT')} record, release ${manifest.places.release}; estensione indicata dal confine tratteggiato sulla mappa. Dati incompleti; fonti e licenze conservate per ogni luogo.`, url: 'https://docs.overturemaps.org/attribution/' }, - { name: 'Ricerca online', text: 'Photon / OpenStreetMap: se la ricerca online è abilitata, nomi e indirizzi cercati e area vengono inviati al servizio. Le categorie sono cercate nel pacchetto locale. Nessuna disponibilità garantita.', url: 'https://photon.komoot.io' }, + { name: 'Ricerca online', text: 'Photon / OpenStreetMap: se la ricerca online è abilitata, nomi e indirizzi cercati e il centro della mappa vengono inviati al servizio. Se Photon non trova una ricerca che nomina un quartiere (per esempio «Eataly Lingotto»), una seconda richiesta invia le altre parole con il punto pubblico OpenStreetMap di quel quartiere al posto del centro mappa. Categorie, fermate e linee sono cercate solo sul dispositivo. Nessuna disponibilità garantita.', url: 'https://photon.komoot.io' }, + { name: 'Quartieri', text: `${localities.localities.length} nomi di quartiere con il loro punto OpenStreetMap (© OpenStreetMap contributors · ODbL), estratti il ${localities.retrievedAt}: servono a leggere ricerche come «bar San Salvario». Aree approssimate, non confini.`, url: 'https://www.openstreetmap.org/copyright' }, { name: 'Percorsi stradali', text: 'FOSSGIS / OpenStreetMap: partenza e destinazione inviate al servizio e registrate nei log. Massimo una richiesta al secondo; servizio pubblico per uso moderato.', url: 'https://www.openstreetmap.org/fixthemap' }, { name: 'Fermate e previsioni', text: `Data source: GTT S.p.A. – Gruppo Torinese Trasporti. Dati per uso non commerciale. Orari programmati GTT ${manifest.gtt.version} inclusi nell’app; versioni più recenti verificate tramite hash vengono scaricate da ${mirrorHosts().join(', ')} (il server vede indirizzo IP e ora della richiesta, non la fermata né la posizione). Il feed tempo reale è scaricato per l’intera città: non contiene la tua posizione né la fermata scelta.`, url: 'https://www.gtt.to.it' }, { name: STOP_LIVE_SETTING, text: STOP_LIVE_DISCLOSURE, url: 'https://www.gtt.to.it' }, diff --git a/src/services/search-relevance.test.ts b/src/services/search-relevance.test.ts index 472f886..f482407 100644 --- a/src/services/search-relevance.test.ts +++ b/src/services/search-relevance.test.ts @@ -1,6 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { searchLocalPlaces, searchLocalResult, searchPlaces, categoryLabel, createLocalPlaceSearch } from "./search"; +import { distanceMeters } from "./geo"; import { createPlaceCatalog, placeCatalog, type PlaceCatalog, type CatalogPlace, type PlaceSearchEntry } from './place-catalog'; const docks = { latitude: 45.0937, longitude: 7.6832 }; @@ -276,3 +277,98 @@ test("common food and shopping categories have useful Italian labels", () => { assert.equal(categoryLabel("ice_cream_shop"), "Gelateria"); assert.equal(categoryLabel("clothing_store"), "Abbigliamento"); }); + +const centre = { latitude: 45.0703, longitude: 7.6869 }; +const sanSalvario = { latitude: 45.05495, longitude: 7.68015 }; +const lingotto = { latitude: 45.02615, longitude: 7.64989 }; + +test("multi-word queries match words across name, address, category and neighbourhood", () => { + const viaPo = searchLocalPlaces("farmacia via po", centre); + assert.ok(viaPo.length >= 4); + assert.ok(viaPo.slice(0, 4).every((place) => place.category === "pharmacy" && /^Via Po\b/i.test(place.address ?? "")), "pharmacies on Via Po lead"); + assert.equal(viaPo[0]?.name, "Farmacia Po"); + assert.deepEqual(searchLocalPlaces("farmacia in via po", centre).map((place) => place.id), viaPo.map((place) => place.id), "linking words are optional"); + + const bars = searchLocalPlaces("bar san salvario", centre); + assert.ok(bars.length >= 10); + for (const place of bars.slice(0, 10)) { + assert.ok(distanceMeters(place.coordinate, sanSalvario) <= 2000 || /san salvario/i.test(place.name), place.name); + } + assert.ok(!bars.some((place) => /Barbagusto|Baretti/i.test(`${place.name} ${place.address}`) && !/bar|cafe|coffee|pub/.test(place.category ?? "")), + "a category word is not a prefix of other names or streets"); + + const address = searchLocalPlaces("via nizza 230", centre); + assert.ok(address.length >= 10); + assert.ok(address.slice(0, 10).every((place) => /Via Nizza,? 230/i.test(place.address ?? "")), "the numbered address leads"); + assert.ok(!searchLocalPlaces("via nizza 23", centre).slice(0, 10).some((place) => /Via Nizza,? 230/i.test(place.address ?? "")), "house numbers match exactly"); +}); + +test("a neighbourhood alone is offered as an area, not a list of every business in it", () => { + const area = searchLocalPlaces("San Salvario", centre); + assert.equal(area[0]?.kind, "area"); + assert.equal(area[0]?.name, "San Salvario"); + assert.equal(area[0]?.attributions[0], "© OpenStreetMap contributors · ODbL"); + assert.ok(area.slice(1).every((place) => /san salvario/i.test(`${place.name} ${place.address}`))); + assert.equal(searchLocalPlaces("Lingotto", centre)[0]?.kind, "area"); + // Exact business names still lead over the neighbourhood reading of their words. + assert.equal(searchLocalPlaces("Rough San Salvario", centre)[0]?.name, "Rough San Salvario"); + assert.equal(searchLocalPlaces("Da Mido", centre)[0]?.name, "Da Mido | San Salvario"); +}); + +test("Eataly Lingotto: Photon is asked once with the typed words, then with the name near the neighbourhood", async () => { + // Public OSM objects returned by Photon on 2026-11-02 for "Eataly" biased to the Lingotto node. + const features = [ + { geometry: { coordinates: [7.667453, 45.03535] }, properties: { osm_type: "W", osm_id: 96238045, osm_key: "shop", osm_value: "supermarket", type: "house", name: "Eataly", street: "Via Nizza", housenumber: "224", postcode: "10126", city: "Torino" } }, + { geometry: { coordinates: [7.683867, 45.067292] }, properties: { osm_type: "N", osm_id: 1478015126, osm_key: "amenity", osm_value: "restaurant", type: "house", name: "Eataly Lagrange", street: "Via Giuseppe Luigi Lagrange", housenumber: "3", postcode: "10123", city: "Torino" } }, + ]; + assert.equal(searchLocalPlaces("Eataly Lingotto", centre).length, 0, "the local package has no Lingotto branch"); + const original = global.fetch; + const urls: URL[] = []; + try { + global.fetch = async (input) => { + const url = new URL(String(input)); + urls.push(url); + return Response.json({ features: url.searchParams.get("q") === "Eataly" ? features : [] }); + }; + const result = await searchPlaces("Eataly Lingotto", { center: centre, policy: "local-and-online" }); + assert.deepEqual(urls.map((url) => url.searchParams.get("q")), ["Eataly Lingotto", "Eataly"]); + assert.equal(urls[0]!.searchParams.get("lat"), String(centre.latitude)); + assert.equal(urls[1]!.searchParams.get("lat"), String(lingotto.latitude), "the retry is biased to the public neighbourhood node"); + assert.deepEqual(result.places.map((place) => place.name), ["Eataly"], "answers outside the neighbourhood are dropped"); + assert.equal(result.places[0]?.address, "Via Nizza 224, 10126 Torino"); + assert.equal(result.places[0]?.kind, "place"); + assert.ok(Math.abs(result.places[0]!.distanceMeters! - distanceMeters(centre, result.places[0]!.coordinate)) < 1, "distance from the search centre, not the bias"); + // Cached for five minutes: the same search makes no new request. + await searchPlaces("Eataly Lingotto", { center: centre, policy: "local-and-online" }); + assert.equal(urls.length, 2); + } finally { global.fetch = original; } +}); + +test("category, neighbourhood and stop words alone stay local; online answers are labelled as addresses, streets or areas", async () => { + const original = global.fetch; + let requests = 0; + try { + global.fetch = async () => { + requests += 1; + return Response.json({ features: [ + { geometry: { coordinates: [7.6666, 45.0354] }, properties: { osm_type: "N", osm_id: 1, osm_key: "place", osm_value: "house", type: "house", street: "Via Nizza", housenumber: "230", postcode: "10126", city: "Torino" } }, + { geometry: { coordinates: [7.67, 45.04] }, properties: { osm_type: "W", osm_id: 2, osm_key: "highway", osm_value: "secondary", type: "street", name: "Via Nizza", postcode: "10126", city: "Torino" } }, + { geometry: { coordinates: [7.68, 45.055] }, properties: { osm_type: "N", osm_id: 3, osm_key: "place", osm_value: "suburb", type: "district", name: "San Salvario", city: "Torino" } }, + { geometry: { coordinates: [7.678, 45.062] }, properties: { osm_type: "N", osm_id: 4, osm_key: "highway", osm_value: "bus_stop", type: "house", name: "Porta Nuova", city: "Torino" } }, + ] }); + }; + await searchPlaces("bar san salvario", { center: centre, policy: "local-and-online" }); + await searchPlaces("pizzeria a lingotto", { center: centre, policy: "local-and-online" }); + // Stop codes and line names are answered from the bundled GTT catalog. + for (const query of ["472", "fermata 472", "stop 472", "fermate castello", "M1", "linea 4", "bus 15", "tram 4", "metro M1", "10N"]) await searchPlaces(query, { center: centre, policy: "local-and-online" }); + assert.equal(requests, 0); + const result = await searchPlaces("via nizza 230 online fixture", { center: centre, policy: "local-and-online" }); + const byId = new Map(result.places.map((place) => [place.id, place])); + assert.deepEqual([byId.get("osm:N:1")?.kind, byId.get("osm:N:1")?.name, byId.get("osm:N:1")?.address], ["address", "Via Nizza 230", "10126 Torino"]); + assert.equal(byId.get("osm:W:2")?.kind, "street"); + assert.equal(byId.get("osm:N:3")?.kind, "area"); + assert.equal(byId.get("osm:N:4")?.kind, "place", "a named highway object such as a bus stop is not a street"); + assert.equal(byId.get("osm:N:4")?.name, "Porta Nuova"); + assert.equal(requests, 1); + } finally { global.fetch = original; } +}); diff --git a/src/services/search.ts b/src/services/search.ts index e99b3df..1583e21 100644 --- a/src/services/search.ts +++ b/src/services/search.ts @@ -1,7 +1,9 @@ -import type { Coordinate, Place, SearchOptions, SearchResult } from "../domain/types"; +import type { Coordinate, Place, PlaceKind, SearchOptions, SearchResult } from "../domain/types"; import { distanceMeters, normalize } from "./geo"; import { checkAbort, fetchJSON, parseServiceData, requestQueue, ServiceError } from "./network"; import { getPlaceCoverage, LOCAL_SEARCH_RADIUS_METERS } from "./place-coverage"; +import localityData from "../data/localities.json"; +import { isTransitQuery } from "./transit-search"; import { correctionAttribution, placeCatalog, type CatalogPlace, type PlaceCatalog, type PlaceSearchEntry } from "./place-catalog"; const request = requestQueue(1000); const LOCAL_RESULT_LIMIT = 60; @@ -155,11 +157,12 @@ function createIndex(places: readonly PlaceSearchEntry[]) { ); return { place, name, nameWords, - allWords: [...nameWords, ...words(place.address ?? "")], + addressWords: words(place.address ?? ""), categoryTerms: categoryMembership(categories), }; }); } +type IndexEntry = ReturnType[number]; const index = createIndex(placeCatalog.entries); /** One insertion/deletion/substitution or adjacent transposition, only for full alphabetic tokens. */ @@ -179,33 +182,147 @@ function tokenMatches(token: string, word: string): boolean { return /^\d+$/.test(token) ? word === token : word.startsWith(token); } +/** A neighbourhood read from the bundled OpenStreetMap gazetteer; its radius is approximate. */ +export interface Locality { id: string; name: string; kind: string; coordinate: Coordinate; radiusMeters: number; words: string[] } +const LOCALITY_ATTRIBUTION = localityData.attribution; +const LOCALITIES: readonly Locality[] = localityData.localities.map((item) => ({ + id: item.id, name: item.name, kind: item.kind, radiusMeters: item.radiusMeters, + coordinate: { latitude: item.latitude, longitude: item.longitude }, words: words(item.name), +})); +// Linking words are optional: "farmacia in via Po" and "bar a San Salvario" read like their bare forms. +const FILLER_WORDS = new Set(["di", "del", "della", "dei", "delle", "da", "a", "al", "alla", "ai", "in", "presso", "vicino", "zona", "quartiere"]); + +/** How a typed query reads: its words, which are optional and which spell a known neighbourhood. */ +export interface QueryPlan { + normalized: string; + tokens: string[]; + /** Tokens that every match must account for. */ + required: boolean[]; + /** At most one neighbourhood, spelled by whole consecutive words. */ + locality: { locality: Locality; start: number; end: number } | null; + /** The whole query is one Italian category ("farmacie", "ristoranti"). */ + categoryTerms: string[]; +} + +export function planQuery(query: string): QueryPlan { + const normalized = normalize(query); + const tokens = words(normalized); + const optional = tokens.map((token) => FILLER_WORDS.has(token)); + const required = optional.some((item) => !item) ? optional.map((item) => !item) : tokens.map(() => true); + let locality: QueryPlan["locality"] = null; + // The longest neighbourhood spelled by whole words wins ("Barriera di Milano" over "Milano"). + for (const candidate of LOCALITIES) { + const size = candidate.words.length; + if (locality && locality.end - locality.start >= size) continue; + for (let start = 0; start + size <= tokens.length; start += 1) { + if (candidate.words.every((word, offset) => tokens[start + offset] === word)) { locality = { locality: candidate, start, end: start + size }; break; } + } + } + return { normalized, tokens, required, locality, categoryTerms: aliases[normalized] ?? [] }; +} + +/** Name evidence outranks category, address and area evidence; a typo is the weakest. */ +const NAME = 3, FIELD = 2, TYPO = 1; +function tokenEvidence(token: string, entry: IndexEntry): number { + if (!aliases[token] && entry.nameWords.some((word) => tokenMatches(token, word))) return NAME; + // A category word means the category or that whole word in the name: "bar" never matches + // "Barbagusto" or "Via Baretti". + if (aliases[token]) return entry.nameWords.includes(token) ? NAME : aliases[token]!.some((term) => entry.categoryTerms.has(term)) ? FIELD : 0; + if (entry.addressWords.some((word) => tokenMatches(token, word))) return FIELD; + return entry.nameWords.some((word) => oneTypo(token, word)) ? TYPO : 0; +} + +/** Adjacent query words found in the same order in the address, such as "via po" or "nizza 230". */ +function addressPhrase(tokens: string[], addressWords: string[]): number { + let best = 0; + for (let start = 0; start < tokens.length; start += 1) { + for (let at = 0; at < addressWords.length; at += 1) { + let length = 0; + while (start + length < tokens.length && at + length < addressWords.length && addressWords[at + length] === tokens[start + length]) length += 1; + best = Math.max(best, length); + } + } + return best > 1 ? best : 0; +} + +function localityPlace(locality: Locality, center: Coordinate): Place { + return { + id: `locality:${locality.id}`, name: locality.name, coordinate: { ...locality.coordinate }, kind: "area", + category: locality.kind, source: "OpenStreetMap (quartieri)", attributions: [LOCALITY_ATTRIBUTION], + dataUpdatedAt: localityData.osmBase ?? undefined, distanceMeters: distanceMeters(center, locality.coordinate), + }; +} + +type Match = { place: Place | PlaceSearchEntry; rank: number; score: number; distance: number; catalogIds: string[] }; + function localMatches(query: string, center: Coordinate, searchIndex = index, catalog = placeCatalog) { - const q = normalize(query); - const tokens = words(q); - const categoryTerms = aliases[q] ?? []; + const plan = planQuery(query); + const { normalized: q, tokens, required, locality, categoryTerms } = plan; const coverage = getPlaceCoverage(center, categoryTerms.length ? LOCAL_SEARCH_RADIUS_METERS : null, [...catalog.metadata.bounds]); - if (q.length < 2) return { groups: [] as PlaceGroup[], coverage }; - const matches: { place: PlaceSearchEntry; rank: number; exactTokens: number; distance: number }[] = []; + if (q.length < 2) return { groups: [] as PlaceGroup[], coverage, plan }; + const origin = locality?.locality.coordinate ?? center; + const matches: Match[] = []; for (const entry of searchIndex) { let rank = 0; + let score = 0; if (categoryTerms.length) { // A restaurant furniture supplier is not somewhere to eat, even if its name matches. if (categoryTerms.some((term) => entry.categoryTerms.has(term))) rank = 4; - } else if (entry.name === q) rank = 5; - else if (tokens.every((token) => entry.nameWords.some((word) => tokenMatches(token, word)))) rank = 4; - else if (tokens.every((token) => entry.allWords.some((word) => tokenMatches(token, word)))) rank = 3; - else if (tokens.every((token) => entry.nameWords.some((word) => tokenMatches(token, word) || oneTypo(token, word)))) rank = 2; + } else if (entry.name === q) rank = 6; + else { + let weakest = NAME; + let byName = 0; + let outsideArea = false; + let evaluated = 0; + score = 0; + for (const [i, token] of tokens.entries()) { + if (locality && i >= locality.start && i < locality.end) continue; + if (!required[i]) { if (entry.nameWords.includes(token)) score += 1; continue; } + evaluated += 1; + const evidence = tokenEvidence(token, entry); + if (evidence) outsideArea = true; + if (evidence === NAME) byName += 1; + weakest = Math.min(weakest, evidence); + // Category words describe what was asked for; distance, not their spelling, orders those matches. + if (!aliases[token]) score += (evidence === NAME ? 2 : 0) + (entry.nameWords.includes(token) || entry.addressWords.includes(token) ? 1 : 0); + } + if (locality) { + // The neighbourhood's words count as one: all in the name, all in the address, or the place lies inside it. + const span = tokens.slice(locality.start, locality.end); + const inName = span.every((token) => entry.nameWords.some((word) => tokenMatches(token, word))); + const inArea = inName || span.every((token) => entry.addressWords.includes(token)) + || distanceMeters(entry.place.coordinate, locality.locality.coordinate) <= locality.locality.radiusMeters; + evaluated += span.length; + if (inName) { byName += span.length; score += span.length * 2; } + if (!inArea) weakest = 0; + } + // Every required word is accounted for, and not only by the neighbourhood: "San Salvario" + // alone names the area, it does not list every business inside it. + if (weakest > 0 && outsideArea) { + rank = weakest === TYPO ? 2 : byName === evaluated ? 5 : 3; + score += addressPhrase(tokens, entry.addressWords) * 2; + } + } if (!rank) continue; const distance = distanceMeters(center, entry.place.coordinate); if (categoryTerms.length && distance > LOCAL_SEARCH_RADIUS_METERS) continue; matches.push({ - place: { ...entry.place, distanceMeters: distance }, rank, distance, - exactTokens: categoryTerms.length ? 0 : tokens.filter((token) => entry.nameWords.includes(token)).length, + place: { ...entry.place, distanceMeters: distance }, rank, score, catalogIds: [entry.place.id], + distance: origin === center ? distance : distanceMeters(origin, entry.place.coordinate), }); } - matches.sort((a, b) => b.rank - a.rank || b.exactTokens - a.exactTokens || + if (!categoryTerms.length && q.length >= 3) { + // The neighbourhood itself: first when named exactly, after full-name matches when typed partly. + for (const candidate of LOCALITIES) { + const key = candidate.words.join(" "); + if (key === q || (key.startsWith(q) && q.length >= 4)) { + matches.push({ place: localityPlace(candidate, center), rank: key === q ? 7 : 4.5, score: 0, catalogIds: [], distance: 0 }); + } + } + } + matches.sort((a, b) => b.rank - a.rank || b.score - a.score || a.distance - b.distance || a.place.id.localeCompare(b.place.id)); - return { groups: deduplicateGroups(matches.map(({ place }) => ({ place, catalogIds: [place.id] }))), coverage }; + return { groups: deduplicateGroups(matches.map(({ place, catalogIds }) => ({ place, catalogIds }))), coverage, plan }; } function limitedPlaces(groups: PlaceGroup[], limit: number, catalog: PlaceCatalog) { @@ -296,7 +413,70 @@ type PhotonResponse = { properties: Record; }[]; }; +const AREA_TYPES = new Set(["city", "district", "locality", "county", "state", "country"]); +/** One Photon feature as a result, labelled as a venue, civic address, street or area. */ +function photonPlace(feature: PhotonResponse["features"][number], center: Coordinate, query: string): Place[] { + if (!feature.geometry?.coordinates || feature.geometry.coordinates.length < 2) return []; + const p = feature.properties ?? {}; + const text = (value: unknown) => value === undefined || value === null || value === "" ? "" : String(value); + const coordinate = { longitude: feature.geometry.coordinates[0]!, latitude: feature.geometry.coordinates[1]! }; + const key = text(p.osm_key), value = text(p.osm_value), type = text(p.type); + const street = [text(p.street), text(p.housenumber)].filter(Boolean).join(" "); + const locality = [text(p.postcode), text(p.city)].filter(Boolean).join(" "); + const kind: PlaceKind = !p.name && (type === "house" || value === "house") && p.housenumber ? "address" + // Only Photon's street type is a street: named highway objects include bus stops (type "house"). + : type === "street" ? "street" + : key === "place" || key === "boundary" || AREA_TYPES.has(type) ? "area" : "place"; + const name = text(p.name) || (kind === "address" ? street : "") || text(p.street) || text(p.city) || query; + const address = kind === "address" ? locality : kind === "street" ? [text(p.district), locality].filter(Boolean).join(", ") + : [street, locality].filter(Boolean).join(", "); + return [{ + kind, id: `osm:${text(p.osm_type)}:${text(p.osm_id)}`, name, coordinate, + category: kind === "address" ? "house" : value, address, + source: "Photon / OpenStreetMap", attributions: ["© OpenStreetMap contributors · ODbL"], + distanceMeters: distanceMeters(center, coordinate), + }]; +} + +const PHOTON_CACHE_MS = 5 * 60_000; const cache = new Map(); +/** One rate-limited, cached Photon lookup; the same text and rounded bias reuse the answer for five minutes. */ +async function photon(text: string, bias: Coordinate, signal?: AbortSignal): Promise { + const key = `${normalize(text)}:${bias.latitude.toFixed(3)}:${bias.longitude.toFixed(3)}`; + const cached = cache.get(key); + if (cached && Date.now() - cached.at < PHOTON_CACHE_MS) return cached.places; + const params = new URLSearchParams({ q: text, lat: String(bias.latitude), lon: String(bias.longitude), limit: "12" }); + const result = await request( + () => fetchJSON(`https://photon.komoot.io/api/?${params}`, { signal }, 'photon'), + signal, + ); + const places = parseServiceData('photon', () => { + if (!Array.isArray(result.features)) + throw new ServiceError("Ricerca online: risposta non valida.", "invalid"); + return result.features.flatMap((feature) => photonPlace(feature, bias, text)); + }); + if (cache.size > 80) cache.clear(); + checkAbort(signal); + cache.set(key, { at: Date.now(), places }); + return places; +} + +/** The query without its neighbourhood words, keeping the typed spelling when it splits the same way. */ +function withoutLocality(query: string, plan: QueryPlan): string { + const span = plan.locality!; + const raw = query.trim().split(/\s+/); + const keep = raw.length === plan.tokens.length + ? raw.filter((_, i) => i < span.start || i >= span.end) + : plan.tokens.filter((_, i) => i < span.start || i >= span.end); + return keep.filter((word, i) => !FILLER_WORDS.has(normalize(word)) || i > 0 && i < keep.length - 1).join(" "); +} + +/** + * Local results first, then Photon for names and addresses when online search is allowed. When + * Photon finds nothing for a query that names a known neighbourhood ("Eataly Lingotto"), one more + * lookup sends only the remaining words, biased to that neighbourhood's public OSM node instead of + * the map centre, and keeps answers inside its approximate radius. + */ export async function searchPlaces( query: string, options: SearchOptions, @@ -304,65 +484,27 @@ export async function searchPlaces( checkAbort(options.signal); const q = query.trim(); const matches = localMatches(q, options.center); + const { plan } = matches; // Photon geocodes names and addresses; using it as category discovery returns unrelated distant names. + // Stop codes and line names ("472", "M1", "fermata 472", "linea 4") are answered from the bundled GTT catalog. + const transitOnly = isTransitQuery(q); + const categoryOnly = plan.categoryTerms.length > 0 || plan.tokens.every((token, i) => + !plan.required[i] || !!aliases[token] || (!!plan.locality && i >= plan.locality.start && i < plan.locality.end)); // Policy is checked before cache access too: opting out must never redisplay cached remote results. - if (normalize(q).length < 2 || options.policy === 'local-only' || aliases[normalize(q)]) { + if (plan.normalized.length < 2 || options.policy === 'local-only' || categoryOnly || transitOnly) { checkAbort(options.signal); return localResult(matches); } - const key = `${normalize(q)}:${options.center.latitude.toFixed(3)}:${options.center.longitude.toFixed(3)}`; let online: Place[] = []; try { - const cached = cache.get(key); - if (cached && Date.now() - cached.at < 5 * 60_000) online = cached.places; - else { - const params = new URLSearchParams({ - q, - lat: String(options.center.latitude), - lon: String(options.center.longitude), - limit: "12", - }); - const result = await request( - () => - fetchJSON(`https://photon.komoot.io/api/?${params}`, { - signal: options.signal, - }, 'photon'), - options.signal, - ); - online = parseServiceData('photon', () => { - if (!Array.isArray(result.features)) - throw new ServiceError( - "Ricerca online: risposta non valida.", - "invalid", - ); - return result.features.flatMap((f) => { - if (!f.geometry?.coordinates || f.geometry.coordinates.length < 2) - return []; - const p = f.properties; - const coordinate = { - longitude: f.geometry.coordinates[0]!, - latitude: f.geometry.coordinates[1]!, - }; - return [ - { - id: `osm:${p.osm_type}:${p.osm_id}`, - name: String(p.name ?? p.street ?? p.city ?? q), - coordinate, - category: String(p.osm_value ?? ""), - address: [p.street, p.housenumber, p.postcode, p.city] - .filter(Boolean) - .join(" "), - source: "Photon / OpenStreetMap", - attributions: ["© OpenStreetMap contributors · ODbL"], - distanceMeters: distanceMeters(options.center, coordinate), - }, - ]; - }); - }); - if (cache.size > 80) cache.clear(); - checkAbort(options.signal); - cache.set(key, { at: Date.now(), places: online }); - } + online = await photon(q, options.center, options.signal); + const remaining = plan.locality ? withoutLocality(q, plan) : ""; + if (!online.length && plan.locality && normalize(remaining).length >= 2) { + const area = plan.locality.locality; + online = (await photon(remaining, area.coordinate, options.signal)) + .filter((place) => distanceMeters(place.coordinate, area.coordinate) <= area.radiusMeters) + .map((place) => ({ ...place, distanceMeters: distanceMeters(options.center, place.coordinate) })); + } else online = online.map((place) => ({ ...place, distanceMeters: distanceMeters(options.center, place.coordinate) })); } catch (error) { checkAbort(options.signal); if (!matches.groups.length) throw error; diff --git a/src/services/transit-search.test.ts b/src/services/transit-search.test.ts new file mode 100644 index 0000000..ca83fe3 --- /dev/null +++ b/src/services/transit-search.test.ts @@ -0,0 +1,82 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import type { Stop } from '../domain/types'; +import { searchMapStops, searchRows, searchRowCount, showsSearch } from '../features/search/search-rows'; +import { endpointStops, isTransitQuery, searchTransit } from './transit-search'; + +const centre = { latitude: 45.0703, longitude: 7.6869 }; + +test('a typed stop code surfaces that stop, with or without the word fermata', () => { + for (const query of ['472', 'fermata 472', 'Fermata 472']) { + const result = searchTransit(query, centre); + assert.equal(result.code?.code, '472', query); + assert.equal(result.code?.name, 'Fermata 472 - CASTELLO'); + } + const short = searchTransit('47', centre).code; + assert.ok(!short || short.code === '47', 'codes match whole, never as a prefix'); + assert.equal(searchTransit('fermata 472', centre).explicit, true); + assert.equal(searchTransit('linea 472', centre).code, null, 'a line query is not a stop code'); +}); + +test('a line name offers that line’s nearest stops, nearest first', () => { + for (const [query, name] of [['15', '15'], ['M1', 'M1'], ['m1', 'M1'], ['linea 4', '4']] as const) { + const line = searchTransit(query, centre).line; + assert.equal(line?.name, name, query); + assert.ok(line!.stops.length > 0 && line!.stops.length <= 3); + assert.ok(line!.stops.every((stop) => stop.lines.includes(name))); + } + assert.equal(searchTransit('Eataly', centre).line, null); +}); + +test('stop names match whole typed words; numbers never match inside names', () => { + const named = searchTransit('lingotto', centre).named; + assert.ok(named.length > 0 && named.every((stop) => /lingotto/i.test(stop.name))); + assert.deepEqual(searchTransit('230', centre).named, []); + assert.deepEqual(searchTransit('li', centre).named, []); +}); + +const stop = (id: string, code: string, lines: string[] = ['15']): Stop => ({ id, code, name: `Fermata ${code} - PROVA`, coordinate: centre, lines }); +const place = { id: 'p', name: 'Luogo', coordinate: centre, source: 'Fixture', attributions: [] }; + +test('rows lead with a typed code and line, then places; named stops follow unless asked for', () => { + const code = stop('a', '472'); + const rows = searchRows([place], { code, line: { name: '15', stops: [stop('b', '471')] }, named: [stop('c', '9')], explicit: false }); + assert.deepEqual(rows.map((row) => row.kind === 'section' ? `#${row.title}` : row.kind), ['#Fermata', 'stop', '#Linea 15 · fermate vicine', 'stop', '#Luoghi e indirizzi', 'place', '#Fermate', 'stop']); + assert.equal(searchRowCount(rows), 4); + const asked = searchRows([place], { code: null, line: null, named: [stop('c', '9')], explicit: true }); + assert.deepEqual(asked.map((row) => row.kind === 'section' ? `#${row.title}` : row.kind), ['#Fermate', 'stop', '#Luoghi e indirizzi', 'place']); + assert.deepEqual(searchRows([place], { code: null, line: null, named: [], explicit: false }).map((row) => row.kind), ['place'], 'one kind needs no heading'); +}); + +test('one-character stop codes and lines open results; other single characters do not', () => { + const four = searchTransit('4', centre); + assert.ok(four.line, 'line 4 exists'); + assert.equal(showsSearch('4', four), true); + assert.equal(showsSearch('x', searchTransit('x', centre)), false); + assert.equal(showsSearch('ba', searchTransit('ba', centre)), true); +}); + +test('endpoint editors offer a line’s nearest stops, deduplicated with code and name matches', () => { + for (const query of ['M1', 'linea 4']) { + const stops = endpointStops(searchTransit(query, centre)); + assert.ok(stops.length > 0 && stops.length <= 3, query); + } + const a = stop('a', '1'); const b = stop('b', '2'); + assert.deepEqual(endpointStops({ code: a, line: { name: '15', stops: [a, b] }, named: [b], explicit: false }).map((item) => item.id), ['a', 'b']); +}); + +test('every recognised transit prefix and code-shaped token is a device-only query', () => { + for (const query of ['472', 'fermata 472', 'stop 472', 'bus 15', 'tram 4', 'metro M1', 'linea 4', 'M1', '10N', 'Fermate Castello']) assert.equal(isTransitQuery(query), true, query); + for (const query of ['Eataly', 'via nizza 230', 'porta nuova', 'bar 24']) assert.equal(isTransitQuery(query), false, query); +}); + +test('the map pins every listed stop and frames name matches when they lead or nothing else matched', () => { + const a = stop('a', '1'); const b = stop('b', '2'); + assert.deepEqual(searchMapStops({ code: null, line: null, named: [a, b], explicit: true }, 5), { pinned: [a, b], framed: [a, b] }); + assert.deepEqual(searchMapStops({ code: null, line: null, named: [a], explicit: false }, 0), { pinned: [a], framed: [a] }); + assert.deepEqual(searchMapStops({ code: null, line: null, named: [a], explicit: false }, 3), { pinned: [a], framed: [] }, 'places lead, so they are framed'); + assert.deepEqual(searchMapStops({ code: a, line: { name: '15', stops: [a, b] }, named: [], explicit: false }, 3), { pinned: [a, b], framed: [a, b] }); + const castello = searchTransit('fermata castello', centre); + assert.ok(castello.named.length > 0); + assert.equal(searchMapStops(castello, 0).framed.length, castello.named.length); +}); diff --git a/src/services/transit-search.ts b/src/services/transit-search.ts new file mode 100644 index 0000000..cba7141 --- /dev/null +++ b/src/services/transit-search.ts @@ -0,0 +1,77 @@ +import type { Coordinate, Place, Stop } from '../domain/types'; +import { catalogStops } from '../transit-data/stop-catalog'; +import { distanceMeters, normalize } from './geo'; + +/** Stops and lines named by a search, from the bundled GTT stop catalog (no request leaves the device). */ +export interface TransitSearch { + /** The stop whose code was typed ("472", "fermata 472"). */ + code: Stop | null; + /** A line typed by name ("15", "M1", "linea 4") and its stops nearest the reference point. */ + line: { name: string; stops: Stop[] } | null; + /** Stops whose names contain every typed word, nearest first. */ + named: Stop[]; + /** The query asked for transport explicitly ("fermata …", "linea …"), so these lead the results. */ + explicit: boolean; +} + +export const EMPTY_TRANSIT_SEARCH: TransitSearch = { code: null, line: null, named: [], explicit: false }; +const STOP_WORDS = new Set(['fermata', 'fermate', 'stop']); +const LINE_WORDS = new Set(['linea', 'linee', 'line', 'bus', 'tram', 'metro']); +/** Nearby stops offered for a line. */ +export const LINE_STOP_LIMIT = 3; +const NAMED_LIMIT = 3; + +const CODE_OR_LINE = /^(?:\d{1,5}|[a-z]{1,2}\d{1,4}[a-z]?|\d{1,4}[a-z])$/; +/** + * The query asks for transport and is answered only from the bundled catalog: it starts with a stop + * or line word ("fermata", "stop", "linea", "bus", "tram", "metro", …) or is one code-or-line-shaped + * token ("472", "M1", "10N"). Such text never goes to an online geocoder. + */ +export function isTransitQuery(query: string): boolean { + const tokens = normalize(query).split(' ').filter(Boolean); + if (!tokens.length) return false; + return STOP_WORDS.has(tokens[0]!) || LINE_WORDS.has(tokens[0]!) || (tokens.length === 1 && CODE_OR_LINE.test(tokens[0]!)); +} + +const nameWords = (stop: Stop) => normalize(stop.name.replace(/^Fermata\s+\d+\s*-\s*/i, '')).split(' ').filter(Boolean); +const nearest = (stops: readonly Stop[], center: Coordinate, limit: number) => stops + .map(stop => ({ stop, distance: distanceMeters(center, stop.coordinate) })) + .sort((a, b) => a.distance - b.distance || a.stop.id.localeCompare(b.stop.id)).slice(0, limit).map(item => item.stop); + +export function searchTransit(query: string, center: Coordinate, stops: readonly Stop[] = catalogStops()): TransitSearch { + const tokens = normalize(query).split(' ').filter(Boolean); + if (!tokens.length) return EMPTY_TRANSIT_SEARCH; + const askedStop = STOP_WORDS.has(tokens[0]!); + const askedLine = LINE_WORDS.has(tokens[0]!); + const rest = askedStop || askedLine ? tokens.slice(1) : tokens; + const text = rest.join(' '); + if (!text) return EMPTY_TRANSIT_SEARCH; + const code = !askedLine && /^\d{1,5}$/.test(text) ? stops.find(stop => stop.code === text) ?? null : null; + let line: TransitSearch['line'] = null; + if (!askedStop && text.length <= 8) { + const serving = stops.filter(stop => stop.lines.some(name => normalize(name) === text)); + const name = serving[0]?.lines.find(item => normalize(item) === text); + if (name) line = { name, stops: nearest(serving, center, LINE_STOP_LIMIT) }; + } + // A bare number is a code or a line, never a fragment of a stop name. + const named = /^\d+$/.test(text) || text.length < 3 || askedLine ? [] : nearest(stops.filter(stop => { + const words = nameWords(stop); + return rest.every(token => words.some(word => word.startsWith(token))); + }), center, NAMED_LIMIT).filter(stop => stop.id !== code?.id); + return { code, line, named, explicit: askedStop || askedLine }; +} + +/** A stop as a route endpoint (the planner plans to and from places). */ +export function stopAsPlace(stop: Stop): Place { + return { + id: `stop:${stop.id}`, name: stop.name, coordinate: { ...stop.coordinate }, category: 'Fermata GTT', + address: `Fermata ${stop.code}${stop.lines.length ? ` · linee ${stop.lines.slice(0, 6).join(', ')}` : ''}`, + source: 'GTT', attributions: ['Dati GTT'], + }; +} + +/** Stops a search offers as route endpoints: the typed code, the line's nearest stops, then name matches. */ +export function endpointStops(transit: TransitSearch): Stop[] { + const stops = [...(transit.code ? [transit.code] : []), ...(transit.line?.stops ?? []), ...transit.named]; + return stops.filter((stop, index) => stops.findIndex(other => other.id === stop.id) === index); +} diff --git a/src/ui/Text.tsx b/src/ui/Text.tsx index 47b54db..694a659 100644 --- a/src/ui/Text.tsx +++ b/src/ui/Text.tsx @@ -1,6 +1,6 @@ import { Children, type ReactNode } from "react"; import { Text as NativeText, type TextProps } from "react-native"; -import { numericRuns } from "./numeric-runs"; +import { numberParts, numericRuns } from "./numeric-runs"; const explicitFamily = /(^|\s)font-(sans|mono|display)(\s|$)/; @@ -15,12 +15,14 @@ export function Text({ className, ...props }: TextProps & { className?: string } /** * Times, minutes, distances, stop codes and accuracy: digits in Geist Mono with tabular figures; - * spaces, colons and units in Geist Sans so "64 m" and "23:33" stay tight (see numeric-runs.ts). + * spaces, colons, units and the decimal/thousands separator glyph in Geist Sans so "64 m", "23:33" + * and "4,2 km" stay tight (see numeric-runs.ts). */ export function Num({ className, style, children, ...props }: TextProps & { className?: string }) { // Keys combine the child and run positions so several string children never collide. const parts = Children.toArray(children).flatMap((child, childIndex): ReactNode[] => typeof child === "string" || typeof child === "number" - ? numericRuns(String(child)).map((run, index) => run.numeric ? run.text : {run.text}) + ? numericRuns(String(child)).flatMap((run, index): ReactNode[] => !run.numeric ? [{run.text}] + : numberParts(run.text).map((part, partIndex) => part.separator ? {part.text} : part.text)) : [child]); return {parts}; } diff --git a/src/ui/numeric-runs.test.ts b/src/ui/numeric-runs.test.ts index 5063be3..9e984f2 100644 --- a/src/ui/numeric-runs.test.ts +++ b/src/ui/numeric-runs.test.ts @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { numericRuns } from './numeric-runs'; +import { numberParts, numericRuns } from './numeric-runs'; test('digits stay monospaced while separators and units are set apart', () => { assert.deepEqual(numericRuns('64 m'), [{ text: '64', numeric: true }, { text: ' m', numeric: false }]); @@ -10,3 +10,15 @@ test('digits stay monospaced while separators and units are set apart', () => { assert.deepEqual(numericRuns('M1'), [{ text: 'M', numeric: false }, { text: '1', numeric: true }]); assert.equal(numericRuns('').length, 0); }); + +test('decimal and thousands separators stay inside the number run; units, spaces and time colons do not', () => { + assert.deepEqual(numericRuns('4,2 km'), [{ text: '4,2', numeric: true }, { text: ' km', numeric: false }]); + assert.deepEqual(numericRuns('1.250 m'), [{ text: '1.250', numeric: true }, { text: ' m', numeric: false }]); + assert.deepEqual(numericRuns('23:51'), [{ text: '23', numeric: true }, { text: ':', numeric: false }, { text: '51', numeric: true }]); + assert.deepEqual(numericRuns('64 m'), [{ text: '64', numeric: true }, { text: ' m', numeric: false }]); + // Inside the run, only the separator glyph leaves the monospaced cell (no gap around the comma). + assert.deepEqual(numberParts('4,2'), [{ text: '4', separator: false }, { text: ',', separator: true }, { text: '2', separator: false }]); + assert.deepEqual(numberParts('1.250'), [{ text: '1', separator: false }, { text: '.', separator: true }, { text: '250', separator: false }]); + assert.deepEqual(numberParts('64'), [{ text: '64', separator: false }]); + assert.equal(numberParts('12.345,6').map(part => part.text).join(''), '12.345,6'); +}); diff --git a/src/ui/numeric-runs.ts b/src/ui/numeric-runs.ts index 76f59a0..73d94f6 100644 --- a/src/ui/numeric-runs.ts +++ b/src/ui/numeric-runs.ts @@ -11,3 +11,12 @@ export function numericRuns(text: string): { text: string; numeric: boolean }[] } return runs; } + +/** + * A number's digit groups and the decimal/thousands separators between them ("4,2" → 4 | , | 2). + * The separators stay inside the number, but Geist Mono gives a comma or point a full digit cell, so + * "4,2 km" read as "4 , 2 km"; Num draws only the separator glyph in Geist Sans, keeping digits tabular. + */ +export function numberParts(number: string): { text: string; separator: boolean }[] { + return [...number.matchAll(/(\d+)|([.,])/g)].map(match => ({ text: match[0], separator: match[2] !== undefined })); +}