From 65e870b8f059d3811359f11ee9a2403cbe4e6af5 Mon Sep 17 00:00:00 2001 From: ehonis Date: Sun, 8 Nov 2026 10:56:48 -0500 Subject: [PATCH] Planning polish: footer returns, Start always starts, one 'What is it?' (#95) (+1 more) Published from the private repository by oss-sync. - Climbing: counts are what was climbed, one summary everywhere, charts where you look (#97) - Planning polish: footer returns, Start always starts, one 'What is it?' (#95) 70 files changed, 3265 insertions(+), 547 deletions(-) --- .gitignore | 3 + AGENTS.md | 38 +++- app/blockmenu.dom.test.jsx | 92 +++++++++ app/editing.dom.test.jsx | 116 +++++++++++ app/editing.test.js | 96 +++++++++ app/gear.test.js | 22 ++- app/libsync.native.diff | 4 - app/package-lock.json | 49 +++++ app/package.json | 3 + app/planflow.test.js | 24 +++ app/prescription.test.js | 48 +++++ app/progress.test.js | 73 ++++++- app/smoke/editor.jsx | 79 ++++++-- app/smoke/fixtures.jsx | 2 + app/smoke/log.jsx | 4 +- app/smoke/misc.jsx | 18 +- app/smoke/planner.jsx | 23 ++- app/smoke/profile.jsx | 24 +++ app/smoke/progress.jsx | 16 +- app/smoke/sheet.jsx | 99 +++++++++- app/smoke/today.jsx | 41 +++- app/src/css/editor.css | 27 +-- app/src/css/feed.css | 10 + app/src/css/profile.css | 19 ++ app/src/css/setlog.css | 17 ++ app/src/editor.jsx | 244 ++++++++++++++--------- app/src/lib/gear.js | 13 +- app/src/lib/grades.js | 110 ++++++++++- app/src/lib/metrics.js | 140 +++++++++----- app/src/lib/planflow.js | 9 +- app/src/lib/prescription.js | 105 ++++++++-- app/src/lib/stats.js | 48 +---- app/src/lib/trainer.js | 8 +- app/src/lib/viz.jsx | 13 +- app/src/lib/vizscale.js | 15 ++ app/src/modal.jsx | 82 ++++++-- app/src/planner.jsx | 47 ++++- app/src/session.jsx | 28 +++ app/src/sessionlog.jsx | 15 +- app/src/setlog.jsx | 88 ++++++--- app/src/sheet.jsx | 10 +- app/src/tabs.jsx | 31 ++- app/src/testing.jsx | 39 +++- app/starter.build.mjs | 21 +- app/trainer.test.js | 44 ++++- app/workout.test.js | 46 ++++- content/starter.json | 300 ++++++++++++++++++++++++++++- examples/plan.json | 298 ++++++++++++++++++++++++++++ mobile/src/features/editor.tsx | 43 ++++- mobile/src/features/log.tsx | 32 ++- mobile/src/features/planner.tsx | 51 +++-- mobile/src/features/progress.tsx | 28 ++- mobile/src/features/session.tsx | 20 ++ mobile/src/features/sessionlog.tsx | 15 +- mobile/src/features/setlog.tsx | 71 +++++-- mobile/src/features/sheet.tsx | 10 +- mobile/src/features/tabs.tsx | 30 ++- mobile/src/features/testing.tsx | 38 +++- mobile/src/lib/gear.js | 13 +- mobile/src/lib/grades.js | 110 ++++++++++- mobile/src/lib/metrics.js | 140 +++++++++----- mobile/src/lib/planflow.js | 9 +- mobile/src/lib/prescription.js | 105 ++++++++-- mobile/src/lib/stats.js | 49 +---- mobile/src/lib/trainer.js | 8 +- mobile/src/lib/viz.tsx | 13 +- mobile/src/lib/vizscale.js | 15 ++ scripts/test.mjs | 2 +- server/config.test.js | 9 +- test/fixtures/plan.json | 300 ++++++++++++++++++++++++++++- 70 files changed, 3265 insertions(+), 547 deletions(-) create mode 100644 app/blockmenu.dom.test.jsx create mode 100644 app/editing.dom.test.jsx create mode 100644 app/editing.test.js diff --git a/.gitignore b/.gitignore index bb5eff9..3c776ed 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,9 @@ app/node_modules/ app/smoke/.smoke.mjs app/.mdtest.mjs app/.planflowtest.mjs +app/.editingtest.mjs +app/.editingdomtest.mjs +app/.blockmenudomtest.mjs # Your actual training log and its snapshots. Runtime state, not source: # it changes on every session and would be pure merge noise. Back it up with diff --git a/AGENTS.md b/AGENTS.md index e7b1be6..d38f5f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,7 +50,7 @@ reasons behind the design, and the things that have been removed on purpose. | `app/` | React 19 + Vite frontend. `app/src/` is the UI; `app/src/lib/` is the pure logic, tested without a DOM. | | `server/` | Plain Node `http`/`fs`/`crypto`, no npm dependencies. | | `mobile/` | The native iPhone app (Expo). The web's phone layout rebuilt in React Native, with `app/src/lib/` copied in at the same paths. Its own install and rules: read `mobile/AGENTS.md` before changing it, and port a web change there when it touches a screen the app has. | -| `content/starter.json` | What a fresh install runs on: catalogs and the rest card, no programme. **Generated.** | +| `content/starter.json` | What a fresh install runs on: catalogs, the rest card, and two plain climbing cards (Bouldering, Rock climbing, #97), no programme. **Generated.** | | `content/exercises.json` | The shared exercise library (#63, written by #64), merged into every plan's lift catalog as it is served (§5). Optional: an install without it runs on the plan alone. `test/fixtures/exercises.json` is a small one the suites use. | | `examples/plan.json` | A small, invented example plan (Settings → "Use the example plan"). **Generated.** | | `test/fixtures/plan.json` | A large synthetic climbing-and-triathlon programme used by the test suites (smoke render, every app suite, `starter.test.mjs`) and by `starter.build.mjs` / `muscles.build.mjs`. The canonical fixture, and the source both generated files are built from. | @@ -890,6 +890,23 @@ no rebuild. An older plan file may also carry `recommender`, `checkin`, `journal `MAX_CLIMBS`, 99, the bound the per-rep grade pickers share). Switching it off strips the list, and asks first when anything was said on it (`saidIn`). Per-rep grade pickers have the same bound (`repCount`), so a lap's grade and its record always pair up. +- **Described climbs are the count** (#97). With the detail off a row counts its `reps`. + With it on, the list holds the count as blank records, which are the count standing in + (often the plan's prefill), never climbs: once ANY climb in a row is described (something + said on its record, or a doubled lap's grade picked), the described climbs are the row's + count; until one is, `reps` stands. `climbsCounted` in `lib/grades.js` is the one statement + 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. +- **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 + (`mootHardest`): every reader takes the climbs then, so it was a second, ignored answer. +- **A climbing card being logged opens on its log** (#97): on a sheet for today or earlier, + a card whose log counts climbs (`climbLogLeads` in `session.jsx`) shows its dose, "last + time", the log, then the protocol and evidence in one fold ("About this session", + `SessionAbout`). A day still to come is planning and keeps the protocol open. - **Lifts are chosen at log time**, so they are `out.lifts` (one record per exercise with `implement` and `sets: [{ reps, weight }]`), not `out.sets`. Rows store their own `name`/`implementLabel` so retiring a catalog entry never blanks history. The exercise @@ -1180,7 +1197,22 @@ no rebuild. An older plan file may also carry `recommender`, `checkin`, `journal the page draws whichever apply and have data. Two points minimum for a line. - **Groups render in registry order, and Climbing is last.** The page leads with workouts and time for the period; hard finger days are a Climbing chart. Pinned in - `progress.test.js` (`climbing charts come after the general ones`). + `progress.test.js` (`climbing charts come after the general ones`). The one exception + (#97): with **Climbing picked** as the activity the Climbing group leads (`metricsFor`), + because the person asked about climbing. Inside the group the pyramids and hardest sent + come first, then climbs per week and hard finger days. +- **Hardest sent is like with like** (#97): the best of each WEEK, at the day it was sent, + and each point carries the card it came from (`of`); the chart's change is measured + from the earliest point of the newest point's card (`deltaBase` in `lib/vizscale.js`). + Points with no `of` compare first to last. **Volume cards are not a hardest send** + (`volumeCard` in `metrics.js`): a card whose declared finger load (`sched.fingerLoad`, + else its category's) is `light`, `sub` or `none` (ARC, traverses, doubled lead laps, + the economy drill) is left out of both hardest lines, so an ARC day never reads as a + drop; its climbs still count in the pyramids and Climbs per week. Read off the + declaration, never a list of names; a card that declares neither is kept. +- **Hard finger days have one rule**, `hardDates` in `lib/fingers.js`; Progress reads it. +- **Gear hours are typed or measured time only** (`loggedMinutes`), never the card's + estimate that `data.minutes` carries when nothing was typed (#97). - Charts are titled in plain words ("Effort per week", not "training load"); the effort chart is still sRPE (RPE × minutes), which is why minutes are measured when possible. @@ -1566,7 +1598,7 @@ What that means for the code that stays: from `settings.json` on the next save, as any removed setting always was. - **Climbing follows, it does not lead.** In Log a workout the sports catalog comes first and the Climbing folders after it; on Progress the headline is general and the Climbing - group is last. Both are ordered in code, because the owner's plan file is outside the + group is last (unless Climbing is the activity picked, #97). Both are ordered in code, because the owner's plan file is outside the repo and cannot be reordered from here. The one exception is a single **Climbing** row under Recent in Log a workout (#81): a door, the same as Recent being the person's own history, not climbing leading the catalog. diff --git a/app/blockmenu.dom.test.jsx b/app/blockmenu.dom.test.jsx new file mode 100644 index 0000000..5f54d04 --- /dev/null +++ b/app/blockmenu.dom.test.jsx @@ -0,0 +1,92 @@ +// The block's ⋯ (editor.jsx BlockMenu) in a real DOM (happy-dom), driven as a +// phone drives it: a tap takes no focus, so a name being typed is never blurred +// into the plan. Every action in the menu carries it (#95 review: Circuit turned +// the block into another component and the name box reset to "New block"). +// Bundled by esbuild (JSX) and run in node. +import assert from 'node:assert/strict' +import { createRequire } from 'node:module' +import { Window } from 'happy-dom' + +const win = new Window({ url: 'http://localhost/' }) +win.matchMedia = (q) => ({ matches: /coarse/.test(q), media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }) +for (const k of ['window', 'document', 'navigator', 'MutationObserver', 'HTMLElement', 'HTMLIFrameElement', 'HTMLInputElement', 'Node', 'Event', 'getComputedStyle', 'localStorage']) { + const value = k === 'window' ? win : k === 'getComputedStyle' ? win.getComputedStyle.bind(win) : win[k] + Object.defineProperty(globalThis, k, { value, configurable: true, writable: true }) +} +win.scrollTo = () => {} +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +const { act, useState } = await import('react') +const { createRoot } = await import('react-dom/client') +const { PrescriptionEditor } = await import('./src/editor.jsx') +const { normalizePrescription } = await import('./src/lib/prescription.js') +const { liftFieldOf } = await import('./src/lib/lifts.js') +const PLAN = createRequire(import.meta.url)('../test/fixtures/plan.json') +const liftField = liftFieldOf(PLAN) + +const tests = [] +const test = (name, fn) => tests.push([name, fn]) + +let latest = null +function Host({ start }) { + const [pres, setPres] = useState(start) + latest = pres + return +} + +async function mount(start) { + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + await act(async () => root.render()) + return () => act(() => root.unmount()) +} + +const click = (el) => act(() => { el.dispatchEvent(new win.MouseEvent('click', { bubbles: true })) }) +const byText = (re) => [...document.querySelectorAll('button')].find(b => re.test(b.textContent.trim())) +/** Type into a controlled box the way React hears it, and never blur it (a phone's tap). */ +const typeInto = (input, value) => act(() => { + const set = Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'value').set + set.call(input, value) + input.dispatchEvent(new win.Event('input', { bubbles: true })) +}) +const nameBox = () => document.querySelector('.blockmenu-name input') + +const START = normalizePrescription({ title: 'Legs', blocks: [ + { name: 'Main', items: [{ kind: 'interval', name: 'Spin', sets: [{ seconds: 300 }] }] }, +] }, { liftField }) + +test('a name being typed survives Circuit (the block becomes another component)', async () => { + const done = await mount(START) + await click(byText(/^Add a block$/)) + assert.equal(nameBox().value, 'New block') + await typeInto(nameBox(), 'Finisher') + await click(document.querySelector('.blockmenu input[role=switch]')) + const b = latest.blocks.at(-1) + assert.ok(b.circuit, 'Circuit did not switch on') + assert.equal(b.name, 'Finisher', 'the name being typed was thrown away when Circuit was tapped') + assert.equal(nameBox()?.value, 'Finisher', 'the reopened menu shows the old name') + await done() +}) + +test('a name being typed goes with a move, and with Where it lands', async () => { + const done = await mount(START) + await click(byText(/^Add a block$/)) + await typeInto(nameBox(), 'Cool-down') + await click(byText(/^Move block up$/)) + assert.deepEqual(latest.blocks.map(x => x.name), ['Cool-down', 'Main'], 'the move lost the name') + await typeInto(nameBox(), 'Warm-up') + await click(byText(/^Where it lands/)) + const run = PLAN.quotaCategories.find(c => c.key === 'run') || PLAN.quotaCategories[0] + await click(byText(new RegExp(`^A separate ${run.name} workout$`))) + assert.deepEqual([latest.blocks[0].name, latest.blocks[0].category], ['Warm-up', run.key]) + await done() +}) + +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}`) } +} +console.log(`block menu (dom): ${tests.length - failed} passed${failed ? `, ${failed} failed` : ''}`) +await win.happyDOM.close() +process.exit(failed ? 1 : 0) diff --git a/app/editing.dom.test.jsx b/app/editing.dom.test.jsx new file mode 100644 index 0000000..bf34aed --- /dev/null +++ b/app/editing.dom.test.jsx @@ -0,0 +1,116 @@ +// The footer policy in a real DOM (happy-dom), for EACH layer that has a footer: +// the session sheet (`Modal`) and the planner (`FullScreen`'s sticky bar). The +// owner's bug class (#77) and its sequel (C N1, reproduced by the G regrade in +// both): a box that has focus is REMOVED, as the exercise picker's search box +// is when an exercise is picked, and on iOS the row tapped takes no focus, so +// no blur reaches React and the footer stayed hidden with nothing saying why. +// Bundled by esbuild (JSX) and run in node. +import assert from 'node:assert/strict' +import { Window } from 'happy-dom' + +const win = new Window({ url: 'http://localhost/' }) +// A finger, not a mouse: the footer only hides on a touch screen. +win.matchMedia = (q) => ({ matches: /coarse/.test(q), media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }) +for (const k of ['window', 'document', 'navigator', 'MutationObserver', 'HTMLElement', 'HTMLIFrameElement', 'Node', 'Event', 'getComputedStyle']) { + const value = k === 'window' ? win : k === 'getComputedStyle' ? win.getComputedStyle.bind(win) : win[k] + Object.defineProperty(globalThis, k, { value, configurable: true, writable: true }) +} +win.scrollTo = () => {} +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +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 tests = [] +const test = (name, fn) => tests.push([name, fn]) +const wait = (ms) => act(() => new Promise(r => setTimeout(r, ms))) + +/** The picker's shape: a search box, and a row that takes it away when tapped (no focus moves). */ +function Picker() { + const [open, setOpen] = useState(true) + return ( + <> + {open && } + + + + ) +} + +async function mount(el) { + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + await act(async () => root.render(el)) + return { host, done: () => act(() => root.unmount()) } +} + +const focusOn = (el) => act(() => { el.focus() }) +const tapRow = (host) => act(() => { host.querySelector('.row').dispatchEvent(new win.MouseEvent('click', { bubbles: true })) }) + +test('the session sheet: its footer comes back after the focused search box is removed', async () => { + const { host, done } = await mount( + {}} footer={}>) + assert.ok(host.querySelector('.modal-foot'), 'a sheet at rest has its footer') + await focusOn(host.querySelector('input[type=search]')) + assert.equal(host.querySelector('.modal-foot'), null, 'the footer stays up while a box has focus') + await tapRow(host) + assert.equal(host.querySelector('input[type=search]'), null) + await wait(EDIT_SETTLE_MS + 150) + assert.ok(host.querySelector('.modal-foot'), 'the sheet’s footer stayed hidden after the focused box went (C N1)') + await done() +}) + +test('the planner: its sticky bar comes back after the focused search box is removed', async () => { + const { host, done } = await mount( + {}}>
) + const fs = () => host.querySelector('.fs') + await focusOn(host.querySelector('input[type=search]')) + assert.ok(fs().hasAttribute('data-editing'), 'the bar stays up while a box has focus') + await tapRow(host) + await wait(EDIT_SETTLE_MS + 150) + assert.equal(fs().hasAttribute('data-editing'), false, 'the planner’s keep bar stayed hidden after the focused box went (C N1)') + await done() +}) + +/** A block's ⋯ (editor.jsx BlockMenu): a popover portalled to the body, its name box focused. */ +function WithMenu() { + const [open, setOpen] = useState(true) + return ( + <> + {open && setOpen(false)} over>} + + + ) +} + +test('the planner: a focused box in a popover over it, closed by its X, brings the bar back', async () => { + const { host, done } = await mount( + {}}>
) + await focusOn(document.querySelector('input[aria-label="Block name"]')) + assert.ok(host.querySelector('.fs').hasAttribute('data-editing')) + await tapRow(host) + assert.equal(document.querySelector('input[aria-label="Block name"]'), null) + await wait(EDIT_SETTLE_MS + 150) + assert.equal(host.querySelector('.fs').hasAttribute('data-editing'), false, 'a box closed away in a portal left the bar hidden') + await done() +}) + +test('both layers: a box still focused after the change keeps the footer hidden', async () => { + const { host, done } = await mount( + {}} footer={}>) + await focusOn(host.querySelector('input[type=number]')) + await tapRow(host) // the search box goes; the weight box still has focus + await wait(EDIT_SETTLE_MS + 150) + assert.equal(host.querySelector('.modal-foot'), null, 'the footer came back under a box still being typed in') + await done() +}) + +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}`) } +} +console.log(`editing (dom): ${tests.length - failed} passed${failed ? `, ${failed} failed` : ''}`) +await win.happyDOM.close() +process.exit(failed ? 1 : 0) diff --git a/app/editing.test.js b/app/editing.test.js new file mode 100644 index 0000000..e9a7591 --- /dev/null +++ b/app/editing.test.js @@ -0,0 +1,96 @@ +// The footer policy's memory (modal.jsx `editWatch`, #77, C N1): the footer hides +// while a box has focus and comes back once nothing is being typed into, even +// when the focused box is REMOVED from the page and no blur ever fires (the +// exercise picker's search box, the moment an exercise is picked). Bundled by +// esbuild (modal.jsx is JSX) and run in node, with a fake page. +import assert from 'node:assert/strict' +import { editWatch, EDIT_SETTLE_MS } from './src/modal.jsx' + +const tests = [] +const test = (name, fn) => tests.push([name, fn]) +const wait = (ms) => new Promise(r => setTimeout(r, ms)) + +const box = (type = 'number') => ({ tagName: 'INPUT', type }) +const button = { tagName: 'BUTTON' } + +/** A page with one thing in focus, and the footer's state as the watch sets it. */ +function page({ touch = true } = {}) { + const p = { active: null, shown: [] } + p.watch = editWatch({ + typing: () => Boolean(p.active && p.active.tagName === 'INPUT'), + set: (v) => p.shown.push(v), + delay: 5, + touch: () => touch, + }) + p.focus = (el) => { p.active = el; p.watch.focus(el) } + p.blur = (el, next = null) => { p.active = next; p.watch.blur(el, next) } + return p +} + +test('a focused box removed with no blur brings the footer back (C N1)', async () => { + const p = page() + const search = box('search') + p.focus(search) + assert.deepEqual(p.shown, [true]) + // The picker closes: the box is gone, focus is on the body, and nothing blurred. + p.active = null + p.watch.changed() + await wait(20) + assert.deepEqual(p.shown, [true, false], 'the footer stayed hidden after the focused box went') +}) + +test('a change while a box still has focus keeps the footer hidden', async () => { + const p = page() + const w = box() + p.focus(w) + p.watch.changed() + await wait(20) + assert.deepEqual(p.shown, [true]) +}) + +test('box to box never shows the footer in between; letting go shows it after the settle', async () => { + const p = page() + const a = box() + const b = box() + p.focus(a) + p.blur(a, b) + p.focus(b) + await wait(20) + assert.deepEqual(p.shown, [true]) + p.blur(b, button) + await wait(20) + assert.deepEqual(p.shown, [true, false]) +}) + +test('focus back inside the settle keeps it hidden; the timer re-reads the page', async () => { + const p = page() + const a = box() + p.focus(a) + p.blur(a, null) + p.focus(a) + await wait(20) + assert.deepEqual(p.shown, [true]) + // A blur that lands on a box React did not report: the timer asks the page. + p.watch.blur(a, null) + p.active = box() + await wait(20) + assert.deepEqual(p.shown, [true]) +}) + +test('a mouse never hides the footer, and a switch is not typing', async () => { + const p = page({ touch: false }) + p.focus(box()) + const q = page() + q.focus({ tagName: 'INPUT', type: 'checkbox' }) + q.watch.changed() + await wait(20) + assert.deepEqual([p.shown, q.shown], [[], []]) + assert.ok(EDIT_SETTLE_MS >= 200, 'the settle is long enough that a tap lands on what was under the finger') +}) + +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}`) } +} +console.log(`editing: ${tests.length - failed} passed${failed ? `, ${failed} failed` : ''}`) +if (failed) process.exit(1) diff --git a/app/gear.test.js b/app/gear.test.js index ef86a42..926253f 100644 --- a/app/gear.test.js +++ b/app/gear.test.js @@ -145,13 +145,31 @@ check('weights count reps, from the lift chooser', () => { check('climbing gear counts hours', () => { const entries = [rope, - did('2026-09-01', 'board', { gear: ['gear-rope'] }, { minutes: 90 }), - did('2026-09-03', 'board', { gear: ['gear-rope'] }, { minutes: 150 })] + did('2026-09-01', 'board', { gear: ['gear-rope'], minutesSpent: 90 }), + did('2026-09-03', 'board', { gear: ['gear-rope'], minutesSpent: 150 })] const row = gearUsage({ plan, entries, strava: null }).find(r => r.id === 'gear-rope') eq(row.minutes, 240) eq(headlineFor(row), { value: 4, unit: 'hr' }) }) +check('gear hours never count the card\'s estimate, only time typed or measured (#97 F6)', () => { + // The seed's shape: data.minutes is the card's 120 because no time was typed. + const estimate = did('2026-10-19', 'fun-sport', { gear: ['gear-rope'] }, { minutes: 120 }) + const typed = did('2026-10-20', 'fun-sport', { gear: ['gear-rope'], minutesSpent: 39 }, { minutes: 120 }) + // A correction stored before minutesSpent existed still counts as typed. + const corrected = did('2026-10-21', 'fun-sport', { gear: ['gear-rope'] }, { minutes: 21, minutesSource: 'typed' }) + const row = gearUsage({ plan, entries: [rope, estimate, typed, corrected], strava: null }).find(r => r.id === 'gear-rope') + eq(row.minutes, 60, '39 typed + 21 corrected, and nothing for the estimate') + eq(row.sessions, 3, 'the estimated session is still a use') +}) + +check('a climbing set log\'s reps count, read from out.sets (#97 F6)', () => { + const entries = [plates, did('2026-09-01', 'repeaters', { + gear: ['gear-plates'], sets: { [opt('repeaters').logSpec.exercises[0].key]: [{ reps: 6 }, { reps: 6 }] }, + })] + eq(gearUsage({ plan, entries, strava: null }).find(r => r.id === 'gear-plates').reps, 12) +}) + check('one workout can wear two things at once', () => { const entries = [rope, plates, did('2026-09-01', 'log-workout', { activity: 'lift', gear: ['gear-rope', 'gear-plates'] })] diff --git a/app/libsync.native.diff b/app/libsync.native.diff index 366cf62..49f6c43 100644 --- a/app/libsync.native.diff +++ b/app/libsync.native.diff @@ -23,10 +23,6 @@ - if (unsynced !== 0 && !confirmFn(lossMessage(unsynced))) { thaw(); return { signedOut: false, unsynced } } + // Native: confirmFn is a system alert, so it may return a promise. + if (unsynced !== 0 && !(await confirmFn(lossMessage(unsynced)))) { thaw(); return { signedOut: false, unsynced } } -=== stats.js -- import { totalSets, totalReps } from '../setlog.jsx' -+ // Native: the web's app/src/setlog.jsx is features/setlog.tsx here. -+ import { totalSets, totalReps } from '../features/setlog' === store.js - import { handoffTarget, retirePushSubscription } from './handoff.js' - import { isSignedOut, makeLocalPersist, onSignedOutElsewhere } from './signout.js' diff --git a/app/package-lock.json b/app/package-lock.json index 65fc074..055f0b3 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -14,6 +14,7 @@ }, "devDependencies": { "@vitejs/plugin-react": "^5.1.0", + "happy-dom": "^15.11.7", "vite": "^7.1.5" } }, @@ -1338,6 +1339,19 @@ "dev": true, "license": "ISC" }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/esbuild": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", @@ -1433,6 +1447,21 @@ "node": ">=6.9.0" } }, + "node_modules/happy-dom": { + "version": "15.11.7", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-15.11.7.tgz", + "integrity": "sha512-KyrFvnl+J9US63TEzwoiJOQzZBJY7KgBushJA8X61DMbNsH+2ONkDuLDnCnwUiPTF42tLoEmrPyoqbenVA5zrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^4.5.0", + "webidl-conversions": "^7.0.0", + "whatwg-mimetype": "^3.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -1808,6 +1837,26 @@ } } }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", diff --git a/app/package.json b/app/package.json index 1b224f3..b041722 100644 --- a/app/package.json +++ b/app/package.json @@ -32,6 +32,8 @@ "test:trainer": "node trainer.test.js", "test:drafts": "node drafts.test.js", "test:planflow": "esbuild planflow.test.js --bundle --platform=node --format=esm --jsx=automatic --packages=external --outfile=.planflowtest.mjs --log-level=error && node .planflowtest.mjs", + "test:editing": "esbuild editing.test.js --bundle --platform=node --format=esm --jsx=automatic --packages=external --outfile=.editingtest.mjs --log-level=error && node .editingtest.mjs && esbuild editing.dom.test.jsx --bundle --platform=node --format=esm --jsx=automatic --packages=external --outfile=.editingdomtest.mjs --log-level=error && node .editingdomtest.mjs", + "test:blockmenu": "esbuild blockmenu.dom.test.jsx --bundle --platform=node --format=esm --jsx=automatic --packages=external --outfile=.blockmenudomtest.mjs --log-level=error && node .blockmenudomtest.mjs", "test:done": "node done.test.js", "test:history": "node history.test.js", "test:fingers": "node fingers.test.js", @@ -49,6 +51,7 @@ }, "devDependencies": { "@vitejs/plugin-react": "^5.1.0", + "happy-dom": "^15.11.7", "vite": "^7.1.5" } } diff --git a/app/planflow.test.js b/app/planflow.test.js index ebedd45..c81a97c 100644 --- a/app/planflow.test.js +++ b/app/planflow.test.js @@ -296,6 +296,30 @@ test('a hand-built workout of pieces is filed from a block\'s sport, else from " assert.equal(c.nameOf('rowing'), 'Rowing') }) +test('"What is it?" is asked only where its answer is used (C N6)', () => { + const liftField = liftFieldOf(PLAN) + // The model's review: a Lift block and a Run block. It lands as two workouts, + // each filed by its block, so there is nothing to ask. + const review = blankPrescription({ title: 'Legs and a run', blocks: [ + { name: 'Main lifts', category: 'lift' }, { name: 'Core' }, { name: 'Easy run', category: 'run' }, + ] }) + const filled = withItem(withItem(review), { ...squat, id: 'r', kind: 'interval', name: 'Easy run' }, 2) + assert.equal(needsFiling(filled, PLAN, liftField), false, 'a plan whose blocks are filed is asked what it is') + const oneBlock = withItem(blankPrescription({ title: 'Spin', blocks: [{ name: 'Spin', category: 'bike' }] }), + { ...squat, kind: 'interval', name: 'Spin' }) + assert.equal(needsFiling(oneBlock, PLAN, liftField), false) + // Wherever it IS asked, every answer on offer files the workout as answered. + const spin = appendPiece(blankFor([]), 'Easy spin', { by: 'time' }) + const offCatalog = { ...spin, blocks: [{ ...spin.blocks[0], activity: 'not-a-sport' }] } + const asked = [spin, offCatalog, appendPiece(blankFor([]), 'Hollow hold', { by: 'reps' })] + for (const pres of asked) { + assert.equal(needsFiling(pres, PLAN, liftField), true) + for (const a of fileChoices(PLAN).pinned) { + assert.equal(filedFor(pres, PLAN, liftField, a.key).activity, a.key, `answering ${a.key} did nothing`) + } + } +}) + /* ------------------------------------------------------------- durations */ test('a timed piece reads in minutes and starts at ten (C F10)', () => { diff --git a/app/prescription.test.js b/app/prescription.test.js index 34e462a..b66d863 100644 --- a/app/prescription.test.js +++ b/app/prescription.test.js @@ -357,6 +357,54 @@ t('reordering moves one exercise and says where it landed', () => { assert.equal(stuck.itemId, 'b0i0') }) +t('an exercise moves to another block whole: its sets, its uid, at the end (C N12)', () => { + const p = normalizePrescription({ + title: 'x', blocks: [ + { name: 'Main', category: 'lift', items: [{ kind: 'lift', exercise: 'back-squat', sets: [{ reps: 5, weight: 185 }] }] }, + { name: 'Accessory', items: [ + { kind: 'lift', exercise: 'bench-press', sets: [{ reps: 8, weight: 135 }, { reps: 8, weight: 135 }] }, + { kind: 'lift', exercise: 'barbell-curl', sets: [{ reps: 10 }] }, + ] }, + { name: 'Core', circuit: { work: 40, rest: 20, rounds: 3, countIn: 10 }, items: [ + { kind: 'lift', exercise: 'plank', sets: [{ seconds: 45 }] }, + ] }, + ], + }, { liftField }) + const bench = { ...p.blocks[1].items[0], uid: 'u-bench' } + const withUid = { ...p, blocks: p.blocks.map((b, i) => (i === 1 ? { ...b, items: [bench, b.items[1]] } : b)) } + const names = (q, bi) => q.blocks[bi].items.map(i => i.name) + + const r = moveItem(withUid, 'b1i0', { block: 'b0' }) + assert.deepEqual(names(r.pres, 0), [names(p, 0)[0], bench.name], 'it did not land at the end of Main') + assert.deepEqual(names(r.pres, 1), [names(p, 1)[1]], 'it stayed in Accessory too') + assert.equal(r.itemId, 'b0i1', 'the answer does not name where it landed') + const landed = r.pres.blocks[0].items[1] + assert.equal(landed.uid, 'u-bench', 'the move lost the exercise\u2019s identity (a synced copy would see a new one)') + assert.deepEqual(landed.sets.map(st => [st.reps, st.weight]), [[8, 135], [8, 135]], 'its numbers did not come with it') + + // Into a circuit: one set, its timing; the rounds are the circuit's. + const c = moveItem(withUid, 'b1i0', { block: 'b2' }) + assert.equal(c.pres.blocks[2].items.at(-1).sets.length, 1) + assert.equal(c.itemId, 'b2i1') + + // The block it leaves empty goes, as after a removal; the landing id follows. + const lone = moveItem(p, 'b0i0', { block: 'b1' }) + assert.deepEqual(lone.pres.blocks.map(b => b.name), ['Accessory', 'Core']) + assert.equal(lone.itemId, 'b0i2') + // A note keeps it. + const noted = { ...p, blocks: p.blocks.map((b, i) => (i === 0 ? { ...b, note: 'Work up to a top set' } : b)) } + assert.equal(moveItem(noted, 'b0i0', { block: 'b1' }).pres.blocks.length, 3) + + // Its own block, or a block or exercise that is not there: unchanged. + for (const [id, block] of [['b1i0', 'b1'], ['b1i0', 'b9'], ['b9i9', 'b0']]) { + const same = moveItem(p, id, { block }) + assert.equal(same.pres, p) + assert.equal(same.itemId, id) + } + // Up and down still stop at the block's edge. + assert.deepEqual(names(moveItem(p, 'b1i1', 'down').pres, 1), names(p, 1)) +}) + t('once he has moved off the prescription the last set carries forward', () => { const steps = prescriptionSteps(legs) const run = markSet(emptyRun(T0), steps[1], { reps: 8, weight: 155 }, { at: T0, steps }) diff --git a/app/progress.test.js b/app/progress.test.js index b168f9b..98d4656 100644 --- a/app/progress.test.js +++ b/app/progress.test.js @@ -16,10 +16,10 @@ import { EMPTY_SCOPE, resolveScope, scopeOptions, describeScope, weeksIn, activityScopeOf, ACTIVITY_SCOPES, } from './src/lib/scope.js' import { - metricsFor, totalsFor, METRICS, declaredMetrics, pyramidOf, bodyweightSeries, + metricsFor, totalsFor, METRICS, declaredMetrics, pyramidOf, bodyweightSeries, volumeCard, } from './src/lib/metrics.js' import { climbLine } from './src/lib/grades.js' -import { timeX } from './src/lib/vizscale.js' +import { timeX, deltaBase } from './src/lib/vizscale.js' const plan = JSON.parse(readFileSync(new URL('../test/fixtures/plan.json', import.meta.url), 'utf8')) @@ -416,9 +416,10 @@ check('F5: hard workouts on two dates are two', () => { check('F6: the doubled lead laps\' per-lap grades are routes on the chart', () => { const laps = (date, grades) => did(date, 'lead-laps', { rpe: 6, sets: { doubles: [{ reps: grades.length, grades }] } }) const r = at([laps('2026-09-02', [10.1, 10.2]), laps('2026-09-09', [10.2, 10.3])]) - const m = metric(r, 'hardestRoute') - ok(m, 'no hardest-route chart from lead laps') - eq(m.points.map(p => m.fmtY(p.y)), ['5.10', '5.10+']) + // They are routes, in the route pyramid. Lead laps are volume by declaration + // (fingerLoad light), so they are not a hardest send (#97 review): see below. + eq(pyramidOf(r, plan, 'yds'), [{ band: 10, label: '5.10', sent: 4, tried: 4 }]) + eq(metric(r, 'hardestRoute'), undefined, 'lead laps drew a hardest-sent line') }) check('F6: an old integer route grade is not a boulder, and off-ladder is not plotted', () => { @@ -587,5 +588,67 @@ check('a climbing row reads as its climbs: "8 routes · hardest 5.10+"', () => { eq(climbLine(opt, { sets: { routes: [{ reps: 8 }] }, hardestYds: 10.3 }), '8 routes · hardest 5.10+') }) +check('#97 F1: Climbs per week counts the climbs described, never the prefilled count', () => { + // The regrade's week: 10 prefilled with 3 described, then 5 prefilled with 2: 5, not 15. + const blank = { grade: '', fell: false, felt: '', style: '' } + const night = (n, said) => Array.from({ length: n }, (_, i) => (i < said.length ? { ...blank, ...said[i] } : blank)) + const r = at([ + did('2026-09-02', 'fun-boulder', { sets: { problems: [{ reps: 10, climbs: night(10, [{ grade: 3, outcome: 'send' }, { grade: 4, outcome: 'fell' }, { grade: 4, outcome: 'fell' }]) }] } }), + did('2026-09-03', 'fun-sport', { sets: { routes: [{ reps: 5, climbs: night(5, [{ grade: 10.2, outcome: 'send' }, { grade: 9.2 }]) }] } }), + ]) + eq(metric(r, 'climbs').points.find(p => p.x === '2026-08-31').y, 5) +}) + +check('#97 F3: with Climbing picked, the Climbing charts lead; on the whole page they follow', () => { + const entries = [...LOG, did('2026-09-03', 'fun-boulder', { hardest: 4, sets: { problems: [{ reps: 6 }] } })] + const picked = metricsFor(plan, at(entries, { activity: 'climbing' })).map(g => g.name) + eq(picked[0], 'Climbing', `groups: ${picked}`) + const whole = metricsFor(plan, at(entries)).map(g => g.name) + eq(whole.filter(n => n !== 'This session').at(-1), 'Climbing', 'the unfiltered page still ends on climbing') + // Inside the group, what was climbed by grade comes first. + const keys = metricsFor(plan, at(entries, { activity: 'climbing' }))[0].metrics.map(m => m.key) + ok(keys.indexOf('boulderPyramid') < keys.indexOf('climbs') && keys.indexOf('climbs') >= 0, `climbing order: ${keys}`) +}) + +check('#97 review: ARC and other volume days are not a hardest send, so never a decline', () => { + // The seed's Sep 14 and Sep 21: two ARC days, laps at 5.7 to 5.11−, then 5.7 to + // 5.10. Per session they drew "▼ 5.11− → 5.9 since Sep 14". (Dated two weeks earlier + // here, Aug 31 and Sep 7, so both fall before the suite's TODAY.) + const arc = (date, rows) => did(date, 'arc', { rpe: 5, sets: { bout: rows.map(grades => ({ + reps: grades.length, seconds: null, climbs: grades.map(grade => ({ grade, outcome: 'send' })) })) } }) + const sep14 = arc('2026-08-31', [[7.2, 8.2, 10.2, 10.1, 11.1, 7.2, 8.2, 10.2, 7.2], [9.2, 10.3, 7.2, 8.2, 7.2, 10.2, 7.2, 8.2]]) + const sep21 = arc('2026-09-07', [[7.2, 8.2, 7.2, 8.2, 9.2, 7.2, 8.2, 7.2, 8.2, 7.2, 9.2, 10.2], [7.2, 8.2, 7.2, 8.2, 9.2, 7.2]]) + const opt = (id) => plan.dailyMenu.find(m => m.id === id) + ok(volumeCard(opt('arc'), plan) && volumeCard(opt('lead-laps'), plan) && volumeCard(opt('economy'), plan), 'endurance cards are volume') + ok(!volumeCard(opt('fun-sport'), plan) && !volumeCard(opt('board'), plan), 'a limit or a free day is not') + ok(!volumeCard({ id: 'x', sched: {} }, plan), 'a card that declares nothing is kept') + const r = at([sep14, sep21]) + eq(metric(r, 'hardestRoute'), undefined, 'two ARC days drew a hardest-sent line') + // Their climbs still count where volume belongs. + ok(pyramidOf(r, plan, 'yds').some(row => row.band === 11), 'the ARC 5.11- left the pyramid') + ok(metric(r, 'climbs').points.some(p => p.y === 17), 'the ARC laps left Climbs per week') + // With a free day beside them, the line is the free day alone. + const sport = (date, grade) => did(date, 'fun-sport', { sets: { routes: [{ reps: 1, climbs: [{ grade, outcome: 'send' }] }] } }) + const mixed = metric(at([sep14, sport('2026-09-02', 10.2), sep21, sport('2026-09-09', 10.1)]), 'hardestRoute') + eq(mixed.points.map(p => `${p.x} ${mixed.fmtY(p.y)} ${p.of}`), ['2026-09-02 5.10 fun-sport', '2026-09-09 5.10− fun-sport']) +}) + +check('#97 F7: the hardest sent is the best of each week, its change measured within one card', () => { + const sport = (date, grade) => did(date, 'fun-sport', { sets: { routes: [{ reps: 1, climbs: [{ grade, outcome: 'send' }] }] } }) + const crag = (date, grade) => did(date, 'crag-day', { sets: { burns: [{ reps: 1, climbs: [{ grade, outcome: 'send' }] }] } }) + const m = metric(at([sport('2026-09-02', 11.1), crag('2026-09-09', 10.2)]), 'hardestRoute') + eq(m.points.map(p => p.of), ['fun-sport', 'crag-day']) + eq(deltaBase(m.points), null, 'no change is claimed between two different sessions') + // Two sessions in one week: one point, the harder, on the day it was sent. + const week = metric(at([sport('2026-09-01', 10.2), crag('2026-09-02', 9.2), sport('2026-09-09', 10.3)]), 'hardestRoute') + eq(week.points.map(p => `${p.x} ${week.fmtY(p.y)}`), ['2026-09-01 5.10', '2026-09-09 5.10+']) + // Like with like: the change is from the same card's earliest point. + const like = metric(at([sport('2026-09-01', 10.2), crag('2026-09-09', 9.2), sport('2026-09-15', 10.3)]), 'hardestRoute') + eq(deltaBase(like.points).x, '2026-09-01') + // Points that say nothing about what they are of compare first to last, as before. + eq(deltaBase([{ x: 'a', y: 1 }, { x: 'b', y: 2 }]).x, 'a') + eq(deltaBase([{ x: 'a', y: 1 }]), null, 'one point is no change') +}) + console.log(failed ? `\n${failed} progress test(s) failed` : '\nall progress tests pass') process.exit(failed ? 1 : 0) diff --git a/app/smoke/editor.jsx b/app/smoke/editor.jsx index 59cb50f..e1ad7a4 100644 --- a/app/smoke/editor.jsx +++ b/app/smoke/editor.jsx @@ -4,7 +4,7 @@ */ import { renderToString } from 'react-dom/server' import { dayWords } from '../src/lib/dates.js' -import { PrescriptionEditor, BlockMenu, blockTag, noteDraft, landsOf } from '../src/editor.jsx' +import { PrescriptionEditor, BlockMenu, BlockQuota, blockTag, noteDraft, landsOf } from '../src/editor.jsx' import { normalizePrescription, setCircuit, noteBlock, tickSet, setTicked, addSet } from '../src/lib/prescription.js' import { SessionLog } from '../src/sessionlog.jsx' import { readFileSync } from 'node:fs' @@ -287,8 +287,9 @@ export default [ // The switch moved into each block's ⋯ (#79): the circuit says so on its head, and // no block carries a full-width switch any more. `BlockMenu(…)` pins the new address. if (/role="switch"/.test(html)) throw new Error('a full-width Circuit switch is back on a block') - if (!/class="presc-blocktag">CircuitCircuit · 3 rounds { - const b = { id: 'b1', name: 'Main', note: '', category: 'lift', items: [] } - const html = renderToString() + onReorder={noop} onMove={noop} onMoveItem={noop} onRemove={noop} onClose={noop} />) const t = text(html) if (!/ c.key === 'lift') - if (!new RegExp(`aria-pressed="true"[^>]*>(?:(?!).)*${lift.name}`).test(html)) throw new Error('the block\u2019s own split is not marked') + if (!t.includes(`A separate ${lift.name} workout`)) throw new Error('"Where it lands" does not say where it lands now') + // Where it lands is its own list behind that row: every answer, the block's own marked. + const lands = renderToString() + if (!text(lands).includes('Part of the workout beside it')) throw new Error('no way back to part of the workout beside it') + for (const c of plan.quotaCategories) if (!text(lands).includes(`A separate ${c.name} workout`)) throw new Error(`no way to land as ${c.name}`) + if (!new RegExp(`aria-pressed="true"[^>]*>(?:(?!).)*${lift.name} workout`).test(lands)) throw new Error('the block\u2019s own split is not marked') // Ends and the only block: nothing that cannot be done is offered. - const one = renderToString() - if (/Move block|Remove block|Reorder exercises/.test(one)) throw new Error('the only block offers a move, a removal or a reorder') + const one = renderToString() + if (/Move block|Remove block|Reorder exercises|Move an exercise|Where it lands/.test(one)) throw new Error('the only block offers a move, a removal, a reorder or a split') if (!/Edit the note/.test(one)) throw new Error('a note that exists is not offered for editing') }], + /* + * A SHORT SHEET (#95, C N10). The web's ⋯ opened in place as a 1,000px panel + * (Name, note, reorder, moves, Circuit, twelve "where it lands" chips, Remove 34px + * from Done), pushing the exercises off the screen. Now a popover (a bottom sheet + * on a phone): one list, where it lands behind one row, Remove last and apart. + * Pinned absent: the chips on the first page, the Done button beside Remove. + */ + ['BlockMenu(a short sheet: a popover, one list, where it lands behind one row, Remove last and apart)', null, () => { + const b = { id: 'b0', name: 'Main', note: '', category: null, items: [] } + const html = renderToString() + if (!/class="pop-scrim over"/.test(html) || !/role="dialog"[^>]*aria-label="Main: block options"/.test(html)) throw new Error('the block menu is not a sheet over the editor') + if (/class="implchip/.test(html) || /blockquota/.test(html)) throw new Error('the "where it lands" chips are back on the menu\u2019s first page') + if (/>Done/.test(html)) throw new Error('the name is not on the first page') + }], + /* + * ONE LINE ON A CIRCUIT'S HEAD (#95, C N9). "Circuit · Part of the workout beside + * it" beside "3 rounds" broke the head in two at 390. The head says "Circuit · 3 + * rounds"; where it lands is a line of its own under it. + */ + ['PrescriptionEditor(a long circuit name gives way, the head stays one line)', null, () => { + const css = readFileSync(new URL('../src/css/editor.css', import.meta.url), 'utf8') + if (!/\.cx-block > \.presc-blockhead \{[^}]*flex-wrap: nowrap/.test(css)) throw new Error('a circuit head can wrap again') + if (!/\.cx-block \.presc-blocktoggle h3 \{[^}]*text-overflow: ellipsis/.test(css)) throw new Error('a long circuit name pushes the rounds and the ⋯ off the line') + const tsx = readFileSync(new URL('../../mobile/src/features/editor.tsx', import.meta.url), 'utf8') + if (!/numberOfLines=\{1\} style=\{\{ flex: 1, minWidth: 0 \}\}>\{b\.name\}/.test(tsx)) throw new Error('the phone\u2019s circuit name wraps its head') + }], + ['PrescriptionEditor(a circuit in a split workout: "Circuit · 3 rounds" on the head, where it lands under it)', null, () => { + const pres = normalizePrescription({ title: 'Legs and a run', blocks: [ + { name: 'Main lifts', category: 'lift', items: [{ kind: 'lift', name: 'Squat', exercise: SQUAT.key, sets: [{ reps: 5 }] }] }, + { name: 'Core', circuit: { work: 40, rest: 20, rounds: 3, countIn: 10 }, items: [{ kind: 'lift', name: 'Plank', exercise: 'plank', sets: [{ seconds: 45 }] }] }, + { name: 'Easy run', category: 'run', items: [{ kind: 'interval', name: 'Run', sets: [{ seconds: 1200 }] }] }, + ] }, { liftField: LIFT_FIELD }) + const html = renderToString() + const core = html.slice(html.indexOf('cx-block')) + const head = core.slice(0, core.indexOf('
')) + if (!/class="presc-blockn">Circuit · 3 roundsPart of the workout beside it { const html = renderToString() if (/class="cx-switch"|
m.discipline !== 'climbing') } /* * An invented Strava cache: one bike, one pair of shoes, an athlete with a diff --git a/app/smoke/log.jsx b/app/smoke/log.jsx index 8593526..59a4a77 100644 --- a/app/smoke/log.jsx +++ b/app/smoke/log.jsx @@ -120,7 +120,9 @@ export default [ (html) => { const t = text(html) if (!/90 min · 8 routes · hardest 5\.10\+/.test(t)) throw new Error(`the route row: ${[...t.matchAll(/list-row-meta">([^<]*)/g)].map(m => m[1])}`) - if (!/3 problems · hardest V4/.test(t)) throw new Error('the boulder row should name its hardest SEND, not the fall') + // Two problems described, the third left blank: two climbed (#97, F1). + if (!/2 problems · hardest V4/.test(t)) throw new Error('the boulder row should name its hardest SEND, not the fall, and count what was described') + if (/3 problems/.test(t)) throw new Error('an undescribed record counted as a problem') }], ['LogTab(one category, no filters)', { - if (climbingShortcut(example)) throw new Error('a Climbing door on the example plan') - const t = text(renderToString()) - if (t.includes('Bouldering · Rock climbing')) throw new Error('a Climbing door on the example plan') + if (t.includes('Bouldering · Rock climbing')) throw new Error('a Climbing door on a plan with no climbing') + }], + // A FRESH INSTALL can log a climb (#97, F4): the starter's Climbing door, and + // behind it both of its cards, each reachable by folder. + ['starter: ActivityChooser(the Climbing door leads to both climbing cards)', null, () => { + if (!climbingShortcut(starter)) throw new Error('no Climbing door on a fresh install') + const t = text(renderToString()) + for (const name of ['Bouldering', 'Rock climbing']) { + if (!new RegExp(`>${name}<`).test(t)) throw new Error(`no ${name} card behind the starter's Climbing door`) + } }], // Behind the door: every climbing card on one screen, by folder, each saying // its category, and found by the words a climber would type. diff --git a/app/smoke/planner.jsx b/app/smoke/planner.jsx index 2697900..56beb32 100644 --- a/app/smoke/planner.jsx +++ b/app/smoke/planner.jsx @@ -97,7 +97,9 @@ export default [ ['BuildStep(start from several kinds: one block each, in the order tapped)', null, () => { const [a, b] = [plan.plannerKinds.kinds[2], plan.plannerKinds.kinds[0]] const html = renderToString(builder(blankFor([a, b]), [a, b])) - if (!/
/.test(html)) throw new Error('a picked kind is folded away') + // Folded after a pick (#95, C N4), never lost: the head names every pick, in order. + const head = text(html.slice(html.indexOf(''))).replace(/&/g, '&') + if (!head.includes(`${a.label} + ${b.label}`)) throw new Error('a picked kind is folded away and not named') // The blocks are written in the order the kinds were tapped: which came first is a fact about the session. const blocks = [...html.matchAll(/class="presc-blocktoggle"[^>]*>(?:(?!<\/h3>).)*?

([^<]+)<\/h3>/g)].map(m => m[1].replace(/&/g, '&')) if (blocks.join() !== `${a.label},${b.label}`) throw new Error(`the blocks are ${blocks.join()}, not ${a.label},${b.label}`) @@ -436,6 +438,25 @@ export default [ for (const g of plan.plannerKinds.groups) if (!hasIcon(g.icon)) throw new Error(`group ${g.key}: icon "${g.icon}" is not registered`) for (const c of plan.quotaCategories) if (!hasIcon(c.icon)) throw new Error(`category ${c.key}: icon "${c.icon}" is not registered`) }], + /* + * A PICK FOLDS THE LIST (#95, C N4). "Start from" stayed open after a pick, three + * screens of chips, and the block it made landed under all of them: the chip lit + * and nothing seemed to happen. On the builder a picked kind folds the list, its + * head says what was picked, and the screen goes to the new block. The ask's + * "Add a kind" is a brief, not a builder: it stays open with its picks. + */ + ['BuildStep(a Start-from pick folds the list and says what was picked)', null, () => { + const zone2 = plan.plannerKinds.kinds.find(k => k.group === 'bike') || plan.plannerKinds.kinds[0] + const html = renderToString(builder(blankFor([zone2]), [zone2])) + const from = html.match(/
]*>/)?.[0] + if (!from) throw new Error('no Start from on an empty builder') + if (/\bopen=""/.test(from)) throw new Error('Start from stays open after a pick, and the block it made is three screens down') + const head = html.slice(html.indexOf('')) + if (!text(head).replace(/&/g, '&').includes(zone2.label)) throw new Error('the folded Start from does not say what was picked') + if (!html.includes(`

${zone2.label.replace(/&/g, '&')}

`)) throw new Error('the pick made no block') + const ask = renderToString() + if (!/
, (html) => { if (!/
t.id === 'critical-force')} + onSave={noop} onDone={noop} />, + (html) => { + if (/class="prof-actions"[^>]*>(?:(?!<\/div>).)*Cancel/s.test(html)) throw new Error('Cancel sits beside Save again') + if (!/class="btn quiet test-cancel"[^>]*>Cancel t.id === 'critical-force')} + onSave={noop} onDone={noop} initialAsk />, + (html) => { + const t = text(html) + if (!/Discard the results you typed\?/.test(t)) throw new Error('the question is missing') + if (!/>Keep them]*>Discard, + (html) => { + const card = html.slice(html.indexOf('Critical force')) + if (!/class="test-one"/.test(card) || !/18\.2/.test(text(card)) || !/2026/.test(text(card))) throw new Error('the one result is not said with its date') + }], + ['TestingTab(two results draw the line)', , + (html) => { if (!/class="viz"/.test(html)) throw new Error('two results drew no chart') }], /* #76: the newest result being empty never hides the last usable ceiling, and a result without a metric is no point on its chart. */ ['TestingTab(an empty newer CF result does not hide the ceiling)', Boulders by grade

')) if (b.indexOf('>V5<') > b.indexOf('>V3<')) throw new Error('the pyramid is not hardest first') const names = metricsGroups(t) - // The plan's own declared charts ('This session') follow, as they always have. + // Climbing is PICKED here, so its charts lead the page (#97, F3), pyramids first. + if (names[0] !== 'Climbing') throw new Error(`climbing is picked and not first: ${names}`) + if (t.indexOf('>Boulders by grade') > t.indexOf('>Climbs per week')) throw new Error('volume leads the pyramids') + }], + // The other side of that move: on the whole page Climbing still comes last (§10.8). + ['ProgressView(climbing follows the general charts on the whole page)', , + (html) => { + const names = metricsGroups(text(html)) + if (!names.includes('Climbing')) throw new Error(`no Climbing group: ${names}`) if (names.filter(n => n !== 'This session').at(-1) !== 'Climbing') throw new Error(`climbing is not last: ${names}`) }], + // The filter chips are one sideways row, not a wrapped stack (#97, F3). + ['ProgressView(the activity chips are one row)', null, () => { + const css = readFileSync(new URL('../src/css/feed.css', import.meta.url), 'utf8') + if (!/\.progacts, \.progcats, \.logfilters \{\s*flex-wrap: nowrap; overflow-x: auto/.test(css)) throw new Error('the filter chips wrap into a stack again') + }], // F17: the body graph keeps to the period. Its two readings are in August; the // 8-week page (from the newest date's week back) holds none of them. ['ProgressView(bodyweight keeps to the period)', ${o}<`).test(html)) throw new Error(`no ${o} outcome`) if (/>OnsightNext problem\s*/g, '>'))) throw new Error('no Next problem beside the current one') // Style, felt, tries and Remove wait behind Details. - if (!/
Details<\/summary>/.test(html)) throw new Error('the optional detail is not folded') + if (!/
[\s\S]*?More details<\/summary>/.test(html)) throw new Error('the optional detail is not folded behind a control that says it opens') + if (/Details<\/summary>/.test(html)) throw new Error('the bare "Details" label is back (#97, F9a)') if (!/Remove problem/.test(t)) throw new Error('no way to remove a problem') - if (!/1 sent/.test(t) || !/fell on 1/.test(t) || !/5 problems/.test(t)) throw new Error('the footer must count problems, sends and falls') + // Two described of five listed: the foot counts the two (#97, F1). + if (!/1 sent/.test(t) || !/fell on 1/.test(t) || !/2 problems/.test(t)) throw new Error('the footer must count problems, sends and falls') + if (/5 problems/.test(t)) throw new Error('the prefilled count is read as problems climbed') // The count is the list now: no reps box, no stepper, no table. if (/aria-label="set 1 reps"/.test(html) || /one more problem/.test(html)) throw new Error('the count is typed or stepped beside the list') if (/exlog-table/.test(html)) throw new Error('a one-column table for a list of climbs') @@ -708,6 +714,8 @@ export default [ const html = renderToString( m.id === 'fun-boulder')} onSave={noop} out={{ sets: { problems: [{ reps: 25, climbs: Array.from({ length: 25 }, () => ({ grade: '', fell: false, felt: '', style: '' })) }] } }} />) if (!/24 more problems, not described/.test(text(html)) || !/25 problems/.test(text(html))) throw new Error('a 25-problem evening was cut short') + // Nothing described yet: the count stands, and nothing says otherwise (#97). + if (/not counted/.test(text(html))) throw new Error('a count nobody has described into is called not counted') }], // Sets come off from the foot, with Undo, never from an X beside the number // being typed (#81, E F1: a 30px X removed a whole evening's routes). @@ -715,7 +723,9 @@ export default [ const opt = plan.dailyMenu.find(m => m.id === 'repeaters') const html = renderToString() if (/Remove set \d/.test(html) || /exlog-x/.test(html)) throw new Error('the per-row X is back') - if (!/Remove last set/.test(html)) throw new Error('no way to take a set off') + // Any set, chosen in the foot (#97, F9d), not only the last. + if (!/>Remove a set)) if (t.includes('Interval timer')) throw new Error('a timer for resting') }], - ['example: no climbing folders', null, () => { - const keys = climbingFolders(example).map(f => f.key) - if (keys.join() !== 'plan') throw new Error(`the example is foldered as ${keys.join(', ')}`) + // A plan with no climbing cards has no climbing folders (the starter and the + // example carry two plain ones since #97, so the plan here is the example less them). + ['a plan with no climbing: no climbing folders', null, () => { + const keys = climbingFolders(noClimbing).map(f => f.key) + if (keys.join() !== 'plan') throw new Error(`a plan with no climbing is foldered as ${keys.join(', ')}`) + }], + // The starter's two climbing cards file under the two doors (#97, F4). + ['starter: its climbing cards are in Bouldering and Rock climbing', null, () => { + const folders = climbingFolders(starter) + const count = (key) => folders.find(f => f.key === key)?.count || 0 + if (count('bouldering') !== 1 || count('rock-climbing') !== 1) throw new Error(`the starter is foldered as ${folders.map(f => `${f.key} ${f.count}`).join(', ')}`) }], /* * Start on a circuit: a plan that is nothing but a circuit runs on the timer's @@ -1234,4 +1252,67 @@ export default [ const free = renderToString() if (!/What did you lift\?/.test(free)) throw new Error('a free-form lift lost its lift list') }], + // "Last time you did this" on a climbing card answers what was climbed, and an + // old date is in words (#97, F2): it said "2026-10-19" and nothing else. + ['PriorNote(a climbing night reads as what was climbed)', m.id === 'fun-sport')} + excludeId="now" entries={[{ id: 'daily-2026-08-19', kind: 'daily', date: '2026-08-19', updatedAt: 'z', + data: { optId: 'fun-sport', level: 2, done: true, out: { sets: { routes: [{ reps: 2, climbs: [ + { grade: 10.2, outcome: 'send' }, { grade: 11.2, outcome: 'fell' }] }] } } } }]} />, + (html) => { + const t = text(html) + if (!/2 routes · hardest 5\.10/.test(t)) throw new Error(`last time reads: ${t.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ')}`) + if (/\d sets?, \d+ reps/.test(t)) throw new Error('last time counts sets and reps on a climbing card') + if (/2026-08-19/.test(t)) throw new Error('an old date is printed as ISO') + }], + // The typed "hardest" field under a list of graded climbs is a second answer + // nothing reads; it goes while climbs are graded, and its unit is said once (#97, F9b). + ['SessionLog(the typed hardest is moot under graded climbs)', null, () => { + const card = plan.dailyMenu.find(m => m.id === 'fun-boulder') + const at = (out) => text(renderToString()) + const count = at({ sets: { problems: [{ reps: 6 }] } }) + if (!/Hardest thing you climbed \(V\)/.test(count)) throw new Error('a count-only night lost its hardest field') + if (/\(V\) \(V\)/.test(count)) throw new Error('the unit is printed twice') + const graded = at({ hardest: 6, sets: { problems: [{ reps: 2, climbs: [{ grade: 4, outcome: 'send' }, { grade: 5, outcome: 'fell' }] }] } }) + if (/Hardest thing you climbed/.test(graded)) throw new Error('the typed hardest sits under the graded climbs') + }], + // A climbing card being logged opens on its log; the protocol and evidence are + // one fold under it (#97, F5). Before, the log began about 1,070px down. + ['Sheet(a climbing card opens on its log, protocol folded)', m.id === 'fun-boulder')} + entry={{ id: `daily-${TODAY}`, kind: 'daily', date: TODAY, updatedAt: 'z', + data: { optId: 'fun-boulder', level: 2, out: {} } }} + entries={[]} isFuture={false} onLog={noop} onSave={noop} onClose={noop} />, + (html) => { + const log = html.indexOf('class="setlog"') + const about = html.indexOf('class="sess-about"') + if (log < 0) throw new Error('no set log on the sheet') + if (about < 0 || about < log) throw new Error('the protocol is not folded under the log') + const firstProtocol = Math.min(...['class="sess ', 'class="ev-note"', 'class="sect-nav"'].map(k => html.indexOf(k)).filter(i => i >= 0)) + if (firstProtocol < about) throw new Error('protocol prose sits above the log, outside its fold') + if (!/rec-dose/.test(html.slice(0, log))) throw new Error('the dose line left the top of the card') + }], + // The other side: a climbing card on a day still to come is planning, protocol open. + ['Sheet(a climbing card on a later day keeps its protocol open)', m.id === 'fun-boulder')} + entry={null} entries={[]} isFuture onLog={noop} onSave={noop} onClose={noop} />, + (html) => { + if (/sess-about/.test(html)) throw new Error('a future day folds the protocol it is being planned from') + if (!/class="sess /.test(html)) throw new Error('no protocol on a future day') + }], + // A card that counts no climbs keeps its order: protocol, then the log. + ['Sheet(a hangboard card keeps protocol then log)', m.id === 'repeaters')} + entry={{ id: `daily-${TODAY}`, kind: 'daily', date: TODAY, updatedAt: 'z', data: { optId: 'repeaters', level: 3, out: {} } }} + entries={[]} isFuture={false} onLog={noop} onSave={noop} onClose={noop} />, + (html) => { + if (/sess-about/.test(html)) throw new Error('a hangboard card folded its protocol') + if (html.indexOf('class="sess ') > html.indexOf('class="setlog"')) throw new Error('the hangboard log moved above its protocol') + }], + // "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, () => { + const note = /Pre-filled from the plan/ + const bare = renderToString( m.id === 'climb-bouldering')} out={{}} onSave={noop} />) + if (note.test(bare)) throw new Error('an empty box is said to be pre-filled') + const filled = renderToString( m.id === 'fun-boulder')} out={{}} onSave={noop} />) + if (!note.test(filled)) throw new Error('a pre-filled count no longer says where it came from') + }], ] diff --git a/app/smoke/today.jsx b/app/smoke/today.jsx index f66e091..f86f708 100644 --- a/app/smoke/today.jsx +++ b/app/smoke/today.jsx @@ -304,6 +304,32 @@ export default [ // Already on today: no way "back to today" to offer. if (/class="btn quiet">Today { + const tomorrow = isoShift(TODAY, 1) + const planned = { ...PLANNED_ENTRY, id: `daily-${tomorrow}`, date: tomorrow } + const opened = renderToString() + if (!/

Tomorrow<\/h2>/.test(opened)) throw new Error('Today stayed on another day, so the workout never opened') + if (!text(opened).includes(PRESCRIPTION.title)) throw new Error('the opened workout is not on the day shown') + const idle = renderToString() + if (!/

Today<\/h2>/.test(idle)) throw new Error('Today moved to another day with nothing being opened') + const unknown = renderToString() + if (!/

Today<\/h2>/.test(unknown)) throw new Error('an id that is no entry moved the day') + // Only one thing drives Today's day at a time: while a workout is being opened, + // a day asked for ("See it on Mon", #101) is handed back, not applied (both platforms). + for (const f of ['src/tabs.jsx', '../mobile/src/features/tabs.tsx']) { + const src = readFileSync(new URL(`../${f}`, import.meta.url), 'utf8') + if (!/if \(showDay\?\.date && opening\) \{ onDayShown\?\.\(\); return \}/.test(src)) throw new Error(`${f}: an asked-for day and an opening both drive Today`) + if (!/if \(opening && followed !== opening\.id\)/.test(src)) throw new Error(`${f}: an opening is followed more than once`) + } + }], ['DaySwitcher(another day says which, offers the way back, and stops at max)', null, () => { const t = TODAY const y = isoShift(t, -1) @@ -476,7 +502,20 @@ export default [ if (!t.includes('Head cold, stayed in bed')) throw new Error('the note is not on the row') }], // A FRESH INSTALL. content/starter.json is the first thing a stranger's - // install renders: no climbing cards, the catalogs only. + // install renders: the catalogs, the rest card and two plain climbing cards (#97). ['starter: TodayTab', ], ['example: TodayTab', ], + // A climbing night's row says what was climbed, in the Log's own line (#97, F2): + // it read "1 set", the set log's container. + ['TodayTab(a climbing row says what was climbed, not "1 set")', , + (html) => { + const t = text(html).replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ') + if (!/40 min · 5 routes · hardest 5\.10/.test(t)) throw new Error(`the climbing row: ${t.slice(t.indexOf('Sport climbing'), t.indexOf('Sport climbing') + 120)}`) + if (/1 set\b/.test(t)) throw new Error('the row counts the set log, not the climbs') + }], ] diff --git a/app/src/css/editor.css b/app/src/css/editor.css index 30c0977..7a5c3f0 100644 --- a/app/src/css/editor.css +++ b/app/src/css/editor.css @@ -425,19 +425,20 @@ .presc-blocktag { font-size: var(--fs-label); color: var(--ink-dim); } .presc-blockmore { flex: 0 0 auto; } .presc-blockmore.on { color: var(--ink); background: var(--panel-3); } -.blockmenu { - display: grid; gap: var(--sp-3); margin: 0 0 var(--sp-3); padding: var(--sp-3); - border: 1px solid var(--line); border-radius: var(--r-card); background: var(--panel-2); -} -.blockmenu-list { margin: 0; } -.blockmenu-label { display: block; font-size: var(--fs-label); color: var(--ink-dim); margin-bottom: var(--sp-2); } -.blockmenu .blockquota { margin: 0; } -.blockmenu .blockquota-chips { margin: 0; } -.blockmenu .cx-switch { margin: 0; } -/* Remove on the left, Done on the right: apart, and Remove is not the primary. */ -.blockmenu-foot { display: flex; align-items: center; gap: var(--sp-3); } -.blockmenu-done { margin-left: auto; } -.blockmenu-rm { color: var(--bad); } +/* The block's ⋯ is a short sheet (#95, C N10): a popover, a bottom sheet on a + phone. One list; Remove last, a gap and a line away from the rest. */ +.blockmenu { display: grid; gap: var(--sp-3); align-content: start; } +.blockmenu-list, .blockmenu .blockquota { margin: 0; } +.blockmenu .blockmenu-on { flex: none; color: var(--accent); } +.blockmenu .cx-switch { margin: 0; cursor: pointer; } +.blockmenu-rm { margin: var(--sp-3) 0 0; } +.blockmenu-rm .list-row, .blockmenu-rm .list-row > svg:first-child { color: var(--bad); } +/* A circuit's head stays one line; where it lands is the line under it (C N9). + A long name gives way with an ellipsis, never the rounds or the ⋯. */ +.cx-blockmeta { flex: none; white-space: nowrap; } +.cx-block > .presc-blockhead { flex-wrap: nowrap; } +.cx-block .presc-blocktoggle h3 { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.presc-blockland { margin: 0 0 var(--sp-2); font-size: var(--fs-label); color: var(--ink-dim); } .presc-blocknote-edit { display: block; margin: 0 0 var(--sp-2); } .presc-blocknote-edit textarea { width: 100%; } .presc-addblock { margin-top: var(--sp-2); } diff --git a/app/src/css/feed.css b/app/src/css/feed.css index 3d28d21..b88412e 100644 --- a/app/src/css/feed.css +++ b/app/src/css/feed.css @@ -147,3 +147,13 @@ /* An activity rather than training, in the session form. */ .out-casual span { display: grid; gap: 2px; } .out-casual em { font-style: normal; font-size: var(--fs-label); color: var(--ink-faint); } + +/* One row of filter chips that scrolls sideways (#97, F3): two wrapped rows of + chips put the first chart, and the first workout, a screen down on a phone. + Bled to the gutter so the cut-off chip says there is more. */ +.progacts, .progcats, .logfilters { + flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; + margin-inline: calc(-1 * var(--gutter)); padding-inline: var(--gutter); +} +.progacts::-webkit-scrollbar, .progcats::-webkit-scrollbar, .logfilters::-webkit-scrollbar { display: none; } +.progacts > .chip, .progcats > .chip, .logfilters > .chip { flex: none; } diff --git a/app/src/css/profile.css b/app/src/css/profile.css index ae228cb..41fd1a8 100644 --- a/app/src/css/profile.css +++ b/app/src/css/profile.css @@ -156,3 +156,22 @@ code { background: var(--panel-2); padding: 1px var(--sp-1); border-radius: var( .prof-trouble > summary { list-style: none; } .prof-trouble > summary::-webkit-details-marker { display: none; } .prof-trouble[open] > summary .list-row-chev { transform: rotate(180deg); } + +/* Leaving a test with numbers typed asks first, in place (#97, F8). The way out + is quiet and sits under the result, never beside Save. */ +.test-ask { + display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; + padding: var(--sp-3); border: 1px solid var(--line-strong); border-radius: var(--r-control); + background: var(--panel-2); font-size: var(--fs-label); +} +.test-ask > span { flex: 1 1 100%; } +.test-cancel { margin-top: var(--sp-4); } +/* A test's only result: a number and a date until there are two (#97, F9f). */ +.test-one { + display: flex; align-items: baseline; gap: var(--sp-2); flex-wrap: wrap; + padding: var(--sp-3) 0; border-top: 1px solid var(--line); +} +.test-one-label { font-size: var(--fs-label); color: var(--ink-dim); flex: 1 1 auto; } +.test-one-value { font-size: var(--fs-title); font-weight: 600; font-variant-numeric: tabular-nums; } +.test-one-unit { font-size: var(--fs-label); font-weight: 500; color: var(--ink-dim); } +.test-one-date { font-size: var(--fs-caption); color: var(--ink-faint); flex-basis: 100%; } diff --git a/app/src/css/setlog.css b/app/src/css/setlog.css index 8c93a7d..c9a5acb 100644 --- a/app/src/css/setlog.css +++ b/app/src/css/setlog.css @@ -138,3 +138,20 @@ background: var(--panel-2); font-size: var(--fs-label); } .exlog-confirm > span { flex: 1 1 100%; } + +/* "More details" reads as something that opens (#97, F9a): a chevron that turns. */ +.climb-more > summary::-webkit-details-marker { display: none; } +.climb-more > summary { list-style: none; gap: var(--sp-1); align-self: flex-start; } +.climb-more-chev { transition: transform var(--dur-fast) var(--ease-out); } +.climb-more[open] .climb-more-chev { transform: rotate(180deg); } +/* Which set to take off, asked in the foot (#97, F9d). */ +.exlog-pick { display: flex; flex-wrap: wrap; gap: var(--sp-2); align-items: center; margin-top: var(--sp-2); } + +/* A climbing card being logged: the protocol under the log, in one fold (#97, F5). */ +.sess-about > summary { + display: flex; align-items: center; gap: var(--sp-1); min-height: var(--tap); + font-weight: 600; cursor: pointer; list-style: none; +} +.sess-about > summary::-webkit-details-marker { display: none; } +.sess-about-chev { transition: transform var(--dur-fast) var(--ease-out); color: var(--ink-dim); } +.sess-about[open] .sess-about-chev { transform: rotate(180deg); } diff --git a/app/src/editor.jsx b/app/src/editor.jsx index ca43b15..6397e08 100644 --- a/app/src/editor.jsx +++ b/app/src/editor.jsx @@ -8,6 +8,7 @@ */ import { useEffect, useRef, useState } from 'react' import { Icon } from './lib/icons.jsx' +import { Popover } from './modal.jsx' import { prescriptionSteps, itemLine, setLine, patchSet, addSet, removeSet, removeItem, patchItem, patchBlock, appendLift, moveItem, setCircuit, setTiming, circuitTiming, @@ -98,23 +99,20 @@ function PieceAdder({ unit, onAdd, label = pieceWords(null) }) { * `none` is a real answer and the default for a warm-up: a block that is not a * workout in its own right belongs to the one beside it. */ -function BlockQuota({ categories, value, onChange }) { +export function BlockQuota({ categories, value, onChange }) { if (!categories.length) return null + const row = (key, label, icon = null) => ( + + ) return ( -
- Where it lands: part of the workout beside it, or a separate one -
- - {categories.map(c => ( - - ))} -
+
+ {row(null, 'Part of the workout beside it')} + {categories.map(c => row(c.key, `A separate ${c.name} workout`, c.icon))}
) } @@ -127,10 +125,14 @@ function BlockQuota({ categories, value, onChange }) { * lands as one entry says nothing about it. */ export function blockTag(block, pres, categories = []) { + return [block?.circuit ? 'Circuit' : null, landsWords(block, pres, categories)].filter(Boolean).join(' · ') || null +} + +/** Where a block lands, in words, only while the workout really splits (`landsOf`). */ +export function landsWords(block, pres, categories = []) { const lands = categories.length ? landsOf(pres).get(block?.id) : null const cat = lands === 'own' ? categories.find(c => c.key === block.category) : null - const words = cat ? `A separate ${cat.name} workout` : lands === 'beside' ? 'Part of the workout beside it' : null - return [block?.circuit ? 'Circuit' : null, words].filter(Boolean).join(' · ') || null + return cat ? `A separate ${cat.name} workout` : lands === 'beside' ? 'Part of the workout beside it' : null } /** @@ -168,24 +170,6 @@ const setCount = (block) => { return `${n} set${n === 1 ? '' : 's'}` } -/** - * Any block can be a circuit (issue #68): its exercises one after another on - * the interval timer, which is what Start runs. A switch, because it is on or - * off, with the words beside it. - */ -function CircuitSwitch({ on, onChange }) { - return ( - - ) -} - /** * A block switched to Circuit: the same head and fold as any block, then the * circuit's timing in one row, its exercises in order with their own timing @@ -197,7 +181,12 @@ const loadOf = (it) => { return w !== null && w !== undefined && w !== '' ? `${w} ${it.weightLabel || 'lb'}` : null } -function CircuitBlock({ block: b, pres, onChange, onDrop, liftField, entries, entryId, open, onToggle, extra, menu = null, tag = null, lead = null }) { +/* + * The circuit's head is ONE line (C N9): its name, "Circuit · 3 rounds" and the + * ⋯. Where it lands, when the workout splits, is a line of its own under the + * head: beside "3 rounds" it broke the head in two at 390. + */ +function CircuitBlock({ block: b, pres, onChange, onDrop, liftField, entries, entryId, open, onToggle, extra, menu = null, lands = null, lead = null }) { const [more, setMore] = useState(false) const c = b.circuit const items = b.items.map(it => ({ id: it.id, key: it.exercise, name: it.name, timing: circuitTiming(it), load: loadOf(it) })) @@ -209,12 +198,12 @@ function CircuitBlock({ block: b, pres, onChange, onDrop, liftField, entries, en

{b.name}

- - {tag && {tag}} - {setCount(b)} + + {`Circuit · ${setCount(b)}`} {menu && menu({ reorder: null })}
+ {lands &&

{lands}

} {open && ( <> {lead} @@ -247,61 +236,118 @@ function CircuitBlock({ block: b, pres, onChange, onDrop, liftField, entries, en * full-width Circuit switch and the "Part of the workout beside it" fold, even * a run and an empty warm-up, so before the first set of a planned Pull came * two rows of planning per block (C F14, G F8). They live here now, with what - * a block could not do at all before: be renamed, given a note, moved, removed. - * The head keeps one word of it (`blockTag`). Opens in place under the head, - * one at a time; Remove is last, apart from the rest, and has Undo. + * a block could not do at all before: be renamed, given a note, moved, removed, + * and give an exercise to another block (C N12). + * + * A SHORT SHEET (#95, C N10), the phone's system action sheet on the web: a + * popover (a bottom sheet under 640px) over the editor, not a 1,000px panel + * opened in place that pushed the exercises off the screen. One list; "Where it + * lands" and "Move an exercise" are one row each, opening their own list in the + * same sheet. Remove is last, apart from the rest, and has Undo. The X, the + * scrim and Escape close it, and keep a name being typed. A block just added + * opens here with its name selected (`fresh`), so typing names it. */ export function BlockMenu({ - block: b, first, last, only, categories = [], onRename, onNote, onCircuit, onQuota, - onReorder = null, onMove, onRemove, onClose, + block: b, blocks = [], first, last, only, categories = [], onRename, onNote, onCircuit, onQuota, + onReorder = null, onMove, onMoveItem = null, onRemove, onClose, fresh = false, }) { const [name, setName] = useState(b.name) + // 'main', 'lands', 'move' (which exercise), or an exercise's id (to which block). + const [page, setPage] = useState('main') + const nameBox = useRef(null) useEffect(() => setName(b.name), [b.name]) + useEffect(() => { if (fresh) { nameBox.current?.focus(); nameBox.current?.select() } }, [fresh]) const commit = () => { if (name.trim() && name.trim() !== b.name) onRename(name); else setName(b.name) } + const close = () => { commit(); onClose() } + /* + * A name still being typed goes WITH every action, applied in the same write + * (#95 review): on iOS a tap takes no focus, so no blur stored it, and Circuit + * turns the block into another component, which threw the name box away. + */ + const typed = () => (name.trim() && name.trim() !== b.name ? name.trim() : null) + const others = blocks.filter(x => x.id !== b.id) + const items = b.items || [] + const moving = items.find(it => it.id === page) || null + const landsName = !b.category ? 'Part of the workout beside it' + : `A separate ${categories.find(c => c.key === b.category)?.name || b.category} workout` + const row = (icon, title, onClick, meta = null, more = false) => ( + + ) + const heading = page === 'lands' ? `Where ${b.name} lands` + : page === 'move' ? 'Move which exercise?' + : moving ? `Move ${moving.name} to` : b.name + return ( -
- -
- - {onReorder && ( - )} - {!first && ( - +
{heading}
+ +
+
+ {page === 'main' && ( + <> + +
+ {row('NotebookPen', b.note ? 'Edit the note' : 'Add a note', () => onNote(typed()))} + {onReorder && row('ArrowUpDown', 'Reorder exercises', () => onReorder(typed()))} + {onMoveItem && items.length > 0 && others.length > 0 + && row('MoveHorizontal', 'Move an exercise to another block', () => setPage(items.length === 1 ? items[0].id : 'move'), null, true)} + {!first && row('ArrowUp', 'Move block up', () => onMove('up', typed()))} + {!last && row('ArrowDown', 'Move block down', () => onMove('down', typed()))} + + {categories.length > 0 && row('Layers', 'Where it lands', () => setPage('lands'), landsName, true)} +
+ {!only && ( +
+ +
+ )} + )} - {!last && ( - + {page === 'lands' && ( + { onQuota(key, typed()); setPage('main') }} /> )} -
- - -
- {!only && ( - + {page === 'move' && ( +
+ {items.map(it => row('Dumbbell', it.name, () => setPage(it.id), null, true))} +
+ )} + {moving && ( +
+ {others.map(x => row(x.circuit ? 'Repeat' : 'Layers', x.name, () => onMoveItem(moving.id, x.id, typed()), + x.circuit ? 'A circuit: it keeps one set' : null))} +
)} -
-
+ ) } @@ -399,6 +445,8 @@ export function PrescriptionEditor({ // The block whose ⋯ is open (one at a time), and the one whose note is being written. const [menuFor, setMenuFor] = useState(null) const [noteFor, setNoteFor] = useState(null) + // A block just added: its menu opens with the name selected (C N10). + const [freshMenu, setFreshMenu] = useState(false) const total = prescriptionSteps(pres).length const blocks = pres.blocks || [] @@ -423,11 +471,24 @@ export function PrescriptionEditor({ setShut(new Set()) remove(removeBlock(pres, b.id), syncedWith?.length ? `${words}. ${syncLine(syncedWith)}` : words) } + // The plan with a block's name being typed in its menu applied, for that menu's next action. + const named = (b, name) => (name ? renameBlock(pres, b.id, name) : pres) + // An exercise to the end of another block (C N12), said in a toast with Undo: + // it lands out of sight, and into a circuit it keeps one set. + const moveTo = (itemId, blockId, base = pres) => { + const it = itemOf(itemId) + const to = blocks.find(x => x.id === blockId) + const r = moveItem(base, itemId, { block: blockId }) + if (r.pres === base) return + setMenuFor(null) + setShut(new Set()) + remove(r.pres, `Moved ${it?.name || 'it'} to ${to?.name || 'another block'}`) + } const menuOf = (b) => () => ( ) @@ -435,14 +496,15 @@ export function PrescriptionEditor({ const leadOf = (b, bi) => ({ reorder = null } = {}) => ( <> {menuFor === b.id && ( - moveTo(itemId, blockId, named(b, name))} onRename={(name) => onChange(renameBlock(pres, b.id, name))} - onNote={() => { setNoteFor(b.id); setMenuFor(null) }} - onCircuit={(on) => onChange(setCircuit(pres, b.id, on))} - onQuota={(key) => onChange(patchBlock(pres, b.id, { category: key }))} - onReorder={reorder ? () => { setMenuFor(null); reorder() } : null} - onMove={(dir) => { const r = moveBlock(pres, b.id, dir); regroup(r.pres); setMenuFor(r.blockId) }} + onNote={(name) => { if (name) onChange(named(b, name)); setNoteFor(b.id); setMenuFor(null) }} + onCircuit={(on, name) => { setFreshMenu(false); onChange(setCircuit(named(b, name), b.id, on)) }} + onQuota={(key, name) => onChange(patchBlock(named(b, name), b.id, { category: key }))} + onReorder={reorder ? (name) => { if (name) onChange(named(b, name)); setMenuFor(null); reorder() } : null} + onMove={(dir, name) => { const r = moveBlock(named(b, name), b.id, dir); setFreshMenu(false); regroup(r.pres); setMenuFor(r.blockId) }} onRemove={() => dropBlock(b)} onClose={() => setMenuFor(null)} /> )} @@ -459,7 +521,7 @@ export function PrescriptionEditor({ toggleBlock(b.id)} - menu={menuOf(b)} tag={blockTag(b, pres, categories)} lead={leadOf(b, bi)()} /> + menu={menuOf(b)} lands={landsWords(b, pres, categories)} lead={leadOf(b, bi)()} /> ) : ( { const r = addBlock(pres); regroup(r.pres); setMenuFor(r.blockId) }}> + onClick={() => { const r = addBlock(pres); regroup(r.pres); setFreshMenu(true); setMenuFor(r.blockId) }}> Add a block {/* Only where there is nothing to be done about it. A session the user is still diff --git a/app/src/lib/gear.js b/app/src/lib/gear.js index e9148d9..a4928ed 100644 --- a/app/src/lib/gear.js +++ b/app/src/lib/gear.js @@ -34,6 +34,7 @@ import { isDone } from './store.js' import { optFor } from './menu.js' import { loggedActivity } from './activities.js' +import { loggedMinutes } from './minutes.js' export const GEAR_KIND = 'gear' @@ -218,7 +219,12 @@ export function gearUsage({ plan, entries = [], strava = null }) { const out = e.data?.out || {} const miles = num(out.distance) - const minutes = num(e.data?.minutes ?? out.duration) + // Typed or measured time only (#97, F6). `data.minutes` is filled with the + // card's estimate when no time was given, so a 39-minute climbing session + // logged on a 120-minute card added two hours to the shoes. An entry whose + // card is gone keeps the one time it carries, its own duration. + const opt = optFor(menu, e.data?.optId) + const minutes = num(loggedMinutes(e, opt) ?? (opt ? 0 : out.duration)) const reps = repsIn(e, menu) const onStrava = Boolean(out.strava?.id) @@ -251,8 +257,11 @@ function repsIn(entry, menu) { } // The climbing set log, where a session declares its own exercises. const opt = optFor(menu, entry?.data?.optId) + // Its rows live in `out.sets[key]` (#97, F6: this read `out[key]`, where they + // never are, so a climbing set log added no reps at all). for (const ex of (opt?.logSpec?.exercises || [])) { - for (const set of (Array.isArray(out[ex.key]) ? out[ex.key] : [])) { + const rows = out.sets?.[ex.key] + for (const set of (Array.isArray(rows) ? rows : [])) { n += num(set?.reps) || 1 } } diff --git a/app/src/lib/grades.js b/app/src/lib/grades.js index 7b8cfe8..1a72b27 100644 --- a/app/src/lib/grades.js +++ b/app/src/lib/grades.js @@ -200,6 +200,22 @@ export function hardestGrade(list) { /* ------------------------------------------------------------ scale-aware --- */ +/** + * The rungs beside a grade on a ladder, for one-tap picks: one easier, the same, + * one harder, as `{ step, value, label }` (#97). A grade off this ladder (written + * the other way, or by hand) offers only itself, labelled by `fmt`; the ends offer + * what is there. + */ +export function nearRungs(ladder, value, fmt = String) { + const list = ladder || [] + const at = list.findIndex(g => g.value === Number(value)) + if (at < 0) return [{ step: 0, value: Number(value), label: fmt(Number(value)) }] + return [-1, 0, 1] + .map(step => ({ step, rung: list[at + step] })) + .filter(x => x.rung) + .map(({ step, rung }) => ({ step, value: rung.value, label: rung.label })) +} + /** The label for a value on a named scale: 'v' is the V ladder, anything else routes. */ export const labelOn = (scale, value) => (scale === 'v' ? vLabel(value) : gradeLabel(value)) @@ -404,6 +420,71 @@ export function climbSaid(c) { /** How many climbs in these rows have something said about them — what turning the detail off would lose. */ export const saidIn = (rows) => climbsIn(rows).filter(climbSaid).length +/* + * WHAT A ROW COUNTS (regrade F1, #97). + * + * A count-only row counts its `reps`: the number in the box, typed or left as the + * plan wrote it, in plain sight and editable. With the per-climb detail on, the + * box is gone and the number becomes the length of a list of mostly blank + * records: "Log each problem" over the plan's 10, three problems described, and + * the night read "10 problems" everywhere while the climber had said three. The + * blanks are the plan's number standing in, a placeholder (AGENTS.md §6.4), never + * climbs. So once any climb in a row is DESCRIBED, the described climbs are the + * row's count; until one is, the row still counts `reps`, exactly as it did with + * the detail off (switching it on alone says nothing new). + * + * A read rule, not a migration: stored rows are read as they are, and every row + * logged before this whose climbs were all described (every one in the logs + * this was checked on) reads exactly as before. + * + * A lap is described when its record says something, or, on the doubled lead + * laps that ask a grade per lap, when its grade was picked. + */ +function toldOf(row) { + const n = climbCount(row?.reps) + const list = Array.isArray(row?.[CLIMB_FIELD]) ? row[CLIMB_FIELD] : [] + const grades = Array.isArray(row?.[GRADE_FIELD]) ? row[GRADE_FIELD] : [] + const told = [] + for (let k = 0; k < n; k++) { + if (climbSaid(list[k]) || (grades[k] !== '' && grades[k] != null)) told.push(k) + } + return told +} + +/** How many climbs this row counts: the described ones once any is, else its count. */ +export function climbsCounted(row) { + 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 +} + +/** Climbs in the row's list nobody has described, while others are: not counted. */ +export function untoldIn(row) { + if (!Array.isArray(row?.[CLIMB_FIELD])) return 0 + const told = toldOf(row).length + return told > 0 ? climbCount(row?.reps) - told : 0 +} + +/** + * The foot of a climbing exercise, in numbers, for both set logs: how many climbs + * count, how many of those went clean or fell, down-climbs, lengths of wall, and + * how many listed climbs are waiting to be described (and so do not count). + */ +export function climbTotals(rows) { + const list = rows || [] + const count = list.reduce((s, r) => s + climbsCounted(r), 0) + const said = climbsIn(list).filter(climbSaid) + return { + count, + sent: said.filter(isClean).length, + falls: fallsIn(list), + downs: downsIn(list), + lengths: lengthsIn(list), + untold: list.reduce((s, r) => s + untoldIn(r), 0), + } +} + /** Every climb record across a list of set rows, in the order they were climbed. */ export function climbsIn(rows) { return (rows || []) @@ -424,10 +505,10 @@ export const downsIn = (rows) => climbsIn(rows).filter(c => c.down === 'both' || * LENGTHS of wall covered, which is what a down-climb changes. * * One length is one trip up or down. An ordinary lap is one; a lap climbed and - * down-climbed is two; a pure down-climb is one. Reps that carry no climb record - * count as one each, so a session with the detail switched off — or switched on - * halfway through — reads exactly as its rep count rather than dropping the laps - * the user did not describe. + * down-climbed is two; a pure down-climb is one. The laps are the row's COUNTED + * climbs (`climbsCounted`): with the detail off, its rep count; with it on, the + * climbs described, once any is, since the blank records after them are the + * plan's number standing in, not laps. * * Deliberately NOT `reps`. The rep count is how many climbs the user did and the climb * list follows it; lengths is how much climbing that was. Merging them would put @@ -435,7 +516,7 @@ export const downsIn = (rows) => climbsIn(rows).filter(c => c.down === 'both' || */ export function lengthsIn(rows) { return (rows || []).reduce((sum, r) => { - const n = climbCount(r?.reps) + const n = climbsCounted(r) const list = Array.isArray(r?.[CLIMB_FIELD]) ? r[CLIMB_FIELD] : [] const extra = list.filter(c => c?.down === 'both').length return sum + n + extra @@ -598,14 +679,15 @@ export function sessionGradesOf(opt, out) { } /** - * How many climbs a session was, described or not: the count on every climbing - * exercise's rows. The same number the set log's foot shows. + * How many climbs a session was: what every climbing exercise's rows COUNT + * (`climbsCounted`: the count, or the described climbs once the detail has any). + * The same number the set log's foot shows. */ 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 += Math.max(0, Math.floor(Number(r?.reps) || 0)) + for (const r of out?.sets?.[ex.key] || []) n += climbsCounted(r) } return n } @@ -640,6 +722,18 @@ export function hardestTried(opt, out, scale) { return climbs.length ? most(climbs.map(c => c.grade)) : most(typedHardest(opt, out, scale)) } +/** + * Is a card's typed "hardest" field moot here: the session graded climbs on its + * ladder, so every reader takes those instead (`hardestSent`, the pyramid)? The + * form then leaves it out (#97, F9b): under a list of described climbs it was a + * second answer to the question the list answers, and it was ignored anyway. Its + * stored value is kept and comes back with the field if the detail goes. + */ +export function mootHardest(opt, out, f) { + const scale = scaleOfOutput(f) + return Boolean(scale) && graded(opt, out, scale).length > 0 +} + /** The grade bands (whole grades) a session touched, as `"v:4"` / `"yds:10"` keys. */ export function bandsOf(opt, out) { const keys = new Set() diff --git a/app/src/lib/metrics.js b/app/src/lib/metrics.js index d53f1f5..d7b862e 100644 --- a/app/src/lib/metrics.js +++ b/app/src/lib/metrics.js @@ -24,7 +24,7 @@ import { optFor } from './menu.js' import { isTraining } from './store.js' import { mondayOf } from './dates.js' import { resolveMinutes, minutesSourceOf } from './minutes.js' -import { isHardEntry } from './fingers.js' +import { hardDates } from './fingers.js' import { gradeIndex, rungLabel, vRungLabel, hardestSent, climbsOf, sessionGradesOf, climbVolume, bandOf, bandLabel, axisLadder, indexOn, @@ -123,12 +123,32 @@ const has = (set, ...keys) => keys.some(k => set.has(k)) /** * The dates in scope that cost a hard finger exposure. A DAY is a hard finger * day, not a session: a split night (max hangs, then repeaters) is one exposure, - * and counting sessions made it two (F5). `lib/fingers.js` `hardDates` is the - * same rule; this one keeps to the scope's entries, which are already done. + * and counting sessions made it two (F5). ONE rule, `lib/fingers.js` `hardDates` + * (#97 F10: this was a second copy of it), over the scope's entries. */ -function hardDays(resolved, plan) { - const menu = plan?.dailyMenu || [] - return [...new Set(resolved.entries.filter(e => isHardEntry(e, menu)).map(e => e.date))].sort() +const hardDays = (resolved, plan) => hardDates(resolved.entries, plan?.dailyMenu || []) + +/* + * HARDEST SENT, LIKE WITH LIKE (#97, F7). Per session, an ARC day (easy on + * purpose) after a lead day drew "▼ 5.11− → 5.9": a different session read as a + * decline. So the line is the best of each WEEK, at the day it was sent (an easy + * day in a week with a hard one cannot lower it), and each point says which card + * it came from (`of`): the chart's change is measured from the earliest point of + * the same card as the newest (lib/vizscale.js `deltaBase`), and claims none when + * there is no earlier one. + */ +function bestPerWeek(resolved, plan, value) { + const best = new Map() + for (const e of resolved.entries) { + const y = value(e) + if (y === null || y === undefined || !Number.isFinite(y)) continue + const w = mondayOf(e.date) + const was = best.get(w) + if (!was || y > was.y || (y === was.y && e.date < was.x)) { + best.set(w, { x: e.date, y, of: optOf(plan, e)?.id ?? null }) + } + } + return [...best.values()].sort((a, b) => String(a.x).localeCompare(String(b.x))) } /* --------------------------------------------------- one exercise, compared */ @@ -226,14 +246,33 @@ export function pyramidOf(resolved, plan, scale) { /** The hardest send of one ladder per session, as a chart value (a rung index for routes). */ /** The ladder the scope's route sends are written on (see axisLadder in grades.js). */ -const routeAxis = (r, plan) => axisLadder(r.entries.map(e => { +/* + * HARDEST SENT IS A LIMIT MEASURE (#97 review). A card whose declared finger load + * is sub-maximal is volume by design: ARC, traverses, doubled lead laps, the + * economy drill. Its hardest send is whatever the day's easy laps happened to + * be, and plotted beside a limit day it read as a decline ("▼ 5.11− → 5.9", two + * ARC days in the seed). So those cards are left out of the hardest lines; their + * climbs still count in the pyramids and Climbs per week. Read off the card's + * own declaration (`sched.fingerLoad`), else its category's, never a list of + * names; a card that declares neither is kept. + */ +const SUBMAXIMAL = new Set(['light', 'sub', 'none']) +export function volumeCard(opt, plan) { + const own = opt?.sched?.fingerLoad + const cat = (plan?.quotaCategories || []).find(c => c.key === opt?.category)?.fingerLoad + return SUBMAXIMAL.has(own ?? cat) +} + +/** The hardest send of one ladder on an entry, or null on a volume card (above). */ +const limitSent = (plan, e, scale) => { const opt = optOf(plan, e) - return opt ? hardestSent(opt, e.data?.out || {}, 'yds') : null -})) + return opt && !volumeCard(opt, plan) ? hardestSent(opt, e.data?.out || {}, scale) : null +} + +const routeAxis = (r, plan) => axisLadder(r.entries.map(e => limitSent(plan, e, 'yds'))) const sentOn = (plan, scale) => (e) => { - const opt = optOf(plan, e) - const best = opt ? hardestSent(opt, e.data?.out || {}, scale) : null + const best = limitSent(plan, e, scale) if (best === null) return null return scale === 'v' ? best : gradeIndex(best) } @@ -419,37 +458,11 @@ export const METRICS = [ /* * LAST, on purpose (2026-10-25, issue #31). Groups render in the order their * first chart appears here, and this is a workout log first: the climbing - * charts follow the general ones rather than leading them. + * charts follow the general ones rather than leading them (unless Climbing is + * picked: `metricsFor`). Inside the group, what was climbed by grade leads, the + * question a climber opens the page with (#97, F3); volume and hard finger days + * follow. */ - { - key: 'hardFingers', - group: 'Climbing', - kind: 'bar', - label: 'Hard finger days per week', - applies: (r) => has(r.disciplines, 'climbing'), - series: (r, plan) => { - const days = new Set(hardDays(r, plan)) - // Each DATE once, in its week, however many sessions it held. - const firsts = new Set() - return byWeek(r, plan, e => { - if (!days.has(e.date) || firsts.has(e.date)) return 0 - firsts.add(e.date) - return 1 - }) - }, - }, - { - key: 'climbs', - group: 'Climbing', - kind: 'bar', - label: 'Climbs per week', - help: 'Routes, problems and laps counted, described or not', - applies: (r) => has(r.disciplines, 'climbing'), - series: (r, plan) => byWeek(r, plan, e => { - const opt = optOf(plan, e) - return opt ? climbVolume(opt, e.data?.out || {}) : 0 - }), - }, /* * D12: what was climbed, by grade. A pyramid per ladder (V and routes are two * ladders), the sends solid and the climbs that did not go faint beside them, @@ -475,9 +488,10 @@ export const METRICS = [ group: 'Climbing', kind: 'line', label: 'Hardest boulder sent', + help: 'The best of each week, endurance and volume days left out', applies: (r) => has(r.disciplines, 'climbing'), fmtY: (v) => vRungLabel(Math.round(v)), - series: (r, plan) => perSession(r, sentOn(plan, 'v')), + series: (r, plan) => bestPerWeek(r, plan, sentOn(plan, 'v')), }, { key: 'routePyramid', @@ -493,6 +507,7 @@ export const METRICS = [ group: 'Climbing', kind: 'line', label: 'Hardest route sent', + help: 'The best of each week, endurance and volume days left out', applies: (r) => has(r.disciplines, 'climbing'), // The axis is the ladder the log is written on (axisLadder): a plus/minus // log is not labelled with letter rungs it never used. @@ -503,14 +518,42 @@ export const METRICS = [ }, series: (r, plan) => { const ladder = routeAxis(r, plan) - return perSession(r, (e) => { - const opt = optOf(plan, e) - const best = opt ? hardestSent(opt, e.data?.out || {}, 'yds') : null + return bestPerWeek(r, plan, (e) => { + const best = limitSent(plan, e, 'yds') return best === null ? null : indexOn(ladder, best) }) }, }, + { + key: 'hardFingers', + group: 'Climbing', + kind: 'bar', + label: 'Hard finger days per week', + applies: (r) => has(r.disciplines, 'climbing'), + series: (r, plan) => { + const days = new Set(hardDays(r, plan)) + // Each DATE once, in its week, however many sessions it held. + const firsts = new Set() + return byWeek(r, plan, e => { + if (!days.has(e.date) || firsts.has(e.date)) return 0 + firsts.add(e.date) + return 1 + }) + }, + }, + { + key: 'climbs', + group: 'Climbing', + kind: 'bar', + label: 'Climbs per week', + help: 'Routes, problems and laps: the count, or the climbs described', + applies: (r) => has(r.disciplines, 'climbing'), + series: (r, plan) => byWeek(r, plan, e => { + const opt = optOf(plan, e) + return opt ? climbVolume(opt, e.data?.out || {}) : 0 + }), + }, { key: 'fingers', group: 'Climbing', @@ -592,6 +635,13 @@ export function metricsFor(plan, resolved) { if (!g) { g = { name: m.group, metrics: [] }; groups.push(g) } g.metrics.push(m) } + // Climbing follows the general charts on the whole page (§10.8). Once the + // person has PICKED Climbing it leads (#97, F3): they asked about climbing, and + // the pyramids sat two to four screens under three bars the unfiltered page has. + if (resolved?.scope?.activity === 'climbing') { + const at = groups.findIndex(g => g.name === 'Climbing') + if (at > 0) groups.unshift(...groups.splice(at, 1)) + } return groups } diff --git a/app/src/lib/planflow.js b/app/src/lib/planflow.js index 5bde957..8919fcc 100644 --- a/app/src/lib/planflow.js +++ b/app/src/lib/planflow.js @@ -140,9 +140,16 @@ export function filedFor(pres, plan, liftField, chosen = null) { return f && (f.category || f.activity) ? { ...pres, category: f.category || null, activity: f.activity || null } : pres } -/** Nothing on it says what it is: the keep step asks, once, in one row (`fileChoices`). */ +/** + * Nothing on it says what it is: the keep step asks, once, in one row + * (`fileChoices`). Asked exactly where `filedFor` would use the answer: a + * category on the plan or on any block files it already (a model's Lift block + * beside its Run block), and a question whose answer is thrown away is a dead + * control (C N6). + */ export function needsFiling(pres, plan, liftField) { if (!hasWork(pres)) return false + if (pres.category || (pres.blocks || []).some(b => b.category)) return false const f = filedFor(pres, plan, liftField) return !f.category && !f.activity } diff --git a/app/src/lib/prescription.js b/app/src/lib/prescription.js index 999a123..d4d2d71 100644 --- a/app/src/lib/prescription.js +++ b/app/src/lib/prescription.js @@ -994,26 +994,69 @@ function appendNamed(pres, name) { /** * Keep what the user has already done across an edit to the prescription. * - * Ids are positional, so adding a set to block one renumbers everything after it. - * Re-keying by (item name, set index) rather than by id is what stops that - * renumbering from unticking half the session. An item the user deleted takes its - * logged sets with it, which is correct — the user deleted it. + * Ids are positional, so adding a block, removing an exercise or moving one to + * another block renumbers the sets after it, and a run keyed by the old ids + * would put its done marks on whatever took their place (#95 review: Hard + * moved to Main, its mark landed on Easy). So each item is matched to itself + * (`sameItems`) and its sets follow it, set by set. An item the user deleted + * takes its logged sets with it, which is correct — the user deleted it. */ export function remapRun(run, before, after) { if (!run?.sets) return run - const key = (s) => `${s.itemName}::${s.index}` - const old = new Map(prescriptionSteps(before).map(s => [s.setId, key(s)])) - const next = new Map(prescriptionSteps(after).map(s => [key(s), s.setId])) - + const ids = new Map() + for (const [a, b] of sameItems(before, after)) { + a.sets.forEach((st, k) => { if (b.sets[k]) ids.set(st.id, b.sets[k].id) }) + } const sets = {} for (const [id, value] of Object.entries(run.sets)) { - const id2 = next.get(old.get(id)) + const id2 = ids.get(id) if (id2) sets[id2] = value } - const skipped = (run.skipped || []) - .map(id => next.get(old.get(id))) - .filter(Boolean) - return { ...run, sets, skipped, cursor: next.get(old.get(run.cursor)) || null } + const skipped = (run.skipped || []).map(id => ids.get(id)).filter(Boolean) + return { ...run, sets, skipped, cursor: ids.get(run.cursor) || null } +} + +/** + * Which item of `after` each item of `before` is, as [before, after] pairs. + * By `uid` where both have one (a synced workout); then the longest run of + * names in the same order, which a move or a removal leaves intact and which + * keeps two "Hard" intervals apart (matching by name alone put both on the + * last one); then what moved out of that order (a swap) by name; then an item + * still in its own place under a new name (renamed, or its exercise swapped). + */ +function sameItems(before, after) { + const was = (before?.blocks || []).flatMap(b => b.items || []) + const now = (after?.blocks || []).flatMap(b => b.items || []) + const pairs = new Map() + const taken = new Set() + was.forEach((it, i) => { + if (!it.uid) return + const j = now.findIndex((x, k) => !taken.has(k) && x.uid === it.uid) + if (j >= 0) { pairs.set(i, j); taken.add(j) } + }) + const a = was.map((_, i) => i).filter(i => !pairs.has(i)) + const b = now.map((_, j) => j).filter(j => !taken.has(j)) + // Longest common subsequence of names, over what the uids left. + const L = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0)) + for (let i = a.length - 1; i >= 0; i--) { + for (let j = b.length - 1; j >= 0; j--) { + L[i][j] = was[a[i]].name === now[b[j]].name ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]) + } + } + for (let i = 0, j = 0; i < a.length && j < b.length;) { + if (was[a[i]].name === now[b[j]].name) { pairs.set(a[i], b[j]); taken.add(b[j]); i++; j++ } + else if (L[i + 1][j] >= L[i][j + 1]) i++ + else j++ + } + // What moved out of that order (a swap), by name; then a rename, by place. + for (const same of [(it, x) => x.name === it.name, (it, x) => x.id === it.id]) { + was.forEach((it, i) => { + if (pairs.has(i)) return + const j = now.findIndex((x, k) => !taken.has(k) && same(it, x)) + if (j >= 0) { pairs.set(i, j); taken.add(j) } + }) + } + return [...pairs].map(([i, j]) => [was[i], now[j]]) } /* ------------------------------------------------------------- the split */ @@ -1249,10 +1292,10 @@ export const removeItem = (pres, itemId) => mapItem(pres, itemId, () => null) * muscle groups and moves it with arrow buttons — this is a web app, not a * native one, so there is no dragging. * - * WITHIN a block only. The blocks are the seams the session splits on (see - * `splitPrescription`), so dragging a lift into the warm-up would silently move - * it to a different entry and a different quota — a reorder should change the - * order and nothing else. + * Up and down stay WITHIN a block. The blocks are the seams the session splits + * on (see `splitPrescription`), so dragging a lift into the warm-up would + * silently move it to a different entry — a reorder should change the order and + * nothing else. Another block is its own, named choice (`{ block }`, below). * * Ids are positional and `reindex` re-mints them, so a move renumbers every set * after it — which is why it hands back the moved item's NEW id along with the @@ -1263,6 +1306,7 @@ export const removeItem = (pres, itemId) => mapItem(pres, itemId, () => null) * answers, so the caller never has to special-case the first and last rows. */ export function moveItem(pres, itemId, dir) { + if (dir && typeof dir === 'object') return moveItemTo(pres, itemId, dir.block) const step = dir === 'up' ? -1 : 1 let landed = itemId const blocks = (pres?.blocks || []).map((b, bi) => { @@ -1278,6 +1322,33 @@ export function moveItem(pres, itemId, dir) { return { pres: reindex({ ...pres, blocks }), itemId: landed } } +/** + * `moveItem(pres, id, { block })`: to the END of another block (#95, C N12), + * where moving Face pull from Accessory to Main was a remove and an add, its + * numbers lost. The exercise goes whole, its uid with it, so a synced copy + * sees the same exercise in its new place. Into a circuit it keeps its first + * set, as `setCircuit` does to a whole block: rounds are the circuit's. The + * block it leaves follows the editor's one rule for an empty block + * (`blockSurvives`): gone unless it has a note or was picked. Same block, or + * no such block or exercise: unchanged. + */ +function moveItemTo(pres, itemId, blockId) { + const blocks = pres?.blocks || [] + const from = blocks.findIndex(b => b.items.some(it => it.id === itemId)) + const to = blocks.findIndex(b => b.id === blockId) + if (from < 0 || to < 0 || from === to) return { pres, itemId } + const item = blocks[from].items.find(it => it.id === itemId) + const moved = blocks[to].circuit ? { ...item, sets: item.sets.slice(0, 1) } : item + const next = blocks.map((b, bi) => { + if (bi === from) return { ...b, items: b.items.filter(it => it.id !== itemId) } + if (bi === to) return { ...b, items: [...b.items, moved] } + return b + }) + const kept = next.filter((b, bi) => bi === to || blockSurvives(b)) + const at = kept.indexOf(next[to]) + return { pres: reindex({ ...pres, blocks: kept }), itemId: `b${at}i${next[to].items.length - 1}` } +} + /** * Is this whole prescription lifting? * diff --git a/app/src/lib/stats.js b/app/src/lib/stats.js index 39315d6..94b79d2 100644 --- a/app/src/lib/stats.js +++ b/app/src/lib/stats.js @@ -1,26 +1,15 @@ /* - * What a session adds up to, in words, on one line. + * What a rest day says, on one line. * - * Pulled out of `tabs.jsx` on 2026-09-21 because the day list stopped being the - * only place that asks. The quota bars ask it too: pressing a bar opens onto the - * workouts that filled it, and a row reading "Lunch Ride With friends · 45 min" - * is a row that has not said which ride it was — pressing a bar felt like it - * went nowhere, partly because there was nothing on the row worth arriving at. + * This file used to hold `sessionStats`, the one-line readout of any session, + * pulled out of `tabs.jsx` on 2026-09-21 for the quota bars. The bars went in + * #31 and nothing called it after (regrade F10, #97): each list now builds its + * own line from the shared readers (`climbLine`, `liftedLine`, `loggedMinutes`), + * so it was removed rather than left to drift from them. * * Pure, and takes the resolved card rather than the menu, so it has no opinion * about where an entry came from. */ -import { totalSets, totalReps } from '../setlog.jsx' -import { liftedLine, liftFieldIn } from './lifts.js' - -/** "8:04 /mi" from distance and time — the number you'd have worked out anyway. */ -function paceLabel(out) { - const mi = Number(out.distance) - const min = Number(out.duration) - if (!(mi > 0) || !(min > 0)) return null - const per = min / mi - return `${Math.floor(per)}:${String(Math.round((per % 1) * 60)).padStart(2, '0')} /mi` -} /** * A rest day has no numbers, so its readout is WHY: the reason chip RestPrompt @@ -35,28 +24,3 @@ export function restStats(entry, opt) { const note = typeof out.notes === 'string' ? out.notes.trim() : '' return [why, note ? (note.length > 80 ? `${note.slice(0, 79)}…` : note) : null].filter(Boolean) } - -/** The one-line readout of a session, wherever one is listed. */ -export function sessionStats(entry, opt) { - if (opt?.role === 'rest') return restStats(entry, opt) - const out = entry?.data?.out || {} - const bits = [] - const mins = entry?.data?.minutes ?? opt?.minutes - if (mins) bits.push(`${mins} min`) - if (Number(out.distance) > 0) bits.push(`${out.distance} mi`) - const pace = paceLabel(out) - if (pace) bits.push(pace) - if (Number(out.speed) > 0) bits.push(`${out.speed} mph`) - if (Number(out.elevation) > 0) bits.push(`${out.elevation} ft up`) - const sets = totalSets(out) - const reps = totalReps(out) - if (sets) bits.push(`${sets} set${sets === 1 ? '' : 's'}${reps ? `, ${reps} reps` : ''}`) - // A lift session's exercises are their own list, not the plan's set log — see - // lib/lifts.js. "6 exercises · 18 sets · 4,120 lb" in one bit. - const lifting = liftedLine(entry, liftFieldIn(opt)) - if (lifting) bits.push(lifting) - if (Number.isFinite(out.intensity)) bits.push(`intensity ${out.intensity}/4`) - if (Number.isFinite(out.rpe)) bits.push(`RPE ${out.rpe}`) - if (Number.isFinite(out.fingers)) bits.push(`fingers ${out.fingers}/5`) - return bits -} diff --git a/app/src/lib/trainer.js b/app/src/lib/trainer.js index ee4a74c..9634c95 100644 --- a/app/src/lib/trainer.js +++ b/app/src/lib/trainer.js @@ -29,7 +29,7 @@ import { optFor } from './menu.js' import { sharePeople, sharedPeopleOn, addPerson } from './shared.js' import { isLiftOnly, followWeightModes, endCircuit, circuitOnly, circuitEnded, runProgress, prescriptionSteps, finishRun, - runOutputs, fillOut, blockTimer, + runOutputs, fillOut, blockTimer, remapRun, } from './prescription.js' import { compile, settle } from './timer.js' import { liftFieldIn } from './lifts.js' @@ -360,7 +360,11 @@ export function applyOut(entry, opt, out) { * logged sets became (#58, `followWeightModes`). */ export function applyPlan(entry, opt, plan) { - const data = followWeightModes(entry.data, { ...entry.data, plan }, liftFieldIn(opt)) + // A run's marks are keyed by set ids, which the edit may have renumbered (a + // move, a removal): they follow their sets (`remapRun`). + const before = entry.data?.plan + const run = entry.data?.run?.sets && before?.blocks ? { run: remapRun(entry.data.run, before, plan) } : {} + const data = followWeightModes(entry.data, { ...entry.data, plan, ...run }, liftFieldIn(opt)) return { ...entry, data: { ...data, name: plan.title || entry.data?.name } } } diff --git a/app/src/lib/viz.jsx b/app/src/lib/viz.jsx index 6d040a2..53ecef0 100644 --- a/app/src/lib/viz.jsx +++ b/app/src/lib/viz.jsx @@ -14,7 +14,7 @@ import { useLayoutEffect, useMemo, useRef, useState } from 'react' import { localIso } from './dates.js' -import { timeX, dateWords, needsYear } from './vizscale.js' +import { timeX, dateWords, needsYear, deltaBase } from './vizscale.js' export const SERIES = ['var(--series-1)', 'var(--series-2)', 'var(--series-3)'] @@ -148,8 +148,11 @@ export function LineChart({ points, label, help, unit = '', height = 190, color const path = data.map((d, i) => `${i ? 'L' : 'M'}${xAt(i).toFixed(1)},${yAt(d.y).toFixed(1)}`).join('') const last = data[data.length - 1] + // Like with like (lib/vizscale.js `deltaBase`): the change is from the earliest + // point of the same kind as the newest, when the points say what they are of. const first = data[0] - const delta = data.length > 1 ? last.y - first.y : null + const since = deltaBase(data) + const delta = since ? last.y - since.y : null const onMove = e => { // Touch events carry no clientX of their own — read the first touch point. @@ -168,13 +171,13 @@ export function LineChart({ points, label, help, unit = '', height = 190, color {fmtY ? fmt(last.y) : last.y} {!fmtY && {unit}} {delta != null && delta !== 0 && (() => { - const real = !noisePct || Math.abs(delta) > (first.y * noisePct) / 100 + const real = !noisePct || Math.abs(delta) > (since.y * noisePct) / 100 return ( 0 ? 'up' : 'down') : 'noise'}`}> {delta > 0 ? '▲' : '▼'}{' '} {fmtY - ? `${fmt(first.y)} → ${fmt(last.y)} since ${day(first.x)}` - : `${Math.abs(Number(delta.toFixed(1)))}${unit} since ${day(first.x)}`} + ? `${fmt(since.y)} → ${fmt(last.y)} since ${day(since.x)}` + : `${Math.abs(Number(delta.toFixed(1)))}${unit} since ${day(since.x)}`} {noisePct && !real && ' · inside noise'} ) diff --git a/app/src/lib/vizscale.js b/app/src/lib/vizscale.js index a53240b..0e1ecbc 100644 --- a/app/src/lib/vizscale.js +++ b/app/src/lib/vizscale.js @@ -45,3 +45,18 @@ export function needsYear(xs, thisYear = new Date().getFullYear()) { const years = new Set(xs.filter(x => ISO.test(String(x))).map(x => Number(String(x).slice(0, 4)))) return years.size > 1 || (years.size === 1 && !years.has(thisYear)) } + +/** + * The point a line's change is measured FROM ("▲ 5.10 → 5.11 since …"). The first + * point, unless the points say what they are of (`of`, the card a "hardest sent" + * came from, #97 F7): then the earliest point of the same thing as the newest, so + * an easy ARC day after a lead day is not drawn as a decline. Null when the newest + * point has nothing like it before it: no change is claimed at all. + */ +export function deltaBase(data) { + if (!data?.length || data.length < 2) return null + const last = data[data.length - 1] + if (last.of == null) return data[0] + const base = data.find(d => d.of === last.of) + return base && base !== last ? base : null +} diff --git a/app/src/modal.jsx b/app/src/modal.jsx index 41c507b..cedde20 100644 --- a/app/src/modal.jsx +++ b/app/src/modal.jsx @@ -72,28 +72,78 @@ export const EDIT_SETTLE_MS = 400 /** A finger, not a mouse: where a footer under the box being typed in is a hazard. */ const touchScreen = () => typeof window !== 'undefined' && Boolean(window.matchMedia?.('(pointer: coarse)').matches) +/** Is a box being typed into right now, anywhere on the page? */ +const typingNow = () => { + const el = typeof document !== 'undefined' ? document.activeElement : null + return isTextEntry(el) && el.isConnected !== false +} + +/** + * The footer policy's memory, as plain events (`useEditing` feeds it). A box + * taking focus hides the footer; it comes back `delay` after nothing is being + * typed into, checked again when the timer runs. + * + * NOT ONLY ON BLUR (C N1). A focused box that is REMOVED from the page fires no + * blur React hears: the exercise picker's search box goes the moment an exercise + * is picked, and on iOS the row tapped does not take focus, so the footer, with + * the only way to keep the plan, stayed hidden with nothing saying why. + * `changed()` is called whenever the page's content changes or focus leaves + * anything, and asks the page itself (`typing`) whether a box still has focus. + */ +export function editWatch({ typing = typingNow, set, delay = EDIT_SETTLE_MS, touch = touchScreen } = {}) { + let on = false + let timer = null + const settle = () => { + clearTimeout(timer) + timer = setTimeout(() => { + timer = null + if (on && !typing()) { on = false; set(false) } + }, delay) + } + return { + focus(el) { + if (!isTextEntry(el) || !touch()) return + clearTimeout(timer) + if (!on) { on = true; set(true) } + }, + // Moving from one box straight to another never shows the footer in between. + blur(el, next) { + if (!on || !isTextEntry(el) || isTextEntry(next)) return + settle() + }, + changed() { if (on && !typing()) settle() }, + stop() { clearTimeout(timer) }, + } +} + /** * Whether a box inside this layer has focus, for the footer policy above. - * Spread `bind` on the layer's root: React's focus events bubble. Moving from - * one box straight to another never shows the footer in between. Touch screens - * only: with a mouse there is no keyboard rising under a thumb, and hiding the - * footer would only cost a click ("Write it for me" after typing the ask). + * Spread `bind` on the layer's root: React's focus events bubble (through a + * portal too), and while editing the page is watched for a box removed under + * the focus (`editWatch`): the whole body, because a box in a popover over the + * layer (a block's name) is portalled out of it. Touch screens only: with a + * mouse there is no keyboard rising under a thumb, and hiding the footer would + * only cost a click ("Write it for me" after typing the ask). */ export function useEditing() { const [editing, setEditing] = useState(false) - const timer = useRef(null) - useEffect(() => () => clearTimeout(timer.current), []) + const watch = useRef(null) + if (!watch.current) watch.current = editWatch({ set: setEditing }) + useEffect(() => () => watch.current.stop(), []) + useEffect(() => { + if (!editing || typeof document === 'undefined') return undefined + const changed = () => watch.current.changed() + const mo = typeof MutationObserver !== 'undefined' && document.body ? new MutationObserver(changed) : null + mo?.observe(document.body, { childList: true, subtree: true }) + // Focus leaving for somewhere React does not see (another window, a box in a + // portal closing): asked once the move has landed. + const out = () => setTimeout(changed, 0) + document.addEventListener('focusout', out, true) + return () => { mo?.disconnect(); document.removeEventListener('focusout', out, true) } + }, [editing]) const bind = { - onFocus: (e) => { - if (!isTextEntry(e.target) || !touchScreen()) return - clearTimeout(timer.current) - setEditing(true) - }, - onBlur: (e) => { - if (!isTextEntry(e.target) || isTextEntry(e.relatedTarget)) return - clearTimeout(timer.current) - timer.current = setTimeout(() => setEditing(false), EDIT_SETTLE_MS) - }, + onFocus: (e) => watch.current.focus(e.target), + onBlur: (e) => watch.current.blur(e.target, e.relatedTarget), } return { editing, bind } } diff --git a/app/src/planner.jsx b/app/src/planner.jsx index 22eabe0..07255c3 100644 --- a/app/src/planner.jsx +++ b/app/src/planner.jsx @@ -18,7 +18,7 @@ * the phone; this file is the web's view of it. */ -import { useEffect, useMemo, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { Icon } from './lib/icons.jsx' import { FullScreen } from './modal.jsx' import { PrescriptionEditor } from './editor.jsx' @@ -232,11 +232,22 @@ export function groupedKinds(plan) { * component. Labels only: a kind's `hint` and `prompt` are written for the * model and never reach the hand-built route. Every kind is in the page (a * `
`), so the reachability tests can see each one. + * + * `onPicked` (the builder's Start from, #95, C N4): a pick folds the list and + * hands the kind back, so the screen can go to the block it made. Left open, + * the list was three screens of chips and the block landed under all of it: + * the chip lit, and nothing seemed to happen. Folded, its head says what was + * picked; open it again to add another. */ -export function KindChips({ plan, picked = [], setPicked, title, className = 'askkinds' }) { +export function KindChips({ plan, picked = [], setPicked, title, className = 'askkinds', onPicked = null }) { const groups = groupedKinds(plan) + const [open, setOpen] = useState(!onPicked && picked.length > 0) const has = (k) => picked.some(p => p.key === k.key) - const toggle = (k) => setPicked(has(k) ? picked.filter(p => p.key !== k.key) : [...picked, k]) + const toggle = (k) => { + const adding = !has(k) + setPicked(adding ? [...picked, k] : picked.filter(p => p.key !== k.key)) + if (adding && onPicked) { setOpen(false); onPicked(k) } + } const known = new Set(groups.flatMap(g => g.items.map(k => k.key))) // A draft written before #59 may carry a "Something else" kind; it is shown, and can be taken off. const extra = picked.filter(k => !known.has(k.key)) @@ -246,10 +257,11 @@ export function KindChips({ plan, picked = [], setPicked, title, className = 'as ) return ( -
0 || undefined}> +
0) || undefined} + onToggle={(e) => setOpen(e.currentTarget.open)}>

{title}

- {picked.length ? `${picked.length} picked` : 'Optional'} + {!picked.length ? 'Optional' : onPicked ? kindsLine(picked) : `${picked.length} picked`}
{extra.length > 0 &&
{extra.map(chip)}
} @@ -263,6 +275,9 @@ export function KindChips({ plan, picked = [], setPicked, title, className = 'as ) } +/** "Legs + Zone 2 ride": what a folded Start from has picked. */ +export const kindsLine = (picked) => picked.map(k => k.label).join(' + ') + /* ------------------------------------------------- step: how long, what for */ /** @@ -679,19 +694,31 @@ export function BuildStep({ }) { const sets = prescriptionSteps(pres).length const empty = !hasWork(pres) + // A Start-from pick makes a block (last, in the order tapped): go to it once it is drawn. + const editor = useRef(null) + const goToNew = useRef(false) + useEffect(() => { + if (!goToNew.current) return + goToNew.current = false + const last = [...(editor.current?.querySelectorAll('.presc-block') || [])].at(-1) + last?.scrollIntoView?.({ block: 'start', behavior: 'smooth' }) + }, [pres]) return ( <> {empty && setPicked && ( - + { goToNew.current = true }} /> )} - setPres(appendPiece(pres, name, { blockId, by, unit })) - } /> +
+ setPres(appendPiece(pres, name, { blockId, by, unit })) + } /> +
{fileAs &&
{fileAs}
} {day &&
{day}
} diff --git a/app/src/session.jsx b/app/src/session.jsx index 6aaf9f6..bc87737 100644 --- a/app/src/session.jsx +++ b/app/src/session.jsx @@ -19,6 +19,7 @@ import { Icon } from './lib/icons.jsx' import { MovesList, hasMoves } from './howto.jsx' import { ceilingState, CF_CORRECTION_KG } from './lib/force.js' import { blockTimers } from './lib/workout.js' +import { countsClimbs } from './lib/grades.js' /** Latest usable max, expressed as TOTAL load on the fingers (bodyweight + added). */ export function resolveMax(entries) { @@ -334,3 +335,30 @@ export function SessionView({ session, entries, variant = 'compact', showEvidenc ) } + +/* ------------------------------------------------- a climbing card, doing */ + +/* + * A CLIMBING CARD BEING LOGGED OPENS ON ITS LOG (#97, F5). The sheet put the + * protocol, the evidence chip, its tabs and "The moves" above the set log, and the + * per-climb log started about 1,070px down: a card you are standing in the gym + * with read as an essay. Lifts got a doing mode in #79; this is the climbing one. + * Order on a day being logged: the dose (one line, still what the session is), + * "last time", the log, then the protocol and its evidence in ONE fold. On a day + * still to come it is planning, and the protocol stays open as before. + * + * Which cards: those whose log counts climbs (routes, problems, laps), read off + * the plan's own declarations (`countsClimbs`), so it holds for any plan file. + */ +export const climbLogLeads = (opt) => (opt?.logSpec?.exercises || []).some(ex => countsClimbs(ex)) + +/** The protocol and evidence of a card, folded under the log. */ +export function SessionAbout({ session, entries }) { + if (!session?.protocol) return null + return ( +
+ About this session + +
+ ) +} diff --git a/app/src/sessionlog.jsx b/app/src/sessionlog.jsx index bea4f3c..6fad868 100644 --- a/app/src/sessionlog.jsx +++ b/app/src/sessionlog.jsx @@ -15,6 +15,7 @@ import { ActivityPicker } from './activitypicker.jsx' import { activityOf, activityLabel } from './lib/activities.js' import { liftsLine, liftsDone, liftFieldIn } from './lib/lifts.js' import { priorSessions } from './lib/history.js' +import { climbLine, mootHardest } from './lib/grades.js' import { asksItsOwnDuration, minutesFor, minutesSourceOf } from './lib/minutes.js' import { visibleOutputs, pruneHidden, derivedValue, filledBy } from './lib/outputs.js' import { gateResolver } from './lib/activities.js' @@ -43,10 +44,14 @@ const dayLabel = (iso) => dayWords(iso) * Its lifting is what was lifted (`liftsDone`): on a planned workout done on the * sheet, the plan's sets (D11). */ -function priorWork(entry, field = null) { +function priorWork(entry, field = null, session = null) { const out = entry?.data?.out || {} const bits = [] - const sets = totalSets(out) + // A climbing session answers "what did I climb last time" first, in the line + // every list uses (lib/grades.js `climbLine`, #97 F2), not "1 set, 5 reps". + const climbed = session ? climbLine(session, out) : '' + if (climbed) bits.push(climbed) + const sets = climbed ? 0 : totalSets(out) const reps = totalReps(out) if (sets) bits.push(`${sets} set${sets === 1 ? '' : 's'}${reps ? `, ${reps} reps` : ''}`) const lifting = liftsLine({ lifts: liftsDone(entry) }, field) @@ -86,7 +91,7 @@ export function PriorNote({ entries, session, excludeId, entry = null, all = fal : priorTitle(1, whose)} {shown.map(e => { - const work = priorWork(e, liftFieldIn(session)) + const work = priorWork(e, liftFieldIn(session), session) return (
@@ -576,6 +581,8 @@ export function SessionLog({ const planHolds = Boolean(entry?.data?.plan?.blocks?.length) const fields = visibleOutputs(session, out, derive) .filter(f => !(f.type === 'lifts' && planHolds && !(Array.isArray(out[f.key]) && out[f.key].length))) + // A typed "hardest" under a list of graded climbs is moot (lib/grades.js, #97 F9b). + .filter(f => !mootHardest(session, out, f)) // Pruned on the way in, so what is stored and what is on screen can never // disagree — correcting a run to a lift takes its distance with it rather than @@ -637,7 +644,7 @@ export function SessionLog({ return (
{outcomesFor(scale).map(o => ( @@ -253,8 +261,9 @@ export function ClimbLog({ count, values, spec, onChange, onMore, onDrop, what = ))}
+ {/* Says it opens (#97, F9a: "Details" alone read as a label). */}
- Details + More details
{(spec?.styles?.length ?? 0) > 0 && (