Skip to content

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.

CSV export of workouts and body data, read back losslessly by our importer; GymMane CSV import (#647)

Duarte Santos6b7190278d0a
diff --git a/frontend/src/lib/export-csv.js b/frontend/src/lib/export-csv.js
new file mode 100644
index 000000000..84d77e37b
--- /dev/null
+++ b/frontend/src/lib/export-csv.js
@@ -0,0 +1,139 @@
+// The training history as a spreadsheet (#647): Settings > Data > "Export as CSV".
+//
+// One row per set, the shape every other app's importer reads (Strong, Hevy and the like), so a
+// file from here opens in Excel or Sheets and moves to another app without a converter. Numbers
+// are written with a dot and no grouping whatever the language, dates as ISO, exercise names in
+// English: a spreadsheet in a German or Brazilian locale still reads the columns right, and so
+// does our own importer (lib/import-csv.js), which takes this file back without losing anything
+// it can store. The `exercise_id` column is what makes that lossless: the name is for people,
+// the id is what the re-import files the sets under.
+//
+// Body weight and measurements are a second file. They are one row per day, not per set, and a
+// mixed file would leave every workout row with twenty empty measurement columns.
+
+import { EXIDX } from './exercises.js'
+import { capWords } from './format.js'
+import { MEASUREMENT_FIELDS } from './measurements.js'
+import { hasCompletedWork, isWarmupRow, isFailureSet, isSideSet, dropsOf } from './workout-model.js'
+import { workoutDay } from './history.js'
+
+export const WORKOUT_COLUMNS = [
+ 'date', 'start_time', 'end_time', 'workout', 'workout_note', 'exercise', 'exercise_id', 'body_part',
+ 'superset_id', 'set', 'set_type', 'side', 'weight', 'unit', 'reps', 'rpe', 'rir', 'distance_km',
+ 'seconds', 'incline', 'note',
+]
+
+/** One CSV field, RFC 4180: quoted when it holds a comma, a quote or a line break. */
+export function csvField(v) {
+ if (v == null) return ''
+ let s = String(v)
+ // A name starting with = + - @ is a formula to a spreadsheet, and a shared plan's name came from
+ // someone else. The apostrophe is how spreadsheets spell "this is text"; the importer drops it.
+ if (/^[=+\-@\t\r]/.test(s) && !/^-?\d/.test(s)) s = "'" + s
+ return /[",\r\n]/.test(s) || /^\s|\s$/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s
+}
+
+const line = cells => cells.map(csvField).join(',')
+// The BOM is for Excel, which reads a UTF-8 file without one as the system code page and turns
+// every "ü" into two characters. The importer strips it again.
+const csvText = (header, rows) => '' + [line(header), ...rows.map(line)].join('\r\n') + '\r\n'
+
+// Dot decimal, no grouping, no float noise ("62.5", never "62,5" or "62.50000001").
+const n = v => (Number.isFinite(+v) && v !== '' && v != null ? String(Math.round(+v * 1e6) / 1e6) : '')
+const p2 = x => String(x).padStart(2, '0')
+const stamp = ms => {
+ if (!Number.isFinite(ms) || !ms) return ''
+ const d = new Date(ms)
+ return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())} ${p2(d.getHours())}:${p2(d.getMinutes())}`
+}
+
+/** Workouts whose day falls inside [from, to] (ISO days, either may be null for open), oldest first. */
+const workoutsIn = (S, from, to) => (S.workouts || [])
+ .filter(w => { const d = workoutDay(w); return d && (!from || d >= from) && (!to || d <= to) })
+ .sort((a, b) => (workoutDay(a) === workoutDay(b) ? (a.start || 0) - (b.start || 0) : workoutDay(a) < workoutDay(b) ? -1 : 1))
+
+/** The exercise behind an entry and its name: the user's own as typed, a catalogue one in English. */
+function exerciseFor(S, id) {
+ const mine = (S.customEx || []).find(c => c && c.id === id)
+ if (mine) return { ex: mine, name: mine.n || id }
+ const ex = EXIDX[id] || null
+ return { ex, name: ex ? capWords(ex.n) : id }
+}
+
+/**
+ * Rows of the workout file. `from`/`to` limit it to a stretch of days. Only completed sets are
+ * written, the way the history and the text export count them: an unticked set never happened.
+ */
+export function workoutRows(S, { from = null, to = null } = {}) {
+ const unit = S.unit === 'lb' ? 'lb' : 'kg'
+ const rows = []
+ for (const w of workoutsIn(S, from, to)) {
+ const day = workoutDay(w)
+ // Superset tags are random ids; in a spreadsheet 1, 2, 3 per workout reads better and says the same.
+ const groups = new Map()
+ const head = [day, stamp(w.start), w.end > w.start ? stamp(w.end) : '', w.name || '', w.note || '']
+ for (const e of w.entries || []) {
+ const { ex, name } = exerciseFor(S, e.id)
+ if (e.sg && !groups.has(e.sg)) groups.set(e.sg, groups.size + 1)
+ const exCells = [name, e.id, ex?.bp || '', e.sg ? groups.get(e.sg) : '']
+ let no = 0, noteLeft = e.note || ''
+ // The entry's note rides on its first row only: the importer keeps one note per exercise.
+ const push = cells => { rows.push([...head, ...exCells, ...cells, noteLeft]); noteLeft = '' }
+ const cardio = s => !(s.r > 0) && (s.min > 0 || s.speed > 0)
+ for (const s of e.sets || []) {
+ if (!hasCompletedWork(s)) continue
+ no++
+ const type = isWarmupRow(s) ? 'warmup' : isFailureSet(s) ? 'failure' : 'normal'
+ if (cardio(s)) {
+ const km = (Number(s.speed) || 0) * (Number(s.min) || 0) / 60
+ push([no, type, '', '', unit, '', '', '', n(km) || '0', n(Math.round((Number(s.min) || 0) * 60)), s.incline != null ? n(s.incline) : ''])
+ continue
+ }
+ const effort = x => [x.rpe != null ? n(x.rpe) : '', x.rir != null ? n(x.rir) : '']
+ const one = (x, side) => {
+ if (side && !x.done) return
+ push([no, type, side, n(x.w || 0), unit, x.sec > 0 && !(x.r > 0) ? '' : n(x.r || 0), ...effort(x), '', x.sec > 0 && !(x.r > 0) ? n(x.sec) : '', ''])
+ // A drop-set's drops follow as rows of their own under the same set number.
+ for (const d of dropsOf(x)) push([no, 'drop', side, n(d.w || 0), unit, n(d.r || 0), '', '', '', '', ''])
+ }
+ if (isSideSet(s)) { one(s.sides.L, 'L'); one(s.sides.R, 'R') }
+ else one(s, '')
+ }
+ }
+ }
+ return rows
+}
+
+export const workoutsCSV = (S, range) => csvText(WORKOUT_COLUMNS, workoutRows(S, range))
+
+/**
+ * Body weight and measurements, one row per day. Weight in the profile's unit (the header says
+ * which, so the importer needs no unit column), measurements in centimetres the way they are
+ * stored, body fat in percent. Custom measurement fields get a column each, under their own name.
+ */
+export function bodyCSV(S, { from = null, to = null } = {}) {
+ const unit = S.unit === 'lb' ? 'lb' : 'kg'
+ const inside = d => d && (!from || d >= from) && (!to || d <= to)
+ const days = new Map()
+ const at = d => { if (!days.has(d)) days.set(d, { w: null, m: null }); return days.get(d) }
+ for (const b of S.bodyweight || []) if (inside(b?.d) && b.w > 0) at(b.d).w = b.w
+ for (const m of S.measurements || []) if (inside(m?.d)) at(m.d).m = m
+ const fields = MEASUREMENT_FIELDS.filter(f => [...days.values()].some(v => v.m && v.m[f.key] != null))
+ const custom = new Map()
+ for (const v of days.values()) for (const o of v.m?.other || []) if (o?.id && o.value != null && !custom.has(o.id)) custom.set(o.id, o.name || 'Other')
+ const header = ['date', 'weight_' + unit,
+ ...fields.map(f => f.kind === 'percent' ? 'body_fat_percent' : f.key.replace(/[A-Z]/g, c => '_' + c.toLowerCase()) + '_cm'),
+ ...custom.values()]
+ const rows = [...days.keys()].sort().map(d => {
+ const { w, m } = days.get(d)
+ return [d, w != null ? n(w) : '', ...fields.map(f => (m && m[f.key] != null ? n(m[f.key]) : '')),
+ ...[...custom.keys()].map(id => { const o = (m?.other || []).find(x => x?.id === id); return o?.value != null ? n(o.value) : '' })]
+ })
+ return csvText(header, rows)
+}
+
+/** How many rows each file would have, for the sheet's summary line. */
+export const csvCounts = (S, range) => ({
+ workouts: workoutsIn(S, range?.from, range?.to).length,
+ sets: workoutRows(S, range).length,
+})
diff --git a/frontend/src/lib/export-csv.test.js b/frontend/src/lib/export-csv.test.js
new file mode 100644
index 000000000..7fc27c4fc
--- /dev/null
+++ b/frontend/src/lib/export-csv.test.js
@@ -0,0 +1,218 @@
+import { describe, expect, it } from 'vitest'
+import { csvField, workoutsCSV, workoutRows, bodyCSV, WORKOUT_COLUMNS } from './export-csv.js'
+import { parseCSV, parseWorkoutCSV, parseBodyweight, parseImport, mergeImport } from './import-csv.js'
+
+// Local times, the way the app stores a workout's start and end.
+const at = (d, h, m = 0) => new Date(`${d}T${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:00`).getTime()
+
+const state = (extra = {}) => ({
+ unit: 'kg',
+ customEx: [{ id: 'cx1', n: 'Grip Trainer, "Heavy"', bp: 'lower arms', custom: true, eq: 'custom' }],
+ workouts: [
+ {
+ id: 'w1', d: '2026-03-02', start: at('2026-03-02', 18, 5), end: at('2026-03-02', 19, 10),
+ name: 'Push, day A', note: 'Felt "fresh"\nslept 8 h', routineId: 'r1', prs: [],
+ entries: [
+ { id: '0025', note: 'Paused, 1 s', sets: [
+ { w: 40, r: 10, done: true, phase: 'warmup' },
+ { w: 62.5, r: 8, done: true, rpe: 8.5 },
+ { w: 62.5, r: 6, done: true, failure: true, rir: 0 },
+ { w: 60, r: 8, done: false },
+ ] },
+ { id: '0334', sg: 'sgA', sets: [{ w: 10, r: 12, done: true }, { w: 10, r: 12, done: true }] },
+ { id: '0294', sg: 'sgA', sets: [
+ { w: 14, r: 10, done: true, type: 'dropset', drops: [{ w: 10, r: 8 }, { w: 6, r: 6 }] },
+ { done: true, w: 14, r: 15, rir: 1, sides: { L: { w: 14, r: 8, done: true, rir: 2 }, R: { w: 12, r: 7, done: true, rir: 1 } } },
+ ] },
+ { id: '0463', sets: [{ sec: 60, w: 0, done: true }, { sec: 45, w: 10, done: true }] },
+ { id: 'cx1', sets: [{ w: 30, r: 20, done: true }] },
+ ],
+ },
+ {
+ id: 'w2', d: '2026-03-02', start: at('2026-03-02', 20), end: at('2026-03-02', 20, 40),
+ name: 'Cardio', entries: [{ id: '3666', sets: [{ min: 22.5, speed: 6.4, incline: 8, done: true }, { min: 10, speed: 0, done: true }] }],
+ },
+ { id: 'w3', d: '2026-03-05', start: at('2026-03-05', 7), end: at('2026-03-05', 7), name: '=HYPERLINK("x")', entries: [{ id: '0043', sets: [{ w: 100, r: 5, done: true }] }] },
+ ],
+ bodyweight: [{ d: '2026-03-01', w: 80.4, t: at('2026-03-01', 8) }, { d: '2026-03-04', w: 80.1, t: at('2026-03-04', 8) }],
+ measurements: [{ d: '2026-03-04', waist: 84.5, bodyFat: 17.2, upperArmLeft: 36, other: [{ id: 'm1', name: 'Neck, relaxed', value: 39 }] }],
+ ...extra,
+})
+
+const fresh = () => ({ workouts: [], bodyweight: [], customEx: [], exWeights: {} })
+
+describe('csvField', () => {
+ it('quotes commas, quotes and line breaks the RFC 4180 way', () => {
+ expect(csvField('plain')).toBe('plain')
+ expect(csvField('a, b')).toBe('"a, b"')
+ expect(csvField('say "hi"')).toBe('"say ""hi"""')
+ expect(csvField('two\nlines')).toBe('"two\nlines"')
+ expect(csvField(' padded ')).toBe('" padded "')
+ expect(csvField(null)).toBe('')
+ expect(csvField(62.5)).toBe('62.5')
+ })
+ it('keeps a spreadsheet from running a name as a formula, but leaves negative numbers alone', () => {
+ expect(csvField('=1+1')).toBe("'=1+1")
+ expect(csvField('@cmd')).toBe("'@cmd")
+ expect(csvField('-5')).toBe('-5')
+ })
+})
+
+describe('the workout CSV', () => {
+ const text = workoutsCSV(state())
+ const rows = parseCSV(text)
+ const col = name => WORKOUT_COLUMNS.indexOf(name)
+ const body = rows.slice(1)
+
+ it('has one header and one row per completed set, CRLF and a BOM for Excel', () => {
+ expect(text.startsWith('')).toBe(true)
+ expect(text).toContain('\r\n')
+ expect(rows[0]).toEqual(WORKOUT_COLUMNS)
+ // 3 bench (the unticked one is left out) + 2 raises + 1 curl, 2 drops, 2 sides + 2 holds + 1 grip + 2 cardio + 1 squat
+ expect(body.length).toBe(16)
+ })
+
+ it('writes ISO dates, dot decimals and English names next to the catalogue id', () => {
+ const bench = body.find(r => r[col('exercise_id')] === '0025' && r[col('set')] === '2')
+ expect(bench[col('date')]).toBe('2026-03-02')
+ expect(bench[col('start_time')]).toBe('2026-03-02 18:05')
+ expect(bench[col('end_time')]).toBe('2026-03-02 19:10')
+ expect(bench[col('exercise')]).toBe('Barbell Bench Press')
+ expect(bench[col('weight')]).toBe('62.5')
+ expect(bench[col('unit')]).toBe('kg')
+ expect(bench[col('rpe')]).toBe('8.5')
+ })
+
+ it('marks warm-ups, failure sets, drops, sides and supersets', () => {
+ const types = body.filter(r => r[col('exercise_id')] === '0025').map(r => r[col('set_type')])
+ expect(types).toEqual(['warmup', 'normal', 'failure'])
+ const curl = body.filter(r => r[col('exercise_id')] === '0294')
+ expect(curl.map(r => [r[col('set')], r[col('set_type')], r[col('side')], r[col('weight')], r[col('reps')]])).toEqual([
+ ['1', 'normal', '', '14', '10'], ['1', 'drop', '', '10', '8'], ['1', 'drop', '', '6', '6'],
+ ['2', 'normal', 'L', '14', '8'], ['2', 'normal', 'R', '12', '7'],
+ ])
+ expect(curl[3][col('rir')]).toBe('2')
+ const ss = body.filter(r => r[col('superset_id')]).map(r => r[col('superset_id')])
+ expect(new Set(ss)).toEqual(new Set(['1']))
+ })
+
+ it('writes cardio as distance and seconds, a hold as seconds only', () => {
+ const run = body.find(r => r[col('exercise_id')] === '3666')
+ expect(run[col('seconds')]).toBe('1350')
+ expect(run[col('distance_km')]).toBe('2.4')
+ expect(run[col('incline')]).toBe('8')
+ expect(run[col('weight')]).toBe('')
+ const hold = body.find(r => r[col('exercise_id')] === '0463')
+ expect(hold[col('seconds')]).toBe('60')
+ expect(hold[col('distance_km')]).toBe('')
+ expect(hold[col('reps')]).toBe('')
+ })
+
+ it('survives commas, quotes and line breaks in names and notes', () => {
+ const grip = body.find(r => r[col('exercise_id')] === 'cx1')
+ expect(grip[col('exercise')]).toBe('Grip Trainer, "Heavy"')
+ const first = body[0]
+ expect(first[col('workout')]).toBe('Push, day A')
+ expect(first[col('workout_note')]).toBe('Felt "fresh"\nslept 8 h')
+ expect(first[col('note')]).toBe('Paused, 1 s')
+ // The note rides on the entry's first row only.
+ expect(body.filter(r => r[col('note')]).length).toBe(1)
+ })
+
+ it('writes the profile unit and limits to a range of days', () => {
+ const lb = parseCSV(workoutsCSV(state({ unit: 'lb' })))
+ expect(lb[1][col('unit')]).toBe('lb')
+ expect(workoutRows(state(), { from: '2026-03-03', to: '2026-03-31' }).length).toBe(1)
+ })
+
+ it('is a header and nothing else for an empty history', () => {
+ const empty = parseCSV(workoutsCSV({ unit: 'kg', workouts: [] }))
+ expect(empty).toEqual([WORKOUT_COLUMNS])
+ expect(parseWorkoutCSV(workoutsCSV({ unit: 'kg' })).error).toBe('empty')
+ })
+})
+
+describe('the round trip: our export through our own importer', () => {
+ const S = state()
+ const parsed = parseWorkoutCSV(workoutsCSV(S), { unit: 'kg' })
+ const into = fresh()
+ mergeImport(into, parsed)
+ // Compared without what an import cannot know (ids, the routine link, PRs) and with the
+ // superset tags read as "which entries go together".
+ const shape = w => ({
+ d: w.d, start: w.start, end: w.end, name: w.name, note: w.note,
+ entries: w.entries.map(e => ({ id: e.id, note: e.note, sets: e.sets.filter(s => s.done || s.sides).map(s => {
+ const { phase, ...rest } = s
+ return { ...rest, ...(phase === 'warmup' ? { phase } : {}) }
+ }) })),
+ groups: w.entries.map(e => (e.sg ? w.entries.filter(x => x.sg === e.sg).map(x => x.id).join('+') : null)),
+ })
+
+ it('is recognised as ours', () => {
+ expect(parsed.source).toBe('openGym')
+ expect(parsed.skipped).toBe(0)
+ })
+
+ it('brings back every workout, set, note and superset as it was', () => {
+ expect(into.workouts.map(shape)).toEqual(S.workouts.map(shape))
+ })
+
+ it('keeps two sessions on one day apart and the volume the app would count', () => {
+ expect(into.workouts.filter(w => w.d === '2026-03-02').map(w => w.name)).toEqual(['Push, day A', 'Cardio'])
+ // bench 62.5*8 + 62.5*6, raises 2*120, curls 140 + 80 + 36 and 112 + 84, plank 0, grip 600
+ expect(into.workouts[0].vol).toBe(500 + 375 + 240 + 140 + 80 + 36 + 112 + 84 + 600)
+ })
+
+ it('makes the custom exercise again under its own id and name on a fresh device', () => {
+ expect(into.customEx).toEqual([expect.objectContaining({ id: 'cx1', n: 'Grip Trainer, "Heavy"', bp: 'lower arms', custom: true })])
+ })
+
+ it('files the sets under the custom exercise the device already has', () => {
+ const p = parseWorkoutCSV(workoutsCSV(S), { unit: 'kg', customEx: S.customEx })
+ expect(p.customEx).toEqual([])
+ expect(p.workouts[0].entries.some(e => e.id === 'cx1')).toBe(true)
+ })
+
+ it('converts to the profile unit, drops and sides included', () => {
+ const lb = parseWorkoutCSV(workoutsCSV(S), { unit: 'lb' })
+ const curl = lb.workouts[0].entries.find(e => e.id === '0294')
+ expect(curl.sets[0].w).toBe(30.9)
+ expect(curl.sets[0].drops[0].w).toBe(22)
+ expect(curl.sets[1].sides.R.w).toBe(26.5)
+ expect(lb.converted).toBe(true)
+ })
+
+ it('drops the formula guard again on the way back in', () => {
+ expect(into.workouts[2].name).toBe('=HYPERLINK("x")')
+ })
+
+ it('ignores an id that is a key of Object.prototype and matches by name instead', () => {
+ const csv = WORKOUT_COLUMNS.join(',') + '\n' + '2026-03-02,2026-03-02 18:00,,X,,Barbell Bench Press,constructor,chest,,1,normal,,60,kg,5,,,,,,'
+ const p = parseWorkoutCSV(csv, { unit: 'kg' })
+ expect(p.workouts[0].entries[0].id).toBe('0025')
+ })
+})
+
+describe('the body CSV', () => {
+ const text = bodyCSV(state())
+ const rows = parseCSV(text)
+
+ it('has a row per day with weight and measurements, in cm and percent', () => {
+ expect(rows[0]).toEqual(['date', 'weight_kg', 'waist_cm', 'upper_arm_left_cm', 'body_fat_percent', 'Neck, relaxed'])
+ expect(rows.slice(1)).toEqual([
+ ['2026-03-01', '80.4', '', '', '', ''],
+ ['2026-03-04', '80.1', '84.5', '36', '17.2', '39'],
+ ])
+ })
+
+ it('says the unit in the header, so our importer reads it back in any profile', () => {
+ expect(parseCSV(bodyCSV(state({ unit: 'lb' })))[0][1]).toBe('weight_lb')
+ const back = parseBodyweight(text, { unit: 'kg' })
+ expect(back.bodyweight.map(b => [b.d, b.w])).toEqual([['2026-03-01', 80.4], ['2026-03-04', 80.1]])
+ expect(parseImport(text, { unit: 'kg' }).kind).toBe('bodyweight')
+ })
+
+ it('is just the header with nothing logged', () => {
+ expect(parseCSV(bodyCSV({ unit: 'kg' }))).toEqual([['date', 'weight_kg']])
+ })
+})
diff --git a/frontend/src/lib/import-csv.gymmane.test.js b/frontend/src/lib/import-csv.gymmane.test.js
new file mode 100644
index 000000000..47febcf95
--- /dev/null
+++ b/frontend/src/lib/import-csv.gymmane.test.js
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest'
+import { parseWorkoutCSV } from './import-csv.js'
+
+// Hand-written from the header GymMane's code writes (services/local_store.dart, read for #647);
+// no real export yet, so the values are made up and only the columns are theirs.
+const GYMMANE = [
+ 'date,exercise,muscle,set,reps,weight_kg,volume_kg,est_1rm_kg,distance_km,duration_s,rpe',
+ '2026-05-04,Bench Press,Chest,1,8,60,480,75.2,,,8',
+ '2026-05-04,Bench Press,Chest,2,7,60,420,73.1,,,9',
+ '2026-05-04,Cable Kickback Thing,Glutes,1,12,15,180,21,,,',
+ '2026-05-04,Running,Cardio,1,0,0,0,0,3.2,1200,',
+].join('\n')
+
+describe('a GymMane CSV', () => {
+ const p = parseWorkoutCSV(GYMMANE, { unit: 'kg' })
+ const [w] = p.workouts
+
+ it('is recognised and read as one workout', () => {
+ expect(p.source).toBe('GymMane')
+ expect(p.workouts.length).toBe(1)
+ expect(p.skipped).toBe(0)
+ })
+
+ it('reads weight, reps and RPE, not the volume or 1RM columns', () => {
+ const bench = w.entries.find(e => e.id === '0025')
+ expect(bench.sets).toEqual([{ w: 60, r: 8, done: true, rpe: 8 }, { w: 60, r: 7, done: true, rpe: 9 }])
+ })
+
+ it('takes duration_s as the set time and muscle as the body part of a new exercise', () => {
+ const run = w.entries.find(e => e.sets[0].min)
+ expect(run.sets[0]).toMatchObject({ min: 20, speed: 9.6 })
+ expect(p.customEx.find(c => c.n === 'cable kickback thing').bp).toBe('upper legs')
+ })
+})
diff --git a/frontend/src/lib/import-csv.js b/frontend/src/lib/import-csv.js
index cb91456a2..72b8d9b53 100644
--- a/frontend/src/lib/import-csv.js
+++ b/frontend/src/lib/import-csv.js
@@ -10,6 +10,9 @@
// FitNotes 2 (iOS) Date,Exercise,Category,Weight (kg),Weight (lbs),Reps,Distance,Distance Unit,Time,Notes,Kind
// Strong Date,Workout Name,Duration,Exercise Name,Set Order,Weight,Reps,Distance,Seconds,Notes,Workout Notes,RPE
// Hevy title,start_time,end_time,description,exercise_title,superset_id,exercise_notes,set_index,set_type,weight_kg,reps,distance_km,duration_seconds,rpe
+// openGym our own CSV export, lib/export-csv.js WORKOUT_COLUMNS (#647)
+// Read from the header GymMane documents in its code (not from a real file yet, #647):
+// GymMane date,exercise,muscle,set,reps,weight_kg,volume_kg,est_1rm_kg,distance_km,duration_s,rpe
// Anything else falls through to loose header matching, which covers Lyfta and the
// spreadsheet round-trips people actually have on disk, as long as the file has a
// date, an exercise name and something measured.
@@ -20,7 +23,7 @@
import { EXDB, EXIDX, canonicalExId, isCardio as isCardioEx } from './exercises.js'
import { uid } from './format.js'
-import { isWarmupRow } from './workout-model.js'
+import { isWarmupRow, completedVolumeOf, syncSideAggregate } from './workout-model.js'
import { HEVY_TITLE_MAP } from './hevy-id-map.js'
import { clampIncline, inclineFrom } from './incline.js'
@@ -71,12 +74,14 @@ const norm = h => h.toLowerCase().replace(/#/g, ' no ').replace(/[^a-z0-9]+/g, '
// header text -> the field we care about. Specific names first; first match wins.
const COLUMNS = [
['exercise', ['exercise', 'exercise name', 'exercise title']],
+ // Our own export's catalogue id, which makes a re-import lossless (lib/export-csv.js).
+ ['exerciseId', ['exercise id']],
['date', ['date', 'workout date']],
['startTime', ['start time', 'start date']],
['endTime', ['end time']],
['workoutNo', ['workout no']],
['workoutName', ['workout name', 'title', 'workout']],
- ['category', ['category', 'body part', 'muscle group']],
+ ['category', ['category', 'body part', 'muscle group', 'muscle']],
['weightKg', ['weight kg']],
['weightLb', ['weight lbs', 'weight lb']],
['weight', ['weight']],
@@ -92,11 +97,14 @@ const COLUMNS = [
['distanceUnit', ['distance unit']],
// gravl writes a treadmill's grade per set; "Incline (%)" normalises to the same name.
['incline', ['incline', 'incline percent']],
- ['seconds', ['seconds', 'duration seconds', 'set duration sec']],
+ ['seconds', ['seconds', 'duration seconds', 'set duration sec', 'duration s']],
['time', ['time', 'duration']],
// Strong's current export: the whole workout's length, in seconds, on every row.
['durationSec', ['duration sec', 'duration secs']],
['setType', ['set type']],
+ // The set's number and, for a set logged per side, which side the row is (our own export).
+ ['setNo', ['set', 'set order', 'set index']],
+ ['side', ['side']],
// Hevy numbers the supersets of a workout; rows sharing a number were done as one.
['superset', ['superset id']],
// The session's note, before the per-set one: Strong writes both, "Notes" first, and a
@@ -123,6 +131,8 @@ function mapHeader(header) {
/** Name of the app a header looks like — shown back to the user so they can sanity-check. */
export function detectSource(header) {
const h = header.map(norm)
+ if (h.includes('exercise id') && h.includes('set type')) return 'openGym'
+ if (h.includes('exercise') && h.includes('est 1rm kg')) return 'GymMane'
if (h.includes('exercise title') && h.includes('set index')) return 'Hevy'
if (h.includes('exercise name') && h.includes('set order')) return 'Strong'
if (h.includes('exercise') && h.includes('kind')) return 'FitNotes (iOS)'
@@ -332,6 +342,9 @@ const CATEGORY_BP = Object.assign(Object.create(null), {
calves: 'lower legs', abs: 'waist', core: 'waist', obliques: 'waist',
arms: 'upper arms', biceps: 'upper arms', triceps: 'upper arms', forearms: 'lower arms',
cardio: 'cardio', 'full body': 'upper legs', olympic: 'upper legs', neck: 'neck',
+ // The catalogue's own body parts, as our export writes them.
+ 'upper legs': 'upper legs', 'lower legs': 'lower legs', 'upper arms': 'upper arms',
+ 'lower arms': 'lower arms', waist: 'waist',
})
/* ----------------------------------------------------------- conversion --- */
@@ -482,6 +495,10 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
if (rows.length < 2) return { error: 'empty' }
const map = mapHeader(rows[0])
const source = detectSource(rows[0])
+ // Our own export (lib/export-csv.js) says more than the others: the catalogue id, which side of
+ // a per-side set a row is, a drop-set's drops as rows of their own. Read that way only when the
+ // header says it is ours.
+ const own = source === 'openGym'
const dateCol = map.date !== undefined ? 'date' : map.startTime !== undefined ? 'startTime' : null
if (!dateCol || map.exercise === undefined) return { error: 'unrecognised' }
// Strong's Duration is how long the whole workout took ("1h 5m", "52m"), written on every
@@ -504,13 +521,22 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
let sets = 0, skipped = 0, matched = 0, warmups = 0, rpeSets = 0, rirSets = 0
let sawLb = false, sawKg = false
- const cell = (r, f) => (map[f] === undefined ? '' : String(r[map[f]] ?? '').trim())
+ // The export puts an apostrophe in front of a name a spreadsheet would run as a formula.
+ const cell = (r, f) => {
+ const v = map[f] === undefined ? '' : String(r[map[f]] ?? '').trim()
+ return own && /^'[=+\-@\t\r]/.test(v) ? v.slice(1) : v
+ }
for (let i = 1; i < rows.length; i++) {
const r = rows[i]
const name = cell(r, 'exercise')
- const when = parseWhen(cell(r, dateCol))
+ let when = parseWhen(cell(r, dateCol))
if (!name || !when) { skipped++; continue }
+ // Ours writes the day and the start apart, so a session that ran past midnight keeps its day.
+ if (own && map.startTime !== undefined) {
+ const st = parseWhen(cell(r, 'startTime'))
+ if (st && st.t != null) when = { d: when.d, t: st.t }
+ }
// explicit kg/lb columns beat a generic column plus a unit column
let w = 0, rowUnit = ''
@@ -527,7 +553,8 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
const reps = Math.round(num(cell(r, 'reps')))
const secs = num(cell(r, 'seconds'))
const setNote = cell(r, 'note')
- const mins = secs > 0 ? Math.round(secs / 60 * 10) / 10 : toMinutes(cell(r, 'time'))
+ // Ours keeps cardio minutes to hundredths, the way the app stores them.
+ const mins = secs > 0 ? Math.round(secs / 60 * (own ? 100 : 10)) / (own ? 100 : 10) : toMinutes(cell(r, 'time'))
const km = map.distanceKm !== undefined && cell(r, 'distanceKm')
? num(cell(r, 'distanceKm'))
: map.distanceM !== undefined && cell(r, 'distanceM')
@@ -541,17 +568,26 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
const warmup = /warm/i.test(cell(r, 'setType'))
if (warmup) warmups++
- const key = keyOf(name)
+ // Our own file names the exercise by id: a catalogue id is taken as it is, and a custom one
+ // keeps its id too, so the same exercise on another device is the same exercise. Never a key
+ // of Object.prototype ("constructor" would find a function in every index).
+ const rawId = own ? cell(r, 'exerciseId') : ''
+ const fileId = /^[A-Za-z0-9][\w.-]{0,63}$/.test(rawId) && !(rawId in Object.prototype) ? rawId : ''
+ const key = fileId ? 'id:' + fileId : keyOf(name)
// The match is cached per exact title, not per word bag: the bag drops "weighted", so
// "Triceps Dip" and "Triceps Dip (Weighted)" would share one match, the first title's.
- const exact = name.trim().toLowerCase()
+ const exact = fileId ? key : name.trim().toLowerCase()
let id = resolved.get(exact)
if (id === undefined) {
- const own = priorCustom(customEx, importId('im', source + '|' + name.toLowerCase()), name)
- if (own) prior.set(key, own)
- // Hevy CSV: prefer the generated English-title map (same table as the API import).
- // Localized titles still fall through to the word-bag matcher.
- id = own ? own.id : canonicalExId((source === 'Hevy' ? matchHevyTitle(name) : null) || matchExercise(name))
+ if (fileId && Object.hasOwn(EXIDX, fileId)) id = canonicalExId(fileId)
+ else {
+ const mine = priorCustom(customEx, fileId || importId('im', source + '|' + name.toLowerCase()), name)
+ if (mine) prior.set(key, mine)
+ // Hevy CSV: prefer the generated English-title map (same table as the API import).
+ // Localized titles still fall through to the word-bag matcher. A custom exercise of ours
+ // stays custom: it was not in the catalogue on purpose.
+ id = mine ? mine.id : fileId ? null : canonicalExId((source === 'Hevy' ? matchHevyTitle(name) : null) || matchExercise(name))
+ }
resolved.set(exact, id)
}
if (id) matched++
@@ -559,7 +595,7 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
let c = created.get(key)
if (!c) {
c = {
- id: importId('im', source + '|' + name.toLowerCase()), n: name.toLowerCase(), custom: true, eq: 'custom', tg: '', desc: '',
+ id: fileId || importId('im', source + '|' + name.toLowerCase()), n: own ? name : name.toLowerCase(), custom: true, eq: 'custom', tg: '', desc: '',
bp: CATEGORY_BP[cell(r, 'category').toLowerCase()] || (km ? 'cardio' : null)
// Seconds with nothing else is a hold when the name says what it is (a plank is
// core work); a name that says nothing keeps being read as cardio, as before.
@@ -579,14 +615,16 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
// loose match ("Walking" → walking lunge) would turn a walk into a hold.
const nameBp = bpFromName(name.toLowerCase())
const exCardio = isCardioEx(id) || (created.get(key) || prior.get(key))?.bp === 'cardio' || nameBp === 'cardio'
- const timed = secs > 0 && !km && !reps && !exCardio && (source === 'Strong' || !!nameBp)
- const isCardio = !timed && (km > 0 || mins > 0) && !reps
+ // Ours says it outright: a cardio row always has a distance, "0" included, a timed one none.
+ const ownCardio = own && cell(r, 'distanceKm') !== ''
+ const timed = own ? secs > 0 && !reps && !ownCardio : secs > 0 && !km && !reps && !exCardio && (source === 'Strong' || !!nameBp)
+ const isCardio = own ? ownCardio && !timed : !timed && (km > 0 || mins > 0) && !reps
// `u` carries the row's own unit into the conversion pass below and is dropped there —
// it never reaches the stored set.
const set = timed
? { sec: Math.round(secs), w, done: true, u: rowUnit, ...(warmup ? { phase: 'warmup' } : {}) }
: isCardio
- ? { min: mins || 0, speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0, ...inclineFrom({ incline: clampIncline(num(cell(r, 'incline'))) }), done: true, ...(warmup ? { phase: 'warmup' } : {}) }
+ ? { min: mins || 0, speed: mins > 0 ? Math.round(km / (mins / 60) * (own ? 100 : 10)) / (own ? 100 : 10) : 0, ...inclineFrom({ incline: clampIncline(num(cell(r, 'incline'))) }), done: true, ...(warmup ? { phase: 'warmup' } : {}) }
: { w, r: reps || 0, done: true, u: rowUnit, ...(warmup ? { phase: 'warmup' } : {}) }
// A "failure" set type (Hevy's CSV writes one) is the app's set taken to failure; not on
// cardio, which has no effort to read it as.
@@ -603,8 +641,9 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
// Strong and Hevy write the workout's start on every row, so two sessions on one day are
// told apart by it (and by the name) and stay two workouts (#505). FitNotes has no times, and
- // a generic file may stamp each set with its own, so everything else stays one per day.
- const sessionKey = (source === 'Strong' || source === 'Hevy') && when.t != null
+ // a generic file may stamp each set with its own, so everything else stays one per day. Ours
+ // writes the start on every row the way those two do.
+ const sessionKey = (source === 'Strong' || source === 'Hevy' || own) && when.t != null
? when.d + '|' + when.t + '|' + (cell(r, 'workoutName') || '')
: when.d
let day = byDate.get(sessionKey)
@@ -624,7 +663,31 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
if (len > 0) day.end = (day.start ?? 18 * 3600000) + Math.round(len * 60000)
}
if (!day.ex.has(id)) day.ex.set(id, [])
- day.ex.get(id).push(set)
+ const list = day.ex.get(id)
+ const prev = list[list.length - 1]
+ const side = own ? cell(r, 'side').toUpperCase() : ''
+ const setNo = cell(r, 'setNo')
+ // A drop is a row of its own in our file, under the set it belongs to (and its side).
+ if (own && /^drop$/i.test(cell(r, 'setType')) && prev && !isCardio && !timed) {
+ const into = (side === 'L' || side === 'R') && prev.sides ? prev.sides[side] : prev
+ into.type = 'dropset'
+ into.drops = [...(into.drops || []), { w, r: reps || 0 }]
+ continue
+ }
+ if (own && (side === 'L' || side === 'R') && !isCardio && !timed) {
+ const half = { w, r: reps || 0, done: true, ...(set.rir != null ? { rir: set.rir } : {}), ...(set.rpe != null ? { rpe: set.rpe } : {}) }
+ // The other side of the set the previous row started: same set number, side not yet filled.
+ if (prev && prev._sides && prev._no === setNo && !prev._sides.includes(side)) {
+ prev.sides[side] = half
+ prev._sides.push(side)
+ continue
+ }
+ const row = { done: true, u: rowUnit, sides: { L: { w: 0, r: 0, done: false }, R: { w: 0, r: 0, done: false } }, _no: setNo, _sides: [side] }
+ row.sides[side] = half
+ if (set.phase) row.phase = set.phase
+ if (set.failure) row.failure = true
+ list.push(row)
+ } else list.push(set)
// A note written against a set belongs to the exercise that day; the app keeps one per entry.
if (setNote) {
const list = day.notes.get(id) || []
@@ -663,7 +726,17 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
const workouts = days.map(day => {
const d = day.d
const entries = [...day.ex.entries()].map(([id, ss]) => {
- const conv2 = ss.map(({ u, ...s }) => (s.w !== undefined ? { ...s, w: convRow({ ...s, u }) } : s))
+ // Drops and sides are in the row's unit too. Per-side rows get their summary from the sides.
+ const conv2 = ss.map(({ u, _no, _sides, ...s }) => {
+ if (s.w === undefined && !s.sides) return s
+ const c = x => convRow({ w: x, u })
+ const drops = d => (Array.isArray(d) ? { drops: d.map(x => ({ ...x, w: c(x.w) })) } : {})
+ if (s.sides) {
+ const side = x => ({ ...x, w: c(x.w), ...drops(x.drops) })
+ return syncSideAggregate({ ...s, sides: { L: side(s.sides.L), R: side(s.sides.R) } })
+ }
+ return { ...s, w: c(s.w), ...drops(s.drops) }
+ })
const mx = Math.max(0, ...conv2.filter(s => !isWarmupRow(s)).map(s => s.w || 0))
const note = (day.notes.get(id) || []).join(' · ').slice(0, 280)
return { id, sets: conv2, topW: mx || null, ...(day.sg.has(id) ? { sg: day.sg.get(id) } : {}), ...(note ? { note } : {}) }
@@ -681,7 +754,8 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
}
// Work sets only, like `workoutVolume` for a workout finished in the app: warm-ups are
// promised to stay out of the volume, and this number is stored with the workout for good.
- w.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (isWarmupRow(s) ? 0 : (s.w || 0) * (s.r || 0)), 0), 0)
+ // completedVolumeOf counts a drop-set's drops and each side of a per-side set at its own load.
+ w.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (isWarmupRow(s) ? 0 : completedVolumeOf(s)), 0), 0)
return w
})