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.

Favoriten-Uebungen (#6): Stern im Detail-Sheet, Favoriten zuoberst im Picker, in der Bibliothek und im Muskel-Explorer

Duarte Santosf16250554951
diff --git a/frontend/src/components/MuscleExplorer.jsx b/frontend/src/components/MuscleExplorer.jsx
index e0cdfb649..9916377ed 100644
--- a/frontend/src/components/MuscleExplorer.jsx
+++ b/frontend/src/components/MuscleExplorer.jsx
@@ -11,6 +11,7 @@ import { Thumb } from './Media.jsx'
import Icon from './Icon.jsx'
import { Button } from './ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
+import { isFav, sortFavouritesFirst } from '../lib/favourites.js'
// One explorer for the Library and every catalogue picker. Supplying `onPick` turns
// a result into a selection; without it the explorer behaves like the normal Library.
@@ -37,7 +38,8 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) {
const base = targeted.filter(e => (!bp || e.bp === bp) && matchExercise(e, q))
const eqOpts = equipmentOf(base)
const eqOn = eqOpts.includes(eq) ? eq : ''
- const exercises = eqOn ? base.filter(e => e.eq === eqOn) : base
+ // Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order.
+ const exercises = sortFavouritesFirst(eqOn ? base.filter(e => e.eq === eqOn) : base, S)
const choose = ex => onPick ? onPick(ex) : onDetail(ex)
return <>
@@ -82,7 +84,7 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) {
const primary = musclesOf(e)[selected] === 1
return <div key={e.id} className="item" {...tappable(() => choose(e))}>
<Thumb ex={e} />
- <div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss">{t(primary ? 'Primary target' : 'Also trains')} · <span className="capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</span></div></div>
+ <div className="grow"><div className="tt capitalize">{isFav(S, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss">{t(primary ? 'Primary target' : 'Also trains')} · <span className="capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</span></div></div>
{onPick ? <Icon name="plus" className="chev" /> : <>
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
<Button size="sm" variant="tinted" icon="plus" onClick={ev => { ev.stopPropagation(); onPlan(e) }}>{t('Plan')}</Button>
diff --git a/frontend/src/index.css b/frontend/src/index.css
index e684a11f4..76a51d0bf 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -416,6 +416,11 @@ h4.sec{
font-weight:500;text-transform:capitalize;
}
.tag.acc{background:var(--acc-soft);color:var(--acc)}
+/* favourite marker (issue #6): a small yellow star glued to the exercise name — distinct from
+ the accent "chosen" tag at the row's end, which means "already in a routine or the log" */
+.fav-star{color:var(--yellow);font-size:12px;display:inline-block;margin-right:5px;vertical-align:-1px}
+.fav-btn{margin-top:-4px}
+.fav-btn.on{color:var(--yellow)}
/* ---------------------------------------------------------------- chips -- */
.chips{
diff --git a/frontend/src/lib/favourites.js b/frontend/src/lib/favourites.js
new file mode 100644
index 000000000..1ba870a85
--- /dev/null
+++ b/frontend/src/lib/favourites.js
@@ -0,0 +1,29 @@
+// Favourite exercises (issue #6): a personal shortlist that floats to the top of the picker,
+// the Library and the muscle explorer so building a routine takes fewer scrolls.
+//
+// Stored as a flat id list in synced state (S.favEx) — catalogue or custom ids alike. It is
+// personal, so it stays out of shared plan bundles (lib/plan-share.js) on purpose. Profiles
+// written before the field existed simply have no list, hence every reader tolerates undefined.
+
+export const favIds = S => (Array.isArray(S?.favEx) ? S.favEx : [])
+
+export const isFav = (S, id) => favIds(S).includes(id)
+
+/** Flip one exercise in a state draft. Returns true when it is a favourite afterwards. */
+export function toggleFav(s, id) {
+ const list = favIds(s)
+ const on = !list.includes(id)
+ s.favEx = on ? [...list, id] : list.filter(x => x !== id)
+ return on
+}
+
+/**
+ * Favourites first, everything else after — both halves keep the order they came in, so a
+ * list that is already sorted by name (or by usage) stays that way within each half.
+ */
+export function sortFavouritesFirst(list, S) {
+ const fav = favIds(S)
+ if (!fav.length) return list
+ const set = new Set(fav)
+ return [...list.filter(e => set.has(e.id)), ...list.filter(e => !set.has(e.id))]
+}
diff --git a/frontend/src/lib/favourites.test.js b/frontend/src/lib/favourites.test.js
new file mode 100644
index 000000000..84e3d5f8d
--- /dev/null
+++ b/frontend/src/lib/favourites.test.js
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest'
+import { favIds, isFav, toggleFav, sortFavouritesFirst } from './favourites.js'
+
+const ex = id => ({ id, n: id })
+
+describe('favourites', () => {
+ it('reads a profile without the field as no favourites', () => {
+ expect(favIds({})).toEqual([])
+ expect(favIds({ favEx: null })).toEqual([])
+ expect(isFav({}, '0001')).toBe(false)
+ })
+
+ it('toggles an id in and out of the list and reports the new state', () => {
+ const s = {}
+ expect(toggleFav(s, '0001')).toBe(true)
+ expect(toggleFav(s, 'c123')).toBe(true)
+ expect(s.favEx).toEqual(['0001', 'c123'])
+ expect(isFav(s, '0001')).toBe(true)
+ expect(toggleFav(s, '0001')).toBe(false)
+ expect(s.favEx).toEqual(['c123'])
+ })
+
+ it('moves favourites to the front and keeps both halves in their original order', () => {
+ const list = ['a', 'b', 'c', 'd', 'e'].map(ex)
+ const S = { favEx: ['d', 'b', 'zzz-not-listed'] }
+ expect(sortFavouritesFirst(list, S).map(e => e.id)).toEqual(['b', 'd', 'a', 'c', 'e'])
+ })
+
+ it('returns the very same list when there are no favourites', () => {
+ const list = ['a', 'b'].map(ex)
+ expect(sortFavouritesFirst(list, {})).toBe(list)
+ })
+})
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index a916f6af8..fd9b1e23d 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(620)
- expect(inherited).toHaveLength(598)
+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(621)
+ expect(inherited).toHaveLength(603)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('5f1f5dcac5d51dd96f9d1e3506c6a65fd098071b971739686f3cc0360cca35ec')
+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('45ca712c8ea299590a096c9ee98c12932734ee27fee460660df8a687a2b065f6')
})
test('does not leak European Portuguese UI terms', () => {
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index b2f0cd041..c4a7a9185 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -93,6 +93,12 @@ export default {
'Search {0} exercises…': '{0} Übungen durchsuchen…',
'Chosen': 'Gewählt',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Noch nichts gewählt — füge Übungen hinzu, dann erscheinen sie hier.',
+ 'Add to favourites': 'Zu Favoriten hinzufügen',
+ 'Remove from favourites': 'Aus Favoriten entfernen',
+ 'Added to favourites': 'Zu Favoriten hinzugefügt',
+ 'Removed from favourites': 'Aus Favoriten entfernt',
+ 'Favourites': 'Favoriten',
+ 'No favourites here — tap the star on an exercise to add it.': 'Keine Favoriten hier — tippe bei einer Übung auf den Stern.',
'No match': 'Kein Treffer',
'Show more': 'Mehr anzeigen',
'Intervals': 'Intervalle',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 01e3b64bc..b08123d91 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -89,6 +89,12 @@ export default {
'Search {0} exercises…': 'Buscar entre {0} ejercicios…',
'Chosen': 'Elegidos',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Nada elegido aún — añade ejercicios y aparecerán aquí.',
+ 'Add to favourites': 'Añadir a favoritos',
+ 'Remove from favourites': 'Quitar de favoritos',
+ 'Added to favourites': 'Añadido a favoritos',
+ 'Removed from favourites': 'Quitado de favoritos',
+ 'Favourites': 'Favoritos',
+ 'No favourites here — tap the star on an exercise to add it.': 'Sin favoritos aquí — toca la estrella de un ejercicio para añadirlo.',
'No match': 'Sin resultados',
'Show more': 'Mostrar más',
'Intervals': 'Intervalos',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 687918725..54372917e 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -89,6 +89,12 @@ export default {
'Search {0} exercises…': 'Rechercher parmi {0} exercices…',
'Chosen': 'Choisis',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Rien de choisi — ajoute des exercices et ils apparaîtront ici.',
+ 'Add to favourites': 'Ajouter aux favoris',
+ 'Remove from favourites': 'Retirer des favoris',
+ 'Added to favourites': 'Ajouté aux favoris',
+ 'Removed from favourites': 'Retiré des favoris',
+ 'Favourites': 'Favoris',
+ 'No favourites here — tap the star on an exercise to add it.': 'Aucun favori ici — touche l’étoile d’un exercice pour l’ajouter.',
'No match': 'Aucun résultat',
'Show more': 'Afficher plus',
'Intervals': 'Intervalles',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 96a1a2f43..9e8928ec3 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -89,6 +89,12 @@ export default {
'Search {0} exercises…': '{0} व्यायामों में खोजें…',
'Chosen': 'चुने हुए',
'Nothing chosen yet — add exercises and they’ll show up here.': 'अभी कुछ नहीं चुना — व्यायाम जोड़ें तो वे यहाँ दिखेंगे।',
+ 'Add to favourites': 'पसंदीदा में जोड़ें',
+ 'Remove from favourites': 'पसंदीदा से हटाएँ',
+ 'Added to favourites': 'पसंदीदा में जोड़ा गया',
+ 'Removed from favourites': 'पसंदीदा से हटाया गया',
+ 'Favourites': 'पसंदीदा',
+ 'No favourites here — tap the star on an exercise to add it.': 'यहाँ कोई पसंदीदा नहीं — किसी व्यायाम पर तारे को टैप करें।',
'No match': 'कोई परिणाम नहीं',
'Show more': 'और दिखाएँ',
'Intervals': 'इंटरवल',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index c2da363b8..941ca3ef9 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -92,6 +92,12 @@ export default {
'Search {0} exercises…': '{0} gyakorlat keresése…',
'Chosen': 'Kiválasztva',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Még nincs kiválasztva semmi — adj hozzá gyakorlatokat, és itt fognak megjelenni.',
+ 'Add to favourites': 'Kedvencekhez adás',
+ 'Remove from favourites': 'Eltávolítás a kedvencekből',
+ 'Added to favourites': 'Hozzáadva a kedvencekhez',
+ 'Removed from favourites': 'Eltávolítva a kedvencekből',
+ 'Favourites': 'Kedvencek',
+ 'No favourites here — tap the star on an exercise to add it.': 'Itt nincs kedvenc — koppints egy gyakorlat csillagára.',
'No match': 'Nincs találat',
'Show more': 'Több megjelenítése',
'Intervals': 'Intervallumok',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 497b57553..057c4b143 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -89,6 +89,12 @@ export default {
'Search {0} exercises…': 'Cerca tra {0} esercizi…',
'Chosen': 'Scelti',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Ancora niente — aggiungi esercizi e appariranno qui.',
+ 'Add to favourites': 'Aggiungi ai preferiti',
+ 'Remove from favourites': 'Rimuovi dai preferiti',
+ 'Added to favourites': 'Aggiunto ai preferiti',
+ 'Removed from favourites': 'Rimosso dai preferiti',
+ 'Favourites': 'Preferiti',
+ 'No favourites here — tap the star on an exercise to add it.': 'Nessun preferito qui — tocca la stella di un esercizio per aggiungerlo.',
'No match': 'Nessun risultato',
'Show more': 'Mostra altro',
'Intervals': 'Intervalli',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 6b3d8d2c1..667d9e1ab 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -87,8 +87,14 @@ export default {
'Create one and start with this exercise': '새로 만들어 이 운동으로 시작',
'Add exercise': '운동 추가',
'Search {0} exercises…': '{0}개 운동 검색…',
- 'Chosen': '즐겨찾기',
+ 'Chosen': '선택됨',
'Nothing chosen yet — add exercises and they’ll show up here.': '아직 없어요 — 운동을 추가하면 여기에 표시됩니다.',
+ 'Add to favourites': '즐겨찾기에 추가',
+ 'Remove from favourites': '즐겨찾기에서 제거',
+ 'Added to favourites': '즐겨찾기에 추가했어요',
+ 'Removed from favourites': '즐겨찾기에서 제거했어요',
+ 'Favourites': '즐겨찾기',
+ 'No favourites here — tap the star on an exercise to add it.': '즐겨찾기가 없어요 — 운동의 별을 눌러 추가하세요.',
'No match': '검색 결과 없음',
'Show more': '더 보기',
'Intervals': '인터벌',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 1d136a97a..ca0a2e956 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -89,6 +89,12 @@ export default {
'Search {0} exercises…': 'Szukaj wśród {0} ćwiczeń…',
'Chosen': 'Wybrane',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Nic nie wybrano — dodaj ćwiczenia, a pojawią się tutaj.',
+ 'Add to favourites': 'Dodaj do ulubionych',
+ 'Remove from favourites': 'Usuń z ulubionych',
+ 'Added to favourites': 'Dodano do ulubionych',
+ 'Removed from favourites': 'Usunięto z ulubionych',
+ 'Favourites': 'Ulubione',
+ 'No favourites here — tap the star on an exercise to add it.': 'Brak ulubionych — dotknij gwiazdki przy ćwiczeniu, aby je dodać.',
'No match': 'Brak wyników',
'Show more': 'Pokaż więcej',
'Intervals': 'Interwały',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 9480788dd..f3e5f60f6 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -32,6 +32,7 @@ export const PT_BR_OVERRIDES = {
'Create one and start with this exercise': 'Crie uma e comece com este exercício',
'Search {0} exercises…': 'Buscar entre {0} exercícios…',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Nenhum exercício escolhido — adicione exercícios e eles aparecerão aqui.',
+ 'No favourites here — tap the star on an exercise to add it.': 'Sem favoritos aqui — toque na estrela de um exercício para adicioná-lo.',
'The sets you logged for this exercise in this session will be lost.': 'As séries registradas para este exercício nesta sessão serão perdidas.',
'Swap exercise': 'Trocar exercício',
'Swap exercise?': 'Trocar exercício?',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index b23868852..896fe83cb 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -89,6 +89,12 @@ export default {
'Search {0} exercises…': 'Pesquisar {0} exercícios…',
'Chosen': 'Escolhidos',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Ainda nada escolhido — adiciona exercícios e eles aparecem aqui.',
+ 'Add to favourites': 'Adicionar aos favoritos',
+ 'Remove from favourites': 'Remover dos favoritos',
+ 'Added to favourites': 'Adicionado aos favoritos',
+ 'Removed from favourites': 'Removido dos favoritos',
+ 'Favourites': 'Favoritos',
+ 'No favourites here — tap the star on an exercise to add it.': 'Sem favoritos aqui — toca na estrela de um exercício para o adicionar.',
'No match': 'Sem resultados',
'Show more': 'Mostrar mais',
'Intervals': 'Intervalos',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index f05aa66ae..d5ea1b649 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -87,8 +87,14 @@ export default {
'Create one and start with this exercise': 'Создай новую и начни с этого упражнения',
'Add exercise': 'Добавить упражнение',
'Search {0} exercises…': 'Поиск среди {0} упражнений…',
- 'Chosen': 'Избранные',
+ 'Chosen': 'Выбранные',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Пока ничего нет — добавляй упражнения, и они появятся здесь.',
+ 'Add to favourites': 'В избранное',
+ 'Remove from favourites': 'Убрать из избранного',
+ 'Added to favourites': 'Добавлено в избранное',
+ 'Removed from favourites': 'Убрано из избранного',
+ 'Favourites': 'Избранное',
+ 'No favourites here — tap the star on an exercise to add it.': 'Здесь нет избранного — нажми на звезду у упражнения.',
'No match': 'Ничего не найдено',
'Show more': 'Показать ещё',
'Intervals': 'Интервалы',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index e6fb2e12a..96c05ce72 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -92,6 +92,12 @@ export default {
'Search {0} exercises…': 'ค้นหาใน {0} ท่า…',
'Chosen': 'ที่เลือกไว้',
'Nothing chosen yet — add exercises and they’ll show up here.': 'ยังไม่ได้เลือกอะไรเลย — เพิ่มท่าออกกำลังกายแล้วจะโผล่มาที่นี่',
+ 'Add to favourites': 'เพิ่มในรายการโปรด',
+ 'Remove from favourites': 'นำออกจากรายการโปรด',
+ 'Added to favourites': 'เพิ่มในรายการโปรดแล้ว',
+ 'Removed from favourites': 'นำออกจากรายการโปรดแล้ว',
+ 'Favourites': 'รายการโปรด',
+ 'No favourites here — tap the star on an exercise to add it.': 'ยังไม่มีรายการโปรดที่นี่ — แตะดาวที่ท่าออกกำลังกายเพื่อเพิ่ม',
'No match': 'ไม่พบผลลัพธ์',
'Show more': 'แสดงเพิ่ม',
'Intervals': 'อินเทอร์วัล',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index a3d5fb91f..5582f29b9 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -89,6 +89,12 @@ export default {
'Search {0} exercises…': '{0} egzersiz içinde ara…',
'Chosen': 'Seçilenler',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Henüz seçim yok — egzersiz ekledikçe burada görünecekler.',
+ 'Add to favourites': 'Favorilere ekle',
+ 'Remove from favourites': 'Favorilerden çıkar',
+ 'Added to favourites': 'Favorilere eklendi',
+ 'Removed from favourites': 'Favorilerden çıkarıldı',
+ 'Favourites': 'Favoriler',
+ 'No favourites here — tap the star on an exercise to add it.': 'Burada favori yok — eklemek için bir egzersizin yıldızına dokun.',
'No match': 'Sonuç yok',
'Show more': 'Daha fazla göster',
'Intervals': 'Aralıklar',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 911e3d242..1a44347a9 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -89,6 +89,12 @@ export default {
'Search {0} exercises…': '搜索 {0} 个动作…',
'Chosen': '常用',
'Nothing chosen yet — add exercises and they’ll show up here.': '还没有常用动作——添加后会显示在这里。',
+ 'Add to favourites': '加入收藏',
+ 'Remove from favourites': '取消收藏',
+ 'Added to favourites': '已加入收藏',
+ 'Removed from favourites': '已取消收藏',
+ 'Favourites': '收藏',
+ 'No favourites here — tap the star on an exercise to add it.': '这里还没有收藏——点动作旁的星标即可加入。',
'No match': '没有匹配',
'Show more': '显示更多',
'Intervals': '间歇数',
diff --git a/frontend/src/sheets.favourites.test.jsx b/frontend/src/sheets.favourites.test.jsx
new file mode 100644
index 000000000..1a8249123
--- /dev/null
+++ b/frontend/src/sheets.favourites.test.jsx
@@ -0,0 +1,96 @@
+// @vitest-environment happy-dom
+// Favourites (issue #6): the detail sheet's star writes S.favEx, and the picker floats
+// favourites to the top of its list without disturbing the order of everything else.
+import React, { act } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createRoot } from 'react-dom/client'
+import { EXDB } from './lib/exercises.js'
+import { DEF, useStore } from './store/useStore.js'
+import { useUI } from './store/useUI.js'
+import { exerciseDetailSheet, exercisePicker } from './sheets.jsx'
+
+const mounted = []
+const S = () => useStore.getState().S
+
+// Renders whatever sheet is on top and returns its host element.
+function renderTop() {
+ const sheet = useUI.getState().sheets.at(-1)
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push(root)
+ act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
+ return host
+}
+
+const names = host => [...host.querySelectorAll('.item .tt')].map(el => el.textContent)
+const starOf = host => host.querySelector('.fav-btn')
+
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ useUI.setState({ sheets: [], toastMsg: '' })
+ useStore.setState({ S: structuredClone(DEF), user: null })
+ document.body.innerHTML = ''
+})
+
+afterEach(() => {
+ act(() => { mounted.splice(0).forEach(root => root.unmount()) })
+})
+
+describe('exercise detail star', () => {
+ it('adds and removes the exercise from favourites with a toast', () => {
+ const ex = EXDB[0]
+ exerciseDetailSheet(ex)
+ const host = renderTop()
+ expect(starOf(host).getAttribute('aria-label')).toBe('Add to favourites')
+ act(() => starOf(host).click())
+ expect(S().favEx).toEqual([ex.id])
+ expect(useUI.getState().toastMsg).toBe('Added to favourites')
+ expect(starOf(host).getAttribute('aria-label')).toBe('Remove from favourites')
+ expect(starOf(host).getAttribute('aria-pressed')).toBe('true')
+ act(() => starOf(host).click())
+ expect(S().favEx).toEqual([])
+ expect(useUI.getState().toastMsg).toBe('Removed from favourites')
+ })
+
+ it('tolerates a profile written before the field existed', () => {
+ useStore.setState(s => { const next = { ...s.S }; delete next.favEx; return { S: next } })
+ exerciseDetailSheet(EXDB[0])
+ const host = renderTop()
+ act(() => starOf(host).click())
+ expect(S().favEx).toEqual([EXDB[0].id])
+ })
+})
+
+describe('exercise picker', () => {
+ it('lists favourites first and marks them, keeping the rest in catalogue order', () => {
+ const plain = names((exercisePicker(vi.fn()), renderTop())).slice(1) // drop "Create your own"
+ useUI.setState({ sheets: [] })
+ const fav = [plain[7], plain[3]]
+ const favIds = fav.map(n => EXDB.find(e => e.n === n).id)
+ useStore.setState(s => ({ S: { ...s.S, favEx: favIds } }))
+ exercisePicker(vi.fn())
+ const host = renderTop()
+ const shown = names(host).slice(1)
+ // Favourites keep the list's own order among themselves — not the order they were starred in.
+ expect(shown.slice(0, 2)).toEqual(plain.filter(n => fav.includes(n)))
+ expect(shown.slice(2)).toEqual(plain.filter(n => !fav.includes(n)))
+ const rows = [...host.querySelectorAll('.item')].slice(1)
+ expect(rows.slice(0, 2).every(r => r.querySelector('.tt .fav-star'))).toBe(true)
+ expect(rows[2].querySelector('.tt .fav-star')).toBeNull()
+ })
+
+ it('offers a Favourites chip only when there are favourites, and it filters to them', () => {
+ exercisePicker(vi.fn())
+ let host = renderTop()
+ const chip = h => [...h.querySelectorAll('.chips .chip')].find(b => b.textContent.startsWith('Favourites'))
+ expect(chip(host)).toBeUndefined()
+ useUI.setState({ sheets: [] })
+ useStore.setState(s => ({ S: { ...s.S, favEx: [EXDB[5].id, EXDB[9].id] } }))
+ exercisePicker(vi.fn())
+ host = renderTop()
+ expect(chip(host).textContent).toBe('Favourites (2)')
+ act(() => chip(host).click())
+ expect(names(host)).toEqual([EXDB[5].n, EXDB[9].n])
+ })
+})
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 9c795f120..2a4beaae3 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -31,6 +31,7 @@ import { isWarmupRow } from './lib/workout-model.js'
import { nextUnfinishedUnit } from './lib/supersetFlow.js'
import { swapActiveExercise } from './lib/active-exercise-swap.js'
import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js'
+import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js'
import { buildSessionEntries } from './lib/session-start.js'
import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'
@@ -622,8 +623,20 @@ function ExerciseDetail({ ex, close }) {
const st = useStore(s => s.S)
const last = lastEntryFor(st, ex.id)
const best = bestWeightFor(st, ex.id)
+ const fav = isFav(st, ex.id)
+ const flipFav = () => {
+ let on = false
+ update(s => { on = toggleFav(s, ex.id) })
+ toast(on ? t('Added to favourites') : t('Removed from favourites'))
+ }
return <>
- <h3 className="capitalize">{exerciseNameFor(ex)}</h3>
+ <div className="row between" style={{ gap: 8, alignItems: 'flex-start' }}>
+ <h3 className="capitalize">{exerciseNameFor(ex)}</h3>
+ <button className={'iconbtn fav-btn' + (fav ? ' on' : '')} aria-pressed={fav}
+ aria-label={fav ? t('Remove from favourites') : t('Add to favourites')} onClick={flipFav}>
+ <Icon name={fav ? 'starFill' : 'star'} />
+ </button>
+ </div>
<Media ex={ex} />
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0' }}>
<span className="tag acc">{t(ex.bp)}</span>
@@ -769,6 +782,7 @@ export function deleteCustomEx(ex, afterDelete) {
s.customEx = (s.customEx || []).filter(x => x.id !== ex.id)
s.routines.forEach(r => { r.ex = r.ex.filter(e => e.id !== ex.id); cleanupSg(r.ex) })
delete s.exWeights[ex.id]
+ s.favEx = (s.favEx || []).filter(id => id !== ex.id)
})
toast(t('Exercise deleted'))
afterDelete && afterDelete()
@@ -788,7 +802,7 @@ function ExercisePicker({ onPick, close }) {
const st = useStore(s => s.S)
const usage = usageMap(st)
const [q, setQ] = useState('')
- const [bp, setBp] = useState('') // '' = all, '★' = chosen, else a body part
+ const [bp, setBp] = useState('') // '' = all, '★' = chosen, '☆' = favourites, else a body part
const [eq, setEq] = useState('') // '' = any equipment
const [showAll, setShowAll] = useState(false)
const [shown, setShown] = useState(50)
@@ -798,16 +812,18 @@ function ExercisePicker({ onPick, close }) {
const onSearchFocus = useSheetKeyboard(searchRef)
const all = allExercises(st)
const profile = activeProfile(st)
- let base = all.filter(e =>
- (bp === '★' ? usage[e.id] : (!bp || e.bp === bp)) &&
- matchExercise(e, q))
+ const inScope = e => bp === '★' ? usage[e.id] : bp === '☆' ? isFav(st, e.id) : (!bp || e.bp === bp)
+ let base = all.filter(e => inScope(e) && matchExercise(e, q))
if (bp === '★') base = [...base].sort((a, b) => (usage[b.id] - usage[a.id]) || exerciseNameFor(a).localeCompare(exerciseNameFor(b)))
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(st, e)) : base
const eqOpts = equipmentOf(eqFiltered)
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
const eqOn = eqOpts.includes(eq) ? eq : ''
- const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
+ // Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order.
+ const f = sortFavouritesFirst(eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered, st)
const chosenCount = Object.keys(usage).length
+ const favCount = (st.favEx || []).length
+ const special = bp === '★' || bp === '☆'
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
if (byMuscle) return <>
@@ -833,6 +849,7 @@ function ExercisePicker({ onPick, close }) {
</button>
</div>}
<div className="chips" ref={bpStrip} style={{ margin: eqOpts.length > 1 ? '10px 0 6px' : '10px 0' }}>
+ {favCount > 0 && <button className={'chip' + (bp === '☆' ? ' on' : '')} onClick={() => { setBp('☆'); setEq(''); setShown(50) }}><Icon name="starFill" className="fav-star" />{t('Favourites')} ({favCount})</button>}
{chosenCount > 0 && <button className={'chip' + (bp === '★' ? ' on' : '')} onClick={() => { setBp('★'); setEq(''); setShown(50) }}><Icon name="starFill" style={{ fontSize: 12, display: 'inline-block', marginRight: 4, verticalAlign: '-1px' }} />{t('Chosen')} ({chosenCount})</button>}
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(50) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(50) }}>{t(b)}</button>)}
@@ -842,12 +859,13 @@ function ExercisePicker({ onPick, close }) {
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(50) }}>{t(x)}</button>)}
</div>}
<div className="list">
- {bp !== '★' && <div className="item" {...tappable(() => customExSheet(null, ex => onPick(ex), q.trim()))}>
+ {!special && <div className="item" {...tappable(() => customExSheet(null, ex => onPick(ex), q.trim()))}>
<div className="thumb thumb-x"><Icon name="sparkles" /></div>
<div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, no animation')}</div></div><Icon name="plus" className="chev" />
</div>}
{f.slice(0, shown).map(e => <div key={e.id} className="item" {...tappable(() => onPick(e))}>
- <Thumb ex={e} /><div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
+ <Thumb ex={e} /><div className="grow"><div className="tt capitalize">{isFav(st, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
+ {/* Accent tag = already in a routine/log ("Chosen"); the yellow star by the name = favourite. */}
{usage[e.id] && <span className="tag acc"><Icon name="starFill" /></span>}
{/* A "+" glyph reads as "add this now" — it used to just open the same detail sheet as
tapping the row, so it added nothing until you'd scrolled past the sets/reps config
@@ -858,6 +876,7 @@ function ExercisePicker({ onPick, close }) {
onClick={ev => { ev.stopPropagation(); onPick(e, true) }}><Icon name="plus" /></button>
</div>)}
{f.length === 0 && bp === '★' && <div className="empty">{t('Nothing chosen yet — add exercises and they’ll show up here.')}</div>}
+ {f.length === 0 && bp === '☆' && <div className="empty">{t('No favourites here — tap the star on an exercise to add it.')}</div>}
</div>
{f.length > shown && <><div style={{ height: 8 }} /><Button onClick={() => setShown(s => s + 50)}>{t('Show more')}</Button></>}
</>
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 15f74dc1e..33dd4a7ee 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -36,6 +36,9 @@ export const DEF = {
// 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: {},
+ // 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: [],
// First day of the week as a getDay() index — 1 Monday, 0 Sunday. Monday is the default so
// every profile written before this setting existed keeps the week it has been looking at.
// See lib/format.js: nothing reads this field directly, everything goes through the helpers.
diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsx
index b591abb30..52eac47de 100644
--- a/frontend/src/views/Library.jsx
+++ b/frontend/src/views/Library.jsx
@@ -11,6 +11,7 @@ import { exerciseDetailSheet, addToRoutineSheet, customExSheet } from '../sheets
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js'
+import { isFav, sortFavouritesFirst } from '../lib/favourites.js'
export default function Library() {
const nav = useNavigate()
@@ -27,7 +28,8 @@ export default function Library() {
const eqOpts = equipmentOf(eqFiltered)
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
const eqOn = eqOpts.includes(eq) ? eq : ''
- const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
+ // Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order.
+ const f = sortFavouritesFirst(eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered, S)
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
@@ -61,7 +63,7 @@ export default function Library() {
const best = bestWeightFor(S, e.id)
return <div key={e.id} className="item" {...tappable(() => exerciseDetailSheet(e))}>
<Thumb ex={e} />
- <div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
+ <div className="grow"><div className="tt capitalize">{isFav(S, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
<Button size="sm" variant="tinted" icon="plus" onClick={ev => { ev.stopPropagation(); addToRoutineSheet(e) }}>{t('Plan')}</Button>
</div>
diff --git a/frontend/src/views/Library.test.jsx b/frontend/src/views/Library.test.jsx
new file mode 100644
index 000000000..b4d95435f
--- /dev/null
+++ b/frontend/src/views/Library.test.jsx
@@ -0,0 +1,68 @@
+// @vitest-environment happy-dom
+// Favourites (issue #6): the Library floats starred exercises to the top of the current
+// result list — after the search and body-part filters, without reordering the rest.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Library from './Library.jsx'
+import { EXDB } from '../lib/exercises.js'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+const mocks = vi.hoisted(() => {
+ const state = { S: null }
+ state.snapshot = () => ({ S: state.S, user: null, update: mut => { const next = structuredClone(state.S); mut(next); state.S = next } })
+ return state
+})
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
+ useStore.getState = mocks.snapshot
+ return { useStore }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
+vi.mock('../sheets.jsx', () => ({ exerciseDetailSheet: vi.fn(), addToRoutineSheet: vi.fn(), customExSheet: vi.fn() }))
+
+const mounted = []
+function render() {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push(root)
+ act(() => root.render(<Library />))
+ return host
+}
+const names = host => [...host.querySelectorAll('.item .tt')].map(el => el.textContent).slice(1) // drop "Create your own"
+
+beforeEach(() => {
+ mocks.S = { unit: 'kg', lang: 'en', routines: [], workouts: [], customEx: [], exWeights: {}, equipProfiles: [], activeEquipId: null, equipFilterOn: false }
+ document.body.innerHTML = ''
+})
+afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
+
+describe('Library favourites', () => {
+ it('puts favourites first, marked with a star, and leaves the rest in catalogue order', () => {
+ const plain = names(render())
+ act(() => { mounted.splice(0).forEach(root => root.unmount()) })
+ const fav = [plain[6], plain[2]]
+ mocks.S.favEx = fav.map(n => EXDB.find(e => e.n === n).id)
+ const host = render()
+ const shown = names(host)
+ expect(shown.slice(0, 2)).toEqual(plain.filter(n => fav.includes(n)))
+ expect(shown.slice(2)).toEqual(plain.filter(n => !fav.includes(n)))
+ const rows = [...host.querySelectorAll('.item')].slice(1)
+ expect(rows[0].querySelector('.fav-star')).not.toBeNull()
+ expect(rows[2].querySelector('.fav-star')).toBeNull()
+ })
+
+ it('keeps a favourite on top inside a body-part filter, but never pulls one in from elsewhere', () => {
+ const chest = EXDB.filter(e => e.bp === 'chest')
+ const legs = EXDB.find(e => e.bp !== 'chest')
+ mocks.S.favEx = [chest[4].id, legs.id]
+ const host = render()
+ const chip = [...host.querySelectorAll('.chips .chip')].find(b => b.textContent === 'chest')
+ act(() => chip.click())
+ const shown = names(host)
+ expect(shown[0]).toBe(chest[4].n)
+ expect(shown).not.toContain(legs.n)
+ })
+})