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
Plan/Settings/Home: ownership-aware scheduling screens, QueueRow's own copy for a managed pass — screens and integration tests, localized in all 14 packs
giulioleuci6bb610fd0ce1
diff --git a/frontend/src/components/QueueRow.jsx b/frontend/src/components/QueueRow.jsxindex 53fc30e9f..7588ad3fd 100644--- a/frontend/src/components/QueueRow.jsx+++ b/frontend/src/components/QueueRow.jsx@@ -12,7 +12,7 @@ import Icon from './Icon.jsx'// S.dayPlan) is not lit and wears its day instead of a state word — it still starts on a tap.// Reads through queueView so the words here and the today row (effectiveRoutineIds →// queueNext) can never disagree about which is next.-export default function QueueRow({ S, today, onStart }) {+export default function QueueRow({ S, today, onStart, managed }) {const v = queueView(S, today)if (!v) return nullconst word = { done: t('Done'), next: t('Up next'), later: t('Later') }@@ -23,8 +23,10 @@ export default function QueueRow({ S, today, onStart }) {// "today" only when the today row really offers it: a 'rest' or routine override for today// wins over the queue there (effectiveRoutineIds), and this line must not contradict it.const shownToday = !!next && effectiveRoutineIds(S, today, today).includes(next.id)- const status = v.complete ? t('Week complete, ask the coach')- : v.waiting ? t('Next week starts {0}', fmtDate(v.startsOn, true))+ // A pass this app manages refills itself (lib/rotation.js) — "ask the coach" and naming a+ // whole week are a planner's copy, wrong for a pass with no coach and no week shape at all.+ const status = v.complete ? (managed ? t('Pass complete') : t('Week complete, ask the coach'))+ : v.waiting ? (managed ? t('Next pass starts {0}', fmtDate(v.startsOn, true)) : t('Next week starts {0}', fmtDate(v.startsOn, true))): shownToday ? t('Next: {0}, today', next.name): next ? t('Next: {0}', next.name): t('Next: {0}', pinned.name + ' · ' + fmtDate(pinned.on, true))diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 5932ba48a..496cfdcc2 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1691,4 +1691,29 @@ export default {'Yellow': 'Gelb','Enter how long it took — at least 1 minute.': 'Gib ein, wie lange es gedauert hat — mindestens 1 Minute.','Coach week': 'Coach-Woche',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Rotation',+ 'Fixed Week': 'Feste Woche',+ 'Scheduling': 'Zeitplanung',+ 'Externally managed': 'Extern verwaltet',+ 'Position {0}': 'Position {0}',+ 'Add routine to the rotation': 'Routine zur Rotation hinzufügen',+ 'Add to the rotation': 'Zur Rotation hinzufügen',+ 'Build a rotation instead': 'Stattdessen eine Rotation erstellen',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Noch keine Rotation. Füge Routinen in der Reihenfolge hinzu, in der du sie trainieren willst — die erste, die du noch nicht abgehakt hast, bleibt die nächste.',+ 'Use this rotation': 'Diese Rotation übernehmen',+ 'Use this rotation?': 'Diese Rotation übernehmen?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'openGym übernimmt ab jetzt das Auffüllen dieser Warteschlange — die App deines Coaches sollte sie nicht mehr beschreiben.',+ 'Start new pass': 'Neuen Durchgang starten',+ 'Start pass': 'Durchgang starten',+ 'This rotation could not be read — it may have been written by another device.': 'Diese Rotation konnte nicht gelesen werden — sie wurde möglicherweise von einem anderen Gerät geschrieben.',+ 'Discard it': 'Verwerfen',+ 'Switch to Fixed Week?': 'Zu Feste Woche wechseln?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'Die Rotation stoppt und ihr aktueller Durchgang wird verworfen. Dein Wochenplan kommt genau so zurück, wie er war, und die Reihenfolge bleibt gespeichert, damit du später einen neuen Durchgang starten kannst.',+ 'Use Fixed Week': 'Feste Woche verwenden',+ 'No rotation yet — add routines to it in Plan.': 'Noch keine Rotation — füge im Plan Routinen hinzu.',+ 'Set up in Plan': 'Im Plan einrichten',+ 'Pass complete': 'Durchgang abgeschlossen',+ 'Next pass starts {0}': 'Nächster Durchgang beginnt {0}',+}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 6db6379db..bf6b40444 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1671,4 +1671,29 @@ export default {'Yellow': 'Amarillo','Enter how long it took — at least 1 minute.': 'Indica cuánto duró — al menos 1 minuto.','Coach week': 'Semana del entrenador',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Rotación',+ 'Fixed Week': 'Semana fija',+ 'Scheduling': 'Programación',+ 'Externally managed': 'Gestionada externamente',+ 'Position {0}': 'Posición {0}',+ 'Add routine to the rotation': 'Añadir rutina a la rotación',+ 'Add to the rotation': 'Añadir a la rotación',+ 'Build a rotation instead': 'Crear una rotación en su lugar',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Aún no hay rotación. Añade rutinas en el orden en que quieres entrenarlas — la primera que no hayas registrado sigue siendo la siguiente.',+ 'Use this rotation': 'Usar esta rotación',+ 'Use this rotation?': '¿Usar esta rotación?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'openGym se encargará de rellenar esta cola a partir de ahora — la app de tu entrenador ya no debería escribir en ella.',+ 'Start new pass': 'Iniciar nueva pasada',+ 'Start pass': 'Iniciar pasada',+ 'This rotation could not be read — it may have been written by another device.': 'No se pudo leer esta rotación — puede que la haya escrito otro dispositivo.',+ 'Discard it': 'Descartarla',+ 'Switch to Fixed Week?': '¿Cambiar a Semana fija?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'La rotación se detiene y su pasada actual se descarta. Tu plan semanal vuelve exactamente como estaba, y la secuencia se guarda para que puedas iniciar una nueva pasada más adelante.',+ 'Use Fixed Week': 'Usar Semana fija',+ 'No rotation yet — add routines to it in Plan.': 'Aún no hay rotación — añade rutinas en el Plan.',+ 'Set up in Plan': 'Configurar en el Plan',+ 'Pass complete': 'Pasada completada',+ 'Next pass starts {0}': 'La próxima pasada empieza {0}',+}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex d7878c08a..7ec918979 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1671,4 +1671,29 @@ export default {'Yellow': 'Jaune','Enter how long it took — at least 1 minute.': 'Indique combien de temps ça a duré — au moins 1 minute.','Coach week': 'Semaine du coach',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Rotation',+ 'Fixed Week': 'Semaine fixe',+ 'Scheduling': 'Planification',+ 'Externally managed': 'Gérée en externe',+ 'Position {0}': 'Position {0}',+ 'Add routine to the rotation': 'Ajouter une routine à la rotation',+ 'Add to the rotation': 'Ajouter à la rotation',+ 'Build a rotation instead': 'Créer une rotation à la place',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Aucune rotation pour l’instant. Ajoute des routines dans l’ordre où tu veux les faire — la première que tu n’as pas encore loggée reste la suivante.',+ 'Use this rotation': 'Utiliser cette rotation',+ 'Use this rotation?': 'Utiliser cette rotation ?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'openGym prendra en charge le remplissage de cette file à partir de maintenant — l’appli de ton coach ne devrait plus y écrire.',+ 'Start new pass': 'Démarrer un nouveau passage',+ 'Start pass': 'Démarrer un passage',+ 'This rotation could not be read — it may have been written by another device.': 'Cette rotation n’a pas pu être lue — elle a peut-être été écrite par un autre appareil.',+ 'Discard it': 'L’abandonner',+ 'Switch to Fixed Week?': 'Passer à Semaine fixe ?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'La rotation s’arrête et son passage en cours est abandonné. Ton planning hebdomadaire revient exactement comme il était, et la séquence est conservée pour démarrer un nouveau passage plus tard.',+ 'Use Fixed Week': 'Utiliser Semaine fixe',+ 'No rotation yet — add routines to it in Plan.': 'Aucune rotation pour l’instant — ajoute des routines dans le Plan.',+ 'Set up in Plan': 'Configurer dans le Plan',+ 'Pass complete': 'Passage terminé',+ 'Next pass starts {0}': 'Le prochain passage commence {0}',+}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex fe937c8f8..71f1db4ac 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1671,4 +1671,29 @@ export default {'Yellow': 'पीला','Enter how long it took — at least 1 minute.': 'बताएँ कि इसमें कितना समय लगा — कम से कम 1 मिनट।','Coach week': 'कोच का सप्ताह',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'रोटेशन',+ 'Fixed Week': 'नियत सप्ताह',+ 'Scheduling': 'शेड्यूलिंग',+ 'Externally managed': 'बाहरी रूप से प्रबंधित',+ 'Position {0}': 'स्थान {0}',+ 'Add routine to the rotation': 'रोटेशन में रूटीन जोड़ें',+ 'Add to the rotation': 'रोटेशन में जोड़ें',+ 'Build a rotation instead': 'इसके बजाय एक रोटेशन बनाएं',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'अभी कोई रोटेशन नहीं। रूटीन को उसी क्रम में जोड़ें जिसमें आप उन्हें ट्रेन करना चाहते हैं — जिसे आपने अभी तक लॉग नहीं किया है वह अगला बना रहता है।',+ 'Use this rotation': 'इस रोटेशन का उपयोग करें',+ 'Use this rotation?': 'इस रोटेशन का उपयोग करें?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'अब से openGym इस कतार को भरने का काम संभाल लेगा — आपके कोच के ऐप को अब इसमें कुछ नहीं लिखना चाहिए।',+ 'Start new pass': 'नया पास शुरू करें',+ 'Start pass': 'पास शुरू करें',+ 'This rotation could not be read — it may have been written by another device.': 'यह रोटेशन पढ़ा नहीं जा सका — हो सकता है इसे किसी अन्य डिवाइस ने लिखा हो।',+ 'Discard it': 'इसे हटा दें',+ 'Switch to Fixed Week?': 'नियत सप्ताह पर स्विच करें?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'रोटेशन रुक जाता है और उसका मौजूदा पास हटा दिया जाता है। आपकी साप्ताहिक योजना बिल्कुल वैसी ही वापस आ जाती है जैसी थी, और क्रम सुरक्षित रहता है ताकि आप बाद में नया पास शुरू कर सकें।',+ 'Use Fixed Week': 'नियत सप्ताह का उपयोग करें',+ 'No rotation yet — add routines to it in Plan.': 'अभी कोई रोटेशन नहीं — योजना में रूटीन जोड़ें।',+ 'Set up in Plan': 'योजना में सेट करें',+ 'Pass complete': 'पास पूरा हुआ',+ 'Next pass starts {0}': 'अगला पास {0} से शुरू होगा',+}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex b34f60996..d6756ba1f 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1674,4 +1674,29 @@ export default {'Yellow': 'Sárga','Enter how long it took — at least 1 minute.': 'Add meg, meddig tartott — legalább 1 perc.','Coach week': 'Edzői hét',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Rotáció',+ 'Fixed Week': 'Fix hét',+ 'Scheduling': 'Ütemezés',+ 'Externally managed': 'Külsőleg kezelt',+ 'Position {0}': 'Pozíció {0}',+ 'Add routine to the rotation': 'Rutin hozzáadása a rotációhoz',+ 'Add to the rotation': 'Hozzáadás a rotációhoz',+ 'Build a rotation instead': 'Rotáció létrehozása helyette',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Még nincs rotáció. Add hozzá a rutinokat abban a sorrendben, ahogy edzeni szeretnéd őket — amit még nem naplóztál, az marad a következő.',+ 'Use this rotation': 'Ezen rotáció használata',+ 'Use this rotation?': 'Ezt a rotációt használod?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'Mostantól az openGym veszi át ennek a várólistának a feltöltését — az edződ alkalmazásának többé nem kellene írnia bele.',+ 'Start new pass': 'Új menet indítása',+ 'Start pass': 'Menet indítása',+ 'This rotation could not be read — it may have been written by another device.': 'Ezt a rotációt nem sikerült beolvasni — lehet, hogy egy másik eszköz írta.',+ 'Discard it': 'Elvetése',+ 'Switch to Fixed Week?': 'Átváltasz Fix hétre?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'A rotáció leáll, és a jelenlegi menete elvész. A heti terved pontosan úgy tér vissza, ahogy volt, a sorrend pedig megmarad, hogy később új menetet indíthass.',+ 'Use Fixed Week': 'Fix hét használata',+ 'No rotation yet — add routines to it in Plan.': 'Még nincs rotáció — adj hozzá rutinokat a Tervben.',+ 'Set up in Plan': 'Beállítás a Tervben',+ 'Pass complete': 'Menet kész',+ 'Next pass starts {0}': 'A következő menet {0}-kor kezdődik',+}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 61d4f8ee6..1d78748b6 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1671,4 +1671,29 @@ export default {'Yellow': 'Giallo','Enter how long it took — at least 1 minute.': 'Inserisci quanto è durato — almeno 1 minuto.','Coach week': 'Settimana del coach',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Rotazione',+ 'Fixed Week': 'Settimana fissa',+ 'Scheduling': 'Pianificazione',+ 'Externally managed': 'Gestita esternamente',+ 'Position {0}': 'Posizione {0}',+ 'Add routine to the rotation': 'Aggiungi routine alla rotazione',+ 'Add to the rotation': 'Aggiungi alla rotazione',+ 'Build a rotation instead': 'Crea una rotazione invece',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Ancora nessuna rotazione. Aggiungi le routine nell’ordine in cui vuoi allenarle — la prima che non hai ancora registrato resta la prossima.',+ 'Use this rotation': 'Usa questa rotazione',+ 'Use this rotation?': 'Usare questa rotazione?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'openGym si occuperà da ora in poi di riempire questa coda — l’app del tuo coach non dovrebbe più scriverci.',+ 'Start new pass': 'Avvia nuovo giro',+ 'Start pass': 'Avvia giro',+ 'This rotation could not be read — it may have been written by another device.': 'Questa rotazione non può essere letta — potrebbe essere stata scritta da un altro dispositivo.',+ 'Discard it': 'Scartala',+ 'Switch to Fixed Week?': 'Passare a Settimana fissa?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'La rotazione si ferma e il giro attuale viene scartato. Il tuo piano settimanale torna esattamente come era, e la sequenza viene mantenuta così puoi avviare un nuovo giro più avanti.',+ 'Use Fixed Week': 'Usa Settimana fissa',+ 'No rotation yet — add routines to it in Plan.': 'Ancora nessuna rotazione — aggiungi routine nel Piano.',+ 'Set up in Plan': 'Configura nel Piano',+ 'Pass complete': 'Giro completato',+ 'Next pass starts {0}': 'Il prossimo giro inizia {0}',+}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 616d2d3e7..760bd609c 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1671,4 +1671,29 @@ export default {'Yellow': '노랑','Enter how long it took — at least 1 minute.': '걸린 시간을 입력하세요 — 최소 1분.','Coach week': '코치 주간',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': '로테이션',+ 'Fixed Week': '고정 주간',+ 'Scheduling': '일정 관리',+ 'Externally managed': '외부에서 관리됨',+ 'Position {0}': '순서 {0}',+ 'Add routine to the rotation': '로테이션에 루틴 추가',+ 'Add to the rotation': '로테이션에 추가',+ 'Build a rotation instead': '대신 로테이션 만들기',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': '아직 로테이션이 없어요. 훈련하고 싶은 순서대로 루틴을 추가하세요 — 아직 기록하지 않은 첫 번째 루틴이 계속 다음이 돼요.',+ 'Use this rotation': '이 로테이션 사용하기',+ 'Use this rotation?': '이 로테이션을 사용할까요?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': '이제부터 openGym이 이 대기열을 채우는 일을 맡아요 — 코치의 앱은 더 이상 여기에 쓰지 않아야 해요.',+ 'Start new pass': '새 패스 시작',+ 'Start pass': '패스 시작',+ 'This rotation could not be read — it may have been written by another device.': '이 로테이션을 읽을 수 없어요 — 다른 기기에서 작성했을 수 있어요.',+ 'Discard it': '삭제하기',+ 'Switch to Fixed Week?': '고정 주간으로 전환할까요?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': '로테이션이 멈추고 현재 패스는 삭제돼요. 주간 계획은 그대로 돌아오고, 순서는 저장되어 나중에 새 패스를 시작할 수 있어요.',+ 'Use Fixed Week': '고정 주간 사용',+ 'No rotation yet — add routines to it in Plan.': '아직 로테이션이 없어요 — 계획에서 루틴을 추가하세요.',+ 'Set up in Plan': '계획에서 설정',+ 'Pass complete': '패스 완료',+ 'Next pass starts {0}': '다음 패스는 {0}에 시작해요',+}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex f4b6447b1..20e725dc1 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1671,4 +1671,29 @@ export default {'Yellow': 'Żółty','Enter how long it took — at least 1 minute.': 'Wpisz, ile to trwało — co najmniej 1 minutę.','Coach week': 'Tydzień trenera',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Rotacja',+ 'Fixed Week': 'Stały tydzień',+ 'Scheduling': 'Harmonogram',+ 'Externally managed': 'Zarządzane zewnętrznie',+ 'Position {0}': 'Pozycja {0}',+ 'Add routine to the rotation': 'Dodaj plan do rotacji',+ 'Add to the rotation': 'Dodaj do rotacji',+ 'Build a rotation instead': 'Utwórz rotację zamiast tego',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Brak rotacji. Dodawaj plany w kolejności, w jakiej chcesz je trenować — pierwszy jeszcze niezarejestrowany zostaje następny.',+ 'Use this rotation': 'Użyj tej rotacji',+ 'Use this rotation?': 'Użyć tej rotacji?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'Od teraz openGym przejmie uzupełnianie tej kolejki — aplikacja trenera nie powinna już do niej zapisywać.',+ 'Start new pass': 'Rozpocznij nowe przejście',+ 'Start pass': 'Rozpocznij przejście',+ 'This rotation could not be read — it may have been written by another device.': 'Nie udało się odczytać tej rotacji — mogła zostać zapisana przez inne urządzenie.',+ 'Discard it': 'Odrzuć ją',+ 'Switch to Fixed Week?': 'Przełączyć na Stały tydzień?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'Rotacja zatrzymuje się, a jej bieżące przejście zostaje odrzucone. Twój plan tygodnia wraca dokładnie taki, jaki był, a kolejność zostaje zapisana, aby można było później rozpocząć nowe przejście.',+ 'Use Fixed Week': 'Użyj Stałego tygodnia',+ 'No rotation yet — add routines to it in Plan.': 'Brak rotacji — dodaj plany w Planie.',+ 'Set up in Plan': 'Skonfiguruj w Planie',+ 'Pass complete': 'Przejście ukończone',+ 'Next pass starts {0}': 'Następne przejście zaczyna się {0}',+}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex eeaf4a415..d1254231c 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1016,6 +1016,30 @@ export const PT_BR_OVERRIDES = {'Up next': 'Próximo','Later': 'Depois','Coach week': 'Semana do Coach',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Rotação',+ 'Fixed Week': 'Semana fixa',+ 'Scheduling': 'Agendamento',+ 'Externally managed': 'Gerenciada externamente',+ 'Position {0}': 'Posição {0}',+ 'Add routine to the rotation': 'Adicionar rotina à rotação',+ 'Add to the rotation': 'Adicionar à rotação',+ 'Build a rotation instead': 'Criar uma rotação em vez disso',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Ainda sem rotação. Adicione as rotinas na ordem em que quer treiná-las — a primeira que ainda não registrou continua sendo a próxima.',+ 'Use this rotation': 'Usar esta rotação',+ 'Use this rotation?': 'Usar esta rotação?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'A partir de agora, o openGym passa a preencher esta fila — o aplicativo do seu treinador não deve mais escrever nela.',+ 'Start new pass': 'Iniciar nova passagem',+ 'Start pass': 'Iniciar passagem',+ 'This rotation could not be read — it may have been written by another device.': 'Não foi possível ler esta rotação — ela pode ter sido escrita por outro dispositivo.',+ 'Discard it': 'Descartar',+ 'Switch to Fixed Week?': 'Mudar para Semana fixa?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'A rotação para e a passagem atual é descartada. Seu plano semanal volta exatamente como estava, e a sequência é salva para que você possa iniciar uma nova passagem mais tarde.',+ 'Use Fixed Week': 'Usar Semana fixa',+ 'No rotation yet — add routines to it in Plan.': 'Ainda sem rotação — adicione rotinas no Plano.',+ 'Set up in Plan': 'Configurar no Plano',+ 'Pass complete': 'Passagem concluída',+ 'Next pass starts {0}': 'A próxima passagem começa em {0}',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex ebb820ac2..2cb2ea4a9 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1671,4 +1671,29 @@ export default {'Yellow': 'Amarelo','Enter how long it took — at least 1 minute.': 'Indica quanto tempo demorou — pelo menos 1 minuto.','Coach week': 'Semana do treinador',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Rotação',+ 'Fixed Week': 'Semana fixa',+ 'Scheduling': 'Agendamento',+ 'Externally managed': 'Gerida externamente',+ 'Position {0}': 'Posição {0}',+ 'Add routine to the rotation': 'Adicionar rotina à rotação',+ 'Add to the rotation': 'Adicionar à rotação',+ 'Build a rotation instead': 'Criar uma rotação em vez disso',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Ainda sem rotação. Adiciona as rotinas pela ordem em que as queres treinar — a primeira que ainda não registaste continua a ser a seguinte.',+ 'Use this rotation': 'Usar esta rotação',+ 'Use this rotation?': 'Usar esta rotação?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'A partir de agora, a openGym passa a preencher esta fila — a app do teu treinador já não deve escrever nela.',+ 'Start new pass': 'Iniciar nova passagem',+ 'Start pass': 'Iniciar passagem',+ 'This rotation could not be read — it may have been written by another device.': 'Não foi possível ler esta rotação — pode ter sido escrita por outro dispositivo.',+ 'Discard it': 'Descartá-la',+ 'Switch to Fixed Week?': 'Mudar para Semana fixa?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'A rotação para e a passagem atual é descartada. O teu plano semanal volta exatamente como estava, e a sequência é guardada para poderes iniciar uma nova passagem mais tarde.',+ 'Use Fixed Week': 'Usar Semana fixa',+ 'No rotation yet — add routines to it in Plan.': 'Ainda sem rotação — adiciona rotinas no Plano.',+ 'Set up in Plan': 'Configurar no Plano',+ 'Pass complete': 'Passagem concluída',+ 'Next pass starts {0}': 'A próxima passagem começa a {0}',+}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex ef0fdea1b..7e4fd877f 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1671,4 +1671,29 @@ export default {'Yellow': 'Жёлтый','Enter how long it took — at least 1 minute.': 'Укажите, сколько это длилось — не меньше 1 минуты.','Coach week': 'Неделя тренера',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Ротация',+ 'Fixed Week': 'Фиксированная неделя',+ 'Scheduling': 'Расписание',+ 'Externally managed': 'Управляется извне',+ 'Position {0}': 'Позиция {0}',+ 'Add routine to the rotation': 'Добавить программу в ротацию',+ 'Add to the rotation': 'Добавить в ротацию',+ 'Build a rotation instead': 'Создать ротацию вместо этого',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Ротации пока нет. Добавляй программы в том порядке, в котором хочешь их тренировать — первая незалогированная всегда следующая.',+ 'Use this rotation': 'Использовать эту ротацию',+ 'Use this rotation?': 'Использовать эту ротацию?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'Теперь openGym сам будет пополнять эту очередь — приложению тренера больше не нужно в неё писать.',+ 'Start new pass': 'Начать новый проход',+ 'Start pass': 'Начать проход',+ 'This rotation could not be read — it may have been written by another device.': 'Не удалось прочитать эту ротацию — возможно, она была записана с другого устройства.',+ 'Discard it': 'Отменить её',+ 'Switch to Fixed Week?': 'Переключиться на фиксированную неделю?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'Ротация останавливается, и текущий проход отменяется. Твой недельный план возвращается точно таким, каким был, а последовательность сохраняется, чтобы позже начать новый проход.',+ 'Use Fixed Week': 'Использовать фиксированную неделю',+ 'No rotation yet — add routines to it in Plan.': 'Ротации пока нет — добавь программы в разделе «План».',+ 'Set up in Plan': 'Настроить в Плане',+ 'Pass complete': 'Проход завершён',+ 'Next pass starts {0}': 'Следующий проход начнётся {0}',+}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex ea4d36b4e..71ce966c3 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1682,4 +1682,29 @@ export default {'Yellow': 'เหลือง','Enter how long it took — at least 1 minute.': 'ใส่ระยะเวลาที่ใช้ — อย่างน้อย 1 นาที','Coach week': 'สัปดาห์ของโค้ช',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'การหมุนเวียน',+ 'Fixed Week': 'สัปดาห์คงที่',+ 'Scheduling': 'การจัดตาราง',+ 'Externally managed': 'จัดการจากภายนอก',+ 'Position {0}': 'ตำแหน่ง {0}',+ 'Add routine to the rotation': 'เพิ่มรูทีนเข้าการหมุนเวียน',+ 'Add to the rotation': 'เพิ่มเข้าการหมุนเวียน',+ 'Build a rotation instead': 'สร้างการหมุนเวียนแทน',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'ยังไม่มีการหมุนเวียน เพิ่มรูทีนตามลำดับที่ต้องการฝึก — รูทีนแรกที่ยังไม่ได้บันทึกจะเป็นรายการถัดไปเสมอ',+ 'Use this rotation': 'ใช้การหมุนเวียนนี้',+ 'Use this rotation?': 'ใช้การหมุนเวียนนี้?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'ต่อจากนี้ openGym จะเติมคิวนี้ให้เอง — แอปของโค้ชไม่ควรเขียนลงคิวนี้อีกต่อไป',+ 'Start new pass': 'เริ่มรอบใหม่',+ 'Start pass': 'เริ่มรอบ',+ 'This rotation could not be read — it may have been written by another device.': 'อ่านการหมุนเวียนนี้ไม่ได้ — อาจถูกเขียนจากอุปกรณ์อื่น',+ 'Discard it': 'ทิ้งไป',+ 'Switch to Fixed Week?': 'เปลี่ยนเป็นสัปดาห์คงที่?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'การหมุนเวียนจะหยุด และรอบปัจจุบันจะถูกยกเลิก แผนรายสัปดาห์ของคุณจะกลับมาเหมือนเดิมทุกประการ และลำดับจะถูกเก็บไว้เพื่อเริ่มรอบใหม่ได้ในภายหลัง',+ 'Use Fixed Week': 'ใช้สัปดาห์คงที่',+ 'No rotation yet — add routines to it in Plan.': 'ยังไม่มีการหมุนเวียน — เพิ่มรูทีนได้ในแผน',+ 'Set up in Plan': 'ตั้งค่าในแผน',+ 'Pass complete': 'รอบเสร็จสมบูรณ์',+ 'Next pass starts {0}': 'รอบถัดไปเริ่ม {0}',+}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 14400285c..25a5b6bf5 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1671,4 +1671,29 @@ export default {'Yellow': 'Sarı','Enter how long it took — at least 1 minute.': 'Ne kadar sürdüğünü gir — en az 1 dakika.','Coach week': 'Koç haftası',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': 'Rotasyon',+ 'Fixed Week': 'Sabit Hafta',+ 'Scheduling': 'Zamanlama',+ 'Externally managed': 'Harici olarak yönetiliyor',+ 'Position {0}': 'Sıra {0}',+ 'Add routine to the rotation': 'Rotasyona rutin ekle',+ 'Add to the rotation': 'Rotasyona ekle',+ 'Build a rotation instead': 'Bunun yerine bir rotasyon oluştur',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': 'Henüz rotasyon yok. Rutinleri antrenman yapmak istediğin sırayla ekle — henüz kaydetmediğin ilk rutin her zaman sıradaki olur.',+ 'Use this rotation': 'Bu rotasyonu kullan',+ 'Use this rotation?': 'Bu rotasyon kullanılsın mı?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': 'Bundan sonra bu kuyruğu doldurma işini openGym üstlenecek — koçunun uygulaması artık buraya yazmamalı.',+ 'Start new pass': 'Yeni tur başlat',+ 'Start pass': 'Tur başlat',+ 'This rotation could not be read — it may have been written by another device.': 'Bu rotasyon okunamadı — başka bir cihaz tarafından yazılmış olabilir.',+ 'Discard it': 'Sil',+ 'Switch to Fixed Week?': 'Sabit Haftaya geçilsin mi?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': 'Rotasyon durur ve mevcut turu silinir. Haftalık planın tam olarak eskisi gibi geri döner ve sıralama daha sonra yeni bir tur başlatabilmen için saklanır.',+ 'Use Fixed Week': 'Sabit Haftayı kullan',+ 'No rotation yet — add routines to it in Plan.': "Henüz rotasyon yok — Plan'da rutin ekle.",+ 'Set up in Plan': "Plan'da ayarla",+ 'Pass complete': 'Tur tamamlandı',+ 'Next pass starts {0}': 'Sıradaki tur {0} tarihinde başlıyor',+}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 69c1a6d0b..55c9f2d47 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1671,4 +1671,29 @@ export default {'Yellow': '黄色','Enter how long it took — at least 1 minute.': '请输入用时 — 至少 1 分钟。','Coach week': '教练周',+ // Rotation (lib/rotation.js) — an in-app alternative to the weekday plan.+ 'Rotation': '轮换',+ 'Fixed Week': '固定周',+ 'Scheduling': '排期',+ 'Externally managed': '由外部管理',+ 'Position {0}': '第 {0} 位',+ 'Add routine to the rotation': '将训练日添加到轮换',+ 'Add to the rotation': '添加到轮换',+ 'Build a rotation instead': '改为创建轮换',+ 'No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.': '还没有轮换。按你想训练的顺序添加训练日——尚未记录的第一个训练日将始终是下一个。',+ 'Use this rotation': '使用此轮换',+ 'Use this rotation?': '使用此轮换?',+ 'openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.': '从现在起,openGym 将接管这个队列的填充——教练的应用不应再写入它。',+ 'Start new pass': '开始新一轮',+ 'Start pass': '开始一轮',+ 'This rotation could not be read — it may have been written by another device.': '无法读取此轮换——可能是由另一台设备写入的。',+ 'Discard it': '丢弃它',+ 'Switch to Fixed Week?': '切换到固定周?',+ 'The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.': '轮换会停止,当前这一轮会被丢弃。你的每周计划会完全恢复原样,顺序会被保留,方便你以后重新开始新一轮。',+ 'Use Fixed Week': '使用固定周',+ 'No rotation yet — add routines to it in Plan.': '还没有轮换——在计划中添加训练日。',+ 'Set up in Plan': '在计划中设置',+ 'Pass complete': '本轮已完成',+ 'Next pass starts {0}': '下一轮从 {0} 开始',+}diff --git a/frontend/src/views/Home.jsx b/frontend/src/views/Home.jsxindex f4a26e484..496204207 100644--- a/frontend/src/views/Home.jsx+++ b/frontend/src/views/Home.jsx@@ -8,7 +8,8 @@ import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, starterimport LineChart from '../components/LineChart.jsx'import Icon from '../components/Icon.jsx'import QueueRow from '../components/QueueRow.jsx'-import { queueView, weekTally, pinState } from '../lib/queue.js'+import { queueOf, queueView, weekTally, pinState } from '../lib/queue.js'+import { scheduleModeOf } from '../lib/rotation.js'import { Button } from '../components/ui.jsx'import { tappable } from '../lib/use-sheet-keyboard.js'import { glyphOf } from '../lib/glyphs.js'@@ -31,8 +32,6 @@ export default function Home() {// An open editor on a saved workout (lib/session-edit.js) holds S.active too, but it is not a// session in progress: the row takes you back to it as an edit, the way the tab bar does.const editingSaved = !!S.active?.editingWorkoutId- // On a rest day, saying when you train next beats leaving the row as a full stop.- const next = !S.active && !todayRoutines.length ? nextTrainingDay(S, todayISO()) : nullconst bw = lastBW(S)const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length - 2] : nullconst delta = bw && prevBW ? bw.w - prevBW.w : null@@ -61,6 +60,22 @@ export default function Home() {// A coach week (S.queue) read through the same tolerant reader QueueRow uses, so a malformed// queue from another client shows the weekday dots, never an empty card.const queue = queueView(S, todayISO())+ // Rotation and the weekday strip are mutually exclusive here too, matching Settings/Plan: a+ // live queue, or Rotation chosen with nothing built yet (S.scheduleMode) — in which case there+ // is no queue for QueueRow to render, so an empty-state card takes its place instead.+ const rotating = scheduleModeOf(S) === 'rotation'+ // A planner-written queue (no rotationId) still names its weekday when it hasn't started yet —+ // that copy predates rotation and stays as it is. Our own rotation has no weekday of its own+ // (lib/rotation.js): naming one here — including on the pass's own one-day empty gap (THE+ // ONE-DAY BOUNDARY, rotation.js) or before a first routine is even added — would be the+ // fixed-week model leaking into a schedule that was never weekday-based.+ const liveQ = queueOf(S)+ const plannerQueue = !!queue && !liveQ?.rotationId+ // Ownership, not mere presence of a rotationId: a stale id left over from a rebuilt rotation+ // would otherwise still read as "this app manages it" (lib/rotation.js).+ const managedQueue = !!liveQ && !!S.rotation && liveQ.rotationId === S.rotation.id+ // On a rest day, saying when you train next beats leaving the row as a full stop.+ const next = !S.active && !todayRoutines.length && !(rotating && !plannerQueue) ? nextTrainingDay(S, todayISO()) : null// The streak card's fraction: this calendar week's workouts over the weekdays with a plan, or,// in a coach week, the queue's sessions and your own days together (lib/queue.js weekTally).const { done: doneThisWeek, planned: plannedPerWeek } = weekTally(S, todayISO())@@ -82,7 +97,10 @@ export default function Home() {{/* A coach week runs by order, not by weekday, so its progress row stands in for theseven dots (components/QueueRow.jsx). The today row below stays as it is: the queue'snext session reaches it through effectiveRoutineIds like any planned routine. */}- {queue ? <QueueRow S={S} today={todayISO()} onStart={onQueueStart} /> : <>+ {rotating ? (queue ? <QueueRow S={S} today={todayISO()} onStart={onQueueStart} managed={managedQueue} /> : <div className="empty">+ {t('No rotation yet — add routines to it in Plan.')}+ <div style={{ marginTop: 10 }}><Button size="sm" variant="tinted" onClick={() => nav('/plan')}>{t('Set up in Plan')}</Button></div>+ </div>) : <><div className="row between" style={{ marginBottom: 8 }}><button className="iconbtn" style={{ width: 30, height: 30, fontSize: 15 }} onClick={() => setWeekOffset(w => w - 1)} aria-label={t('Previous week')}><Icon name="chevronLeft" /></button><div className="small muted" style={{ fontWeight: 500 }}>{wkLabel}</div>diff --git a/frontend/src/views/Home.queue.test.jsx b/frontend/src/views/Home.queue.test.jsxindex 50ad29510..988894824 100644--- a/frontend/src/views/Home.queue.test.jsx+++ b/frontend/src/views/Home.queue.test.jsx@@ -48,7 +48,7 @@ afterEach(() => {})const setS = (over = {}) => useStore.setState(s => ({- S: { ...s.S, routines, week: {}, dayPlan: {}, workouts: [], active: null, queue: queue(), ...over }, user: null,+ S: { ...s.S, routines, week: {}, dayPlan: {}, workouts: [], active: null, queue: queue(), rotation: null, scheduleMode: null, ...over }, user: null,}))const mount = () => act(() => root.render(<Home />))const chips = () => [...host.querySelectorAll('.queue .chip')]@@ -108,6 +108,26 @@ describe('Home — coach week progress row', () => {expect(host.querySelector('.today-row .ss').textContent).toMatch(/^Next session: \w+, US W1 D1$/)})+ it('a rotation-managed queue never names a weekday on its empty gap — the row above already says what is next', () => {+ const startsOn = daysFromToday(2)+ setS({ queue: queue({ startsOn, rotationId: 'r1' }) })+ mount()+ expect(status()).toBe('Next week starts ' + fmtDate(startsOn, true))+ expect(todayTitle()).toBe('Rest day')+ expect(host.querySelector('.today-row .ss')).toBeNull()+ })++ it('Rotation chosen with nothing built yet hides the weekday strip and offers an empty state instead', () => {+ setS({ queue: null, rotation: null, scheduleMode: 'rotation', week: {} })+ mount()+ expect(host.querySelector('.week')).toBeNull()+ expect(host.querySelectorAll('.wday').length).toBe(0)+ expect(host.querySelector('.queue')).toBeNull()+ expect(host.textContent).toContain('No rotation yet')+ expect(todayTitle()).toBe('Rest day')+ expect(host.querySelector('.today-row .ss')).toBeNull()+ })+it('a complete week says so, every chip is inert, and the day goes back to the weekday plan', () => {setS({ workouts: [logged('d1'), logged('d2'), logged('d3')], week: { [new Date().getDay()]: ['own'] } })mount()@@ -117,6 +137,26 @@ describe('Home — coach week progress row', () => {expect(todayTitle()).toBe('Core')})+ it('a pass this app manages gets its own copy, not the coach-week wording', () => {+ setS({+ queue: queue({ rotationId: 'r1' }),+ rotation: { id: 'r1', sequence: ['d1', 'd2', 'd3'], label: 'US W1' },+ workouts: [logged('d1'), logged('d2'), logged('d3')],+ })+ mount()+ expect(status()).toBe('Pass complete')+ })++ it('a managed pass waiting on its startsOn says so without naming a coach week', () => {+ const startsOn = daysFromToday(2)+ setS({+ queue: queue({ startsOn, rotationId: 'r1' }),+ rotation: { id: 'r1', sequence: ['d1', 'd2', 'd3'], label: 'US W1' },+ })+ mount()+ expect(status()).toBe('Next pass starts ' + fmtDate(startsOn, true))+ })+it('own routines on the weekday ride along beside the queue session', () => {setS({ week: { [new Date().getDay()]: ['own'] } })mount()diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsxindex 5e49475d4..c69534812 100644--- a/frontend/src/views/Plan.jsx+++ b/frontend/src/views/Plan.jsx@@ -2,7 +2,7 @@ import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { DAYN, weekOrder, weekStartOf, uid, exCount, routineCount } from '../lib/format.js'import { t } from '../lib/i18n.js'-import { dayAssignSheet, dayAddRoutineSheet, starterPlanSheet, planToolsSheet, confirmSheet } from '../sheets.jsx'+import { dayAssignSheet, dayAddRoutineSheet, starterPlanSheet, planToolsSheet, confirmSheet, menuSheet } from '../sheets.jsx'import Icon from '../components/Icon.jsx'import { Button } from '../components/ui.jsx'import SwipeToDelete from '../components/SwipeToDelete.jsx'@@ -12,6 +12,8 @@ import { glyphOf, DEFAULT_GLYPH } from '../lib/glyphs.js'import { DEMO } from '../lib/demo.js'import { MOBILE } from '../lib/mobile.js'import { coachAvailable } from '../lib/coach.js'+import { queueOf } from '../lib/queue.js'+import { scheduleModeOf, queueRecovery, rotationIds, saveRotation, startNewPass, startPass } from '../lib/rotation.js'export default function Plan() {const nav = useNavigate()@@ -55,6 +57,46 @@ export default function Plan() {onConfirm: () => update(s => { deleteRoutine(s, r.id) })})+ /* The rotation editor. What it shows is the live pass when there is one, otherwise the saved+ sequence — S.rotation is only a definition, so the pass is the truth whenever it exists.+ Every edit writes straight through saveRotation: an edit IS the save (and, for a queue+ somebody else wrote, the adoption), so there is no half-edited state to lose. `since` and+ `startsOn` carry over, so progress already logged survives a reorder. */+ const liveQ = queueOf(S)+ const seq = liveQ?.ids ?? rotationIds(S)+ const seqLabel = liveQ?.label || S.rotation?.label || t('Rotation')+ // Ownership, not presence: a planner's queue has no rotationId, or one that does not match the+ // saved rotation here — that's what makes it someone else's to write, not this app's.+ const managed = !!liveQ && !!S.rotation && liveQ.rotationId === S.rotation.id+ const external = !!liveQ && !managed+ // The editor shows for any live queue — so "Use this rotation" stays reachable for a planner's+ // week — or once Rotation is chosen with nothing built yet (S.scheduleMode). The weekday grid+ // is hidden only for a pass this app actually manages: an external queue keeps both on screen,+ // since the weekday routines still ride alongside it (effectiveRoutineIds, history.js).+ const rotating = scheduleModeOf(S) === 'rotation' || queueRecovery(S)+ const hideGrid = managed || S.scheduleMode === 'rotation'+ const setSeq = ids => update(s => {+ // Emptying the sequence is how you leave the rotation from here: no pass, no definition, and+ // the weekday plan — untouched all along — is the schedule again.+ if (ids.length) saveRotation(s, ids, seqLabel)+ else { s.queue = null; s.rotation = null; s.scheduleMode = 'week' }+ })+ const moveInSeq = (i, d) => { const n = [...seq]; const [x] = n.splice(i, 1); n.splice(i + d, 0, x); setSeq(n) }+ const addToSeq = () => menuSheet({+ title: t('Add to the rotation'),+ items: S.routines.filter(r => !seq.includes(r.id)).map(r => ({+ icon: glyphOf(r.emoji), label: r.name, onClick: () => setSeq([...seq, r.id]),+ })),+ })+ // The only path from a coach-written queue into a managed one: behind a confirmation, since it+ // hands refilling over to this app from here on — the coach's app should not still be writing it.+ const adopt = () => confirmSheet({+ title: t('Use this rotation?'),+ message: t('openGym will take over refilling this queue from here on — the coach’s app should no longer write to it.'),+ confirmText: t('Use this rotation'),+ onConfirm: () => setSeq(seq),+ })+return <><div className="hdr"><div><h1>{t('Plan')}</h1><div className="sub">{t('Your weekly routine')}</div></div>@@ -70,37 +112,88 @@ export default function Plan() {</button>}<div className="cols"><div>- <h4 className="sec">{t('Week schedule')}</h4>- <div className="list" style={{ display: 'flex', flexDirection: 'column' }}>- {weekOrder(weekStartOf(S)).map(d => {- const dayRoutines = [].concat(S.week[d] || []).map(id => S.routines.find(x => x.id === id)).filter(Boolean)- // An empty day stays one tappable row → pick its first routine (today's behaviour).- if (!dayRoutines.length) return <div key={d} className="item" {...tappable(() => dayAssignSheet(d))}>- <div className="grow"><div className="tt">{t(DAYN[d])}</div></div>- <span className="tag">{t('Rest')}</span>- <Icon name="chevronRight" className="chev" /></div>- // A populated day: always-visible routine sub-rows + inline ✕. Adding a second routine- // is a small + in the day's header, centred over the ✕ column (#276): a full-width- // "+ Add routine" under every planned day made the week read as a list of buttons,- // when most people train one routine a day. The + keeps the option for those who don't.- return <div key={d} className="item" style={{ display: 'block', padding: '10px 14px' }}>- <div className="row between" style={{ marginBottom: 6 }}>- <div className="tt">{t(DAYN[d])}</div>- <div className="row" style={{ gap: 8 }}>- <div className="small dim">{routineCount(dayRoutines.length)}</div>- <button className="iconbtn sm" aria-label={t('Add routine')} title={t('Add routine')}- style={{ width: 30, height: 30, margin: '-5px 3px', fontSize: 15 }}- onClick={() => dayAddRoutineSheet(d)}><Icon name="plus" /></button>+ {/* Rotation (lib/rotation.js) shows for any live queue, so a coach's week can still be+ adopted from here — but only a pass this app manages hides the weekday grid below it;+ an external queue keeps both, editor above grid, since the weekday routines still ride+ alongside it (effectiveRoutineIds, history.js). */}+ {rotating && <div className="rotation">+ <h4 className="sec">{t('Rotation')}{external && <span className="tag" style={{ marginLeft: 8 }}>{t('Externally managed')}</span>}</h4>+ {queueRecovery(S) ? <div className="empty">+ {t('This rotation could not be read — it may have been written by another device.')}+ <div style={{ marginTop: 10 }}>+ <Button size="sm" variant="tinted" aria-label={t('Discard it')} onClick={() => update(s => { s.queue = null })}>{t('Discard it')}</Button>+ </div>+ </div> : <>+ {seq.length ? <div className="list" style={{ display: 'flex', flexDirection: 'column' }}>+ {seq.map((id, i) => {+ const r = S.routines.find(x => x.id === id)+ return <div key={id} className="item rotation-row">+ <span className="lrow-i"><Icon name={glyphOf(r?.emoji)} /></span>+ <div className="grow" style={{ minWidth: 0 }}>+ <div className="tt">{r?.name ?? id}</div><div className="ss">{t('Position {0}', i + 1)}</div>+ </div>+ {/* A coach's own queue is read-only here: the one way to change what it holds is+ to adopt it first ("Use this rotation" below), never a tap on one of its rows. */}+ {!external && <>+ <button className="iconbtn sm" aria-label={t('Move up')} title={t('Move up')} disabled={i === 0} onClick={() => moveInSeq(i, -1)}><Icon name="chevronUp" /></button>+ <button className="iconbtn sm" aria-label={t('Move down')} title={t('Move down')} disabled={i === seq.length - 1} onClick={() => moveInSeq(i, 1)}><Icon name="chevronDown" /></button>+ <button className="iconbtn sm" aria-label={t('Remove')} title={t('Remove')} onClick={() => setSeq(seq.filter(x => x !== id))}><Icon name="xmark" /></button>+ </>}</div>- </div>- {dayRoutines.map(r => <div key={r.id} className="row" style={{ gap: 8, padding: '4px 0 4px 8px' }}>- <span className="lrow-i" style={{ width: 26, height: 26, fontSize: 14 }}><Icon name={glyphOf(r.emoji)} /></span>- <div className="grow" style={{ minWidth: 0 }}><div className="tt" style={{ fontSize: 14 }}>{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>- <button className="iconbtn sm" aria-label={t('Remove')} onClick={() => removeFromDay(d, r.id)}><Icon name="xmark" /></button>- </div>)}+ })}+ </div> : <div className="empty">{t('No rotation yet. Add routines in the order you want to train them — the first one you have not logged stays next.')}</div>}+ <div className="row" style={{ gap: 8, marginTop: 8, flexWrap: 'wrap' }}>+ {!external && <Button size="sm" variant="tinted" icon="plus" aria-label={t('Add routine to the rotation')}+ disabled={S.routines.every(r => seq.includes(r.id))} onClick={addToSeq}>{t('Add routine')}</Button>}+ {external && <Button size="sm" variant="tinted" aria-label={t('Use this rotation')} onClick={adopt}>{t('Use this rotation')}</Button>}+ {!!liveQ && !external && <Button size="sm" aria-label={t('Start new pass')}+ onClick={() => update(s => startNewPass(s))}>{t('Start new pass')}</Button>}+ {!liveQ && !queueRecovery(S) && <Button size="sm" variant="tinted" aria-label={t('Cancel')} onClick={() => update(s => { s.scheduleMode = 'week' })}>{t('Cancel')}</Button>}</div>- })}- </div>+ </>}+ </div>}+ {!hideGrid && <>+ <h4 className="sec">{t('Week schedule')}</h4>+ <div className="list" style={{ display: 'flex', flexDirection: 'column' }}>+ {weekOrder(weekStartOf(S)).map(d => {+ const dayRoutines = [].concat(S.week[d] || []).map(id => S.routines.find(x => x.id === id)).filter(Boolean)+ // An empty day stays one tappable row → pick its first routine (today's behaviour).+ if (!dayRoutines.length) return <div key={d} className="item" {...tappable(() => dayAssignSheet(d))}>+ <div className="grow"><div className="tt">{t(DAYN[d])}</div></div>+ <span className="tag">{t('Rest')}</span>+ <Icon name="chevronRight" className="chev" /></div>+ // A populated day: always-visible routine sub-rows + inline ✕. Adding a second routine+ // is a small + in the day's header, centred over the ✕ column (#276): a full-width+ // "+ Add routine" under every planned day made the week read as a list of buttons,+ // when most people train one routine a day. The + keeps the option for those who don't.+ return <div key={d} className="item" style={{ display: 'block', padding: '10px 14px' }}>+ <div className="row between" style={{ marginBottom: 6 }}>+ <div className="tt">{t(DAYN[d])}</div>+ <div className="row" style={{ gap: 8 }}>+ <div className="small dim">{routineCount(dayRoutines.length)}</div>+ <button className="iconbtn sm" aria-label={t('Add routine')} title={t('Add routine')}+ style={{ width: 30, height: 30, margin: '-5px 3px', fontSize: 15 }}+ onClick={() => dayAddRoutineSheet(d)}><Icon name="plus" /></button>+ </div>+ </div>+ {dayRoutines.map(r => <div key={r.id} className="row" style={{ gap: 8, padding: '4px 0 4px 8px' }}>+ <span className="lrow-i" style={{ width: 26, height: 26, fontSize: 14 }}><Icon name={glyphOf(r.emoji)} /></span>+ <div className="grow" style={{ minWidth: 0 }}><div className="tt" style={{ fontSize: 14 }}>{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>+ <button className="iconbtn sm" aria-label={t('Remove')} onClick={() => removeFromDay(d, r.id)}><Icon name="xmark" /></button>+ </div>)}+ </div>+ })}+ </div>+ {/* Two dead ends land here with a saved sequence but no active pass — "Discard it" on a+ malformed queue, and Settings' "Use Fixed Week" (which keeps the sequence on purpose).+ "Build a rotation instead" only ever meant "start one from scratch", so it stays+ hidden once there is already a sequence to resume instead. */}+ {!liveQ && seq.length > 0+ ? <Button size="sm" variant="tinted" icon="shuffle" style={{ marginTop: 8 }}+ aria-label={t('Start pass')} onClick={() => update(s => startPass(s))}>{t('Start pass')}</Button>+ : !S.rotation && <Button size="sm" variant="tinted" icon="shuffle" style={{ marginTop: 8 }}+ aria-label={t('Build a rotation instead')} onClick={() => update(s => { s.scheduleMode = 'rotation' })}>{t('Build a rotation instead')}</Button>}+ </>}</div><div><div className="row between" style={{ marginTop: 22, marginBottom: 10 }}><h4 className="sec" style={{ margin: 0 }}>{t('Routines')}</h4>diff --git a/frontend/src/views/Plan.rotation.test.jsx b/frontend/src/views/Plan.rotation.test.jsxnew file mode 100644index 000000000..cb3f6c514--- /dev/null+++ b/frontend/src/views/Plan.rotation.test.jsx@@ -0,0 +1,167 @@+// @vitest-environment happy-dom+// Plan's rotation editor: one row per sequence position, add/remove/move writing straight through+// lib/rotation.js, adoption of an externally written queue, recovery for a malformed one, and the+// rotation editor and the weekday grid as two mutually exclusive views of the schedule.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++const mocks = vi.hoisted(() => {+ const state = { S: null }+ state.snapshot = () => ({+ S: state.S,+ update: mut => { const next = structuredClone(state.S); mut(next); state.S = next },+ config: {}, user: null, coachLocal: { mode: 'off' },+ })+ 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.fn() }))+vi.mock('../sheets.jsx', () => ({+ dayAssignSheet: vi.fn(), dayAddRoutineSheet: vi.fn(), starterPlanSheet: vi.fn(),+ planToolsSheet: vi.fn(), menuSheet: vi.fn(), confirmSheet: vi.fn(),+}))+vi.mock('../lib/mobile.js', () => ({ MOBILE: false }))+vi.mock('../lib/demo.js', () => ({ DEMO: false }))+vi.mock('../lib/coach.js', () => ({ coachAvailable: () => false }))++import Plan from './Plan.jsx'+import { menuSheet, confirmSheet } from '../sheets.jsx'+import { todayISO } from '../lib/format.js'++const routines = [+ { id: 'a', name: 'A', emoji: null, ex: [{ id: '0025' }] },+ { id: 'b', name: 'B', emoji: null, ex: [{ id: '0025' }] },+ { id: 'c', name: 'C', emoji: null, ex: [{ id: '0025' }] },+]+const live = (over = {}) => ({ ids: ['a', 'b'], since: Date.now() - 86400000, startsOn: todayISO(), label: 'My split', ...over })+const baseS = over => ({ routines, week: { 1: ['c'] }, dayPlan: {}, workouts: [], queue: null, rotation: null, scheduleMode: null, ...over })++let host, root+beforeEach(() => { host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host); menuSheet.mockClear(); confirmSheet.mockClear() })+afterEach(() => { act(() => root.unmount()); host.remove() })++const mount = over => { mocks.S = baseS(over); act(() => root.render(<Plan />)) }+const rows = () => [...host.querySelectorAll('.rotation-row')]+const names = () => rows().map(r => r.querySelector('.tt').textContent)+const click = el => act(() => el.dispatchEvent(new MouseEvent('click', { bubbles: true })))+const byLabel = label => [...host.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === label || b.textContent.trim() === label)++describe('Plan — the rotation editor', () => {+ it('lists the live pass in order, and hides the weekday grid for a managed pass', () => {+ mount({ queue: live({ rotationId: 'r1' }), rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })+ expect(names()).toEqual(['A', 'B'])+ expect(host.textContent).not.toContain('Week schedule')+ })++ it('nothing saved shows the weekday grid, with a button into the rotation editor', () => {+ mount()+ expect(host.textContent).toContain('Week schedule')+ expect(rows()).toEqual([])+ click(byLabel('Build a rotation instead'))+ expect(mocks.S.scheduleMode).toBe('rotation')+ // the mocked store is not reactive, so re-mount to see the persisted choice render+ mount({ scheduleMode: mocks.S.scheduleMode })+ expect(host.textContent).toContain('Rotation')+ expect(host.textContent).not.toContain('Week schedule')+ })++ it('Cancel gives the schedule back to the weekday plan', () => {+ mount({ scheduleMode: 'rotation' })+ expect(host.textContent).toContain('Rotation')+ click(byLabel('Cancel'))+ expect(mocks.S.scheduleMode).toBe('week')+ mount({ scheduleMode: mocks.S.scheduleMode })+ expect(host.textContent).toContain('Week schedule')+ expect(host.textContent).not.toContain('Rotation')+ })++ it('adding a routine offers only the ones not in the sequence, and saves the pass', () => {+ mount({ queue: live({ rotationId: 'r1' }), rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })+ click(byLabel('Add routine to the rotation'))+ const items = menuSheet.mock.calls[0][0].items+ expect(items.map(i => i.label)).toEqual(['C'])+ act(() => items[0].onClick())+ expect(mocks.S.queue.ids).toEqual(['a', 'b', 'c'])+ expect(mocks.S.rotation.sequence).toEqual(['a', 'b', 'c'])+ })++ it('move down reorders without restarting the pass', () => {+ const since = Date.now() - 86400000+ mount({ queue: live({ since, rotationId: 'r1' }), rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })+ click(rows()[0].querySelector('[aria-label="Move down"]'))+ expect(mocks.S.queue.ids).toEqual(['b', 'a'])+ expect(mocks.S.queue.since).toBe(since)+ })++ it('removing the last routine hands the schedule back to the weekday plan', () => {+ mount({ queue: live({ ids: ['a'], rotationId: 'r1' }), rotation: { id: 'r1', sequence: ['a'], label: 'My split' } })+ click(rows()[0].querySelector('[aria-label="Remove"]'))+ expect(mocks.S.queue).toBe(null)+ expect(mocks.S.rotation).toBe(null)+ expect(mocks.S.scheduleMode).toBe('week')+ expect(mocks.S.week).toEqual({ 1: ['c'] })+ })++ it('an externally written pass says so, keeps the weekday grid, and can be adopted behind a confirm', () => {+ mount({ queue: live() }) // no rotationId, no rotation+ expect(host.textContent).toContain('Externally managed')+ expect(host.textContent).toContain('Week schedule')+ click(byLabel('Use this rotation'))+ expect(mocks.S.rotation).toBe(null) // not adopted yet — waiting on the confirm+ act(() => confirmSheet.mock.calls.at(-1)[0].onConfirm())+ expect(mocks.S.rotation.sequence).toEqual(['a', 'b'])+ expect(mocks.S.queue.rotationId).toBe(mocks.S.rotation.id)+ // (the mocked store is not reactive, so re-mount to see the adopted pass render)+ mount({ queue: live({ rotationId: mocks.S.rotation.id }), rotation: mocks.S.rotation })+ expect(host.textContent).not.toContain('Externally managed')+ expect(host.textContent).not.toContain('Week schedule')+ })++ it('an external queue keeps its rows read-only — no button but the adoption one writes rotationId', () => {+ mount({ queue: live() }) // no rotationId, no rotation in state+ expect(host.textContent).toContain('Externally managed')+ expect(host.textContent).toContain('Week schedule')+ expect(rows()[0].querySelectorAll('button').length).toBe(0) // read-only: no per-row buttons at all+ expect(byLabel('Add routine to the rotation')).toBeUndefined()+ expect(byLabel('Move up')).toBeUndefined()+ expect(byLabel('Move down')).toBeUndefined()+ expect(mocks.S.queue.rotationId).toBeUndefined()+ click(byLabel('Use this rotation'))+ act(() => confirmSheet.mock.calls.at(-1)[0].onConfirm())+ expect(mocks.S.queue.rotationId).toBe(mocks.S.rotation.id)+ })++ it('Start new pass rewinds the current one', () => {+ mount({+ queue: live({ since: Date.now() - 5 * 86400000, startsOn: '2026-09-01', rotationId: 'r1' }),+ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' },+ })+ click(byLabel('Start new pass'))+ expect(mocks.S.queue.startsOn).toBe(todayISO())+ expect(mocks.S.queue.ids).toEqual(['a', 'b'])+ })++ it('a malformed queue offers recovery instead of an editor full of nothing', () => {+ mount({ queue: { ids: ['gone'], since: Date.now() } })+ expect(host.textContent).toContain('This rotation could not be read')+ click(byLabel('Discard it'))+ expect(mocks.S.queue).toBe(null)+ })++ it('a saved sequence with no live pass offers Start pass, not Build a rotation instead', () => {+ // The state "Discard it" or Settings' "Use Fixed Week" leave behind: a saved rotation, no queue.+ mount({ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })+ expect(host.textContent).toContain('Week schedule')+ expect(byLabel('Build a rotation instead')).toBeUndefined()+ click(byLabel('Start pass'))+ expect(mocks.S.queue.ids).toEqual(['a', 'b'])+ expect(mocks.S.queue.rotationId).toBe('r1')+ })+})diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex d04cc7246..333fbb054 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -9,6 +9,8 @@ import { ACCENTS, ACCENT_NAMES, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY,import { inventoryFor, ownsPlates } from '../lib/plates.js'import { effortOf } from '../lib/history.js'import { unlock, playOnSilentSupported, vibrateSupported } from '../lib/sound.js'+import { scheduleModeOf, queueRecovery, rotationIds, startPass } from '../lib/rotation.js'+import { queueOf } from '../lib/queue.js'import { api, webauthnOK, passkeyRegister, IS_ANDROID } from '../lib/api.js'import { pushSupported, enablePush, disablePush, sendTestPush, syncPushSubscription } from '../lib/push.js'import { wakeLockSupported } from '../lib/wakelock.js'@@ -53,6 +55,11 @@ export default function Settings() {const importRef = useRef(null)const wakeOK = wakeLockSupported()+ // A planner's own queue (no rotationId, or one that doesn't match the saved rotation here) is+ // not this app's to switch off or overwrite — the Scheduling row goes read-only for it.+ const liveQ = queueOf(S)+ const externalQ = !!liveQ && (!S.rotation || liveQ.rotationId !== S.rotation.id)+// Two honest choices on a unit switch (issue #22): convert the numbers, or keep them and only// change the label — the old behaviour, still right for someone who logged in lb all along// under a kg label. Closing the sheet leaves the unit as it was.@@ -68,6 +75,31 @@ export default function Settings() {})}+ // Fixed Week or Rotation. A live queue always wins (scheduleModeOf, lib/rotation.js) — a queue+ // written by a planner switches the app to Rotation on its own — but choosing Rotation with+ // nothing built yet has no queue to derive from, so S.scheduleMode is what keeps it selected+ // (and the weekday grid hidden, on both Home and Plan) until the first routine is added.+ // Fixed Week stops the pass but keeps the sequence for a later fresh pass.+ const setScheduleMode = v => {+ if (v === scheduleModeOf(S)) return+ if (v === 'week') {+ // A planner's own queue is never this app's to drop — this control is text-only while one+ // is live (below), but the guard stays here too rather than trust the render alone.+ confirmSheet({+ title: t('Switch to Fixed Week?'),+ message: t('The rotation stops and its current pass is dropped. Your weekday plan comes back exactly as it is, and the sequence is kept so you can start a new pass later.'),+ confirmText: t('Use Fixed Week'),+ onConfirm: () => update(s => { if (!externalQ) s.queue = null; s.scheduleMode = 'week' }),+ })+ return+ }+ update(s => { s.scheduleMode = 'rotation' })+ // A malformed queue is not a live pass: Plan's recovery is the honest answer, not a new pass+ // written over data another client may still fix.+ if (!queueRecovery(S) && rotationIds(S).length) update(s => { startPass(s) })+ else nav('/plan')+ }+// --- update check state ---const [updateInfo, setUpdateInfo] = useState(null) // { hasUpdate, latestVersion, apkUrl, hashUrl } | nullconst [android, setAndroid] = useState(false)@@ -335,6 +367,15 @@ export default function Settings() {{/* ---------- general ---------- */}<Section title={t('General')} footer={t('Switching the unit offers to convert every stored weight.')}>+ {/* Fixed Week (S.week) or Rotation (the live queue, lib/queue.js + lib/rotation.js).+ Derived from the queue, never stored. */}+ <Row icon="shuffle" iconTint="var(--green)" title={t('Scheduling')}>+ {externalQ+ ? <span className="small dim">{t('Rotation')} · {t('Externally managed')}</span>+ : <Segmented className="seg-inline"+ options={[{ value: 'week', label: t('Fixed Week') }, { value: 'rotation', label: t('Rotation') }]}+ value={scheduleModeOf(S)} onChange={setScheduleMode} />}+ </Row><SelectRowicon="globe" iconTint="var(--blue)" title={t('Language')}value={lang} onChange={v => update(s => { s.lang = v; s.langAuto = false })}diff --git a/frontend/src/views/Settings.schedule.test.jsx b/frontend/src/views/Settings.schedule.test.jsxnew file mode 100644index 000000000..299c7aef1--- /dev/null+++ b/frontend/src/views/Settings.schedule.test.jsx@@ -0,0 +1,140 @@+// @vitest-environment happy-dom+// Settings → Scheduling: the control's selection is DERIVED from the live queue (never stored),+// Fixed Week clears the pass after confirming and keeps the rotation, and Rotation+// either starts a pass from the saved sequence or sends you to Plan.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Settings from './Settings.jsx'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++const mocks = vi.hoisted(() => {+ const state = { S: null, nav: null }+ state.snapshot = () => ({+ S: state.S,+ user: null,+ update: mut => { const next = structuredClone(state.S); mut(next); state.S = next },+ replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),+ signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),+ })+ return state+})+vi.mock('../store/useStore.js', () => {+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()+ useStore.getState = mocks.snapshot+ return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }+})+vi.mock('../store/useUI.js', () => {+ const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })+ const useUI = selector => selector ? selector(snap()) : snap()+ useUI.getState = snap+ return { useUI }+})+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))+vi.mock('../lib/api.js', () => ({+ api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,+}))+vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))+vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))+vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))+vi.mock('../sheets.jsx', () => ({+ loadStarterPlan: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: vi.fn(),+}))+vi.mock('../lib/update.js', () => ({ checkForUpdate: vi.fn(), downloadAndInstall: vi.fn() }))++import { confirmSheet } from '../sheets.jsx'+import { todayISO } from '../lib/format.js'++const routines = [{ id: 'a', name: 'A', emoji: null, ex: [] }, { id: 'b', name: 'B', emoji: null, ex: [] }]+const baseS = over => ({+ unit: 'kg', lang: 'en', weekStart: 1, checkIn: true, theme: 'dark', accent: 'lime', restSec: 90,+ workoutView: 'cards', wc: {}, reminder: { on: false, time: '08:00', tz: null }, effort: null,+ routines, week: {}, dayPlan: {}, workouts: [], bodyweight: [], exWeights: {}, customEx: [],+ equipProfiles: [], activeEquipId: null, gymCards: [], favEx: [], exNotes: {}, barWeights: {},+ queue: null, rotation: null, scheduleMode: null, active: null, ...over,+})++let host, root+beforeEach(() => {+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)+ mocks.nav = vi.fn(); confirmSheet.mockClear()+})+afterEach(() => { act(() => root.unmount()); host.remove() })++const mount = over => { mocks.S = baseS(over); act(() => root.render(<Settings />)) }+// the two-option Segmented rendered by the Scheduling row+const seg = () => [...host.querySelectorAll('button')].filter(b => ['Fixed Week', 'Rotation'].includes(b.textContent))+const pick = label => act(() => seg().find(b => b.textContent === label).dispatchEvent(new MouseEvent('click', { bubbles: true })))+const selected = () => seg().find(b => b.className.includes('on'))?.textContent++describe('Settings — Scheduling', () => {+ it('selects Fixed Week without a usable queue, Rotation with one this app manages', () => {+ mount()+ expect(selected()).toBe('Fixed Week')+ mount({+ queue: { ids: ['a', 'b'], since: Date.now(), startsOn: todayISO(), label: 'Rotation', rotationId: 'r1' },+ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'Rotation' },+ })+ expect(selected()).toBe('Rotation')+ })++ it('a malformed queue selects Fixed Week, never Rotation', () => {+ mount({ queue: { ids: ['gone'], since: Date.now() } })+ expect(selected()).toBe('Fixed Week')+ })++ it('Rotation stays selected on S.scheduleMode alone, with no live queue at all', () => {+ mount({ scheduleMode: 'rotation' })+ expect(selected()).toBe('Rotation')+ })++ it('a planner-written queue makes Scheduling read-only text, not a control to flip', () => {+ // No rotationId, and no S.rotation to match it against — this app does not own the queue.+ mount({ queue: { ids: ['a', 'b'], since: Date.now(), startsOn: todayISO(), label: 'US W1' } })+ expect(seg()).toEqual([])+ expect(host.textContent).toContain('Externally managed')+ })++ it('Fixed Week asks first, then drops the pass and keeps the sequence', () => {+ mount({+ queue: { ids: ['a', 'b'], since: Date.now(), startsOn: todayISO(), label: 'Rotation', rotationId: 'r1' },+ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'Rotation' },+ week: { 1: ['a'] },+ })+ pick('Fixed Week')+ expect(mocks.S.queue).not.toBe(null) // nothing happens before the confirmation+ act(() => confirmSheet.mock.calls[0][0].onConfirm())+ expect(mocks.S.queue).toBe(null)+ expect(mocks.S.scheduleMode).toBe('week')+ expect(mocks.S.rotation.sequence).toEqual(['a', 'b'])+ expect(mocks.S.week).toEqual({ 1: ['a'] })+ })++ it('Rotation starts a fresh pass from the saved sequence', () => {+ mount({ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })+ pick('Rotation')+ expect(mocks.S.queue.ids).toEqual(['a', 'b'])+ expect(mocks.S.queue.rotationId).toBe('r1')+ expect(mocks.S.queue.startsOn).toBe(todayISO())+ expect(mocks.S.scheduleMode).toBe('rotation')+ expect(mocks.nav).not.toHaveBeenCalled()+ })++ it('Rotation with nothing saved sends you to Plan, but stays selected — a live queue is not the only signal', () => {+ mount()+ pick('Rotation')+ expect(mocks.S.queue).toBe(null)+ expect(mocks.S.scheduleMode).toBe('rotation')+ expect(mocks.nav).toHaveBeenCalledWith('/plan')+ })++ it('a malformed queue sends you to Plan instead of starting a pass over it', () => {+ mount({ queue: { ids: ['gone'], since: Date.now() }, rotation: { id: 'r1', sequence: ['a'], label: 'x' } })+ pick('Rotation')+ expect(mocks.S.queue.ids).toEqual(['gone']) // untouched: Plan does the recovery+ expect(mocks.nav).toHaveBeenCalledWith('/plan')+ })+})