feat: extract exercise catalogue and logging
This commit is contained in:
1 parent
f8024d344d
commit
c8f4d5bd18
22 files changed
+3188
-48
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 } 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
|
||||
|
||||
|
||||
+56
-26
@@ -7,11 +7,13 @@
|
||||
// map can actually draw, via ALIAS below. Anything genuinely undrawable (hands,
|
||||
// ankles, "cardiovascular system") maps to null and is dropped rather than guessed at.
|
||||
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { EXIDX, smOf } from './exercises.js'
|
||||
|
||||
// The muscles a map can shade, in head-to-toe order — also the order of any list
|
||||
// built from them, so "what am I neglecting" reads top-down like a body.
|
||||
/** Completed-work boundary shared with the session runtime: warm-up rows never count. */
|
||||
const isWarmupRow = set => !!(set && (set.phase === 'warmup' || set.warmup === true))
|
||||
|
||||
export const MUSCLES = [
|
||||
'trapezius', 'deltoids', 'chest', 'upper-back', 'serratus',
|
||||
'biceps', 'triceps', 'forearm',
|
||||
@@ -65,6 +67,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,16 +75,22 @@ const SECONDARY = 0.4 // a supporting muscle counts this much against a primar
|
||||
|
||||
const arrayOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]
|
||||
|
||||
// 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))
|
||||
|| [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 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
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -103,11 +112,12 @@ 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)
|
||||
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 +126,27 @@ 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(ex) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -143,8 +163,6 @@ export function matchesMuscleGroups(ex, requested) {
|
||||
/** Muscles one exercise trains: { slug: 0…1 }. Duplicate metadata never adds load twice. */
|
||||
export function musclesOf(ex) {
|
||||
if (!ex) return {}
|
||||
const sourceEx = metadataOf(ex)
|
||||
if (sourceEx !== ex) return musclesOf(sourceEx)
|
||||
if (ex.muscleWeights && typeof ex.muscleWeights === 'object' && !Array.isArray(ex.muscleWeights)) {
|
||||
const snapshot = {}
|
||||
MUSCLES.forEach(slug => {
|
||||
@@ -158,8 +176,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 +201,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, 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 = {
|
||||
|
||||
@@ -596,5 +596,8 @@ export default {
|
||||
'secondary': 'sekundär',
|
||||
'No exercises with an estimated 1RM yet.': 'Noch keine Übungen mit geschätztem 1RM.',
|
||||
'Tap a muscle to see its exercises.': 'Tippe auf einen Muskel, um seine Übungen zu sehen.',
|
||||
'Primary muscle groups': 'Primäre Muskelgruppen',
|
||||
'Additional muscle groups': 'Zusätzliche Muskelgruppen',
|
||||
'No explicit muscle group': 'Keine explizite Muskelgruppe',
|
||||
'Unpair': 'Trennen'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': 'secundario',
|
||||
'No exercises with an estimated 1RM yet.': 'Aún no hay ejercicios con 1RM estimado.',
|
||||
'Tap a muscle to see its exercises.': 'Toca un músculo para ver sus ejercicios.',
|
||||
'Primary muscle groups': 'Grupos musculares primarios',
|
||||
'Additional muscle groups': 'Grupos musculares adicionales',
|
||||
'No explicit muscle group': 'Sin grupo muscular explícito',
|
||||
'Unpair': 'Desvincular'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': 'secondaire',
|
||||
"No exercises with an estimated 1RM yet.": "Aucun exercice avec un 1RM estimé pour l'instant.",
|
||||
'Tap a muscle to see its exercises.': 'Touchez un muscle pour voir ses exercices.',
|
||||
'Primary muscle groups': 'Groupes musculaires principaux',
|
||||
'Additional muscle groups': 'Groupes musculaires supplémentaires',
|
||||
'No explicit muscle group': 'Aucun groupe musculaire explicite',
|
||||
'Unpair': 'Dissocier'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': 'द्वितीयक',
|
||||
'No exercises with an estimated 1RM yet.': 'अभी तक अनुमानित 1RM वाला कोई व्यायाम नहीं।',
|
||||
'Tap a muscle to see its exercises.': 'व्यायाम देखने के लिए किसी मांसपेशी पर टैप करें।',
|
||||
'Primary muscle groups': 'प्राथमिक मांसपेशी समूह',
|
||||
'Additional muscle groups': 'अतिरिक्त मांसपेशी समूह',
|
||||
'No explicit muscle group': 'कोई स्पष्ट मांसपेशी समूह नहीं',
|
||||
'Unpair': 'अलग करें'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': 'secondario',
|
||||
'No exercises with an estimated 1RM yet.': 'Nessun esercizio con 1RM stimato finora.',
|
||||
'Tap a muscle to see its exercises.': 'Tocca un muscolo per vedere i suoi esercizi.',
|
||||
'Primary muscle groups': 'Gruppi muscolari primari',
|
||||
'Additional muscle groups': 'Gruppi muscolari aggiuntivi',
|
||||
'No explicit muscle group': 'Nessun gruppo muscolare esplicito',
|
||||
'Unpair': 'Separa'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': '보조',
|
||||
'No exercises with an estimated 1RM yet.': '추정 1RM이 있는 운동이 아직 없습니다.',
|
||||
'Tap a muscle to see its exercises.': '근육을 눌러 해당 운동을 확인하세요.',
|
||||
'Primary muscle groups': '주요 근육 그룹',
|
||||
'Additional muscle groups': '추가 근육군',
|
||||
'No explicit muscle group': '명시적 근육군 없음',
|
||||
'Unpair': '분리'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': 'drugorzędny',
|
||||
'No exercises with an estimated 1RM yet.': 'Brak ćwiczeń z oszacowanym 1RM.',
|
||||
'Tap a muscle to see its exercises.': 'Dotknij mięśnia, aby zobaczyć jego ćwiczenia.',
|
||||
'Primary muscle groups': 'Podstawowe grupy mięśniowe',
|
||||
'Additional muscle groups': 'Dodatkowe grupy mięśniowe',
|
||||
'No explicit muscle group': 'Brak jawnej grupy mięśniowej',
|
||||
'Unpair': 'Rozłącz'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': 'secundário',
|
||||
'No exercises with an estimated 1RM yet.': 'Ainda não há exercícios com 1RM estimado.',
|
||||
'Tap a muscle to see its exercises.': 'Toque num músculo para ver os seus exercícios.',
|
||||
'Primary muscle groups': 'Grupos musculares primários',
|
||||
'Additional muscle groups': 'Grupos musculares adicionais',
|
||||
'No explicit muscle group': 'Nenhum grupo muscular explícito',
|
||||
'Unpair': 'Desfazer'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': 'вспомогательная',
|
||||
'No exercises with an estimated 1RM yet.': 'Пока нет упражнений с расчётным 1ПМ.',
|
||||
'Tap a muscle to see its exercises.': 'Нажмите на мышцу, чтобы увидеть её упражнения.',
|
||||
'Primary muscle groups': 'Основные группы мышц',
|
||||
'Additional muscle groups': 'Дополнительные мышечные группы',
|
||||
'No explicit muscle group': 'Без явной мышечной группы',
|
||||
'Unpair': 'Разъединить'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': 'ikincil',
|
||||
'No exercises with an estimated 1RM yet.': 'Henüz tahmini 1RM olan egzersiz yok.',
|
||||
'Tap a muscle to see its exercises.': 'Egzersizlerini görmek için bir kas seçin.',
|
||||
'Primary muscle groups': 'Birincil kas grupları',
|
||||
'Additional muscle groups': 'Ek kas grupları',
|
||||
'No explicit muscle group': 'Açık kas grubu yok',
|
||||
'Unpair': 'Ayır'
|
||||
}
|
||||
@@ -579,5 +579,8 @@ export default {
|
||||
'secondary': '次要',
|
||||
'No exercises with an estimated 1RM yet.': '暂无估算1RM的动作。',
|
||||
'Tap a muscle to see its exercises.': '点击肌肉查看其动作。',
|
||||
'Primary muscle groups': '主要肌群',
|
||||
'Additional muscle groups': '其他肌群',
|
||||
'No explicit muscle group': '无明确肌群',
|
||||
'Unpair': '取消组合'
|
||||
}
|
||||
+33
-6
@@ -11,10 +11,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 } from './components/ui.jsx'
|
||||
import { Button, Slider, Switch, Segmented, SelectRow, Row, 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'
|
||||
@@ -291,9 +291,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>}
|
||||
@@ -348,6 +348,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 }
|
||||
@@ -355,11 +367,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))
|
||||
@@ -372,6 +389,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)} />
|
||||
|
||||
Reference in new issue
Block a user