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
improvements for qr code check-in feature
Sebastian G0ef72ae6194a
diff --git a/frontend/src/index.css b/frontend/src/index.cssindex a66b8f414..140da1b24 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -1160,9 +1160,18 @@ h4.sec{scroll-snap-align:center;flex:0 0 100%;box-sizing:border-box;background:var(--surface);border-radius:var(--r-xl);padding:22px 18px;display:flex;flex-direction:column;align-items:center;gap:14px;+ transition:transform var(--fast),box-shadow var(--fast),opacity var(--fast);}-.ci-card .ci-label{font-size:19px;font-weight:600;letter-spacing:-.014em;text-align:center}+/* header row: edit — title — trash. The two icon buttons are equal fixed widths so the title,+ flexed between them, stays optically centered on the card no matter how long it is. */+.ci-card-hd{display:flex;align-items:center;gap:8px;width:100%}+.ci-card-btn{width:30px;height:30px;font-size:14px;flex:none}+.ci-card .ci-label{flex:1;min-width:0;font-size:19px;font-weight:600;letter-spacing:-.014em;text-align:center;overflow-wrap:anywhere}.ci-card .ci-value{font-size:14px;color:var(--label-2);word-break:break-all;text-align:center;font-variant-numeric:tabular-nums}+/* long-press reorder: the lifted card floats above the rest, which dim slightly to recede. */+.ci-rail.is-reordering{scroll-snap-type:none}+.ci-rail.is-reordering .ci-card:not(.is-dragging){opacity:.6}+.ci-card.is-dragging{transform:scale(1.03);box-shadow:0 12px 30px -8px rgba(0,0,0,.4);z-index:2}/* The QR itself: lean-qr paints 1 module per pixel, so scale it up with the browser'snearest-neighbour so every module stays a crisp square instead of a blurred blob. Whitequiet-zone padding is baked in by the renderer; the plate underneath just frames it. */diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 5b0e2ff54..92b60cf97 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1158,6 +1158,13 @@ export default {'Membership number or code': 'Mitgliedsnummer oder Code','Save card': 'Karte speichern','Gym card': 'Studio-Karte',+ 'Edit card': 'Karte bearbeiten',+ 'Re-scan': 'Neu scannen',+ 'Scan it with the camera or import a photo.': 'Scanne sie mit der Kamera oder importiere ein Foto.',+ 'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Importiere ein Foto deiner Mitgliedskarte oder scanne sie mit der Kamera. Keine zusätzliche App im Studio nötig — öffne einfach diesen Bildschirm.',+ 'Long-press a card to reorder': 'Karte gedrückt halten, um sie umzusortieren',+ 'Card updated': 'Karte aktualisiert',+ 'Scan or import a code first': 'Zuerst einen Code scannen oder importieren','Card added': 'Karte hinzugefügt','Nothing to save yet': 'Noch nichts zu speichern',"That's not a QR code — only QR cards can be shown here": 'Das ist kein QR-Code — hier lassen sich nur QR-Karten anzeigen',diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 33dd4a7ee..c2c76868c 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -55,6 +55,10 @@ export const DEF = {// kind of code the gym issued. Just data, so it syncs and backs up like everything else.// [{ id, label, value, fmt }]gymCards: [],+ // The card the check-in screen last settled on, so it reopens where you left it (handy when+ // you have more than one gym). Holds a gymCards id, or null before any card exists / is chosen;+ // a stale id (card since removed) is simply ignored by the view.+ lastGymCardId: null,// Whether the check-in feature is on at all (Settings toggle). Off hides the Home// card and the /checkin route; the saved gymCards stay so turning it back on restores them.// Defaults on; an older profile without the key reads as on (`!== false`).diff --git a/frontend/src/views/CheckIn.jsx b/frontend/src/views/CheckIn.jsxindex e40d01ed5..6fb60f32d 100644--- a/frontend/src/views/CheckIn.jsx+++ b/frontend/src/views/CheckIn.jsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from 'react'+import { useEffect, useLayoutEffect, useRef, useState } from 'react'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'@@ -12,25 +12,54 @@ import QrCanvas from '../components/QrCanvas.jsx'import CameraScan from '../components/CameraScan.jsx'import { Button, TextField } from '../components/ui.jsx'import { confirmSheet } from '../sheets.jsx'-import { tappable } from '../lib/use-sheet-keyboard.js'-// Gym check-in (reached from the Home "Check in" card; app and PWA alike). Shows each saved membership-// code as a QR the turnstile can read, swiped through horizontally, with a trailing "+" to add-// another. We only ever store the code's value + symbology; the QR is regenerated from it here-// every time (see lib/qr.js), so nothing sensitive is kept as an image.+// Long-press before a card lifts for reordering, and the finger travel that instead counts as a+// horizontal swipe of the rail. Mirrors the routine-editor drag (views/RoutineEdit.jsx) so the+// gesture feels the same across the app.+const CI_LONG_PRESS_MS = 380+const CI_DRAG_SLOP = 8++// Gym check-in (reached from the Home "Check in" card; app and PWA alike). Shows each saved+// membership code as a QR the turnstile can read, swiped through horizontally, with a trailing+// "+" to add another. We only ever store the code's value + symbology; the QR is regenerated from+// it here every time (see lib/qr.js), so nothing sensitive is kept as an image.+//+// The rail reopens on the card you used last (lastGymCardId) and remembers the one you settle on,+// so a member with two gyms lands on the right code without swiping. Cards are added by scanning+// or importing a photo only — never by typing a code, which is too easy to fat-finger into a+// code that silently fails at the turnstile. An existing card can be edited (rename, re-scan) and+// the whole rail can be reordered with a long-press drag.export default function CheckIn() {const nav = useNavigate()const cards = useStore(s => s.S.gymCards) || []+ const lastId = useStore(s => s.S.lastGymCardId)+ const update = useStore(s => s.update)const railRef = useRef(null)const [active, setActive] = useState(0)+ const reorder = useRailReorder(railRef, cards)++ // Open on the last-used card. Done once on mount (and whenever the saved id changes from+ // elsewhere) with layout effect so the jump happens before paint — no visible scroll from 0.+ // A stale id (its card was removed) falls back to the first card.+ useLayoutEffect(() => {+ const rail = railRef.current+ if (!rail || !cards.length) return+ const idx = Math.max(0, cards.findIndex(c => c.id === lastId))+ rail.scrollLeft = idx * rail.clientWidth+ setActive(idx)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [lastId, cards.length])- // Which card the horizontal scroll has settled on — drives the little dots. Reading it off the- // scroll position keeps the rail itself the single control; no separate paging state to sync.+ // Which card the horizontal scroll has settled on — drives the dots and gets remembered as the+ // last-used card. Reading it off the scroll position keeps the rail itself the single control.const onScroll = () => {const rail = railRef.currentif (!rail) returnconst i = Math.round(rail.scrollLeft / rail.clientWidth)+ if (i === active) returnsetActive(i)+ const card = cards[i]+ if (card && card.id !== lastId) update(s => { s.lastGymCardId = card.id }, false)}return <div className="narrow">@@ -42,9 +71,13 @@ export default function CheckIn() {</div></div>- <div className="ci-rail" ref={railRef} onScroll={onScroll}>- {cards.map(card => <CardFace key={card.id} card={card} />)}- <button className="ci-add" onClick={openAddCard}>+ <div className={'ci-rail' + (reorder.dragging ? ' is-reordering' : '')} ref={railRef} onScroll={onScroll}>+ {cards.map(card => <CardFace+ key={card.id}+ card={card}+ dragging={reorder.dragId === card.id}+ />)}+ <button className="ci-add" onClick={openAddCard} data-nodrag><Icon name="plus" /><span className="ci-add-t">{t('Add a card')}</span></button>@@ -56,75 +89,200 @@ export default function CheckIn() {<span className={'ci-dot' + (active >= cards.length ? ' on' : '')} /></div>}+ {cards.length > 1 && <div className="muted small" style={{ textAlign: 'center', marginTop: 10 }}>+ {t('Long-press a card to reorder')}+ </div>}+{!cards.length && <div className="muted small" style={{ textAlign: 'center', marginTop: 18, lineHeight: 1.5 }}>- {t('Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.')}+ {t('Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.')}</div>}</div>}-// One saved card: its label, the QR, and the raw value underneath (handy when a reader is fussy-// and a staff member types it in). Long-press / the trash button removes it.-function CardFace({ card }) {+// One saved card: its label centered above the QR, and the raw value underneath (handy when a+// reader is fussy and a staff member types it in). The edit button opens the same sheet used to+// add a card, pre-filled; the trash button removes it after a confirm.+function CardFace({ card, dragging }) {const update = useStore(s => s.update)const remove = () => confirmSheet({title: t('Remove this card?'),message: card.label,confirmText: t('Remove'),danger: true,- onConfirm: () => update(s => { s.gymCards = (s.gymCards || []).filter(c => c.id !== card.id) }),+ onConfirm: () => update(s => {+ s.gymCards = (s.gymCards || []).filter(c => c.id !== card.id)+ if (s.lastGymCardId === card.id) s.lastGymCardId = (s.gymCards[0]?.id) || null+ }),})- return <div className="ci-card">- <div className="row between" style={{ width: '100%', alignItems: 'flex-start' }}>- <div className="ci-label" style={{ flex: 1 }}>{card.label}</div>- <button className="iconbtn" style={{ width: 30, height: 30, fontSize: 14, color: 'var(--red)' }} onClick={remove} aria-label={t('Remove')}><Icon name="trash" /></button>+ return <div className={'ci-card' + (dragging ? ' is-dragging' : '')} data-ci-card data-ci-id={card.id}>+ <div className="ci-card-hd">+ <button className="iconbtn ci-card-btn" onClick={() => openEditCard(card)} aria-label={t('Edit')} data-nodrag><Icon name="pencil" /></button>+ <div className="ci-label">{card.label}</div>+ <button className="iconbtn ci-card-btn" style={{ color: 'var(--red)' }} onClick={remove} aria-label={t('Remove')} data-nodrag><Icon name="trash" /></button></div><div className="ci-qr-plate"><QrCanvas value={card.value} size={230} /></div><div className="ci-value">{card.value}</div></div>}-/* ------------------------------------------------------------- add-card sheet -- */+/* ------------------------------------------------------- long-press reorder -- */++// Horizontal drag-to-reorder for the rail. A long-press lifts the card under the finger; moving+// then drops it before whichever card its centre passes. Kept self-contained (not the routine+// editor's vertical hook) because the rail is a scroll-snap track, not a stacked list — the+// gesture maths is horizontal and the scroll container is the element itself.+//+// Returns { dragging, dragId } for styling; the reorder itself is committed to the store on drop.+function useRailReorder(railRef, cards) {+ const [state, setState] = useState({ dragging: false, dragId: null })+ const cardsRef = useRef(cards)+ cardsRef.current = cards++ useEffect(() => {+ const rail = railRef.current+ if (!rail) return undefined+ let gesture = null++ const clearTimer = () => { if (gesture?.timer) { clearTimeout(gesture.timer); gesture.timer = null } }++ const lift = g => {+ g.active = true+ setState({ dragging: true, dragId: g.id })+ }++ // Drop before the card whose horizontal centre the pointer has passed, then persist the new+ // order. A no-op move (dropped in place) still clears state but writes nothing.+ const drop = g => {+ const list = cardsRef.current+ const from = list.findIndex(c => c.id === g.id)+ if (from >= 0) {+ const cardEls = [...rail.querySelectorAll('[data-ci-card]')]+ const centres = cardEls.map(el => { const r = el.getBoundingClientRect(); return r.left + r.width / 2 })+ let to = centres.reduce((n, cx, i) => n + (i !== from && g.lastX > cx ? 1 : 0), 0)+ to = Math.min(to, list.length - 1)+ if (to !== from) {+ useStore.getState().update(s => {+ const arr = s.gymCards+ const [moved] = arr.splice(from, 1)+ arr.splice(to, 0, moved)+ })+ }+ }+ setState({ dragging: false, dragId: null })+ }++ const onPointerDown = event => {+ if (event.isPrimary === false || (event.pointerType === 'mouse' && event.button !== 0)) return+ const target = event.target+ if (!target?.closest || target.closest('button,a,input,textarea,select,[data-nodrag]')) return+ const cardEl = target.closest('[data-ci-card]')+ if (!cardEl || !rail.contains(cardEl)) return+ gesture = { id: cardEl.dataset.ciId, pointerId: event.pointerId, startX: event.clientX, lastX: event.clientX, active: false, timer: null }+ gesture.timer = window.setTimeout(() => lift(gesture), CI_LONG_PRESS_MS)+ }++ const onPointerMove = event => {+ if (!gesture || event.pointerId !== gesture.pointerId) return+ gesture.lastX = event.clientX+ if (!gesture.active) {+ // Moved before the long-press fired — it's a swipe of the rail, not a reorder. Bail so the+ // native scroll-snap takes over.+ if (Math.abs(event.clientX - gesture.startX) > CI_DRAG_SLOP) { clearTimer(); gesture = null }+ return+ }+ event.preventDefault()+ }++ const onPointerUp = event => {+ if (!gesture || event.pointerId !== gesture.pointerId) return+ clearTimer()+ if (gesture.active) drop(gesture)+ gesture = null+ }++ const cancel = () => { if (gesture) { clearTimer(); if (gesture.active) setState({ dragging: false, dragId: null }); gesture = null } }++ // Once a drag is active the rail must not also pan-scroll; a non-passive touchmove is the only+ // thing that can stop the browser claiming the gesture as a horizontal pan.+ const onTouchMove = event => { if (gesture?.active) event.preventDefault() }++ document.addEventListener('pointerdown', onPointerDown)+ document.addEventListener('pointermove', onPointerMove, { passive: false })+ document.addEventListener('pointerup', onPointerUp)+ document.addEventListener('pointercancel', cancel)+ rail.addEventListener('touchmove', onTouchMove, { passive: false })+ window.addEventListener('blur', cancel)+ return () => {+ cancel()+ document.removeEventListener('pointerdown', onPointerDown)+ document.removeEventListener('pointermove', onPointerMove)+ document.removeEventListener('pointerup', onPointerUp)+ document.removeEventListener('pointercancel', cancel)+ rail.removeEventListener('touchmove', onTouchMove)+ window.removeEventListener('blur', cancel)+ }+ }, [railRef])++ return state+}++/* ------------------------------------------------------------- add/edit sheet -- */// Opens the add-card sheet. Co-located with the view (not sheets.jsx) because it pulls in the// scanner paths — keeping it here keeps them out of the shared sheets module.export function openAddCard() {- useUI.getState().openSheet(close => <AddCard close={close} />)+ useUI.getState().openSheet(close => <CardSheet close={close} />)}-function saveCard({ label, value, fmt }) {- const update = useStore.getState().update- const toast = useUI.getState().toast- const trimmed = (value || '').trim()- if (!trimmed) { toast(t('Nothing to save yet')); return false }- // We can read many barcode kinds but only redraw QR faithfully — refuse anything else rather- // than store a code that would display as the wrong bars at the turnstile.- if (fmt && !canRenderFmt(fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return false }- update(s => {- if (!Array.isArray(s.gymCards)) s.gymCards = []- s.gymCards.push({ id: uid(), label: (label || '').trim() || t('Gym card'), value: trimmed, fmt: 'qrcode' })- })- toast(t('Card added'))- return true+// Opens the same sheet on an existing card to rename it or re-scan its code.+export function openEditCard(card) {+ useUI.getState().openSheet(close => <CardSheet close={close} card={card} />)}-function AddCard({ close }) {- const [label, setLabel] = useState('')- const [value, setValue] = useState('')+// Shared sheet for adding and editing a card. Without `card` it creates a new one; with `card` it+// updates that entry in place. The code always comes from a scan or a photo — there is no text+// field for it — so an edit that only renames keeps the existing scanned code untouched.+function CardSheet({ close, card }) {+ const editing = !!card+ const [label, setLabel] = useState(card?.label || '')+ const [value, setValue] = useState(card?.value || '')const [busy, setBusy] = useState(false)const fileRef = useRef(null)const toast = useUI(s => s.toast)- const commitTyped = () => { if (saveCard({ label, value, fmt: 'qrcode' })) close() }+ const commit = () => {+ const trimmed = value.trim()+ if (!trimmed) { toast(t('Scan or import a code first')); return }+ const update = useStore.getState().update+ if (editing) {+ update(s => {+ const c = (s.gymCards || []).find(x => x.id === card.id)+ if (!c) return+ c.label = label.trim() || t('Gym card')+ c.value = trimmed+ })+ toast(t('Card updated'))+ } else {+ update(s => {+ if (!Array.isArray(s.gymCards)) s.gymCards = []+ const id = uid()+ s.gymCards.push({ id, label: label.trim() || t('Gym card'), value: trimmed, fmt: 'qrcode' })+ s.lastGymCardId = id+ })+ toast(t('Card added'))+ }+ close()+ }// Camera scan: in the app, hands off to the native scanner; in a browser, opens our own camera// sheet on top of this one. Either way the value drops straight into the form so the user can// still name it before saving.const doScan = async () => {if (!MOBILE) {- useUI.getState().openSheet(close => <CameraScan- onCancel={close}+ useUI.getState().openSheet(closeCam => <CameraScan+ onCancel={closeCam}onFound={code => {- close()+ closeCam()if (!canRenderFmt(code.fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return }setValue(code.value)}} />)@@ -157,23 +315,20 @@ function AddCard({ close }) {}return <>- <h3>{t('Add a card')}</h3>- <div className="muted small" style={{ marginBottom: 14 }}>{t('Scan it, import a photo, or type the code by hand.')}</div>+ <h3>{editing ? t('Edit card') : t('Add a card')}</h3>+ <div className="muted small" style={{ marginBottom: 14 }}>{t('Scan it with the camera or import a photo.')}</div><div className="row" style={{ gap: 8, marginBottom: 16 }}>- <Button variant="tinted" icon="camera" onClick={doScan} disabled={busy}>{t('Scan')}</Button>+ <Button variant="tinted" icon="camera" onClick={doScan} disabled={busy}>{editing ? t('Re-scan') : t('Scan')}</Button><Button variant="tinted" icon="image" onClick={() => fileRef.current?.click()} disabled={busy}>{t('Import photo')}</Button></div><label className="sect-t">{t('Label')}</label>- <TextField value={label} onChange={e => setLabel(e.target.value)} placeholder={t('e.g. FitZone downtown')} style={{ marginBottom: 12 }} />-- <label className="sect-t">{t('Code')}</label>- <TextField value={value} onChange={e => setValue(e.target.value)} placeholder={t('Membership number or code')} inputMode="text" style={{ marginBottom: 16 }} />+ <TextField value={label} onChange={e => setLabel(e.target.value)} placeholder={t('e.g. FitZone downtown')} style={{ marginBottom: 16 }} />{value.trim() && <div className="ci-qr-plate" style={{ alignSelf: 'center', marginBottom: 16 }}><QrCanvas value={value.trim()} size={150} /></div>}- <Button variant="primary" onClick={commitTyped} disabled={busy || !value.trim()}>{t('Save card')}</Button>+ <Button variant="primary" onClick={commit} disabled={busy || !value.trim()}>{editing ? t('Save card') : t('Save card')}</Button><input ref={fileRef} type="file" accept="image/*" hidden onChange={onFile} /></>