From 389315625c6144a9a81ad30d06de5cf5ad5e70f4 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Thu, 23 Jul 2026 14:50:36 +0200 Subject: [PATCH] Import history from FitNotes, Strong, Hevy and Apple Health Losing years of logging is the thing that stops people trying another tracker, so Settings -> Data -> Import from another app now reads their exports directly. All of these ship the same thing in a different dialect: one row per set with a date, an exercise name and some mix of weight/reps/distance/time. So the parser builds a column map from the header rather than assuming positions, and a new app is usually a few header aliases. Verified against real exports from Strong (1903 sets) and Hevy, both FitNotes column layouts, and an Apple Health body-mass extract. Exercise matching is the part that decides whether this is useful. Parenthetical qualifiers and BB/DB shorthand are normalised, names are compared as an order-independent bag of words, and a curated table maps the plain names people actually log onto the dataset's qualified ones - without it, 'Squat' resolved to 'weighted squat' and 'Leg Press' to 'smith leg press'. Where a name stays genuinely ambiguous it is left unmatched and becomes a custom exercise rather than guessed at: filing years of training under the wrong lift is worse than a name the user can see and fix. Nothing in the file is ever dropped. A summary sheet shows workouts, sets, matches, misses and any unit conversion before anything is written, and merging skips days that already have data, so importing twice - or from two apps - never duplicates a workout. --- CHANGELOG.md | 20 ++ README.md | 3 +- frontend/src/lib/import-csv.js | 485 ++++++++++++++++++++++++++++++++ frontend/src/locales/de.js | 21 +- frontend/src/locales/es.js | 21 +- frontend/src/locales/fr.js | 21 +- frontend/src/locales/hi.js | 21 +- frontend/src/locales/it.js | 21 +- frontend/src/locales/ko.js | 21 +- frontend/src/locales/pl.js | 21 +- frontend/src/locales/pt.js | 21 +- frontend/src/locales/ru.js | 21 +- frontend/src/locales/tr.js | 21 +- frontend/src/locales/zh.js | 21 +- frontend/src/sheets.jsx | 85 ++++++ frontend/src/views/Settings.jsx | 9 +- 16 files changed, 820 insertions(+), 13 deletions(-) create mode 100644 frontend/src/lib/import-csv.js diff --git a/CHANGELOG.md b/CHANGELOG.md index cc0b65b..b550526 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## Unreleased + +- 📥 **Import your history from another app.** Settings → Data → *Import from another app* + reads an export from **FitNotes** (both the Android and the FitNotes 2 iOS format), + **Strong** and **Hevy**, and pulls body-weight history out of an **Apple Health** export. + Anything else with a date, an exercise name and weight/reps columns is read too. + - Every row becomes a set, grouped into workouts by date, so your history arrives with + its real dates rather than as one lump. Hevy and Strong also carry session length, so + the activity heatmap fills in properly. + - Exercise names are matched against the 1,324-exercise library — parenthetical + qualifiers like "(Barbell)" and shorthand like BB/DB are normalised, and a curated + table covers the plain names people actually log ("Bench Press", "Squat", "RDL"). + Where a name is genuinely ambiguous it is *not* guessed at: it becomes one of your own + exercises instead, because filing years of training under the wrong lift is worse than + an unmatched name you can see and fix. + - A summary shows what will happen — workouts, sets, how many exercises matched, which + ones didn't, and whether weights need converting — before anything is written. + - Importing is idempotent: days you already have data for are left alone, so running it + twice, or importing from two apps, never duplicates a workout. + ## v1.2.1 — 2026-07-23 A muscle map across the app, and a live demo you can try without installing anything. diff --git a/README.md b/README.md index 63346f3..a41c3b9 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a - 🛠️ **Admin dashboard** (optional) — for whoever runs the instance: who's training right now, per-user history, disable accounts, and invite-only signup. Off by default, so a fresh instance stays open with no admin - 🎨 **Designed, not assembled** — light/dark themes and 8 accent colors saved to your profile, over a hand-drawn icon set instead of emoji, so it looks the same on every phone - 🌍 **12 languages** — full UI translation (EN, DE, ES, FR, IT, PT, PL, TR, RU, ZH, KO, HI); exercise instructions localized in 10 of them, loaded on demand so the app stays fast +- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy**, or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped - 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry** ## Quick start (self-host) @@ -139,7 +140,7 @@ Push notification keys are generated on first run and saved to `./data/vapid.jso Rough, community-driven — ideas and PRs welcome: - [ ] More starter plans (upper/lower, full-body, 5×5) -- [ ] Importers from Strong / Hevy (CSV → openGym JSON) +- [x] Importers from FitNotes / Strong / Hevy, and body weight from Apple Health - [ ] Body measurements (waist, arms…) alongside weight - [ ] Per-exercise notes & plate calculator - [ ] Exercise instructions in German & Portuguese (UI is translated; upstream dataset doesn't ship these yet) diff --git a/frontend/src/lib/import-csv.js b/frontend/src/lib/import-csv.js new file mode 100644 index 0000000..0b80865 --- /dev/null +++ b/frontend/src/lib/import-csv.js @@ -0,0 +1,485 @@ +// Import a training history exported from another app. +// +// Every one of these apps exports the same thing in a different dialect: one row per +// *set*, carrying a date, an exercise name and some mix of weight/reps/distance/time. +// So this reads a column MAP built from the header rather than fixed positions, which +// means a new app is usually a few header aliases rather than another importer. +// +// Verified against real exports: +// FitNotes (Android) Date,Exercise,Category,Weight,Weight Unit,Reps,Distance,Distance Unit,Time,Comment +// 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 +// 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. +// +// Apple Health is a different animal — an XML dump, often hundreds of MB — and only its +// body-weight records are interesting here. parseBodyweight() scans for those without +// building a DOM. + +import { EXDB, EXIDX } from './exercises.js' +import { uid } from './format.js' + +/* ----------------------------------------------------------------- CSV ---- */ + +/** + * A real CSV reader: quoted fields, embedded commas and newlines, doubled quotes, BOM + * and CRLF. Splitting on commas breaks on the first exercise named "Bench Press, Close + * Grip" — and a whole history would import shifted by one column without ever erroring. + */ +export function parseCSV(text) { + const rows = [] + let row = [], field = '', quoted = false + const s = String(text).replace(/^/, '') + for (let i = 0; i < s.length; i++) { + const c = s[i] + if (quoted) { + if (c === '"') { if (s[i + 1] === '"') { field += '"'; i++ } else quoted = false } + else field += c + } else if (c === '"') quoted = true + else if (c === ',') { row.push(field); field = '' } + else if (c === '\n' || c === '\r') { + if (c === '\r' && s[i + 1] === '\n') i++ + row.push(field); field = '' + if (row.some(x => x !== '')) rows.push(row) + row = [] + } else field += c + } + row.push(field) + if (row.some(x => x !== '')) rows.push(row) + return rows +} + +const norm = h => h.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim() + +// header text -> the field we care about. Specific names first; first match wins. +const COLUMNS = [ + ['exercise', ['exercise', 'exercise name', 'exercise title']], + ['date', ['date', 'workout date']], + ['startTime', ['start time']], + ['endTime', ['end time']], + ['workoutName', ['workout name', 'title']], + ['category', ['category', 'body part', 'muscle group']], + ['weightKg', ['weight kg']], + ['weightLb', ['weight lbs', 'weight lb']], + ['weight', ['weight']], + ['weightUnit', ['weight unit', 'unit']], + ['reps', ['reps', 'repetitions']], + ['distanceKm', ['distance km']], + ['distance', ['distance']], + ['distanceUnit', ['distance unit']], + ['seconds', ['seconds', 'duration seconds']], + ['time', ['time', 'duration']], + ['setType', ['set type']], + ['note', ['comment', 'comments', 'notes', 'note']], +] + +function mapHeader(header) { + const map = {} + header.forEach((h, i) => { + const n = norm(h) + for (const [field, names] of COLUMNS) { + if (map[field] === undefined && names.includes(n)) { map[field] = i; return } + } + }) + return map +} + +/** 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 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)' + if (h.includes('exercise') && h.includes('weight unit')) return 'FitNotes' + if (h.includes('exercise') && h.includes('category')) return 'FitNotes' + return null +} + +/* ------------------------------------------------------ exercise matching -- */ + +// Other apps bolt qualifiers onto names — Hevy writes "Leg Press (Machine)", Strong +// "Snatch (Barbell)", FitNotes "Lat Pulldown (Pulley)" — while the dataset writes +// "barbell snatch". Strip the parentheses, expand the shorthand, then compare as a +// sorted bag of words so word order stops mattering. +const SYN = [ + [/\bbb\b/g, 'barbell'], [/\bdb\b/g, 'dumbbell'], [/\bkb\b/g, 'kettlebell'], + [/\bohp\b/g, 'overhead press'], [/\bbw\b/g, 'body weight'], [/\bbodyweight\b/g, 'body weight'], + [/\bmachine\b/g, 'lever'], [/\bsmith machine\b/g, 'smith'], [/\bez bar\b/g, 'ez barbell'], + [/\bpull ups?\b/g, 'pull up'], [/\bchin ups?\b/g, 'chin up'], [/\bpush ups?\b/g, 'push up'], + [/\bsit ups?\b/g, 'sit up'], [/\bdips?\b/g, 'dip'], [/\braises?\b/g, 'raise'], + [/\bcurls?\b/g, 'curl'], [/\bpresses\b/g, 'press'], [/\bextensions?\b/g, 'extension'], + [/\bcables?\b/g, 'cable'], [/\bseated\b/g, 'seated'], [/\bassisted\b/g, 'assisted'], +] +// Words that say nothing about which exercise this is, so they shouldn't stop a match. +const FILLER = new Set(['the', 'a', 'with', 'and', 'v', 'variation', 'version', 'pulley', 'weighted']) + +function wordsOf(name) { + // Parentheses are unwrapped rather than dropped: "Bench Press (Barbell)" carries its + // equipment in there, and the dataset writes that as "barbell bench press". + let k = String(name || '').toLowerCase() + .replace(/[()[\]]/g, ' ') + .replace(/[^a-z0-9]+/g, ' ') + .trim() + SYN.forEach(([re, to]) => { k = k.replace(re, to) }) + return k.split(' ').filter(w => w && !FILLER.has(w)) +} +const keyOf = name => wordsOf(name).sort().join(' ') + +let INDEX = null +function buildIndex() { + if (INDEX) return INDEX + INDEX = { exact: new Map(), all: [] } + EXDB.forEach(e => { + const w = wordsOf(e.n) + const k = w.slice().sort().join(' ') + if (!INDEX.exact.has(k)) INDEX.exact.set(k, e.id) + INDEX.all.push({ id: e.id, set: new Set(w), n: w.length }) + }) + return INDEX +} + +// Curated: the names people actually log, mapped by hand to the dataset id they mean. +// +// Other apps let you name a lift "Bench Press"; the dataset only has qualified names +// like "barbell bench press". Word-overlap alone can't resolve that — "bench press" sits +// inside thirty-three entries — and where it *is* unique it tends to be wrong, happily +// resolving "Squat" to "weighted squat" and "Leg Press" to "smith leg press". So the +// common vocabulary is spelled out. The convention is that an unqualified name means the +// canonical barbell version, which is what these apps assume when they show it to you. +// Extending this table is the intended way to improve import accuracy. +const ALIAS_EX = { + 'bench press': '0025', 'barbell bench press': '0025', 'flat bench press': '0025', + 'incline bench press': '0047', 'decline bench press': '0033', + 'close grip bench press': '0030', 'close-grip bench press': '0030', + squat: '0043', 'back squat': '0043', 'barbell squat': '0043', 'front squat': '0042', + deadlift: '0032', 'romanian deadlift': '0085', rdl: '0085', 'sumo deadlift': '0117', + 'lat pulldown': '2330', 'lat pull down': '2330', pulldown: '2330', + shrug: '0095', shrugs: '0095', + 'overhead press': '0091', 'military press': '0091', 'shoulder press': '0091', ohp: '0091', + 'barbell row': '0027', 'bent over row': '0027', 'bent-over row': '0027', + 'dumbbell row': '0292', 'one arm dumbbell row': '0292', + 'leg curl': '0586', 'lying leg curl': '0586', 'seated leg curl': '0586', + 'leg press': '0739', 'leg extension': '0585', + 'calf raise': '1372', 'standing calf raise': '1372', 'seated calf raise': '0088', + 'lateral raise': '0334', 'side raise': '0334', 'reverse fly': '0348', 'rear delt fly': '0348', + 'bicep curl': '0294', 'biceps curl': '0294', 'dumbbell curl': '0294', + 'preacher curl': '0070', 'barbell curl': '0031', + 'tricep pushdown': '0241', 'triceps pushdown': '0241', pushdown: '0241', + skullcrusher: '0060', 'skull crusher': '0060', 'lying triceps extension': '0061', + lunge: '0054', lunges: '0054', 'cable crossover': '1269', 'cable cross over': '1269', +} + +let ALIAS_IDX = null +const aliasIndex = () => { + if (!ALIAS_IDX) { + ALIAS_IDX = new Map() + for (const k in ALIAS_EX) ALIAS_IDX.set(wordsOf(k).sort().join(' '), ALIAS_EX[k]) + } + return ALIAS_IDX +} + +/** + * Find the dataset exercise a foreign name refers to, or null. + * + * Curated alias first, then an exact word-bag match, then entries that contain every + * word of the query — but only when exactly one candidate is that close. Guessing + * between "barbell bench press" and "dumbbell bench press" would file years of training + * under the wrong lift, which is worse than leaving it as a custom exercise the user can + * see and fix. + */ +export function matchExercise(name) { + const idx = buildIndex() + const w = wordsOf(name) + if (!w.length) return null + // Compared as a sorted bag of words, so "Squat (Barbell)" finds the 'barbell squat' + // alias — the exporters disagree about whether the equipment leads or trails. + const sorted = w.slice().sort().join(' ') + const aliased = aliasIndex().get(sorted) + if (aliased && EXIDX[aliased]) return aliased + const exact = idx.exact.get(sorted) + if (exact) return exact + const q = new Set(w) + let best = null, bestExtra = Infinity, ties = 0 + for (const c of idx.all) { + let ok = true + for (const word of q) if (!c.set.has(word)) { ok = false; break } + if (!ok) continue + const extra = c.n - q.size + if (extra > 2) continue + if (extra < bestExtra) { best = c.id; bestExtra = extra; ties = 1 } + else if (extra === bestExtra) ties++ + } + return ties === 1 ? best : null +} + +// Categories the exporters use -> the dataset's body parts, for exercises we invent. +const CATEGORY_BP = { + chest: 'chest', back: 'back', lats: 'back', shoulders: 'shoulders', delts: 'shoulders', + legs: 'upper legs', quads: 'upper legs', hamstrings: 'upper legs', glutes: 'upper legs', + 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', +} + +/* ----------------------------------------------------------- conversion --- */ + +const num = v => { const n = parseFloat(String(v ?? '').replace(',', '.')); return isFinite(n) ? n : 0 } +const LB_TO_KG = 0.45359237 +const p2 = n => String(n).padStart(2, '0') +const MON = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 } + +/** "2020-12-30 18:51:52" · "2024-03-07" · "22 Dec 2025, 08:00" · "07/03/2024" -> { d, t } */ +export function parseWhen(s) { + const v = String(s || '').trim() + let m = v.match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[T ](\d{1,2}):(\d{2}))?/) + if (m) return { d: `${m[1]}-${p2(m[2])}-${p2(m[3])}`, t: hm(m[4], m[5]) } + m = v.match(/^(\d{1,2})\s+([A-Za-z]{3})[a-z]*\.?\s+(\d{4})(?:,?\s+(\d{1,2}):(\d{2}))?/) + if (m && MON[m[2].toLowerCase()]) return { d: `${m[3]}-${p2(MON[m[2].toLowerCase()])}-${p2(m[1])}`, t: hm(m[4], m[5]) } + m = v.match(/^([A-Za-z]{3})[a-z]*\.?\s+(\d{1,2}),?\s+(\d{4})(?:,?\s+(\d{1,2}):(\d{2}))?/) + if (m && MON[m[1].toLowerCase()]) return { d: `${m[3]}-${p2(MON[m[1].toLowerCase()])}-${p2(m[2])}`, t: hm(m[4], m[5]) } + // Day-first when ambiguous: FitNotes/Strong/Hevy all write unambiguous dates, so a + // bare numeric one came through a spreadsheet, and those are usually European. + m = v.match(/^(\d{1,2})[/.](\d{1,2})[/.](\d{4})(?:[, ]+(\d{1,2}):(\d{2}))?/) + if (m) { + const [, a, b, y] = m + const day = +a > 12 ? a : +b > 12 ? b : a + const mon = day === a ? b : a + return { d: `${y}-${p2(mon)}-${p2(day)}`, t: hm(m[4], m[5]) } + } + return null +} +const hm = (h, mi) => (h === undefined ? null : (parseInt(h, 10) || 0) * 3600000 + (parseInt(mi, 10) || 0) * 60000) + +/** "HH:MM:SS" · "MM:SS" · "90" -> minutes */ +function toMinutes(v) { + const s = String(v ?? '').trim() + if (!s) return 0 + if (s.includes(':')) { + const p = s.split(':').map(x => parseInt(x, 10) || 0) + const sec = p.length === 3 ? p[0] * 3600 + p[1] * 60 + p[2] : p[0] * 60 + p[1] + return Math.round(sec / 60 * 10) / 10 + } + const m = s.match(/(\d+)\s*h/i), mm = s.match(/(\d+)\s*m/i) // Strong's "2h 38m" + if (m || mm) return (m ? +m[1] * 60 : 0) + (mm ? +mm[1] : 0) + return Math.round(num(s) * 10) / 10 +} +const KM = { m: 0.001, km: 1, cm: 0.00001, in: 0.0000254, ft: 0.0003048, yd: 0.0009144, mi: 1.609344 } +const toKm = (v, unit) => num(v) * (KM[String(unit || 'km').toLowerCase().trim()] ?? 1) + +/* --------------------------------------------------------------- parse ---- */ + +/** + * Read an export into workouts openGym understands, WITHOUT touching state — the caller + * shows the summary for confirmation first. Nothing here throws on a bad row: a history + * of several thousand sets will contain oddities, and losing the file over one of them + * helps nobody. Bad rows are counted and reported instead. + */ +export function parseWorkoutCSV(text, { unit = 'kg' } = {}) { + const rows = parseCSV(text) + if (rows.length < 2) return { error: 'empty' } + const map = mapHeader(rows[0]) + const source = detectSource(rows[0]) + const dateCol = map.date !== undefined ? 'date' : map.startTime !== undefined ? 'startTime' : null + if (!dateCol || map.exercise === undefined) return { error: 'unrecognised' } + + const resolved = new Map() // exercise name -> dataset id | null, resolved once + const byDate = new Map() + const created = new Map() + const unmatched = new Set() + let sets = 0, skipped = 0, matched = 0, warmups = 0 + let sawLb = false, sawKg = false + + const cell = (r, f) => (map[f] === undefined ? '' : String(r[map[f]] ?? '').trim()) + + for (let i = 1; i < rows.length; i++) { + const r = rows[i] + const name = cell(r, 'exercise') + const when = parseWhen(cell(r, dateCol)) + if (!name || !when) { skipped++; continue } + + // explicit kg/lb columns beat a generic column plus a unit column + let w = 0, rowUnit = '' + if (map.weightKg !== undefined && cell(r, 'weightKg')) { w = num(cell(r, 'weightKg')); rowUnit = 'kg' } + else if (map.weightLb !== undefined && cell(r, 'weightLb')) { w = num(cell(r, 'weightLb')); rowUnit = 'lb' } + else { + w = num(cell(r, 'weight')) + const u = cell(r, 'weightUnit').toLowerCase() + rowUnit = u.startsWith('lb') ? 'lb' : u.startsWith('kg') ? 'kg' : '' + } + if (rowUnit === 'lb') sawLb = true + if (rowUnit === 'kg') sawKg = true + + const reps = Math.round(num(cell(r, 'reps'))) + const secs = num(cell(r, 'seconds')) + const mins = secs > 0 ? Math.round(secs / 60 * 10) / 10 : toMinutes(cell(r, 'time')) + const km = map.distanceKm !== undefined && cell(r, 'distanceKm') + ? num(cell(r, 'distanceKm')) + : toKm(cell(r, 'distance'), cell(r, 'distanceUnit')) + if (!w && !reps && !mins && !km) { skipped++; continue } + if (/warm/i.test(cell(r, 'setType'))) warmups++ + + const key = keyOf(name) + let id = resolved.get(key) + if (id === undefined) { id = matchExercise(name); resolved.set(key, id) } + if (id) matched++ + else { + let c = created.get(key) + if (!c) { + c = { + id: 'im' + uid(), n: name.toLowerCase(), custom: true, eq: 'custom', tg: '', desc: '', + bp: CATEGORY_BP[cell(r, 'category').toLowerCase()] || (km || (mins && !reps) ? 'cardio' : 'upper legs'), + } + created.set(key, c) + unmatched.add(name) + } + id = c.id + } + + const isCardio = (km > 0 || mins > 0) && !reps + const set = isCardio + ? { min: mins || 0, speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0, done: true } + : { w, r: reps || 0, done: true } + + let day = byDate.get(when.d) + if (!day) { + day = { ex: new Map(), name: cell(r, 'workoutName') || '', start: when.t, end: null } + byDate.set(when.d, day) + } + if (!day.name) day.name = cell(r, 'workoutName') || '' + if (map.endTime !== undefined) { const e = parseWhen(cell(r, 'endTime')); if (e && e.t != null) day.end = e.t } + else if (map.time !== undefined && !map.seconds && reps) { /* FitNotes' Time is per-set */ } + if (!day.ex.has(id)) day.ex.set(id, []) + day.ex.get(id).push(set) + sets++ + } + + // lb -> kg only when the file disagrees with the profile. The app never converts units + // on its own, so importing unconverted would silently rewrite someone's numbers. + const fileUnit = sawLb && !sawKg ? 'lb' : sawKg && !sawLb ? 'kg' : '' + const converted = !!fileUnit && fileUnit !== unit + const conv = converted + ? (fileUnit === 'lb' ? x => Math.round(x * LB_TO_KG * 10) / 10 : x => Math.round(x / LB_TO_KG * 10) / 10) + : x => x + + const dates = [...byDate.keys()].sort() + const workouts = dates.map(d => { + const day = byDate.get(d) + const entries = [...day.ex.entries()].map(([id, ss]) => { + const conv2 = ss.map(s => (s.w !== undefined ? { ...s, w: conv(s.w) } : s)) + const mx = Math.max(0, ...conv2.map(s => s.w || 0)) + return { id, sets: conv2, topW: mx || null } + }) + const base = new Date(d + 'T00:00:00').getTime() + const start = base + (day.start ?? 18 * 3600000) + const end = day.end != null ? base + day.end : start + const w = { + id: 'iw' + uid(), d, start, end: end > start ? end : start, + routineId: null, name: day.name || 'Imported', entries, prs: [], + } + w.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (s.w || 0) * (s.r || 0), 0), 0) + return w + }) + + return { + kind: 'workouts', source, workouts, customEx: [...created.values()], + matched, created: created.size, unmatchedNames: [...unmatched].sort(), + sets, skipped, warmups, fileUnit, converted, + from: dates[0] || null, to: dates[dates.length - 1] || null, + } +} + +/* ------------------------------------------------------- body weight ------ */ + +/** + * Body-weight history from Apple Health, or any CSV with a date and a weight. + * + * Health's own export is one big `export.xml` — often several hundred MB, nearly all of + * it step counts and heart rate. Building a DOM would blow up the tab, so the body-mass + * records are pulled out with a scan instead. Health writes weights in the unit the + * phone is set to and labels each record, so the unit is read per record. + */ +export function parseBodyweight(text, { unit = 'kg' } = {}) { + const s = String(text) + const out = new Map() // iso date -> { w, t } (one weigh-in per day, the last) + let fileUnit = '' + + if (s.includes('HKQuantityTypeIdentifierBodyMass')) { + const re = /]*type="HKQuantityTypeIdentifierBodyMass"[^>]*>/g + let m + while ((m = re.exec(s))) { + const tag = m[0] + const val = /value="([\d.]+)"/.exec(tag) + const dt = /startDate="([^"]+)"/.exec(tag) || /creationDate="([^"]+)"/.exec(tag) + const u = /unit="([^"]+)"/.exec(tag) + if (!val || !dt) continue + const when = parseWhen(dt[1]) + if (!when) continue + if (u) fileUnit = /lb/i.test(u[1]) ? 'lb' : 'kg' + out.set(when.d, { w: parseFloat(val[1]), t: new Date(dt[1]).getTime() || null }) + } + } else { + const rows = parseCSV(s) + if (rows.length < 2) return { error: 'empty' } + const map = mapHeader(rows[0]) + // a weight-only CSV: whichever weight column it has + const wCol = map.weightKg ?? map.weightLb ?? map.weight + const dCol = map.date ?? map.startTime + if (wCol === undefined || dCol === undefined) return { error: 'unrecognised' } + if (map.weightKg !== undefined) fileUnit = 'kg' + else if (map.weightLb !== undefined) fileUnit = 'lb' + for (let i = 1; i < rows.length; i++) { + const when = parseWhen(String(rows[i][dCol] ?? '')) + const w = num(rows[i][wCol]) + if (!when || !w) continue + out.set(when.d, { w, t: new Date(when.d).getTime() + (when.t ?? 0) }) + } + } + + if (!out.size) return { error: 'unrecognised' } + const converted = !!fileUnit && fileUnit !== unit + const conv = converted + ? (fileUnit === 'lb' ? x => Math.round(x * LB_TO_KG * 10) / 10 : x => Math.round(x / LB_TO_KG * 10) / 10) + : x => Math.round(x * 10) / 10 + const dates = [...out.keys()].sort() + return { + kind: 'bodyweight', source: 'Apple Health', + bodyweight: dates.map(d => ({ d, w: conv(out.get(d).w), t: out.get(d).t || new Date(d).getTime() })), + fileUnit, converted, from: dates[0], to: dates[dates.length - 1], + } +} + +/** Sniff the file and parse it as whatever it is. */ +export function parseImport(text, opts) { + const s = String(text) + if (s.includes('HKQuantityTypeIdentifier') || /^\s* b.d)) + const fresh = parsed.bodyweight.filter(b => !have.has(b.d)) + S.bodyweight = [...S.bodyweight, ...fresh].sort((a, b) => (a.d < b.d ? -1 : 1)) + return { added: fresh.length, skipped: parsed.bodyweight.length - fresh.length } + } + const have = new Set(S.workouts.map(w => w.d)) + const fresh = parsed.workouts.filter(w => !have.has(w.d)) + const used = new Set(fresh.flatMap(w => w.entries.map(e => e.id))) + const customs = parsed.customEx.filter(c => used.has(c.id) && !EXIDX[c.id]) + S.customEx = [...(S.customEx || []), ...customs] + S.workouts = [...S.workouts, ...fresh].sort((a, b) => (a.d < b.d ? -1 : 1)) + // seed the weight suggestions from the newest imported set of each lift + fresh.forEach(w => w.entries.forEach(e => { + const mx = Math.max(0, ...e.sets.map(s => s.w || 0), e.topW || 0) + if (mx > 0) { const cur = S.exWeights[e.id]; if (!cur || w.d >= cur.d) S.exWeights[e.id] = { w: mx, d: w.d } } + })) + return { added: fresh.length, skipped: parsed.workouts.length - fresh.length } +} diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 28fe80e..308e421 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -398,5 +398,24 @@ export default { 'Adductors': 'Adduktoren', 'Hip flexors': 'Hüftbeuger', 'Calves': 'Waden', - 'Shins': 'Schienbein' + 'Shins': 'Schienbein', + // --- import from another app --- + 'Import from another app': 'Aus anderer App importieren', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — oder Körpergewicht aus Apple Health', + 'Import from {0}': 'Aus {0} importieren', + 'Import history': 'Verlauf importieren', + 'Weigh-ins': 'Wiegungen', + 'Exercises matched': 'Übungen erkannt', + 'Added as your own': 'Als eigene angelegt', + 'The file is in {0} and your profile is in {1} — weights will be converted.': 'Die Datei ist in {0}, dein Profil in {1} — die Gewichte werden umgerechnet.', + 'The file does not say which unit it uses — numbers are imported as they are.': 'Die Datei nennt keine Einheit — die Zahlen werden unverändert übernommen.', + '{0} days already have data here and will be left alone.': '{0} Tage haben hier schon Daten und bleiben unangetastet.', + 'Not in the library — added as your own exercises': 'Nicht in der Bibliothek — als eigene Übungen angelegt', + 'Nothing new to import': 'Nichts Neues zu importieren', + '{0} workouts imported': '{0} Trainings importiert', + '{0} weigh-ins imported': '{0} Wiegungen importiert', + 'Could not read that file': 'Datei konnte nicht gelesen werden', + 'That file is empty': 'Diese Datei ist leer', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Die Spalten dieser Datei sind unbekannt — unterstützte Apps stehen in der Doku.', + 'Nothing to import from that file': 'Aus dieser Datei gibt es nichts zu importieren' } diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index fcf8827..9ca5b8e 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -380,5 +380,24 @@ export default { 'Adductors': 'Aductores', 'Hip flexors': 'Flexores de cadera', 'Calves': 'Gemelos', - 'Shins': 'Tibiales' + 'Shins': 'Tibiales', + // --- import from another app --- + 'Import from another app': 'Importar de otra app', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — o peso corporal de Apple Health', + 'Import from {0}': 'Importar de {0}', + 'Import history': 'Importar historial', + 'Weigh-ins': 'Pesajes', + 'Exercises matched': 'Ejercicios reconocidos', + 'Added as your own': 'Añadidos como propios', + 'The file is in {0} and your profile is in {1} — weights will be converted.': 'El archivo está en {0} y tu perfil en {1} — los pesos se convertirán.', + 'The file does not say which unit it uses — numbers are imported as they are.': 'El archivo no indica la unidad — los números se importan tal cual.', + '{0} days already have data here and will be left alone.': '{0} días ya tienen datos aquí y no se tocarán.', + 'Not in the library — added as your own exercises': 'No están en la biblioteca — añadidos como ejercicios propios', + 'Nothing new to import': 'Nada nuevo que importar', + '{0} workouts imported': '{0} entrenamientos importados', + '{0} weigh-ins imported': '{0} pesajes importados', + 'Could not read that file': 'No se pudo leer ese archivo', + 'That file is empty': 'Ese archivo está vacío', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'No se reconocen las columnas del archivo — consulta la documentación.', + 'Nothing to import from that file': 'No hay nada que importar de ese archivo' } diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index f5f1e06..8ff8a55 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -380,5 +380,24 @@ export default { 'Adductors': 'Adducteurs', 'Hip flexors': 'Fléchisseurs de hanche', 'Calves': 'Mollets', - 'Shins': 'Tibiaux' + 'Shins': 'Tibiaux', + // --- import from another app --- + 'Import from another app': 'Importer depuis une autre app', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — ou le poids depuis Apple Santé', + 'Import from {0}': 'Importer depuis {0}', + 'Import history': 'Importer l\'historique', + 'Weigh-ins': 'Pesées', + 'Exercises matched': 'Exercices reconnus', + 'Added as your own': 'Ajoutés comme les vôtres', + 'The file is in {0} and your profile is in {1} — weights will be converted.': 'Le fichier est en {0} et votre profil en {1} — les poids seront convertis.', + 'The file does not say which unit it uses — numbers are imported as they are.': 'Le fichier n\'indique pas l\'unité — les nombres sont importés tels quels.', + '{0} days already have data here and will be left alone.': '{0} jours ont déjà des données ici et ne seront pas touchés.', + 'Not in the library — added as your own exercises': 'Absents de la bibliothèque — ajoutés comme vos exercices', + 'Nothing new to import': 'Rien de nouveau à importer', + '{0} workouts imported': '{0} séances importées', + '{0} weigh-ins imported': '{0} pesées importées', + 'Could not read that file': 'Impossible de lire ce fichier', + 'That file is empty': 'Ce fichier est vide', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colonnes non reconnues — voir la documentation pour les apps prises en charge.', + 'Nothing to import from that file': 'Rien à importer depuis ce fichier' } diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 72daaab..383ccc7 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -380,5 +380,24 @@ export default { 'Adductors': 'एडक्टर', 'Hip flexors': 'हिप फ्लेक्सर', 'Calves': 'पिंडली', - 'Shins': 'पिंडली की हड्डी' + 'Shins': 'पिंडली की हड्डी', + // --- import from another app --- + 'Import from another app': 'दूसरे ऐप से आयात करें', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — या Apple Health से वज़न', + 'Import from {0}': '{0} से आयात करें', + 'Import history': 'इतिहास आयात करें', + 'Weigh-ins': 'वज़न मापन', + 'Exercises matched': 'पहचाने गए व्यायाम', + 'Added as your own': 'अपने रूप में जोड़े', + 'The file is in {0} and your profile is in {1} — weights will be converted.': 'फ़ाइल {0} में है और आपकी प्रोफ़ाइल {1} में — वज़न बदले जाएंगे।', + 'The file does not say which unit it uses — numbers are imported as they are.': 'फ़ाइल में इकाई नहीं दी — संख्याएँ जस की तस आयात होंगी।', + '{0} days already have data here and will be left alone.': '{0} दिनों में पहले से डेटा है, वे अछूते रहेंगे।', + 'Not in the library — added as your own exercises': 'लाइब्रेरी में नहीं — अपने व्यायाम के रूप में जोड़े गए', + 'Nothing new to import': 'आयात करने को कुछ नया नहीं', + '{0} workouts imported': '{0} वर्कआउट आयात हुए', + '{0} weigh-ins imported': '{0} वज़न रिकॉर्ड आयात हुए', + 'Could not read that file': 'वह फ़ाइल पढ़ी नहीं जा सकी', + 'That file is empty': 'वह फ़ाइल खाली है', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'फ़ाइल के कॉलम पहचाने नहीं गए — समर्थित ऐप्स के लिए दस्तावेज़ देखें।', + 'Nothing to import from that file': 'उस फ़ाइल से आयात करने को कुछ नहीं' } diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index ccd3912..aced745 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -380,5 +380,24 @@ export default { 'Adductors': 'Adduttori', 'Hip flexors': 'Flessori dell\'anca', 'Calves': 'Polpacci', - 'Shins': 'Tibiali' + 'Shins': 'Tibiali', + // --- import from another app --- + 'Import from another app': 'Importa da un\'altra app', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — o il peso da Apple Salute', + 'Import from {0}': 'Importa da {0}', + 'Import history': 'Importa lo storico', + 'Weigh-ins': 'Pesate', + 'Exercises matched': 'Esercizi riconosciuti', + 'Added as your own': 'Aggiunti come tuoi', + 'The file is in {0} and your profile is in {1} — weights will be converted.': 'Il file è in {0} e il tuo profilo in {1} — i pesi verranno convertiti.', + 'The file does not say which unit it uses — numbers are imported as they are.': 'Il file non indica l\'unità — i numeri vengono importati così come sono.', + '{0} days already have data here and will be left alone.': '{0} giorni hanno già dati qui e non verranno toccati.', + 'Not in the library — added as your own exercises': 'Non nella libreria — aggiunti come tuoi esercizi', + 'Nothing new to import': 'Niente di nuovo da importare', + '{0} workouts imported': '{0} allenamenti importati', + '{0} weigh-ins imported': '{0} pesate importate', + 'Could not read that file': 'Impossibile leggere il file', + 'That file is empty': 'Il file è vuoto', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colonne non riconosciute — vedi la documentazione per le app supportate.', + 'Nothing to import from that file': 'Niente da importare da questo file' } diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index cbda2ac..f6d3a70 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -380,5 +380,24 @@ export default { 'Adductors': '내전근', 'Hip flexors': '고관절 굴곡근', 'Calves': '종아리', - 'Shins': '정강이' + 'Shins': '정강이', + // --- import from another app --- + 'Import from another app': '다른 앱에서 가져오기', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — 또는 Apple 건강의 체중', + 'Import from {0}': '{0}에서 가져오기', + 'Import history': '기록 가져오기', + 'Weigh-ins': '체중 기록', + 'Exercises matched': '인식된 운동', + 'Added as your own': '내 운동으로 추가', + 'The file is in {0} and your profile is in {1} — weights will be converted.': '파일은 {0}, 프로필은 {1} — 무게가 변환됩니다.', + 'The file does not say which unit it uses — numbers are imported as they are.': '파일에 단위가 없습니다 — 숫자를 그대로 가져옵니다.', + '{0} days already have data here and will be left alone.': '{0}일은 이미 데이터가 있어 그대로 둡니다.', + 'Not in the library — added as your own exercises': '라이브러리에 없음 — 내 운동으로 추가됨', + 'Nothing new to import': '가져올 새 항목이 없습니다', + '{0} workouts imported': '운동 {0}개를 가져왔습니다', + '{0} weigh-ins imported': '체중 기록 {0}개를 가져왔습니다', + 'Could not read that file': '파일을 읽을 수 없습니다', + 'That file is empty': '파일이 비어 있습니다', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': '열을 인식할 수 없습니다 — 지원 앱은 문서를 참고하세요.', + 'Nothing to import from that file': '이 파일에서 가져올 내용이 없습니다' } diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 7d32fb1..7f265b9 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -380,5 +380,24 @@ export default { 'Adductors': 'Przywodziciele', 'Hip flexors': 'Zginacze bioder', 'Calves': 'Łydki', - 'Shins': 'Piszczele' + 'Shins': 'Piszczele', + // --- import from another app --- + 'Import from another app': 'Importuj z innej aplikacji', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — albo masa ciała z Apple Health', + 'Import from {0}': 'Importuj z {0}', + 'Import history': 'Importuj historię', + 'Weigh-ins': 'Ważenia', + 'Exercises matched': 'Rozpoznane ćwiczenia', + 'Added as your own': 'Dodane jako własne', + 'The file is in {0} and your profile is in {1} — weights will be converted.': 'Plik jest w {0}, a Twój profil w {1} — ciężary zostaną przeliczone.', + 'The file does not say which unit it uses — numbers are imported as they are.': 'Plik nie podaje jednostki — liczby zostaną zaimportowane bez zmian.', + '{0} days already have data here and will be left alone.': '{0} dni ma już tutaj dane i pozostanie bez zmian.', + 'Not in the library — added as your own exercises': 'Brak w bibliotece — dodane jako własne ćwiczenia', + 'Nothing new to import': 'Brak nowych danych do importu', + '{0} workouts imported': 'Zaimportowano {0} treningów', + '{0} weigh-ins imported': 'Zaimportowano {0} ważeń', + 'Could not read that file': 'Nie udało się odczytać pliku', + 'That file is empty': 'Ten plik jest pusty', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Nie rozpoznano kolumn — obsługiwane aplikacje znajdziesz w dokumentacji.', + 'Nothing to import from that file': 'Brak danych do importu z tego pliku' } diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 09a28f9..cb427f7 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -380,5 +380,24 @@ export default { 'Adductors': 'Adutores', 'Hip flexors': 'Flexores do quadril', 'Calves': 'Panturrilhas', - 'Shins': 'Tibiais' + 'Shins': 'Tibiais', + // --- import from another app --- + 'Import from another app': 'Importar de outra app', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — ou o peso da Apple Saúde', + 'Import from {0}': 'Importar de {0}', + 'Import history': 'Importar histórico', + 'Weigh-ins': 'Pesagens', + 'Exercises matched': 'Exercícios reconhecidos', + 'Added as your own': 'Adicionados como teus', + 'The file is in {0} and your profile is in {1} — weights will be converted.': 'O ficheiro está em {0} e o teu perfil em {1} — os pesos serão convertidos.', + 'The file does not say which unit it uses — numbers are imported as they are.': 'O ficheiro não indica a unidade — os números são importados tal como estão.', + '{0} days already have data here and will be left alone.': '{0} dias já têm dados aqui e não serão tocados.', + 'Not in the library — added as your own exercises': 'Não estão na biblioteca — adicionados como exercícios teus', + 'Nothing new to import': 'Nada de novo para importar', + '{0} workouts imported': '{0} treinos importados', + '{0} weigh-ins imported': '{0} pesagens importadas', + 'Could not read that file': 'Não foi possível ler o ficheiro', + 'That file is empty': 'Esse ficheiro está vazio', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colunas não reconhecidas — vê a documentação para apps suportadas.', + 'Nothing to import from that file': 'Nada para importar desse ficheiro' } diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 5fa7e55..9242278 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -380,5 +380,24 @@ export default { 'Adductors': 'Приводящие', 'Hip flexors': 'Сгибатели бедра', 'Calves': 'Икры', - 'Shins': 'Голени' + 'Shins': 'Голени', + // --- import from another app --- + 'Import from another app': 'Импорт из другого приложения', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — или вес из Apple Health', + 'Import from {0}': 'Импорт из {0}', + 'Import history': 'Импорт истории', + 'Weigh-ins': 'Взвешивания', + 'Exercises matched': 'Распознано упражнений', + 'Added as your own': 'Добавлено как свои', + 'The file is in {0} and your profile is in {1} — weights will be converted.': 'Файл в {0}, а профиль в {1} — веса будут пересчитаны.', + 'The file does not say which unit it uses — numbers are imported as they are.': 'В файле не указана единица — числа импортируются как есть.', + '{0} days already have data here and will be left alone.': 'В {0} дней уже есть данные — они останутся без изменений.', + 'Not in the library — added as your own exercises': 'Нет в библиотеке — добавлены как свои упражнения', + 'Nothing new to import': 'Нечего импортировать', + '{0} workouts imported': 'Импортировано тренировок: {0}', + '{0} weigh-ins imported': 'Импортировано взвешиваний: {0}', + 'Could not read that file': 'Не удалось прочитать файл', + 'That file is empty': 'Файл пуст', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Колонки не распознаны — список поддерживаемых приложений в документации.', + 'Nothing to import from that file': 'В этом файле нечего импортировать' } diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 07298fd..40f6a64 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -380,5 +380,24 @@ export default { 'Adductors': 'Adduktörler', 'Hip flexors': 'Kalça fleksörleri', 'Calves': 'Baldırlar', - 'Shins': 'İncik' + 'Shins': 'İncik', + // --- import from another app --- + 'Import from another app': 'Başka uygulamadan içe aktar', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — veya Apple Health\'ten vücut ağırlığı', + 'Import from {0}': '{0} uygulamasından içe aktar', + 'Import history': 'Geçmişi içe aktar', + 'Weigh-ins': 'Tartımlar', + 'Exercises matched': 'Eşleşen egzersizler', + 'Added as your own': 'Kendi egzersizin olarak eklendi', + 'The file is in {0} and your profile is in {1} — weights will be converted.': 'Dosya {0}, profilin {1} — ağırlıklar dönüştürülecek.', + 'The file does not say which unit it uses — numbers are imported as they are.': 'Dosya birimi belirtmiyor — sayılar olduğu gibi aktarılıyor.', + '{0} days already have data here and will be left alone.': '{0} günde zaten veri var, bunlara dokunulmayacak.', + 'Not in the library — added as your own exercises': 'Kütüphanede yok — kendi egzersizlerin olarak eklendi', + 'Nothing new to import': 'İçe aktarılacak yeni bir şey yok', + '{0} workouts imported': '{0} antrenman içe aktarıldı', + '{0} weigh-ins imported': '{0} tartım içe aktarıldı', + 'Could not read that file': 'Dosya okunamadı', + 'That file is empty': 'Bu dosya boş', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Sütunlar tanınmadı — desteklenen uygulamalar için belgelere bak.', + 'Nothing to import from that file': 'Bu dosyada içe aktarılacak bir şey yok' } diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 648f5f0..48bbfcb 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -380,5 +380,24 @@ export default { 'Adductors': '内收肌', 'Hip flexors': '髋屈肌', 'Calves': '小腿', - 'Shins': '胫前肌' + 'Shins': '胫前肌', + // --- import from another app --- + 'Import from another app': '从其他应用导入', + 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes、Strong、Hevy — 或来自 Apple 健康的体重', + 'Import from {0}': '从 {0} 导入', + 'Import history': '导入历史记录', + 'Weigh-ins': '称重记录', + 'Exercises matched': '已匹配动作', + 'Added as your own': '添加为自定义', + 'The file is in {0} and your profile is in {1} — weights will be converted.': '文件使用 {0},你的配置使用 {1} — 重量将被换算。', + 'The file does not say which unit it uses — numbers are imported as they are.': '文件未标明单位 — 数字按原样导入。', + '{0} days already have data here and will be left alone.': '有 {0} 天已存在数据,将保持不变。', + 'Not in the library — added as your own exercises': '不在动作库中 — 已添加为自定义动作', + 'Nothing new to import': '没有新内容可导入', + '{0} workouts imported': '已导入 {0} 次训练', + '{0} weigh-ins imported': '已导入 {0} 条称重记录', + 'Could not read that file': '无法读取该文件', + 'That file is empty': '该文件是空的', + 'That file\'s columns aren\'t recognised — see the docs for supported apps.': '无法识别该文件的列 — 支持的应用请见文档。', + 'Nothing to import from that file': '该文件中没有可导入的内容' } diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 14c9ae7..677f7d2 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -15,6 +15,7 @@ import { Button, Slider } from './components/ui.jsx' import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js' import BodyMap from './components/BodyMap.jsx' import { loadOfWorkouts } from './lib/muscles.js' +import { parseImport, mergeImport } from './lib/import-csv.js' const S = () => useStore.getState().S const update = (...a) => useStore.getState().update(...a) @@ -120,6 +121,90 @@ export function bwSheet(opts = {}) { return h } +/* ============================ import from another app ============================ */ +// Shows what a parsed export would actually do before anything is written. An import is +// the one action where "just try it" is expensive — it's someone's entire training +// history — so the numbers, the unit conversion and the exercises we couldn't recognise +// are all on screen before the confirm button. +function ImportSummary({ parsed, close }) { + const st = useStore(s => s.S) + const isBW = parsed.kind === 'bodyweight' + const have = isBW + ? parsed.bodyweight.filter(b => st.bodyweight.some(x => x.d === b.d)).length + : parsed.workouts.filter(w => st.workouts.some(x => x.d === w.d)).length + const fresh = (isBW ? parsed.bodyweight.length : parsed.workouts.length) - have + + const doImport = () => { + let res + update(s => { res = mergeImport(s, parsed) }) + close() + toast(isBW + ? t('{0} weigh-ins imported', res.added) + : t('{0} workouts imported', res.added)) + } + + return <> +

