From 0ef72ae6194a00b7ef94a7f08951159515649d0d Mon Sep 17 00:00:00 2001 From: Sebastian G Date: Mon, 7 Sep 2026 10:16:24 +0200 Subject: [PATCH 1/4] improvements for qr code check-in feature - removed ability to manually enter code to be displayed as QR code. Codes can only be scanned via camera or imported from an image on the device - Cards can be edited once they are created. E.g. changing the description, re-scanning the code - You can change the order of code-cards via long-press - Last selected code-card will be shown when selecting "check in" on home screen - Optics: Correctly centered titles of code-cards --- frontend/src/index.css | 11 +- frontend/src/locales/de.js | 7 + frontend/src/store/useStore.js | 4 + frontend/src/views/CheckIn.jsx | 257 ++++++++++++++++++++++++++------- 4 files changed, 227 insertions(+), 52 deletions(-) diff --git a/frontend/src/index.css b/frontend/src/index.css index a66b8f4..140da1b 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's nearest-neighbour so every module stays a crisp square instead of a blurred blob. White quiet-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.js index 5b0e2ff..92b60cf 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.js index 33dd4a7..c2c7686 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.jsx index e40d01e..6fb60f3 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) - // 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. + // 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 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.current if (!rail) return const i = Math.round(rail.scrollLeft / rail.clientWidth) + if (i === active) return setActive(i) + const card = cards[i] + if (card && card.id !== lastId) update(s => { s.lastGymCardId = card.id }, false) } return
@@ -42,9 +71,13 @@ export default function CheckIn() {
-
- {cards.map(card => )} - @@ -56,75 +89,200 @@ export default function CheckIn() { = cards.length ? ' on' : '')} />
} + {cards.length > 1 &&
+ {t('Long-press a card to reorder')} +
} + {!cards.length &&
- {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.')}
} } -// 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
-
-
{card.label}
- + return
+
+ +
{card.label}
+
{card.value}
} -/* ------------------------------------------------------------- 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 => ) + useUI.getState().openSheet(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 => ) } -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 => { - 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 <> -

{t('Add a card')}

-
{t('Scan it, import a photo, or type the code by hand.')}
+

{editing ? t('Edit card') : t('Add a card')}

+
{t('Scan it with the camera or import a photo.')}
- +
- setLabel(e.target.value)} placeholder={t('e.g. FitZone downtown')} style={{ marginBottom: 12 }} /> - - - setValue(e.target.value)} placeholder={t('Membership number or code')} inputMode="text" style={{ marginBottom: 16 }} /> + setLabel(e.target.value)} placeholder={t('e.g. FitZone downtown')} style={{ marginBottom: 16 }} /> {value.trim() &&
} - + From b7a42778700ed4b022056dee17f1705c20e8cbd6 Mon Sep 17 00:00:00 2001 From: Sebastian G Date: Mon, 7 Sep 2026 10:24:06 +0200 Subject: [PATCH 2/4] added test for reordering qr.code-cards, last selected qr-code-card, edit card --- frontend/src/store/useStore.gymcards.test.jsx | 76 +++++++++++++++++++ frontend/src/views/CheckIn.jsx | 29 ++++--- frontend/src/views/CheckIn.reorder.test.jsx | 58 ++++++++++++++ 3 files changed, 152 insertions(+), 11 deletions(-) create mode 100644 frontend/src/views/CheckIn.reorder.test.jsx diff --git a/frontend/src/store/useStore.gymcards.test.jsx b/frontend/src/store/useStore.gymcards.test.jsx index d3fcab9..ab301c7 100644 --- a/frontend/src/store/useStore.gymcards.test.jsx +++ b/frontend/src/store/useStore.gymcards.test.jsx @@ -68,6 +68,82 @@ describe('gymCards state', () => { }) }) +// lastGymCardId remembers which card the check-in screen last settled on, so it reopens there. +// It is plain profile data on the same update()/persist() path; these pin the contracts the view +// relies on — a fresh default, add points it at the new card, edit-in-place touches only that +// card, and removing the remembered card falls back to the first survivor (or null when none). +describe('lastGymCardId', () => { + it('defaults to null on a fresh profile', () => { + expect(useStore.getState().S.lastGymCardId).toBeNull() + }) + + it('persists to localStorage like any other field', () => { + useStore.getState().update(s => { s.lastGymCardId = 'c9' }, false) + const saved = JSON.parse(localStorage.getItem('gym_state_v1')) + expect(saved.lastGymCardId).toBe('c9') + }) + + it('adding a card points lastGymCardId at the new card (view contract)', () => { + // Mirrors CardSheet's add branch: push a card and remember its id in one update. + useStore.getState().update(s => { + const id = 'new1' + s.gymCards.push({ id, label: 'FitZone', value: 'ABC', fmt: 'qrcode' }) + s.lastGymCardId = id + }, false) + expect(useStore.getState().S.lastGymCardId).toBe('new1') + }) + + it('removing the remembered card falls back to the first survivor', () => { + useStore.getState().update(s => { + s.gymCards.push({ id: 'a', label: 'A', value: '1', fmt: 'qrcode' }) + s.gymCards.push({ id: 'b', label: 'B', value: '2', fmt: 'qrcode' }) + s.lastGymCardId = 'a' + }, false) + // Mirrors CardFace's remove: drop the card, then repoint a now-stale lastGymCardId. + useStore.getState().update(s => { + s.gymCards = s.gymCards.filter(c => c.id !== 'a') + if (s.lastGymCardId === 'a') s.lastGymCardId = s.gymCards[0]?.id || null + }, false) + expect(useStore.getState().S.lastGymCardId).toBe('b') + }) + + it('removing the last remaining remembered card resets to null', () => { + useStore.getState().update(s => { + s.gymCards.push({ id: 'only', label: 'Only', value: 'x', fmt: 'qrcode' }) + s.lastGymCardId = 'only' + }, false) + useStore.getState().update(s => { + s.gymCards = s.gymCards.filter(c => c.id !== 'only') + if (s.lastGymCardId === 'only') s.lastGymCardId = s.gymCards[0]?.id || null + }, false) + expect(useStore.getState().S.gymCards).toEqual([]) + expect(useStore.getState().S.lastGymCardId).toBeNull() + }) +}) + +// Editing a card (rename / re-scan) updates that entry in place — same id, same slot, other cards +// untouched. Mirrors CardSheet's edit branch, which finds the card by id and overwrites its label +// and value only. +describe('editing a card in place', () => { + it('updates label and value of the matching card, leaving order and siblings intact', () => { + useStore.getState().update(s => { + s.gymCards.push({ id: 'a', label: 'A', value: '1', fmt: 'qrcode' }) + s.gymCards.push({ id: 'b', label: 'B', value: '2', fmt: 'qrcode' }) + }, false) + + useStore.getState().update(s => { + const c = s.gymCards.find(x => x.id === 'b') + c.label = 'B renamed' + c.value = 'rescanned' + }, false) + + const cards = useStore.getState().S.gymCards + expect(cards.map(c => c.id)).toEqual(['a', 'b']) // order + count unchanged + expect(cards[0]).toMatchObject({ label: 'A', value: '1' }) // sibling untouched + expect(cards[1]).toMatchObject({ id: 'b', label: 'B renamed', value: 'rescanned', fmt: 'qrcode' }) + }) +}) + // The Settings switch. On by default; an older profile that predates the key must read as on // too, and off only hides the feature — the cards themselves survive the round trip. describe('checkIn switch', () => { diff --git a/frontend/src/views/CheckIn.jsx b/frontend/src/views/CheckIn.jsx index 6fb60f3..b62f253 100644 --- a/frontend/src/views/CheckIn.jsx +++ b/frontend/src/views/CheckIn.jsx @@ -16,8 +16,22 @@ import { confirmSheet } from '../sheets.jsx' // 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 +export const CI_LONG_PRESS_MS = 380 +export const CI_DRAG_SLOP = 8 + +// Move the card at `from` to sit at index `to`, returning a new array (the input is left alone). +// This is the whole of the reorder once the drop target is known — kept as a pure function, apart +// from the pointer maths that computes `to`, so the ordering contract can be tested without a DOM. +// Out-of-range or no-op moves return an unchanged copy rather than throwing. +export function moveGymCard(cards, from, to) { + const next = [...cards] + if (from < 0 || from >= next.length) return next + const target = Math.max(0, Math.min(to, next.length - 1)) + if (target === from) return next + const [moved] = next.splice(from, 1) + next.splice(target, 0, moved) + return next +} // 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 @@ -158,15 +172,8 @@ function useRailReorder(railRef, cards) { 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) - }) - } + const to = centres.reduce((n, cx, i) => n + (i !== from && g.lastX > cx ? 1 : 0), 0) + if (to !== from) useStore.getState().update(s => { s.gymCards = moveGymCard(s.gymCards, from, to) }) } setState({ dragging: false, dragId: null }) } diff --git a/frontend/src/views/CheckIn.reorder.test.jsx b/frontend/src/views/CheckIn.reorder.test.jsx new file mode 100644 index 0000000..6e3d97d --- /dev/null +++ b/frontend/src/views/CheckIn.reorder.test.jsx @@ -0,0 +1,58 @@ +// @vitest-environment happy-dom +// @vitest-environment happy-dom + +// The rail's reorder maths. The drop handler in CheckIn.jsx turns a pointer position into a target +// index; moveGymCard is the pure part that then rearranges the array. These tests cover that +// contract — a move is a splice, the input is never mutated, and degenerate moves (in place, out of +// range) are safe no-ops — the same shape reorderRoutineUnit is tested to. +// +// moveGymCard itself is pure, but importing CheckIn.jsx loads the store (which registers a +// visibilitychange listener at module load) and the scanner/sheet modules, so the file runs under +// happy-dom with those heavy imports stubbed. The function under test touches none of them. + +import { describe, expect, it, vi } from 'vitest' + +vi.mock('../lib/scan.js', () => ({ scanCode: vi.fn(), importCodeFromImage: vi.fn() })) +vi.mock('../components/CameraScan.jsx', () => ({ default: () => null })) +vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() })) + +import { moveGymCard } from './CheckIn.jsx' + +const cards = (...ids) => ids.map(id => ({ id, label: id.toUpperCase(), value: id, fmt: 'qrcode' })) +const ids = list => list.map(c => c.id) + +describe('moveGymCard', () => { + it('moves a card forward to a later slot', () => { + expect(ids(moveGymCard(cards('a', 'b', 'c', 'd'), 0, 2))).toEqual(['b', 'c', 'a', 'd']) + }) + + it('moves a card backward to an earlier slot', () => { + expect(ids(moveGymCard(cards('a', 'b', 'c', 'd'), 3, 1))).toEqual(['a', 'd', 'b', 'c']) + }) + + it('is a permutation — no card is lost or duplicated', () => { + const before = cards('a', 'b', 'c', 'd', 'e') + const after = moveGymCard(before, 4, 0) + expect(ids(after).sort()).toEqual(['a', 'b', 'c', 'd', 'e']) + expect(after).toHaveLength(before.length) + }) + + it('leaves the array unchanged when dropped in place', () => { + expect(ids(moveGymCard(cards('a', 'b', 'c'), 1, 1))).toEqual(['a', 'b', 'c']) + }) + + it('clamps a target past the end to the last slot', () => { + expect(ids(moveGymCard(cards('a', 'b', 'c'), 0, 99))).toEqual(['b', 'c', 'a']) + }) + + it('ignores an out-of-range source without throwing', () => { + expect(ids(moveGymCard(cards('a', 'b'), 5, 0))).toEqual(['a', 'b']) + }) + + it('does not mutate the input array', () => { + const before = cards('a', 'b', 'c') + const snapshot = ids(before) + moveGymCard(before, 0, 2) + expect(ids(before)).toEqual(snapshot) + }) +}) From 23744c921bb4a9a324ce7934a97bcc0c99d7fa05 Mon Sep 17 00:00:00 2001 From: Sebastian G Date: Mon, 7 Sep 2026 10:32:28 +0200 Subject: [PATCH 3/4] i18n: translate QR check-in improvement strings for all locales --- frontend/src/lib/pt-br-locale.test.js | 6 +++--- frontend/src/locales/es.js | 7 +++++++ frontend/src/locales/fr.js | 7 +++++++ frontend/src/locales/hi.js | 7 +++++++ frontend/src/locales/hu.js | 7 +++++++ frontend/src/locales/it.js | 7 +++++++ frontend/src/locales/ko.js | 7 +++++++ frontend/src/locales/pl.js | 7 +++++++ frontend/src/locales/pt-BR.js | 5 +++++ frontend/src/locales/pt.js | 7 +++++++ frontend/src/locales/ru.js | 7 +++++++ frontend/src/locales/th.js | 7 +++++++ frontend/src/locales/tr.js | 7 +++++++ frontend/src/locales/zh.js | 7 +++++++ 14 files changed, 92 insertions(+), 3 deletions(-) diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index 1e6dc9b..aa131ee 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => { .sort(byCodeUnit) const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex') - expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(626) - expect(inherited).toHaveLength(613) + expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(631) + expect(inherited).toHaveLength(615) // If this fails, review the changed keys and wording before accepting a new hash. From // frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list - expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('81d277306b3029090b7a2ba6cc19108ca207ea65d738487155123260b6e9525d') + expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('8aa678164e6e66010767af67175b1be48139334f54cdd07b75c3f28866a48f57') }) test('does not leak European Portuguese UI terms', () => { diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index b933ef8..be1eb37 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': 'Número de socio o código', 'Save card': 'Guardar tarjeta', 'Gym card': 'Tarjeta del gimnasio', + 'Edit card': 'Editar tarjeta', + 'Re-scan': 'Volver a escanear', + 'Scan it with the camera or import a photo.': 'Escanéala con la cámara o importa una 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.': 'Importa una foto de tu tarjeta de socio o escanéala con la cámara. No hace falta otra app en el gimnasio — solo abre esta pantalla.', + 'Long-press a card to reorder': 'Mantén pulsada una tarjeta para reordenar', + 'Card updated': 'Tarjeta actualizada', + 'Scan or import a code first': 'Primero escanea o importa un código', 'Card added': 'Tarjeta añadida', 'Nothing to save yet': 'Nada que guardar todavía', "That's not a QR code — only QR cards can be shown here": 'Eso no es un código QR — aquí solo se pueden mostrar tarjetas QR', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 4437662..704d0d1 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': 'Numéro de membre ou code', 'Save card': 'Enregistrer la carte', 'Gym card': 'Carte de salle', + 'Edit card': 'Modifier la carte', + 'Re-scan': 'Rescanner', + 'Scan it with the camera or import a photo.': 'Scanne-la avec l’appareil photo ou importe une photo.', + 'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Importe une photo de ta carte de membre ou scanne-la avec l’appareil photo. Aucune autre appli nécessaire à la salle — ouvre simplement cet écran.', + 'Long-press a card to reorder': 'Appuie longuement sur une carte pour la réorganiser', + 'Card updated': 'Carte mise à jour', + 'Scan or import a code first': 'Scanne ou importe d’abord un code', 'Card added': 'Carte ajoutée', 'Nothing to save yet': 'Rien à enregistrer pour l’instant', "That's not a QR code — only QR cards can be shown here": 'Ce n’est pas un code QR — seules les cartes QR peuvent être affichées ici', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 7b5bb0d..923066c 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': 'मेंबरशिप नंबर या कोड', 'Save card': 'कार्ड सहेजें', 'Gym card': 'जिम कार्ड', + 'Edit card': 'कार्ड संपादित करें', + 'Re-scan': 'फिर से स्कैन करें', + 'Scan it with the camera or import a photo.': 'इसे कैमरे से स्कैन करें या फ़ोटो इम्पोर्ट करें।', + 'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': 'अपने मेंबरशिप कार्ड की फ़ोटो इम्पोर्ट करें या कैमरे से स्कैन करें। जिम में किसी और ऐप की ज़रूरत नहीं — बस यह स्क्रीन खोलें।', + 'Long-press a card to reorder': 'क्रम बदलने के लिए कार्ड को देर तक दबाएँ', + 'Card updated': 'कार्ड अपडेट हुआ', + 'Scan or import a code first': 'पहले कोई कोड स्कैन या इम्पोर्ट करें', 'Card added': 'कार्ड जोड़ा गया', 'Nothing to save yet': 'अभी सहेजने के लिए कुछ नहीं', "That's not a QR code — only QR cards can be shown here": 'यह QR कोड नहीं है — यहाँ केवल QR कार्ड दिखाए जा सकते हैं', diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js index b8a3d46..da6702b 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -807,6 +807,13 @@ export default { 'Membership number or code': 'Tagsági szám vagy kód', 'Save card': 'Kártya mentése', 'Gym card': 'Terembérlet', + 'Edit card': 'Kártya szerkesztése', + 'Re-scan': 'Újraolvasás', + 'Scan it with the camera or import a photo.': 'Olvasd be a kamerával, vagy importálj egy fotó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.': 'Importálj egy fotót a tagsági kártyádról, vagy olvasd be a kamerával. Nincs szükség külön alkalmazásra a teremben — csak nyisd meg ezt a képernyőt.', + 'Long-press a card to reorder': 'Tartsd nyomva a kártyát az átrendezéshez', + 'Card updated': 'Kártya frissítve', + 'Scan or import a code first': 'Előbb olvass be vagy importálj egy kódot', 'Card added': 'Kártya hozzáadva', 'Nothing to save yet': 'Még nincs mit menteni', "That's not a QR code — only QR cards can be shown here": 'Ez nem QR-kód — itt csak QR-kártyák jeleníthetők meg', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index bbd9057..3a98e9f 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': 'Numero tessera o codice', 'Save card': 'Salva tessera', 'Gym card': 'Tessera palestra', + 'Edit card': 'Modifica tessera', + 'Re-scan': 'Scansiona di nuovo', + 'Scan it with the camera or import a photo.': 'Scansionala con la fotocamera o importa una 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.': 'Importa una foto della tua tessera o scansionala con la fotocamera. Nessuna app extra in palestra — apri semplicemente questa schermata.', + 'Long-press a card to reorder': 'Tieni premuta una tessera per riordinarla', + 'Card updated': 'Tessera aggiornata', + 'Scan or import a code first': 'Prima scansiona o importa un codice', 'Card added': 'Tessera aggiunta', 'Nothing to save yet': 'Ancora niente da salvare', "That's not a QR code — only QR cards can be shown here": 'Non è un codice QR — qui si possono mostrare solo tessere QR', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index aba5bf2..c411344 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': '회원 번호 또는 코드', 'Save card': '카드 저장', 'Gym card': '헬스장 카드', + 'Edit card': '카드 편집', + 'Re-scan': '다시 스캔', + 'Scan it with the camera or import a photo.': '카메라로 스캔하거나 사진을 가져오세요.', + 'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': '회원 카드 사진을 가져오거나 카메라로 스캔하세요. 헬스장에서 다른 앱은 필요 없어요 — 이 화면만 열면 됩니다.', + 'Long-press a card to reorder': '순서를 바꾸려면 카드를 길게 누르세요', + 'Card updated': '카드가 업데이트됨', + 'Scan or import a code first': '먼저 코드를 스캔하거나 가져오세요', 'Card added': '카드가 추가되었습니다', 'Nothing to save yet': '아직 저장할 내용이 없습니다', "That's not a QR code — only QR cards can be shown here": 'QR 코드가 아닙니다 — 여기서는 QR 카드만 표시할 수 있습니다', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 544b6c4..195fed8 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': 'Numer członkowski lub kod', 'Save card': 'Zapisz kartę', 'Gym card': 'Karta siłowni', + 'Edit card': 'Edytuj kartę', + 'Re-scan': 'Zeskanuj ponownie', + 'Scan it with the camera or import a photo.': 'Zeskanuj ją aparatem lub zaimportuj zdjęcie.', + 'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Zaimportuj zdjęcie karty członkowskiej lub zeskanuj ją aparatem. Na siłowni nie potrzebujesz innej aplikacji — po prostu otwórz ten ekran.', + 'Long-press a card to reorder': 'Przytrzymaj kartę, aby zmienić kolejność', + 'Card updated': 'Karta zaktualizowana', + 'Scan or import a code first': 'Najpierw zeskanuj lub zaimportuj kod', 'Card added': 'Dodano kartę', 'Nothing to save yet': 'Nie ma jeszcze nic do zapisania', "That's not a QR code — only QR cards can be shown here": 'To nie jest kod QR — tutaj można pokazać tylko karty QR', diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js index ebcb22c..6d7b4b8 100644 --- a/frontend/src/locales/pt-BR.js +++ b/frontend/src/locales/pt-BR.js @@ -621,6 +621,11 @@ export const PT_BR_OVERRIDES = { 'Scan': 'Escanear', 'e.g. FitZone downtown': 'ex. FitZone centro', 'Gym card': 'Cartão da academia', + 'Re-scan': 'Escanear de novo', + 'Scan it with the camera or import a photo.': 'Escaneie com a câmera ou importe uma 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.': 'Importe uma foto do seu cartão de sócio ou escaneie com a câmera. Não é preciso outro app na academia — é só abrir esta tela.', + 'Long-press a card to reorder': 'Mantenha o cartão pressionado para reordenar', + 'Scan or import a code first': 'Primeiro escaneie ou importe um código', 'Could not read that image': 'Não foi possível ler essa imagem', 'Camera permission is needed to scan. Enable it in Settings.': 'É necessária a permissão da câmera para escanear. Ative-a nos Ajustes.', 'Scanning is not available on this device.': 'O escaneamento não está disponível neste dispositivo.', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index f06f986..a1eead5 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': 'Número de sócio ou código', 'Save card': 'Guardar cartão', 'Gym card': 'Cartão do ginásio', + 'Edit card': 'Editar cartão', + 'Re-scan': 'Digitalizar de novo', + 'Scan it with the camera or import a photo.': 'Digitaliza-o com a câmara ou importa uma 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.': 'Importa uma foto do teu cartão de sócio ou digitaliza-o com a câmara. Não é preciso outra app no ginásio — basta abrir este ecrã.', + 'Long-press a card to reorder': 'Mantém premido um cartão para reordenar', + 'Card updated': 'Cartão atualizado', + 'Scan or import a code first': 'Primeiro digitaliza ou importa um código', 'Card added': 'Cartão adicionado', 'Nothing to save yet': 'Ainda não há nada para guardar', "That's not a QR code — only QR cards can be shown here": 'Isto não é um código QR — aqui só podem ser mostrados cartões QR', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index adcc629..db18d51 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': 'Номер участника или код', 'Save card': 'Сохранить карту', 'Gym card': 'Карта зала', + 'Edit card': 'Изменить карту', + 'Re-scan': 'Сканировать заново', + 'Scan it with the camera or import a photo.': 'Отсканируйте её камерой или импортируйте фото.', + 'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Импортируйте фото клубной карты или отсканируйте её камерой. В зале не нужно отдельное приложение — просто откройте этот экран.', + 'Long-press a card to reorder': 'Удерживайте карту, чтобы изменить порядок', + 'Card updated': 'Карта обновлена', + 'Scan or import a code first': 'Сначала отсканируйте или импортируйте код', 'Card added': 'Карта добавлена', 'Nothing to save yet': 'Пока нечего сохранять', "That's not a QR code — only QR cards can be shown here": 'Это не QR-код — здесь можно показывать только QR-карты', diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js index 229a024..a647758 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -815,6 +815,13 @@ export default { 'Membership number or code': 'หมายเลขสมาชิกหรือรหัส', 'Save card': 'บันทึกบัตร', 'Gym card': 'บัตรยิม', + 'Edit card': 'แก้ไขบัตร', + 'Re-scan': 'สแกนใหม่', + 'Scan it with the camera or import a photo.': 'สแกนด้วยกล้องหรือนำเข้ารูปถ่าย', + 'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': 'นำเข้ารูปถ่ายบัตรสมาชิกหรือสแกนด้วยกล้อง ไม่ต้องใช้แอปอื่นที่ยิม — แค่เปิดหน้าจอนี้', + 'Long-press a card to reorder': 'กดบัตรค้างไว้เพื่อจัดลำดับใหม่', + 'Card updated': 'อัปเดตบัตรแล้ว', + 'Scan or import a code first': 'สแกนหรือนำเข้ารหัสก่อน', 'Card added': 'เพิ่มบัตรแล้ว', 'Nothing to save yet': 'ยังไม่มีอะไรให้บันทึก', "That's not a QR code — only QR cards can be shown here": 'นี่ไม่ใช่คิวอาร์โค้ด — ที่นี่แสดงได้เฉพาะบัตรคิวอาร์โค้ดเท่านั้น', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index d4d554b..b3318ea 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': 'Üyelik numarası veya kodu', 'Save card': 'Kartı kaydet', 'Gym card': 'Salon kartı', + 'Edit card': 'Kartı düzenle', + 'Re-scan': 'Yeniden tara', + 'Scan it with the camera or import a photo.': 'Kamerayla tara ya da bir fotoğraf içe aktar.', + 'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Üyelik kartının fotoğrafını içe aktar ya da kamerayla tara. Salonda ekstra bir uygulamaya gerek yok — sadece bu ekranı aç.', + 'Long-press a card to reorder': 'Sırayı değiştirmek için karta uzun bas', + 'Card updated': 'Kart güncellendi', + 'Scan or import a code first': 'Önce bir kod tara ya da içe aktar', 'Card added': 'Kart eklendi', 'Nothing to save yet': 'Henüz kaydedilecek bir şey yok', "That's not a QR code — only QR cards can be shown here": 'Bu bir QR kod değil — burada yalnızca QR kartlar gösterilebilir', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 05108b7..a489dee 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -1139,6 +1139,13 @@ export default { 'Membership number or code': '会员号或代码', 'Save card': '保存卡片', 'Gym card': '健身房卡片', + 'Edit card': '编辑卡片', + 'Re-scan': '重新扫描', + 'Scan it with the camera or import a photo.': '用相机扫描或导入照片。', + 'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': '导入会员卡照片,或用相机扫描。在健身房无需额外应用——打开此界面即可。', + 'Long-press a card to reorder': '长按卡片可重新排序', + 'Card updated': '卡片已更新', + 'Scan or import a code first': '请先扫描或导入代码', 'Card added': '已添加卡片', 'Nothing to save yet': '暂无可保存的内容', "That's not a QR code — only QR cards can be shown here": '这不是二维码——此处只能显示二维码卡片', From 3685e279a6f8347ef30275292946386a4e8f6694 Mon Sep 17 00:00:00 2001 From: Sebastian G Date: Mon, 7 Sep 2026 11:21:26 +0200 Subject: [PATCH 4/4] removed buggy reorder feature --- frontend/src/index.css | 9 +- frontend/src/lib/pt-br-locale.test.js | 4 +- frontend/src/locales/de.js | 2 + frontend/src/locales/es.js | 2 + frontend/src/locales/fr.js | 2 + frontend/src/locales/hi.js | 2 + frontend/src/locales/hu.js | 2 + frontend/src/locales/it.js | 2 + frontend/src/locales/ko.js | 2 + frontend/src/locales/pl.js | 2 + frontend/src/locales/pt.js | 2 + frontend/src/locales/ru.js | 2 + frontend/src/locales/th.js | 2 + frontend/src/locales/tr.js | 2 + frontend/src/locales/zh.js | 2 + frontend/src/views/CheckIn.jsx | 143 ++++---------------- frontend/src/views/CheckIn.reorder.test.jsx | 8 +- 17 files changed, 60 insertions(+), 130 deletions(-) diff --git a/frontend/src/index.css b/frontend/src/index.css index 140da1b..5168b61 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -1168,10 +1168,11 @@ h4.sec{ .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} +/* reorder row under a card (only shown with >1 card): ◀ position ▶ to nudge the card one slot + along the rail. A plain, reliable control — no drag gesture to fight the horizontal scroll. */ +.ci-reorder{display:flex;align-items:center;justify-content:center;gap:14px;margin-top:2px} +.ci-reorder .ci-pos{font-size:13px;color:var(--label-2);font-variant-numeric:tabular-nums;min-width:44px;text-align:center} +.ci-reorder .iconbtn:disabled{opacity:.3;pointer-events:none} /* The QR itself: lean-qr paints 1 module per pixel, so scale it up with the browser's nearest-neighbour so every module stays a crisp square instead of a blurred blob. White quiet-zone padding is baked in by the renderer; the plate underneath just frames it. */ diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index aa131ee..6517939 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -28,10 +28,10 @@ describe('Brazilian Portuguese locale', () => { const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex') expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(631) - expect(inherited).toHaveLength(615) + expect(inherited).toHaveLength(617) // If this fails, review the changed keys and wording before accepting a new hash. From // frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list - expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('8aa678164e6e66010767af67175b1be48139334f54cdd07b75c3f28866a48f57') + expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('6a9e0df18bdd7020d2ad84104a020f2728f68b629933235fae7741b4ec71226d') }) test('does not leak European Portuguese UI terms', () => { diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 92b60cf..5e206ae 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -1158,6 +1158,8 @@ export default { 'Membership number or code': 'Mitgliedsnummer oder Code', 'Save card': 'Karte speichern', 'Gym card': 'Studio-Karte', + 'Move left': 'Nach links', + 'Move right': 'Nach rechts', '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.', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index be1eb37..6b14d47 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': 'Número de socio o código', 'Save card': 'Guardar tarjeta', 'Gym card': 'Tarjeta del gimnasio', + 'Move left': 'Mover a la izquierda', + 'Move right': 'Mover a la derecha', 'Edit card': 'Editar tarjeta', 'Re-scan': 'Volver a escanear', 'Scan it with the camera or import a photo.': 'Escanéala con la cámara o importa una foto.', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 704d0d1..f3b37a4 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': 'Numéro de membre ou code', 'Save card': 'Enregistrer la carte', 'Gym card': 'Carte de salle', + 'Move left': 'Déplacer à gauche', + 'Move right': 'Déplacer à droite', 'Edit card': 'Modifier la carte', 'Re-scan': 'Rescanner', 'Scan it with the camera or import a photo.': 'Scanne-la avec l’appareil photo ou importe une photo.', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 923066c..936f19a 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': 'मेंबरशिप नंबर या कोड', 'Save card': 'कार्ड सहेजें', 'Gym card': 'जिम कार्ड', + 'Move left': 'बाएँ ले जाएँ', + 'Move right': 'दाएँ ले जाएँ', 'Edit card': 'कार्ड संपादित करें', 'Re-scan': 'फिर से स्कैन करें', 'Scan it with the camera or import a photo.': 'इसे कैमरे से स्कैन करें या फ़ोटो इम्पोर्ट करें।', diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js index da6702b..4deed29 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -807,6 +807,8 @@ export default { 'Membership number or code': 'Tagsági szám vagy kód', 'Save card': 'Kártya mentése', 'Gym card': 'Terembérlet', + 'Move left': 'Balra', + 'Move right': 'Jobbra', 'Edit card': 'Kártya szerkesztése', 'Re-scan': 'Újraolvasás', 'Scan it with the camera or import a photo.': 'Olvasd be a kamerával, vagy importálj egy fotót.', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 3a98e9f..64cf97a 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': 'Numero tessera o codice', 'Save card': 'Salva tessera', 'Gym card': 'Tessera palestra', + 'Move left': 'Sposta a sinistra', + 'Move right': 'Sposta a destra', 'Edit card': 'Modifica tessera', 'Re-scan': 'Scansiona di nuovo', 'Scan it with the camera or import a photo.': 'Scansionala con la fotocamera o importa una foto.', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index c411344..2bc5b8f 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': '회원 번호 또는 코드', 'Save card': '카드 저장', 'Gym card': '헬스장 카드', + 'Move left': '왼쪽으로 이동', + 'Move right': '오른쪽으로 이동', 'Edit card': '카드 편집', 'Re-scan': '다시 스캔', 'Scan it with the camera or import a photo.': '카메라로 스캔하거나 사진을 가져오세요.', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 195fed8..c20cfaa 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': 'Numer członkowski lub kod', 'Save card': 'Zapisz kartę', 'Gym card': 'Karta siłowni', + 'Move left': 'Przesuń w lewo', + 'Move right': 'Przesuń w prawo', 'Edit card': 'Edytuj kartę', 'Re-scan': 'Zeskanuj ponownie', 'Scan it with the camera or import a photo.': 'Zeskanuj ją aparatem lub zaimportuj zdjęcie.', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index a1eead5..60c8cd1 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': 'Número de sócio ou código', 'Save card': 'Guardar cartão', 'Gym card': 'Cartão do ginásio', + 'Move left': 'Mover para a esquerda', + 'Move right': 'Mover para a direita', 'Edit card': 'Editar cartão', 'Re-scan': 'Digitalizar de novo', 'Scan it with the camera or import a photo.': 'Digitaliza-o com a câmara ou importa uma foto.', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index db18d51..cafbfc8 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': 'Номер участника или код', 'Save card': 'Сохранить карту', 'Gym card': 'Карта зала', + 'Move left': 'Влево', + 'Move right': 'Вправо', 'Edit card': 'Изменить карту', 'Re-scan': 'Сканировать заново', 'Scan it with the camera or import a photo.': 'Отсканируйте её камерой или импортируйте фото.', diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js index a647758..9061748 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -815,6 +815,8 @@ export default { 'Membership number or code': 'หมายเลขสมาชิกหรือรหัส', 'Save card': 'บันทึกบัตร', 'Gym card': 'บัตรยิม', + 'Move left': 'ย้ายไปทางซ้าย', + 'Move right': 'ย้ายไปทางขวา', 'Edit card': 'แก้ไขบัตร', 'Re-scan': 'สแกนใหม่', 'Scan it with the camera or import a photo.': 'สแกนด้วยกล้องหรือนำเข้ารูปถ่าย', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index b3318ea..d51bbca 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': 'Üyelik numarası veya kodu', 'Save card': 'Kartı kaydet', 'Gym card': 'Salon kartı', + 'Move left': 'Sola taşı', + 'Move right': 'Sağa taşı', 'Edit card': 'Kartı düzenle', 'Re-scan': 'Yeniden tara', 'Scan it with the camera or import a photo.': 'Kamerayla tara ya da bir fotoğraf içe aktar.', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index a489dee..053d497 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -1139,6 +1139,8 @@ export default { 'Membership number or code': '会员号或代码', 'Save card': '保存卡片', 'Gym card': '健身房卡片', + 'Move left': '向左移动', + 'Move right': '向右移动', 'Edit card': '编辑卡片', 'Re-scan': '重新扫描', 'Scan it with the camera or import a photo.': '用相机扫描或导入照片。', diff --git a/frontend/src/views/CheckIn.jsx b/frontend/src/views/CheckIn.jsx index b62f253..546b293 100644 --- a/frontend/src/views/CheckIn.jsx +++ b/frontend/src/views/CheckIn.jsx @@ -1,4 +1,4 @@ -import { useEffect, useLayoutEffect, useRef, useState } from 'react' +import { useLayoutEffect, useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' @@ -13,16 +13,9 @@ import CameraScan from '../components/CameraScan.jsx' import { Button, TextField } from '../components/ui.jsx' import { confirmSheet } from '../sheets.jsx' -// 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. -export const CI_LONG_PRESS_MS = 380 -export const CI_DRAG_SLOP = 8 - // Move the card at `from` to sit at index `to`, returning a new array (the input is left alone). -// This is the whole of the reorder once the drop target is known — kept as a pure function, apart -// from the pointer maths that computes `to`, so the ordering contract can be tested without a DOM. -// Out-of-range or no-op moves return an unchanged copy rather than throwing. +// Backs the on-card ◀ ▶ reorder buttons. Out-of-range or no-op moves return an unchanged copy +// rather than throwing, so a button at either end is simply inert. export function moveGymCard(cards, from, to) { const next = [...cards] if (from < 0 || from >= next.length) return next @@ -41,8 +34,8 @@ export function moveGymCard(cards, from, to) { // 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. +// code that silently fails at the turnstile. An existing card can be edited (rename, re-scan), and +// with more than one card each carries ◀ ▶ buttons to nudge its position along the rail. export default function CheckIn() { const nav = useNavigate() const cards = useStore(s => s.S.gymCards) || [] @@ -50,7 +43,6 @@ export default function CheckIn() { 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. @@ -85,13 +77,14 @@ export default function CheckIn() {
-
- {cards.map(card => + {cards.map((card, i) => )} - @@ -103,10 +96,6 @@ export default function CheckIn() { = cards.length ? ' on' : '')} />
} - {cards.length > 1 &&
- {t('Long-press a card to reorder')} -
} - {!cards.length &&
{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.')}
} @@ -115,8 +104,10 @@ export default function CheckIn() { // 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 }) { +// add a card, pre-filled; the trash button removes it after a confirm. With more than one card, a +// row of ◀ ▶ buttons nudges this card one slot along the rail — a plain, reliable reorder that +// doesn't fight the rail's horizontal scroll the way a drag gesture did. +function CardFace({ card, index, count }) { const update = useStore(s => s.update) const remove = () => confirmSheet({ title: t('Remove this card?'), @@ -128,111 +119,23 @@ function CardFace({ card, dragging }) { if (s.lastGymCardId === card.id) s.lastGymCardId = (s.gymCards[0]?.id) || null }), }) - return
+ const move = to => update(s => { s.gymCards = moveGymCard(s.gymCards, index, to) }) + return
- +
{card.label}
- +
{card.value}
+ {count > 1 &&
+ + {index + 1} / {count} + +
}
} -/* ------------------------------------------------------- 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 }) - const to = centres.reduce((n, cx, i) => n + (i !== from && g.lastX > cx ? 1 : 0), 0) - if (to !== from) useStore.getState().update(s => { s.gymCards = moveGymCard(s.gymCards, from, to) }) - } - 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 diff --git a/frontend/src/views/CheckIn.reorder.test.jsx b/frontend/src/views/CheckIn.reorder.test.jsx index 6e3d97d..9ce35aa 100644 --- a/frontend/src/views/CheckIn.reorder.test.jsx +++ b/frontend/src/views/CheckIn.reorder.test.jsx @@ -1,10 +1,10 @@ // @vitest-environment happy-dom // @vitest-environment happy-dom -// The rail's reorder maths. The drop handler in CheckIn.jsx turns a pointer position into a target -// index; moveGymCard is the pure part that then rearranges the array. These tests cover that -// contract — a move is a splice, the input is never mutated, and degenerate moves (in place, out of -// range) are safe no-ops — the same shape reorderRoutineUnit is tested to. +// moveGymCard backs the on-card ◀ ▶ reorder buttons: it moves the card at `from` to index `to`, +// returning a new array. These tests cover that contract — a move is a splice, the input is never +// mutated, and degenerate moves (in place, out of range, past the ends) are safe no-ops, so a +// button at either end of the rail is simply inert. // // moveGymCard itself is pure, but importing CheckIn.jsx loads the store (which registers a // visibilitychange listener at module load) and the scanner/sheet modules, so the file runs under