El registro de actividad abre plegado en los diez más nuevos
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

"Muéstrame los últimos 10 y que diga mostrar más, para que no se vea todo eso para abajo." Exacto:
con 25 eventos el registro llenaba la pantalla y empujaba el resto del panel fuera de vista, y con un
día movido son cientos. El encabezado ya decía cuántos hay ("25 events, kept for 90 days"); el cuerpo
ahora empieza por los diez más nuevos y un botón **Show more** revela diez más por vez.

Tres detalles que lo hacen correcto en vez de sólo corto:

  · **Lo que ya está cargado se revela antes de pedir nada.** El botón revela de la lista que tiene y
    sólo va al servidor cuando no le queda nada por mostrar — y entonces pide la página siguiente con
    `before`, que ya sabía hacer. Sin esto, cada clic sería un viaje de red para datos que ya estaban
    en memoria.
  · **Al lado del botón dice "10 of 25"**, así que nunca queda la duda de cuánto falta; el número sale
    del `total` del servidor, no del largo de lo cargado.
  · **El botón desaparece cuando no queda nada**, en vez de quedarse invitando a un clic que no hace
    nada. Y al recargar (el ↻ del encabezado) vuelve a plegarse, que es el punto de plegarlo.

De paso, `load` ya no asume que la respuesta traiga `events`: una respuesta sin eventos es una
respuesta sin eventos, no un crash — y un crash acá se lleva la tarjeta entera del panel.

Tests: 4 en `Admin.test.jsx` (abre en diez y revela hasta el final; pide la página siguiente cuando se
le acaba lo cargado, y no antes; log vacío sin botón). Mutation-check de las dos mitades: sin el
recorte se renderizan todos, y con la página en 50 fallan los dos de plegado.
This commit is contained in:
dsantillan committed 2026-09-23 19:57:43 -04:00
1 parent f36a32e8af
commit e1d28f971d
2 files changed
+96 -8

No files matched your search

