Salud: un número por lugar, y la barra no se corrige a mitad del gesto
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

Dos reportes, y eran dos cosas distintas.

**"Veo todos los valores duplicados".** La hoja de una métrica mostraba el mismo número tres veces:
el titular, la lista de horas y el recibo que agregué en el commit anterior — que repetía la suma, el
valor más nuevo y los últimos tres valores *además* de las horas, que son esos mismos números. El
recibo existe para responder "por qué el número no coincide con la app Salud", y para eso alcanza con
la forma de lo que llegó (cuántos datos, cómo vienen marcados, de qué fuentes); los valores ya están
en la lista de horas. Así que ahora:

  · el titular es el día, y nada más lo repite;
  · la lista de horas son sus valores, y el recibo se queda solo con la forma **cuando hay horas**;
  · "Día por día" empieza en ayer (hoy ya es el titular, en el tamaño que merece un titular);
  · la lista de campos solo aparece cuando aporta algo — varios campos (Min/Avg/Max del pulso, las
    fases del sueño) o una métrica que el catálogo no conoce — en vez de repetir el `qty` de arriba.

Un número, un lugar. El test lo comprueba contando: la lista de días no contiene el valor de hoy, y
el recibo con horas no trae valores.

**"Cuando bajo para ver las demás tarjetas se desplaza hacia arriba el menú".** Esto es el bug que
`lib/viewport-guard.js` ya documenta: en iOS el viewport visual se despega del de layout y todo lo
`position:fixed` — la barra de tabs, el temporizador — queda donde termina el layout viewport, o sea
a media pantalla. La corrección del módulo es un `scrollTo`, y la hacía en **cada** evento de scroll
del viewport visual. Durante un gesto `offsetTop` se mueve con el rebote del final de la página y con
la barra de Safari que se colapsa, así que corregir ahí vuelve a scrollear la página bajo el dedo
varias veces por segundo: lo que se ve es la barra deslizándose hacia arriba mientras uno scrollea,
en la pantalla más larga de la app. Ahora la corrección espera a que el scroll se detenga — una sola
vez, y un scroll que sigue reiniciando la espera. La corrección por teclado, que es para lo que se
escribió el módulo, no cambia.

Mutation-check del debounce: corrigiendo por evento otra vez, el test nuevo falla.
This commit is contained in:
dsantillan committed 2026-09-23 18:18:29 -04:00
1 parent 4ba9e29d1e
commit 309aba8766
6 files changed
+114 -16

No files matched your search

