From 9f4b2f59a0172e624dd656d8911f46ebac9b2adb Mon Sep 17 00:00:00 2001 From: ehonis Date: Sun, 8 Nov 2026 12:12:16 -0500 Subject: [PATCH] The runner: one controller for web and phone, pinned by tests first (#98) Published from the private repository by oss-sync. - The runner: one controller for web and phone, pinned by tests first (#98) 16 files changed, 1867 insertions(+), 662 deletions(-) --- .gitignore | 7 + AGENTS.md | 2 +- app/native.test.js | 91 +++++++ app/package.json | 3 + app/runflow.test.js | 267 +++++++++++++++++++ app/runner.dom.test.jsx | 438 ++++++++++++++++++++++++++++++++ app/src/lib/runflow.js | 427 +++++++++++++++++++++++++++++++ app/src/runner.jsx | 395 ++++++---------------------- mobile/AGENTS.md | 7 + mobile/src/features/planner.tsx | 3 +- mobile/src/features/runner.tsx | 408 ++++++----------------------- mobile/src/lib/runflow.js | 427 +++++++++++++++++++++++++++++++ mobile/src/ui/KeyboardBar.tsx | 6 +- mobile/src/ui/Sheet.tsx | 7 +- mobile/src/ui/sheetPolicy.ts | 39 +++ scripts/test.mjs | 2 +- 16 files changed, 1867 insertions(+), 662 deletions(-) create mode 100644 app/native.test.js create mode 100644 app/runflow.test.js create mode 100644 app/runner.dom.test.jsx create mode 100644 app/src/lib/runflow.js create mode 100644 mobile/src/lib/runflow.js create mode 100644 mobile/src/ui/sheetPolicy.ts diff --git a/.gitignore b/.gitignore index 3c776ed..84583d3 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,13 @@ app/.planflowtest.mjs app/.editingtest.mjs app/.editingdomtest.mjs app/.blockmenudomtest.mjs +app/.runnerdomtest.mjs +app/.nativetest.mjs +# Every bundled test the suites write (esbuild --outfile), wherever a suite puts it. +app/.*test.mjs +app/smoke/.*test.mjs +app/.*domtest.mjs +app/smoke/.*domtest.mjs # Your actual training log and its snapshots. Runtime state, not source: # it changes on every session and would be pure merge noise. Back it up with diff --git a/AGENTS.md b/AGENTS.md index 5b7849e..1213376 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -96,7 +96,7 @@ reasons behind the design, and the things that have been removed on purpose. | Naming | `app/src/lib/naming.js` | `nameFor`, `titleFor`, `out.title`, quick-name chips. | | Grades | `app/src/lib/grades.js` | The only grade scales in the app. | | Prescriptions | `app/src/lib/prescription.js` | The model under planning and the runner. Pure; `now` is an argument. | -| Runner | `app/src/runner.jsx` | Set-by-set screen for a planned session. One writer. | +| Runner | `app/src/runner.jsx`, `app/src/lib/runflow.js` | Set-by-set screen for a planned session. One writer. Its state and every tap's write are `useRunner` and the `*Tap` functions in `lib/runflow.js` (#98), shared with the phone; each platform's `WorkoutRunner` is its screens and its own sounds (`feedback`). Tested as data by `app/runflow.test.js` and tap by tap in a real DOM by `app/runner.dom.test.jsx`. | | Workout mode | `app/src/workout.jsx`, `app/src/lib/workout.js` | The climbing cards' rep clock and set log. | | Interval timer | `app/src/timer.jsx`, `app/src/timer.css`, `app/src/lib/timer.js` | The general timer: from any workout's sheet and the + menu. Pure model, `now` as an argument; presets are `kind: 'timer'` entries (§6.5). | | Circuits | `app/src/circuit.jsx`, `lib/timer.js` (`exercises`, `circuitDone`, `stopRun`), `lib/prescription.js` (`block.circuit`, `blockTimer`, `endCircuit`, `circuitPlan`, `loggedCircuit`) | #68. One editor (Work / Rest / Rounds, each exercise's own timing behind a tap) for a plan's block switched to Circuit and a timer preset with exercises; both run on `TimerRun` and log themselves (§6.5, §6.6). Tested by `app/circuit.test.js`. | diff --git a/app/native.test.js b/app/native.test.js new file mode 100644 index 0000000..6d6e589 --- /dev/null +++ b/app/native.test.js @@ -0,0 +1,91 @@ +// The phone's frame rules while typing (#77, #98), run in node: the predicates +// in mobile/src/ui/sheetPolicy.ts (bundled by esbuild, which reads TypeScript), +// and pins that every layer with something at its foot asks them rather than a +// copy of its own. A React Native screen cannot be rendered here (no native +// test renderer is installed, and D13 adds no dependency to mobile/), so the +// rule is tested as data and each call site is held to it in the source. +import assert from 'node:assert/strict' +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join } from 'node:path' +import { keyboardEvents, showFoot, canSwipe, showActs } from '../mobile/src/ui/sheetPolicy.ts' + +const ROOT = new URL('../mobile/src/', import.meta.url).pathname +const read = (f) => readFileSync(join(ROOT, f), 'utf8') +const walk = (dir) => readdirSync(join(ROOT, dir)).flatMap(n => { + const p = join(dir, n) + return statSync(join(ROOT, p)).isDirectory() ? walk(p) : /\.tsx?$/.test(n) ? [p] : [] +}) + +const tests = [] +const test = (name, fn) => tests.push([name, fn]) + +test('the keys count as up from keyboardWillShow and as gone only on keyboardDidHide', () => { + assert.deepEqual(keyboardEvents('ios'), { show: 'keyboardWillShow', hide: 'keyboardDidHide' }) + assert.deepEqual(keyboardEvents('android'), { show: 'keyboardDidShow', hide: 'keyboardDidHide' }) +}) + +test('a footer: none while typing, none while confirming, none when there is none', () => { + assert.equal(showFoot({ footer: 'Start', typing: false }), true) + assert.equal(showFoot({ footer: 'Start', typing: true }), false, 'the footer rides the keyboard onto the keypad') + assert.equal(showFoot({ footer: 'Start', confirming: true, typing: false }), false) + assert.equal(showFoot({ footer: null, typing: false }), false) +}) + +test('a swipe down closes only an untouched sheet with no box being typed in', () => { + assert.equal(canSwipe({ touched: false, typing: false }), true) + assert.equal(canSwipe({ touched: true, typing: false }), false, 'a swipe throws away what was typed') + assert.equal(canSwipe({ touched: false, typing: true }), false, 'a swipe closes the sheet mid-number') + assert.equal(canSwipe({ dismissable: false, touched: false, typing: false }), false) +}) + +test("the runner's Done set and All sets are not drawn while the keys are up", () => { + assert.equal(showActs({ typing: true }), false) + assert.equal(showActs({ typing: false }), true) +}) + +test('every layer asks sheetPolicy: the sheet, the planner’s sticky bar, the runner, the keyboard hook', () => { + const sheet = read('ui/Sheet.tsx') + if (!/const canSwipe = swipeAllowed\(\{ dismissable, touched, typing \}\)/.test(sheet) || !/allowSwipeDismissal=\{canSwipe\}/.test(sheet) + || !/onRequestClose=\{\(\) => \{ if \(canSwipe\) onClose\(\) \}\}/.test(sheet)) throw new Error('the sheet decides its own swipe') + if (!/const showFoot = footAllowed\(\{ footer, confirming, typing \}\)/.test(sheet) || !/\{showFoot \? \(/.test(sheet)) throw new Error('the sheet decides its own footer') + if (!/const markDirty = useCallback\(\(\) => setTouched\(true\), \[\]\)/.test(sheet) || !//.test(sheet)) throw new Error('an edit no longer locks the swipe') + const planner = read('features/planner.tsx') + if (!/const showFoot = footAllowed\(\{ footer: foot, typing \}\)/.test(planner)) throw new Error('the planner’s bar decides for itself') + const runner = read('features/runner.tsx') + if (!/\{!showActs\(\{ typing \}\) \? null : \(\s*/.test(runner)) throw new Error('the runner draws its actions over the keys') + const bar = read('ui/KeyboardBar.tsx') + if (!/const on = keyboardEvents\(Platform\.OS\)/.test(bar)) throw new Error('useKeyboardShown has its own events') +}) + +test('ONE keyboard hook: nothing else listens to the keyboard, and nothing waits on keyboardWillHide', () => { + const others = walk('.').filter(f => f !== 'ui/KeyboardBar.tsx' && /Keyboard\.addListener\(/.test(read(f))) + assert.deepEqual(others, [], 'a second keyboard hook is back') + const will = walk('.').filter(f => f !== 'ui/sheetPolicy.ts' && /keyboardWillHide/.test(read(f))) + assert.deepEqual(will, [], 'something comes back while the keys are still leaving') + for (const f of ['ui/Sheet.tsx', 'features/planner.tsx', 'features/runner.tsx']) { + if (!/useKeyboardShown\(\)/.test(read(f))) throw new Error(`${f} does not read the one hook`) + } +}) + +test('every Input carries the keyboard bar, and no sheet footer is a Close', () => { + const kit = read('ui/kit.tsx') + if (!/\{bar \? : null\}/.test(kit)) throw new Error('kit Input lost its keyboard bar') + const raw = walk('features').filter(f => / /squat/i.test(e.name)) + +const tests = [] +const test = (name, fn) => tests.push([name, fn]) + +const LEGS = normalizePrescription({ title: 'Legs', blocks: [{ name: 'Main', items: [ + { kind: 'lift', name: 'Back squat', exercise: SQUAT.key, implement: 'barbell', sets: [{ reps: 5, weight: 100 }, { reps: 5, weight: 100 }] }, +] }] }, { liftField: LIFTS }) +const ROWS = normalizePrescription({ title: 'Rows', blocks: [{ name: 'Main', items: [ + { kind: 'interval', name: 'Row', sets: [{ distance: 500, unit: 'm', restSec: 60 }, { distance: 500, unit: 'm', restSec: 60 }] }, +] }] }, { liftField: LIFTS }) +const CORE = normalizePrescription({ title: 'Core', blocks: [{ name: 'Main', items: [ + { kind: 'interval', name: 'Plank', sets: [{ seconds: 30 }] }, +] }] }, { liftField: LIFTS }) +const CIRCUITS = normalizePrescription({ title: 'Abs', blocks: [ + { name: 'One', circuit: { work: 20, rest: 10, rounds: 1 }, items: [{ kind: 'lift', name: 'Crunch', sets: [{}] }] }, + { name: 'Two', circuit: { work: 20, rest: 10, rounds: 1 }, items: [{ kind: 'lift', name: 'Plank', sets: [{}] }] }, +] }, { liftField: LIFTS }) +const entryOf = (plan, run = null, out = {}) => ({ id: 'daily-x', kind: 'daily', date: '2026-11-08', data: { optId: 'planned', plan, run, out } }) + +/* --------------------------------------------------------------- writes */ + +test('commitOf: the log only when asked, and a finished run reopened by the next write', () => { + const e = entryOf(LEGS, { ...emptyRun(1), endedAt: 50 }) + const [run, opts] = commitOf(e, { ...e.data.run, cursor: 'x' }) + assert.equal(run.endedAt, null, 'a write into a finished run left it finished') + assert.equal(opts.out, null) + assert.equal(opts.done, undefined) + const [again] = commitOf(e, { ...e.data.run, endedAt: 99 }) + assert.equal(again.endedAt, 99, 'a NEW end was taken off') + const [, logged] = commitOf(e, e.data.run, { outputs: true, done: true }) + assert.ok(logged.out, 'outputs asked for and not written') + assert.equal(logged.done, true) + const [same, carried] = writeOf(e, e.data.run, { plan: LEGS }) + assert.equal(same.endedAt, null) + assert.deepEqual(carried, { plan: LEGS }) +}) + +test('markTap: the set, the log and the cursor in one write', () => { + const [s1, s2] = prescriptionSteps(LEGS) + const t = markTap(entryOf(LEGS), prescriptionSteps(LEGS), s1, { reps: 5, weight: 110 }) + assert.equal(t.write[0].sets[s1.setId].weight, 110) + assert.equal(t.cursor, s2.setId) + assert.equal(t.write[1].out.lifts[0].sets[0].weight, 110) + assert.ok(!t.write[0].restUntil, 'a lift set started a rest') +}) + +test('unmark, skip, unskip, jump: where the cursor goes, and the log only for unmark', () => { + const steps = prescriptionSteps(LEGS) + const [s1, s2] = steps + const marked = markTap(entryOf(LEGS), steps, s1, { reps: 5, weight: 100 }).write[0] + const u = unmarkTap(entryOf(LEGS, marked), s1.setId) + assert.equal(u.write[0].sets[s1.setId], undefined) + assert.ok(u.write[1].out) + assert.equal(u.cursor, s1.setId) + const sk = skipTap(entryOf(LEGS), steps, s1) + assert.ok(sk.write[0].skipped.includes(s1.setId)) + assert.equal(sk.write[1].out, null) + assert.equal(sk.cursor, s2.setId) + const un = unskipTap(entryOf(LEGS, sk.write[0]), s1.setId) + assert.ok(!un.write[0].skipped.includes(s1.setId)) + assert.equal(un.cursor, s1.setId) + const j = jumpTap(entryOf(LEGS), s2.setId) + assert.equal(j.write[0].cursor, s2.setId) + assert.equal(j.write[1].out, null) + assert.equal(j.cursor, s2.setId) +}) + +test('addSetTap and patchItemTap: the plan changes, the run and the cursor do not', () => { + const [s1] = prescriptionSteps(LEGS) + const run = { ...emptyRun(1), cursor: s1.setId } + const a = addSetTap(entryOf(LEGS, run), s1, { weight: 120 }) + assert.deepEqual(a.write[0], run) + assert.equal(a.write[1].plan.blocks[0].items[0].sets.length, 3) + assert.equal(a.write[1].plan.blocks[0].items[0].sets[2].weight, 120) + assert.ok(!('cursor' in a), 'adding a set moved the cursor') + const p = patchItemTap(entryOf(LEGS, run), s1, { weightMode: 'side' }, LIFTS) + assert.deepEqual(p.write[0], run) + assert.ok(p.write[1].plan, 'the meaning is not on the plan') + assert.ok(!('cursor' in p)) +}) + +test('finishTap: done, the log and an end, one write', () => { + const t = finishTap(entryOf(LEGS)) + assert.ok(t.write[0].endedAt) + assert.equal(t.write[1].done, true) + assert.ok(t.write[1].out) +}) + +test('the rest: an interval set starts it; bump, pause, skip and Back are instants on the run', () => { + const steps = prescriptionSteps(ROWS) + const [s1, s2] = steps + const run = markTap(entryOf(ROWS), steps, s1, {}).write[0] + assert.ok(run.restUntil > Date.now()) + const e = entryOf(ROWS, run) + assert.equal(restBumpTap(e, 10, 1000).write[0].restUntil, run.restUntil + 10_000) + assert.ok(restPauseTap(e, Date.now()).write[0].restPause) + assert.equal(restSkipTap(e).write[0].restUntil, 0) + const b = restBackTap(e) + assert.equal(b.cursor, s1.setId) + assert.equal(b.write[0].restUntil, 0) + for (const t of [restBumpTap(e, 10), restPauseTap(e), restSkipTap(e), b]) assert.equal(t.write[1].out, null, 'a clock nudge rewrote the log') + void s2 +}) + +test("a timed set: start from the draft's seconds, nudge, stop with nothing logged, end with what was held", () => { + const steps = prescriptionSteps(CORE) + const [p] = steps + const started = holdStartTap(entryOf(CORE), p, { seconds: 40 }, 1000).write[0] + const hold = holdOn(started, p.setId) + assert.equal(hold.seconds, 40, 'the draft\'s seconds were not used') + const fromPlan = holdOn(holdStartTap(entryOf(CORE), p, {}, 1000).write[0], p.setId) + assert.equal(fromPlan.seconds, 30) + const e = entryOf(CORE, started) + const stopped = holdStopTap(e) + assert.equal(stopped.write[0].hold, null) + assert.equal(stopped.write[0].sets?.[p.setId], undefined) + const none = holdEndTap(e, steps, p, {}, null) + assert.equal(none.write[0].hold, null) + assert.equal(none.write[0].sets?.[p.setId], undefined, 'a mis-tap logged the set') + assert.ok(!('cursor' in none)) + assert.equal(none.write[1].out, null) + const held = holdEndTap(e, steps, p, {}, 28) + assert.equal(held.write[0].sets[p.setId].seconds, 28) + assert.ok(held.write[1].out) +}) + +test('holdActTap: a clock control is applied to the clock as it stands now', () => { + const steps = prescriptionSteps(CORE) + const run = holdStartTap(entryOf(CORE), steps[0], {}, 1000).write[0] + const hold = holdOn(run, steps[0].setId) + const program = compile(holdConfig(hold.seconds, { name: 'Plank', key: null })) + const t = holdActTap(entryOf(CORE, run), hold, program, bump, 5000, 10) + assert.deepEqual(t.write[0].hold.timer, bump(program, settle(program, hold.timer, 5000), 5000, 10)) + assert.equal(t.write[0].hold.setId, hold.setId) + assert.equal(t.write[1].out, null) +}) + +test('skipCircuitTap: nothing of it logged, the cursor past it', () => { + const steps = prescriptionSteps(CIRCUITS) + const t = skipCircuitTap(entryOf(CIRCUITS, emptyRun(1)), steps[0]) + assert.ok(t.write[0].skipped.includes(steps[0].setId)) + assert.equal(t.cursor, steps[1].setId) +}) + +/* ------------------------------------------------- someone else's copy (#96) */ + +// Sam's copy of a workout the owner shared, still carrying the owner's words. +const NOTED = normalizePrescription({ title: 'Legs', why: 'Owner reasons.', notes: ['Owner note.'], blocks: [{ name: 'Main', items: [ + { kind: 'lift', name: 'Back squat', exercise: SQUAT.key, implement: 'barbell', note: 'Owner cue.', sets: [{ reps: 5, weight: 100 }] }, +] }] }, { liftField: LIFTS }) +const copyOf = (plan) => ({ ...entryOf(plan, emptyRun(1)), data: { ...entryOf(plan, emptyRun(1)).data, sharedFrom: { id: 'owner', name: 'Alex' } } }) + +test("a copy: the runner reads the plan as shown, without the owner's words (#96 planShown)", () => { + const shown = presOf(copyOf(NOTED)) + assert.ok(!shown.why, "the owner's why shows on someone's copy") + assert.ok(!(shown.notes || []).length, "the owner's notes show on someone's copy") + assert.ok(!shown.blocks[0].items[0].note, "the owner's exercise note shows on someone's copy") + assert.equal(presOf(entryOf(NOTED)), NOTED, 'the owner\'s own entry is not read as it is stored') + // The steps the runner walks are the shown plan's: no owner's cue on Sam's set screen. + assert.ok(!prescriptionSteps(shown)[0].item.note, "the owner's cue is on Sam's set screen") +}) + +test("a copy: Add a set and the weight's meaning write the owner's words back exactly as stored", () => { + const e = copyOf(NOTED) + const [s1] = prescriptionSteps(NOTED) + for (const [what, t] of [['Add a set', addSetTap(e, s1, {})], ["the weight's meaning", patchItemTap(e, s1, { weightMode: 'side' }, LIFTS)]]) { + const plan = t.write[1].plan + assert.equal(plan.why, NOTED.why, `${what} dropped the owner's why from the stored copy`) + assert.deepEqual(plan.notes, NOTED.notes, `${what} dropped the owner's notes from the stored copy`) + assert.equal(plan.blocks[0].items[0].note, 'Owner cue.', `${what} dropped the exercise's note`) + } + assert.ok(patchItemTap(e, s1, { weightMode: 'side' }, LIFTS).write[1].plan.blocks[0].items[0].weightMode, 'the switch did not land') +}) + +/* ------------------------------------------------------------ circuits */ + +const clockOf = (block) => compile(blockTimer(block)) + +test('circuitTick: running is a save; nothing done is as if it never started', () => { + const block = CIRCUITS.blocks[0] + const program = clockOf(block) + const timer = startRun(program, 1000) + const saved = circuitTick({ run: null, pres: CIRCUITS, block, program, timer, only: true }) + assert.equal(saved.write[0].circuit.block, block.id) + assert.equal(saved.write[0].startedAt, 1000) + assert.deepEqual(saved.write[1], {}) + assert.ok(!saved.back && !saved.ended) + const together = circuitSaved(null, block.id, timer, { together: true, withIds: ['sam'] }) + assert.deepEqual(together.circuit.with, ['sam']) + const stopped = { ...timer, finishedAt: 1500 } + const gone = circuitTick({ run: saved.write[0], pres: CIRCUITS, block, program, timer: stopped, only: true }) + assert.equal(gone.write[0], null, 'an untouched run was left on the entry') + assert.ok(gone.back) + const kept = circuitTick({ run: { ...saved.write[0], skipped: ['zz'] }, pres: CIRCUITS, block, program, timer: stopped, only: true }) + assert.equal(kept.write[0].circuit, null) + assert.deepEqual(kept.write[0].skipped, ['zz'], 'what was already done went with an empty circuit') +}) + +test('circuitTick: ended with work done, the log; the next circuit straight after, the last one finishes', () => { + const [one, two] = CIRCUITS.blocks + const p1 = clockOf(one) + const t1 = startRun(p1, 1000) + const end1 = settle(p1, t1, 1000 + 10 * 60_000) + assert.ok(end1.finishedAt != null, 'the clock did not run out') + const first = circuitTick({ run: null, pres: CIRCUITS, block: one, program: p1, timer: end1, only: true, together: true, withIds: ['sam'] }) + assert.ok(first.ended) + assert.equal(first.next, two.id, 'a plan of circuits did not go on to the next') + assert.equal(first.logged, null) + assert.equal(first.write[1].done, undefined) + assert.equal(first.write[1].outputs, true) + assert.equal(first.share.key, t1.startedAt, 'the shared result is not keyed by its clock') + assert.deepEqual(first.share.with, ['sam']) + assert.deepEqual(first.share.items, togetherItems(one), 'a shared result does not carry each side\'s shape (#96)') + assert.ok(first.share.items.every(it => 'by' in it), 'a shared result\'s items do not say how each was timed (#96 togetherItems)') + const p2 = clockOf(two) + const end2 = settle(p2, startRun(p2, 2000), 2000 + 10 * 60_000) + const last = circuitTick({ run: first.write[0], pres: CIRCUITS, block: two, program: p2, timer: end2, only: true }) + assert.equal(last.write[1].done, true, 'the last circuit did not finish the plan') + assert.ok(last.write[0].endedAt) + assert.equal(last.logged, 'Logged') + assert.equal(last.share, null) + const mixed = circuitTick({ run: null, pres: CIRCUITS, block: one, program: p1, timer: end1, only: false }) + assert.equal(mixed.logged, 'Logged on this workout') + assert.equal(mixed.next, null) +}) + +/* ------------------------------------------------------- one controller */ + +test('both runners take their writes from lib/runflow.js and keep none of their own', () => { + for (const f of ['src/runner.jsx', '../mobile/src/features/runner.tsx']) { + const src = readFileSync(new URL(f, import.meta.url), 'utf8') + if (!/useRunner\(\{ entry, onRun, onExit, onFinish, shown, together, liftField, feedback: /.test(src)) throw new Error(`${f} does not run useRunner`) + if (!/circuitTick\(\{ run: runRef\.current/.test(src)) throw new Error(`${f}'s circuit does not run circuitTick`) + const own = src.match(/\bconst (commit|mark|unmark|skip|finish|stopHold|beginHold|holdAct|shareResult|save|patchThisItem|addAnother|jump) = /g) + if (own) throw new Error(`${f} writes for itself again: ${own.join(', ')}`) + if (/\b(markSet|skipSet|unmarkSet|finishRun|endCircuit|reopened|runOutputs)\(/.test(src.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''))) throw new Error(`${f} calls a run write directly`) + } +}) + +let failed = 0 +for (const [name, fn] of tests) { + try { await fn(); console.log(` ok ${name}`) } catch (e) { failed += 1; console.log(` FAIL ${name}\n ${e.stack?.split('\n').slice(0, 3).join('\n ')}`) } +} +console.log(failed ? `${failed} of ${tests.length} runflow cases failed` : `${tests.length} runflow cases`) +process.exit(failed ? 1 : 0) diff --git a/app/runner.dom.test.jsx b/app/runner.dom.test.jsx new file mode 100644 index 0000000..b844ffc --- /dev/null +++ b/app/runner.dom.test.jsx @@ -0,0 +1,438 @@ +// The runner in a real DOM (happy-dom), driven tap by tap: the screen the owner +// edits weights on mid-workout (#98). These are CHARACTERISATION tests, written +// against the runner before its writes moved into lib/runflow.js, and kept to +// prove the move changed nothing: every tap's write (the run, the log, the done +// flag, the plan), where the cursor lands, what the boxes hold, and which cue +// sounds. The host applies each write the way the app does (`applyRun`, the one +// writer), so a stale-closure double write shows up as a wrong entry here. +// Bundled by esbuild (JSX) and run in node. +import assert from 'node:assert/strict' +import { createRequire } from 'node:module' +import { Window } from 'happy-dom' + +const win = new Window({ url: 'http://localhost/' }) +win.matchMedia = (q) => ({ matches: /coarse/.test(q), media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }) +for (const k of ['window', 'document', 'navigator', 'MutationObserver', 'HTMLElement', 'HTMLIFrameElement', 'HTMLInputElement', 'Node', 'Event', 'getComputedStyle', 'localStorage']) { + const value = k === 'window' ? win : k === 'getComputedStyle' ? win.getComputedStyle.bind(win) : win[k] + Object.defineProperty(globalThis, k, { value, configurable: true, writable: true }) +} +win.scrollTo = () => {} +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +// The clock, moved by hand: every value on the runner's screen is Date.now() minus an instant. +const realNow = Date.now +let skew = 0 +Date.now = () => realNow() + skew + +const { act, useState } = await import('react') +const { createRoot } = await import('react-dom/client') +const { WorkoutRunner } = await import('./src/runner.jsx') +const { PlanProvider } = await import('./src/lib/planctx.jsx') +const { CUES } = await import('./src/lib/cues.js') +const { normalizePrescription, prescriptionSteps } = await import('./src/lib/prescription.js') +const { liftFieldOf } = await import('./src/lib/lifts.js') +const { applyRun } = await import('./src/lib/trainer.js') +const require = createRequire(import.meta.url) +const { mergeLibrary } = require('../server/library.js') +const PLAN = mergeLibrary(require('../test/fixtures/plan.json'), require('../test/fixtures/exercises.json')) +const CARD = PLAN.dailyMenu.find(m => m.id === 'planned') +const LIFTS = liftFieldOf(PLAN) +const SQUAT = LIFTS.exercises.find(e => /squat/i.test(e.name)) + +// Which cue sounded, in order. +let heard = [] +for (const k of Object.keys(CUES)) CUES[k] = () => heard.push(k) + +const tests = [] +const test = (name, fn) => tests.push([name, fn]) +const wait = (ms) => act(() => new Promise(r => setTimeout(r, ms))) + +const TODAY = new Date().toISOString().slice(0, 10) +const LEGS = normalizePrescription({ + title: 'Legs', blocks: [ + { name: 'Warm-up', note: 'Ten minutes, nothing heavy.', + items: [{ kind: 'interval', name: 'Bike easy', sets: [{ seconds: 600, restSec: 0 }] }] }, + { name: 'Main', items: [{ + kind: 'lift', name: 'Back squat', exercise: SQUAT.key, implement: 'barbell', + sets: [{ reps: 8, weight: 135, restSec: 90 }, { reps: 8, weight: 135, restSec: 90 }, { reps: 6, weight: 155, restSec: 120 }], + }] }, + ], +}, { liftField: LIFTS }) +const ROWS = normalizePrescription({ + title: 'Rows', blocks: [{ name: 'Main', items: [ + { kind: 'interval', name: 'Row 500', sets: [{ distance: 500, unit: 'm', restSec: 60 }, { distance: 500, unit: 'm', restSec: 60 }] }, + ] }], +}, { liftField: LIFTS }) +const CORE = normalizePrescription({ + title: 'Core', blocks: [{ name: 'Main', items: [ + { kind: 'lift', exercise: 'plank', implement: 'bodyweight', sets: [{ seconds: 45 }, { seconds: 45 }] }, + ] }], +}, { liftField: LIFTS }) +const MIXED = normalizePrescription({ + title: 'Mixed', blocks: [ + { name: 'Finisher', circuit: { work: 30, rest: 15, rounds: 2 }, items: [ + { kind: 'lift', name: 'Crunch', sets: [{}] }, { kind: 'lift', name: 'Plank', sets: [{ seconds: 20 }] }, + ] }, + { name: 'Main', items: [{ kind: 'lift', name: 'Back squat', exercise: SQUAT.key, implement: 'barbell', sets: [{ reps: 5, weight: 100 }] }] }, + ], +}, { liftField: LIFTS }) +const entryOf = (plan, run = null) => ({ + id: `daily-${TODAY}`, kind: 'daily', date: TODAY, updatedAt: 'z', + data: { slot: 'main', optId: 'planned', name: plan.title, done: false, plan, out: { activity: 'lift', category: 'lift' }, ...(run ? { run } : {}) }, +}) + +let unmountLast = null +/** Mount a runner whose host applies every write as the app does, and records it. */ +async function mount(start, props = {}) { + const writes = [] + const calls = { exit: 0, finish: 0 } + const state = { entry: start } + function Host() { + const [entry, setEntry] = useState(start) + state.entry = entry + return ( + + { + writes.push({ run, opts }) + setEntry(cur => (run ? applyRun(cur, CARD, run, opts) : { ...cur, data: { ...cur.data, run: null } })) + }} + onExit={() => { calls.exit += 1 }} onFinish={() => { calls.finish += 1 }} {...props} /> + + ) + } + if (unmountLast) await unmountLast() + document.body.innerHTML = '' + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + unmountLast = () => { unmountLast = null; return act(() => root.unmount()) } + heard = [] + await act(async () => root.render()) + return { host, writes, calls, state, last: () => writes.at(-1), done: () => unmountLast?.() } +} + +const click = (el) => act(() => { el.dispatchEvent(new win.MouseEvent('click', { bubbles: true })) }) +const buttons = () => [...document.querySelectorAll('button')] +const byText = (re) => buttons().find(b => re.test(b.textContent.trim())) +const byLabel = (re) => buttons().find(b => re.test(b.getAttribute('aria-label') || '')) +const tapText = async (re) => { const b = byText(re); assert.ok(b, `no button ${re}`); await click(b) } +const tapLabel = async (re) => { const b = byLabel(re); assert.ok(b, `no button labelled ${re}`); await click(b) } +const box = (which) => document.querySelectorAll('.bigstep-in')[which === 'weight' ? 1 : 0] +const typeInto = (input, value) => act(() => { + const set = Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'value').set + set.call(input, value) + input.dispatchEvent(new win.Event('input', { bubbles: true })) +}) +const where = () => document.querySelector('.run-where span')?.textContent || '' +const steps = (p) => prescriptionSteps(p) + +/* --------------------------------------------------------------- marking */ + +test('Done set writes the set, the log and the cursor in ONE write, and moves on', async () => { + const r = await mount(entryOf(LEGS)) + const [bike, s1, s2] = steps(LEGS) + assert.match(where(), /Warm-up · Set 1 of 1/) + await tapText(/Log this set without the clock/) + assert.equal(r.writes.length, 1, 'marking a set is one write') + const w = r.last() + assert.ok(w.run.sets[bike.setId], 'the set is not on the run') + assert.equal(w.run.cursor, s1.setId) + assert.ok(w.opts.out, 'the log was not written with the set') + assert.equal(w.opts.done, undefined, 'marking a set says nothing about done') + assert.deepEqual(heard, ['setDone']) + assert.match(where(), /Main · Set 1 of 3/, 'the screen did not move on') + // The boxes hold the plan's numbers for an untouched set. + assert.equal(box('reps').value, '8') + assert.equal(box('weight').value, '135') + // A weight typed, then Done set: the typed number is what is logged. + await typeInto(box('weight'), '140') + assert.equal(r.writes.length, 1, 'typing wrote the entry') + await tapText(/^Done set$/) + const m = r.last() + assert.equal(m.run.sets[s1.setId].weight, 140) + assert.equal(m.run.sets[s1.setId].reps, 8) + // A lift has no programmed rest (AGENTS.md §6.4): straight on to the next set. + assert.ok(!m.run.restUntil, 'a lift set started a rest') + const row = m.opts.out.lifts.find(l => l.exercise === SQUAT.key || l.key === SQUAT.key || l.name === 'Back squat') + assert.ok(row, 'the log has no squat row') + assert.equal(row.sets[0].weight, 140) + assert.equal(r.state.entry.data.run.sets[s1.setId].weight, 140, 'the entry lost the set') + assert.ok(r.state.entry.data.run.sets[bike.setId], 'the second write took the first set with it') + assert.match(where(), /Main · Set 2 of 3/) + assert.equal(box('weight').value, '140', 'the next set does not carry what was lifted') + assert.equal(r.state.entry.data.run.cursor, s2.setId) + await r.done() +}) + +test('Skip a set: skipped on the run, cursor on, the log untouched; All sets puts it back', async () => { + const r = await mount(entryOf(LEGS)) + const [bike, s1] = steps(LEGS) + await tapLabel(/^Skip set 1 of Bike easy$/) + const w = r.last() + assert.ok((w.run.skipped || []).includes(bike.setId)) + assert.equal(w.run.cursor, s1.setId) + assert.equal(w.opts.out, null, 'a skip rewrote the log') + assert.deepEqual(heard, []) + assert.match(where(), /Main · Set 1 of 3/) + await tapText(/^All sets$/) + await tapLabel(/^Put set 1 of Bike easy back$/) + assert.ok(!(r.last().run.skipped || []).includes(bike.setId), 'the skip stayed') + assert.match(where(), /Warm-up · Set 1 of 1/, 'putting a set back does not go to it') + await r.done() +}) + +test('Undo this set and All sets: unmark writes the log, a jump moves the cursor and closes the list', async () => { + const r = await mount(entryOf(LEGS)) + const [bike, s1, , s3] = steps(LEGS) + await tapText(/Log this set without the clock/) + await tapText(/^All sets$/) + assert.ok(document.querySelector('[role=dialog][aria-label="All sets"]')) + await tapLabel(/^Undo set 1 of Bike easy$/) + const u = r.last() + assert.equal(u.run.sets[bike.setId], undefined, 'the set is still marked') + assert.ok(u.opts.out, 'an unmark did not rewrite the log') + // The jump. + const n = r.writes.length + const go = [...document.querySelectorAll('.setlist-go')] + assert.equal(go.length, 4) + await click(go[3]) + assert.equal(r.writes.length, n + 1) + assert.equal(r.last().run.cursor, s3.setId) + assert.equal(r.last().opts.out, null) + assert.equal(document.querySelector('[role=dialog][aria-label="All sets"]'), null, 'the list stayed open') + assert.match(where(), /Main · Set 3 of 3/) + assert.equal(box('weight').value, '155') + void s1 + await r.done() +}) + +test('Undo this set on a marked set, from the set screen', async () => { + const [bike, s1] = steps(LEGS) + const r = await mount(entryOf(LEGS)) + await tapText(/Log this set without the clock/) + await tapText(/^All sets$/) + await click(document.querySelectorAll('.setlist-go')[0]) + assert.match(where(), /Warm-up · Set 1 of 1/) + await tapText(/^Undo this set$/) + assert.equal(r.last().run.sets[bike.setId], undefined) + assert.match(where(), /Warm-up · Set 1 of 1/, 'the cursor left the set being undone') + void s1 + await r.done() +}) + +test('Add a set: the plan grows by one set like the boxes, nothing else moves', async () => { + const r = await mount(entryOf(LEGS)) + await tapText(/Log this set without the clock/) + await typeInto(box('weight'), '150') + const before = r.state.entry.data.run + await tapLabel(/^One more set of Back squat, same as this one$/) + const w = r.last() + const squat = w.opts.plan.blocks[1].items[0] + assert.equal(squat.sets.length, 4) + assert.equal(squat.sets[3].weight, 150, 'the new set is not what is in the boxes') + assert.deepEqual(w.run, before, 'adding a set changed the run') + assert.equal(w.opts.out, undefined) + assert.match(where(), /Main · Set 1 of 4/) + assert.equal(box('weight').value, '150', 'the draft was reset by adding a set') + await r.done() +}) + +test("The weight's meaning: one write to the plan, the boxes untouched", async () => { + const r = await mount(entryOf(LEGS)) + await tapText(/Log this set without the clock/) + await typeInto(box('weight'), '45') + const sw = byLabel(/^Weight in .*Switch to /) + assert.ok(sw, 'no meaning switch on a barbell') + await click(sw) + const w = r.last() + assert.ok(w.opts.plan, 'the switch did not write the plan') + assert.ok(w.opts.plan.blocks[1].items[0].weightMode, 'the plan item has no mode') + assert.equal(box('weight').value, '45', 'the switch reset the box') + await r.done() +}) + +/* --------------------------------------------------------------- a hold */ + +test('A timed set: Start writes the clock, Stop clears it and logs nothing, the end marks the seconds held', async () => { + skew = 0 + const r = await mount(entryOf(CORE)) + const [p1, p2] = steps(CORE) + await tapText(/^Start 0:45$/) + assert.ok(r.last().run.hold, 'Start did not put the clock on the run') + assert.equal(r.last().run.hold.setId, p1.setId) + await tapLabel(/^Stop the clock, log nothing$/) + assert.equal(r.last().run.hold, null) + assert.equal(r.last().run.sets?.[p1.setId], undefined, 'stopping logged the set') + assert.ok(byText(/^Start 0:45$/), 'not back on the set screen') + // Started again and left to run out. + await tapText(/^Start 0:45$/) + heard = [] + skew += 120_000 + await wait(400) + const w = r.last() + assert.equal(w.run.hold, null, 'the finished clock stayed on the run') + assert.equal(w.run.sets[p1.setId].seconds, 45) + assert.equal(w.run.cursor, p2.setId) + assert.ok(w.opts.out, 'the held seconds are not in the log') + assert.ok(heard.includes('setDone'), 'the end of a hold did not sound') + assert.match(where(), /Set 2 of 2/) + skew = 0 + await r.done() +}) + +/* ------------------------------------------------------------ the rest */ + +test('The rest: it starts off an interval set; +10 moves it, Pause holds it, Back returns, Skip ends it', async () => { + const r = await mount(entryOf(ROWS)) + const [s1, s2] = steps(ROWS) + await tapText(/^Done set$/) + const until = r.last().run.restUntil + assert.ok(until > Date.now(), 'the rest did not start off the set') + assert.equal(r.last().run.cursor, s2.setId) + assert.match(document.querySelector('.rest-label').textContent, /^Rest/) + assert.match(document.querySelector('.rest-next').textContent, /Set 2 of 2/) + await tapLabel(/^10 seconds more$/) + assert.equal(r.last().run.restUntil, until + 10_000) + assert.equal(r.last().opts.out, null, 'a clock nudge recomputed the log') + await tapLabel(/^Pause$/) + assert.ok(r.last().run.restPause, 'the rest is not paused') + assert.match(document.querySelector('.rest-label').textContent, /paused/) + await tapLabel(/^Resume$/) + await tapLabel(/^Back$/) + assert.equal(r.last().run.restUntil || 0, 0) + assert.equal(r.last().run.cursor, s1.setId) + assert.match(where(), /Main · Set 1 of 2/, 'Back did not return to the set just done') + assert.ok(byText(/^Undo this set$/), 'Back unmarked the set just done') + await tapText(/^All sets$/) + await click(document.querySelectorAll('.setlist-go')[1]) + await tapText(/^Done set$/) + assert.ok(r.last().run.restUntil > Date.now()) + await tapLabel(/^Skip the rest$/) + assert.equal(r.last().run.restUntil || 0, 0) + assert.equal(r.last().opts.out, null) + await r.done() +}) + +/* ---------------------------------------------------------- finishing */ + +test('Finish: one write with the log, done and an end; then onFinish', async () => { + const r = await mount(entryOf(LEGS)) + await tapText(/Log this set without the clock/) + for (let i = 0; i < 3; i += 1) { + await tapText(/^Done set$/) + if (byLabel(/^Skip the rest$/)) await tapLabel(/^Skip the rest$/) + } + assert.ok(byText(/^That is everything$/) || document.querySelector('.finish'), 'not on the finish screen') + heard = [] + const n = r.writes.length + await tapText(/^Finish workout$/) + assert.equal(r.writes.length, n + 1, 'finishing is one write') + const w = r.last() + assert.equal(w.opts.done, true) + assert.ok(w.opts.out) + assert.ok(w.run.endedAt, 'no end on the run') + assert.equal(r.calls.finish, 1) + assert.equal(r.calls.exit, 0) + assert.deepEqual(heard, ['finished']) + await r.done() +}) + +test('Leaving: Keep going writes nothing; Finish with sets left asks again; Leave it open exits', async () => { + const r = await mount(entryOf(LEGS)) + await tapText(/Log this set without the clock/) + const n = r.writes.length + await tapLabel(/^Leave the workout$/) + assert.ok(document.querySelector('[role=dialog][aria-label="Leave the workout?"]')) + await tapText(/^Keep going$/) + assert.equal(document.querySelector('[role=dialog]'), null) + assert.equal(r.writes.length, n) + await tapLabel(/^Leave the workout$/) + await tapText(/^Finish with 3 sets left$/) + assert.ok(document.querySelector('[role=dialog][aria-label="Finish with 3 sets left?"]')) + await tapText(/^Finish anyway$/) + assert.equal(r.last().opts.done, true) + assert.ok(r.last().run.endedAt) + assert.equal(r.calls.finish, 1) + await r.done() + const again = await mount(entryOf(LEGS)) + await tapLabel(/^Leave the workout$/) + await tapText(/^Leave it open$/) + assert.equal(again.calls.exit, 1) + assert.equal(again.writes.length, 0) + await again.done() +}) + +test('A finished run opened again: the first set marked takes the end off', async () => { + const [bike] = steps(LEGS) + const r = await mount(entryOf(LEGS, { startedAt: Date.now() - 600_000, endedAt: Date.now() - 60_000, sets: {}, skipped: [], cursor: bike.setId })) + await tapText(/Log this set without the clock/) + assert.equal(r.last().run.endedAt ?? null, null, 'the run still reads finished') + await r.done() +}) + +/* ------------------------------------------------------------- circuits */ + +test('Skip a circuit in a mixed plan asks first, then marks it skipped and moves on', async () => { + const r = await mount(entryOf(MIXED)) + assert.ok(byText(/^Start the circuit$/), 'the circuit step is not shown') + await tapLabel(/^Skip Finisher$/) + assert.ok(document.querySelector('[role=dialog][aria-label="Skip Finisher?"]')) + assert.equal(r.writes.length, 0, 'asking wrote something') + await tapText(/^Skip the circuit$/) + const w = r.last() + const [c1, c2, main] = steps(MIXED) + assert.ok([c1, c2].every(s => (w.run.skipped || []).includes(s.setId)), 'the circuit is not skipped') + assert.equal(w.run.cursor, main.setId) + assert.match(where(), /Main · Set 1 of 1/) + await r.done() +}) + +test('Start the circuit opens its timer, and starting is a write', async () => { + const r = await mount(entryOf(MIXED)) + await tapText(/^Start the circuit$/) + assert.ok(r.last()?.run?.circuit, 'starting the circuit wrote no clock') + assert.equal(r.last().run.circuit.block, MIXED.blocks[0].id) + await r.done() +}) + +test('A circuit run to its end logs every round in one write and says so', async () => { + skew = 0 + const r = await mount(entryOf(MIXED)) + await tapText(/^Start the circuit$/) + const startedAt = r.last().run.circuit.timer.startedAt + skew += 10 * 60_000 + await wait(600) + const w = r.writes.find(x => x.run && x.run.circuit === null && x.opts.out) + assert.ok(w, 'the end of the circuit wrote no log') + const [c1, c2, main] = steps(MIXED) + assert.ok(w.run.sets[c1.setId] && w.run.sets[c2.setId], 'the circuit\'s sets are not marked') + assert.equal(w.run.circuitKeys?.[MIXED.blocks[0].id], startedAt, 'the result is not keyed by its clock') + assert.equal(w.opts.done, undefined, 'a mixed plan was finished by its circuit') + assert.equal(w.run.cursor ?? main.setId, main.setId) + assert.ok(document.body.textContent.includes('Logged on this workout'), 'the end does not say it was logged') + skew = 0 + await r.done() +}) + +test('Sound: muted, a set marks in silence; a side not on screen never sounds', async () => { + const r = await mount(entryOf(LEGS)) + await tapLabel(/^Turn sound off$/) + await tapText(/Log this set without the clock/) + assert.deepEqual(heard, [], 'a muted runner sounded') + assert.ok(r.last().run.sets, 'muted, the set was not written') + await r.done() + const hidden = await mount(entryOf(LEGS), { shown: false }) + await tapText(/Log this set without the clock/) + assert.deepEqual(heard, [], 'a hidden side sounded') + assert.equal(hidden.writes.length, 1) + await hidden.done() +}) + +let failed = 0 +for (const [name, fn] of tests) { + try { await fn(); console.log(` ok ${name}`) } catch (e) { failed += 1; console.log(` FAIL ${name}\n ${e.stack?.split('\n').slice(0, 3).join('\n ')}`) } +} +win.happyDOM?.abort?.() +console.log(failed ? `${failed} of ${tests.length} runner DOM cases failed` : `${tests.length} runner DOM cases`) +process.exit(failed ? 1 : 0) diff --git a/app/src/lib/runflow.js b/app/src/lib/runflow.js new file mode 100644 index 0000000..2e7935d --- /dev/null +++ b/app/src/lib/runflow.js @@ -0,0 +1,427 @@ +/* + * The runner, as state (#98): the writes every tap makes, and one hook that the + * web's `WorkoutRunner` (app/src/runner.jsx) and the phone's + * (mobile/src/features/runner.tsx) both run, so each platform keeps only its + * screens. What the planner got from lib/planflow.js, for the screen the owner + * edits weights on mid-workout. + * + * Invariants kept here, so neither view can lose them: + * - ONE writer. Every tap is one `onRun(run, opts)`: the position, and in the + * same call the log (`out`) and the done flag when they changed. Two calls once + * spread the same entry, so the second landed on the first and every marked set + * came back as set one with the clock at zero. + * - `out` is left off (null) a write that changes no logged set (a skip, a jump, + * a clock nudge): recomputing the log on every tick is work for no change. + * - Every write goes through `reopened` (lib/timer.js): a finished workout opened + * again is running again from the first thing done in it. + * - The clocks are instants on the run (`restUntil`, `run.hold`, `run.circuit`): + * nothing here counts down, it subtracts, so a closed app comes back right. + * + * Sounds and haptics differ by platform, so they are not here: the hook calls + * `feedback(event, { muted, shown, … })` and each view decides. The events are + * named after the taps: mark, unmark, skip, unskip, addSet, jump, holdStart, + * holdAct, holdStop, holdEnd, finish, cue (a hold's segment changed: `cue`), + * restOver (the rest ran out: `step`, `restUntil`; once per deadline). + * The rest's own controls (Back, ±10, Pause, Skip) and the weight's meaning + * send none, on purpose: neither runner sounded or buzzed on them before the + * move (ControlRow's buttons answer the press themselves), so adding events + * here would have changed what a tap feels like. + * + * On someone else's copy (`sharedFrom`, #96) the plan is read as SHOWN + * (`presOf` = lib/shared.js `planShown`: no owner's words), and every write + * of the plan puts the hidden words back as stored (`withStoredWords`). + */ + +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { + prescriptionSteps, runProgress, firstOpen, runElapsed, + markSet, unmarkSet, skipSet, unskipSet, endRest, goToSet, finishRun, + emptyRun, setDraft, carryForward, runOutputs, isLogged, addSetLike, patchRunItem, + endCircuit, circuitToOpen, nextCircuit, +} from './prescription.js' +import { + compile, circuitDone, view as timerView, settle, moved, cueFor, holdConfig, holdOn, startHold, heldSeconds, + restClock, restPausedAt, toggleRest, bumpRest, restBack, reopened, +} from './timer.js' +import { planShown, withStoredWords } from './shared.js' +import { togetherItems } from './trainer.js' + +/** + * @typedef {[any, { out?: any, done?: boolean, plan?: any }]} RunWrite + * What one tap writes: the next run and the options `onRun` takes. + * @typedef {{ write: RunWrite, cursor?: string | null }} RunTap + * A write, and where the runner's cursor goes after it (absent: it stays). + */ + +/* --------------------------------------------------------------- writes */ + +const runOf = (entry) => entry?.data?.run || null +// The plan as this log's person sees it: never the owner's notes on a copy +// (lib/shared.js `planShown`, #96). A write of the plan puts them back (`withStoredWords`). +export const presOf = (entry) => planShown(entry) + +/** + * A write of the run, and the log it implies when `outputs` (a logged set changed). + * @param {any} entry @param {any} nextRun @param {{ outputs?: boolean, done?: boolean }} [opts] + * @returns {RunWrite} + */ +export function commitOf(entry, nextRun, { outputs = false, done = undefined } = {}) { + const r = reopened(nextRun, runOf(entry)) + return [r, { out: outputs ? runOutputs(presOf(entry), r, entry?.data?.out || {}) : null, done }] +} + +/** + * A write that carries its own options (a plan grown by a set, a weight's meaning). + * @param {any} entry @param {any} nextRun @param {any} opts @returns {RunWrite} + */ +export const writeOf = (entry, nextRun, opts) => [reopened(nextRun, runOf(entry)), opts] + +/** Done set: the numbers in the boxes, the log with it, on to the next. @returns {RunTap} */ +export function markTap(entry, steps, step, draft) { + const next = markSet(runOf(entry) || emptyRun(), step, draft || {}, { steps }) + return { write: commitOf(entry, next, { outputs: true }), cursor: next.cursor } +} + +/** Undo a set: off the run and the log, and the cursor on it. @returns {RunTap} */ +export const unmarkTap = (entry, setId) => ({ write: commitOf(entry, unmarkSet(runOf(entry), setId), { outputs: true }), cursor: setId }) + +/** Skip the set the runner is on. The log is untouched. @returns {RunTap} */ +export function skipTap(entry, steps, step) { + const next = skipSet(runOf(entry) || emptyRun(), step.setId, { steps }) + return { write: commitOf(entry, next), cursor: next.cursor } +} + +/** Put a skipped set back, and go to it. @returns {RunTap} */ +export const unskipTap = (entry, setId) => ({ write: commitOf(entry, unskipSet(runOf(entry), setId)), cursor: setId }) + +/** + * One more set of the one the runner is on, with the numbers in the boxes now. + * The plan grows a set at the end of the item and nothing else moves: not the + * cursor, not the draft, not the log, not the clock. @returns {RunTap} + */ +export const addSetTap = (entry, step, draft) => + ({ write: writeOf(entry, runOf(entry), { plan: withStoredWords(entry, addSetLike(presOf(entry), step.itemId, { ...step.set, ...(draft || {}) })) }) }) + +/** + * What this exercise's weight means (#58): the plan, and the log once a set of + * it is logged. The plan it changes is the one SHOWN, so the words hidden from + * a copy go back as stored (`withStoredWords`), as Add a set's do: written from + * the shown plan, the switch dropped the owner's notes from Sam's stored copy. + * @returns {RunTap} + */ +export function patchItemTap(entry, step, patch, liftField) { + const next = patchRunItem(presOf(entry), runOf(entry), step.itemId, patch, entry?.data?.out || {}, liftField) + return { write: writeOf(entry, runOf(entry), { ...next, plan: withStoredWords(entry, next.plan) }) } +} + +/** A set chosen from All sets. @returns {RunTap} */ +export const jumpTap = (entry, setId) => ({ write: commitOf(entry, goToSet(runOf(entry) || emptyRun(), setId)), cursor: setId }) + +/** Finish: the log, done and the end in ONE write. @returns {RunTap} */ +export const finishTap = (entry) => ({ write: commitOf(entry, finishRun(runOf(entry) || emptyRun()), { outputs: true, done: true }) }) + +/* The rest: an instant on the run, moved, paused, ended or taken back to the set. */ +/** @returns {RunTap} */ +export function restBackTap(entry) { + const next = restBack(runOf(entry)) + return { write: commitOf(entry, next), cursor: next.cursor } +} +/** @returns {RunTap} */ +export const restBumpTap = (entry, delta, at = Date.now()) => ({ write: commitOf(entry, bumpRest(runOf(entry), at, delta)) }) +/** @returns {RunTap} */ +export const restPauseTap = (entry, at = Date.now()) => ({ write: commitOf(entry, toggleRest(runOf(entry), at)) }) +/** @returns {RunTap} */ +export const restSkipTap = (entry) => ({ write: commitOf(entry, endRest(runOf(entry))) }) + +/* A timed set's clock (#75): `run.hold`, started, nudged, stopped, ended. */ + +/** Start: the draft's seconds, else the plan's. @returns {RunTap} */ +export function holdStartTap(entry, step, draft, at = Date.now()) { + const seconds = Number(draft?.seconds) > 0 ? draft.seconds : step.set.seconds + return { write: commitOf(entry, startHold(runOf(entry) || emptyRun(at), step.setId, seconds, at, { name: step.item.name, key: step.item.exercise || null })) } +} + +/** One of the clock's controls (`fn` from lib/timer.js: back, bump, skip, togglePause). @returns {RunTap} */ +export function holdActTap(entry, hold, program, fn, at = Date.now(), ...args) { + const run = runOf(entry) + return { write: commitOf(entry, { ...run, hold: { ...hold, timer: fn(program, settle(program, hold.timer, at), at, ...args) } }) } +} + +/** Stop the clock: nothing is logged. @returns {RunTap} */ +export const holdStopTap = (entry) => ({ write: commitOf(entry, { ...runOf(entry), hold: null }) }) + +/** + * The clock ran out: the set is marked with the seconds held. Under DONE_AFTER + * (`secs` null: a mis-tap, a look) it marks nothing and the set is as it was. + * @returns {RunTap} + */ +export function holdEndTap(entry, steps, step, draft, secs) { + const base = { ...runOf(entry), hold: null } + if (secs == null) return { write: commitOf(entry, base) } + const next = markSet(base, step, { ...(draft || {}), seconds: secs }, { steps }) + return { write: commitOf(entry, next, { outputs: true }), cursor: next.cursor } +} + +/** Skip a whole circuit (asked first): none of it is logged. @returns {RunTap} */ +export function skipCircuitTap(entry, step) { + const next = endCircuit(runOf(entry), presOf(entry), step.blockId, [], {}) + return { write: commitOf(entry, next), cursor: next.cursor } +} + +/* ------------------------------------------------------------ circuits */ + +/** + * A circuit's clock as it stands, on the run (`run.circuit`), so a closed app or + * another device comes back to the same second. Together or not, and with whom, + * is decided at Start and kept with it. + */ +export function circuitSaved(run, blockId, timer, { together = false, withIds = null } = {}) { + const base = run || emptyRun(timer.startedAt) + return { ...base, startedAt: base.startedAt || timer.startedAt, + circuit: { block: blockId, timer, ...(together ? { together: true, with: withIds } : {}) } } +} + +/** + * Every change of a circuit's clock, and what follows it. Still running: the + * clock is saved. Ended with nothing done: as if it never started (`back`). + * Ended with work done: each exercise's rounds marked (`endCircuit`, keyed by + * the clock's start so writing it twice changes nothing) and the log in the same + * write; a plan of nothing but circuits is finished and done with its last, and + * runs the next straight after (`next`). Done together, `share` is the result + * for every other side (the Together rule, lib/trainer.js). + * + * `write` is `[run | null, opts]`: a null run takes the run off the entry. + */ +export function circuitTick({ run, pres, block, program, timer, only, together = false, withIds = null }) { + if (timer.finishedAt == null) return { write: [circuitSaved(run, block.id, timer, { together, withIds }), {}] } + const done = circuitDone(program, timer) + if (!done.some(d => d.length)) { + const rest = { ...(run || {}), circuit: null } + const untouched = !Object.keys(rest.sets || {}).length && !(rest.skipped || []).length + return { write: [untouched ? null : rest, {}], back: true } + } + const at = timer.finishedAt + const seconds = timerView(program, timer, at).elapsed + const key = timer.startedAt + const next = endCircuit(run, pres, block.id, done, { at, seconds, key }) + const all = runProgress(next, prescriptionSteps(pres)).left === 0 + const then = only && !all ? nextCircuit(pres, next) : null + const write = only && all ? [finishRun(next, { at }), { outputs: true, done: true }] : [next, { outputs: true }] + const share = together ? { + block: { uid: block.uid || null, id: block.id, name: block.name }, + items: togetherItems(block), + done, at, seconds, key, ...(withIds ? { with: withIds } : {}), + } : null + return { write, ended: true, share, next: then ? then.id : null, logged: then ? null : (only && all ? 'Logged' : 'Logged on this workout') } +} + +/* ------------------------------------------------------------- the hook */ + +/** + * The runner's state and taps. `onRun(run, opts)` is the one writer; `onExit` + * leaves; `onFinish` (else `onExit`) follows a finish, so a workout with sides + * hands over to the next (`SidesWorkout`). `shown` false: a side not on screen, + * whose clock runs but which never sounds. `together`: a shared workout's + * circuit done on one clock (#68). `feedback(event, info)`: the platform's + * sounds and haptics (see the top of this file). + * + * @param {{ + * entry: any, onRun: (run: any, opts: any) => void, onExit: () => void, onFinish?: (() => void) | null, + * shown?: boolean, together?: any, liftField?: any, feedback?: (event: string, info: any) => void, + * }} args + */ +export function useRunner({ entry, onRun, onExit, onFinish = null, shown = true, together = null, liftField = null, feedback = () => {} }) { + const pres = presOf(entry) + const steps = useMemo(() => prescriptionSteps(pres), [pres]) + const run = runOf(entry) + + const [now, setNow] = useState(() => Date.now()) + const [cursor, setCursor] = useState(() => run?.cursor || firstOpen(run, steps)) + const [draft, setDraft_] = useState(/** @type {any} */ (null)) + const [listOpen, setListOpen] = useState(false) + const [muted, setMuted] = useState(false) + // The leave dialog: null, 'ask' (Keep going / Leave it open / Finish…), or + // 'finish' (finishing with sets still to do asks again). + const [leaving, setLeaving] = useState(/** @type {null | 'ask' | 'finish'} */ (null)) + const [skipping, setSkipping] = useState(false) // a whole circuit's Skip asks first + const rangAt = useRef(0) + + /* + * A circuit block (#68) runs on the interval timer's screen. A plan of nothing + * but circuits goes straight to it; in a plan with other work it is a step that + * starts when asked, and so is a shared workout's side not on screen: each + * person's clock starts on their own Start (`circuitToOpen`). A circuit that + * can be done together waits on its start screen, where that is chosen. + */ + const [circuitId, setCircuitId] = useState(() => circuitToOpen(pres, run, { shown: shown && !together?.offer })) + // Each circuit done together on this screen: its result, and what each other + // side said (null while asking). Try again asks again (lib/trainer.js). + const [shared, setShared] = useState(/** @type {{ result: any, said: any[] | null }[]} */ ([])) + // Straight on from one circuit to the next in a plan of circuits, said in its count-in. + const [chained, setChained] = useState(false) + const circuitBlock = circuitId ? (pres?.blocks || []).find(b => b.id === circuitId && b.circuit) || null : null + + const step = steps.find(s => s.setId === cursor) || steps[0] || null + const progress = runProgress(run, steps) + // The rest stands still while paused (lib/timer.js `restClock`). + const rest = restClock(run, now) + const restPaused = restPausedAt(run) != null + const elapsed = runElapsed(run, now) + const done = progress.left === 0 && progress.total > 0 + + // A timed set's clock (#75), on the run (`run.hold`), so it survives the app closing. + const hold = step ? holdOn(run, step.setId) : null + const holdProgram = useMemo( + () => (hold ? compile(holdConfig(hold.seconds, { name: step.item.name, key: step.item.exercise || null })) : null), + [hold?.seconds, step?.item?.name, step?.item?.exercise]) // eslint-disable-line react-hooks/exhaustive-deps -- the program is the hold's seconds and the exercise, not the objects holding them + const holdNow = hold ? settle(holdProgram, hold.timer, now) : null + + const info = (more = {}) => ({ muted, shown, ...more }) + const send = (/** @type {RunTap} */ tap) => { + onRun(...tap.write) + if (tap.cursor !== undefined) setCursor(tap.cursor) + } + + // A repaint tick, nothing more: every value on screen is subtracted from Date.now(). + useEffect(() => { + const iv = setInterval(() => setNow(Date.now()), 250) + return () => clearInterval(iv) + }, []) + + /* + * The rest bell: once, on the transition to zero, keyed by the deadline it + * belongs to (`rangAt`, not a boolean: a second rest of the same length must + * ring again and a re-render must not). A side not on screen rings nothing. + */ + useEffect(() => { + if (!run?.restUntil || rest > 0) return + if (rangAt.current === run.restUntil) return + rangAt.current = run.restUntil + if (!shown) return + feedback('restOver', info({ step, restUntil: run.restUntil })) + }, [rest, run?.restUntil, muted, step, shown]) // eslint-disable-line react-hooks/exhaustive-deps -- `feedback` is the platform's and may be a new function each render; the bell is keyed by the deadline + + // What is in the boxes for the set the runner is on. Recomputed when the set + // changes, never while the user is typing in it. + useEffect(() => { + if (!step) { setDraft_(null); return } + const carried = isLogged(run, step.setId) ? null : carryForward(run, steps, step) + setDraft_(carried ? { ...setDraft(run, step), ...carried } : setDraft(run, step)) + }, [cursor, step?.setId]) // eslint-disable-line react-hooks/exhaustive-deps -- the boxes follow the set, never a sync of the run while typing + + const patch = (p) => setDraft_(d => ({ ...(d || {}), ...p })) + + /** Persist run state, and the outputs it implies where they changed. */ + const commit = useCallback((nextRun, opts = {}) => onRun(...commitOf(entry, nextRun, opts)), [onRun, entry]) + + const mark = () => { + if (!step) return + feedback('mark', info()) + send(markTap(entry, steps, step, draft)) + } + const unmark = (setId) => { feedback('unmark', info()); send(unmarkTap(entry, setId)) } + const skip = () => { + if (!step) return + feedback('skip', info()) + send(skipTap(entry, steps, step)) + } + const unskip = (setId) => { feedback('unskip', info()); send(unskipTap(entry, setId)) } + const addSet = () => { + if (!step) return + feedback('addSet', info()) + send(addSetTap(entry, step, draft)) + } + const patchItem = (p) => { if (step) send(patchItemTap(entry, step, p, liftField)) } + const jump = (setId) => { + feedback('jump', info()) + send(jumpTap(entry, setId)) + setListOpen(false) + } + + const restGoBack = () => send(restBackTap(entry)) + const restBump = (n) => send(restBumpTap(entry, n, Date.now())) + const restPause = () => send(restPauseTap(entry, Date.now())) + const restSkip = () => send(restSkipTap(entry)) + + const beginHold = () => { + if (!step) return + feedback('holdStart', info()) + const at = Date.now() + send(holdStartTap(entry, step, draft, at)) + setNow(at) + } + const holdAct = (fn, ...args) => { + if (!hold) return + feedback('holdAct', info()) + const at = Date.now() + send(holdActTap(entry, hold, holdProgram, fn, at, ...args)) + setNow(at) + } + const stopHold = () => { feedback('holdStop', info()); send(holdStopTap(entry)) } + + // A hold's cues, on each change of segment (the count-in ending, the hold ending). + const heard = useRef(/** @type {any} */ (null)) + useEffect(() => { + if (!holdNow) { heard.current = null; return } + const was = heard.current + heard.current = holdNow + if (was && was.startedAt === holdNow.startedAt && moved(was, holdNow) && shown && !muted) { + const c = cueFor(holdProgram, holdNow) + if (c && c !== 'finished') feedback('cue', info({ cue: c })) + } + }) + + // The end of a hold marks the set with what was held, once per clock. + const ended = useRef(/** @type {number | null} */ (null)) + useEffect(() => { + if (!hold || holdNow?.finishedAt == null || ended.current === hold.timer.startedAt) return + ended.current = hold.timer.startedAt + const secs = heldSeconds(holdProgram, holdNow) + if (secs != null) feedback('holdEnd', info()) + send(holdEndTap(entry, steps, step, draft, secs)) + }, [holdNow?.finishedAt]) // eslint-disable-line react-hooks/exhaustive-deps -- once per clock's end, read with what is on screen then + + const finish = () => { + setLeaving(null) + feedback('finish', info()) + send(finishTap(entry)) + // With more than one side, finishing one hands over to the next (SidesWorkout). + ;(onFinish || onExit)() + } + + const skipCircuit = () => { + setSkipping(false) + send(skipCircuitTap(entry, step)) + } + + /* Circuits: the one write path for the circuit screen, and its comings and goings. */ + const circuitWrite = (next, opts) => (next ? commit(next, opts) : onRun(null, {})) + const startCircuit = (blockId) => setCircuitId(blockId) + const circuitNext = (id) => { setChained(true); setCircuitId(id) } + const circuitBack = (only) => { + setCircuitId(null) + setChained(false) + if (only) (onFinish || onExit)() + else setCursor(c => firstOpen(runOf(entry), steps) || c) + } + const shareResult = async (result) => { + const same = (x) => x.result.key === result.key && x.result.block.id === result.block.id + setShared(list => [...list.filter(x => !same(x)), { result, said: null }]) + let said + try { said = await together.write(result) } catch { said = null } + setShared(list => list.map(x => (same(x) ? { result, said: said || [] } : x))) + } + const retryShared = () => shared.filter(x => x.said?.some(y => y.status === 'missed')).forEach(x => shareResult(x.result)) + + return { + pres, steps, run, step, cursor, draft, progress, rest, restPaused, elapsed, done, now, + hold, holdProgram, holdNow, muted, setMuted, + listOpen, openList: () => setListOpen(true), closeList: () => setListOpen(false), + leaving, askLeave: () => setLeaving('ask'), askFinish: () => setLeaving('finish'), keepGoing: () => setLeaving(null), + skipping, askSkipCircuit: () => setSkipping(true), keepCircuit: () => setSkipping(false), skipCircuit, + circuitBlock, chained, shared, circuitWrite, startCircuit, circuitNext, circuitBack, shareResult, retryShared, + tick: () => setNow(Date.now()), + patch, mark, unmark, skip, unskip, addSet, patchItem, jump, + restGoBack, restBump, restPause, restSkip, beginHold, holdAct, stopHold, finish, + } +} diff --git a/app/src/runner.jsx b/app/src/runner.jsx index ce4beac..fddbfa0 100644 --- a/app/src/runner.jsx +++ b/app/src/runner.jsx @@ -40,32 +40,22 @@ * mid-session costs nothing, which is the entire point of the first decision. */ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { Icon } from './lib/icons.jsx' import { NumInput } from './numinput.jsx' import { useModalLayer } from './modal.jsx' import { CUES, primeAudio, resumeAudio, acquireWakeLock, releaseWakeLock } from './lib/cues.js' import { lastLift, liftFieldOf } from './lib/lifts.js' -import { - prescriptionSteps, runProgress, firstOpen, runElapsed, - markSet, unmarkSet, skipSet, unskipSet, endRest, goToSet, finishRun, - emptyRun, setDraft, carryForward, runOutputs, isLogged, isSkipped, setLine, itemLine, - setFieldsFor, addSetLike, patchRunItem, measureOfItem, - blockTimer, circuitOnly, circuitTiming, endCircuit, circuitToOpen, nextCircuit, -} from './lib/prescription.js' -import { - compile, startRun, circuitDone, view as timerView, describe, totalSeconds, settle, back, bump, skip as skipSegment, - togglePause, moved, cueFor, holdConfig, isTimedSet, holdOn, startHold, heldSeconds, - restClock, restPausedAt, toggleRest, bumpRest, restBack, reopened, -} from './lib/timer.js' +import { isLogged, isSkipped, setLine, itemLine, setFieldsFor, measureOfItem, blockTimer, circuitOnly, circuitTiming } from './lib/prescription.js' +import { compile, startRun, view as timerView, describe, totalSeconds, back, bump, skip as skipSegment, togglePause, isTimedSet } from './lib/timer.js' +import { useRunner, circuitTick } from './lib/runflow.js' import { clock } from './lib/workout.js' import { Stepper, boxFor, stepBox, TimeInput, weightSwitch, SwapWords, ExerciseSheet } from './exercises.jsx' import { ExerciseBody, musclesOf, muscleWords } from './lib/bodymap.jsx' import { usePlan } from './lib/planctx.jsx' import { TimerRun, WorkHead, LeaveDialog, leaveActions, ControlRow, setsWord } from './timer.jsx' import { timingWords } from './circuit.jsx' -import { andWords, togetherSaid, togetherItems } from './lib/trainer.js' -import { planShown, withStoredWords } from './lib/shared.js' +import { andWords, togetherSaid } from './lib/trainer.js' const mmss = (s) => `${Math.floor(s / 60)}:${String(Math.abs(s) % 60).padStart(2, '0')}` @@ -97,81 +87,15 @@ const mmss = (s) => `${Math.floor(s / 60)}:${String(Math.abs(s) % 60).padStart(2 * is written to every side when it ends (`write`, which says who it missed). */ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onFinish = null, who = null, switcher = null, shown = true, together = null }) { - // As this log's person sees it: never the owner's notes on a copy (lib/shared.js `planShown`, #96). - const pres = planShown(entry) - const steps = useMemo(() => prescriptionSteps(pres), [pres]) const liftField = liftFieldOf(usePlan()) - const run = entry?.data?.run || null - - const [now, setNow] = useState(() => Date.now()) - const [cursor, setCursor] = useState(() => run?.cursor || firstOpen(run, steps)) - const [draft, setDraft_] = useState(null) - const [listOpen, setListOpen] = useState(false) - const [muted, setMuted] = useState(false) - // The leave dialog: null, 'ask' (Keep going / Leave it open / Finish…), or - // 'finish' (finishing with sets still to do asks again). - const [leaving, setLeaving] = useState(null) - const [skipping, setSkipping] = useState(false) // a whole circuit's Skip asks first const lock = useRef(null) - const rangAt = useRef(0) + // The state and every tap's write are lib/runflow.js, shared with the phone; + // this file is the screens, and the web's sounds. + const r = useRunner({ entry, onRun, onExit, onFinish, shown, together, liftField, feedback: webFeedback }) + const { pres, steps, run, step, progress, rest, restPaused, elapsed, done, hold, holdProgram, holdNow, muted, circuitBlock } = r useModalLayer() - /* - * A circuit block (issue #68) runs on the interval timer's screen. A plan - * that is nothing but circuits goes straight to it, so an ab circuit is open, - * Start, and it runs; in a plan with other work the circuit is a step that - * says what it is and starts when asked, and so does a shared workout's side - * that is not on screen: each person's clock starts on their own Start - * (`circuitToOpen`). One whose timer is on the entry - * (left open, or the page reloaded) comes back running. - */ - // A circuit that can be done together waits on its start screen, where that is chosen. - const [circuitId, setCircuitId] = useState(() => circuitToOpen(pres, run, { shown: shown && !together?.offer })) - // Each circuit done together on this screen: its result, and what each other - // side said (null while asking). Try again asks again (lib/trainer.js). - const [shared, setShared] = useState([]) - const shareResult = async (result) => { - const same = (x) => x.result.key === result.key && x.result.block.id === result.block.id - setShared(list => [...list.filter(x => !same(x)), { result, said: null }]) - let said - try { said = await together.write(result) } catch { said = null } - setShared(list => list.map(x => (same(x) ? { result, said: said || [] } : x))) - } - // Straight on from one circuit to the next in a plan of circuits, said in its count-in. - const [chained, setChained] = useState(false) - const circuitBlock = circuitId ? (pres?.blocks || []).find(b => b.id === circuitId && b.circuit) || null : null - - const step = steps.find(s => s.setId === cursor) || steps[0] || null - const progress = runProgress(run, steps) - // The rest stands still while paused (lib/timer.js `restClock`). - const rest = restClock(run, now) - const restPaused = restPausedAt(run) != null - const elapsed = runElapsed(run, now) - const done = progress.left === 0 && progress.total > 0 - - /* - * A timed set's clock (#75): a plank or a 90-second interval is started with - * "Start 0:30", counts down on the timer's face and marks itself, logging the - * seconds actually held. It is on the run (`run.hold`), so it survives the - * app closing like the rest clock does. - */ - const hold = step ? holdOn(run, step.setId) : null - const holdProgram = useMemo( - () => (hold ? compile(holdConfig(hold.seconds, { name: step.item.name, key: step.item.exercise || null })) : null), - [hold?.seconds, step?.item?.name, step?.item?.exercise]) // eslint-disable-line react-hooks/exhaustive-deps - const holdNow = hold ? settle(holdProgram, hold.timer, now) : null - - /* ------------------------------------------------------------ the clock */ - - // A repaint tick, nothing more. Every value on screen is derived by - // subtracting from Date.now(), so a throttled background tab cannot drift the - // session — it just repaints less often while nobody is looking. - useEffect(() => { - const iv = setInterval(() => setNow(Date.now()), 250) - return () => clearInterval(iv) - }, []) - // The screen stays on while the user is in here, and the audio context is retaken // after the phone has been in a pocket — backgrounding suspends it and coming // back does not always resume, which looks exactly like a broken timer. @@ -180,7 +104,7 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF acquireWakeLock().then(l => { if (live) lock.current = l; else releaseWakeLock(l) }) const onVis = () => { if (document.visibilityState !== 'visible') return - setNow(Date.now()) + r.tick() resumeAudio() acquireWakeLock().then(l => { lock.current = l }) } @@ -190,177 +114,18 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF document.removeEventListener('visibilitychange', onVis) releaseWakeLock(lock.current) } - }, []) - - /* - * The rest bell. - * - * Fires once, on the transition to zero, keyed by the deadline it belongs to — - * `rangAt` rather than a boolean, because a second rest of the same length must - * ring again and a re-render must not. - * - * It also asks the service worker to post a notification, which is best effort - * and honestly so: if iOS has frozen the tab there is no timer left to fire, - * and there is no reliable way to schedule a local notification from a page. - * The clock is still correct when the user comes back, which is the guarantee that - * actually matters. - */ - useEffect(() => { - if (!run?.restUntil || rest > 0) return - if (rangAt.current === run.restUntil) return - rangAt.current = run.restUntil - if (!shown) return - if (!muted) CUES.work() - if (document.visibilityState !== 'visible') notifyRestOver(step) - }, [rest, run?.restUntil, muted, step, shown]) - - /* ------------------------------------------------------------- the draft */ - - // What is in the boxes for the set the user is on. Recomputed when the set changes, - // never while the user is typing in it. - useEffect(() => { - if (!step) { setDraft_(null); return } - const carried = isLogged(run, step.setId) ? null : carryForward(run, steps, step) - setDraft_(carried ? { ...setDraft(run, step), ...carried } : setDraft(run, step)) - }, [cursor, step?.setId]) - - const patch = (p) => setDraft_(d => ({ ...(d || {}), ...p })) - - /* ------------------------------------------------------------- the writes */ - - /* - * Every write goes through `reopened` (lib/timer.js): a workout finished and - * opened again from its sheet is running again from the first thing done in - * it, and only a write that finishes it sets an end. - */ - const write = (nextRun, opts) => onRun(reopened(nextRun, run), opts) - - /** Persist run state, and the outputs it implies where they changed. */ - const commit = useCallback((nextRun, { outputs = false, done = undefined } = {}) => { - const r = reopened(nextRun, entry?.data?.run || null) - onRun(r, { - out: outputs ? runOutputs(pres, r, entry?.data?.out || {}) : null, - done, - }) - }, [onRun, pres, entry]) - - const mark = () => { - if (!step) return - primeAudio() - if (!muted && shown) CUES.setDone() - const next = markSet(run || emptyRun(), step, draft || {}, { steps }) - commit(next, { outputs: true }) - setCursor(next.cursor) - } - - const unmark = (setId) => { - const next = unmarkSet(run, setId) - commit(next, { outputs: true }) - setCursor(setId) - } - - const skip = () => { - if (!step) return - const next = skipSet(run || emptyRun(), step.setId, { steps }) - commit(next) - setCursor(next.cursor) - } - - /** - * One more set of the one the user is on, with the numbers in the boxes right now. - * The plan grows a set at the end of this item and nothing else moves: the - * cursor stays where it is (the user has not marked this set yet), the draft is - * untouched, and `out` is left off because no logged set changed. The clock is - * not started by it either — adding a set is not doing one. - */ - const addAnother = () => { - if (!step) return - write(run, { plan: withStoredWords(entry, addSetLike(pres, step.itemId, { ...step.set, ...(draft || {}) })) }) - } - - // What this exercise's weight means (#58), on the plan, and on the log in the - // same write once a set of it is logged, so every set and the log say the same. - const patchThisItem = (p) => write(run, patchRunItem(pres, run, step.itemId, p, entry?.data?.out || {}, liftField)) - - const jump = (setId) => { - commit(goToSet(run || emptyRun(), setId)) - setCursor(setId) - setListOpen(false) - } - - /* ---------------------------------------------------- a timed set's clock */ - - const beginHold = () => { - if (!step) return - primeAudio() - const at = Date.now() - const seconds = Number(draft?.seconds) > 0 ? draft.seconds : step.set.seconds - commit(startHold(run || emptyRun(at), step.setId, seconds, at, { name: step.item.name, key: step.item.exercise || null })) - setNow(at) - } - const holdAct = (fn, ...args) => { - if (!hold) return - primeAudio() - const at = Date.now() - commit({ ...run, hold: { ...hold, timer: fn(holdProgram, settle(holdProgram, hold.timer, at), at, ...args) } }) - setNow(at) - } - const stopHold = () => commit({ ...run, hold: null }) - - // Its cues, on each change of segment (the count-in ending, the hold ending). - const heard = useRef(null) - useEffect(() => { - if (!holdNow) { heard.current = null; return } - const was = heard.current - heard.current = holdNow - if (was && was.startedAt === holdNow.startedAt && moved(was, holdNow) && shown && !muted) { - const c = cueFor(holdProgram, holdNow) - if (c && c !== 'finished') CUES[c]?.() - } - }) - - // The end of a hold marks the set with what was held, once per clock; under - // DONE_AFTER (a mis-tap, a look) it marks nothing and the set is as it was. - const ended = useRef(null) - useEffect(() => { - if (!hold || holdNow?.finishedAt == null || ended.current === hold.timer.startedAt) return - ended.current = hold.timer.startedAt - const secs = heldSeconds(holdProgram, holdNow) - const base = { ...run, hold: null } - if (secs == null) { commit(base); return } - if (!muted && shown) CUES.setDone() - const next = markSet(base, step, { ...(draft || {}), seconds: secs }, { steps }) - commit(next, { outputs: true }) - setCursor(next.cursor) - }, [holdNow?.finishedAt]) // eslint-disable-line react-hooks/exhaustive-deps - - const finish = () => { - setLeaving(null) - if (!muted && shown) CUES.finished() - // Done, the outputs and the end time in one write, for the same reason as - // above — `onSetDone` used to be a second call and would have taken the run - // with it. - commit(finishRun(run || emptyRun()), { outputs: true, done: true }) - // With more than one side, finishing one hands over to the next (SidesWorkout). - ;(onFinish || onExit)() - } + }, []) // eslint-disable-line react-hooks/exhaustive-deps -- once per runner; `tick` only sets the clock if (circuitBlock) { const only = circuitOnly(pres) return ( shared.filter(x => x.said?.some(y => y.status === 'missed')).forEach(x => shareResult(x.result))} - intro={chained ? `Next: ${circuitBlock.name}` : null} - onNext={(id) => { setChained(true); setCircuitId(id) }} + together={together} onShare={r.shareResult} shared={r.shared} onRetry={r.retryShared} + intro={r.chained ? `Next: ${circuitBlock.name}` : null} + onNext={r.circuitNext} who={who} switcher={switcher} shown={shown} - onRun={(next, opts) => (next ? commit(next, opts) : onRun(null, {}))} - onBack={() => { - setCircuitId(null) - setChained(false) - if (only) (onFinish || onExit)() - else setCursor(c => firstOpen(entry?.data?.run, steps) || c) - }} + onRun={r.circuitWrite} + onBack={() => r.circuitBack(only)} onLeave={onExit} /> ) } @@ -381,9 +146,9 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF return (
- setLeaving('ask')} /> + onExit={r.askLeave} /> {switcher} @@ -393,66 +158,75 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF {rest > 0 ? ( { const next = restBack(run); commit(next); setCursor(next.cursor) }} - onBump={(n) => commit(bumpRest(run, Date.now(), n))} - onPause={() => commit(toggleRest(run, Date.now()))} - onSkip={() => commit(endRest(run))} /> + onBack={r.restGoBack} onBump={r.restBump} onPause={r.restPause} onSkip={r.restSkip} /> ) : done ? ( setListOpen(true)} /> + onFinish={r.finish} onReview={r.openList} /> ) : step?.block?.circuit ? ( setCircuitId(step.blockId)} - onList={() => setListOpen(true)} - onSkip={() => setSkipping(true)} /> + onStart={() => r.startCircuit(step.blockId)} + onList={r.openList} + onSkip={r.askSkipCircuit} /> ) : hold && holdNow ? ( - holdAct(togglePause)} - onBack={() => holdAct(back)} onBump={(n) => holdAct(bump, n)} onPause={() => holdAct(togglePause)} - onSkip={() => holdAct(skipSegment)} onStop={stopHold} /> + r.holdAct(togglePause)} + onBack={() => r.holdAct(back)} onBump={(n) => r.holdAct(bump, n)} onPause={() => r.holdAct(togglePause)} + onSkip={() => r.holdAct(skipSegment)} onStop={r.stopHold} /> ) : step ? ( unmark(step.setId)} onAddSet={addAnother} - onStartHold={beginHold} - onPatchItem={patchThisItem} - onList={() => setListOpen(true)} /> + onPatch={r.patch} onMark={r.mark} onSkip={r.skip} onUnmark={() => r.unmark(step.setId)} onAddSet={r.addSet} + onStartHold={r.beginHold} + onPatchItem={r.patchItem} + onList={r.openList} /> ) : null} - {listOpen && ( - { commit(unskipSet(run, id)); setCursor(id) }} - onClose={() => setListOpen(false)} onFinish={progress.left === 0 ? finish : null} /> + {r.listOpen && ( + )} - {leaving === 'ask' && ( + {r.leaving === 'ask' && ( setLeaving(null)} - actions={leaveActions({ left: progress.left, onLeave: onExit, onFinish: finish, onAskFinish: () => setLeaving('finish') })} /> + onKeep={r.keepGoing} + actions={leaveActions({ left: progress.left, onLeave: onExit, onFinish: r.finish, onAskFinish: r.askFinish })} /> )} - {leaving === 'finish' && ( + {r.leaving === 'finish' && ( setLeaving(null)} - actions={[{ label: 'Finish anyway', kind: 'secondary', onClick: finish }]} /> + onKeep={r.keepGoing} + actions={[{ label: 'Finish anyway', kind: 'secondary', onClick: r.finish }]} /> )} - {skipping && step?.block?.circuit && ( + {r.skipping && step?.block?.circuit && ( setSkipping(false)} - actions={[{ label: 'Skip the circuit', kind: 'secondary', onClick: () => { - setSkipping(false) - const next = endCircuit(run, pres, step.blockId, [], {}) - commit(next) - setCursor(next.cursor) - } }]} /> + keepLabel="Keep it" onKeep={r.keepCircuit} + actions={[{ label: 'Skip the circuit', kind: 'secondary', onClick: r.skipCircuit }]} /> )}
) } +/** + * The web's sounds for the runner's taps (lib/runflow.js `feedback`). A tap that + * starts something primes the audio context (iOS opens it only on a gesture); a + * set marked, a hold ended and a finish sound unless muted or off screen; the + * rest bell also asks for a notification while the page is hidden. + */ +function webFeedback(event, { muted, shown, cue, step }) { + if (event === 'mark' || event === 'holdStart' || event === 'holdAct') primeAudio() + if ((event === 'mark' || event === 'holdEnd') && !muted && shown) CUES.setDone() + if (event === 'finish' && !muted && shown) CUES.finished() + if (event === 'cue') CUES[cue]?.() + if (event === 'restOver') { + if (!muted) CUES.work() + if (document.visibilityState !== 'visible') notifyRestOver(step) + } +} + /* --------------------------------------------------------------- circuits */ /** @@ -485,46 +259,19 @@ function CircuitRun({ const runRef = useRef(run) runRef.current = run - const save = (timer) => { - const base = runRef.current || emptyRun(timer.startedAt) - onRun({ ...base, startedAt: base.startedAt || timer.startedAt, - circuit: { block: block.id, timer, ...(withThem ? { together: true, with: withIds } : {}) } }, {}) - } - // Starting is a write: the entry says it is running from the first second. - useEffect(() => { if (!live) save(initial) }, []) // eslint-disable-line react-hooks/exhaustive-deps - + // Every change of the clock, and what follows it, is lib/runflow.js `circuitTick`. const onTimer = (timer) => { - if (timer.finishedAt == null) { save(timer); return } - const done = circuitDone(program, timer) - const base = runRef.current - if (!done.some(d => d.length)) { - const rest = { ...(base || {}), circuit: null } - const untouched = !Object.keys(rest.sets || {}).length && !(rest.skipped || []).length - onRun(untouched ? null : rest, {}) - onBack() - return - } - const at = timer.finishedAt - const seconds = timerView(program, timer, at).elapsed - // Keyed by the clock's start, so writing this result again changes nothing. - const key = timer.startedAt - const next = endCircuit(base, pres, block.id, done, { at, seconds, key }) - const all = runProgress(next, prescriptionSteps(pres)).left === 0 - const then = only && !all ? nextCircuit(pres, next) : null - if (only && all) onRun(finishRun(next, { at }), { outputs: true, done: true }) - else onRun(next, { outputs: true }) + const t = circuitTick({ run: runRef.current, pres, block, program, timer, only, together: withThem, withIds }) + onRun(...t.write) + if (t.back) { onBack(); return } // Done together: the same result on every other side, each through its own writer. - if (withThem && onShare) { - onShare({ - block: { uid: block.uid || null, id: block.id, name: block.name }, - items: togetherItems(block), - done, at, seconds, key, ...(withIds ? { with: withIds } : {}), - }) - } + if (t.share && onShare) onShare(t.share) // A plan of circuits runs the next one straight after, not back to the day. - if (then) { onNext(then.id); return } - setLogged(only && all ? 'Logged' : 'Logged on this workout') + if (t.next) { onNext(t.next); return } + if (t.logged) setLogged(t.logged) } + // Starting is a write: the entry says it is running from the first second. + useEffect(() => { if (!live) onTimer(initial) }, []) // eslint-disable-line react-hooks/exhaustive-deps -- once, as the circuit opens /* * Done together, the words come from what each side SAID (rule 5): who it is diff --git a/mobile/AGENTS.md b/mobile/AGENTS.md index cd869f1..73d5e5f 100644 --- a/mobile/AGENTS.md +++ b/mobile/AGENTS.md @@ -145,6 +145,13 @@ Use `npx expo install ` for dependencies so versions match the SDK. `Input`. While the keyboard is up a `Modal` shows no footer and allows no swipe-down, and the planner's `StepPage` hides its sticky bar (`useKeyboardShown`); they come back on `keyboardDidHide`. Deliberate and native: the web hides its footers on focus instead. + Every layer asks the same predicates, `ui/sheetPolicy.ts` (`showFoot`, `canSwipe`, + `showActs`, `keyboardEvents`), which have no React Native import so `app/native.test.js` + runs them in node and holds each call site to them. `useKeyboardShown` is the only + keyboard listener in the app. +- **The runner's state and writes are `lib/runflow.js`** (#98, the web's, copied): `useRunner` + and the `*Tap` functions. `features/runner.tsx` is the screens and `nativeFeedback` (cues and + haptics per tap); a change to how a set is marked is made once, in the lib. - **Toasts over sheets (#77).** A presented `Modal`, `FullScreen` or `Popover` is drawn above the root, so each mounts its own `ToastHost` (inside its native modal) and only the most recently mounted live host renders (`useTopHost` in `ui/ToastHost.tsx`); the root's takes diff --git a/mobile/src/features/planner.tsx b/mobile/src/features/planner.tsx index 1a523a2..10dfc71 100644 --- a/mobile/src/features/planner.tsx +++ b/mobile/src/features/planner.tsx @@ -20,6 +20,7 @@ import { T } from '../ui/Text' import { Btn, Card, Chip, IconBtn, Input, Press, SectionHeader } from '../ui/kit' import { FullScreen } from '../ui/Sheet' import { useKeyboardShown } from '../ui/KeyboardBar' +import { showFoot as footAllowed } from '../ui/sheetPolicy' import { PrescriptionEditor } from './editor' import { NumInput } from './numinput' import { impact, success, tap, warn } from '../ui/haptics' @@ -66,7 +67,7 @@ export function StepPage({ children, foot = null, after = null, scrollRef = null }) { const insets = useSafeAreaInsets() const typing = useKeyboardShown() - const showFoot = Boolean(foot) && !typing + const showFoot = footAllowed({ footer: foot, typing }) return ( `${Math.floor(s / 60)}:${String(Math.abs(s) % 60).padStart(2, '0')}` @@ -123,77 +116,12 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF }) { void session const insets = useSafeAreaInsets() - // As this log's person sees it: never the owner's notes on a copy (lib/shared.js `planShown`, #96). - const pres: any = planShown(entry) - const steps: any[] = useMemo(() => prescriptionSteps(pres), [pres]) const liftField = liftFieldOf(usePlan()) - const run = entry?.data?.run || null - - const [now, setNow] = useState(() => Date.now()) - const [cursor, setCursor] = useState(() => run?.cursor || (firstOpen as any)(run, steps)) - const [draft, setDraft_] = useState(null) - const [listOpen, setListOpen] = useState(false) - // The leave dialog: null, 'ask' (Keep going / Leave it open / Finish…), or - // 'finish' (finishing with sets still to do asks again). - const [leaving, setLeaving] = useState(null) - const [skipping, setSkipping] = useState(false) // a whole circuit's Skip asks first - const [muted, setMuted] = useState(false) const lock = useRef(null) - const rangAt = useRef(0) - - /* - * A circuit block (issue #68) runs on the interval timer's screen. A plan that - * is nothing but circuits goes straight to it (open, Start, it runs); in a plan - * with other work the circuit is a step that starts when asked, and so is a - * shared workout's side that is not on screen: each person's clock starts on - * their own Start (`circuitToOpen`). One whose timer is on the entry (left open, a cold start) comes back running. - */ - // A circuit that can be done together waits on its start screen, where that is chosen. - const [circuitId, setCircuitId] = useState(() => (circuitToOpen as any)(pres, run, { shown: shown && !together?.offer })) - // Each circuit done together on this screen: its result, and what each other - // side said (null while asking). Try again asks again (lib/trainer.js). - const [shared, setShared] = useState<{ result: any; said: any[] | null }[]>([]) - const shareResult = async (result: any) => { - const same = (x: any) => x.result.key === result.key && x.result.block.id === result.block.id - setShared((list) => [...list.filter((x) => !same(x)), { result, said: null }]) - let said: any[] | null - try { said = await together.write(result) } catch { said = null } - setShared((list) => list.map((x) => (same(x) ? { result, said: said || [] } : x))) - } - // Straight on from one circuit to the next in a plan of circuits, said in its count-in. - const [chained, setChained] = useState(false) - const circuitBlock = circuitId ? (pres?.blocks || []).find((b: any) => b.id === circuitId && b.circuit) || null : null - - const step = steps.find(s => s.setId === cursor) || steps[0] || null - const progress: any = runProgress(run, steps) - // The rest stands still while paused (lib/timer.js `restClock`). - const rest: number = restClock(run, now) - const restPaused = restPausedAt(run) != null - const elapsed = runElapsed(run, now) - const done = progress.left === 0 && progress.total > 0 - - /* - * A timed set's clock (#75): a plank or a 90-second interval is started with - * "Start 0:30", counts down on the timer's face and marks itself, logging the - * seconds actually held. It is on the run (`run.hold`), so it survives the - * app closing like the rest clock does. - */ - const hold: any = step ? holdOn(run, step.setId) : null - const holdProgram = useMemo( - () => (hold ? tCompile(holdConfig(hold.seconds, { name: step.item.name, key: step.item.exercise || null })) : null), - // eslint-disable-next-line react-hooks/exhaustive-deps - [hold?.seconds, step?.item?.name, step?.item?.exercise]) - const holdNow: any = hold ? settle(holdProgram, hold.timer, now) : null - - /* ------------------------------------------------------------ the clock */ - - // A repaint tick, nothing more. Every value on screen is derived by - // subtracting from Date.now(), so a suspended app cannot drift the session — - // it just repaints less often while nobody is looking. - useEffect(() => { - const iv = setInterval(() => setNow(Date.now()), 250) - return () => clearInterval(iv) - }, []) + // The state and every tap's write are lib/runflow.js, the web's own; this + // file is the screens, and the phone's cues and haptics. + const r = useRunner({ entry, onRun, onExit, onFinish, shown, together, liftField, feedback: nativeFeedback }) + const { pres, steps, run, step, progress, rest, restPaused, elapsed, done, hold, holdProgram, holdNow, muted, circuitBlock } = r // The screen stays on while the user is in here, and the clock resyncs the // instant the app comes back from a pocket rather than on the next tick. @@ -201,7 +129,7 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF let live = true acquireWakeLock().then(l => { if (live) lock.current = l; else releaseWakeLock(l) }) const off = onForeground(() => { - setNow(Date.now()) + r.tick() resumeAudio() }) return () => { @@ -209,169 +137,9 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF off() releaseWakeLock(lock.current) } - }, []) - - /* - * The rest bell. - * - * Fires once, on the transition to zero, keyed by the deadline it belongs to — - * `rangAt` rather than a boolean, because a second rest of the same length - * must ring again and a re-render must not. - * - * Native: iOS suspends JS in the background, so a rest that ran out while the - * phone was locked is noticed on return. A buzz then, seconds or minutes late, - * would be a false "go now", so only a bell within a few seconds of the - * deadline rings. The web's service-worker notification has no native - * counterpart without expo-notifications; the clock is still right on return, - * which is the guarantee that matters. - */ - useEffect(() => { - if (!run?.restUntil || rest > 0) return - if (rangAt.current === run.restUntil) return - rangAt.current = run.restUntil - if (shown && !muted && Date.now() - run.restUntil < 5000) CUES.work() - }, [rest, run?.restUntil, muted, shown]) - - /* ------------------------------------------------------------- the draft */ - - // What is in the boxes for the set the user is on. Recomputed when the set - // changes, never while the user is typing in it. - useEffect(() => { - if (!step) { setDraft_(null); return } - const carried = isLogged(run, step.setId) ? null : carryForward(run, steps, step) - setDraft_(carried ? { ...setDraft(run, step), ...carried } : setDraft(run, step)) - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [cursor, step?.setId]) - - const patch = (p: any) => setDraft_((d: any) => ({ ...(d || {}), ...p })) - - /* ------------------------------------------------------------- the writes */ - - /* - * Every write goes through `reopened` (lib/timer.js): a workout finished and - * opened again from its sheet is running again from the first thing done in - * it, and only a write that finishes it sets an end. - */ - const write = (nextRun: any, opts: any) => onRun(reopened(nextRun, run), opts) - - /** Persist run state, and the outputs it implies where they changed. */ - const commit = useCallback((nextRun: any, { outputs = false, done = undefined }: { outputs?: boolean; done?: boolean } = {}) => { - const r = reopened(nextRun, entry?.data?.run || null) - onRun(r, { - out: outputs ? runOutputs(pres, r, entry?.data?.out || {}) : null, - done, - }) - }, [onRun, pres, entry]) - - const mark = () => { - if (!step) return - primeAudio() - // A logged set always answers the thumb; the mute is for the clock's cues. - if (muted) success(); else CUES.setDone() - const next: any = (markSet as any)(run || emptyRun(), step, draft || {}, { steps }) - commit(next, { outputs: true }) - setCursor(next.cursor) - } - - const unmark = (setId: string) => { - tap() - const next = unmarkSet(run, setId) - commit(next, { outputs: true }) - setCursor(setId) - } - - const skip = () => { - if (!step) return - tap() - const next: any = (skipSet as any)(run || emptyRun(), step.setId, { steps }) - commit(next) - setCursor(next.cursor) - } - - /** - * One more set of the one the user is on, with the numbers in the boxes right - * now. The plan grows a set at the end of this item and nothing else moves: - * the cursor stays where it is, the draft is untouched, and `out` is left off - * because no logged set changed. The clock is not started by it either — - * adding a set is not doing one. - */ - const addAnother = () => { - if (!step) return - impact() - write(run, { plan: withStoredWords(entry, (addSetLike as any)(pres, step.itemId, { ...step.set, ...(draft || {}) })) }) - } - - // What this exercise's weight means (#58), on the plan, and on the log in the - // same write once a set of it is logged, so every set and the log say the same. - const patchThisItem = (p: any) => { - if (step) write(run, (patchRunItem as any)(pres, run, step.itemId, p, entry?.data?.out || {}, liftField)) - } - - const jump = (setId: string) => { - tap() - commit((goToSet as any)(run || emptyRun(), setId)) - setCursor(setId) - setListOpen(false) - } - - /* ---------------------------------------------------- a timed set's clock */ - - const beginHold = () => { - if (!step) return - impact() - const at = Date.now() - const seconds = Number(draft?.seconds) > 0 ? draft.seconds : step.set.seconds - commit(startHold(run || emptyRun(at), step.setId, seconds, at, { name: step.item.name, key: step.item.exercise || null })) - setNow(at) - } - const holdAct = (fn: any, ...args: any[]) => { - if (!hold) return - const at = Date.now() - commit({ ...run, hold: { ...hold, timer: fn(holdProgram, settle(holdProgram, hold.timer, at), at, ...args) } }) - setNow(at) - } - const stopHold = () => { tap(); commit({ ...run, hold: null }) } - - // Its cues, on each change of segment (the count-in ending, the hold ending). - const heard = useRef(null) - useEffect(() => { - if (!holdNow) { heard.current = null; return } - const was = heard.current - heard.current = holdNow - if (was && was.startedAt === holdNow.startedAt && moved(was, holdNow) && shown && !muted) { - const c = cueFor(holdProgram, holdNow) - if (c && c !== 'finished') (CUES as any)[c]?.() - } - }) - - // The end of a hold marks the set with what was held, once per clock; under - // DONE_AFTER (a mis-tap, a look) it marks nothing and the set is as it was. - const ended = useRef(null) - useEffect(() => { - if (!hold || holdNow?.finishedAt == null || ended.current === hold.timer.startedAt) return - ended.current = hold.timer.startedAt - const secs = heldSeconds(holdProgram, holdNow) - const base = { ...run, hold: null } - if (secs == null) { commit(base); return } - // A hidden side's hold ends silently, as the web's: the cue is about the side on screen. - if (shown) { if (muted) success(); else CUES.setDone() } - const next: any = (markSet as any)(base, step, { ...(draft || {}), seconds: secs }, { steps }) - commit(next, { outputs: true }) - setCursor(next.cursor) - }, [holdNow?.finishedAt]) // eslint-disable-line react-hooks/exhaustive-deps + }, []) // eslint-disable-line react-hooks/exhaustive-deps -- once per runner; `tick` only sets the clock - const finish = () => { - setLeaving(null) - if (muted) success(); else CUES.finished() - // Done, the outputs and the end time in one write, for the same reason as - // above — `onSetDone` used to be a second call and would have taken the run - // with it. - commit((finishRun as any)(run || emptyRun()), { outputs: true, done: true }) - // With more than one side, finishing one hands over to the next (SidesWorkout). - ;(onFinish || onExit)() - } - - const askExit = () => setLeaving('ask') + const askExit = r.askLeave const frame = (body: React.ReactNode) => embedded ? ( {body} @@ -389,18 +157,12 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF const only = circuitOnly(pres) const body = ( shared.filter((x) => x.said?.some((y: any) => y.status === 'missed')).forEach((x) => shareResult(x.result))} - intro={chained ? `Next: ${circuitBlock.name}` : null} - onNext={(id: string) => { setChained(true); setCircuitId(id) }} + together={together} onShare={r.shareResult} shared={r.shared} onRetry={r.retryShared} + intro={r.chained ? `Next: ${circuitBlock.name}` : null} + onNext={r.circuitNext} who={who} switcher={switcher} shown={shown} - onRun={(next: any, opts: any) => (next ? commit(next, opts) : onRun(null, {}))} - onBack={() => { - setCircuitId(null) - setChained(false) - if (only) (onFinish || onExit)() - else setCursor((c: any) => (firstOpen as any)(entry?.data?.run, steps) || c) - }} + onRun={r.circuitWrite} + onBack={() => r.circuitBack(only)} onLeave={onExit} /> ) // The timer pads its own foot, so its frame pads only the top. @@ -429,7 +191,7 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF return frame( <> - @@ -442,66 +204,79 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF {rest > 0 ? ( { const next: any = restBack(run); commit(next); setCursor(next.cursor) }} - onBump={(n: number) => commit(bumpRest(run, Date.now(), n))} - onPause={() => commit(toggleRest(run, Date.now()))} - onSkip={() => commit(endRest(run))} /> + onBack={r.restGoBack} onBump={r.restBump} onPause={r.restPause} onSkip={r.restSkip} /> ) : done ? ( setListOpen(true)} /> + onFinish={r.finish} onReview={r.openList} /> ) : step?.block?.circuit ? ( { impact(); setCircuitId(step.blockId) }} - onList={() => { tap(); setListOpen(true) }} - onSkip={() => { warn(); setSkipping(true) }} /> + onStart={() => { impact(); r.startCircuit(step.blockId) }} + onList={() => { tap(); r.openList() }} + onSkip={() => { warn(); r.askSkipCircuit() }} /> ) : hold && holdNow ? ( - holdAct(togglePause)} - onBack={() => holdAct(tBack)} onBump={(n: number) => holdAct(tBump, n)} onPause={() => holdAct(togglePause)} - onSkip={() => holdAct(tSkip)} onStop={stopHold} /> + r.holdAct(togglePause)} + onBack={() => r.holdAct(tBack)} onBump={(n: number) => r.holdAct(tBump, n)} onPause={() => r.holdAct(togglePause)} + onSkip={() => r.holdAct(tSkip)} onStop={r.stopHold} /> ) : step ? ( unmark(step.setId)} onAddSet={addAnother} - onStartHold={beginHold} - onPatchItem={patchThisItem} - onList={() => setListOpen(true)} /> + onPatch={r.patch} onMark={r.mark} onSkip={r.skip} onUnmark={() => r.unmark(step.setId)} onAddSet={r.addSet} + onStartHold={r.beginHold} + onPatchItem={r.patchItem} + onList={r.openList} /> ) : null} - {listOpen && ( - { tap(); commit(unskipSet(run, id)); setCursor(id) }} - onClose={() => setListOpen(false)} onFinish={progress.left === 0 ? finish : null} /> + {r.listOpen && ( + )} - {leaving === 'ask' ? ( + {r.leaving === 'ask' ? ( setLeaving(null)} - actions={leaveActions({ left: progress.left, onLeave: onExit, onFinish: finish, onAskFinish: () => { warn(); setLeaving('finish') } })} /> + onKeep={r.keepGoing} + actions={leaveActions({ left: progress.left, onLeave: onExit, onFinish: r.finish, onAskFinish: () => { warn(); r.askFinish() } })} /> ) : null} - {leaving === 'finish' ? ( + {r.leaving === 'finish' ? ( setLeaving(null)} - actions={[{ label: 'Finish anyway', kind: 'secondary', onClick: finish }]} /> + onKeep={r.keepGoing} + actions={[{ label: 'Finish anyway', kind: 'secondary', onClick: r.finish }]} /> ) : null} - {skipping && step?.block?.circuit ? ( + {r.skipping && step?.block?.circuit ? ( setSkipping(false)} - actions={[{ label: 'Skip the circuit', kind: 'secondary', onClick: () => { - setSkipping(false) - const next: any = (endCircuit as any)(run, pres, step.blockId, [], {}) - commit(next) - setCursor(next.cursor) - } }]} /> + keepLabel="Keep it" onKeep={r.keepCircuit} + actions={[{ label: 'Skip the circuit', kind: 'secondary', onClick: r.skipCircuit }]} /> ) : null} , ) } +/** + * The phone's cues and haptics for the runner's taps (lib/runflow.js + * `feedback`). A logged set always answers the thumb: muted, it is a haptic + * instead of the cue. A hold's end on a side not on screen is silent, as on the + * web; a late rest bell (the phone was locked through the deadline) would be a + * false "go now", so only one within a few seconds of it rings. The web's + * service-worker notification has no native counterpart without a native module. + */ +function nativeFeedback(event: string, { muted, shown, cue, restUntil }: { muted: boolean; shown: boolean; cue?: string; restUntil?: number }) { + switch (event) { + case 'mark': primeAudio(); if (muted) success(); else CUES.setDone(); break + case 'holdEnd': if (shown) { if (muted) success(); else CUES.setDone() } break + case 'finish': if (muted) success(); else CUES.finished(); break + case 'unmark': case 'skip': case 'unskip': case 'jump': case 'holdStop': tap(); break + case 'addSet': case 'holdStart': impact(); break + case 'cue': (CUES as any)[cue as string]?.(); break + case 'restOver': if (!muted && restUntil != null && Date.now() - restUntil < 5000) CUES.work(); break + default: break + } +} + /* --------------------------------------------------------------- circuits */ /** @@ -515,7 +290,7 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF */ function CircuitRun({ pres, block, run, only, intro, who, switcher, shown, onRun, onNext, onBack, onLeave, together = null, onShare = null, shared = [], onRetry = null }: any) { - const { compile, startRun, circuitDone, view } = timerLib as any + const { compile, startRun } = timerLib as any const { andWords, togetherSaid } = trainerLib as any const config = useMemo(() => blockTimer(block), [block]) const program = useMemo(() => compile(config), [config]) @@ -531,47 +306,20 @@ function CircuitRun({ pres, block, run, only, intro, who, switcher, shown, onRun const runRef = useRef(run) runRef.current = run - const save = (timer: any) => { - const base = runRef.current || emptyRun(timer.startedAt) - onRun({ ...base, startedAt: base.startedAt || timer.startedAt, - circuit: { block: block.id, timer, ...(withThem ? { together: true, with: withIds } : {}) } }, {}) - } - // Starting is a write: the entry says it is running from the first second. - useEffect(() => { if (!live) save(initial) }, []) // eslint-disable-line react-hooks/exhaustive-deps - + // Every change of the clock, and what follows it, is lib/runflow.js `circuitTick`. const onTimer = (timer: any) => { - if (timer.finishedAt == null) { save(timer); return } - const done: any[][] = circuitDone(program, timer) - const base = runRef.current - if (!done.some(d => d.length)) { - const rest = { ...(base || {}), circuit: null } - const untouched = !Object.keys(rest.sets || {}).length && !(rest.skipped || []).length - onRun(untouched ? null : rest, {}) - onBack() - return - } - const at = timer.finishedAt - const seconds = view(program, timer, at).elapsed - // Keyed by the clock's start, so writing this result again changes nothing. - const key = timer.startedAt - const next: any = (endCircuit as any)(base, pres, block.id, done, { at, seconds, key }) - const all = (runProgress(next, prescriptionSteps(pres)) as any).left === 0 - const then: any = only && !all ? (nextCircuit as any)(pres, next) : null - if (only && all) onRun((finishRun as any)(next, { at }), { outputs: true, done: true }) - else onRun(next, { outputs: true }) - success() + const t = circuitTick({ run: runRef.current, pres, block, program, timer, only, together: withThem, withIds }) + onRun(...t.write) + if (t.back) { onBack(); return } + if (t.ended) success() // Done together: the same result on every other side, each through its own writer. - if (withThem && onShare) { - onShare({ - block: { uid: block.uid || null, id: block.id, name: block.name }, - items: (trainerLib as any).togetherItems(block), - done, at, seconds, key, ...(withIds ? { with: withIds } : {}), - }) - } + if (t.share && onShare) onShare(t.share) // A plan of circuits runs the next one straight after, not back to the day. - if (then) { onNext(then.id); return } - setLogged(only && all ? 'Logged' : 'Logged on this workout') + if (t.next) { onNext(t.next); return } + if (t.logged) setLogged(t.logged) } + // Starting is a write: the entry says it is running from the first second. + useEffect(() => { if (!live) onTimer(initial) }, []) // eslint-disable-line react-hooks/exhaustive-deps -- once, as the circuit opens // Done together, the words come from what each side SAID (rule 5); never // "for you and Sam" over a miss. @@ -816,7 +564,7 @@ function SetScreen({ step, steps, run, draft, entries, entryId, briefing = [], o keypad (#75); the keys' own bar (‹ › Done editing, kit's Input) puts it away. They come back once the keys have gone (`keyboardDidHide`, the sheet's rule), not as they start to leave under a lifting thumb (#94). */} - {typing ? null : ( + {!showActs({ typing }) ? null : ( {logged ? ( diff --git a/mobile/src/lib/runflow.js b/mobile/src/lib/runflow.js new file mode 100644 index 0000000..2e7935d --- /dev/null +++ b/mobile/src/lib/runflow.js @@ -0,0 +1,427 @@ +/* + * The runner, as state (#98): the writes every tap makes, and one hook that the + * web's `WorkoutRunner` (app/src/runner.jsx) and the phone's + * (mobile/src/features/runner.tsx) both run, so each platform keeps only its + * screens. What the planner got from lib/planflow.js, for the screen the owner + * edits weights on mid-workout. + * + * Invariants kept here, so neither view can lose them: + * - ONE writer. Every tap is one `onRun(run, opts)`: the position, and in the + * same call the log (`out`) and the done flag when they changed. Two calls once + * spread the same entry, so the second landed on the first and every marked set + * came back as set one with the clock at zero. + * - `out` is left off (null) a write that changes no logged set (a skip, a jump, + * a clock nudge): recomputing the log on every tick is work for no change. + * - Every write goes through `reopened` (lib/timer.js): a finished workout opened + * again is running again from the first thing done in it. + * - The clocks are instants on the run (`restUntil`, `run.hold`, `run.circuit`): + * nothing here counts down, it subtracts, so a closed app comes back right. + * + * Sounds and haptics differ by platform, so they are not here: the hook calls + * `feedback(event, { muted, shown, … })` and each view decides. The events are + * named after the taps: mark, unmark, skip, unskip, addSet, jump, holdStart, + * holdAct, holdStop, holdEnd, finish, cue (a hold's segment changed: `cue`), + * restOver (the rest ran out: `step`, `restUntil`; once per deadline). + * The rest's own controls (Back, ±10, Pause, Skip) and the weight's meaning + * send none, on purpose: neither runner sounded or buzzed on them before the + * move (ControlRow's buttons answer the press themselves), so adding events + * here would have changed what a tap feels like. + * + * On someone else's copy (`sharedFrom`, #96) the plan is read as SHOWN + * (`presOf` = lib/shared.js `planShown`: no owner's words), and every write + * of the plan puts the hidden words back as stored (`withStoredWords`). + */ + +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { + prescriptionSteps, runProgress, firstOpen, runElapsed, + markSet, unmarkSet, skipSet, unskipSet, endRest, goToSet, finishRun, + emptyRun, setDraft, carryForward, runOutputs, isLogged, addSetLike, patchRunItem, + endCircuit, circuitToOpen, nextCircuit, +} from './prescription.js' +import { + compile, circuitDone, view as timerView, settle, moved, cueFor, holdConfig, holdOn, startHold, heldSeconds, + restClock, restPausedAt, toggleRest, bumpRest, restBack, reopened, +} from './timer.js' +import { planShown, withStoredWords } from './shared.js' +import { togetherItems } from './trainer.js' + +/** + * @typedef {[any, { out?: any, done?: boolean, plan?: any }]} RunWrite + * What one tap writes: the next run and the options `onRun` takes. + * @typedef {{ write: RunWrite, cursor?: string | null }} RunTap + * A write, and where the runner's cursor goes after it (absent: it stays). + */ + +/* --------------------------------------------------------------- writes */ + +const runOf = (entry) => entry?.data?.run || null +// The plan as this log's person sees it: never the owner's notes on a copy +// (lib/shared.js `planShown`, #96). A write of the plan puts them back (`withStoredWords`). +export const presOf = (entry) => planShown(entry) + +/** + * A write of the run, and the log it implies when `outputs` (a logged set changed). + * @param {any} entry @param {any} nextRun @param {{ outputs?: boolean, done?: boolean }} [opts] + * @returns {RunWrite} + */ +export function commitOf(entry, nextRun, { outputs = false, done = undefined } = {}) { + const r = reopened(nextRun, runOf(entry)) + return [r, { out: outputs ? runOutputs(presOf(entry), r, entry?.data?.out || {}) : null, done }] +} + +/** + * A write that carries its own options (a plan grown by a set, a weight's meaning). + * @param {any} entry @param {any} nextRun @param {any} opts @returns {RunWrite} + */ +export const writeOf = (entry, nextRun, opts) => [reopened(nextRun, runOf(entry)), opts] + +/** Done set: the numbers in the boxes, the log with it, on to the next. @returns {RunTap} */ +export function markTap(entry, steps, step, draft) { + const next = markSet(runOf(entry) || emptyRun(), step, draft || {}, { steps }) + return { write: commitOf(entry, next, { outputs: true }), cursor: next.cursor } +} + +/** Undo a set: off the run and the log, and the cursor on it. @returns {RunTap} */ +export const unmarkTap = (entry, setId) => ({ write: commitOf(entry, unmarkSet(runOf(entry), setId), { outputs: true }), cursor: setId }) + +/** Skip the set the runner is on. The log is untouched. @returns {RunTap} */ +export function skipTap(entry, steps, step) { + const next = skipSet(runOf(entry) || emptyRun(), step.setId, { steps }) + return { write: commitOf(entry, next), cursor: next.cursor } +} + +/** Put a skipped set back, and go to it. @returns {RunTap} */ +export const unskipTap = (entry, setId) => ({ write: commitOf(entry, unskipSet(runOf(entry), setId)), cursor: setId }) + +/** + * One more set of the one the runner is on, with the numbers in the boxes now. + * The plan grows a set at the end of the item and nothing else moves: not the + * cursor, not the draft, not the log, not the clock. @returns {RunTap} + */ +export const addSetTap = (entry, step, draft) => + ({ write: writeOf(entry, runOf(entry), { plan: withStoredWords(entry, addSetLike(presOf(entry), step.itemId, { ...step.set, ...(draft || {}) })) }) }) + +/** + * What this exercise's weight means (#58): the plan, and the log once a set of + * it is logged. The plan it changes is the one SHOWN, so the words hidden from + * a copy go back as stored (`withStoredWords`), as Add a set's do: written from + * the shown plan, the switch dropped the owner's notes from Sam's stored copy. + * @returns {RunTap} + */ +export function patchItemTap(entry, step, patch, liftField) { + const next = patchRunItem(presOf(entry), runOf(entry), step.itemId, patch, entry?.data?.out || {}, liftField) + return { write: writeOf(entry, runOf(entry), { ...next, plan: withStoredWords(entry, next.plan) }) } +} + +/** A set chosen from All sets. @returns {RunTap} */ +export const jumpTap = (entry, setId) => ({ write: commitOf(entry, goToSet(runOf(entry) || emptyRun(), setId)), cursor: setId }) + +/** Finish: the log, done and the end in ONE write. @returns {RunTap} */ +export const finishTap = (entry) => ({ write: commitOf(entry, finishRun(runOf(entry) || emptyRun()), { outputs: true, done: true }) }) + +/* The rest: an instant on the run, moved, paused, ended or taken back to the set. */ +/** @returns {RunTap} */ +export function restBackTap(entry) { + const next = restBack(runOf(entry)) + return { write: commitOf(entry, next), cursor: next.cursor } +} +/** @returns {RunTap} */ +export const restBumpTap = (entry, delta, at = Date.now()) => ({ write: commitOf(entry, bumpRest(runOf(entry), at, delta)) }) +/** @returns {RunTap} */ +export const restPauseTap = (entry, at = Date.now()) => ({ write: commitOf(entry, toggleRest(runOf(entry), at)) }) +/** @returns {RunTap} */ +export const restSkipTap = (entry) => ({ write: commitOf(entry, endRest(runOf(entry))) }) + +/* A timed set's clock (#75): `run.hold`, started, nudged, stopped, ended. */ + +/** Start: the draft's seconds, else the plan's. @returns {RunTap} */ +export function holdStartTap(entry, step, draft, at = Date.now()) { + const seconds = Number(draft?.seconds) > 0 ? draft.seconds : step.set.seconds + return { write: commitOf(entry, startHold(runOf(entry) || emptyRun(at), step.setId, seconds, at, { name: step.item.name, key: step.item.exercise || null })) } +} + +/** One of the clock's controls (`fn` from lib/timer.js: back, bump, skip, togglePause). @returns {RunTap} */ +export function holdActTap(entry, hold, program, fn, at = Date.now(), ...args) { + const run = runOf(entry) + return { write: commitOf(entry, { ...run, hold: { ...hold, timer: fn(program, settle(program, hold.timer, at), at, ...args) } }) } +} + +/** Stop the clock: nothing is logged. @returns {RunTap} */ +export const holdStopTap = (entry) => ({ write: commitOf(entry, { ...runOf(entry), hold: null }) }) + +/** + * The clock ran out: the set is marked with the seconds held. Under DONE_AFTER + * (`secs` null: a mis-tap, a look) it marks nothing and the set is as it was. + * @returns {RunTap} + */ +export function holdEndTap(entry, steps, step, draft, secs) { + const base = { ...runOf(entry), hold: null } + if (secs == null) return { write: commitOf(entry, base) } + const next = markSet(base, step, { ...(draft || {}), seconds: secs }, { steps }) + return { write: commitOf(entry, next, { outputs: true }), cursor: next.cursor } +} + +/** Skip a whole circuit (asked first): none of it is logged. @returns {RunTap} */ +export function skipCircuitTap(entry, step) { + const next = endCircuit(runOf(entry), presOf(entry), step.blockId, [], {}) + return { write: commitOf(entry, next), cursor: next.cursor } +} + +/* ------------------------------------------------------------ circuits */ + +/** + * A circuit's clock as it stands, on the run (`run.circuit`), so a closed app or + * another device comes back to the same second. Together or not, and with whom, + * is decided at Start and kept with it. + */ +export function circuitSaved(run, blockId, timer, { together = false, withIds = null } = {}) { + const base = run || emptyRun(timer.startedAt) + return { ...base, startedAt: base.startedAt || timer.startedAt, + circuit: { block: blockId, timer, ...(together ? { together: true, with: withIds } : {}) } } +} + +/** + * Every change of a circuit's clock, and what follows it. Still running: the + * clock is saved. Ended with nothing done: as if it never started (`back`). + * Ended with work done: each exercise's rounds marked (`endCircuit`, keyed by + * the clock's start so writing it twice changes nothing) and the log in the same + * write; a plan of nothing but circuits is finished and done with its last, and + * runs the next straight after (`next`). Done together, `share` is the result + * for every other side (the Together rule, lib/trainer.js). + * + * `write` is `[run | null, opts]`: a null run takes the run off the entry. + */ +export function circuitTick({ run, pres, block, program, timer, only, together = false, withIds = null }) { + if (timer.finishedAt == null) return { write: [circuitSaved(run, block.id, timer, { together, withIds }), {}] } + const done = circuitDone(program, timer) + if (!done.some(d => d.length)) { + const rest = { ...(run || {}), circuit: null } + const untouched = !Object.keys(rest.sets || {}).length && !(rest.skipped || []).length + return { write: [untouched ? null : rest, {}], back: true } + } + const at = timer.finishedAt + const seconds = timerView(program, timer, at).elapsed + const key = timer.startedAt + const next = endCircuit(run, pres, block.id, done, { at, seconds, key }) + const all = runProgress(next, prescriptionSteps(pres)).left === 0 + const then = only && !all ? nextCircuit(pres, next) : null + const write = only && all ? [finishRun(next, { at }), { outputs: true, done: true }] : [next, { outputs: true }] + const share = together ? { + block: { uid: block.uid || null, id: block.id, name: block.name }, + items: togetherItems(block), + done, at, seconds, key, ...(withIds ? { with: withIds } : {}), + } : null + return { write, ended: true, share, next: then ? then.id : null, logged: then ? null : (only && all ? 'Logged' : 'Logged on this workout') } +} + +/* ------------------------------------------------------------- the hook */ + +/** + * The runner's state and taps. `onRun(run, opts)` is the one writer; `onExit` + * leaves; `onFinish` (else `onExit`) follows a finish, so a workout with sides + * hands over to the next (`SidesWorkout`). `shown` false: a side not on screen, + * whose clock runs but which never sounds. `together`: a shared workout's + * circuit done on one clock (#68). `feedback(event, info)`: the platform's + * sounds and haptics (see the top of this file). + * + * @param {{ + * entry: any, onRun: (run: any, opts: any) => void, onExit: () => void, onFinish?: (() => void) | null, + * shown?: boolean, together?: any, liftField?: any, feedback?: (event: string, info: any) => void, + * }} args + */ +export function useRunner({ entry, onRun, onExit, onFinish = null, shown = true, together = null, liftField = null, feedback = () => {} }) { + const pres = presOf(entry) + const steps = useMemo(() => prescriptionSteps(pres), [pres]) + const run = runOf(entry) + + const [now, setNow] = useState(() => Date.now()) + const [cursor, setCursor] = useState(() => run?.cursor || firstOpen(run, steps)) + const [draft, setDraft_] = useState(/** @type {any} */ (null)) + const [listOpen, setListOpen] = useState(false) + const [muted, setMuted] = useState(false) + // The leave dialog: null, 'ask' (Keep going / Leave it open / Finish…), or + // 'finish' (finishing with sets still to do asks again). + const [leaving, setLeaving] = useState(/** @type {null | 'ask' | 'finish'} */ (null)) + const [skipping, setSkipping] = useState(false) // a whole circuit's Skip asks first + const rangAt = useRef(0) + + /* + * A circuit block (#68) runs on the interval timer's screen. A plan of nothing + * but circuits goes straight to it; in a plan with other work it is a step that + * starts when asked, and so is a shared workout's side not on screen: each + * person's clock starts on their own Start (`circuitToOpen`). A circuit that + * can be done together waits on its start screen, where that is chosen. + */ + const [circuitId, setCircuitId] = useState(() => circuitToOpen(pres, run, { shown: shown && !together?.offer })) + // Each circuit done together on this screen: its result, and what each other + // side said (null while asking). Try again asks again (lib/trainer.js). + const [shared, setShared] = useState(/** @type {{ result: any, said: any[] | null }[]} */ ([])) + // Straight on from one circuit to the next in a plan of circuits, said in its count-in. + const [chained, setChained] = useState(false) + const circuitBlock = circuitId ? (pres?.blocks || []).find(b => b.id === circuitId && b.circuit) || null : null + + const step = steps.find(s => s.setId === cursor) || steps[0] || null + const progress = runProgress(run, steps) + // The rest stands still while paused (lib/timer.js `restClock`). + const rest = restClock(run, now) + const restPaused = restPausedAt(run) != null + const elapsed = runElapsed(run, now) + const done = progress.left === 0 && progress.total > 0 + + // A timed set's clock (#75), on the run (`run.hold`), so it survives the app closing. + const hold = step ? holdOn(run, step.setId) : null + const holdProgram = useMemo( + () => (hold ? compile(holdConfig(hold.seconds, { name: step.item.name, key: step.item.exercise || null })) : null), + [hold?.seconds, step?.item?.name, step?.item?.exercise]) // eslint-disable-line react-hooks/exhaustive-deps -- the program is the hold's seconds and the exercise, not the objects holding them + const holdNow = hold ? settle(holdProgram, hold.timer, now) : null + + const info = (more = {}) => ({ muted, shown, ...more }) + const send = (/** @type {RunTap} */ tap) => { + onRun(...tap.write) + if (tap.cursor !== undefined) setCursor(tap.cursor) + } + + // A repaint tick, nothing more: every value on screen is subtracted from Date.now(). + useEffect(() => { + const iv = setInterval(() => setNow(Date.now()), 250) + return () => clearInterval(iv) + }, []) + + /* + * The rest bell: once, on the transition to zero, keyed by the deadline it + * belongs to (`rangAt`, not a boolean: a second rest of the same length must + * ring again and a re-render must not). A side not on screen rings nothing. + */ + useEffect(() => { + if (!run?.restUntil || rest > 0) return + if (rangAt.current === run.restUntil) return + rangAt.current = run.restUntil + if (!shown) return + feedback('restOver', info({ step, restUntil: run.restUntil })) + }, [rest, run?.restUntil, muted, step, shown]) // eslint-disable-line react-hooks/exhaustive-deps -- `feedback` is the platform's and may be a new function each render; the bell is keyed by the deadline + + // What is in the boxes for the set the runner is on. Recomputed when the set + // changes, never while the user is typing in it. + useEffect(() => { + if (!step) { setDraft_(null); return } + const carried = isLogged(run, step.setId) ? null : carryForward(run, steps, step) + setDraft_(carried ? { ...setDraft(run, step), ...carried } : setDraft(run, step)) + }, [cursor, step?.setId]) // eslint-disable-line react-hooks/exhaustive-deps -- the boxes follow the set, never a sync of the run while typing + + const patch = (p) => setDraft_(d => ({ ...(d || {}), ...p })) + + /** Persist run state, and the outputs it implies where they changed. */ + const commit = useCallback((nextRun, opts = {}) => onRun(...commitOf(entry, nextRun, opts)), [onRun, entry]) + + const mark = () => { + if (!step) return + feedback('mark', info()) + send(markTap(entry, steps, step, draft)) + } + const unmark = (setId) => { feedback('unmark', info()); send(unmarkTap(entry, setId)) } + const skip = () => { + if (!step) return + feedback('skip', info()) + send(skipTap(entry, steps, step)) + } + const unskip = (setId) => { feedback('unskip', info()); send(unskipTap(entry, setId)) } + const addSet = () => { + if (!step) return + feedback('addSet', info()) + send(addSetTap(entry, step, draft)) + } + const patchItem = (p) => { if (step) send(patchItemTap(entry, step, p, liftField)) } + const jump = (setId) => { + feedback('jump', info()) + send(jumpTap(entry, setId)) + setListOpen(false) + } + + const restGoBack = () => send(restBackTap(entry)) + const restBump = (n) => send(restBumpTap(entry, n, Date.now())) + const restPause = () => send(restPauseTap(entry, Date.now())) + const restSkip = () => send(restSkipTap(entry)) + + const beginHold = () => { + if (!step) return + feedback('holdStart', info()) + const at = Date.now() + send(holdStartTap(entry, step, draft, at)) + setNow(at) + } + const holdAct = (fn, ...args) => { + if (!hold) return + feedback('holdAct', info()) + const at = Date.now() + send(holdActTap(entry, hold, holdProgram, fn, at, ...args)) + setNow(at) + } + const stopHold = () => { feedback('holdStop', info()); send(holdStopTap(entry)) } + + // A hold's cues, on each change of segment (the count-in ending, the hold ending). + const heard = useRef(/** @type {any} */ (null)) + useEffect(() => { + if (!holdNow) { heard.current = null; return } + const was = heard.current + heard.current = holdNow + if (was && was.startedAt === holdNow.startedAt && moved(was, holdNow) && shown && !muted) { + const c = cueFor(holdProgram, holdNow) + if (c && c !== 'finished') feedback('cue', info({ cue: c })) + } + }) + + // The end of a hold marks the set with what was held, once per clock. + const ended = useRef(/** @type {number | null} */ (null)) + useEffect(() => { + if (!hold || holdNow?.finishedAt == null || ended.current === hold.timer.startedAt) return + ended.current = hold.timer.startedAt + const secs = heldSeconds(holdProgram, holdNow) + if (secs != null) feedback('holdEnd', info()) + send(holdEndTap(entry, steps, step, draft, secs)) + }, [holdNow?.finishedAt]) // eslint-disable-line react-hooks/exhaustive-deps -- once per clock's end, read with what is on screen then + + const finish = () => { + setLeaving(null) + feedback('finish', info()) + send(finishTap(entry)) + // With more than one side, finishing one hands over to the next (SidesWorkout). + ;(onFinish || onExit)() + } + + const skipCircuit = () => { + setSkipping(false) + send(skipCircuitTap(entry, step)) + } + + /* Circuits: the one write path for the circuit screen, and its comings and goings. */ + const circuitWrite = (next, opts) => (next ? commit(next, opts) : onRun(null, {})) + const startCircuit = (blockId) => setCircuitId(blockId) + const circuitNext = (id) => { setChained(true); setCircuitId(id) } + const circuitBack = (only) => { + setCircuitId(null) + setChained(false) + if (only) (onFinish || onExit)() + else setCursor(c => firstOpen(runOf(entry), steps) || c) + } + const shareResult = async (result) => { + const same = (x) => x.result.key === result.key && x.result.block.id === result.block.id + setShared(list => [...list.filter(x => !same(x)), { result, said: null }]) + let said + try { said = await together.write(result) } catch { said = null } + setShared(list => list.map(x => (same(x) ? { result, said: said || [] } : x))) + } + const retryShared = () => shared.filter(x => x.said?.some(y => y.status === 'missed')).forEach(x => shareResult(x.result)) + + return { + pres, steps, run, step, cursor, draft, progress, rest, restPaused, elapsed, done, now, + hold, holdProgram, holdNow, muted, setMuted, + listOpen, openList: () => setListOpen(true), closeList: () => setListOpen(false), + leaving, askLeave: () => setLeaving('ask'), askFinish: () => setLeaving('finish'), keepGoing: () => setLeaving(null), + skipping, askSkipCircuit: () => setSkipping(true), keepCircuit: () => setSkipping(false), skipCircuit, + circuitBlock, chained, shared, circuitWrite, startCircuit, circuitNext, circuitBack, shareResult, retryShared, + tick: () => setNow(Date.now()), + patch, mark, unmark, skip, unskip, addSet, patchItem, jump, + restGoBack, restBump, restPause, restSkip, beginHold, holdAct, stopHold, finish, + } +} diff --git a/mobile/src/ui/KeyboardBar.tsx b/mobile/src/ui/KeyboardBar.tsx index 772ba89..ced9506 100644 --- a/mobile/src/ui/KeyboardBar.tsx +++ b/mobile/src/ui/KeyboardBar.tsx @@ -24,6 +24,7 @@ import { colors, font, radius, space, TAP } from '../theme' import { Icon } from '../lib/icons' import { T } from './Text' import { tap } from './haptics' +import { keyboardEvents } from './sheetPolicy' /* Which field of how many has focus, from one listener however many inputs are mounted. */ let focus = { current: 0, count: 0 } @@ -54,8 +55,9 @@ const snapshot = () => focus export function useKeyboardShown() { const [shown, setShown] = useState(() => Keyboard.isVisible()) useEffect(() => { - const show = Keyboard.addListener(Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow', () => setShown(true)) - const hide = Keyboard.addListener('keyboardDidHide', () => setShown(false)) + const on = keyboardEvents(Platform.OS) + const show = Keyboard.addListener(on.show, () => setShown(true)) + const hide = Keyboard.addListener(on.hide, () => setShown(false)) return () => { show.remove(); hide.remove() } }, []) return shown diff --git a/mobile/src/ui/Sheet.tsx b/mobile/src/ui/Sheet.tsx index d68a735..aa2addb 100644 --- a/mobile/src/ui/Sheet.tsx +++ b/mobile/src/ui/Sheet.tsx @@ -41,6 +41,7 @@ import { warn } from './haptics' import { useKeyboardShown } from './KeyboardBar' import ToastHost from './ToastHost' import { SheetDirty } from './sheetDirty' +import { canSwipe as swipeAllowed, showFoot as footAllowed } from './sheetPolicy' /** The tones the CSS gives .modal.t-* / .fs.t-*: which colour the icon and the edge take. */ export const TONES: Record = { @@ -127,8 +128,8 @@ export function Modal({ const markDirty = useCallback(() => setTouched(true), []) // The toasts sit under this sheet's header, so they never cover its X. const [headH, setHeadH] = useState(0) - const canSwipe = dismissable && !touched && !typing - const showFoot = Boolean(footer) && !confirming && !typing + const canSwipe = swipeAllowed({ dismissable, touched, typing }) + const showFoot = footAllowed({ footer, confirming, typing }) const body = confirming ? ( @@ -185,7 +186,7 @@ export function Modal({ + Boolean(footer) && !confirming && !typing + +/** + * A swipe down closes the sheet only while nothing in it was changed and no box + * is being typed in. Focusing a box is not a change (`touched` comes from an + * edit, ui/sheetDirty.ts); the header's X always closes. + */ +export const canSwipe = ({ dismissable = true, touched, typing }: { dismissable?: boolean; touched: boolean; typing: boolean }) => + dismissable && !touched && !typing + +/** The runner's bottom actions (Done set, All sets, Add a set): none while the keys are up. */ +export const showActs = ({ typing }: { typing: boolean }) => !typing diff --git a/scripts/test.mjs b/scripts/test.mjs index f7a15b1..4a8bac9 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -26,7 +26,7 @@ const APP_SUITES = [ 'test:handoff', 'palette', 'test:fingers', 'test:streak', 'test:gear', 'test:progress', 'test:workout', 'test:circuit', 'test:tests', 'test:sessionops', 'test:lifts', 'test:presc', 'test:naming', 'test:md', 'test:starter', 'test:exercises', 'test:signout', 'test:whoami', 'test:shared', - 'test:trainer', 'test:drafts', 'test:planflow', 'test:editing', 'test:blockmenu', 'test:done', 'test:history', 'test:libsync', 'test:cycles', 'smoke', + 'test:trainer', 'test:drafts', 'test:planflow', 'test:editing', 'test:blockmenu', 'test:runflow', 'test:runner', 'test:native', 'test:done', 'test:history', 'test:libsync', 'test:cycles', 'smoke', ] const scripts = JSON.parse(readFileSync(join(APP, 'package.json'), 'utf8')).scripts