From db98ca20ee4bc435c6165b4e7f1d936dd97ab6a3 Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 9 Nov 2026 11:50:26 -0800 Subject: [PATCH] Navigation: Easy sharing and cleaner pages --- openpilot/starpilot/galaxy/server.py | 28 +- .../tests/browser/navigation-compact.cjs | 4 +- .../galaxy/tests/test_navigation.mjs | 45 +++ .../galaxy/tests/test_navigation_http.py | 53 ++- .../galaxy/tests/test_navigation_map.mjs | 30 ++ openpilot/starpilot/galaxy/web/css/galaxy.css | 2 +- .../starpilot/galaxy/web/css/navigation.css | 67 +++- .../galaxy/web/css/offline-road-maps.css | 32 +- .../starpilot/galaxy/web/data/catalog.json | 2 +- .../starpilot/galaxy/web/js/navigation-map.js | 35 +- .../galaxy/web/js/navigation-setup.js | 81 ++++ .../starpilot/galaxy/web/js/navigation.js | 356 +++++++++++------- .../galaxy/web/js/offline-road-maps.js | 51 ++- .../starpilot/galaxy/web/js/onroad-layout.js | 39 +- .../starpilot/navigation/google_places.py | 141 +++++++ .../starpilot/navigation/google_routes.py | 10 +- .../starpilot/navigation/google_tiles.py | 67 +++- openpilot/starpilot/navigation/owner.py | 243 ++++++++++-- openpilot/starpilot/navigation/share.py | 55 +++ .../navigation/tests/test_google_routes.py | 2 +- .../navigation/tests/test_google_search.py | 136 +++++++ .../navigation/tests/test_google_tiles.py | 15 + .../navigation/tests/test_map_tiles.py | 24 ++ .../starpilot/navigation/tests/test_owner.py | 214 ++++++++++- 24 files changed, 1476 insertions(+), 256 deletions(-) create mode 100644 openpilot/starpilot/galaxy/web/js/navigation-setup.js create mode 100644 openpilot/starpilot/navigation/google_places.py create mode 100644 openpilot/starpilot/navigation/share.py create mode 100644 openpilot/starpilot/navigation/tests/test_google_search.py diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index 4dc4d7b934..fcb9928241 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -1011,15 +1011,19 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe self.json(400, {'error': 'Invalid map tile'}) return try: - query = parse_qs(urlsplit(self.path).query, keep_blank_values=True, max_num_fields=1) - theme = query.get('theme', ['light'])[0] - if set(query) - {'theme'} or theme not in ('light', 'dark'): + query = parse_qs(urlsplit(self.path).query, keep_blank_values=True, max_num_fields=2) + theme = query.get('theme', ['light']) + provider = query.get('provider', ['mapbox']) + if (set(query) - {'theme', 'provider'} or len(theme) != 1 or theme[0] not in ('light', 'dark') or + len(provider) != 1 or provider[0] not in ('mapbox', 'google')): raise ValueError('Invalid map theme') except ValueError: self.json(400, {'error': 'Invalid map theme'}) return try: - tile = navigation_owner().map_tile(*(int(value) for value in match.groups()), theme) + coords = (int(value) for value in match.groups()) + tile = (navigation_owner().map_tile(*coords, theme[0], provider='google') + if provider[0] == 'google' else navigation_owner().map_tile(*coords, theme[0])) except (OSError, ValueError, RuntimeError): self.json(503, {'error': 'Map tiles are unavailable'}) else: @@ -1888,15 +1892,16 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe raise ValidationError('Enter a destination to search') if 'autocomplete' in payload and payload['autocomplete'] is not True: raise ValidationError('Enter a destination to search') - result = {'results': (navigation_owner().search_places(payload['query'], identity, payload['searchId'], payload['clientId'], - autocomplete='autocomplete' in payload) - if 'searchId' in payload else navigation_owner().search(payload['query']))} + results = (navigation_owner().search_places(payload['query'], identity, payload['searchId'], payload['clientId'], + autocomplete='autocomplete' in payload) + if 'searchId' in payload else navigation_owner().search(payload['query'])) + result = {'results': results, 'provider': getattr(results, 'provider', 'mapbox')} else: fields = {'configure': {'patch'}, 'select': {'destination'}, 'selectPlace': {'id', 'searchId'}, 'cancelSearch': {'searchId'}, 'clear': set(), 'favorite': {'destination'}, 'favoritePlace': {'id', 'searchId'}, 'removeFavorite': {'id'}, 'labelFavorite': {'id', 'label'}, 'removeRecent': {'id'}, 'clearRecents': set(), 'selectRoute': {'index'}, 'testGoogleKey': set(), - 'resolveShare': {'text'}} + 'resolveShare': {'text'}, 'share': {'text'}} action = payload.get('action') optional = ({'label'} if action in ('favorite', 'favoritePlace') and 'label' in payload else {'key'} if action == 'testGoogleKey' and 'key' in payload else set()) @@ -1905,7 +1910,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe needs_park = action == 'configure' and isinstance(payload['patch'], dict) and bool({'token', 'googleKey'} & payload['patch'].keys()) def authorized(): return self.settings_session() == identity and (not needs_park or configuration_allowed()) - with (nullcontext() if action in ('selectPlace', 'favoritePlace', 'testGoogleKey', 'resolveShare') else effect_lock): + with (nullcontext() if action in ('selectPlace', 'favoritePlace', 'testGoogleKey', 'resolveShare', 'share') else effect_lock): if not authorized(): raise PermissionError('Park your car before changing a map key' if needs_park else 'Sign in to Galaxy') nav = navigation_owner() @@ -1916,6 +1921,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe result = dict(nav.snapshot(), googleKeyTest=nav.test_google_key(payload.get('key'))) elif action == 'resolveShare': result = dict(nav.snapshot(), sharedText=nav.resolve_share(payload['text'])) + elif action == 'share': + result = nav.share(payload['text'], **keywords) elif action == 'selectPlace': result = nav.select_place(payload['id'], payload['searchId'], identity, **keywords) elif action == 'cancelSearch': @@ -1945,7 +1952,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe except ConflictError as error: self.json(409, {'error': str(error)}) except ValidationError as error: - self.json(400, {'error': str(error)}) + query = getattr(error, 'query', None) + self.json(400, {'error': str(error), **({'query': query} if query else {})}) except PermissionError as error: if self.require_session(): self.json(409, {'error': str(error)}) diff --git a/openpilot/starpilot/galaxy/tests/browser/navigation-compact.cjs b/openpilot/starpilot/galaxy/tests/browser/navigation-compact.cjs index 34d8d28b8e..1575ec88b5 100644 --- a/openpilot/starpilot/galaxy/tests/browser/navigation-compact.cjs +++ b/openpilot/starpilot/galaxy/tests/browser/navigation-compact.cjs @@ -87,14 +87,14 @@ const status = { enabled: true, hasKey: true, isMetric: true, status: 'noDestina await page.screenshot({ path: `/private/tmp/navigation-offline-${width}.png`, fullPage: true }) } await offlineLink.click() - await page.getByText('Map Overlay Roads', { exact: true }).waitFor() + await page.getByText('Offline Map Management', { exact: true }).waitFor() assert.equal(await page.getByRole('button', { name: 'Offline Maps', exact: true }).getAttribute('aria-pressed'), 'true') await page.getByRole('button', { name: 'Destination', exact: true }).click() status.network = 'unknown' await page.evaluate(() => window.navigation.client.load()) assert.equal(await offlineLink.count(), 0, 'unknown device state must not be presented as offline') await page.goto('http://navigation.test/?shell=1#/navigation/maps') - await page.getByText('Map Overlay Roads', { exact: true }).waitFor() + await page.getByText('Offline Map Management', { exact: true }).waitFor() assert.equal(await page.getByRole('button', { name: 'Offline Maps', exact: true }).getAttribute('aria-pressed'), 'true') await page.getByRole('button', { name: 'Destination', exact: true }).click() await page.waitForURL('**#/navigation') diff --git a/openpilot/starpilot/galaxy/tests/test_navigation.mjs b/openpilot/starpilot/galaxy/tests/test_navigation.mjs index 9e30757c04..b1212027e5 100644 --- a/openpilot/starpilot/galaxy/tests/test_navigation.mjs +++ b/openpilot/starpilot/galaxy/tests/test_navigation.mjs @@ -257,4 +257,49 @@ console.log("Local HTTP search UUID fallback passed") assert.ok(NavigationPage.template.includes(' body.text.includes("!3d") ? response({ ...snapshot("s"), enabled: true, destination: place, shared: place }) : + body.text === "Atlantis" ? response({ error: "No map location found for Atlantis" }, 400) : + response({ error: "Open StarPilot to search for Starbucks", query: "Starbucks" }, 400), + configure: () => { off = false; return response({ ...snapshot("c"), enabled: true }) } } + const client = new NavigationClient({ publish: (state) => states.push(state), later: () => 0, cancelTimer: () => {}, + fetcher: async (url, options) => { + const body = options.body ? JSON.parse(options.body) : null + sent.push({ url, body }) + if (url.includes("/search")) return response({ results: [place], provider: "google" }) + if (body?.action) return answers[body.action](body) + return response({ ...snapshot(), enabled: !off }) + } }) + await client.start() + const page = { client, query: "" } + await NavigationPage.methods.openShared.call(page, "Starbucks") + assert.deepEqual(sent.slice(1).map(({ url, body }) => body?.action || url), ["share", "configure", "./api/navigation/search"]) + assert.equal(page.query, "Starbucks") + assert.equal(sent.at(-1).body.query, "Starbucks") + const shown = states.at(-1) + assert.deepEqual([shown.results, shown.resultsProvider, shown.error, shown.stale, shown.data.enabled], [[place], "google", "", false, true]) + sent.length = 0 + await NavigationPage.methods.openShared.call(page, "https://www.google.com/maps/place/Library/data=!3d41!4d-88") + assert.deepEqual(sent.map(({ body }) => body?.action), ["share"]) + assert.equal(states.at(-1).data.destination.name, "Library") + sent.length = 0 + page.query = "" + await NavigationPage.methods.openShared.call(page, "Atlantis") + assert.deepEqual([sent.length, page.query, states.at(-1).error], [1, "", "No map location found for Atlantis"]) + assert.equal(client.refusal, null) + client.stop() + assert.equal(NavigationPage.computed.googlePlaces.call({ data: { routeProvider: "google", hasGoogleKey: true } }), true) + assert.equal(NavigationPage.computed.googlePlaces.call({ data: { routeProvider: "mapbox", hasGoogleKey: true } }), false) + const tests = NavigationPage.computed.googleTests.call({ googleTest: { ok: true, message: "map", routes: { ok: false, failure: "disabled", message: "off" }, + places: { ok: false, failure: "budget", message: "used up" } } }) + assert.deepEqual(tests.map((row) => [row.name, row.ok, row.missing, row.link?.href]), [["Map Tiles API", true, false, undefined], + ["Routes API", false, true, "https://console.cloud.google.com/apis/library/routes.googleapis.com"], ["Places API (New)", false, false, undefined]]) + assert.equal(NavigationPage.computed.googleWorking.call({ googleTests: tests }), "2 of 3 APIs working") + assert.ok(NavigationPage.template.includes("Google isn't used until the Mapbox key above is added too.")) + console.log("Shared places: comma lookup, 400 query search, navigation turned on, Google source and key test summary passed") +} await import("./test_navigation_map.mjs") diff --git a/openpilot/starpilot/galaxy/tests/test_navigation_http.py b/openpilot/starpilot/galaxy/tests/test_navigation_http.py index 31e079633e..e09d891cba 100644 --- a/openpilot/starpilot/galaxy/tests/test_navigation_http.py +++ b/openpilot/starpilot/galaxy/tests/test_navigation_http.py @@ -169,10 +169,13 @@ class NavigationHttpTest(unittest.TestCase): status, body, _ = self.action('configure', patch={'googleKey': key, 'mapProvider': 'google'}) self.assertEqual((status, body['hasGoogleKey'], body['mapProvider']), (200, True, 'google')) self.assertNotIn(key, json.dumps(self.request('/api/navigation/status', cookie=self.local_cookie)[1])) - with patch('openpilot.starpilot.navigation.google_tiles.test_key', return_value={'ok': False, 'message': 'Billing is off'}) as tested: + with (patch('openpilot.starpilot.navigation.google_tiles.test_key', return_value={'ok': False, 'message': 'Billing is off'}) as tested, + patch('openpilot.starpilot.navigation.google_routes.test_routes', return_value={'ok': True, 'failure': None, 'message': 'routes'}), + patch('openpilot.starpilot.navigation.google_places.test_places', return_value={'ok': True, 'failure': None, 'message': 'places'})): self.parked = False status, body, _ = self.action('testGoogleKey') self.assertEqual((status, body['googleKeyTest']['message'], body['hasGoogleKey']), (200, 'Billing is off', True)) + self.assertEqual((body['googleKeyTest']['routes']['ok'], body['googleKeyTest']['places']['message']), (True, 'places')) self.assertEqual(self.action('testGoogleKey', key='AIzaSyOtherKey_0123456789abcdefgh')[0], 200) self.assertEqual([call.args[0] for call in tested.call_args_list], [key, 'AIzaSyOtherKey_0123456789abcdefgh']) self.assertEqual(self.action('testGoogleKey', key='bad key')[0], 400) @@ -186,6 +189,33 @@ class NavigationHttpTest(unittest.TestCase): resolved.assert_called_once_with('Bellagio https://maps.app.goo.gl/abc123') self.assertEqual(self.action('resolveShare')[0], 400) + def test_shared_place_turns_navigation_on_and_starts_the_route(self): + self.assertEqual(self.action('share', text='geo:40.5,-89.5')[1], {'error': 'Add your Mapbox access token first'}) + self.navigation.configure({'token': 'pk.test'}, self.navigation.read()['revision'], True) + self.assertFalse(self.navigation.snapshot()['enabled']) + status, body, _ = self.action('share', remote=True, text='https://www.google.com/maps/place/Bellagio/data=!3d36.1126!4d-115.1767') + self.assertEqual(status, 200) + self.assertEqual(body['shared'], {'name': 'Bellagio', 'latitude': 36.1126, 'longitude': -115.1767}) + self.assertTrue(body['enabled'] and body['hasKey']) + self.assertEqual((body['destination']['latitude'], body['revision']), (36.1126, self.navigation.snapshot()['revision'])) + self.assertNotIn('pk.test', json.dumps(body)) + feature = {'features': [{'properties': {'name': '3600 S Las Vegas Blvd', 'full_address': '3600 S Las Vegas Blvd, Las Vegas, NV'}, + 'geometry': {'coordinates': [-115.17, 36.11]}}]} + with patch('openpilot.starpilot.navigation.owner.response_json', return_value=feature) as geocode: + status, body, _ = self.action('share', text='https://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd,+Las+Vegas,+NV/data=!4m2!3m1!1s0x1:0x2') + self.assertEqual((status, body['shared']), (200, {'name': 'Bellagio', 'latitude': 36.11, 'longitude': -115.17})) + self.assertEqual(geocode.call_args.args[2]['q'], '3600 S Las Vegas Blvd, Las Vegas, NV') + with patch('openpilot.starpilot.navigation.owner.response_json', return_value={'features': []}): + self.assertEqual(self.action('share', text='https://maps.google.com/?q=Nowhere,+Atlantis')[1], + {'error': 'No map location found for Nowhere', 'query': 'Nowhere, Atlantis'}) + self.assertEqual(self.action('share', text='Starbucks')[:2], (400, {'error': 'Open StarPilot to search for Starbucks', 'query': 'Starbucks'})) + revision = self.navigation.read()['revision'] + stale = {'action': 'share', 'revision': '0', 'text': 'geo:40.5,-89.5'} + self.assertEqual(self.request('/api/navigation/action', payload=stale, cookie=self.local_cookie)[0], 409) + self.assertEqual(self.navigation.read()['revision'], revision) + self.assertEqual(self.action('share')[0], 400) + self.assertNotIn('query', self.action('share', text='x' * 8193)[1]) + def test_stale_or_invalid_actions_never_overwrite_configuration(self): self.action('configure', patch={'enabled': True}) before = self.navigation.path.read_bytes() @@ -233,6 +263,27 @@ class NavigationHttpTest(unittest.TestCase): self.assertEqual(self.action('clearRecents')[1]['recents'],[]) self.assertEqual(self.action('removeFavorite',id=place)[1]['favorites'],[]) + def test_search_names_the_provider_that_found_the_places(self): + self.action('configure', patch={'token':'pk.synthetic','enabled':True}) + def search(): + return {'query':'bellagio', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())} + suggestion = {'suggestions':[{'mapbox_id':'poi/id','name':'Coffee Shop','feature_type':'poi'}]} + with patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion): + self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox') + key = 'AIzaSyFixtureKey_0123456789abcdef' + self.action('configure', patch={'googleKey':key, 'routeProvider':'google'}) + found = [{'name':'Bellagio','address':'3600 S Las Vegas Blvd','latitude':36.1126,'longitude':-115.1767}] + with patch('openpilot.starpilot.navigation.google_places.text_search', return_value=found) as google: + status, result, _ = self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie) + self.assertEqual((status, result['provider'], result['results'][0]['name']), (200, 'google', 'Bellagio')) + self.assertNotIn('searchId', result['results'][0]) + self.assertEqual(google.call_args.args[1], key) + self.assertNotIn(key, json.dumps(result)) + from openpilot.starpilot.navigation.google_places import GooglePlacesFailed + with (patch('openpilot.starpilot.navigation.google_places.text_search', side_effect=GooglePlacesFailed('budget')), + patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion)): + self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox') + def test_temporary_search_result_cannot_be_saved(self): self.action('configure', patch={'token':'pk.synthetic','enabled':True}) search = {'query':'coffee', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())} diff --git a/openpilot/starpilot/galaxy/tests/test_navigation_map.mjs b/openpilot/starpilot/galaxy/tests/test_navigation_map.mjs index a09c0fdc0b..24f16633ef 100644 --- a/openpilot/starpilot/galaxy/tests/test_navigation_map.mjs +++ b/openpilot/starpilot/galaxy/tests/test_navigation_map.mjs @@ -186,3 +186,33 @@ console.log('Follow, pinch and double-tap zoom passed') globalThis.requestAnimationFrame = originalRaf; globalThis.cancelAnimationFrame = originalCancelRaf } console.log('Live map theme changes: correct requests, cache disposal, late-response isolation, camera preservation and observer cleanup passed') + +{ + // Switching mapProvider between Mapbox and Google clears cached tiles, appends provider=google, and crops 256px parent tiles. + const savedFetch = globalThis.fetch, savedBitmap = globalThis.createImageBitmap + globalThis.requestAnimationFrame = fn => { frames.set(++frameId, fn); return frameId } + globalThis.cancelAnimationFrame = id => frames.delete(id) + const urls = [] + let closed = 0 + globalThis.fetch = async url => { urls.push(url); return { ok: true, blob: async () => ({}) } } + globalThis.createImageBitmap = async () => ({ width: 256, close() { closed++ } }) + const switched = new RasterMap(canvas) + switched.draw = () => {} + switched.update({ mapProvider: 'mapbox', hasGoogleKey: true }, false) + await switched.load('1/0/0') + assert.ok(urls.at(-1).endsWith('1/0/0.png?theme=dark')) + assert.equal(switched.tiles.size, 1) + const crop = switched.placeholder(2, 1, 1) + assert.deepEqual(crop.slice(1), [128, 128, 128], '256px Google/custom tiles crop using their actual bitmap width') + switched.update({ mapProvider: 'google', hasGoogleKey: true }, false) + assert.equal(switched.tiles.size, 0, 'switching map provider clears cached tiles from the previous provider') + assert.equal(closed, 1) + await switched.load('1/0/0') + assert.ok(urls.at(-1).endsWith('1/0/0.png?theme=dark&provider=google')) + switched.update({ mapProvider: 'google', hasGoogleKey: true, googleMap: { failure: 'Quota reached' } }, false) + assert.equal(switched.provider, 'mapbox', 'a Google map failure falls back to Mapbox tiles') + switched.close() + globalThis.fetch = savedFetch; globalThis.createImageBitmap = savedBitmap + globalThis.requestAnimationFrame = originalRaf; globalThis.cancelAnimationFrame = originalCancelRaf +} +console.log('Map provider switching: Google tile URL, cache invalidation, fallback, and 256px placeholder cropping passed') diff --git a/openpilot/starpilot/galaxy/web/css/galaxy.css b/openpilot/starpilot/galaxy/web/css/galaxy.css index 9436e615d9..d66862475a 100644 --- a/openpilot/starpilot/galaxy/web/css/galaxy.css +++ b/openpilot/starpilot/galaxy/web/css/galaxy.css @@ -1390,7 +1390,7 @@ background: var(--surface-container-high); color: var(--on-surface-variant); bor .gx-starport-pill:has(> i)::before { display: none; } .gx-starport-pill--ready { color: var(--success); border-color: color-mix(in srgb, var(--success) 40%, transparent); background: color-mix(in srgb, var(--success) 12%, transparent); } .gx-starport-pill--soon { color: var(--warning); border-color: color-mix(in srgb, var(--warning) 40%, transparent); background: color-mix(in srgb, var(--warning) 12%, transparent); } -.gx-starport-pill--expired, .gx-starport-pill--broken { color: var(--error); border-color: color-mix(in srgb, var(--error) 40%, transparent); background: color-mix(in srgb, var(--error) 12%, transparent); } +.gx-starport-pill--expired, .gx-starport-pill--broken, .gx-starport-pill--danger, .gx-starport-pill--error { color: var(--error); border-color: color-mix(in srgb, var(--error) 40%, transparent); background: color-mix(in srgb, var(--error) 12%, transparent); } .gx-starport-list { list-style: none; margin: 0; padding: 0; display: grid; border: 1px solid var(--outline); border-radius: var(--radius-md); overflow: hidden; } .gx-starport-list > .gx-starport-row + .gx-starport-row { border-top: 1px solid var(--outline); } .gx-starport-row { display: flex; align-items: center; gap: var(--sp-3); min-width: 0; margin: 0; padding: var(--sp-3) var(--sp-4); } diff --git a/openpilot/starpilot/galaxy/web/css/navigation.css b/openpilot/starpilot/galaxy/web/css/navigation.css index 53609a8b63..933df45870 100644 --- a/openpilot/starpilot/galaxy/web/css/navigation.css +++ b/openpilot/starpilot/galaxy/web/css/navigation.css @@ -122,6 +122,67 @@ .gx-navigation__token-link { margin-bottom: var(--sp-4); } -.gx-navigation__gps { scroll-margin-top: 100px; } -.gx-navigation__gps li { margin-block: var(--sp-2); line-height: 1.5; } -.gx-navigation__gps summary { cursor: pointer; min-height: 44px; display: list-item; align-content: center; } +.gx-navigation__gps { scroll-margin-top: 100px; display: grid; gap: var(--sp-3); } +.gx-navigation__gps li { margin-block: var(--sp-1); line-height: 1.45; } +.gx-navigation__gps summary { cursor: pointer; min-height: 44px; display: flex; align-items: center; } +.gx-navigation__gps-status { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin: 0; } +.gx-navigation__gps-guides { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--sp-3); margin-top: var(--sp-3); } +.gx-navigation__gps-card { display: grid; gap: var(--sp-2); align-content: start; padding: var(--sp-3) var(--sp-4); border: 1px solid var(--outline); border-radius: var(--radius-md); background: var(--surface-container); } +.gx-navigation__gps-card > strong { display: inline-flex; align-items: center; gap: var(--sp-2); color: var(--on-surface); } +.gx-navigation__gps-card > strong .bi { color: var(--primary); } + +.gx-navigation__prefs { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--sp-3); padding-top: var(--sp-3); margin-top: var(--sp-2); border-top: 1px solid var(--outline); } +.gx-navigation__prefs-head { display: grid; gap: 2px; min-width: 200px; flex: 1 1 220px; } +.gx-navigation__pref-chips { display: flex; flex-wrap: wrap; gap: var(--sp-2); } +.gx-navigation__pref { display: inline-flex; align-items: center; gap: var(--sp-2); min-height: 40px; padding: 0 14px; border-radius: var(--radius-full); border: 1px solid var(--outline); background: var(--surface-container); color: var(--on-surface); font-size: .88rem; font-weight: var(--fw-medium); cursor: pointer; user-select: none; transition: background var(--motion-fast), border-color var(--motion-fast), color var(--motion-fast); } +.gx-navigation__pref > i { font-size: .95rem; color: var(--text-muted); } +.gx-navigation__pref--on { background: color-mix(in srgb, var(--primary) 16%, var(--surface-container)); border-color: var(--primary); color: var(--primary); } +.gx-navigation__pref--on > i { color: var(--primary); } +.gx-navigation__pref:has(input:focus-visible) { outline: 2px solid var(--primary); outline-offset: 3px; } +.gx-navigation__pref--disabled { opacity: .55; cursor: default; } + +.gx-navigation__step-title { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-1); } +.gx-navigation__step-title h3 { margin: 0; } +.gx-navigation__step-title .gx-starport-pill { padding: 2px 10px; font-size: .75rem; } + +/* Setup choices: compact M3 choice buttons with an expandable info popover. */ +.gx-choice { border: 0; margin: 0; padding: 0; min-width: 0; display: grid; gap: var(--sp-2); } +.gx-choice__head { display: flex; align-items: center; gap: var(--sp-2); } +.gx-choice__legend { padding: 0; font-weight: var(--fw-medium); float: left; } +.gx-choice__info-btn { display: inline-grid; place-items: center; width: 32px; height: 32px; min-height: 32px !important; padding: 0; border: 0; border-radius: 50%; background: transparent; color: var(--text-muted); font-size: .95rem; cursor: pointer; transition: background var(--motion-fast), color var(--motion-fast); } +.gx-choice__info-btn:hover, .gx-choice__info-btn[aria-expanded="true"] { background: var(--surface-container-high); color: var(--primary); } +.gx-choice__hint { margin: 0; color: var(--text-muted); font-size: .85rem; } +.gx-choice__grid { display: flex; flex-wrap: wrap; gap: var(--sp-2); } +.gx-choice__card { flex: 1 1 160px; display: flex; align-items: center; min-height: 44px; padding: 8px 14px; border: 1px solid var(--outline); + border-radius: var(--radius-md); background: var(--surface-container); cursor: pointer; min-width: 0; transition: background var(--motion-fast), border-color var(--motion-fast); } +.gx-choice__card--on { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 14%, var(--surface-container)); box-shadow: 0 0 0 1px var(--primary); } +.gx-choice__card--off { opacity: .6; cursor: default; } +.gx-choice__card:has(input:focus-visible) { outline: 2px solid var(--primary); outline-offset: 3px; } +.gx-choice__title { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); width: 100%; min-width: 0; line-height: 1.3; } +.gx-choice__title strong { flex: 1 1 auto; min-width: 0; font-size: .9rem; } +.gx-choice__title .bi { flex: 0 0 auto; color: var(--text-muted); font-size: 1rem; } +.gx-choice__card--on .gx-choice__title .bi { color: var(--primary); } +.gx-choice__title .gx-starport-pill { padding: 2px 8px; font-size: .72rem; margin-left: auto; } +.gx-choice__active-summary { margin: 0; color: var(--text-muted); font-size: .83rem; line-height: 1.4; } +.gx-choice__popover { display: grid; gap: var(--sp-2); padding: var(--sp-3) var(--sp-4); border: 1px solid var(--outline); border-radius: var(--radius-md); background: var(--surface-container-high, var(--surface-container)); font-size: .85rem; } +.gx-choice__popover-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); } +.gx-choice__popover-close { display: inline-grid; place-items: center; width: 28px; height: 28px; min-height: 28px !important; padding: 0; border: 0; border-radius: 50%; background: transparent; color: var(--text-muted); cursor: pointer; } +.gx-choice__popover-close:hover { background: var(--glass-active-bg); color: var(--on-surface); } +.gx-choice__popover-list { margin: 0; display: grid; gap: var(--sp-2); } +.gx-choice__popover-item { display: grid; gap: 2px; padding-top: var(--sp-2); border-top: 1px solid var(--outline); } +.gx-choice__popover-item dt { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); } +.gx-choice__popover-item dt .gx-starport-pill { padding: 1px 8px; font-size: .7rem; } +.gx-choice__popover-item dd { margin: 0; color: var(--on-surface-variant, var(--text-muted)); line-height: 1.45; } +.gx-choice__limit { color: var(--text-muted); font-size: .82rem; line-height: 1.4; } +.gx-compare { display: grid; margin-top: var(--sp-3); border: 1px solid var(--outline); border-radius: var(--radius-md); overflow: hidden; } +.gx-compare__row { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, 1fr); gap: var(--sp-3); padding: var(--sp-2) var(--sp-3); font-size: .85rem; } +.gx-compare__row + .gx-compare__row { border-top: 1px solid var(--outline); } +.gx-compare__row--head { font-weight: var(--fw-medium); background: var(--surface-container); } +.gx-compare__row > :first-child { color: var(--text-muted); } +.gx-compare__row--head > :first-child { color: inherit; } +.gx-navigation__sources { display: flex; flex-wrap: wrap; gap: var(--sp-2); list-style: none; margin: 0; padding: 0; } +.gx-navigation__sources .gx-navigation__chip { text-decoration: none; border: 1px solid var(--outline); } +.gx-navigation__power .gx-row__info { display: grid; gap: 2px; } +.gx-navigation .gx-starport-step__body { padding-left: 0; } +@media (min-width: 640px) { .gx-navigation .gx-starport-step__body { padding-left: calc(36px + var(--sp-4)); } } +@media (max-width: 540px) { .gx-compare__row { grid-template-columns: 1fr; gap: 2px; } .gx-compare__row--head { display: none; } .gx-compare__row > :nth-child(2)::before { content: "Mapbox: "; } .gx-compare__row > :nth-child(3)::before { content: "Google: "; } } diff --git a/openpilot/starpilot/galaxy/web/css/offline-road-maps.css b/openpilot/starpilot/galaxy/web/css/offline-road-maps.css index 2c8a748296..2995b39b14 100644 --- a/openpilot/starpilot/galaxy/web/css/offline-road-maps.css +++ b/openpilot/starpilot/galaxy/web/css/offline-road-maps.css @@ -1,26 +1,28 @@ /* Offline road maps for the Android Auto overlay (#/navigation, Offline Maps tab). */ -.gx-navigation__offline { display: grid; gap: 16px; padding: 0 0 96px; } -.gx-offline-roads { padding: 24px; display: grid; gap: 14px; } -/* Keep the section header flush with the card's rounded top like every other Galaxy card. */ -.gx-offline-roads > .gx-section__header { margin: -24px -24px 0; } -.gx-offline-roads__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; } -.gx-offline-roads__stat { display: grid; gap: 2px; padding: 12px 14px; border-radius: 14px; background: color-mix(in srgb, currentColor 6%, transparent); } -.gx-offline-roads__stat span { font-size: .78rem; opacity: .7; } +.gx-navigation__offline { display: grid; gap: var(--sp-4, 16px); padding: 0 0 96px; } +.gx-offline-roads { padding: var(--panel-padding, 20px); display: grid; gap: var(--sp-4, 16px); min-width: 0; } +.gx-offline-roads__head { display: flex; align-items: flex-start; gap: var(--sp-4, 16px); min-width: 0; } +.gx-offline-roads__head > div { flex: 1; min-width: 0; } +.gx-offline-roads__head .gx-note { margin: 0; line-height: 1.45; } +.gx-offline-roads__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: var(--sp-3, 12px); } +.gx-offline-roads__stat { display: grid; gap: 2px; padding: var(--sp-3, 12px) var(--sp-4, 16px); border-radius: var(--radius-md, 14px); border: 1px solid var(--outline); background: var(--surface-container); } +.gx-offline-roads__stat span { font-size: .78rem; color: var(--text-muted); } .gx-offline-roads__stat strong { font-size: 1.05rem; } -.gx-offline-roads__stat small { opacity: .7; font-size: .76rem; display: flex; flex-wrap: wrap; gap: 4px 12px; } +.gx-offline-roads__stat small { color: var(--text-muted); font-size: .76rem; display: flex; flex-wrap: wrap; gap: 4px 12px; } .gx-offline-roads__stat--wide { grid-column: 1 / -1; } .gx-offline-roads__bar { display: flex; height: 8px; border-radius: 6px; overflow: hidden; background: color-mix(in srgb, currentColor 12%, transparent); margin: 6px 0 2px; } .gx-offline-roads__bar i { display: block; height: 100%; transition: width .4s ease; } .gx-offline-roads__legend { display: inline-flex; align-items: center; gap: 6px; } .gx-offline-roads__legend b { width: 8px; height: 8px; border-radius: 50%; display: inline-block; } -.gx-offline-roads__picker { display: grid; grid-template-columns: minmax(0, 2fr) minmax(240px, 1fr); gap: 14px; align-items: start; } +.gx-offline-roads__picker { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(240px, 1fr); gap: var(--sp-3, 12px); align-items: start; } @media (max-width: 760px) { .gx-offline-roads__picker { grid-template-columns: 1fr; } } -.gx-offline-roads__map { position: relative; border-radius: 16px; overflow: hidden; background: #0e0e1a; height: 340px; } +.gx-offline-roads__map { position: relative; border-radius: var(--radius-md, 16px); border: 1px solid var(--outline); overflow: hidden; background: var(--navigation-land, #191a1a); height: clamp(260px, 42svh, 360px); } .gx-offline-roads__map canvas { width: 100%; height: 100%; display: block; cursor: crosshair; touch-action: none; } +.gx-offline-roads__provider { position: absolute; left: 10px; top: 10px; padding: 4px 10px; border-radius: var(--radius-full, 20px); border: 1px solid var(--glass-border); background: var(--glass-bg); color: var(--glass-text); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); font-size: .75rem; font-weight: var(--fw-medium, 500); pointer-events: none; } .gx-offline-roads__map .gx-navigation-map__controls { position: absolute; right: 10px; top: 10px; display: grid; gap: 6px; } -.gx-offline-roads__hint { position: absolute; left: 12px; bottom: 10px; padding: 6px 10px; border-radius: 10px; background: #0e0e1acc; color: #e8e6f5; font-size: .8rem; pointer-events: none; } -.gx-offline-roads__form { display: grid; gap: 8px; } +.gx-offline-roads__hint { position: absolute; left: 10px; right: 10px; bottom: 10px; width: fit-content; max-width: calc(100% - 20px); padding: 6px 12px; border-radius: 10px; border: 1px solid var(--glass-border); background: var(--glass-bg); color: var(--glass-text); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); font-size: .8rem; pointer-events: none; } +.gx-offline-roads__form { display: grid; gap: 8px; padding: var(--sp-3, 12px); border: 1px solid var(--outline); border-radius: var(--radius-md, 14px); background: var(--surface-container); } .gx-offline-roads__areas { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; } -.gx-offline-roads__areas li { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 14px; background: color-mix(in srgb, currentColor 5%, transparent); } -.gx-offline-roads__area { display: grid; gap: 2px; min-width: 0; flex: 1; } -.gx-offline-roads__area small { opacity: .72; } +.gx-offline-roads__areas li { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-radius: var(--radius-md, 14px); border: 1px solid var(--outline); background: var(--surface-container); } +.gx-offline-roads__area { display: grid; gap: 2px; min-width: 160px; flex: 1; } +.gx-offline-roads__area small { color: var(--text-muted); } diff --git a/openpilot/starpilot/galaxy/web/data/catalog.json b/openpilot/starpilot/galaxy/web/data/catalog.json index 7fe322c987..fe3ab8566e 100644 --- a/openpilot/starpilot/galaxy/web/data/catalog.json +++ b/openpilot/starpilot/galaxy/web/data/catalog.json @@ -143,7 +143,7 @@ "name": "Setup", "path": "/navigation/setup", "tab": "setup", - "description": "Configure navigation and Mapbox", + "description": "Keys, map and route sources, and GPS", "icon": "bi-gear" } ] diff --git a/openpilot/starpilot/galaxy/web/js/navigation-map.js b/openpilot/starpilot/galaxy/web/js/navigation-map.js index 52153e2553..713d851be5 100644 --- a/openpilot/starpilot/galaxy/web/js/navigation-map.js +++ b/openpilot/starpilot/galaxy/web/js/navigation-map.js @@ -139,6 +139,11 @@ export class RasterMap { const theme = value === 'light' ? 'light' : 'dark' if (this.closed || this.theme === theme) return this.theme = theme + this.clearTiles() + this.changed('') + this.draw() + } + clearTiles() { for (const controller of this.pending.values()) controller.abort() this.pending.clear() for (const image of this.tiles.values()) image.close() @@ -147,8 +152,6 @@ export class RasterMap { this.failures = 0 clearTimeout(this.retryTimer) this.retryTimer = null - this.changed('') - this.draw() } pause() { if (this.follow) { this.follow = false; this.changed() } @@ -206,6 +209,9 @@ export class RasterMap { if (data?.location && (this.locationFresh || data.location.lastKnown === true && !this.lastLocation)) { this.lastLocation = { ...data.location, bearing: Number.isFinite(data.location.bearing) ? data.location.bearing : this.lastLocation?.bearing } } + const provider = data?.mapProvider === 'google' && data?.hasGoogleKey && !data?.googleMap?.failure ? 'google' : 'mapbox' + if (this.provider && this.provider !== provider) this.clearTiles() + this.provider = provider this.data = data || {} this.stale = stale // A newly chosen route is shown whole once; Recenter returns to following the car. @@ -253,7 +259,7 @@ export class RasterMap { for (let up = 1; up <= 5 && zoom - up >= 0; up++) { const image = this.tiles.get(`${zoom - up}/${x >> up}/${y >> up}`) if (image) { - const span = SIZE / 2 ** up + const span = (image.width || SIZE) / 2 ** up return [image, (x - ((x >> up) << up)) * span, (y - ((y >> up) << up)) * span, span] } } @@ -348,8 +354,9 @@ export class RasterMap { timedOut = true; controller.abort() }, 8000) + const providerQuery = this.provider === 'google' ? '&provider=google' : '' try { - const response = await fetch(`./api/navigation/map/tiles/${key}.png?theme=${this.theme}`, { + const response = await fetch(`./api/navigation/map/tiles/${key}.png?theme=${this.theme}${providerQuery}`, { credentials: 'same-origin', signal: controller.signal }); if (!response.ok) throw new Error('Map tiles unavailable') @@ -359,22 +366,26 @@ export class RasterMap { return } this.tiles.set(key, image); + this.failed.delete(key); this.failures = 0 while (this.tiles.size > TILE_BITMAPS) { const oldest = this.tiles.keys().next().value; this.tiles.get(oldest).close(); this.tiles.delete(oldest) } - if (!this.failed.size) this.changed('') + this.changed('') + if (this.failed.size && !this.retryTimer) { + this.retryTimer = setTimeout(() => { this.retryTimer = null; this.retry() }, 400) + } } catch (error) { if (this.pending.get(key) === controller && (timedOut || !controller.signal.aborted)) { this.failed.add(key); if (this.failed.size > 64) this.failed.delete(this.failed.values().next().value); // A quick refusal (a busy moment) is retried quickly and silently; a hung request or a run of failures is reported. this.failures = (this.failures || 0) + 1 - const persistent = timedOut || this.failures >= 6 + const persistent = timedOut || this.failures >= 8 if (persistent) this.changed('Map tiles unavailable. Check the saved key and connection. Reconnecting automatically…') - this.retryTimer ??= setTimeout(() => { this.retryTimer = null; this.retry() }, persistent ? 5000 : 800) + this.retryTimer ??= setTimeout(() => { this.retryTimer = null; this.retry() }, persistent ? 3000 : 600) } } finally { clearTimeout(timer); @@ -410,6 +421,9 @@ export const NavigationMap = { props: ['data', 'stale'], data: () => ({ error: '', map: null, locationFresh: false, lastLocation: null, following: true }), + computed: { + googleMap() { return this.data?.mapProvider === 'google' && !!this.data?.hasGoogleKey && !this.data?.googleMap?.failure }, + }, mounted() { this.map = markRaw(new RasterMap(this.$refs.canvas, (error) => { if (error !== undefined) this.error = error @@ -447,9 +461,12 @@ export const NavigationMap = { {{error}} - -
+
+ Google Maps · {{ data?.googleMap?.copyright || 'Map data © Google' }} · Terms +
+ ` diff --git a/openpilot/starpilot/galaxy/web/js/navigation-setup.js b/openpilot/starpilot/galaxy/web/js/navigation-setup.js new file mode 100644 index 0000000000..77b4cbf3ae --- /dev/null +++ b/openpilot/starpilot/galaxy/web/js/navigation-setup.js @@ -0,0 +1,81 @@ +// Pieces of the navigation setup page: a compact M3 choice group with an info popover and the Mapbox/Google comparison. +export const ChoiceGroup = { + name: "ChoiceGroup", + props: { label: { type: String, required: true }, hint: { type: String, default: "" }, modelValue: { type: String, default: "" }, + options: { type: Array, required: true }, disabled: { type: Boolean, default: false } }, + emits: ["update:modelValue"], + data() { return { infoOpen: false } }, + computed: { + selectedOption() { return this.options.find((option) => option.value === this.modelValue) || this.options[0] || null }, + }, + methods: { + pick(event, option) { + event.target.checked = this.modelValue === option.value + if (!option.disabled && !this.disabled) this.$emit("update:modelValue", option.value) + }, + }, + template: ` +
+
+ {{ label }} + +
+

{{ hint }}

+
+ +
+

{{ selectedOption.detail }}

+
+
+ {{ label }} options + +
+
+
+
{{ option.label }} {{ option.badge }}
+
{{ option.detail }} {{ option.limit }}
+
+
+
+
`, +} + +// What each service does and where it stops. Mapbox always does search and offline roads. +export const COMPARE_ROWS = [ + ["Place search and addresses", "Yes", "No, Mapbox does this"], + ["Offline road maps", "Yes", "No, Google tiles can't be saved"], + ["Lane arrows on the turn card", "Yes", "No"], + ["Traffic in route times", "Yes", "Yes, with a correction every 7½ minutes"], + ["Map picture", "Road lines", "Street map with traffic colors"], + ["Needs", "Mapbox token", "Google key with billing on"], + ["Free monthly allowance", "Set by Mapbox; counted for this comma", "100,000 map tiles, 10,000 routes, 5,000 traffic routes"], + ["When the allowance runs out", "Typing suggestions, address lookups and offline downloads pause until the 1st", "The comma stops at 99% and uses Mapbox until it resets"], +] + +export const SourceCompare = { + name: "SourceCompare", + data() { return { rows: COMPARE_ROWS } }, + template: ` +
Compare Mapbox and Google +
+
What you getMapboxGoogle
+
+ {{ row[0] }}{{ row[1] }}{{ row[2] }}
+
+

Counts cover this comma only. Mapbox and Google bill everything that uses your key, including other apps.

+
`, +} diff --git a/openpilot/starpilot/galaxy/web/js/navigation.js b/openpilot/starpilot/galaxy/web/js/navigation.js index c2c25315e2..b179a3f057 100644 --- a/openpilot/starpilot/galaxy/web/js/navigation.js +++ b/openpilot/starpilot/galaxy/web/js/navigation.js @@ -1,4 +1,4 @@ -import { SHORT_MAP_LINK, isMapLink, parseSharedDestination } from "./share-destination.js" +import { isMapLink } from "./share-destination.js" import { GxNotice } from "./notice.js" import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js" import { connectionError } from "./polling.js" @@ -7,6 +7,7 @@ import { MapOperationsPanel } from "./map-operations.js" import { OfflineRoadMapsPanel } from "./offline-road-maps.js" import { GalaxySelect } from "./galaxy-select.js" import { reportSave } from "./save-feedback.js" +import { ChoiceGroup, SourceCompare } from "./navigation-setup.js" export function searchUuid() { if (typeof crypto.randomUUID === "function") return crypto.randomUUID() @@ -24,8 +25,10 @@ export function remainingLocationLease(lease, requestStarted, now = performance. const STATUS = new Set(["disabled", "needsKey", "noDestination", "waitingForLocation", "routing", "guiding", "arrived", "routeUnavailable", "stale"]) const ROUTE_AVOIDANCES = [{ key: "avoidTolls", label: "Avoid tolls" }, { key: "avoidHighways", label: "Avoid highways" }, { key: "avoidFerries", label: "Avoid ferries" }] -const GPS_MODES = [{ value: "backup", label: "Phone GPS as backup" }, { value: "comma", label: "Comma and car GPS only" }, - { value: "phone", label: "Prefer phone GPS" }] +const GPS_MODES = [ + { value: "backup", label: "Comma and car, phone as backup", hint: "Uses the comma's or car's GPS. The phone fills in only when neither has a fix." }, + { value: "comma", label: "Comma and car only", hint: "Never uses the phone. Choose this if you don't share phone GPS." }, + { value: "phone", label: "Phone first", hint: "Uses the phone whenever it has a recent fix, otherwise the comma or car." }] const GPS_NAMES = { comma: "Comma", car: "Car", phone: "Phone" } const coordinate = (value) => !!value && Number.isFinite(value.latitude) && Math.abs(value.latitude) <= 90 && Number.isFinite(value.longitude) && Math.abs(value.longitude) <= 180 @@ -94,10 +97,11 @@ export class NavigationClient { this.busy = false this.error = "" this.stale = false + this.refusal = null } emit() { this.publish({ data: this.data, results: this.results, searched: this.searched, busy: this.busy, error: this.error, stale: this.stale, - suggestions: this.suggestions }) } + suggestions: this.suggestions, resultsProvider: this.resultsProvider, suggestionsProvider: this.suggestionsProvider }) } stop() { if (this.searchId && this.data) { this.fetcher("./api/navigation/action", { method: "POST", credentials: "same-origin", cache: "no-store", @@ -179,6 +183,7 @@ export class NavigationClient { this.suggestions = [] } else { this.suggestions = payload.results + this.suggestionsProvider = payload.provider this.suggestionResultsQuery = text } this.emit() @@ -205,6 +210,7 @@ export class NavigationClient { } async run(operation, body = null) { + this.refusal = null if (!this.active || this.busy) return null this.controller?.abort() if (this.timer !== null) this.cancelTimer(this.timer) @@ -217,7 +223,7 @@ export class NavigationClient { if (operation !== "status") this.error = "" this.emit() const deadline = this.later(() => controller.abort(), operation === "search" ? 24000 : operation === "action" && body?.action === "selectPlace" ? 12000 : - operation === "action" && body?.action === "testGoogleKey" ? 45000 : operation === "action" && body?.action === "resolveShare" ? 20000 : 4000) + operation === "action" && body?.action === "testGoogleKey" ? 45000 : operation === "action" && body?.action === "resolveShare" ? 20000 : operation === "action" && body?.action === "share" ? 30000 : 4000) try { // Status polls name the route lines they already hold; the comma then leaves them out. const query = operation === "status" && this.data?.routeKey ? `?routeKey=${this.data.routeKey}` : "" @@ -232,12 +238,17 @@ export class NavigationClient { if (response.status === 401 || response.status === 503 && ["access_unavailable", "setup_required"].includes(payload?.code)) { this.stop(); this.unauthorized(); return null } - if (!response.ok) throw new Error(payload?.error || "Navigation could not complete this request.") + if (!response.ok) { + // A shared place the comma could not pin down comes back with the search to show instead. + if (response.status === 400 && body?.action === "share" && typeof payload?.query === "string") { this.refusal = payload; return null } + throw new Error(payload?.error || "Navigation could not complete this request.") + } this.error = "" if (operation === "search") { if (!Array.isArray(payload.results) || payload.results.length > 20 || !payload.results.every(validSearchResult)) throw new Error("Search results could not be read.") this.results = payload.results + this.resultsProvider = payload.provider this.searched = true } else { if (payload?.routeUnchanged === true) { @@ -260,7 +271,7 @@ export class NavigationClient { } if (!sameSnapshot(payload, this.data)) this.data = payload this.stale = false - if (operation === "action" && ["select", "selectPlace", "clear"].includes(body.action)) { this.results = []; this.searched = false } + if (operation === "action" && ["select", "selectPlace", "clear", "share"].includes(body.action)) { this.results = []; this.searched = false } } return payload } catch (error) { @@ -295,15 +306,33 @@ export const FavoriteChoices = { export const NavigationPage = { name: "NavigationPage", - components: { GxNotice, BluetoothNotice, MapOperationsPanel, NavigationMap, OfflineRoadMapsPanel, FavoriteChoices, GalaxySelect }, + components: { GxNotice, BluetoothNotice, MapOperationsPanel, NavigationMap, OfflineRoadMapsPanel, FavoriteChoices, GalaxySelect, ChoiceGroup, SourceCompare }, props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true }, go: { type: Function, default: null }, initialTab: { type: String, default: "route" }, tabs: { type: Array, required: true } }, - data() { return { bluetooth: bluetoothConnection(), data: null, results: [], busy: false, error: "", stale: false, tab: this.initialTab, gpsGuide: "android", query: "", token: "", googleKey: "", googleTest: null, searched: false, - suggestions: [], suggestOpen: false, savedSuggestionPlaces: {}, favoritePicker: null, searchPending: false } }, + data() { return { bluetooth: bluetoothConnection(), data: null, results: [], busy: false, error: "", stale: false, tab: this.initialTab, gpsGuide: "android", query: "", token: "", googleKey: "", googleTest: null, mapboxOpen: false, googleOpen: false, searched: false, + suggestions: [], suggestOpen: false, savedSuggestionPlaces: {}, favoritePicker: null, searchPending: false, resultsProvider: null, suggestionsProvider: null } }, watch: { initialTab(value) { this.tab = value } }, computed: { routeAvoidances() { return ROUTE_AVOIDANCES }, gpsModes() { return GPS_MODES }, + googleReady() { return !!this.data?.hasGoogleKey }, + mapChoices() { + return [{ value: "mapbox", label: "Mapbox", detail: "Road lines, drawn from saved or live Mapbox data.", limit: "Works offline once roads are saved." }, + { value: "google", label: "Google", detail: "Google's street map with traffic colors.", disabled: !this.googleReady, badge: this.googleReady ? "" : "Needs key", + limit: "Needs internet and the Mapbox key. Google tiles can't be saved offline." }] + }, + routeChoices() { + return [{ value: "mapbox", label: "Mapbox", detail: "Turn-by-turn with lane arrows.", limit: "Counted against your Mapbox allowance." }, + { value: "google", label: "Google", detail: "Routes that follow live traffic, and place search by Google.", disabled: !this.googleReady, badge: this.googleReady ? "" : "Needs key", + limit: "Needs the Mapbox key too. No lane arrows. Falls back to Mapbox when its limits run out." }] + }, + gpsChoices() { return GPS_MODES.map((mode) => ({ value: mode.value, label: mode.label, detail: mode.hint })) }, + destinationWays() { + return [{ icon: "bi-search", title: "Search here", detail: "Type an address or place on the Destination page." }, + { icon: "bi-link-45deg", title: "Paste a Google Maps link", detail: "Paste a place link into search, short links included." }, + { icon: "bi-android2", title: "Share from Android", detail: "Google Maps → Share → StarPilot. The route starts on your comma." }, + { icon: "bi-apple", title: "Share from iPhone", detail: "Google Maps or Apple Maps → Share → StarPilot. The route starts on your comma." }] + }, gpsLabel() { if (this.mode !== "local" || !this.ready || this.stale) return "GPS Source" const source = this.data?.location?.lastKnown ? null : GPS_NAMES[this.data?.location?.source] @@ -336,9 +365,33 @@ export const NavigationPage = { return [["searchSessions", "Searches"], ["geocoding", "Address lookups"], ["directions", "Routes"], ["staticTiles", "Map views"]] .filter(([key]) => usage[key]).map(([key, label]) => ({ key, label, ...usage[key] })) }, + // Place search follows the Directions choice, as on the comma. + googlePlaces() { return this.data?.routeProvider === "google" && !!this.data?.hasGoogleKey }, + sources() { + if (!this.data) return [] + const google = (value) => value === "google" && !!this.data.hasGoogleKey ? "Google" : "Mapbox" + return [{ label: "Map", value: google(this.data.mapProvider), icon: "bi-map" }, + { label: "Directions", value: google(this.data.routeProvider), icon: "bi-signpost-split" }, + { label: "Places", value: google(this.data.routeProvider), icon: "bi-geo-alt" }, + { label: "Position", value: this.gpsLabel.replace("GPS: ", ""), icon: "bi-crosshair" }] + }, googleUsage() { return this.data?.googleMap?.usage || null }, googleRouteUsage() { return this.data?.googleRoutes?.usage || null }, googleEssentialUsage() { return this.data?.googleRoutes?.essentials || null }, + googlePlaceUsage() { return this.data?.googlePlaces?.usage || null }, + googleSuggestionUsage() { return this.data?.googlePlaces?.suggestions || null }, + googleTests() { + const test = this.googleTest + if (!test) return [] + return [["Map Tiles API", test, "tile.googleapis.com"], ["Routes API", test.routes, "routes.googleapis.com"], ["Places API (New)", test.places, "places.googleapis.com"]] + .filter(([, result]) => result).map(([name, result, api]) => ({ name, ok: !!result.ok, message: result.message, missing: !result.ok && result.failure !== "budget", + link: result.failure === "billing" ? { href: "https://console.cloud.google.com/billing", label: "Turn on billing" } : + ["key", "disabled"].includes(result.failure) ? { href: `https://console.cloud.google.com/apis/library/${api}`, label: `Open ${name} in Google Cloud` } : null })) + }, + googleWorking() { + const rows = this.googleTests + return rows.length ? `${rows.length - rows.filter((row) => row.missing).length} of ${rows.length} APIs working` : "" + }, path() { return routePath(this.data?.route) }, summary() { const instruction = this.data?.instruction, route = this.data?.alternatives?.[this.data?.selectedRoute || 0] @@ -384,17 +437,15 @@ export const NavigationPage = { this.tab = tab this.go?.(tab === 'route' ? '/navigation' : `/navigation/${tab}`) }, + // The comma opens the link, looks the place up, turns navigation on and starts the route. async openShared(text) { - let parsed = parseSharedDestination(text) - // A Google Maps short link is followed on the comma to the full link, which carries the coordinates. - if (!parsed.destination && SHORT_MAP_LINK.test(text)) { - const resolved = (await this.client.action('resolveShare', { text: String(text).slice(0, 8192) }))?.sharedText - if (resolved) parsed = parseSharedDestination(resolved) - } - if (parsed.destination) { await this.client.action('select', { destination: parsed.destination }); return } + if (await this.client.action('share', { text: String(text).slice(0, 8192) })) return + const query = this.client.refusal?.query + if (!query) return // Text shares can be ambiguous ("Starbucks"); show the results and let the driver pick. - this.query = parsed.query - await this.client.search(parsed.query) + if (!this.client.data?.enabled && !await this.client.action('configure', { patch: { enabled: true } })) return + this.query = query + await this.client.search(query) }, async search() { if (this.searchPending) return @@ -485,132 +536,175 @@ export const NavigationPage = { template: `

Navigation

-

Set a destination, prepare offline maps, and configure navigation and Mapbox.

+

Pick a destination, save maps for offline use, and choose where maps, directions and position come from.

+
-