Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

wip(catalogue): type filter in the library, description + fix link in the exercise sheet, pack languages from the catalogue

Duarte Santosacdb6fa2e2c6
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 9c45eee37..63f334cde 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -2095,3 +2095,4 @@ body.no-tabbar.resting #toast{bottom:calc(100px + var(--sab))}
[dir="rtl"] .hm-wrap,[dir="rtl"] .cal-grid{direction:ltr}
/* Tight tracking is tuned for Latin; Arabic is a connected script and gets none. */
[dir="rtl"] *{letter-spacing:0}
+.exfix-link{display:inline-flex;align-items:center;gap:5px;margin:14px 0 4px;color:var(--label-3);text-decoration:none}
diff --git a/frontend/src/lib/catalogue-langs.js b/frontend/src/lib/catalogue-langs.js
new file mode 100644
index 000000000..e39fd0b63
--- /dev/null
+++ b/frontend/src/lib/catalogue-langs.js
@@ -0,0 +1,3 @@
+// generated by scripts/catalogue/build.mjs from catalogue/ — do not edit
+export const INSTR_LANGS = ["en","ar","es","fr","hi","hu","it","ko","pl","pt-BR","ru","tr","zh","zh-TW"]
+export const EXERCISE_NAME_LANGS = ["de","es","fr","hu","it","pl","pt-BR","ru"]
diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js
index 80344addb..7d9c7da08 100644
--- a/frontend/src/lib/exercises.js
+++ b/frontend/src/lib/exercises.js
@@ -51,6 +51,14 @@ export function equipmentOf(list) {
return Object.keys(c).sort((a, b) => c[b] - c[a] || (a < b ? -1 : 1))
}
+// Kinds of exercise (catalogue "category") present in a list, in a fixed order that reads from
+// lifting to everything around it. Custom exercises carry none and only show under "Any type".
+export const CATEGORIES = ['strength', 'calisthenics', 'olympic', 'plyometrics', 'isometric', 'cardio', 'stretching', 'mobility', 'yoga', 'pilates', 'combat', 'rehab']
+export function categoriesOf(list) {
+ const have = new Set(list.map(e => e.cat).filter(Boolean))
+ return CATEGORIES.filter(c => have.has(c))
+}
+
// Custom (user-created) exercises live in synced state S.customEx (issue #11) and are
// merged into the id index here so every EXIDX[id] lookup keeps working unchanged.
let customIds = new Set()
diff --git a/frontend/src/lib/i18n-core.js b/frontend/src/lib/i18n-core.js
index 8940989bb..0dc2447bb 100644
--- a/frontend/src/lib/i18n-core.js
+++ b/frontend/src/lib/i18n-core.js
@@ -9,8 +9,10 @@ export const LANGS = {
tr: 'Türkçe', ru: 'Русский', uk: 'Українська', zh: '简体中文', 'zh-TW': '繁體中文',
ko: '한국어', hi: 'हिन्दी', bn: 'বাংলা', th: 'ไทย', hu: 'Magyar', ar: 'العربية'
}
-export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'zh-TW', 'hi', 'pl', 'ko', 'pt-BR', 'hu', 'ar']
-export const EXERCISE_NAME_LANGS = ['pt-BR', 'hu', 'de', 'es', 'ru', 'it', 'fr', 'pl']
+// Languages with exercise instructions / names, generated from catalogue/i18n by
+// scripts/catalogue/build.mjs. A pack can be partial; what it lacks shows in English.
+import { INSTR_LANGS, EXERCISE_NAME_LANGS } from './catalogue-langs.js'
+export { INSTR_LANGS, EXERCISE_NAME_LANGS }
// Languages rendered right-to-left; i18n.js setLang applies the direction from this.
export const RTL_LANGS = new Set(['ar'])
export const DATE_LOCALES = {
@@ -143,6 +145,9 @@ export const instrFor = ex => {
return (enInstr && enInstr[ex.id]) || ex.st || []
}
+// Whether the steps instrFor shows are in the current language rather than the English fallback.
+export const instrTranslated = ex => !!(instr && ex && instr[ex.id])
+
// A sentence or two on what the exercise is, in the current language when someone has written
// it, otherwise in English. Empty for exercises nobody has described yet and for custom ones.
export const descFor = ex => {
diff --git a/frontend/src/lib/i18n.js b/frontend/src/lib/i18n.js
index 387c3ea7f..88d363eaa 100644
--- a/frontend/src/lib/i18n.js
+++ b/frontend/src/lib/i18n.js
@@ -7,12 +7,12 @@ import { useSyncExternalStore } from 'react'
import {
LANGS, INSTR_LANGS, EXERCISE_NAME_LANGS, DATE_LOCALES, DERIVED_LOCALES, RTL_LANGS,
getLang, dateLocale, t, tn, instrFor, exerciseNameFor, exerciseNameSearchText, getVersion,
- baseLang, derivePack, _setLangState, exerciseNameClass, descFor, _setDetailsLoader, _setDetails
+ baseLang, derivePack, _setLangState, exerciseNameClass, descFor, instrTranslated, _setDetailsLoader, _setDetails
} from './i18n-core.js'
export {
LANGS, INSTR_LANGS, EXERCISE_NAME_LANGS, DATE_LOCALES, DERIVED_LOCALES, RTL_LANGS,
- getLang, dateLocale, t, tn, instrFor, descFor, exerciseNameFor, exerciseNameSearchText, exerciseNameClass, baseLang
+ getLang, dateLocale, t, tn, instrFor, instrTranslated, descFor, exerciseNameFor, exerciseNameSearchText, exerciseNameClass, baseLang
}
// Vite code-splits locale, instruction and exercise-name packs via import.meta.glob. They are
diff --git a/frontend/src/lib/zh-tw-instructions.test.js b/frontend/src/lib/zh-tw-instructions.test.js
index 3d97d82d9..0dd2b096b 100644
--- a/frontend/src/lib/zh-tw-instructions.test.js
+++ b/frontend/src/lib/zh-tw-instructions.test.js
@@ -12,8 +12,8 @@ describe('Traditional Chinese (zh-TW) exercise instructions', () => {
expect(Object.keys(zhTW)).toHaveLength(EXDB.length)
})
- test('enables zh-TW in INSTR_LANGS when the pack is complete', () => {
- expect(INSTR_LANGS.includes('zh-TW')).toBe(Object.keys(zhTW).length === EXDB.length)
+ test('enables zh-TW in INSTR_LANGS when there is a pack', () => {
+ expect(INSTR_LANGS.includes('zh-TW')).toBe(Object.keys(zhTW).length > 0)
})
test('contains only known exercises with complete, non-empty step lists', () => {
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index eaef4de9b..d841e21dc 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -9,7 +9,7 @@ import { usesBar, defaultBarWeight, hasBarOverride, isNoBar } from './lib/bar.js
import { PLATE_SIZES, pairsOf, ownsPlates, withPlatePairs, withStandardPlates, withLoadKind, loadKindFor, baseWeightFor, dropGrid } from './lib/plates.js'
import { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.js'
import { beep, vibrate } from './lib/sound.js'
-import { t, tn, dateLocale, instrFor, exerciseNameFor, exerciseNameClass, getLang, INSTR_LANGS } from './lib/i18n.js'
+import { t, tn, dateLocale, instrFor, instrTranslated, descFor, exerciseNameFor, exerciseNameClass, getLang, useLang } from './lib/i18n.js'
import { nav, closeThenNav, navToWorkout } from './lib/nav.js'
import { buildStarterPlan, starterPlanDays, starterPlanOptions } from './lib/starter.js'
import Media, { Thumb } from './components/Media.jsx'
@@ -906,6 +906,7 @@ export function detailTags(ex) {
}
function ExerciseDetail({ ex, close }) {
+ useLang() // the description and steps arrive in their own chunk the first time a sheet asks
const st = useStore(s => s.S)
const last = lastEntryFor(st, ex.id)
const best = bestWeightFor(st, ex.id)
@@ -927,7 +928,7 @@ function ExerciseDetail({ ex, close }) {
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0' }}>
{detailTags(ex).map(tg => <span key={tg.key} className={'tag' + (tg.acc ? ' acc' : '')}>{tg.icon && <Icon name={tg.icon} />}{tg.label}</span>)}
</div>
- {ex.desc && <div className="exnote">{ex.desc}</div>}
+ {descFor(ex) && <div className="exnote">{descFor(ex)}</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" style={{ whiteSpace: 'nowrap' }}>{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target, speedUnitOf(st))).join(', ')}` : ''}</div>}
<Button variant="primary" icon="plus" style={{ margin: '10px 0 4px' }} onClick={() => addToRoutineSheet(ex)}>{t('Add to my plan')}</Button>
{last && <Button icon="history" style={{ marginTop: 4 }} onClick={() => exerciseHistorySheet(ex.id)}>{t('History')}</Button>}
@@ -943,7 +944,12 @@ function ExerciseDetail({ ex, close }) {
calculator would answer "your 1RM is 23 kg" about a number that gets smaller as you get
stronger (issue #232). Cardio has none for the same kind of reason. */}
{!isCardio(ex) && !isAssisted(ex) && <OneRM ex={ex} />}
- {instrFor(ex).length > 0 &&<><h4 className="sec">{t('How to')}{!INSTR_LANGS.includes(getLang()) && <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}> · {t('instructions in English')}</span>}</h4><ol className="steps-list">{instrFor(ex).map((s, i) => <li key={i}>{s}</li>)}</ol></>}
+ {instrFor(ex).length > 0 &&<><h4 className="sec">{t('How to')}{getLang() !== 'en' && !instrTranslated(ex) && <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}> · {t('instructions in English')}</span>}</h4><ol className="steps-list">{instrFor(ex).map((s, i) => <li key={i}>{s}</li>)}</ol></>}
+ {/* The catalogue is community-edited (catalogue/README.md): a wrong muscle, a clumsy step or a
+ missing translation is one tap from an issue that already names the exercise. */}
+ {!isCustomEx(ex) && !ex.missing && <a className="small dim exfix-link" target="_blank" rel="noopener"
+ href={'https://github.com/DuarteSantos8/openGym/issues/new?template=exercise.yml&exercise=' + encodeURIComponent(ex.id + ', ' + ex.n)}>
+ <Icon name="pencil" /> {t('Suggest a fix for this exercise')}</a>}
</>
}
export const exerciseDetailSheet = ex => ui().openSheet(close => <ExerciseDetail ex={ex} close={close} />)
@@ -1592,7 +1598,7 @@ function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, i
{!cardio && (ex.secondaries?.length ? ex.secondaries : smOf(ex)).filter(trainedBy(ex)).slice(0, 3)
.map((s, i) => <span key={i} className="tag dim">{t(MUSCLE_NAME[s] || s)}</span>)}
</div>
- {ex.desc && <div className="exnote">{ex.desc}</div>}
+ {descFor(ex) && <div className="exnote">{descFor(ex)}</div>}
{!cardio && <div style={{ marginBottom: 14 }}>
<Segmented className="seg-range" value={mode} onChange={setMode}
options={[{ value: 'reps', label: t('Reps') }, { value: 'time', label: t('Time') }]} />
diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsx
index 340d5886e..a5e410884 100644
--- a/frontend/src/views/Library.jsx
+++ b/frontend/src/views/Library.jsx
@@ -1,7 +1,7 @@
import { useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
-import { EXDB, BODYPARTS, allExercises, equipmentOf, searchExercises } from '../lib/exercises.js'
+import { EXDB, BODYPARTS, allExercises, equipmentOf, categoriesOf, searchExercises } from '../lib/exercises.js'
import { MUSCLE_NAME } from '../lib/muscles.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { bestWeightFor } from '../lib/history.js'
@@ -22,15 +22,21 @@ export default function Library() {
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
const [eq, setEq] = useState('')
+ const [cat, setCat] = useState('')
const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session
const [shown, setShown] = useState(40)
- const bpStrip = useRef(null), eqStrip = useRef(null)
+ const bpStrip = useRef(null), eqStrip = useRef(null), catStrip = useRef(null)
const moreRef = useAutoMore(() => setShown(s => s + 40))
const profile = activeProfile(S)
// Your own exercises, counted the way the list below shows them (allExercises puts every
// custom entry in front of the catalogue; deleting one removes it from customEx outright).
const ownCount = (S.customEx || []).filter(c => c && c.id).length
- const base = searchExercises(allExercises(S).filter(e => !bp || e.bp === bp), q)
+ const inPart = searchExercises(allExercises(S).filter(e => !bp || e.bp === bp), q)
+ // Kind of exercise (strength, stretching, cardio...), the same fallback as equipment below: a
+ // choice the search or body part has narrowed away is ignored for now, never a dead end.
+ const catOpts = categoriesOf(inPart)
+ const catOn = catOpts.includes(cat) ? cat : ''
+ const base = catOn ? inPart.filter(e => e.cat === catOn) : inPart
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(S, e)) : base
const eqOpts = equipmentOf(eqFiltered)
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
@@ -39,9 +45,10 @@ export default function Library() {
const f = sortFavouritesFirst(eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered, S)
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
+ useRevealActiveChip(catStrip, catOn)
// A live count at the end of the search field while a search or filter narrows the list
// (idea and first version: GitLab !31) — how many are left, before scrolling to find out.
- const narrowed = !!(q.trim() || bp || eqOn)
+ const narrowed = !!(q.trim() || bp || eqOn || catOn)
return <>
<div className="hdr lib-hdr"><div><h1>{t('Exercises')}</h1></div>
@@ -65,10 +72,14 @@ export default function Library() {
{/* Changing body part keeps the equipment filter (issue #71): the eqOn fallback above drops
it only for the current view if the new body part has nothing under it, without forgetting
the choice. "All" clears it, since it spans every body part. */}
- <div className="chips" ref={bpStrip} style={{ marginBottom: eqOpts.length > 1 ? 8 : 12 }}>
+ <div className="chips" ref={bpStrip} style={{ marginBottom: eqOpts.length > 1 || catOpts.length > 1 ? 8 : 12 }}>
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(40) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setShown(40) }}>{t(b)}</button>)}
</div>
+ {catOpts.length > 1 && <div className="chips" ref={catStrip} style={{ marginBottom: 8 }}>
+ <button className={'chip nocap' + (!catOn ? ' on' : '')} onClick={() => { setCat(''); setShown(40) }}>{t('Any type')}</button>
+ {catOpts.map(x => <button key={x} className={'chip' + (catOn === x ? ' on' : '')} onClick={() => { setCat(x); setShown(40) }}>{t(x)}</button>)}
+ </div>}
{eqOpts.length > 1 && <div className="chips" ref={eqStrip} style={{ marginBottom: 12 }}>
<button className={'chip nocap' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(40) }}>{t('Any equipment')}</button>
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(40) }}>{t(x)}</button>)}
diff --git a/scripts/catalogue/build.mjs b/scripts/catalogue/build.mjs
index 1f0b4adec..f47ca031a 100644
--- a/scripts/catalogue/build.mjs
+++ b/scripts/catalogue/build.mjs
@@ -76,6 +76,13 @@ for (const [lang, rowsOf] of Object.entries(i18n)) {
if (Object.keys(desc).length) files[`frontend/src/exercise-desc/${lang}.js`] = pack(desc)
}
+// Which languages have instruction and name packs, for i18n-core (a pack may be partial: anything
+// it lacks falls back to English one exercise at a time).
+const packLangs = dir => ['en', ...Object.keys(files).filter(f => f.startsWith(`frontend/src/${dir}/`)).map(f => f.slice(`frontend/src/${dir}/`.length, -3)).filter(l => l !== 'en').sort()]
+files['frontend/src/lib/catalogue-langs.js'] = header +
+ `export const INSTR_LANGS = ${JSON.stringify(packLangs('instr'))}\n` +
+ `export const EXERCISE_NAME_LANGS = ${JSON.stringify(packLangs('exercise-names').filter(l => l !== 'en'))}\n`
+
// catalogue/browse/: one page per body part with each exercise's still, so contributors can see
// what an id is without running the app. GitHub renders these Markdown tables with the pictures.
const slug = s => s.replace(/\s+/g, '-')
diff --git a/scripts/catalogue/import-drafts.mjs b/scripts/catalogue/import-drafts.mjs
new file mode 100644
index 000000000..f5dcad709
--- /dev/null
+++ b/scripts/catalogue/import-drafts.mjs
@@ -0,0 +1,77 @@
+#!/usr/bin/env node
+// Folds the v1.4.0 drafting work into catalogue/: the new exercises of the Gym visual pack and
+// descriptions for the ones that shipped before. One-off, kept for the record like import-legacy.
+//
+// node scripts/catalogue/import-drafts.mjs /path/to/opengym-media
+//
+// Reads <archive>/work/drafts.json (ids, female drawings) and <archive>/work/meta/out/*.json (the
+// text, checked against work/meta/SPEC.md). Existing entries only ever gain a description and a
+// category; nothing they already had is changed.
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+const EX = path.join(ROOT, 'catalogue/exercises')
+const archive = path.resolve(process.argv[2] || '/mnt/backup-hdd/opengym-media')
+const outDir = path.join(archive, 'work/meta/out')
+const { drafts, femaleVariants } = JSON.parse(fs.readFileSync(path.join(archive, 'work/drafts.json'), 'utf8'))
+
+const read = id => JSON.parse(fs.readFileSync(path.join(EX, id + '.json'), 'utf8'))
+const write = e => fs.writeFileSync(path.join(EX, e.id + '.json'), JSON.stringify(e, null, 2) + '\n')
+const ORDER = ['id', 'name', 'bodyPart', 'equipment', 'target', 'secondaryMuscles', 'category', 'description', 'instructions', 'muscleMap', 'femaleVariant', 'variantOf', 'textSource']
+const ordered = e => Object.fromEntries(ORDER.filter(k => e[k] !== undefined).map(k => [k, e[k]]))
+
+const rows = new Map()
+for (const f of fs.readdirSync(outDir).filter(f => f.endsWith('.json')).sort()) {
+ for (const r of JSON.parse(fs.readFileSync(path.join(outDir, f), 'utf8'))) rows.set(r.id, r)
+}
+
+const existing = new Set(fs.readdirSync(EX).filter(f => f.endsWith('.json')).map(f => f.slice(0, -5)))
+const names = new Map([...existing].map(id => [read(id).name, id]))
+let described = 0, added = 0, renamed = 0, missing = []
+
+for (const id of existing) {
+ const r = rows.get(id)
+ if (!r) continue
+ const e = read(id)
+ if (!e.description && r.description) { e.description = r.description; described++ }
+ if (!e.category && r.category) e.category = r.category
+ write(ordered(e))
+}
+
+for (const d of drafts) {
+ if (existing.has(d.id)) continue
+ const r = rows.get(d.id)
+ if (!r) { missing.push(d.id); continue }
+ // Two drawings can carry the same title (a second camera angle, a corrected re-draw). Names stay
+ // unique so a search result is never ambiguous: the later id becomes "v. 2", "v. 3", ...
+ let name = r.name
+ if (names.has(name)) {
+ let k = 2
+ const base = name.replace(/ v\. \d+$/, '')
+ while (names.has(`${base} v. ${k}`)) k++
+ name = `${base} v. ${k}`
+ renamed++
+ }
+ names.set(name, d.id)
+ write(ordered({
+ id: d.id, name, bodyPart: r.bodyPart, equipment: r.equipment, target: r.target,
+ secondaryMuscles: r.secondaryMuscles, category: r.category, description: r.description,
+ instructions: r.instructions, textSource: 'opengym',
+ }))
+ added++
+}
+
+let linked = 0
+for (const [male, female] of Object.entries(femaleVariants)) {
+ if (!fs.existsSync(path.join(EX, male + '.json'))) continue
+ const e = read(male)
+ e.femaleVariant = female
+ write(ordered(e))
+ write({ id: female, variantOf: male })
+ linked++
+}
+
+console.log(`described ${described} existing, added ${added} new (${renamed} renamed to stay unique), linked ${linked} female drawings`)
+if (missing.length) console.log(`no text yet for ${missing.length}: ${missing.slice(0, 20).join(' ')}${missing.length > 20 ? ' ...' : ''}`)