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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Add editable aliases for built-in and custom exercises
Space-Hermes5b5e5a5506da
diff --git a/api/sync-stamps.js b/api/sync-stamps.jsindex a8ea2e6d5..fe0e7cf67 100644--- a/api/sync-stamps.js+++ b/api/sync-stamps.js@@ -66,7 +66,7 @@ const OWN_MERGE = new Set(['workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'measurements', 'favEx','exWeights', 'balanceOverrides', 'loadKind', 'plates', 'dbLoad', 'dumbbells', 'dayNotes', 'dayPhotos',]);-const PER_KEY = new Set(['week', 'dayPlan', 'exNotes', 'barWeights']);+const PER_KEY = new Set(['week', 'dayPlan', 'exNotes', 'barWeights', 'exAliases']);// The maps whose every entry carries its own edit time (sync-merge.js STAMPED_MAPS): merged per// key by the app, so never stamped here as a whole setting. dayNotes is a note per day off,// dayPhotos a progress photo filed under a day (#557), one entry per photo.diff --git a/api/test/exercise-aliases.test.js b/api/test/exercise-aliases.test.jsnew file mode 100644index 000000000..b5f140d93--- /dev/null+++ b/api/test/exercise-aliases.test.js@@ -0,0 +1,13 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { stampPut } from '../sync-stamps.js';++test('the API stamps built-in aliases independently per exercise, including a clear', () => {+ const before = { _ts: 10, exAliases: { a: ['Old'], b: ['Row'] }, edited: { 'exAliases.a': 10, 'exAliases.b': 10 } };+ const after = structuredClone(before);+ after.exAliases.a = [];+ stampPut(before, after, { overRead: true, now: 100 });+ assert.equal(after.edited['exAliases.a'], 100);+ assert.equal(after.edited['exAliases.b'], 10);+ assert.deepEqual(after.exAliases, { a: [], b: ['Row'] });+});diff --git a/frontend/src/components/ExerciseAliases.jsx b/frontend/src/components/ExerciseAliases.jsxnew file mode 100644index 000000000..ef4dedf1a--- /dev/null+++ b/frontend/src/components/ExerciseAliases.jsx@@ -0,0 +1,38 @@+import { useId, useState } from 'react'+import { useStore } from '../store/useStore.js'+import { exerciseAliases, normalizeAliases } from '../lib/exercise-aliases.js'+import { isCustomEx } from '../lib/exercises.js'+import { t } from '../lib/i18n.js'+import { Button } from './ui.jsx'++export function ExerciseAliasesField({ value, onChange }) {+ const id = useId()+ return <div style={{ marginTop: 12 }}>+ <label className="small muted" htmlFor={id}>{t('Aliases')}</label>+ <input id={id} className="input" value={value} onChange={e => onChange(e.target.value)}+ maxLength={1640} aria-describedby={id + '-help'} />+ <div id={id + '-help'} className="small dim">{t('Alternative names for search. Separate with commas.')}</div>+ </div>+}++export default function ExerciseAliasesEditor({ ex }) {+ const st = useStore(s => s.S)+ const update = useStore(s => s.update)+ const current = isCustomEx(ex) ? st.customEx?.find(c => c.id === ex.id) || ex : ex+ const saved = exerciseAliases(current, st.exAliases)+ const [value, setValue] = useState(() => saved.join(', '))+ const aliases = normalizeAliases(value)+ const save = () => {+ update(s => {+ if (isCustomEx(ex)) {+ const c = s.customEx?.find(c => c.id === ex.id)+ if (c) c.aliases = aliases+ } else s.exAliases = { ...s.exAliases, [ex.id]: aliases }+ })+ setValue(aliases.join(', '))+ }+ return <>+ <ExerciseAliasesField value={value} onChange={setValue} />+ <Button onClick={save} disabled={JSON.stringify(aliases) === JSON.stringify(saved)} style={{ marginTop: 8 }}>{t('Save aliases')}</Button>+ </>+}diff --git a/frontend/src/lib/exercise-aliases.js b/frontend/src/lib/exercise-aliases.jsnew file mode 100644index 000000000..abd5f6a63--- /dev/null+++ b/frontend/src/lib/exercise-aliases.js@@ -0,0 +1,17 @@+const MAX_ALIASES = 20+const MAX_LENGTH = 80+let overrides = {}++export function normalizeAliases(value) {+ const values = typeof value === 'string' ? value.split(/[,\n]/) : Array.isArray(value) ? value : []+ const seen = new Set()+ return values.filter(v => typeof v === 'string').map(v => v.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, MAX_LENGTH))+ .filter(v => { const key = v.toLocaleLowerCase(); if (!v || seen.has(key)) return false; seen.add(key); return true })+ .slice(0, MAX_ALIASES)+}++// Register every adopted/restored state, including an empty map when switching profiles.+export const registerExerciseAliases = map => { overrides = map && typeof map === 'object' && !Array.isArray(map) ? map : {} }+export const aliasSnapshot = () => overrides+export const exerciseAliases = (ex, map = overrides) => normalizeAliases(+ map && Object.hasOwn(map, ex?.id) ? map[ex.id] : ex?.aliases)diff --git a/frontend/src/lib/exercise-aliases.test.js b/frontend/src/lib/exercise-aliases.test.jsnew file mode 100644index 000000000..afd5ff8bd--- /dev/null+++ b/frontend/src/lib/exercise-aliases.test.js@@ -0,0 +1,53 @@+import { afterEach, expect, it } from 'vitest'+import { normalizeAliases, registerExerciseAliases } from './exercise-aliases.js'+import { CATALOGUE, searchExercises, searchScore } from './exercises.js'+import { stampEdits, mergeStates, sinceReset } from './sync-merge.js'+import { buildPlanBundle, parsePlan, mergePlan } from './plan-share.js'++afterEach(() => registerExerciseAliases({}))+it('normalizes bounded text without accepting malformed imported values', () => {+ expect(normalizeAliases(' OHP, overhead press, ohp,\n Military press ')).toEqual(['OHP', 'overhead press', 'Military press'])+ expect(normalizeAliases([null, {}, 42, ' x ', 'X'])).toEqual(['x'])+ expect(normalizeAliases({ bad: true })).toEqual([])+ expect(normalizeAliases(['x'.repeat(100)])[0]).toHaveLength(80)+ expect(normalizeAliases(Array.from({ length: 30 }, (_, i) => String(i)))).toHaveLength(20)+})+it('updates cached built-in search immediately, clears aliases and isolates profiles', () => {+ const ex = CATALOGUE.find(e => e.id === '1162')+ const original = structuredClone(ex)+ expect(searchExercises([ex], 'my special lift')).toEqual([])+ registerExerciseAliases({ [ex.id]: ['my special lift'] })+ expect(searchExercises([ex], 'my special lift')).toEqual([ex])+ expect(searchScore(ex, 'my special lift')).toBeGreaterThan(0)+ registerExerciseAliases({ [ex.id]: [] })+ expect(searchExercises([ex], 'my special lift')).toEqual([])+ registerExerciseAliases(null)+ expect(ex).toEqual(original)+})+it('finds custom aliases without changing the primary name or identity', () => {+ const ex = { id: 'c1', n: 'My press', aliases: ['Viking lift'], custom: true }+ expect(searchExercises([ex], 'Viking lift')).toEqual([ex])+ expect(searchScore(ex, 'Viking lift')).toBeGreaterThan(0)+})+it('merges different exercise edits and preserves an explicit clear against stale devices', () => {+ const before = { _ts: 1, exAliases: { a: ['Old'] } }+ const a = { _ts: 2, exAliases: { a: [] } }+ const b = { _ts: 3, exAliases: { a: ['Old'], b: ['Row'] } }+ stampEdits(before, a, 20)+ stampEdits(before, b, 30)+ for (const [left, right] of [[a, b], [b, a]]) {+ const merged = mergeStates(left, right)+ expect(merged.exAliases).toEqual({ a: [], b: ['Row'] })+ expect(JSON.parse(JSON.stringify(merged)).exAliases).toEqual(merged.exAliases)+ }+ expect(sinceReset(a, 100).exAliases).toEqual({})+})+it('preserves custom aliases in a shared plan', () => {+ const source = { unit: 'kg', week: {}, routines: [{ id: 'r1', name: 'A', ex: [{ id: 'c1', sets: 3, reps: 8 }] }],+ customEx: [{ id: 'c1', n: 'My press', bp: 'shoulders', eq: 'barbell', aliases: ['Viking lift'] }] }+ const bundle = buildPlanBundle(source)+ expect(bundle.customEx[0].aliases).toEqual(['Viking lift'])+ const target = { unit: 'kg', routines: [], customEx: [], week: {} }+ mergePlan(target, parsePlan(JSON.stringify(bundle)))+ expect(target.customEx[0].aliases).toEqual(['Viking lift'])+})diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.jsindex 999e687c4..5ab4a0310 100644--- a/frontend/src/lib/exercises.js+++ b/frontend/src/lib/exercises.js@@ -1,3 +1,4 @@+import { exerciseAliases, aliasSnapshot } from './exercise-aliases.js'import { EXDB, EXALIAS } from './exercises-data.js'import MUSCLE_MAP from './exercise-muscle-map.json' with { type: 'json' }import V13_IDS from './catalogue-v13-ids.json' with { type: 'json' }@@ -147,8 +148,9 @@ function isSubsequence(needle, hay) {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]]+ const ex = exercise && typeof exercise === 'object' ? exercise : {}+ const source = { ...ex, aliases: exerciseAliases(ex) }+ const fields = [['n', 100], ['aliases', 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)@@ -327,11 +329,11 @@ const VOCAB = new Set()function corpusOf(e) {const v = getVersion()const hit = corpusCache.get(e)- if (hit && hit.v === v) return hit+ if (hit && hit.v === v && hit.aliases === aliasSnapshot()) return hitconst sm = Array.isArray(e?.sm) ? e.sm : []const name = normalizeStr(exerciseNameSearchText(e))const s = normalizeStr([- name,+ name, ...exerciseAliases(e),e?.tg || '', t(e?.tg || ''),e?.eq || '', t(e?.eq || ''),e?.bp || '', t(e?.bp || ''),@@ -343,7 +345,7 @@ function corpusOf(e) {// a body part and an equipment word would start matching as one.// The joined form only counts from the start of a name word, or "thigh" would find "sumo// deadlift high pull" through "deadlifthighpull".- const entry = { v, s, name, ...joinedOf(name), nameWords: name.split(/[\s\-‐-―()/,]+/).filter(Boolean) }+ const entry = { v, s, name, aliases: aliasSnapshot(), ...joinedOf(name), nameWords: name.split(/[\s\-‐-―()/,]+/).filter(Boolean) }for (const w of entry.nameWords) VOCAB.add(w)corpusCache.set(e, entry)return entrydiff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.jsindex 180b79db9..2f47c8edf 100644--- a/frontend/src/lib/plan-share.js+++ b/frontend/src/lib/plan-share.js@@ -1,3 +1,4 @@+import { normalizeAliases } from './exercise-aliases.js'// Share a weekly plan.//// Two jobs:@@ -200,6 +201,8 @@ const muscleList = v => inMuscleOrder([...new Set((Array.isArray(v) ? v : []).fi* that are empty stay absent, so a file written before this change reads the same as one after. */function cleanCustom(c) {const o = { id: c.id, n: c.n, bp: c.bp }+ const aliases = normalizeAliases(c.aliases)+ if (aliases.length) o.aliases = aliasesif (c.desc) o.desc = c.desc// The link to a video or guide travels with a shared plan (#246), cleaned both ways like any// other field of someone else's file; the exercise's own photo or video never does — it is adiff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex 6290217a6..dc6ebf2ec 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -405,7 +405,7 @@ const RESET_LISTS = {workouts: workoutKey, routines: x => x?.id, customEx: x => x?.id, bodyweight: bodyweightKey,measurements: bodyweightKey, gymCards: x => x?.id, equipProfiles: x => x?.id, favEx: x => x,}-const RESET_MAPS = ['exNotes', 'barWeights', ...STAMPED_MAPS]+const RESET_MAPS = ['exNotes', 'barWeights', 'exAliases', ...STAMPED_MAPS]/** An entry's name in resetIds: a workout's id (or day and start), a weigh-in's day and time, … */export const entryKey = (field, x) => String(RESET_LISTS[field](x))// Per field, the most names a reset keeps — far more workouts than anyone logs, and a bound on@@ -464,6 +464,7 @@ export function sinceReset(S, at, ids) {out.gymCards = []out.favEx = []out.exNotes = {}+ out.exAliases = {}out.barWeights = {}for (const f of STAMPED_MAPS) {out[f] = Object.fromEntries(Object.entries(isMap(S[f]) ? S[f] : {}).filter(([, v]) => after(stampOf(v))))@@ -618,7 +619,7 @@ const OWN_MERGE = new Set(['exWeights', 'balanceOverrides', 'loadKind', 'plates', 'dbLoad', 'dumbbells', 'dayNotes', 'dayPhotos',])// Stamped per key instead of whole: one day of the plan, one exercise's note or bar.-const PER_KEY = new Set(['week', 'dayPlan', 'exNotes', 'barWeights'])+const PER_KEY = new Set(['week', 'dayPlan', 'exNotes', 'barWeights', 'exAliases'])// The order of the routines, as the list shows them, is a choice of its own (`edited.routineOrder`):// a reorder on one device was lost to the other's whole copy whenever that one was newer.export const ORDER_KEY = 'routineOrder'@@ -846,7 +847,7 @@ export function mergeStates(a0, b0, { prefer } = {}) {if (kept) out.exWeights[id] = clone(kept)else delete out.exWeights[id]}- for (const f of ['exNotes', 'barWeights']) {+ for (const f of ['exNotes', 'barWeights', 'exAliases']) {if (n[f] || o[f]) out[f] = clone({ ...(o[f] || {}), ...(n[f] || {}) })}// The plate-loading choices (lib/plates.js) are stamped the same way: an exercise's loading and@@ -1130,7 +1131,7 @@ export function localExtras(local, server) {const setup = ['gymCards', 'equipProfiles'].reduce((n, f) => n + list(local?.[f]).filter(x => x && x.id != null && !ids(f).has(x.id)).length, 0) +list(local?.measurements).filter(e => e && e.d != null && !measured.has(e.d)).length +Object.entries(isMap(local?.dayNotes) ? local.dayNotes : {}).filter(([k, v]) => readNote(v) && !readNote(server?.dayNotes?.[k])).length +- keysNew('week') + keysNew('dayPlan') + keysNew('exNotes')+ keysNew('week') + keysNew('dayPlan') + keysNew('exNotes') + keysNew('exAliases')return {workouts: list(local?.workouts).filter(w => !have.has(workoutKey(w))).length,bodyweight: list(local?.bodyweight).filter(e => e && e.d != null && (!days.has(e.d) || differs(e, days.get(e.d)))).length,diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 18b83259b..64e5d2eca 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1,5 +1,8 @@// Arabic UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "أسماء بديلة",+ "Alternative names for search. Separate with commas.": "أسماء بديلة للبحث. افصل بينها بفواصل.",+ "Save aliases": "حفظ الأسماء البديلة",'Confirm': 'تأكيد','Cancel': 'إلغاء','Press back again to exit': 'اضغط زر الرجوع مرة أخرى للخروج',diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.jsindex b2e61da08..05d00326a 100644--- a/frontend/src/locales/bn.js+++ b/frontend/src/locales/bn.js@@ -1,5 +1,8 @@// Bengali UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "বিকল্প নাম",+ "Alternative names for search. Separate with commas.": "অনুসন্ধানের জন্য বিকল্প নাম। কমা দিয়ে আলাদা করুন।",+ "Save aliases": "বিকল্প নাম সংরক্ষণ করুন",'Confirm': 'নিশ্চিত করুন','Cancel': 'বাতিল','Press back again to exit': 'বের হতে আবার ব্যাক চাপুন',diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 9a644c0a6..0251c21fa 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1,5 +1,8 @@// German UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Alternative Namen",+ "Alternative names for search. Separate with commas.": "Alternative Namen für die Suche. Mit Kommas trennen.",+ "Save aliases": "Alternative Namen speichern",// --- generic ---'Confirm': 'Bestätigen','Cancel': 'Abbrechen',diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex c8668f164..6f1e57818 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1,5 +1,8 @@// Spanish UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Alias",+ "Alternative names for search. Separate with commas.": "Nombres alternativos para buscar. Sepáralos con comas.",+ "Save aliases": "Guardar alias",'Confirm': 'Confirmar','Cancel': 'Cancelar','Press back again to exit': 'Pulsa atrás otra vez para salir',diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex c28134d54..f00a659d1 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1,5 +1,8 @@// French UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Autres noms",+ "Alternative names for search. Separate with commas.": "Autres noms pour la recherche. Sépare-les par des virgules.",+ "Save aliases": "Enregistrer les autres noms",'Confirm': 'Confirmer','Cancel': 'Annuler','Press back again to exit': 'Appuie de nouveau pour quitter',diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 9b190d7f1..057492a9a 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1,5 +1,8 @@// Hindi UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "वैकल्पिक नाम",+ "Alternative names for search. Separate with commas.": "खोज के लिए वैकल्पिक नाम। कॉमा से अलग करें।",+ "Save aliases": "वैकल्पिक नाम सहेजें",'Confirm': 'पुष्टि करें','Cancel': 'रद्द करें','Press back again to exit': 'बाहर निकलने के लिए फिर से बैक दबाएँ',diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 5f484166a..7b4bf950d 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1,5 +1,8 @@// Hungarian UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Más elnevezések",+ "Alternative names for search. Separate with commas.": "Alternatív nevek a kereséshez. Vesszővel válaszd el őket.",+ "Save aliases": "Elnevezések mentése",// --- generic ---'Confirm': 'Megerősítés','Cancel': 'Mégse',diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex a606ef55a..abb821037 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1,5 +1,8 @@// Italian UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Nomi alternativi",+ "Alternative names for search. Separate with commas.": "Nomi alternativi per la ricerca. Separali con virgole.",+ "Save aliases": "Salva nomi alternativi",'Confirm': 'Conferma','Cancel': 'Annulla','Press back again to exit': 'Premi di nuovo indietro per uscire',diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex ce8d6c8e8..cf0fe4274 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1,5 +1,8 @@// Korean UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "다른 이름",+ "Alternative names for search. Separate with commas.": "검색에 사용할 다른 이름입니다. 쉼표로 구분하세요.",+ "Save aliases": "다른 이름 저장",'Confirm': '확인','Cancel': '취소','Press back again to exit': '뒤로를 한 번 더 누르면 종료됩니다',diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 0fd87d5e5..218ecd587 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1,5 +1,8 @@// Polish UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Alternatywne nazwy",+ "Alternative names for search. Separate with commas.": "Alternatywne nazwy do wyszukiwania. Oddziel je przecinkami.",+ "Save aliases": "Zapisz alternatywne nazwy",'Confirm': 'Potwierdź','Cancel': 'Anuluj','Press back again to exit': 'Naciśnij wstecz ponownie, aby wyjść',diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 2dabc1249..abc1c5761 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1,5 +1,8 @@// Portuguese UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Nomes alternativos",+ "Alternative names for search. Separate with commas.": "Nomes alternativos para a pesquisa. Separa-os com vírgulas.",+ "Save aliases": "Guardar nomes alternativos",'Confirm': 'Confirmar','Cancel': 'Cancelar','Press back again to exit': 'Prima novamente para sair',diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex b1952e201..c0b8e9076 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1,5 +1,8 @@// Russian UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Другие названия",+ "Alternative names for search. Separate with commas.": "Другие названия для поиска. Разделяйте запятыми.",+ "Save aliases": "Сохранить названия",'Confirm': 'Подтвердить','Cancel': 'Отмена','Press back again to exit': 'Нажмите «Назад» ещё раз, чтобы выйти',diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 468d1545d..303be5172 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1,5 +1,8 @@// Thai UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "ชื่ออื่น",+ "Alternative names for search. Separate with commas.": "ชื่ออื่นสำหรับการค้นหา คั่นด้วยเครื่องหมายจุลภาค",+ "Save aliases": "บันทึกชื่ออื่น",// --- generic ---'Confirm': 'ยืนยัน','Cancel': 'ยกเลิก',diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 492144e52..137106b7b 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1,5 +1,8 @@// Turkish UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Alternatif adlar",+ "Alternative names for search. Separate with commas.": "Arama için alternatif adlar. Virgülle ayırın.",+ "Save aliases": "Alternatif adları kaydet",'Confirm': 'Onayla','Cancel': 'İptal','Press back again to exit': 'Çıkmak için geri tuşuna tekrar basın',diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 86039b6f4..3d275b1c7 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1,5 +1,8 @@// Ukrainian UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "Інші назви",+ "Alternative names for search. Separate with commas.": "Інші назви для пошуку. Розділяйте комами.",+ "Save aliases": "Зберегти назви",'Confirm': 'Підтвердити','Cancel': 'Скасувати','Press back again to exit': 'Натисни «Назад» ще раз, щоб вийти',diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex 1499efc1b..2ef99c347 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -1,4 +1,7 @@export default {+ "Aliases": "別名",+ "Alternative names for search. Separate with commas.": "用於搜尋的其他名稱,請以逗號分隔。",+ "Save aliases": "儲存別名",'Confirm': '確認','Cancel': '取消','Press back again to exit': '再按一次返回以退出',diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 05818a188..60bed647a 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1,5 +1,8 @@// Simplified Chinese UI strings. Keys are the English source strings (see lib/i18n.js).export default {+ "Aliases": "别名",+ "Alternative names for search. Separate with commas.": "用于搜索的其他名称,请用逗号分隔。",+ "Save aliases": "保存别名",'Confirm': '确认','Cancel': '取消','Press back again to exit': '再按一次返回退出',diff --git a/frontend/src/sheets.aliases.test.jsx b/frontend/src/sheets.aliases.test.jsxnew file mode 100644index 000000000..853b9b504--- /dev/null+++ b/frontend/src/sheets.aliases.test.jsx@@ -0,0 +1,59 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, expect, it } from 'vitest'+import { DEF, useStore } from './store/useStore.js'+import { useUI } from './store/useUI.js'+import { bindUI } from './components/ui.jsx'+import { customExSheet, exerciseDetailSheet } from './sheets.jsx'+import { CATALOGUE, registerCustom, searchExercises } from './lib/exercises.js'+import { registerExerciseAliases } from './lib/exercise-aliases.js'+import { _setLangState } from './lib/i18n-core.js'++bindUI(useUI)+let root, host+beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ useStore.setState({ S: structuredClone(DEF), user: null, config: null })+ useUI.setState({ sheets: [], toastMsg: '' })+ registerCustom([]); registerExerciseAliases({}); _setLangState('en', null, null, null)+ host = document.createElement('div'); document.body.append(host); root = createRoot(host)+})+afterEach(() => { act(() => root.unmount()); host.remove(); registerCustom([]); registerExerciseAliases({}) })+const render = () => act(() => root.render(useUI.getState().sheets.at(-1).render(() => {})))+const type = (el, value) => act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, value)+ el.dispatchEvent(new Event('input', { bubbles: true }))+})+const field = () => host.querySelector('input[aria-describedby]')+const click = text => act(() => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text).click())++it('saves, reopens and clears built-in aliases without creating a custom exercise or touching history', () => {+ const ex = CATALOGUE.find(e => e.id === '1162')+ const before = structuredClone(useStore.getState().S)+ exerciseDetailSheet(ex); render()+ expect(host.querySelector('label[for="' + field().id + '"]').textContent).toBe('Aliases')+ type(field(), ' OHP, Military press, ohp '); click('Save aliases')+ expect(useStore.getState().S.exAliases[ex.id]).toEqual(['OHP', 'Military press'])+ expect(useStore.getState().S.customEx).toEqual([])+ expect(useStore.getState().S.workouts).toEqual(before.workouts)+ exerciseDetailSheet(ex); render()+ expect(field().value).toBe('OHP, Military press')+ type(field(), ''); click('Save aliases')+ expect(useStore.getState().S.exAliases[ex.id]).toEqual([])+})+it('edits custom aliases and preserves its media, name and identity', () => {+ const ex = { id: 'c1', n: 'My press', bp: 'shoulders', eq: 'barbell', custom: true, aliases: ['Old name'], url: 'https://example.com/demo' }+ useStore.setState(s => ({ S: { ...s.S, customEx: [ex] } })); registerCustom([ex])+ customExSheet(ex); render()+ expect(field().value).toBe('Old name')+ type(field(), 'Viking lift'); click('Save')+ const saved = useStore.getState().S.customEx[0]+ expect(saved).toMatchObject({ id: ex.id, n: ex.n, url: ex.url, aliases: ['Viking lift'] })+ expect(searchExercises([saved], 'Viking lift')).toEqual([saved])+})+it('leaves unsaved edits out of state', () => {+ exerciseDetailSheet(CATALOGUE.find(e => e.id === '1162')); render()+ type(field(), 'Unsaved name')+ expect(useStore.getState().S.exAliases).toEqual({})+})diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex 21aa7f810..552d88931 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -1,3 +1,5 @@+import ExerciseAliasesEditor, { ExerciseAliasesField } from './components/ExerciseAliases.jsx'+import { normalizeAliases } from './lib/exercise-aliases.js'import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'import { useStore } from './store/useStore.js'import { useUI } from './store/useUI.js'@@ -1077,6 +1079,7 @@ function ExerciseDetail({ ex, close }) {</button></div><Media ex={ex} />+ <ExerciseAliasesEditor key={ex.id} ex={ex} /><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>@@ -1205,6 +1208,7 @@ function CustomExForm({ existing, prefill, onDone, close }) {const nameRef = useRef(null)const onNameFocus = useSheetKeyboard(nameRef)const [n, setN] = useState(existing ? existing.n : (prefill || ''))+ const [aliases, setAliases] = useState(() => normalizeAliases(existing?.aliases).join(', '))const [bp, setBp] = useState(existing ? existing.bp : '')const [eq, setEq] = useState(existing ? (existing.eq || '') : '')const storedEq = existing && typeof existing.eq === 'string' && existing.eq && !ALL_EQUIPMENT.includes(existing.eq) ? existing.eq : null@@ -1271,6 +1275,7 @@ function CustomExForm({ existing, prefill, onDone, close }) {const tg = (existing && prim.includes(existing.tg)) ? existing.tg : (primaryTaps.find(m => prim.includes(m)) || prim[0] || '')let id = existing && existing.idconst extra = c => {+ c.aliases = normalizeAliases(aliases)if (!keepMedia) { if (ref) c.media = ref; else delete c.media }if (link) c.url = link; else delete c.url}@@ -1293,6 +1298,7 @@ function CustomExForm({ existing, prefill, onDone, close }) {<h3>{existing ? t('Edit custom exercise') : t('Create your own exercise')}</h3><div className="muted small" style={{ marginBottom: 12 }}>{t('Name it and pick a body part. It works just like any other exercise.')}</div><input ref={nameRef} className="input" placeholder={t('Exercise name')} maxLength={80} value={n} onFocus={onNameFocus} onChange={e => setN(e.target.value)} />+ <ExerciseAliasesField value={aliases} onChange={setAliases} /><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>diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 0dbade684..258cd9284 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -1,3 +1,4 @@+import { registerExerciseAliases } from '../lib/exercise-aliases.js'import { create } from 'zustand'import { api, setRemoteAuth } from '../lib/api.js'import { localTZ } from '../lib/format.js'@@ -145,7 +146,7 @@ export const DEF = {// Standing per-exercise notes, keyed by exercise id: the gym-specific facts that are true// every time you do the movement ("seat 4, pin 7"). Distinct from a routine's `note`, which// belongs to one exercise in one plan, and from a session note, which belongs to one day.- exNotes: {},+ exNotes: {}, exAliases: {},// Favourite exercise ids (issue #6) — sorted to the top of the picker/Library. Personal, so// it syncs with the profile but is never part of a shared plan bundle (lib/favourites.js).favEx: [],@@ -339,7 +340,7 @@ function loadState() {// weigh-ins and custom exercises. A custom exercise is all a new guest may have made — with its// photo or video, which the server counts as unreferenced until the state that names it lands —// so a profile created from such a copy takes it at once, like one holding a workout.-const hasData = st => !!((st.workouts || []).length || (st.routines || []).length || (st.bodyweight || []).length || (st.customEx || []).length || (st.measurements || []).length)+const hasData = st => !!((st.workouts || []).length || (st.routines || []).length || (st.bodyweight || []).length || (st.customEx || []).length || (st.measurements || []).length || Object.values(st.exAliases || {}).some(v => Array.isArray(v) && v.length))// Decide whether a pulled account state may replace the local saved state. A local active workout// is deliberately carried forward: the server stores completed/saved state, while the in-progress@@ -623,6 +624,7 @@ export const useStore = create((set, get) => {// goes out with it on the next push, without a stamp of its own (healCustomEx).S.customEx = healCustomEx(S.customEx)registerCustom(S.customEx)+ registerExerciseAliases(S.exAliases)// A refused write used to take the change with it — Finish looked like it simply did// nothing. The copy is kept in memory either way and marked as owed to the server, so a// signed-in device still gets it there; and it is said out loud once, because a change that@@ -909,6 +911,7 @@ export const useStore = create((set, get) => {handedOver = falsemeta.set(S, { base: readStoredSync(), owed: storedOwed() })registerCustom(S.customEx)+ registerExerciseAliases(S.exAliases)set({ S })followSignIn()return true@@ -954,6 +957,7 @@ export const useStore = create((set, get) => {merged._ts = Math.max(Number(theirs._ts) || 0, Number(mine._ts) || 0)meta.set(merged, { base: readStoredSync(), owed: storedOwed() })registerCustom(merged.customEx)+ registerExerciseAliases(merged.exAliases)set({ S: merged })return}@@ -1344,6 +1348,7 @@ export const useStore = create((set, get) => {const S0 = loadState()S0.customEx = healCustomEx(S0.customEx)registerCustom(S0.customEx)+ registerExerciseAliases(S0.exAliases)// Which photos and videos are still waiting for the server, known before the first sign-out// check has to ask (lib/media-owed.js). A copy without any leaves the media store unopened.if (referencedHashes(S0).size) loadPending()