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
Rest wheel: an iOS-style minutes and seconds picker for any duration up to 15:00
Duarte Santosd9803350bf10
diff --git a/frontend/src/components/DurationWheel.jsx b/frontend/src/components/DurationWheel.jsxnew file mode 100644index 000000000..4cfc861b8--- /dev/null+++ b/frontend/src/components/DurationWheel.jsx@@ -0,0 +1,245 @@+// An iOS-style duration picker: two scroll wheels, minutes and seconds, any value in [min, max].+//+// Each wheel is a plain scroller with CSS scroll snapping, so a flick keeps its native momentum+// on iPhone Safari and in the Android WebView, and a mouse wheel or a trackpad scrolls it on a+// desktop. Where it comes to rest is the value: a short pause in the scroll events (or the+// `scrollend` event, where there is one) reads the row under the highlight band and reports it.+// A value outside the range (15:30 on a 15:00 wheel, 0:03 on a 5-second minimum) is reported+// clamped and the wheel rolls back to it, the way the iOS timer does.+//+// Keyboard and screen readers get one spinbutton per wheel: arrows step by one, Page Up/Down by+// a bigger step, Home/End jump to the ends. Both carry the whole duration as aria-valuetext+// ("1 minute 30 seconds"), so either wheel tells you what is set.+//+// The wheels are laid out left to right in every language (minutes first, the way a duration is+// written in digits); the unit labels follow the page direction.+//+// <DurationWheel value={sec} onChange={setSec} max={900} off={t('Off')} />+// durationSheet({ title, value, max, off, onDone: sec => … }) // the sheet with a Done button+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'+import { t } from '../lib/i18n.js'+import { vibrate } from '../lib/sound.js'+import { useUI } from '../store/useUI.js'+import { REST_MAX, clampDuration, splitDuration, joinDuration, fmtDuration, durationText } from '../lib/duration.js'+import { Button } from './ui.jsx'++// One row of a wheel, in CSS px. Kept in step with --dw-item in index.css.+export const WHEEL_ITEM = 40+// How long the scroll events have to stop before the wheel counts as settled, where the browser+// has no `scrollend` (Safari before 18.x, older WebViews).+export const SETTLE_MS = 120++const pad2 = n => String(n).padStart(2, '0')++/**+ * One wheel. `index` is what the parent holds; `onPick(i)` is called when the wheel comes to+ * rest on another row. `nonce` re-syncs the wheel to `index` after a pick the parent clamped.+ */+export function WheelColumn({ count, index, onPick, label, unit, format = String, valueText, disabledAt, step = 10, nonce = 0 }) {+ const scroller = useRef(null)+ const live = useRef(index) // the row under the band right now+ const touching = useRef(false)+ const programmatic = useRef(false) // a scroll we started: no tick, no pick on the way+ const settleTimer = useRef(null)+ const frame = useRef(0)+ const mounted = useRef(false)+ const [shown, setShown] = useState(index)+ const latest = useRef({ index, onPick, count })+ latest.current = { index, onPick, count }++ const clampIdx = i => Math.max(0, Math.min(count - 1, i))+ const rowAt = el => clampIdx(Math.round(el.scrollTop / WHEEL_ITEM))++ // The rows near the band lean back like a drum: smaller and fainter the further they are.+ const paint = useCallback(() => {+ frame.current = 0+ const el = scroller.current+ if (!el) return+ const top = el.scrollTop+ const items = el.querySelectorAll('.dw-it')+ const first = Math.max(0, Math.floor(top / WHEEL_ITEM) - 3)+ const last = Math.min(items.length - 1, Math.ceil(top / WHEEL_ITEM) + 3)+ for (let i = first; i <= last; i++) {+ const d = (i * WHEEL_ITEM - top) / WHEEL_ITEM+ const a = Math.min(3, Math.abs(d))+ items[i].style.transform = `rotateX(${(-d * 20).toFixed(1)}deg) scale(${(1 - a * 0.07).toFixed(3)})`+ items[i].style.opacity = String(Math.max(0.15, 1 - a * 0.3))+ }+ }, [])++ const scrollToRow = useCallback((i, smooth) => {+ const el = scroller.current+ if (!el) return+ const top = i * WHEEL_ITEM+ if (Math.abs(el.scrollTop - top) < 1) return+ programmatic.current = true+ if (typeof el.scrollTo === 'function') el.scrollTo({ top, behavior: smooth ? 'smooth' : 'auto' })+ else el.scrollTop = top+ if (!smooth) programmatic.current = false+ }, [])++ const settle = useCallback(() => {+ clearTimeout(settleTimer.current)+ const el = scroller.current+ if (!el || touching.current) return+ const was = programmatic.current+ programmatic.current = false+ const i = rowAt(el)+ // Without snapping (an old engine), finish the job ourselves.+ if (Math.abs(el.scrollTop - i * WHEEL_ITEM) >= 1) scrollToRow(i, true)+ if (!was && i !== latest.current.index) latest.current.onPick(i)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [scrollToRow, count])++ // Start where the value is; follow it when it changes from outside (a key, a clamp).+ useLayoutEffect(() => {+ if (touching.current) return+ const el = scroller.current+ if (el && rowAt(el) !== index) scrollToRow(index, mounted.current)+ live.current = index+ setShown(index)+ mounted.current = true+ if (!frame.current) frame.current = requestAnimationFrame(paint)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [index, nonce])++ useEffect(() => {+ const el = scroller.current+ if (!el) return+ const onScroll = () => {+ const i = rowAt(el)+ if (i !== live.current) {+ live.current = i+ setShown(i)+ // the click of a detent, where the phone can give one (Android); iOS has no buzz for a page+ if (!programmatic.current) vibrate(4)+ }+ if (!frame.current) frame.current = requestAnimationFrame(paint)+ clearTimeout(settleTimer.current)+ settleTimer.current = setTimeout(settle, SETTLE_MS)+ }+ const onEnd = () => settle()+ const down = () => { touching.current = true; programmatic.current = false }+ const up = () => { touching.current = false; clearTimeout(settleTimer.current); settleTimer.current = setTimeout(settle, SETTLE_MS) }+ // A mouse wheel moves one row per notch; a trackpad's small deltas scroll natively.+ const onWheel = e => {+ if (e.ctrlKey) return+ const notch = e.deltaMode !== 0 || Math.abs(e.deltaY) >= 50+ if (!notch || !e.deltaY) return+ e.preventDefault()+ const next = clampIdx(live.current + Math.sign(e.deltaY))+ if (next === live.current) return+ programmatic.current = false+ if (typeof el.scrollTo === 'function') el.scrollTo({ top: next * WHEEL_ITEM, behavior: 'smooth' })+ else { el.scrollTop = next * WHEEL_ITEM; onScroll() }+ }+ el.addEventListener('scroll', onScroll, { passive: true })+ el.addEventListener('scrollend', onEnd)+ el.addEventListener('touchstart', down, { passive: true })+ el.addEventListener('touchend', up, { passive: true })+ el.addEventListener('touchcancel', up, { passive: true })+ el.addEventListener('wheel', onWheel, { passive: false })+ return () => {+ el.removeEventListener('scroll', onScroll)+ el.removeEventListener('scrollend', onEnd)+ el.removeEventListener('touchstart', down)+ el.removeEventListener('touchend', up)+ el.removeEventListener('touchcancel', up)+ el.removeEventListener('wheel', onWheel)+ clearTimeout(settleTimer.current)+ cancelAnimationFrame(frame.current)+ frame.current = 0+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [settle, paint])++ // Tapping a row above or below the band rolls it in, like on iOS; it counts once it settles.+ const tapRow = i => {+ const el = scroller.current+ if (!el || i === live.current) return+ programmatic.current = false+ if (typeof el.scrollTo === 'function') el.scrollTo({ top: i * WHEEL_ITEM, behavior: 'smooth' })+ else onPick(i)+ }++ const key = e => {+ const big = Math.max(1, step)+ const to = {+ ArrowUp: index + 1, ArrowDown: index - 1, PageUp: index + big, PageDown: index - big, Home: 0, End: count - 1,+ }[e.key]+ if (to === undefined) return+ e.preventDefault()+ const i = clampIdx(to)+ if (i !== index) onPick(i)+ }++ return (+ <div className="dw-col" role="spinbutton" tabIndex={0} aria-label={label}+ aria-valuenow={index} aria-valuemin={0} aria-valuemax={count - 1} aria-valuetext={valueText}+ onKeyDown={key}>+ <div className="dw-scroll" ref={scroller}>+ <div className="dw-pad" aria-hidden="true" />+ {Array.from({ length: count }, (_, i) => (+ <div key={i} aria-hidden="true"+ className={'dw-it' + (i === shown ? ' on' : '') + (disabledAt && disabledAt(i) ? ' out' : '')}+ onClick={() => tapRow(i)}>+ <span className="dw-n">{format(i)}</span>+ </div>+ ))}+ <div className="dw-pad" aria-hidden="true" />+ </div>+ {unit && <span className="dw-unit" aria-hidden="true">{unit}</span>}+ </div>+ )+}++/**+ * Minutes and seconds wheels for a duration in seconds. `onChange(sec)` gets every value the+ * wheels come to rest on, already clamped to [min, max]. `off` names 0 for a screen reader+ * ("Off" for the rest timer); without it 0 reads as "0 seconds".+ */+export default function DurationWheel({ value, onChange, min = 0, max = REST_MAX, off = null, className = '' }) {+ const v = clampDuration(value, min, max)+ const { m, s } = splitDuration(v)+ const maxM = Math.floor(max / 60)+ const [nonce, setNonce] = useState(0)+ const live = useRef({ m, s })+ live.current = { m, s }+ const pick = (mm, ss) => {+ const next = joinDuration(mm, ss, min, max)+ setNonce(n => n + 1) // the wheels go back to what was kept, if it was clamped+ if (next !== v) onChange(next)+ }+ const text = durationText(v, { off })+ return (+ <div className={'dw ' + className} data-nodrag="" dir="ltr">+ <span className="dw-band" aria-hidden="true" />+ <WheelColumn count={maxM + 1} index={m} nonce={nonce} step={5}+ onPick={i => pick(i, live.current.s)} label={t('Minutes')} unit={t('min')} valueText={text}+ disabledAt={i => i * 60 > max || (i + 1) * 60 - 1 < min} />+ <WheelColumn count={60} index={s} nonce={nonce} step={10} format={pad2}+ onPick={i => pick(live.current.m, i)} label={t('Seconds')} unit={t('sec')} valueText={text}+ disabledAt={i => m * 60 + i > max || m * 60 + i < min} />+ </div>+ )+}++/* A sheet with the wheel, a read-out of what is set and Done. Nothing is saved until Done:+ closing the sheet any other way leaves the setting as it was. */+function DurationSheet({ title, value, min, max, off, footer, onDone, close }) {+ const [v, setV] = useState(clampDuration(value, min, max))+ return <>+ <h3>{title}</h3>+ <div className="dw-read" aria-hidden="true">{fmtDuration(v, { off })}</div>+ <DurationWheel value={v} onChange={setV} min={min} max={max} off={off} />+ {footer && <p className="dim small dw-foot">{footer}</p>}+ <Button variant="primary" onClick={() => { close(); onDone(v) }}>{t('Done')}</Button>+ <div style={{ height: 8 }} />+ </>+}++/** Opens the wheel in a bottom sheet; `onDone(sec)` runs on Done with the clamped value. */+export function durationSheet({ title, value, min = 0, max = REST_MAX, off = null, footer = null, onDone }) {+ return useUI.getState().openSheet(close =>+ <DurationSheet title={title} value={value} min={min} max={max} off={off} footer={footer} onDone={onDone} close={close} />)+}diff --git a/frontend/src/components/DurationWheel.test.jsx b/frontend/src/components/DurationWheel.test.jsxnew file mode 100644index 000000000..677300966--- /dev/null+++ b/frontend/src/components/DurationWheel.test.jsx@@ -0,0 +1,153 @@+// @vitest-environment happy-dom+import React, { act, useState } 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(() => ({ sheets: [], vibrate: vi.fn() }))+vi.mock('../store/useUI.js', () => {+ const snap = () => ({ openSheet: render => { mocks.sheets.push(render); return { close: vi.fn() } } })+ const useUI = selector => selector ? selector(snap()) : snap()+ useUI.getState = snap+ return { useUI }+})+vi.mock('../lib/sound.js', () => ({ vibrate: (...a) => mocks.vibrate(...a) }))++import DurationWheel, { durationSheet, WHEEL_ITEM, SETTLE_MS } from './DurationWheel.jsx'++let host, root+beforeEach(() => {+ mocks.sheets = []+ mocks.vibrate.mockClear()+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+ vi.useRealTimers()+})++// A controlled wheel, the way Settings and the workout use it.+function Harness({ start, onChange, ...rest }) {+ const [v, setV] = useState(start)+ return <DurationWheel value={v} onChange={x => { setV(x); onChange(x) }} {...rest} />+}+const mount = (props) => {+ const onChange = vi.fn()+ act(() => root.render(<Harness onChange={onChange} {...props} />))+ const [min, sec] = host.querySelectorAll('[role="spinbutton"]')+ return { onChange, min, sec }+}+const key = (el, k) => act(() => { el.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true })) })++describe('DurationWheel', () => {+ it('is two spinbuttons, minutes and seconds, each telling the whole duration', () => {+ const { min, sec } = mount({ start: 105 })+ expect(min.getAttribute('aria-label')).toBe('Minutes')+ expect(sec.getAttribute('aria-label')).toBe('Seconds')+ expect(min.getAttribute('aria-valuenow')).toBe('1')+ expect(sec.getAttribute('aria-valuenow')).toBe('45')+ expect(min.getAttribute('aria-valuemax')).toBe('15')+ expect(sec.getAttribute('aria-valuemax')).toBe('59')+ expect(min.getAttribute('aria-valuetext')).toBe('1 minute 45 seconds')+ expect(sec.getAttribute('aria-valuetext')).toBe('1 minute 45 seconds')+ expect(min.tabIndex).toBe(0)+ // the selected rows are marked for the eye; the rows themselves are hidden from screen readers+ expect(min.querySelector('.dw-it.on').textContent).toBe('1')+ expect(sec.querySelector('.dw-it.on').textContent).toBe('45')+ expect(sec.querySelector('.dw-it').getAttribute('aria-hidden')).toBe('true')+ })++ it('names 0 with the "off" label when it means no timer', () => {+ const { min } = mount({ start: 0, off: 'Off' })+ expect(min.getAttribute('aria-valuetext')).toBe('Off')+ })++ it('steps with the arrows, jumps with Page Up/Down and Home/End', () => {+ const { onChange, min, sec } = mount({ start: 90 })+ key(sec, 'ArrowUp')+ expect(onChange).toHaveBeenLastCalledWith(91)+ key(sec, 'ArrowDown'); key(sec, 'ArrowDown')+ expect(onChange).toHaveBeenLastCalledWith(89)+ key(sec, 'PageUp')+ expect(onChange).toHaveBeenLastCalledWith(99)+ key(min, 'PageUp')+ expect(onChange).toHaveBeenLastCalledWith(6 * 60 + 39)+ key(min, 'Home')+ expect(onChange).toHaveBeenLastCalledWith(39)+ key(min, 'End')+ expect(onChange).toHaveBeenLastCalledWith(900) // 15:39 is past the end: 15:00+ })++ it('keeps any value in range: 15:00 is the most, a rest-pause wheel stops at 5 s and 5:00', () => {+ const { onChange, sec } = mount({ start: 900 })+ key(sec, 'ArrowUp') // 15:01 → still 15:00, nothing to report+ expect(onChange).not.toHaveBeenCalled()+ act(() => root.unmount()); root = createRoot(host)+ const b = mount({ start: 10, min: 5, max: 300 })+ expect(b.min.getAttribute('aria-valuemax')).toBe('5')+ key(b.sec, 'PageDown')+ expect(b.onChange).toHaveBeenLastCalledWith(5)+ key(b.min, 'End')+ expect(b.onChange).toHaveBeenLastCalledWith(300)+ })++ it('dims the rows a wheel cannot land on', () => {+ const { sec } = mount({ start: 900 })+ const rows = sec.querySelectorAll('.dw-it')+ expect(rows[0].classList.contains('out')).toBe(false)+ expect(rows[1].classList.contains('out')).toBe(true)+ })++ it('reports where a scroll comes to rest, after the scroll events stop, and ticks on the way', () => {+ vi.useFakeTimers()+ const { onChange, sec } = mount({ start: 60 })+ const scroller = sec.querySelector('.dw-scroll')+ act(() => {+ scroller.dispatchEvent(new Event('touchstart'))+ scroller.scrollTop = 30 * WHEEL_ITEM+ scroller.dispatchEvent(new Event('scroll'))+ })+ expect(mocks.vibrate).toHaveBeenCalledTimes(1)+ // still under the finger: nothing is picked yet+ act(() => { vi.advanceTimersByTime(SETTLE_MS + 10) })+ expect(onChange).not.toHaveBeenCalled()+ act(() => { scroller.dispatchEvent(new Event('touchend')); vi.advanceTimersByTime(SETTLE_MS + 10) })+ expect(onChange).toHaveBeenLastCalledWith(90)+ expect(sec.getAttribute('aria-valuetext')).toBe('1 minute 30 seconds')+ })++ it('lays its wheels out left to right in every language and keeps the sheet from swiping on it', () => {+ mount({ start: 90 })+ const dw = host.querySelector('.dw')+ expect(dw.getAttribute('dir')).toBe('ltr')+ expect(dw.hasAttribute('data-nodrag')).toBe(true)+ })+})++describe('durationSheet', () => {+ it('opens the wheel with a read-out, and Done hands back the value', () => {+ const onDone = vi.fn()+ durationSheet({ title: 'Rest timer', value: 105, off: 'Off', footer: 'Scroll to 0:00 to turn the rest timer off.', onDone })+ expect(mocks.sheets).toHaveLength(1)+ const close = vi.fn()+ act(() => root.render(mocks.sheets[0](close)))+ expect(host.querySelector('h3').textContent).toBe('Rest timer')+ expect(host.querySelector('.dw-read').textContent).toBe('1:45')+ const sec = host.querySelectorAll('[role="spinbutton"]')[1]+ key(sec, 'ArrowUp')+ expect(host.querySelector('.dw-read').textContent).toBe('1:46')+ act(() => { [...host.querySelectorAll('button')].find(b => b.textContent === 'Done').click() })+ expect(close).toHaveBeenCalled()+ expect(onDone).toHaveBeenCalledWith(106)+ })++ it('reads 0 as Off', () => {+ durationSheet({ title: 'Rest timer', value: 0, off: 'Off', onDone: vi.fn() })+ act(() => root.render(mocks.sheets[0](vi.fn())))+ expect(host.querySelector('.dw-read').textContent).toBe('Off')+ })+})diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 6efe40355..a2765128d 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -1751,6 +1751,59 @@ body.chips-dragging *{cursor:inherit}.coach-cta-t span{font-size:13px;color:var(--label-2);line-height:1.35}.coach-cta-chev{color:var(--acc);font-size:15px;flex:none}+/* ------------------------------------------------- duration wheel picker -- */+/* components/DurationWheel.jsx: two scroll-snap wheels under one highlight band. --dw-item is+ WHEEL_ITEM there. The band sits behind the rows; the rows fade and lean back toward the edges+ (painted from JS while scrolling), and the mask softens the top and bottom rows further. */+.dw{--dw-item:40px;position:relative;display:flex;justify-content:center;height:calc(var(--dw-item) * 5);+ margin:4px auto 16px;max-width:320px;user-select:none;-webkit-user-select:none;touch-action:pan-y}+.dw-band{position:absolute;inset-inline:6px;top:calc(var(--dw-item) * 2);height:var(--dw-item);border-radius:10px;+ background:color-mix(in srgb,var(--label) 10%,transparent);pointer-events:none}+.dw-col{position:relative;flex:1;min-width:0;outline:none;border-radius:10px}+.dw-col:focus-visible::after{content:'';position:absolute;inset-inline:8px;top:calc(var(--dw-item) * 2);height:var(--dw-item);+ border-radius:10px;box-shadow:0 0 0 2px var(--acc);pointer-events:none}+.dw-scroll{height:100%;overflow-y:scroll;overflow-x:hidden;scroll-snap-type:y mandatory;overscroll-behavior:contain;+ -webkit-overflow-scrolling:touch;scrollbar-width:none;perspective:420px;+ -webkit-mask-image:linear-gradient(to bottom,transparent 0,#000 34%,#000 66%,transparent 100%);+ mask-image:linear-gradient(to bottom,transparent 0,#000 34%,#000 66%,transparent 100%)}+.dw-scroll::-webkit-scrollbar{display:none}+.dw-pad{height:calc(var(--dw-item) * 2)}+.dw-it{height:var(--dw-item);scroll-snap-align:center;display:flex;align-items:center;justify-content:flex-end;+ padding-inline-end:calc(50% + 2px);font-size:22px;font-variant-numeric:tabular-nums;color:var(--label-2);+ cursor:pointer;transform-origin:50% 50%;will-change:transform,opacity}+.dw-it.on{color:var(--label);font-weight:600}+.dw-it.out{color:var(--label-4)}+.dw-unit{position:absolute;top:calc(var(--dw-item) * 2);height:var(--dw-item);display:flex;align-items:center;+ inset-inline-start:calc(50% + 8px);font-size:17px;font-weight:600;color:var(--label);pointer-events:none}+.dw-read{text-align:center;font-size:34px;font-weight:700;letter-spacing:-.02em;font-variant-numeric:tabular-nums;margin:-4px 0 2px}+.dw-foot{text-align:center;margin:-6px 0 14px;line-height:1.4}+@media (hover:hover){.dw-it:hover{color:var(--label)}}++/* ------------------------------------------------------- Settings (v1.3.11) -- */+/* A sub-page's nav bar: the back button names where it goes, the title sits in the middle. */+.sp-nav{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,max-content) minmax(0,1fr);align-items:center;column-gap:6px;+ min-height:44px;margin:4px -6px 10px}+.sp-back{display:inline-flex;align-items:center;gap:2px;color:var(--acc);font-size:17px;padding:6px;border-radius:10px;+ min-width:0;max-width:100%;justify-self:start}+.sp-back span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.sp-back .icn{font-size:22px;--icon-stroke:2.2;flex:none}+.sp-title{text-align:center;font-weight:600;font-size:17px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:0}+.sp-root-title{font-size:34px;line-height:1.06;font-weight:700;letter-spacing:-.028em;margin:2px 0 10px}+@media (max-width:420px){.sp-root-title{font-size:30px}}+.sp-search{margin-bottom:18px}+/* the account card on top of the root: a big round avatar, the name, one line under it */+.lrow.sp-acct{padding-block:12px;gap:14px}+.sp-avatar{width:56px;height:56px;border-radius:50%;flex:none;display:grid;place-items:center;font-size:30px;+ background:linear-gradient(160deg,var(--surface-3),var(--surface-2));color:var(--label-2)}+.sp-acct .lrow-t{font-size:19px;font-weight:600}+.sp-avatar.on{background:var(--acc-soft);color:var(--acc);font-size:24px;font-weight:700}+.sp-version{text-align:center;margin-top:4px;line-height:1.6}+.lrow.dis .lrow-i,.lrow.dis .lrow-t,.lrow.dis .sw{opacity:.45}+/* a row a search result jumped to: a short accent wash that fades out */+.lrow.sp-flash{animation:spflash 1.8s ease}+@keyframes spflash{0%,45%{background:var(--acc-soft)}100%{background:transparent}}+.sp-empty{color:var(--label-2);text-align:center;padding:28px 12px;line-height:1.4}+/* ----------------------------------------------------------- RTL (Arabic) -- *//* Directional icons flip: back chevrons point right, trailing chevrons point left. */[dir="rtl"] [data-icon="chevronLeft"],diff --git a/frontend/src/lib/duration.js b/frontend/src/lib/duration.jsnew file mode 100644index 000000000..b04b2b66c--- /dev/null+++ b/frontend/src/lib/duration.js@@ -0,0 +1,55 @@+// Durations in whole seconds, as the rest timer stores them (S.restSec, S.restPauseSec, an+// exercise's target.restSec). The scroll-wheel picker (components/DurationWheel.jsx) reads and+// writes them as minutes + seconds, and every place that shows one goes through fmtDuration, so+// a value off the old 60/90/120/150/180 list ("1:45") reads the same everywhere.+import { t, tn } from './i18n.js'++// The rest timer's range: 0 is "no rest timer", 15 minutes the most a wheel offers.+export const REST_MAX = 15 * 60+// A rest-pause burst's rest: never 0 (lib/history.js clamps it to 5 s), five minutes at most.+export const REST_PAUSE_MIN = 5+export const REST_PAUSE_MAX = 5 * 60++/** Whole seconds within [min, max]. Anything that is not a number reads as `min`. */+export function clampDuration(sec, min = 0, max = REST_MAX) {+ const n = Math.round(Number(sec))+ if (!Number.isFinite(n)) return min+ return Math.min(max, Math.max(min, n))+}++/** { m, s } for a number of seconds: 90 → { m: 1, s: 30 }. */+export function splitDuration(sec) {+ const n = Math.max(0, Math.round(Number(sec)) || 0)+ return { m: Math.floor(n / 60), s: n % 60 }+}++/** Minutes and seconds back into seconds, clamped to the wheel's range. */+export function joinDuration(m, s, min = 0, max = REST_MAX) {+ return clampDuration((Number(m) || 0) * 60 + (Number(s) || 0), min, max)+}++/**+ * The short form a row shows: "45s" under a minute, "1:30" from a minute up, "Off" for 0 when+ * the caller says 0 means off. Digits stay Western, like the rest of the app's numbers.+ */+export function fmtDuration(sec, { off = null } = {}) {+ const n = Math.max(0, Math.round(Number(sec)) || 0)+ if (!n && off != null) return off+ if (n < 60) return n + 's'+ const { m, s } = splitDuration(n)+ return m + ':' + String(s).padStart(2, '0')+}++/**+ * What a screen reader says: "1 minute 30 seconds", "45 seconds", "2 minutes". 0 is `off` when+ * given (the rest timer's "Off"), "0 seconds" otherwise.+ */+export function durationText(sec, { off = null } = {}) {+ const { m, s } = splitDuration(sec)+ if (!m && !s) return off != null ? off : tn('{0} second', '{0} seconds', 0)+ return [m ? tn('{0} minute', '{0} minutes', m) : null, s ? tn('{0} second', '{0} seconds', s) : null]+ .filter(Boolean).join(' ')+}++/** The rest timer's own wording for a row or a preview: "1:30" or "Off". */+export const fmtRest = sec => fmtDuration(sec, { off: t('Off') })diff --git a/frontend/src/lib/duration.test.js b/frontend/src/lib/duration.test.jsnew file mode 100644index 000000000..1cd6ced5b--- /dev/null+++ b/frontend/src/lib/duration.test.js@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest'+import { REST_MAX, REST_PAUSE_MIN, REST_PAUSE_MAX, clampDuration, splitDuration, joinDuration, fmtDuration, durationText, fmtRest } from './duration.js'++describe('durations for the rest wheels', () => {+ it('has the ranges the wheels offer: rest 0 to 15:00, a rest-pause burst 5 s to 5:00', () => {+ expect(REST_MAX).toBe(900)+ expect([REST_PAUSE_MIN, REST_PAUSE_MAX]).toEqual([5, 300])+ })++ it('clamps to whole seconds in range, and reads junk as the minimum', () => {+ expect(clampDuration(105)).toBe(105)+ expect(clampDuration(1000)).toBe(900)+ expect(clampDuration(-4)).toBe(0)+ expect(clampDuration(89.6)).toBe(90)+ expect(clampDuration('75')).toBe(75)+ expect(clampDuration(undefined)).toBe(0)+ expect(clampDuration(null, 5, 300)).toBe(5)+ expect(clampDuration(2, 5, 300)).toBe(5)+ })++ it('splits and joins minutes and seconds, joining clamped', () => {+ expect(splitDuration(105)).toEqual({ m: 1, s: 45 })+ expect(splitDuration(0)).toEqual({ m: 0, s: 0 })+ expect(splitDuration(900)).toEqual({ m: 15, s: 0 })+ expect(joinDuration(2, 15)).toBe(135)+ expect(joinDuration(15, 30)).toBe(900) // 15:30 on a 15:00 wheel+ expect(joinDuration(0, 3, 5, 300)).toBe(5) // under the burst minimum+ expect(joinDuration(6, 0, 5, 300)).toBe(300)+ })++ it('formats any value, not only the old 60/90/120/150/180 list', () => {+ expect(fmtDuration(45)).toBe('45s')+ expect(fmtDuration(60)).toBe('1:00')+ expect(fmtDuration(105)).toBe('1:45')+ expect(fmtDuration(605)).toBe('10:05')+ expect(fmtDuration(0)).toBe('0s')+ expect(fmtDuration(0, { off: 'Off' })).toBe('Off')+ expect(fmtRest(0)).toBe('Off')+ expect(fmtRest(undefined)).toBe('Off')+ expect(fmtRest(135)).toBe('2:15')+ })++ it('reads out a duration for a screen reader', () => {+ expect(durationText(90)).toBe('1 minute 30 seconds')+ expect(durationText(61)).toBe('1 minute 1 second')+ expect(durationText(120)).toBe('2 minutes')+ expect(durationText(45)).toBe('45 seconds')+ expect(durationText(0)).toBe('0 seconds')+ expect(durationText(0, { off: 'Off' })).toBe('Off')+ })+})