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.

feat(measurements): unitless custom fields, units in the body CSV and measurements in its import (#718, #699)

Duarte Santos7c6fd6682660
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 50ebfa2ee..c2ce3d1a9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -90,6 +90,11 @@ per muscle. Settings → Workout → Fine-tuning turns it off.
light day keep their own numbers.
- **Deleted a weigh-in by mistake? Undo.** Deleting one now shows a toast with Undo, on the log
sheet and in All weigh-ins, and the weigh-in comes back as if nothing happened (#756).
+- **Custom measurements get their own unit** (#699, #718, thanks @zykll18). Muscle ratio in %,
+ lean mass in kg or lb, a calf in cm or in, or no unit at all for a visceral fat score. The chart,
+ the history and backups keep it, and your old custom fields stay in cm like before. The body
+ CSV export says each field's unit in its column, and importing that file now brings the
+ measurements back too, not just the weigh-ins.
**Security.** Follow-ups to v1.4.2's audit.
- **Pairing the phone app asks you to confirm it's you** (passkey, or your password where that
diff --git a/CLAUDE.md b/CLAUDE.md
index f10fe35e2..b97640e4e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -95,12 +95,13 @@ machine, never in CI (see "Exercise media" below and docs/APP_STORES.md).
session back, is a pure helper here with a unit test beside it.**
- **Body measurements (`lib/measurements.js`, `views/Measurements.jsx`)**: one check-in per day.
Built-in circumferences and legacy custom fields store cm and follow the profile's cm/in
- display. Custom definitions may specify `unit: 'cm' | 'in' | '%' | 'kg' | 'lb'`; that
+ display. Custom definitions may specify `unit: 'cm' | 'in' | '%' | 'kg' | 'lb' | 'none'`; that
display choice stays fixed when the profile switches kg/lb. Custom values store canonical cm, kg
- (to 0.001 kg so a tenth of a pound round-trips), or percent (0 to 100). Each
+ (to 0.001 kg so a tenth of a pound round-trips), percent (0 to 100) or a plain number. Each
custom reading also carries its unit, preserving its meaning in backups without definitions.
Once values exist, the unit selector permits cm/in or kg/lb conversions within the recorded
- type; a different type needs a new field.
+ type; a different type needs a new field. The body CSV names a custom column with its unit,
+ "Muscle ratio (%)", and the importer reads those columns back (only from our own header).
- **`views/`**: one file per screen, routed by `react-router-dom` from `App.jsx`.
- **`sheets.jsx`**: the bottom sheets (exercise picker, exercise config, workout detail, plan
import...). It is large; a new sheet can go into `components/` as its own file.
diff --git a/frontend/src/lib/export-csv.js b/frontend/src/lib/export-csv.js
index 54f4dd952..acb4ca990 100644
--- a/frontend/src/lib/export-csv.js
+++ b/frontend/src/lib/export-csv.js
@@ -13,7 +13,7 @@
import { EXIDX } from './exercises.js'
import { capWords } from './format.js'
-import { MEASUREMENT_FIELDS } from './measurements.js'
+import { MEASUREMENT_FIELDS, builtinCsvColumn, customCsvColumn, customDisplayValue } from './measurements.js'
import { hasCompletedWork, isWarmupRow, isFailureSet, isSideSet, dropsOf } from './workout-model.js'
import { workoutDay } from './history.js'
@@ -125,7 +125,8 @@ export const workoutsCSV = (S, range) => csvText(WORKOUT_COLUMNS, workoutRows(S,
/**
* 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.
+ * stored, body fat in percent. Custom measurement fields get a column each, under their own name
+ * with their unit in brackets and their values in it (#718; lib/measurements.js customCsvColumn).
*/
export function bodyCSV(S, { from = null, to = null } = {}) {
const unit = S.unit === 'lb' ? 'lb' : 'kg'
@@ -135,15 +136,20 @@ export function bodyCSV(S, { from = null, to = null } = {}) {
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))
+ // The field's own name and unit where it still exists, else what the reading carries.
+ const defs = new Map((S.customMeasurements || []).filter(c => c?.id).map(c => [c.id, c]))
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()]
+ for (const v of days.values()) for (const o of v.m?.other || []) {
+ if (!o?.id || o.value == null || custom.has(o.id)) continue
+ const def = defs.get(o.id)
+ custom.set(o.id, { name: def?.name || o.name || 'Other', unit: def?.unit || o.unit })
+ }
+ const header = ['date', 'weight_' + unit, ...fields.map(builtinCsvColumn),
+ ...[...custom.values()].map(c => customCsvColumn(c.name, c.unit))]
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) : '' })]
+ ...[...custom].map(([id, c]) => { const o = (m?.other || []).find(x => x?.id === id); return o?.value != null ? n(customDisplayValue(o.value, c.unit)) : '' })]
})
return csvText(header, rows)
}
diff --git a/frontend/src/lib/export-csv.test.js b/frontend/src/lib/export-csv.test.js
index dbf01369a..5baeebcd5 100644
--- a/frontend/src/lib/export-csv.test.js
+++ b/frontend/src/lib/export-csv.test.js
@@ -208,7 +208,7 @@ describe('the body CSV', () => {
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[0]).toEqual(['date', 'weight_kg', 'waist_cm', 'upper_arm_left_cm', 'body_fat_percent', 'Neck, relaxed (cm)'])
expect(rows.slice(1)).toEqual([
['2026-03-01', '80.4', '', '', '', ''],
['2026-03-04', '80.1', '84.5', '36', '17.2', '39'],
diff --git a/frontend/src/lib/import-csv.js b/frontend/src/lib/import-csv.js
index ca476926a..1be362f45 100644
--- a/frontend/src/lib/import-csv.js
+++ b/frontend/src/lib/import-csv.js
@@ -23,6 +23,10 @@
import { EXDB, EXIDX, canonicalExId, isCardio as isCardioEx } from './exercises.js'
import { uid } from './format.js'
+import {
+ MEASUREMENT_FIELDS, builtinCsvColumn, parseCustomCsvColumn, fromCsvUnit, sameMeasurementKind,
+ emptyMeasurement, measurementEntryHasValues, normalizeMeasurementEntry, normalizeMeasurementsState,
+} from './measurements.js'
import { isWarmupRow, completedVolumeOf, syncSideAggregate } from './workout-model.js'
import { HEVY_TITLE_MAP } from './hevy-id-map.js'
import { clampIncline, inclineFrom } from './incline.js'
@@ -790,7 +794,7 @@ export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
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 = '', source = 'Apple Health'
+ let fileUnit = '', source = 'Apple Health', measurements = []
if (s.includes('HKQuantityTypeIdentifierBodyMass')) {
const re = /<Record[^>]*type="HKQuantityTypeIdentifierBodyMass"[^>]*>/g
@@ -835,6 +839,7 @@ export function parseBodyweight(text, { unit = 'kg' } = {}) {
const wCol = map.weightKg ?? map.weightLb ?? map.weight
const dCol = map.date ?? map.startTime
if (wCol === undefined || dCol === undefined) return { error: 'unrecognised' }
+ measurements = bodyCsvMeasurements(rows)
if (map.weightKg !== undefined) fileUnit = 'kg'
else if (map.weightLb !== undefined) fileUnit = 'lb'
for (let i = 1; i < rows.length; i++) {
@@ -845,13 +850,39 @@ export function parseBodyweight(text, { unit = 'kg' } = {}) {
}
}
- return finishBodyweight(out, unit, source, fileUnit)
+ return finishBodyweight(out, unit, source, fileUnit, measurements)
+}
+
+// Our own body CSV (lib/export-csv.js bodyCSV) carries the measurements too (#718): a column per
+// built-in field (`waist_cm`) and per custom field ("Muscle ratio (%)", lib/measurements.js). Only
+// a file with our header is read this way, so another app's Notes column never turns into a
+// measurement. Values stay in their column's unit here; mergeImport files them.
+function bodyCsvMeasurements(rows) {
+ const head = rows[0].map(h => String(h ?? '').trim())
+ if (head[0]?.toLowerCase() !== 'date' || !/^weight_(kg|lb)$/.test(head[1] || '')) return []
+ const builtin = new Map(MEASUREMENT_FIELDS.map(f => [builtinCsvColumn(f), f.key]))
+ const cols = head.slice(2).map((h, i) => builtin.has(h) ? { i: i + 2, key: builtin.get(h) } : { i: i + 2, ...parseCustomCsvColumn(h) })
+ .filter(c => c.key || c.name)
+ const days = []
+ for (const r of rows.slice(1)) {
+ const when = parseWhen(String(r[0] ?? ''))
+ if (!when) continue
+ const values = {}, other = []
+ for (const c of cols) {
+ const raw = String(r[c.i] ?? '').trim()
+ const v = parseFloat(raw.replace(',', '.'))
+ if (raw === '' || !Number.isFinite(v)) continue
+ if (c.key) values[c.key] = v; else other.push({ name: c.name, unit: c.unit, value: v })
+ }
+ if (Object.keys(values).length || other.length) days.push({ d: when.d, values, other })
+ }
+ return days
}
/** The weigh-ins collected per day, converted to `unit` — each in its own record's unit if it
- * had one, else the file's. */
-function finishBodyweight(out, unit, source, fileUnit = '') {
- if (!out.size) return { error: 'unrecognised' }
+ * had one, else the file's. Measurements from our own body CSV ride along as they are. */
+function finishBodyweight(out, unit, source, fileUnit = '', measurements = []) {
+ if (!out.size && !measurements.length) return { error: 'unrecognised' }
const units = new Set([...out.values()].map(b => b.unit || fileUnit).filter(Boolean))
fileUnit = [...units].sort().join(' / ')
const converted = [...units].some(sourceUnit => sourceUnit !== unit)
@@ -863,16 +894,55 @@ function finishBodyweight(out, unit, source, fileUnit = '') {
return roundWeight(w)
}
const dates = [...out.keys()].sort()
+ const all = [...new Set([...dates, ...measurements.map(m => m.d)])].sort()
return {
kind: 'bodyweight', source,
bodyweight: dates.map(d => ({ d, w: conv(out.get(d)), t: out.get(d).t || new Date(d).getTime() })),
- fileUnit, converted, from: dates[0], to: dates[dates.length - 1],
+ ...(measurements.length ? { measurements } : {}),
+ fileUnit, converted, from: all[0], to: all[all.length - 1],
}
}
/** A weigh-in a person could have: above zero and below MAX_BODY_KG in the given unit. */
const bodyOk = (w, u) => w > 0 && w <= (u === 'lb' ? MAX_BODY_KG / LB_TO_KG : MAX_BODY_KG)
+/**
+ * Measurements read from our own body CSV (bodyCsvMeasurements), into state the way weigh-ins
+ * go: a day that already has a check-in keeps it. A custom column goes to the field of the same
+ * name, made with the column's unit if there is none; one whose unit is another kind than that
+ * field's (kg into a % field) is left out rather than relabelled. Returns how many days came in.
+ */
+function mergeMeasurements(S, days) {
+ normalizeMeasurementsState(S)
+ const have = new Set(S.measurements.map(e => e.d))
+ const fresh = days.filter(m => !have.has(m.d))
+ const byName = new Map(S.customMeasurements.map(c => [c.name.toLowerCase(), c]))
+ for (const m of fresh) for (const o of m.other) {
+ if (byName.has(o.name.toLowerCase())) continue
+ const field = { id: uid(), name: o.name.slice(0, 60), enabled: true, unit: o.unit }
+ S.customMeasurements.push(field)
+ byName.set(o.name.toLowerCase(), field)
+ }
+ let n = 0
+ for (const m of fresh) {
+ const entry = emptyMeasurement(m.d, S.customMeasurements)
+ for (const [key, v] of Object.entries(m.values)) entry[key] = v
+ for (const o of m.other) {
+ const field = byName.get(o.name.toLowerCase())
+ if (!sameMeasurementKind(field.unit, o.unit)) continue
+ const item = entry.other.find(x => x.id === field.id)
+ if (item) item.value = fromCsvUnit(o.value, o.unit)
+ }
+ // Normalizing drops what no field could hold (a 140 % or a negative); nothing left, no day.
+ const clean = normalizeMeasurementEntry(entry, S.customMeasurements)
+ if (!measurementEntryHasValues(clean)) continue
+ S.measurements.push(clean)
+ n++
+ }
+ normalizeMeasurementsState(S)
+ return n
+}
+
/** Sniff the file and parse it as whatever it is. */
export function parseImport(text, opts) {
const s = String(text)
@@ -898,7 +968,9 @@ export function mergeImport(S, parsed) {
// Connect (lib/health-connect.js healthRecords), where it would land a second time.
const fresh = parsed.bodyweight.filter(b => !have.has(b.d)).map(b => ({ ...b, src: b.src || 'import' }))
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 res = { added: fresh.length, skipped: parsed.bodyweight.length - fresh.length }
+ if (parsed.measurements?.length) res.measurements = mergeMeasurements(S, parsed.measurements)
+ return res
}
const have = new Set(S.workouts.map(w => w.d))
// Every parse invents fresh ids for the names it cannot match, and a later export of the same
diff --git a/frontend/src/lib/measurements-csv.test.js b/frontend/src/lib/measurements-csv.test.js
new file mode 100644
index 000000000..9eeb8875c
--- /dev/null
+++ b/frontend/src/lib/measurements-csv.test.js
@@ -0,0 +1,104 @@
+import { describe, expect, it } from 'vitest'
+import { bodyCSV } from './export-csv.js'
+import { parseCSV, parseBodyweight, parseImport, mergeImport } from './import-csv.js'
+import {
+ CUSTOM_MEASUREMENT_UNITS, fromMeasurementDisplay, measurementSeries, measurementUnitLabel,
+ normalizeMeasurementsState, parseCustomCsvColumn,
+} from './measurements.js'
+
+// #718 follow-ups: a unitless custom field (a score, a count), and the units travelling through
+// the body CSV both ways, so an export read back into a fresh profile means the same thing.
+const custom = [
+ { id: 'ratio', name: 'Muscle ratio', unit: '%', enabled: true },
+ { id: 'lean', name: 'Lean mass', unit: 'lb', enabled: true },
+ { id: 'knee', name: 'Knee', enabled: true },
+ { id: 'visc', name: 'Visceral fat', unit: 'none', enabled: true },
+]
+const state = () => normalizeMeasurementsState({
+ unit: 'kg', bodyweight: [{ d: '2026-10-01', w: 80, t: 1 }], customMeasurements: structuredClone(custom),
+ measurements: [{ d: '2026-10-01', waist: 84.5, other: [
+ { id: 'ratio', value: 40.5, unit: '%' }, { id: 'lean', value: 60, unit: 'lb' },
+ { id: 'knee', value: 38.1 }, { id: 'visc', value: 0, unit: 'none' },
+ ] }],
+})
+
+describe('a custom measurement without a unit', () => {
+ it('is one of the units, shows no label and keeps a zero', () => {
+ expect(CUSTOM_MEASUREMENT_UNITS).toContain('none')
+ expect(measurementUnitLabel('none')).toBe('')
+ expect(fromMeasurementDisplay(0, 'kg', { unit: 'none' })).toBe(0)
+ expect(fromMeasurementDisplay(12, 'lb', { unit: 'none' })).toBe(12)
+ const S = state()
+ expect(S.measurements[0].other.find(o => o.id === 'visc')).toMatchObject({ value: 0, unit: 'none' })
+ expect(measurementSeries({ ...S, unit: 'lb' }, 'other:visc').map(p => p.y)).toEqual([0])
+ })
+})
+
+describe('the body CSV with custom units (#718)', () => {
+ const text = bodyCSV(state())
+ const rows = parseCSV(text)
+
+ it('says each custom field\'s unit in its column and writes the values in it', () => {
+ expect(rows[0]).toEqual(['date', 'weight_kg', 'waist_cm', 'Muscle ratio (%)', 'Lean mass (lb)', 'Knee (cm)', 'Visceral fat'])
+ expect(rows[1]).toEqual(['2026-10-01', '80', '84.5', '40.5', '132.3', '38.1', '0'])
+ })
+
+ it('reads the columns back apart', () => {
+ expect(parseCustomCsvColumn('Lean mass (lb)')).toEqual({ name: 'Lean mass', unit: 'lb' })
+ expect(parseCustomCsvColumn('Visceral fat')).toEqual({ name: 'Visceral fat', unit: 'none' })
+ })
+
+ it('brings measurements back into a fresh profile with the same fields and units', () => {
+ const parsed = parseImport(text, { unit: 'kg' })
+ expect(parsed.kind).toBe('bodyweight')
+ expect(parsed.measurements).toHaveLength(1)
+ const S = normalizeMeasurementsState({ unit: 'kg', bodyweight: [] })
+ const res = mergeImport(S, parsed)
+ expect(res.measurements).toBe(1)
+ expect(S.customMeasurements.map(c => [c.name, c.unit])).toEqual([
+ ['Muscle ratio', '%'], ['Lean mass', 'lb'], ['Knee', 'cm'], ['Visceral fat', 'none'],
+ ])
+ const m = S.measurements[0]
+ expect(m.waist).toBe(84.5)
+ const byName = Object.fromEntries(m.other.map(o => [S.customMeasurements.find(c => c.id === o.id).name, o]))
+ expect(byName['Muscle ratio']).toMatchObject({ value: 40.5, unit: '%' })
+ expect(byName['Lean mass'].value).toBeCloseTo(60, 1)
+ expect(byName.Knee.value).toBe(38.1)
+ expect(byName['Visceral fat']).toMatchObject({ value: 0, unit: 'none' })
+ })
+
+ it('files a column under the field of that name, converting within its kind, and leaves a clashing one out', () => {
+ const csv = 'date,weight_kg,Lean mass (kg),Muscle ratio (kg)\n2026-10-02,,61,50\n'
+ const S = state()
+ const res = mergeImport(S, parseBodyweight(csv, { unit: 'kg' }))
+ expect(res.measurements).toBe(1)
+ expect(S.customMeasurements).toHaveLength(4)
+ const day = S.measurements.find(e => e.d === '2026-10-02')
+ expect(day.other.find(o => o.id === 'lean')).toMatchObject({ value: 61, unit: 'lb' })
+ expect(day.other.find(o => o.id === 'ratio').value).toBeNull()
+ })
+
+ it('leaves a day that already has measurements alone, and imports a measurements-only file', () => {
+ const S = state()
+ const parsed = parseBodyweight('date,weight_kg,waist_cm\n2026-10-01,,90\n2026-10-03,,83\n', { unit: 'kg' })
+ expect(parsed.error).toBeUndefined()
+ expect(parsed.bodyweight).toEqual([])
+ expect(mergeImport(S, parsed).measurements).toBe(1)
+ expect(S.measurements.map(e => [e.d, e.waist])).toEqual([['2026-10-01', 84.5], ['2026-10-03', 83]])
+ })
+
+ it('does not read another app\'s extra columns as measurements', () => {
+ const parsed = parseBodyweight('Date,Weight,Notes\n2026-10-01,80,after coffee\n', { unit: 'kg' })
+ expect(parsed.bodyweight).toHaveLength(1)
+ expect(parsed.measurements || []).toEqual([])
+ })
+})
+
+describe('importing measurements that make no sense', () => {
+ it('skips a day whose only values no field can hold', () => {
+ const S = state()
+ const res = mergeImport(S, parseBodyweight('date,weight_kg,Muscle ratio (%)\n2026-10-05,,140\n', { unit: 'kg' }))
+ expect(res.measurements).toBe(0)
+ expect(S.measurements.map(e => e.d)).toEqual(['2026-10-01'])
+ })
+})
diff --git a/frontend/src/lib/measurements.js b/frontend/src/lib/measurements.js
index d007c1d97..eeff0454a 100644
--- a/frontend/src/lib/measurements.js
+++ b/frontend/src/lib/measurements.js
@@ -1,5 +1,6 @@
-// Canonical storage: lengths in cm, masses in kg, percentages as-is. A custom field's unit
-// selects its display unit. Legacy fields without one still follow the profile's cm/in choice.
+// Canonical storage: lengths in cm, masses in kg, percentages and plain numbers as-is. A custom
+// field's unit selects its display unit ('none' is a score or a count with no unit at all).
+// Legacy fields without one still follow the profile's cm/in choice.
export const MEASUREMENT_FIELDS = [
{ key: 'neck', label: 'Neck', group: 'Torso' },
@@ -28,13 +29,17 @@ export const DEFAULT_MEASUREMENT_KEYS = MEASUREMENT_FIELDS.filter(f => !f.option
const round = n => Math.round(n * 10) / 10
const valid = (v, unit) => v != null && v !== '' && Number.isFinite(+v) &&
- (unit === '%' ? +v >= 0 && +v <= 100 : +v > 0)
+ (unit === '%' ? +v >= 0 && +v <= 100 : unit === 'none' ? +v >= 0 : +v > 0)
? (unit === 'kg' || unit === 'lb' ? Math.round(+v * 1000) / 1000 : round(+v)) : null
const LB_PER_KG = 2.2046226218
-export const CUSTOM_MEASUREMENT_UNITS = ['cm', 'in', '%', 'kg', 'lb']
+export const CUSTOM_MEASUREMENT_UNITS = ['cm', 'in', '%', 'kg', 'lb', 'none']
const unitOf = field => CUSTOM_MEASUREMENT_UNITS.includes(field?.unit) ? field.unit : null
const withUnit = field => unitOf(field) ? { unit: field.unit } : {}
-const unitKind = unit => unit === '%' ? 'percent' : unit === 'kg' || unit === 'lb' ? 'mass' : 'length'
+const unitKind = unit => unit === '%' ? 'percent' : unit === 'none' ? 'none' : unit === 'kg' || unit === 'lb' ? 'mass' : 'length'
+// What goes after the number: nothing for a unitless field.
+export const measurementUnitLabel = unit => unit === 'none' ? '' : unit
+// A unit where 0 is a reading, not an empty field: 0 % or a score of 0.
+export const zeroIsReading = unit => unit === '%' || unit === 'none'
export const measurementUnit = (unit, field) => field?.key === 'bodyFat' ? '%' : unitOf(field) || (unit === 'lb' ? 'in' : 'cm')
export const toMeasurementDisplay = (value, unit, field) => {
@@ -177,3 +182,22 @@ export function measurementEntryHasValues(entry) {
return MEASUREMENT_KEYS.some(k => valid(entry?.[k], k === 'bodyFat' ? '%' : null) != null) ||
(entry?.other || []).some(o => valid(o?.value, unitOf(o)) != null)
}
+
+// ---- CSV columns (lib/export-csv.js bodyCSV, read back by lib/import-csv.js parseBodyweight) ----
+// A built-in field is a fixed snake_case column in cm (body fat in percent). A custom field's
+// column is its name with its unit in brackets, "Muscle ratio (%)", its values in that unit; a
+// legacy field without a unit stores cm, so its column says cm. A unitless field is its bare name.
+export const builtinCsvColumn = f => f.kind === 'percent' ? 'body_fat_percent' : f.key.replace(/[A-Z]/g, c => '_' + c.toLowerCase()) + '_cm'
+export const customCsvColumn = (name, unit) => unit === 'none' ? name : `${name} (${unitOf({ unit }) || 'cm'})`
+export function parseCustomCsvColumn(header) {
+ const h = String(header ?? '').trim()
+ const m = /^(.*\S)\s*\((cm|in|%|kg|lb)\)$/.exec(h)
+ return m ? { name: m[1], unit: m[2] } : { name: h, unit: 'none' }
+}
+// A value in a column's unit, into canonical storage (cm, kg, percent or the plain number).
+export const fromCsvUnit = (v, unit) => unit === 'in' ? v * 2.54 : unit === 'lb' ? v / LB_PER_KG : v
+// Whether readings in `a` can be shown in `b` (cm and in, kg and lb), with a legacy field's
+// missing unit counting as a length.
+export const sameMeasurementKind = (a, b) => unitKind(unitOf({ unit: a })) === unitKind(unitOf({ unit: b }))
+// A custom reading as the field shows it: in the field's unit, or cm for a legacy field.
+export const customDisplayValue = (value, unit) => unitOf({ unit }) ? toMeasurementDisplay(value, 'kg', { unit }) : value
diff --git a/frontend/src/lib/measurements.test.js b/frontend/src/lib/measurements.test.js
index decfe9928..cf6345d20 100644
--- a/frontend/src/lib/measurements.test.js
+++ b/frontend/src/lib/measurements.test.js
@@ -145,7 +145,7 @@ describe('custom measurement units (#699)', () => {
expect(customMeasurementUnits(length.customMeasurements[0], length.measurements)).toEqual(['cm', 'in'])
const percent = state('%', [0])
expect(customMeasurementUnits(percent.customMeasurements[0], percent.measurements)).toEqual(['%'])
- expect(customMeasurementUnits(field('cm'), [])).toEqual(['cm', 'in', '%', 'kg', 'lb'])
+ expect(customMeasurementUnits(field('cm'), [])).toEqual(['cm', 'in', '%', 'kg', 'lb', 'none'])
const before = structuredClone(mass.measurements)
mass.customMeasurements[0].unit = 'lb'
normalizeMeasurementsState(mass)
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 3068b4509..86c05d945 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -2549,4 +2549,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "تُضاف قبل مجموعات العمل. تُحتسب في حجمك (الإعدادات)، لكنها لا تُحتسب في الأرقام القياسية أو التدرج. كل واحدة تقلص الفجوة إلى وزن العمل إلى النصف، ولا تقل أبدًا عن وزن البار في تمارين البار، ويمكنك تعديل أي منها أثناء الجلسة.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "تم حذف الوزن",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "بدون وحدة",
+ "{0} measurement check-in imported": "تم استيراد {0} تسجيل قياسات",
+ "{0} measurement check-ins imported": "تم استيراد {0} تسجيلات قياسات",
}
diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.js
index ef12dd9d5..9aa56d411 100644
--- a/frontend/src/locales/bn.js
+++ b/frontend/src/locales/bn.js
@@ -2573,4 +2573,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "ওয়ার্ক সেটের আগে যোগ হয়। আপনার ভলিউমে গোনা হয় (সেটিংস), কিন্তু রেকর্ড আর প্রগ্রেশনে নয়। প্রতিটি ওয়ার্ক ওয়েটের দূরত্বের অর্ধেক কমায়, বারবেল লিফটে বারের নিচে কখনো নামে না, আর সেশনের মাঝেও যেকোনোটা বদলাতে পারবেন।",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "ওজন মুছে ফেলা হয়েছে",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "কোনো একক নেই",
+ "{0} measurement check-in imported": "{0}টি মাপের রেকর্ড ইমপোর্ট হয়েছে",
+ "{0} measurement check-ins imported": "{0}টি মাপের রেকর্ড ইমপোর্ট হয়েছে",
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index d3a83d0c0..81819d1c8 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -2514,4 +2514,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "Kommen vor deine Arbeitssätze. Sie zählen in dein Volumen (Einstellungen), aber nicht für Rekorde und Progression. Jeder halbiert den Abstand zum Arbeitsgewicht, bei Langhantelübungen nie leichter als die leere Stange, und im Training kannst du jeden davon trotzdem ändern.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Wiegung gelöscht",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Ohne Einheit",
+ "{0} measurement check-in imported": "{0} Messung importiert",
+ "{0} measurement check-ins imported": "{0} Messungen importiert",
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 91ca274ee..bef22e7fb 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -2494,4 +2494,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "Se añaden antes de tus series de trabajo. Cuentan en tu volumen (Ajustes), pero no para los récords ni la progresión. Cada una reduce a la mitad la distancia hasta el peso de trabajo, sin bajar nunca de la barra vacía en un ejercicio con barra, y puedes cambiar cualquiera durante la sesión.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Pesaje eliminado",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Sin unidad",
+ "{0} measurement check-in imported": "{0} registro de medidas importado",
+ "{0} measurement check-ins imported": "{0} registros de medidas importados",
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 9122ba3a0..bcd658838 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -2494,4 +2494,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "Ajoutées avant tes séries de travail. Elles comptent dans ton volume (Réglages), mais restent exclues des records et de la progression. Chacune réduit de moitié l’écart avec la charge de travail, sans jamais descendre sous la barre à vide pour un exercice à la barre, et tu peux toujours les modifier pendant la séance.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Pesée supprimée",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Sans unité",
+ "{0} measurement check-in imported": "{0} relevé de mensurations importé",
+ "{0} measurement check-ins imported": "{0} relevés de mensurations importés",
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index f461a81da..ab297dc31 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -2494,4 +2494,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "ये आपके वर्क सेट से पहले जुड़ते हैं। ये आपके वॉल्यूम में गिने जाते हैं (सेटिंग्स), लेकिन रिकॉर्ड और प्रोग्रेशन में नहीं। हर सेट वर्क वज़न तक बची दूरी को आधा कर देता है, बारबेल लिफ़्ट में कभी खाली बार से हल्का नहीं होता, और कसरत के बीच भी आप इनमें से किसी को बदल सकते हैं।",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "वज़न हटाया गया",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "कोई इकाई नहीं",
+ "{0} measurement check-in imported": "{0} माप रिकॉर्ड आयात हुआ",
+ "{0} measurement check-ins imported": "{0} माप रिकॉर्ड आयात हुए",
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 7522415b4..1541e76ee 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -2497,4 +2497,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "A munkasorozatok elé kerülnek. Beleszámítanak a volumenedbe (Beállítások), de a rekordokból és a progresszióból kimaradnak. Mindegyik a felére zárja a különbséget a munkasúlyhoz, rúddal végzett gyakorlatnál soha nem könnyebb az üres rúdnál, és edzés közben is bármelyiket módosíthatod.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Mérés törölve",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Nincs mértékegység",
+ "{0} measurement check-in imported": "{0} méretfelvétel importálva",
+ "{0} measurement check-ins imported": "{0} méretfelvétel importálva",
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index ee52ab5de..ae3db7bde 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -2494,4 +2494,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "Vengono aggiunte prima delle serie di lavoro. Contano nel tuo volume (Impostazioni), ma non per record e progressione. Ognuna dimezza la distanza dal peso di lavoro, senza mai scendere sotto il bilanciere scarico negli esercizi con bilanciere, e puoi comunque modificarle durante la sessione.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Pesata eliminata",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Senza unità",
+ "{0} measurement check-in imported": "{0} rilevazione di misure importata",
+ "{0} measurement check-ins imported": "{0} rilevazioni di misure importate",
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index f1b008598..1e384cb31 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -2494,4 +2494,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "작업 세트 앞에 추가됩니다. 볼륨에는 포함되지만(설정), 기록과 진행에는 포함되지 않습니다. 각 세트는 작업 중량까지의 차이를 절반으로 줄이고 바벨 운동에서는 빈 바보다 가벼워지지 않으며, 운동 중에도 언제든 바꿀 수 있어요.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "체중 기록 삭제됨",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "단위 없음",
+ "{0} measurement check-in imported": "측정 기록 {0}개를 가져왔습니다",
+ "{0} measurement check-ins imported": "측정 기록 {0}개를 가져왔습니다",
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index d53521b08..cc0365d84 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -2494,4 +2494,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "Dodawane przed seriami roboczymi. Liczą się do Twojej objętości (Ustawienia), ale nie do rekordów i progresji. Każda zmniejsza o połowę dystans do ciężaru roboczego, przy sztandze nigdy nie schodzi poniżej pustego gryfu, a w trakcie treningu nadal możesz każdą zmienić.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Ważenie usunięte",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Bez jednostki",
+ "{0} measurement check-in imported": "Zaimportowano {0} pomiar",
+ "{0} measurement check-ins imported": {"one":"Zaimportowano {0} pomiar","few":"Zaimportowano {0} pomiary","many":"Zaimportowano {0} pomiarów","other":"Zaimportowano {0} pomiaru"},
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 4f7bb89a6..f42a00864 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1600,6 +1600,10 @@ export const PT_BR_OVERRIDES = {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "Entram antes das suas séries de trabalho. Contam no seu volume (Ajustes), mas ficam de fora dos recordes e da progressão. Cada uma fecha metade da distância até o peso de trabalho, nunca abaixo da barra vazia em um exercício com barra, e você ainda pode mudar qualquer uma no meio do treino.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Pesagem excluída",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Sem unidade",
+ "{0} measurement check-in imported": "{0} registro de medidas importado",
+ "{0} measurement check-ins imported": "{0} registros de medidas importados",
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 3f96669aa..c442286bb 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -2494,4 +2494,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "São acrescentadas antes das tuas séries de trabalho. Contam no teu volume (Definições), mas ficam de fora dos recordes e da progressão. Cada uma reduz a metade a distância até ao peso de trabalho, nunca abaixo da barra vazia num exercício com barra, e podes alterar qualquer uma a meio da sessão.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Pesagem eliminada",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Sem unidade",
+ "{0} measurement check-in imported": "{0} registo de medidas importado",
+ "{0} measurement check-ins imported": "{0} registos de medidas importados",
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 0727da3d1..a6d79d746 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -2498,4 +2498,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "Добавляются перед рабочими подходами. Они учитываются в вашем объёме (Настройки), но не в рекордах и прогрессии. Каждый вдвое сокращает разрыв до рабочего веса, но в упражнениях со штангой никогда не легче пустого грифа, и любой из них можно изменить прямо во время тренировки.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Взвешивание удалено",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Без единицы",
+ "{0} measurement check-in imported": "Импортирован {0} замер",
+ "{0} measurement check-ins imported": {"one":"Импортирован {0} замер","few":"Импортировано {0} замера","many":"Импортировано {0} замеров","other":"Импортировано {0} замера"},
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 8dfcbad54..43953ced0 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -2505,4 +2505,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "เพิ่มไว้ก่อนเซ็ตหลัก นับรวมในปริมาณงานของคุณ (การตั้งค่า) แต่ไม่นับในสถิติหรือการเพิ่มน้ำหนัก แต่ละเซ็ตจะลดช่องว่างไปครึ่งหนึ่งจนถึงน้ำหนักเซ็ตหลัก ท่าบาร์เบลจะไม่เบากว่าบาร์เปล่า และยังปรับเปลี่ยนได้ระหว่างออกกำลังกาย",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "ลบการชั่งน้ำหนักแล้ว",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "ไม่มีหน่วย",
+ "{0} measurement check-in imported": "นำเข้าบันทึกสัดส่วน {0} รายการแล้ว",
+ "{0} measurement check-ins imported": "นำเข้าบันทึกสัดส่วน {0} รายการแล้ว",
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index eef60ea2f..95d225858 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -2494,4 +2494,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "Çalışma setlerinden önce eklenir. Hacmine sayılır (Ayarlar), ama rekor ve ilerlemeye sayılmaz. Her biri çalışma ağırlığına kalan farkı yarıya indirir, halter hareketlerinde boş barın altına hiç inmez ve antrenman sırasında hâlâ istediğini değiştirebilirsin.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Tartım silindi",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Birimsiz",
+ "{0} measurement check-in imported": "{0} ölçüm kaydı içe aktarıldı",
+ "{0} measurement check-ins imported": "{0} ölçüm kaydı içe aktarıldı",
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 1a08c7ee8..8d242761b 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -2491,4 +2491,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "Додаються перед робочими підходами. Вони враховуються у твоєму обсязі (Налаштування), але не в рекордах і прогресії. Кожен удвічі скорочує розрив до робочої ваги, але у вправах зі штангою ніколи не легший за порожній гриф, і будь-який із них можна змінити під час тренування.",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "Зважування видалено",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "Без одиниці",
+ "{0} measurement check-in imported": "Імпортовано {0} вимір",
+ "{0} measurement check-ins imported": {"one":"Імпортовано {0} вимір","few":"Імпортовано {0} виміри","many":"Імпортовано {0} вимірів","other":"Імпортовано {0} виміру"},
}
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index 9841a4741..49d87e5ce 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -2487,4 +2487,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "排在正式組之前。會列入你的總訓練量(設定),但不列入個人紀錄與漸進計算。每組都會把與正式重量的差距縮小一半,槓鈴動作不會低於空槓,訓練中仍可隨時修改任何一組。",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "已刪除體重紀錄",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "無單位",
+ "{0} measurement check-in imported": "已匯入 {0} 筆身體測量紀錄",
+ "{0} measurement check-ins imported": "已匯入 {0} 筆身體測量紀錄",
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index dae465f1b..b8332368d 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -2494,4 +2494,8 @@ export default {
"Added before your work sets. They count in your volume (Settings), but stay out of records and progression. Each one closes half the gap to the work weight, never below the bar on a barbell lift, and you can still change any of them mid-session.": "加在正式组之前。计入你的容量(设置),但不计入纪录和进阶。每一组都把与正式重量的差距缩小一半,杠铃动作不会低于空杠,训练中仍可随时调整任意一组。",
// --- weigh-in undo (#756) ---
"Weigh-in deleted": "称重记录已删除",
+ // --- unitless custom measurements, measurements from the body CSV (#718) ---
+ "No unit": "无单位",
+ "{0} measurement check-in imported": "已导入 {0} 条身体测量记录",
+ "{0} measurement check-ins imported": "已导入 {0} 条身体测量记录",
}
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 1ac9c76fe..5adc9fd16 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -448,17 +448,21 @@ const effortLine = (effort, n, scale) => effort === 'none'
function ImportSummary({ parsed, close }) {
const st = useStore(s => s.S)
const isBW = parsed.kind === 'bodyweight'
- const have = isBW
+ // Our own body CSV brings measurement check-ins along (#718); a day that has one keeps it.
+ const checkIns = isBW ? parsed.measurements || [] : []
+ const haveM = checkIns.filter(m => (st.measurements || []).some(x => x.d === m.d)).length
+ 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
+ : parsed.workouts.filter(w => st.workouts.some(x => x.d === w.d)).length) + haveM
+ const fresh = (isBW ? parsed.bodyweight.length + checkIns.length : parsed.workouts.length) - have
const doImport = () => {
let res
update(s => { res = mergeImport(s, parsed) })
close()
+ const measured = res.measurements ? tn('{0} measurement check-in imported', '{0} measurement check-ins imported', res.measurements) : ''
toast(isBW
- ? tn('{0} weigh-in imported', '{0} weigh-ins imported', res.added)
+ ? (res.added || !measured ? tn('{0} weigh-in imported', '{0} weigh-ins imported', res.added) + (measured ? ' · ' + measured : '') : measured)
: tn('{0} workout imported', '{0} workouts imported', res.added))
}
@@ -471,6 +475,7 @@ function ImportSummary({ parsed, close }) {
<div className="tiles" style={{ textAlign: 'start' }}>
{isBW ? <>
<div className="tile"><div className="l">{t('Weigh-ins')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{parsed.bodyweight.length}</div></div>
+ {checkIns.length > 0 && <div className="tile"><div className="l">{t('Body measurements')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{checkIns.length}</div></div>}
<div className="tile"><div className="l">{t('New')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{fresh}</div></div>
</> : <>
<div className="tile"><div className="l">{t('Workouts')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{parsed.workouts.length}</div></div>
@@ -526,7 +531,7 @@ export function importFromApp(file, onDone) {
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("We don't recognise that file's columns. Check the docs for supported apps.")); return }
- if (parsed.kind === 'bodyweight' ? !parsed.bodyweight.length : !parsed.workouts.length) {
+ if (parsed.kind === 'bodyweight' ? !parsed.bodyweight.length && !parsed.measurements?.length : !parsed.workouts.length) {
toast(t('Nothing to import from that file')); return
}
ui().openSheet(close => <ImportSummary parsed={parsed} close={close} />)
diff --git a/frontend/src/views/Measurements.jsx b/frontend/src/views/Measurements.jsx
index 815ea8b88..82655f1f8 100644
--- a/frontend/src/views/Measurements.jsx
+++ b/frontend/src/views/Measurements.jsx
@@ -7,6 +7,7 @@ import {
fromMeasurementDisplay, latestMeasurement, measurementEntryHasValues,
measurementSeries, measurementUnit, measurementValue, normalizeMeasurementEntry,
toMeasurementDisplay, normalizeMeasurementsState, CUSTOM_MEASUREMENT_UNITS, customMeasurementUnits,
+ measurementUnitLabel, zeroIsReading,
} from '../lib/measurements.js'
import { fmtDate, fmtNum, todayISO, uid } from '../lib/format.js'
import { t } from '../lib/i18n.js'
@@ -19,7 +20,10 @@ import { confirmSheet } from '../sheets.jsx'
const update = (fn, ...rest) => useStore.getState().update(s => { fn(s); normalizeMeasurementsState(s) }, ...rest)
const toast = message => useUI.getState().toast(message)
-const fieldUnit = (field, profileUnit) => measurementUnit(profileUnit, field)
+// The label after a number: empty for a unitless field (#718).
+const fieldUnit = (field, profileUnit) => measurementUnitLabel(measurementUnit(profileUnit, field))
+const unitOptions = units => units.map(value => ({ value, label: value === 'none' ? t('No unit') : value }))
+const withUnit = (value, unit) => unit ? fmtNum(value) + ' ' + unit : fmtNum(value)
const shownValue = (entry, field, profileUnit) => {
const value = measurementValue(entry, field.key)
if (value == null) return null
@@ -55,8 +59,9 @@ function MeasurementLog({ sourceDate, close }) {
base.t = source && date === source.d ? source.t : (date === todayISO() ? Date.now() : new Date(date + 'T12:00:00').getTime())
for (const field of fields) {
const raw = values[field.key]
- const percent = fieldUnit(field, S.unit) === '%'
- const value = raw == null || (raw === 0 && !percent) ? null : Math.round(+raw * 10) / 10
+ const shown = measurementUnit(S.unit, field)
+ const percent = shown === '%'
+ const value = raw == null || (raw === 0 && !zeroIsReading(shown)) ? null : Math.round(+raw * 10) / 10
if (percent && value != null && (value < 0 || value > 100)) {
toast(field.key === 'bodyFat' ? t('Body fat must be between 0 and 100%.') : t('{0} must be between 0 and 100%.', field.label)); return
}
@@ -150,7 +155,7 @@ function ManageMeasurements({ close }) {
<Switch checked={field.enabled !== false} onChange={on => toggleCustom(field.id, on)} />
</div>
<SelectRow title={t('Measurement unit')} value={measurementUnit(S.unit, field)}
- options={customMeasurementUnits(field, S.measurements).map(value => ({ value, label: value }))}
+ options={unitOptions(customMeasurementUnits(field, S.measurements))}
onChange={value => setCustomUnit(field.id, value)} />
</div>)}
</Section>)}
@@ -158,7 +163,7 @@ function ManageMeasurements({ close }) {
<h4 className="sec">{t('Custom measurement')}</h4>
<div className="sect-b">
<SelectRow title={t('Measurement unit')} value={unit} onChange={setUnit}
- options={CUSTOM_MEASUREMENT_UNITS.map(value => ({ value, label: value }))} />
+ options={unitOptions(CUSTOM_MEASUREMENT_UNITS)} />
</div>
<div className="row" style={{ gap: 8, alignItems: 'stretch' }}>
<TextField value={name} maxLength={60} placeholder={t('Custom measurement')} onChange={e => setName(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') add() }} />
@@ -219,7 +224,7 @@ export default function Measurements() {
<div>
<div className="muted small">{field ? t(field.label) : t('Body measurements')}</div>
<div className="big" style={{ marginTop: 3 }}>{latest ? <>{fmtNum(latest.y)} <span className="muted" style={{ fontSize: '1rem' }}>{unit}</span></> : '–'}</div>
- {delta != null && delta !== 0 && <div className="small" style={{ marginTop: 3, color: 'var(--label-2)' }}>{delta > 0 ? '+' : ''}{fmtNum(delta)} {unit} {t('since previous')}</div>}
+ {delta != null && delta !== 0 && <div className="small" style={{ marginTop: 3, color: 'var(--label-2)' }}>{delta > 0 ? '+' : ''}{withUnit(delta, unit)} {t('since previous')}</div>}
</div>
<Button size="sm" icon="plus" onClick={() => measurementLogSheet()}>{t('Log')}</Button>
</div>
@@ -252,7 +257,7 @@ export default function Measurements() {
<button className="iconbtn" style={{ color: 'var(--red)' }} onClick={() => remove(entry)} aria-label={t('Delete')}><Icon name="trash" /></button>
</div>
</div>
- {previewFields.length > 0 && <div className="measure-preview">{previewFields.map(({ field: f, value }) => <span key={f.key}>{t(f.label)} <b>{fmtNum(value)} {fieldUnit(f, S.unit)}</b></span>)}</div>}
+ {previewFields.length > 0 && <div className="measure-preview">{previewFields.map(({ field: f, value }) => <span key={f.key}>{t(f.label)} <b>{withUnit(value, fieldUnit(f, S.unit))}</b></span>)}</div>}
</div>
})}</div> : <div className="empty small">{t('No measurements yet')}</div>}
</div>
diff --git a/frontend/src/views/Measurements.unitless.test.jsx b/frontend/src/views/Measurements.unitless.test.jsx
new file mode 100644
index 000000000..2f646f2ec
--- /dev/null
+++ b/frontend/src/views/Measurements.unitless.test.jsx
@@ -0,0 +1,97 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { MemoryRouter } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Measurements, { manageMeasurementsSheet, measurementLogSheet } from './Measurements.jsx'
+import { DEF, useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { bindUI } from '../components/ui.jsx'
+import { normalizeMeasurementsState } from '../lib/measurements.js'
+import { importFromApp } from '../sheets.jsx'
+
+// #718 follow-up: a custom measurement can have no unit at all (a scale's visceral fat rating,
+// a metabolic age), and our own body CSV brings measurements back in.
+const mounted = []
+function render(node) {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push([root, host])
+ act(() => root.render(node))
+ return host
+}
+function topSheet() {
+ const sheet = useUI.getState().sheets.at(-1)
+ return render(sheet.render(() => useUI.getState().closeSheet(sheet.id)))
+}
+const buttons = host => [...host.querySelectorAll('button')]
+const button = (host, text) => buttons(host).find(el => el.textContent.trim() === text)
+const unitRows = host => buttons(host).filter(el => el.querySelector('.lrow-t')?.textContent === 'Measurement unit')
+const field = (host, name) => [...host.querySelectorAll('.measure-field')].find(el => el.firstElementChild.textContent === name)
+const type = (input, value) => act(() => {
+ Object.getOwnPropertyDescriptor(input.constructor.prototype, 'value').set.call(input, value)
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+})
+const install = patch => useStore.setState({ S: normalizeMeasurementsState({ ...structuredClone(DEF), measurementEnabled: [], ...patch }), user: null })
+const visc = { id: 'visc', name: 'Visceral fat', unit: 'none', enabled: true }
+
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ bindUI(useUI)
+ useUI.setState({ sheets: [], toast: vi.fn() })
+ install({})
+})
+afterEach(() => {
+ act(() => mounted.splice(0).forEach(([root, host]) => { root.unmount(); host.remove() }))
+})
+
+describe('a custom measurement without a unit', () => {
+ it('can be created as "No unit"', () => {
+ manageMeasurementsSheet()
+ const host = topSheet()
+ act(() => unitRows(host).at(-1).click())
+ const picker = topSheet()
+ act(() => button(picker, 'No unit').click())
+ type(host.querySelector('input[placeholder="Custom measurement"]'), 'Visceral fat')
+ act(() => button(host, 'Add').click())
+ expect(useStore.getState().S.customMeasurements).toEqual([expect.objectContaining({ name: 'Visceral fat', unit: 'none' })])
+ })
+
+ it('logs a plain number, zero included, with nothing after it', () => {
+ install({ unit: 'lb', customMeasurements: [visc] })
+ measurementLogSheet()
+ const host = topSheet()
+ expect(field(host, 'Visceral fat').querySelector('i').textContent).toBe('')
+ type(field(host, 'Visceral fat').querySelector('input'), '0')
+ act(() => button(host, 'Save').click())
+ expect(useStore.getState().S.measurements[0].other[0]).toMatchObject({ value: 0, unit: 'none' })
+ })
+
+ it('shows the number on its own on the page', () => {
+ install({ customMeasurements: [visc], measurements: [
+ { d: '2026-10-01', other: [{ id: 'visc', value: 9, unit: 'none' }] },
+ { d: '2026-10-02', other: [{ id: 'visc', value: 8, unit: 'none' }] },
+ ] })
+ const host = render(<MemoryRouter><Measurements /></MemoryRouter>)
+ expect(host.querySelector('.big').textContent.trim()).toBe('8')
+ expect(host.textContent).toContain('-1 since previous')
+ expect(host.querySelector('.measure-preview b').textContent.trim()).toBe('8')
+ })
+})
+
+describe('importing our own body CSV', () => {
+ it('counts the measurement check-ins it brings, even without a single weigh-in', async () => {
+ install({ unit: 'kg', bodyweight: [] })
+ const file = new File(['date,weight_kg,waist_cm,Visceral fat\n2026-10-01,,84,9\n2026-10-02,,83.5,8\n'], 'body.csv', { type: 'text/csv' })
+ importFromApp(file)
+ for (let i = 0; i < 50 && !useUI.getState().sheets.length; i++) await new Promise(r => setTimeout(r, 5))
+ const host = topSheet()
+ const tiles = [...host.querySelectorAll('.tile')].map(t => t.textContent)
+ expect(tiles).toContain('Body measurements2')
+ act(() => button(host, 'Import').click())
+ expect(useStore.getState().S.measurements.map(e => e.d)).toEqual(['2026-10-01', '2026-10-02'])
+ expect(useStore.getState().S.customMeasurements).toEqual([expect.objectContaining({ name: 'Visceral fat', unit: 'none' })])
+ expect(useUI.getState().toast).toHaveBeenCalledWith('2 measurement check-ins imported')
+ })
+})