Add "map around me" mode to Navigate app

This commit is contained in:
James Babcock committed 2026-09-20 17:02:24 -07:00
1 parent 286a3819bf
commit 146fe66bdd
3 files changed
+228 -40

No files matched your search

+94 -28
View File
@@ -114,7 +114,7 @@ const largeFont = getFont("terminus32");
const mediumFont = getFont("terminus24"); const mediumFont = getFont("terminus24");
const smallFont = getDefaultSmallFont(); const smallFont = getDefaultSmallFont();
type NavPhase = "idle" | "acquiring" | "routing" | "navigating" | "arrived"; type NavPhase = "idle" | "acquiring" | "routing" | "navigating" | "map" | "arrived";
type MapMode = "follow" | "overview"; type MapMode = "follow" | "overview";
type NavWindow = { type NavWindow = {
@@ -196,8 +196,8 @@ type NavTarget =
| { kind: "place"; name: string; place: string; longitude: number; latitude: number }; | { kind: "place"; name: string; place: string; longitude: number; latitude: number };
/** /**
* An entry on the idle page's list: a destination, or (while no Mapbox * An entry on the idle page's list: the map, a destination, or (while no
* token is set) one of the setup actions offered in its place. * Mapbox token is set) one of the setup actions offered in its place.
*/ */
type IdleEntry = type IdleEntry =
| { kind: "saved"; destination: SavedDestination } | { kind: "saved"; destination: SavedDestination }
@@ -249,7 +249,7 @@ const tracker = new LocationTracker({
onLocation: (fix) => handleFix(fix), onLocation: (fix) => handleFix(fix),
onError: (message) => { onError: (message) => {
statusMessage = message; statusMessage = message;
if (phase === "acquiring") phase = "idle"; if (phase === "acquiring") stopNavigation(message);
render(); render();
}, },
}); });
@@ -299,6 +299,10 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
window.viewportHeight = message.viewport.height; window.viewportHeight = message.viewport.height;
window.menu?.resize(message.viewport); window.menu?.resize(message.viewport);
window.lastSubmittedFingerprint = ""; window.lastSubmittedFingerprint = "";
if (phase === "map") {
resetMapState();
maybeRefreshMap();
}
render(); render();
break; break;
case "close-window": case "close-window":
@@ -386,6 +390,31 @@ function startNavigation(query: string, requestedProfile: RouteProfile): Promise
); );
} }
async function startMap(): Promise<void> {
if (!isMapboxConfigured()) return;
stopNavigation("");
const generation = navigationGeneration;
phase = "acquiring";
mapMode = "follow";
zoomOffset = 0;
statusMessage = "Locating you for the map...";
render();
try {
ensureTracking();
await waitForFix();
if (generation !== navigationGeneration) return;
phase = "map";
statusMessage = "";
ensureTickTimer();
maybeRefreshMap();
render();
} catch (error) {
if (generation !== navigationGeneration) return;
stopNavigation(String((error as Error)?.message ?? error));
render();
}
}
async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfile): Promise<string> { async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfile): Promise<string> {
const query = target.kind === "query" ? target.query : target.name; const query = target.kind === "query" ? target.query : target.name;
if (!isMapboxConfigured()) { if (!isMapboxConfigured()) {
@@ -397,6 +426,7 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
const generation = ++navigationGeneration; const generation = ++navigationGeneration;
const checkCurrent = () => { if (generation !== navigationGeneration) throw new Error("Navigation cancelled."); }; const checkCurrent = () => { if (generation !== navigationGeneration) throw new Error("Navigation cancelled."); };
const hadActiveRoute = phase === "navigating" && follower !== null; const hadActiveRoute = phase === "navigating" && follower !== null;
const hadActiveMap = phase === "map";
const previous = { const previous = {
destination, destination,
destinationName, destinationName,
@@ -459,11 +489,10 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
if (generation !== navigationGeneration) throw error; if (generation !== navigationGeneration) throw error;
const message = String((error as Error)?.message ?? error); const message = String((error as Error)?.message ?? error);
statusMessage = message; statusMessage = message;
// A failed new destination shouldn't kill guidance that was already // A failed new destination shouldn't close the existing map or guidance.
// running; fall back to the ongoing route (and its destination, which // Restore the destination too: geocoding may have overwritten it.
// the geocode step may have partially overwritten). if (hadActiveRoute || hadActiveMap) {
if (hadActiveRoute) { phase = hadActiveRoute ? "navigating" : "map";
phase = "navigating";
destination = previous.destination; destination = previous.destination;
destinationName = previous.destinationName; destinationName = previous.destinationName;
destinationPlace = previous.destinationPlace; destinationPlace = previous.destinationPlace;
@@ -484,7 +513,6 @@ function adoptRoute(route: Route): void {
mapMode = "follow"; mapMode = "follow";
zoomOffset = 0; zoomOffset = 0;
statusMessage = ""; statusMessage = "";
routeGeneration++;
resetMapState(); resetMapState();
ensureTracking(); ensureTracking();
ensureTickTimer(); ensureTickTimer();
@@ -502,7 +530,6 @@ function stopNavigation(finalStatus: string): void {
destination = null; destination = null;
destinationName = ""; destinationName = "";
destinationPlace = ""; destinationPlace = "";
routeGeneration++;
resetMapState(); resetMapState();
stopTrackingIfIdle(); stopTrackingIfIdle();
ensureTickTimer(); ensureTickTimer();
@@ -523,6 +550,12 @@ function handleFix(fix: TrackedLocation): void {
} }
for (const waiter of firstFixWaiters.splice(0)) waiter(fix); for (const waiter of firstFixWaiters.splice(0)) waiter(fix);
if (phase === "map") {
statusMessage = "";
maybeRefreshMap();
render();
return;
}
if (phase !== "navigating" || !follower) return; if (phase !== "navigating" || !follower) return;
progress = follower.update(fix.longitude, fix.latitude); progress = follower.update(fix.longitude, fix.latitude);
@@ -595,7 +628,7 @@ function waitForFix(): Promise<TrackedLocation> {
/** Hold the magnetometer only while its reading is actually on screen. */ /** Hold the magnetometer only while its reading is actually on screen. */
function reconcileCompass(): void { function reconcileCompass(): void {
const wanted = const wanted =
window !== null && window.foreground && screenOn && phase === "navigating" && mapMode === "follow"; window !== null && window.foreground && screenOn && (phase === "navigating" || phase === "map") && mapMode === "follow";
if (wanted === compassActive) return; if (wanted === compassActive) return;
compassActive = wanted; compassActive = wanted;
if (wanted) { if (wanted) {
@@ -633,7 +666,7 @@ function angularDistance(a: number, b: number): number {
} }
function ensureTickTimer(): void { function ensureTickTimer(): void {
const shouldRun = phase === "navigating"; const shouldRun = phase === "navigating" || phase === "map";
if (shouldRun && tickTimer === null) { if (shouldRun && tickTimer === null) {
tickTimer = setInterval(() => { tickTimer = setInterval(() => {
maybeRefreshMap(); maybeRefreshMap();
@@ -649,6 +682,7 @@ function ensureTickTimer(): void {
// Map pane // Map pane
function resetMapState(): void { function resetMapState(): void {
routeGeneration++;
mapImage = null; mapImage = null;
mapFetchedKey = ""; mapFetchedKey = "";
mapInFlight = false; mapInFlight = false;
@@ -679,7 +713,7 @@ function currentBearing(): number {
function currentZoom(): number { function currentZoom(): number {
let zoom: number; let zoom: number;
if (profile === "walking") { if (phase === "map" || profile === "walking") {
zoom = 16.5; zoom = 16.5;
} else if (progress && progress.metersToNextManeuver < 250) { } else if (progress && progress.metersToNextManeuver < 250) {
zoom = 16.5; zoom = 16.5;
@@ -706,7 +740,7 @@ function desiredMapView(): { camera: StaticMapCamera; key: string; path: Array<[
const position = currentPosition(); const position = currentPosition();
if (!position) return null; if (!position) return null;
const zoom = currentZoom(); const zoom = currentZoom();
const bearing = Math.round(currentBearing() / BEARING_BUCKET_DEG) * BEARING_BUCKET_DEG; const bearing = phase === "map" ? 0 : Math.round(currentBearing() / BEARING_BUCKET_DEG) * BEARING_BUCKET_DEG;
const path = const path =
follower && progress follower && progress
? simplifyPath(follower.routeSliceAround(progress.alongMeters, 250, 3000), 80) ? simplifyPath(follower.routeSliceAround(progress.alongMeters, 250, 3000), 80)
@@ -724,6 +758,7 @@ function desiredMapView(): { camera: StaticMapCamera; key: string; path: Array<[
* a few seconds passed while moving. Single-flight with failure backoff. * a few seconds passed while moving. Single-flight with failure backoff.
*/ */
function maybeRefreshMap(): void { function maybeRefreshMap(): void {
if (phase !== "navigating" && phase !== "map") return;
if (!window || !window.foreground || !screenOn) return; if (!window || !window.foreground || !screenOn) return;
if (mapInFlight || Date.now() < mapNextRetryAtMs) return; if (mapInFlight || Date.now() < mapNextRetryAtMs) return;
if (!isMapboxConfigured()) return; if (!isMapboxConfigured()) return;
@@ -733,7 +768,8 @@ function maybeRefreshMap(): void {
let stale = mapImage === null || view.key !== mapFetchedKey; let stale = mapImage === null || view.key !== mapFetchedKey;
if (!stale && view.camera.kind === "center" && mapLastFetchCenter) { if (!stale && view.camera.kind === "center" && mapLastFetchCenter) {
const moved = haversineMeters(mapLastFetchCenter, [view.camera.longitude, view.camera.latitude]); const moved = haversineMeters(mapLastFetchCenter, [view.camera.longitude, view.camera.latitude]);
const viewportMeters = MAP_SIZE * metersPerPixel(view.camera.zoom, view.camera.latitude); const size = mapDimensions();
const viewportMeters = Math.min(size.width, size.height) * metersPerPixel(view.camera.zoom, view.camera.latitude);
if (moved > viewportMeters * MOVE_REFRESH_FRACTION) stale = true; if (moved > viewportMeters * MOVE_REFRESH_FRACTION) stale = true;
else if (Date.now() - mapLastFetchAtMs > IDLE_REFRESH_MS && moved > IDLE_REFRESH_MIN_MOVE_M) stale = true; else if (Date.now() - mapLastFetchAtMs > IDLE_REFRESH_MS && moved > IDLE_REFRESH_MIN_MOVE_M) stale = true;
} }
@@ -743,13 +779,12 @@ function maybeRefreshMap(): void {
const generation = routeGeneration; const generation = routeGeneration;
fetchStaticMapGray({ fetchStaticMapGray({
camera: view.camera, camera: view.camera,
width: MAP_SIZE, ...mapDimensions(),
height: MAP_SIZE,
routePath: view.path.length >= 2 ? view.path : undefined, routePath: view.path.length >= 2 ? view.path : undefined,
}) })
.then((image) => { .then((image) => {
mapInFlight = false;
if (generation !== routeGeneration) return; // Route/mode changed mid-fetch. if (generation !== routeGeneration) return; // Route/mode changed mid-fetch.
mapInFlight = false;
levelMap(image); levelMap(image);
mapImage = image; mapImage = image;
mapFetchedKey = view.key; mapFetchedKey = view.key;
@@ -760,6 +795,7 @@ function maybeRefreshMap(): void {
render(); render();
}) })
.catch((error) => { .catch((error) => {
if (generation !== routeGeneration) return;
mapInFlight = false; mapInFlight = false;
mapNextRetryAtMs = Date.now() + MAP_RETRY_BACKOFF_MS; mapNextRetryAtMs = Date.now() + MAP_RETRY_BACKOFF_MS;
mapLastError = String((error as Error)?.message ?? error); mapLastError = String((error as Error)?.message ?? error);
@@ -767,6 +803,12 @@ function maybeRefreshMap(): void {
}); });
} }
function mapDimensions(): { width: number; height: number } {
return phase === "map" && window
? { width: window.viewportWidth, height: Math.max(1, window.viewportHeight - 30) }
: { width: MAP_SIZE, height: MAP_SIZE };
}
/** Keep every Nth point (ends always included) to bound the overlay URL size. */ /** Keep every Nth point (ends always included) to bound the overlay URL size. */
function simplifyPath(path: Array<[number, number]>, maxPoints: number): Array<[number, number]> { function simplifyPath(path: Array<[number, number]>, maxPoints: number): Array<[number, number]> {
if (path.length <= maxPoints) return path; if (path.length <= maxPoints) return path;
@@ -848,6 +890,7 @@ function startSummary(picked: GeocodeCandidate, candidates: GeocodeCandidate[],
} }
function describeRouteStatus(): string { function describeRouteStatus(): string {
if (phase === "map") return "Showing the map around your current location. No destination set.";
if (phase === "arrived") return `Arrived at ${destinationName}.`; if (phase === "arrived") return `Arrived at ${destinationName}.`;
if (phase !== "navigating" || !follower) return "Navigation is not active."; if (phase !== "navigating" || !follower) return "Navigation is not active.";
if (!progress) return `Navigating to ${destinationName}; waiting for a GPS fix.`; if (!progress) return `Navigating to ${destinationName}; waiting for a GPS fix.`;
@@ -869,12 +912,12 @@ function describeRouteStatus(): string {
*/ */
function windowMenuItems(win: NavWindow): MenuItem[] { function windowMenuItems(win: NavWindow): MenuItem[] {
const items: MenuItem[] = []; const items: MenuItem[] = [];
if (phase === "navigating" || phase === "arrived") { if (phase !== "idle") {
items.push({ items.push({
label: "Stop navigation", label: phase === "map" ? "Close map" : "Stop navigation",
onSelect: (ctx) => { onSelect: (ctx) => {
ctx.stack.pop(); ctx.stack.pop();
stopNavigation("Navigation stopped."); stopNavigation(phase === "map" ? "" : "Navigation stopped.");
render(); render();
}, },
}); });
@@ -1141,9 +1184,15 @@ function tokenSetupEntries(): IdleEntry[] {
function idleEntries(): IdleEntry[] { function idleEntries(): IdleEntry[] {
if (!isMapboxConfigured()) return tokenSetupEntries(); if (!isMapboxConfigured()) return tokenSetupEntries();
const entries: IdleEntry[] = loadSavedDestinations() const entries: IdleEntry[] = [{
kind: "action",
label: "Map around me",
detail: "Follow my location",
run: () => { void startMap(); },
}];
entries.push(...loadSavedDestinations()
.filter((destination) => destination.address) .filter((destination) => destination.address)
.map((destination): IdleEntry => ({ kind: "saved", destination })); .map((destination): IdleEntry => ({ kind: "saved", destination })));
for (const destination of loadRecentDestinations()) { for (const destination of loadRecentDestinations()) {
entries.push({ kind: "recent", destination }); entries.push({ kind: "recent", destination });
} }
@@ -1223,7 +1272,7 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void {
mapMode = mapMode === "follow" ? "overview" : "follow"; mapMode = mapMode === "follow" ? "overview" : "follow";
resetMapState(); resetMapState();
maybeRefreshMap(); maybeRefreshMap();
} else if (phase === "arrived") { } else if (phase === "arrived" || phase === "map") {
stopNavigation(""); stopNavigation("");
} else if (phase === "idle") { } else if (phase === "idle") {
const entry = idleEntries()[idleSelection]; const entry = idleEntries()[idleSelection];
@@ -1240,7 +1289,7 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void {
return; return;
} }
if (event.type === "scroll-up" || event.type === "scroll-down") { if (event.type === "scroll-up" || event.type === "scroll-down") {
if (phase === "navigating" && mapMode === "follow") { if ((phase === "navigating" || phase === "map") && mapMode === "follow") {
zoomOffset = Math.max(-3, Math.min(2, zoomOffset + (event.type === "scroll-up" ? 0.5 : -0.5))); zoomOffset = Math.max(-3, Math.min(2, zoomOffset + (event.type === "scroll-up" ? 0.5 : -0.5)));
maybeRefreshMap(); maybeRefreshMap();
renderAndSubmit(win, frameId); renderAndSubmit(win, frameId);
@@ -1267,6 +1316,8 @@ function paintContent(win: NavWindow): GrayImage {
const image = new GrayImage(win.viewportWidth, win.viewportHeight, 0); const image = new GrayImage(win.viewportWidth, win.viewportHeight, 0);
if (editing) { if (editing) {
paintEdit(image, editing); paintEdit(image, editing);
} else if (phase === "map") {
paintMap(image);
} else if (phase === "idle" || phase === "acquiring" || phase === "routing") { } else if (phase === "idle" || phase === "acquiring" || phase === "routing") {
paintIdle(image, win); paintIdle(image, win);
} else { } else {
@@ -1303,7 +1354,7 @@ function paintIdle(image: GrayImage, win: NavWindow): void {
const hint = !configured const hint = !configured
? "Navigation needs a Mapbox public token (free at mapbox.com). Get one, then enter it here or in Settings > API Keys." ? "Navigation needs a Mapbox public token (free at mapbox.com). Get one, then enter it here or in Settings > API Keys."
: entries.length : entries.length
? "Pick a destination below, or say one via Voice input (system menu, long-press)." ? "View the map or pick a destination below. Use Voice input (system menu, long-press) to say a destination."
: "Ask the voice assistant to navigate somewhere, or pick Voice input from the system menu (long-press) to say a destination. Save Home, Work and other places from the app menu."; : "Ask the voice assistant to navigate somewhere, or pick Voice input from the system menu (long-press) to say a destination. Save Home, Work and other places from the app menu.";
const hintLines = wrapText(smallFont, hint, image.width - 48); const hintLines = wrapText(smallFont, hint, image.width - 48);
const hintStep = smallFont.lineHeight + 2; const hintStep = smallFont.lineHeight + 2;
@@ -1329,7 +1380,7 @@ function paintIdle(image: GrayImage, win: NavWindow): void {
} }
} }
/** Saved destinations (name + address) then recent places, one selectable row each. */ /** Map action, saved destinations, then recent places, one selectable row each. */
function paintIdleList(image: GrayImage, win: NavWindow, entries: IdleEntry[], top: number): void { function paintIdleList(image: GrayImage, win: NavWindow, entries: IdleEntry[], top: number): void {
const rowHeight = listRowHeight(smallFont); const rowHeight = listRowHeight(smallFont);
const listBottom = image.height - 30; const listBottom = image.height - 30;
@@ -1458,6 +1509,21 @@ function paintNavigating(image: GrayImage, win: NavWindow): void {
drawFooter(image, `${GESTURE_SCROLL} zoom ${GESTURE_CLICK} ${modeHint} ${GESTURE_DOUBLE_CLICK} back`, PANEL_X + 8); drawFooter(image, `${GESTURE_SCROLL} zoom ${GESTURE_CLICK} ${modeHint} ${GESTURE_DOUBLE_CLICK} back`, PANEL_X + 8);
} }
function paintMap(image: GrayImage): void {
const { width, height } = mapDimensions();
if (mapImage) {
image.bitBlt(mapImage, 0, 0);
drawChevron(image, width / 2, height / 2, headHeadingDeg ?? 0);
} else {
image.drawText(smallFont, 24, height / 2 - 8, mapLastError ? "Map unavailable; retrying..." : "Loading map...", 170);
}
if (statusMessage) {
image.fillRect(0, 0, width, smallFont.lineHeight + 8, 0);
image.drawText(smallFont, 16, 4, truncateText(smallFont, statusMessage, width - 32), 200);
}
drawFooter(image, `${GESTURE_SCROLL} zoom ${GESTURE_CLICK} destinations ${GESTURE_DOUBLE_CLICK} back`);
}
/** /**
* Position chevron, fixed at the map center and rotated `angleDeg` clockwise * Position chevron, fixed at the map center and rotated `angleDeg` clockwise
* from straight up (the map's render bearing) to the wearer's head heading. * from straight up (the map's render bearing) to the wearer's head heading.
+1 -1
View File
@@ -100,7 +100,7 @@ test('Navigate resize preserves its active route and window, and remeasures an o
menu: { resize: (size) => { menuSize = size; } }, lastSubmittedFingerprint: 'old' }; menu: { resize: (size) => { menuSize = size; } }, lastSubmittedFingerprint: 'old' };
const route = { destination: 'Home' }; const route = { destination: 'Home' };
const resize = resizeHandler('app/apps/navigate/navigate-app.worker.ts', { const resize = resizeHandler('app/apps/navigate/navigate-app.worker.ts', {
window, route, render: () => { paints++; }, window, route, phase: 'navigating', render: () => { paints++; },
}); });
resize({ width: 576, height: 260 }); resize({ width: 576, height: 260 });
assert.equal(window.viewportHeight, 260); assert.equal(window.viewportHeight, 260);
+133 -11
View File
@@ -12,8 +12,8 @@ const route = { coordinates: [[-122.4, 37.7], [-122.4, 37.71]], distanceMeters:
{ distanceMeters: 0, durationSec: 0, instruction: 'Arrive', maneuverType: 'arrive' }] }; { distanceMeters: 0, durationSec: 0, instruction: 'Arrive', maneuverType: 'arrive' }] };
const fix = latitude => ({ latitude, longitude: -122.4, timestampMs: Date.now(), bearingDeg: 0, speedMps: 1.5, accuracyMeters: 5 }); const fix = latitude => ({ latitude, longitude: -122.4, timestampMs: Date.now(), bearingDeg: 0, speedMps: 1.5, accuracyMeters: 5 });
function fixture() { function fixture() {
const messages = [], timers = new Set(), holds = [], maps = [], errors = []; const messages = [], timers = new Set(), timeouts = new Set(), holds = [], maps = [], errors = [], requests = [];
let callbacks, compass, delayRoute = null; let callbacks, compass, delayRoute = null, delayMap = null, routeError = null;
const routeMath = loader()('app/apps/navigate/route-follower.ts'); const routeMath = loader()('app/apps/navigate/route-follower.ts');
const tracker = { running: false, isRunning() { return this.running; }, start() { this.running = true; }, stop() { this.running = false; } }; const tracker = { running: false, isRunning() { return this.running; }, start() { this.running = true; }, stop() { this.running = false; } };
const sensor = { LocationTracker: function (value) { callbacks = value; return tracker; }, COMPASS_CHANGED: 15, const sensor = { LocationTracker: function (value) { callbacks = value; return tracker; }, COMPASS_CHANGED: 15,
@@ -26,34 +26,42 @@ function fixture() {
'../../native/settings-store': { onSettingsStoreChanged() {} }, '../../native/settings-store': { onSettingsStoreChanged() {} },
'./navigation-sensors': sensor, './navigation-sensors': sensor,
'./route-follower': routeMath, './route-follower': routeMath,
'./destinations': { findSavedDestinationByName: () => null, rememberRecentDestination() {} }, './destinations': { findSavedDestinationByName: () => null, rememberRecentDestination() {},
loadSavedDestinations: () => [{ name: 'Home', address: '123 Main St' }], loadRecentDestinations: () => [] },
'../compass/calibration': { calibrateHeading: value => value + 5, normalizeHeading: value => (value + 360) % 360 }, '../compass/calibration': { calibrateHeading: value => value + 5, normalizeHeading: value => (value + 360) % 360 },
'../../native/frame-timings': { startFrame: () => 1, finishFrame() {}, span: (_id, _name, fn) => fn(), runWithFrame: (_id, fn) => fn() }, '../../native/frame-timings': { startFrame: () => 1, finishFrame() {}, logFrame() {}, span: (_id, _name, fn) => fn(), runWithFrame: (_id, fn) => fn() },
'../../native/active-display': { getActiveDisplay: () => null }, '../../native/active-display': { getActiveDisplay: () => null },
'../../ui/window-menu': { WindowMenu: class { paint() { return []; } } }, '../../ui/window-menu': { WindowMenu: class { paint() { return []; } isOpen() { return false; } resize() {} } },
'../../graphics/plane': { planesFingerprint: () => 'frame' }, '../../graphics/plane': { planesFingerprint: () => 'frame' },
'../../native/mapbox': { '../../native/mapbox': {
isMapboxConfigured: () => true, isMapboxConfigured: () => true,
geocodeForward: async () => [{ name: 'Test park', placeFormatted: 'San Francisco', latitude: 37.71, longitude: -122.4 }], geocodeForward: async () => { requests.push('geocode'); return [{ name: 'Test park', placeFormatted: 'San Francisco', latitude: 37.71, longitude: -122.4 }]; },
fetchRoute: async () => delayRoute ? await delayRoute : route, fetchRoute: async () => { requests.push('route'); if (routeError) throw routeError; return delayRoute ? await delayRoute : route; },
fetchStaticMapGray: async options => { maps.push(options); return { pixels: new Uint8Array([0, 128, 255]) }; }, fetchStaticMapGray: async options => { maps.push(options); return delayMap ? await delayMap : { pixels: new Uint8Array([0, 128, 255]) }; },
}, },
}; };
const global = { postMessage: message => messages.push(message) }; const global = { postMessage: message => messages.push(message) };
const source = fs.readFileSync(path.join(__dirname, '../app/apps/navigate/navigate-app.worker.ts'), 'utf8') + const source = fs.readFileSync(path.join(__dirname, '../app/apps/navigate/navigate-app.worker.ts'), 'utf8') +
'\nexports.probe = { startNavigation, stopNavigation, state: () => ({ phase, headHeadingDeg, progress }) };'; '\nexports.probe = { startNavigation, startMap, stopNavigation, idleEntries, describeRouteStatus, state: () => ({ phase, headHeadingDeg, progress, mapImage, mapInFlight, mapLastError }) };';
const exports = {}; const exports = {};
vm.runInNewContext(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText, { vm.runInNewContext(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText, {
exports, global, Uint8Array, setTimeout, clearTimeout, exports, global, Uint8Array,
setTimeout: fn => { timeouts.add(fn); return fn; }, clearTimeout: fn => timeouts.delete(fn),
setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn), setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn),
console: { log() {}, warn() {}, error: error => errors.push(error) }, require: id => modules[id] ?? {}, console: { log() {}, warn() {}, error: error => errors.push(error) }, require: id => modules[id] ?? {},
}); });
const send = data => global.onmessage({ data }); const send = data => global.onmessage({ data });
send({ type: 'open-window', windowId: 'navigate:main', surfaceId: 'window:navigate:main', title: 'Navigate', viewport: { width: 576, height: 480 } }); send({ type: 'open-window', windowId: 'navigate:main', surfaceId: 'window:navigate:main', title: 'Navigate', viewport: { width: 576, height: 480 } });
send({ type: 'foreground', windowId: 'navigate:main', foreground: true, focused: true }); send({ type: 'foreground', windowId: 'navigate:main', foreground: true, focused: true });
return { ...exports.probe, send, timers, holds, maps, errors, tracker, return { ...exports.probe, send, timers, holds, maps, errors, tracker, requests,
input: type => send({ type: 'input', windowId: 'navigate:main', focused: true, frameId: 1, event: { type } }),
tick: () => { for (const callback of timers) callback(); },
expireFix: () => { for (const callback of timeouts) callback(); timeouts.clear(); },
failRoute: () => { routeError = new Error('Route unavailable'); },
fix: latitude => send({ type: 'navigation-sensors', event: { kind: 'location', location: fix(latitude), id: 1 } }), fix: latitude => send({ type: 'navigation-sensors', event: { kind: 'location', location: fix(latitude), id: 1 } }),
heading: value => compass?.({ command: 15, headingDegrees: value }), heading: value => compass?.({ command: 15, headingDegrees: value }),
holdMap: () => { let resolve, reject; delayMap = new Promise((done, fail) => { resolve = done; reject = fail; });
return { resolve: () => resolve({ pixels: new Uint8Array([0, 128, 255]) }), reject }; },
holdRoute: () => { let resolve; delayRoute = new Promise(done => { resolve = done; }); return () => resolve(route); } }; holdRoute: () => { let resolve; delayRoute = new Promise(done => { resolve = done; }); return () => resolve(route); } };
} }
@@ -76,3 +84,117 @@ test('closing Navigate while a route request is pending cannot restart guidance
await assert.rejects(starting, /Navigation cancelled/); await assert.rejects(starting, /Navigation cancelled/);
assert.equal(h.state().phase, 'idle'); assert.equal(h.tracker.running, false); assert.equal(h.timers.size, 0); assert.equal(h.state().phase, 'idle'); assert.equal(h.tracker.running, false); assert.equal(h.timers.size, 0);
}); });
test('front page map entry follows location without routing, supports zoom and returns to destinations', async () => {
const h = fixture();
assert.equal(h.idleEntries()[0].label, 'Map around me');
assert.equal(h.idleEntries()[1].destination.name, 'Home');
h.input('click');
assert.equal(h.state().phase, 'acquiring');
assert.equal(h.tracker.running, true);
h.fix(37.7); await flush();
assert.equal(h.state().phase, 'map');
assert.deepEqual(h.requests, []);
assert.equal(h.maps.at(-1).width, 576);
assert.equal(h.maps.at(-1).height, 450);
assert.equal(h.maps.at(-1).routePath, undefined);
assert.equal(h.maps.at(-1).camera.latitude, 37.7);
assert.equal(h.maps.at(-1).camera.bearingDeg, 0);
assert.match(h.describeRouteStatus(), /No destination/);
h.heading(90); assert.equal(h.state().headHeadingDeg, 107);
h.fix(37.705); await flush();
assert.equal(h.maps.at(-1).camera.latitude, 37.705);
const zoom = h.maps.at(-1).camera.zoom;
h.input('scroll-up'); await flush();
assert.equal(h.maps.at(-1).camera.zoom, zoom + 0.5);
h.input('click');
assert.equal(h.state().phase, 'idle');
assert.equal(h.tracker.running, false);
assert.equal(h.holds.at(-1), false);
assert.equal(h.timers.size, 0);
const count = h.maps.length;
h.send({ type: 'foreground', foreground: true, focused: true });
assert.equal(h.maps.length, count);
assert.deepEqual(h.errors, []);
});
test('map suspends fetching and compass while hidden and resizes to the viewport', async () => {
const h = fixture(), starting = h.startMap();
h.fix(37.7); await starting; await flush();
const count = h.maps.length;
h.send({ type: 'screen', on: false });
h.fix(37.71); h.tick(); await flush();
assert.equal(h.maps.length, count);
assert.equal(h.holds.at(-1), false);
h.send({ type: 'screen', on: true }); await flush();
assert.equal(h.maps.at(-1).camera.latitude, 37.71);
h.send({ type: 'resize-window', windowId: 'navigate:main', viewport: { width: 540, height: 260 } }); await flush();
assert.equal(h.maps.at(-1).width, 540);
assert.equal(h.maps.at(-1).height, 230);
h.send({ type: 'close-window' });
assert.equal(h.tracker.running, false);
assert.equal(h.timers.size, 0);
assert.deepEqual(h.errors, []);
});
test('starting a destination from map mode switches to route guidance', async () => {
const h = fixture(), starting = h.startMap();
h.fix(37.7); await starting; await flush();
await h.startNavigation('Test park', 'walking'); await flush();
assert.equal(h.state().phase, 'navigating');
assert.deepEqual(h.requests, ['geocode', 'route']);
assert.equal(h.maps.at(-1).width, 260);
assert.ok(h.maps.at(-1).routePath.length >= 2);
assert.deepEqual(h.errors, []);
});
test('failed destination lookup keeps map mode and tracking active', async () => {
const h = fixture(), starting = h.startMap();
h.fix(37.7); await starting; await flush();
h.failRoute();
await assert.rejects(h.startNavigation('Test park', 'walking'), /Route unavailable/);
assert.equal(h.state().phase, 'map');
assert.equal(h.tracker.running, true);
h.fix(37.705); await flush();
assert.equal(h.maps.at(-1).routePath, undefined);
assert.match(h.describeRouteStatus(), /No destination/);
});
test('map requires a fresh fix and releases tracking when GPS times out', async () => {
const h = fixture(), starting = h.startMap();
h.send({ type: 'navigation-sensors', event: { kind: 'location', location: { ...fix(37.7), timestampMs: Date.now() - 120000 } } });
await flush();
assert.equal(h.state().phase, 'acquiring');
assert.equal(h.maps.length, 0);
h.expireFix(); await starting;
assert.equal(h.state().phase, 'idle');
assert.equal(h.tracker.running, false);
assert.equal(h.timers.size, 0);
});
test('closing map during GPS acquisition cannot reopen it on a late fix', async () => {
const h = fixture(), starting = h.startMap();
h.send({ type: 'close-window' });
h.fix(37.7); h.expireFix(); await starting;
assert.equal(h.state().phase, 'idle');
assert.equal(h.tracker.running, false);
assert.equal(h.maps.length, 0);
assert.equal(h.timers.size, 0);
});
for (const completion of ['resolve', 'reject']) {
test(`old map fetch ${completion} cannot overwrite a new mode or clear its pending fetch`, async () => {
const h = fixture(), oldMap = h.holdMap(), starting = h.startMap();
h.fix(37.7); await starting;
h.input('click');
const newMap = h.holdMap();
await h.startMap();
oldMap[completion](new Error('Old map failed')); await flush();
assert.equal(h.state().mapInFlight, true);
assert.equal(h.state().mapImage, null);
assert.equal(h.state().mapLastError, '');
newMap.resolve(); await flush();
assert.ok(h.state().mapImage);
assert.equal(h.state().mapInFlight, false);
});
}