{parsed.source ? t('Import from {0}', parsed.source) : t('Import history')}

+
+ {parsed.from === parsed.to ? fmtDate(parsed.from, true) : fmtDate(parsed.from, true) + ' – ' + fmtDate(parsed.to, true)} +
+ +
+ {isBW ? <> +
{t('Weigh-ins')}
{parsed.bodyweight.length}
+
{t('New')}
{fresh}
+ : <> +
{t('Workouts')}
{parsed.workouts.length}
+
{t('Sets')}
{parsed.sets}
+
{t('Exercises matched')}
{parsed.matched}
+
{t('Added as your own')}
{parsed.created}
+ } +
+ + {parsed.converted &&
+ {t('The file is in {0} and your profile is in {1} — weights will be converted.', parsed.fileUnit, st.unit)} +
} + {!isBW && !parsed.fileUnit &&
+ {t('The file does not say which unit it uses — numbers are imported as they are.')} +
} + {have > 0 &&
+ {t('{0} days already have data here and will be left alone.', have)} +
} + {!isBW && parsed.unmatchedNames.length > 0 && <> +

{t('Not in the library — added as your own exercises')}

+
+ {parsed.unmatchedNames.slice(0, 12).map(n => {n})} + {parsed.unmatchedNames.length > 12 && +{parsed.unmatchedNames.length - 12}} +
+ } + + +
+ + +} + +/** Read a CSV/XML export, then show what it would do. */ +export function importFromApp(file, onDone) { + const rd = new FileReader() + rd.onload = () => { + let parsed + try { parsed = parseImport(String(rd.result), { unit: S().unit }) } + catch (e) { toast(t('Could not read that file')); return } + if (parsed.error === 'empty') { toast(t('That file is empty')); return } + if (parsed.error) { toast(t("That file's columns aren't recognised — see the docs for supported apps.")); return } + if (parsed.kind === 'bodyweight' ? !parsed.bodyweight.length : !parsed.workouts.length) { + toast(t('Nothing to import from that file')); return + } + ui().openSheet(close => ) + onDone && onDone() + } + rd.onerror = () => toast(t('Could not read that file')) + rd.readAsText(file) +} + /* ============================ target weight ============================ */ export function bwDeltaColor(delta, currentW) { if (!delta) return 'var(--label-2)' diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index 92b7b07..e72f479 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -7,7 +7,7 @@ import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/ap import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js' import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js' import { DEMO, REPO } from '../lib/demo.js' -import { loadStarterPlan, confirmSheet } from '../sheets.jsx' +import { loadStarterPlan, confirmSheet, importFromApp } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx' @@ -18,6 +18,7 @@ export default function Settings() { const { update, replaceState, setUser, pullState, pushState, signOut, resetDemo } = useStore() const toast = useUI(s => s.toast) const fileRef = useRef(null) + const importRef = useRef(null) const doExport = () => { const blob = new Blob([JSON.stringify(S, null, 2)], { type: 'application/json' }) @@ -128,10 +129,16 @@ export default function Settings() {
fileRef.current.click()} /> + importRef.current.click()} /> confirmSheet({ title: t('Reset everything?'), message: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'), confirmText: t('Delete everything'), danger: true, onConfirm: () => { replaceState(JSON.parse(JSON.stringify(DEF)), true); nav('/home'); toast(t('All data reset')) } })} />
+ {/* Reset after reading so picking the same file twice still fires onChange. */} + { const f = ev.target.files[0]; if (f) importFromApp(f); ev.target.value = '' }} />