diff --git a/README.md b/README.md index 3b02412..33b8357 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Bike trainer control web app using Web Bluetooth. Tested with Wahoo KICKR Core 2 - Shows each deployment's build time in the viewer's local timezone and links it to the GitHub pull request that produced the build, falling back to the closed pull-request list when no associated PR is available. - Connects to compatible bike trainers and standard Bluetooth heart rate monitors through Web Bluetooth, remembers authorized devices, and restores the trainer, heart-rate monitor, and `+` Click controller from one browser permission snapshot after a reload. Each browser chooser filters by the required advertised service, so trainer pairing shows FTMS hardware while heart-rate pairing shows standard heart-rate monitors. The trainer adapter is based on capability instead of a vendor-specific name, allowing the same path to support Wahoo, Elite, and other standards-compliant trainers while keeping one active trainer for a ride. FTMS control commands wait for the trainer's matching acknowledgement and establish control with the standard Request Control and Start/Resume procedures before resistance is restored. Runtime resistance updates are coalesced to the newest target and sent at most twice per second, preventing ramps and live terrain feedback from building a stale command backlog on slower trainers. A timed-out control response or disconnected GATT write invalidates the old command path and triggers a clean automatic reconnect instead of repeatedly writing through a dead characteristic. The trainer and heart-rate monitor begin reconnecting immediately and independently; the remembered Click controller joins those parallel attempts while a session is open and not manually paused. Trainers and the active Click controller keep advertisement discovery active through the GATT handshake so Chrome can react as soon as they broadcast, while heart-rate monitors use direct GATT retries because common HRMs do not reliably surface advertisements through Chrome's watcher. A shared coordinator deduplicates requests to the same physical device without letting a slow sensor block the others, and each device's service and notification setup stays sequential for reliable GATT communication. - Shows live speed, power, cadence, heart rate, elapsed time, distance, and estimated calories, with MPH and KM/H display modes. -- Keeps an optional rider profile in IndexedDB with name, profile image, rider and bike weight, an inclusive free-form sex or gender identity field, and editable front-chainring and rear-cassette tooth counts. Weight follows the dashboard's pounds or kilograms display, while calculations use canonical kilograms. Rider and bike mass scale terrain load, and the configured tooth counts define up to 24 ordered virtual gear ratios; identity, name, and image never affect workout calculations. +- Keeps an optional rider profile in IndexedDB with name, profile image, rider and bike weight, an inclusive free-form sex or gender identity field, editable front-chainring and rear-cassette tooth counts, and the app-wide MPH or KM/H display preference. Profile images are resized and compressed to a compact WebP in the browser before storage. Weight follows the profile's selected pounds or kilograms display, while calculations use canonical kilograms. The browser warns before reloading while the open profile contains unsaved changes. Each ride captures an immutable, physics-only snapshot of rider weight, bike weight, chainrings, and cassette before recording begins, preserves it through active-session recovery and continuation, and round-trips it through Ride Control TCX files so historical rides remain attributable to the settings that produced them. Those physics fields lock after recording begins and unlock when the session ends; name, image, identity, and display units remain editable. Rider and bike mass scale terrain load, and the configured tooth counts define up to 24 ordered virtual gear ratios; identity, name, and image never affect workout calculations or enter session history. - Provides direct resistance control with buttons, a slider, and keyboard shortcuts with matching button feedback, shows smoothing progress inside the slider thumb, and records resistance changes alongside the other ride metrics. - Offers original terrain workouts built as repeatable courses, with gentle, rolling, and climbing options and distinctive winding top-down route shapes. Courses explicitly support loops, point-to-point routes, and out-and-back routes; an out-and-back follows the supplied path to its turnaround, then reverses the same location and elevation data back to the start before repeating. Prairie Roll adds a non-intersecting, curving 15-mile loop of repeated gradual climbs and descents. Granite Switchbacks adds a sustained four-mile ascent whose hairpin corners briefly get steeper before immediately returning to the steady climbing grade, followed by a ridge and a descending sequence of five recovery rollers. Ridgeline Time Trial is a ten-mile out-and-back with a gradual five-mile, roughly 300-foot hillclimb to the turnaround and the identical terrain in reverse on the return. Every course begins flat without giving nearly level routes an unnecessarily long rollout: low-climb courses use about 0.4 km, moderate rollers use about 0.8 km, and climbing-focused courses retain a 1.5 km rollout. The course then automatically adjusts trainer resistance from the current grade, tracks the rider in compact, vertically aligned top-down and elevation views with a clearly labelled ridden-this-lap, ridden-this-trip, or ridden-this-route path and pulsing position markers while pedaling, and uses clear mid-contrast preview lines with a shared elevation scale so gentle rollers remain visibly low beside genuinely mountainous routes. It shows course distance progress to two decimal places alongside course percentage, current grade, and effective trainer resistance directly on the map, with grade and resistance values matching their graph colors, and derives cumulative ride climbing and downhill from course distance so those totals remain aligned with the advertised full-course climb. Elevation appears in feet with MPH or meters with KM/H, and terrain totals and progress are recorded with the session and preserved in saved history and TCX import/export. Currently open in-progress sessions resolve bundled workout IDs to the latest course definition, preventing stale geometry from lingering before a ride is saved; saved history keeps the exact workout snapshot used by that ride. A workout can be selected before riding or planned while viewing a completed session; ending a workout keeps it selected and previews it at 0% for the next session unless the rider clears or replaces it. A newly planned workout immediately replaces the prior course on the dashboard at 0% progress without changing the completed ride's recorded data. It then remains locked from the moment riding begins until that session ends; definition refreshes for that same workout remain allowed without opening a path to switch courses. Routes contain geometry and elevation rather than an arbitrary resistance baseline; one shared terrain engine derives the load from grade before virtual gearing is applied. - Downloads terrain workouts as standard GPX 1.1 files with ordinary geographic and elevation data plus Ride Control metadata for stable ids, difficulty, exact distance, starting location, and route type. Valid GPX tracks or routes can be imported through the file picker or by dropping a file anywhere in the workout tray, then saved into the current device's custom library with every valid route point preserved. The map-first BikeGPX browser lists only fully prepared public routes, searches them by name, place, distance, or difficulty, filters in the dashboard's current units, continuously scrolls a virtualized list, previews complete routes over OpenStreetMap, shows the selected route's elevation profile beside its finalized statistics, and imports it in one click. Every visible route already includes finalized distance, climbing, maximum grade, and difficulty, and the first matching route previews automatically. Imported route descriptions can open an in-app map with start and finish markers and an animated bicycle; routes with genuinely nearby endpoints become loops while other routes remain point-to-point. Stable fingerprints prevent duplicate imports. The workout library supports immediate filtering, renaming, removing, and vertical drag reordering with persistent order. The terrain tray and BikeGPX browser remember their open state, scroll positions, searches, filters, and selected route across reloads. Missing descriptions use a cached starting-city lookup that is saved with the workout. diff --git a/bun.lock b/bun.lock index efeaebc..8c28ff6 100644 --- a/bun.lock +++ b/bun.lock @@ -10,6 +10,7 @@ "@dnd-kit/sortable": "10.0.0", "@garmin/fitsdk": "^21.208.0", "@tailwindcss/vite": "^4.3.3", + "@tanstack/react-form": "^1.33.2", "@tanstack/react-router": "^1.170.18", "@tanstack/react-store": "^0.11.0", "@tanstack/react-virtual": "^3.14.7", @@ -19,6 +20,7 @@ "react": "^19.2.8", "react-dom": "^19.2.8", "tailwindcss": "^4.3.3", + "zod": "^4.4.3", }, "devDependencies": { "@biomejs/biome": "^2.5.5", @@ -310,8 +312,16 @@ "@tailwindcss/vite": ["@tailwindcss/vite@4.3.3", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="], + "@tanstack/devtools-event-client": ["@tanstack/devtools-event-client@0.4.4", "", { "bin": { "intent": "./bin/intent.js" } }, "sha512-6T5Yop/793YI+H+5J8Hsyj4kCih9sl4t3ElLgKioW5hk3ocn+ZdSJ94tT7vL7uabxSugWYBZlOTMPzEw2puvQw=="], + + "@tanstack/form-core": ["@tanstack/form-core@1.33.2", "", { "dependencies": { "@tanstack/devtools-event-client": "^0.4.1", "@tanstack/pacer-lite": "^0.1.1", "@tanstack/store": "^0.11.0" } }, "sha512-F60zJd15bGrXKonc1kpRYnNRNfiES7F+hgvrPMrsZznPLqZtO2DIg76OU6R25kCYkqYQY5xvuKteuWcUsc587A=="], + "@tanstack/history": ["@tanstack/history@1.162.0", "", {}, "sha512-79pf/RkhteYZTRgcR4F9kbk84P2N8rugQJswxfIqovlbRiT3yI7eBE+5QorIrZaOKktsgzRlXh1l/du/xpl4iA=="], + "@tanstack/pacer-lite": ["@tanstack/pacer-lite@0.1.1", "", {}, "sha512-y/xtNPNt/YeyoVxE/JCx+T7yjEzpezmbb+toK8DDD1P4m7Kzs5YR956+7OKexG3f8aXgC3rLZl7b1V+yNUSy5w=="], + + "@tanstack/react-form": ["@tanstack/react-form@1.33.2", "", { "dependencies": { "@tanstack/form-core": "1.33.2", "@tanstack/react-store": "^0.11.0" }, "peerDependencies": { "@tanstack/react-start": "*", "react": "^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@tanstack/react-start"] }, "sha512-nEfayOu+27q5cZ5E0G5dmnddqLcLjdFCatbL/LCs/iLD469a1o1yYJlr8RISV3GfnqsBpm0hf+8kM4okh5fPCw=="], + "@tanstack/react-router": ["@tanstack/react-router@1.170.18", "", { "dependencies": { "@tanstack/history": "1.162.0", "@tanstack/react-store": "^0.9.3", "@tanstack/router-core": "1.171.15", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-wpbGYZEp/fmz1q4bn7BD8VZ+/VZ7GBqSJv5V969pU+chP8y7dquWDmKTFMohvUegb9lg12m1uPVvD6kB2wORvQ=="], "@tanstack/react-store": ["@tanstack/react-store@0.11.0", "", { "dependencies": { "@tanstack/store": "0.11.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-tX4YXh3PDkmpvGQWkWqKpzs/MSqbtuwY9dWdWhtV9Q50PmO+jOkUKIWIX4G85dwt7lxdHLXsiaEKPdKmC8F41w=="], diff --git a/package.json b/package.json index 0b6ae8b..a73ab0d 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "@dnd-kit/sortable": "10.0.0", "@garmin/fitsdk": "^21.208.0", "@tailwindcss/vite": "^4.3.3", + "@tanstack/react-form": "^1.33.2", "@tanstack/react-router": "^1.170.18", "@tanstack/react-store": "^0.11.0", "@tanstack/react-virtual": "^3.14.7", @@ -28,7 +29,8 @@ "leaflet": "^1.9.4", "react": "^19.2.8", "react-dom": "^19.2.8", - "tailwindcss": "^4.3.3" + "tailwindcss": "^4.3.3", + "zod": "^4.4.3" }, "devDependencies": { "@biomejs/biome": "^2.5.5", diff --git a/src/app.tsx b/src/app.tsx index 0d053c8..954efc0 100644 --- a/src/app.tsx +++ b/src/app.tsx @@ -1,6 +1,6 @@ import { useNavigate, useRouterState } from '@tanstack/react-router'; import { useSelector } from '@tanstack/react-store'; -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { AppFooter } from './components/app-footer'; import { BuildDetailsDialog } from './components/build-details-dialog'; import { Dashboard, DashboardToolbar, DashboardWorkspace } from './components/dashboard-layout'; @@ -60,7 +60,8 @@ import { unreachable } from './lib/errors'; import { maximumGear, resistanceForVirtualGear } from './lib/gears'; import { type AppShortcut, appShortcutForKey, gearingKeyboardShortcuts } from './lib/keyboard'; import { profileTotalMassKg, type RiderProfile } from './lib/profile'; -import { requestUnloadConfirmation, sessionNeedsUnloadWarning } from './lib/session'; +import { sessionNeedsUnloadWarning } from './lib/session'; +import { requestUnloadConfirmation } from './lib/unload'; import { rememberWelcomeDismissal, shouldShowWelcome } from './lib/welcome'; import { workoutDashboardPreview, @@ -151,13 +152,13 @@ function initialNavigation(linkedRoute: AppRoute, pathname: string): InitialNavi } export function App({ initialSession = emptySession }: { initialSession?: StoredSession }) { - const routerNavigation = useRouterState({ - select: (state) => ({ - pathname: state.location.pathname, - route: appRouteFromRouterMatch(state.matches.at(-1)), - }), + const pathname = useRouterState({ + select: (state) => state.location.pathname, }); - const { pathname, route: matchedAppRoute } = routerNavigation; + const routerMatch = useRouterState({ + select: (state) => state.matches.at(-1), + }); + const matchedAppRoute = useMemo(() => appRouteFromRouterMatch(routerMatch), [routerMatch]); const navigate = useNavigate(); const [initialAppNavigation] = useState(() => initialNavigation(matchedAppRoute, pathname)); const restoringRoute = useRef( @@ -306,7 +307,8 @@ export function App({ initialSession = emptySession }: { initialSession?: Stored }, trainer.lastPedalingAt, trainer.trainerReportsDistance, - initialSession + initialSession, + riderProfile.ready ? riderProfile.profile : undefined ); const dashboardWorkout = workoutDashboardPreview({ distance: session.rideDistance, @@ -556,10 +558,9 @@ export function App({ initialSession = emptySession }: { initialSession?: Stored devicesConnecting={devicesConnecting} onOpenDevices={() => setActiveOverlay(APP_OVERLAY.DEVICES)} onOpenHistory={() => setActiveOverlay(APP_OVERLAY.HISTORY)} + onOpenProfile={() => setActiveOverlay(APP_OVERLAY.PROFILE)} onOpenShortcuts={() => setActiveOverlay(APP_OVERLAY.SHORTCUTS)} - onSelectSpeedUnit={preferencesStore.actions.selectSpeedUnit} pairedDeviceCount={pairedDeviceCount} - speedUnit={speedUnit} /> setActiveOverlay(APP_OVERLAY.PRIVACY)} - onOpenProfile={() => setActiveOverlay(APP_OVERLAY.PROFILE)} onOpenTerms={() => setActiveOverlay(APP_OVERLAY.TERMS)} onOpenVersion={() => setActiveOverlay(APP_OVERLAY.BUILD)} onOpenWelcome={() => setActiveOverlay(APP_OVERLAY.WELCOME)} @@ -720,7 +720,9 @@ export function App({ initialSession = emptySession }: { initialSession?: Stored setActiveOverlay(undefined)} onSave={riderProfile.save} + onSelectSpeedUnit={preferencesStore.actions.selectSpeedUnit} open={activeOverlay === APP_OVERLAY.PROFILE} + physicsSettingsLocked={warnBeforeUnload} profile={riderProfile.profile} speedUnit={speedUnit} storageError={riderProfile.storageError} diff --git a/src/components/app-footer.tsx b/src/components/app-footer.tsx index 36330fb..15cb135 100644 --- a/src/components/app-footer.tsx +++ b/src/components/app-footer.tsx @@ -5,13 +5,11 @@ const linkClass = export function AppFooter({ onOpenPrivacy, - onOpenProfile, onOpenTerms, onOpenVersion, onOpenWelcome, }: { onOpenPrivacy: () => void; - onOpenProfile: () => void; onOpenTerms: () => void; onOpenVersion: () => void; onOpenWelcome: () => void; @@ -35,10 +33,6 @@ export function AppFooter({ Sponsor - - Contact diff --git a/src/components/bikegpx-browser-dialog.tsx b/src/components/bikegpx-browser-dialog.tsx index b6908fd..fa99401 100644 --- a/src/components/bikegpx-browser-dialog.tsx +++ b/src/components/bikegpx-browser-dialog.tsx @@ -1,5 +1,5 @@ import { useVirtualizer } from '@tanstack/react-virtual'; -import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCloseOnEscape, useDialogInitialFocus } from '../hooks/use-dialog-behavior'; import { usePersistentScrollPosition } from '../hooks/use-persistent-scroll-position'; import { @@ -10,20 +10,20 @@ import { type BikeGpxRouteSummary, bikeGpxPreviewRoute, bikeGpxRouteLocation, - bikeGpxRouteMatchesQuery, bikeGpxRouteUrl, fetchBikeGpxRoute, formatBikeGpxRouteStats, } from '../lib/bikegpx'; +import { matchingBikeGpxRoutes } from '../lib/bikegpx-browser-form'; import { BIKEGPX_ROUTE_LIST_SCROLL_POSITION_STORAGE_KEY, - bikeGpxBrowserSearchForRoute, - bikeGpxBrowserSearchWithSelectedRoute, - loadBikeGpxBrowserSearch, + initialBikeGpxBrowserSearch, persistBikeGpxBrowserSearch, + type ReportedBikeGpxRouteId, + reconcileBikeGpxBrowserRoute, } from '../lib/bikegpx-browser-preferences'; import { errorMessage } from '../lib/errors'; -import { convertDistance, distanceUnitLabel } from '../lib/units'; +import { distanceUnitLabel } from '../lib/units'; import { isWorkoutDifficulty, WORKOUT_DIFFICULTY, @@ -68,40 +68,6 @@ function requestRouteCourse( return request; } -function matchingRoutes( - routes: BikeGpxRouteSummary[], - query: string, - country: string, - difficulty: WorkoutDifficulty | undefined, - minimumDistance: string, - maximumDistance: string, - speedUnit: SpeedUnit, - analyses: Record -): BikeGpxRouteSummary[] { - const minimum = optionalDistance(minimumDistance); - const maximum = optionalDistance(maximumDistance); - return routes.filter((route) => { - const displayedDistance = convertDistance(route.distanceKm, speedUnit); - const analysis = analyses[route.id]; - return ( - (!country || route.country === country) && - (!(difficulty && analysis) || analysis.difficulty === difficulty) && - (minimum === undefined || displayedDistance >= minimum) && - (maximum === undefined || displayedDistance <= maximum) && - bikeGpxRouteMatchesQuery(route, query, analysis) - ); - }); -} - -function optionalDistance(value: string): number | undefined { - const normalized = value.trim(); - if (!normalized) { - return; - } - const distance = Number(normalized); - return Number.isFinite(distance) && distance >= 0 ? distance : undefined; -} - function RouteListItem({ analysis, onSelect, @@ -606,12 +572,8 @@ export function BikeGpxBrowserDialog({ }) { useCloseOnEscape(true, onClose); const closeButtonRef = useDialogInitialFocus(); - const reportedRouteId = useRef(undefined); - const [search, setSearchState] = useState(() => - requestedRouteId - ? bikeGpxBrowserSearchForRoute(requestedRouteId) - : loadBikeGpxBrowserSearch() - ); + const reportedRouteId = useRef(undefined); + const [search, setSearchState] = useState(() => initialBikeGpxBrowserSearch(requestedRouteId)); const setSearch = useCallback((update: (current: typeof search) => typeof search) => { setSearchState((current) => { const next = update(current); @@ -621,7 +583,6 @@ export function BikeGpxBrowserDialog({ }, []); const { country, difficulty, maximumDistance, minimumDistance, query, selectedRouteId } = search; - const deferredQuery = useDeferredValue(query); const routes = catalog ? catalog.routes : []; const analyses = catalog ? catalog.analyses : EMPTY_ROUTE_ANALYSES; const countries = useMemo( @@ -630,55 +591,44 @@ export function BikeGpxBrowserDialog({ ); const filteredRoutes = useMemo( () => - matchingRoutes( + matchingBikeGpxRoutes( routes, - deferredQuery, - country, - difficulty, - minimumDistance, - maximumDistance, + { + country, + difficulty, + maximumDistance, + minimumDistance, + query, + }, speedUnit, analyses ), - [ - analyses, - country, - deferredQuery, - difficulty, - maximumDistance, - minimumDistance, - routes, - speedUnit, - ] + [analyses, country, difficulty, maximumDistance, minimumDistance, query, routes, speedUnit] ); const selectedRoute = bikeGpxPreviewRoute(filteredRoutes, selectedRouteId); useEffect(() => { - if (requestedRouteId === selectedRouteId) { - if (reportedRouteId.current === requestedRouteId) { - reportedRouteId.current = undefined; - } - return; - } - if (!(requestedRouteId && requestedRouteId !== selectedRouteId)) { + const reconciliation = reconcileBikeGpxBrowserRoute( + search, + requestedRouteId, + reportedRouteId.current + ); + reportedRouteId.current = reconciliation.reportedRouteId; + if (reconciliation.search === search) { return; } - const next = - reportedRouteId.current === requestedRouteId - ? bikeGpxBrowserSearchWithSelectedRoute(search, requestedRouteId) - : bikeGpxBrowserSearchForRoute(requestedRouteId); - reportedRouteId.current = undefined; - setSearchState(next); - persistBikeGpxBrowserSearch(next); - }, [requestedRouteId, search, selectedRouteId]); + setSearchState(reconciliation.search); + persistBikeGpxBrowserSearch(reconciliation.search); + }, [requestedRouteId, search]); const reportSelectedRoute = useCallback( (routeId: string | undefined) => { - reportedRouteId.current = routeId; + reportedRouteId.current = routeId ?? null; onSelectRouteId?.(routeId); }, [onSelectRouteId] ); useEffect(() => { if ( + reportedRouteId.current === undefined && !(requestedRouteId && requestedRouteId !== selectedRouteId) && selectedRoute && selectedRoute.id !== requestedRouteId diff --git a/src/components/dashboard-tools.tsx b/src/components/dashboard-tools.tsx index 74244eb..b0dd8d9 100644 --- a/src/components/dashboard-tools.tsx +++ b/src/components/dashboard-tools.tsx @@ -1,5 +1,3 @@ -import { SPEED_UNIT_OPTIONS } from '../lib/units'; -import type { SpeedUnit } from '../types'; import { DevicePairingButton } from './device-pairing'; export function DashboardTools({ @@ -7,22 +5,20 @@ export function DashboardTools({ devicesConnecting, onOpenDevices, onOpenHistory, + onOpenProfile, onOpenShortcuts, - onSelectSpeedUnit, pairedDeviceCount, - speedUnit, }: { connectedDeviceCount: number; devicesConnecting: boolean; onOpenDevices: () => void; onOpenHistory: () => void; + onOpenProfile: () => void; onOpenShortcuts: () => void; - onSelectSpeedUnit: (unit: SpeedUnit) => void; pairedDeviceCount: number; - speedUnit: SpeedUnit; }) { return ( -
+
-
- {SPEED_UNIT_OPTIONS.map((option) => ( - - ))} -
+ -
-
-
- {imageUrl ? ( - {name.trim() - ) : ( - - )} -
-
- - { - const [file] = Array.from(event.target.files ?? []); - if (file) { - if ( - PROFILE_IMAGE_TYPES.some((type) => type === file.type) - ) { - setImage(file); - setError(''); - } else { - setError('Choose a JPEG, PNG, or WebP profile image.'); - } - } - event.target.value = ''; - }} - type="file" - /> - {image ? ( - - ) : null} -

