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
@@ -274,6 +274,48 @@ export function SelectRow({ icon, iconTint, title, value, options, onChange, she
|
||||
)
|
||||
}
|
||||
|
||||
/** Multi-select row for additive exercise metadata. The sheet mirrors selection locally so
|
||||
* each tap updates its checkmark immediately while the caller persists the value. */
|
||||
export function MultiSelectRow({ icon, iconTint, title, values, options, onToggle, sheetTitle, noneLabel, doneLabel }) {
|
||||
const selected = options.filter(o => values.includes(o.value))
|
||||
const summary = selected.length ? selected.map(o => o.label).join(', ') : (noneLabel || '')
|
||||
const open = () => {
|
||||
const { openSheet } = require_ui()
|
||||
openSheet(close => <MultiSelectSheet values={values} options={options} onToggle={onToggle}
|
||||
title={sheetTitle || title} doneLabel={doneLabel} close={close} />)
|
||||
}
|
||||
return (
|
||||
<Row icon={icon} iconTint={iconTint} title={title} value={summary} accessory="chevron" onClick={open} />
|
||||
)
|
||||
}
|
||||
|
||||
function MultiSelectSheet({ values, options, onToggle, title, doneLabel, close }) {
|
||||
const [sel, setSel] = useState(values)
|
||||
const toggle = value => {
|
||||
setSel(current => current.includes(value) ? current.filter(x => x !== value) : [...current, value])
|
||||
onToggle(value)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<h3>{title}</h3>
|
||||
<div className="sect-b">
|
||||
{options.map(o => {
|
||||
const on = sel.includes(o.value)
|
||||
return (
|
||||
<button key={o.value} className={'lrow tap' + (on ? ' on' : '')} onClick={() => toggle(o.value)}>
|
||||
<span className="lrow-m"><span className="lrow-t">{o.label}</span>
|
||||
{o.subtitle && <span className="lrow-s">{o.subtitle}</span>}</span>
|
||||
{on && <Icon name="check" className="lrow-k" />}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div style={{ height: 8 }} />
|
||||
<Button variant="primary" onClick={close}>{doneLabel || 'Done'}</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// Late import keeps this module free of a cycle at load time (useUI pulls in the
|
||||
// store, which pulls in helpers that import controls).
|
||||
let _ui = null
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -618,4 +618,9 @@ export default {
|
||||
'Delete profile?': 'Profil löschen?',
|
||||
'"{0}" and its equipment list will be removed.': '„{0}“ und die zugehörige Geräteliste werden entfernt.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtert die Übungsbibliothek und die Auswahl und markiert Übungen in Routinen, die Geräte brauchen, die du im aktiven Profil nicht hast.',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Primäre Muskelgruppen',
|
||||
'Additional muscle groups': 'Zusätzliche Muskelgruppen',
|
||||
'No explicit muscle group': 'Keine explizite Muskelgruppe'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': '¿Eliminar perfil?',
|
||||
'"{0}" and its equipment list will be removed.': '«{0}» y su lista de equipo se eliminarán.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtra la biblioteca de ejercicios y el selector, y marca los ejercicios de las rutinas que necesitan algo que no tienes en el perfil activo.',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Grupos musculares primarios',
|
||||
'Additional muscle groups': 'Grupos musculares adicionales',
|
||||
'No explicit muscle group': 'Sin grupo muscular explícito'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': 'Supprimer le profil ?',
|
||||
'"{0}" and its equipment list will be removed.': '« {0} » et sa liste d’équipement seront supprimés.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtre la bibliothèque d’exercices et le sélecteur, et signale les exercices de routine qui nécessitent quelque chose que tu n’as pas dans le profil actif.',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Groupes musculaires principaux',
|
||||
'Additional muscle groups': 'Groupes musculaires supplémentaires',
|
||||
'No explicit muscle group': 'Aucun groupe musculaire explicite'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': 'प्रोफ़ाइल हटाएँ?',
|
||||
'"{0}" and its equipment list will be removed.': '“{0}” और उसकी उपकरण सूची हटा दी जाएगी।',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'कसरत लाइब्रेरी और चयनकर्ता को फ़िल्टर करता है, और उन रूटीन कसरतों को चिह्नित करता है जिनके लिए सक्रिय प्रोफ़ाइल में मौजूद न होने वाला उपकरण चाहिए।',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'प्राथमिक मांसपेशी समूह',
|
||||
'Additional muscle groups': 'अतिरिक्त मांसपेशी समूह',
|
||||
'No explicit muscle group': 'कोई स्पष्ट मांसपेशी समूह नहीं'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': 'Eliminare il profilo?',
|
||||
'"{0}" and its equipment list will be removed.': '“{0}” e il suo elenco di attrezzi verranno rimossi.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtra la libreria degli esercizi e il selettore, e segnala gli esercizi delle routine che richiedono qualcosa che non hai nel profilo attivo.',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Gruppi muscolari primari',
|
||||
'Additional muscle groups': 'Gruppi muscolari aggiuntivi',
|
||||
'No explicit muscle group': 'Nessun gruppo muscolare esplicito'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': '프로필을 삭제할까요?',
|
||||
'"{0}" and its equipment list will be removed.': '‘{0}’과(와) 해당 장비 목록이 삭제됩니다.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': '운동 라이브러리와 선택기를 필터링하고, 활성 프로필에 없는 장비가 필요한 루틴 운동을 표시합니다.',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': '주요 근육 그룹',
|
||||
'Additional muscle groups': '추가 근육군',
|
||||
'No explicit muscle group': '명시적 근육군 없음'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': 'Usunąć profil?',
|
||||
'"{0}" and its equipment list will be removed.': '„{0}” i jego lista sprzętu zostaną usunięte.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtruje bibliotekę ćwiczeń i selektor oraz oznacza ćwiczenia w rutynach, które wymagają czegoś, czego nie masz w aktywnym profilu.',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Podstawowe grupy mięśniowe',
|
||||
'Additional muscle groups': 'Dodatkowe grupy mięśniowe',
|
||||
'No explicit muscle group': 'Brak jawnej grupy mięśniowej'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': 'Eliminar perfil?',
|
||||
'"{0}" and its equipment list will be removed.': '«{0}» e a respetiva lista de equipamento serão removidos.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtra a biblioteca de exercícios e o seletor, e assinala os exercícios das rotinas que precisam de algo que não tens no perfil ativo.',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Grupos musculares primários',
|
||||
'Additional muscle groups': 'Grupos musculares adicionais',
|
||||
'No explicit muscle group': 'Nenhum grupo muscular explícito'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': 'Удалить профиль?',
|
||||
'"{0}" and its equipment list will be removed.': '«{0}» и его список инвентаря будут удалены.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Фильтрует библиотеку упражнений и выбор, а также отмечает упражнения в программах, для которых нужно то, чего нет в активном профиле.',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Основные группы мышц',
|
||||
'Additional muscle groups': 'Дополнительные мышечные группы',
|
||||
'No explicit muscle group': 'Без явной мышечной группы'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': 'Profil silinsin mi?',
|
||||
'"{0}" and its equipment list will be removed.': '“{0}” ve ekipman listesi kaldırılacak.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Hareket kitaplığını ve seçiciyi filtreler, ayrıca aktif profilinde olmayan bir şeye ihtiyaç duyan rutin hareketlerini işaretler.',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Birincil kas grupları',
|
||||
'Additional muscle groups': 'Ek kas grupları',
|
||||
'No explicit muscle group': 'Açık kas grubu yok'
|
||||
}
|
||||
@@ -601,4 +601,9 @@ export default {
|
||||
'Delete profile?': '删除配置?',
|
||||
'"{0}" and its equipment list will be removed.': '“{0}”及其器械清单将被删除。',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': '筛选动作库和选择器,并标记训练计划中需要当前配置里没有的器械的动作。',
|
||||
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': '主要肌群',
|
||||
'Additional muscle groups': '其他肌群',
|
||||
'No explicit muscle group': '无明确肌群'
|
||||
}
|
||||
+33
-6
@@ -12,10 +12,10 @@ import { starterRoutines } from './lib/starter.js'
|
||||
import Media, { Thumb } from './components/Media.jsx'
|
||||
import Stepper from './components/Stepper.jsx'
|
||||
import Icon from './components/Icon.jsx'
|
||||
import { Button, Slider, Switch, Segmented, SelectRow, Row, TextField } from './components/ui.jsx'
|
||||
import { Button, Slider, Switch, Segmented, SelectRow, Row, TextField, MultiSelectRow } from './components/ui.jsx'
|
||||
import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
|
||||
import BodyMap from './components/BodyMap.jsx'
|
||||
import { exerciseMuscleSnapshot, loadOfWorkouts } from './lib/muscles.js'
|
||||
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata } from './lib/muscles.js'
|
||||
import { parseImport, mergeImport } from './lib/import-csv.js'
|
||||
import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'
|
||||
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
|
||||
@@ -292,9 +292,9 @@ function ExerciseDetail({ ex, close }) {
|
||||
<Media ex={ex} />
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0' }}>
|
||||
<span className="tag acc">{t(ex.bp)}</span>
|
||||
{ex.tg && <span className="tag"><Icon name="target" />{t(ex.tg)}</span>}
|
||||
{(ex.primaries?.length ? ex.primaries : (ex.tg ? [ex.tg] : [])).map((s, i) => <span key={i} className="tag"><Icon name="target" />{t(s)}</span>)}
|
||||
<span className="tag"><Icon name="dumbbell" />{t(ex.eq)}</span>
|
||||
{smOf(ex).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}
|
||||
{(ex.secondaries?.length ? ex.secondaries : smOf(ex)).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}
|
||||
</div>
|
||||
{ex.desc && <div className="exnote">{ex.desc}</div>}
|
||||
{best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent">{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}</div>}
|
||||
@@ -349,6 +349,18 @@ function CustomExForm({ existing, prefill, onDone, close }) {
|
||||
const [n, setN] = useState(existing ? existing.n : (prefill || ''))
|
||||
const [bp, setBp] = useState(existing ? existing.bp : '')
|
||||
const [desc, setDesc] = useState(existing ? (existing.desc || '') : '')
|
||||
const [primaries, setPrimaries] = useState(() => {
|
||||
if (existing && Array.isArray(existing.primaries) && existing.primaries.length) return [...existing.primaries]
|
||||
const norm = hasExplicitMuscleMetadata(existing || {}) ? normalizeMuscleGroups(existing || {}) : []
|
||||
return norm.length ? [norm[0]] : []
|
||||
})
|
||||
const [secondaries, setSecondaries] = useState(() => {
|
||||
if (existing && Array.isArray(existing.primaries) && existing.primaries.length) return [...(existing.secondaries || [])]
|
||||
const norm = hasExplicitMuscleMetadata(existing || {}) ? normalizeMuscleGroups(existing || {}) : []
|
||||
return norm.slice(1)
|
||||
})
|
||||
const togglePrimary = value => setPrimaries(current => current.includes(value) ? current.filter(m => m !== value) : [...current, value])
|
||||
const toggleSecondary = value => setSecondaries(current => current.includes(value) ? current.filter(m => m !== value) : [...current, value])
|
||||
const save = () => {
|
||||
const name = n.trim()
|
||||
if (!name) { toast(t('Give it a name')); return }
|
||||
@@ -356,11 +368,16 @@ function CustomExForm({ existing, prefill, onDone, close }) {
|
||||
const dup = allExercises(S()).find(e => e.n.toLowerCase() === name.toLowerCase() && e.id !== (existing || {}).id)
|
||||
if (dup) { toast(t('“{0}” already exists', dup.n)); return }
|
||||
const d = desc.trim().slice(0, 1000)
|
||||
const prim = [...primaries]
|
||||
const sm = secondaries.filter(m => !prim.includes(m))
|
||||
const groups = [...prim, ...sm]
|
||||
let id = existing && existing.id
|
||||
if (existing) update(s => { const c = (s.customEx || []).find(x => x.id === id); if (c) { c.n = name; c.bp = bp; c.desc = d } })
|
||||
if (existing) update(s => { const c = (s.customEx || []).find(x => x.id === id); if (c) {
|
||||
c.n = name; c.bp = bp; c.desc = d; c.tg = prim[0] || ''; c.sm = sm; c.muscleGroups = groups; c.primaries = prim; c.secondaries = sm
|
||||
} })
|
||||
else {
|
||||
id = 'c' + uid()
|
||||
update(s => { (s.customEx = s.customEx || []).push({ id, n: name, bp, desc: d, tg: '', eq: 'custom', custom: true }) })
|
||||
update(s => { (s.customEx = s.customEx || []).push({ id, n: name, bp, desc: d, tg: prim[0] || '', sm, muscleGroups: groups, primaries: prim, secondaries: sm, eq: 'custom', custom: true }) })
|
||||
}
|
||||
close()
|
||||
toast(existing ? t('Saved') : t('“{0}” created', name))
|
||||
@@ -373,6 +390,16 @@ function CustomExForm({ existing, prefill, onDone, close }) {
|
||||
<div className="chips" style={{ margin: '12px 0' }}>
|
||||
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => setBp(b)}>{t(b)}</button>)}
|
||||
</div>
|
||||
{bp && bp !== 'cardio' && <>
|
||||
<MultiSelectRow title={t('Primary muscle groups')} sheetTitle={t('Primary muscle groups')}
|
||||
values={primaries}
|
||||
options={MUSCLES.map(m => ({ value: m, label: t(MUSCLE_NAME[m]) }))}
|
||||
onToggle={togglePrimary} noneLabel={t('No explicit muscle group')} doneLabel={t('Done')} />
|
||||
<MultiSelectRow title={t('Additional muscle groups')} sheetTitle={t('Additional muscle groups')}
|
||||
values={secondaries}
|
||||
options={MUSCLES.filter(m => !primaries.includes(m)).map(m => ({ value: m, label: t(MUSCLE_NAME[m]) }))}
|
||||
onToggle={toggleSecondary} noneLabel={t('No explicit muscle group')} doneLabel={t('Done')} />
|
||||
</>}
|
||||
{bp === 'cardio' && <div className="small dim row" style={{ marginBottom: 10, gap: 5 }}><Icon name="figureRun" style={{ fontSize: 13 }} />{t('Cardio exercises log time + speed instead of weight × reps.')}</div>}
|
||||
<textarea className="input" rows={4} maxLength={1000} placeholder={t('Description (optional) — setup, cues, anything you want to remember')}
|
||||
value={desc} onChange={e => setDesc(e.target.value)} />
|
||||
|
||||
@@ -192,7 +192,7 @@ function MuscleBalance({ S }) {
|
||||
{sel && <>
|
||||
<h4 className="sec" style={{ marginTop: 14 }}>{t('Exercises')} · {t(MUSCLE_NAME[sel])}</h4>
|
||||
{muscleExercises.length ? muscleExercises.map(row => (
|
||||
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch' }}>
|
||||
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch', cursor: 'pointer' }} onClick={() => onExercise && onExercise(row.id)}>
|
||||
<span className="nm" style={{ whiteSpace: 'normal', lineHeight: 1.35, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
|
||||
<span style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{row.name}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { bestWeightForEntry, metricModeForEntry, metricRowsForEntry } from '../lib/history.js'
|
||||
|
||||
const source = readFileSync(new URL('./Stats.jsx', import.meta.url), 'utf8')
|
||||
|
||||
describe('Stats mixed-entry metric contract', () => {
|
||||
it('selects authoritative reps rows before timed rows without stale topW', () => {
|
||||
const entry = { target: { mode: 'time', sec: 60 }, topW: 200, sets: [
|
||||
{ phase: 'work', mode: 'reps', w: 100, r: 5, done: true },
|
||||
{ phase: 'work', mode: 'time', w: 200, sec: 60, done: true }
|
||||
] }
|
||||
expect(metricModeForEntry(entry)).toBe('reps')
|
||||
expect(metricRowsForEntry(entry, metricModeForEntry(entry))).toEqual([entry.sets[0]])
|
||||
expect(bestWeightForEntry(entry)).toBe(100)
|
||||
})
|
||||
|
||||
it('renders one clickable muscle exercise list rather than a duplicate non-clickable copy', () => {
|
||||
expect((source.match(/muscleExercises\.length \? muscleExercises\.map\(row =>/g) || []).length).toBe(1)
|
||||
expect(source).toContain('onClick={() => onExercise && onExercise(row.id)}')
|
||||
})
|
||||
|
||||
it('uses the shared metric mode and row helpers rather than entryMode as a chart gate', () => {
|
||||
expect(source).toContain('metricModeForEntry')
|
||||
expect(source).toContain('metricRowsForEntry')
|
||||
expect(source).toContain('bestWeightForEntry')
|
||||
expect(source).not.toContain('const loggedMode = entryMode(en)')
|
||||
expect(source).not.toContain('(en.topW || 0)')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user