+17 -1
View File
@@ -16,6 +16,15 @@
*/
const KEYBOARD_MIN_PX = 100
const SETTLE_MS = 350 // the keyboard's dismiss animation; the offset is only wrong after it
/* How long after the last visual-viewport scroll the correction may run.
*
* Not zero, and that is the point. `offsetTop` moves *while the finger moves* — the rubber band at
* the end of a page, and the browser chrome collapsing on the way down — so correcting on every
* scroll event re-scrolls the page under the gesture several times a second. Everything
* `position:fixed` is painted against the layout viewport, so what a person sees is the tab bar
* sliding upward while they scroll. A correction is only needed once the scroll has stopped, and
* by then it either is or is not necessary. */
const SCROLL_SETTLE_MS = 180
const isText = el => !!el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable)
@@ -75,6 +84,7 @@ export function installViewportGuard(win = window) {
const vv = win.visualViewport
if (!vv) return () => {}
let wasOpen = keyboardOpen(win)
let scrollTimer = null
const timers = new Set()
const later = (fn, ms) => { const t = win.setTimeout(() => { timers.delete(t); fn() }, ms); timers.add(t) }
const settle = () => { realign(win); later(() => realign(win), SETTLE_MS) }
@@ -84,7 +94,12 @@ export function installViewportGuard(win = window) {
if (wasOpen && !open) settle()
wasOpen = open
}
const onScroll = () => { if (!wasOpen) realign(win) }
const onScroll = () => {
if (wasOpen) return
// One pending correction, always the latest: a scroll that keeps going keeps resetting it.
if (scrollTimer) win.clearTimeout(scrollTimer)
scrollTimer = win.setTimeout(() => { scrollTimer = null; realign(win) }, SCROLL_SETTLE_MS)
}
const onFocusOut = e => { if (isText(e.target)) settle() }
vv.addEventListener('resize', onResize)
@@ -94,6 +109,7 @@ export function installViewportGuard(win = window) {
vv.removeEventListener('resize', onResize)
vv.removeEventListener('scroll', onScroll)
win.document.removeEventListener('focusout', onFocusOut)
if (scrollTimer) win.clearTimeout(scrollTimer)
timers.forEach(t => win.clearTimeout(t))
}
}
+22
View File
@@ -103,6 +103,28 @@ describe('viewport guard', () => {
vi.useRealTimers()
})
/* The correction is a `scrollTo`, and during a gesture it is what makes the tab bar look like it
slides: `offsetTop` moves with the rubber band and with the browser chrome collapsing, so a
correction on every event re-scrolls the page under the finger several times a second. It waits
for the scroll to stop instead — and a scroll that keeps going keeps resetting the wait. */
it('corrects once, after a scroll settles — never mid-gesture', () => {
vi.useFakeTimers()
try {
const w = fakeWindow({ offsetTop: 190 })
installViewportGuard(w)
// A finger dragging: ten events, and nothing happens while it moves.
for (let i = 0; i < 10; i++) { w.fire(w.visualViewport, 'scroll'); vi.advanceTimersByTime(40) }
expect(w.scrollTo).not.toHaveBeenCalled()
// The scroll stops: one correction, not ten.
vi.advanceTimersByTime(200)
expect(w.scrollTo).toHaveBeenCalledTimes(1)
expect(w.scrollTo).toHaveBeenCalledWith(0, 0)
// ...and a settled scroll that needs no correction still asks for nothing.
vi.advanceTimersByTime(200)
expect(w.scrollTo).toHaveBeenCalledTimes(1)
} finally { vi.useRealTimers() }
})
it('does nothing while the keyboard is open, and nothing at all without a visualViewport', () => {
const w = fakeWindow({ vvHeight: 480, offsetTop: 190 })
installViewportGuard(w)
+19 -9
View File
@@ -390,19 +390,25 @@ const STAMP_LABEL = { day: 'one total a day', hour: 'one total an hour', sample:
export const stampLabel = kind => (STAMP_LABEL[kind] ? t(STAMP_LABEL[kind]) : String(kind || ''))
/** The receipt as rows: how it was stamped, where it came from, what it adds up to. */
export function receiptRows(shape) {
export function receiptRows(shape, { withValues = true } = {}) {
if (!shape || !shape.points) return []
const rows = [
{ key: 'points', label: t('Datapoints in the last sync'), value: fmtValue(shape.points) },
{ key: 'stamps', label: t('How they were stamped'), value: stampLabel(shape.stamps) },
{ key: 'sources', label: t('Sources'), value: (shape.sources || []).join(', ') || t('not reported') }
]
if (shape.sum != null && shape.field) rows.push({ key: 'sum', label: t('{0} adds up to', shape.field), value: fmtValue(shape.sum, 0) })
if (shape.newest) rows.push({ key: 'newest', label: t('Newest value'), value: fmtValue(shape.newest.value, 0) })
// The three newest values, oldest first: a run of rising numbers is the tell that they are running
// totals rather than one hour each, and it is the difference between 499 and 840.
if (Array.isArray(shape.tail) && shape.tail.length > 1) {
rows.push({ key: 'tail', label: t('Latest values, oldest first'), value: shape.tail.map(([, v]) => fmtValue(v, 0)).join(' → ') })
/* The numbers, only when the sheet is not already showing them. With hours behind the day, the
hour list below is those very values — a receipt that repeats them makes the sheet look like it
is counting everything twice, which is precisely the impression this section exists to rule
out. `withValues: false` keeps the shape and drops the numbers. */
if (withValues) {
if (shape.sum != null && shape.field) rows.push({ key: 'sum', label: t('{0} adds up to', shape.field), value: fmtValue(shape.sum, 0) })
if (shape.newest) rows.push({ key: 'newest', label: t('Newest value'), value: fmtValue(shape.newest.value, 0) })
// The three newest values, oldest first: a run of rising numbers is the tell that they are
// running totals rather than one hour each — the difference between 499 and 840.
if (Array.isArray(shape.tail) && shape.tail.length > 1) {
rows.push({ key: 'tail', label: t('Latest values, oldest first'), value: shape.tail.map(([, v]) => fmtValue(v, 0)).join(' → ') })
}
}
return rows
}
@@ -461,9 +467,13 @@ export function hourChartPoints(day, rows) {
* The chart shows a shape; this shows the numbers the shape is made of, which is the difference
* between "it went up" and "it went up on Tuesday". `hours` rides along so a row can say whether
* that day can be opened hour by hour.
*
* `skip` leaves a day out, and exists for one caller: the sheet already shows today's number at the
* top, in the size a headline deserves, so repeating it as the first row of the list is the same
* number twice on one screen.
*/
export function historyRows(card, { limit = 14 } = {}) {
const series = (card && card.series) || []
export function historyRows(card, { limit = 14, skip = null } = {}) {
const series = ((card && card.series) || []).filter(p => !skip || p.day !== skip)
return series.slice(-limit).reverse().map(p => ({
key: p.day,
day: p.day,
+6
View File
@@ -343,6 +343,9 @@ describe('days, units and captions', () => {
expect(rows[0].label).toBeTruthy()
// A limit keeps the sheet short on a metric with a year of history: the newest days win.
expect(historyRows(c, { limit: 2 }).map(r => r.day)).toEqual(['2026-05-03', '2026-05-02'])
// `skip` leaves out the day the sheet already shows at the top as a headline: the same number
// twice on one screen is what a person reads as a bug.
expect(historyRows(c, { skip: '2026-05-03' }).map(r => r.day)).toEqual(['2026-05-02', '2026-05-01'])
expect(historyRows({ series: [] })).toEqual([])
})
@@ -370,6 +373,9 @@ describe('days, units and captions', () => {
expect(get('newest')).toBe('499')
// A run of rising numbers is the tell that they are running totals, not one hour each.
expect(get('tail')).toBe('340 → 420 → 499')
// With hours on the screen the numbers live there, so the receipt is only the shape.
const shapeOnly = receiptRows({ points: 720, stamps: 'hour', sources: ['Apple Watch'], sum: 840, newest: { value: 499 }, tail: [[1, 340], [2, 499]] }, { withValues: false })
expect(shapeOnly.map(r => r.key)).toEqual(['points', 'stamps', 'sources'])
expect(receiptRows(null)).toEqual([])
expect(receiptRows({ points: 0 })).toEqual([])
// Nothing reported is said as nothing, not as an empty join.
+10 -5
View File
@@ -226,10 +226,15 @@ function MetricSheet({ card, metric, close, onReset }) {
return () => { live = false }
}, [card.name, day, dayHours])
const receipt = receiptRows(metric && metric.shape)
const conflict = dayConflict(metric && metric.days ? metric.days.find(d => d.day === card.day) : null)
const hourList = hourRows(hours, card)
const history = historyRows(card)
/* Each number appears once on this sheet, and the sections are cut to keep it that way:
the hours are the day's values, so the receipt stops repeating them; today's number is the
headline, so the day list starts at yesterday; a single field is that headline, so the field
list is only worth a section when there is more than one (heart rate's Min/Avg/Max, sleep's
stages, an unknown metric's whatever-it-sent). */
const receipt = receiptRows(metric && metric.shape, { withValues: hourList.length === 0 })
const conflict = dayConflict(metric && metric.days ? metric.days.find(d => d.day === card.day) : null)
const history = historyRows(card, { skip: card.day })
const val = r => fmtValue(r.value, card.dec) + (unitLabel(card.unit) ? ' ' + unitLabel(card.unit) : '')
return <>
@@ -267,7 +272,7 @@ function MetricSheet({ card, metric, close, onReset }) {
: t('This day\'s hours add up to {0} but the day shows {1}, which means the phone sent a total for the day as well as its hours.', fmtValue(conflict.sum, card.dec), fmtValue(conflict.shown, card.dec))}
</div>}
{history.length > 1 && <>
{history.length > 0 && <>
<h4 className="sec">{t('Day by day')}</h4>
<div className="list">
{history.map(r => <Row key={r.key} title={r.label}
@@ -278,7 +283,7 @@ function MetricSheet({ card, metric, close, onReset }) {
</div>
</>}
{rows.length > 0 && <>
{(rows.length > 1 || card.unknown) && <>
<h4 className="sec">{t('What the watch sent')}</h4>
<div className="list">{rows.map(r => <Row key={r.key} title={r.label}
subtitle={r.n > 1 ? t('{0} samples', r.n) : null}
+40 -1
View File
@@ -444,12 +444,51 @@ describe('the detail sheet', () => {
expect(text).toContain('What arrived last')
expect(text).toContain('one total an hour')
expect(text).toContain('Apple Watch, iPhone')
expect(text).toContain('340 → 420 → 499')
/* The numbers are shown once, in the section that owns them. The hours are listed below, so the
receipt stops at the shape of what arrived: had it repeated the values too, the sheet would
read as if everything had been counted twice — the exact impression this section exists to
rule out. */
expect(text).not.toContain('340 → 420 → 499')
expect(text).not.toContain('adds up to')
// Today's number is the headline; the day list starts at yesterday, so it is not repeated as a
// row either.
const heading = [...sheetEl().querySelectorAll('h4.sec')].find(h => h.textContent.includes('Day by day'))
const dayList = heading.nextElementSibling.textContent
expect(dayList).toContain('11,000')
expect(dayList).not.toContain('12,481')
// The day keeps the phone's total, and the sheet says why the two numbers differ instead of
// leaving whoever noticed to guess.
expect(text).toContain('The phone declared 499 for this day, and its hours add up to 340')
})
it('shows the values in the receipt when there are no hours to show them in', async () => {
const withShape = () => ({
...VITALS,
metrics: {
step_count: {
units: 'count', sources: ['Apple Watch'],
shape: {
at: Date.now(), points: 720, field: 'qty', stamps: 'hour', sources: ['Apple Watch'],
sum: 840, newest: { stamp: '2026-09-23 14:00:00 +0000', value: 499, ms: 1 },
head: [], tail: [['2026-09-23 12:00:00 +0000', 340], ['2026-09-23 13:00:00 +0000', 420], ['2026-09-23 14:00:00 +0000', 499]]
},
// Days grouping: one total a day, so there are no hourly rows to carry these values.
days: [{ day: '2026-09-03', n: 1, f: { qty: bucket(499) }, lastTs: Date.now() }]
}
}
})
// The hours request answers with nothing: the card says the day has no hours behind it.
route(withShape(), { ok: true, metric: 'step_count', day: '2026-09-03', hours: [] })
await mountWithSheets()
openSteps()
await act(async () => {})
const text = sheet()
expect(text).toContain('adds up to')
expect(text).toContain('340 → 420 → 499')
expect(text).not.toContain('Hour by hour')
})
it('says the automation groups by day instead of drawing an empty hour list', async () => {
route(VITALS, HOURS)
await mountWithSheets()