- JPEG, PNG, or WebP. Stored only in this browser. -

-
-
+ { + event.preventDefault(); + event.stopPropagation(); + form.handleSubmit(); + }} + > + + {(field) => ( +
+
+ {imageUrl ? ( + { + ) : ( + + )} +
+
+ + { + const [file] = Array.from(event.target.files ?? []); + if (file) { + selectProfileImage(file, (image) => + field.handleChange(image) + ); + } + event.target.value = ''; + }} + type="file" + /> + {field.state.value ? ( + + ) : null} +

+ JPEG, PNG, or WebP. Resized and compressed in this browser + before storage. +

+ {imageError ? ( +

+ {imageError} +

+ ) : null} + +
+
+ )} +
- -
+ {physicsSettingsLocked ? ( +

+ Weight and drivetrain settings are locked after a ride starts so its + recorded profile remains accurate. End the session to edit them for your + next ride. +

+ ) : null}

Rider and bike weight adjust terrain load. Chainring and cassette sizes define the virtual gear ratios. Your profile stays in IndexedDB on this device.

- {error || storageError ? ( + {saveError || storageError ? (

- {error || storageError} + {saveError || storageError}

) : null}
diff --git a/src/components/rename-workout-dialog.tsx b/src/components/rename-workout-dialog.tsx index 6ac7057..0a4ef88 100644 --- a/src/components/rename-workout-dialog.tsx +++ b/src/components/rename-workout-dialog.tsx @@ -1,8 +1,11 @@ -import { type FormEvent, useState } from 'react'; +import { useForm, useSelector } from '@tanstack/react-form'; +import { useEffect, useState } from 'react'; import { useCloseOnEscape, useDialogInitialFocus } from '../hooks/use-dialog-behavior'; import { errorMessage } from '../lib/errors'; +import { renameWorkoutFormSchema } from '../lib/rename-workout-form'; import { MAX_WORKOUT_NAME_LENGTH } from '../lib/workout-file'; import type { WorkoutCourse } from '../types'; +import { FormFieldError } from './form-field-error'; export function RenameWorkoutDialog({ course, @@ -13,21 +16,33 @@ export function RenameWorkoutDialog({ onClose: () => void; onRename: (courseId: string, name: string) => void; }) { - const [name, setName] = useState(course.name); const [renameError, setRenameError] = useState(''); const nameInputRef = useDialogInitialFocus(); useCloseOnEscape(true, onClose); + const form = useForm({ + defaultValues: { name: course.name }, + onSubmit: ({ value }) => { + setRenameError(''); + try { + const validated = renameWorkoutFormSchema.parse(value); + onRename(course.id, validated.name); + onClose(); + } catch (error) { + setRenameError(errorMessage(error)); + } + }, + validators: { + onChange: renameWorkoutFormSchema, + onSubmit: renameWorkoutFormSchema, + }, + }); + const canSubmit = useSelector(form.store, (state) => state.canSubmit); + const isSubmitting = useSelector(form.store, (state) => state.isSubmitting); - const submitRename = (event: FormEvent) => { - event.preventDefault(); + useEffect(() => { + form.reset({ name: course.name }); setRenameError(''); - try { - onRename(course.id, name); - onClose(); - } catch (error) { - setRenameError(errorMessage(error)); - } - }; + }, [course.name, form]); return (
@@ -50,19 +65,32 @@ export function RenameWorkoutDialog({ ×
-
- - setName(event.target.value)} - placeholder="Name this workout" - ref={nameInputRef} - value={name} - /> + { + event.preventDefault(); + event.stopPropagation(); + form.handleSubmit(); + }} + > + + {(field) => ( + + )} + {renameError ? (

{renameError} @@ -78,7 +106,7 @@ export function RenameWorkoutDialog({ +

+ ); +} + +function SessionHistoryRowContent({ + highlightedIds, + index, + onSelect, + row, + selectedId, + speedUnit, +}: { + highlightedIds: Set; + index: number; + onSelect: (id: string) => void; + row: SessionHistoryRow; + selectedId?: string; + speedUnit: SpeedUnit; +}) { + if (row.kind === SESSION_HISTORY_ROW_KIND.DATE) { + return ( +

0 ? 'pt-4' : ''}`} + > + {row.date.toUpperCase()} +

+ ); + } + return ( + onSelect(row.session.id)} + selected={selectedId === row.session.id} + session={row.session} + speedUnit={speedUnit} + /> + ); +} + export function SessionHistoryList({ error, highlightedSessionIds, @@ -33,20 +141,73 @@ export function SessionHistoryList({ summaries: SavedSessionSummary[]; total: number; }) { - const groups = useMemo(() => groupSessionsByDate(summaries), [summaries]); + const rows = useMemo( + () => + groupSessionsByDate(summaries).flatMap((group) => [ + { + date: group.date, + key: `date:${group.key}`, + kind: SESSION_HISTORY_ROW_KIND.DATE, + }, + ...group.sessions.map((session) => ({ + key: `session:${session.id}`, + kind: SESSION_HISTORY_ROW_KIND.SESSION, + session, + })), + ]), + [summaries] + ); const highlightedIds = useMemo(() => new Set(highlightedSessionIds), [highlightedSessionIds]); + const sessionListRef = useRef(null); const sessionListScroll = usePersistentScrollPosition( SESSION_HISTORY_SCROLL_POSITION_STORAGE_KEY, open, summaries.length ); + const setSessionListRef = useCallback( + (element: HTMLElement | null) => { + sessionListRef.current = element; + sessionListScroll.ref(element); + }, + [sessionListScroll.ref] + ); + const rowKey = useCallback((index: number) => rows[index]?.key ?? index, [rows]); + const estimateRowSize = useCallback( + (index: number) => + rows[index]?.kind === SESSION_HISTORY_ROW_KIND.DATE + ? ESTIMATED_DATE_ROW_HEIGHT + : ESTIMATED_SESSION_ROW_HEIGHT, + [rows] + ); + const rowVirtualizer = useVirtualizer({ + count: rows.length, + estimateSize: estimateRowSize, + getItemKey: rowKey, + getScrollElement: () => sessionListRef.current, + initialRect: SESSION_HISTORY_INITIAL_RECT, + overscan: SESSION_HISTORY_OVERSCAN, + useFlushSync: false, + }); + const selectedRowIndex = rows.findIndex( + (row) => row.kind === SESSION_HISTORY_ROW_KIND.SESSION && row.session.id === selectedId + ); + const previousSelectedId = useRef(selectedId); + + useEffect(() => { + const selectionChanged = previousSelectedId.current !== selectedId; + const hadPreviousSelection = previousSelectedId.current !== undefined; + previousSelectedId.current = selectedId; + if (selectionChanged && hadPreviousSelection && selectedRowIndex >= 0) { + rowVirtualizer.scrollToIndex(selectedRowIndex, { align: 'auto' }); + } + }, [rowVirtualizer, selectedId, selectedRowIndex]); return (
) : null} - {groups.map((group) => ( -
-

- {group.date.toUpperCase()} -

-
- {group.sessions.map((session) => { - const highlighted = highlightedIds.has(session.id); - const imported = isImportedSession(session); - return ( - - ); - })} -
+ {rows.length > 0 ? ( +
+ {rowVirtualizer.getVirtualItems().map((virtualRow) => { + const row = rows[virtualRow.index]; + if (!row) { + return null; + } + return ( +
+ +
+ ); + })}
- ))} + ) : null} {summaries.length < total ? ( - ))} -
- + + {(field) => ( +
+ How did it feel? +
+ {SESSION_FEELING_OPTIONS.map((option) => ( + + ))} +
+ +
+ )} +
- -