chore+fix: repo hygiene, code-review fixes, audit cleanup
Three independent code reviews + a security audit produced ~200 findings.
This commit lands the high-impact subset. Tests pass (53), typecheck
clean, eslint clean (3 minor exhaustive-deps warnings left).
REPO HYGIENE
- Add .editorconfig, .prettierrc.json, .prettierignore.
- Add ESLint flat config (.eslintrc.cjs) — correctness-focused, no style
rules (Prettier owns formatting).
- Add `format` / `format:check` / `lint` npm scripts.
- Add CHANGELOG.md (Keep a Changelog format, back-filled to 0.1.x).
- Reformat all source via Prettier so future diffs stay small.
DATA SAFETY (src/main/store.ts)
- Atomic write (tmp + rename) with retry on transient EBUSY/EPERM —
was non-atomic writeFileSync, vulnerable to truncation on power loss.
- On corrupt JSON, rename to `app-state.json.corrupt-<ts>` instead of
silently overwriting the user's exercises/history with defaults.
- Validate parsed shape before merging — reject arrays/scalars where
objects expected; per-field array checks.
- Strip `id` from incoming patches in updateExercise/updateChallenge —
a runtime caller (IPC) could otherwise smuggle id changes through.
- clearHistory now refuses an unbounded wipe (no beforeTs => no-op);
callers must pass an explicit boundary.
- unref() the debounce timer so it doesn't keep the event loop alive.
SECURITY (src/main/*)
- gsi-server: hard 256 KB body cap (was unbounded — local OOM vector),
reject any Origin/Sec-Fetch-Site header (blocks browser CSRF from
visited pages), require application/json Content-Type, generic 400
on parse error (no error string echo to client), closeAllConnections
+ async close on stop.
- dota2: validate auth.token from payload with timingSafeEqual against
the per-install token — was unauthenticated, any local process could
forge match-end events. Narrow object shape before spread-merge to
avoid throws on hostile payloads like {player:"x"}. Reset latest /
prevState after match_end so the next match starts clean.
- ipc: gate `dev:simulateMatchEnd` registration behind `!app.isPackaged`
so it does not exist in shipped builds.
- preload: gate the matching `simulateMatchEnd` export behind
`import.meta.env.MODE !== 'production'` so the bundler dead-code-
eliminates it from the production preload bundle.
- windows: shell.openExternal allowlist (http/https/mailto only) — was
forwarding any URL, including file:/javascript:/custom URI handlers
(some Windows handlers have been RCE vectors). will-navigate blocks
navigation to anywhere except file:// or the dev URL.
CORRECTNESS (src/main/* + src/shared/*)
- shared/types.ts isQuietAt: fix wrap-around + day-of-week filter.
With from=22:00 to=07:00 days=[Mon..Fri], the window started THE
PREVIOUS DAY when we're in the AM half — old code checked today's
day-of-week and got the wrong answer Sat 02:00 and Mon 01:00. Now
the filter is evaluated against the window's START day. Also reject
malformed HH:MM strings instead of producing NaN.
- scheduler: call broadcastState() after firing exercises so the
renderer's Dashboard/Exercises pages don't show stale nextFireAt
until the next state-changing IPC. Guard powerMonitor listeners
against double-registration on dev hot-reload.
- dota2: fix `launchOptionStatus = steamRunning ? 'queued' : 'queued'`
tautology — both branches now correctly read 'queued'.
- steam-launch-options: replace `require('node:fs')` inside atomicWrite
with the top-level import; retry on transient EBUSY/EPERM.
CORRECTNESS (src/renderer/*)
- lib/history.ts: replace `today.getTime() - i * MS_DAY` arithmetic
with `setDate(date - i)` calendar arithmetic in dailyRepsRange and
currentStreak — DST transitions shift epoch math by ±1h and cause
dayKey() to emit duplicate or missing days at the boundary.
- lib/icon.tsx: restrict name lookup to ICON_CHOICES set — an arbitrary
string from a corrupted state file could otherwise resolve to
unrelated Lucide exports and crash the renderer.
- lib/format.ts: guard formatCountdown against NaN/Infinity.
- i18n/index.ts: replace regex-based interpolation with split/join so
variable values containing regex metacharacters interpolate
literally; warn in dev on missing keys; clamp pluralRu(-N) via abs.
- ReminderApp: keyboard shortcuts moved INTO ExerciseReminder so Enter
respects the stepper's `adjusted` flag (was always passing planned
reps). Stepper capped at 5× planned. Don't hijack Space when a
button is focused. `key={exercise.id+nextFireAt}` forces a fresh
component for back-to-back reminders so stepper state resets. Match
summary view gets Esc-to-close. Functional setMode in onMarkDone
avoids races against stale `mode.done`.
- UpdaterCard: guard against NaN/Infinity in download-progress events
(electron-updater fires early events with undefined fields).
- Games: gate DevPanel behind `import.meta.env.DEV` in addition to the
main-side IPC gate, and narrow the `simulateMatchEnd` access.
- Add aria-labels for the +/- stepper buttons (i18n keys added).
TESTS
- +2 quiet-hours tests covering wrap-around + day-filter combo and
malformed HH:MM fallback. Total 53 passing.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -54,24 +54,16 @@ export default function ReminderApp(): JSX.Element {
|
||||
}
|
||||
}, [])
|
||||
|
||||
// ESC closes the match summary view too — keyboard parity with exercise mode.
|
||||
useEffect(() => {
|
||||
if (mode.kind !== 'exercise') return
|
||||
const ex = mode.exercise
|
||||
const snoozeMin = settings?.snoozeMinutes ?? 5
|
||||
if (mode.kind !== 'match') return
|
||||
function onKey(e: KeyboardEvent): void {
|
||||
if (e.key === 'Enter') {
|
||||
window.api.markDone(ex.id).then(close)
|
||||
} else if (e.key === ' ' || e.code === 'Space') {
|
||||
e.preventDefault()
|
||||
window.api.snooze(ex.id, snoozeMin).then(close)
|
||||
} else if (e.key === 'Escape') {
|
||||
window.api.skip(ex.id).then(close)
|
||||
}
|
||||
if (e.key === 'Escape') close()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [mode, settings?.snoozeMinutes])
|
||||
}, [mode.kind])
|
||||
|
||||
function close(): void {
|
||||
setMode({ kind: 'idle' })
|
||||
@@ -83,7 +75,10 @@ export default function ReminderApp(): JSX.Element {
|
||||
if (mode.kind === 'idle') return <div className="reminder-shell" />
|
||||
if (mode.kind === 'exercise') {
|
||||
return (
|
||||
// key={exercise.id} forces a fresh component (and fresh stepper state)
|
||||
// when a new reminder arrives while the previous modal is still open.
|
||||
<ExerciseReminder
|
||||
key={mode.exercise.id + ':' + mode.exercise.nextFireAt}
|
||||
exercise={mode.exercise}
|
||||
snoozeMinutes={settings?.snoozeMinutes ?? 5}
|
||||
lang={lang}
|
||||
@@ -97,11 +92,17 @@ export default function ReminderApp(): JSX.Element {
|
||||
done={mode.done}
|
||||
lang={lang}
|
||||
onMarkDone={(id) =>
|
||||
setMode({
|
||||
kind: 'match',
|
||||
summary: mode.summary,
|
||||
done: new Set([...mode.done, id])
|
||||
})
|
||||
// Functional update so a second rapid click can't race against a stale
|
||||
// `mode.done` captured in this closure.
|
||||
setMode((m) =>
|
||||
m.kind === 'match'
|
||||
? {
|
||||
kind: 'match',
|
||||
summary: m.summary,
|
||||
done: new Set([...m.done, id])
|
||||
}
|
||||
: m
|
||||
)
|
||||
}
|
||||
onClose={close}
|
||||
/>
|
||||
@@ -124,14 +125,13 @@ function ExerciseReminder({
|
||||
|
||||
const [actualReps, setActualReps] = useState(exercise.reps)
|
||||
const adjusted = actualReps !== exercise.reps
|
||||
// Cap the stepper at 5× planned so a stuck "+" button can't log nonsense.
|
||||
const REP_CAP = Math.max(50, exercise.reps * 5)
|
||||
|
||||
async function done(): Promise<void> {
|
||||
// Only pass actualReps when user adjusted — otherwise leave undefined
|
||||
// so history records the full planned value cleanly.
|
||||
await window.api.markDone(
|
||||
exercise.id,
|
||||
adjusted ? actualReps : undefined
|
||||
)
|
||||
await window.api.markDone(exercise.id, adjusted ? actualReps : undefined)
|
||||
onClose()
|
||||
}
|
||||
async function snooze(): Promise<void> {
|
||||
@@ -143,7 +143,38 @@ function ExerciseReminder({
|
||||
onClose()
|
||||
}
|
||||
const dec = (): void => setActualReps((n) => Math.max(0, n - 1))
|
||||
const inc = (): void => setActualReps((n) => n + 1)
|
||||
const inc = (): void => setActualReps((n) => Math.min(REP_CAP, n + 1))
|
||||
|
||||
// Keyboard shortcuts live INSIDE the component so they have access to the
|
||||
// current `actualReps` — pressing Enter respects the stepper's adjustment.
|
||||
useEffect(() => {
|
||||
function onKey(e: KeyboardEvent): void {
|
||||
// Don't hijack Space when a button is focused (default activation).
|
||||
const targetTag = (e.target as HTMLElement | null)?.tagName
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
void done()
|
||||
} else if (
|
||||
(e.key === ' ' || e.code === 'Space') &&
|
||||
targetTag !== 'BUTTON'
|
||||
) {
|
||||
e.preventDefault()
|
||||
void snooze()
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
void skip()
|
||||
} else if (e.key === 'ArrowUp' || e.key === '+') {
|
||||
e.preventDefault()
|
||||
inc()
|
||||
} else if (e.key === 'ArrowDown' || e.key === '-') {
|
||||
e.preventDefault()
|
||||
dec()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [actualReps, snoozeMinutes])
|
||||
|
||||
return (
|
||||
<div className="reminder-shell flex flex-col h-full">
|
||||
@@ -181,7 +212,7 @@ function ExerciseReminder({
|
||||
<button
|
||||
onClick={dec}
|
||||
className="w-9 h-9 grid place-items-center rounded-full bg-surface-2 text-text/65 hover:text-text hover:bg-hairline/25 active:scale-90 transition-all"
|
||||
aria-label="−"
|
||||
aria-label={t('reminder.aria.decrement')}
|
||||
>
|
||||
<Minus size={16} strokeWidth={2.5} />
|
||||
</button>
|
||||
@@ -201,14 +232,17 @@ function ExerciseReminder({
|
||||
<button
|
||||
onClick={inc}
|
||||
className="w-9 h-9 grid place-items-center rounded-full bg-surface-2 text-text/65 hover:text-text hover:bg-hairline/25 active:scale-90 transition-all"
|
||||
aria-label="+"
|
||||
aria-label={t('reminder.aria.increment')}
|
||||
>
|
||||
<Plus size={16} strokeWidth={2.5} />
|
||||
</button>
|
||||
</div>
|
||||
{adjusted && (
|
||||
<div className="text-[12px] text-accent mt-2 font-medium">
|
||||
{t('reminder.partial', { actual: actualReps, planned: exercise.reps })}
|
||||
{t('reminder.partial', {
|
||||
actual: actualReps,
|
||||
planned: exercise.reps
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -320,7 +354,8 @@ function MatchSummaryView({
|
||||
<p className="text-[13px] text-text/65 mt-1.5 font-medium">
|
||||
<span className="font-mono-num font-bold text-text">{minutes}</span>{' '}
|
||||
{t('fmt.m')} ·{' '}
|
||||
{tn('match.summary.challenges', summary.results.length)}{' · '}
|
||||
{tn('match.summary.challenges', summary.results.length)}
|
||||
{' · '}
|
||||
{allDone ? (
|
||||
<span className="text-success font-bold">
|
||||
{t('match.summary.all_done')}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Check, MoreHorizontal } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import type { Exercise, Tick } from '@shared/types'
|
||||
import { Icon } from '../lib/icon'
|
||||
import { formatCountdown, formatInterval } from '../lib/format'
|
||||
import { formatCountdown } from '../lib/format'
|
||||
import { Switch } from './ui/Switch'
|
||||
import { useT } from '../i18n'
|
||||
|
||||
@@ -78,9 +78,7 @@ export function ExerciseCard({
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={C}
|
||||
strokeDashoffset={dashOffset}
|
||||
className={
|
||||
isDue ? 'stroke-accent' : 'stroke-accent/85'
|
||||
}
|
||||
className={isDue ? 'stroke-accent' : 'stroke-accent/85'}
|
||||
style={{ transition: 'stroke-dashoffset 0.5s linear' }}
|
||||
/>
|
||||
)}
|
||||
@@ -159,9 +157,7 @@ export function ExerciseCard({
|
||||
isDue ? 'text-accent' : 'text-text'
|
||||
].join(' ')}
|
||||
>
|
||||
{exercise.enabled
|
||||
? formatCountdown(ms, lang)
|
||||
: t('fmt.paused')}
|
||||
{exercise.enabled ? formatCountdown(ms, lang) : t('fmt.paused')}
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
|
||||
@@ -83,7 +83,9 @@ export function HistoryHeatmap({
|
||||
<div className="bg-surface rounded-2xl p-5 shadow-card dark:ring-0.5 dark:ring-hairline/30">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<div className="text-[14px] text-text/75 font-semibold">
|
||||
{lang === 'en' ? 'Activity, last 12 weeks' : 'Активность за 12 недель'}
|
||||
{lang === 'en'
|
||||
? 'Activity, last 12 weeks'
|
||||
: 'Активность за 12 недель'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -115,9 +117,7 @@ export function HistoryHeatmap({
|
||||
<div key={wi} className="flex flex-col gap-[3px]">
|
||||
{w.map((c, di) => {
|
||||
if (!c) {
|
||||
return (
|
||||
<div key={di} className="w-[12px] h-[12px]" />
|
||||
)
|
||||
return <div key={di} className="w-[12px] h-[12px]" />
|
||||
}
|
||||
const b = bucket(c.reps)
|
||||
const tone =
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import {
|
||||
Sun,
|
||||
Dumbbell,
|
||||
Joystick,
|
||||
Flame,
|
||||
Settings2,
|
||||
X
|
||||
} from 'lucide-react'
|
||||
import { Sun, Dumbbell, Joystick, Flame, Settings2, X } from 'lucide-react'
|
||||
import { useT } from '../i18n'
|
||||
|
||||
type Item = {
|
||||
|
||||
@@ -94,11 +94,7 @@ function Body({
|
||||
<Cell
|
||||
tone="info"
|
||||
icon={
|
||||
<RefreshCw
|
||||
size={16}
|
||||
strokeWidth={2.4}
|
||||
className="animate-spin"
|
||||
/>
|
||||
<RefreshCw size={16} strokeWidth={2.4} className="animate-spin" />
|
||||
}
|
||||
title={t('updater.checking')}
|
||||
/>
|
||||
@@ -145,8 +141,16 @@ function Body({
|
||||
)
|
||||
}
|
||||
if (status.kind === 'downloading') {
|
||||
const pct = Math.max(0, Math.min(100, status.percent || 0))
|
||||
const mb = (n: number): string => (n / 1024 / 1024).toFixed(1)
|
||||
// electron-updater fires early `download-progress` events where some
|
||||
// fields are undefined; guard against NaN/Infinity so we never render
|
||||
// "NaN%" or "NaN MB/s".
|
||||
const rawPct = Number.isFinite(status.percent) ? status.percent : 0
|
||||
const pct = Math.max(0, Math.min(100, rawPct))
|
||||
const mb = (n: number): string =>
|
||||
Number.isFinite(n) ? (n / 1024 / 1024).toFixed(1) : '0.0'
|
||||
const speed = Number.isFinite(status.bytesPerSecond)
|
||||
? (status.bytesPerSecond / 1024 / 1024).toFixed(2)
|
||||
: '0.00'
|
||||
return (
|
||||
<div className="px-4 py-4">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
@@ -161,7 +165,7 @@ function Body({
|
||||
{t('updater.downloading.subtitle', {
|
||||
got: mb(status.transferred),
|
||||
total: mb(status.total),
|
||||
speed: (status.bytesPerSecond / 1024 / 1024).toFixed(2)
|
||||
speed
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -24,15 +24,13 @@ const legacyMap: Record<LegacyVariant, Variant> = {
|
||||
}
|
||||
|
||||
const variantClasses: Record<Variant, string> = {
|
||||
filled:
|
||||
'bg-accent text-white hover:brightness-105 active:brightness-95',
|
||||
filled: 'bg-accent text-white hover:brightness-105 active:brightness-95',
|
||||
tinted:
|
||||
'bg-accent/12 text-accent hover:bg-accent/18 active:bg-accent/22 dark:bg-accent/20 dark:hover:bg-accent/25',
|
||||
plain: 'text-accent hover:bg-accent/10 active:bg-accent/15',
|
||||
destructive:
|
||||
'bg-destructive/12 text-destructive hover:bg-destructive/18 active:bg-destructive/22 dark:bg-destructive/20',
|
||||
success:
|
||||
'bg-success text-white hover:brightness-105 active:brightness-95'
|
||||
success: 'bg-success text-white hover:brightness-105 active:brightness-95'
|
||||
}
|
||||
|
||||
const sizeClasses: Record<Size, string> = {
|
||||
|
||||
@@ -116,8 +116,7 @@ export const ru: Dict = {
|
||||
// Games
|
||||
'games.kicker': 'Трекинг матчей',
|
||||
'games.title': 'Игры',
|
||||
'games.subtitle':
|
||||
'Подключи игру — челленджи сработают сразу после матча',
|
||||
'games.subtitle': 'Подключи игру — челленджи сработают сразу после матча',
|
||||
'games.subtitle.live': '{n} live',
|
||||
'games.section.supported': 'Поддерживаемые',
|
||||
'games.scanning': 'Сканируем установленные игры…',
|
||||
@@ -205,6 +204,8 @@ export const ru: Dict = {
|
||||
'reminder.reps': 'раз',
|
||||
'reminder.next_in': 'Следующее через {interval}',
|
||||
'reminder.partial': 'Засчитаем {actual} из {planned}',
|
||||
'reminder.aria.decrement': 'Уменьшить количество повторов',
|
||||
'reminder.aria.increment': 'Увеличить количество повторов',
|
||||
'reminder.btn.done': 'Готово',
|
||||
'match.title.won': 'Победа',
|
||||
'match.title.lost': 'Поражение',
|
||||
@@ -423,6 +424,8 @@ export const en: Dict = {
|
||||
'reminder.reps': 'reps',
|
||||
'reminder.next_in': 'Next in {interval}',
|
||||
'reminder.partial': "We'll log {actual} of {planned}",
|
||||
'reminder.aria.decrement': 'Decrease rep count',
|
||||
'reminder.aria.increment': 'Increase rep count',
|
||||
'reminder.btn.done': 'Done',
|
||||
'match.title.won': 'Victory',
|
||||
'match.title.lost': 'Defeat',
|
||||
|
||||
@@ -14,17 +14,25 @@ export type TFn = (key: string, vars?: TVars) => string
|
||||
/**
|
||||
* Look up a key in the dictionary, substitute `{var}` placeholders.
|
||||
* Returns the key itself if not found — surfaces missing translations.
|
||||
*
|
||||
* Substitution is done by string split/join rather than a regex so that
|
||||
* variable values containing regex metacharacters (e.g. a user-supplied
|
||||
* exercise name with `$1` or `.*`) are interpolated literally.
|
||||
*/
|
||||
export function translate(
|
||||
lang: Language,
|
||||
key: string,
|
||||
vars?: TVars
|
||||
): string {
|
||||
export function translate(lang: Language, key: string, vars?: TVars): string {
|
||||
const dict = getDict(lang)
|
||||
let s = dict[key] ?? key
|
||||
let s = dict[key]
|
||||
if (s === undefined) {
|
||||
// Surface missing translations in dev; in prod render the key so the user
|
||||
// sees something deterministic instead of a blank.
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`[i18n] missing key "${key}" for lang "${lang}"`)
|
||||
}
|
||||
s = key
|
||||
}
|
||||
if (vars) {
|
||||
for (const k of Object.keys(vars)) {
|
||||
s = s.replace(new RegExp(`\\{${k}\\}`, 'g'), String(vars[k]))
|
||||
s = s.split(`{${k}}`).join(String(vars[k]))
|
||||
}
|
||||
}
|
||||
return s
|
||||
@@ -37,8 +45,10 @@ export function translate(
|
||||
* many → 0, 5-20, 25-30…
|
||||
*/
|
||||
function pluralRu(n: number): 'one' | 'few' | 'many' {
|
||||
const mod10 = n % 10
|
||||
const mod100 = n % 100
|
||||
// Always pluralize on the absolute value — a "-1" count is the same form as "1".
|
||||
const abs = Math.abs(Math.trunc(n))
|
||||
const mod10 = abs % 10
|
||||
const mod100 = abs % 100
|
||||
if (mod10 === 1 && mod100 !== 11) return 'one'
|
||||
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 >= 20)) return 'few'
|
||||
return 'many'
|
||||
@@ -55,12 +65,7 @@ export function translateN(
|
||||
n: number,
|
||||
vars?: TVars
|
||||
): string {
|
||||
const form =
|
||||
lang === 'ru'
|
||||
? pluralRu(n)
|
||||
: n === 1
|
||||
? 'one'
|
||||
: 'many'
|
||||
const form = lang === 'ru' ? pluralRu(n) : n === 1 ? 'one' : 'many'
|
||||
return translate(lang, `${keyBase}_${form}`, { n, ...vars })
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ const SUFFIX = {
|
||||
|
||||
export function formatCountdown(ms: number, lang: Language = 'ru'): string {
|
||||
const s = SUFFIX[lang] ?? SUFFIX.ru
|
||||
if (ms <= 0) return s.now
|
||||
if (!Number.isFinite(ms) || ms <= 0) return s.now
|
||||
const totalSec = Math.floor(ms / 1000)
|
||||
const h = Math.floor(totalSec / 3600)
|
||||
const m = Math.floor((totalSec % 3600) / 60)
|
||||
@@ -17,10 +17,7 @@ export function formatCountdown(ms: number, lang: Language = 'ru'): string {
|
||||
return `${sec}${s.s}`
|
||||
}
|
||||
|
||||
export function formatInterval(
|
||||
minutes: number,
|
||||
lang: Language = 'ru'
|
||||
): string {
|
||||
export function formatInterval(minutes: number, lang: Language = 'ru'): string {
|
||||
const s = SUFFIX[lang] ?? SUFFIX.ru
|
||||
if (minutes < 60) return `${minutes} ${s.minLong}`
|
||||
const h = Math.floor(minutes / 60)
|
||||
|
||||
@@ -94,19 +94,12 @@ describe('currentStreak', () => {
|
||||
})
|
||||
|
||||
it('ignores skip and snooze', () => {
|
||||
const hist = [
|
||||
entry('a', day(0), 'skip'),
|
||||
entry('a', day(1), 'snooze')
|
||||
]
|
||||
const hist = [entry('a', day(0), 'skip'), entry('a', day(1), 'snooze')]
|
||||
expect(currentStreak(hist)).toBe(0)
|
||||
})
|
||||
|
||||
it('multiple entries same day count once', () => {
|
||||
const hist = [
|
||||
entry('a', day(0)),
|
||||
entry('b', day(0)),
|
||||
entry('a', day(1))
|
||||
]
|
||||
const hist = [entry('a', day(0)), entry('b', day(0)), entry('a', day(1))]
|
||||
expect(currentStreak(hist)).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import type { Exercise, HistoryEntry } from '@shared/types'
|
||||
|
||||
const MS_DAY = 24 * 60 * 60 * 1000
|
||||
|
||||
/** YYYY-MM-DD in local time. */
|
||||
export function dayKey(ts: number): string {
|
||||
const d = new Date(ts)
|
||||
@@ -16,6 +14,18 @@ export function todayKey(): string {
|
||||
return dayKey(Date.now())
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new Date offset by `dayDelta` calendar days from `base`, with the
|
||||
* time-of-day preserved. Uses `setDate` (calendar arithmetic) rather than
|
||||
* subtracting `n * 24h` of milliseconds — across DST transitions ms arithmetic
|
||||
* drifts by ±1h and `dayKey` can emit the wrong day.
|
||||
*/
|
||||
function shiftDays(base: Date, dayDelta: number): Date {
|
||||
const d = new Date(base.getTime())
|
||||
d.setDate(d.getDate() + dayDelta)
|
||||
return d
|
||||
}
|
||||
|
||||
/**
|
||||
* Reps logged on a given local day. Uses `actualReps` if present, otherwise
|
||||
* looks up exercise's planned `reps`.
|
||||
@@ -46,28 +56,27 @@ export function dailyRepsRange(
|
||||
): { key: string; date: Date; reps: number }[] {
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const buckets = new Map<string, number>()
|
||||
const buckets = new Map<string, { date: Date; reps: number }>()
|
||||
const byId = new Map(exercises.map((e) => [e.id, e]))
|
||||
|
||||
// Seed all days with 0 so heatmap renders contiguous.
|
||||
// Seed all days with 0 so heatmap renders contiguous. Use calendar arithmetic
|
||||
// (setDate) — DST transitions would shift epoch-based math by ±1h, causing
|
||||
// dayKey() to emit duplicate or missing days at the boundary.
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
const d = new Date(today.getTime() - i * MS_DAY)
|
||||
buckets.set(dayKey(d.getTime()), 0)
|
||||
const d = shiftDays(today, -i)
|
||||
buckets.set(dayKey(d.getTime()), { date: d, reps: 0 })
|
||||
}
|
||||
|
||||
for (const e of entries) {
|
||||
if (e.action !== 'done') continue
|
||||
const k = dayKey(e.ts)
|
||||
if (!buckets.has(k)) continue
|
||||
const bucket = buckets.get(k)
|
||||
if (!bucket) continue
|
||||
const reps = e.actualReps ?? byId.get(e.exerciseId)?.reps ?? 0
|
||||
buckets.set(k, (buckets.get(k) ?? 0) + reps)
|
||||
bucket.reps += reps
|
||||
}
|
||||
|
||||
return Array.from(buckets, ([key, reps]) => ({
|
||||
key,
|
||||
date: new Date(`${key}T00:00:00`),
|
||||
reps
|
||||
}))
|
||||
return Array.from(buckets, ([key, { date, reps }]) => ({ key, date, reps }))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -84,21 +93,22 @@ export function currentStreak(entries: HistoryEntry[]): number {
|
||||
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const yesterday = shiftDays(today, -1)
|
||||
const todayK = dayKey(today.getTime())
|
||||
const yesterdayK = dayKey(today.getTime() - MS_DAY)
|
||||
const yesterdayK = dayKey(yesterday.getTime())
|
||||
|
||||
// Start from today if active today, else yesterday (grace), else 0.
|
||||
let cursor = doneDays.has(todayK)
|
||||
let cursor: Date | null = doneDays.has(todayK)
|
||||
? today
|
||||
: doneDays.has(yesterdayK)
|
||||
? new Date(today.getTime() - MS_DAY)
|
||||
? yesterday
|
||||
: null
|
||||
if (!cursor) return 0
|
||||
|
||||
let streak = 0
|
||||
while (doneDays.has(dayKey(cursor.getTime()))) {
|
||||
streak++
|
||||
cursor = new Date(cursor.getTime() - MS_DAY)
|
||||
cursor = shiftDays(cursor, -1)
|
||||
}
|
||||
return streak
|
||||
}
|
||||
|
||||
@@ -24,13 +24,27 @@ export const ICON_CHOICES = [
|
||||
|
||||
export type IconName = (typeof ICON_CHOICES)[number]
|
||||
|
||||
const ICON_SET = new Set<string>(ICON_CHOICES)
|
||||
|
||||
/**
|
||||
* Render a Lucide icon by name. Restricted to the curated ICON_CHOICES set —
|
||||
* an arbitrary string from a corrupted state file could otherwise resolve to
|
||||
* unrelated Lucide exports (`default`, `createLucideIcon`, etc.) and crash
|
||||
* the renderer.
|
||||
*/
|
||||
export function Icon({
|
||||
name,
|
||||
...props
|
||||
}: { name: string } & LucideProps): JSX.Element {
|
||||
const Cmp = (Lucide as unknown as Record<string, React.ComponentType<LucideProps>>)[
|
||||
name
|
||||
]
|
||||
if (!ICON_SET.has(name)) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`[Icon] unknown icon name "${name}" — falling back`)
|
||||
}
|
||||
return <Lucide.Activity {...props} />
|
||||
}
|
||||
const Cmp = (
|
||||
Lucide as unknown as Record<string, React.ComponentType<LucideProps>>
|
||||
)[name]
|
||||
if (!Cmp) return <Lucide.Activity {...props} />
|
||||
return <Cmp {...props} />
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ const which = params.get('window') ?? 'main'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<ThemeProvider>{which === 'reminder' ? <ReminderApp /> : <App />}</ThemeProvider>
|
||||
<ThemeProvider>
|
||||
{which === 'reminder' ? <ReminderApp /> : <App />}
|
||||
</ThemeProvider>
|
||||
</React.StrictMode>
|
||||
)
|
||||
|
||||
@@ -130,9 +130,7 @@ function ExerciseRow({
|
||||
<div
|
||||
className={[
|
||||
'w-9 h-9 rounded-lg grid place-items-center shrink-0',
|
||||
exercise.enabled
|
||||
? 'bg-accent text-white'
|
||||
: 'bg-text/15 text-text/45'
|
||||
exercise.enabled ? 'bg-accent text-white' : 'bg-text/15 text-text/45'
|
||||
].join(' ')}
|
||||
>
|
||||
<Icon name={exercise.icon} size={18} strokeWidth={2.2} />
|
||||
|
||||
@@ -54,9 +54,7 @@ export default function GamesPage(): JSX.Element {
|
||||
}
|
||||
}
|
||||
|
||||
const liveCount = games.filter(
|
||||
(g) => g.enabled && g.integrationActive
|
||||
).length
|
||||
const liveCount = games.filter((g) => g.enabled && g.integrationActive).length
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-y-auto">
|
||||
@@ -170,11 +168,7 @@ function GameCard({
|
||||
</div>
|
||||
</div>
|
||||
{game.installed && game.integrationActive && (
|
||||
<Switch
|
||||
checked={game.enabled}
|
||||
onChange={onToggle}
|
||||
disabled={busy}
|
||||
/>
|
||||
<Switch checked={game.enabled} onChange={onToggle} disabled={busy} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -280,8 +274,16 @@ function StatusBadge({
|
||||
function DevPanel({ games }: { games: GameStatus[] }): JSX.Element | null {
|
||||
const [open, setOpen] = useState(false)
|
||||
const { t } = useT()
|
||||
// Never render in packaged builds — the matching IPC handler is also
|
||||
// unregistered there, so the buttons would do nothing anyway.
|
||||
if (!import.meta.env.DEV) return null
|
||||
const dota = games.find((g) => g.id === 'dota2')
|
||||
if (!dota?.enabled) return null
|
||||
// In dev the preload exposes window.api.simulateMatchEnd; the conditional
|
||||
// type still hides it, so we narrow here.
|
||||
const api = window.api as typeof window.api & {
|
||||
simulateMatchEnd?: (id: 'dota2', stats: Record<string, number>) => void
|
||||
}
|
||||
return (
|
||||
<div className="mt-10">
|
||||
<button
|
||||
@@ -305,7 +307,7 @@ function DevPanel({ games }: { games: GameStatus[] }): JSX.Element | null {
|
||||
).map((p) => (
|
||||
<button
|
||||
key={p.label}
|
||||
onClick={() => window.api.simulateMatchEnd('dota2', p.stats)}
|
||||
onClick={() => api.simulateMatchEnd?.('dota2', p.stats)}
|
||||
className="text-[12px] px-3 py-1.5 rounded-full bg-surface-2 hover:bg-accent/15 hover:text-accent text-text/70 font-medium transition-colors active:scale-95"
|
||||
>
|
||||
{p.label}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { ReactNode, useEffect, useState } from 'react'
|
||||
import { useAppStore } from '../store/appStore'
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }): JSX.Element {
|
||||
export function ThemeProvider({
|
||||
children
|
||||
}: {
|
||||
children: ReactNode
|
||||
}): JSX.Element {
|
||||
const settings = useAppStore((s) => s.state?.settings)
|
||||
const [osTheme, setOsTheme] = useState<'light' | 'dark'>('dark')
|
||||
|
||||
|
||||
@@ -31,7 +31,9 @@ export const useAppStore = create<Store>((set) => ({
|
||||
export function subscribeToBackend(): () => void {
|
||||
const store = useAppStore.getState()
|
||||
store.hydrate()
|
||||
const u1 = window.api.onStateChanged((s) => useAppStore.getState().setState(s))
|
||||
const u1 = window.api.onStateChanged((s) =>
|
||||
useAppStore.getState().setState(s)
|
||||
)
|
||||
const u2 = window.api.onTick((t) => useAppStore.getState().setTicks(t))
|
||||
return () => {
|
||||
u1()
|
||||
|
||||
@@ -6,22 +6,22 @@
|
||||
|
||||
:root {
|
||||
/* Brand & semantic colors (iOS system palette) */
|
||||
--accent: 255 107 53; /* Apple Fitness Move orange */
|
||||
--accent-2: 255 45 85; /* systemPink */
|
||||
--success: 52 199 89; /* systemGreen */
|
||||
--warning: 255 159 10; /* systemOrange dark */
|
||||
--destructive: 255 59 48; /* systemRed */
|
||||
--info: 0 122 255; /* systemBlue */
|
||||
--accent: 255 107 53; /* Apple Fitness Move orange */
|
||||
--accent-2: 255 45 85; /* systemPink */
|
||||
--success: 52 199 89; /* systemGreen */
|
||||
--warning: 255 159 10; /* systemOrange dark */
|
||||
--destructive: 255 59 48; /* systemRed */
|
||||
--info: 0 122 255; /* systemBlue */
|
||||
|
||||
color-scheme: light dark;
|
||||
}
|
||||
|
||||
/* Light — polished iOS groupedBackground with warm undertone */
|
||||
:root {
|
||||
--bg: 245 245 249; /* slightly warmer than 242,242,247 */
|
||||
--bg: 245 245 249; /* slightly warmer than 242,242,247 */
|
||||
--surface: 255 255 255;
|
||||
--surface-2: 240 240 245; /* subtle separation for inputs/sections */
|
||||
--text: 17 17 19; /* not pure black — softer */
|
||||
--surface-2: 240 240 245; /* subtle separation for inputs/sections */
|
||||
--text: 17 17 19; /* not pure black — softer */
|
||||
--text-secondary: 60 60 67;
|
||||
--text-tertiary: 60 60 67;
|
||||
--hairline: 60 60 67;
|
||||
@@ -114,8 +114,8 @@ body {
|
||||
}
|
||||
|
||||
.font-mono-num {
|
||||
font-family: 'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code',
|
||||
Menlo, monospace;
|
||||
font-family:
|
||||
'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-feature-settings: 'ss02', 'ss19', 'zero';
|
||||
letter-spacing: -0.01em;
|
||||
|
||||
Reference in New Issue
Block a user