diff --git a/AGENTS.md b/AGENTS.md index 0730f61..f38f805 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -680,7 +680,12 @@ no rebuild. An older plan file may also carry `recommender`, `checkin`, `journal of it, and every reader goes through it: `climbVolume` (Climbs per week, `climbLine`), `lengthsIn`, `totalReps`, and the set logs' foot (`climbTotals`). The form says the rest are "not described, so not counted". A read rule: nothing stored is rewritten, and a row - whose climbs are all described reads as it always did. + whose climbs are all described reads as it always did. The rule is per EXERCISE (#111): + once a climb in any of its sets is described, every set of it with the detail on counts + its described climbs (`anyTold`; callers pass the exercise's rows), or Add set's copied + count read as climbs ("2 described, Add set, 4 routes"). The starter's Bouldering and + Rock climbing exercises declare `addSets: false`: a day of routes is one list, and Add + route is its one door. - **One climbing line everywhere** (#97): Today's row, "Last time you did this" and the Log all say `climbLine` ("5 routes · hardest 5.10"), never "1 set". A card's typed "hardest" field is left out of the form while the session has graded climbs on its ladder @@ -704,17 +709,36 @@ no rebuild. An older plan file may also carry `recommender`, `checkin`, `journal plus, on a planned entry that `isDone` and is dated on or before today, each plan lift item that no logged row with a number stands for (by uid, else by exercise), as a row in the runner's shape (holds as seconds, a circuit item once a round). So a run left - after one exercise, or one lift added by hand, covers only what it logged. On the plan's + after one exercise, or one lift added by hand, covers only what it logged. A BLANK + logged row that stands for an item (a circuit's counted exercise, `{ reps: '' }` a + round) is that item, read once, never a second exercise (#111). On the plan's own day only the sets typed into count (a plan done by one set is not every target lifted); from the next day on, every set with a number (done as written). Read, never written. A row names its exercise by `key` (`liftKeyOf` also reads an older row's `exercise`). A control that says "did this set as planned" must write `typed`: the sheet's ✓ does (`tickSet`, #79), and on a done plan's earlier day the ✓s are read, not toggled, the way `liftsDone` reads it (`setTicked(s, asWritten)`). +- **Edited is not ticked** (#111). A number typed or stepped writes `typed` (the log, + D11); a ✓ writes `typed` AND `ticked`. The ✓ shows `ticked` (`setTicked`); a set only + edited (`setEdited`) reads as logged everywhere (`setLogged`, `liftsDone`, the Today row's + "k of n sets") and is drawn with an accent ring, and a tap on it TICKS it. Only a tap on a + ticked set takes the tick off, with both marks ("I did not do this one"). Before, the two + were one mark, so "+5, lift, tap ✓" un-logged the set. A set ticked before the mark + existed carries `typed` alone and reads as edited. Doing mode folds an exercise and moves + on by ticks only (`itemTicked`), so tuning every weight first finishes nothing. Every + copy that drops `typed` drops `ticked` (`unmarked`, `withFills`, `crossingSet`, the + server's `newPlanSet`); `keepTyped` keeps both. +- **What crosses to someone else's plan** is `crossingSet` (lib/shared.js, #111): never a + weight or a note, and a lift set the owner typed into or ticked crosses BLANK (it is the + owner's log, and as a target it read on their side as lifted the next day); an untouched + target crosses as written. The server's sync carries no lift numbers at all + (`freshItem`), which `sharedsync.test.js` pins. - **What a lift's weight means is switched once per exercise** (#58; moved off the set row in #93). On a card (lift log, planner editor, doing mode; web and phone) it is one switch beside the implement (`ModeSwitch`, "on the bar ⇆"), and every flip shows - a toast with Undo (`modeFlip`); the runner keeps its 44px pill under the big weight. + a toast with Undo (`modeFlip`); the runner's is the same switch beside the implement + under the exercise's name (#111: it was a pill 6px under the big weight that flipped in + silence), and the big weight says only "lb". In a set's cell the weight says only its unit (`weightUnit`: "lb"): the switch used to be the cell's biggest target, and a tap aimed at 90 made it 90 per side. Switched when the implement has more than one meaning: dumbbell and kettlebell "per hand" / "1 DB" @@ -739,7 +763,11 @@ no rebuild. An older plan file may also carry `recommender`, `checkin`, `journal the lift log (`addLift`, or picking its implement), a new exercise in the editor (`appendLift`), each lift of a model's FIRST draft (`server/drafts.js`, which reads the person's own log as the answer lands, `rememberedModes`; - `server/drafts.test.js` holds it to the app's rule). + `server/drafts.test.js` holds it to the app's rule). A lift the model names no + implement for gets one first, as a lift added by hand does (#111): the one it had + on a revision, else `defaultImplement` (`defaultImplementOf` and + `rememberedImplements` on the server, held to the app's by the same test; the + sheet's own revise path, `reviseWeightModes`, too). - On a revision an exercise the model kept, on the same implement, keeps exactly what it had, a deliberate default included; only one new in the revision gets memory (`reviseWeightModes`; on a draft, `server/drafts.js`, so it is on the @@ -781,11 +809,16 @@ no rebuild. An older plan file may also carry `recommender`, `checkin`, `journal between the ±, its unit drawn inside it); in doing mode the ✓ is at the row's start, where the set's number is when planning, never beside the weight's +. "Last time" is in `dayWords` ("Fri, Nov 7") and, where this exercise has blank sets, a button that - fills them (`lastTimeFill`: blanks only, the weight only in the same meaning). + fills them (`lastTimeFill`: blanks only, the weight only in the same meaning; on a card + with nothing on it yet that is nobody else's, `grow` also adds the sets last time had + more of, so one tap rebuilds 3 × 10, #111). Last time is before the entry being shown + (`lastLift`, by lib/order.js `before`, the rule `priorSessions` uses), never a later day. **Copy down** (`copyDownFills`) fills the empty sets under a set with its numbers, from its own line at the row's right edge (16px clear of every stepper), with Undo ("Copied to 2 sets") that puts back only the sets still as it left them: anything - typed into or ticked since stays (`unfills`). The ✓ is 16px clear of the reps' −. Both are NUMBERS ONLY in one write + typed into or ticked since stays (`unfills`). The ✓ is 16px clear of the reps' −, and the + reps' + 8 from the weight's − (#111: at 2 they read as one strip); the number boxes gave + the width for it (40–42 wide, still 44 tall), so a set is still one row at 390. Copy down is NUMBERS ONLY in one write (`withFills`): no set added or removed, so a synced workout's structure and the other person's log are untouched, and a filled set is not `typed`: it is a target, lifted (D10, D11) only once its ✓ is ticked. A new exercise starts on `defaultImplement` @@ -1469,8 +1502,9 @@ pinned in `app/smoke/sheet.jsx` and `app/smoke/editor.jsx`: - **Doing mode** (`PrescriptionEditor doing`): a planned workout on its day or after opens on the first exercise with a set still to do (`firstUnticked`), and the next opens as it is finished. Each card is the name, the implement as one small switch, last time, and per set - reps, weight and a ✓ (`SetTick`; it writes `typed`, so it is the log, D11, and touches a - plan for today, D10). A set with no number cannot be ticked (its ✓ goes to its first box), + reps, weight and a ✓ (`SetTick`; it writes `typed` and `ticked`, so it is the log, D11, + and touches a plan for today, D10; an edited set is a ring a tap ticks, #111). A set with + no number cannot be ticked (its ✓ goes to its first box), so a ✓ always means logged. A block note is stored when its box is left (`noteDraft`). A done plan's earlier day reads as done as written (`asWritten`). A day still to come is still planning and gets the planner's editor. - **Planning is one tap away, never above the sets.** A block's Circuit switch, where it diff --git a/app/editing.dom.test.jsx b/app/editing.dom.test.jsx index bf34aed..d22361e 100644 --- a/app/editing.dom.test.jsx +++ b/app/editing.dom.test.jsx @@ -21,6 +21,8 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true const { act, useState } = await import('react') const { createRoot } = await import('react-dom/client') const { Modal, FullScreen, Popover, EDIT_SETTLE_MS } = await import('./src/modal.jsx') +const { NumInput } = await import('./src/numinput.jsx') +const { TimeInput, Stepper } = await import('./src/exercises.jsx') const tests = [] const test = (name, fn) => tests.push([name, fn]) @@ -107,6 +109,46 @@ test('both layers: a box still focused after the change keeps the footer hidden' await done() }) +test('#111 B F2: a tap on a number box selects it, so typing replaces the number (as the phone does)', async () => { + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + let got = null + let focused = 0 + function Boxes() { + const [v, setV] = useState(0) + got = v + return ( + <> + { focused += 1 }} /> + {}} /> + {}} /> + + ) + } + await act(async () => root.render()) + for (const label of ['rest', 'time', 'lb']) { + const box = host.querySelector(`input[aria-label="${label}"]`) + await act(async () => { box.focus() }) + await wait(5) + assert.equal(box.selectionStart, 0, `${label}: the caret is not at the start`) + assert.equal(box.selectionEnd, box.value.length, `${label}: "${box.value}" is not selected, so typing appends to it`) + } + assert.equal(focused, 1, 'the box\'s own onFocus no longer runs') + // "0", tapped, then 2: the box holds 2, not 20. + const rest = host.querySelector('input[aria-label="rest"]') + await act(async () => { rest.focus() }) + await wait(5) + await act(async () => { + const v = rest.value.slice(0, rest.selectionStart) + '2' + rest.value.slice(rest.selectionEnd) + Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'value').set.call(rest, v) + rest.dispatchEvent(new win.Event('input', { bubbles: true })) + }) + assert.equal(got, 2, 'tapping 0 and typing 2 stored 20') + await act(() => root.unmount()) + host.remove() +}) + let failed = 0 for (const [name, fn] of tests) { try { await fn(); console.log(` PASS ${name}`) } catch (e) { failed++; console.log(` FAIL ${name}\n ${e.message}`) } diff --git a/app/lifts.test.js b/app/lifts.test.js index 7315375..1c6b398 100644 --- a/app/lifts.test.js +++ b/app/lifts.test.js @@ -26,7 +26,7 @@ import { weightModesFor, weightModeOf, weightLabelOf, weightPatch, nextWeightMode, rememberedWeightMode, weightModeWords, liftFieldIn, weightBoxOf, liftMeasure, measureFor, muscleName, blankSet, canSwitchMeasure, liftsDone, planLifts, liftedLine, implementChoices, - lastTimeFill, lastTimeWhen, withFills, copyDownFills, canCopyDown, unfills, cardKey, cardIdentity, rememberedImplement, defaultImplement, weightUnit, weightMeaning, pickerGroupFor, + lastTimeFill, fillLift, lastTimeWhen, withFills, copyDownFills, canCopyDown, unfills, cardKey, cardIdentity, rememberedImplement, defaultImplement, weightUnit, weightMeaning, pickerGroupFor, } from './src/lib/lifts.js' import { isRepeatable, extraEntryId } from './src/lib/store.js' import { gateResolver, catalogOf as activityCatalog } from './src/lib/activities.js' @@ -1106,5 +1106,57 @@ check('#93 copy down on a lift log row: the stored shape, nothing added', () => eq(out[0].sets.length, 3, 'a row was added or removed') }) +check('#111 D F2: a circuit\'s counted exercise is one exercise in what was lifted, not two', () => { + const blank = (n) => Array.from({ length: n }, () => ({ reps: '', weight: '' })) + const e = { id: 'c', kind: 'daily', date: '2026-11-07', data: { done: true, plan: { blocks: [{ name: 'C', circuit: { work: 30, rest: 10, rounds: 2 }, items: [ + { id: 'b0i0', uid: 'u0', kind: 'lift', name: 'Bench press', exercise: 'bench-press', sets: [{ id: 'b0i0s0', reps: 10 }] }, + { id: 'b0i1', uid: 'u1', kind: 'lift', name: 'Plank', exercise: 'plank', sets: [{ id: 'b0i1s0', seconds: 30 }] }, + { id: 'b0i2', uid: 'u2', kind: 'lift', name: 'Bent-over row', exercise: 'bent-over-row', sets: [{ id: 'b0i2s0', reps: 8 }] }] }] }, + out: { lifts: [{ uid: 'b0i0', key: 'bench-press', name: 'Bench press', sets: blank(2) }, + { uid: 'b0i1', key: 'plank', name: 'Plank', sets: [{ seconds: 30, weight: '' }, { seconds: 30, weight: '' }] }, + { uid: 'b0i2', key: 'bent-over-row', name: 'Bent-over row', sets: blank(2) }] } } } + const rows = liftsDone(e, '2026-11-08') + eq(rows.map(r => r.key), ['bench-press', 'plank', 'bent-over-row'], 'a counted exercise was listed twice') + eq(rows.reduce((n, r) => n + r.sets.length, 0), 6, '3 exercises × 2 rounds is 6 sets') + eq(rows[0].sets[0].reps, 10, 'the plan\'s count is read, done as written, the next day') + // On its own day, untyped, the blank row is what there is: once, not dropped, not doubled. + const today = liftsDone({ ...e, date: '2026-11-08' }, '2026-11-08') + eq(today.filter(r => r.key === 'bench-press').length, 1) +}) + +check('#111 D F3: "last time" on an earlier day\'s sheet is never a later session', () => { + const lifted = (id, date, weight, extra = {}) => ({ id, kind: 'daily', date, ...extra, data: { done: true, out: { lifts: [{ uid: `${id}-1`, key: 'bent-over-row', name: 'Bent-over row', sets: [{ reps: 10, weight }] }] } } }) + const entries = [lifted('nov8', '2026-11-08', 40), lifted('nov7', '2026-11-07', 90), lifted('nov5', '2026-11-05', 85)] + eq(lastLift(entries, 'bent-over-row', 'nov7', liftField, null, '2026-11-08').date, '2026-11-05', 'Nov 7 said last time was Nov 8') + eq(lastLift(entries, 'bent-over-row', 'nov8', liftField, null, '2026-11-08').date, '2026-11-07', 'today\'s last time is the newest before it') + eq(lastLift(entries, 'bent-over-row', null, liftField, null, '2026-11-08').date, '2026-11-08', 'no entry, no bound') + // The same day: the session that came first is the last time of the one after it, never the reverse. + const am = lifted('daily-2026-11-08', '2026-11-08', 50, {}) + const pm = { ...lifted('daily-2026-11-08-planned', '2026-11-08', 60), data: { ...lifted('x', '2026-11-08', 60).data, slot: 'extra' } } + eq(lastLift([am, pm], 'bent-over-row', 'daily-2026-11-08', liftField, null, '2026-11-08'), null, 'the morning took the evening as its last time') + eq(lastLift([am, pm], 'bent-over-row', 'daily-2026-11-08-planned', liftField, null, '2026-11-08').date, '2026-11-08') +}) + +check('#111 C F2: "Use" on an untouched card rebuilds last time\'s sets, and only where it may add one', () => { + const prior = { date: '2026-11-01', row: { implement: 'barbell', sets: [{ reps: 10, weight: 95 }, { reps: 10, weight: 95 }, { reps: 8, weight: 100 }] } } + const card = (sets) => ({ kind: 'lift', implement: 'barbell', sets }) + const blank = [{ id: 's0', reps: null, weight: null }] + eq(lastTimeFill(liftField, card(blank), prior).length, 1, 'without grow, a fill never adds a set (a synced workout)') + const fills = lastTimeFill(liftField, card(blank), prior, { grow: true }) + eq(fills.map(f => [f.setId, Boolean(f.add), f.patch.reps, f.patch.weight]), [['s0', false, 10, 95], [null, true, 10, 95], [null, true, 8, 100]]) + // Laid onto a plan's sets: three sets, the numbers as targets, no marks. + const sets = withFills([{ id: 's0', reps: null, weight: null, unit: null, note: '' }], fills) + eq(sets.map(x => [x.reps, x.weight, x.typed ?? null]), [[10, 95, null], [10, 95, null], [8, 100, null]]) + eq(sets.slice(1).every(x => !('id' in x)), true, 'an added set took another set\'s id') + // Laid onto a logged row: three sets too. + const list = [{ uid: 'u1', key: 'back-squat', implement: 'barbell', sets: [{ reps: '', weight: '' }] }] + eq(fillLift(list, 'u1', fills.map((f, i) => (f.add ? f : { ...f, setId: String(i) })))[0].sets, [{ reps: 10, weight: 95 }, { reps: 10, weight: 95 }, { reps: 8, weight: 100 }]) + // Anything already on the card: blanks only, no set added. + eq(lastTimeFill(liftField, card([{ id: 's0', reps: 12, weight: null }, { id: 's1', reps: null, weight: null }]), prior, { grow: true }).some(f => f.add), false) + eq(lastTimeFill(liftField, card([{ id: 's0', reps: null, weight: null, typed: true }]), prior, { grow: true }).some(f => f.add), false) + // As many sets as last time already: nothing to add. + eq(lastTimeFill(liftField, card([{ id: 'a' }, { id: 'b' }, { id: 'c' }].map(x => ({ ...x, reps: null, weight: null }))), prior, { grow: true }).some(f => f.add), false) +}) + console.log(failed ? `\n${failed} lift/output test(s) failed` : '\nall lift and output tests pass') process.exit(failed ? 1 : 0) diff --git a/app/prescription.test.js b/app/prescription.test.js index b66d863..ede9ad4 100644 --- a/app/prescription.test.js +++ b/app/prescription.test.js @@ -20,7 +20,7 @@ import { splitPrescription, moveItem, isLiftOnly, blankPrescription, appendPiece, dropEmptyBlocks, patchItem, reviseWeightModes, followWeightModes, patchRunItem, measureOfItem, addBlock, renameBlock, noteBlock, removeBlock, moveBlock, tickSet, setTicked, itemTicked, firstUnticked, - patchBlock, planProgress, doingMove, + patchBlock, planProgress, doingMove, setEdited, setLogged, keepTyped, itemProgress, } from './src/lib/prescription.js' import { liftVolume, liftsIn, liftSummary, rememberedWeightMode, liftsDone } from './src/lib/lifts.js' import { createRequire } from 'node:module' @@ -796,6 +796,23 @@ t('weight mode: a finished run logs the mode with the lift', () => { assert.equal(liftsIn(runOutputs(switched, run))[0].weightMode, 'one') }) +t('#111 C F1: a lift the model names no implement for starts on the one last lifted with, and its mode', () => { + const logged = { id: 'daily-2026-09-17', kind: 'daily', date: '2026-09-17', updatedAt: 'a', + data: { out: { lifts: [{ uid: 'u1', key: 'back-squat', implement: 'barbell', weightMode: 'side', sets: [{ reps: 10, weight: 95 }] }] } } } + const opts = { today: '2026-11-08' } + const reply = normalizePrescription({ title: 'Legs', blocks: [{ name: 'Main', items: [ + { kind: 'lift', exercise: 'back-squat', sets: [{ reps: 10 }] }] }] }, { liftField }) + assert.equal(reply.blocks[0].items[0].implement || '', '', 'the fixture must leave the squat with no implement') + const got = reviseWeightModes(null, reply, liftField, [logged], opts).blocks[0].items[0] + assert.equal(got.implement, 'barbell', 'a written squat had no implement') + assert.equal(got.implementLabel, 'Barbell') + assert.equal(got.weightMode, 'side', 'the remembered mode did not follow') + // A kept exercise the model dropped the implement of keeps the one it had. + const mine = reviseWeightModes(null, normalizePrescription({ title: 'Legs', blocks: [{ name: 'Main', items: [ + { kind: 'lift', exercise: 'back-squat', implement: 'trap-bar', sets: [{ reps: 5 }] }] }] }, { liftField }), liftField, [], opts) + assert.equal(reviseWeightModes(mine, reply, liftField, [logged], opts).blocks[0].items[0].implement, 'trap-bar') +}) + t('weight mode, the rule: a revision keeps exactly what each kept exercise had; only new ones get memory', () => { const logged = { id: 'daily-2026-10-20', kind: 'daily', date: '2026-10-20', updatedAt: 'a', data: { out: { lifts: [{ uid: 'u1', key: BSS, implement: 'dumbbell', weightMode: 'one', weightLabel: 'lb · one dumbbell', sets: [{ reps: '8', weight: '25' }] }] } } } @@ -1104,9 +1121,42 @@ t('tickSet marks a set done with the typed mark, and takes it off again; numbers assert.equal(on.blocks[1].items[0].sets[1].typed, undefined, 'the tick reached another set') const off = tickSet(on, 'b1i0', 'b1i0s0', false) assert.equal('typed' in off.blocks[1].items[0].sets[0], false) + assert.equal('ticked' in off.blocks[1].items[0].sets[0], false) assert.equal(off.blocks[1].items[0].sets[0].weight, 90) - // A number typed is ticked too: the same mark. - assert.ok(setTicked(patchSet(p, 'b1i0', 'b1i0s1', { weight: 95 }).blocks[1].items[0].sets[1])) + // A number typed is logged (typed) but not ticked: an edit is not a tick (#111). + const typed = patchSet(p, 'b1i0', 'b1i0s1', { weight: 95 }).blocks[1].items[0].sets[1] + assert.equal(setTicked(typed), false, 'stepping a weight lit the set\'s ✓') + assert.ok(setEdited(typed) && setLogged(typed), 'a typed number is the log (D11)') +}) + +t('#111 A F1: tune the weight, lift, tap ✓ — the set stays logged; only a tick comes off', () => { + const p = threeBlocks() + // +5 on set 1's weight, then the tap the ✓ makes (SetTick: onToggle(!on), on = setTicked). + const edited = patchSet(p, 'b1i0', 'b1i0s0', { weight: 95 }) + const s0 = edited.blocks[1].items[0].sets[0] + const tapped = tickSet(edited, 'b1i0', 'b1i0s0', !setTicked(s0)) + const s1 = tapped.blocks[1].items[0].sets[0] + assert.equal(s1.typed, true, 'the tap after an edit un-logged the set') + assert.equal(s1.ticked, true) + assert.equal(s1.weight, 95) + assert.ok(setTicked(s1) && setLogged(s1)) + // A second tap is "I did not do this one": the tick and the log go, the numbers stay. + const off = tickSet(tapped, 'b1i0', 'b1i0s0', !setTicked(s1)).blocks[1].items[0].sets[0] + assert.equal(setLogged(off), false) + assert.equal(off.weight, 95) + // Tweaking every weight before lifting does not finish (and fold) the exercise. + const both = patchSet(edited, 'b1i0', 'b1i0s1', { weight: 95 }) + assert.equal(itemTicked(both.blocks[1].items[0]), false, 'edits alone finished the exercise') + assert.equal(firstUnticked(both), 'b1i0') + assert.equal(planProgress(both).done, 2, 'the Today row must still count edited sets as logged (D11)') + // A set ticked before the mark existed (typed alone) reads edited: logged, and a tap ticks it. + const old = { id: 'x', reps: 10, weight: 90, typed: true } + assert.ok(setEdited(old) && !setTicked(old)) + // Added sets and kept plans carry neither mark; a revision keeps the tick where it keeps the typing. + assert.equal('ticked' in addSet(tapped, 'b1i0').blocks[1].items[0].sets[2], false) + assert.equal('ticked' in dropEmptyBlocks(tapped).blocks[1].items[0].sets[0], false) + const revised = keepTyped(tapped, normalizePrescription(tapped, { liftField })) + assert.equal(revised.blocks[1].items[0].sets[0].ticked, true, 'a revision dropped the tick') }) t('firstUnticked is the first exercise with a set to do; null once every set is ticked', () => { @@ -1155,6 +1205,12 @@ t('planProgress counts ticked sets out of every set (the Today row: "4 of 18 set assert.equal(all.done, 0, 'nothing ticked yet') const one = planProgress(tickSet(p, 'b1i0', 'b1i0s0', true)) assert.deepEqual(one, { done: 1, total: all.total }) + assert.deepEqual(planProgress(patchSet(p, 'b1i0', 'b1i0s0', { weight: 95 })), { done: 1, total: all.total }, 'an edited set is logged') + // The card's "k of n done" is the same count, exercise by exercise (#111 review). + const mixed = tickSet(patchSet(patchSet(p, 'b1i0', 'b1i0s0', { weight: 95 }), 'b2i0', 'b2i0s0', { reps: 12 }), 'b1i0', 'b1i0s1', true) + const cards = mixed.blocks.flatMap(b => b.items).map(it => itemProgress(it)) + assert.deepEqual(cards.map(c => c.done), [2, 1], 'the card counted ticks only, or edits only') + assert.equal(cards.reduce((n, c) => n + c.done, 0), planProgress(mixed).done, 'the card and the Today row disagree') assert.deepEqual(planProgress(null), { done: 0, total: 0 }) }) diff --git a/app/runner.dom.test.jsx b/app/runner.dom.test.jsx index 0fa4b54..9999a0d 100644 --- a/app/runner.dom.test.jsx +++ b/app/runner.dom.test.jsx @@ -34,6 +34,7 @@ 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 { useToasts } = await import('./src/lib/toast.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')) @@ -244,7 +245,7 @@ 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 /) + const sw = byLabel(/^Weight is .*Switch to /) assert.ok(sw, 'no meaning switch on a barbell') await click(sw) const w = r.last() @@ -254,6 +255,39 @@ test("The weight's meaning: one write to the plan, the boxes untouched", async ( await r.done() }) +/** The toasts on screen, as the shell's deck would show them, each with its action as a button. */ +function Toasts() { + return
{useToasts().map(t => ( +

{t.text}{t.action && }

+ ))}
+} + +test("#111 B F1: the runner's meaning switch says what it did, with Undo, and sits by the implement, not the number", async () => { + const r = await mount(entryOf(LEGS)) + await tapText(/Log this set without the clock/) + const probe = document.createElement('div') + document.body.appendChild(probe) + const toasts = createRoot(probe) + await act(async () => toasts.render()) + const sw = byLabel(/^Weight is .*Switch to /) + assert.ok(sw.closest('.run-impl'), 'the switch is not beside the implement') + assert.equal(sw.closest('.run-inputs'), null, 'the switch is in the number boxes') + assert.deepEqual([...document.querySelectorAll('.run-inputs .bigstep-label')].map(x => x.textContent), ['reps', 'lb'], 'the big weight says more than its unit') + const before = r.state.entry.data.plan.blocks[1].items[0].weightMode ?? null + await click(sw) + const flipped = r.state.entry.data.plan.blocks[1].items[0].weightMode ?? null + assert.notEqual(flipped, before, 'the switch wrote nothing') + // The newest: an earlier case's flip may still be showing its own. + const note = [...probe.querySelectorAll('p')].filter(p => /Back squat: weight now /.test(p.textContent)).at(-1) + assert.ok(note, 'the flip was silent') + const undo = [...note.querySelectorAll('button')].find(b => /Undo/.test(b.textContent)) + assert.ok(undo, 'the flip offers no Undo') + await click(undo) + assert.equal(r.state.entry.data.plan.blocks[1].items[0].weightMode ?? null, before, 'Undo did not put the meaning back') + await act(() => toasts.unmount()) + 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 () => { diff --git a/app/shared.test.js b/app/shared.test.js index 5736a11..7576c94 100644 --- a/app/shared.test.js +++ b/app/shared.test.js @@ -6,12 +6,13 @@ import { sharePeople, sharedWithOf, sharedPeopleOn, withLine, sharedOut, hasOwnMarks, copyIdFor, sharedCopy, withSharedPerson, addPerson, removePerson, copyExercises, hasExercises, isSynced, withSync, openSide, inStep, inStepLine, shareSummary, takeOffWords, undoTakeOff, - planShown, syncedSides, ownWordsOn, withStoredWords, + planShown, syncedSides, ownWordsOn, withStoredWords, crossingSet, } from './src/lib/shared.js' import { withAck, adoptAcks } from './src/lib/store.js' import { formOut, categoryOf } from './src/lib/category.js' import { createCopyQueue, openedCopy } from './src/lib/copyqueue.js' -import { patchSet, dropEmptyBlocks, keepTyped } from './src/lib/prescription.js' +import { patchSet, dropEmptyBlocks, keepTyped, tickSet } from './src/lib/prescription.js' +import { liftsDone } from './src/lib/lifts.js' const tests = [] const test = (name, fn) => tests.push([name, fn]) @@ -701,6 +702,41 @@ test('who a removal says the exercises stay in step with, from where the sheet s assert.equal(syncedSides({ id: 'x', data: {} }, [], null), null) }) +test('#111 D F1: a set the owner typed crosses blank, by the first share and by Copy my exercises', () => { + let mine = { blocks: [{ id: 'b0', name: 'Main', items: [{ id: 'b0i0', uid: 'u1', kind: 'lift', name: 'Bench press', exercise: 'bench-press', + sets: [{ id: 'b0i0s0', reps: 8, weight: 135 }, { id: 'b0i0s1', reps: 8, weight: 135 }, { id: 'b0i0s2', reps: 8, weight: 135 }] }] }] } + mine = patchSet(mine, 'b0i0', 'b0i0s0', { reps: 10 }) + mine = tickSet(mine, 'b0i0', 'b0i0s1', true) + const owner = { id: 'daily-2026-11-08', kind: 'daily', date: '2026-11-08', data: { optId: 'planned', done: false, plan: mine } } + const TODAY = '2026-11-08' + const first = sharedCopy(owner, { owner: { id: 'owner', name: 'Alex' }, today: TODAY }).data.plan.blocks[0].items[0].sets + const empty = (o) => { const c = sharedCopy(o, { today: TODAY }); return { ...c, data: { ...c.data, plan: { blocks: [] } } } } + const copied = copyExercises(empty(owner), owner, TODAY).data.plan.blocks[0].items[0].sets + for (const [how, sets] of [['the first share', first], ['Copy my exercises', copied]]) { + assert.equal(sets[0].reps, null, `${how} carried the owner's typed 10 reps`) + assert.equal(sets[1].reps, null, `${how} carried a set the owner ticked`) + assert.equal(sets[2].reps, 8, `${how} lost an untouched target`) + assert.ok(sets.every(x => x.weight === null && !x.typed && !x.ticked), `${how} carried a weight or a mark`) + } + // So nothing of the owner's reads as theirs the next day (D11). + const theirs = { id: 'c', kind: 'daily', date: '2026-11-08', data: { done: false, plan: { blocks: [{ name: 'Main', items: [{ kind: 'lift', exercise: 'bench-press', sets: first }] }] } } } + assert.deepEqual(liftsDone(theirs, '2026-11-09').flatMap(r => r.sets.map(x => x.reps)), [8], 'only the plan\'s target reads as done as written') + // An interval's numbers are its shape, typed or not (server/sharedsync.js keeps them). + assert.equal(crossingSet('interval', { seconds: 60, typed: true }).seconds, 60) + // A plan for a LATER day: nothing is lifted yet, so a number typed there is planning + // (patchSet marks every edit) and crosses as a target (#111 review). Wednesday's Row + // set 1 edited to 6 reps on Tuesday: Sam gets 6, by either path; never the weight. + const wednesday = { ...owner, id: 'daily-2026-11-11', date: '2026-11-11' } + const later = sharedCopy(wednesday, { today: TODAY }).data.plan.blocks[0].items[0].sets + const laterCopied = copyExercises(empty(wednesday), wednesday, TODAY).data.plan.blocks[0].items[0].sets + for (const [how, sets] of [['the first share', later], ['Copy my exercises', laterCopied]]) { + assert.deepEqual(sets.map(x => x.reps), [10, 8, 8], `${how} blanked a planned target on a later day`) + assert.ok(sets.every(x => x.weight === null && !x.typed && !x.ticked), `${how} carried a weight or a mark`) + } + // The same workout once its day has come is the owner's log again. + assert.equal(sharedCopy(wednesday, { today: '2026-11-11' }).data.plan.blocks[0].items[0].sets[0].reps, null) +}) + for (const [name, fn] of tests) { try { await fn(); console.log(` ok ${name}`) } catch (err) { failed++; console.log(` FAIL ${name}\n ${err.message}`) } } diff --git a/app/smoke/editor.jsx b/app/smoke/editor.jsx index 6d55979..041517a 100644 --- a/app/smoke/editor.jsx +++ b/app/smoke/editor.jsx @@ -17,7 +17,7 @@ import { PRIOR_LIFTS, HELD_CARD, HELD_FIELD, HELD_ENTRY, } from './fixtures.jsx' -import { removeItem, appendLift } from '../src/lib/prescription.js' +import { removeItem, appendLift, planProgress } from '../src/lib/prescription.js' import { lastTimeFill } from '../src/lib/lifts.js' /* Walk a component's returned element tree (no render): what it hands its children. */ @@ -609,6 +609,24 @@ export default [ if (!/implswitch/.test(meta) || !/modeswitch/.test(meta)) throw new Error('the meaning is not beside what it is done with') const css = readFileSync(new URL('../src/css/editor.css', import.meta.url), 'utf8') if (!/\.presc-sets\.doing \.presc-set \{ gap: var\(--sp-4\); \}/.test(css)) throw new Error('the ✓ is not 16px clear of the reps’ −') + // …and the row still fits 390's 330: ✓ 44 + 16 + two steppers of 130 + the 8px seam. + if (!/\.presc-sets\.doing \.presc-setfields > \.stepper \{ flex-basis: calc\(3 \* var\(--tap\) - 2px\); \}/.test(css)) throw new Error('the doing steppers grew: redo the 390 sum') + // The reps' + and the weight's − are two controls, 8px apart, not one strip (#111). + if (!/\.presc-sets\.doing \.presc-setfields \{ gap: var\(--sp-2\); \}/.test(css)) throw new Error('the reps’ + and the weight’s − are under 8px apart') + }], + // The card's head and the Today row count the same sets (#111 review): an edited + // set is in the log (D11), so set 1 stepped and set 2 ticked is "2 of 3 done". + ['ExerciseCard(doing: the head counts edited and ticked sets, as the Today row does)', null, () => { + const item = { id: 'b0i0', uid: 'u-row', kind: 'lift', name: 'Bent-over row', exercise: 'bent-over-row', implement: 'ez-bar', + weightLabel: 'lb on the bar', line: '3 × 10', sets: [ + { id: 's0', reps: 10, weight: 95, typed: true }, + { id: 's1', reps: 10, weight: 90, typed: true, ticked: true }, + { id: 's2', reps: 10, weight: 90 }] } + const html = renderToString() + if (!/2 of 3 done/.test(html)) throw new Error('the card head does not count the edited set') + if (planProgress({ blocks: [{ items: [item] }] }).done !== 2) throw new Error('the Today row counts differently') + if (!/class="presc-tick edited"/.test(html) || !/class="presc-tick on"/.test(html)) throw new Error('the edited and ticked looks are not both drawn') }], ['modeFlip(one tap writes the next meaning and offers Undo, which writes the old one back)', null, () => { const item = { kind: 'lift', name: 'Bent-over row', implement: 'ez-bar', weightLabel: 'lb on the bar' } diff --git a/app/smoke/runner.jsx b/app/smoke/runner.jsx index b347cad..46d531d 100644 --- a/app/smoke/runner.jsx +++ b/app/smoke/runner.jsx @@ -66,18 +66,20 @@ export default [ throw new Error('the weight box is not a text box, so a decimal point will not survive typing') } }], - /* The runner has the same switch, a full 44px, on the plan item (#58). */ - ['WorkoutRunner(a dumbbell lift: the weight label is the switch)', , (html) => { - if (!/]*class="bigstep-label stepper-swap"/.test(html)) throw new Error('the runner has no weight switch') - if (!/Switch to lb per hand/.test(html)) throw new Error('the runner switch does not say what a tap does') - const box = (html.match(/class="bigstep-label stepper-swap"[^>]*>(.*?)<\/button>/) || [])[1] || '' - if (box.replace(/<[^>]+>/g, '').replace(//g, '').trim() !== '1 DB') throw new Error(`the runner's box says "${box.replace(/<[^>]+>/g, '').replace(//g, '').trim()}"`) + const impl = (html.match(/
([\s\S]*?)<\/div>/) || [])[1] || '' + if (!/]*class="modeswitch"[^>]*aria-label="Weight is lb · one dumbbell\. Switch to lb per hand"/.test(impl)) throw new Error('the runner has no meaning switch beside the implement') + if (/stepper-swap/.test(html)) throw new Error('the meaning switch is back under the big weight') + if ((html.match(/Switch to/g) || []).length !== 1) throw new Error('a second meaning switch is on the set screen') + if (!/lb<\/span>/.test(html)) throw new Error('the big weight does not say its unit') if (!/25 lb · one dumbbell/.test(text(html))) throw new Error('the target does not say one dumbbell') }], ['WorkoutRunner(a machine lift: no switch)', { + for (const id of ['climb-bouldering', 'climb-routes']) { + const html = renderToString( m.id === id)} out={{}} onSave={noop} />) + if (/Add set/.test(html)) throw new Error(`${id} offers Add set beside Add route`) + } + const bouts = renderToString( m.id === 'fun-boulder')} out={{}} onSave={noop} />) + if (!/Add set/.test(bouts)) throw new Error('a card that does not say addSets: false lost Add set') + }], // "Pre-filled from the plan" only where the plan filled something in (#97 review): // the starter's Bouldering card has no default count and opens on an empty box. ['SetLog(the pre-filled note only when the plan pre-fills)', null, () => { diff --git a/app/smoke/system.jsx b/app/smoke/system.jsx index c9c6b95..0664537 100644 --- a/app/smoke/system.jsx +++ b/app/smoke/system.jsx @@ -207,9 +207,13 @@ export default [ const stepper = 2 + 2 * TAP + row.mid const need = row.tick + row.tickGap + 2 * stepper + row.seam if (need > inside) throw new Error(`a set needs ${need}pt of ${inside}: it wraps onto two rows`) - if (row.tick < 44 || row.mid < 44) throw new Error('the ✓ or the number is under 44') - // The ✓ 16 clear of the reps' −, so a left-thumb miss on − never ticks (#93 review). + // The number box is 44 tall and gave 2 of its width for the seam (#111): never under 40. + if (row.tick < 44 || row.mid < 40) throw new Error('the ✓ is under 44, or the number box under 40 wide') + // The ✓ 16 clear of the reps' −, so a left-thumb miss on − never ticks (#93 review), + // and the two steppers 8 apart, so the reps' + and the weight's − are two + // controls, not one strip (#111). if (row.tickGap < 16) throw new Error(`the ✓ is ${row.tickGap}pt from the reps' −`) + if (row.seam < 8) throw new Error(`the reps' + is ${row.seam}pt from the weight's −`) // Copy down on its own line at the right edge, 16 clear of the rows above and below. if (!/copyDown: \{ alignSelf: 'flex-end'[^}]*marginVertical: space\[2\]/.test(src) || !/sets: \{ gap: space\[2\]/.test(src)) throw new Error('Copy down is back beside a stepper column') // The card is keyed by the exercise, from the same lib function the web tests (#93, A F1). diff --git a/app/src/css/editor.css b/app/src/css/editor.css index 7a5c3f0..54014c5 100644 --- a/app/src/css/editor.css +++ b/app/src/css/editor.css @@ -214,26 +214,6 @@ font-size: var(--fs-label); color: var(--ink-dim); line-height: 1; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -/* What a lift's weight means, switched on its own label (#58): now only the - runner's (`BigStepper`, a full 44px pill on its own line below). The card's is - `.modeswitch`, once per exercise (#93): in a set's cell it was the cell's - biggest target and a tap aimed at the number flipped what it meant. */ -.stepper-swap { - position: relative; display: inline-block; max-width: 64px; - padding: var(--sp-1) var(--sp-1); margin-top: 2px; - background: var(--panel-3); border: 1px solid var(--line-strong); border-radius: var(--r-control); - color: var(--ink-dim); font: inherit; font-size: var(--fs-label); line-height: 1.2; - text-align: center; cursor: pointer; -} -.stepper-swap-end { white-space: nowrap; } -.stepper-swap svg { vertical-align: -1px; margin-left: 2px; } -.stepper-swap::after { content: ''; position: absolute; inset: -2px -10px -12px; } -.stepper-swap:hover, .stepper-swap:active { color: var(--ink); } -.bigstep .stepper-swap { - max-width: none; min-height: var(--tap); padding: 0 var(--sp-4); border-radius: var(--r-pill); - font-size: var(--fs-label); white-space: nowrap; -} -.bigstep .stepper-swap::after { display: none; } .expick { border: 1px solid var(--line); border-radius: var(--r-control); overflow: hidden; } .expick-head { display: flex; gap: var(--sp-2); padding: var(--sp-2); border-bottom: 1px solid var(--line); } @@ -366,9 +346,12 @@ /* Reps and weight still share one row at 390px with 44px boxes: reps is two digits and keeps its basis, the weight takes the spare width. */ .presc-sets.doing .presc-set { gap: var(--sp-4); } -/* 44 + 16 + 134 + 2 + 134 = 330, a 390 phone's whole row: the pair is two - steppers, so 2px between them is a seam inside one control. */ -.presc-sets.doing .presc-setfields { gap: 2px; } +/* The reps' + and the weight's −, the two most-pressed controls, 8px apart + (#111): at 2px they read as one strip, and a slip did the opposite thing to the + other number. The number boxes give the width for it, not the ✓'s 16: + 44 + 16 + 130 + 8 + 130 = 328 of a 390 phone's 330, the weight's box taking the + last 2 (reps 40 wide, weight 42; both 44 tall, between two 44px buttons). */ +.presc-sets.doing .presc-setfields { gap: var(--sp-2); } /* Copy down (#93): its own quiet line under the set it copies, at the row's right edge, 16px clear of every stepper above and below (the grid's 8 and its own 8), and nowhere near a ✓. At the steppers' left it sat 9px from two reps' +: a low @@ -377,7 +360,8 @@ justify-self: end; min-height: var(--tap); padding: 0 var(--sp-3); margin: var(--sp-2) 0; font-size: var(--fs-label); color: var(--ink-dim); } -.presc-sets.doing .presc-setfields > .stepper { flex-basis: calc(3 * var(--tap) + 2px); } +.presc-sets.doing .presc-setfields > .stepper { flex-basis: calc(3 * var(--tap) - 2px); } +.presc-sets.doing .presc-setfields > .stepper .stepper-mid { min-width: calc(var(--tap) - 4px); } .presc-sets.doing .presc-setfields > .stepper:first-child:not(:last-child) { flex-grow: 0; } .presc-tick { flex: 0 0 auto; width: var(--tap); height: var(--tap); display: grid; place-items: center; @@ -385,6 +369,8 @@ color: var(--ink-dim); font: inherit; font-size: var(--fs-label); font-variant-numeric: tabular-nums; cursor: pointer; } .presc-tick.on { background: var(--accent-soft); border-color: var(--accent-line); color: var(--ink); } +/* Edited (#111): a number typed or stepped is logged (D11) but not ticked; a tap ticks it. */ +.presc-tick.edited { border: 2px solid var(--accent-line); color: var(--ink); } .presc-tickn { line-height: 1; } .presc-tick.locked { cursor: default; border-style: dashed; } /* Not `.empty`: that is the empty-state component, whose padding made a blank set's ✓ 50×66 and wrapped its row (#93). */ diff --git a/app/src/css/runner.css b/app/src/css/runner.css index d4ac242..2bb9f2d 100644 --- a/app/src/css/runner.css +++ b/app/src/css/runner.css @@ -50,7 +50,9 @@ .run-addset:active { transform: translateY(1px); } .run-move { margin: var(--sp-3) 0 2px; font-size: var(--fs-screen); line-height: var(--lh-tight); font-weight: 600; } -.run-impl { font-size: var(--fs-label); color: var(--ink-dim); } +/* The implement, and what its weight means as the sheet's switch (#111): under + the name, a screen's height from the big weight's number. */ +.run-impl { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: var(--sp-2); font-size: var(--fs-label); color: var(--ink-dim); } /* What was asked for, always on screen and never in the box. The distinction is the whole model: `data.plan` is the target, `data.run` is what happened. */ diff --git a/app/src/editor.jsx b/app/src/editor.jsx index 6397e08..c26180d 100644 --- a/app/src/editor.jsx +++ b/app/src/editor.jsx @@ -543,6 +543,7 @@ export function PrescriptionEditor({ onPatchSet={(id, setId, patch) => onChange(patchSet(pres, id, setId, patch))} /* "Use last time" (#93): the numbers as targets, in one write, never ticked. */ onFill={(id, fills) => onChange(patchItem(pres, id, { sets: withFills(itemOf(id)?.sets, fills) }))} + growFill={!syncedWith?.length} onAddSet={(id) => onChange(addSet(pres, id))} onRemoveSet={dropSet} onRemove={dropItem} diff --git a/app/src/exercises.jsx b/app/src/exercises.jsx index 7866617..60581c9 100644 --- a/app/src/exercises.jsx +++ b/app/src/exercises.jsx @@ -32,16 +32,16 @@ import { Fragment, useEffect, useMemo, useRef, useState } from 'react' import { Icon } from './lib/icons.jsx' -import { NumInput } from './numinput.jsx' +import { NumInput, selectOnFocus } from './numinput.jsx' import { setFieldsFor, measureOfItem, timeBox, bumpTime } from './lib/prescription.js' import { acceptMinutesText, minutesText, numOrNull } from './lib/numtext.js' import { searchExercises, implementsFor, lastLift, catalogOf, exerciseOf, muscleName, measureFor, - weightModesFor, weightPatch, nextWeightMode, rememberedWeightMode, weightModeWords, weightBoxOf, + weightModesFor, weightPatch, nextWeightMode, rememberedWeightMode, weightModeWords, implementChoices, implementLabel, weightModeOf, weightMeaning, weightUnit, lastTimeFill, lastTimeWhen, pickerGroupFor, copyDownFills, canCopyDown, unfills, cardIdentity, cardKey, } from './lib/lifts.js' -import { setTicked, itemTicked, setHasNumber, doingMove } from './lib/prescription.js' +import { setTicked, setEdited, itemTicked, itemProgress, setHasNumber, doingMove } from './lib/prescription.js' import { ExerciseBody, BodyMap, musclesOf, muscleWords } from './lib/bodymap.jsx' import { HowBody } from './howto.jsx' import { Popover } from './modal.jsx' @@ -56,7 +56,7 @@ import { Explain } from './blurb.jsx' * plate and a length are; one rep and five seconds because that is what those * are. The weight's label comes off the IMPLEMENT — "30 lb per hand" and * "135 lb on the bar" are different numbers and the box has to say which — and - * the mode the user switched it to (`weightSwitch`). + * the mode the user switched it to (`modeFlip`). */ export const STEP = { reps: () => ({ label: 'reps', step: 1, min: 0 }), @@ -103,7 +103,7 @@ export function stepBox({ step = 1, min = null, max = null, time = false }, valu * A minutes box over seconds (#78): `NumInput`'s rules for "45", "1.5" and * "1:40" (lib/numtext.js `acceptMinutesText`); it shows "1:40", never "1.67". */ -export function TimeInput({ value, onChange, blank = null, placeholder = '—', ...rest }) { +export function TimeInput({ value, onChange, blank = null, placeholder = '—', onFocus, ...rest }) { const shown = minutesText(value) const [text, setText] = useState(shown) const last = useRef(numOrNull(value)) @@ -122,21 +122,10 @@ export function TimeInput({ value, onChange, blank = null, placeholder = '—', const ph = numOrNull(placeholder) === null ? placeholder : minutesText(placeholder) return ( setText(shown)} {...rest} /> + onChange={change} onBlur={() => setText(shown)} onFocus={selectOnFocus(onFocus)} {...rest} /> ) } -/** - * The tap that changes what a lift's weight means (issue #58), or null where - * its implement has one meaning. Hands the stepper the label to show as a - * button and what one tap does; the same for the editor, the log and the runner. - */ -export function weightSwitch(liftField, item, onPatch) { - if (item?.kind !== 'lift' || weightModesFor(liftField, item.implement).length < 2) return null - const next = weightPatch(liftField, item.implement, nextWeightMode(liftField, item)) - return { box: weightBoxOf(liftField, item), next: next.weightLabel, onSwitch: () => onPatch(next) } -} - /** * What tapping an implement chip writes: the implement, in the mode this * exercise was last logged in with it (lib/lifts.js). Null for the chip already @@ -172,18 +161,6 @@ export function countSwitch(liftField, item, onPatch) { } } -/** A switch's words, the last one held to the swap mark so a wrap never strands it. */ -export function SwapWords({ label, size }) { - const words = String(label).split(' ') - const last = words.pop() - return ( - <> - {words.length ? `${words.join(' ')} ` : ''} - {last} - - ) -} - /** * One number, moved with thumbs. * @@ -251,10 +228,10 @@ export function modeFlip(liftField, item, write, toast = { push: pushToast, dism /** * The card's one switch for what its weight means (#93; #58's switch, moved * out of every set's cell): "on the bar ⇆", once per exercise, beside what it - * is done with. A hold's "seconds ⇆" is the same kind of switch and sits here + * is done with; the runner's too, under the name (#111). A hold's "seconds ⇆" is the same kind of switch and sits here * too. With one meaning the words are said, not offered. */ -function ModeSwitch({ words, aria, onSwitch }) { +export function ModeSwitch({ words, aria, onSwitch }) { if (!onSwitch) return {words} return ( ) } + const look = on ? 'on' : edited ? 'edited' : '' return ( - ) @@ -569,7 +552,7 @@ export function SetTick({ n, on, onToggle, locked = false, empty = false, onProm export function ExerciseCard({ item, liftField, entries = [], entryId = null, defaultOpen = false, defaultEditing = false, blank = null, onPatch, onPatchSet, onAddSet, onRemoveSet, onRemove, doing = false, onTick = null, focus = false, - asWritten = false, onFill = null, + asWritten = false, onFill = null, growFill = false, }) { const [open, setOpen] = useState(defaultOpen) const [about, setAbout] = useState(false) @@ -623,7 +606,8 @@ export function ExerciseCard({ // stays short enough not to squeeze the name on a phone. const modeWords = item.kind === 'lift' ? weightModeWords(liftField, item) : null const ticking = doing && onTick - const ticks = ticking ? item.sets.filter(s => setTicked(s, asWritten)).length : 0 + // In the log, ticked or edited: the Today row's count too (`itemProgress`, #111). + const ticks = ticking ? itemProgress(item, asWritten).done : 0 const finished = ticking && itemTicked(item, asWritten) const line = ticking && ticks && !finished ? [`${ticks} of ${item.sets.length} done`, item.line].filter(Boolean).join(' · ') @@ -641,7 +625,7 @@ export function ExerciseCard({ const t = setTimeout(() => root.current?.scrollIntoView?.({ block: 'start', behavior: 'smooth' }), 60) return () => clearTimeout(t) }, [finished, focus, ticking]) - const fill = onFill && prior && !asWritten ? lastTimeFill(liftField, item, prior) : [] + const fill = onFill && prior && !asWritten ? lastTimeFill(liftField, item, prior, { grow: growFill }) : [] const copyDown = onFill && !asWritten ? (s) => copyDownWrite(item, s.id, (f) => fillNow.current?.(f), undefined, () => itemNow.current) : null const lastTime = prior && onFill(fill) : null} /> /* What the weight means and how a hold is counted: once, on the card, beside @@ -761,7 +745,7 @@ export function ExerciseCard({
{ticking ? onTick(s.id, v)} - empty={!setHasNumber(s)} + empty={!setHasNumber(s)} edited={setEdited(s)} onPrompt={(e) => e.currentTarget.closest('.presc-set')?.querySelector('input')?.focus()} /> : {i + 1}} @@ -939,7 +923,7 @@ export function ExerciseSection({ title, count, items, liftField, entries = [], entryId = null, firstOpenId = null, blank = null, addLabel = 'Add an exercise here', open = true, onToggle = null, - onPatch, onPatchSet, onAddSet, onRemoveSet, onRemove, onFill = null, + onPatch, onPatchSet, onAddSet, onRemoveSet, onRemove, onFill = null, growFill = false, onMove = null, onAdd = null, extra = null, foot = null, note = null, menu = null, tag = null, lead = null, doing = false, onTick = null, focusId = null, asWritten = false, }) { @@ -1034,7 +1018,7 @@ export function ExerciseSection({ onAddSet={() => onAddSet(it.id)} onRemoveSet={(setId) => onRemoveSet(it.id, setId)} onRemove={() => onRemove(it.id)} - onFill={onFill ? (fills) => onFill(it.id, fills) : null} /> + onFill={onFill ? (fills) => onFill(it.id, fills) : null} growFill={growFill} /> )) )} diff --git a/app/src/lib/grades.js b/app/src/lib/grades.js index 236a6b0..ed19241 100644 --- a/app/src/lib/grades.js +++ b/app/src/lib/grades.js @@ -467,19 +467,31 @@ function toldOf(row) { return told } -/** How many climbs this row counts: the described ones once any is, else its count. */ -export function climbsCounted(row) { +/** + * Does any row of this exercise have a described climb? Then the described + * climbs are the count in EVERY row of it with the detail on (#111, E F1): Add + * set copies the last row's count into a new row of blank records, and counted + * by its own `reps` that row passed for climbs ("2 described, Add set, 4 routes"). + * A row is not a session of its own; the exercise is one list of climbs. + */ +export const anyTold = (rows) => Array.isArray(rows) && rows.some(r => Array.isArray(r?.[CLIMB_FIELD]) && toldOf(r).length > 0) + +/** + * How many climbs this row counts: the described ones once any is (in this row, + * or in another row of the same exercise, `rows`), else its count. + */ +export function climbsCounted(row, rows = null) { const reps = Math.max(0, Math.floor(Number(row?.reps) || 0)) if (!Array.isArray(row?.[CLIMB_FIELD])) return reps const told = toldOf(row).length - return told > 0 ? told : reps + return told > 0 || anyTold(rows) ? told : reps } -/** Climbs in the row's list nobody has described, while others are: not counted. */ -export function untoldIn(row) { +/** Climbs in the row's list nobody has described, while others are (here or elsewhere in `rows`): not counted. */ +export function untoldIn(row, rows = null) { if (!Array.isArray(row?.[CLIMB_FIELD])) return 0 const told = toldOf(row).length - return told > 0 ? climbCount(row?.reps) - told : 0 + return told > 0 || anyTold(rows) ? climbCount(row?.reps) - told : 0 } /** @@ -489,7 +501,7 @@ export function untoldIn(row) { */ export function climbTotals(rows) { const list = rows || [] - const count = list.reduce((s, r) => s + climbsCounted(r), 0) + const count = list.reduce((s, r) => s + climbsCounted(r, list), 0) const said = climbsIn(list).filter(climbSaid) return { count, @@ -497,7 +509,7 @@ export function climbTotals(rows) { falls: fallsIn(list), downs: downsIn(list), lengths: lengthsIn(list), - untold: list.reduce((s, r) => s + untoldIn(r), 0), + untold: list.reduce((s, r) => s + untoldIn(r, list), 0), } } @@ -532,7 +544,7 @@ export const downsIn = (rows) => climbsIn(rows).filter(c => c.down === 'both' || */ export function lengthsIn(rows) { return (rows || []).reduce((sum, r) => { - const n = climbsCounted(r) + const n = climbsCounted(r, rows) const list = Array.isArray(r?.[CLIMB_FIELD]) ? r[CLIMB_FIELD] : [] const extra = list.filter(c => c?.down === 'both').length return sum + n + extra @@ -703,7 +715,8 @@ export function climbVolume(opt, out) { let n = 0 for (const ex of exercisesOf(opt)) { if (!countsClimbs(ex)) continue - for (const r of out?.sets?.[ex.key] || []) n += climbsCounted(r) + const rows = out?.sets?.[ex.key] || [] + for (const r of rows) n += climbsCounted(r, rows) } return n } diff --git a/app/src/lib/history.js b/app/src/lib/history.js index 46216b9..e1eb0fc 100644 --- a/app/src/lib/history.js +++ b/app/src/lib/history.js @@ -21,6 +21,7 @@ import { liftsDone, liftKeyOf } from './lifts.js' import { isDone } from './store.js' +import { before } from './order.js' /** * Which optIds count as "this session", for history. @@ -70,38 +71,6 @@ export function samePlanned(entry, e) { return sameExercises(exercisesOf(entry), exercisesOf(e)) } -/** - * Where an entry sits in its day, as the day list shows it (tabs.jsx): the main - * session first, then the extras by id. - */ -const dayPlace = (e) => [e?.data?.slot === 'extra' ? 1 : 0, String(e?.id || '')] - -/** - * When a session started, in ms, where something measured or stamped it: its - * run, the WHOOP or Strava workout attached to it, then its done tap. Null when - * nothing did (a lift typed on the sheet): a day carries no other clock. - */ -function startedAt(e) { - const d = e?.data || {} - for (const v of [d.run?.startedAt, d.out?.whoop?.start, d.out?.strava?.start, d.doneAt]) { - const t = typeof v === 'number' ? v : Date.parse(v) - if (Number.isFinite(t) && t > 0) return t - } - return null -} - -/** - * Is `e` before `me`: an earlier day, or earlier the same day, by when each - * started where both say, else by the day list's order. - */ -function before(e, me) { - if (String(e.date) !== String(me.date)) return String(e.date) < String(me.date) - const [ta, tb] = [startedAt(e), startedAt(me)] - if (ta !== null && tb !== null && ta !== tb) return ta < tb - const [a, b] = [dayPlace(e), dayPlace(me)] - return a[0] !== b[0] ? a[0] < b[0] : a[1] < b[1] -} - /** * Every time you DID this workout (`isDone`: not a plan still to come, not one * marked undone) BEFORE the one being shown, newest first, that one left out. diff --git a/app/src/lib/lifts.js b/app/src/lib/lifts.js index c6ef2be..1bc1e03 100644 --- a/app/src/lib/lifts.js +++ b/app/src/lib/lifts.js @@ -33,6 +33,7 @@ import { localIso, dayWords } from './dates.js' import { isDone } from './store.js' +import { before } from './order.js' export const LIFT_FIELD = 'lifts' @@ -525,11 +526,18 @@ export function liftsDone(entry, today = localIso()) { for (const b of plan.blocks) { for (const it of Array.isArray(b?.items) ? b.items : []) { if (it?.kind !== 'lift') continue - // Only a row with a number stands for an item: a blank one hides nothing. + // A row with a number logged for an item is that item's log. const by = logged.find(l => !used.has(l) && (l?.sets || []).some(numbered) && standsFor(l, it)) if (by) { used.add(by); rows.push(by); continue } const row = itemRow(b, it, typedOnly) - if (row) rows.push(row) + // A BLANK row for it (a circuit's counted exercise, written `{ reps: '' }` + // a round for them to fill in, §6.5) hides nothing the plan says, but it + // is still this item, never a second exercise (#111, D F2: 3 exercises × 2 + // rounds read "4 exercises · 8 sets"). The item is read once: its sets + // where they count, else the blank row, as before. + const blankBy = logged.find(l => !used.has(l) && standsFor(l, it)) + if (blankBy) used.add(blankBy) + if (row || blankBy) rows.push(row || blankBy) } } return [...rows, ...logged.filter(l => !used.has(l))] @@ -847,13 +855,20 @@ export const liftedLine = (entry, field = null, today = localIso()) => liftsLine * as much as a logged row (D11). `measure` keeps a hold's last time to holds: sixty * reps of an old Plank is not a number to beat in seconds. * + * BEFORE the entry being edited (#111, D F3), by the rule "The last 5 times you + * did this" uses (lib/order.js `before`): a sheet opened on Nov 7 said "Last + * time · Today", and its Use filled Nov 7's blanks from Nov 8. An entry not in + * `entries` yet (nothing to compare) is not bounded, as there. + * * @param {any[]} entries @param {string} key @param {string | null} [excludeId] @param {any} [field] * @param {'reps' | 'time' | null} [measure] @param {string} [today] */ export function lastLift(entries = [], key, excludeId = null, field = null, measure = null, today = localIso()) { const hits = [] + const me = excludeId ? entries.find(e => e?.id === excludeId) : null for (const e of entries) { if (e?.deleted || e?.kind !== 'daily' || e.id === excludeId) continue + if (me?.date && !before(e, me)) continue for (const l of liftsDone(e, today)) { if (liftKeyOf(l) !== key) continue if (measure && liftMeasure(l, field) !== measure) continue @@ -873,15 +888,24 @@ export const lastTimeWhen = (prior, today = localIso()) => (prior?.date ? dayWor /** * What "use last time" writes (#93): last time's numbers into this exercise's * BLANK boxes, set by set (set 3 takes last time's set 3, or its last set when - * it had fewer), as `[{ setId, patch }]`. It never overwrites a number, never - * adds a set, and fills the weight only when it means the same thing as last - * time (the same implement in the same mode): 90 lb per side is not 90 lb on - * the bar. Empty when there is nothing to fill, which is when the line stops - * being a button. + * it had fewer), as `[{ setId, patch }]`. It never overwrites a number, and + * fills the weight only when it means the same thing as last time (the same + * implement in the same mode): 90 lb per side is not 90 lb on the bar. Empty + * when there is nothing to fill, which is when the line stops being a button. + * + * `grow` (#111, C F2): "Use" said "3 × 10 @ 95 lb" and wrote 1 × 10, because a + * new exercise has one blank set. On a card where nothing is filled in yet + * (no number, no mark on any set), it also adds the sets last time had more + * of, as `{ add: true, patch }` fills after the others, in order; writers lay + * them on with `withFills` (a plan) or `fillLift` (the log). The caller says + * when adding a set is its to do: never on a synced workout, where a set added + * is structure that crosses to the other person. * * `item` is the card's (exercises.jsx): `{ kind, implement, weightMode, sets: [{ id, … }] }`. + * + * @param {any} field @param {any} item @param {any} prior @param {{ grow?: boolean }} [opts] */ -export function lastTimeFill(field, item, prior) { +export function lastTimeFill(field, item, prior, { grow = false } = {}) { const rows = (prior?.row?.sets || []).filter(r => num(r?.reps) !== null || num(r?.seconds) !== null || num(r?.weight) !== null) if (item?.kind !== 'lift' || !rows.length) return [] const row = prior.row @@ -889,13 +913,33 @@ export function lastTimeFill(field, item, prior) { && weightModeOf(field, item) === weightModeOf(field, row) const count = liftMeasure(row, field) === 'time' ? 'seconds' : 'reps' const blank = (v) => v === null || v === undefined || v === '' - return (item.sets || []).flatMap((s, i) => { + const sets = item.sets || [] + const fills = sets.flatMap((s, i) => { const from = rows[i] || rows.at(-1) const patch = {} if (count in s && blank(s[count]) && num(from[count]) !== null) patch[count] = num(from[count]) if ('weight' in s && blank(s.weight) && sameLoad && num(from.weight) !== null) patch.weight = num(from.weight) return Object.keys(patch).length ? [{ setId: s.id, patch }] : [] }) + const untouched = sets.length > 0 && sets.every(s => !holdsNumber(s) && s?.typed !== true && s?.ticked !== true) + if (!grow || !untouched || rows.length <= sets.length) return fills + const added = rows.slice(sets.length).flatMap(from => { + const patch = {} + if (num(from[count]) !== null) patch[count] = num(from[count]) + if (sameLoad && num(from.weight) !== null) patch.weight = num(from.weight) + return Object.keys(patch).length ? [{ setId: null, add: true, patch }] : [] + }) + return [...fills, ...added] +} + +/** "Use last time"'s fills (`lastTimeFill`) on a logged lift row (`out.lifts`), added sets included. */ +export function fillLift(list, uid, fills = []) { + return fills.reduce((l, f) => { + if (!f.add) return setLiftSet(l, uid, Number(f.setId), f.patch) + const grown = addLiftSet(l, uid) + const n = liftsIn({ [LIFT_FIELD]: grown }).find(x => x.uid === uid)?.sets?.length || 0 + return setLiftSet(grown, uid, n - 1, f.patch) + }, list) } /** @@ -905,12 +949,17 @@ export function lastTimeFill(field, item, prior) { * D11). Any old mark on it goes; a patch that says `typed` (an Undo putting a * set back exactly) keeps its own. */ -export const withFills = (sets = [], fills = []) => sets.map(s => { - const f = fills.find(x => x.setId === s.id) - if (!f) return s - const { typed: _t, ...rest } = s - return { ...rest, ...f.patch } -}) +export const withFills = (sets = [], fills = []) => { + const now = sets.map(s => { + const f = fills.find(x => !x.add && x.setId === s.id) + if (!f) return s + const { typed: _t, ticked: _k, ...rest } = s + return { ...rest, ...f.patch } + }) + // Sets "Use" adds (`grow`): the last set's shape, blank as it was, holding the patch; ids are the writer's. + const { id: _i, typed: _t, ticked: _k, ...shape } = sets.at(-1) || {} + return [...now, ...fills.filter(f => f.add).map(f => ({ ...shape, note: '', ...f.patch }))] +} const COPIED = ['reps', 'seconds', 'weight', 'distance'] const holdsNumber = (s) => COPIED.some(f => num(s?.[f]) !== null) @@ -947,10 +996,11 @@ export const canCopyDown = (sets = [], i) => holdsNumber(sets[i]) && i + 1 < set export const unfills = (sets = [], fills = [], now = withFills(sets, fills)) => fills.flatMap(f => { const s = sets.find(x => x.id === f.setId) const cur = now.find(x => x.id === f.setId) - if (!s || !cur || cur.typed === true) return [] + if (!s || !cur || cur.typed === true || cur.ticked === true) return [] if (Object.keys(f.patch).some(k => num(cur[k]) !== num(f.patch[k]))) return [] const patch = Object.fromEntries(Object.keys(f.patch).map(k => [k, s[k]])) - return [{ setId: f.setId, patch: s.typed === true ? { ...patch, typed: true } : patch }] + const marks = { ...(s.typed === true ? { typed: true } : {}), ...(s.ticked === true ? { ticked: true } : {}) } + return [{ setId: f.setId, patch: { ...patch, ...marks } }] }) /** diff --git a/app/src/lib/order.js b/app/src/lib/order.js new file mode 100644 index 0000000..ef0301a --- /dev/null +++ b/app/src/lib/order.js @@ -0,0 +1,39 @@ +/* + * Which of two sessions came first (#96, #111): what "the last time" means + * everywhere it is asked. `priorSessions` (lib/history.js) and `lastLift` + * (lib/lifts.js) both bound by it, so "The last 5 times you did this" and "Last + * time · …" over an exercise never disagree about which day was before which. + * Its own file because lib/history.js imports lib/lifts.js. + */ + +/** + * Where an entry sits in its day, as the day list shows it (tabs.jsx): the main + * session first, then the extras by id. + */ +const dayPlace = (e) => [e?.data?.slot === 'extra' ? 1 : 0, String(e?.id || '')] + +/** + * When a session started, in ms, where something measured or stamped it: its + * run, the WHOOP or Strava workout attached to it, then its done tap. Null when + * nothing did (a lift typed on the sheet): a day carries no other clock. + */ +function startedAt(e) { + const d = e?.data || {} + for (const v of [d.run?.startedAt, d.out?.whoop?.start, d.out?.strava?.start, d.doneAt]) { + const t = typeof v === 'number' ? v : Date.parse(v) + if (Number.isFinite(t) && t > 0) return t + } + return null +} + +/** + * Is `e` before `me`: an earlier day, or earlier the same day, by when each + * started where both say, else by the day list's order. + */ +export function before(e, me) { + if (String(e.date) !== String(me.date)) return String(e.date) < String(me.date) + const [ta, tb] = [startedAt(e), startedAt(me)] + if (ta !== null && tb !== null && ta !== tb) return ta < tb + const [a, b] = [dayPlace(e), dayPlace(me)] + return a[0] !== b[0] ? a[0] < b[0] : a[1] < b[1] +} diff --git a/app/src/lib/prescription.js b/app/src/lib/prescription.js index 79cde36..13df823 100644 --- a/app/src/lib/prescription.js +++ b/app/src/lib/prescription.js @@ -1254,10 +1254,7 @@ export const patchSet = (pres, itemId, setId, patch) => export const addSet = (pres, itemId) => mapItem(pres, itemId, it => ({ ...it, sets: [...it.sets, untypedSet(it.sets.at(-1))] })) -const untypedSet = (s) => { - const { typed: _t, ...rest } = s || {} - return rest -} +const untypedSet = (s) => unmarked(s) /** * One more set of this, from the RUNNER, copying what the user just did rather than @@ -1497,7 +1494,8 @@ export function keepTyped(before, after) { items: (b.items || []).map(it => { const old = it.kind === 'lift' ? take(it) : null if (!old) return it - return { ...it, sets: (it.sets || []).map((x, i) => (old.sets?.[i]?.typed === true && same(old.sets[i], x) ? { ...x, typed: true } : x)) } + return { ...it, sets: (it.sets || []).map((x, i) => (old.sets?.[i]?.typed === true && same(old.sets[i], x) + ? { ...x, typed: true, ...(old.sets[i].ticked === true ? { ticked: true } : {}) } : x)) } }), })), } @@ -1528,11 +1526,19 @@ export function reviseWeightModes(before, after, liftField, entries = [], { excl blocks: after.blocks.map(b => ({ ...b, items: b.items.map(it => { - if (it.kind !== 'lift' || !it.exercise || !it.implement) return it + if (it.kind !== 'lift' || !it.exercise) return it const old = take(it) - const mode = old && old.implement === it.implement ? (old.weightMode || null) - : rememberedWeightMode(liftField, entries, it.exercise, it.implement, excludeId, today) - return inMode(it, liftField, mode) + // A lift the model named no implement for (#111, C F1: a catalog that + // declares none for Back squat leaves it nothing to name) keeps the one + // it had, else starts where one added by hand does (`defaultImplement`), + // so its weight means something and memory runs. + const implement = it.implement || old?.implement + || defaultImplement(liftField, it.exercise, { entries, excludeId, ...(today ? { today } : {}) }) + if (!implement) return it + const was = it.implement ? it : { ...it, implement, implementLabel: implementLabel(liftField, implement) } + const mode = old && old.implement === implement ? (old.weightMode || null) + : rememberedWeightMode(liftField, entries, it.exercise, implement, excludeId, today) + return inMode(was, liftField, mode) }), })), } @@ -1599,28 +1605,52 @@ export function moveBlock(pres, blockId, dir) { * says". That IS the log (D11, AGENTS.md §6.4 "Planned lifts are the log"), so * the tick writes the same mark a typed number leaves (`typed`), which is what * `liftsDone` reads on the plan's own day and what makes a plan for today - * touched, and so done (D10). Taking the tick off takes the mark: the numbers - * stay, as targets. A tick is never a number: nothing is copied anywhere, and a - * set with no number cannot be ticked (`setHasNumber`), because the log would - * hold nothing for it and a ✓ must always mean logged. + * touched, and so done (D10). A tick is never a number: nothing is copied + * anywhere, and a set with no number cannot be ticked (`setHasNumber`), because + * the log would hold nothing for it and a ✓ must always mean logged. + * + * EDITED IS NOT TICKED (#111, A F1). A tick also writes its own mark, + * `ticked`, because a number typed or stepped leaves `typed` too: with one mark + * for both, "+5 on the weight, lift, tap ✓" lit the ✓ on the +5 and the tap + * took it off, un-logging the set and putting today's plan back to Planned. So + * the ✓ shows `ticked` (`setTicked`); a set only edited (`setEdited`) still + * counts as logged for every reader (D11) and a tap on it TICKS it. Only a tap + * on a ticked set takes the tick off, and with it the mark the numbers left: + * "I did not do this one" (the numbers stay, as targets). Sets ticked before + * the mark existed carry `typed` alone and read as edited: still logged, one + * tap from ticked, never un-logged by a tap. Nothing stored is rewritten. */ export const tickSet = (pres, itemId, setId, on) => mapItem(pres, itemId, it => ({ ...it, sets: it.sets.map(s => { if (s.id !== setId) return s - if (on) return setHasNumber(s) ? { ...s, typed: true } : s - const { typed: _t, ...rest } = s - return rest + if (on) return setHasNumber(s) ? { ...s, typed: true, ticked: true } : s + return unmarked(s) }), })) +/** A set without either mark (`typed`, `ticked`): its numbers as targets. */ +export const unmarked = (s) => { + const { typed: _t, ticked: _k, ...rest } = s || {} + return rest +} + +/** + * Is this set's ✓ on? Ticked on the plan's own day. `asWritten` is a done plan + * whose day has passed: there every set with a number is the log, ticked or + * not, exactly as `liftsDone` reads it (lib/lifts.js). + */ +export const setTicked = (s, asWritten = false) => setHasNumber(s) && (asWritten || s?.ticked === true) + /** - * Is this set done? Ticked (or typed into, the same mark) on the plan's own - * day. `asWritten` is a done plan whose day has passed: there every set with a - * number is the log, ticked or not, exactly as `liftsDone` reads it (lib/lifts.js). + * A set whose number was typed or stepped but not ticked: logged (D11, it + * carries `typed`), shown as edited, and ticked by a tap on its ✓. */ -export const setTicked = (s, asWritten = false) => setHasNumber(s) && (asWritten || s?.typed === true) +export const setEdited = (s) => setHasNumber(s) && s?.typed === true && s?.ticked !== true + +/** Is this set in the log (D11): ticked, or edited (a number typed into it). */ +export const setLogged = (s, asWritten = false) => setTicked(s, asWritten) || setEdited(s) /** Does this set hold a number to log? A ✓ on one without is nothing logged. */ export const setHasNumber = (s) => ['reps', 'weight', 'seconds', 'distance'].some(f => num(s?.[f]) !== null) @@ -1653,8 +1683,19 @@ export function doingMove(before = {}, after = {}) { * logged so far ("1 exercise · 1 set · 900 lb" over a plan of six). */ export function planProgress(pres, asWritten = false) { - const sets = (pres?.blocks || []).flatMap(b => b.items || []).flatMap(it => it.sets || []) - return { done: sets.filter(s => setTicked(s, asWritten)).length, total: sets.length } + return (pres?.blocks || []).flatMap(b => b.items || []).map(it => itemProgress(it, asWritten)) + .reduce((a, p) => ({ done: a.done + p.done, total: a.total + p.total }), { done: 0, total: 0 }) +} + +/** + * How far one exercise has got: its sets in the log (`setLogged`: ticked or + * edited) out of its sets. The card's "2 of 3 done" and the Today row's + * "4 of 18 sets" (`planProgress`) are both this, so they never disagree (#111 + * review). Whether the card is FINISHED (folds, moves on) is ticks only (`itemTicked`). + */ +export function itemProgress(it, asWritten = false) { + const sets = it?.sets || [] + return { done: sets.filter(s => setLogged(s, asWritten)).length, total: sets.length } } /** @@ -1815,6 +1856,6 @@ export const dropEmptyBlocks = (pres) => reindex({ .map(({ wasCircuit: _w, ...b }) => ({ ...b, items: (b.items || []).map(untyped) })), }) -const untyped = (it) => ({ ...it, sets: (it.sets || []).map(({ typed: _t, ...s }) => s) }) +const untyped = (it) => ({ ...it, sets: (it.sets || []).map(unmarked) }) export { catalogOf } diff --git a/app/src/lib/shared.js b/app/src/lib/shared.js index 0f8a0dd..81ad770 100644 --- a/app/src/lib/shared.js +++ b/app/src/lib/shared.js @@ -28,6 +28,7 @@ */ import { extraEntryId } from './store.js' +import { localIso } from './dates.js' import { blankSet, liftMeasure } from './lifts.js' import { reindex, remapRun } from './prescription.js' @@ -188,18 +189,35 @@ function keyed(pres) { */ const noMode = ({ weightMode: _m, weightLabel: _l, ...rest }) => rest -/** A copy of their own last set: its numbers as a start, but not typed until they type into it. */ -const untypedCopy = ({ typed: _t, ...s }) => ({ ...s, note: '' }) +/** A copy of their own last set: its numbers as a start, but not typed (or ticked) until they type into it. */ +const untypedCopy = ({ typed: _t, ticked: _k, ...s }) => ({ ...s, note: '' }) -/** One of the owner's sets on their side: the target, not the owner's weight, cue or anything they typed. */ -const theirSet = ({ typed: _t, ...s }) => ({ ...s, weight: null, note: '' }) +/** + * One of the owner's sets as it arrives on someone else's side (#111, D F1): + * the target, never the owner's weight, cue, or anything the owner did. On a + * workout dated today or earlier (`logged`), a lift set the owner typed into or + * ticked is the owner's LOG (D11), so it crosses blank, as every lift set the server's sync carries does (server/sharedsync.js + * `freshItem`, held to this by sharedsync.test.js): carried as a target, the + * owner's 10 reps read on their side, from the next day on, as reps they lifted. + * An untouched target crosses as the plan wrote it. On a plan for a later day + * nothing has been lifted yet: a number typed there is planning (`patchSet` + * marks every edit), a target like any other, and crosses as one. An + * interval's numbers are its shape, typed or not, as the server keeps them. + * + * @param {string | undefined} kind @param {any} s @param {{ logged?: boolean }} [opts] + */ +export function crossingSet(kind, s, { logged = true } = {}) { + const { typed, ticked: _k, ...rest } = s || {} + const owners = logged && kind === 'lift' && typed === true + return { ...rest, ...(owners ? { reps: null, seconds: null, distance: null } : {}), weight: null, note: '' } +} /** * One of the owner's exercises on their side: the target, not the owner's * weight, what it meant, or the planner's note on it ("3x10 at 95 was RPE 6 * last time", written from the owner's log). */ -const theirItem = (item) => ({ ...noMode(item), note: '', sets: (item.sets || []).map(theirSet) }) +const theirItem = (item, logged) => ({ ...noMode(item), note: '', sets: (item.sets || []).map(x => crossingSet(item.kind, x, { logged })) }) /** * The owner's plan as the start of theirs: the exercises, never the owner's @@ -208,9 +226,9 @@ const theirItem = (item) => ({ ...noMode(item), note: '', sets: (item.sets || [] * the owner's conversation with the planner or its reasoning about the owner's * log (`thread`, `why`, `notes`, `changed`). */ -function theirPlan(mine) { +function theirPlan(mine, logged) { const { draftId: _d, ...plan } = ownerWordsOff(mine) - return { ...plan, blocks: mine.blocks.map(b => ({ ...b, items: (b.items || []).map(theirItem) })) } + return { ...plan, blocks: mine.blocks.map(b => ({ ...b, items: (b.items || []).map(it => theirItem(it, logged)) })) } } /** @@ -337,9 +355,9 @@ export function syncedSides(entry, on = [], side = null) { } /** Their plan with every exercise and set of the owner's that it lacks. Never takes anything out. */ -function copyPlan(theirs, mine) { +function copyPlan(theirs, mine, logged) { if (!mine?.blocks?.length) return theirs - if (!theirs?.blocks?.length) return theirPlan(mine) + if (!theirs?.blocks?.length) return theirPlan(mine, logged) const have = new Map(keyed(theirs).map(x => [x.key, x.item])) const blocks = theirs.blocks.map(b => ({ ...b, items: [...(b.items || [])] })) let changed = false @@ -348,12 +366,12 @@ function copyPlan(theirs, mine) { if (!t) { // A new exercise goes at the end of the same block (a block of the owner's if they have none there). while (blocks.length <= bi) blocks.push({ ...mine.blocks[blocks.length], items: [] }) - blocks[bi].items.push(theirItem(item)) + blocks[bi].items.push(theirItem(item, logged)) changed = true } else if ((item.sets || []).length > (t.sets || []).length) { // More sets of the owner's: copies of their own last set, as adding a set does. const sets = [...(t.sets || [])] - while (sets.length < item.sets.length) sets.push(sets.length ? untypedCopy(sets.at(-1)) : theirSet(item.sets[sets.length])) + while (sets.length < item.sets.length) sets.push(sets.length ? untypedCopy(sets.at(-1)) : crossingSet(item.kind, item.sets[sets.length], { logged })) const b = blocks.find(x => x.items.includes(t)) b.items = b.items.map(x => (x === t ? { ...t, sets } : x)) changed = true @@ -386,14 +404,19 @@ function copyLifts(theirs, mine) { * plan's exercises and set counts (with no weight; their logged sets kept across * the renumber), otherwise the logged lifts as blank rows. Only ever adds: their * numbers, their own exercises and anything they took out of a set count stay as - * they are. The same object back when there is nothing to copy. + * they are. The same object back when there is nothing to copy. `today` + * decides whether the owner's typed numbers are a log or still a plan + * (`crossingSet`). + * + * @param {any} copy @param {any} ownerEntry @param {string} [today] */ -export function copyExercises(copy, ownerEntry) { +export function copyExercises(copy, ownerEntry, today = localIso()) { const mine = ownerEntry?.data if (!copy?.data || copy.deleted || !mine || ownerEntry.deleted) return copy if (mine.plan) { const before = copy.data.plan - const plan = copyPlan(before, mine.plan) + const logged = !ownerEntry.date || String(ownerEntry.date) <= today + const plan = copyPlan(before, mine.plan, logged) if (plan === before) return copy const next = reindex(plan) const data = { ...copy.data, plan: next } @@ -435,7 +458,7 @@ export function copyIdFor(ownerEntry, theirDay = []) { * the session, the shared facts and the owner's exercises without the owner's * weights; none of the owner's numbers, effort or notes. */ -export function sharedCopy(ownerEntry, { id, session = null, owner = null } = {}) { +export function sharedCopy(ownerEntry, { id, session = null, owner = null, today = localIso() } = {}) { const d = ownerEntry?.data || {} const copyId = id || ownerEntry.id const data = { @@ -449,12 +472,15 @@ export function sharedCopy(ownerEntry, { id, session = null, owner = null } = {} } if (d.minutes !== undefined) data.minutes = d.minutes if (d.training === false) data.training = false - return copyExercises({ id: copyId, kind: 'daily', date: ownerEntry.date, data }, ownerEntry) + return copyExercises({ id: copyId, kind: 'daily', date: ownerEntry.date, data }, ownerEntry, today) } /** Are this workout's exercises kept the same on this person's side? */ export const isSynced = (entry, personId) => sharedWithOf(entry).some(s => s.id === personId && s.sync === true) +/** Is anyone else on this workout: shared by its owner, or someone's copy? Then a set added may cross (#111). */ +export const isSharedEntry = (entry) => sharedWithOf(entry).length > 0 || Boolean(entry?.data?.sharedFrom) + /** The owner's entry with someone added to it, synced (or, `remove`, taken off it). */ export function withSharedPerson(ownerEntry, personId, entryId, { remove = false } = {}) { const rest = sharedWithOf(ownerEntry).filter(s => s.id !== personId) diff --git a/app/src/liftlog.jsx b/app/src/liftlog.jsx index 14ad698..55feaf0 100644 --- a/app/src/liftlog.jsx +++ b/app/src/liftlog.jsx @@ -43,7 +43,7 @@ import { useRef, useState } from 'react' import { implementsFor, weightLabelOf, weightModeOf, liftsIn, liftSummary, liftsLine, liftMeasure, - addLift, removeLift, patchLift, addLiftSet, removeLiftSet, setLiftSet, moveLift, + addLift, removeLift, patchLift, addLiftSet, removeLiftSet, setLiftSet, moveLift, fillLift, LIFT_FIELD, blankSet, } from './lib/lifts.js' import { removalWords } from './lib/removal.js' @@ -97,7 +97,7 @@ function asItem(field, lift) { const hintFor = (theirs, lift) => theirs.find(l => l.uid === lift.uid && l.key === lift.key) || theirs.find(l => l.key === lift.key) || null -export function LiftLog({ field, out, entries = [], entryId = null, onSave, hints = null }) { +export function LiftLog({ field, out, entries = [], entryId = null, onSave, hints = null, grow = false }) { const list = liftsIn(out) // The out as of the latest render: an Undo lands seconds later, over whatever was logged since. const outNow = useRef(out) @@ -152,7 +152,8 @@ export function LiftLog({ field, out, entries = [], entryId = null, onSave, hint note={field.hint} onPatch={(uid, patch) => write(patchLift(field, list, uid, patch))} onPatchSet={(uid, setId, patch) => write(setLiftSet(list, uid, Number(setId), patch))} - onFill={(uid, fills) => write(fills.reduce((l, f) => setLiftSet(l, uid, Number(f.setId), f.patch), list))} + onFill={(uid, fills) => write(fillLift(list, uid, fills))} + growFill={grow} onAddSet={(uid) => write(addLiftSet(list, uid))} onRemoveSet={(uid, setId) => remove(removeLiftSet(list, uid, Number(setId)), removalWords(liftOf(uid), Number(setId), { lastTakesItem: false }))} diff --git a/app/src/numinput.jsx b/app/src/numinput.jsx index c8c7238..4b7b8a3 100644 --- a/app/src/numinput.jsx +++ b/app/src/numinput.jsx @@ -15,7 +15,21 @@ import { useEffect, useRef, useState } from 'react' import { acceptNumberText, numOrNull } from './lib/numtext.js' -export function NumInput({ value, onChange, decimal = true, blank = null, ...rest }) { +/** + * A tap on a number box selects what is in it (#111, B F2), as the phone's + * boxes do (`selectTextOnFocus`): tapping "0" and typing 2 stored 20, and 90 → + * 95 meant tap, delete, type. iOS Safari puts the caret back after focus, so + * the selection is made again once the tap has landed. The box's own `onFocus` + * still runs. + */ +export const selectOnFocus = (onFocus) => (e) => { + const el = e.currentTarget + el.select?.() + setTimeout(() => { if (el.ownerDocument?.activeElement === el) el.setSelectionRange?.(0, el.value.length) }, 0) + onFocus?.(e) +} + +export function NumInput({ value, onChange, decimal = true, blank = null, onFocus, ...rest }) { const shown = value === '' || value === null || value === undefined ? '' : String(value) const [text, setText] = useState(shown) const last = useRef(numOrNull(value)) @@ -36,6 +50,6 @@ export function NumInput({ value, onChange, decimal = true, blank = null, ...res return ( setText(shown)} {...rest} /> + onChange={change} onBlur={() => setText(shown)} onFocus={selectOnFocus(onFocus)} {...rest} /> ) } diff --git a/app/src/runner.jsx b/app/src/runner.jsx index c766b2a..c55a1ef 100644 --- a/app/src/runner.jsx +++ b/app/src/runner.jsx @@ -45,12 +45,12 @@ import { Icon } from './lib/icons.jsx' import { NumInput } from './numinput.jsx' import { useModalLayer, Popover } from './modal.jsx' import { CUES, primeAudio, resumeAudio, acquireWakeLock, releaseWakeLock } from './lib/cues.js' -import { lastLift, liftFieldOf } from './lib/lifts.js' +import { lastLift, liftFieldOf, weightUnit } from './lib/lifts.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 { Stepper, boxFor, stepBox, TimeInput, modeFlip, ModeSwitch, ExerciseSheet } from './exercises.jsx' import { ExerciseBody, musclesOf, muscleWords } from './lib/bodymap.jsx' import { usePlan } from './lib/planctx.jsx' import { WorkHead, LeaveDialog, leaveActions, ControlRow, setsWord } from './workchrome.jsx' @@ -402,7 +402,13 @@ function SetScreen({ step, steps, run, draft, entries, entryId, briefing = [], o () => (item.exercise ? lastLift(entries, item.exercise, entryId, liftField, item.kind === 'lift' ? measureOfItem(item) : null) : null), [entries, item, entryId, liftField]) const muscles = musclesOf(liftField, item.exercise) - const swap = weightSwitch(liftField, item, onPatchItem) + /* What the weight means (#111, B F1): the sheet's switch (`modeFlip`: a toast + with Undo, through the latest write so an Undo lands on the plan as it is + then), beside the implement under the name. It was a pill 6px under the big + weight that flipped what the number meant, and taught weight memory, in silence. */ + const patchNow = useRef(onPatchItem) + patchNow.current = onPatchItem + const flip = modeFlip(liftField, item, (p) => patchNow.current(p)) const [about, setAbout] = useState(false) const target = setLine(step.set, item) @@ -438,7 +444,15 @@ function SetScreen({ step, steps, run, draft, entries, entryId, briefing = [], o ) :

{item.name}

} {about && setAbout(false)} />} - {item.implementLabel &&
{item.implementLabel}
} + {(item.implementLabel || flip) && ( +
+ {item.implementLabel && {item.implementLabel}} + {flip && ( + + )} +
+ )} {/* What it works. Bigger here than anywhere else, because this is the one screen the user is looking at while doing it. */} @@ -454,11 +468,13 @@ function SetScreen({ step, steps, run, draft, entries, entryId, briefing = [], o {/* The same fields the editor shows, from the same function — a box the user can plan in and not record in is worse than no box. See setFieldsFor. */}
- {fields.map(f => ( - onPatch({ [f]: v })} /> - ))} + {fields.map(f => { + const b = boxFor(f, item, step.set) + return ( + onPatch({ [f]: v })} /> + ) + })}
{briefing.map((b, i) => ( @@ -543,7 +559,7 @@ function SetScreen({ step, steps, run, draft, entries, entryId, briefing = [], o * is two to a screen with 64px targets and a value you can read from arm's * length on the floor. */ -export function BigStepper({ label, value, step = 1, min = null, onChange, swap = null, time = false }) { +export function BigStepper({ label, unit = null, value, step = 1, min = null, onChange, time = false }) { // A piece's time is a minutes box (`boxFor`, #78), pressed exactly as the editor's. const bump = (d) => onChange(stepBox({ step, min, time }, value, d)) return ( @@ -559,12 +575,9 @@ export function BigStepper({ label, value, step = 1, min = null, onChange, swap {time ? : } - {swap ? ( - - ) : {label}} + {/* The unit only ("lb"): what the number means is said once, by the + implement (`modeFlip`), never a switch under the number (#111). */} + {unit ?? label}
+ {/* A day of routes is one list (#111, E F2): a card that says `addSets: false` + has Add route and no second door that starts "Set 2" at route 1. */} + {exercise.addSets !== false && ( + + )} {/* Off the number row on purpose: a remove beside the box being typed in is a remove pressed by accident. The set comes back with Undo. */} {rows.length > 1 && !picking && ( @@ -662,8 +668,8 @@ export function signedLoad(row, sign) { */ export function totalReps(out) { return Object.values(out?.sets || {}) - .flat() - .reduce((s, r) => s + (Array.isArray(r?.[CLIMB_FIELD]) ? climbsCounted(r) : (Number(r?.reps) || 0)), 0) + .reduce((s, rows) => s + (Array.isArray(rows) ? rows : []) + .reduce((n, r) => n + (Array.isArray(r?.[CLIMB_FIELD]) ? climbsCounted(r, rows) : (Number(r?.reps) || 0)), 0), 0) } /** diff --git a/app/workout.test.js b/app/workout.test.js index 7a6a0cc..c7c2d39 100644 --- a/app/workout.test.js +++ b/app/workout.test.js @@ -1373,6 +1373,24 @@ check('with the detail on, the described climbs are the count, never the prefill eq(climbsCounted({ reps: 2, grades: [10.2, 10.1] }), 2, 'no detail: the laps are the count') }) +check('Add set never inflates the count: the described climbs count in every set of the exercise (#111, E F1)', () => { + // The regrade's repro: Rock climbing, 2 routes described (5.10 sent, 5.11 fell), Add set. + const one = detailOn({ reps: 2 }) + one.climbs[0] = { ...blankClimb(), grade: 10.2, outcome: 'send' } + one.climbs[1] = { ...blankClimb(), grade: 11.2, outcome: 'fell' } + const added = detailOn({ reps: 2 }) + const rows = [one, added] + eq(climbTotals(rows).count, 2, 'the copied count in set 2 read as climbs') + eq(climbTotals(rows).untold, 2, 'set 2\'s blanks are waiting, not climbed') + eq(climbsCounted(added, rows), 0) + eq(climbVolume(opt('fun-sport'), { sets: { routes: rows } }), 2, 'Climbs per week charted the copy') + eq(lengthsIn(rows), 2) + // Nothing described anywhere: every set's count stands, as with the detail off. + eq(climbTotals([detailOn({ reps: 4 }), detailOn({ reps: 3 })]).count, 7) + // A row without the detail keeps its count beside a described one. + eq(climbTotals([one, { reps: 5 }]).count, 7) +}) + check('a blank rep count still offers one picker, and a silly one is capped', () => { eq(repCount(''), 1, 'no reps typed must not hide the grade input') eq(repCount(0), 1) diff --git a/content/starter.json b/content/starter.json index 5f0c80f..a6e25e6 100644 --- a/content/starter.json +++ b/content/starter.json @@ -192,6 +192,7 @@ "key": "problems", "name": "Problems climbed", "defaultSets": 1, + "addSets": false, "fields": [ "reps" ], @@ -338,6 +339,7 @@ "key": "routes", "name": "Routes climbed", "defaultSets": 1, + "addSets": false, "fields": [ "reps" ], diff --git a/examples/plan.json b/examples/plan.json index 997108c..5a01fa8 100644 --- a/examples/plan.json +++ b/examples/plan.json @@ -381,6 +381,7 @@ "key": "problems", "name": "Problems climbed", "defaultSets": 1, + "addSets": false, "fields": [ "reps" ], @@ -527,6 +528,7 @@ "key": "routes", "name": "Routes climbed", "defaultSets": 1, + "addSets": false, "fields": [ "reps" ], diff --git a/mobile/src/features/editor.tsx b/mobile/src/features/editor.tsx index e52f1ca..1bd40a0 100644 --- a/mobile/src/features/editor.tsx +++ b/mobile/src/features/editor.tsx @@ -374,6 +374,7 @@ export function PrescriptionEditor({ onPatchSet={(id: string, setId: string, patch: any) => onChange(patchSet(pres, id, setId, patch))} /* "Use last time" (#93): the numbers as targets, in one write, never ticked. */ onFill={(id: string, fills: any[]) => onChange(patchItem(pres, id, { sets: withFills(itemOf(id)?.sets, fills) }))} + growFill={!syncedWith?.length} onAddSet={(id: string) => onChange(addSet(pres, id))} onRemoveSet={dropSet} onRemove={dropItem} diff --git a/mobile/src/features/exercises.tsx b/mobile/src/features/exercises.tsx index f22eca2..2d5f02c 100644 --- a/mobile/src/features/exercises.tsx +++ b/mobile/src/features/exercises.tsx @@ -36,11 +36,11 @@ import { impact, success, tap, warn } from '../ui/haptics' import { Icon } from '../lib/icons' import { pushToast, dismissToast } from '../lib/toast' import { NumInput } from './numinput' -import { setFieldsFor, measureOfItem, timeBox, bumpTime, setTicked, itemTicked, setHasNumber, doingMove } from '../lib/prescription.js' +import { setFieldsFor, measureOfItem, timeBox, bumpTime, setTicked, setEdited, itemTicked, itemProgress, setHasNumber, doingMove } from '../lib/prescription.js' import { acceptMinutesText, minutesText, numOrNull } from '../lib/numtext.js' import { searchExercises, implementsFor, lastLift, catalogOf, exerciseOf, muscleName, measureFor, - weightModesFor, weightPatch, nextWeightMode, rememberedWeightMode, weightModeWords, weightBoxOf, + weightModesFor, weightPatch, nextWeightMode, rememberedWeightMode, weightModeWords, implementChoices, implementLabel, weightModeOf, weightMeaning, weightUnit, lastTimeFill, lastTimeWhen, pickerGroupFor, copyDownFills, canCopyDown, unfills, cardIdentity, cardKey, } from '../lib/lifts.js' @@ -55,7 +55,7 @@ import { Explain } from './blurb' * are; one rep and five seconds because that is what those are. The weight's * label comes off the IMPLEMENT — "30 lb per hand" and "135 lb on the bar" are * different numbers and the box has to say which — and the mode the user - * switched it to (`weightSwitch`). + * switched it to (`modeFlip`). */ export const STEP: Record { label: string; step: number; min: number }> = { reps: () => ({ label: 'reps', step: 1, min: 0 }), @@ -155,19 +155,6 @@ const sw = StyleSheet.create({ }, }) -export type WeightSwap = { box: string; next: string; aria?: string; onSwitch: () => void } | null - -/** - * The tap that changes what a lift's weight means (issue #58), or null where - * its implement has one meaning: the runner's 44pt pill. The card's is - * `modeFlip` (#93), once per exercise and with Undo. - */ -export function weightSwitch(liftField: any, item: any, onPatch: (patch: any) => void): WeightSwap { - if (item?.kind !== 'lift' || weightModesFor(liftField, item.implement).length < 2) return null - const next = weightPatch(liftField, item.implement, nextWeightMode(liftField, item)) - return { box: weightBoxOf(liftField, item), next: next.weightLabel, onSwitch: () => { tap(); onPatch(next) } } -} - /** * What tapping an implement chip writes: the implement, in the mode this * exercise was last logged in with it (lib/lifts.js). Null for the chip already @@ -183,12 +170,15 @@ export function implementPick(liftField: any, item: any, impl: any, entries: any } } +/** A card switch: the words its box shows, what a tap switches to, and the tap. */ +export type CardSwitch = { box: string; next: string; aria?: string; onSwitch: () => void } | null + /** * The tap that counts a hold in reps instead, or back (issue #63 review), or * null. Offered on a movement the catalog calls a hold while nothing is counted * on it yet, under the count's own box, like the weight's meaning. */ -export function countSwitch(liftField: any, item: any, onPatch: (patch: any) => void): WeightSwap { +export function countSwitch(liftField: any, item: any, onPatch: (patch: any) => void): CardSwitch { if (item?.kind !== 'lift' || !item.exercise || measureFor(liftField, item.exercise) !== 'time') return null const counted = (item.sets || []).some((s: any) => (s.reps !== null && s.reps !== undefined && s.reps !== '') || (s.seconds !== null && s.seconds !== undefined && s.seconds !== '')) @@ -302,10 +292,10 @@ export function modeFlip(liftField: any, item: any, write: (patch: any) => void, /** * The card's one switch for what its weight means (#93; #58's switch, moved out * of every set's cell): "on the bar ⇆", once per exercise, beside what it is done - * with. A hold's "seconds ⇆" sits here too. With one meaning the words are said, - * not offered. + * with; the runner's too, under the name (#111). A hold's "seconds ⇆" sits here + * too. With one meaning the words are said, not offered. */ -function ModeSwitch({ words, aria, onSwitch }: { words: string; aria?: string; onSwitch?: () => void }) { +export function ModeSwitch({ words, aria, onSwitch }: { words: string; aria?: string; onSwitch?: () => void }) { if (!onSwitch) return {words} return ( @@ -319,12 +309,14 @@ function ModeSwitch({ words, aria, onSwitch }: { words: string; aria?: string; o * The set row's widths (#93, F N1), named so `app/smoke/system.jsx` can add * them up for a 390pt phone: the ✓, the gap after it (16 clear of the reps' −, * so a left-thumb miss on − never ticks), each stepper's middle, and the seam - * between the two steppers. 44 + 16 + 2 × (1 + 44 + 44 + 44 + 1) + 2 = 330, - * inside the card's 332, so reps, weight and the ✓ are ONE row; - * they wrapped onto two (each set about 100pt tall) when the meaning switch - * widened the weight's middle. + * between the two steppers. 44 + 16 + 2 × (1 + 44 + 42 + 44 + 1) + 8 = 332, the + * card's 332, so reps, weight and the ✓ are ONE row; they wrapped onto two (each + * set about 100pt tall) when the meaning switch widened the weight's middle. The + * seam is 8 (#111): at 2 the reps' + and the weight's −, the two most-pressed + * controls, read as one strip and a slip did the opposite thing. The number + * boxes gave the width for it (42 wide, still 44 tall, between 44pt buttons). */ -export const SET_ROW = { tick: TAP, tickGap: space[4], mid: TAP, seam: 2 } +export const SET_ROW = { tick: TAP, tickGap: space[4], mid: 42, seam: space[2] } /* ------------------------------------------------------- what the movement is */ @@ -604,11 +596,13 @@ function pickImplement(liftField: any, item: any, entries: any[], entryId: strin /** * A set's ✓ in doing mode (#79): "I did this set as it says" (the web's * `SetTick`). The set's number until it is ticked, a check on the accent tint - * after; it writes `typed` (prescription.js `tickSet`), which is the log (D11). - * 44pt at the row's end; ticking buzzes as a set logged does. + * after; it writes `typed` and `ticked` (prescription.js `tickSet`), which is the + * log (D11). 44pt at the row's end; ticking buzzes as a set logged does. + * `edited` (#111): a number typed or stepped, logged but not ticked, is an accent + * ring round the number, and a tap on it ticks it; only a ticked set comes off. */ -export function SetTick({ n, on, onToggle, locked = false, empty = false, onPrompt }: { - n: number; on: boolean; onToggle: (v: boolean) => void; locked?: boolean; empty?: boolean; onPrompt?: () => void +export function SetTick({ n, on, onToggle, locked = false, empty = false, edited = false, onPrompt }: { + n: number; on: boolean; onToggle: (v: boolean) => void; locked?: boolean; empty?: boolean; edited?: boolean; onPrompt?: () => void }) { /* A done plan's earlier day (`asWritten`): its sets ARE the log as written, so the mark is read, not toggled; a number changed or a set removed corrects it. */ @@ -633,8 +627,9 @@ export function SetTick({ n, on, onToggle, locked = false, empty = false, onProm } return ( { if (!on) success(); else tap(); onToggle(!on) }} - accessibilityRole="checkbox" accessibilityState={{ checked: on }} accessibilityLabel={`Set ${n} done`} - style={[st.tick, on && st.tickOn]}> + accessibilityRole="checkbox" accessibilityState={{ checked: on ? true : edited ? 'mixed' : false }} + accessibilityLabel={!on && edited ? `Set ${n}: logged as typed. Tick it` : `Set ${n} done`} + style={[st.tick, on ? st.tickOn : edited && st.tickEdited]}> {on ? : {String(n)}} @@ -658,7 +653,7 @@ export function SetTick({ n, on, onToggle, locked = false, empty = false, onProm export function ExerciseCard({ item, liftField, entries = [], entryId = null, defaultOpen = false, defaultEditing = false, blank = null, onPatch, onPatchSet, onAddSet, onRemoveSet, onRemove, doing = false, onTick = null, focus = false, - asWritten = false, onFill = null, + asWritten = false, onFill = null, growFill = false, }: any) { const [open, setOpen] = useState(defaultOpen) const [about, setAbout] = useState(false) @@ -705,12 +700,13 @@ export function ExerciseCard({ // stays short enough not to squeeze the name on a phone. const modeWords = item.kind === 'lift' ? weightModeWords(liftField, item) : null const ticking = Boolean(doing && onTick) - const ticks = ticking ? item.sets.filter((s: any) => setTicked(s, asWritten)).length : 0 + // In the log, ticked or edited: the Today row's count too (`itemProgress`, #111). + const ticks = ticking ? itemProgress(item, asWritten).done : 0 const finished = ticking && itemTicked(item, asWritten) const line = ticking && ticks && !finished ? [`${ticks} of ${item.sets.length} done`, item.line].filter(Boolean).join(' · ') : item.line - const fill: any[] = onFill && prior && !asWritten ? lastTimeFill(liftField, item, prior) : [] + const fill: any[] = onFill && prior && !asWritten ? lastTimeFill(liftField, item, prior, { grow: growFill }) : [] const copyDown = onFill && !asWritten ? (s: any) => { impact(); copyDownWrite(item, s.id, (f) => fillNow.current?.(f), undefined, () => itemNow.current) } : null /* Doing mode moves on with the workout (#94, B F2, lib/prescription.js `doingMove`): finished, this card folds; next, it opens and the sheet scrolls to it. */ @@ -848,7 +844,7 @@ export function ExerciseCard({ {ticking ? ( onTick(s.id, v)} - empty={!setHasNumber(s)} onPrompt={() => setAsked({ id: s.id, n: (asked?.n || 0) + 1 })} /> + empty={!setHasNumber(s)} edited={setEdited(s)} onPrompt={() => setAsked({ id: s.id, n: (asked?.n || 0) + 1 })} /> ) : {String(i + 1)}} {setFieldsFor(item, s).map((f: string, fi: number) => { @@ -1038,7 +1034,7 @@ export function ExerciseSection({ title, count, items, liftField, entries = [], entryId = null, firstOpenId = null, blank = null, addLabel = 'Add an exercise here', open = true, onToggle = null, - onPatch, onPatchSet, onAddSet, onRemoveSet, onRemove, onFill = null, + onPatch, onPatchSet, onAddSet, onRemoveSet, onRemove, onFill = null, growFill = false, onMove = null, onAdd = null, extra = null, foot = null, note = null, menu = null, tag = null, lead = null, doing = false, onTick = null, focusId = null, asWritten = false, }: any) { @@ -1119,7 +1115,7 @@ export function ExerciseSection({ onAddSet={() => onAddSet(it.id)} onRemoveSet={(setId: any) => onRemoveSet(it.id, setId)} onRemove={() => onRemove(it.id)} - onFill={onFill ? (fills: any[]) => onFill(it.id, fills) : null} /> + onFill={onFill ? (fills: any[]) => onFill(it.id, fills) : null} growFill={growFill} /> )) )} @@ -1249,6 +1245,8 @@ const st = StyleSheet.create({ borderWidth: 1, borderColor: colors.lineStrong, }, tickOn: { backgroundColor: colors.accentSoft, borderColor: colors.accentLine }, + // Edited (#111): logged by a number typed, not yet ticked. + tickEdited: { borderWidth: 2, borderColor: colors.accentLine }, doingMeta: { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', rowGap: space[3], columnGap: space[2], marginTop: space[3] }, implSwitch: { flexDirection: 'row', alignItems: 'center', gap: space[1], minHeight: TAP, paddingHorizontal: space[3], diff --git a/mobile/src/features/liftlog.tsx b/mobile/src/features/liftlog.tsx index 95ba4eb..e7a5707 100644 --- a/mobile/src/features/liftlog.tsx +++ b/mobile/src/features/liftlog.tsx @@ -20,7 +20,7 @@ import React, { useRef, useState } from 'react' import { View } from 'react-native' import { implementsFor, weightLabelOf, weightModeOf, liftsIn, liftSummary, liftsLine, liftMeasure, - addLift, removeLift, patchLift, addLiftSet, removeLiftSet, setLiftSet, moveLift, + addLift, removeLift, patchLift, addLiftSet, removeLiftSet, setLiftSet, moveLift, fillLift, LIFT_FIELD, blankSet, } from '../lib/lifts.js' import { removalWords } from '../lib/removal.js' @@ -66,7 +66,7 @@ function asItem(field: any, lift: any) { const hintFor = (theirs: any[], lift: any) => theirs.find((l) => l.uid === lift.uid && l.key === lift.key) || theirs.find((l) => l.key === lift.key) || null -export function LiftLog({ field, out, entries = [], entryId = null, onSave, hints = null }: any) { +export function LiftLog({ field, out, entries = [], entryId = null, onSave, hints = null, grow = false }: any) { const list = liftsIn(out) // The out as of the latest render: an Undo lands seconds later, over whatever was logged since. const outNow = useRef(out) @@ -113,7 +113,8 @@ export function LiftLog({ field, out, entries = [], entryId = null, onSave, hint note={field.hint} onPatch={(uid: any, patch: any) => write(patchLift(field, list, uid, patch))} onPatchSet={(uid: any, setId: any, patch: any) => write(setLiftSet(list, uid, Number(setId), patch))} - onFill={(uid: any, fills: any[]) => write(fills.reduce((l: any, f: any) => setLiftSet(l, uid, Number(f.setId), f.patch), list))} + onFill={(uid: any, fills: any[]) => write(fillLift(list, uid, fills))} + growFill={grow} onAddSet={(uid: any) => write(addLiftSet(list, uid))} onRemoveSet={(uid: any, setId: any) => remove(removeLiftSet(list, uid, Number(setId)), removalWords(liftOf(uid), Number(setId), { lastTakesItem: false }))} diff --git a/mobile/src/features/runner.tsx b/mobile/src/features/runner.tsx index a5bd06b..571fb19 100644 --- a/mobile/src/features/runner.tsx +++ b/mobile/src/features/runner.tsx @@ -56,7 +56,7 @@ import { Icon } from '../lib/icons' import { onForeground } from '../lib/foreground' import { NumInput } from './numinput' import { CUES, primeAudio, resumeAudio, acquireWakeLock, releaseWakeLock } from '../lib/cues' -import { lastLift, liftFieldOf } from '../lib/lifts.js' +import { lastLift, liftFieldOf, weightUnit } from '../lib/lifts.js' import { isLogged, isSkipped, setLine, itemLine, setFieldsFor, measureOfItem, blockTimer, circuitOnly, circuitTiming, } from '../lib/prescription.js' @@ -66,7 +66,7 @@ import { clock } from '../lib/workout.js' import { TimerRun, WorkHead, LeaveDialog, leaveActions, ControlRow, setsWord, KIND_COLOR } from './timer' import { timingWords } from './circuit' import * as trainerLib from '../lib/trainer.js' -import { Stepper, boxFor, stepBox, TimeInput, weightSwitch, ExerciseSheet, type WeightSwap } from './exercises' +import { Stepper, boxFor, stepBox, TimeInput, modeFlip, ModeSwitch, ExerciseSheet } from './exercises' import { ExerciseBody, musclesOf, muscleWords } from '../lib/bodymap' import { usePlan } from '../lib/planctx.jsx' import { dayPhrase } from '../lib/dates.js' @@ -445,7 +445,12 @@ function SetScreen({ step, steps, run, draft, entries, entryId, briefing = [], o () => (item.exercise ? lastLift(entries, item.exercise, entryId, liftField, item.kind === 'lift' ? measureOfItem(item) : null) : null), [entries, item, entryId, liftField]) const muscles = musclesOf(liftField, item.exercise) - const swap = weightSwitch(liftField, item, onPatchItem) + /* What the weight means (#111, B F1): the sheet's switch (`modeFlip`: a toast + with Undo, through the latest write), beside the implement under the name. + It was a pill under the big weight that flipped the meaning in silence. */ + const patchNow = useRef(onPatchItem) + patchNow.current = onPatchItem + const flip = modeFlip(liftField, item, (p: any) => patchNow.current(p)) const [about, setAbout] = useState(false) const target = setLine(step.set, item) @@ -489,7 +494,15 @@ function SetScreen({ step, steps, run, draft, entries, entryId, briefing = [], o {item.name} )} {about ? setAbout(false)} /> : null} - {item.implementLabel ? {item.implementLabel} : null} + {item.implementLabel || flip ? ( + + {item.implementLabel ? {item.implementLabel} : null} + {flip ? ( + + ) : null} + + ) : null} {/* What it works. Bigger here than anywhere else, because this is the one screen the user is looking at while doing it. */} @@ -509,11 +522,13 @@ function SetScreen({ step, steps, run, draft, entries, entryId, briefing = [], o {/* The same fields the editor shows, from the same function — a box the user can plan in and not record in is worse than no box. */} - {fields.map((f: string) => ( - onPatch({ [f]: v })} /> - ))} + {fields.map((f: string) => { + const b = boxFor(f, item, step.set) + return ( + onPatch({ [f]: v })} /> + ) + })} {briefing.map((b: any, i: number) => ( @@ -635,8 +650,9 @@ function RunBtn({ kind = 'primary', big, icon, iconSize = 16, label, a11y, onPre * length on the floor. Its 56pt number is one of the two sizes above * font.stat (the interval timer's clock is the other, docs/DESIGN.md "Type"). */ -function BigStepper({ label, value, step = 1, min = null, onChange, swap = null, time = false }: { - swap?: WeightSwap +function BigStepper({ label, unit = null, value, step = 1, min = null, onChange, time = false }: { + /** The unit said under the number ("lb"); what it means is the implement's switch (#111). */ + unit?: string | null /** A piece's time: a minutes box (`boxFor`, #78), as in the editor. */ time?: boolean label: string @@ -664,13 +680,7 @@ function BigStepper({ label, value, step = 1, min = null, onChange, swap = null, )} - {swap ? ( - - {swap.box} - - - ) : {label}} + {unit ?? label} bump(1)} style={st.bigstepBtn} accessibilityRole="button" accessibilityLabel={`more ${label}`}> @@ -893,6 +903,8 @@ const st = StyleSheet.create({ minHeight: TAP, paddingHorizontal: space[3], marginVertical: -space[3], borderRadius: radius.pill, }, bodyMap: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: space[2], marginTop: space[2], marginBottom: 2 }, + // The web's .run-impl: the implement and its meaning switch under the name (#111). + impl: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap', gap: space[2] }, target: { marginTop: space[4], marginBottom: space[2] }, inputs: { gap: space[4], marginTop: space[3], marginBottom: space[2] }, bigstep: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: space[3] }, @@ -901,11 +913,6 @@ const st = StyleSheet.create({ backgroundColor: colors.panel2, borderWidth: 1, borderColor: colors.lineStrong, }, bigstepMid: { flex: 1, maxWidth: 190, alignItems: 'center', gap: space[1] }, - // The web's .bigstep .stepper-swap: the weight's meaning as a 44px pill (#58). - swap: { - flexDirection: 'row', alignItems: 'center', gap: space[1], minHeight: TAP, paddingHorizontal: space[4], - borderRadius: radius.pill, backgroundColor: colors.panel3, borderWidth: 1, borderColor: colors.lineStrong, - }, bigstepIn: { width: '100%', padding: 0, paddingHorizontal: 0, paddingVertical: 0, minHeight: 58, textAlign: 'center', backgroundColor: 'transparent', borderWidth: 0, color: colors.ink, diff --git a/mobile/src/features/sessionlog.tsx b/mobile/src/features/sessionlog.tsx index a185d11..f85ac6c 100644 --- a/mobile/src/features/sessionlog.tsx +++ b/mobile/src/features/sessionlog.tsx @@ -31,6 +31,7 @@ import { GearPicker } from './gearpicker' import { WhoopWorkouts } from './whoop' import { StravaActivities } from './strava' import { dayWords } from '../lib/dates.js' +import { isSharedEntry } from '../lib/shared.js' /* --------------------------------------------------------------- notes --- */ @@ -540,7 +541,7 @@ export function SessionLog({ // Exercises chosen at log time, with their own implement and sets. if (f.type === 'lifts') { return ( - + ) } // A number the app can work out is a PLACEHOLDER, and one a service diff --git a/mobile/src/features/setlog.tsx b/mobile/src/features/setlog.tsx index bfa1b0a..866e5ed 100644 --- a/mobile/src/features/setlog.tsx +++ b/mobile/src/features/setlog.tsx @@ -36,7 +36,7 @@ import { routeLadder, routeSystem, setRouteSystem, ROUTE_SYSTEMS, labelOn, scaleOfExercise, climbCount, detailOn, dropClimb, putClimb, climbSaid, saidIn, outcomesFor, outcomeOf, outcomeLabel, withOutcome, MAX_CLIMBS, - climbsCounted, climbTotals, nearRungs, + climbsCounted, climbTotals, nearRungs, anyTold, } from '../lib/grades.js' const FIELD_META: Record = { @@ -271,7 +271,7 @@ export function climbWords(c: any) { * grade per lap; `onDrop(i)` where a climb can be taken out (the set log, with * Undo); workout mode moves the count with its own stepper. */ -export function ClimbLog({ count, values, spec, onChange, onMore, onDrop, what = 'climb', where = '', omitGrade = false, initialCurrent = null }: any) { +export function ClimbLog({ count, values, spec, onChange, onMore, onDrop, what = 'climb', where = '', omitGrade = false, initialCurrent = null, toldElsewhere = false }: any) { const [system] = useRouteSystem() const scale = spec?.scale === 'v' ? 'v' : 'yds' const ladder = ladderFor(scale, system) @@ -290,7 +290,8 @@ export function ClimbLog({ count, values, spec, onChange, onMore, onDrop, what = const untold = current >= 0 ? climbs.filter((c, k) => k > current && !climbSaid(c)).length : 0 // Once one climb is described the described ones are the count (lib/grades.js // `climbsCounted`, #97): the line says the blanks after them do not count. - const anySaid = climbs.some((c) => climbSaid(c)) + // Another set of this exercise described counts too (`anyTold`, #111). + const anySaid = climbs.some((c) => climbSaid(c)) || toldElsewhere const next = nextBlank >= 0 ? { label: `Next ${what}`, go: () => setPicked(nextBlank) } : onMore ? { label: `Add ${what}`, go: () => { setPicked(count); onMore() } } : null @@ -510,6 +511,7 @@ function Exercise({ exercise, rows, sign, onRows, onSign, hintRows = null }: any 1 ? `set ${i + 1} ` : ''} + toldElsewhere={anyTold(rows.filter((_: any, j: number) => j !== i))} onChange={(list: any) => setList(i, CLIMB_FIELD, list)} onDrop={(k: number) => removeClimb(i, k)} onMore={climbCount(r.reps) < MAX_CLIMBS ? () => bump(i, 1) : undefined} /> @@ -554,7 +556,7 @@ function Exercise({ exercise, rows, sign, onRows, onSign, hintRows = null }: any {/* While the detail is on, the climb list IS the count: shown, not typed. */} {f === 'reps' && Array.isArray(r[CLIMB_FIELD]) ? ( - {String(climbsCounted(r))} + {String(climbsCounted(r, rows))} ) : ( : null} - + {/* A day of routes is one list (#111, E F2): a card that says `addSets: false` + has Add route and no second door that starts "Set 2" at route 1. */} + {exercise.addSets !== false ? : null} {/* Off the number row on purpose: the set comes back with Undo. */} {/* Any set, picked from a system sheet (the web asks in its foot, #97 F9d); the swipe on a row does the same. Every removal comes back with Undo. */} @@ -665,8 +669,8 @@ export function signedLoad(row: any, sign: string) { /** Total completed reps across every exercise; a row with the detail on counts what it counts (#97). */ export function totalReps(out: any): number { return (Object.values(out?.sets || {}) as any[]) - .flat() - .reduce((s: number, r: any) => s + (Array.isArray(r?.[CLIMB_FIELD]) ? climbsCounted(r) : (Number(r?.reps) || 0)), 0) + .reduce((s: number, rows: any) => s + (Array.isArray(rows) ? rows : []) + .reduce((n: number, r: any) => n + (Array.isArray(r?.[CLIMB_FIELD]) ? climbsCounted(r, rows) : (Number(r?.reps) || 0)), 0), 0) } /** diff --git a/mobile/src/lib/grades.js b/mobile/src/lib/grades.js index 236a6b0..ed19241 100644 --- a/mobile/src/lib/grades.js +++ b/mobile/src/lib/grades.js @@ -467,19 +467,31 @@ function toldOf(row) { return told } -/** How many climbs this row counts: the described ones once any is, else its count. */ -export function climbsCounted(row) { +/** + * Does any row of this exercise have a described climb? Then the described + * climbs are the count in EVERY row of it with the detail on (#111, E F1): Add + * set copies the last row's count into a new row of blank records, and counted + * by its own `reps` that row passed for climbs ("2 described, Add set, 4 routes"). + * A row is not a session of its own; the exercise is one list of climbs. + */ +export const anyTold = (rows) => Array.isArray(rows) && rows.some(r => Array.isArray(r?.[CLIMB_FIELD]) && toldOf(r).length > 0) + +/** + * How many climbs this row counts: the described ones once any is (in this row, + * or in another row of the same exercise, `rows`), else its count. + */ +export function climbsCounted(row, rows = null) { const reps = Math.max(0, Math.floor(Number(row?.reps) || 0)) if (!Array.isArray(row?.[CLIMB_FIELD])) return reps const told = toldOf(row).length - return told > 0 ? told : reps + return told > 0 || anyTold(rows) ? told : reps } -/** Climbs in the row's list nobody has described, while others are: not counted. */ -export function untoldIn(row) { +/** Climbs in the row's list nobody has described, while others are (here or elsewhere in `rows`): not counted. */ +export function untoldIn(row, rows = null) { if (!Array.isArray(row?.[CLIMB_FIELD])) return 0 const told = toldOf(row).length - return told > 0 ? climbCount(row?.reps) - told : 0 + return told > 0 || anyTold(rows) ? climbCount(row?.reps) - told : 0 } /** @@ -489,7 +501,7 @@ export function untoldIn(row) { */ export function climbTotals(rows) { const list = rows || [] - const count = list.reduce((s, r) => s + climbsCounted(r), 0) + const count = list.reduce((s, r) => s + climbsCounted(r, list), 0) const said = climbsIn(list).filter(climbSaid) return { count, @@ -497,7 +509,7 @@ export function climbTotals(rows) { falls: fallsIn(list), downs: downsIn(list), lengths: lengthsIn(list), - untold: list.reduce((s, r) => s + untoldIn(r), 0), + untold: list.reduce((s, r) => s + untoldIn(r, list), 0), } } @@ -532,7 +544,7 @@ export const downsIn = (rows) => climbsIn(rows).filter(c => c.down === 'both' || */ export function lengthsIn(rows) { return (rows || []).reduce((sum, r) => { - const n = climbsCounted(r) + const n = climbsCounted(r, rows) const list = Array.isArray(r?.[CLIMB_FIELD]) ? r[CLIMB_FIELD] : [] const extra = list.filter(c => c?.down === 'both').length return sum + n + extra @@ -703,7 +715,8 @@ export function climbVolume(opt, out) { let n = 0 for (const ex of exercisesOf(opt)) { if (!countsClimbs(ex)) continue - for (const r of out?.sets?.[ex.key] || []) n += climbsCounted(r) + const rows = out?.sets?.[ex.key] || [] + for (const r of rows) n += climbsCounted(r, rows) } return n } diff --git a/mobile/src/lib/history.js b/mobile/src/lib/history.js index 46216b9..e1eb0fc 100644 --- a/mobile/src/lib/history.js +++ b/mobile/src/lib/history.js @@ -21,6 +21,7 @@ import { liftsDone, liftKeyOf } from './lifts.js' import { isDone } from './store.js' +import { before } from './order.js' /** * Which optIds count as "this session", for history. @@ -70,38 +71,6 @@ export function samePlanned(entry, e) { return sameExercises(exercisesOf(entry), exercisesOf(e)) } -/** - * Where an entry sits in its day, as the day list shows it (tabs.jsx): the main - * session first, then the extras by id. - */ -const dayPlace = (e) => [e?.data?.slot === 'extra' ? 1 : 0, String(e?.id || '')] - -/** - * When a session started, in ms, where something measured or stamped it: its - * run, the WHOOP or Strava workout attached to it, then its done tap. Null when - * nothing did (a lift typed on the sheet): a day carries no other clock. - */ -function startedAt(e) { - const d = e?.data || {} - for (const v of [d.run?.startedAt, d.out?.whoop?.start, d.out?.strava?.start, d.doneAt]) { - const t = typeof v === 'number' ? v : Date.parse(v) - if (Number.isFinite(t) && t > 0) return t - } - return null -} - -/** - * Is `e` before `me`: an earlier day, or earlier the same day, by when each - * started where both say, else by the day list's order. - */ -function before(e, me) { - if (String(e.date) !== String(me.date)) return String(e.date) < String(me.date) - const [ta, tb] = [startedAt(e), startedAt(me)] - if (ta !== null && tb !== null && ta !== tb) return ta < tb - const [a, b] = [dayPlace(e), dayPlace(me)] - return a[0] !== b[0] ? a[0] < b[0] : a[1] < b[1] -} - /** * Every time you DID this workout (`isDone`: not a plan still to come, not one * marked undone) BEFORE the one being shown, newest first, that one left out. diff --git a/mobile/src/lib/lifts.js b/mobile/src/lib/lifts.js index c6ef2be..1bc1e03 100644 --- a/mobile/src/lib/lifts.js +++ b/mobile/src/lib/lifts.js @@ -33,6 +33,7 @@ import { localIso, dayWords } from './dates.js' import { isDone } from './store.js' +import { before } from './order.js' export const LIFT_FIELD = 'lifts' @@ -525,11 +526,18 @@ export function liftsDone(entry, today = localIso()) { for (const b of plan.blocks) { for (const it of Array.isArray(b?.items) ? b.items : []) { if (it?.kind !== 'lift') continue - // Only a row with a number stands for an item: a blank one hides nothing. + // A row with a number logged for an item is that item's log. const by = logged.find(l => !used.has(l) && (l?.sets || []).some(numbered) && standsFor(l, it)) if (by) { used.add(by); rows.push(by); continue } const row = itemRow(b, it, typedOnly) - if (row) rows.push(row) + // A BLANK row for it (a circuit's counted exercise, written `{ reps: '' }` + // a round for them to fill in, §6.5) hides nothing the plan says, but it + // is still this item, never a second exercise (#111, D F2: 3 exercises × 2 + // rounds read "4 exercises · 8 sets"). The item is read once: its sets + // where they count, else the blank row, as before. + const blankBy = logged.find(l => !used.has(l) && standsFor(l, it)) + if (blankBy) used.add(blankBy) + if (row || blankBy) rows.push(row || blankBy) } } return [...rows, ...logged.filter(l => !used.has(l))] @@ -847,13 +855,20 @@ export const liftedLine = (entry, field = null, today = localIso()) => liftsLine * as much as a logged row (D11). `measure` keeps a hold's last time to holds: sixty * reps of an old Plank is not a number to beat in seconds. * + * BEFORE the entry being edited (#111, D F3), by the rule "The last 5 times you + * did this" uses (lib/order.js `before`): a sheet opened on Nov 7 said "Last + * time · Today", and its Use filled Nov 7's blanks from Nov 8. An entry not in + * `entries` yet (nothing to compare) is not bounded, as there. + * * @param {any[]} entries @param {string} key @param {string | null} [excludeId] @param {any} [field] * @param {'reps' | 'time' | null} [measure] @param {string} [today] */ export function lastLift(entries = [], key, excludeId = null, field = null, measure = null, today = localIso()) { const hits = [] + const me = excludeId ? entries.find(e => e?.id === excludeId) : null for (const e of entries) { if (e?.deleted || e?.kind !== 'daily' || e.id === excludeId) continue + if (me?.date && !before(e, me)) continue for (const l of liftsDone(e, today)) { if (liftKeyOf(l) !== key) continue if (measure && liftMeasure(l, field) !== measure) continue @@ -873,15 +888,24 @@ export const lastTimeWhen = (prior, today = localIso()) => (prior?.date ? dayWor /** * What "use last time" writes (#93): last time's numbers into this exercise's * BLANK boxes, set by set (set 3 takes last time's set 3, or its last set when - * it had fewer), as `[{ setId, patch }]`. It never overwrites a number, never - * adds a set, and fills the weight only when it means the same thing as last - * time (the same implement in the same mode): 90 lb per side is not 90 lb on - * the bar. Empty when there is nothing to fill, which is when the line stops - * being a button. + * it had fewer), as `[{ setId, patch }]`. It never overwrites a number, and + * fills the weight only when it means the same thing as last time (the same + * implement in the same mode): 90 lb per side is not 90 lb on the bar. Empty + * when there is nothing to fill, which is when the line stops being a button. + * + * `grow` (#111, C F2): "Use" said "3 × 10 @ 95 lb" and wrote 1 × 10, because a + * new exercise has one blank set. On a card where nothing is filled in yet + * (no number, no mark on any set), it also adds the sets last time had more + * of, as `{ add: true, patch }` fills after the others, in order; writers lay + * them on with `withFills` (a plan) or `fillLift` (the log). The caller says + * when adding a set is its to do: never on a synced workout, where a set added + * is structure that crosses to the other person. * * `item` is the card's (exercises.jsx): `{ kind, implement, weightMode, sets: [{ id, … }] }`. + * + * @param {any} field @param {any} item @param {any} prior @param {{ grow?: boolean }} [opts] */ -export function lastTimeFill(field, item, prior) { +export function lastTimeFill(field, item, prior, { grow = false } = {}) { const rows = (prior?.row?.sets || []).filter(r => num(r?.reps) !== null || num(r?.seconds) !== null || num(r?.weight) !== null) if (item?.kind !== 'lift' || !rows.length) return [] const row = prior.row @@ -889,13 +913,33 @@ export function lastTimeFill(field, item, prior) { && weightModeOf(field, item) === weightModeOf(field, row) const count = liftMeasure(row, field) === 'time' ? 'seconds' : 'reps' const blank = (v) => v === null || v === undefined || v === '' - return (item.sets || []).flatMap((s, i) => { + const sets = item.sets || [] + const fills = sets.flatMap((s, i) => { const from = rows[i] || rows.at(-1) const patch = {} if (count in s && blank(s[count]) && num(from[count]) !== null) patch[count] = num(from[count]) if ('weight' in s && blank(s.weight) && sameLoad && num(from.weight) !== null) patch.weight = num(from.weight) return Object.keys(patch).length ? [{ setId: s.id, patch }] : [] }) + const untouched = sets.length > 0 && sets.every(s => !holdsNumber(s) && s?.typed !== true && s?.ticked !== true) + if (!grow || !untouched || rows.length <= sets.length) return fills + const added = rows.slice(sets.length).flatMap(from => { + const patch = {} + if (num(from[count]) !== null) patch[count] = num(from[count]) + if (sameLoad && num(from.weight) !== null) patch.weight = num(from.weight) + return Object.keys(patch).length ? [{ setId: null, add: true, patch }] : [] + }) + return [...fills, ...added] +} + +/** "Use last time"'s fills (`lastTimeFill`) on a logged lift row (`out.lifts`), added sets included. */ +export function fillLift(list, uid, fills = []) { + return fills.reduce((l, f) => { + if (!f.add) return setLiftSet(l, uid, Number(f.setId), f.patch) + const grown = addLiftSet(l, uid) + const n = liftsIn({ [LIFT_FIELD]: grown }).find(x => x.uid === uid)?.sets?.length || 0 + return setLiftSet(grown, uid, n - 1, f.patch) + }, list) } /** @@ -905,12 +949,17 @@ export function lastTimeFill(field, item, prior) { * D11). Any old mark on it goes; a patch that says `typed` (an Undo putting a * set back exactly) keeps its own. */ -export const withFills = (sets = [], fills = []) => sets.map(s => { - const f = fills.find(x => x.setId === s.id) - if (!f) return s - const { typed: _t, ...rest } = s - return { ...rest, ...f.patch } -}) +export const withFills = (sets = [], fills = []) => { + const now = sets.map(s => { + const f = fills.find(x => !x.add && x.setId === s.id) + if (!f) return s + const { typed: _t, ticked: _k, ...rest } = s + return { ...rest, ...f.patch } + }) + // Sets "Use" adds (`grow`): the last set's shape, blank as it was, holding the patch; ids are the writer's. + const { id: _i, typed: _t, ticked: _k, ...shape } = sets.at(-1) || {} + return [...now, ...fills.filter(f => f.add).map(f => ({ ...shape, note: '', ...f.patch }))] +} const COPIED = ['reps', 'seconds', 'weight', 'distance'] const holdsNumber = (s) => COPIED.some(f => num(s?.[f]) !== null) @@ -947,10 +996,11 @@ export const canCopyDown = (sets = [], i) => holdsNumber(sets[i]) && i + 1 < set export const unfills = (sets = [], fills = [], now = withFills(sets, fills)) => fills.flatMap(f => { const s = sets.find(x => x.id === f.setId) const cur = now.find(x => x.id === f.setId) - if (!s || !cur || cur.typed === true) return [] + if (!s || !cur || cur.typed === true || cur.ticked === true) return [] if (Object.keys(f.patch).some(k => num(cur[k]) !== num(f.patch[k]))) return [] const patch = Object.fromEntries(Object.keys(f.patch).map(k => [k, s[k]])) - return [{ setId: f.setId, patch: s.typed === true ? { ...patch, typed: true } : patch }] + const marks = { ...(s.typed === true ? { typed: true } : {}), ...(s.ticked === true ? { ticked: true } : {}) } + return [{ setId: f.setId, patch: { ...patch, ...marks } }] }) /** diff --git a/mobile/src/lib/order.js b/mobile/src/lib/order.js new file mode 100644 index 0000000..ef0301a --- /dev/null +++ b/mobile/src/lib/order.js @@ -0,0 +1,39 @@ +/* + * Which of two sessions came first (#96, #111): what "the last time" means + * everywhere it is asked. `priorSessions` (lib/history.js) and `lastLift` + * (lib/lifts.js) both bound by it, so "The last 5 times you did this" and "Last + * time · …" over an exercise never disagree about which day was before which. + * Its own file because lib/history.js imports lib/lifts.js. + */ + +/** + * Where an entry sits in its day, as the day list shows it (tabs.jsx): the main + * session first, then the extras by id. + */ +const dayPlace = (e) => [e?.data?.slot === 'extra' ? 1 : 0, String(e?.id || '')] + +/** + * When a session started, in ms, where something measured or stamped it: its + * run, the WHOOP or Strava workout attached to it, then its done tap. Null when + * nothing did (a lift typed on the sheet): a day carries no other clock. + */ +function startedAt(e) { + const d = e?.data || {} + for (const v of [d.run?.startedAt, d.out?.whoop?.start, d.out?.strava?.start, d.doneAt]) { + const t = typeof v === 'number' ? v : Date.parse(v) + if (Number.isFinite(t) && t > 0) return t + } + return null +} + +/** + * Is `e` before `me`: an earlier day, or earlier the same day, by when each + * started where both say, else by the day list's order. + */ +export function before(e, me) { + if (String(e.date) !== String(me.date)) return String(e.date) < String(me.date) + const [ta, tb] = [startedAt(e), startedAt(me)] + if (ta !== null && tb !== null && ta !== tb) return ta < tb + const [a, b] = [dayPlace(e), dayPlace(me)] + return a[0] !== b[0] ? a[0] < b[0] : a[1] < b[1] +} diff --git a/mobile/src/lib/prescription.js b/mobile/src/lib/prescription.js index 79cde36..13df823 100644 --- a/mobile/src/lib/prescription.js +++ b/mobile/src/lib/prescription.js @@ -1254,10 +1254,7 @@ export const patchSet = (pres, itemId, setId, patch) => export const addSet = (pres, itemId) => mapItem(pres, itemId, it => ({ ...it, sets: [...it.sets, untypedSet(it.sets.at(-1))] })) -const untypedSet = (s) => { - const { typed: _t, ...rest } = s || {} - return rest -} +const untypedSet = (s) => unmarked(s) /** * One more set of this, from the RUNNER, copying what the user just did rather than @@ -1497,7 +1494,8 @@ export function keepTyped(before, after) { items: (b.items || []).map(it => { const old = it.kind === 'lift' ? take(it) : null if (!old) return it - return { ...it, sets: (it.sets || []).map((x, i) => (old.sets?.[i]?.typed === true && same(old.sets[i], x) ? { ...x, typed: true } : x)) } + return { ...it, sets: (it.sets || []).map((x, i) => (old.sets?.[i]?.typed === true && same(old.sets[i], x) + ? { ...x, typed: true, ...(old.sets[i].ticked === true ? { ticked: true } : {}) } : x)) } }), })), } @@ -1528,11 +1526,19 @@ export function reviseWeightModes(before, after, liftField, entries = [], { excl blocks: after.blocks.map(b => ({ ...b, items: b.items.map(it => { - if (it.kind !== 'lift' || !it.exercise || !it.implement) return it + if (it.kind !== 'lift' || !it.exercise) return it const old = take(it) - const mode = old && old.implement === it.implement ? (old.weightMode || null) - : rememberedWeightMode(liftField, entries, it.exercise, it.implement, excludeId, today) - return inMode(it, liftField, mode) + // A lift the model named no implement for (#111, C F1: a catalog that + // declares none for Back squat leaves it nothing to name) keeps the one + // it had, else starts where one added by hand does (`defaultImplement`), + // so its weight means something and memory runs. + const implement = it.implement || old?.implement + || defaultImplement(liftField, it.exercise, { entries, excludeId, ...(today ? { today } : {}) }) + if (!implement) return it + const was = it.implement ? it : { ...it, implement, implementLabel: implementLabel(liftField, implement) } + const mode = old && old.implement === implement ? (old.weightMode || null) + : rememberedWeightMode(liftField, entries, it.exercise, implement, excludeId, today) + return inMode(was, liftField, mode) }), })), } @@ -1599,28 +1605,52 @@ export function moveBlock(pres, blockId, dir) { * says". That IS the log (D11, AGENTS.md §6.4 "Planned lifts are the log"), so * the tick writes the same mark a typed number leaves (`typed`), which is what * `liftsDone` reads on the plan's own day and what makes a plan for today - * touched, and so done (D10). Taking the tick off takes the mark: the numbers - * stay, as targets. A tick is never a number: nothing is copied anywhere, and a - * set with no number cannot be ticked (`setHasNumber`), because the log would - * hold nothing for it and a ✓ must always mean logged. + * touched, and so done (D10). A tick is never a number: nothing is copied + * anywhere, and a set with no number cannot be ticked (`setHasNumber`), because + * the log would hold nothing for it and a ✓ must always mean logged. + * + * EDITED IS NOT TICKED (#111, A F1). A tick also writes its own mark, + * `ticked`, because a number typed or stepped leaves `typed` too: with one mark + * for both, "+5 on the weight, lift, tap ✓" lit the ✓ on the +5 and the tap + * took it off, un-logging the set and putting today's plan back to Planned. So + * the ✓ shows `ticked` (`setTicked`); a set only edited (`setEdited`) still + * counts as logged for every reader (D11) and a tap on it TICKS it. Only a tap + * on a ticked set takes the tick off, and with it the mark the numbers left: + * "I did not do this one" (the numbers stay, as targets). Sets ticked before + * the mark existed carry `typed` alone and read as edited: still logged, one + * tap from ticked, never un-logged by a tap. Nothing stored is rewritten. */ export const tickSet = (pres, itemId, setId, on) => mapItem(pres, itemId, it => ({ ...it, sets: it.sets.map(s => { if (s.id !== setId) return s - if (on) return setHasNumber(s) ? { ...s, typed: true } : s - const { typed: _t, ...rest } = s - return rest + if (on) return setHasNumber(s) ? { ...s, typed: true, ticked: true } : s + return unmarked(s) }), })) +/** A set without either mark (`typed`, `ticked`): its numbers as targets. */ +export const unmarked = (s) => { + const { typed: _t, ticked: _k, ...rest } = s || {} + return rest +} + +/** + * Is this set's ✓ on? Ticked on the plan's own day. `asWritten` is a done plan + * whose day has passed: there every set with a number is the log, ticked or + * not, exactly as `liftsDone` reads it (lib/lifts.js). + */ +export const setTicked = (s, asWritten = false) => setHasNumber(s) && (asWritten || s?.ticked === true) + /** - * Is this set done? Ticked (or typed into, the same mark) on the plan's own - * day. `asWritten` is a done plan whose day has passed: there every set with a - * number is the log, ticked or not, exactly as `liftsDone` reads it (lib/lifts.js). + * A set whose number was typed or stepped but not ticked: logged (D11, it + * carries `typed`), shown as edited, and ticked by a tap on its ✓. */ -export const setTicked = (s, asWritten = false) => setHasNumber(s) && (asWritten || s?.typed === true) +export const setEdited = (s) => setHasNumber(s) && s?.typed === true && s?.ticked !== true + +/** Is this set in the log (D11): ticked, or edited (a number typed into it). */ +export const setLogged = (s, asWritten = false) => setTicked(s, asWritten) || setEdited(s) /** Does this set hold a number to log? A ✓ on one without is nothing logged. */ export const setHasNumber = (s) => ['reps', 'weight', 'seconds', 'distance'].some(f => num(s?.[f]) !== null) @@ -1653,8 +1683,19 @@ export function doingMove(before = {}, after = {}) { * logged so far ("1 exercise · 1 set · 900 lb" over a plan of six). */ export function planProgress(pres, asWritten = false) { - const sets = (pres?.blocks || []).flatMap(b => b.items || []).flatMap(it => it.sets || []) - return { done: sets.filter(s => setTicked(s, asWritten)).length, total: sets.length } + return (pres?.blocks || []).flatMap(b => b.items || []).map(it => itemProgress(it, asWritten)) + .reduce((a, p) => ({ done: a.done + p.done, total: a.total + p.total }), { done: 0, total: 0 }) +} + +/** + * How far one exercise has got: its sets in the log (`setLogged`: ticked or + * edited) out of its sets. The card's "2 of 3 done" and the Today row's + * "4 of 18 sets" (`planProgress`) are both this, so they never disagree (#111 + * review). Whether the card is FINISHED (folds, moves on) is ticks only (`itemTicked`). + */ +export function itemProgress(it, asWritten = false) { + const sets = it?.sets || [] + return { done: sets.filter(s => setLogged(s, asWritten)).length, total: sets.length } } /** @@ -1815,6 +1856,6 @@ export const dropEmptyBlocks = (pres) => reindex({ .map(({ wasCircuit: _w, ...b }) => ({ ...b, items: (b.items || []).map(untyped) })), }) -const untyped = (it) => ({ ...it, sets: (it.sets || []).map(({ typed: _t, ...s }) => s) }) +const untyped = (it) => ({ ...it, sets: (it.sets || []).map(unmarked) }) export { catalogOf } diff --git a/mobile/src/lib/shared.js b/mobile/src/lib/shared.js index 0f8a0dd..81ad770 100644 --- a/mobile/src/lib/shared.js +++ b/mobile/src/lib/shared.js @@ -28,6 +28,7 @@ */ import { extraEntryId } from './store.js' +import { localIso } from './dates.js' import { blankSet, liftMeasure } from './lifts.js' import { reindex, remapRun } from './prescription.js' @@ -188,18 +189,35 @@ function keyed(pres) { */ const noMode = ({ weightMode: _m, weightLabel: _l, ...rest }) => rest -/** A copy of their own last set: its numbers as a start, but not typed until they type into it. */ -const untypedCopy = ({ typed: _t, ...s }) => ({ ...s, note: '' }) +/** A copy of their own last set: its numbers as a start, but not typed (or ticked) until they type into it. */ +const untypedCopy = ({ typed: _t, ticked: _k, ...s }) => ({ ...s, note: '' }) -/** One of the owner's sets on their side: the target, not the owner's weight, cue or anything they typed. */ -const theirSet = ({ typed: _t, ...s }) => ({ ...s, weight: null, note: '' }) +/** + * One of the owner's sets as it arrives on someone else's side (#111, D F1): + * the target, never the owner's weight, cue, or anything the owner did. On a + * workout dated today or earlier (`logged`), a lift set the owner typed into or + * ticked is the owner's LOG (D11), so it crosses blank, as every lift set the server's sync carries does (server/sharedsync.js + * `freshItem`, held to this by sharedsync.test.js): carried as a target, the + * owner's 10 reps read on their side, from the next day on, as reps they lifted. + * An untouched target crosses as the plan wrote it. On a plan for a later day + * nothing has been lifted yet: a number typed there is planning (`patchSet` + * marks every edit), a target like any other, and crosses as one. An + * interval's numbers are its shape, typed or not, as the server keeps them. + * + * @param {string | undefined} kind @param {any} s @param {{ logged?: boolean }} [opts] + */ +export function crossingSet(kind, s, { logged = true } = {}) { + const { typed, ticked: _k, ...rest } = s || {} + const owners = logged && kind === 'lift' && typed === true + return { ...rest, ...(owners ? { reps: null, seconds: null, distance: null } : {}), weight: null, note: '' } +} /** * One of the owner's exercises on their side: the target, not the owner's * weight, what it meant, or the planner's note on it ("3x10 at 95 was RPE 6 * last time", written from the owner's log). */ -const theirItem = (item) => ({ ...noMode(item), note: '', sets: (item.sets || []).map(theirSet) }) +const theirItem = (item, logged) => ({ ...noMode(item), note: '', sets: (item.sets || []).map(x => crossingSet(item.kind, x, { logged })) }) /** * The owner's plan as the start of theirs: the exercises, never the owner's @@ -208,9 +226,9 @@ const theirItem = (item) => ({ ...noMode(item), note: '', sets: (item.sets || [] * the owner's conversation with the planner or its reasoning about the owner's * log (`thread`, `why`, `notes`, `changed`). */ -function theirPlan(mine) { +function theirPlan(mine, logged) { const { draftId: _d, ...plan } = ownerWordsOff(mine) - return { ...plan, blocks: mine.blocks.map(b => ({ ...b, items: (b.items || []).map(theirItem) })) } + return { ...plan, blocks: mine.blocks.map(b => ({ ...b, items: (b.items || []).map(it => theirItem(it, logged)) })) } } /** @@ -337,9 +355,9 @@ export function syncedSides(entry, on = [], side = null) { } /** Their plan with every exercise and set of the owner's that it lacks. Never takes anything out. */ -function copyPlan(theirs, mine) { +function copyPlan(theirs, mine, logged) { if (!mine?.blocks?.length) return theirs - if (!theirs?.blocks?.length) return theirPlan(mine) + if (!theirs?.blocks?.length) return theirPlan(mine, logged) const have = new Map(keyed(theirs).map(x => [x.key, x.item])) const blocks = theirs.blocks.map(b => ({ ...b, items: [...(b.items || [])] })) let changed = false @@ -348,12 +366,12 @@ function copyPlan(theirs, mine) { if (!t) { // A new exercise goes at the end of the same block (a block of the owner's if they have none there). while (blocks.length <= bi) blocks.push({ ...mine.blocks[blocks.length], items: [] }) - blocks[bi].items.push(theirItem(item)) + blocks[bi].items.push(theirItem(item, logged)) changed = true } else if ((item.sets || []).length > (t.sets || []).length) { // More sets of the owner's: copies of their own last set, as adding a set does. const sets = [...(t.sets || [])] - while (sets.length < item.sets.length) sets.push(sets.length ? untypedCopy(sets.at(-1)) : theirSet(item.sets[sets.length])) + while (sets.length < item.sets.length) sets.push(sets.length ? untypedCopy(sets.at(-1)) : crossingSet(item.kind, item.sets[sets.length], { logged })) const b = blocks.find(x => x.items.includes(t)) b.items = b.items.map(x => (x === t ? { ...t, sets } : x)) changed = true @@ -386,14 +404,19 @@ function copyLifts(theirs, mine) { * plan's exercises and set counts (with no weight; their logged sets kept across * the renumber), otherwise the logged lifts as blank rows. Only ever adds: their * numbers, their own exercises and anything they took out of a set count stay as - * they are. The same object back when there is nothing to copy. + * they are. The same object back when there is nothing to copy. `today` + * decides whether the owner's typed numbers are a log or still a plan + * (`crossingSet`). + * + * @param {any} copy @param {any} ownerEntry @param {string} [today] */ -export function copyExercises(copy, ownerEntry) { +export function copyExercises(copy, ownerEntry, today = localIso()) { const mine = ownerEntry?.data if (!copy?.data || copy.deleted || !mine || ownerEntry.deleted) return copy if (mine.plan) { const before = copy.data.plan - const plan = copyPlan(before, mine.plan) + const logged = !ownerEntry.date || String(ownerEntry.date) <= today + const plan = copyPlan(before, mine.plan, logged) if (plan === before) return copy const next = reindex(plan) const data = { ...copy.data, plan: next } @@ -435,7 +458,7 @@ export function copyIdFor(ownerEntry, theirDay = []) { * the session, the shared facts and the owner's exercises without the owner's * weights; none of the owner's numbers, effort or notes. */ -export function sharedCopy(ownerEntry, { id, session = null, owner = null } = {}) { +export function sharedCopy(ownerEntry, { id, session = null, owner = null, today = localIso() } = {}) { const d = ownerEntry?.data || {} const copyId = id || ownerEntry.id const data = { @@ -449,12 +472,15 @@ export function sharedCopy(ownerEntry, { id, session = null, owner = null } = {} } if (d.minutes !== undefined) data.minutes = d.minutes if (d.training === false) data.training = false - return copyExercises({ id: copyId, kind: 'daily', date: ownerEntry.date, data }, ownerEntry) + return copyExercises({ id: copyId, kind: 'daily', date: ownerEntry.date, data }, ownerEntry, today) } /** Are this workout's exercises kept the same on this person's side? */ export const isSynced = (entry, personId) => sharedWithOf(entry).some(s => s.id === personId && s.sync === true) +/** Is anyone else on this workout: shared by its owner, or someone's copy? Then a set added may cross (#111). */ +export const isSharedEntry = (entry) => sharedWithOf(entry).length > 0 || Boolean(entry?.data?.sharedFrom) + /** The owner's entry with someone added to it, synced (or, `remove`, taken off it). */ export function withSharedPerson(ownerEntry, personId, entryId, { remove = false } = {}) { const rest = sharedWithOf(ownerEntry).filter(s => s.id !== personId) diff --git a/server/drafts.js b/server/drafts.js index cb8c07f..040794e 100644 --- a/server/drafts.js +++ b/server/drafts.js @@ -185,7 +185,7 @@ function createDrafts({ max = MAX_DRAFTS, maxAgeMs = MAX_AGE_MS, now = () => Dat Promise.resolve() .then(() => plan({ kind, draft: working, message, signal: ctrl.signal })) - .then((built) => settle(d => merged(d, kind, built?.plan, built?.remembered))) + .then((built) => settle(d => merged(d, kind, built?.plan, built?.remembered, built?.lifting))) .catch((err) => settle(d => failed(d, String(err?.message || err || 'the planner failed')))) return working } @@ -202,7 +202,7 @@ function createDrafts({ max = MAX_DRAFTS, maxAgeMs = MAX_AGE_MS, now = () => Dat * same rule as `reviseWeightModes` in app/src/lib/prescription.js, here so it * is on the draft, whatever happens to the page that asked. */ - function withWeightModes(before, after, remembered) { + function withWeightModes(before, after, remembered, lifting = null) { const items = (blocks) => (Array.isArray(blocks) ? blocks : []).flatMap(b => (Array.isArray(b?.items) ? b.items : [])) const left = items(before).filter(it => it?.kind === 'lift') const take = (it) => { @@ -212,12 +212,18 @@ function createDrafts({ max = MAX_DRAFTS, maxAgeMs = MAX_AGE_MS, now = () => Dat return after.map(b => (Array.isArray(b?.items) ? { ...b, items: b.items.map(it => { - if (it?.kind !== 'lift' || !it.exercise || !it.implement) return it + if (it?.kind !== 'lift' || !it.exercise) return it const old = take(it) - const mode = old && old.implement === it.implement ? old.weightMode - : remembered?.get(`${it.exercise}|${it.implement}`) + // No implement from the model (#111, C F1: the catalog declares none for + // a Back squat, so it cannot name one): the one it had on a revision, else + // where one added by hand starts (`defaultImplementOf`), so the weight + // means something and memory runs. The app labels it (`normalizeItem`). + const implement = it.implement || old?.implement || defaultImplementOf(lifting?.field, it.exercise, lifting?.last) + if (!implement) return it + const mode = old && old.implement === implement ? old.weightMode + : remembered?.get(`${it.exercise}|${implement}`) const { weightMode: _m, ...rest } = it - return mode ? { ...rest, weightMode: mode } : rest + return { ...rest, implement, ...(mode ? { weightMode: mode } : {}) } }), } : b)) } @@ -228,7 +234,7 @@ function createDrafts({ max = MAX_DRAFTS, maxAgeMs = MAX_AGE_MS, now = () => Dat * blank; on a revision the user's own category choice stands, and `changed` * becomes the newest line of the thread. */ - function merged(d, kind, built, remembered = null) { + function merged(d, kind, built, remembered = null, lifting = null) { if (!built || !Array.isArray(built.blocks) || !built.blocks.length) { return failed(d, 'the planner returned nothing usable') } @@ -238,7 +244,7 @@ function createDrafts({ max = MAX_DRAFTS, maxAgeMs = MAX_AGE_MS, now = () => Dat ...d, status: 'ready', error: null, updatedAt: stamp(), pres: { ...cur, ...built, - blocks: withWeightModes(cur.blocks, built.blocks, remembered), + blocks: withWeightModes(cur.blocks, built.blocks, remembered, lifting), category: cur.category || built.category || null, activity: cur.activity || built.activity || null, ask: cur.ask || null, @@ -251,7 +257,7 @@ function createDrafts({ max = MAX_DRAFTS, maxAgeMs = MAX_AGE_MS, now = () => Dat ...d, status: 'ready', error: null, updatedAt: stamp(), pres: { ...built, - blocks: withWeightModes([], built.blocks, remembered), + blocks: withWeightModes([], built.blocks, remembered, lifting), category: built.category || primary.category || null, activity: built.activity || primary.activity || null, focus: built.focus || d.ask.goal || d.ask.label, @@ -429,4 +435,65 @@ function rememberedModes(entries, today) { return new Map([...best].map(([k, v]) => [k, v.mode])) } -module.exports = { createDrafts, dirOf, keptIdsIn, rememberedModes, MAX_DRAFTS, MAX_AGE_MS, CLAIM_MS, RESTARTED } +/* + * The implement each exercise was last LIFTED with (#111): app/src/lib/lifts.js + * `rememberedImplement` for every exercise at once, read as `rememberedModes` + * reads (the same rows, the same entries, the newest decides). + */ +function rememberedImplements(entries, today) { + const best = new Map() + for (const e of Object.values(entries || {})) { + if (!e || e.deleted || e.kind !== 'daily' || !(String(e.date || '') <= today)) continue + if (e.data?.done === false && e.data?.undone === true) continue + const at = `${e.date || ''}|${e.updatedAt || ''}` + const seen = new Set() + for (const l of liftedRows(e, today)) { + const key = l?.key || l?.exercise + if (!key || seen.has(key) || !l.implement || !(l.sets || []).some(numbered)) continue + seen.add(key) + const b = best.get(key) + if (!b || at > b.at) best.set(key, { at, implement: l.implement }) + } + } + return new Map([...best].map(([k, v]) => [k, v.implement])) +} + +/** The plan's `type: "lifts"` field (the exercise catalog), as app/src/lib/lifts.js `liftFieldOf`. */ +function liftFieldOf(plan) { + for (const opt of Array.isArray(plan?.dailyMenu) ? plan.dailyMenu : []) { + for (const f of Array.isArray(opt?.outputs) ? opt.outputs : []) if (f?.type === 'lifts') return f + } + return null +} + +/* + * What a model-written lift is done with when it names nothing (#111): app/src/ + * lib/lifts.js `defaultImplement`, the rule a lift added by hand starts on, and + * drafts.test.js holds the two to the same answers. `last` is + * `rememberedImplements`. In order: the one it was last lifted with (if the + * catalog still has it), the only one the catalog offers it, the first it + * declares, the one implement its library `equipment` line names; else none. + */ +function defaultImplementOf(field, key, last = null) { + const all = Array.isArray(field?.implements) ? field.implements : [] + const known = (v) => all.some(i => i.value === v) + const remembered = last?.get?.(key) + if (remembered && known(remembered)) return remembered + const ex = (Array.isArray(field?.exercises) ? field.exercises : []).find(e => e?.key === key) || null + const declared = Array.isArray(ex?.implements) && ex.implements.length ? ex.implements : null + const offered = declared ? all.filter(i => declared.includes(i.value)) : all + if (offered.length === 1) return offered[0].value + if (declared && known(declared[0])) return declared[0] + const said = String(ex?.equipment || '').toLowerCase() + if (!said) return '' + const named = all.filter(i => { + const word = String(i.label || '').toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + return word && new RegExp(`(^|[^a-z])${word}s?([^a-z]|$)`).test(said) + }) + return named.length === 1 ? named[0].value : '' +} + +module.exports = { + createDrafts, dirOf, keptIdsIn, rememberedModes, rememberedImplements, liftFieldOf, defaultImplementOf, + MAX_DRAFTS, MAX_AGE_MS, CLAIM_MS, RESTARTED, +} diff --git a/server/drafts.test.js b/server/drafts.test.js index 375ff71..2a8cffe 100644 --- a/server/drafts.test.js +++ b/server/drafts.test.js @@ -6,7 +6,7 @@ const fs = require('fs') const os = require('os') const path = require('path') -const { createDrafts, rememberedModes, keptIdsIn, RESTARTED, CLAIM_MS } = require('./drafts.js') +const { createDrafts, rememberedModes, rememberedImplements, defaultImplementOf, liftFieldOf, keptIdsIn, RESTARTED, CLAIM_MS } = require('./drafts.js') let failed = 0 const ok = (v, m) => { if (!v) throw new Error(m || 'expected truthy') } @@ -167,6 +167,45 @@ const ASK = { picked: [{ key: 'legs', label: 'Legs', prompt: 'a leg day', catego eq(JSON.parse(fs.readFileSync(path.join(dir, `${d.id}.json`), 'utf8')).pres.blocks[0].items.map(it => it.weightMode ?? null), [null, 'one', 'one']) }) + await step('a lift the model named no implement for starts where one added by hand does (#111, C F1)', async () => { + const field = liftFieldOf(JSON.parse(fs.readFileSync(path.join(__dirname, '../test/fixtures/plan.json'), 'utf8'))) + const TODAY = '2026-11-08' + const squat = { id: 'sq', kind: 'daily', date: '2026-09-17', updatedAt: 'a', data: { out: { lifts: [{ uid: 'sq-1', key: 'back-squat', implement: 'barbell', weightMode: 'side', sets: [{ reps: 10, weight: 95 }] }] } } } + const entries = { [squat.id]: squat } + const dir = tmp(); const s = createDrafts(); const p = fakePlanner() + const d = s.create(dir, ASK, p.fn) + await tick() + const lift = (o) => ({ kind: 'lift', sets: [{ reps: 10 }], ...o }) + p.calls[0].resolve({ + ...PLAN({ blocks: [{ name: 'Main', items: [ + lift({ name: 'Back squat', exercise: 'back-squat' }), + lift({ name: 'Pull-up', exercise: 'pull-up' }), + lift({ name: 'Bench press', exercise: 'bench-press' }), + lift({ name: 'Split squat', exercise: 'split-squat', implement: 'kettlebell' }), + ] }] }), + remembered: rememberedModes(entries, TODAY), + lifting: { field, last: rememberedImplements(entries, TODAY) }, + }) + await tick() + const items = s.read(dir, d.id).pres.blocks[0].items + eq(items.map(it => it.implement ?? null), ['barbell', 'bodyweight', null, 'kettlebell'], + 'the squat did not start on the barbell it was last lifted with, the pull-up on its first declared implement, or a named one moved') + eq(items[0].weightMode, 'side', 'the remembered mode of the remembered implement was not applied') + // The server's rule is the app's, case for case. + const { defaultImplement } = await import('../app/src/lib/lifts.js') + const log = Object.values(entries) + for (const key of ['back-squat', 'pull-up', 'bench-press', 'split-squat', 'plank', 'no-such-exercise']) { + eq(defaultImplementOf(field, key, rememberedImplements(entries, TODAY)) || '', defaultImplement(field, key, { entries: log, today: TODAY }) || '', `the server and the app disagree on ${key}`) + } + // A revision keeps the implement a kept exercise had when the model drops it. + const mine = { ...s.read(dir, d.id).pres } + s.revise(dir, d.id, { message: 'harder', pres: mine }, p.fn) + await tick() + p.calls[1].resolve({ ...PLAN({ blocks: [{ name: 'Main', items: [lift({ name: 'Split squat', exercise: 'split-squat' })] }] }), remembered: new Map(), lifting: { field, last: new Map() } }) + await tick() + eq(s.read(dir, d.id).pres.blocks[0].items[0].implement, 'kettlebell', 'a revision lost the implement the exercise had') + }) + await step('weight-mode memory: the server reads a log exactly as the app does (#58)', async () => { const { rememberedWeightMode } = await import('../app/src/lib/lifts.js') const TODAY = '2026-10-28' diff --git a/server/server.js b/server/server.js index cf2e22f..199feed 100644 --- a/server/server.js +++ b/server/server.js @@ -56,7 +56,7 @@ const fsp = require('fs/promises') const path = require('path') const { spawn } = require('child_process') const planner = require('./planner.js') -const { createDrafts, dirOf: draftsDir, keptIdsIn, rememberedModes } = require('./drafts.js') +const { createDrafts, dirOf: draftsDir, keptIdsIn, rememberedModes, rememberedImplements, liftFieldOf } = require('./drafts.js') const { createBushidoNotify } = require('./notify.js') const notifyFacts = require('./notify-facts.js') const { createConfig } = require('./config.js') @@ -2422,8 +2422,17 @@ const server = http.createServer(async (req, res) => { // space: with the owner in it, the owner's memory (the plan lands in the // owner's log; each copy is that person's own); without, the default, since // the owner's memory is not theirs (#59). - .then(r => ({ ...r, remembered: group && !group.some(p => p.owner) ? new Map() - : rememberedModes(readStateSync(target).state.entries, todayKey()) })) + // Which implement each exercise was last lifted with, the same way, and the + // catalog, for a lift the model named none for (#111). + .then(r => { + const mine = !(group && !group.some(p => p.owner)) + const entries = mine ? readStateSync(target).state.entries : null + return { + ...r, + remembered: mine ? rememberedModes(entries, todayKey()) : new Map(), + lifting: { field: liftFieldOf(plan), last: mine ? rememberedImplements(entries, todayKey()) : new Map() }, + } + }) } const answer = (fn) => { try { return send(res, 200, { draft: fn() }) } catch (err) { diff --git a/server/sharedsync.js b/server/sharedsync.js index 9081c1b..0fd7410 100644 --- a/server/sharedsync.js +++ b/server/sharedsync.js @@ -302,7 +302,7 @@ const blankPlanSet = (unit = null) => ({ reps: null, weight: null, seconds: null function newPlanSet(item, sets) { const last = sets.at(-1) if (item.kind !== 'lift' && last) { - const { typed: _t, ...shape } = last + const { typed: _t, ticked: _k, ...shape } = last return { ...shape, note: '' } } return blankPlanSet(last?.unit ?? item.unit ?? null) diff --git a/server/sharedsync.test.js b/server/sharedsync.test.js index 96dfc22..1769d78 100644 --- a/server/sharedsync.test.js +++ b/server/sharedsync.test.js @@ -108,6 +108,14 @@ check('removed on one side: gone on the other unless the other logged on it', () const typedAll = (data) => ({ ...data, plan: { ...data.plan, blocks: data.plan.blocks.map(b => ({ ...b, items: b.items.map(i => ({ ...i, sets: i.sets.map(x => ({ ...x, typed: true })) })) })) } }) +check('#111: an exercise added over there arrives with none of their typed or ticked numbers (the app\'s crossingSet rule)', () => { + const before = alex() + const after = edit(before, bs => { bs[0].items.push(lift('BP', 'Bench press', [set({ reps: 10, weight: 135, typed: true, ticked: true }), set({ reps: 10, weight: 135, typed: true })])); return bs }) + const got = itemNamed(carry(sam(), shapeOf(before), after), 'Bench press') + ok(got, 'the new exercise did not arrive') + eq(got.sets.map(x => [x.reps, x.weight, x.typed ?? null, x.ticked ?? null]), [[null, null, null, null], [null, null, null, null]], 'a typed number or its marks crossed') +}) + check('numbers typed into the plan are logged too: the other side\'s removal never takes them', () => { // Sam filled in sets on the sheet without ever starting the runner. const typed = typedAll({ ...sam(), run: undefined }) diff --git a/test/fixtures/plan.json b/test/fixtures/plan.json index ca454db..4278413 100644 --- a/test/fixtures/plan.json +++ b/test/fixtures/plan.json @@ -5191,6 +5191,7 @@ "key": "problems", "name": "Problems climbed", "defaultSets": 1, + "addSets": false, "fields": [ "reps" ], @@ -5337,6 +5338,7 @@ "key": "routes", "name": "Routes climbed", "defaultSets": 1, + "addSets": false, "fields": [ "reps" ],