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
Halloween: tests for the date window, the settings page, reduced motion, once a day and the lazy-load guard
Duarte Santos42f064cfddec
diff --git a/frontend/src/components/Seasonal.lazy.test.jsx b/frontend/src/components/Seasonal.lazy.test.jsxnew file mode 100644index 000000000..63ed681b2--- /dev/null+++ b/frontend/src/components/Seasonal.lazy.test.jsx@@ -0,0 +1,83 @@+// @vitest-environment happy-dom+// Seasonal themes cost nothing when they are not showing (components/Seasonal.jsx): the theme's+// module is not in the main bundle, and it is not even fetched until a theme is on.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { join, relative } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++const st = vi.hoisted(() => ({ S: {}, loaded: 0 }))+vi.mock('../store/useStore.js', () => ({ useStore: sel => sel({ S: st.S }) }))+vi.mock('../seasonal/halloween.jsx', () => {+ st.loaded+++ return { Layer: () => <i className="layer" />, Deco: ({ spot }) => <i className={'deco-' + spot} /> }+})++const SRC = join(__dirname, '..')+const files = (dir, out = []) => {+ for (const n of readdirSync(dir)) {+ const p = join(dir, n)+ if (statSync(p).isDirectory()) { if (n !== 'locales' && n !== 'node_modules') files(p, out) }+ else if (/\.(js|jsx)$/.test(n) && !/\.test\./.test(n)) out.push(p)+ }+ return out+}++describe('no theme code in the main bundle', () => {+ it('only components/Seasonal.jsx names a theme module, and only through import()', () => {+ const naming = files(SRC).filter(f => !f.includes(join('src', 'seasonal') + '/')).filter(f => /seasonal\/halloween/.test(readFileSync(f, 'utf8')))+ expect(naming.map(f => relative(SRC, f))).toEqual([join('components', 'Seasonal.jsx')])+ const text = readFileSync(join(SRC, 'components', 'Seasonal.jsx'), 'utf8')+ expect(text).not.toMatch(/^\s*import[^(]*seasonal\/halloween/m)+ expect(text).toMatch(/import\('\.\.\/seasonal\/halloween\.jsx'\)/)+ })+ it('the theme\'s stylesheet comes with its module, not with index.css', () => {+ expect(readFileSync(join(SRC, 'index.css'), 'utf8')).not.toMatch(/hw-|halloween/)+ expect(readFileSync(join(SRC, 'seasonal', 'halloween.jsx'), 'utf8')).toMatch(/import '\.\/halloween\.css'/)+ })+})++describe('fetched only while a theme shows', () => {+ let host, root+ beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(2026, 9, 25, 12))+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)+ })+ afterEach(() => { act(() => root.unmount()); host.remove(); vi.useRealTimers(); delete document.documentElement.dataset.season })++ it('switched off in season: nothing rendered, nothing loaded, no data-season', async () => {+ st.S = { seasonal: { halloween: 'off' } }+ const { SeasonalLayer, SeasonDeco } = await import('./Seasonal.jsx')+ await act(async () => root.render(<><SeasonalLayer /><SeasonDeco spot="home-hero" /></>))+ expect(host.innerHTML).toBe('')+ expect(st.loaded).toBe(0)+ expect(document.documentElement.dataset.season).toBeUndefined()+ })++ it('out of season on Auto: the same', async () => {+ vi.setSystemTime(new Date(2026, 11, 3, 12))+ st.S = {}+ const { SeasonalLayer } = await import('./Seasonal.jsx')+ await act(async () => root.render(<SeasonalLayer />))+ expect(host.innerHTML).toBe('')+ expect(st.loaded).toBe(0)+ })++ it('on: the module comes in and draws its spots', async () => {+ vi.useRealTimers()+ st.S = { seasonal: { halloween: 'on' } }+ const { SeasonalLayer, SeasonDeco } = await import('./Seasonal.jsx')+ const settle = async () => { for (let i = 0; i < 4; i++) await act(async () => { await new Promise(r => setTimeout(r, 20)) }) }+ await act(async () => root.render(<SeasonDeco spot="home-hero" />))+ await settle()+ expect(st.loaded).toBe(1)+ expect(host.querySelector('.deco-home-hero')).not.toBeNull()+ await act(async () => root.render(<><SeasonDeco spot="home-hero" /><SeasonalLayer /></>))+ await settle()+ expect(host.querySelector('.layer')).not.toBeNull()+ expect(document.documentElement.dataset.season).toBe('halloween')+ })+})diff --git a/frontend/src/lib/seasonal.test.js b/frontend/src/lib/seasonal.test.jsnew file mode 100644index 000000000..fc7d64593--- /dev/null+++ b/frontend/src/lib/seasonal.test.js@@ -0,0 +1,93 @@+// @vitest-environment happy-dom+// Seasonal themes (lib/seasonal.js): the date window, the choice, the opt-in colours, once a day.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { THEMES, inSeason, seasonChoice, themeOn, activeSeason, seasonAccent, onceToday, doneToday } from './seasonal.js'++const local = (y, m, d, h = 12, min = 0) => new Date(y, m - 1, d, h, min)++describe('the Halloween window', () => {+ it('runs from 1 October to the end of 31 October, local time', () => {+ expect(inSeason('halloween', local(2026, 9, 30, 23, 59))).toBe(false)+ expect(inSeason('halloween', local(2026, 10, 1, 0, 0))).toBe(true)+ expect(inSeason('halloween', local(2026, 10, 31, 23, 59))).toBe(true)+ expect(inSeason('halloween', local(2026, 11, 1, 0, 0))).toBe(false)+ expect(inSeason('halloween', local(2027, 3, 1))).toBe(false)+ })++ it('follows the clock on the wall, not UTC: one instant, two answers', () => {+ const was = process.env.TZ+ try {+ const instant = new Date(Date.UTC(2026, 9, 31, 23, 30)) // 31 Oct 23:30 UTC+ process.env.TZ = 'America/Los_Angeles' // 31 Oct, 16:30: still Halloween+ expect(inSeason('halloween', new Date(instant))).toBe(true)+ process.env.TZ = 'Pacific/Auckland' // 1 Nov, 12:30: over+ expect(inSeason('halloween', new Date(instant))).toBe(false)+ } finally {+ if (was === undefined) delete process.env.TZ; else process.env.TZ = was+ }+ })++ it('a window may wrap the new year', () => {+ const winter = { id: 'x', from: [12, 20], to: [1, 6] }+ expect(inSeason(winter, local(2026, 12, 31))).toBe(true)+ expect(inSeason(winter, local(2027, 1, 6))).toBe(true)+ expect(inSeason(winter, local(2027, 1, 7))).toBe(false)+ })++ it('every theme in the list has the fields the settings page reads', () => {+ for (const th of THEMES) {+ expect(th.title && th.during && th.back && th.icon, th.id).toBeTruthy()+ expect(th.from).toHaveLength(2)+ expect(th.to).toHaveLength(2)+ if (th.colors) expect(th.colorsTitle && th.colorsNote, th.id).toBeTruthy()+ }+ })+})++describe('the choice', () => {+ const oct = local(2026, 10, 25), may = local(2026, 5, 3)+ it('absent, or a value it does not know, reads as Auto', () => {+ expect(seasonChoice({}, 'halloween')).toBe('auto')+ expect(seasonChoice({ seasonal: { halloween: 'spooky' } }, 'halloween')).toBe('auto')+ expect(themeOn({}, 'halloween', oct)).toBe(true)+ expect(themeOn({}, 'halloween', may)).toBe(false)+ })+ it('On shows it all year, Off never', () => {+ expect(themeOn({ seasonal: { halloween: 'on' } }, 'halloween', may)).toBe(true)+ expect(themeOn({ seasonal: { halloween: 'off' } }, 'halloween', oct)).toBe(false)+ expect(activeSeason({ seasonal: { halloween: 'off' } }, oct)).toBe(null)+ expect(activeSeason({}, oct)).toBe('halloween')+ })+ it('the colours stand in for the accent only while the theme shows, and only when chosen', () => {+ expect(seasonAccent({}, oct)).toBe(null)+ expect(seasonAccent({ seasonal: { halloweenColors: true } }, oct)).toBe('orange')+ expect(seasonAccent({ seasonal: { halloweenColors: true } }, may)).toBe(null)+ expect(seasonAccent({ seasonal: { halloween: 'off', halloweenColors: true } }, oct)).toBe(null)+ })+})++describe('once a day', () => {+ beforeEach(() => localStorage.clear())+ afterEach(() => localStorage.clear())+ it('fires the first time on a local date, then not again until the next one', () => {+ const morning = local(2026, 10, 25, 7), night = local(2026, 10, 25, 23, 59), next = local(2026, 10, 26, 0, 1)+ expect(doneToday('spider', morning)).toBe(false)+ expect(onceToday('spider', morning)).toBe(true)+ expect(doneToday('spider', night)).toBe(true)+ expect(onceToday('spider', night)).toBe(false)+ expect(onceToday('spider', next)).toBe(true)+ })+ it('keys are separate: the spider does not use up the pumpkin', () => {+ const d = local(2026, 10, 25)+ expect(onceToday('spider', d)).toBe(true)+ expect(onceToday('pumpkin', d)).toBe(true)+ })+ it('storage that is not there answers no, so nothing repeats on every start', () => {+ const blocked = () => { throw new Error('blocked') }+ vi.stubGlobal('localStorage', { getItem: blocked, setItem: blocked, clear() {} })+ try {+ expect(onceToday('spider')).toBe(false)+ expect(doneToday('spider')).toBe(true)+ } finally { vi.unstubAllGlobals() }+ })+})diff --git a/frontend/src/seasonal/halloween.test.jsx b/frontend/src/seasonal/halloween.test.jsxnew file mode 100644index 000000000..77c6cc62e--- /dev/null+++ b/frontend/src/seasonal/halloween.test.jsx@@ -0,0 +1,128 @@+// @vitest-environment happy-dom+// Halloween's moving parts (seasonal/halloween.jsx): the spider once a day at a start, the+// reduced-motion path, the workout screen, and the pumpkin's one surprise a day.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++const ui = vi.hoisted(() => ({ toast: null }))+vi.mock('../store/useUI.js', () => ({ useUI: { getState: () => ({ toast: ui.toast }) } }))+const buzz = vi.hoisted(() => ({ vibrate: null }))+vi.mock('../lib/sound.js', () => ({ vibrate: p => buzz.vibrate(p) }))++let host, root, reduce = false+// Each test gets the module afresh: the spider's and the witch's "this session" live in it.+const load = async () => { vi.resetModules(); return import('./halloween.jsx') }+beforeEach(() => {+ localStorage.clear()+ reduce = false+ window.matchMedia = q => ({ matches: reduce && /reduce/.test(q), addEventListener() {}, removeEventListener() {} })+ ui.toast = vi.fn(); buzz.vibrate = vi.fn()+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)+})+afterEach(() => { act(() => root.unmount()); host.remove(); vi.useRealTimers() })+const render = el => act(() => root.render(el))++describe('the spider', () => {+ it('drops at the first start of the day, and not at the next one', async () => {+ let { Layer } = await load()+ render(<Layer hidden={false} fresh />)+ expect(host.querySelector('.hw-spider .hw-drop')).not.toBeNull()+ expect(host.querySelector('.hw-spider').getAttribute('aria-hidden')).toBe('true')+ act(() => root.unmount()); root = createRoot(host)+ ;({ Layer } = await load()) // a second start, same day+ render(<Layer hidden={false} fresh />)+ expect(host.querySelector('.hw-spider')).toBeNull()+ })++ it('does not drop over a start straight into a workout, and keeps the day for later', async () => {+ const { Layer } = await load()+ render(<Layer hidden fresh={false} />)+ expect(host.innerHTML).toBe('')+ expect(localStorage.getItem('og_season_spider')).toBeNull()+ })++ it('one tap and it scurries off, and is gone when it is out of sight', async () => {+ const { Layer } = await load()+ render(<Layer hidden={false} fresh />)+ act(() => { host.querySelector('.hw-spiderbtn').dispatchEvent(new Event('pointerdown', { bubbles: true })) })+ expect(host.querySelector('.hw-spider').classList.contains('hw-scurry')).toBe(true)+ act(() => {+ const e = new Event('animationend', { bubbles: true }); e.animationName = 'hw-scurry'+ host.querySelector('.hw-spiderbtn').dispatchEvent(e)+ })+ expect(host.querySelector('.hw-spider')).toBeNull()+ })++ it('with reduced motion: no drop, a still spider in the corner for a few seconds, no witch', async () => {+ reduce = true+ vi.useFakeTimers()+ const { Layer } = await load()+ const random = vi.spyOn(Math, 'random').mockReturnValue(0)+ render(<Layer hidden={false} fresh />)+ expect(host.querySelector('.hw-spider.hw-still')).not.toBeNull()+ expect(host.querySelector('.hw-drop, .hw-spiderbtn')).toBeNull()+ act(() => { vi.advanceTimersByTime(4000) })+ expect(host.querySelector('.hw-spider')).toBeNull()+ act(() => { vi.advanceTimersByTime(120000) })+ expect(host.querySelector('.hw-witch')).toBeNull()+ random.mockRestore()+ })++ it('the witch flies at most once a session', async () => {+ vi.useFakeTimers()+ const { Layer } = await load()+ const random = vi.spyOn(Math, 'random').mockReturnValue(0)+ render(<Layer hidden={false} fresh={false} />)+ act(() => { vi.advanceTimersByTime(20001) })+ const w = host.querySelector('.hw-witch')+ expect(w).not.toBeNull()+ act(() => { w.dispatchEvent(new Event('animationend', { bubbles: true })) })+ render(<Layer hidden />)+ render(<Layer hidden={false} fresh={false} />)+ act(() => { vi.advanceTimersByTime(120000) })+ expect(host.querySelector('.hw-witch')).toBeNull()+ random.mockRestore()+ })+})++describe('the pumpkin', () => {+ it('peeks out of its card; one tap a day says boo, buzzes, and leaves the card alone', async () => {+ const { Deco } = await load()+ const card = vi.fn()+ render(<div onClick={card}><Deco spot="home-streak" /></div>)+ const btn = () => host.querySelector('.hw-pumpkin')+ expect(btn().getAttribute('aria-hidden')).toBe('true')+ act(() => btn().click())+ expect(card).not.toHaveBeenCalled()+ expect(ui.toast).toHaveBeenCalledTimes(1)+ expect(ui.toast.mock.calls[0][0]).toMatch(/^Boo!/)+ expect(buzz.vibrate).toHaveBeenCalledTimes(1)+ expect(host.querySelector('.hw-burst')).not.toBeNull()+ act(() => btn().click())+ expect(ui.toast.mock.calls[1][0]).toBe('The pumpkin is napping. Come back tomorrow.')+ expect(buzz.vibrate).toHaveBeenCalledTimes(1)+ })++ it('with reduced motion the surprise is the toast alone, no bats flying out', async () => {+ reduce = true+ const { Deco } = await load()+ render(<Deco spot="home-streak" />)+ act(() => host.querySelector('.hw-pumpkin').click())+ expect(ui.toast).toHaveBeenCalledTimes(1)+ expect(host.querySelector('.hw-burst')).toBeNull()+ })+})++describe('the spots', () => {+ it('cobwebs and bats are decoration: hidden from assistive tech, never in a tap\'s way', async () => {+ const { Deco } = await load()+ render(<><Deco spot="home-hero" /><Deco spot="plan-card" /><Deco spot="header-bats" /><Deco spot="workout" /></>)+ const deco = [...host.children]+ expect(deco).toHaveLength(3) // an unknown spot draws nothing+ for (const el of deco) expect(el.getAttribute('aria-hidden')).toBe('true')+ expect(host.querySelectorAll('button')).toHaveLength(0)+ })+})diff --git a/frontend/src/views/Settings.themes.test.jsx b/frontend/src/views/Settings.themes.test.jsxnew file mode 100644index 000000000..4a1a31c1f--- /dev/null+++ b/frontend/src/views/Settings.themes.test.jsx@@ -0,0 +1,128 @@+// @vitest-environment happy-dom+// Settings → Look & Home → Seasonal themes (v1.4.3): Halloween's Auto / On / Off, its opt-in+// colours, and the line under it that says when it is back.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Settings from './Settings.jsx'+import { bindUI } from '../components/ui.jsx'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++const mocks = vi.hoisted(() => {+ const state = { S: null, MOBILE: false, user: null }+ state.snapshot = () => ({+ S: state.S,+ user: state.user,+ update: mut => {+ const next = structuredClone(state.S)+ mut(next)+ state.S = next+ },+ replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),+ signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),+ })+ return state+})+vi.mock('../store/useStore.js', () => {+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()+ useStore.getState = mocks.snapshot+ return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }+})+vi.mock('../store/useUI.js', () => {+ const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })+ const useUI = selector => selector ? selector(snap()) : snap()+ useUI.getState = snap+ return { useUI }+})+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))+vi.mock('../lib/api.js', () => ({+ api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,+}))+vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))+vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))+vi.mock('../lib/mobile.js', () => ({ get MOBILE() { return mocks.MOBILE }, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))+vi.mock('../sheets.jsx', () => ({+ loadStarterPlan: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),+}))++// The Settings view reads the build-time version constant at render time.+globalThis.__APP_VERSION__ ??= 'test'++// SelectRow opens its choices through the bound UI store; capture the sheet to render it here.+let sheet = null+bindUI({ getState: () => ({ openSheet: render => { sheet = render; return { close: () => {} } } }) })++let host, root+beforeEach(() => {+ sheet = null+ mocks.S = {+ unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',+ gifSize: 'full', workouts: [], routines: [], exWeights: {},+ }+ mocks.MOBILE = false+ mocks.user = null+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+})++const mount = (page = 'themes') => act(() => root.render(<Settings page={page} />))+const rowOf = title => [...host.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === title)+const pressed = () => [...rowOf('Halloween').querySelectorAll('.seg button')].find(b => b.getAttribute('aria-pressed') === 'true')?.textContent+const press = label => act(() => { [...rowOf('Halloween').querySelectorAll('.seg button')].find(b => b.textContent === label).click() })+const footer = () => host.querySelector('.sect-f')?.textContent+const at = (y, m, d) => { vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(y, m - 1, d, 12)) }+afterEach(() => vi.useRealTimers())++describe('Seasonal themes', () => {+ it('Look & Home opens the page, and names the theme that shows right now', () => {+ at(2026, 10, 25)+ mount('look')+ expect(rowOf('Seasonal themes').querySelector('.lrow-v').textContent).toBe('Halloween')+ act(() => root.unmount()); root = createRoot(host)+ at(2026, 11, 2)+ mount('look')+ expect(rowOf('Seasonal themes').querySelector('.lrow-v')).toBeNull()+ })++ it('reads as Auto when never chosen, in season says what it brings', () => {+ at(2026, 10, 25)+ mount()+ expect(pressed()).toBe('Auto')+ expect(footer()).toMatch(/^Spiders, bats and one shy pumpkin/)+ })++ it('out of season, Auto says it is back next October', () => {+ at(2027, 3, 14)+ mount()+ expect(footer()).toBe('Back next October. The spiders are on holiday.')+ })++ it('On and Off are stored with the profile, beside the colours', () => {+ at(2026, 10, 25)+ mocks.S.seasonal = { halloweenColors: true }+ mount()+ press('Off')+ expect(mocks.S.seasonal).toEqual({ halloween: 'off', halloweenColors: true })+ mount()+ expect(pressed()).toBe('Off')+ expect(footer()).toBe('Off, even in season. Fair enough.')+ press('On')+ expect(mocks.S.seasonal.halloween).toBe('on')+ })++ it('Spooky colors is off until switched on', () => {+ mount()+ const sw = rowOf('Spooky colors').querySelector('[role="switch"]')+ expect(sw.getAttribute('aria-checked')).toBe('false')+ act(() => sw.click())+ expect(mocks.S.seasonal).toEqual({ halloweenColors: true })+ })+})