Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77007636df | ||
|
|
433493773d | ||
|
|
5a9ec04ba8 | ||
|
|
a0b89ddf71 | ||
|
|
81481f2131 | ||
|
|
a6ae931461 | ||
|
|
9e59be9cba | ||
|
|
68998607e8 | ||
|
|
50c56fec79 | ||
|
|
72e54c579d | ||
|
|
fd62177375 | ||
|
|
0a753ad4c7 | ||
|
|
34fb03b265 | ||
|
|
e7ccca98e7 | ||
|
|
4745f5e091 | ||
|
|
a41dce511b | ||
|
|
9378cabfe5 | ||
|
|
c735659567 | ||
|
|
c5c05ee651 | ||
|
|
36085f225f |
147
CHANGELOG.md
147
CHANGELOG.md
@@ -6,6 +6,148 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.5.6] — 2026-05-22
|
||||
|
||||
Большой релиз с 7 новыми фичами + экран «Что нового», который покажется
|
||||
автоматически после установки этой версии.
|
||||
|
||||
### Added
|
||||
|
||||
- **Категории напоминаний** (#7) — кроме упражнений теперь
|
||||
hydration / eye-rest (20-20-20) / posture. Каждая со своим CTA в
|
||||
окне напоминания. В SAMPLE добавлены примеры.
|
||||
- **TTS-голосовые подсказки** (#8) — диктор произносит название
|
||||
упражнения и количество. Opt-in в Settings → «Голосовая подсказка».
|
||||
Web Speech API: подбор голоса под язык (ru-RU / en-US).
|
||||
- **Достижения** (#10) — milestones по total reps (100/500/1000/5k/10k),
|
||||
streaks (3/7/14/30/100 дней), first_day, today_quad. На Dashboard
|
||||
карточка с unlocked + 2 ближайших по прогрессу. Прогресс-бар до
|
||||
следующего достижения.
|
||||
- **Дневная цель** (#12) — soft cap reps/день в exercise editor.
|
||||
Когда total reps за сегодня (с actualReps) ≥ dailyGoal → scheduler
|
||||
переносит fire на завтра. История = source of truth.
|
||||
- **Авто-пауза на ВКС** (#5) — сканирует процессы tasklist'ом раз в
|
||||
30с: Zoom/Teams (старый+new)/Discord/Webex/Slack/Skype/Meet/Whereby/
|
||||
GoToMeeting. Если запущен — fires не выполняются.
|
||||
- **Адаптивный шедулер** (#2) — opt-in флаг в exercise editor.
|
||||
Heuristic-модель строит hour-of-day success rate по 30 дням истории
|
||||
(≥10 событий обязательно). При попадании fire в «плохой» час
|
||||
(success ≤ 30%) сдвигает на ближайший «хороший» (≥50%), в пределах
|
||||
4 часов.
|
||||
- **Export / Import** (#9) — Settings → Data. Native save/open
|
||||
dialogs Electron. JSON-snapshot всего persisted-state (включая
|
||||
историю). Import = replace, не merge — UI просит подтверждение.
|
||||
- **Экран «Что нового»** — модалка с заметками релизов. Показывается
|
||||
автоматически когда `lastSeenVersion` ≠ текущей версии (после
|
||||
обновления). Доступна также из Settings → «О приложении».
|
||||
Реестр заметок в `src/shared/release-notes.ts`, версионируется
|
||||
per-app.
|
||||
|
||||
### Changed
|
||||
|
||||
- Settings.lastSeenVersion (optional) — отслеживает что пользователь
|
||||
видел.
|
||||
- IPC.getAppVersion → app.getVersion() для renderer.
|
||||
- DEFAULT_SETTINGS: добавлены `voicePromptsEnabled: false`,
|
||||
`meetingAutoPause: true`.
|
||||
- Exercise type расширен: `category?`, `dailyGoal?`, `adaptive?`.
|
||||
Все обратно совместимые (optional).
|
||||
|
||||
### Performance
|
||||
|
||||
- Scheduler запрашивает history только если есть упражнения с
|
||||
dailyGoal или adaptive — иначе экономит IPC.
|
||||
|
||||
## [0.5.5] — 2026-05-22
|
||||
|
||||
Большой sweep по ревизии: 4 спринта правок (≈14 пунктов), все 135 тестов
|
||||
зелёные. Главное — UI больше не залипает при retry'ях I/O, GSI порт не
|
||||
зависает в TIME_WAIT после выхода, sandbox включён, шрифты self-hosted.
|
||||
|
||||
### Security
|
||||
|
||||
- **`sandbox: true`** на обоих BrowserWindow. Preload использует только
|
||||
contextBridge + ipcRenderer (sandbox-safe), никаких Node-built-ins.
|
||||
OS-уровневый sandbox изолирует renderer на уровне процессов — даже
|
||||
RCE в зависимости рендерера не получит Node-доступа через preload.
|
||||
- **CSP ужесточён.** Убраны `https://fonts.googleapis.com` и
|
||||
`https://fonts.gstatic.com` origins (шрифты теперь self-hosted),
|
||||
добавлены `connect-src 'self'`, `base-uri 'self'`,
|
||||
`frame-ancestors 'none'`.
|
||||
|
||||
### Added
|
||||
|
||||
- **Self-hosted шрифты.** Plus Jakarta Sans, Bricolage Grotesque,
|
||||
JetBrains Mono подключены через `@fontsource/*` пакеты — в bundle
|
||||
лежат локально, без интернета шрифты работают, CSP без внешних
|
||||
origins. +22 .woff/.woff2 (~500KB) в installer.
|
||||
- **`src/main/logger.ts`** — структурный logger с уровнями
|
||||
(debug/info/warn/error) и ротацией. Пишет в
|
||||
`%APPDATA%/Exercise Reminder/logs/latest.log` (≤1MB) и дублирует
|
||||
в console. При 1MB ротируется в `prev.log`. `LAUDE_DEBUG=1`
|
||||
включает debug-уровень. Подключён в hot paths: store, updater,
|
||||
GSI server, registry, dota2 provider — особенно полезно для
|
||||
диагностики «челленджи не срабатывают» (видно token verify,
|
||||
POST_GAME detection, фильтрацию challenges).
|
||||
- `<html lang>` синхронизируется с `settings.language` через
|
||||
ThemeProvider — screen readers корректно произносят язык.
|
||||
- `dev:simulateMatchEnd` channel вынесен в IPC enum
|
||||
(`IPC.devSimulateMatchEnd`).
|
||||
- `test:coverage` npm script.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`broadcastState` больше не шлёт `history`** через IPC. Раньше
|
||||
каждый markDone/snooze отправлял весь state включая до 10k
|
||||
history-записей (~500KB JSON) к каждому BrowserWindow. Теперь
|
||||
`AppState` (renderer-facing) без `history`, а `PersistedState`
|
||||
(internal) с историей. Renderer и так дёргал `getHistory()`
|
||||
отдельно, поведение не изменилось — только perf.
|
||||
- **`lib/icon.tsx`**: `import * as Lucide` (wildcard, ~500KB всех
|
||||
1500+ иконок в bundle) → explicit named imports + ICON_MAP.
|
||||
В bundle только 18 ICON_CHOICES.
|
||||
- **ChallengeEditor**: multiplier клампится в UI до [0.5, 1000]
|
||||
(совпадает с validate.ts). Раньше save с 9999 молча отклонялся
|
||||
IPC-валидатором.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`atomicWrite` spin-loop → async setTimeout.** Раньше при retry
|
||||
на EBUSY/EPERM (антивирус, OneDrive) main process замораживался
|
||||
на 50/200/800ms × до 3 итераций ≈ секунда залипания UI. Сейчас
|
||||
async sleep — event-loop живёт. Аналогичный фикс в
|
||||
`games/steam-launch-options.ts`. Сохранён sync-вариант для
|
||||
`flushNow` в `before-quit` (там event-loop уже не работает).
|
||||
- **`before-quit` дожидается `stopGamesRegistry`** через
|
||||
`e.preventDefault()` + `app.exit(0)`. Раньше GSI HTTP server
|
||||
не успевал `closeAllConnections` до exit, и следующий запуск
|
||||
получал EADDRINUSE на порту 4701 (TIME_WAIT) — GSI молча не
|
||||
работал.
|
||||
- **IPC `getState` не мутирует кэш.** Раньше `state.settings.startWithWindows`
|
||||
перезаписывалось напрямую, разъезжаясь с persisted-disk-значением
|
||||
до следующего mutation. Сейчас возвращается поверхностная копия.
|
||||
|
||||
## [0.5.4] — 2026-05-19
|
||||
|
||||
Обновление приложения теперь по-настоящему фоновое + почти моментальный
|
||||
рестарт в новую версию.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Скачивание апдейта — фоновое.** Раньше клик «Скачать» блокировал
|
||||
кнопку (`busy=true`) до конца download'а (минуты на медленной сети).
|
||||
Теперь IPC `updaterDownload` — fire-and-forget, прогресс приходит
|
||||
через события. Пользователь сразу может уйти на Dashboard и
|
||||
продолжать упражнения, апдейт качается в фоне.
|
||||
- **«Рестарт» — почти моментальный.** `quitAndInstall(true, true)`:
|
||||
isSilent=true — NSIS без UI установщика (~1-2 сек вместо ~5-10),
|
||||
isForceRunAfter=true — гарантия что приложение откроется после.
|
||||
Раньше показывался диалог установщика с прогрессом, теперь —
|
||||
только мгновение между закрытием и появлением новой версии.
|
||||
- Подсказка на экране скачивания: «можно закрыть это окно, продолжится
|
||||
в фоне». На downloaded-экране: «нажми Рестарт — приложение
|
||||
моментально откроется в новой версии».
|
||||
|
||||
## [0.5.3] — 2026-05-19
|
||||
|
||||
Полировка кастомного тайтлбара и размера окна.
|
||||
@@ -201,7 +343,10 @@
|
||||
иконки), системный трей, автозапуск с Windows, native-уведомления,
|
||||
NSIS-инсталлятор, auto-update через electron-updater.
|
||||
|
||||
[Unreleased]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/compare/v0.5.3...HEAD
|
||||
[Unreleased]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/compare/v0.5.6...HEAD
|
||||
[0.5.6]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.6
|
||||
[0.5.5]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.5
|
||||
[0.5.4]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.4
|
||||
[0.5.3]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.3
|
||||
[0.5.2]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.2
|
||||
[0.5.1]: https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/tag/v0.5.1
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## TL;DR
|
||||
|
||||
**Laude / Exercise Reminder** — Windows desktop приложение на Electron 33, которое напоминает делать упражнения и опционально парсит статистику матчей Dota 2 (через GSI) в количество повторений. Текущая версия — **0.5.3**. Один разработчик (AnRil), один remote — self-hosted Gitea.
|
||||
**Laude / Exercise Reminder** — Windows desktop приложение на Electron 33, которое напоминает делать упражнения и опционально парсит статистику матчей Dota 2 (через GSI) в количество повторений. Текущая версия — **0.5.6**. Один разработчик (AnRil), один remote — self-hosted Gitea.
|
||||
|
||||
## Стек
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
Windows desktop приложение, которое напоминает делать упражнения во время работы за компьютером. Опционально подключается к Dota 2 и после каждого матча превращает статистику (смерти, убийства, ассисты) в количество повторений.
|
||||
|
||||
[](https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/latest)
|
||||
[]()
|
||||
[](https://xn--90adajar8af4h.xn--p1ai/git/AnRil/laude/releases/latest)
|
||||
[]()
|
||||
[]()
|
||||
|
||||
## Что внутри
|
||||
|
||||
34
package-lock.json
generated
34
package-lock.json
generated
@@ -1,13 +1,16 @@
|
||||
{
|
||||
"name": "laude",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "laude",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.4",
|
||||
"dependencies": {
|
||||
"@fontsource/bricolage-grotesque": "^5.2.10",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@fontsource/plus-jakarta-sans": "^5.2.8",
|
||||
"electron-updater": "^6.8.3",
|
||||
"framer-motion": "^11.11.17",
|
||||
"lucide-react": "^0.460.0",
|
||||
@@ -1264,6 +1267,33 @@
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/bricolage-grotesque": {
|
||||
"version": "5.2.10",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/bricolage-grotesque/-/bricolage-grotesque-5.2.10.tgz",
|
||||
"integrity": "sha512-V2xS+1P7C8IrSypXLUx/bLtX/LsTlYtV2k2CsU+S/0t8qepZ2hvKSlyJIx7Ub/iY8Bbnj+IjAuUF9nvFz+BbIg==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/jetbrains-mono": {
|
||||
"version": "5.2.8",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/jetbrains-mono/-/jetbrains-mono-5.2.8.tgz",
|
||||
"integrity": "sha512-6w8/SG4kqvIMu7xd7wt6x3idn1Qux3p9N62s6G3rfldOUYHpWcc2FKrqf+Vo44jRvqWj2oAtTHrZXEP23oSKwQ==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/plus-jakarta-sans": {
|
||||
"version": "5.2.8",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/plus-jakarta-sans/-/plus-jakarta-sans-5.2.8.tgz",
|
||||
"integrity": "sha512-P5qE49fqdeD+7DXH1KBxmMPlB17LTz1zvBhFH0tFzfnYTKVJVyb0pR6plh0ZGXxcB+Oayb54FZZw3V42/DawTw==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@gar/promisify": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.3.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "laude",
|
||||
"version": "0.5.3",
|
||||
"version": "0.5.6",
|
||||
"description": "Exercise reminder — Windows desktop app",
|
||||
"main": "out/main/index.js",
|
||||
"author": "AnRil",
|
||||
@@ -14,6 +14,7 @@
|
||||
"typecheck": "npm run typecheck:node && npm run typecheck:web",
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"format": "prettier --write \"src/**/*.{ts,tsx,css}\" \"*.{json,md}\" \".github/**/*.yml\"",
|
||||
"format:check": "prettier --check \"src/**/*.{ts,tsx,css}\" \"*.{json,md}\"",
|
||||
"lint": "eslint src --ext .ts,.tsx --max-warnings 0",
|
||||
@@ -24,6 +25,9 @@
|
||||
"gen:icons": "powershell -ExecutionPolicy Bypass -File scripts/gen-icons.ps1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/bricolage-grotesque": "^5.2.10",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@fontsource/plus-jakarta-sans": "^5.2.8",
|
||||
"electron-updater": "^6.8.3",
|
||||
"framer-motion": "^11.11.17",
|
||||
"lucide-react": "^0.460.0",
|
||||
|
||||
94
src/main/adaptive.ts
Normal file
94
src/main/adaptive.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Адаптивный шедулер v1: смотрит на исторические success/skip-паттерны
|
||||
* по часам дня и сдвигает следующий fire на ближайший «хороший» час.
|
||||
*
|
||||
* Без ML, чистая heuristic. Идея: каждому часу 0..23 присваиваем
|
||||
* success-rate = done / (done + skip + snooze). Если интервал шедулера
|
||||
* приходится на «плохой» час (success ≤ 30%), сдвигаем fire вперёд на
|
||||
* ближайший «хороший» (≥ 50% success или не имеющий данных = neutral).
|
||||
*
|
||||
* Окно учитываемой истории: 30 дней. Требует минимум 10 событий по
|
||||
* упражнению, иначе истории слишком мало для статистики — возвращаем
|
||||
* candidate без изменений.
|
||||
*
|
||||
* Этот модуль НЕ обязателен для работы шедулера; вызывается опционально
|
||||
* когда у упражнения `adaptive: true`.
|
||||
*/
|
||||
import type { Exercise, HistoryEntry } from '@shared/types'
|
||||
|
||||
const LOOKBACK_MS = 30 * 24 * 60 * 60 * 1000 // 30 дней
|
||||
const MIN_EVENTS_FOR_TRUST = 10
|
||||
const BAD_HOUR_THRESHOLD = 0.3
|
||||
const GOOD_HOUR_THRESHOLD = 0.5
|
||||
/** Максимальный сдвиг — чтобы не утащить fire на 6 часов вперёд. */
|
||||
const MAX_SHIFT_HOURS = 4
|
||||
|
||||
type HourStats = {
|
||||
done: number
|
||||
skipped: number
|
||||
total: number
|
||||
}
|
||||
|
||||
function buildHourStats(
|
||||
exerciseId: string,
|
||||
history: HistoryEntry[]
|
||||
): HourStats[] {
|
||||
const cutoff = Date.now() - LOOKBACK_MS
|
||||
const stats: HourStats[] = Array.from({ length: 24 }, () => ({
|
||||
done: 0,
|
||||
skipped: 0,
|
||||
total: 0
|
||||
}))
|
||||
for (const e of history) {
|
||||
if (e.exerciseId !== exerciseId) continue
|
||||
if (e.ts < cutoff) continue
|
||||
const h = new Date(e.ts).getHours()
|
||||
stats[h].total++
|
||||
if (e.action === 'done') stats[h].done++
|
||||
else stats[h].skipped++ // skip + snooze оба считаются «не done»
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
function isHourGood(s: HourStats): boolean {
|
||||
if (s.total === 0) return true // нет данных — нейтрально, ОК
|
||||
return s.done / s.total >= GOOD_HOUR_THRESHOLD
|
||||
}
|
||||
|
||||
function isHourBad(s: HourStats): boolean {
|
||||
if (s.total < 3) return false // данных мало, не делаем выводы
|
||||
return s.done / s.total <= BAD_HOUR_THRESHOLD
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает скорректированный timestamp следующего fire. Если candidate
|
||||
* попадает на «плохой» час и есть «хороший» час в пределах MAX_SHIFT_HOURS,
|
||||
* сдвигаем на начало этого хорошего часа. Иначе возвращаем candidate
|
||||
* как есть.
|
||||
*/
|
||||
export function adjustNextFireAt(
|
||||
exercise: Exercise,
|
||||
candidateTs: number,
|
||||
history: HistoryEntry[]
|
||||
): number {
|
||||
// Сначала собираем total — если истории мало, не двигаем.
|
||||
const stats = buildHourStats(exercise.id, history)
|
||||
const total = stats.reduce((s, h) => s + h.total, 0)
|
||||
if (total < MIN_EVENTS_FOR_TRUST) return candidateTs
|
||||
|
||||
const candDate = new Date(candidateTs)
|
||||
const candHour = candDate.getHours()
|
||||
if (!isHourBad(stats[candHour])) return candidateTs
|
||||
|
||||
// Ищем ближайший «хороший» час в будущем (внутри MAX_SHIFT_HOURS).
|
||||
for (let shift = 1; shift <= MAX_SHIFT_HOURS; shift++) {
|
||||
const h = (candHour + shift) % 24
|
||||
if (isHourGood(stats[h])) {
|
||||
const target = new Date(candDate)
|
||||
target.setHours(candHour + shift, 0, 0, 0)
|
||||
return target.getTime()
|
||||
}
|
||||
}
|
||||
// Не нашли — оставляем как есть.
|
||||
return candidateTs
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
isSteamRunning
|
||||
} from './steam-launch-options'
|
||||
import type { GameId, GameStatus, LaunchOptionStatus } from '@shared/types'
|
||||
import { log } from '../logger'
|
||||
|
||||
const APP_ID = '570'
|
||||
const INSTALL_DIR = 'dota 2 beta'
|
||||
@@ -198,6 +199,8 @@ export class Dota2Provider implements GameProvider {
|
||||
this.latest = undefined
|
||||
}
|
||||
|
||||
private rejectedTokenLogged = false
|
||||
|
||||
private handle(g: DotaGsi): void {
|
||||
// Verify the per-install token. Dota always sends auth.token; anything
|
||||
// without it (or with the wrong one) is some other process on localhost
|
||||
@@ -207,6 +210,15 @@ export class Dota2Provider implements GameProvider {
|
||||
typeof incoming !== 'string' ||
|
||||
!safeEqualStrings(incoming, this.token)
|
||||
) {
|
||||
// Логируем только ОДИН раз за процесс — Dota шлёт payload каждые
|
||||
// ~100ms во время матча, иначе zass'мём latest.log.
|
||||
if (!this.rejectedTokenLogged) {
|
||||
this.rejectedTokenLogged = true
|
||||
log.warn(
|
||||
'[dota2] GSI payload with invalid/missing token rejected. ' +
|
||||
'Если приложение переустанавливалось — заново подключи Dota 2 в Games.'
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -235,8 +247,12 @@ export class Dota2Provider implements GameProvider {
|
||||
if (prev && prev !== state && state === 'DOTA_GAMERULES_STATE_POST_GAME') {
|
||||
// De-dupe: Dota can fire POST_GAME repeatedly while the scoreboard is open.
|
||||
const now = Date.now()
|
||||
if (now - this.lastMatchEndAt < 30_000) return
|
||||
if (now - this.lastMatchEndAt < 30_000) {
|
||||
log.debug('[dota2] suppressed duplicate POST_GAME within 30s window')
|
||||
return
|
||||
}
|
||||
this.lastMatchEndAt = now
|
||||
log.info('[dota2] POST_GAME detected, emitting match_end event')
|
||||
|
||||
const p = this.latest?.player ?? {}
|
||||
const m = this.latest?.map ?? {}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type Server,
|
||||
type ServerResponse
|
||||
} from 'node:http'
|
||||
import { log } from '../logger'
|
||||
|
||||
export type GsiHandler = (
|
||||
payload: unknown,
|
||||
@@ -87,7 +88,7 @@ async function onRequest(
|
||||
payload = text.length > 0 ? JSON.parse(text) : {}
|
||||
} catch (err) {
|
||||
// Log the real reason locally; do not echo it to the client.
|
||||
console.warn('[gsi] bad request:', err instanceof Error ? err.message : err)
|
||||
log.warn('[gsi] bad request', err instanceof Error ? err.message : err)
|
||||
res.statusCode = 400
|
||||
res.end()
|
||||
return
|
||||
@@ -99,7 +100,7 @@ async function onRequest(
|
||||
res.setHeader('Content-Type', 'text/plain')
|
||||
res.end('ok')
|
||||
} catch (err) {
|
||||
console.error('[gsi] handler threw:', err)
|
||||
log.error('[gsi] handler threw', err)
|
||||
res.statusCode = 500
|
||||
res.end()
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
import { STAT_LABELS } from '@shared/types'
|
||||
import { getChallenges, getGamesEnabled } from '../store'
|
||||
import { fireMatchSummary } from '../notifications'
|
||||
import { log } from '../logger'
|
||||
|
||||
const providers: Record<GameId, GameProvider> = {
|
||||
dota2: new Dota2Provider()
|
||||
@@ -25,14 +26,23 @@ async function onMatchEnd(
|
||||
payload: MatchEndPayload
|
||||
): Promise<void> {
|
||||
const provider = providers[gameId]
|
||||
const challenges = getChallenges().filter(
|
||||
(c) => c.gameId === gameId && c.enabled
|
||||
const allChallenges = getChallenges().filter((c) => c.gameId === gameId)
|
||||
const enabledChallenges = allChallenges.filter((c) => c.enabled)
|
||||
log.info(
|
||||
`[games] match_end gameId=${gameId} stats=${JSON.stringify(
|
||||
payload.stats
|
||||
)} challenges=${enabledChallenges.length}/${allChallenges.length} (enabled/total)`
|
||||
)
|
||||
const results: ChallengeResult[] = []
|
||||
for (const ch of challenges) {
|
||||
for (const ch of enabledChallenges) {
|
||||
const statValue = payload.stats[ch.stat] ?? 0
|
||||
const reps = Math.round(statValue * ch.multiplier)
|
||||
if (reps <= 0) continue
|
||||
if (reps <= 0) {
|
||||
log.debug(
|
||||
`[games] skip challenge "${ch.name}": ${ch.stat}=${statValue} × ${ch.multiplier} = ${reps}`
|
||||
)
|
||||
continue
|
||||
}
|
||||
results.push({
|
||||
challengeId: ch.id,
|
||||
name: ch.name,
|
||||
@@ -44,7 +54,21 @@ async function onMatchEnd(
|
||||
stat: ch.stat
|
||||
})
|
||||
}
|
||||
if (results.length === 0) return
|
||||
if (results.length === 0) {
|
||||
log.warn(
|
||||
`[games] match_end produced no reps (no enabled challenges matched stats). ` +
|
||||
`Enabled challenges: ${enabledChallenges.length}, stats keys: ${Object.keys(
|
||||
payload.stats
|
||||
).join(',')}`
|
||||
)
|
||||
return
|
||||
}
|
||||
log.info(
|
||||
`[games] firing match summary: ${results.length} challenges, total reps ${results.reduce(
|
||||
(s, r) => s + r.reps,
|
||||
0
|
||||
)}`
|
||||
)
|
||||
|
||||
const summary: MatchSummary = {
|
||||
gameId,
|
||||
@@ -61,8 +85,9 @@ export async function startGamesRegistry(): Promise<void> {
|
||||
running = true
|
||||
try {
|
||||
await startGsiServer()
|
||||
log.info('[games] GSI server started on port 4701')
|
||||
} catch (err) {
|
||||
console.error('GSI server failed to start:', err)
|
||||
log.error('[games] GSI server failed to start', err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -79,7 +104,7 @@ export async function startGamesRegistry(): Promise<void> {
|
||||
try {
|
||||
await provider.reconcile?.()
|
||||
} catch (err) {
|
||||
console.error('reconcile failed for', id, err)
|
||||
log.error(`[games] reconcile failed for ${id}`, err)
|
||||
}
|
||||
if (!enabled[id]) continue
|
||||
await provider.start((e) => {
|
||||
|
||||
@@ -123,20 +123,19 @@ function writeBackup(path: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(path: string, contents: string): void {
|
||||
async function atomicWrite(path: string, contents: string): Promise<void> {
|
||||
// Write to temp then rename (atomic on Windows for same directory). Retry a
|
||||
// few times on transient EBUSY/EPERM (AV scanners and OneDrive sometimes
|
||||
// hold a handle briefly during a Steam config rewrite).
|
||||
//
|
||||
// Раньше тут был busy-loop sleep — Steam-конфиги пишутся редко, но из main
|
||||
// process, и при попадании на занятый файл (Steam ещё держит handle) морозили
|
||||
// весь UI на 250мс. Заменили на async setTimeout-sleep.
|
||||
const tmp = path + '.exr.tmp'
|
||||
const delays = [0, 50, 200]
|
||||
let lastErr: unknown
|
||||
for (const delay of delays) {
|
||||
if (delay > 0) {
|
||||
const until = Date.now() + delay
|
||||
while (Date.now() < until) {
|
||||
/* spin */
|
||||
}
|
||||
}
|
||||
if (delay > 0) await new Promise<void>((r) => setTimeout(r, delay))
|
||||
try {
|
||||
writeFileSync(tmp, contents, 'utf-8')
|
||||
renameSync(tmp, path)
|
||||
@@ -148,11 +147,11 @@ function atomicWrite(path: string, contents: string): void {
|
||||
throw lastErr
|
||||
}
|
||||
|
||||
function modifyLaunchOptions(
|
||||
async function modifyLaunchOptions(
|
||||
configPath: string,
|
||||
appId: string,
|
||||
fn: (current: string) => string | null
|
||||
): boolean {
|
||||
): Promise<boolean> {
|
||||
let raw: string
|
||||
try {
|
||||
raw = readFileSync(configPath, 'utf-8')
|
||||
@@ -188,7 +187,7 @@ function modifyLaunchOptions(
|
||||
|
||||
writeBackup(configPath)
|
||||
try {
|
||||
atomicWrite(configPath, stringifyVdf(parsed))
|
||||
await atomicWrite(configPath, stringifyVdf(parsed))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
@@ -225,7 +224,7 @@ async function applyOptionToAllConfigs(
|
||||
): Promise<void> {
|
||||
const paths = await getLocalConfigPaths()
|
||||
for (const p of paths) {
|
||||
modifyLaunchOptions(p, appId, (current) => {
|
||||
await modifyLaunchOptions(p, appId, (current) => {
|
||||
if (current.includes(option)) return current
|
||||
return current.length > 0 ? `${current} ${option}` : option
|
||||
})
|
||||
@@ -238,7 +237,7 @@ async function removeOptionFromAllConfigs(
|
||||
): Promise<void> {
|
||||
const paths = await getLocalConfigPaths()
|
||||
for (const p of paths) {
|
||||
modifyLaunchOptions(p, appId, (current) => {
|
||||
await modifyLaunchOptions(p, appId, (current) => {
|
||||
if (!current.includes(option)) return current
|
||||
return current
|
||||
.split(/\s+/)
|
||||
|
||||
@@ -73,11 +73,26 @@ if (!gotLock) {
|
||||
}
|
||||
})
|
||||
|
||||
app.on('before-quit', () => {
|
||||
// Перехватываем первый before-quit, чтобы дождаться `stopGamesRegistry`
|
||||
// (закрывает GSI HTTP server со всеми pending connections). Без этого
|
||||
// следующий запуск получает EADDRINUSE на port 4701 (TIME_WAIT), и
|
||||
// GSI молча не работает. После cleanup'а — реально quit.
|
||||
let quitting = false
|
||||
app.on('before-quit', (e) => {
|
||||
if (quitting) return
|
||||
e.preventDefault()
|
||||
quitting = true
|
||||
stopScheduler()
|
||||
stopUpdater()
|
||||
void stopGamesRegistry()
|
||||
void (async () => {
|
||||
try {
|
||||
await stopGamesRegistry()
|
||||
} catch (err) {
|
||||
console.error('[index] stopGamesRegistry threw:', err)
|
||||
}
|
||||
flushNow()
|
||||
app.exit(0)
|
||||
})()
|
||||
})
|
||||
|
||||
app.on('activate', () => {
|
||||
|
||||
@@ -4,8 +4,10 @@ import {
|
||||
systemPreferences,
|
||||
BrowserWindow,
|
||||
app,
|
||||
dialog,
|
||||
shell
|
||||
} from 'electron'
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { IPC } from '@shared/ipc'
|
||||
import type { Exercise, GameId, Settings } from '@shared/types'
|
||||
import {
|
||||
@@ -14,8 +16,11 @@ import {
|
||||
clearHistory,
|
||||
deleteChallenge,
|
||||
deleteExercise,
|
||||
exportState,
|
||||
getHistory,
|
||||
getState,
|
||||
getStateForRenderer,
|
||||
importState,
|
||||
markDone,
|
||||
setGameEnabled,
|
||||
skip,
|
||||
@@ -56,8 +61,13 @@ import {
|
||||
|
||||
export function registerIpc(): void {
|
||||
ipcMain.handle(IPC.getState, () => {
|
||||
const state = getState()
|
||||
state.settings.startWithWindows = isAutostartEnabled()
|
||||
// Без history (см. getStateForRenderer) и с актуальным значением
|
||||
// autostart из OS — мутацию делаем по копии, не по cache.
|
||||
const state = getStateForRenderer()
|
||||
state.settings = {
|
||||
...state.settings,
|
||||
startWithWindows: isAutostartEnabled()
|
||||
}
|
||||
return state
|
||||
})
|
||||
|
||||
@@ -169,6 +179,8 @@ export function registerIpc(): void {
|
||||
nativeTheme.shouldUseDarkColors ? 'dark' : 'light'
|
||||
)
|
||||
|
||||
ipcMain.handle(IPC.getAppVersion, () => app.getVersion())
|
||||
|
||||
ipcMain.handle(IPC.quit, () => app.quit())
|
||||
ipcMain.handle(IPC.reminderClose, () => hideReminderWindow())
|
||||
|
||||
@@ -275,7 +287,7 @@ export function registerIpc(): void {
|
||||
// otherwise fabricate arbitrary match-end events at will.
|
||||
if (!app.isPackaged) {
|
||||
ipcMain.handle(
|
||||
'dev:simulateMatchEnd',
|
||||
IPC.devSimulateMatchEnd,
|
||||
(_e, id: GameId, stats: Record<string, number>) => {
|
||||
simulateMatchEnd(id, stats)
|
||||
}
|
||||
@@ -285,12 +297,60 @@ export function registerIpc(): void {
|
||||
// Auto-updater
|
||||
ipcMain.handle(IPC.updaterStatus, () => getUpdaterStatus())
|
||||
ipcMain.handle(IPC.updaterCheck, () => checkForUpdates())
|
||||
ipcMain.handle(IPC.updaterDownload, () => downloadUpdate())
|
||||
ipcMain.handle(IPC.updaterInstall, () => quitAndInstall())
|
||||
// download/install — fire-and-forget. Прогресс и завершение приходят в
|
||||
// renderer через evtUpdaterStatus, ждать promise бессмысленно — renderer
|
||||
// только зря держал бы `busy=true` весь download (минуты на медленной сети).
|
||||
ipcMain.on(IPC.updaterDownload, () => {
|
||||
void downloadUpdate()
|
||||
})
|
||||
ipcMain.on(IPC.updaterInstall, () => quitAndInstall())
|
||||
|
||||
// History
|
||||
ipcMain.handle(IPC.getHistory, (_e, sinceMs?: number) => getHistory(sinceMs))
|
||||
ipcMain.handle(IPC.clearHistory, (_e, beforeTs?: number) =>
|
||||
clearHistory(beforeTs)
|
||||
)
|
||||
|
||||
// Export / Import. Используем native save/open dialogs Electron'а —
|
||||
// renderer не получает прямого доступа к ФС.
|
||||
ipcMain.handle(IPC.exportState, async (event) => {
|
||||
const win = BrowserWindow.fromWebContents(event.sender) ?? undefined
|
||||
const stamp = new Date()
|
||||
.toISOString()
|
||||
.replace(/[:T]/g, '-')
|
||||
.slice(0, 16)
|
||||
const defaultPath = `laude-backup-${stamp}.json`
|
||||
const result = await dialog.showSaveDialog(win!, {
|
||||
title: 'Сохранить резервную копию',
|
||||
defaultPath,
|
||||
filters: [{ name: 'JSON', extensions: ['json'] }]
|
||||
})
|
||||
if (result.canceled || !result.filePath) return { ok: false, path: null }
|
||||
try {
|
||||
writeFileSync(result.filePath, exportState(), 'utf-8')
|
||||
return { ok: true, path: result.filePath }
|
||||
} catch (e) {
|
||||
return { ok: false, path: null, error: String(e) }
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle(IPC.importState, async (event) => {
|
||||
const win = BrowserWindow.fromWebContents(event.sender) ?? undefined
|
||||
const result = await dialog.showOpenDialog(win!, {
|
||||
title: 'Восстановить из резервной копии',
|
||||
properties: ['openFile'],
|
||||
filters: [{ name: 'JSON', extensions: ['json'] }]
|
||||
})
|
||||
if (result.canceled || result.filePaths.length === 0) {
|
||||
return { ok: false }
|
||||
}
|
||||
try {
|
||||
const raw = readFileSync(result.filePaths[0], 'utf-8')
|
||||
const ok = importState(raw)
|
||||
if (ok) broadcastState()
|
||||
return { ok }
|
||||
} catch (e) {
|
||||
return { ok: false, error: String(e) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
125
src/main/logger.ts
Normal file
125
src/main/logger.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
/* eslint-disable no-console -- этот файл — единственное место где console.*
|
||||
разрешён намеренно: дублирование лога в stderr для dev-режима. */
|
||||
/**
|
||||
* Минимальный logger для main process.
|
||||
*
|
||||
* Пишет в файл `%APPDATA%/Exercise Reminder/logs/latest.log` + дублирует
|
||||
* в stderr через console.* (чтобы dev-режим оставался удобным).
|
||||
*
|
||||
* Ротация: при достижении 1MB latest.log переименовывается в prev.log
|
||||
* (предыдущий prev.log удаляется). Две сессии истории — этого достаточно
|
||||
* для воспроизведения «случилось вчера, а сегодня перезапустил». Никакой
|
||||
* remote-телеметрии: лог локальный, пользователь сам может вложить его в
|
||||
* issue если что-то сломалось.
|
||||
*
|
||||
* Уровни:
|
||||
* - debug: подробный traceback, видим только если LAUDE_DEBUG=1
|
||||
* - info: значимые события (startup, GSI matched, updater progress)
|
||||
* - warn: recoverable issues (transient network, retry succeeded)
|
||||
* - error: что-то реально сломалось (atomic write fail, IPC validation)
|
||||
*/
|
||||
import { app } from 'electron'
|
||||
import {
|
||||
appendFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
renameSync,
|
||||
statSync,
|
||||
unlinkSync
|
||||
} from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const ROTATE_AT_BYTES = 1 * 1024 * 1024 // 1 MB
|
||||
|
||||
type Level = 'debug' | 'info' | 'warn' | 'error'
|
||||
|
||||
let logDir = ''
|
||||
let logPath = ''
|
||||
let prevPath = ''
|
||||
|
||||
function ensurePaths(): void {
|
||||
if (logDir) return
|
||||
try {
|
||||
logDir = join(app.getPath('userData'), 'logs')
|
||||
if (!existsSync(logDir)) mkdirSync(logDir, { recursive: true })
|
||||
logPath = join(logDir, 'latest.log')
|
||||
prevPath = join(logDir, 'prev.log')
|
||||
} catch {
|
||||
// app.getPath не готов (очень ранний boot) — отложим, console продолжит.
|
||||
}
|
||||
}
|
||||
|
||||
function rotateIfNeeded(): void {
|
||||
if (!logPath) return
|
||||
try {
|
||||
if (!existsSync(logPath)) return
|
||||
const size = statSync(logPath).size
|
||||
if (size < ROTATE_AT_BYTES) return
|
||||
if (existsSync(prevPath)) unlinkSync(prevPath)
|
||||
renameSync(logPath, prevPath)
|
||||
} catch {
|
||||
// не критично — продолжим писать в latest.log с overflow
|
||||
}
|
||||
}
|
||||
|
||||
function ts(): string {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
function levelTag(l: Level): string {
|
||||
return l.toUpperCase().padEnd(5, ' ')
|
||||
}
|
||||
|
||||
function write(level: Level, msg: string, extra?: unknown): void {
|
||||
// Always dup to console for dev. structuredClone-style serialize:
|
||||
const line = `[${ts()}] ${levelTag(level)} ${msg}${
|
||||
extra !== undefined ? ' ' + safeStringify(extra) : ''
|
||||
}\n`
|
||||
switch (level) {
|
||||
case 'error':
|
||||
console.error(line.trimEnd())
|
||||
break
|
||||
case 'warn':
|
||||
console.warn(line.trimEnd())
|
||||
break
|
||||
case 'debug':
|
||||
case 'info':
|
||||
default:
|
||||
console.log(line.trimEnd())
|
||||
}
|
||||
ensurePaths()
|
||||
rotateIfNeeded()
|
||||
if (!logPath) return
|
||||
try {
|
||||
appendFileSync(logPath, line, 'utf-8')
|
||||
} catch {
|
||||
// Если AV держит файл — переживём, в console уже залогировали.
|
||||
}
|
||||
}
|
||||
|
||||
function safeStringify(v: unknown): string {
|
||||
if (v instanceof Error) {
|
||||
return v.stack ?? `${v.name}: ${v.message}`
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(v)
|
||||
} catch {
|
||||
return String(v)
|
||||
}
|
||||
}
|
||||
|
||||
const DEBUG_ENABLED = process.env.LAUDE_DEBUG === '1'
|
||||
|
||||
export const log = {
|
||||
debug: (msg: string, extra?: unknown): void => {
|
||||
if (DEBUG_ENABLED) write('debug', msg, extra)
|
||||
},
|
||||
info: (msg: string, extra?: unknown): void => write('info', msg, extra),
|
||||
warn: (msg: string, extra?: unknown): void => write('warn', msg, extra),
|
||||
error: (msg: string, extra?: unknown): void => write('error', msg, extra)
|
||||
}
|
||||
|
||||
/** Путь к логам (для диагностики). Возвращает пустую строку до initLogger(). */
|
||||
export function getLogDir(): string {
|
||||
return logDir
|
||||
}
|
||||
97
src/main/meeting-detect.ts
Normal file
97
src/main/meeting-detect.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Эвристическое обнаружение «человек на ВКС» по списку запущенных процессов.
|
||||
*
|
||||
* Идея: если запущен Zoom/Teams/Discord/Meet/Webex — пользователь скорее
|
||||
* всего на встрече или собирается зайти. Останавливаем напоминания, чтобы
|
||||
* не прерывать. После «снятия» процессов возобновляем.
|
||||
*
|
||||
* Проверка раз в 30 сек через `tasklist` (CSV-режим, без окна). Не используем
|
||||
* audio capture API / mic state — это потребовало бы Windows-specific
|
||||
* native-модуля; задача fit-for-purpose, не security-critical.
|
||||
*
|
||||
* False positive vs false negative tradeoff: лучше один лишний скип
|
||||
* напоминания, чем один pop-up посреди митинга. Поэтому даже если
|
||||
* процесс запущен, но митинга нет (Teams в фоне) — пауза. Пользователь
|
||||
* это переживёт, обратное — не очень.
|
||||
*/
|
||||
import { exec } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import { log } from './logger'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
/**
|
||||
* Имена процессов (Windows .exe). Регистр игнорируется при сравнении.
|
||||
* Покрываем основные VOIP-приложения для индустрии WFH.
|
||||
*/
|
||||
const MEETING_PROCESSES = new Set([
|
||||
'zoom.exe',
|
||||
'teams.exe',
|
||||
'ms-teams.exe', // новые Teams 2.0
|
||||
'discord.exe',
|
||||
'webex.exe',
|
||||
'webexmta.exe',
|
||||
'meet.exe', // Google Meet desktop (редкость)
|
||||
'slack.exe', // huddle
|
||||
'skype.exe',
|
||||
'gotomeeting.exe',
|
||||
'whereby.exe'
|
||||
])
|
||||
|
||||
let cachedActive = false
|
||||
let lastCheckAt = 0
|
||||
const CACHE_MS = 30_000
|
||||
|
||||
/**
|
||||
* Проверяет, запущен ли хотя бы один из meeting-процессов. Кеширует
|
||||
* результат на CACHE_MS, чтобы tasklist не дёргался каждую секунду из
|
||||
* scheduler-tick'а.
|
||||
*/
|
||||
export async function isMeetingActive(): Promise<boolean> {
|
||||
if (process.platform !== 'win32') return false
|
||||
const now = Date.now()
|
||||
if (now - lastCheckAt < CACHE_MS) return cachedActive
|
||||
lastCheckAt = now
|
||||
try {
|
||||
// CSV без заголовков (/NH), скрытое окно.
|
||||
const { stdout } = await execAsync('tasklist /FO CSV /NH', {
|
||||
windowsHide: true,
|
||||
maxBuffer: 4 * 1024 * 1024 // tasklist бывает большой
|
||||
})
|
||||
const lower = stdout.toLowerCase()
|
||||
for (const proc of MEETING_PROCESSES) {
|
||||
// Простой substring-match достаточен: формат CSV-row
|
||||
// "zoom.exe","12345","Console","1","85,432 K".
|
||||
if (lower.includes(`"${proc}",`)) {
|
||||
if (!cachedActive) {
|
||||
log.info(`[meeting] detected ${proc} — pausing reminders`)
|
||||
}
|
||||
cachedActive = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
if (cachedActive) {
|
||||
log.info('[meeting] no meeting processes — resuming reminders')
|
||||
}
|
||||
cachedActive = false
|
||||
return false
|
||||
} catch (e) {
|
||||
// tasklist может фейлиться на нестандартных образах Windows. Лучше
|
||||
// продолжить работу как обычно (не паузить), чем глушить напоминания
|
||||
// навсегда.
|
||||
log.warn('[meeting] tasklist failed, assuming no meeting', e)
|
||||
cachedActive = false
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Синхронный «последнее известное значение» без запроса. Используется
|
||||
* в scheduler-tick'е — он не async. Background refresh идёт отдельно. */
|
||||
export function isMeetingActiveSync(): boolean {
|
||||
return cachedActive
|
||||
}
|
||||
|
||||
/** Background refresh, дёргаем из scheduler'а. Не await'им. */
|
||||
export function refreshMeetingState(): void {
|
||||
void isMeetingActive()
|
||||
}
|
||||
@@ -1,10 +1,30 @@
|
||||
import { powerMonitor, BrowserWindow } from 'electron'
|
||||
import { IPC } from '@shared/ipc'
|
||||
import type { Tick } from '@shared/types'
|
||||
import type { Exercise, Tick, HistoryEntry } from '@shared/types'
|
||||
import { isQuietAt } from '@shared/types'
|
||||
import { getExercises, getSettings, updateExercise } from './store'
|
||||
import { getExercises, getHistory, getSettings, updateExercise } from './store'
|
||||
import { fireReminder } from './notifications'
|
||||
import { broadcastState } from './state-actions'
|
||||
import { isMeetingActiveSync, refreshMeetingState } from './meeting-detect'
|
||||
import { adjustNextFireAt } from './adaptive'
|
||||
|
||||
/**
|
||||
* Сколько reps пользователь сделал по упражнению `ex` за сегодня (local day).
|
||||
* Учитываем actualReps если задано (частичное выполнение), иначе planned reps.
|
||||
*/
|
||||
function repsDoneToday(ex: Exercise, history: HistoryEntry[]): number {
|
||||
const todayKey = new Date()
|
||||
todayKey.setHours(0, 0, 0, 0)
|
||||
const startMs = todayKey.getTime()
|
||||
let sum = 0
|
||||
for (const e of history) {
|
||||
if (e.action !== 'done') continue
|
||||
if (e.exerciseId !== ex.id) continue
|
||||
if (e.ts < startMs) continue
|
||||
sum += e.actualReps ?? ex.reps
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
/**
|
||||
* TICK_MS drives the per-second countdown UI; CHECK_MS gates the (cheaper)
|
||||
@@ -27,21 +47,51 @@ function checkDueExercises(): void {
|
||||
// CHECK_MS pass after the window ends will pick them up.
|
||||
if (isQuietAt(settings.quietHours, new Date())) return
|
||||
|
||||
// Авто-пауза на встречах. Sync-чтение кеша (последнее значение); refresh
|
||||
// запускаем в фоне чтобы кеш «зрел» к следующему tick'у. На холодном
|
||||
// старте кеш false — первое срабатывание может прийти в момент митинга,
|
||||
// но 30 сек спустя система догонит и больше не будет fire'ить.
|
||||
if (settings.meetingAutoPause) {
|
||||
refreshMeetingState()
|
||||
if (isMeetingActiveSync()) return
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const exercises = getExercises()
|
||||
// history запрашивается если у какого-нибудь упражнения есть
|
||||
// dailyGoal или adaptive: false — иначе экономим IPC-нагрузку.
|
||||
const needsHistory = exercises.some(
|
||||
(e) => e.dailyGoal !== undefined || e.adaptive
|
||||
)
|
||||
const history = needsHistory ? getHistory() : []
|
||||
let anyFired = false
|
||||
for (const ex of exercises) {
|
||||
if (!ex.enabled) continue
|
||||
if (ex.nextFireAt <= now) {
|
||||
const updated = updateExercise(ex.id, {
|
||||
nextFireAt: now + ex.intervalMinutes * 60_000
|
||||
})
|
||||
if (ex.nextFireAt > now) continue
|
||||
// Soft cap: если dailyGoal задан и уже выполнен — переносим
|
||||
// следующий fire на «начало завтра» (без повторных проверок до утра).
|
||||
if (ex.dailyGoal !== undefined && ex.dailyGoal > 0) {
|
||||
const done = repsDoneToday(ex, history)
|
||||
if (done >= ex.dailyGoal) {
|
||||
const tomorrow = new Date()
|
||||
tomorrow.setHours(0, 0, 0, 0)
|
||||
tomorrow.setDate(tomorrow.getDate() + 1)
|
||||
updateExercise(ex.id, { nextFireAt: tomorrow.getTime() })
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Базовый candidate. Если adaptive — сдвигаем на «хороший» час
|
||||
// по исторической статистике успеха/скипов.
|
||||
let nextFireAt = now + ex.intervalMinutes * 60_000
|
||||
if (ex.adaptive) {
|
||||
nextFireAt = adjustNextFireAt(ex, nextFireAt, history)
|
||||
}
|
||||
const updated = updateExercise(ex.id, { nextFireAt })
|
||||
if (updated) {
|
||||
anyFired = true
|
||||
fireReminder(updated, settings.notificationMode)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Push fresh state so the renderer's Dashboard/Exercises pages don't show
|
||||
// stale `nextFireAt` until the next state-changing IPC arrives.
|
||||
if (anyFired) broadcastState()
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { BrowserWindow } from 'electron'
|
||||
import { IPC } from '@shared/ipc'
|
||||
import { getExercises, getState, updateExercise } from './store'
|
||||
import { getExercises, getStateForRenderer, updateExercise } from './store'
|
||||
|
||||
export function broadcastState(): void {
|
||||
const state = getState()
|
||||
// Используем variant без `history` — иначе при 10k записей через IPC
|
||||
// на каждый markDone летит 500KB JSON × M подписчиков. Renderer
|
||||
// запрашивает историю отдельно через IPC.getHistory.
|
||||
const state = getStateForRenderer()
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
if (!win.isDestroyed()) win.webContents.send(IPC.evtStateChanged, state)
|
||||
}
|
||||
|
||||
@@ -17,9 +17,11 @@ import {
|
||||
GameId,
|
||||
HistoryAction,
|
||||
HistoryEntry,
|
||||
PersistedState,
|
||||
SAMPLE_EXERCISES,
|
||||
Settings
|
||||
} from '@shared/types'
|
||||
import { log } from './logger'
|
||||
|
||||
/**
|
||||
* Keep at most this many history entries (≈2.7 years at 10/day).
|
||||
@@ -30,7 +32,7 @@ const HISTORY_MAX = 10_000
|
||||
const WRITE_DEBOUNCE_MS = 1500
|
||||
const WRITE_RETRY_DELAYS = [50, 200, 800] // ms backoff on transient EBUSY/EPERM
|
||||
|
||||
let cache: AppState | null = null
|
||||
let cache: PersistedState | null = null
|
||||
let storePath = ''
|
||||
let pendingWrite: NodeJS.Timeout | null = null
|
||||
|
||||
@@ -43,7 +45,7 @@ function getStorePath(): string {
|
||||
return storePath
|
||||
}
|
||||
|
||||
function makeInitial(): AppState {
|
||||
function makeInitial(): PersistedState {
|
||||
const now = Date.now()
|
||||
return {
|
||||
exercises: SAMPLE_EXERCISES.map((e) => ({
|
||||
@@ -88,12 +90,11 @@ function quarantineCorrupt(p: string, reason: string): void {
|
||||
.replace(/Z$/, '')
|
||||
const dest = `${p}.corrupt-${stamp}`
|
||||
renameSync(p, dest)
|
||||
console.error(
|
||||
`[store] app-state.json was unreadable (${reason}); ` +
|
||||
`moved to ${dest} and starting fresh.`
|
||||
log.error(
|
||||
`[store] app-state.json was unreadable (${reason}); moved to ${dest} and starting fresh.`
|
||||
)
|
||||
} catch (e) {
|
||||
console.error('[store] failed to quarantine corrupt state file:', e)
|
||||
log.error('[store] failed to quarantine corrupt state file', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,8 +145,8 @@ function runMigrations(s: StoredState): StoredState {
|
||||
return cursor
|
||||
}
|
||||
|
||||
/** Coerce a (possibly partial) migrated state into a fully-formed AppState. */
|
||||
function coerce(s: StoredState): AppState {
|
||||
/** Coerce a (possibly partial) migrated state into a fully-formed PersistedState. */
|
||||
function coerce(s: StoredState): PersistedState {
|
||||
return {
|
||||
exercises: Array.isArray(s.exercises) ? (s.exercises as Exercise[]) : [],
|
||||
settings: {
|
||||
@@ -162,11 +163,12 @@ function coerce(s: StoredState): AppState {
|
||||
}
|
||||
}
|
||||
|
||||
function load(): AppState {
|
||||
function load(): PersistedState {
|
||||
const p = getStorePath()
|
||||
if (!existsSync(p)) {
|
||||
const initial = makeInitial()
|
||||
atomicWrite(
|
||||
// Cold path — sync write на инициализации (event-loop ещё не активен).
|
||||
atomicWriteSync(
|
||||
p,
|
||||
JSON.stringify(
|
||||
{ __schemaVersion: CURRENT_SCHEMA_VERSION, ...initial },
|
||||
@@ -180,7 +182,7 @@ function load(): AppState {
|
||||
try {
|
||||
raw = readFileSync(p, 'utf-8')
|
||||
} catch (e) {
|
||||
console.error('[store] cannot read state file:', e)
|
||||
log.error('[store] cannot read state file', e)
|
||||
return makeInitial() // do not quarantine — we can't read it anyway
|
||||
}
|
||||
let parsed: unknown
|
||||
@@ -235,8 +237,16 @@ export function clearHistory(beforeTs?: number): number {
|
||||
/**
|
||||
* Atomically write to `path` via a sibling .tmp file + rename. Retries a few
|
||||
* times on transient EBUSY/EPERM (AV/OneDrive holding the file).
|
||||
*
|
||||
* Async version (используется debounced scheduleWrite/flush) — раньше был
|
||||
* busy-loop `while (Date.now() < until)`, который морозил весь main process
|
||||
* на retry-delay (до 800мс). При активном AV это превращалось в видимое
|
||||
* залипание UI. Сейчас sleep через setTimeout-promise.
|
||||
*
|
||||
* Для процесса-выхода используется `atomicWriteSync` — там event-loop уже
|
||||
* не работает, async sleep не сработает.
|
||||
*/
|
||||
function atomicWrite(path: string, contents: string): void {
|
||||
async function atomicWrite(path: string, contents: string): Promise<void> {
|
||||
const tmp = `${path}.tmp`
|
||||
let lastErr: unknown
|
||||
for (let i = 0; i <= WRITE_RETRY_DELAYS.length; i++) {
|
||||
@@ -246,7 +256,6 @@ function atomicWrite(path: string, contents: string): void {
|
||||
return
|
||||
} catch (e) {
|
||||
lastErr = e
|
||||
// best-effort cleanup of the stale .tmp
|
||||
try {
|
||||
if (existsSync(tmp)) unlinkSync(tmp)
|
||||
} catch {
|
||||
@@ -254,40 +263,97 @@ function atomicWrite(path: string, contents: string): void {
|
||||
}
|
||||
const delay = WRITE_RETRY_DELAYS[i]
|
||||
if (delay === undefined) break
|
||||
// Synchronous sleep — write path is short and called outside the hot loop.
|
||||
await new Promise<void>((r) => setTimeout(r, delay))
|
||||
}
|
||||
}
|
||||
log.error('[store] atomic write failed after retries', lastErr)
|
||||
}
|
||||
|
||||
/**
|
||||
* Синхронный вариант для use-cases где event loop уже не работает
|
||||
* (process exit в `before-quit`). При retry — короткий sync sleep, потому
|
||||
* что иначе мы дропнем pending write при exit'е.
|
||||
*/
|
||||
function atomicWriteSync(path: string, contents: string): void {
|
||||
const tmp = `${path}.tmp`
|
||||
let lastErr: unknown
|
||||
for (let i = 0; i <= WRITE_RETRY_DELAYS.length; i++) {
|
||||
try {
|
||||
writeFileSync(tmp, contents, 'utf-8')
|
||||
renameSync(tmp, path)
|
||||
return
|
||||
} catch (e) {
|
||||
lastErr = e
|
||||
try {
|
||||
if (existsSync(tmp)) unlinkSync(tmp)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
const delay = WRITE_RETRY_DELAYS[i]
|
||||
if (delay === undefined) break
|
||||
// Event-loop остановлен, async sleep не вернётся — приходится spin.
|
||||
const until = Date.now() + delay
|
||||
while (Date.now() < until) {
|
||||
/* spin */
|
||||
}
|
||||
}
|
||||
}
|
||||
console.error('[store] atomic write failed after retries:', lastErr)
|
||||
log.error('[store] atomic sync write failed after retries', lastErr)
|
||||
}
|
||||
|
||||
function flush(): void {
|
||||
async function flush(): Promise<void> {
|
||||
if (!cache) return
|
||||
// Persist the schema version alongside the state so future migrations know
|
||||
// where to pick up from. The renderer never reads this key.
|
||||
const payload = { __schemaVersion: CURRENT_SCHEMA_VERSION, ...cache }
|
||||
atomicWrite(getStorePath(), JSON.stringify(payload, null, 2))
|
||||
await atomicWrite(getStorePath(), JSON.stringify(payload, null, 2))
|
||||
}
|
||||
|
||||
function flushSync(): void {
|
||||
if (!cache) return
|
||||
const payload = { __schemaVersion: CURRENT_SCHEMA_VERSION, ...cache }
|
||||
atomicWriteSync(getStorePath(), JSON.stringify(payload, null, 2))
|
||||
}
|
||||
|
||||
function scheduleWrite(): void {
|
||||
if (pendingWrite) return
|
||||
pendingWrite = setTimeout(() => {
|
||||
pendingWrite = null
|
||||
flush()
|
||||
void flush()
|
||||
}, WRITE_DEBOUNCE_MS)
|
||||
// Don't keep the event loop alive solely for a pending write — `before-quit`
|
||||
// calls `flushNow()` and we explicitly want the process to exit on schedule.
|
||||
pendingWrite.unref?.()
|
||||
}
|
||||
|
||||
export function getState(): AppState {
|
||||
/**
|
||||
* Internal persisted state — единственный source of truth. Включает историю.
|
||||
* Mutate напрямую (mutations внутри store.ts), затем scheduleWrite().
|
||||
*/
|
||||
export function getState(): PersistedState {
|
||||
if (!cache) cache = load()
|
||||
return cache
|
||||
}
|
||||
|
||||
/**
|
||||
* State для отправки renderer'у. Копия БЕЗ `history` — историю renderer
|
||||
* запрашивает отдельным IPC.getHistory. Раньше каждый markDone/snooze
|
||||
* отправлял весь state через evtStateChanged, и при 10k entries в истории
|
||||
* это 500KB JSON × N IPC mutations подряд → заметный лаг.
|
||||
*
|
||||
* Возвращаемая копия безопасна для мутации (ipc.ts накладывает на settings
|
||||
* актуальное OS-значение startWithWindows) — мы НЕ мутируем cache.
|
||||
*/
|
||||
export function getStateForRenderer(): AppState {
|
||||
const p = getState()
|
||||
return {
|
||||
exercises: p.exercises,
|
||||
settings: p.settings,
|
||||
challenges: p.challenges,
|
||||
gamesEnabled: p.gamesEnabled
|
||||
}
|
||||
}
|
||||
|
||||
export function getSettings(): Settings {
|
||||
return getState().settings
|
||||
}
|
||||
@@ -389,7 +455,9 @@ export function flushNow(): void {
|
||||
clearTimeout(pendingWrite)
|
||||
pendingWrite = null
|
||||
}
|
||||
flush()
|
||||
// before-quit вызывает нас когда event-loop уже на пути к выходу — async
|
||||
// promise не успеет resolved, поэтому sync.
|
||||
flushSync()
|
||||
}
|
||||
|
||||
export function getChallenges(): Challenge[] {
|
||||
@@ -436,3 +504,56 @@ export function setGameEnabled(id: GameId, enabled: boolean): void {
|
||||
state.gamesEnabled = { ...state.gamesEnabled, [id]: enabled }
|
||||
scheduleWrite()
|
||||
}
|
||||
|
||||
// ----- Export / Import -----
|
||||
|
||||
/**
|
||||
* Полный snapshot persisted-state (включая историю и schema-version).
|
||||
* Используется для backup'а или переноса на другую машину.
|
||||
*/
|
||||
export function exportState(): string {
|
||||
const state = getState()
|
||||
return JSON.stringify(
|
||||
{
|
||||
__schemaVersion: CURRENT_SCHEMA_VERSION,
|
||||
__exportedAt: new Date().toISOString(),
|
||||
__appVersion: app.getVersion(),
|
||||
...state
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Импорт snapshot'а. Перезаписывает текущий state. Возвращает true при
|
||||
* успехе. Идёт через тот же coerce + runMigrations что и load() — это
|
||||
* валидирует тип/диапазоны.
|
||||
*
|
||||
* НЕ объединяет с текущим state (merge сложен: дубликаты id, конфликты
|
||||
* settings) — простое replace. Перед импортом UI должен спросить
|
||||
* подтверждение.
|
||||
*/
|
||||
export function importState(raw: string): boolean {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(raw)
|
||||
} catch (e) {
|
||||
log.warn('[store] import: invalid JSON', e)
|
||||
return false
|
||||
}
|
||||
if (!isValidParsed(parsed)) {
|
||||
log.warn('[store] import: expected object')
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const migrated = runMigrations(parsed)
|
||||
const coerced = coerce(migrated)
|
||||
cache = coerced
|
||||
flushSync()
|
||||
return true
|
||||
} catch (e) {
|
||||
log.error('[store] import: coerce/migrate failed', e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { app, BrowserWindow } from 'electron'
|
||||
import { autoUpdater } from 'electron-updater'
|
||||
import { IPC } from '@shared/ipc'
|
||||
import type { UpdaterStatus } from '@shared/types'
|
||||
import { log } from './logger'
|
||||
|
||||
let currentStatus: UpdaterStatus = { kind: 'idle' }
|
||||
let lastCheckedAt: number | undefined
|
||||
@@ -98,7 +99,7 @@ export function initUpdater(): void {
|
||||
if (silentMode) {
|
||||
// Background check failed — keep previous status, don't show red banner.
|
||||
// Will retry on the next hourly tick.
|
||||
console.warn('[updater] silent check failed:', message)
|
||||
log.warn('[updater] silent check failed', message)
|
||||
return
|
||||
}
|
||||
setStatus({ kind: 'error', message })
|
||||
@@ -148,7 +149,7 @@ export async function checkForUpdates(
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
if (silentMode) {
|
||||
console.warn('[updater] silent check failed (sync):', message)
|
||||
log.warn('[updater] silent check failed (sync)', message)
|
||||
} else {
|
||||
setStatus({ kind: 'error', message })
|
||||
}
|
||||
@@ -172,5 +173,12 @@ export async function downloadUpdate(): Promise<void> {
|
||||
|
||||
export function quitAndInstall(): void {
|
||||
if (!app.isPackaged) return
|
||||
autoUpdater.quitAndInstall()
|
||||
// (isSilent=true, isForceRunAfter=true):
|
||||
// - isSilent: NSIS работает без UI-диалогов установки → restart занимает
|
||||
// ~1-2 сек вместо ~5-10 (без чёрного окна установщика на половину экрана).
|
||||
// - isForceRunAfter: гарантируем что после установки приложение запустится
|
||||
// автоматически, даже если в NSIS-конфиге runAfterFinish был выключен
|
||||
// для этого сценария. Без этого пользователь нажал «Рестарт» — и остался
|
||||
// без открытого приложения.
|
||||
autoUpdater.quitAndInstall(true, true)
|
||||
}
|
||||
|
||||
408
src/main/validate.test.ts
Normal file
408
src/main/validate.test.ts
Normal file
@@ -0,0 +1,408 @@
|
||||
/**
|
||||
* Тесты для IPC validation layer.
|
||||
*
|
||||
* Этот слой — security-boundary между renderer и main. Если он сломается,
|
||||
* compromised renderer сможет писать в стор NaN, отрицательные, Infinity,
|
||||
* сверхдлинные строки или undefined-enum'ы. Поэтому покрытие важно для:
|
||||
*
|
||||
* 1. Тип-проверок (строка/число/булево/массив)
|
||||
* 2. Range-checks (reps ∈ [1,9999], minutes ∈ [1,1440] и т.д.)
|
||||
* 3. Enum allowlist (theme/lang/notify-mode/stat)
|
||||
* 4. Edge cases: NaN, Infinity, MAX_SAFE_INTEGER, 0, отрицательные, длина строк
|
||||
* 5. Partial-patch semantics (отсутствие поля ≠ невалидное значение)
|
||||
* 6. Сложный nested case: quietHours с HH:MM regex и dedup days
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
validateExerciseInput,
|
||||
validateExercisePatch,
|
||||
validateChallengeInput,
|
||||
validateChallengePatch,
|
||||
validateSettingsPatch,
|
||||
validateId,
|
||||
validateActualReps,
|
||||
validateSnoozeMinutes
|
||||
} from './validate'
|
||||
|
||||
const validExercise = {
|
||||
name: 'Push-ups',
|
||||
reps: 10,
|
||||
intervalMinutes: 30,
|
||||
icon: 'Dumbbell',
|
||||
enabled: true
|
||||
}
|
||||
|
||||
describe('validateExerciseInput', () => {
|
||||
it('accepts a fully-formed valid input', () => {
|
||||
expect(validateExerciseInput(validExercise)).toEqual(validExercise)
|
||||
})
|
||||
|
||||
it('rejects non-objects', () => {
|
||||
expect(validateExerciseInput(null)).toBeNull()
|
||||
expect(validateExerciseInput(undefined)).toBeNull()
|
||||
expect(validateExerciseInput('string')).toBeNull()
|
||||
expect(validateExerciseInput(42)).toBeNull()
|
||||
expect(validateExerciseInput([])).toBeNull() // arrays not allowed
|
||||
})
|
||||
|
||||
it('rejects missing required fields', () => {
|
||||
expect(validateExerciseInput({ ...validExercise, name: undefined })).toBeNull()
|
||||
expect(validateExerciseInput({ ...validExercise, reps: undefined })).toBeNull()
|
||||
expect(
|
||||
validateExerciseInput({ ...validExercise, intervalMinutes: undefined })
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects out-of-range reps', () => {
|
||||
expect(validateExerciseInput({ ...validExercise, reps: 0 })).toBeNull()
|
||||
expect(validateExerciseInput({ ...validExercise, reps: -1 })).toBeNull()
|
||||
expect(validateExerciseInput({ ...validExercise, reps: 10_000 })).toBeNull()
|
||||
expect(validateExerciseInput({ ...validExercise, reps: NaN })).toBeNull()
|
||||
expect(
|
||||
validateExerciseInput({ ...validExercise, reps: Infinity })
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('truncates reps with Math.trunc (5.7 → 5)', () => {
|
||||
const r = validateExerciseInput({ ...validExercise, reps: 5.7 })
|
||||
expect(r?.reps).toBe(5)
|
||||
})
|
||||
|
||||
it('rejects out-of-range intervalMinutes (> 24h)', () => {
|
||||
expect(
|
||||
validateExerciseInput({ ...validExercise, intervalMinutes: 0 })
|
||||
).toBeNull()
|
||||
expect(
|
||||
validateExerciseInput({ ...validExercise, intervalMinutes: 1441 })
|
||||
).toBeNull()
|
||||
expect(
|
||||
validateExerciseInput({ ...validExercise, intervalMinutes: -1 })
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects empty name', () => {
|
||||
expect(validateExerciseInput({ ...validExercise, name: '' })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects name longer than MAX_STR_LEN (200)', () => {
|
||||
expect(
|
||||
validateExerciseInput({ ...validExercise, name: 'x'.repeat(201) })
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts name exactly at MAX_STR_LEN', () => {
|
||||
const r = validateExerciseInput({ ...validExercise, name: 'x'.repeat(200) })
|
||||
expect(r?.name).toHaveLength(200)
|
||||
})
|
||||
|
||||
it('defaults icon to Activity if missing', () => {
|
||||
const { icon: _ignored, ...rest } = validExercise
|
||||
void _ignored
|
||||
expect(validateExerciseInput(rest)?.icon).toBe('Activity')
|
||||
})
|
||||
|
||||
it('defaults enabled to true if missing', () => {
|
||||
const { enabled: _ignored, ...rest } = validExercise
|
||||
void _ignored
|
||||
expect(validateExerciseInput(rest)?.enabled).toBe(true)
|
||||
})
|
||||
|
||||
// Дизайн validateExerciseInput: required-поля (name/reps/intervalMinutes)
|
||||
// строгие — невалидное значение reject'ит весь input. Optional-поля
|
||||
// (icon/enabled) lenient — невалидное молча подменяется дефолтом. Это
|
||||
// фиксирует контракт: malicious renderer не сможет создать запись с
|
||||
// reps=-1, но если он пришлёт `enabled: 'yes'`, получит просто enabled=true.
|
||||
it('coerces invalid enabled to true (lenient default for optional fields)', () => {
|
||||
expect(
|
||||
validateExerciseInput({ ...validExercise, enabled: 'yes' })?.enabled
|
||||
).toBe(true)
|
||||
expect(
|
||||
validateExerciseInput({ ...validExercise, enabled: 1 })?.enabled
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
// А вот в patch optional-поля строгие — нет defaults, есть `if (v ===
|
||||
// undefined) return null`. Это правильнее: если renderer пришёл с патчем,
|
||||
// в котором есть поле, оно должно быть валидным.
|
||||
it('strict patch: rejects invalid enabled in patch (unlike input)', () => {
|
||||
expect(validateExercisePatch({ enabled: 'yes' })).toBeNull()
|
||||
expect(validateExercisePatch({ enabled: 1 })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects non-string name', () => {
|
||||
expect(validateExerciseInput({ ...validExercise, name: 42 })).toBeNull()
|
||||
expect(validateExerciseInput({ ...validExercise, name: null })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateExercisePatch', () => {
|
||||
it('accepts an empty patch (no-op update)', () => {
|
||||
expect(validateExercisePatch({})).toEqual({})
|
||||
})
|
||||
|
||||
it('accepts partial patches', () => {
|
||||
expect(validateExercisePatch({ reps: 12 })).toEqual({ reps: 12 })
|
||||
expect(validateExercisePatch({ name: 'New' })).toEqual({ name: 'New' })
|
||||
expect(validateExercisePatch({ enabled: false })).toEqual({ enabled: false })
|
||||
})
|
||||
|
||||
it('rejects patch with a single invalid field', () => {
|
||||
// Patch is all-or-nothing: one bad field rejects the whole patch.
|
||||
expect(validateExercisePatch({ name: 'OK', reps: -1 })).toBeNull()
|
||||
expect(validateExercisePatch({ name: '', reps: 10 })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects non-object', () => {
|
||||
expect(validateExercisePatch(null)).toBeNull()
|
||||
expect(validateExercisePatch([])).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts nextFireAt and lastDoneAt with valid ranges', () => {
|
||||
expect(validateExercisePatch({ nextFireAt: 0 })).toEqual({ nextFireAt: 0 })
|
||||
expect(validateExercisePatch({ lastDoneAt: 1_000_000_000_000 })).toEqual({
|
||||
lastDoneAt: 1_000_000_000_000
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects negative timestamps', () => {
|
||||
expect(validateExercisePatch({ nextFireAt: -1 })).toBeNull()
|
||||
expect(validateExercisePatch({ lastDoneAt: -1 })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects NaN/Infinity timestamps', () => {
|
||||
expect(validateExercisePatch({ nextFireAt: NaN })).toBeNull()
|
||||
expect(validateExercisePatch({ nextFireAt: Infinity })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateChallengeInput', () => {
|
||||
const valid = {
|
||||
name: 'Deaths → squats',
|
||||
gameId: 'dota2',
|
||||
stat: 'deaths' as const,
|
||||
multiplier: 3,
|
||||
exerciseName: 'Приседания',
|
||||
icon: 'Activity',
|
||||
enabled: true
|
||||
}
|
||||
|
||||
it('accepts valid input', () => {
|
||||
expect(validateChallengeInput(valid)).toEqual(valid)
|
||||
})
|
||||
|
||||
it('rejects unknown stat', () => {
|
||||
expect(validateChallengeInput({ ...valid, stat: 'pizza' })).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts all valid stats', () => {
|
||||
const stats = ['deaths', 'kills', 'assists', 'last_hits', 'denies', 'duration_min']
|
||||
for (const stat of stats) {
|
||||
expect(validateChallengeInput({ ...valid, stat })).not.toBeNull()
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects negative multiplier', () => {
|
||||
expect(validateChallengeInput({ ...valid, multiplier: -1 })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects multiplier > 1000', () => {
|
||||
expect(validateChallengeInput({ ...valid, multiplier: 1001 })).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts zero multiplier (legitimate "disable" semantics)', () => {
|
||||
expect(validateChallengeInput({ ...valid, multiplier: 0 })?.multiplier).toBe(0)
|
||||
})
|
||||
|
||||
it('accepts fractional multiplier (e.g. 0.5×)', () => {
|
||||
expect(validateChallengeInput({ ...valid, multiplier: 0.5 })?.multiplier).toBe(0.5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateChallengePatch', () => {
|
||||
it('accepts empty patch', () => {
|
||||
expect(validateChallengePatch({})).toEqual({})
|
||||
})
|
||||
|
||||
it('rejects unknown stat in patch', () => {
|
||||
expect(validateChallengePatch({ stat: 'mana' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateSettingsPatch', () => {
|
||||
it('accepts empty patch', () => {
|
||||
expect(validateSettingsPatch({})).toEqual({})
|
||||
})
|
||||
|
||||
it('accepts each boolean toggle independently', () => {
|
||||
expect(validateSettingsPatch({ globalEnabled: false })).toEqual({
|
||||
globalEnabled: false
|
||||
})
|
||||
expect(validateSettingsPatch({ soundEnabled: true })).toEqual({
|
||||
soundEnabled: true
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects unknown theme', () => {
|
||||
expect(validateSettingsPatch({ theme: 'sepia' })).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts all valid themes', () => {
|
||||
expect(validateSettingsPatch({ theme: 'light' })?.theme).toBe('light')
|
||||
expect(validateSettingsPatch({ theme: 'dark' })?.theme).toBe('dark')
|
||||
expect(validateSettingsPatch({ theme: 'system' })?.theme).toBe('system')
|
||||
})
|
||||
|
||||
it('rejects unknown language', () => {
|
||||
expect(validateSettingsPatch({ language: 'fr' })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects unknown notification mode', () => {
|
||||
expect(validateSettingsPatch({ notificationMode: 'sms' })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects out-of-range snoozeMinutes', () => {
|
||||
expect(validateSettingsPatch({ snoozeMinutes: 0 })).toBeNull()
|
||||
expect(validateSettingsPatch({ snoozeMinutes: 1441 })).toBeNull()
|
||||
expect(validateSettingsPatch({ snoozeMinutes: -5 })).toBeNull()
|
||||
})
|
||||
|
||||
describe('quietHours subobject', () => {
|
||||
const baseQh = {
|
||||
enabled: true,
|
||||
from: '22:00',
|
||||
to: '08:00',
|
||||
days: [0, 1, 2, 3, 4, 5, 6]
|
||||
}
|
||||
|
||||
it('accepts a valid quietHours', () => {
|
||||
expect(validateSettingsPatch({ quietHours: baseQh })?.quietHours).toEqual(
|
||||
baseQh
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects non-object quietHours', () => {
|
||||
expect(validateSettingsPatch({ quietHours: 'always' })).toBeNull()
|
||||
expect(validateSettingsPatch({ quietHours: null })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects malformed HH:MM', () => {
|
||||
expect(
|
||||
validateSettingsPatch({ quietHours: { ...baseQh, from: '2500' } })
|
||||
).toBeNull()
|
||||
expect(
|
||||
validateSettingsPatch({ quietHours: { ...baseQh, to: 'bedtime' } })
|
||||
).toBeNull()
|
||||
expect(
|
||||
validateSettingsPatch({ quietHours: { ...baseQh, from: '8' } })
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts HH:MM with 1-digit hour (9:30)', () => {
|
||||
// Regex is /^\d{1,2}:\d{2}$/ — допускаем «9:30», парсер сам разберётся.
|
||||
const r = validateSettingsPatch({
|
||||
quietHours: { ...baseQh, from: '9:30' }
|
||||
})
|
||||
expect(r?.quietHours?.from).toBe('9:30')
|
||||
})
|
||||
|
||||
it('dedupes days array', () => {
|
||||
const r = validateSettingsPatch({
|
||||
quietHours: { ...baseQh, days: [1, 2, 2, 3, 1] }
|
||||
})
|
||||
expect(r?.quietHours?.days).toEqual([1, 2, 3])
|
||||
})
|
||||
|
||||
it('rejects out-of-range day (7)', () => {
|
||||
expect(
|
||||
validateSettingsPatch({ quietHours: { ...baseQh, days: [0, 7] } })
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects negative day', () => {
|
||||
expect(
|
||||
validateSettingsPatch({ quietHours: { ...baseQh, days: [-1] } })
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects non-array days', () => {
|
||||
expect(
|
||||
validateSettingsPatch({ quietHours: { ...baseQh, days: 'all' } })
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts empty days array (window effectively disabled)', () => {
|
||||
const r = validateSettingsPatch({
|
||||
quietHours: { ...baseQh, days: [] }
|
||||
})
|
||||
expect(r?.quietHours?.days).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateId', () => {
|
||||
it('accepts reasonable id strings', () => {
|
||||
expect(validateId('abc')).toBe('abc')
|
||||
expect(validateId('uuid-v4-style-thing-123')).toBe('uuid-v4-style-thing-123')
|
||||
})
|
||||
|
||||
it('rejects non-strings', () => {
|
||||
expect(validateId(42)).toBeNull()
|
||||
expect(validateId(null)).toBeNull()
|
||||
expect(validateId(undefined)).toBeNull()
|
||||
expect(validateId({})).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects empty string', () => {
|
||||
expect(validateId('')).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects strings longer than 64 chars', () => {
|
||||
expect(validateId('x'.repeat(65))).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateActualReps', () => {
|
||||
it('returns undefined for undefined/null (means: use planned reps)', () => {
|
||||
expect(validateActualReps(undefined)).toBeUndefined()
|
||||
expect(validateActualReps(null)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('accepts zero (partial completion = "did 0 of 10")', () => {
|
||||
expect(validateActualReps(0)).toBe(0)
|
||||
})
|
||||
|
||||
it('accepts large values up to cap', () => {
|
||||
expect(validateActualReps(100_000)).toBe(100_000)
|
||||
})
|
||||
|
||||
it('rejects negative', () => {
|
||||
expect(validateActualReps(-1)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects values above cap', () => {
|
||||
expect(validateActualReps(100_001)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects NaN/Infinity', () => {
|
||||
expect(validateActualReps(NaN)).toBeUndefined()
|
||||
expect(validateActualReps(Infinity)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateSnoozeMinutes', () => {
|
||||
it('accepts valid minutes', () => {
|
||||
expect(validateSnoozeMinutes(15)).toBe(15)
|
||||
expect(validateSnoozeMinutes(1)).toBe(1)
|
||||
expect(validateSnoozeMinutes(1440)).toBe(1440)
|
||||
})
|
||||
|
||||
it('rejects 0 and above 24h', () => {
|
||||
expect(validateSnoozeMinutes(0)).toBeNull()
|
||||
expect(validateSnoozeMinutes(1441)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects non-numbers', () => {
|
||||
expect(validateSnoozeMinutes('15')).toBeNull()
|
||||
expect(validateSnoozeMinutes(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -18,7 +18,8 @@ import type {
|
||||
Settings,
|
||||
Theme,
|
||||
Language,
|
||||
NotificationMode
|
||||
NotificationMode,
|
||||
ReminderCategory
|
||||
} from '@shared/types'
|
||||
|
||||
const MAX_STR_LEN = 200
|
||||
@@ -33,6 +34,12 @@ const VALID_STATS: GameStat[] = [
|
||||
'denies',
|
||||
'duration_min'
|
||||
]
|
||||
const VALID_CATEGORIES: ReminderCategory[] = [
|
||||
'exercise',
|
||||
'hydration',
|
||||
'eyes',
|
||||
'posture'
|
||||
]
|
||||
const HHMM_RE = /^\d{1,2}:\d{2}$/
|
||||
|
||||
function isObj(v: unknown): v is Record<string, unknown> {
|
||||
@@ -84,6 +91,17 @@ export function validateExerciseInput(
|
||||
const intervalMinutes = intInRange(raw.intervalMinutes, 1, 24 * 60)
|
||||
const icon = safeStr(raw.icon, 64) ?? 'Activity'
|
||||
const enabled = bool(raw.enabled) ?? true
|
||||
const category = oneOf(raw.category, VALID_CATEGORIES) // undefined OK = default
|
||||
const dailyGoal =
|
||||
raw.dailyGoal === undefined || raw.dailyGoal === null
|
||||
? undefined
|
||||
: intInRange(raw.dailyGoal, 1, 100_000)
|
||||
// dailyGoal: undefined = не задан (нет soft-cap'a), null от UI приводим к
|
||||
// undefined; иначе — должен пройти int-range, иначе reject (нельзя
|
||||
// отправить из renderer'а NaN/негатив и тихо обнулить).
|
||||
if (raw.dailyGoal !== undefined && raw.dailyGoal !== null && dailyGoal === undefined) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
name === undefined ||
|
||||
reps === undefined ||
|
||||
@@ -91,7 +109,18 @@ export function validateExerciseInput(
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return { name, reps, intervalMinutes, icon, enabled }
|
||||
const out: Omit<Exercise, 'id' | 'nextFireAt' | 'lastDoneAt'> = {
|
||||
name,
|
||||
reps,
|
||||
intervalMinutes,
|
||||
icon,
|
||||
enabled
|
||||
}
|
||||
if (category !== undefined) out.category = category
|
||||
if (dailyGoal !== undefined) out.dailyGoal = dailyGoal
|
||||
const adaptive = bool(raw.adaptive)
|
||||
if (adaptive !== undefined) out.adaptive = adaptive
|
||||
return out
|
||||
}
|
||||
|
||||
export function validateExercisePatch(
|
||||
@@ -124,6 +153,26 @@ export function validateExercisePatch(
|
||||
if (v === undefined) return null
|
||||
out.enabled = v
|
||||
}
|
||||
if ('category' in raw) {
|
||||
const v = oneOf(raw.category, VALID_CATEGORIES)
|
||||
if (v === undefined) return null
|
||||
out.category = v
|
||||
}
|
||||
if ('dailyGoal' in raw) {
|
||||
// Допустим null/undefined как «снять goal».
|
||||
if (raw.dailyGoal === null || raw.dailyGoal === undefined) {
|
||||
out.dailyGoal = undefined
|
||||
} else {
|
||||
const v = intInRange(raw.dailyGoal, 1, 100_000)
|
||||
if (v === undefined) return null
|
||||
out.dailyGoal = v
|
||||
}
|
||||
}
|
||||
if ('adaptive' in raw) {
|
||||
const v = bool(raw.adaptive)
|
||||
if (v === undefined) return null
|
||||
out.adaptive = v
|
||||
}
|
||||
// Allow scheduler-controlled fields to be patched (used by store.markDone
|
||||
// through this same boundary), but range-check them.
|
||||
if ('nextFireAt' in raw) {
|
||||
@@ -244,6 +293,27 @@ export function validateSettingsPatch(raw: unknown): Partial<Settings> | null {
|
||||
if (v === undefined) return null
|
||||
out.soundEnabled = v
|
||||
}
|
||||
if ('voicePromptsEnabled' in raw) {
|
||||
const v = bool(raw.voicePromptsEnabled)
|
||||
if (v === undefined) return null
|
||||
out.voicePromptsEnabled = v
|
||||
}
|
||||
if ('meetingAutoPause' in raw) {
|
||||
const v = bool(raw.meetingAutoPause)
|
||||
if (v === undefined) return null
|
||||
out.meetingAutoPause = v
|
||||
}
|
||||
if ('lastSeenVersion' in raw) {
|
||||
// Принимаем строку 0.0.0 .. 999.999.999 (semver-light) или null/undefined
|
||||
// для сброса.
|
||||
if (raw.lastSeenVersion === null || raw.lastSeenVersion === undefined) {
|
||||
out.lastSeenVersion = undefined
|
||||
} else {
|
||||
const v = safeStr(raw.lastSeenVersion, 32)
|
||||
if (v === undefined || !/^\d+\.\d+\.\d+(-[\w.]+)?$/.test(v)) return null
|
||||
out.lastSeenVersion = v
|
||||
}
|
||||
}
|
||||
if ('notificationMode' in raw) {
|
||||
const v = oneOf(raw.notificationMode, VALID_NOTIFY)
|
||||
if (v === undefined) return null
|
||||
|
||||
@@ -106,7 +106,12 @@ export function createMainWindow(showImmediately = true): BrowserWindow {
|
||||
...(icon ? { icon } : {}),
|
||||
webPreferences: {
|
||||
preload: preloadPath(),
|
||||
sandbox: false,
|
||||
// sandbox: true — preload использует только contextBridge + ipcRenderer
|
||||
// (оба sandbox-safe), никаких Node-built-ins (fs/path/child_process).
|
||||
// Sandbox изолирует renderer от Chromium GPU/IPC процессов на уровне
|
||||
// OS-сэндбокса; даже RCE через зависимости renderer'а не получит
|
||||
// полного Node-доступа из preload.
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
}
|
||||
@@ -171,7 +176,7 @@ export function createReminderWindow(): BrowserWindow {
|
||||
...(icon ? { icon } : {}),
|
||||
webPreferences: {
|
||||
preload: preloadPath(),
|
||||
sandbox: false,
|
||||
sandbox: true, // см. createMainWindow — preload не использует Node.
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ const api = {
|
||||
getAccentColor: (): Promise<string> => ipcRenderer.invoke(IPC.getAccentColor),
|
||||
getOsTheme: (): Promise<'light' | 'dark'> =>
|
||||
ipcRenderer.invoke(IPC.getOsTheme),
|
||||
getAppVersion: (): Promise<string> => ipcRenderer.invoke(IPC.getAppVersion),
|
||||
|
||||
pauseAll: (): Promise<void> => ipcRenderer.invoke(IPC.pauseAll),
|
||||
resumeAll: (): Promise<void> => ipcRenderer.invoke(IPC.resumeAll),
|
||||
@@ -96,7 +97,7 @@ const api = {
|
||||
id: GameId,
|
||||
stats: Record<string, number>
|
||||
): Promise<void> =>
|
||||
ipcRenderer.invoke('dev:simulateMatchEnd', id, stats)
|
||||
ipcRenderer.invoke(IPC.devSimulateMatchEnd, id, stats)
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -105,8 +106,10 @@ const api = {
|
||||
ipcRenderer.invoke(IPC.updaterStatus),
|
||||
updaterCheck: (): Promise<UpdaterStatus> =>
|
||||
ipcRenderer.invoke(IPC.updaterCheck),
|
||||
updaterDownload: (): Promise<void> => ipcRenderer.invoke(IPC.updaterDownload),
|
||||
updaterInstall: (): Promise<void> => ipcRenderer.invoke(IPC.updaterInstall),
|
||||
// Fire-and-forget. Прогресс и завершение прилетают через onUpdaterStatus —
|
||||
// renderer не должен `await`'ить, иначе busy-state висит весь download.
|
||||
updaterDownload: (): void => ipcRenderer.send(IPC.updaterDownload),
|
||||
updaterInstall: (): void => ipcRenderer.send(IPC.updaterInstall),
|
||||
|
||||
// History
|
||||
getHistory: (sinceMs?: number): Promise<HistoryEntry[]> =>
|
||||
@@ -114,6 +117,12 @@ const api = {
|
||||
clearHistory: (beforeTs?: number): Promise<number> =>
|
||||
ipcRenderer.invoke(IPC.clearHistory, beforeTs),
|
||||
|
||||
// Export / Import — открывают native save/open dialogs из main process.
|
||||
exportState: (): Promise<{ ok: boolean; path: string | null }> =>
|
||||
ipcRenderer.invoke(IPC.exportState),
|
||||
importState: (): Promise<{ ok: boolean; error?: string }> =>
|
||||
ipcRenderer.invoke(IPC.importState),
|
||||
|
||||
onTick: (h: Handler<Tick[]>): Unsub => on(IPC.evtTick, h),
|
||||
onFire: (h: Handler<Exercise>): Unsub => on(IPC.evtFire, h),
|
||||
onMatchEnd: (h: Handler<MatchSummary>): Unsub => on(IPC.evtMatchEnd, h),
|
||||
|
||||
@@ -3,11 +3,14 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; script-src 'self'" />
|
||||
<!--
|
||||
CSP: всё локально, без внешних origins. Шрифты подгружаются через
|
||||
@fontsource/* импорты в globals.css. style-src 'unsafe-inline' нужен
|
||||
для Tailwind utility-классов и инлайн-стилей framer-motion. font-src
|
||||
включает data: на случай если кто-то вставит base64 SVG-glyph.
|
||||
-->
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:; script-src 'self'; connect-src 'self'; base-uri 'self'; frame-ancestors 'none'" />
|
||||
<title>Exercise Reminder</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700;12..96,800&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -4,6 +4,8 @@ import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { Sidebar } from './components/Sidebar'
|
||||
import { Titlebar } from './components/Titlebar'
|
||||
import { ErrorBoundary } from './components/ErrorBoundary'
|
||||
import { WhatsNewModal } from './components/WhatsNewModal'
|
||||
import { unseenVersions } from '@shared/release-notes'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import Exercises from './pages/Exercises'
|
||||
import GamesPage from './pages/Games'
|
||||
@@ -17,7 +19,12 @@ let backendSubscribed = false
|
||||
|
||||
export default function App(): JSX.Element {
|
||||
const hydrated = useAppStore((s) => s.hydrated)
|
||||
const settings = useAppStore((s) => s.state?.settings)
|
||||
const [mobileNavOpen, setMobileNavOpen] = useState(false)
|
||||
const [whatsNew, setWhatsNew] = useState<{
|
||||
open: boolean
|
||||
versions: string[]
|
||||
}>({ open: false, versions: [] })
|
||||
|
||||
useEffect(() => {
|
||||
if (backendSubscribed) return undefined
|
||||
@@ -29,6 +36,43 @@ export default function App(): JSX.Element {
|
||||
}
|
||||
}, [])
|
||||
|
||||
// После хидрации сверяем текущую версию приложения с lastSeenVersion.
|
||||
// Если первая хидрация и lastSeenVersion ещё не записан — это либо
|
||||
// первый запуск, либо обновление со старой версии (где поля не было) —
|
||||
// в любом случае пишем текущую версию и НЕ показываем модалку (мы не
|
||||
// хотим бить нового пользователя CHANGELOG'ом).
|
||||
// Если lastSeenVersion есть и не совпадает с current → показываем.
|
||||
useEffect(() => {
|
||||
if (!hydrated || !settings) return
|
||||
void window.api.getAppVersion().then((current) => {
|
||||
const last = settings.lastSeenVersion
|
||||
if (!last) {
|
||||
// Первая запись — сохраняем тихо.
|
||||
window.api.updateSettings({ lastSeenVersion: current })
|
||||
return
|
||||
}
|
||||
if (last !== current) {
|
||||
const versions = unseenVersions(current, last)
|
||||
if (versions.length > 0) {
|
||||
setWhatsNew({ open: true, versions })
|
||||
} else {
|
||||
// Версии есть, заметок нет — просто обновляем.
|
||||
window.api.updateSettings({ lastSeenVersion: current })
|
||||
}
|
||||
}
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [hydrated])
|
||||
|
||||
function closeWhatsNew(): void {
|
||||
setWhatsNew({ open: false, versions: [] })
|
||||
// Записываем «видел» только после закрытия — если пользователь убил
|
||||
// окно процессом до клика, при следующем запуске покажется снова.
|
||||
void window.api.getAppVersion().then((current) => {
|
||||
window.api.updateSettings({ lastSeenVersion: current })
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<HashRouter>
|
||||
@@ -50,6 +94,11 @@ export default function App(): JSX.Element {
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
<WhatsNewModal
|
||||
open={whatsNew.open}
|
||||
versions={whatsNew.versions}
|
||||
onClose={closeWhatsNew}
|
||||
/>
|
||||
</div>
|
||||
</HashRouter>
|
||||
</ErrorBoundary>
|
||||
|
||||
@@ -20,6 +20,7 @@ import type {
|
||||
import { statLabel } from '@shared/types'
|
||||
import { Icon } from './lib/icon'
|
||||
import { formatInterval } from './lib/format'
|
||||
import { speak } from './lib/tts'
|
||||
import { translate, translateN } from './i18n'
|
||||
|
||||
type Mode =
|
||||
@@ -41,11 +42,32 @@ export default function ReminderApp(): JSX.Element {
|
||||
const u0 = window.api.onStateChanged((s) => setSettings(s.settings))
|
||||
const u1 = window.api.onFire((ex) => {
|
||||
setMode({ kind: 'exercise', exercise: ex })
|
||||
if (settingsRef.current?.soundEnabled) playBeep()
|
||||
const s = settingsRef.current
|
||||
if (s?.soundEnabled) playBeep()
|
||||
if (s?.voicePromptsEnabled) {
|
||||
// «{exercise.name}, {n} раз/раза/раз». Простая локальная фраза без
|
||||
// ключа в dict — короткая команда, не нуждается в полном переводе.
|
||||
const lang = s.language ?? 'ru'
|
||||
const phrase =
|
||||
lang === 'ru'
|
||||
? `${ex.name}. ${ex.reps} ${repWordRu(ex.reps)}`
|
||||
: `${ex.name}. ${ex.reps} ${ex.reps === 1 ? 'rep' : 'reps'}`
|
||||
speak(phrase, lang)
|
||||
}
|
||||
})
|
||||
const u2 = window.api.onMatchEnd((summary) => {
|
||||
setMode({ kind: 'match', summary, done: new Set() })
|
||||
if (settingsRef.current?.soundEnabled) playBeep()
|
||||
const s = settingsRef.current
|
||||
if (s?.soundEnabled) playBeep()
|
||||
if (s?.voicePromptsEnabled) {
|
||||
const total = summary.results.reduce((acc, r) => acc + r.reps, 0)
|
||||
const lang = s.language ?? 'ru'
|
||||
const phrase =
|
||||
lang === 'ru'
|
||||
? `Матч завершён. ${total} ${repWordRu(total)} ждут.`
|
||||
: `Match complete. ${total} ${total === 1 ? 'rep' : 'reps'} await.`
|
||||
speak(phrase, lang)
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
u0()
|
||||
@@ -201,7 +223,7 @@ function ExerciseReminder({
|
||||
</motion.div>
|
||||
|
||||
<div className="text-[13px] uppercase tracking-[0.18em] text-accent font-bold">
|
||||
{t('reminder.kicker')}
|
||||
{t(`category.${exercise.category ?? 'exercise'}.cta`)}
|
||||
</div>
|
||||
<h1 className="font-serif text-[30px] leading-tight tracking-tight mt-2 mb-3 font-bold">
|
||||
{exercise.name}
|
||||
@@ -478,6 +500,18 @@ function ChallengeRow({
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* CLDR-минимум для русского склонения «раз». 1 раз / 2 раза / 5 раз.
|
||||
* Не тащим сюда полную плюрализацию из i18n — это TTS-only фраза.
|
||||
*/
|
||||
function repWordRu(n: number): string {
|
||||
const m10 = Math.abs(n) % 10
|
||||
const m100 = Math.abs(n) % 100
|
||||
if (m10 === 1 && m100 !== 11) return 'раз'
|
||||
if (m10 >= 2 && m10 <= 4 && (m100 < 10 || m100 >= 20)) return 'раза'
|
||||
return 'раз'
|
||||
}
|
||||
|
||||
function playBeep(): void {
|
||||
try {
|
||||
const Ctx =
|
||||
|
||||
128
src/renderer/src/components/AchievementsCard.tsx
Normal file
128
src/renderer/src/components/AchievementsCard.tsx
Normal file
@@ -0,0 +1,128 @@
|
||||
import { useMemo } from 'react'
|
||||
import { Award, Activity, Flame, Sparkles, TrendingUp, Lock } from 'lucide-react'
|
||||
import type { Exercise, HistoryEntry } from '@shared/types'
|
||||
import {
|
||||
computeAchievements,
|
||||
type AchievementProgress
|
||||
} from '../lib/achievements'
|
||||
import { useT } from '../i18n'
|
||||
|
||||
const ICON_BY_NAME = {
|
||||
Activity,
|
||||
Flame,
|
||||
Sparkles,
|
||||
TrendingUp
|
||||
} as const
|
||||
|
||||
type Props = {
|
||||
history: HistoryEntry[]
|
||||
exercises: Exercise[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Сетка достижений. Показывает: (1) все unlocked прямо, (2) первое
|
||||
* unlocked-в-прогрессе (ближайшее по %% — мотивация), (3) остальные
|
||||
* как блёклые «locked». В компактной grid 4-в-ряд.
|
||||
*/
|
||||
export function AchievementsCard({ history, exercises }: Props): JSX.Element {
|
||||
const { t } = useT()
|
||||
|
||||
const achievements = useMemo(
|
||||
() => computeAchievements(history, exercises),
|
||||
[history, exercises]
|
||||
)
|
||||
|
||||
const unlocked = achievements.filter((a) => a.unlocked)
|
||||
const locked = achievements.filter((a) => !a.unlocked)
|
||||
// Сортируем locked по близости к unlock'у — чтобы «осталось 12»
|
||||
// оказалось вверху, а «осталось 9999» внизу.
|
||||
const nearestLocked = [...locked].sort((a, b) => {
|
||||
const ap = a.current / a.target
|
||||
const bp = b.current / b.target
|
||||
return bp - ap
|
||||
})
|
||||
|
||||
// Показываем: все unlocked + first 2 nearest locked (preview-мотивация).
|
||||
const visible = [...unlocked, ...nearestLocked.slice(0, 2)]
|
||||
|
||||
if (visible.length === 0) return <></>
|
||||
|
||||
return (
|
||||
<div className="bg-surface rounded-2xl p-5 shadow-card dark:ring-0.5 dark:ring-hairline/30">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-7 h-7 rounded-lg bg-accent text-white grid place-items-center">
|
||||
<Award size={14} strokeWidth={2.6} />
|
||||
</div>
|
||||
<div className="text-[14px] text-text/75 font-semibold">
|
||||
{t('achievements.title')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-[12px] text-text/55 font-mono-num font-medium">
|
||||
{t('achievements.unlocked_of', {
|
||||
n: unlocked.length,
|
||||
total: achievements.length
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2">
|
||||
{visible.map((a) => (
|
||||
<Badge key={a.def.id} a={a} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Badge({ a }: { a: AchievementProgress }): JSX.Element {
|
||||
const { t } = useT()
|
||||
const IconCmp = ICON_BY_NAME[a.def.icon as keyof typeof ICON_BY_NAME] ?? Award
|
||||
const pct = Math.min(100, Math.round((a.current / a.target) * 100))
|
||||
const toneBg = {
|
||||
accent: 'bg-accent',
|
||||
warning: 'bg-warning',
|
||||
success: 'bg-success',
|
||||
info: 'bg-info'
|
||||
}[a.def.tone]
|
||||
|
||||
return (
|
||||
<div
|
||||
className={[
|
||||
'rounded-xl p-2.5 transition-opacity',
|
||||
a.unlocked ? 'bg-surface-2' : 'bg-surface-2 opacity-55'
|
||||
].join(' ')}
|
||||
title={t(a.def.descKey, { target: a.target })}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-1.5">
|
||||
<div
|
||||
className={[
|
||||
'w-7 h-7 rounded-lg grid place-items-center text-white shrink-0',
|
||||
a.unlocked ? toneBg : 'bg-text/30'
|
||||
].join(' ')}
|
||||
>
|
||||
{a.unlocked ? (
|
||||
<IconCmp size={14} strokeWidth={2.4} />
|
||||
) : (
|
||||
<Lock size={12} strokeWidth={2.4} />
|
||||
)}
|
||||
</div>
|
||||
<div className="text-[12px] font-semibold truncate">
|
||||
{t(a.def.titleKey)}
|
||||
</div>
|
||||
</div>
|
||||
{!a.unlocked && (
|
||||
<>
|
||||
<div className="h-1 rounded-full bg-text/10 overflow-hidden">
|
||||
<div
|
||||
className={['h-full', toneBg].join(' ')}
|
||||
style={{ width: `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-[10px] text-text/55 mt-1 font-mono-num font-medium">
|
||||
{t('achievements.progress', { n: a.target - a.current })}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { Exercise } from '@shared/types'
|
||||
import type { Exercise, ReminderCategory } from '@shared/types'
|
||||
import { REMINDER_CATEGORIES } from '@shared/types'
|
||||
import { Modal } from './ui/Modal'
|
||||
import { Button } from './ui/Button'
|
||||
import { ICON_CHOICES, Icon } from '../lib/icon'
|
||||
@@ -11,6 +12,10 @@ type Draft = {
|
||||
icon: string
|
||||
intervalMinutes: number
|
||||
enabled: boolean
|
||||
category: ReminderCategory
|
||||
/** undefined = без дневной цели (только interval). */
|
||||
dailyGoal?: number
|
||||
adaptive?: boolean
|
||||
}
|
||||
|
||||
const EMPTY: Draft = {
|
||||
@@ -18,7 +23,10 @@ const EMPTY: Draft = {
|
||||
reps: 10,
|
||||
icon: 'Activity',
|
||||
intervalMinutes: 30,
|
||||
enabled: true
|
||||
enabled: true,
|
||||
category: 'exercise',
|
||||
dailyGoal: undefined,
|
||||
adaptive: false
|
||||
}
|
||||
|
||||
type Props = {
|
||||
@@ -44,7 +52,10 @@ export function ExerciseEditor({
|
||||
reps: exercise.reps,
|
||||
icon: exercise.icon,
|
||||
intervalMinutes: exercise.intervalMinutes,
|
||||
enabled: exercise.enabled
|
||||
enabled: exercise.enabled,
|
||||
category: exercise.category ?? 'exercise',
|
||||
dailyGoal: exercise.dailyGoal,
|
||||
adaptive: exercise.adaptive ?? false
|
||||
})
|
||||
} else {
|
||||
setDraft(EMPTY)
|
||||
@@ -101,6 +112,26 @@ export function ExerciseEditor({
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label={t('editor.field.category')}>
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{REMINDER_CATEGORIES.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
onClick={() => setDraft({ ...draft, category: c })}
|
||||
className={[
|
||||
'h-10 px-2 rounded-xl text-[13px] font-semibold transition-all active:scale-95 truncate',
|
||||
draft.category === c
|
||||
? 'bg-accent text-white'
|
||||
: 'bg-surface-2 text-text/65 hover:text-text'
|
||||
].join(' ')}
|
||||
>
|
||||
{t(`category.${c}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label={t('editor.field.reps')}>
|
||||
<input
|
||||
@@ -132,6 +163,58 @@ export function ExerciseEditor({
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field label={t('editor.field.daily_goal')}>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder={t('editor.field.daily_goal.placeholder')}
|
||||
value={draft.dailyGoal ?? ''}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value
|
||||
if (v === '') setDraft({ ...draft, dailyGoal: undefined })
|
||||
else
|
||||
setDraft({
|
||||
...draft,
|
||||
dailyGoal: Math.max(1, Number(v) || 1)
|
||||
})
|
||||
}}
|
||||
className="ios-input font-mono-num flex-1"
|
||||
/>
|
||||
{draft.dailyGoal !== undefined && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDraft({ ...draft, dailyGoal: undefined })}
|
||||
className="h-9 px-3 rounded-xl bg-surface-2 text-text/65 text-[13px] font-semibold hover:text-text"
|
||||
>
|
||||
{t('editor.field.daily_goal.clear')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-[12px] text-text/55 mt-1.5 leading-snug">
|
||||
{t('editor.field.daily_goal.hint')}
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
<label className="flex items-start gap-3 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.adaptive ?? false}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, adaptive: e.target.checked })
|
||||
}
|
||||
className="mt-0.5 w-4 h-4 accent-accent"
|
||||
/>
|
||||
<div>
|
||||
<div className="text-[14px] font-semibold leading-tight">
|
||||
{t('editor.field.adaptive.label')}
|
||||
</div>
|
||||
<div className="text-[12px] text-text/55 mt-1 leading-snug">
|
||||
{t('editor.field.adaptive.hint')}
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<Field label={t('editor.field.icon')}>
|
||||
<div className="grid grid-cols-8 gap-2 max-h-44 overflow-y-auto p-2 rounded-2xl bg-surface-2">
|
||||
{ICON_CHOICES.map((name) => (
|
||||
|
||||
@@ -24,6 +24,9 @@ function formatChecked(ts: number, t: TFn): string {
|
||||
|
||||
export function UpdaterCard(): JSX.Element {
|
||||
const [status, setStatus] = useState<UpdaterStatus>({ kind: 'idle' })
|
||||
// busy используется только для синхронного `check()` — для асинхронного
|
||||
// download/install статус сам переключится через события (downloading →
|
||||
// downloaded), отдельный busy-флаг будет только дублировать визуально.
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -39,16 +42,15 @@ export function UpdaterCard(): JSX.Element {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
async function download(): Promise<void> {
|
||||
setBusy(true)
|
||||
try {
|
||||
await window.api.updaterDownload()
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
function download(): void {
|
||||
// Fire-and-forget — UI моментально перейдёт в kind:'downloading' через
|
||||
// первое же event'ное обновление статуса. Никакого `await` — пользователь
|
||||
// должен иметь возможность уйти на Dashboard, продолжать упражнения,
|
||||
// пока обновление качается в фоне.
|
||||
window.api.updaterDownload()
|
||||
}
|
||||
function install(): void {
|
||||
void window.api.updaterInstall()
|
||||
window.api.updaterInstall()
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -180,6 +182,10 @@ function Body({
|
||||
transition={{ duration: 0.3, ease: 'linear' }}
|
||||
/>
|
||||
</div>
|
||||
{/* Подсказка: download идёт в фоне, не нужно сидеть на этом экране. */}
|
||||
<div className="text-[12px] text-text/55 mt-3 font-medium">
|
||||
{t('updater.downloading.hint')}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
108
src/renderer/src/components/WhatsNewModal.tsx
Normal file
108
src/renderer/src/components/WhatsNewModal.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
import { useMemo } from 'react'
|
||||
import { Sparkles, Wrench, Shield, Gauge } from 'lucide-react'
|
||||
import { Modal } from './ui/Modal'
|
||||
import { Button } from './ui/Button'
|
||||
import { useT } from '../i18n'
|
||||
import { RELEASE_NOTES } from '@shared/release-notes'
|
||||
import type { ReleaseNoteItem } from '@shared/release-notes'
|
||||
import type { Language } from '@shared/types'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
versions: string[]
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const TAG_META = {
|
||||
new: { icon: Sparkles, cls: 'bg-accent text-white' },
|
||||
fix: { icon: Wrench, cls: 'bg-info text-white' },
|
||||
security: { icon: Shield, cls: 'bg-warning text-white' },
|
||||
perf: { icon: Gauge, cls: 'bg-success text-white' }
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Показывает заметки релизов для одной или нескольких версий. Используется
|
||||
* (a) автоматически после апдейта (когда `lastSeenVersion` != `currentVersion`)
|
||||
* и (b) вручную из Settings.
|
||||
*/
|
||||
export function WhatsNewModal({
|
||||
open,
|
||||
versions,
|
||||
onClose
|
||||
}: Props): JSX.Element {
|
||||
const { t, lang } = useT()
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={t('whatsnew.title')}
|
||||
size="md"
|
||||
footer={<Button onClick={onClose}>{t('whatsnew.btn.close')}</Button>}
|
||||
>
|
||||
<div className="space-y-6">
|
||||
{versions.length === 0 && (
|
||||
<div className="text-[14px] text-text/65 font-medium py-2">
|
||||
{t('whatsnew.empty')}
|
||||
</div>
|
||||
)}
|
||||
{versions.map((v) => (
|
||||
<VersionSection key={v} version={v} lang={lang} />
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
function VersionSection({
|
||||
version,
|
||||
lang
|
||||
}: {
|
||||
version: string
|
||||
lang: Language
|
||||
}): JSX.Element {
|
||||
const items = useMemo<ReleaseNoteItem[]>(() => {
|
||||
const notes = RELEASE_NOTES[version]
|
||||
if (!notes) return []
|
||||
return notes[lang] ?? notes.ru
|
||||
}, [version, lang])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="text-[12px] uppercase tracking-wider text-text/55 font-bold mb-3 font-mono-num">
|
||||
v{version}
|
||||
</div>
|
||||
<div className="space-y-2.5">
|
||||
{items.map((it, i) => (
|
||||
<NoteRow key={i} item={it} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NoteRow({ item }: { item: ReleaseNoteItem }): JSX.Element {
|
||||
const meta = TAG_META[item.tag ?? 'new']
|
||||
const IconCmp = meta.icon
|
||||
return (
|
||||
<div className="flex items-start gap-3">
|
||||
<div
|
||||
className={[
|
||||
'w-8 h-8 rounded-lg grid place-items-center shrink-0 mt-0.5',
|
||||
meta.cls
|
||||
].join(' ')}
|
||||
>
|
||||
<IconCmp size={15} strokeWidth={2.4} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-[14px] font-semibold leading-snug">
|
||||
{item.title}
|
||||
</div>
|
||||
{item.detail && (
|
||||
<div className="text-[13px] text-text/65 mt-1 leading-snug">
|
||||
{item.detail}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -143,6 +143,28 @@ export const ru: Dict = {
|
||||
'settings.section.appearance': 'Внешний вид',
|
||||
'settings.section.language': 'Язык',
|
||||
'settings.section.updates': 'Обновления',
|
||||
'settings.section.data': 'Данные',
|
||||
'settings.data.export.label': 'Экспортировать всё',
|
||||
'settings.data.export.hint':
|
||||
'Сохрани резервную копию упражнений, истории, челленджей и настроек в JSON-файл.',
|
||||
'settings.data.export.btn': 'Сохранить',
|
||||
'settings.data.export.ok': 'Сохранено в {path}',
|
||||
'settings.data.export.err': 'Не удалось сохранить',
|
||||
'settings.data.import.label': 'Восстановить из файла',
|
||||
'settings.data.import.hint':
|
||||
'Загрузить ранее сохранённую копию. Текущие данные будут перезаписаны.',
|
||||
'settings.data.import.btn': 'Восстановить',
|
||||
'settings.data.import.confirm':
|
||||
'Все текущие упражнения, история и настройки будут заменены содержимым файла. Продолжить?',
|
||||
'settings.data.import.ok': 'Восстановлено',
|
||||
'settings.data.import.err': 'Файл не подошёл — это не наша резервная копия?',
|
||||
'settings.section.about': 'О приложении',
|
||||
'settings.whatsnew.label': 'Что нового',
|
||||
'settings.whatsnew.hint': 'Посмотреть заметки последних релизов.',
|
||||
'settings.whatsnew.btn': 'Открыть',
|
||||
'whatsnew.title': 'Что нового',
|
||||
'whatsnew.btn.close': 'Понятно',
|
||||
'whatsnew.empty': 'Для этой версии заметок пока нет.',
|
||||
'settings.notification_mode.label': 'Режим уведомления',
|
||||
'settings.notification_mode.hint': 'Как должно выглядеть напоминание',
|
||||
'settings.notification_mode.modal': 'Окно поверх всех',
|
||||
@@ -150,6 +172,12 @@ export const ru: Dict = {
|
||||
'settings.notification_mode.both': 'Окно и уведомление',
|
||||
'settings.sound.label': 'Звук уведомления',
|
||||
'settings.sound.hint': 'Короткий сигнал при срабатывании',
|
||||
'settings.voice.label': 'Голосовая подсказка',
|
||||
'settings.voice.hint':
|
||||
'Диктор произносит название упражнения и количество — полезно когда фокус на коде.',
|
||||
'settings.meeting_pause.label': 'Пауза на встречах',
|
||||
'settings.meeting_pause.hint':
|
||||
'Не дёргать, если запущен Zoom / Teams / Discord / Webex / Slack-huddle.',
|
||||
'settings.snooze.label': '«Отложить» на',
|
||||
'settings.snooze.hint': 'Сколько минут добавлять при отложении',
|
||||
'settings.snooze.1': '1 минута',
|
||||
@@ -194,12 +222,53 @@ export const ru: Dict = {
|
||||
'updater.available.title': 'Доступна v{v}',
|
||||
'updater.downloading.title': 'Загружаем обновление',
|
||||
'updater.downloading.subtitle': '{got} / {total} МБ · {speed} МБ/с',
|
||||
'updater.downloading.hint': 'Можно закрыть это окно — скачивание продолжится в фоне.',
|
||||
'updater.downloaded.title': 'Готово · v{v}',
|
||||
'updater.downloaded.subtitle': 'Перезапусти для применения',
|
||||
'updater.downloaded.subtitle': 'Нажми «Рестарт» — приложение моментально откроется в новой версии.',
|
||||
'updater.error.title': 'Ошибка проверки',
|
||||
'updater.idle.title': 'Проверить обновления',
|
||||
'updater.idle.subtitle': 'Авто-проверка раз в час',
|
||||
|
||||
// Achievements
|
||||
'achievements.title': 'Достижения',
|
||||
'achievements.unlocked_of': '{n} из {total}',
|
||||
'achievements.progress': 'осталось {n}',
|
||||
'achievement.reps.desc': 'Сделай {target} повторений всего',
|
||||
'achievement.reps_100.title': 'Сотня',
|
||||
'achievement.reps_500.title': 'Пятьсот',
|
||||
'achievement.reps_1000.title': 'Тысяча',
|
||||
'achievement.reps_5000.title': 'Пять тысяч',
|
||||
'achievement.reps_10000.title': 'Десять тысяч',
|
||||
'achievement.streak.desc': '{target} дней подряд',
|
||||
'achievement.streak_3.title': 'Три дня',
|
||||
'achievement.streak_7.title': 'Неделя',
|
||||
'achievement.streak_14.title': 'Две недели',
|
||||
'achievement.streak_30.title': 'Месяц',
|
||||
'achievement.streak_100.title': 'Сто дней',
|
||||
'achievement.first_day.title': 'Первый шаг',
|
||||
'achievement.first_day.desc': 'Закрой первое напоминание',
|
||||
'achievement.today_quad.title': 'Ударный день',
|
||||
'achievement.today_quad.desc': '40+ повторений за день',
|
||||
|
||||
// Categories
|
||||
'category.exercise': 'Упражнение',
|
||||
'category.hydration': 'Гидратация',
|
||||
'category.eyes': 'Отдых глазам',
|
||||
'category.posture': 'Осанка',
|
||||
'category.exercise.cta': 'Время тренировки',
|
||||
'category.hydration.cta': 'Время попить',
|
||||
'category.eyes.cta': 'Дай глазам отдохнуть',
|
||||
'category.posture.cta': 'Проверь осанку',
|
||||
'editor.field.category': 'Категория',
|
||||
'editor.field.daily_goal': 'Дневная цель',
|
||||
'editor.field.daily_goal.placeholder': 'без ограничения',
|
||||
'editor.field.daily_goal.clear': 'Снять',
|
||||
'editor.field.daily_goal.hint':
|
||||
'Когда наберёшь столько повторений за день, напоминания этого упражнения умолкнут до завтра.',
|
||||
'editor.field.adaptive.label': 'Адаптивное расписание',
|
||||
'editor.field.adaptive.hint':
|
||||
'Шедулер изучает, в какие часы ты чаще делаешь упражнение, и сдвигает напоминания на удобное тебе время. Заработает после 10 событий в истории.',
|
||||
|
||||
// Reminder window
|
||||
'reminder.kicker': 'Время тренировки',
|
||||
'reminder.subkicker': 'Двигайся',
|
||||
@@ -389,6 +458,28 @@ export const en: Dict = {
|
||||
'settings.section.appearance': 'Appearance',
|
||||
'settings.section.language': 'Language',
|
||||
'settings.section.updates': 'Updates',
|
||||
'settings.section.data': 'Data',
|
||||
'settings.data.export.label': 'Export everything',
|
||||
'settings.data.export.hint':
|
||||
'Save a backup of exercises, history, challenges and settings to a JSON file.',
|
||||
'settings.data.export.btn': 'Save',
|
||||
'settings.data.export.ok': 'Saved to {path}',
|
||||
'settings.data.export.err': 'Could not save',
|
||||
'settings.data.import.label': 'Restore from file',
|
||||
'settings.data.import.hint':
|
||||
'Load a previously saved backup. Current data will be overwritten.',
|
||||
'settings.data.import.btn': 'Restore',
|
||||
'settings.data.import.confirm':
|
||||
'All current exercises, history and settings will be replaced with the file contents. Continue?',
|
||||
'settings.data.import.ok': 'Restored',
|
||||
'settings.data.import.err': "Couldn't read the file — not our backup?",
|
||||
'settings.section.about': 'About',
|
||||
'settings.whatsnew.label': "What's new",
|
||||
'settings.whatsnew.hint': 'See the latest release notes.',
|
||||
'settings.whatsnew.btn': 'Open',
|
||||
'whatsnew.title': "What's new",
|
||||
'whatsnew.btn.close': 'Got it',
|
||||
'whatsnew.empty': 'No notes available for this version yet.',
|
||||
'settings.notification_mode.label': 'Notification mode',
|
||||
'settings.notification_mode.hint': 'How a reminder appears',
|
||||
'settings.notification_mode.modal': 'Window on top',
|
||||
@@ -396,6 +487,12 @@ export const en: Dict = {
|
||||
'settings.notification_mode.both': 'Window and notification',
|
||||
'settings.sound.label': 'Notification sound',
|
||||
'settings.sound.hint': 'Short beep on trigger',
|
||||
'settings.voice.label': 'Voice prompt',
|
||||
'settings.voice.hint':
|
||||
'Speaks the exercise name and count — useful when your eyes are on the code.',
|
||||
'settings.meeting_pause.label': 'Pause during meetings',
|
||||
'settings.meeting_pause.hint':
|
||||
'Skip reminders when Zoom / Teams / Discord / Webex / Slack-huddle is running.',
|
||||
'settings.snooze.label': '“Snooze” for',
|
||||
'settings.snooze.hint': 'How many minutes to postpone',
|
||||
'settings.snooze.1': '1 minute',
|
||||
@@ -440,12 +537,53 @@ export const en: Dict = {
|
||||
'updater.available.title': 'v{v} available',
|
||||
'updater.downloading.title': 'Downloading update',
|
||||
'updater.downloading.subtitle': '{got} / {total} MB · {speed} MB/s',
|
||||
'updater.downloading.hint': 'You can close this window — download continues in the background.',
|
||||
'updater.downloaded.title': 'Ready · v{v}',
|
||||
'updater.downloaded.subtitle': 'Restart to apply',
|
||||
'updater.downloaded.subtitle': 'Click Restart — the app will reopen instantly in the new version.',
|
||||
'updater.error.title': 'Check failed',
|
||||
'updater.idle.title': 'Check for updates',
|
||||
'updater.idle.subtitle': 'Auto-check every hour',
|
||||
|
||||
// Achievements
|
||||
'achievements.title': 'Achievements',
|
||||
'achievements.unlocked_of': '{n} of {total}',
|
||||
'achievements.progress': '{n} to go',
|
||||
'achievement.reps.desc': '{target} reps total',
|
||||
'achievement.reps_100.title': 'Century',
|
||||
'achievement.reps_500.title': 'Five hundred',
|
||||
'achievement.reps_1000.title': 'Thousand',
|
||||
'achievement.reps_5000.title': 'Five thousand',
|
||||
'achievement.reps_10000.title': 'Ten thousand',
|
||||
'achievement.streak.desc': '{target} days in a row',
|
||||
'achievement.streak_3.title': 'Three days',
|
||||
'achievement.streak_7.title': 'Week',
|
||||
'achievement.streak_14.title': 'Two weeks',
|
||||
'achievement.streak_30.title': 'Month',
|
||||
'achievement.streak_100.title': 'Hundred days',
|
||||
'achievement.first_day.title': 'First step',
|
||||
'achievement.first_day.desc': 'Close your first reminder',
|
||||
'achievement.today_quad.title': 'Strong day',
|
||||
'achievement.today_quad.desc': '40+ reps in one day',
|
||||
|
||||
// Categories
|
||||
'category.exercise': 'Exercise',
|
||||
'category.hydration': 'Hydration',
|
||||
'category.eyes': 'Eye rest',
|
||||
'category.posture': 'Posture',
|
||||
'category.exercise.cta': 'Workout time',
|
||||
'category.hydration.cta': 'Time to drink',
|
||||
'category.eyes.cta': 'Rest your eyes',
|
||||
'category.posture.cta': 'Check your posture',
|
||||
'editor.field.category': 'Category',
|
||||
'editor.field.daily_goal': 'Daily goal',
|
||||
'editor.field.daily_goal.placeholder': 'no limit',
|
||||
'editor.field.daily_goal.clear': 'Clear',
|
||||
'editor.field.daily_goal.hint':
|
||||
'Once you hit this many reps in a day, this reminder goes quiet until tomorrow.',
|
||||
'editor.field.adaptive.label': 'Adaptive scheduling',
|
||||
'editor.field.adaptive.hint':
|
||||
'Scheduler learns which hours you reliably do this exercise and shifts reminders into your good windows. Kicks in after 10 history events.',
|
||||
|
||||
// Reminder window
|
||||
'reminder.kicker': 'Workout time',
|
||||
'reminder.subkicker': 'Move',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { translate, translateN } from './index'
|
||||
import { ru, en } from './dict'
|
||||
|
||||
describe('translate', () => {
|
||||
it('returns the matching string by key', () => {
|
||||
@@ -30,6 +31,50 @@ describe('translate', () => {
|
||||
// @ts-expect-error testing fallback
|
||||
expect(translate('fr', 'btn.save')).toBe('Сохранить')
|
||||
})
|
||||
|
||||
// Регрессия: до v0.5.2 интерполяция шла через regex, и если
|
||||
// var-значение содержало regex-метасимволы ($1, .*, и т.д.), они
|
||||
// интерпретировались как backreferences. Сейчас split/join.
|
||||
it('substitutes regex metacharacters literally (no regex injection)', () => {
|
||||
expect(
|
||||
translate('ru', 'btn.snooze_min', { n: '$1.*' as unknown as number })
|
||||
).toBe('Отложить $1.* мин')
|
||||
expect(
|
||||
translate('en', 'btn.snooze_min', {
|
||||
n: '$$$&\\1' as unknown as number
|
||||
})
|
||||
).toBe('Snooze $$$&\\1m')
|
||||
})
|
||||
|
||||
it('leaves unsubstituted placeholders intact', () => {
|
||||
// {n} остаётся как есть, если var не передан — это сигнал «забыл vars».
|
||||
expect(translate('ru', 'btn.snooze_min')).toContain('{n}')
|
||||
})
|
||||
})
|
||||
|
||||
describe('dictionary parity', () => {
|
||||
// EN не имеет CLDR-категории `few` — только `one`/`many`. Поэтому RU-ключи
|
||||
// вида `*_few` легитимно отсутствуют в EN, исключаем их из парити-чека.
|
||||
const isRuFewOnly = (k: string): boolean => k.endsWith('_few')
|
||||
|
||||
it('every key in ru (except *_few) exists in en', () => {
|
||||
const missing = Object.keys(ru).filter(
|
||||
(k) => !isRuFewOnly(k) && !(k in en)
|
||||
)
|
||||
expect(missing, `missing in en: ${missing.join(', ')}`).toEqual([])
|
||||
})
|
||||
|
||||
it('every key in en exists in ru', () => {
|
||||
const missing = Object.keys(en).filter((k) => !(k in ru))
|
||||
expect(missing, `missing in ru: ${missing.join(', ')}`).toEqual([])
|
||||
})
|
||||
|
||||
it('weekday.short.0..6 exist in both languages', () => {
|
||||
for (const i of [0, 1, 2, 3, 4, 5, 6]) {
|
||||
expect(ru[`weekday.short.${i}`]).toBeTruthy()
|
||||
expect(en[`weekday.short.${i}`]).toBeTruthy()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('translateN (plural)', () => {
|
||||
|
||||
155
src/renderer/src/lib/achievements.ts
Normal file
155
src/renderer/src/lib/achievements.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Достижения = derived data из истории. Не persisting'ятся: при каждом
|
||||
* прокладывании Dashboard'а пересчитываются из истории.
|
||||
*
|
||||
* Определение достижения: id, человеческий label/description, иконка
|
||||
* (Lucide name), функция-проверка `progress(history, exercises) →
|
||||
* { current, target }` где `current >= target` означает «получено».
|
||||
*
|
||||
* Этим UI получает не только список «полученных», но и прогресс по «почти-
|
||||
* полученным», что важно мотивационно: «осталось 12 повторов до значка
|
||||
* Сотня».
|
||||
*/
|
||||
import type { Exercise, HistoryEntry } from '@shared/types'
|
||||
import { currentStreak, dailyReps, dayKey } from './history'
|
||||
|
||||
export type AchievementDef = {
|
||||
id: string
|
||||
/** Lucide icon name (whitelisted ICON_CHOICES не обязательно — иконки
|
||||
* достижений отдельный набор). */
|
||||
icon: string
|
||||
tone: 'accent' | 'warning' | 'success' | 'info'
|
||||
/** i18n-ключ для названия. */
|
||||
titleKey: string
|
||||
/** i18n-ключ описания. Принимает {target}. */
|
||||
descKey: string
|
||||
}
|
||||
|
||||
export type AchievementProgress = {
|
||||
def: AchievementDef
|
||||
current: number
|
||||
target: number
|
||||
/** Получено = current >= target. */
|
||||
unlocked: boolean
|
||||
}
|
||||
|
||||
/** Сумма всех done-повторений за всё время (учитывая actualReps). */
|
||||
function totalDoneReps(
|
||||
history: HistoryEntry[],
|
||||
exercises: Exercise[]
|
||||
): number {
|
||||
const byId = new Map(exercises.map((e) => [e.id, e]))
|
||||
let sum = 0
|
||||
for (const e of history) {
|
||||
if (e.action !== 'done') continue
|
||||
sum += e.actualReps ?? byId.get(e.exerciseId)?.reps ?? 0
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
/** Сколько уникальных done-дней за всё время. */
|
||||
function totalDoneDays(history: HistoryEntry[]): number {
|
||||
const days = new Set<string>()
|
||||
for (const e of history) {
|
||||
if (e.action === 'done') days.add(dayKey(e.ts))
|
||||
}
|
||||
return days.size
|
||||
}
|
||||
|
||||
/** Самый длинный завершённый streak (для historic-достижений). */
|
||||
function longestStreak(history: HistoryEntry[]): number {
|
||||
const days = new Set<string>()
|
||||
for (const e of history) {
|
||||
if (e.action === 'done') days.add(dayKey(e.ts))
|
||||
}
|
||||
const sorted = Array.from(days).sort()
|
||||
let max = 0
|
||||
let cur = 0
|
||||
let prev = ''
|
||||
for (const d of sorted) {
|
||||
if (prev) {
|
||||
const prevDate = new Date(prev + 'T00:00:00')
|
||||
const curDate = new Date(d + 'T00:00:00')
|
||||
const diffDays = Math.round(
|
||||
(curDate.getTime() - prevDate.getTime()) / (24 * 60 * 60 * 1000)
|
||||
)
|
||||
cur = diffDays === 1 ? cur + 1 : 1
|
||||
} else {
|
||||
cur = 1
|
||||
}
|
||||
if (cur > max) max = cur
|
||||
prev = d
|
||||
}
|
||||
return max
|
||||
}
|
||||
|
||||
const REPS_MILESTONES = [100, 500, 1000, 5000, 10000] as const
|
||||
const STREAK_MILESTONES = [3, 7, 14, 30, 100] as const
|
||||
|
||||
const DEFINITIONS: AchievementDef[] = [
|
||||
...REPS_MILESTONES.map<AchievementDef>((n) => ({
|
||||
id: `reps_${n}`,
|
||||
icon: 'Activity',
|
||||
tone: 'accent' as const,
|
||||
titleKey: `achievement.reps_${n}.title`,
|
||||
descKey: 'achievement.reps.desc'
|
||||
})),
|
||||
...STREAK_MILESTONES.map<AchievementDef>((n) => ({
|
||||
id: `streak_${n}`,
|
||||
icon: 'Flame',
|
||||
tone: 'warning' as const,
|
||||
titleKey: `achievement.streak_${n}.title`,
|
||||
descKey: 'achievement.streak.desc'
|
||||
})),
|
||||
{
|
||||
id: 'first_day',
|
||||
icon: 'Sparkles',
|
||||
tone: 'success',
|
||||
titleKey: 'achievement.first_day.title',
|
||||
descKey: 'achievement.first_day.desc'
|
||||
},
|
||||
{
|
||||
id: 'today_quad',
|
||||
icon: 'TrendingUp',
|
||||
tone: 'info',
|
||||
titleKey: 'achievement.today_quad.title',
|
||||
descKey: 'achievement.today_quad.desc'
|
||||
}
|
||||
]
|
||||
|
||||
export function computeAchievements(
|
||||
history: HistoryEntry[],
|
||||
exercises: Exercise[]
|
||||
): AchievementProgress[] {
|
||||
const total = totalDoneReps(history, exercises)
|
||||
const days = totalDoneDays(history)
|
||||
const longest = longestStreak(history)
|
||||
const currentStreakLen = currentStreak(history)
|
||||
const today = dayKey(Date.now())
|
||||
const todayCount = dailyReps(history, exercises, today)
|
||||
|
||||
return DEFINITIONS.map<AchievementProgress>((def) => {
|
||||
if (def.id.startsWith('reps_')) {
|
||||
const target = Number(def.id.split('_')[1])
|
||||
return { def, current: total, target, unlocked: total >= target }
|
||||
}
|
||||
if (def.id.startsWith('streak_')) {
|
||||
const target = Number(def.id.split('_')[1])
|
||||
// Учитываем максимальный исторический и текущий — берём больший.
|
||||
const cur = Math.max(longest, currentStreakLen)
|
||||
return { def, current: cur, target, unlocked: cur >= target }
|
||||
}
|
||||
if (def.id === 'first_day') {
|
||||
return { def, current: days >= 1 ? 1 : 0, target: 1, unlocked: days >= 1 }
|
||||
}
|
||||
if (def.id === 'today_quad') {
|
||||
return {
|
||||
def,
|
||||
current: todayCount,
|
||||
target: 40,
|
||||
unlocked: todayCount >= 40
|
||||
}
|
||||
}
|
||||
return { def, current: 0, target: 1, unlocked: false }
|
||||
})
|
||||
}
|
||||
@@ -33,6 +33,29 @@ describe('formatCountdown', () => {
|
||||
expect(formatCountdown(999)).toBe('0с')
|
||||
expect(formatCountdown(500)).toBe('0с')
|
||||
})
|
||||
|
||||
// Guard added in v0.5.2 — electron-updater и scheduler могут передать
|
||||
// NaN/Infinity на ранних событиях. Должны вернуть «сейчас», не «NaNс».
|
||||
it('returns "сейчас" for NaN and Infinity (defensive guard)', () => {
|
||||
expect(formatCountdown(NaN)).toBe('сейчас')
|
||||
expect(formatCountdown(Infinity)).toBe('сейчас')
|
||||
expect(formatCountdown(-Infinity)).toBe('сейчас')
|
||||
})
|
||||
|
||||
describe('english locale', () => {
|
||||
it('renders sub-minute with "s"', () => {
|
||||
expect(formatCountdown(45_000, 'en')).toBe('45s')
|
||||
})
|
||||
it('renders minutes+seconds with "m"/"s"', () => {
|
||||
expect(formatCountdown(65_000, 'en')).toBe('1m 05s')
|
||||
})
|
||||
it('renders hours+minutes with "h"/"m"', () => {
|
||||
expect(formatCountdown(3_660_000, 'en')).toBe('1h 01m')
|
||||
})
|
||||
it('returns "now" for zero', () => {
|
||||
expect(formatCountdown(0, 'en')).toBe('now')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatInterval', () => {
|
||||
@@ -53,4 +76,10 @@ describe('formatInterval', () => {
|
||||
expect(formatInterval(90)).toBe('1 ч 30 мин')
|
||||
expect(formatInterval(125)).toBe('2 ч 5 мин')
|
||||
})
|
||||
|
||||
it('english locale', () => {
|
||||
expect(formatInterval(30, 'en')).toBe('30 min')
|
||||
expect(formatInterval(60, 'en')).toBe('1 h')
|
||||
expect(formatInterval(90, 'en')).toBe('1 h 30 min')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Exercise, HistoryEntry } from '@shared/types'
|
||||
import { currentStreak, dailyReps, dayKey, dailyRepsRange } from './history'
|
||||
import {
|
||||
currentStreak,
|
||||
dailyReps,
|
||||
dayKey,
|
||||
dailyRepsRange,
|
||||
plannedRepsToday
|
||||
} from './history'
|
||||
|
||||
const MS_DAY = 24 * 60 * 60 * 1000
|
||||
|
||||
@@ -117,4 +123,77 @@ describe('dailyRepsRange', () => {
|
||||
expect(range.at(-1)?.reps).toBe(10) // today
|
||||
expect(range.at(-2)?.reps).toBe(3) // yesterday, partial
|
||||
})
|
||||
|
||||
// DST regression: до v0.5.2 dailyRepsRange использовал `ts - i*MS_DAY`.
|
||||
// На границе DST (например в EU last Sunday October — 25 час) арифметика
|
||||
// ms-vs-календарь расходилась, и dayKey() выдавал дубликат/пропуск дня.
|
||||
// Сейчас shiftDays() через setDate(). Простой инвариант: количество
|
||||
// уникальных day-keys всегда == days, и все keys строго возрастают.
|
||||
it('produces unique day keys without gaps (DST-safe)', () => {
|
||||
const range = dailyRepsRange([], [], 90)
|
||||
const keys = range.map((r) => r.key)
|
||||
expect(new Set(keys).size).toBe(90)
|
||||
for (let i = 1; i < keys.length; i++) {
|
||||
expect(keys[i] > keys[i - 1]).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('last entry is today', () => {
|
||||
const range = dailyRepsRange([], [], 7)
|
||||
expect(range.at(-1)?.key).toBe(dayKey(Date.now()))
|
||||
})
|
||||
})
|
||||
|
||||
describe('plannedRepsToday', () => {
|
||||
it('returns 0 when no exercises enabled', () => {
|
||||
const exs = [{ ...ex('a', 10), enabled: false }]
|
||||
expect(plannedRepsToday(exs)).toBe(0)
|
||||
})
|
||||
|
||||
it('returns 0 for empty list', () => {
|
||||
expect(plannedRepsToday([])).toBe(0)
|
||||
})
|
||||
|
||||
it('multiplies reps by approximate fires per day', () => {
|
||||
// 60-min interval × 24 = 24 fires/day × 10 reps = 240
|
||||
const exs = [{ ...ex('a', 10), intervalMinutes: 60 }]
|
||||
expect(plannedRepsToday(exs)).toBe(240)
|
||||
})
|
||||
|
||||
it('sums across multiple enabled exercises', () => {
|
||||
const exs = [
|
||||
{ ...ex('a', 10), intervalMinutes: 60 }, // 24 × 10 = 240
|
||||
{ ...ex('b', 5), intervalMinutes: 30 } // 48 × 5 = 240
|
||||
]
|
||||
expect(plannedRepsToday(exs)).toBe(480)
|
||||
})
|
||||
|
||||
it('floor of (1440/interval), minimum 1 fire/day for huge intervals', () => {
|
||||
// 1440-min interval = 1 fire/day; 2000-min interval should still be ≥ 1.
|
||||
const exs = [{ ...ex('a', 7), intervalMinutes: 2000 }]
|
||||
expect(plannedRepsToday(exs)).toBe(7)
|
||||
})
|
||||
})
|
||||
|
||||
describe('currentStreak edge cases', () => {
|
||||
const today = Date.now()
|
||||
|
||||
it('ignores future-dated entries (clock skew, partial restore)', () => {
|
||||
const tomorrow = today + 24 * 60 * 60 * 1000
|
||||
// future entry shouldn't anchor the streak.
|
||||
expect(currentStreak([entry('a', tomorrow)])).toBe(0)
|
||||
})
|
||||
|
||||
it('handles entries spread across the same day with mixed actions', () => {
|
||||
const e = (
|
||||
action: 'done' | 'skip' | 'snooze',
|
||||
ts: number
|
||||
): HistoryEntry => entry('a', ts, action)
|
||||
const hist = [
|
||||
e('skip', today),
|
||||
e('done', today), // done is enough — streak counts the day
|
||||
e('snooze', today)
|
||||
]
|
||||
expect(currentStreak(hist)).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
26
src/renderer/src/lib/icon-choices.test.ts
Normal file
26
src/renderer/src/lib/icon-choices.test.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ICON_CHOICES } from './icon-choices'
|
||||
import { SAMPLE_EXERCISES } from '@shared/types'
|
||||
|
||||
describe('ICON_CHOICES', () => {
|
||||
// Если иконка SAMPLE_EXERCISES не входит в whitelist, при первом запуске
|
||||
// приложения иконка молча заменится на fallback-Activity. Лучше ловить
|
||||
// расхождение в CI.
|
||||
it('contains every icon used by SAMPLE_EXERCISES', () => {
|
||||
const allowed = new Set<string>(ICON_CHOICES)
|
||||
for (const ex of SAMPLE_EXERCISES) {
|
||||
expect(
|
||||
allowed.has(ex.icon),
|
||||
`icon "${ex.icon}" for sample "${ex.name}" is not in ICON_CHOICES`
|
||||
).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('has no duplicates', () => {
|
||||
expect(new Set(ICON_CHOICES).size).toBe(ICON_CHOICES.length)
|
||||
})
|
||||
|
||||
it('is non-empty', () => {
|
||||
expect(ICON_CHOICES.length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
27
src/renderer/src/lib/icon-choices.ts
Normal file
27
src/renderer/src/lib/icon-choices.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Whitelist of allowed Lucide-icon names. Wrapped in a separate .ts file
|
||||
* (без JSX), чтобы его можно было импортировать из node-tests и из shared/
|
||||
* без подтягивания JSX-зависимости icon.tsx.
|
||||
*/
|
||||
export const ICON_CHOICES = [
|
||||
'Activity',
|
||||
'Dumbbell',
|
||||
'StretchHorizontal',
|
||||
'PersonStanding',
|
||||
'Heart',
|
||||
'Footprints',
|
||||
'Hand',
|
||||
'Eye',
|
||||
'Brain',
|
||||
'Bike',
|
||||
'Waves',
|
||||
'Wind',
|
||||
'Sun',
|
||||
'Coffee',
|
||||
'Apple',
|
||||
'GlassWater',
|
||||
'BookOpen',
|
||||
'Sparkles'
|
||||
] as const
|
||||
|
||||
export type IconName = (typeof ICON_CHOICES)[number]
|
||||
@@ -1,30 +1,51 @@
|
||||
import * as Lucide from 'lucide-react'
|
||||
// Explicit-named imports — НЕ wildcard. Wildcard `* as Lucide` ломает
|
||||
// tree-shaking: в bundle попадает вся библиотека (~500KB minified, 1500+
|
||||
// иконок). Сейчас в bundle только 18 ICON_CHOICES.
|
||||
import {
|
||||
Activity,
|
||||
Dumbbell,
|
||||
StretchHorizontal,
|
||||
PersonStanding,
|
||||
Heart,
|
||||
Footprints,
|
||||
Hand,
|
||||
Eye,
|
||||
Brain,
|
||||
Bike,
|
||||
Waves,
|
||||
Wind,
|
||||
Sun,
|
||||
Coffee,
|
||||
Apple,
|
||||
GlassWater,
|
||||
BookOpen,
|
||||
Sparkles
|
||||
} from 'lucide-react'
|
||||
import type { LucideProps } from 'lucide-react'
|
||||
import { ICON_CHOICES, type IconName } from './icon-choices'
|
||||
|
||||
export const ICON_CHOICES = [
|
||||
'Activity',
|
||||
'Dumbbell',
|
||||
'StretchHorizontal',
|
||||
'PersonStanding',
|
||||
'Heart',
|
||||
'Footprints',
|
||||
'Hand',
|
||||
'Eye',
|
||||
'Brain',
|
||||
'Bike',
|
||||
'Waves',
|
||||
'Wind',
|
||||
'Sun',
|
||||
'Coffee',
|
||||
'Apple',
|
||||
'GlassWater',
|
||||
'BookOpen',
|
||||
'Sparkles'
|
||||
] as const
|
||||
export { ICON_CHOICES, type IconName }
|
||||
|
||||
export type IconName = (typeof ICON_CHOICES)[number]
|
||||
|
||||
const ICON_SET = new Set<string>(ICON_CHOICES)
|
||||
const ICON_MAP: Record<IconName, React.ComponentType<LucideProps>> = {
|
||||
Activity,
|
||||
Dumbbell,
|
||||
StretchHorizontal,
|
||||
PersonStanding,
|
||||
Heart,
|
||||
Footprints,
|
||||
Hand,
|
||||
Eye,
|
||||
Brain,
|
||||
Bike,
|
||||
Waves,
|
||||
Wind,
|
||||
Sun,
|
||||
Coffee,
|
||||
Apple,
|
||||
GlassWater,
|
||||
BookOpen,
|
||||
Sparkles
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a Lucide icon by name. Restricted to the curated ICON_CHOICES set —
|
||||
@@ -36,15 +57,12 @@ export function Icon({
|
||||
name,
|
||||
...props
|
||||
}: { name: string } & LucideProps): JSX.Element {
|
||||
if (!ICON_SET.has(name)) {
|
||||
const Cmp = ICON_MAP[name as IconName]
|
||||
if (!Cmp) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn(`[Icon] unknown icon name "${name}" — falling back`)
|
||||
}
|
||||
return <Lucide.Activity {...props} />
|
||||
return <Activity {...props} />
|
||||
}
|
||||
const Cmp = (
|
||||
Lucide as unknown as Record<string, React.ComponentType<LucideProps>>
|
||||
)[name]
|
||||
if (!Cmp) return <Lucide.Activity {...props} />
|
||||
return <Cmp {...props} />
|
||||
}
|
||||
|
||||
67
src/renderer/src/lib/tts.ts
Normal file
67
src/renderer/src/lib/tts.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Тонкая обёртка над Web Speech API для голосовых подсказок упражнений.
|
||||
*
|
||||
* Используется в ReminderApp при `settings.voicePromptsEnabled`. Голос
|
||||
* подбирается под `settings.language`: ищем первый локальный голос
|
||||
* с правильным `lang` префиксом (ru-RU / en-US), fallback на default.
|
||||
*
|
||||
* Тихий fail: если браузер/Electron не поддерживает Speech Synthesis
|
||||
* (мало вероятно в Chromium) — просто ничего не делаем, не падаем.
|
||||
*/
|
||||
import type { Language } from '@shared/types'
|
||||
|
||||
const LANG_BCP47: Record<Language, string> = {
|
||||
ru: 'ru-RU',
|
||||
en: 'en-US'
|
||||
}
|
||||
|
||||
let voicesLoaded = false
|
||||
let cachedVoices: SpeechSynthesisVoice[] = []
|
||||
|
||||
function ensureVoices(): SpeechSynthesisVoice[] {
|
||||
if (typeof window === 'undefined' || !('speechSynthesis' in window)) return []
|
||||
if (voicesLoaded && cachedVoices.length) return cachedVoices
|
||||
cachedVoices = window.speechSynthesis.getVoices()
|
||||
// Chromium часто отдаёт пустой массив до voiceschanged-event'а — подпишемся
|
||||
// один раз, чтобы при следующем speak() voices уже были.
|
||||
if (cachedVoices.length === 0) {
|
||||
window.speechSynthesis.onvoiceschanged = () => {
|
||||
cachedVoices = window.speechSynthesis.getVoices()
|
||||
voicesLoaded = true
|
||||
}
|
||||
} else {
|
||||
voicesLoaded = true
|
||||
}
|
||||
return cachedVoices
|
||||
}
|
||||
|
||||
function pickVoice(lang: Language): SpeechSynthesisVoice | undefined {
|
||||
const target = LANG_BCP47[lang]
|
||||
const voices = ensureVoices()
|
||||
// 1. Точное совпадение `ru-RU` / `en-US`.
|
||||
const exact = voices.find((v) => v.lang === target)
|
||||
if (exact) return exact
|
||||
// 2. Любой голос с правильным language-кодом (`ru`, `en`).
|
||||
const partial = voices.find((v) => v.lang.startsWith(lang))
|
||||
if (partial) return partial
|
||||
// 3. Default — fallback на default-голос системы.
|
||||
return voices.find((v) => v.default)
|
||||
}
|
||||
|
||||
export function speak(text: string, lang: Language): void {
|
||||
if (typeof window === 'undefined' || !('speechSynthesis' in window)) return
|
||||
try {
|
||||
// Прервать предыдущее озвучивание (если игрок быстро жмёт reminder'ы).
|
||||
window.speechSynthesis.cancel()
|
||||
const utter = new SpeechSynthesisUtterance(text)
|
||||
const voice = pickVoice(lang)
|
||||
if (voice) utter.voice = voice
|
||||
utter.lang = LANG_BCP47[lang]
|
||||
utter.rate = 1.0
|
||||
utter.pitch = 1.0
|
||||
utter.volume = 0.85
|
||||
window.speechSynthesis.speak(utter)
|
||||
} catch {
|
||||
// Не критично — TTS опционален.
|
||||
}
|
||||
}
|
||||
@@ -264,11 +264,18 @@ function ChallengeEditor({
|
||||
type="number"
|
||||
step="0.5"
|
||||
min="0.5"
|
||||
max="1000"
|
||||
value={draft.multiplier}
|
||||
onChange={(e) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
multiplier: Math.max(0.5, Number(e.target.value) || 1)
|
||||
// Клампим к диапазону [0.5, 1000] — совпадает с validate.ts
|
||||
// (multiplier ∈ [0, 1000]). Без max=1000 пользователь мог
|
||||
// ввести 9999 и save молча отклонялся IPC-валидатором.
|
||||
multiplier: Math.max(
|
||||
0.5,
|
||||
Math.min(1000, Number(e.target.value) || 1)
|
||||
)
|
||||
})
|
||||
}
|
||||
className="ios-input font-mono-num"
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useAppStore } from '../store/appStore'
|
||||
import { ExerciseCard } from '../components/ExerciseCard'
|
||||
import { ExerciseEditor } from '../components/ExerciseEditor'
|
||||
import { HistoryHeatmap } from '../components/HistoryHeatmap'
|
||||
import { AchievementsCard } from '../components/AchievementsCard'
|
||||
import { Button } from '../components/ui/Button'
|
||||
import type { Exercise, HistoryEntry } from '@shared/types'
|
||||
import { formatCountdown } from '../lib/format'
|
||||
@@ -72,6 +73,9 @@ export default function Dashboard(): JSX.Element {
|
||||
icon: string
|
||||
intervalMinutes: number
|
||||
enabled: boolean
|
||||
category: import('@shared/types').ReminderCategory
|
||||
dailyGoal?: number
|
||||
adaptive?: boolean
|
||||
}): Promise<void> {
|
||||
if (editing) await window.api.updateExercise(editing.id, draft)
|
||||
else await window.api.addExercise(draft)
|
||||
@@ -178,8 +182,9 @@ export default function Dashboard(): JSX.Element {
|
||||
</div>
|
||||
|
||||
{history.length > 0 && (
|
||||
<div className="mb-8">
|
||||
<div className="mb-8 space-y-3">
|
||||
<HistoryHeatmap history={history} exercises={exercises} />
|
||||
<AchievementsCard history={history} exercises={exercises} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import { useAppStore } from '../store/appStore'
|
||||
import { Switch } from '../components/ui/Switch'
|
||||
import { Card, Row, SectionHeader } from '../components/ui/Card'
|
||||
import { UpdaterCard } from '../components/UpdaterCard'
|
||||
import { WhatsNewModal } from '../components/WhatsNewModal'
|
||||
import { RELEASE_NOTES } from '@shared/release-notes'
|
||||
import { useT } from '../i18n'
|
||||
import type {
|
||||
Language,
|
||||
@@ -77,6 +79,18 @@ export default function SettingsPage(): JSX.Element {
|
||||
checked={settings.soundEnabled}
|
||||
onChange={(v) => patch({ soundEnabled: v })}
|
||||
/>
|
||||
<ToggleRow
|
||||
label={t('settings.voice.label')}
|
||||
hint={t('settings.voice.hint')}
|
||||
checked={settings.voicePromptsEnabled}
|
||||
onChange={(v) => patch({ voicePromptsEnabled: v })}
|
||||
/>
|
||||
<ToggleRow
|
||||
label={t('settings.meeting_pause.label')}
|
||||
hint={t('settings.meeting_pause.hint')}
|
||||
checked={settings.meetingAutoPause}
|
||||
onChange={(v) => patch({ meetingAutoPause: v })}
|
||||
/>
|
||||
<SelectRow
|
||||
label={t('settings.snooze.label')}
|
||||
hint={t('settings.snooze.hint')}
|
||||
@@ -158,8 +172,141 @@ export default function SettingsPage(): JSX.Element {
|
||||
|
||||
<SectionHeader title={t('settings.section.updates')} />
|
||||
<UpdaterCard />
|
||||
|
||||
<div className="mt-6">
|
||||
<SectionHeader title={t('settings.section.data')} />
|
||||
<DataCard />
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
<SectionHeader title={t('settings.section.about')} />
|
||||
<AboutCard />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AboutCard(): JSX.Element {
|
||||
const { t } = useT()
|
||||
const [open, setOpen] = useState(false)
|
||||
// Все версии для которых у нас есть заметки, отсортированы desc.
|
||||
const allVersions = Object.keys(RELEASE_NOTES).sort((a, b) => {
|
||||
const pa = a.split('.').map(Number)
|
||||
const pb = b.split('.').map(Number)
|
||||
for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pb[i] - pa[i]
|
||||
return 0
|
||||
})
|
||||
return (
|
||||
<Card>
|
||||
<Row last>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-[15px] font-semibold leading-tight">
|
||||
{t('settings.whatsnew.label')}
|
||||
</div>
|
||||
<div className="text-[13px] text-text/65 mt-1 leading-snug">
|
||||
{t('settings.whatsnew.hint')}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setOpen(true)}
|
||||
className="h-9 px-4 rounded-xl bg-surface-2 hover:bg-hairline/25 text-[14px] font-semibold transition-colors"
|
||||
>
|
||||
{t('settings.whatsnew.btn')}
|
||||
</button>
|
||||
</Row>
|
||||
<WhatsNewModal
|
||||
open={open}
|
||||
versions={allVersions}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function DataCard(): JSX.Element {
|
||||
const { t } = useT()
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [toast, setToast] = useState<string | null>(null)
|
||||
|
||||
// Простое toast'-сообщение в карточке; через 4 сек чистится.
|
||||
useEffect(() => {
|
||||
if (!toast) return
|
||||
const id = setTimeout(() => setToast(null), 4000)
|
||||
return () => clearTimeout(id)
|
||||
}, [toast])
|
||||
|
||||
async function onExport(): Promise<void> {
|
||||
setBusy(true)
|
||||
try {
|
||||
const r = await window.api.exportState()
|
||||
if (r.ok && r.path) {
|
||||
setToast(t('settings.data.export.ok', { path: r.path }))
|
||||
} else if (!r.ok) {
|
||||
setToast(t('settings.data.export.err'))
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function onImport(): Promise<void> {
|
||||
// eslint-disable-next-line no-alert -- modal-confirm для destructive action
|
||||
if (!window.confirm(t('settings.data.import.confirm'))) return
|
||||
setBusy(true)
|
||||
try {
|
||||
const r = await window.api.importState()
|
||||
if (r.ok) setToast(t('settings.data.import.ok'))
|
||||
else if ('error' in r && r.error !== undefined) {
|
||||
setToast(t('settings.data.import.err'))
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Row>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-[15px] font-semibold leading-tight">
|
||||
{t('settings.data.export.label')}
|
||||
</div>
|
||||
<div className="text-[13px] text-text/65 mt-1 leading-snug">
|
||||
{t('settings.data.export.hint')}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={onExport}
|
||||
disabled={busy}
|
||||
className="h-9 px-4 rounded-xl bg-surface-2 hover:bg-hairline/25 text-[14px] font-semibold transition-colors disabled:opacity-50"
|
||||
>
|
||||
{t('settings.data.export.btn')}
|
||||
</button>
|
||||
</Row>
|
||||
<Row last>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-[15px] font-semibold leading-tight">
|
||||
{t('settings.data.import.label')}
|
||||
</div>
|
||||
<div className="text-[13px] text-text/65 mt-1 leading-snug">
|
||||
{t('settings.data.import.hint')}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={onImport}
|
||||
disabled={busy}
|
||||
className="h-9 px-4 rounded-xl bg-surface-2 hover:bg-hairline/25 text-[14px] font-semibold transition-colors disabled:opacity-50"
|
||||
>
|
||||
{t('settings.data.import.btn')}
|
||||
</button>
|
||||
</Row>
|
||||
{toast && (
|
||||
<div className="px-4 py-2.5 text-[13px] text-text/75 bg-accent/8 truncate font-medium">
|
||||
{toast}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -25,5 +25,15 @@ export function ThemeProvider({
|
||||
else document.documentElement.classList.remove('dark')
|
||||
}, [settings?.theme, osTheme])
|
||||
|
||||
// Синхронизируем <html lang> с языком приложения. Без этого screen-readers
|
||||
// продолжают читать английский текст как кириллицу (или ломаются) при
|
||||
// переключении на EN, и наоборот — это a11y-баг.
|
||||
useEffect(() => {
|
||||
const lang = settings?.language ?? 'ru'
|
||||
if (document.documentElement.lang !== lang) {
|
||||
document.documentElement.lang = lang
|
||||
}
|
||||
}, [settings?.language])
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
/* Self-hosted шрифты — раньше тянулись с fonts.googleapis.com через <link>
|
||||
в index.html. Минусы: внешняя зависимость (без интернета шрифты не
|
||||
загружаются), CSP вынужден разрешать style-src https://fonts.googleapis.com
|
||||
и font-src https://fonts.gstatic.com. Сейчас локальные .woff2 в bundle. */
|
||||
@import '@fontsource/plus-jakarta-sans/400.css';
|
||||
@import '@fontsource/plus-jakarta-sans/500.css';
|
||||
@import '@fontsource/plus-jakarta-sans/600.css';
|
||||
@import '@fontsource/plus-jakarta-sans/700.css';
|
||||
@import '@fontsource/plus-jakarta-sans/800.css';
|
||||
@import '@fontsource/bricolage-grotesque/500.css';
|
||||
@import '@fontsource/bricolage-grotesque/600.css';
|
||||
@import '@fontsource/bricolage-grotesque/700.css';
|
||||
@import '@fontsource/bricolage-grotesque/800.css';
|
||||
@import '@fontsource/jetbrains-mono/400.css';
|
||||
@import '@fontsource/jetbrains-mono/500.css';
|
||||
@import '@fontsource/jetbrains-mono/600.css';
|
||||
@import '@fontsource/jetbrains-mono/700.css';
|
||||
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@@ -11,6 +11,7 @@ export const IPC = {
|
||||
updateSettings: 'settings:update',
|
||||
getAccentColor: 'system:accentColor',
|
||||
getOsTheme: 'system:osTheme',
|
||||
getAppVersion: 'system:appVersion',
|
||||
|
||||
pauseAll: 'app:pauseAll',
|
||||
resumeAll: 'app:resumeAll',
|
||||
@@ -38,6 +39,10 @@ export const IPC = {
|
||||
markChallengeDone: 'challenge:markDone',
|
||||
closeMatchSummary: 'matchSummary:close',
|
||||
|
||||
// Dev-only IPC (handler ungated в prod, см. ipc.ts). Держим в enum чтобы
|
||||
// main/preload/renderer не разошлись в hardcoded-строках.
|
||||
devSimulateMatchEnd: 'dev:simulateMatchEnd',
|
||||
|
||||
// Auto-updater
|
||||
updaterStatus: 'updater:status',
|
||||
updaterCheck: 'updater:check',
|
||||
@@ -48,6 +53,10 @@ export const IPC = {
|
||||
getHistory: 'history:get',
|
||||
clearHistory: 'history:clear',
|
||||
|
||||
// Export / Import
|
||||
exportState: 'state:export',
|
||||
importState: 'state:import',
|
||||
|
||||
// events from main → renderer
|
||||
evtTick: 'evt:tick',
|
||||
evtFire: 'evt:fire',
|
||||
|
||||
243
src/shared/release-notes.ts
Normal file
243
src/shared/release-notes.ts
Normal file
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* Заметки релизов для UI «Что нового». Хардкодные — синхронизируются
|
||||
* с CHANGELOG.md руками при релизе. Не парсим .md в runtime: лишняя
|
||||
* сложность, плюс отделение «коротких заметок для пользователя» от
|
||||
* «развёрнутого технического CHANGELOG'а».
|
||||
*
|
||||
* Формат: версия → язык → массив пунктов (короткий заголовок + опц. деталь).
|
||||
* Не более 5-7 пунктов на версию, иначе пользователь скроллит.
|
||||
*/
|
||||
import type { Language } from './types'
|
||||
|
||||
export type ReleaseNoteItem = {
|
||||
/** Лаконичная строка-заголовок (≤ 60 символов). */
|
||||
title: string
|
||||
/** Опциональная одна строка-деталь (≤ 140 символов). */
|
||||
detail?: string
|
||||
/** Категория для tint'а иконки. */
|
||||
tag?: 'new' | 'fix' | 'security' | 'perf'
|
||||
}
|
||||
|
||||
export type ReleaseNotes = Record<Language, ReleaseNoteItem[]>
|
||||
|
||||
export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
|
||||
'0.5.6': {
|
||||
ru: [
|
||||
{
|
||||
title: 'Категории напоминаний',
|
||||
detail:
|
||||
'Помимо упражнений — гидратация, отдых глазам (20-20-20), осанка.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Голосовые подсказки',
|
||||
detail:
|
||||
'Диктор произносит название упражнения и количество. Включается в настройках.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Достижения',
|
||||
detail:
|
||||
'Milestones по количеству повторений и серий — с прогресс-баром до ближайшей цели.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Дневная цель',
|
||||
detail:
|
||||
'Soft-cap на упражнение: набрал N повторов — реминдер умолкает до завтра.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Авто-пауза на ВКС',
|
||||
detail:
|
||||
'Не дёргает напоминаниями, если запущен Zoom/Teams/Discord/Webex/Slack-huddle.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Адаптивный шедулер',
|
||||
detail:
|
||||
'Учит часы, в которые ты честно делаешь упражнение, и сдвигает fire-ы туда.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Экспорт и импорт',
|
||||
detail:
|
||||
'Резервная копия упражнений, истории и настроек в JSON — для переноса на другую машину.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Кнопка «Что нового»',
|
||||
detail: 'Это окно. Открывается автоматически после обновления.',
|
||||
tag: 'new'
|
||||
}
|
||||
],
|
||||
en: [
|
||||
{
|
||||
title: 'Reminder categories',
|
||||
detail:
|
||||
'Beyond exercises — hydration, eye rest (20-20-20), posture.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Voice prompts',
|
||||
detail:
|
||||
'Speaks the exercise name and count. Toggle in Settings.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Achievements',
|
||||
detail:
|
||||
'Milestones by total reps and streaks, with a progress bar to the next one.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Daily goal',
|
||||
detail:
|
||||
'Soft cap per exercise: hit N reps and that reminder goes quiet until tomorrow.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Meeting auto-pause',
|
||||
detail:
|
||||
'No reminders while Zoom/Teams/Discord/Webex/Slack-huddle is running.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Adaptive scheduling',
|
||||
detail:
|
||||
'Learns the hours you reliably do an exercise and shifts fires into those windows.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Export & import',
|
||||
detail:
|
||||
'JSON backup of exercises, history and settings — for moving to another machine.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: "What's new screen",
|
||||
detail: 'This screen. Opens automatically after an update.',
|
||||
tag: 'new'
|
||||
}
|
||||
]
|
||||
},
|
||||
'0.5.5': {
|
||||
ru: [
|
||||
{
|
||||
title: 'Sandbox для окон',
|
||||
detail: 'Окна изолированы на уровне OS — даже RCE в рендере не достанет main.',
|
||||
tag: 'security'
|
||||
},
|
||||
{
|
||||
title: 'Self-hosted шрифты',
|
||||
detail:
|
||||
'Plus Jakarta Sans + Bricolage Grotesque локально в bundle — работает без интернета.',
|
||||
tag: 'security'
|
||||
},
|
||||
{
|
||||
title: 'Логи для диагностики',
|
||||
detail:
|
||||
'%APPDATA%/Exercise Reminder/logs/latest.log — отдашь файл при проблеме.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'UI не залипает при retry-ях I/O',
|
||||
tag: 'perf'
|
||||
},
|
||||
{
|
||||
title: 'GSI больше не зависает на TIME_WAIT при выходе',
|
||||
tag: 'fix'
|
||||
}
|
||||
],
|
||||
en: [
|
||||
{
|
||||
title: 'Window sandbox',
|
||||
detail: 'OS-level isolation — even RCE in the renderer cannot reach main.',
|
||||
tag: 'security'
|
||||
},
|
||||
{
|
||||
title: 'Self-hosted fonts',
|
||||
detail:
|
||||
'Plus Jakarta Sans + Bricolage Grotesque shipped in-bundle — works offline.',
|
||||
tag: 'security'
|
||||
},
|
||||
{
|
||||
title: 'Diagnostic logs',
|
||||
detail:
|
||||
'%APPDATA%/Exercise Reminder/logs/latest.log — share it when something breaks.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'UI no longer freezes during I/O retries',
|
||||
tag: 'perf'
|
||||
},
|
||||
{
|
||||
title: 'GSI port no longer stuck in TIME_WAIT after exit',
|
||||
tag: 'fix'
|
||||
}
|
||||
]
|
||||
},
|
||||
'0.5.4': {
|
||||
ru: [
|
||||
{
|
||||
title: 'Фоновое скачивание апдейта',
|
||||
detail: 'Можно уйти на Dashboard и заниматься — апдейт качается в фоне.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Моментальный рестарт',
|
||||
detail: 'Кнопка «Рестарт» — ~1-2 сек до открытия новой версии, без диалогов NSIS.',
|
||||
tag: 'new'
|
||||
}
|
||||
],
|
||||
en: [
|
||||
{
|
||||
title: 'Background update download',
|
||||
detail: 'You can go to Dashboard and work — the update keeps downloading.',
|
||||
tag: 'new'
|
||||
},
|
||||
{
|
||||
title: 'Instant restart',
|
||||
detail: 'Restart button — ~1-2 sec to the new version, no NSIS dialogs.',
|
||||
tag: 'new'
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает версии, отсортированные desc, для которых есть заметки,
|
||||
* с версиями, не виденными пользователем. Используется для «show whatsnew
|
||||
* after update»: если пользователь прыгнул через несколько версий, показываем
|
||||
* все пропущенные одним списком.
|
||||
*/
|
||||
export function unseenVersions(
|
||||
current: string,
|
||||
lastSeen: string | undefined
|
||||
): string[] {
|
||||
const all = Object.keys(RELEASE_NOTES).sort(compareSemverDesc)
|
||||
if (!lastSeen) {
|
||||
// Первый запуск этого механизма — показываем только текущую версию
|
||||
// чтобы не перегружать историей. Старые версии показывает только
|
||||
// явный «What's new» из Settings.
|
||||
return all.filter((v) => v === current)
|
||||
}
|
||||
return all.filter((v) => compareSemver(v, lastSeen) > 0 && compareSemver(v, current) <= 0)
|
||||
}
|
||||
|
||||
function parseSemver(v: string): [number, number, number] {
|
||||
const parts = v.split('.').map((n) => parseInt(n, 10))
|
||||
return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0]
|
||||
}
|
||||
|
||||
function compareSemver(a: string, b: string): number {
|
||||
const [a1, a2, a3] = parseSemver(a)
|
||||
const [b1, b2, b3] = parseSemver(b)
|
||||
if (a1 !== b1) return a1 - b1
|
||||
if (a2 !== b2) return a2 - b2
|
||||
return a3 - b3
|
||||
}
|
||||
|
||||
function compareSemverDesc(a: string, b: string): number {
|
||||
return -compareSemver(a, b)
|
||||
}
|
||||
@@ -30,7 +30,11 @@ describe('SAMPLE_EXERCISES', () => {
|
||||
expect(ex.icon.length, `icon set for ${ex.name}`).toBeGreaterThan(0)
|
||||
}
|
||||
})
|
||||
|
||||
})
|
||||
// NB: тест «sample icons ⊆ ICON_CHOICES» лежит в
|
||||
// src/renderer/src/lib/icon-choices.test.ts — он тянет renderer-сторону
|
||||
// (ICON_CHOICES), а node-tsconfig сюда не пускает renderer-импорты.
|
||||
|
||||
describe('STAT_LABELS', () => {
|
||||
it('has a Russian label for every GameStat in every GAME_STATS bundle', () => {
|
||||
|
||||
@@ -1,3 +1,20 @@
|
||||
/**
|
||||
* Категория напоминания. По умолчанию `exercise` — для совместимости со
|
||||
* старыми state'ами (поле optional). Категория влияет на:
|
||||
* - tint иконки в карточке (hydration синий, eyes фиолетовый и т.д.)
|
||||
* - текст в окне напоминания («Время попить» вместо «Время тренировки»)
|
||||
* - подсчёт повторений: для hydration/eyes/posture `reps` обычно = 1
|
||||
* (это не «N раз», а просто «сделай»).
|
||||
*/
|
||||
export type ReminderCategory = 'exercise' | 'hydration' | 'eyes' | 'posture'
|
||||
|
||||
export const REMINDER_CATEGORIES: ReminderCategory[] = [
|
||||
'exercise',
|
||||
'hydration',
|
||||
'eyes',
|
||||
'posture'
|
||||
]
|
||||
|
||||
export type Exercise = {
|
||||
id: string
|
||||
name: string
|
||||
@@ -7,6 +24,22 @@ export type Exercise = {
|
||||
enabled: boolean
|
||||
nextFireAt: number
|
||||
lastDoneAt?: number
|
||||
/** Default 'exercise' если undefined — обратная совместимость. */
|
||||
category?: ReminderCategory
|
||||
/**
|
||||
* Опциональная дневная цель в reps. Если задана, scheduler перестаёт
|
||||
* fire'ить упражнение в течение дня, когда total reps за сегодня
|
||||
* (учитывая actualReps в истории) достигают `dailyGoal`. Это «soft cap»
|
||||
* поверх обычного interval'а: не меняет схему таймера, просто блокирует
|
||||
* fires когда цель закрыта. Завтра счётчик обнуляется (по local day).
|
||||
*/
|
||||
dailyGoal?: number
|
||||
/**
|
||||
* Адаптивный режим: scheduler анализирует исторические success/skip
|
||||
* паттерны по часам и сдвигает fire'ы на «хорошие» часы. Не меняет
|
||||
* базовый интервал — корректирует только timestamps.
|
||||
*/
|
||||
adaptive?: boolean
|
||||
}
|
||||
|
||||
export type NotificationMode = 'toast' | 'modal' | 'both'
|
||||
@@ -30,6 +63,18 @@ export type Settings = {
|
||||
globalEnabled: boolean
|
||||
notificationMode: NotificationMode
|
||||
soundEnabled: boolean
|
||||
/**
|
||||
* TTS голос диктора в окне напоминания: «Время приседать. Десять раз».
|
||||
* Полезно когда работаешь head-down (например пишешь код) — beep можно
|
||||
* пропустить, голос — нет.
|
||||
*/
|
||||
voicePromptsEnabled: boolean
|
||||
/**
|
||||
* Авто-пауза напоминаний во время ВКС-звонков. Сканирует список процессов
|
||||
* (Zoom/Teams/Discord/Webex/Slack-huddle/etc) раз в 30 сек, если хоть один
|
||||
* запущен — fires не происходят. Чисто Windows (через tasklist).
|
||||
*/
|
||||
meetingAutoPause: boolean
|
||||
startWithWindows: boolean
|
||||
minimizeToTray: boolean
|
||||
startMinimized: boolean
|
||||
@@ -37,13 +82,30 @@ export type Settings = {
|
||||
language: Language
|
||||
snoozeMinutes: number
|
||||
quietHours: QuietHours
|
||||
/**
|
||||
* Версия, для которой пользователь видел экран «Что нового». Если
|
||||
* `app.getVersion()` отличается — модалка показывается при следующем
|
||||
* запуске и записывает текущую версию.
|
||||
*/
|
||||
lastSeenVersion?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* State, видимое renderer'у (через IPC.getState и evtStateChanged).
|
||||
* `history` намеренно НЕ включена — она достигает 10k записей × ~50 байт =
|
||||
* 500KB JSON, и шлать её на каждый markDone/snooze/etc слишком дорого.
|
||||
* Renderer запрашивает историю отдельно через `getHistory()` IPC (с опц.
|
||||
* `sinceMs` для инкрементальной подгрузки).
|
||||
*/
|
||||
export type AppState = {
|
||||
exercises: Exercise[]
|
||||
settings: Settings
|
||||
challenges: Challenge[]
|
||||
gamesEnabled: Partial<Record<GameId, boolean>>
|
||||
}
|
||||
|
||||
/** Persisted shape — расширяет AppState историей (живёт только в main). */
|
||||
export type PersistedState = AppState & {
|
||||
history?: HistoryEntry[]
|
||||
}
|
||||
|
||||
@@ -162,6 +224,8 @@ export const DEFAULT_SETTINGS: Settings = {
|
||||
globalEnabled: true,
|
||||
notificationMode: 'modal',
|
||||
soundEnabled: true,
|
||||
voicePromptsEnabled: false, // opt-in — на работе с коллегами может смущать
|
||||
meetingAutoPause: true,
|
||||
startWithWindows: false,
|
||||
minimizeToTray: true,
|
||||
startMinimized: false,
|
||||
@@ -235,21 +299,40 @@ export const SAMPLE_EXERCISES: Omit<Exercise, 'id' | 'nextFireAt'>[] = [
|
||||
reps: 10,
|
||||
icon: 'Activity',
|
||||
intervalMinutes: 30,
|
||||
enabled: true
|
||||
enabled: true,
|
||||
category: 'exercise'
|
||||
},
|
||||
{
|
||||
name: 'Отжимания',
|
||||
reps: 10,
|
||||
icon: 'Dumbbell',
|
||||
intervalMinutes: 45,
|
||||
enabled: true
|
||||
enabled: true,
|
||||
category: 'exercise'
|
||||
},
|
||||
{
|
||||
name: 'Растяжка спины',
|
||||
name: 'Стакан воды',
|
||||
reps: 1,
|
||||
icon: 'StretchHorizontal',
|
||||
icon: 'GlassWater',
|
||||
intervalMinutes: 60,
|
||||
enabled: false
|
||||
enabled: false,
|
||||
category: 'hydration'
|
||||
},
|
||||
{
|
||||
name: 'Отдых глазам (20-20-20)',
|
||||
reps: 1,
|
||||
icon: 'Eye',
|
||||
intervalMinutes: 20,
|
||||
enabled: false,
|
||||
category: 'eyes'
|
||||
},
|
||||
{
|
||||
name: 'Проверь осанку',
|
||||
reps: 1,
|
||||
icon: 'PersonStanding',
|
||||
intervalMinutes: 25,
|
||||
enabled: false,
|
||||
category: 'posture'
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user