Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
feat(export): a finished workout as a Garmin .fit activity (#447), hand-written FIT encoder with strength sets, rests and categories
Duarte Santose005785c2696
diff --git a/frontend/src/lib/fit-export.js b/frontend/src/lib/fit-export.jsnew file mode 100644index 000000000..39344512b--- /dev/null+++ b/frontend/src/lib/fit-export.js@@ -0,0 +1,405 @@+// A finished workout as a Garmin .fit activity (#447), for Garmin Connect's "Import Data".+//+// FIT is a small binary container: a 14-byte header, then records, then a CRC. Each record is+// either a definition (which fields a local message type carries, in which base types) or a data+// message laid out the way its definition said. Everything is little-endian, timestamps count+// seconds from the FIT epoch, 1989-12-31T00:00:00Z. A writer for the handful of messages an+// activity needs is a page of code, so this is hand-written rather than a dependency.+//+// What goes in: file_id, file_creator, device_info, a timer start and stop, the session's sets+// (FIT "set" messages: active sets with reps, weight and an exercise category, and the rests+// between them), one lap, the session and the activity. A workout of nothing but cardio becomes+// a run, a ride, a row and so on, with a lap per cardio set instead of strength sets.+//+// openGym keeps a tick time per set (`at`, since v1.3.x), not a start and an end, so when a set+// started is estimated from how long it lasts: its minutes or seconds when it has them, a few+// seconds a rep when it does not. Workouts from before the tick was kept spread their sets over+// the session. No heart rate, no calories: openGym never had them.+import { exOr } from './exercises.js'+import { modeOf, workoutAt } from './history.js'+import { isSideSet, dropsOf } from './workout-model.js'++/* ------------------------------------------------------------- the container -- */++// Seconds between the Unix epoch and the FIT epoch.+export const FIT_EPOCH_OFFSET = 631065600+/** A JavaScript time (ms since 1970) as a FIT date_time (s since 1989-12-31). */+export const fitTime = ms => Math.max(0, Math.round(ms / 1000) - FIT_EPOCH_OFFSET)++// The FIT CRC-16 (CRC-16/ARC: polynomial 0x8005 reflected, start 0), a nibble at a time, the+// way the FIT SDK computes it.+const CRC_TABLE = [0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,+ 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400]+export function fitCrc(bytes, crc = 0) {+ for (let i = 0; i < bytes.length; i++) {+ const b = bytes[i]+ let tmp = CRC_TABLE[crc & 0xF]+ crc = (crc >> 4) & 0x0FFF+ crc = crc ^ tmp ^ CRC_TABLE[b & 0xF]+ tmp = CRC_TABLE[crc & 0xF]+ crc = (crc >> 4) & 0x0FFF+ crc = crc ^ tmp ^ CRC_TABLE[(b >> 4) & 0xF]+ }+ return crc+}++// The base types used here: [base type byte, size, invalid value]. A field left undefined is+// written as its type's invalid value, which is how FIT says "not recorded".+export const BASE = {+ enum: [0x00, 1, 0xFF],+ uint8: [0x02, 1, 0xFF],+ uint16: [0x84, 2, 0xFFFF],+ uint32: [0x86, 4, 0xFFFFFFFF],+ uint32z: [0x8C, 4, 0],+ string: [0x07, 0, 0],+}++const PROTOCOL_VERSION = 0x10 // 1.0: no developer fields, nothing a 1.0 reader cannot read+const PROFILE_VERSION = 2132 // 21.32++/**+ * Encode `messages` into a complete .fit file. A message is `{ global, fields }`, each field+ * `[number, type, value, size?]` (size only for a string). A local message type is defined the+ * first time a layout is used, and defined again only when the slot is reused for another.+ */+export function encodeFit(messages) {+ const out = []+ const u8 = v => out.push(v & 0xFF)+ const u16 = v => { u8(v); u8(v >>> 8) }+ const u32 = v => { u16(v & 0xFFFF); u16(v >>> 16) }+ const enc = typeof TextEncoder === 'function' ? new TextEncoder() : null+ const slots = new Map() // layout signature -> local message type+ const owner = [] // local message type -> the signature it holds now+ let next = 0+ for (const m of messages) {+ const fields = m.fields.filter(Boolean).map(([num, type, value, size]) => {+ const [base, width, invalid] = BASE[type]+ return { num, type, value, base, invalid, size: type === 'string' ? Math.max(1, size || 1) : width }+ })+ const sig = m.global + ':' + fields.map(f => `${f.num}/${f.base}/${f.size}`).join(',')+ let local = slots.get(sig)+ if (local == null || owner[local] !== sig) {+ local = next+ next = (next + 1) % 16+ if (owner[local]) slots.delete(owner[local])+ owner[local] = sig+ slots.set(sig, local)+ // Definition record: header (bit 6 set), reserved, architecture 0 (little-endian), the+ // global message number, the field count, then number/size/base type per field.+ u8(0x40 | local); u8(0); u8(0); u16(m.global); u8(fields.length)+ for (const f of fields) { u8(f.num); u8(f.size); u8(f.base) }+ }+ u8(local)+ for (const f of fields) {+ const v = f.value == null || !Number.isFinite(Number(f.value)) && f.type !== 'string' ? null : f.value+ if (f.type === 'string') {+ // Null-terminated and padded to the defined size; cut on a whole character.+ let bytes = enc ? Array.from(enc.encode(String(v ?? ''))) : Array.from(String(v ?? ''), c => c.charCodeAt(0) & 0x7F)+ while (bytes.length > f.size - 1) {+ bytes = bytes.slice(0, f.size - 1)+ while (bytes.length && (bytes[bytes.length - 1] & 0xC0) === 0x80) bytes.pop()+ if (bytes.length && bytes[bytes.length - 1] >= 0xC0) bytes.pop()+ }+ for (let i = 0; i < f.size; i++) u8(bytes[i] ?? 0)+ } else {+ // A number that does not fit its type is not recorded rather than wrapped round.+ const n = v == null ? f.invalid : Math.round(Number(v))+ const max = f.size === 1 ? 0xFF : f.size === 2 ? 0xFFFF : 0xFFFFFFFF+ const val = n < 0 || n > max ? f.invalid : n+ if (f.size === 1) u8(val); else if (f.size === 2) u16(val); else u32(val)+ }+ }+ }+ const data = Uint8Array.from(out)+ const header = new Uint8Array(14)+ const hv = new DataView(header.buffer)+ header[0] = 14+ header[1] = PROTOCOL_VERSION+ hv.setUint16(2, PROFILE_VERSION, true)+ hv.setUint32(4, data.length, true)+ header.set([0x2E, 0x46, 0x49, 0x54], 8) // ".FIT"+ hv.setUint16(12, fitCrc(header.subarray(0, 12)), true)+ const file = new Uint8Array(14 + data.length + 2)+ file.set(header, 0)+ file.set(data, 14)+ const crc = fitCrc(file.subarray(0, 14 + data.length))+ file[file.length - 2] = crc & 0xFF+ file[file.length - 1] = crc >> 8+ return file+}++/* ------------------------------------------------------- the FIT profile bits -- */++export const MSG = { fileId: 0, session: 18, lap: 19, event: 21, deviceInfo: 23, activity: 34, fileCreator: 49, set: 225 }+export const SPORT = { generic: 0, running: 1, cycling: 2, fitnessEquipment: 4, training: 10, walking: 11, rowing: 15 }+export const SUB_SPORT = { generic: 0, treadmill: 1, indoorCycling: 6, indoorRowing: 14, elliptical: 15, stairClimbing: 16, strengthTraining: 20, cardioTraining: 26 }+const MANUFACTURER_DEVELOPMENT = 255+const UNKNOWN_CATEGORY = 65534++// FIT's exercise_category, by the exercise's name first: the catalogue names are English and say+// what the movement is ("barbell bench press", "lying leg curl"). Specific words come before+// general ones, so a leg curl is not a biceps curl and a split squat is a lunge.+export const CATEGORY = {+ benchPress: 0, calfRaise: 1, cardio: 2, carry: 3, chop: 4, core: 5, crunch: 6, curl: 7, deadlift: 8,+ flye: 9, hipRaise: 10, hipStability: 11, hipSwing: 12, hyperextension: 13, lateralRaise: 14,+ legCurl: 15, legRaise: 16, lunge: 17, olympicLift: 18, plank: 19, plyo: 20, pullUp: 21, pushUp: 22,+ row: 23, shoulderPress: 24, shoulderStability: 25, shrug: 26, sitUp: 27, squat: 28, totalBody: 29,+ tricepsExtension: 30, warmUp: 31, run: 32,+}+const C = CATEGORY+const BY_NAME = [+ [/leg curl|hamstring curl|nordic/, C.legCurl],+ [/leg raise|knee raise|toes to bar|knees to elbow/, C.legRaise],+ [/calf|heel raise/, C.calfRaise],+ [/bench press|chest press|floor press/, C.benchPress],+ [/deadlift|rack pull|good morning/, C.deadlift],+ [/hip thrust|glute bridge|hip raise|bridge/, C.hipRaise],+ [/hyperextension|back extension|superman/, C.hyperextension],+ [/lateral raise|side raise|front raise|rear delt|reverse fly/, C.lateralRaise],+ [/\bfly|flye|crossover|pec deck/, C.flye],+ [/curl/, C.curl],+ [/lunge|split squat|step ?up/, C.lunge],+ [/clean|snatch|jerk/, C.olympicLift],+ [/plank/, C.plank],+ [/burpee|thruster|turkish get/, C.totalBody],+ [/jump|plyo|bound/, C.plyo],+ [/pull ?up|chin ?up|pull ?down/, C.pullUp],+ [/push ?up/, C.pushUp],+ [/\brow\b|rows\b/, C.row],+ [/shoulder press|overhead press|military press|arnold press|push press/, C.shoulderPress],+ [/shrug/, C.shrug],+ [/sit ?up/, C.sitUp],+ [/crunch/, C.crunch],+ [/squat|leg press|hack/, C.squat],+ [/tricep|push ?down|skull|\bdips?\b|kickback/, C.tricepsExtension],+ [/swing/, C.hipSwing],+ [/carry|farmer/, C.carry],+ [/chop/, C.chop],+]+// Then by the muscle it trains, which also covers your own exercises named in any language.+const BY_TARGET = {+ biceps: C.curl, forearms: C.curl, triceps: C.tricepsExtension, pectorals: C.benchPress, delts: C.shoulderPress,+ lats: C.pullUp, 'upper back': C.row, traps: C.shrug, abs: C.crunch, quads: C.squat, glutes: C.hipRaise,+ hamstrings: C.legCurl, calves: C.calfRaise, spine: C.hyperextension, adductors: C.hipStability, abductors: C.hipStability,+}++const RUNNING = /treadmill|\brun|jog|sprint/++/** The FIT exercise_category of an exercise ({ n, tg, bp }), or 65534 (unknown). */+export function fitCategory(ex, mode) {+ const name = String(ex?.n || '').toLowerCase()+ if (mode === 'cardio' || ex?.bp === 'cardio') return RUNNING.test(name) && !/bike|bicycl|cycl|rowing/.test(name) ? C.run : C.cardio+ for (const [re, cat] of BY_NAME) if (re.test(name)) return cat+ return BY_TARGET[ex?.tg] ?? UNKNOWN_CATEGORY+}++/** [sport, sub_sport] of one cardio exercise, read off its name and equipment. */+export function cardioSport(ex) {+ const name = String(ex?.n || '').toLowerCase()+ const eq = String(ex?.eq || '').toLowerCase()+ if (/bike|bicycl|cycl|spin/.test(name)) return [SPORT.cycling, eq === 'stationary bike' || /stationary|indoor|spin|assault/.test(name) ? SUB_SPORT.indoorCycling : SUB_SPORT.generic]+ if (/rowing|rower|\brow\b/.test(name)) return [SPORT.rowing, SUB_SPORT.indoorRowing]+ if (/elliptical|cross trainer/.test(name) || eq === 'elliptical machine') return [SPORT.fitnessEquipment, SUB_SPORT.elliptical]+ if (/stair|stepmill|stepper/.test(name) || eq === 'stepmill machine') return [SPORT.fitnessEquipment, SUB_SPORT.stairClimbing]+ if (/treadmill/.test(name)) return [/walk/.test(name) ? SPORT.walking : SPORT.running, SUB_SPORT.treadmill]+ if (/walk|hik(e|ing)|march/.test(name)) return [SPORT.walking, SUB_SPORT.generic]+ if (RUNNING.test(name)) return [SPORT.running, SUB_SPORT.generic]+ return [SPORT.training, SUB_SPORT.cardioTraining]+}++/* ----------------------------------------------------------- the workout -- */++const LB_TO_KG = 0.45359237+// How long one rep takes, for a rep set that has no clock of its own, and the bounds of a set.+const REP_MS = 3000+const SET_MIN_MS = 15000+const SET_MAX_MS = 120000++// One FIT "set" per thing that was done: a straight set, each side of a per-side set, and each+// drop of a drop set (right after its set, with no rest in between).+function itemsOf(w, exOf) {+ const items = []+ ;(w?.entries || []).forEach(entry => {+ if (!entry?.id) return+ const ex = exOf(entry.id)+ const mode = modeOf({ ...(entry.target || {}), id: entry.id })+ const category = fitCategory(ex, mode)+ const push = (row, at, chained) => {+ const reps = Math.round(Number(row.r) || 0)+ const sec = Number(row.sec) || 0+ const min = Number(row.min) || 0+ const len = mode === 'cardio' ? min * 60000+ : mode === 'time' ? sec * 1000+ : Math.min(SET_MAX_MS, Math.max(SET_MIN_MS, reps * REP_MS))+ if (!(len > 0)) return+ items.push({+ ex, mode, category, len, chained, at: Number.isFinite(at) ? at : null,+ reps: mode === 'reps' && reps > 0 ? reps : null,+ w: mode === 'cardio' ? null : Number(row.w) || 0,+ km: mode === 'cardio' ? (Number(row.speed) || 0) * min / 60 : 0,+ })+ }+ for (const s of entry.sets || []) {+ if (!s) continue+ const rows = isSideSet(s) ? [s.sides.L, s.sides.R].filter(x => x?.done === true) : s.done === true ? [s] : []+ for (const row of rows) {+ push(row, Number.isFinite(row.at) ? row.at : s.at, false)+ for (const d of dropsOf(row)) if (Number(d?.r) > 0) push({ ...d, w: Number(d.w) || 0 }, null, true)+ }+ }+ })+ return items+}++// Each item's start and end (ms). With every set ticked (`at`), a set ends at its tick and+// starts its length earlier, but not before the one ahead of it ended: the gaps are the rests.+// Ticks that do not leave the sets room (a log caught up after the session, all in one go) say+// nothing about when they happened, and those sets are spread like the ones below. Without ticks+// the sets share the session evenly: back to back when their lengths fill it, otherwise with the+// same rest after each one (a drop follows its set at once).+function placeItems(items, start, end) {+ if (!items.length) return []+ if (items.every(x => x.at != null || x.chained)) {+ let cursor = start+ const placed = items.map(x => {+ const tick = x.chained ? cursor + x.len : Math.max(x.at, cursor)+ const s = x.chained ? cursor : Math.max(cursor, tick - x.len)+ const e = Math.max(tick, s + x.len)+ cursor = e+ return { ...x, start: s, end: e }+ })+ if (cursor <= end + 1000) return placed+ }+ const total = Math.max(0, end - start)+ const active = items.reduce((n, x) => n + x.len, 0)+ const rests = items.slice(1).filter(x => !x.chained).length+ const scale = active > total && active > 0 ? total / active : 1+ const rest = rests && active < total ? (total - active) / rests : 0+ let cursor = start+ return items.map((x, i) => {+ if (i > 0 && !x.chained) cursor += rest+ const s = cursor+ const e = s + Math.max(1000, x.len * scale)+ cursor = e+ return { ...x, start: s, end: e }+ })+}++// A small stable number for the file's serial: the same workout exported twice is the same+// device and file to Garmin Connect, which then recognises it as already imported.+function serialOf(w) {+ const s = String(w?.id ?? workoutAt(w))+ let h = 2166136261+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619) >>> 0+ return h || 1+}++/**+ * The FIT messages for a finished workout `w`. `unit` is the profile's weight unit (weights are+ * stored in it, FIT wants kilograms), `version` the app's ("1.4.0"), `exOf(id)` the exercise.+ */+export function workoutFitMessages(w, { unit = 'kg', version = '', exOf = exOr } = {}) {+ const startMs = workoutAt(w)+ if (!Number.isFinite(startMs)) throw new Error('This workout has no date')+ let endMs = Number.isFinite(w?.end) && w.end > startMs ? w.end : startMs+ const items = itemsOf(w, exOf)+ const cardioOnly = items.length > 0 && items.every(x => x.mode === 'cardio')+ // A workout with no end of its own lasts as long as its sets do.+ if (endMs <= startMs) endMs = startMs + items.reduce((n, x) => n + x.len, 0) + Math.max(0, items.length - 1) * 60000+ const placed = placeItems(items, startMs, endMs)+ endMs = Math.max(endMs, ...placed.map(x => x.end))+ const T0 = fitTime(startMs), T1 = fitTime(endMs)+ const elapsedMs = Math.max(0, endMs - startMs)+ const kg = v => (unit === 'lb' ? v * LB_TO_KG : v)+ // software_version has two decimals: v1.4.x (a build suffix and all) reads 1.04.+ const ver = /^(\d+)\.(\d+)/.exec(String(version))+ const swVersion = ver ? Number(ver[1]) * 100 + Number(ver[2]) : undefined+ const serial = serialOf(w)++ let sport = [SPORT.training, SUB_SPORT.strengthTraining]+ if (cardioOnly) {+ const kinds = [...new Set(items.map(x => cardioSport(x.ex).join('/')))]+ sport = kinds.length === 1 ? kinds[0].split('/').map(Number) : [SPORT.training, SUB_SPORT.cardioTraining]+ }+ const km = items.reduce((n, x) => n + x.km, 0)+ const meters = km > 0 ? km * 1000 : undefined++ const msgs = []+ msgs.push({ global: MSG.fileId, fields: [+ [0, 'enum', 4], // type: activity+ [1, 'uint16', MANUFACTURER_DEVELOPMENT],+ [2, 'uint16', 0], // product+ [3, 'uint32z', serial],+ [4, 'uint32', T0], // time_created+ ] })+ msgs.push({ global: MSG.fileCreator, fields: [[0, 'uint16', swVersion]] })+ msgs.push({ global: MSG.event, fields: [[253, 'uint32', T0], [0, 'enum', 0], [1, 'enum', 0]] }) // timer start+ msgs.push({ global: MSG.deviceInfo, fields: [+ [253, 'uint32', T0], [0, 'uint8', 0], [2, 'uint16', MANUFACTURER_DEVELOPMENT], [3, 'uint32z', serial],+ [4, 'uint16', 0], [5, 'uint16', swVersion], [27, 'string', 'openGym', 16],+ ] })++ const laps = []+ if (cardioOnly) {+ // A lap per cardio set: its time, its distance and its speed, the way a watch splits a run.+ placed.forEach(x => {+ const ms = x.end - x.start+ laps.push({ start: x.start, end: x.end, ms, meters: x.km * 1000, speed: ms > 0 ? x.km * 1000 / (ms / 1000) : 0 })+ })+ } else {+ let index = 0+ const setMsg = (s, e, type, x) => msgs.push({ global: MSG.set, fields: [+ [254, 'uint32', fitTime(e)], // timestamp: when the set ended+ [0, 'uint32', e - s], // duration, ms (scale 1000)+ [3, 'uint16', x?.reps ?? undefined], // repetitions+ [4, 'uint16', x && x.w != null && x.mode !== 'cardio' ? kg(x.w) * 16 : undefined], // weight, kg (scale 16)+ [5, 'uint8', type], // set_type: 0 rest, 1 active+ [6, 'uint32', fitTime(s)], // start_time+ [7, 'uint16', x ? x.category : undefined],+ [9, 'uint16', x && x.w != null ? (unit === 'lb' ? 2 : 1) : undefined], // weight_display_unit+ [10, 'uint16', index++], // message_index+ ] })+ let prevEnd = null+ for (const x of placed) {+ if (prevEnd != null && x.start - prevEnd >= 1000) setMsg(prevEnd, x.start, 0, null)+ setMsg(x.start, x.end, 1, x)+ prevEnd = x.end+ }+ laps.push({ start: startMs, end: endMs, ms: elapsedMs, meters, speed: undefined })+ }++ msgs.push({ global: MSG.event, fields: [[253, 'uint32', T1], [0, 'enum', 0], [1, 'enum', 4]] }) // timer stop_all+ laps.forEach((l, i) => msgs.push({ global: MSG.lap, fields: [+ [254, 'uint16', i], [253, 'uint32', fitTime(l.end)], [0, 'enum', 9], [1, 'enum', 1], // event lap, stop+ [2, 'uint32', fitTime(l.start)], [7, 'uint32', l.ms], [8, 'uint32', l.ms],+ [9, 'uint32', l.meters != null && l.meters > 0 ? l.meters * 100 : undefined], // total_distance, cm+ [13, 'uint16', l.speed > 0 ? l.speed * 1000 : undefined], // avg_speed, mm/s+ [25, 'enum', sport[0]], [39, 'enum', sport[1]],+ ] }))+ msgs.push({ global: MSG.session, fields: [+ [254, 'uint16', 0], [253, 'uint32', T1], [0, 'enum', 8], [1, 'enum', 1], // event session, stop+ [2, 'uint32', T0], [5, 'enum', sport[0]], [6, 'enum', sport[1]],+ [7, 'uint32', elapsedMs], [8, 'uint32', elapsedMs],+ [9, 'uint32', meters != null ? meters * 100 : undefined],+ [14, 'uint16', cardioOnly && meters && elapsedMs > 0 ? meters / (elapsedMs / 1000) * 1000 : undefined],+ [25, 'uint16', 0], [26, 'uint16', laps.length],+ ] })+ // local_timestamp: the same moment on the wall clock where the workout happened.+ const offset = -new Date(endMs).getTimezoneOffset() * 60+ msgs.push({ global: MSG.activity, fields: [+ [253, 'uint32', T1], [0, 'uint32', elapsedMs], [1, 'uint16', 1], [2, 'enum', 0], // type manual+ [3, 'enum', 26], [4, 'enum', 1], [5, 'uint32', T1 + offset], // event activity, stop+ ] })+ return msgs+}++/** The finished workout `w` as the bytes of a .fit file. Options as workoutFitMessages. */+export const workoutFit = (w, options) => encodeFit(workoutFitMessages(w, options))++/** "opengym-2026-10-09-1830.fit": the day and the start time, so two sessions a day stay apart. */+export function fitFileName(w) {+ const d = new Date(workoutAt(w))+ if (!Number.isFinite(d.getTime())) return 'opengym-workout.fit'+ const p = n => String(n).padStart(2, '0')+ return `opengym-${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}.fit`+}diff --git a/frontend/src/lib/fit-export.test.js b/frontend/src/lib/fit-export.test.jsnew file mode 100644index 000000000..590c057e2--- /dev/null+++ b/frontend/src/lib/fit-export.test.js@@ -0,0 +1,351 @@+// A finished workout as a Garmin .fit file (#447). The file is read back here with a decoder+// written from the FIT protocol document, independent of the encoder: header, both CRCs, the+// definition and data records, and what the messages say about the workout.+import { describe, it, expect } from 'vitest'+import {+ fitCrc, fitTime, FIT_EPOCH_OFFSET, encodeFit, workoutFitMessages, workoutFit, fitFileName,+ fitCategory, cardioSport, CATEGORY, SPORT, SUB_SPORT, MSG,+} from './fit-export.js'+import { EXIDX } from './exercises.js'++/* ---------------------------------------------------------------- decoder -- */++const SIZE = { 0x00: 1, 0x01: 1, 0x02: 1, 0x83: 2, 0x84: 2, 0x85: 4, 0x86: 4, 0x07: 0, 0x0A: 1, 0x8B: 2, 0x8C: 4, 0x0D: 1 }+function decode(bytes) {+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)+ const header = {+ size: bytes[0], protocol: bytes[1], profile: v.getUint16(2, true), dataSize: v.getUint32(4, true),+ type: String.fromCharCode(...bytes.slice(8, 12)), crc: v.getUint16(12, true),+ }+ const defs = []+ const messages = []+ const definitions = []+ let p = header.size+ const end = header.size + header.dataSize+ while (p < end) {+ const h = bytes[p++]+ expect(h & 0x80, 'no compressed timestamp headers').toBe(0)+ const local = h & 0x0F+ if (h & 0x40) {+ expect(h & 0x20, 'no developer data').toBe(0)+ expect(bytes[p + 1], 'little-endian').toBe(0)+ const global = v.getUint16(p + 2, true)+ const n = bytes[p + 4]+ p += 5+ const fields = []+ for (let i = 0; i < n; i++, p += 3) {+ const [num, size, base] = [bytes[p], bytes[p + 1], bytes[p + 2]]+ expect(SIZE[base], `known base type ${base}`).not.toBeUndefined()+ if (SIZE[base]) expect(size % SIZE[base], 'size is a whole number of values').toBe(0)+ fields.push({ num, size, base })+ }+ defs[local] = { global, fields }+ definitions.push({ local, global })+ } else {+ const def = defs[local]+ expect(def, `local type ${local} defined before use`).toBeTruthy()+ const out = {}+ for (const f of def.fields) {+ let val+ if (f.base === 0x07) {+ const raw = bytes.slice(p, p + f.size)+ const z = raw.indexOf(0)+ val = new TextDecoder().decode(raw.slice(0, z < 0 ? raw.length : z))+ } else if (f.size === 1) val = bytes[p]+ else if (f.size === 2) val = v.getUint16(p, true)+ else val = v.getUint32(p, true)+ out[f.num] = val+ p += f.size+ }+ messages.push({ global: def.global, local, f: out })+ }+ }+ expect(p).toBe(end)+ return { header, messages, definitions, fileCrc: v.getUint16(end, true) }+}+const of = (decoded, global) => decoded.messages.filter(m => m.global === global).map(m => m.f)++/* ----------------------------------------------------------- the container -- */++describe('the FIT CRC', () => {+ it('is CRC-16/ARC, as the FIT SDK computes it', () => {+ expect(fitCrc(new TextEncoder().encode('123456789'))).toBe(0xBB3D)+ expect(fitCrc(new Uint8Array(0))).toBe(0)+ // It can be fed in pieces.+ const bytes = new TextEncoder().encode('openGym .fit')+ expect(fitCrc(bytes.subarray(5), fitCrc(bytes.subarray(0, 5)))).toBe(fitCrc(bytes))+ })+})++describe('FIT time', () => {+ it('counts seconds from 1989-12-31T00:00:00Z', () => {+ expect(FIT_EPOCH_OFFSET).toBe(Date.UTC(1989, 11, 31) / 1000)+ expect(fitTime(Date.UTC(1989, 11, 31))).toBe(0)+ expect(fitTime(Date.UTC(1989, 11, 31, 0, 1, 0))).toBe(60)+ expect(fitTime(Date.UTC(2026, 9, 9, 17))).toBe(Date.UTC(2026, 9, 9, 17) / 1000 - 631065600)+ expect(fitTime(0)).toBe(0)+ })+})++describe('encodeFit', () => {+ const file = encodeFit([+ { global: MSG.fileId, fields: [[0, 'enum', 4], [1, 'uint16', 255], [3, 'uint32z', 1234], [4, 'uint32', 1000]] },+ { global: MSG.deviceInfo, fields: [[0, 'uint8', 0], [27, 'string', 'openGym', 16]] },+ ])+ const d = decode(file)++ it('writes the 14-byte header with its CRC, and the file CRC after the records', () => {+ expect(d.header).toMatchObject({ size: 14, protocol: 0x10, type: '.FIT' })+ expect(d.header.profile).toBeGreaterThan(2000)+ expect(d.header.dataSize).toBe(file.length - 16)+ expect(d.header.crc).toBe(fitCrc(file.subarray(0, 12)))+ expect(d.fileCrc).toBe(fitCrc(file.subarray(0, file.length - 2)))+ // The check a reader does: the CRC over everything, its own two bytes included, is zero.+ expect(fitCrc(file)).toBe(0)+ })++ it('defines each message before its data, and the data decodes back', () => {+ expect(d.definitions.map(x => x.global)).toEqual([MSG.fileId, MSG.deviceInfo])+ expect(d.messages).toEqual([+ { global: MSG.fileId, local: 0, f: { 0: 4, 1: 255, 3: 1234, 4: 1000 } },+ { global: MSG.deviceInfo, local: 1, f: { 0: 0, 27: 'openGym' } },+ ])+ })++ it('writes a value it does not have, or one that does not fit, as the type\'s invalid value', () => {+ const m = decode(encodeFit([{ global: MSG.set, fields: [+ [0, 'uint32', undefined], [3, 'uint16', null], [4, 'uint16', 70000], [5, 'uint8', -1], [7, 'uint16', NaN], [9, 'uint32z', undefined], [10, 'enum', 300],+ ] }])).messages[0].f+ expect(m).toEqual({ 0: 0xFFFFFFFF, 3: 0xFFFF, 4: 0xFFFF, 5: 0xFF, 7: 0xFFFF, 9: 0, 10: 0xFF })+ })++ it('rounds numbers and cuts a long string on a whole character, null-terminated', () => {+ const m = decode(encodeFit([{ global: MSG.deviceInfo, fields: [[5, 'uint16', 104.6], [27, 'string', 'Übungsgerät', 6]] }])).messages[0].f+ expect(m[5]).toBe(105)+ expect(m[27]).toBe('Übun') // Ü is two bytes: 5 bytes fit before the terminator, "Übun" is 5+ })++ it('defines a layout once, and again only when its local slot was taken over', () => {+ const one = { global: MSG.event, fields: [[253, 'uint32', 1], [0, 'enum', 0], [1, 'enum', 0]] }+ const twice = decode(encodeFit([one, one, one]))+ expect(twice.definitions).toHaveLength(1)+ expect(twice.messages).toHaveLength(3)+ // Seventeen layouts and the first again: sixteen local types, so the first is redefined.+ const many = Array.from({ length: 17 }, (_, i) => ({ global: MSG.set, fields: [[10, 'uint16', i], ...Array.from({ length: i }, (_, k) => [20 + k, 'uint8', k])] }))+ const d2 = decode(encodeFit([...many, many[0], many[16]]))+ expect(d2.definitions).toHaveLength(18)+ expect(d2.messages.map(m => m.f[10])).toEqual([...Array.from({ length: 17 }, (_, i) => i), 0, 16])+ expect(d2.messages.at(-1).f[35]).toBe(15)+ })+})++/* ----------------------------------------------------------- the workout -- */++const BENCH = Object.values(EXIDX).find(e => e.n === 'barbell bench press').id+const CURL = Object.values(EXIDX).find(e => e.n === 'dumbbell curl' || /^dumbbell.*curl$/.test(e.n)).id+const PLANK = Object.values(EXIDX).find(e => e.n === 'front plank' || /plank$/.test(e.n)).id+const TREADMILL = '2259' // walking on treadmill+const BIKE = '2138' // stationary bike run v. 3+const T0 = Date.UTC(2026, 9, 9, 17)+const min = n => n * 60000++const strength = {+ id: 'w1', d: '2026-10-09', start: T0, end: T0 + min(50), name: 'Push', vol: 0,+ entries: [+ { id: BENCH, target: { mode: 'reps' }, sets: [+ { w: 40, r: 8, done: true, phase: 'warmup', at: T0 + min(2) },+ { w: 60, r: 8, done: true, at: T0 + min(5) },+ { w: 60, r: 6, done: true, type: 'dropset', drops: [{ w: 45, r: 6 }], at: T0 + min(8) },+ { w: 60, r: 8, done: false },+ ] },+ { id: CURL, target: { mode: 'reps' }, sets: [+ { w: 12, r: 10, done: true, sides: { L: { w: 12, r: 10, done: true, at: T0 + min(12) }, R: { w: 12, r: 9, done: true, at: T0 + min(13) } }, at: T0 + min(13) },+ ] },+ { id: PLANK, target: { mode: 'time' }, sets: [{ sec: 60, w: 0, done: true, at: T0 + min(16) }] },+ { id: TREADMILL, target: { mode: 'cardio' }, sets: [{ min: 20, speed: 6, incline: 8, done: true, at: T0 + min(45) }] },+ ],+}++describe('a strength workout as FIT', () => {+ const d = decode(workoutFit(strength, { unit: 'kg', version: '1.4.0' }))+ const sets = of(d, MSG.set)+ const active = sets.filter(s => s[5] === 1)++ it('is a valid activity file from openGym', () => {+ expect(fitCrc(workoutFit(strength))).toBe(0)+ const [id] = of(d, MSG.fileId)+ expect(id[0]).toBe(4) // activity+ expect(id[1]).toBe(255) // development+ expect(id[3]).toBeGreaterThan(0) // serial, stable per workout+ expect(id[4]).toBe(fitTime(T0))+ expect(of(d, MSG.fileCreator)[0][0]).toBe(104)+ expect(of(d, MSG.deviceInfo)[0][27]).toBe('openGym')+ expect(decode(workoutFit(strength)).messages.find(m => m.global === MSG.fileId).f[3]).toBe(id[3])+ })++ it('runs file_id, creator, timer start, device, sets, timer stop, lap, session, activity in that order', () => {+ const order = d.messages.map(m => m.global).filter((g, i, a) => g !== a[i - 1])+ expect(order).toEqual([MSG.fileId, MSG.fileCreator, MSG.event, MSG.deviceInfo, MSG.set, MSG.event, MSG.lap, MSG.session, MSG.activity])+ const [start, stop] = of(d, MSG.event)+ expect([start[0], start[1], start[253]]).toEqual([0, 0, fitTime(T0)])+ expect([stop[0], stop[1], stop[253]]).toEqual([0, 4, fitTime(T0 + min(50))])+ })++ it('has a strength-training session, lap and activity over the whole workout', () => {+ const [session] = of(d, MSG.session)+ expect([session[5], session[6]]).toEqual([SPORT.training, SUB_SPORT.strengthTraining])+ expect(session[2]).toBe(fitTime(T0))+ expect(session[253]).toBe(fitTime(T0 + min(50)))+ expect(session[7]).toBe(min(50)) // total_elapsed_time, ms+ expect(session[8]).toBe(min(50))+ expect([session[0], session[1], session[25], session[26]]).toEqual([8, 1, 0, 1])+ // The treadmill's 2 km ride along as the distance, in centimetres.+ expect(session[9]).toBe(200000)+ const [lap] = of(d, MSG.lap)+ expect([lap[0], lap[1], lap[2], lap[7], lap[25], lap[39]]).toEqual([9, 1, fitTime(T0), min(50), SPORT.training, SUB_SPORT.strengthTraining])+ const [activity] = of(d, MSG.activity)+ expect([activity[0], activity[1], activity[2], activity[3], activity[4]]).toEqual([min(50), 1, 0, 26, 1])+ expect(activity[5] - activity[253]).toBe(-new Date(T0 + min(50)).getTimezoneOffset() * 60)+ })++ it('writes every set that was done, with its reps, weight and category, and leaves the rest out', () => {+ // Warm-up, two work sets, the drop, left and right, the plank, the treadmill.+ expect(active.map(s => s[3])).toEqual([8, 8, 6, 6, 10, 9, 0xFFFF, 0xFFFF])+ expect(active.map(s => s[4] / 16)).toEqual([40, 60, 60, 45, 12, 12, 0, 0xFFFF / 16])+ expect(active.map(s => s[7])).toEqual([0, 0, 0, 0, 7, 7, CATEGORY.plank, CATEGORY.run])+ expect(active.slice(0, 7).every(s => s[9] === 1)).toBe(true) // kilograms+ expect(sets.map(s => s[10])).toEqual(sets.map((_, i) => i)) // message_index+ })++ it('ends a set at its tick, starts it its length earlier, and fills the gaps with rests', () => {+ const [warm, rest1, work1] = sets+ expect(warm[254]).toBe(fitTime(T0 + min(2)))+ expect(warm[0]).toBe(24000) // 8 reps at 3 s+ expect(warm[6]).toBe(fitTime(T0 + min(2) - 24000))+ expect(rest1[5]).toBe(0)+ expect(rest1[6]).toBe(warm[254])+ expect(rest1[254]).toBe(work1[6])+ expect(rest1[0]).toBe((work1[6] - rest1[6]) * 1000)+ // The drop follows its set with no rest between them.+ const i = sets.findIndex(s => s[4] === 45 * 16)+ expect(sets[i - 1][5]).toBe(1)+ expect(sets[i][6]).toBe(sets[i - 1][254])+ // The plank lasts its minute, the treadmill its 20 minutes.+ expect(active[6][0]).toBe(60000)+ expect(active[7][0]).toBe(min(20))+ expect(active[7][254]).toBe(fitTime(T0 + min(45)))+ // Rest and active alternate, in time order, and never overlap.+ for (let k = 1; k < sets.length; k++) {+ expect(sets[k][6]).toBeGreaterThanOrEqual(sets[k - 1][254])+ if (sets[k][5] === 0) expect(sets[k - 1][5]).toBe(1)+ }+ })++ it('converts pounds to kilograms and says the display unit is pounds', () => {+ const lb = of(decode(workoutFit(strength, { unit: 'lb' })), MSG.set).filter(s => s[5] === 1)+ expect(lb[1][4]).toBe(Math.round(60 * 0.45359237 * 16))+ expect(lb[1][9]).toBe(2)+ })++ it('spreads the sets of a workout from before the tick over the session', () => {+ const old = { id: 'old', d: '2025-01-01', start: T0, end: T0 + min(30), entries: [+ { id: BENCH, target: { mode: 'reps' }, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] },+ ] }+ const s = of(decode(workoutFit(old)), MSG.set)+ expect(s.map(x => x[5])).toEqual([1, 0, 1, 0, 1])+ expect(s[0][6]).toBe(fitTime(T0))+ expect(s.at(-1)[254]).toBe(fitTime(T0 + min(30)))+ expect(s[1][0]).toBe(s[3][0]) // the same rest after each set+ // A workout too short for its sets has them back to back, squeezed into it.+ const short = { ...old, end: T0 + 30000 }+ const s2 = of(decode(workoutFit(short)), MSG.set)+ expect(s2.map(x => x[5])).toEqual([1, 1, 1])+ expect(s2.at(-1)[254]).toBe(fitTime(T0 + 30000))+ })++ it('does not let ticks bunched after the end stretch the session', () => {+ const late = { id: 'late', d: '2026-10-09', start: T0, end: T0 + min(10), entries: [+ { id: BENCH, target: { mode: 'reps' }, sets: [5, 5, 5].map(r => ({ w: 60, r, done: true, at: T0 + min(60) })) },+ ] }+ const dd = decode(workoutFit(late))+ expect(of(dd, MSG.session)[0][7]).toBe(min(10))+ expect(of(dd, MSG.set).at(-1)[254]).toBe(fitTime(T0 + min(10)))+ })++ it('reads a workout with no end as long as its sets', () => {+ const open = { id: 'o', d: '2026-10-09', start: T0, entries: [{ id: PLANK, target: { mode: 'time' }, sets: [{ sec: 45, done: true }] }] }+ expect(of(decode(workoutFit(open)), MSG.session)[0][7]).toBe(45000)+ })++ it('refuses a workout without a date', () => {+ expect(() => workoutFitMessages({ entries: [] })).toThrow()+ })+})++describe('a cardio workout as FIT', () => {+ const walk = { id: 'w2', d: '2026-10-09', start: T0, end: T0 + min(31), entries: [+ { id: TREADMILL, target: { mode: 'cardio' }, sets: [{ min: 10, speed: 5, done: true }, { min: 20, speed: 6, done: true }, { min: 5, speed: 4, done: false }] },+ ] }+ const d = decode(workoutFit(walk))++ it('is a treadmill walk with a lap per set and no strength sets', () => {+ expect(of(d, MSG.set)).toEqual([])+ const [session] = of(d, MSG.session)+ expect([session[5], session[6]]).toEqual([SPORT.walking, SUB_SPORT.treadmill])+ expect(session[26]).toBe(2)+ const km = 5 * 10 / 60 + 6 * 20 / 60+ expect(session[9]).toBe(Math.round(km * 100000))+ expect(session[14]).toBe(Math.round(km * 1000 / (31 * 60) * 1000))+ const laps = of(d, MSG.lap)+ expect(laps.map(l => l[254])).toEqual([0, 1])+ expect(laps.map(l => l[7])).toEqual([min(10), min(20)])+ expect(laps.map(l => l[9])).toEqual([Math.round(5 / 6 * 100000), 200000])+ expect(laps.map(l => l[13])).toEqual([Math.round(5 / 3.6 * 1000), Math.round(6 / 3.6 * 1000)])+ expect(laps[1][253]).toBe(fitTime(T0 + min(31))) // the last lap ends with the workout+ })++ it('is cardio training when the machines differ', () => {+ const mixed = { ...walk, entries: [...walk.entries, { id: BIKE, target: { mode: 'cardio' }, sets: [{ min: 10, speed: 25, done: true }] }] }+ const [session] = of(decode(workoutFit(mixed)), MSG.session)+ expect([session[5], session[6]]).toEqual([SPORT.training, SUB_SPORT.cardioTraining])+ })+})++describe('categories and sports', () => {+ const ex = n => ({ n })+ it('maps exercises to FIT categories by name, then by the muscle they train', () => {+ expect(fitCategory(ex('barbell bench press'))).toBe(CATEGORY.benchPress)+ expect(fitCategory(ex('lying leg curl'))).toBe(CATEGORY.legCurl)+ expect(fitCategory(ex('dumbbell hammer curl'))).toBe(CATEGORY.curl)+ expect(fitCategory(ex('barbell full squat'))).toBe(CATEGORY.squat)+ expect(fitCategory(ex('dumbbell bulgarian split squat'))).toBe(CATEGORY.lunge)+ expect(fitCategory(ex('barbell romanian deadlift'))).toBe(CATEGORY.deadlift)+ expect(fitCategory(ex('cable seated row'))).toBe(CATEGORY.row)+ expect(fitCategory(ex('cable pulldown'))).toBe(CATEGORY.pullUp)+ expect(fitCategory(ex('push up'))).toBe(CATEGORY.pushUp)+ expect(fitCategory(ex('cable pushdown'))).toBe(CATEGORY.tricepsExtension)+ expect(fitCategory(ex('dumbbell lateral raise'))).toBe(CATEGORY.lateralRaise)+ expect(fitCategory(ex('dumbbell fly'))).toBe(CATEGORY.flye)+ expect(fitCategory(ex('barbell hip thrust'))).toBe(CATEGORY.hipRaise)+ expect(fitCategory(ex('standing calf raise'))).toBe(CATEGORY.calfRaise)+ expect(fitCategory(ex('kettlebell swing'))).toBe(CATEGORY.hipSwing)+ expect(fitCategory({ n: 'Bankdrücken eng', tg: 'triceps' })).toBe(CATEGORY.tricepsExtension)+ expect(fitCategory({ n: 'Mystery move' })).toBe(65534)+ expect(fitCategory(EXIDX[TREADMILL], 'cardio')).toBe(CATEGORY.run)+ expect(fitCategory(EXIDX[BIKE], 'cardio')).toBe(CATEGORY.cardio)+ })+ it('reads the sport of a cardio exercise off its name and equipment', () => {+ expect(cardioSport(EXIDX[TREADMILL])).toEqual([SPORT.walking, SUB_SPORT.treadmill])+ expect(cardioSport(EXIDX[BIKE])).toEqual([SPORT.cycling, SUB_SPORT.indoorCycling])+ expect(cardioSport(EXIDX['1161'])).toEqual([SPORT.rowing, SUB_SPORT.indoorRowing])+ expect(cardioSport(EXIDX['2192'])).toEqual([SPORT.fitnessEquipment, SUB_SPORT.elliptical])+ expect(cardioSport(EXIDX['2311'])).toEqual([SPORT.fitnessEquipment, SUB_SPORT.stairClimbing])+ expect(cardioSport(EXIDX['0685'])).toEqual([SPORT.running, SUB_SPORT.generic])+ expect(cardioSport(EXIDX['3094'])).toEqual([SPORT.training, SUB_SPORT.cardioTraining])+ })+ it('names the file after the day and the start time', () => {+ const local = new Date(2026, 9, 9, 18, 5).getTime()+ expect(fitFileName({ start: local })).toBe('opengym-2026-10-09-1805.fit')+ expect(fitFileName({})).toBe('opengym-workout.fit')+ })+})diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 897855a65..f773b4152 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -2216,4 +2216,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'الميل (%)','{0}% incline': 'ميل {0}%',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'تصدير كملف .fit',+ 'Could not create the file': 'تعذّر إنشاء الملف',+ 'Saved. Garmin Connect can take it from here.': 'تم الحفظ. Garmin Connect يتولى الباقي.',}diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.jsindex a39939b97..133f30a13 100644--- a/frontend/src/locales/bn.js+++ b/frontend/src/locales/bn.js@@ -2240,4 +2240,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'ঢাল (%)','{0}% incline': '{0}% ঢাল',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': '.fit ফাইল হিসেবে এক্সপোর্ট করুন',+ 'Could not create the file': 'ফাইলটি তৈরি করা যায়নি',+ 'Saved. Garmin Connect can take it from here.': 'সেভ হয়েছে। বাকিটা Garmin Connect সামলে নেবে।',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 514e64bbd..a86533a54 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -2181,4 +2181,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Steigung (%)','{0}% incline': '{0} % Steigung',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Als .fit-Datei exportieren',+ 'Could not create the file': 'Die Datei konnte nicht erstellt werden',+ 'Saved. Garmin Connect can take it from here.': 'Gespeichert. Ab hier übernimmt Garmin Connect.',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex f0455aefe..b66a4d334 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -2161,4 +2161,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Inclinación (%)','{0}% incline': '{0} % de inclinación',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Exportar como archivo .fit',+ 'Could not create the file': 'No se pudo crear el archivo',+ 'Saved. Garmin Connect can take it from here.': 'Guardado. Garmin Connect se encarga del resto.',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 8ee3987b4..c5ce3ba97 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -2161,4 +2161,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Inclinaison (%)','{0}% incline': '{0} % d’inclinaison',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Exporter en fichier .fit',+ 'Could not create the file': 'Impossible de créer le fichier',+ 'Saved. Garmin Connect can take it from here.': 'Enregistré. Garmin Connect prend le relais.',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 58f1065b7..bca2bc0fd 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -2161,4 +2161,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'ढलान (%)','{0}% incline': '{0}% ढलान',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': '.fit फ़ाइल के रूप में एक्सपोर्ट करें',+ 'Could not create the file': 'फ़ाइल नहीं बन सकी',+ 'Saved. Garmin Connect can take it from here.': 'सेव हो गया। अब आगे Garmin Connect संभाल लेगा।',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 3a565e2a2..de9736a2b 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -2164,4 +2164,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Emelkedő (%)','{0}% incline': '{0}% emelkedő',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Exportálás .fit fájlként',+ 'Could not create the file': 'Nem sikerült létrehozni a fájlt',+ 'Saved. Garmin Connect can take it from here.': 'Elmentve. Innen a Garmin Connect viszi tovább.',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 308ea5bd6..ad0757083 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -2161,4 +2161,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Pendenza (%)','{0}% incline': 'pendenza {0}%',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Esporta come file .fit',+ 'Could not create the file': 'Impossibile creare il file',+ 'Saved. Garmin Connect can take it from here.': 'Salvato. Da qui ci pensa Garmin Connect.',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 7e3478400..986d41c32 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -2161,4 +2161,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': '경사 (%)','{0}% incline': '경사 {0}%',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': '.fit 파일로 내보내기',+ 'Could not create the file': '파일을 만들 수 없어요',+ 'Saved. Garmin Connect can take it from here.': '저장했어요. 이제 Garmin Connect에 맡기세요.',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 3d4b37b51..d61d4d6c7 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -2161,4 +2161,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Nachylenie (%)','{0}% incline': 'nachylenie {0}%',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Eksportuj jako plik .fit',+ 'Could not create the file': 'Nie udało się utworzyć pliku',+ 'Saved. Garmin Connect can take it from here.': 'Zapisano. Dalej zajmie się tym Garmin Connect.',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 08dc91cf4..fe50179e1 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1334,6 +1334,10 @@ export const PT_BR_OVERRIDES = {// --- cardio: treadmill incline ---'Incline (%)': 'Inclinação (%)','{0}% incline': '{0}% de inclinação',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Exportar como arquivo .fit',+ 'Could not create the file': 'Não foi possível criar o arquivo',+ 'Saved. Garmin Connect can take it from here.': 'Salvo. Daqui em diante é com o Garmin Connect.',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 987c704f6..c30c2e3dd 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -2161,4 +2161,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Inclinação (%)','{0}% incline': '{0}% de inclinação',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Exportar como ficheiro .fit',+ 'Could not create the file': 'Não foi possível criar o ficheiro',+ 'Saved. Garmin Connect can take it from here.': 'Guardado. Daqui para a frente é com o Garmin Connect.',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 54b53bd36..226d9cb2f 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -2165,4 +2165,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Наклон (%)','{0}% incline': 'наклон {0}%',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Экспортировать как файл .fit',+ 'Could not create the file': 'Не удалось создать файл',+ 'Saved. Garmin Connect can take it from here.': 'Сохранено. Дальше дело за Garmin Connect.',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex ddbe9a01f..3e0b43127 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -2172,4 +2172,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'ความชัน (%)','{0}% incline': 'ความชัน {0}%',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'ส่งออกเป็นไฟล์ .fit',+ 'Could not create the file': 'สร้างไฟล์ไม่ได้',+ 'Saved. Garmin Connect can take it from here.': 'บันทึกแล้ว ที่เหลือให้ Garmin Connect จัดการ',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex cc6e3ec92..f22634455 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -2161,4 +2161,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Eğim (%)','{0}% incline': '%{0} eğim',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': '.fit dosyası olarak dışa aktar',+ 'Could not create the file': 'Dosya oluşturulamadı',+ 'Saved. Garmin Connect can take it from here.': 'Kaydedildi. Gerisini Garmin Connect halleder.',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 22cfc0027..018cee445 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -2158,4 +2158,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': 'Нахил (%)','{0}% incline': 'нахил {0}%',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': 'Експортувати як файл .fit',+ 'Could not create the file': 'Не вдалося створити файл',+ 'Saved. Garmin Connect can take it from here.': 'Збережено. Далі справа за Garmin Connect.',}diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex 756748092..0485894e3 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -2154,4 +2154,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': '坡度 (%)','{0}% incline': '坡度 {0}%',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': '匯出為 .fit 檔案',+ 'Could not create the file': '無法建立檔案',+ 'Saved. Garmin Connect can take it from here.': '已儲存。接下來交給 Garmin Connect 吧。',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex c01783382..a0629113d 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -2161,4 +2161,8 @@ export default {// --- cardio: treadmill incline ---'Incline (%)': '坡度 (%)','{0}% incline': '坡度 {0}%',+ // --- workout detail: Garmin .fit export ---+ 'Export as .fit file': '导出为 .fit 文件',+ 'Could not create the file': '无法创建文件',+ 'Saved. Garmin Connect can take it from here.': '已保存。接下来交给 Garmin Connect 吧。',}diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex 9c9f7e73b..ba4ffb456 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -52,6 +52,7 @@ import { useAutoMore } from './lib/use-auto-more.js'import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js'import { buildSessionEntries, buildPlannedEntry, builtOutOfProgression } from './lib/session-start.js'import { finishCompare, finishCardio } from './lib/finish-compare.js'+import { workoutFit, fitFileName } from './lib/fit-export.js'import { joinSessionNoProg } from './lib/session-noprog.js'import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js'import { workoutsOn, backfillStart, backfillEnd, completeBackfill, historyAsOf, sessionHistory } from './lib/backfill.js'@@ -2314,6 +2315,14 @@ function WorkoutDetail({ w, close }) {const rec = { ...(st.workouts.find(x => sameWorkout(x, w)) || w), note: note.trim() }toast(await copyText(workoutText(rec, { unit: st.unit, nameOf, speedUnit: speedUnitOf(st) })) ? t('Copied') : t('Could not copy'))}+ // A Garmin .fit activity (#447) of the saved record, for Garmin Connect's Import Data.+ const exportFit = () => {+ const rec = st.workouts.find(x => sameWorkout(x, w)) || w+ let bytes+ try { bytes = workoutFit(rec, { unit: st.unit, version: __APP_VERSION__ }) }+ catch (e) { toast(t('Could not create the file')); return }+ saveFitFile(new Blob([bytes], { type: 'application/vnd.ant.fit' }), fitFileName(rec))+ }const shareAsImage = () => {const rec = st.workouts.find(x => sameWorkout(x, w)) || wui().openSheet(c2 => <ShareWorkoutImage w={rec} nameOf={nameOf} close={c2} />)@@ -2394,6 +2403,8 @@ function WorkoutDetail({ w, close }) {<Button icon="copy" onClick={copyAsText}>{t('Copy as text')}</Button><div style={{ height: 8 }} /><Button icon="share" onClick={shareAsImage}>{t('Share as image')}</Button>+ <div style={{ height: 8 }} />+ <Button icon="download" onClick={exportFit}>{t('Export as .fit file')}</Button><div style={{ height: 10 }} />{/* Matched the way the edits above are, not by id: a workout from before ids has none, andfiltering on `x.id !== undefined` took every other one of them with it. */}@@ -2466,6 +2477,13 @@ async function workoutCardImage(model, { map, body }) {drawWorkoutCard(ctx, layout, colors, shape ? { body: shape, levels: model.levels } : null)return new Promise(resolve => canvas.toBlob(resolve, 'image/png'))}+// The .fit file goes out the way a backup does: the share sheet in the phone app (Files, Drive,+// Garmin Connect itself), a download in the browser.+async function saveFitFile(blob, name) {+ if (MOBILE) { try { await shareExportBlob(blob, name) } catch (e) { /* share sheet dismissed */ } return }+ const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); URL.revokeObjectURL(a.href)+ toast(t('Saved. Garmin Connect can take it from here.'))+}// The phone app goes through the OS share sheet the way a backup does; a browser that can share// files (most phones) opens its own; anything else saves the picture as a download.async function shareImage(blob, name, title) {diff --git a/frontend/src/sheets.workout-detail.test.jsx b/frontend/src/sheets.workout-detail.test.jsxindex e5ae0d1e6..234e6ba49 100644--- a/frontend/src/sheets.workout-detail.test.jsx+++ b/frontend/src/sheets.workout-detail.test.jsx@@ -150,3 +150,32 @@ describe('workout detail', () => {delete document.execCommand})})++// #447: the workout as a Garmin .fit activity, saved as a download in the browser.+describe('export as .fit', () => {+ it('saves the saved record as a .fit file named after its day and time', async () => {+ const blobs = []+ const createObjectURL = vi.fn(blob => { blobs.push(blob); return 'blob:fit' })+ vi.stubGlobal('URL', Object.assign(Object.create(URL), { createObjectURL, revokeObjectURL: vi.fn() }))+ const clicked = []+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function () { clicked.push(this.download) })+ const w = workout([{ id: lifts[0], target: { mode: 'reps' }, sets: [done(60, 5), done(60, 5)] }])+ useStore.setState(s => ({ S: { ...s.S, workouts: [w] } }))+ workoutDetailSheet(w)+ const host = mountTopSheet()+ await act(async () => { button(host, 'Export as .fit file').click() })+ expect(clicked).toHaveLength(1)+ expect(clicked[0]).toMatch(/^opengym-2026-09-15-\d{4}\.fit$/)+ const bytes = new Uint8Array(await blobs[0].arrayBuffer())+ expect(String.fromCharCode(...bytes.slice(8, 12))).toBe('.FIT')+ expect(toast).toHaveBeenCalledWith('Saved. Garmin Connect can take it from here.')+ click.mockRestore()+ })++ it('says so when the workout cannot be written', async () => {+ workoutDetailSheet({ id: 'x', name: 'Nowhen', entries: [], prs: [] })+ const host = mountTopSheet()+ await act(async () => { button(host, 'Export as .fit file').click() })+ expect(toast).toHaveBeenCalledWith('Could not create the file')+ })+})