Port navigate and weather

This commit is contained in:
James Babcock committed 2026-09-18 23:46:27 -07:00
1 parent 2b3e068a23
commit 9e18745e53
33 files changed
+630 -60

No files matched your search

+2
View File
@@ -89,6 +89,7 @@ test('background glasses input still composites frames; phone resume preserves t
}
const settings = { onAnySettingChanged: () => () => {}, previewColorSetting: { get: () => 'white' } };
const modules = {
"../native/ios-navigation-sensors": {},
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) }, knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
'../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {} } },
@@ -157,6 +158,7 @@ test('iOS bandwidth footer toggles live, polls only in foreground and resets its
on: (key, fn) => appEvents.set(key, fn), off: key => appEvents.delete(key) },
Button: View, Color: class {}, Dialogs: {}, GridLayout: View, Image: View, Label: View, Page: View, StackLayout: View };
const modules = {
"../native/ios-navigation-sensors": {},
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': core,
'../apps/all-apps': { ALL_APPS: [] },
+1
View File
@@ -68,6 +68,7 @@ function fixture() {
paint: () => { boardStats.paints++; return new images.GrayImage(100, 80, 200); } }),
};
const modules = {
"../native/ios-navigation-sensors": {},
"../native/compass.ios": { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) },
knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
+122
View File
@@ -0,0 +1,122 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const flush = () => new Promise(resolve => setImmediate(resolve));
function nativeLocation() {
const instances = [];
const FaceclawLocationUpdates = { new() {
const value = { stopped: 0, startOnce() { this.once = true; }, startTracking(ms) { this.interval = ms; },
stop() { this.stopped++; this.eventHandler = null; } };
instances.push(value); return value;
} };
return { instances, load: loader({ FaceclawLocationUpdates }) };
}
const fix = { latitude: 37.7, longitude: -122.4, accuracyMeters: 8, bearingDeg: null, speedMps: null, timestampMs: 1234 };
test('iOS one-shot location resolves a fix, rejects native errors, and releases each provider', async () => {
const h = nativeLocation(), api = h.load('app/native/location.ios.ts');
const result = api.getCurrentLocation(), native = h.instances[0];
assert.equal(native.once, true);
native.eventHandler(JSON.stringify(fix));
assert.deepEqual({ ...await result }, fix); assert.ok(native.stopped);
const denied = api.getCurrentLocation();
h.instances[1].eventHandler(JSON.stringify({ error: 'Permission denied' }));
await assert.rejects(denied, /Permission denied/);
assert.ok(h.instances[1].stopped);
});
test('iOS tracking preserves unavailable course/speed and ignores callbacks after stop or restart', () => {
const h = nativeLocation(), api = h.load('app/native/location-tracker.ios.ts'), fixes = [], errors = [];
const tracker = new api.LocationTracker({ onLocation: fix => fixes.push(fix), onError: error => errors.push(error) });
tracker.start(1000); tracker.start(1000);
assert.equal(h.instances.length, 1); assert.equal(h.instances[0].interval, 1000);
const old = h.instances[0].eventHandler;
old(JSON.stringify(fix)); tracker.stop(); old(JSON.stringify(fix)); tracker.start(); old(JSON.stringify(fix));
assert.equal(fixes.length, 1); assert.equal(fixes[0].bearingDeg, null);
h.instances[1].eventHandler(JSON.stringify({ error: 'Location disabled' }));
assert.equal(tracker.isRunning(), false); assert.deepEqual(errors, ['Location disabled']);
});
test('Navigate worker routes sensor callbacks by stream id and receives true-north correction', () => {
const messages = [], fixes = [], headings = [];
const api = loader({ global: { postMessage: message => messages.push(message) } })('app/apps/navigate/navigation-sensors.ios.ts');
const tracker = new api.LocationTracker({ onLocation: fix => fixes.push(fix), onError() {} });
tracker.start(); const first = messages.at(-1).request.id;
tracker.stop(); tracker.start(); const second = messages.at(-1).request.id;
api.handleNavigationSensorEvent({ kind: 'location', id: first, location: fix });
api.handleNavigationSensorEvent({ kind: 'location', id: second, location: fix });
assert.equal(fixes.length, 1);
const off = api.addCompassListener(event => headings.push(event));
api.handleNavigationSensorEvent({ kind: 'compass', event: { command: 15, headingDegrees: 123 }, declination: 12 });
assert.equal(api.magneticDeclinationDegrees(37.7, -122.4), 12);
off(); api.handleNavigationSensorEvent({ kind: 'compass', event: {}, declination: null });
assert.equal(headings.length, 1); tracker.stop();
});
function sensorHost() {
const pending = [], trackers = [], holds = [], replies = [];
let compass;
class Tracker {
constructor(callbacks) { this.callbacks = callbacks; trackers.push(this); }
start() { this.started = true; }
stop() { this.stopped = true; }
}
const api = loader({}, {
'./location-tracker.ios': { LocationTracker: Tracker },
'./location-permissions.ios': { ensureFineLocationPermission: () => new Promise(resolve => pending.push(resolve)) },
'./compass.ios': { setCompassEnabled: (on, owner) => holds.push([on, owner]),
addCompassListener: fn => { compass = fn; return () => { compass = null; }; } },
'../apps/compass/declination': { refreshDeclination() {}, getDeclinationDegrees: () => 12.5 },
})('app/native/ios-navigation-sensors.ts');
return { host: new api.IosNavigationSensors(event => replies.push(event)), pending, trackers, holds, replies,
heading: () => compass?.({ command: 15, headingDegrees: 90 }) };
}
test('closing Navigate while precise permission is pending cannot start GPS later', async () => {
const h = sensorHost(); h.host.handle({ action: 'start', id: 1, intervalMs: 1000 });
h.host.stop(); h.pending.shift()(true); await flush();
assert.equal(h.trackers.length, 0); assert.equal(h.replies.length, 0);
h.host.handle({ action: 'start', id: 2, intervalMs: 1000 }); h.pending.shift()(false); await flush();
assert.equal(h.replies[0].kind, 'error'); assert.equal(h.replies[0].id, 2);
});
test('Navigate host releases GPS and compass together and ignores an old stream error', async () => {
const h = sensorHost(); h.host.handle({ action: 'start', id: 1, intervalMs: 1000 });
h.pending.shift()(true); await flush();
h.host.handle({ action: 'compass', enabled: true }); h.heading();
assert.equal(h.replies[0].declination, 12.5);
h.trackers[0].callbacks.onLocation(fix); assert.equal(h.replies[1].kind, 'location');
h.host.stop(); h.trackers[0].callbacks.onError('late error'); h.heading();
assert.equal(h.replies.length, 2); assert.equal(h.trackers[0].stopped, true);
assert.deepEqual(h.holds.at(-1), [false, 'worker:navigate']);
});
test('Weather uses the portable location provider and preserves NWS parsing', async () => {
const requests = [], timers = new Set(); let permission = true;
const period = { name: 'Today', temperature: 70, temperatureUnit: 'F', shortForecast: 'Sunny', windSpeed: '5 mph', windDirection: 'W' };
const api = loader({ setTimeout, clearTimeout, setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn) }, {
'./location-permissions': { hasLocationPermission: () => permission },
'./location': { getCurrentLocation: async () => fix },
'../version': { USER_AGENT: 'test' },
'../util/http': { fetchWithUserAgent: async url => { requests.push(url); return { ok: true, json: async () =>
url.includes('/points/') ? { properties: { forecast: 'https://fixture/forecast', relativeLocation: { properties: { city: 'San Francisco', state: 'CA' } } } }
: { properties: { periods: [period] } } }; } },
})('app/native/weather.ts');
const bridge = new api.WeatherBridge(); bridge.start(); await bridge.refreshNow();
assert.equal(bridge.snapshot().phase, 'ready'); assert.equal(bridge.snapshot().current.temperatureF, 70);
assert.equal(bridge.snapshot().locationName, 'San Francisco, CA');
assert.match(requests[0], /37\.7000,-122\.4000/);
bridge.stop(); assert.equal(timers.size, 0);
permission = false; await bridge.refreshNow(); assert.equal(bridge.snapshot().phase, 'permission-required');
});
test('closing Weather during permission prompt cannot restart polling', async () => {
let granted, options, starts = 0, stops = 0;
const api = loader({}, {
'../../native/location-permissions': { hasLocationPermission: () => false, ensureLocationPermission: () => new Promise(resolve => { granted = resolve; }) },
'../../native/weather': { weatherBridge: { start() { starts++; }, stop() { stops++; }, onStateChange: () => () => {}, snapshot() {} } },
'./weather': { WeatherLayer: class {} },
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: opts => { options = opts; return { requestRender() {} }; } },
})('app/apps/weather/weather-app.ts');
api.createWeatherAppWindow({ onClosed() {} }); options.onClosed(); granted(true); await flush();
assert.equal(starts, 0); assert.equal(stops, 1);
});
+78
View File
@@ -0,0 +1,78 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
const path = require('node:path');
const { loader } = require('./helpers/load-typescript.cjs');
const flush = () => new Promise(resolve => setImmediate(resolve));
const route = { coordinates: [[-122.4, 37.7], [-122.4, 37.71]], distanceMeters: 1112, durationSec: 600,
steps: [{ distanceMeters: 1112, durationSec: 600, instruction: 'Head north', maneuverType: 'depart' },
{ 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 });
function fixture() {
const messages = [], timers = new Set(), holds = [], maps = [], errors = [];
let callbacks, compass, delayRoute = null;
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 sensor = { LocationTracker: function (value) { callbacks = value; return tracker; }, COMPASS_CHANGED: 15,
addCompassListener: fn => { compass = fn; return () => { compass = null; }; },
setCompassEnabled: value => holds.push(value), magneticDeclinationDegrees: () => 12,
handleNavigationSensorEvent: event => { if (event.kind === 'location') callbacks.onLocation(event.location); } };
const modules = {
'@nativescript/core/globals': {},
'../../graphics/bdffont': { getFont: () => ({}) }, '../../graphics/ui-fonts': { getDefaultSmallFont: () => ({}) },
'../../native/settings-store': { onSettingsStoreChanged() {} },
'./navigation-sensors': sensor,
'./route-follower': routeMath,
'./destinations': { findSavedDestinationByName: () => null, rememberRecentDestination() {} },
'../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/active-display': { getActiveDisplay: () => null },
'../../ui/window-menu': { WindowMenu: class { paint() { return []; } } },
'../../graphics/plane': { planesFingerprint: () => 'frame' },
'../../native/mapbox': {
isMapboxConfigured: () => true,
geocodeForward: async () => [{ name: 'Test park', placeFormatted: 'San Francisco', latitude: 37.71, longitude: -122.4 }],
fetchRoute: async () => delayRoute ? await delayRoute : route,
fetchStaticMapGray: async options => { maps.push(options); return { pixels: new Uint8Array([0, 128, 255]) }; },
},
};
const global = { postMessage: message => messages.push(message) };
const source = fs.readFileSync(path.join(__dirname, '../app/apps/navigate/navigate-app.worker.ts'), 'utf8') +
'\nexports.probe = { startNavigation, stopNavigation, state: () => ({ phase, headHeadingDeg, progress }) };';
const exports = {};
vm.runInNewContext(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText, {
exports, global, Uint8Array, setTimeout, clearTimeout,
setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn),
console: { log() {}, warn() {}, error: error => errors.push(error) }, require: id => modules[id] ?? {},
});
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: 'foreground', windowId: 'navigate:main', foreground: true, focused: true });
return { ...exports.probe, send, timers, holds, maps, errors, tracker,
fix: latitude => send({ type: 'navigation-sensors', event: { kind: 'location', location: fix(latitude), id: 1 } }),
heading: value => compass?.({ command: 15, headingDegrees: value }),
holdRoute: () => { let resolve; delayRoute = new Promise(done => { resolve = done; }); return () => resolve(route); } };
}
test('shared Navigate worker follows streamed GPS, uses calibrated true heading and stops at arrival', async () => {
const h = fixture(); const starting = h.startNavigation('Test park', 'walking');
h.fix(37.7); assert.match(await starting, /Navigating to Test park/); await flush();
assert.equal(h.state().phase, 'navigating'); assert.ok(h.maps.length > 0);
h.heading(90); assert.equal(h.state().headHeadingDeg, 107);
h.send({ type: 'screen', on: false }); assert.equal(h.holds.at(-1), false); assert.equal(h.tracker.running, true);
h.fix(37.705); assert.ok(h.state().progress.remainingMeters < 600);
h.fix(37.71); assert.equal(h.state().phase, 'arrived'); assert.equal(h.tracker.running, false);
assert.equal(h.timers.size, 0); assert.deepEqual(h.errors, []);
});
test('closing Navigate while a route request is pending cannot restart guidance or GPS', async () => {
const h = fixture(), release = h.holdRoute();
const starting = h.startNavigation('Test park', 'walking');
h.fix(37.7); await flush(); assert.equal(h.state().phase, 'routing');
h.send({ type: 'close-window', windowId: 'navigate:main' }); release();
await assert.rejects(starting, /Navigation cancelled/);
assert.equal(h.state().phase, 'idle'); assert.equal(h.tracker.running, false); assert.equal(h.timers.size, 0);
});