Merge merge request !2 (exercise catalogue and muscle metadata)
Keeps the ExRx-informed primary/secondary metadata for 223 catalogue
entries and the muscle-group UI, with two fixes to the branch:
- muscles.js dropped metadataOf, the muscleSnapshot fallback. A custom
exercise deleted from the catalogue survives in history only as that
snapshot, so without it those sessions silently stopped counting toward
the body map and Stats — loadOfWorkouts returned {} where main returned
{chest: 1}. Restored and widened to the new primaries/secondaries fields.
- It also replaced the shared isWarmupRow import with a local copy that
only matches the exact string 'warmup'. phaseForSet normalises 'warm-up',
'warm_up', casing and whitespace, so warm-up rows written in any other
spelling would have counted as work here while counting as warm-ups
everywhere else. Restored the import.
Both are covered by new tests. Locale conflicts resolved additively; the
three new muscle-group strings read the same in pt-BR, so they stay
inherited and the inheritance fingerprint is re-baselined.
This commit is contained in:
commit
5762096a5f
25 files changed
+3286
-40
No files matched your search
@@ -0,0 +1,27 @@
|
||||
import batch from './exercise-muscle-batch-1.json' with { type: 'json' }
|
||||
import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
|
||||
|
||||
/**
|
||||
* ExRx-informed metadata for the first compound-lift batch. The raw generated catalogue remains
|
||||
* untouched; exercises.js applies this layer to the runtime index.
|
||||
*/
|
||||
export const COMPOUND_LIFT_BATCH_1 = Object.freeze(batch)
|
||||
|
||||
// Keep the phase-2 artifact in its own module for auditing while preserving the phase-1 resolver
|
||||
// interface consumed by exercises.js and downstream muscle helpers.
|
||||
export { MACHINE_BATCH_2 }
|
||||
|
||||
/**
|
||||
* Reserved for owner-approved corrections. This layer is intentionally separate from the
|
||||
* generated batch so a correction can replace a generated body part or muscle list without
|
||||
* editing generated data. Explicit metadata on a user/custom exercise wins as well.
|
||||
*/
|
||||
export const USER_EXERCISE_MUSCLE_OVERRIDES = Object.freeze({})
|
||||
|
||||
export function exerciseMuscleMetadataFor(id) {
|
||||
return {
|
||||
...(COMPOUND_LIFT_BATCH_1[id] || {}),
|
||||
...(MACHINE_BATCH_2[id] || {}),
|
||||
...(USER_EXERCISE_MUSCLE_OVERRIDES[id] || {})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { BODYPARTS, EXDB, EXIDX, registerCustom } from './exercises.js'
|
||||
import { COMPOUND_LIFT_BATCH_1 } from './exercise-muscle-batch-1.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
|
||||
const ids = Object.keys(COMPOUND_LIFT_BATCH_1)
|
||||
const catalogueIds = new Set(EXDB.map(ex => ex.id))
|
||||
|
||||
const duplicateFree = values => values.length === new Set(values).size
|
||||
|
||||
describe('compound-lift muscle metadata batch 1', () => {
|
||||
it('contains a bounded first batch of compound-lift catalogue entries', () => {
|
||||
expect(ids.length).toBeGreaterThanOrEqual(60)
|
||||
expect(ids.length).toBeLessThanOrEqual(120)
|
||||
expect(ids.every(id => catalogueIds.has(id))).toBe(true)
|
||||
})
|
||||
|
||||
it('stores canonical primary and secondary arrays for every batch entry', () => {
|
||||
for (const [id, metadata] of Object.entries(COMPOUND_LIFT_BATCH_1)) {
|
||||
expect(metadata.primaries.length, id).toBeGreaterThan(0)
|
||||
expect(duplicateFree(metadata.primaries), id).toBe(true)
|
||||
expect(duplicateFree(metadata.secondaries), id).toBe(true)
|
||||
expect(metadata.primaries.some(muscle => metadata.secondaries.includes(muscle)), id).toBe(false)
|
||||
expect(metadata.primaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(metadata.secondaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(EXIDX[id]).toMatchObject(metadata)
|
||||
}
|
||||
})
|
||||
|
||||
it('follows the documented ExRx family templates and preserves source-known muscles', () => {
|
||||
expect(COMPOUND_LIFT_BATCH_1['0043']).toEqual({
|
||||
bp: 'upper legs',
|
||||
primaries: ['quadriceps', 'gluteal', 'adductors'],
|
||||
secondaries: ['hamstring', 'calves', 'lower-back', 'abs', 'obliques']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0032']).toEqual({
|
||||
bp: 'full body',
|
||||
primaries: ['gluteal', 'hamstring', 'lower-back'],
|
||||
secondaries: ['quadriceps', 'adductors', 'calves', 'abs', 'obliques']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0025']).toEqual({
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['triceps', 'deltoids', 'biceps']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0091']).toEqual({
|
||||
bp: 'shoulders', primaries: ['deltoids'],
|
||||
secondaries: ['chest', 'triceps', 'trapezius', 'serratus']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0027']).toEqual({
|
||||
bp: 'back', primaries: ['upper-back'],
|
||||
secondaries: ['biceps', 'deltoids', 'forearm']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0652']).toEqual({
|
||||
bp: 'back', primaries: ['upper-back'], secondaries: ['biceps', 'deltoids', 'forearm']
|
||||
})
|
||||
expect(musclesOf(EXDB.find(exercise => exercise.id === '0587'))).toMatchObject({ chest: 0.4 })
|
||||
expect(musclesOf(EXIDX['0587'])).toMatchObject({ chest: 0.4 })
|
||||
})
|
||||
|
||||
it('keeps torso bracing secondary and does not label the twisting press full body', () => {
|
||||
expect(COMPOUND_LIFT_BATCH_1['0414']).toEqual({
|
||||
bp: 'shoulders', primaries: ['deltoids'], secondaries: ['triceps', 'trapezius', 'abs']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['1012']).toEqual({
|
||||
bp: 'shoulders', primaries: ['deltoids'],
|
||||
secondaries: ['triceps', 'trapezius', 'abs', 'obliques']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['1012'].primaries).not.toContain('abs')
|
||||
expect(COMPOUND_LIFT_BATCH_1['1012'].secondaries).toContain('obliques')
|
||||
})
|
||||
|
||||
it('marks the cross-region lifts as Full body while keeping classic areas available', () => {
|
||||
expect(EXIDX['0069']).toMatchObject({ bp: 'full body', primaries: ['quadriceps', 'gluteal', 'adductors'] })
|
||||
expect(EXIDX['0032'].bp).toBe('full body')
|
||||
expect(BODYPARTS).toContain('full body')
|
||||
expect(EXIDX['0025'].bp).toBe('chest')
|
||||
expect(EXIDX['0652'].bp).toBe('back')
|
||||
})
|
||||
|
||||
it('lets an explicit user exercise override the batch and restores the catalogue afterward', () => {
|
||||
registerCustom([{ id: '0025', n: 'Owner bench correction', bp: 'chest', primaries: ['triceps'], secondaries: [] }])
|
||||
expect(EXIDX['0025']).toMatchObject({ primaries: ['triceps'], secondaries: [] })
|
||||
registerCustom([])
|
||||
expect(EXIDX['0025']).toMatchObject(COMPOUND_LIFT_BATCH_1['0025'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import batch from './exercise-muscle-batch-2.json' with { type: 'json' }
|
||||
|
||||
/**
|
||||
* ExRx-informed metadata for machine, cable, sled, and Smith-machine catalogue entries.
|
||||
* `exercises.js` applies this as a runtime overlay so the raw generated catalogue remains
|
||||
* compatible with imports and historical records.
|
||||
*/
|
||||
export const MACHINE_BATCH_2 = Object.freeze(batch)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { BODYPARTS, EXDB, EXIDX, registerCustom } from './exercises.js'
|
||||
import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
|
||||
const ids = Object.keys(MACHINE_BATCH_2)
|
||||
const catalogue = new Map(EXDB.map(exercise => [exercise.id, exercise]))
|
||||
const duplicateFree = values => values.length === new Set(values).size
|
||||
|
||||
const expectMapping = (id, expected) => {
|
||||
expect(MACHINE_BATCH_2[id], id).toEqual(expected)
|
||||
expect(EXIDX[id], id).toMatchObject(expected)
|
||||
}
|
||||
|
||||
describe('machine muscle metadata batch 2', () => {
|
||||
it('contains a bounded batch of machine and cable catalogue entries', () => {
|
||||
expect(ids.length).toBeGreaterThanOrEqual(60)
|
||||
expect(ids.length).toBeLessThanOrEqual(120)
|
||||
expect(ids.length).toBe(119)
|
||||
expect(ids.every(id => catalogue.has(id))).toBe(true)
|
||||
expect(ids.every(id => /machine|cable/.test(catalogue.get(id).eq))).toBe(true)
|
||||
})
|
||||
|
||||
it('uses only existing body-part keys and canonical drawable muscle slugs', () => {
|
||||
for (const [id, metadata] of Object.entries(MACHINE_BATCH_2)) {
|
||||
expect(BODYPARTS, id).toContain(metadata.bp)
|
||||
expect(metadata.primaries.length, id).toBeGreaterThan(0)
|
||||
expect(duplicateFree(metadata.primaries), id).toBe(true)
|
||||
expect(duplicateFree(metadata.secondaries), id).toBe(true)
|
||||
expect(metadata.primaries.some(muscle => metadata.secondaries.includes(muscle)), id).toBe(false)
|
||||
expect(metadata.primaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(metadata.secondaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(EXIDX[id]).toMatchObject(metadata)
|
||||
}
|
||||
})
|
||||
|
||||
it('maps the pec-deck family from the lever seated-fly template', () => {
|
||||
expectMapping('0596', {
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['deltoids', 'biceps', 'serratus']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps chest-press machines to chest with pressing assistants', () => {
|
||||
expectMapping('0577', {
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['deltoids', 'triceps', 'biceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps cable crossovers to drawing-ready upper-back support', () => {
|
||||
expectMapping('0155', {
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['upper-back', 'trapezius']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps machine/cable lat pulldowns to upper back with arm-and-shoulder synergy', () => {
|
||||
expectMapping('0579', {
|
||||
bp: 'back',
|
||||
primaries: ['upper-back'],
|
||||
secondaries: ['biceps', 'deltoids', 'forearm', 'trapezius', 'triceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps seated rows to upper back with the phase-1 pull template', () => {
|
||||
expectMapping('1350', {
|
||||
bp: 'back',
|
||||
primaries: ['upper-back'],
|
||||
secondaries: ['biceps', 'deltoids', 'forearm', 'trapezius', 'chest', 'triceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps assisted triceps dip variants to full synergist support', () => {
|
||||
expectMapping('0019', {
|
||||
bp: 'upper arms',
|
||||
primaries: ['triceps'],
|
||||
secondaries: ['deltoids', 'chest', 'upper-back', 'trapezius', 'biceps']
|
||||
})
|
||||
expectMapping('1451', {
|
||||
bp: 'upper arms',
|
||||
primaries: ['triceps'],
|
||||
secondaries: ['deltoids', 'chest', 'upper-back', 'trapezius', 'biceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps lever triceps extension without ExRx synergist secondaries', () => {
|
||||
expectMapping('0607', {
|
||||
bp: 'upper arms', primaries: ['triceps'], secondaries: []
|
||||
})
|
||||
})
|
||||
|
||||
it('maps sled leg presses to the multi-primary lower-body template', () => {
|
||||
expectMapping('0739', {
|
||||
bp: 'upper legs', primaries: ['quadriceps', 'gluteal', 'adductors'], secondaries: ['hamstring', 'calves']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps leg extensions as quadriceps isolation', () => {
|
||||
expectMapping('0585', {
|
||||
bp: 'upper legs', primaries: ['quadriceps'], secondaries: []
|
||||
})
|
||||
})
|
||||
|
||||
it('maps seated leg curls to hamstrings with calf assistance', () => {
|
||||
expectMapping('0599', {
|
||||
bp: 'upper legs', primaries: ['hamstring'], secondaries: ['calves', 'adductors']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps machine shoulder presses to deltoids with direct press support', () => {
|
||||
expectMapping('0603', {
|
||||
bp: 'shoulders', primaries: ['deltoids'],
|
||||
secondaries: ['chest', 'triceps', 'trapezius', 'serratus', 'biceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves raw dataset metadata while enriching only the runtime catalogue', () => {
|
||||
const raw = catalogue.get('0577')
|
||||
expect(raw).toMatchObject({ id: '0577', n: 'lever chest press', tg: 'pectorals', mg: 'triceps' })
|
||||
expect(raw).not.toHaveProperty('primaries')
|
||||
expect(raw).not.toHaveProperty('secondaries')
|
||||
expect(musclesOf(raw)).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4 })
|
||||
expect(musclesOf(EXIDX['0577'])).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4, biceps: 0.4 })
|
||||
})
|
||||
|
||||
it('gives an explicit custom collision precedence and restores the machine overlay', () => {
|
||||
registerCustom([{
|
||||
id: '0577', n: 'Owner machine press correction', bp: 'chest',
|
||||
primaries: ['triceps'], secondaries: []
|
||||
}])
|
||||
expect(EXIDX['0577']).toMatchObject({ primaries: ['triceps'], secondaries: [] })
|
||||
expect(musclesOf(EXIDX['0577'])).toEqual({ triceps: 1 })
|
||||
registerCustom([])
|
||||
expect(EXIDX['0577']).toMatchObject(MACHINE_BATCH_2['0577'])
|
||||
expect(musclesOf(EXIDX['0577'])).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4, biceps: 0.4 })
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,29 @@
|
||||
import { EXDB } from './exercises-data.js'
|
||||
import { USER_EXERCISE_MUSCLE_OVERRIDES, exerciseMuscleMetadataFor } from './exercise-muscle-batch-1.js'
|
||||
import { t, getVersion, exerciseNameSearchText } from './i18n-core.js'
|
||||
|
||||
export { EXDB }
|
||||
|
||||
// The generated dataset remains the compatibility/raw export. The runtime catalogue applies
|
||||
// owner-approved muscle metadata as a narrow overlay, so imports and historical tests that rely
|
||||
// on the upstream shape keep working while EXIDX and pickers see the corrected model.
|
||||
const catalogueExercise = ex => {
|
||||
const metadata = exerciseMuscleMetadataFor(ex?.id)
|
||||
if (!Object.keys(metadata).length) return ex
|
||||
const out = { ...ex, ...metadata }
|
||||
const user = USER_EXERCISE_MUSCLE_OVERRIDES[ex?.id] || {}
|
||||
// A future dataset row may carry explicit arrays of its own; preserve those over generated
|
||||
// defaults unless the owner has deliberately supplied a correction for the same field.
|
||||
for (const key of ['primaries', 'secondaries']) {
|
||||
if (Object.prototype.hasOwnProperty.call(ex, key) && !Object.prototype.hasOwnProperty.call(user, key)) out[key] = ex[key]
|
||||
}
|
||||
if (Array.isArray(out.primaries)) out.primaries = [...out.primaries]
|
||||
if (Array.isArray(out.secondaries)) out.secondaries = [...out.secondaries]
|
||||
return out
|
||||
}
|
||||
|
||||
export const CATALOGUE = EXDB.map(catalogueExercise)
|
||||
|
||||
// The generated dataset already supplies secondary muscles for most exercises. Keep the
|
||||
// handful of conservative catalogue additions that are useful to the muscle map here so a
|
||||
// dataset refresh does not erase them. Values follow the dataset's existing alias vocabulary.
|
||||
@@ -23,8 +44,8 @@ export const smOf = ex => {
|
||||
}
|
||||
|
||||
export const EXIDX = {}
|
||||
EXDB.forEach(e => { EXIDX[e.id] = e })
|
||||
export const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort()
|
||||
CATALOGUE.forEach(e => { EXIDX[e.id] = e })
|
||||
export const BODYPARTS = [...new Set(CATALOGUE.map(e => e.bp))].sort()
|
||||
|
||||
// Equipment options present in a given list of exercises, most common first (issue #6).
|
||||
// Deriving them from the *already filtered* list keeps the chip row short and means
|
||||
@@ -39,25 +60,78 @@ export function equipmentOf(list) {
|
||||
// merged into the id index here so every EXIDX[id] lookup keeps working unchanged.
|
||||
let customIds = []
|
||||
export function registerCustom(list) {
|
||||
customIds.forEach(id => delete EXIDX[id])
|
||||
customIds.forEach(id => {
|
||||
delete EXIDX[id]
|
||||
const builtIn = CATALOGUE.find(ex => ex.id === id)
|
||||
if (builtIn) EXIDX[id] = builtIn
|
||||
})
|
||||
customIds = (list || []).map(e => e.id)
|
||||
;(list || []).forEach(e => { EXIDX[e.id] = e })
|
||||
}
|
||||
// Full searchable catalogue — customs first so your own exercises are easy to find.
|
||||
export const allExercises = st => [...(st.customEx || []), ...EXDB]
|
||||
export const allExercises = st => [...(st.customEx || []), ...CATALOGUE]
|
||||
|
||||
function searchableText(value) {
|
||||
if (Array.isArray(value)) return value.map(searchableText).join(' ')
|
||||
if (value == null) return ''
|
||||
try { return String(value) } catch { return '' }
|
||||
}
|
||||
|
||||
/** Case-insensitive search over built-in and legacy custom exercise metadata. */
|
||||
function isSubsequence(needle, hay) {
|
||||
let i = 0
|
||||
for (const ch of hay) {
|
||||
if (ch === needle[i]) i++
|
||||
if (i === needle.length) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Fuzzy match score for one exercise against a query. Best hits: exact field match, then
|
||||
// field prefix, then word-boundary starts, then substrings (closer to the start scores
|
||||
// better), and finally typo-tolerant ordered subsequences. Fields are weighted - the name
|
||||
// dominates, target/equipment matter, muscles and description are supporting evidence.
|
||||
// 0 means no match, so matchesExerciseSearch stays a boolean filter while the picker can
|
||||
// rank results by score.
|
||||
export function searchScore(exercise, query) {
|
||||
const needle = searchableText(query).toLowerCase().trim()
|
||||
if (!needle) return 1
|
||||
const source = exercise && typeof exercise === 'object' ? exercise : {}
|
||||
const fields = [['n', 100], ['tg', 40], ['eq', 40], ['sm', 30], ['muscleGroups', 30], ['primaries', 30], ['secondaries', 30], ['desc', 10], ['cues', 10]]
|
||||
// Token-level matching: every query word must match somewhere (any order), so
|
||||
// "press bench" finds "Bench Press". The score sums each token's best hit.
|
||||
const tokens = needle.split(/[^a-z0-9]+/).filter(Boolean)
|
||||
if (!tokens.length) return 0
|
||||
let total = 0
|
||||
for (const token of tokens) {
|
||||
let best = 0
|
||||
for (const [field, weight] of fields) {
|
||||
const hay = searchableText(source[field]).toLowerCase()
|
||||
if (!hay) continue
|
||||
if (hay === token) best = Math.max(best, weight * 4)
|
||||
else if (hay.startsWith(token)) best = Math.max(best, weight * 3)
|
||||
const idx = hay.indexOf(token)
|
||||
if (idx > 0) best = Math.max(best, weight * 2 - Math.min(idx, 20) * 0.5)
|
||||
if (hay.split(/[^a-z0-9]+/).some(w => w.startsWith(token))) best = Math.max(best, weight * 2.5)
|
||||
if (isSubsequence(token, hay)) best = Math.max(best, weight + Math.max(0, 10 - (hay.length - token.length)))
|
||||
}
|
||||
if (!best) return 0 // every token must match
|
||||
total += best
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
export function matchesExerciseSearch(exercise, query) {
|
||||
return searchScore(exercise, query) > 0
|
||||
}
|
||||
|
||||
// Media normally sits next to the app (img/ and gif/, mounted into the web container).
|
||||
// A build can point them somewhere else — the demo build pulls them off a CDN instead of
|
||||
// shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain
|
||||
// Node; the guard keeps this module loadable without Vite.
|
||||
// The defaults are absolute on purpose (issue #79). A bare 'img/' resolves against the
|
||||
// current document's directory, so on the one two-segment route in the app, /plan/r/:id,
|
||||
// every request went to /plan/r/img/… and 404'd — and nginx's extension block has no
|
||||
// try_files, so it 404s rather than falling through to index.html, leaving a blank image
|
||||
// and nothing in the console.
|
||||
const ENV = import.meta.env || {}
|
||||
const IMG_BASE = ENV.VITE_IMG_BASE || '/img/'
|
||||
const GIF_BASE = ENV.VITE_GIF_BASE || '/gif/'
|
||||
const IMG_BASE = ENV.VITE_IMG_BASE || 'img/'
|
||||
const GIF_BASE = ENV.VITE_GIF_BASE || 'gif/'
|
||||
export const imgSrc = ex => IMG_BASE + ex.img
|
||||
export const gifSrc = ex => GIF_BASE + ex.gif
|
||||
|
||||
|
||||
+63
-15
@@ -65,6 +65,7 @@ const BY_BODYPART = {
|
||||
'upper legs': { quadriceps: 0.4, hamstring: 0.35, gluteal: 0.25 },
|
||||
'lower legs': { calves: 0.8, tibialis: 0.2 },
|
||||
neck: { trapezius: 1 },
|
||||
'full body': { chest: 0.2, 'upper-back': 0.2, gluteal: 0.2, quadriceps: 0.2, hamstring: 0.1, abs: 0.1 },
|
||||
cardio: {},
|
||||
}
|
||||
|
||||
@@ -72,18 +73,40 @@ const SECONDARY = 0.4 // a supporting muscle counts this much against a primar
|
||||
|
||||
const arrayOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]
|
||||
|
||||
function firstPresent(object, keys) {
|
||||
if (!object || typeof object !== 'object') return null
|
||||
for (const key of keys) {
|
||||
if (Object.prototype.hasOwnProperty.call(object, key)) return object[key]
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Completed history entries may retain a nested snapshot after their custom exercise is
|
||||
// deleted from the profile catalogue. Prefer that snapshot when the outer entry has no muscle
|
||||
// metadata of its own, while keeping direct/legacy entry fields authoritative when present.
|
||||
function metadataOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return ex
|
||||
const hasDirect = ['muscleGroups', 'muscles', 'targetMuscles'].some(key => Object.prototype.hasOwnProperty.call(ex, key))
|
||||
const DIRECT_KEYS = [
|
||||
'muscleGroups', 'muscles', 'targetMuscles', 'muscleWeights',
|
||||
'primaries', 'primaryMuscles', 'primary', 'secondaries', 'secondaryMuscles', 'secondary',
|
||||
]
|
||||
const hasDirect = DIRECT_KEYS.some(key => Object.prototype.hasOwnProperty.call(ex, key))
|
||||
|| [ex.tg, ex.mg, ...arrayOf(ex.sm)].some(value => value != null && value !== '')
|
||||
return !hasDirect && ex.muscleSnapshot && typeof ex.muscleSnapshot === 'object' && !Array.isArray(ex.muscleSnapshot)
|
||||
? ex.muscleSnapshot
|
||||
: ex
|
||||
}
|
||||
|
||||
function explicitPartsOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return null
|
||||
const primary = firstPresent(ex, ['primaries', 'primaryMuscles', 'primary'])
|
||||
const secondary = firstPresent(ex, ['secondaries', 'secondaryMuscles', 'secondary'])
|
||||
if (primary !== null || secondary !== null) return {
|
||||
primary: arrayOf(primary), secondary: arrayOf(secondary)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function explicitGroupsOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return null
|
||||
if (Object.prototype.hasOwnProperty.call(ex, 'muscleGroups')) {
|
||||
@@ -102,12 +125,14 @@ function explicitGroupsOf(ex) {
|
||||
}
|
||||
|
||||
/** True only when the catalogue explicitly supplied muscle groups, not a body-part fallback. */
|
||||
export function hasExplicitMuscleMetadata(ex) {
|
||||
const source = metadataOf(ex)
|
||||
if (!source || typeof source !== 'object') return false
|
||||
const groups = explicitGroupsOf(source)
|
||||
export function hasExplicitMuscleMetadata(entry) {
|
||||
const ex = metadataOf(entry)
|
||||
if (!ex || typeof ex !== 'object') return false
|
||||
const parts = explicitPartsOf(ex)
|
||||
if (parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))) return true
|
||||
const groups = explicitGroupsOf(ex)
|
||||
if (groups && groups.some(value => canonicalMuscle(value))) return true
|
||||
return [source.tg, source.mg, ...arrayOf(source.sm)].some(value => canonicalMuscle(value))
|
||||
return [ex.tg, ex.mg, ...arrayOf(smOf(ex))].some(value => canonicalMuscle(value))
|
||||
}
|
||||
|
||||
function canonicalMuscle(value) {
|
||||
@@ -116,17 +141,28 @@ function canonicalMuscle(value) {
|
||||
return ALIAS[name] || null
|
||||
}
|
||||
|
||||
/** Canonical unique muscle groups, accepting both new arrays and legacy single fields. */
|
||||
export function muscleGroupsOf(ex) {
|
||||
const sourceEx = metadataOf(ex)
|
||||
const explicit = explicitGroupsOf(sourceEx)
|
||||
const source = explicit || [sourceEx?.tg, sourceEx?.mg, ...arrayOf(smOf(sourceEx))]
|
||||
function canonicalUnique(values) {
|
||||
const out = []
|
||||
source.forEach(value => {
|
||||
for (const value of values || []) {
|
||||
const slug = canonicalMuscle(value)
|
||||
if (slug && !out.includes(slug)) out.push(slug)
|
||||
})
|
||||
if (!out.length && explicit == null) Object.keys(BY_BODYPART[sourceEx?.bp] || {}).forEach(slug => { if (!out.includes(slug)) out.push(slug) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Canonical unique muscle groups, accepting new primary/secondary arrays and legacy fields. */
|
||||
export function muscleGroupsOf(entry) {
|
||||
const ex = metadataOf(entry)
|
||||
const parts = explicitPartsOf(ex)
|
||||
const explicit = explicitGroupsOf(ex)
|
||||
const useParts = parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))
|
||||
const source = useParts
|
||||
? [...parts.primary, ...parts.secondary]
|
||||
: explicit || [ex?.tg, ex?.mg, ...arrayOf(smOf(ex))]
|
||||
const out = canonicalUnique(source)
|
||||
if (!out.length && !useParts && explicit == null) {
|
||||
canonicalUnique(Object.keys(BY_BODYPART[ex?.bp] || {})).forEach(slug => out.push(slug))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -158,8 +194,13 @@ export function musclesOf(ex) {
|
||||
const slug = canonicalMuscle(name)
|
||||
if (slug) out[slug] = Math.max(out[slug] || 0, w)
|
||||
}
|
||||
const parts = explicitPartsOf(ex)
|
||||
const explicit = explicitGroupsOf(ex)
|
||||
if (explicit) explicit.forEach(m => add(m, 1))
|
||||
const useParts = parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))
|
||||
if (useParts) {
|
||||
parts.primary.forEach(m => add(m, 1))
|
||||
parts.secondary.forEach(m => add(m, SECONDARY))
|
||||
} else if (explicit) explicit.forEach(m => add(m, 1))
|
||||
else {
|
||||
add(ex.tg, 1)
|
||||
add(ex.mg, SECONDARY)
|
||||
@@ -178,6 +219,13 @@ export function exerciseMuscleSnapshot(ex) {
|
||||
if (ex.bp != null) out.bp = ex.bp
|
||||
const weights = musclesOf(ex)
|
||||
if (Object.keys(weights).length) out.muscleWeights = { ...weights }
|
||||
const parts = explicitPartsOf(ex)
|
||||
if (parts) {
|
||||
const primaries = canonicalUnique(parts.primary)
|
||||
const secondaries = canonicalUnique(parts.secondary).filter(slug => !primaries.includes(slug))
|
||||
if (primaries.length) out.primaries = primaries
|
||||
if (secondaries.length) out.secondaries = secondaries
|
||||
}
|
||||
if (hasExplicitMuscleMetadata(ex)) out.muscleGroups = [...muscleGroupsOf(ex)]
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -1,9 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { EXIDX, EXDB, smOf } from './exercises.js'
|
||||
import { loadOfWorkouts, musclesOf } from './muscles.js'
|
||||
import { MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, loadOf, loadOfWorkouts, matchesMuscleGroups, muscleGroupsOf, musclesOf } from './muscles.js'
|
||||
|
||||
describe('multi-muscle exercise metadata', () => {
|
||||
it('normalizes legacy primary/secondary fields and removes duplicate groups', () => {
|
||||
const ex = { tg: 'pectorals', mg: 'triceps', sm: ['triceps', 'chest'] }
|
||||
expect(muscleGroupsOf(ex)).toEqual(['chest', 'triceps'])
|
||||
expect(musclesOf(ex)).toEqual({ chest: 1, triceps: 0.4 })
|
||||
})
|
||||
|
||||
it('uses explicit multi-group metadata when present and supports legacy single groups', () => {
|
||||
expect(muscleGroupsOf({ muscleGroups: ['chest', 'pectorals', 'triceps'] })).toEqual(['chest', 'triceps'])
|
||||
expect(muscleGroupsOf({ tg: 'chest' })).toEqual(['chest'])
|
||||
expect(MUSCLE_NAME.chest).toBe('Chest')
|
||||
})
|
||||
|
||||
it('falls back to the legacy body-part map when an optional multi-group field is empty', () => {
|
||||
expect(muscleGroupsOf({ bp: 'back', muscleGroups: [] })).toEqual(['upper-back', 'lower-back'])
|
||||
expect(matchesMuscleGroups({ bp: 'back', muscleGroups: [] }, ['lower-back'])).toBe(true)
|
||||
})
|
||||
|
||||
it('matches an exercise when any requested muscle group matches', () => {
|
||||
const ex = { muscleGroups: ['chest', 'triceps'] }
|
||||
expect(matchesMuscleGroups(ex, ['hamstring', 'triceps'])).toBe(true)
|
||||
expect(matchesMuscleGroups(ex, ['hamstring', 'gluteal'])).toBe(false)
|
||||
expect(matchesMuscleGroups(ex, [])).toBe(true)
|
||||
})
|
||||
|
||||
it('counts one effective set per unique group instead of double counting duplicates', () => {
|
||||
expect(loadOf([{ id: 'inline', ex: { tg: 'chest', sm: ['chest', 'triceps'] }, sets: 2 }]))
|
||||
.toEqual({ chest: 2, triceps: 0.8 })
|
||||
})
|
||||
|
||||
it('uses multi-muscle metadata carried by a history entry when its catalogue id is unavailable', () => {
|
||||
expect(loadOfWorkouts([{ entries: [{
|
||||
id: 'deleted-custom', muscleGroups: ['chest', 'chest', 'triceps'],
|
||||
sets: [{ done: true }]
|
||||
}] }])).toEqual({ chest: 1, triceps: 1 })
|
||||
})
|
||||
})
|
||||
|
||||
// The catalogue keeps the source dataset's secondary-muscle spellings; musclesOf maps
|
||||
// those aliases to the canonical body-map slugs and applies the 0.4 support weight.
|
||||
describe('catalogue secondary muscles', () => {
|
||||
it('maps a bench press to chest, triceps and deltoids', () => {
|
||||
expect(musclesOf(EXIDX['0025'])).toMatchObject({
|
||||
@@ -16,7 +52,7 @@ describe('catalogue secondary muscles', () => {
|
||||
it('maps a squat to glutes, quads and hamstrings', () => {
|
||||
expect(musclesOf(EXIDX['0043'])).toMatchObject({
|
||||
gluteal: 1,
|
||||
quadriceps: 0.4,
|
||||
quadriceps: 1,
|
||||
hamstring: 0.4,
|
||||
})
|
||||
})
|
||||
@@ -44,6 +80,46 @@ describe('catalogue secondary additions', () => {
|
||||
})
|
||||
|
||||
|
||||
describe('explicit multi-primary metadata', () => {
|
||||
it('gives every primary full weight and secondaries supporting weight', () => {
|
||||
const ex = {
|
||||
bp: 'chest', tg: 'abs', mg: 'triceps', sm: ['lower back'],
|
||||
primaries: ['chest', 'triceps', 'chest'], secondaries: ['deltoids', 'triceps']
|
||||
}
|
||||
expect(muscleGroupsOf(ex)).toEqual(['chest', 'triceps', 'deltoids'])
|
||||
expect(musclesOf(ex)).toEqual({ chest: 1, triceps: 1, deltoids: 0.4 })
|
||||
})
|
||||
|
||||
it('keeps the body-part fallback when primaries are absent or explicitly empty', () => {
|
||||
const expected = { 'upper-back': 0.75, 'lower-back': 0.25 }
|
||||
expect(musclesOf({ bp: 'back' })).toEqual(expected)
|
||||
expect(musclesOf({ bp: 'back', primaries: [] })).toEqual(expected)
|
||||
})
|
||||
|
||||
it('keeps legacy metadata when a new array field is present but empty', () => {
|
||||
expect(exerciseMuscleSnapshot({ bp: 'chest', tg: 'abs', primaries: [] })).toMatchObject({
|
||||
muscleGroups: ['abs']
|
||||
})
|
||||
})
|
||||
|
||||
it('provides a conservative Full body fallback for legacy custom exercises', () => {
|
||||
expect(muscleGroupsOf({ bp: 'full body' })).toEqual(['chest', 'upper-back', 'gluteal', 'quadriceps', 'hamstring', 'abs'])
|
||||
expect(musclesOf({ bp: 'full body' })).toEqual({
|
||||
chest: 0.2, 'upper-back': 0.2, gluteal: 0.2, quadriceps: 0.2, hamstring: 0.1, abs: 0.1
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves explicit primary and secondary arrays in history snapshots', () => {
|
||||
expect(exerciseMuscleSnapshot({
|
||||
n: 'Deadlift', bp: 'full body', primaries: ['gluteal', 'lower-back'], secondaries: ['hamstring']
|
||||
})).toMatchObject({
|
||||
n: 'Deadlift', bp: 'full body', primaries: ['gluteal', 'lower-back'], secondaries: ['hamstring'],
|
||||
muscleGroups: ['gluteal', 'lower-back', 'hamstring']
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('map load with warm-up phases', () => {
|
||||
it('excludes warm-up sets from the by-sets-worked map', () => {
|
||||
const w = {
|
||||
@@ -60,3 +136,39 @@ describe('map load with warm-up phases', () => {
|
||||
expect(load.chest).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
// A custom exercise that was deleted from the catalogue survives in history only as the
|
||||
// muscleSnapshot finish-workout wrote. Reading it back is what keeps those sessions in the
|
||||
// body map and in Stats instead of silently contributing nothing.
|
||||
describe('deleted custom exercises', () => {
|
||||
const snapshotEntry = {
|
||||
id: 'gone-custom-1',
|
||||
sets: [{ w: 60, r: 8, done: true }],
|
||||
muscleSnapshot: { n: 'Deleted custom', bp: 'chest', muscleGroups: ['chest'], muscleWeights: { chest: 1 } },
|
||||
}
|
||||
|
||||
it('reads muscle load back out of the snapshot', () => {
|
||||
expect(loadOfWorkouts([{ d: '2026-08-01', entries: [snapshotEntry] }])).toEqual({ chest: 1 })
|
||||
})
|
||||
|
||||
it('reports the snapshot groups as explicit metadata', () => {
|
||||
expect(hasExplicitMuscleMetadata(snapshotEntry)).toBe(true)
|
||||
expect(muscleGroupsOf(snapshotEntry)).toEqual(['chest'])
|
||||
})
|
||||
|
||||
it('still prefers the entry\'s own metadata when it has any', () => {
|
||||
const withOwn = { ...snapshotEntry, tg: 'quadriceps' }
|
||||
expect(muscleGroupsOf(withOwn)).toEqual(['quadriceps'])
|
||||
})
|
||||
})
|
||||
|
||||
// muscles.js counts completed work, so its warm-up boundary has to agree with the one the
|
||||
// session runtime uses — including the legacy spellings phaseForSet normalises.
|
||||
describe('warm-up boundary', () => {
|
||||
it('excludes every phase spelling the workout model treats as a warm-up', () => {
|
||||
const entries = spelling => [{ id: '0025', sets: [{ w: 100, r: 5, done: true, phase: spelling }] }]
|
||||
for (const spelling of ['warmup', 'warm-up', 'warm_up', 'Warmup', ' warmup ']) {
|
||||
expect(loadOfWorkouts([{ d: '2026-08-01', entries: entries(spelling) }]), spelling).toEqual({})
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -28,10 +28,10 @@ describe('Brazilian Portuguese locale', () => {
|
||||
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
|
||||
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(260)
|
||||
expect(inherited).toHaveLength(413)
|
||||
expect(inherited).toHaveLength(416)
|
||||
// If this fails, review the changed keys and wording before accepting a new hash. From
|
||||
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('241f027658796cc753f7f81f9e7511c02cc93c4d4480e98c532fe7b47f331beb')
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('4c32711daa44d6d35d775efd5324036d351b2d6c61d06c734e813b7096f8f704')
|
||||
})
|
||||
|
||||
test('does not leak European Portuguese UI terms', () => {
|
||||
|
||||
Reference in new issue
Block a user