Add a distance unit option

This commit is contained in:
James Babcock committed 2026-10-26 00:45:10 -07:00
1 parent 22f869d31c
commit 1ec77a8ade
5 files changed
+82 -14

No files matched your search

+34 -10
View File
@@ -28,6 +28,7 @@ import { WindowMenu, WindowMenuLayer } from "../../ui/window-menu";
import type { LayerContext } from "../../ui/layers";
import { truncateText, wrapText } from "../../graphics/textwrap";
import { onSettingsStoreChanged } from "../../native/settings-store";
import { formatClockTime } from "../../ui/clock-format";
import { openUrlOnPhone } from "../../native/open-url";
import {
navigateDestinationAddressDraftSetting,
@@ -35,6 +36,9 @@ import {
navigateRememberRecentSetting,
navigateDisplayLayoutSetting,
mapboxApiKeySetting,
distanceUnitSetting,
DISTANCE_UNIT_SETTING_KEY,
TIME_FORMAT_SETTING_KEY,
enumSettingMenuItem,
type ConfigSettingString,
} from "../../ui/dashboard-settings";
@@ -266,8 +270,15 @@ function post(message: WorkerAppReply): void {
// the edit screen live.
onSettingsStoreChanged((key) => {
// The token key repaints too: the phone editor writes it live during
// Edit token, and the idle page changes shape once one is set.
if (key.startsWith("navigate.") || key === MAPBOX_TOKEN_SETTING_KEY) render();
// Edit token, and the idle page changes shape once one is set. So do the
// distance unit and time format (Settings > Customization), for the
// guidance panel.
if (
key.startsWith("navigate.") ||
key === MAPBOX_TOKEN_SETTING_KEY ||
key === DISTANCE_UNIT_SETTING_KEY ||
key === TIME_FORMAT_SETTING_KEY
) render();
});
// The host queues messages until this arrives: posts to a worker whose bundle
@@ -1569,15 +1580,33 @@ function drawFooter(image: GrayImage, text: string, x = 16): void {
}
// ---------------------------------------------------------------------------
// Formatting (imperial; matches the rest of the UI)
// Formatting (distances and clock times follow Settings > Customization)
function metricDistances(): boolean {
return distanceUnitSetting.get() === "kilometers";
}
/** Under a kilometer: 10 m steps up to 100 m, then 50 m steps. */
function formatMeters(meters: number): string {
const step = meters < 100 ? 10 : 50;
return `${Math.max(0, Math.round(meters / step) * step)} m`;
}
function formatDistanceShort(meters: number): string {
if (metricDistances()) {
return meters < 950 ? formatMeters(meters) : `${(meters / 1000).toFixed(1)} km`;
}
const feet = meters * 3.28084;
if (feet < 900) return `${Math.max(0, Math.round(feet / 50) * 50)} ft`;
return `${(feet / 5280).toFixed(1)} mi`;
}
function formatDistance(meters: number): string {
if (metricDistances()) {
if (meters < 950) return formatMeters(meters);
const km = meters / 1000;
return km >= 10 ? `${Math.round(km)} km` : `${km.toFixed(1)} km`;
}
const feet = meters * 3.28084;
if (feet < 1000) return `${Math.max(0, Math.round(feet / 50) * 50)} ft`;
const miles = feet / 5280;
@@ -1597,14 +1626,9 @@ function formatDurationLong(seconds: number): string {
return `${hours}h ${minutes % 60}m`;
}
/** "14:05" / "2:05 PM", as the top-bar clock shows it. */
function formatClock(timestampMs: number): string {
const date = new Date(timestampMs);
let hours = date.getHours();
const minutes = String(date.getMinutes()).padStart(2, "0");
const meridiem = hours >= 12 ? "PM" : "AM";
hours = hours % 12;
if (hours === 0) hours = 12;
return `${hours}:${minutes} ${meridiem}`;
return formatClockTime(new Date(timestampMs));
}
// ---------------------------------------------------------------------------
+7 -1
View File
@@ -6,6 +6,7 @@ import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext } from "../../ui/layers";
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
import { centeredTextY, lineStep, tightRowHeight } from "../../ui/metrics";
import { distanceUnitSetting } from "../../ui/dashboard-settings";
import { renderWeatherIcon } from "./weather-icons";
import { formatTemperature, widestTemperatureSample } from "./temperature-format";
@@ -142,7 +143,7 @@ export class WeatherLayer implements Layer {
const details: string[] = [];
if (current.humidityPercent !== null) details.push(`Humidity ${Math.round(current.humidityPercent)}%`);
if (current.windSpeedMph !== null) {
details.push(`Wind ${current.windDirection ? `${current.windDirection} ` : ""}${Math.round(current.windSpeedMph)} mph`);
details.push(`Wind ${current.windDirection ? `${current.windDirection} ` : ""}${formatWindSpeed(current.windSpeedMph)}`);
}
image.drawText(small, textX, cy, details.join(" ") || "Current forecast", 170);
cy += lineStep(small);
@@ -247,6 +248,11 @@ function forecastRowHeight(font: UiFont): number {
return Math.max(FORECAST_MIN_ROW_HEIGHT, tightRowHeight(font) + 3);
}
/** A wind speed (weather data is kept in mph) in the Distance unit setting's speed unit: "12 mph" / "19 km/h". */
function formatWindSpeed(mph: number): string {
return distanceUnitSetting.get() === "kilometers" ? `${Math.round(mph * 1.609344)} km/h` : `${Math.round(mph)} mph`;
}
function formatAge(ageMs: number): string {
const minutes = Math.max(0, Math.round(ageMs / 60_000));
if (minutes < 1) return "just now";
+19 -2
View File
@@ -37,6 +37,7 @@ export type BatteryDisplayMode = "icon" | "percentage" | "stacked" | "stacked-pe
export type BatteryIndicatorVisibility = "always" | "low" | "never";
export type TimeFormat = "24h" | "12h";
export type TemperatureUnit = "fahrenheit" | "celsius";
export type DistanceUnit = "miles" | "kilometers";
export type ScreenTimeoutSetting = "15s" | "30s" | "1m" | "3m" | "never";
// Auto runs Faceclaw's light curve. Numeric values use the calibrated firmware
// scale, clamped to 2–100; 2 is also the endpoint for screen fades.
@@ -322,14 +323,17 @@ export function batteryIndicatorSettingsKey(): string {
].join("|");
}
/** Exported so the Navigate worker can repaint when it changes. */
export const TIME_FORMAT_SETTING_KEY = "display.timeFormat";
export const timeFormatSetting = new ConfigSettingEnum<TimeFormat>({
id: "timeFormat",
label: "Time format",
storageKey: "display.timeFormat",
storageKey: TIME_FORMAT_SETTING_KEY,
defaultValue: "24h",
values: ["24h", "12h"],
formatValue: timeFormatLabel,
description: "Whether the top-bar clock shows 24-hour or 12-hour time.",
description: "Whether the top-bar clock and other times of day, such as Navigate's arrival time, show 24-hour or 12-hour time.",
});
export const temperatureUnitSetting = new ConfigSettingEnum<TemperatureUnit>({
@@ -342,6 +346,19 @@ export const temperatureUnitSetting = new ConfigSettingEnum<TemperatureUnit>({
description: "Whether the Weather app, its top-bar indicator, and the Glanceboard's system card show temperatures in Fahrenheit or Celsius.",
});
/** Exported so the Navigate worker can repaint when it changes. */
export const DISTANCE_UNIT_SETTING_KEY = "display.distanceUnit";
export const distanceUnitSetting = new ConfigSettingEnum<DistanceUnit>({
id: "distanceUnit",
label: "Distance unit",
storageKey: DISTANCE_UNIT_SETTING_KEY,
defaultValue: "miles",
values: ["miles", "kilometers"],
formatValue: (value) => value === "kilometers" ? "Kilometers" : "Miles",
description: "Whether the Weather app shows wind speed in mph or km/h, and the Navigate app shows distances in miles and feet or kilometers and meters.",
});
/**
* Where the app switcher (the open-window icons) sits: a strip along the
* left or right edge of the display, a row under the window, or a popup box
+3
View File
@@ -49,6 +49,7 @@ import {
autoBrightnessMaxSetting,
autoBrightnessCurveSetting,
dataCollectionSetting,
distanceUnitSetting,
glassesBatteryVisibilitySetting,
phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting,
@@ -292,6 +293,8 @@ function customizationRows(): () => MenuItem[] {
enumSettingMenuItem(timeFormatSetting),
// Fahrenheit or Celsius, wherever weather temperatures show.
enumSettingMenuItem(temperatureUnitSetting),
// Miles or kilometers: Weather's wind speed and Navigate's distances.
enumSettingMenuItem(distanceUnitSetting),
];
const bottomRows = [font, position, depth, statusBar, ...rest];
const popupRows = [font, position, depth, statusBar, statusBarVisibility, windowBorder, ...rest];
+19 -1
View File
@@ -13,7 +13,7 @@ const route = { coordinates: [[-122.4, 37.7], [-122.4, 37.71]], distanceMeters:
const fix = latitude => ({ latitude, longitude: -122.4, timestampMs: Date.now(), bearingDeg: 0, speedMps: 1.5, accuracyMeters: 5 });
function fixture() {
const messages = [], timers = new Set(), timeouts = new Set(), holds = [], maps = [], errors = [], requests = [];
let callbacks, compass, delayRoute = null, delayMap = null, routeError = null;
let callbacks, compass, delayRoute = null, delayMap = null, routeError = null, distanceUnit = 'miles', timeFormat = '24h';
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,
@@ -24,6 +24,8 @@ function fixture() {
'@nativescript/core/globals': {},
'../../graphics/bdffont': { getFont: () => ({}) }, '../../graphics/ui-fonts': { getDefaultSmallFont: () => ({}) },
'../../native/settings-store': { onSettingsStoreChanged() {} },
'../../ui/dashboard-settings': { distanceUnitSetting: { get: () => distanceUnit } },
'../../ui/clock-format': loader({}, { './dashboard-settings': { timeFormatSetting: { get: () => timeFormat } } })('app/ui/clock-format.ts'),
'./navigation-sensors': sensor,
'./route-follower': routeMath,
'./destinations': { findSavedDestinationByName: () => null, rememberRecentDestination() {},
@@ -59,6 +61,8 @@ function fixture() {
tick: () => { for (const callback of timers) callback(); },
expireFix: () => { for (const callback of timeouts) callback(); timeouts.clear(); },
failRoute: () => { routeError = new Error('Route unavailable'); },
setDistanceUnit: value => { distanceUnit = value; },
setTimeFormat: value => { timeFormat = value; },
fix: latitude => send({ type: 'navigation-sensors', event: { kind: 'location', location: fix(latitude), id: 1 } }),
heading: value => compass?.({ command: 15, headingDegrees: value }),
holdMap: () => { let resolve, reject; delayMap = new Promise((done, fail) => { resolve = done; reject = fail; });
@@ -77,6 +81,20 @@ test('shared Navigate worker follows streamed GPS, uses calibrated true heading
assert.equal(h.timers.size, 0); assert.deepEqual(h.errors, []);
});
test('route distances follow the distance unit setting', async () => {
const h = fixture(); const starting = h.startNavigation('Test park', 'walking');
h.fix(37.7); assert.match(await starting, /: 0\.7 mi, about 10 minutes/);
h.fix(37.705); assert.match(h.describeRouteStatus(), /in 0\.3 mi\. 0\.3 mi and/);
h.setDistanceUnit('kilometers'); assert.match(h.describeRouteStatus(), /in 550 m\. 550 m and/);
});
test('arrival times follow the time format setting', async () => {
const h = fixture(); const starting = h.startNavigation('Test park', 'walking');
h.fix(37.7); assert.match(await starting, /arriving \d{1,2}:\d{2}\./);
h.fix(37.705); assert.match(h.describeRouteStatus(), /ETA \d{1,2}:\d{2}\.$/);
h.setTimeFormat('12h'); assert.match(h.describeRouteStatus(), /ETA \d{1,2}:\d{2} [AP]M\.$/);
});
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');