Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
perf: History renders a page of rows at a time and grows as it is scrolled
Duarte Santosc3830ad137a1
diff --git a/frontend/src/views/History.grow.test.jsx b/frontend/src/views/History.grow.test.jsxnew file mode 100644index 000000000..2d8b5aecf--- /dev/null+++ b/frontend/src/views/History.grow.test.jsx@@ -0,0 +1,92 @@+// @vitest-environment happy-dom+// History renders its rows a page at a time as the list is scrolled (performance round 2): a+// 400-workout history used to render every row on each open. Coming back renders as many rows as+// before, so the page can land where it was scrolled to.+import React, { act } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { createRoot } from 'react-dom/client'+import { MemoryRouter } from 'react-router-dom'+let DEF, useStore++const clone = v => JSON.parse(JSON.stringify(v))+let observers = []+class FakeIO {+ constructor(cb) { this.cb = cb; this.els = []; observers.push(this) }+ observe(el) { this.els.push(el) }+ disconnect() { this.els = []; observers = observers.filter(o => o !== this) }+}+// The end of the list comes into reach: every live observer is told.+const reachEnd = () => act(() => { for (const o of [...observers]) o.cb(o.els.map(target => ({ target, isIntersecting: true }))) })++const day = i => new Date(Date.UTC(2025, 0, 1) + i * 864e5).toISOString().slice(0, 10)+function install(n) {+ const st = clone(DEF)+ const workouts = Array.from({ length: n }, (_, i) => ({ id: 'w' + i, d: day(i), start: Date.parse(day(i) + 'T10:00:00Z'), end: Date.parse(day(i) + 'T11:00:00Z'), name: 'Push ' + i, entries: [], prs: [] }))+ Object.assign(st, { routines: [], week: {}, dayPlan: {}, active: null, workouts, weighIn: false })+ useStore.setState({ S: st, user: null })+}++const roots = []+function mount(History) {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ roots.push(root)+ act(() => root.render(<MemoryRouter><History /></MemoryRouter>))+ return host+}+const rows = host => host.querySelectorAll('.list .item').length++describe('History grows as it is scrolled', () => {+ let History, PAGE+ beforeEach(async () => {+ vi.resetModules()+ observers = []+ window.IntersectionObserver = FakeIO+ ;({ DEF, useStore } = await import('../store/useStore.js'))+ ;({ default: History, HISTORY_PAGE: PAGE } = await import('./History.jsx'))+ })+ afterEach(() => {+ for (const r of roots.splice(0)) act(() => r.unmount())+ document.body.innerHTML = ''+ delete window.IntersectionObserver+ })++ it('renders the first page, then a page more each time its end comes into reach, newest first', async () => {+ install(150)+ const host = mount(History)+ expect(rows(host)).toBe(PAGE)+ expect(host.querySelector('.list .item .tt').textContent).toBe('Push 149')+ reachEnd()+ expect(rows(host)).toBe(2 * PAGE)+ reachEnd()+ expect(rows(host)).toBe(150)+ // all there: nothing left to observe+ expect(observers).toHaveLength(0)+ expect(host.querySelector('.list .item:last-child .tt').textContent).toBe('Push 0')+ })++ it('coming back renders as many rows as before (so the scroll position can be restored)', async () => {+ install(300)+ let host = mount(History)+ reachEnd(); reachEnd()+ expect(rows(host)).toBe(3 * PAGE)+ act(() => roots.pop().unmount())+ host = mount(History)+ expect(rows(host)).toBe(3 * PAGE)+ })++ it('a short history is whole, with nothing observed', async () => {+ install(12)+ const host = mount(History)+ expect(rows(host)).toBe(12)+ expect(observers).toHaveLength(0)+ })++ it('without IntersectionObserver the whole list renders, as before', async () => {+ delete window.IntersectionObserver+ install(150)+ const host = mount(History)+ expect(rows(host)).toBe(150)+ })+})diff --git a/frontend/src/views/History.jsx b/frontend/src/views/History.jsxindex 504c45427..5d39a6089 100644--- a/frontend/src/views/History.jsx+++ b/frontend/src/views/History.jsx@@ -1,3 +1,4 @@+import { useEffect, useRef, useState } from 'react'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { t, tn } from '../lib/i18n.js'@@ -16,17 +17,38 @@ export function historyRows(S) {return rows.map((r, i) => [r, i]).sort((a, b) => (a[0].d < b[0].d ? 1 : a[0].d > b[0].d ? -1 : b[1] - a[1])).map(([r]) => r)}+// The list grows as it is scrolled: the first PAGE rows, then PAGE more whenever its end comes+// within a screen or so. A 400-workout history rendered every row (some 1500 components) on each+// open. How far it had grown is kept for the session, so coming back (the back button, the edge+// swipe) renders the same rows and the page lands where it was scrolled to.+export const HISTORY_PAGE = 60+let grownTo = HISTORY_PAGE+export default function History() {const nav = useNavigate()const S = useStore(s => s.S)const rows = historyRows(S)+ const [shown, setShown] = useState(() => Math.max(HISTORY_PAGE, grownTo))+ const end = useRef(null)+ const more = rows.length > shown+ useEffect(() => { grownTo = Math.max(grownTo, shown) }, [shown])+ useEffect(() => {+ if (!more) return+ const IO = typeof window !== 'undefined' ? window.IntersectionObserver : undefined+ // Without an observer (an old engine) the list is simply whole, as before.+ if (typeof IO !== 'function') { setShown(Infinity); return }+ const io = new IO(es => { if (es.some(e => e.isIntersecting)) setShown(n => n + HISTORY_PAGE) }, { rootMargin: '0px 0px 1200px 0px' })+ if (end.current) io.observe(end.current)+ return () => io.disconnect()+ }, [more, shown])return <><div className="hdr"><button className="iconbtn" data-back="/stats" onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button><div style={{ flex: 1, marginInlineStart: 12 }}><h1>{t('History')}</h1><div className="sub">{tn('{0} workout', '{0} workouts', S.workouts.length)}</div></div></div><Button icon="plus" onClick={logPastWorkoutSheet} style={{ marginBottom: 12 }}>{t('Log a past workout')}</Button>- {rows.length ? <div className="list">{rows.map(r => r.w+ {rows.length ? <><div className="list">{(more ? rows.slice(0, shown) : rows).map(r => r.w? <WorkoutRow key={r.w.id} w={r.w} onClick={() => workoutDetailSheet(r.w)} />: <DayNoteRow key={'note-' + r.d} iso={r.d} note={r.note} />)}</div>+ {more && <div ref={end} aria-hidden="true" style={{ height: 1 }} />}</>: <div className="empty"><div className="ico"><Icon name="history" /></div>{t('No workouts yet. Your first one will land here.')}</div>}</>}