+28 -7
View File
@@ -157,19 +157,38 @@ function InvitesCard({ invites, reload, inviteOnly }) {
// Who signed in, who tried and failed, what an admin changed. A card rather than its own route:
// the dashboard is deliberately one page of cards, and the 95 % use of this is a glance at the
// last twenty events. Paging follows Library.jsx's house style — "Show more", not page numbers.
/* How many events the card shows before somebody asks for more.
*
* The log is history and history is long: twenty-five rows is a wall of text that pushes the rest of
* the dashboard off the screen, and a cleared log is a full one again the next day. The count in the
* lead line says how much there is — the newest ten are shown, and one button reveals the rest, ten
* at a time, fetching from the server once everything already loaded is on screen. */
const AUDIT_PAGE = 10
function AuditCard({ tick }) {
const toast = useUI(s => s.toast)
const [meta, setMeta] = useState(null) // last response minus the rows: total, retention, …
const [rows, setRows] = useState([])
const [cat, setCat] = useState('')
const [shown, setShown] = useState(AUDIT_PAGE)
const load = (c, before) => api('/api/admin/audit?limit=50&cat=' + c + (before ? '&before=' + before : ''))
.then(r => { setMeta(r); setRows(x => (before ? x.concat(r.events) : r.events)) })
// `|| []` because a response without events is a response with no events, not a crash: an
// admin card that throws takes the whole dashboard with it.
.then(r => { setMeta(r); setRows(x => (before ? x.concat(r.events || []) : (r.events || []))) })
.catch(e => toast(e.message))
const pick = c => { setCat(c); setRows([]); setMeta(null); load(c) }
const pick = c => { setCat(c); setRows([]); setMeta(null); setShown(AUDIT_PAGE); load(c) }
// Reloads on mount and whenever the header's ↻ bumps the tick. Deliberately not on the 15s
// poll that drives "training now": this is history, not presence.
useEffect(() => { load(cat) }, [tick])
// poll that drives "training now": this is history, not presence. A reload starts folded again,
// which is the point of folding it.
useEffect(() => { setShown(AUDIT_PAGE); load(cat) }, [tick])
const hidden = rows.length - shown
const more = () => {
setShown(n => n + AUDIT_PAGE)
// Everything already fetched is on screen: the next ten come from the server.
if (hidden <= 0 && meta?.nextBefore) load(cat, meta.nextBefore)
}
const clear = () => confirmSheet({
title: 'Clear the activity log?',
@@ -194,7 +213,7 @@ function AuditCard({ tick }) {
{[['', 'All'], ['auth', 'Sign-ins'], ['admin', 'Admin'], ['fail', 'Failed']].map(([v, l]) =>
<button key={v} className={'chip' + (cat === v ? ' on' : '')} onClick={() => pick(v)}>{l}</button>)}
</div>
{rows.map(e => {
{rows.slice(0, shown).map(e => {
const line = auditLine(e)
return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: 'var(--hair) solid var(--sep)' }}>
<div className="grow">
@@ -208,8 +227,10 @@ function AuditCard({ tick }) {
</div>
})}
{meta && !rows.length && <div className="adm-empty">Nothing logged yet.</div>}
{meta?.nextBefore && <div style={{ marginTop: 10 }}>
<Button size="sm" onClick={() => load(cat, meta.nextBefore)}>Show more</Button></div>}
{(hidden > 0 || meta?.nextBefore) && <div className="row" style={{ marginTop: 10, gap: 10, alignItems: 'center' }}>
<Button size="sm" onClick={more}>Show more</Button>
{meta && <span className="small muted">{fmtNum(Math.min(shown, rows.length))} of {fmtNum(meta.total)}</span>}
</div>}
</div>
}
+68 -1
View File
@@ -9,9 +9,10 @@ import Admin from './Admin.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const mocks = vi.hoisted(() => ({ answers: {}, sheets: [] }))
const mocks = vi.hoisted(() => ({ answers: {}, sheets: [], calls: [] }))
vi.mock('../lib/api.js', () => ({
api: path => {
mocks.calls.push(path)
const key = path.split('?')[0]
return key in mocks.answers ? Promise.resolve(mocks.answers[key]) : Promise.reject(new Error('not found'))
}
@@ -48,6 +49,7 @@ const good = { id: 'w1', name: 'Push day', d: '2026-09-10', start: 1000, end: 61
beforeEach(() => {
document.body.innerHTML = ''
mocks.sheets.length = 0
mocks.calls.length = 0
mocks.answers = {
'/api/admin/users': { users: [{ id: 'u1', name: 'Mallory', workouts: 2, lastSync: null, disabled: false }], invite_only: false },
'/api/admin/invites': { invites: [] },
@@ -63,6 +65,71 @@ beforeEach(() => {
})
afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
/* The activity log is history, and history grows: one line per sign-in, per failed attempt, per
admin action. Reported as a wall of twenty-five rows pushing the rest of the dashboard off the
screen. It opens folded to the newest ten with the total in the lead line, and one button reveals
the rest — from what is already loaded first, and from the server once that runs out. */
describe('the activity log', () => {
const withLog = (n, extra = {}) => {
mocks.answers['/api/admin/audit'] = {
events: Array.from({ length: n }, (_, i) => ({ id: n - i, ts: Date.now() - i * 60000, ev: 'auth.login.ok', uid: 'u1', name: 'Daniel', ok: true })),
total: n, nextBefore: null, enabled: true, ip_mode: 'off', retention: { days: 90, max: 5000 }, now: Date.now(), ...extra
}
}
const auditCard = page => [...page.querySelectorAll('.card')].find(c => c.textContent.includes('Activity log'))
const auditRows = card => [...card.querySelectorAll('.row.between')].filter(r => r.querySelector('.small.muted'))
const showMore = card => [...card.querySelectorAll('button')].find(b => b.textContent.trim() === 'Show more')
it('opens with the newest ten and reveals the rest on demand', async () => {
withLog(25)
const page = render(<Admin />)
await settle()
const card = auditCard(page)
expect(auditRows(card).length).toBe(10);
expect(card.textContent).toContain('25 events')
expect(card.textContent).toContain('10 of 25')
act(() => showMore(card).click())
await settle()
expect(auditRows(card).length).toBe(20)
expect(card.textContent).toContain('20 of 25')
act(() => showMore(card).click())
await settle()
expect(auditRows(card).length).toBe(25)
// Everything is on screen and nothing is left on the server: the button goes away rather than
// sitting there inviting a click that does nothing.
expect(showMore(card)).toBeFalsy()
})
it('asks the server for the next page once what it has is shown', async () => {
// A page of fifty with more behind it: revealing past the fifty asks for the next page rather
// than sitting on a button that does nothing.
withLog(50, { total: 80, nextBefore: 3 })
const page = render(<Admin />)
await settle()
const card = auditCard(page)
// Four clicks reveal the fifty that were already loaded — and none of them asks the server.
for (let i = 0; i < 4; i++) { act(() => showMore(card).click()); await settle() }
expect(auditRows(card).length).toBe(50)
expect(mocks.calls.some(c => c.includes('before=3'))).toBe(false, 'a page already here is not re-fetched')
expect(showMore(card)).toBeTruthy()
// The fifth has nothing left to reveal, so it goes and gets the next page.
act(() => showMore(card).click())
await settle()
expect(mocks.calls.some(c => c.includes('before=3'))).toBe(true, 'and then it fetches');
})
it('says nothing to show on an empty log, and no button', async () => {
withLog(0)
const page = render(<Admin />)
await settle()
const card = auditCard(page)
expect(card.textContent).toContain('Nothing logged yet.')
expect(showMore(card)).toBeFalsy()
})
})
describe('Admin user drill-down', () => {
it('opens a profile with malformed workout entries and still offers "Disable account"', async () => {
const page = render(<Admin />)