Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
deb3483f94 | ||
|
|
5ed80d7122 | ||
|
|
baf96ca0fa | ||
|
|
7c40558cd3 | ||
|
|
925181a3b7 | ||
|
|
8196bd3351 |
57
CHANGELOG.md
57
CHANGELOG.md
@@ -6,6 +6,51 @@
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.6.3] — 2026-06-07
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Главный экран получил новый блок прогресса: мягкий уровень, недельные
|
||||||
|
мини-челленджи и “игровой долг” после каток.
|
||||||
|
- Добавлен `src/renderer/src/lib/momentum.ts`: вычисляемая модель ритма недели,
|
||||||
|
XP/уровня и Dota match-debt без изменения persisted state.
|
||||||
|
- Добавлены тесты `momentum.test.ts` на недельные челленджи, игровые долги и
|
||||||
|
расчет уровня.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Визуальный бренд в интерфейсе сменен на “Не Залипай”.
|
||||||
|
- README обновлен под новую продуктовую концепцию: план дня, недельные
|
||||||
|
челленджи, игровые долги и 241 passing tests.
|
||||||
|
|
||||||
|
## [0.6.2] — 2026-06-06
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `npm run verify` и `scripts/verify.ps1`: typecheck, tests, lint, build и
|
||||||
|
audit summary одним локальным прогоном.
|
||||||
|
- Diagnostics card в Settings: версии приложения/runtime, userData/store/log
|
||||||
|
paths, счетчики persisted state, updater/game/GSI/meeting status, открытие
|
||||||
|
папки логов и копирование diagnostics JSON.
|
||||||
|
- Renderer error reporting: `ErrorBoundary`, `window.error` и
|
||||||
|
`unhandledrejection` теперь отправляют отчеты в main logs.
|
||||||
|
- Electron security hardening: deny-by-default permission handlers и запрет
|
||||||
|
`webview` attach.
|
||||||
|
- `docs/SECURITY_TRIAGE.md` с текущим audit baseline и release rules.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Обновлены зависимости: Electron `42.3.3`, electron-builder `26.15.0`,
|
||||||
|
electron-vite `5.0.0`, Vite `7.3.5`, `@vitejs/plugin-react` `5.2.0`,
|
||||||
|
electron-updater `6.8.9`, esbuild `0.28.0`.
|
||||||
|
- Валидация quiet hours стала строгой в renderer и main: значения вроде
|
||||||
|
`25:00` / `09:99` отклоняются до сохранения.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- `npm audit` снижен с 13 vulnerabilities до 0 после staged upgrade Electron
|
||||||
|
runtime и build-chain.
|
||||||
|
|
||||||
## [0.5.8] — 2026-05-22
|
## [0.5.8] — 2026-05-22
|
||||||
|
|
||||||
Автономный QA-проход: проверил все элементы, нашёл и починил несколько
|
Автономный QA-проход: проверил все элементы, нашёл и починил несколько
|
||||||
@@ -16,17 +61,17 @@
|
|||||||
- **Heatmap / streak / достижения теперь обновляются после markDone.**
|
- **Heatmap / streak / достижения теперь обновляются после markDone.**
|
||||||
Был регресс из Sprint C (#9 — отделение history от broadcastState):
|
Был регресс из Sprint C (#9 — отделение history от broadcastState):
|
||||||
`markDone` мутирует Exercise in-place → state.exercises ref не
|
`markDone` мутирует Exercise in-place → state.exercises ref не
|
||||||
меняется → Dashboard useEffect с дептой `[exercises]` не fire'ил →
|
меняется → Dashboard useEffect с дептой `[exercises]` не fire'ил →
|
||||||
history не перетягивалась. Heatmap стоял пока пользователь не
|
history не перетягивалась. Heatmap стоял пока пользователь не
|
||||||
добавит/удалит упражнение. Сейчас новый event `evtHistoryChanged`
|
добавит/удалит упражнение. Сейчас новый event `evtHistoryChanged`
|
||||||
шлётся из main после `markDone/snooze/skip/markChallengeDone/
|
шлётся из main после `markDone/snooze/skip/markChallengeDone/
|
||||||
clearHistory/import`, Dashboard на него подписан.
|
clearHistory/import`, Dashboard на него подписан.
|
||||||
- **Rapid double-click больше не пишет в историю дважды.** В Match
|
- **Rapid double-click больше не пишет в историю дважды.** В Match
|
||||||
Summary при быстром тыке ✓ дважды один и тот же challenge мог
|
Summary при быстром тыке ✓ дважды один и тот же challenge мог
|
||||||
записаться 2 раза → лишние +N reps в стрик. То же для кнопки
|
записаться 2 раза → лишние +N reps в стрик. То же для кнопки
|
||||||
«Готово» в ExerciseCard. ref-based дедуп.
|
«Готово» в ExerciseCard. ref-based дедуп.
|
||||||
- **Native save/open dialogs локализованы.** Раньше title `«Сохранить
|
- **Native save/open dialogs локализованы.** Раньше title `«Сохранить
|
||||||
резервную копию»` показывался даже в EN-локали.
|
резервную копию»` показывался даже в EN-локали.
|
||||||
- **Default exerciseName в challenge editor — пустой** (было
|
- **Default exerciseName в challenge editor — пустой** (было
|
||||||
«Приседания» — выглядело как недопереведённый русский в EN UI).
|
«Приседания» — выглядело как недопереведённый русский в EN UI).
|
||||||
|
|
||||||
@@ -334,7 +379,7 @@
|
|||||||
блокирует CSRF от browser-вкладок. Body cap 256 KB (OOM-вектор
|
блокирует CSRF от browser-вкладок. Body cap 256 KB (OOM-вектор
|
||||||
закрыт). Require `application/json`. Generic 400 без error-echo.
|
закрыт). Require `application/json`. Generic 400 без error-echo.
|
||||||
- **`isQuietAt` wrap-around + day filter.** С `22:00 → 07:00,
|
- **`isQuietAt` wrap-around + day filter.** С `22:00 → 07:00,
|
||||||
days=[Mon..Fri]` теперь правильно проверяется день *начала* окна
|
days=[Mon..Fri]` теперь правильно проверяется день _начала_ окна
|
||||||
(старт Fri 22:00 → активно ночью Sat 02:00).
|
(старт Fri 22:00 → активно ночью Sat 02:00).
|
||||||
- **DST drift в `history.ts`.** Календарная арифметика (`setDate`)
|
- **DST drift в `history.ts`.** Календарная арифметика (`setDate`)
|
||||||
вместо ms-арифметики — на границе DST дни больше не дублируются.
|
вместо ms-арифметики — на границе DST дни больше не дублируются.
|
||||||
@@ -446,7 +491,9 @@
|
|||||||
иконки), системный трей, автозапуск с Windows, native-уведомления,
|
иконки), системный трей, автозапуск с Windows, native-уведомления,
|
||||||
NSIS-инсталлятор, auto-update через electron-updater.
|
NSIS-инсталлятор, auto-update через electron-updater.
|
||||||
|
|
||||||
[Unreleased]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/compare/v0.5.8...HEAD
|
[Unreleased]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/compare/v0.6.3...HEAD
|
||||||
|
[0.6.3]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/compare/v0.6.2...v0.6.3
|
||||||
|
[0.6.2]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/compare/v0.5.8...v0.6.2
|
||||||
[0.5.8]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/tag/v0.5.8
|
[0.5.8]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/tag/v0.5.8
|
||||||
[0.5.7]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/tag/v0.5.7
|
[0.5.7]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/tag/v0.5.7
|
||||||
[0.5.6]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/tag/v0.5.6
|
[0.5.6]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/tag/v0.5.6
|
||||||
|
|||||||
22
README.md
22
README.md
@@ -1,9 +1,9 @@
|
|||||||
# Laude — Exercise Reminder
|
# Не Залипай — Exercise Reminder
|
||||||
|
|
||||||
Windows desktop приложение, которое напоминает делать упражнения во время работы за компьютером. Опционально подключается к Dota 2 и после каждого матча превращает статистику (смерти, убийства, ассисты) в количество повторений.
|
Windows desktop приложение, которое помогает не залипать за компьютером: держит план дня, напоминает размяться, ведёт недельные челленджи и превращает Dota 2 статистику после матча в игровые долги.
|
||||||
|
|
||||||
[](https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/latest)
|
[](https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/latest)
|
||||||
[]()
|
[]()
|
||||||
[]()
|
[]()
|
||||||
|
|
||||||
## Что внутри
|
## Что внутри
|
||||||
@@ -11,6 +11,7 @@ Windows desktop приложение, которое напоминает дел
|
|||||||
- **Гибкие напоминания** — любое количество упражнений, интервал от минуты до часов, разные иконки.
|
- **Гибкие напоминания** — любое количество упражнений, интервал от минуты до часов, разные иконки.
|
||||||
- **Питание** — отдельная вкладка с приёмами пищи по времени суток (завтрак/обед/ужин/перекусы), выбор дней недели, пресеты быстрого добавления. Напоминания по настенным часам, а не по интервалу.
|
- **Питание** — отдельная вкладка с приёмами пищи по времени суток (завтрак/обед/ужин/перекусы), выбор дней недели, пресеты быстрого добавления. Напоминания по настенным часам, а не по интервалу.
|
||||||
- **История и стрики** — heatmap-календарь активности, ежедневный счётчик, серия дней подряд.
|
- **История и стрики** — heatmap-календарь активности, ежедневный счётчик, серия дней подряд.
|
||||||
|
- **Сегодня** — главный экран с планом дня, уровнем, недельными мини-челленджами и игровым долгом.
|
||||||
- **Тихие часы** — окно времени когда напоминания подавляются (например `22:00 → 08:00`), с выбором дней недели.
|
- **Тихие часы** — окно времени когда напоминания подавляются (например `22:00 → 08:00`), с выбором дней недели.
|
||||||
- **Сделал частично** — степпер `−/+` в окне напоминания: если ты сделал 5 из 10, в историю запишется честное число.
|
- **Сделал частично** — степпер `−/+` в окне напоминания: если ты сделал 5 из 10, в историю запишется честное число.
|
||||||
- **Игровая интеграция (Dota 2)** — Game State Integration читает статистику матча, после Победа/Поражение показывает экран с «причитающимися» повторениями (например `10 смертей × 3 = 30 приседаний`).
|
- **Игровая интеграция (Dota 2)** — Game State Integration читает статистику матча, после Победа/Поражение показывает экран с «причитающимися» повторениями (например `10 смертей × 3 = 30 приседаний`).
|
||||||
@@ -45,6 +46,7 @@ npm run dev
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run typecheck # tsc по main + renderer
|
npm run typecheck # tsc по main + renderer
|
||||||
|
npm run verify # typecheck + tests + lint + build + audit summary
|
||||||
npm run test # vitest в watch-режиме
|
npm run test # vitest в watch-режиме
|
||||||
npm run test:run # vitest один раз (для CI)
|
npm run test:run # vitest один раз (для CI)
|
||||||
npm run build # сборка без NSIS
|
npm run build # сборка без NSIS
|
||||||
@@ -56,8 +58,8 @@ npm run release -- -Bump patch # bump версии + tag + push + upload в G
|
|||||||
|
|
||||||
## Архитектура
|
## Архитектура
|
||||||
|
|
||||||
- **Electron 33** — multi-process: main (Node/scheduler/GSI) + preload (contextBridge) + renderer (React)
|
- **Electron 42** — multi-process: main (Node/scheduler/GSI) + preload (contextBridge) + renderer (React)
|
||||||
- **Renderer** — React 18, TypeScript 5, Vite 5, Tailwind 3, framer-motion, react-router, zustand
|
- **Renderer** — React 18, TypeScript 5, Vite 7, Tailwind 3, framer-motion, react-router, zustand
|
||||||
- **Persistence** — единственный JSON-файл `%APPDATA%\Exercise Reminder\app-state.json` (debounced writes)
|
- **Persistence** — единственный JSON-файл `%APPDATA%\Exercise Reminder\app-state.json` (debounced writes)
|
||||||
- **IPC** — типизированные каналы через `src/shared/ipc.ts`, обёрнуто preload-ом
|
- **IPC** — типизированные каналы через `src/shared/ipc.ts`, обёрнуто preload-ом
|
||||||
- **i18n** — самописная микро-система: `src/renderer/src/i18n/dict.ts` (плоский словарь ~200 ключей × 2 языка) + хук `useT()`
|
- **i18n** — самописная микро-система: `src/renderer/src/i18n/dict.ts` (плоский словарь ~200 ключей × 2 языка) + хук `useT()`
|
||||||
@@ -71,19 +73,21 @@ src/main/validate.test.ts (78)
|
|||||||
src/renderer/src/lib/history.test.ts (31)
|
src/renderer/src/lib/history.test.ts (31)
|
||||||
src/renderer/src/i18n/i18n.test.ts (15)
|
src/renderer/src/i18n/i18n.test.ts (15)
|
||||||
src/renderer/src/lib/format.test.ts (14)
|
src/renderer/src/lib/format.test.ts (14)
|
||||||
src/main/scheduler.test.ts (13)
|
src/main/scheduler.test.ts (14)
|
||||||
src/main/games/vdf.test.ts (11)
|
src/main/games/vdf.test.ts (11)
|
||||||
src/main/store.test.ts (10)
|
src/main/store.test.ts (12)
|
||||||
src/renderer/src/lib/achievements.test.ts (10)
|
src/renderer/src/lib/achievements.test.ts (10)
|
||||||
src/shared/release-notes.test.ts (9)
|
src/shared/release-notes.test.ts (9)
|
||||||
src/shared/meals.test.ts (8)
|
src/shared/meals.test.ts (8)
|
||||||
src/main/meeting-detect.test.ts (7)
|
src/main/meeting-detect.test.ts (7)
|
||||||
src/shared/quiet-hours.test.ts (7)
|
src/shared/quiet-hours.test.ts (7)
|
||||||
src/main/adaptive.test.ts (6)
|
src/main/adaptive.test.ts (6)
|
||||||
|
src/renderer/src/lib/day-plan.test.ts (6)
|
||||||
src/shared/types.test.ts (4)
|
src/shared/types.test.ts (4)
|
||||||
src/renderer/src/lib/icon-choices.test.ts (4)
|
src/renderer/src/lib/icon-choices.test.ts (4)
|
||||||
|
src/renderer/src/lib/momentum.test.ts (3)
|
||||||
──────────────────────────────────────────
|
──────────────────────────────────────────
|
||||||
227 ✓
|
241 ✓
|
||||||
```
|
```
|
||||||
|
|
||||||
Покрытие: IPC-валидация (упражнения/челленджи/приёмы пищи), persistence (миграции, карантин битого JSON, history cap), scheduler-гейтинг (тихие часы, ВКС-пауза, daily-goal), планирование приёмов пищи по времени суток (DST-safe), детект ВКС, история/стрики (DST), тихие часы (wrap), парсер VDF для Steam-конфигов, достижения, i18n с плюрализацией RU/EN, дефолты shared-типов.
|
Покрытие: IPC-валидация (упражнения/челленджи/приёмы пищи), persistence (миграции, карантин битого JSON, history cap), scheduler-гейтинг (тихие часы, ВКС-пауза, daily-goal), планирование приёмов пищи по времени суток (DST-safe), детект ВКС, история/стрики (DST), тихие часы (wrap), парсер VDF для Steam-конфигов, достижения, i18n с плюрализацией RU/EN, дефолты shared-типов.
|
||||||
|
|||||||
88
docs/SECURITY_TRIAGE.md
Normal file
88
docs/SECURITY_TRIAGE.md
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
# Security triage
|
||||||
|
|
||||||
|
Дата последнего triage: 2026-06-06
|
||||||
|
|
||||||
|
Этот файл фиксирует текущий статус `npm audit`, принятые решения по
|
||||||
|
dependency-upgrade и минимальные правила перед релизом. Он не заменяет
|
||||||
|
регулярное обновление зависимостей: цель в том, чтобы не терять контекст между
|
||||||
|
релизами и отличать runtime-риск от build-chain риска.
|
||||||
|
|
||||||
|
## Текущий статус
|
||||||
|
|
||||||
|
`npm run verify` выполняет:
|
||||||
|
|
||||||
|
- typecheck;
|
||||||
|
- tests;
|
||||||
|
- lint;
|
||||||
|
- build;
|
||||||
|
- audit summary.
|
||||||
|
|
||||||
|
Наблюдаемый audit snapshot после upgrade:
|
||||||
|
|
||||||
|
- 0 vulnerabilities;
|
||||||
|
- `npm run verify` проходит полностью;
|
||||||
|
- `npm run dist:dir` собирает unpacked Windows build.
|
||||||
|
|
||||||
|
## Выполненные обновления
|
||||||
|
|
||||||
|
- `electron` обновлен до `42.3.3`;
|
||||||
|
- `electron-builder` обновлен до `26.15.0`;
|
||||||
|
- `electron-vite` обновлен до `5.0.0`;
|
||||||
|
- `vite` обновлен до `7.3.5`;
|
||||||
|
- `@vitejs/plugin-react` обновлен до `5.2.0`;
|
||||||
|
- `electron-updater` обновлен до `6.8.9`;
|
||||||
|
- `esbuild` обновлен до `0.28.0`.
|
||||||
|
|
||||||
|
`vite` оставлен на major 7, а не поднят до 8, потому что актуальный
|
||||||
|
`electron-vite@5.0.0` объявляет peer range `^5.0.0 || ^6.0.0 || ^7.0.0`.
|
||||||
|
Переход на Vite 8 стоит делать отдельным шагом после совместимого релиза
|
||||||
|
`electron-vite`.
|
||||||
|
|
||||||
|
## Runtime baseline
|
||||||
|
|
||||||
|
Electron является runtime-платформой приложения, поэтому его audit-риск был
|
||||||
|
самым важным. После обновления runtime-риск из audit закрыт, но перед релизом
|
||||||
|
все равно нужен ручной smoke test Electron-поведения.
|
||||||
|
|
||||||
|
Текущие mitigations:
|
||||||
|
|
||||||
|
- `sandbox: true`;
|
||||||
|
- `contextIsolation: true`;
|
||||||
|
- `nodeIntegration: false`;
|
||||||
|
- строгий preload API через `contextBridge`;
|
||||||
|
- IPC runtime validation;
|
||||||
|
- CSP в renderer `index.html`;
|
||||||
|
- allowlist для внешних URL;
|
||||||
|
- deny-by-default permission handlers;
|
||||||
|
- запрет `webview` attach;
|
||||||
|
- renderer error/unhandled rejection reporting в main logs.
|
||||||
|
|
||||||
|
## Build-chain baseline
|
||||||
|
|
||||||
|
`electron-builder`, `electron-vite`, `vite` и `esbuild` обновлены отдельным
|
||||||
|
шагом от runtime upgrade. `npm run dist:dir` подтверждает, что packaged build
|
||||||
|
создается после обновления build-chain.
|
||||||
|
|
||||||
|
Перед публикацией installer все равно нужно проверить:
|
||||||
|
|
||||||
|
- NSIS installer build через `npm run dist`;
|
||||||
|
- запуск установленного приложения;
|
||||||
|
- сохранение данных в `%APPDATA%\Exercise Reminder\`;
|
||||||
|
- auto-update metadata и `update-channel`;
|
||||||
|
- импорт/экспорт данных;
|
||||||
|
- tray behavior;
|
||||||
|
- main window и reminder window;
|
||||||
|
- Dota 2 GSI install/uninstall и callback listener.
|
||||||
|
|
||||||
|
## Release rule
|
||||||
|
|
||||||
|
Перед релизом:
|
||||||
|
|
||||||
|
- `npm run verify`;
|
||||||
|
- `npm run dist`;
|
||||||
|
- smoke test installed app;
|
||||||
|
- проверка `update-channel`;
|
||||||
|
- повторный `npm audit`.
|
||||||
|
|
||||||
|
Если новый audit снова сообщает high runtime issue, релиз нужно считать
|
||||||
|
blocked, пока риск не разобран отдельно.
|
||||||
4192
package-lock.json
generated
4192
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
17
package.json
17
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "laude",
|
"name": "laude",
|
||||||
"version": "0.6.1",
|
"version": "0.6.3",
|
||||||
"description": "Exercise reminder — Windows desktop app",
|
"description": "Не Залипай — Windows desktop rhythm and exercise reminder",
|
||||||
"main": "out/main/index.js",
|
"main": "out/main/index.js",
|
||||||
"author": "AnRil",
|
"author": "AnRil",
|
||||||
"private": true,
|
"private": true,
|
||||||
@@ -18,6 +18,7 @@
|
|||||||
"format": "prettier --write \"src/**/*.{ts,tsx,css}\" \"*.{json,md}\" \".github/**/*.yml\"",
|
"format": "prettier --write \"src/**/*.{ts,tsx,css}\" \"*.{json,md}\" \".github/**/*.yml\"",
|
||||||
"format:check": "prettier --check \"src/**/*.{ts,tsx,css}\" \"*.{json,md}\"",
|
"format:check": "prettier --check \"src/**/*.{ts,tsx,css}\" \"*.{json,md}\"",
|
||||||
"lint": "eslint src --ext .ts,.tsx --max-warnings 0",
|
"lint": "eslint src --ext .ts,.tsx --max-warnings 0",
|
||||||
|
"verify": "powershell -ExecutionPolicy Bypass -File scripts/verify.ps1",
|
||||||
"dist": "electron-vite build && electron-builder --win --x64",
|
"dist": "electron-vite build && electron-builder --win --x64",
|
||||||
"dist:dir": "electron-vite build && electron-builder --win --x64 --dir",
|
"dist:dir": "electron-vite build && electron-builder --win --x64 --dir",
|
||||||
"publish": "electron-vite build && electron-builder --win --x64 --publish always",
|
"publish": "electron-vite build && electron-builder --win --x64 --publish always",
|
||||||
@@ -28,7 +29,7 @@
|
|||||||
"@fontsource/bricolage-grotesque": "^5.2.10",
|
"@fontsource/bricolage-grotesque": "^5.2.10",
|
||||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||||
"@fontsource/plus-jakarta-sans": "^5.2.8",
|
"@fontsource/plus-jakarta-sans": "^5.2.8",
|
||||||
"electron-updater": "^6.8.3",
|
"electron-updater": "^6.8.9",
|
||||||
"framer-motion": "^11.11.17",
|
"framer-motion": "^11.11.17",
|
||||||
"lucide-react": "^0.460.0",
|
"lucide-react": "^0.460.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
@@ -42,12 +43,12 @@
|
|||||||
"@types/react-dom": "^18.3.1",
|
"@types/react-dom": "^18.3.1",
|
||||||
"@typescript-eslint/eslint-plugin": "^8.15.0",
|
"@typescript-eslint/eslint-plugin": "^8.15.0",
|
||||||
"@typescript-eslint/parser": "^8.15.0",
|
"@typescript-eslint/parser": "^8.15.0",
|
||||||
"@vitejs/plugin-react": "^4.3.3",
|
"@vitejs/plugin-react": "^5.2.0",
|
||||||
"@vitest/coverage-v8": "^4.1.6",
|
"@vitest/coverage-v8": "^4.1.6",
|
||||||
"autoprefixer": "^10.4.20",
|
"autoprefixer": "^10.4.20",
|
||||||
"electron": "^33.2.0",
|
"electron": "^42.3.3",
|
||||||
"electron-builder": "^25.1.8",
|
"electron-builder": "^26.15.0",
|
||||||
"electron-vite": "^2.3.0",
|
"electron-vite": "^5.0.0",
|
||||||
"esbuild": "^0.28.0",
|
"esbuild": "^0.28.0",
|
||||||
"eslint": "^8.57.1",
|
"eslint": "^8.57.1",
|
||||||
"eslint-plugin-react": "^7.37.2",
|
"eslint-plugin-react": "^7.37.2",
|
||||||
@@ -56,7 +57,7 @@
|
|||||||
"prettier": "^3.4.1",
|
"prettier": "^3.4.1",
|
||||||
"tailwindcss": "^3.4.15",
|
"tailwindcss": "^3.4.15",
|
||||||
"typescript": "^5.6.3",
|
"typescript": "^5.6.3",
|
||||||
"vite": "^5.4.11",
|
"vite": "^7.3.5",
|
||||||
"vitest": "^4.1.6"
|
"vitest": "^4.1.6"
|
||||||
},
|
},
|
||||||
"build": {
|
"build": {
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ param(
|
|||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
# Windows PowerShell 5.1 can default to older TLS settings and fail against
|
||||||
|
# modern HTTPS endpoints before curl.exe gets a chance to upload assets.
|
||||||
|
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
||||||
|
|
||||||
$repoOwner = 'AnRil'
|
$repoOwner = 'AnRil'
|
||||||
$repoName = 'laude'
|
$repoName = 'laude'
|
||||||
$giteaHost = 'git.xn--90adajar8af4h.xn--p1ai'
|
$giteaHost = 'git.xn--90adajar8af4h.xn--p1ai'
|
||||||
|
|||||||
31
scripts/verify.ps1
Normal file
31
scripts/verify.ps1
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
function Invoke-Step {
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory = $true)][string]$Name,
|
||||||
|
[Parameter(Mandatory = $true)][string]$Command,
|
||||||
|
[Parameter(Mandatory = $true)][string[]]$Arguments
|
||||||
|
)
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "==> $Name"
|
||||||
|
& $Command @Arguments
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "$Name failed with exit code $LASTEXITCODE"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Invoke-Step 'Typecheck' 'npm.cmd' @('run', 'typecheck')
|
||||||
|
Invoke-Step 'Tests' 'npm.cmd' @('run', 'test:run')
|
||||||
|
Invoke-Step 'Lint' 'npm.cmd' @('run', 'lint')
|
||||||
|
Invoke-Step 'Build' 'npm.cmd' @('run', 'build')
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "==> Audit summary"
|
||||||
|
& npm.cmd audit --audit-level=moderate
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Warning 'npm audit reported vulnerabilities. See the output above; verification gates still passed.'
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Verification complete."
|
||||||
79
src/main/diagnostics.ts
Normal file
79
src/main/diagnostics.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import { app, clipboard, shell } from 'electron'
|
||||||
|
import { existsSync, statSync } from 'node:fs'
|
||||||
|
import type { DiagnosticsInfo } from '@shared/types'
|
||||||
|
import {
|
||||||
|
getGsiBaseUrl,
|
||||||
|
getGsiPort,
|
||||||
|
isGsiServerRunning
|
||||||
|
} from './games/gsi-server'
|
||||||
|
import { listGamesStatus } from './games/registry'
|
||||||
|
import { getLogDir } from './logger'
|
||||||
|
import { isMeetingActiveSync } from './meeting-detect'
|
||||||
|
import { getState, getStorePath } from './store'
|
||||||
|
import { getUpdaterStatus } from './updater'
|
||||||
|
|
||||||
|
function fileSize(path: string): number | null {
|
||||||
|
try {
|
||||||
|
if (!path || !existsSync(path)) return null
|
||||||
|
return statSync(path).size
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getDiagnosticsInfo(): Promise<DiagnosticsInfo> {
|
||||||
|
const state = getState()
|
||||||
|
const store = getStorePath()
|
||||||
|
const games = await listGamesStatus()
|
||||||
|
|
||||||
|
return {
|
||||||
|
generatedAt: Date.now(),
|
||||||
|
app: {
|
||||||
|
version: app.getVersion(),
|
||||||
|
isPackaged: app.isPackaged,
|
||||||
|
platform: process.platform,
|
||||||
|
arch: process.arch
|
||||||
|
},
|
||||||
|
runtime: {
|
||||||
|
electron: process.versions.electron ?? 'unknown',
|
||||||
|
chrome: process.versions.chrome ?? 'unknown',
|
||||||
|
node: process.versions.node
|
||||||
|
},
|
||||||
|
paths: {
|
||||||
|
userData: app.getPath('userData'),
|
||||||
|
store,
|
||||||
|
logs: getLogDir()
|
||||||
|
},
|
||||||
|
store: {
|
||||||
|
bytes: fileSize(store),
|
||||||
|
exercises: state.exercises.length,
|
||||||
|
meals: state.meals.length,
|
||||||
|
challenges: state.challenges.length,
|
||||||
|
history: state.history?.length ?? 0
|
||||||
|
},
|
||||||
|
updater: getUpdaterStatus(),
|
||||||
|
games,
|
||||||
|
gsi: {
|
||||||
|
running: isGsiServerRunning(),
|
||||||
|
port: getGsiPort(),
|
||||||
|
baseUrl: getGsiBaseUrl()
|
||||||
|
},
|
||||||
|
meetingActive: isMeetingActiveSync()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openLogsFolder(): Promise<{
|
||||||
|
ok: boolean
|
||||||
|
error?: string
|
||||||
|
}> {
|
||||||
|
const dir = getLogDir()
|
||||||
|
if (!dir) return { ok: false, error: 'logs-unavailable' }
|
||||||
|
const error = await shell.openPath(dir)
|
||||||
|
return error ? { ok: false, error } : { ok: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function copyDiagnosticsToClipboard(): Promise<DiagnosticsInfo> {
|
||||||
|
const info = await getDiagnosticsInfo()
|
||||||
|
clipboard.writeText(JSON.stringify(info, null, 2))
|
||||||
|
return info
|
||||||
|
}
|
||||||
@@ -144,3 +144,7 @@ export function getGsiBaseUrl(): string {
|
|||||||
export function getGsiPort(): number {
|
export function getGsiPort(): number {
|
||||||
return PORT
|
return PORT
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isGsiServerRunning(): boolean {
|
||||||
|
return server !== null
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { startGamesRegistry, stopGamesRegistry } from './games/registry'
|
|||||||
import { initUpdater, stopUpdater } from './updater'
|
import { initUpdater, stopUpdater } from './updater'
|
||||||
import { IPC } from '@shared/ipc'
|
import { IPC } from '@shared/ipc'
|
||||||
import { log } from './logger'
|
import { log } from './logger'
|
||||||
|
import { installSecurityHardening } from './security'
|
||||||
|
|
||||||
const APP_ID = 'com.anril.exercise-reminder'
|
const APP_ID = 'com.anril.exercise-reminder'
|
||||||
|
|
||||||
@@ -45,6 +46,7 @@ if (!gotLock) {
|
|||||||
app.on('second-instance', () => showMainWindow())
|
app.on('second-instance', () => showMainWindow())
|
||||||
|
|
||||||
app.whenReady().then(() => {
|
app.whenReady().then(() => {
|
||||||
|
installSecurityHardening()
|
||||||
registerIpc()
|
registerIpc()
|
||||||
createTray()
|
createTray()
|
||||||
|
|
||||||
|
|||||||
160
src/main/ipc.ts
160
src/main/ipc.ts
@@ -10,7 +10,12 @@ import {
|
|||||||
import type { IpcMainEvent, IpcMainInvokeEvent } from 'electron'
|
import type { IpcMainEvent, IpcMainInvokeEvent } from 'electron'
|
||||||
import { readFileSync, writeFileSync } from 'node:fs'
|
import { readFileSync, writeFileSync } from 'node:fs'
|
||||||
import { IPC } from '@shared/ipc'
|
import { IPC } from '@shared/ipc'
|
||||||
import type { Exercise, GameId, Settings } from '@shared/types'
|
import type {
|
||||||
|
Exercise,
|
||||||
|
GameId,
|
||||||
|
RendererErrorReport,
|
||||||
|
Settings
|
||||||
|
} from '@shared/types'
|
||||||
import {
|
import {
|
||||||
addChallenge,
|
addChallenge,
|
||||||
addExercise,
|
addExercise,
|
||||||
@@ -68,6 +73,13 @@ import {
|
|||||||
validateSnoozeMinutes
|
validateSnoozeMinutes
|
||||||
} from './validate'
|
} from './validate'
|
||||||
import { log } from './logger'
|
import { log } from './logger'
|
||||||
|
import {
|
||||||
|
copyDiagnosticsToClipboard,
|
||||||
|
getDiagnosticsInfo,
|
||||||
|
openLogsFolder
|
||||||
|
} from './diagnostics'
|
||||||
|
|
||||||
|
const MAX_RENDERER_ERROR_FIELD = 8_000
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Враппер вокруг `ipcMain.handle`: ловит любое исключение в обработчике,
|
* Враппер вокруг `ipcMain.handle`: ловит любое исключение в обработчике,
|
||||||
@@ -105,10 +117,7 @@ function safeOn<F extends (event: IpcMainEvent, ...args: never[]) => void>(
|
|||||||
): void {
|
): void {
|
||||||
ipcMain.on(channel, (event, ...args) => {
|
ipcMain.on(channel, (event, ...args) => {
|
||||||
try {
|
try {
|
||||||
const call = fn as unknown as (
|
const call = fn as unknown as (e: IpcMainEvent, ...a: unknown[]) => void
|
||||||
e: IpcMainEvent,
|
|
||||||
...a: unknown[]
|
|
||||||
) => void
|
|
||||||
call(event, ...args)
|
call(event, ...args)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.error(`[ipc] ${channel} (on) threw`, err)
|
log.error(`[ipc] ${channel} (on) threw`, err)
|
||||||
@@ -116,6 +125,21 @@ function safeOn<F extends (event: IpcMainEvent, ...args: never[]) => void>(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function cleanRendererError(raw: unknown): RendererErrorReport | null {
|
||||||
|
if (typeof raw !== 'object' || raw === null) return null
|
||||||
|
const r = raw as Record<string, unknown>
|
||||||
|
const message = typeof r.message === 'string' ? r.message.trim() : ''
|
||||||
|
if (!message) return null
|
||||||
|
const clean = (v: unknown): string | undefined =>
|
||||||
|
typeof v === 'string' ? v.slice(0, MAX_RENDERER_ERROR_FIELD) : undefined
|
||||||
|
return {
|
||||||
|
message: message.slice(0, MAX_RENDERER_ERROR_FIELD),
|
||||||
|
stack: clean(r.stack),
|
||||||
|
componentStack: clean(r.componentStack),
|
||||||
|
source: clean(r.source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function registerIpc(): void {
|
export function registerIpc(): void {
|
||||||
safeHandle(IPC.getState, () => {
|
safeHandle(IPC.getState, () => {
|
||||||
// Без history (см. getStateForRenderer) и с актуальным значением
|
// Без history (см. getStateForRenderer) и с актуальным значением
|
||||||
@@ -136,17 +160,14 @@ export function registerIpc(): void {
|
|||||||
return ex
|
return ex
|
||||||
})
|
})
|
||||||
|
|
||||||
safeHandle(
|
safeHandle(IPC.updateExercise, (_e, idRaw: unknown, patchRaw: unknown) => {
|
||||||
IPC.updateExercise,
|
const id = validateId(idRaw)
|
||||||
(_e, idRaw: unknown, patchRaw: unknown) => {
|
const patch = validateExercisePatch(patchRaw)
|
||||||
const id = validateId(idRaw)
|
if (!id || !patch) return null
|
||||||
const patch = validateExercisePatch(patchRaw)
|
const ex = updateExercise(id, patch)
|
||||||
if (!id || !patch) return null
|
broadcastState()
|
||||||
const ex = updateExercise(id, patch)
|
return ex
|
||||||
broadcastState()
|
})
|
||||||
return ex
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
safeHandle(IPC.deleteExercise, (_e, idRaw: unknown) => {
|
safeHandle(IPC.deleteExercise, (_e, idRaw: unknown) => {
|
||||||
const id = validateId(idRaw)
|
const id = validateId(idRaw)
|
||||||
@@ -156,21 +177,18 @@ export function registerIpc(): void {
|
|||||||
return ok
|
return ok
|
||||||
})
|
})
|
||||||
|
|
||||||
safeHandle(
|
safeHandle(IPC.toggleExercise, (_e, idRaw: unknown, enabledRaw: unknown) => {
|
||||||
IPC.toggleExercise,
|
const id = validateId(idRaw)
|
||||||
(_e, idRaw: unknown, enabledRaw: unknown) => {
|
if (!id || typeof enabledRaw !== 'boolean') return null
|
||||||
const id = validateId(idRaw)
|
const patch: Partial<Exercise> = { enabled: enabledRaw }
|
||||||
if (!id || typeof enabledRaw !== 'boolean') return null
|
if (enabledRaw) {
|
||||||
const patch: Partial<Exercise> = { enabled: enabledRaw }
|
const ex = getState().exercises.find((e) => e.id === id)
|
||||||
if (enabledRaw) {
|
if (ex) patch.nextFireAt = Date.now() + ex.intervalMinutes * 60_000
|
||||||
const ex = getState().exercises.find((e) => e.id === id)
|
|
||||||
if (ex) patch.nextFireAt = Date.now() + ex.intervalMinutes * 60_000
|
|
||||||
}
|
|
||||||
const ex = updateExercise(id, patch)
|
|
||||||
broadcastState()
|
|
||||||
return ex
|
|
||||||
}
|
}
|
||||||
)
|
const ex = updateExercise(id, patch)
|
||||||
|
broadcastState()
|
||||||
|
return ex
|
||||||
|
})
|
||||||
|
|
||||||
safeHandle(IPC.markDone, (_e, idRaw: unknown, repsRaw?: unknown) => {
|
safeHandle(IPC.markDone, (_e, idRaw: unknown, repsRaw?: unknown) => {
|
||||||
const id = validateId(idRaw)
|
const id = validateId(idRaw)
|
||||||
@@ -299,6 +317,19 @@ export function registerIpc(): void {
|
|||||||
|
|
||||||
safeHandle(IPC.getMeetingActive, () => isMeetingActiveSync())
|
safeHandle(IPC.getMeetingActive, () => isMeetingActiveSync())
|
||||||
|
|
||||||
|
safeHandle(IPC.getDiagnostics, () => getDiagnosticsInfo())
|
||||||
|
|
||||||
|
safeHandle(IPC.openLogsFolder, () => openLogsFolder())
|
||||||
|
|
||||||
|
safeHandle(IPC.copyDiagnostics, () => copyDiagnosticsToClipboard())
|
||||||
|
|
||||||
|
safeHandle(IPC.reportRendererError, (_e, raw: unknown) => {
|
||||||
|
const report = cleanRendererError(raw)
|
||||||
|
if (!report) return false
|
||||||
|
log.error('[renderer] error reported', report)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
safeHandle(IPC.quit, () => app.quit())
|
safeHandle(IPC.quit, () => app.quit())
|
||||||
safeHandle(IPC.reminderClose, () => hideReminderWindow())
|
safeHandle(IPC.reminderClose, () => hideReminderWindow())
|
||||||
|
|
||||||
@@ -369,17 +400,14 @@ export function registerIpc(): void {
|
|||||||
broadcastState()
|
broadcastState()
|
||||||
return c
|
return c
|
||||||
})
|
})
|
||||||
safeHandle(
|
safeHandle(IPC.updateChallenge, (_e, idRaw: unknown, patchRaw: unknown) => {
|
||||||
IPC.updateChallenge,
|
const id = validateId(idRaw)
|
||||||
(_e, idRaw: unknown, patchRaw: unknown) => {
|
const patch = validateChallengePatch(patchRaw)
|
||||||
const id = validateId(idRaw)
|
if (!id || !patch) return null
|
||||||
const patch = validateChallengePatch(patchRaw)
|
const c = updateChallenge(id, patch)
|
||||||
if (!id || !patch) return null
|
broadcastState()
|
||||||
const c = updateChallenge(id, patch)
|
return c
|
||||||
broadcastState()
|
})
|
||||||
return c
|
|
||||||
}
|
|
||||||
)
|
|
||||||
safeHandle(IPC.deleteChallenge, (_e, idRaw: unknown) => {
|
safeHandle(IPC.deleteChallenge, (_e, idRaw: unknown) => {
|
||||||
const id = validateId(idRaw)
|
const id = validateId(idRaw)
|
||||||
if (!id) return false
|
if (!id) return false
|
||||||
@@ -387,31 +415,25 @@ export function registerIpc(): void {
|
|||||||
broadcastState()
|
broadcastState()
|
||||||
return ok
|
return ok
|
||||||
})
|
})
|
||||||
safeHandle(
|
safeHandle(IPC.toggleChallenge, (_e, idRaw: unknown, enabledRaw: unknown) => {
|
||||||
IPC.toggleChallenge,
|
const id = validateId(idRaw)
|
||||||
(_e, idRaw: unknown, enabledRaw: unknown) => {
|
if (!id || typeof enabledRaw !== 'boolean') return null
|
||||||
const id = validateId(idRaw)
|
const c = updateChallenge(id, { enabled: enabledRaw })
|
||||||
if (!id || typeof enabledRaw !== 'boolean') return null
|
broadcastState()
|
||||||
const c = updateChallenge(id, { enabled: enabledRaw })
|
return c
|
||||||
broadcastState()
|
})
|
||||||
return c
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
safeHandle(IPC.closeMatchSummary, () => hideReminderWindow())
|
safeHandle(IPC.closeMatchSummary, () => hideReminderWindow())
|
||||||
|
|
||||||
safeHandle(
|
safeHandle(IPC.markChallengeDone, (_e, idRaw: unknown, repsRaw: unknown) => {
|
||||||
IPC.markChallengeDone,
|
const id = validateId(idRaw)
|
||||||
(_e, idRaw: unknown, repsRaw: unknown) => {
|
const reps = validateActualReps(repsRaw)
|
||||||
const id = validateId(idRaw)
|
if (!id || reps === undefined || reps <= 0) return false
|
||||||
const reps = validateActualReps(repsRaw)
|
markChallengeDone(id, reps)
|
||||||
if (!id || reps === undefined || reps <= 0) return false
|
broadcastState()
|
||||||
markChallengeDone(id, reps)
|
broadcastHistoryChanged()
|
||||||
broadcastState()
|
return true
|
||||||
broadcastHistoryChanged()
|
})
|
||||||
return true
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// Dev helper: simulate a match end with given stats. NEVER registered in
|
// Dev helper: simulate a match end with given stats. NEVER registered in
|
||||||
// packaged builds — a compromised renderer (XSS, malicious npm dep) could
|
// packaged builds — a compromised renderer (XSS, malicious npm dep) could
|
||||||
@@ -448,17 +470,13 @@ export function registerIpc(): void {
|
|||||||
// renderer не получает прямого доступа к ФС.
|
// renderer не получает прямого доступа к ФС.
|
||||||
safeHandle(IPC.exportState, async (event) => {
|
safeHandle(IPC.exportState, async (event) => {
|
||||||
const win = BrowserWindow.fromWebContents(event.sender) ?? undefined
|
const win = BrowserWindow.fromWebContents(event.sender) ?? undefined
|
||||||
const stamp = new Date()
|
const stamp = new Date().toISOString().replace(/[:T]/g, '-').slice(0, 16)
|
||||||
.toISOString()
|
|
||||||
.replace(/[:T]/g, '-')
|
|
||||||
.slice(0, 16)
|
|
||||||
const defaultPath = `laude-backup-${stamp}.json`
|
const defaultPath = `laude-backup-${stamp}.json`
|
||||||
// Native-диалоги OS читают локаль из системы. Title — единственная
|
// Native-диалоги OS читают локаль из системы. Title — единственная
|
||||||
// строка которую мы контролируем; локализуем по settings.language.
|
// строка которую мы контролируем; локализуем по settings.language.
|
||||||
const lang = getState().settings.language ?? 'ru'
|
const lang = getState().settings.language ?? 'ru'
|
||||||
const result = await dialog.showSaveDialog(win!, {
|
const result = await dialog.showSaveDialog(win!, {
|
||||||
title:
|
title: lang === 'en' ? 'Save backup' : 'Сохранить резервную копию',
|
||||||
lang === 'en' ? 'Save backup' : 'Сохранить резервную копию',
|
|
||||||
defaultPath,
|
defaultPath,
|
||||||
filters: [{ name: 'JSON', extensions: ['json'] }]
|
filters: [{ name: 'JSON', extensions: ['json'] }]
|
||||||
})
|
})
|
||||||
@@ -480,7 +498,9 @@ export function registerIpc(): void {
|
|||||||
const lang = getState().settings.language ?? 'ru'
|
const lang = getState().settings.language ?? 'ru'
|
||||||
const result = await dialog.showOpenDialog(win!, {
|
const result = await dialog.showOpenDialog(win!, {
|
||||||
title:
|
title:
|
||||||
lang === 'en' ? 'Restore from backup' : 'Восстановить из резервной копии',
|
lang === 'en'
|
||||||
|
? 'Restore from backup'
|
||||||
|
: 'Восстановить из резервной копии',
|
||||||
properties: ['openFile'],
|
properties: ['openFile'],
|
||||||
filters: [{ name: 'JSON', extensions: ['json'] }]
|
filters: [{ name: 'JSON', extensions: ['json'] }]
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -121,5 +121,6 @@ export const log = {
|
|||||||
|
|
||||||
/** Путь к логам (для диагностики). Возвращает пустую строку до initLogger(). */
|
/** Путь к логам (для диагностики). Возвращает пустую строку до initLogger(). */
|
||||||
export function getLogDir(): string {
|
export function getLogDir(): string {
|
||||||
|
ensurePaths()
|
||||||
return logDir
|
return logDir
|
||||||
}
|
}
|
||||||
|
|||||||
37
src/main/security.ts
Normal file
37
src/main/security.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { app, session } from 'electron'
|
||||||
|
import { log } from './logger'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renderer permissions are denied by default. The app does not need camera,
|
||||||
|
* microphone, geolocation, USB/HID/serial, direct notification permission or
|
||||||
|
* browser-driven openExternal; all trusted privileged actions go through
|
||||||
|
* validated IPC handlers in main.
|
||||||
|
*/
|
||||||
|
export function installSecurityHardening(): void {
|
||||||
|
session.defaultSession.setPermissionRequestHandler(
|
||||||
|
(_webContents, permission, callback, details) => {
|
||||||
|
log.warn('[security] denied permission request', {
|
||||||
|
permission,
|
||||||
|
requestingUrl: 'requestingUrl' in details ? details.requestingUrl : ''
|
||||||
|
})
|
||||||
|
callback(false)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
session.defaultSession.setPermissionCheckHandler(
|
||||||
|
(_webContents, permission, requestingOrigin) => {
|
||||||
|
log.warn('[security] denied permission check', {
|
||||||
|
permission,
|
||||||
|
requestingOrigin
|
||||||
|
})
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
app.on('web-contents-created', (_event, contents) => {
|
||||||
|
contents.on('will-attach-webview', (event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
log.warn('[security] blocked webview attach')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -47,7 +47,7 @@ let cache: PersistedState | null = null
|
|||||||
let storePath = ''
|
let storePath = ''
|
||||||
let pendingWrite: NodeJS.Timeout | null = null
|
let pendingWrite: NodeJS.Timeout | null = null
|
||||||
|
|
||||||
function getStorePath(): string {
|
export function getStorePath(): string {
|
||||||
if (!storePath) {
|
if (!storePath) {
|
||||||
const dir = app.getPath('userData')
|
const dir = app.getPath('userData')
|
||||||
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
||||||
@@ -197,7 +197,8 @@ function sanitizeMeal(raw: unknown, now = Date.now()): Meal | null {
|
|||||||
const meal: Meal = {
|
const meal: Meal = {
|
||||||
...base,
|
...base,
|
||||||
id,
|
id,
|
||||||
nextFireAt: finiteMs(raw.nextFireAt) ?? nextMealOccurrence(base.time, base.days, now)
|
nextFireAt:
|
||||||
|
finiteMs(raw.nextFireAt) ?? nextMealOccurrence(base.time, base.days, now)
|
||||||
}
|
}
|
||||||
const lastDoneAt = finiteMs(raw.lastDoneAt)
|
const lastDoneAt = finiteMs(raw.lastDoneAt)
|
||||||
if (lastDoneAt !== undefined) meal.lastDoneAt = lastDoneAt
|
if (lastDoneAt !== undefined) meal.lastDoneAt = lastDoneAt
|
||||||
|
|||||||
@@ -56,12 +56,8 @@ describe('validateMealInput', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('реджектит кривое время', () => {
|
it('реджектит кривое время', () => {
|
||||||
expect(
|
expect(validateMealInput({ name: 'X', time: '99:99', days: [] })).toBeNull()
|
||||||
validateMealInput({ name: 'X', time: '99:99', days: [] })
|
expect(validateMealInput({ name: 'X', time: 'noon', days: [] })).toBeNull()
|
||||||
).toBeNull()
|
|
||||||
expect(
|
|
||||||
validateMealInput({ name: 'X', time: 'noon', days: [] })
|
|
||||||
).toBeNull()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('реджектит дни вне диапазона и дедупит', () => {
|
it('реджектит дни вне диапазона и дедупит', () => {
|
||||||
@@ -124,8 +120,12 @@ describe('validateExerciseInput', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('rejects missing required fields', () => {
|
it('rejects missing required fields', () => {
|
||||||
expect(validateExerciseInput({ ...validExercise, name: undefined })).toBeNull()
|
expect(
|
||||||
expect(validateExerciseInput({ ...validExercise, reps: undefined })).toBeNull()
|
validateExerciseInput({ ...validExercise, name: undefined })
|
||||||
|
).toBeNull()
|
||||||
|
expect(
|
||||||
|
validateExerciseInput({ ...validExercise, reps: undefined })
|
||||||
|
).toBeNull()
|
||||||
expect(
|
expect(
|
||||||
validateExerciseInput({ ...validExercise, intervalMinutes: undefined })
|
validateExerciseInput({ ...validExercise, intervalMinutes: undefined })
|
||||||
).toBeNull()
|
).toBeNull()
|
||||||
@@ -221,7 +221,9 @@ describe('validateExercisePatch', () => {
|
|||||||
it('accepts partial patches', () => {
|
it('accepts partial patches', () => {
|
||||||
expect(validateExercisePatch({ reps: 12 })).toEqual({ reps: 12 })
|
expect(validateExercisePatch({ reps: 12 })).toEqual({ reps: 12 })
|
||||||
expect(validateExercisePatch({ name: 'New' })).toEqual({ name: 'New' })
|
expect(validateExercisePatch({ name: 'New' })).toEqual({ name: 'New' })
|
||||||
expect(validateExercisePatch({ enabled: false })).toEqual({ enabled: false })
|
expect(validateExercisePatch({ enabled: false })).toEqual({
|
||||||
|
enabled: false
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('rejects patch with a single invalid field', () => {
|
it('rejects patch with a single invalid field', () => {
|
||||||
@@ -273,7 +275,14 @@ describe('validateChallengeInput', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('accepts all valid stats', () => {
|
it('accepts all valid stats', () => {
|
||||||
const stats = ['deaths', 'kills', 'assists', 'last_hits', 'denies', 'duration_min']
|
const stats = [
|
||||||
|
'deaths',
|
||||||
|
'kills',
|
||||||
|
'assists',
|
||||||
|
'last_hits',
|
||||||
|
'denies',
|
||||||
|
'duration_min'
|
||||||
|
]
|
||||||
for (const stat of stats) {
|
for (const stat of stats) {
|
||||||
expect(validateChallengeInput({ ...valid, stat })).not.toBeNull()
|
expect(validateChallengeInput({ ...valid, stat })).not.toBeNull()
|
||||||
}
|
}
|
||||||
@@ -288,11 +297,15 @@ describe('validateChallengeInput', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('accepts zero multiplier (legitimate "disable" semantics)', () => {
|
it('accepts zero multiplier (legitimate "disable" semantics)', () => {
|
||||||
expect(validateChallengeInput({ ...valid, multiplier: 0 })?.multiplier).toBe(0)
|
expect(
|
||||||
|
validateChallengeInput({ ...valid, multiplier: 0 })?.multiplier
|
||||||
|
).toBe(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('accepts fractional multiplier (e.g. 0.5×)', () => {
|
it('accepts fractional multiplier (e.g. 0.5×)', () => {
|
||||||
expect(validateChallengeInput({ ...valid, multiplier: 0.5 })?.multiplier).toBe(0.5)
|
expect(
|
||||||
|
validateChallengeInput({ ...valid, multiplier: 0.5 })?.multiplier
|
||||||
|
).toBe(0.5)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -399,7 +412,9 @@ describe('validateSettingsPatch', () => {
|
|||||||
|
|
||||||
it('rejects non-strings', () => {
|
it('rejects non-strings', () => {
|
||||||
expect(validateSettingsPatch({ lastSeenVersion: 42 })).toBeNull()
|
expect(validateSettingsPatch({ lastSeenVersion: 42 })).toBeNull()
|
||||||
expect(validateSettingsPatch({ lastSeenVersion: ['1', '0', '0'] })).toBeNull()
|
expect(
|
||||||
|
validateSettingsPatch({ lastSeenVersion: ['1', '0', '0'] })
|
||||||
|
).toBeNull()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -426,6 +441,12 @@ describe('validateSettingsPatch', () => {
|
|||||||
expect(
|
expect(
|
||||||
validateSettingsPatch({ quietHours: { ...baseQh, from: '2500' } })
|
validateSettingsPatch({ quietHours: { ...baseQh, from: '2500' } })
|
||||||
).toBeNull()
|
).toBeNull()
|
||||||
|
expect(
|
||||||
|
validateSettingsPatch({ quietHours: { ...baseQh, from: '25:00' } })
|
||||||
|
).toBeNull()
|
||||||
|
expect(
|
||||||
|
validateSettingsPatch({ quietHours: { ...baseQh, to: '09:99' } })
|
||||||
|
).toBeNull()
|
||||||
expect(
|
expect(
|
||||||
validateSettingsPatch({ quietHours: { ...baseQh, to: 'bedtime' } })
|
validateSettingsPatch({ quietHours: { ...baseQh, to: 'bedtime' } })
|
||||||
).toBeNull()
|
).toBeNull()
|
||||||
@@ -479,7 +500,9 @@ describe('validateSettingsPatch', () => {
|
|||||||
describe('validateId', () => {
|
describe('validateId', () => {
|
||||||
it('accepts reasonable id strings', () => {
|
it('accepts reasonable id strings', () => {
|
||||||
expect(validateId('abc')).toBe('abc')
|
expect(validateId('abc')).toBe('abc')
|
||||||
expect(validateId('uuid-v4-style-thing-123')).toBe('uuid-v4-style-thing-123')
|
expect(validateId('uuid-v4-style-thing-123')).toBe(
|
||||||
|
'uuid-v4-style-thing-123'
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('rejects non-strings', () => {
|
it('rejects non-strings', () => {
|
||||||
|
|||||||
@@ -43,7 +43,6 @@ const VALID_CATEGORIES: ReminderCategory[] = [
|
|||||||
'eyes',
|
'eyes',
|
||||||
'posture'
|
'posture'
|
||||||
]
|
]
|
||||||
const HHMM_RE = /^\d{1,2}:\d{2}$/
|
|
||||||
|
|
||||||
function isObj(v: unknown): v is Record<string, unknown> {
|
function isObj(v: unknown): v is Record<string, unknown> {
|
||||||
return typeof v === 'object' && v !== null && !Array.isArray(v)
|
return typeof v === 'object' && v !== null && !Array.isArray(v)
|
||||||
@@ -130,7 +129,11 @@ export function validateExerciseInput(
|
|||||||
// dailyGoal: undefined = не задан (нет soft-cap'a), null от UI приводим к
|
// dailyGoal: undefined = не задан (нет soft-cap'a), null от UI приводим к
|
||||||
// undefined; иначе — должен пройти int-range, иначе reject (нельзя
|
// undefined; иначе — должен пройти int-range, иначе reject (нельзя
|
||||||
// отправить из renderer'а NaN/негатив и тихо обнулить).
|
// отправить из renderer'а NaN/негатив и тихо обнулить).
|
||||||
if (raw.dailyGoal !== undefined && raw.dailyGoal !== null && dailyGoal === undefined) {
|
if (
|
||||||
|
raw.dailyGoal !== undefined &&
|
||||||
|
raw.dailyGoal !== null &&
|
||||||
|
dailyGoal === undefined
|
||||||
|
) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
@@ -438,8 +441,8 @@ export function validateSettingsPatch(raw: unknown): Partial<Settings> | null {
|
|||||||
enabled === undefined ||
|
enabled === undefined ||
|
||||||
from === undefined ||
|
from === undefined ||
|
||||||
to === undefined ||
|
to === undefined ||
|
||||||
!HHMM_RE.test(from) ||
|
validHHMM(from) === undefined ||
|
||||||
!HHMM_RE.test(to)
|
validHHMM(to) === undefined
|
||||||
) {
|
) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,14 @@ import { IPC } from '@shared/ipc'
|
|||||||
import type {
|
import type {
|
||||||
AppState,
|
AppState,
|
||||||
Challenge,
|
Challenge,
|
||||||
|
DiagnosticsInfo,
|
||||||
Exercise,
|
Exercise,
|
||||||
GameId,
|
GameId,
|
||||||
GameStatus,
|
GameStatus,
|
||||||
HistoryEntry,
|
HistoryEntry,
|
||||||
MatchSummary,
|
MatchSummary,
|
||||||
Meal,
|
Meal,
|
||||||
|
RendererErrorReport,
|
||||||
Settings,
|
Settings,
|
||||||
Tick,
|
Tick,
|
||||||
UpdaterStatus
|
UpdaterStatus
|
||||||
@@ -64,6 +66,14 @@ const api = {
|
|||||||
getAppVersion: (): Promise<string> => ipcRenderer.invoke(IPC.getAppVersion),
|
getAppVersion: (): Promise<string> => ipcRenderer.invoke(IPC.getAppVersion),
|
||||||
getMeetingActive: (): Promise<boolean> =>
|
getMeetingActive: (): Promise<boolean> =>
|
||||||
ipcRenderer.invoke(IPC.getMeetingActive),
|
ipcRenderer.invoke(IPC.getMeetingActive),
|
||||||
|
getDiagnostics: (): Promise<DiagnosticsInfo> =>
|
||||||
|
ipcRenderer.invoke(IPC.getDiagnostics),
|
||||||
|
openLogsFolder: (): Promise<{ ok: boolean; error?: string }> =>
|
||||||
|
ipcRenderer.invoke(IPC.openLogsFolder),
|
||||||
|
copyDiagnostics: (): Promise<DiagnosticsInfo> =>
|
||||||
|
ipcRenderer.invoke(IPC.copyDiagnostics),
|
||||||
|
reportRendererError: (report: RendererErrorReport): Promise<boolean> =>
|
||||||
|
ipcRenderer.invoke(IPC.reportRendererError, report),
|
||||||
|
|
||||||
pauseAll: (): Promise<void> => ipcRenderer.invoke(IPC.pauseAll),
|
pauseAll: (): Promise<void> => ipcRenderer.invoke(IPC.pauseAll),
|
||||||
resumeAll: (): Promise<void> => ipcRenderer.invoke(IPC.resumeAll),
|
resumeAll: (): Promise<void> => ipcRenderer.invoke(IPC.resumeAll),
|
||||||
@@ -164,8 +174,7 @@ const api = {
|
|||||||
on(IPC.evtMaximizeChanged, h),
|
on(IPC.evtMaximizeChanged, h),
|
||||||
onMeetingChanged: (h: Handler<boolean>): Unsub =>
|
onMeetingChanged: (h: Handler<boolean>): Unsub =>
|
||||||
on(IPC.evtMeetingChanged, h),
|
on(IPC.evtMeetingChanged, h),
|
||||||
onHistoryChanged: (h: Handler<void>): Unsub =>
|
onHistoryChanged: (h: Handler<void>): Unsub => on(IPC.evtHistoryChanged, h)
|
||||||
on(IPC.evtHistoryChanged, h)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('api', api)
|
contextBridge.exposeInMainWorld('api', api)
|
||||||
|
|||||||
@@ -9,8 +9,11 @@
|
|||||||
для Tailwind utility-классов и инлайн-стилей framer-motion. font-src
|
для Tailwind utility-классов и инлайн-стилей framer-motion. font-src
|
||||||
включает data: на случай если кто-то вставит base64 SVG-glyph.
|
включает 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'" />
|
<meta
|
||||||
<title>Exercise Reminder</title>
|
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>Не Залипай</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -23,9 +23,13 @@ export class ErrorBoundary extends Component<Props, State> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
componentDidCatch(error: Error, info: ErrorInfo): void {
|
componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||||
// No remote telemetry — log to the local console so a curious user
|
|
||||||
// (or dev tools session) can capture it.
|
|
||||||
console.error('[ErrorBoundary]', error, info.componentStack)
|
console.error('[ErrorBoundary]', error, info.componentStack)
|
||||||
|
void window.api?.reportRendererError?.({
|
||||||
|
source: 'ErrorBoundary',
|
||||||
|
message: error.message,
|
||||||
|
stack: error.stack,
|
||||||
|
componentStack: info.componentStack ?? undefined
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
reset = (): void => this.setState({ error: null })
|
reset = (): void => this.setState({ error: null })
|
||||||
|
|||||||
@@ -162,7 +162,7 @@ function SidebarContent({ onNav }: { onNav?: () => void }): JSX.Element {
|
|||||||
<>
|
<>
|
||||||
<div className="px-5 pt-7 pb-6">
|
<div className="px-5 pt-7 pb-6">
|
||||||
<div className="font-serif text-[36px] leading-none tracking-tight font-bold">
|
<div className="font-serif text-[36px] leading-none tracking-tight font-bold">
|
||||||
Laude
|
Не Залипай
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[13px] text-text/55 mt-2 font-medium">
|
<div className="text-[13px] text-text/55 mt-2 font-medium">
|
||||||
{t('sidebar.slogan')}
|
{t('sidebar.slogan')}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ export const ru: Dict = {
|
|||||||
'nav.games': 'Игры',
|
'nav.games': 'Игры',
|
||||||
'nav.challenges': 'Челленджи',
|
'nav.challenges': 'Челленджи',
|
||||||
'nav.settings': 'Настройки',
|
'nav.settings': 'Настройки',
|
||||||
'sidebar.slogan': 'Двигайся осознанно',
|
'sidebar.slogan': 'Держи ритм за компом',
|
||||||
'sidebar.status_tracking': 'Активность отслеживается',
|
'sidebar.status_tracking': 'Активность отслеживается',
|
||||||
'titlebar.menu_aria': 'Меню',
|
'titlebar.menu_aria': 'Меню',
|
||||||
'titlebar.minimize_aria': 'Свернуть',
|
'titlebar.minimize_aria': 'Свернуть',
|
||||||
@@ -26,7 +26,7 @@ export const ru: Dict = {
|
|||||||
'titlebar.restore_aria': 'Восстановить размер',
|
'titlebar.restore_aria': 'Восстановить размер',
|
||||||
'titlebar.tray_aria': 'В трей',
|
'titlebar.tray_aria': 'В трей',
|
||||||
'titlebar.close_aria': 'Закрыть',
|
'titlebar.close_aria': 'Закрыть',
|
||||||
'titlebar.app_title': 'Exercise Reminder',
|
'titlebar.app_title': 'Не Залипай',
|
||||||
|
|
||||||
// Common buttons / actions
|
// Common buttons / actions
|
||||||
'btn.add': 'Добавить',
|
'btn.add': 'Добавить',
|
||||||
@@ -85,9 +85,83 @@ export const ru: Dict = {
|
|||||||
'dashboard.meeting.title': 'Не дёргаем — ты на встрече',
|
'dashboard.meeting.title': 'Не дёргаем — ты на встрече',
|
||||||
'dashboard.meeting.hint':
|
'dashboard.meeting.hint':
|
||||||
'Запущен Zoom / Teams / Discord / Webex / Slack-huddle. Напоминания возобновятся когда закроешь.',
|
'Запущен Zoom / Teams / Discord / Webex / Slack-huddle. Напоминания возобновятся когда закроешь.',
|
||||||
|
'dashboard.plan.title': 'План дня',
|
||||||
|
'dashboard.plan.subtitle': 'Следующее действие и дневные цели',
|
||||||
|
'dashboard.plan.due_count': '{n} ждёт',
|
||||||
|
'dashboard.plan.all_caught_up': 'всё спокойно',
|
||||||
|
'dashboard.plan.next_action': 'Следующее действие',
|
||||||
|
'dashboard.plan.kind.exercise': 'упражнение',
|
||||||
|
'dashboard.plan.kind.meal': 'питание',
|
||||||
|
'dashboard.plan.due_now': 'можно сделать сейчас',
|
||||||
|
'dashboard.plan.next_in': 'через {time}',
|
||||||
|
'dashboard.plan.paused': 'напоминания на паузе',
|
||||||
|
'dashboard.plan.meal_time': 'в {time}',
|
||||||
|
'dashboard.plan.done_now': 'Сделал',
|
||||||
|
'dashboard.plan.ate_now': 'Поел',
|
||||||
|
'dashboard.plan.clear.title': 'На сегодня чисто',
|
||||||
|
'dashboard.plan.clear.hint': 'Можно отдохнуть или добавить новое действие',
|
||||||
|
'dashboard.plan.goals': 'Дневные цели',
|
||||||
|
'dashboard.plan.goals.progress': '{done}/{goal}',
|
||||||
|
'dashboard.plan.goals.remaining': 'осталось {n}',
|
||||||
|
'dashboard.plan.goals.hint': 'прогресс по упражнениям с дневной целью',
|
||||||
|
'dashboard.plan.goals.empty':
|
||||||
|
'Добавь дневную цель в упражнении, чтобы видеть прогресс',
|
||||||
|
'dashboard.plan.meals': 'Питание',
|
||||||
|
'dashboard.plan.meals.progress': '{done}/{total}',
|
||||||
|
'dashboard.plan.recovery': 'Режим',
|
||||||
|
'dashboard.plan.recovery.first.title': 'Первый шаг',
|
||||||
|
'dashboard.plan.recovery.first.hint': 'Начни с одного лёгкого действия',
|
||||||
|
'dashboard.plan.recovery.return.title': 'Мягкий возврат',
|
||||||
|
'dashboard.plan.recovery.return.hint':
|
||||||
|
'{n} дн. без действий — начни с минимума',
|
||||||
|
'dashboard.plan.recovery.steady.title': 'Ритм держится',
|
||||||
|
'dashboard.plan.recovery.steady.today': 'сегодня уже есть действие',
|
||||||
|
'dashboard.plan.recovery.steady.yesterday': 'вчера был активный день',
|
||||||
|
'dashboard.plan.recovery.steady.none': 'держим спокойный темп',
|
||||||
|
'dashboard.plan.up_next': 'Дальше',
|
||||||
|
'dashboard.plan.item.remaining': 'осталось {n}',
|
||||||
|
'dashboard.plan.item.reps': '{n} раз',
|
||||||
'dashboard.empty.title': 'Программа пуста',
|
'dashboard.empty.title': 'Программа пуста',
|
||||||
'dashboard.empty.hint': 'Добавь первое упражнение, чтобы начать',
|
'dashboard.empty.hint': 'Добавь первое упражнение, чтобы начать',
|
||||||
|
|
||||||
|
// Momentum / today redesign
|
||||||
|
'momentum.level.title': 'Уровень',
|
||||||
|
'momentum.level.number': 'уровень {n}',
|
||||||
|
'momentum.level.next': 'до «{name}» осталось {n} XP',
|
||||||
|
'momentum.level.max': 'максимальный уровень',
|
||||||
|
'momentum.level.warmup': 'Разогрелся',
|
||||||
|
'momentum.level.rhythm': 'Вошёл в ритм',
|
||||||
|
'momentum.level.steady': 'Держу форму',
|
||||||
|
'momentum.level.back': 'Железная спина',
|
||||||
|
'momentum.level.machine': 'Машина привычек',
|
||||||
|
'momentum.level.legend': 'Легенда перерывов',
|
||||||
|
'momentum.week.kicker': 'Челленджи недели',
|
||||||
|
'momentum.week.title': 'Ритм за неделю',
|
||||||
|
'momentum.week.summary': '{days} дн · {reps} повт',
|
||||||
|
'momentum.quest.complete': 'закрыто',
|
||||||
|
'momentum.quest.week_rhythm.title': '5 дней без нуля',
|
||||||
|
'momentum.quest.week_rhythm.desc': 'отметь активность в 5 разных дней',
|
||||||
|
'momentum.quest.week_reps.title': '1000 повторов',
|
||||||
|
'momentum.quest.week_reps.desc': 'набери тысячу повторов за неделю',
|
||||||
|
'momentum.quest.match_debt.title': 'Закрыть катки',
|
||||||
|
'momentum.quest.match_debt.desc': 'закрой 3 игровых долга за неделю',
|
||||||
|
'momentum.quest.today_anchor.title': 'Сегодня не ноль',
|
||||||
|
'momentum.quest.today_anchor.desc': 'сделай хотя бы одно действие сегодня',
|
||||||
|
'momentum.game.kicker': 'После катки',
|
||||||
|
'momentum.game.title': 'Игровой долг',
|
||||||
|
'momentum.game.status': 'Dota GSI',
|
||||||
|
'momentum.game.live': 'live',
|
||||||
|
'momentum.game.setup': 'настройка',
|
||||||
|
'momentum.game.off': 'выкл',
|
||||||
|
'momentum.game.today': 'сегодня',
|
||||||
|
'momentum.game.week': 'неделя',
|
||||||
|
'momentum.game.reps': '{n} повт',
|
||||||
|
'momentum.game.entries': '{n} закрыто',
|
||||||
|
'momentum.game.last': 'последняя катка: {date}',
|
||||||
|
'momentum.game.no_matches': 'закрытых игровых долгов пока нет',
|
||||||
|
'momentum.game.no_rules':
|
||||||
|
'Добавь челлендж за матч, и здесь появится долг после каток.',
|
||||||
|
|
||||||
// Exercises
|
// Exercises
|
||||||
'exercises.kicker': 'Программа',
|
'exercises.kicker': 'Программа',
|
||||||
'exercises.title': 'Упражнения',
|
'exercises.title': 'Упражнения',
|
||||||
@@ -188,6 +262,7 @@ export const ru: Dict = {
|
|||||||
'settings.section.language': 'Язык',
|
'settings.section.language': 'Язык',
|
||||||
'settings.section.updates': 'Обновления',
|
'settings.section.updates': 'Обновления',
|
||||||
'settings.section.data': 'Данные',
|
'settings.section.data': 'Данные',
|
||||||
|
'settings.section.diagnostics': 'Диагностика',
|
||||||
'settings.data.export.label': 'Экспортировать всё',
|
'settings.data.export.label': 'Экспортировать всё',
|
||||||
'settings.data.export.hint':
|
'settings.data.export.hint':
|
||||||
'Сохрани резервную копию упражнений, истории, челленджей и настроек в JSON-файл.',
|
'Сохрани резервную копию упражнений, истории, челленджей и настроек в JSON-файл.',
|
||||||
@@ -202,6 +277,20 @@ export const ru: Dict = {
|
|||||||
'Все текущие упражнения, история и настройки будут заменены содержимым файла. Продолжить?',
|
'Все текущие упражнения, история и настройки будут заменены содержимым файла. Продолжить?',
|
||||||
'settings.data.import.ok': 'Восстановлено',
|
'settings.data.import.ok': 'Восстановлено',
|
||||||
'settings.data.import.err': 'Файл не подошёл — это не наша резервная копия?',
|
'settings.data.import.err': 'Файл не подошёл — это не наша резервная копия?',
|
||||||
|
'settings.diagnostics.app.label': 'Приложение',
|
||||||
|
'settings.diagnostics.data.label': 'Данные',
|
||||||
|
'settings.diagnostics.data.legend': 'упр/еда/чел/ист',
|
||||||
|
'settings.diagnostics.gsi.label': 'Dota GSI',
|
||||||
|
'settings.diagnostics.hint':
|
||||||
|
'Технический снимок без токенов: версии, пути, статусы и счетчики.',
|
||||||
|
'settings.diagnostics.loading': 'Загружаем…',
|
||||||
|
'settings.diagnostics.err': 'Не удалось собрать диагностику',
|
||||||
|
'settings.diagnostics.refresh': 'Обновить диагностику',
|
||||||
|
'settings.diagnostics.copy.btn': 'Копировать',
|
||||||
|
'settings.diagnostics.copy.ok': 'Диагностика скопирована',
|
||||||
|
'settings.diagnostics.logs.btn': 'Логи',
|
||||||
|
'settings.diagnostics.logs.ok': 'Папка логов открыта',
|
||||||
|
'settings.diagnostics.logs.err': 'Не удалось открыть папку логов',
|
||||||
'settings.section.about': 'О приложении',
|
'settings.section.about': 'О приложении',
|
||||||
'settings.version.label': 'Версия',
|
'settings.version.label': 'Версия',
|
||||||
'settings.version.hint': 'Текущая установленная версия приложения.',
|
'settings.version.hint': 'Текущая установленная версия приложения.',
|
||||||
@@ -268,9 +357,11 @@ export const ru: Dict = {
|
|||||||
'updater.available.title': 'Доступна v{v}',
|
'updater.available.title': 'Доступна v{v}',
|
||||||
'updater.downloading.title': 'Загружаем обновление',
|
'updater.downloading.title': 'Загружаем обновление',
|
||||||
'updater.downloading.subtitle': '{got} / {total} МБ · {speed} МБ/с',
|
'updater.downloading.subtitle': '{got} / {total} МБ · {speed} МБ/с',
|
||||||
'updater.downloading.hint': 'Можно закрыть это окно — скачивание продолжится в фоне.',
|
'updater.downloading.hint':
|
||||||
|
'Можно закрыть это окно — скачивание продолжится в фоне.',
|
||||||
'updater.downloaded.title': 'Готово · v{v}',
|
'updater.downloaded.title': 'Готово · v{v}',
|
||||||
'updater.downloaded.subtitle': 'Нажми «Рестарт» — приложение моментально откроется в новой версии.',
|
'updater.downloaded.subtitle':
|
||||||
|
'Нажми «Рестарт» — приложение моментально откроется в новой версии.',
|
||||||
'updater.error.title': 'Ошибка проверки',
|
'updater.error.title': 'Ошибка проверки',
|
||||||
'updater.idle.title': 'Проверить обновления',
|
'updater.idle.title': 'Проверить обновления',
|
||||||
'updater.idle.subtitle': 'Авто-проверка раз в час',
|
'updater.idle.subtitle': 'Авто-проверка раз в час',
|
||||||
@@ -380,7 +471,7 @@ export const en: Dict = {
|
|||||||
'nav.games': 'Games',
|
'nav.games': 'Games',
|
||||||
'nav.challenges': 'Challenges',
|
'nav.challenges': 'Challenges',
|
||||||
'nav.settings': 'Settings',
|
'nav.settings': 'Settings',
|
||||||
'sidebar.slogan': 'Move with intention',
|
'sidebar.slogan': 'Keep your PC rhythm',
|
||||||
'sidebar.status_tracking': 'Activity tracking is on',
|
'sidebar.status_tracking': 'Activity tracking is on',
|
||||||
'titlebar.menu_aria': 'Menu',
|
'titlebar.menu_aria': 'Menu',
|
||||||
'titlebar.minimize_aria': 'Minimize',
|
'titlebar.minimize_aria': 'Minimize',
|
||||||
@@ -388,7 +479,7 @@ export const en: Dict = {
|
|||||||
'titlebar.restore_aria': 'Restore size',
|
'titlebar.restore_aria': 'Restore size',
|
||||||
'titlebar.tray_aria': 'To tray',
|
'titlebar.tray_aria': 'To tray',
|
||||||
'titlebar.close_aria': 'Close',
|
'titlebar.close_aria': 'Close',
|
||||||
'titlebar.app_title': 'Exercise Reminder',
|
'titlebar.app_title': 'Ne Zalipay',
|
||||||
|
|
||||||
// Common buttons
|
// Common buttons
|
||||||
'btn.add': 'Add',
|
'btn.add': 'Add',
|
||||||
@@ -446,9 +537,83 @@ export const en: Dict = {
|
|||||||
'dashboard.meeting.hint':
|
'dashboard.meeting.hint':
|
||||||
'Zoom / Teams / Discord / Webex / Slack-huddle is running. Reminders resume when you close it.',
|
'Zoom / Teams / Discord / Webex / Slack-huddle is running. Reminders resume when you close it.',
|
||||||
'dashboard.paused.hint': 'Resume to continue countdown',
|
'dashboard.paused.hint': 'Resume to continue countdown',
|
||||||
|
'dashboard.plan.title': 'Day plan',
|
||||||
|
'dashboard.plan.subtitle': 'Next action and daily goals',
|
||||||
|
'dashboard.plan.due_count': '{n} due',
|
||||||
|
'dashboard.plan.all_caught_up': 'all clear',
|
||||||
|
'dashboard.plan.next_action': 'Next action',
|
||||||
|
'dashboard.plan.kind.exercise': 'exercise',
|
||||||
|
'dashboard.plan.kind.meal': 'meal',
|
||||||
|
'dashboard.plan.due_now': 'ready now',
|
||||||
|
'dashboard.plan.next_in': 'in {time}',
|
||||||
|
'dashboard.plan.paused': 'reminders paused',
|
||||||
|
'dashboard.plan.meal_time': 'at {time}',
|
||||||
|
'dashboard.plan.done_now': 'Done',
|
||||||
|
'dashboard.plan.ate_now': 'Ate',
|
||||||
|
'dashboard.plan.clear.title': 'Clear for today',
|
||||||
|
'dashboard.plan.clear.hint': 'Rest or add another action',
|
||||||
|
'dashboard.plan.goals': 'Daily goals',
|
||||||
|
'dashboard.plan.goals.progress': '{done}/{goal}',
|
||||||
|
'dashboard.plan.goals.remaining': '{n} left',
|
||||||
|
'dashboard.plan.goals.hint': 'progress across exercises with daily goals',
|
||||||
|
'dashboard.plan.goals.empty':
|
||||||
|
'Add a daily goal to an exercise to see progress',
|
||||||
|
'dashboard.plan.meals': 'Meals',
|
||||||
|
'dashboard.plan.meals.progress': '{done}/{total}',
|
||||||
|
'dashboard.plan.recovery': 'Mode',
|
||||||
|
'dashboard.plan.recovery.first.title': 'First step',
|
||||||
|
'dashboard.plan.recovery.first.hint': 'Start with one easy action',
|
||||||
|
'dashboard.plan.recovery.return.title': 'Gentle return',
|
||||||
|
'dashboard.plan.recovery.return.hint':
|
||||||
|
'{n} days without actions — start small',
|
||||||
|
'dashboard.plan.recovery.steady.title': 'Rhythm holding',
|
||||||
|
'dashboard.plan.recovery.steady.today': 'you already logged one today',
|
||||||
|
'dashboard.plan.recovery.steady.yesterday': 'yesterday stayed active',
|
||||||
|
'dashboard.plan.recovery.steady.none': 'keep a calm pace',
|
||||||
|
'dashboard.plan.up_next': 'Up next',
|
||||||
|
'dashboard.plan.item.remaining': '{n} left',
|
||||||
|
'dashboard.plan.item.reps': '{n} reps',
|
||||||
'dashboard.empty.title': 'Program is empty',
|
'dashboard.empty.title': 'Program is empty',
|
||||||
'dashboard.empty.hint': 'Add your first exercise to start',
|
'dashboard.empty.hint': 'Add your first exercise to start',
|
||||||
|
|
||||||
|
// Momentum / today redesign
|
||||||
|
'momentum.level.title': 'Level',
|
||||||
|
'momentum.level.number': 'level {n}',
|
||||||
|
'momentum.level.next': '{n} XP to "{name}"',
|
||||||
|
'momentum.level.max': 'max level',
|
||||||
|
'momentum.level.warmup': 'Warmed up',
|
||||||
|
'momentum.level.rhythm': 'In rhythm',
|
||||||
|
'momentum.level.steady': 'Keeping shape',
|
||||||
|
'momentum.level.back': 'Iron back',
|
||||||
|
'momentum.level.machine': 'Habit machine',
|
||||||
|
'momentum.level.legend': 'Break legend',
|
||||||
|
'momentum.week.kicker': 'Weekly challenges',
|
||||||
|
'momentum.week.title': 'Week rhythm',
|
||||||
|
'momentum.week.summary': '{days} d · {reps} reps',
|
||||||
|
'momentum.quest.complete': 'done',
|
||||||
|
'momentum.quest.week_rhythm.title': '5 non-zero days',
|
||||||
|
'momentum.quest.week_rhythm.desc': 'log activity on 5 different days',
|
||||||
|
'momentum.quest.week_reps.title': '1000 reps',
|
||||||
|
'momentum.quest.week_reps.desc': 'reach one thousand reps this week',
|
||||||
|
'momentum.quest.match_debt.title': 'Close matches',
|
||||||
|
'momentum.quest.match_debt.desc': 'close 3 game debts this week',
|
||||||
|
'momentum.quest.today_anchor.title': 'Today is not zero',
|
||||||
|
'momentum.quest.today_anchor.desc': 'complete at least one action today',
|
||||||
|
'momentum.game.kicker': 'After match',
|
||||||
|
'momentum.game.title': 'Game debt',
|
||||||
|
'momentum.game.status': 'Dota GSI',
|
||||||
|
'momentum.game.live': 'live',
|
||||||
|
'momentum.game.setup': 'setup',
|
||||||
|
'momentum.game.off': 'off',
|
||||||
|
'momentum.game.today': 'today',
|
||||||
|
'momentum.game.week': 'week',
|
||||||
|
'momentum.game.reps': '{n} reps',
|
||||||
|
'momentum.game.entries': '{n} closed',
|
||||||
|
'momentum.game.last': 'last match: {date}',
|
||||||
|
'momentum.game.no_matches': 'no closed game debts yet',
|
||||||
|
'momentum.game.no_rules':
|
||||||
|
'Add a per-match challenge and game debt will show up here.',
|
||||||
|
|
||||||
// Exercises
|
// Exercises
|
||||||
'exercises.kicker': 'Program',
|
'exercises.kicker': 'Program',
|
||||||
'exercises.title': 'Exercises',
|
'exercises.title': 'Exercises',
|
||||||
@@ -549,6 +714,7 @@ export const en: Dict = {
|
|||||||
'settings.section.language': 'Language',
|
'settings.section.language': 'Language',
|
||||||
'settings.section.updates': 'Updates',
|
'settings.section.updates': 'Updates',
|
||||||
'settings.section.data': 'Data',
|
'settings.section.data': 'Data',
|
||||||
|
'settings.section.diagnostics': 'Diagnostics',
|
||||||
'settings.data.export.label': 'Export everything',
|
'settings.data.export.label': 'Export everything',
|
||||||
'settings.data.export.hint':
|
'settings.data.export.hint':
|
||||||
'Save a backup of exercises, history, challenges and settings to a JSON file.',
|
'Save a backup of exercises, history, challenges and settings to a JSON file.',
|
||||||
@@ -563,6 +729,20 @@ export const en: Dict = {
|
|||||||
'All current exercises, history and settings will be replaced with the file contents. Continue?',
|
'All current exercises, history and settings will be replaced with the file contents. Continue?',
|
||||||
'settings.data.import.ok': 'Restored',
|
'settings.data.import.ok': 'Restored',
|
||||||
'settings.data.import.err': "Couldn't read the file — not our backup?",
|
'settings.data.import.err': "Couldn't read the file — not our backup?",
|
||||||
|
'settings.diagnostics.app.label': 'Application',
|
||||||
|
'settings.diagnostics.data.label': 'Data',
|
||||||
|
'settings.diagnostics.data.legend': 'ex/meal/ch/hist',
|
||||||
|
'settings.diagnostics.gsi.label': 'Dota GSI',
|
||||||
|
'settings.diagnostics.hint':
|
||||||
|
'Technical snapshot without tokens: versions, paths, statuses and counts.',
|
||||||
|
'settings.diagnostics.loading': 'Loading…',
|
||||||
|
'settings.diagnostics.err': 'Could not collect diagnostics',
|
||||||
|
'settings.diagnostics.refresh': 'Refresh diagnostics',
|
||||||
|
'settings.diagnostics.copy.btn': 'Copy',
|
||||||
|
'settings.diagnostics.copy.ok': 'Diagnostics copied',
|
||||||
|
'settings.diagnostics.logs.btn': 'Logs',
|
||||||
|
'settings.diagnostics.logs.ok': 'Logs folder opened',
|
||||||
|
'settings.diagnostics.logs.err': 'Could not open logs folder',
|
||||||
'settings.section.about': 'About',
|
'settings.section.about': 'About',
|
||||||
'settings.version.label': 'Version',
|
'settings.version.label': 'Version',
|
||||||
'settings.version.hint': 'Currently installed app version.',
|
'settings.version.hint': 'Currently installed app version.',
|
||||||
@@ -629,9 +809,11 @@ export const en: Dict = {
|
|||||||
'updater.available.title': 'v{v} available',
|
'updater.available.title': 'v{v} available',
|
||||||
'updater.downloading.title': 'Downloading update',
|
'updater.downloading.title': 'Downloading update',
|
||||||
'updater.downloading.subtitle': '{got} / {total} MB · {speed} MB/s',
|
'updater.downloading.subtitle': '{got} / {total} MB · {speed} MB/s',
|
||||||
'updater.downloading.hint': 'You can close this window — download continues in the background.',
|
'updater.downloading.hint':
|
||||||
|
'You can close this window — download continues in the background.',
|
||||||
'updater.downloaded.title': 'Ready · v{v}',
|
'updater.downloaded.title': 'Ready · v{v}',
|
||||||
'updater.downloaded.subtitle': 'Click Restart — the app will reopen instantly in the new version.',
|
'updater.downloaded.subtitle':
|
||||||
|
'Click Restart — the app will reopen instantly in the new version.',
|
||||||
'updater.error.title': 'Check failed',
|
'updater.error.title': 'Check failed',
|
||||||
'updater.idle.title': 'Check for updates',
|
'updater.idle.title': 'Check for updates',
|
||||||
'updater.idle.subtitle': 'Auto-check every hour',
|
'updater.idle.subtitle': 'Auto-check every hour',
|
||||||
|
|||||||
135
src/renderer/src/lib/day-plan.test.ts
Normal file
135
src/renderer/src/lib/day-plan.test.ts
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import type { Exercise, HistoryEntry, Meal } from '@shared/types'
|
||||||
|
import { computeTodayPlan } from './day-plan'
|
||||||
|
|
||||||
|
const NOW = new Date(2026, 5, 6, 12, 0, 0, 0).getTime()
|
||||||
|
const HOUR = 60 * 60 * 1000
|
||||||
|
const DAY = 24 * HOUR
|
||||||
|
|
||||||
|
function exercise(partial: Partial<Exercise> & { id: string }): Exercise {
|
||||||
|
return {
|
||||||
|
id: partial.id,
|
||||||
|
name: partial.name ?? partial.id,
|
||||||
|
reps: partial.reps ?? 10,
|
||||||
|
icon: partial.icon ?? 'Activity',
|
||||||
|
intervalMinutes: partial.intervalMinutes ?? 30,
|
||||||
|
enabled: partial.enabled ?? true,
|
||||||
|
nextFireAt: partial.nextFireAt ?? NOW + HOUR,
|
||||||
|
category: partial.category,
|
||||||
|
dailyGoal: partial.dailyGoal,
|
||||||
|
adaptive: partial.adaptive
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function meal(partial: Partial<Meal> & { id: string }): Meal {
|
||||||
|
return {
|
||||||
|
id: partial.id,
|
||||||
|
name: partial.name ?? partial.id,
|
||||||
|
time: partial.time ?? '13:00',
|
||||||
|
icon: partial.icon ?? 'UtensilsCrossed',
|
||||||
|
enabled: partial.enabled ?? true,
|
||||||
|
days: partial.days ?? [],
|
||||||
|
nextFireAt: partial.nextFireAt ?? NOW + HOUR
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function done(
|
||||||
|
exerciseId: string,
|
||||||
|
ts = NOW,
|
||||||
|
reps?: number,
|
||||||
|
actualReps?: number
|
||||||
|
): HistoryEntry {
|
||||||
|
const entry: HistoryEntry = { exerciseId, ts, action: 'done' }
|
||||||
|
if (reps !== undefined) entry.reps = reps
|
||||||
|
if (actualReps !== undefined) entry.actualReps = actualReps
|
||||||
|
return entry
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('computeTodayPlan', () => {
|
||||||
|
it('summarises daily goals and puts due exercises first', () => {
|
||||||
|
const plan = computeTodayPlan({
|
||||||
|
now: NOW,
|
||||||
|
exercises: [
|
||||||
|
exercise({ id: 'pushups', dailyGoal: 30, nextFireAt: NOW - 1 }),
|
||||||
|
exercise({ id: 'water', dailyGoal: 2, reps: 1, nextFireAt: NOW + HOUR })
|
||||||
|
],
|
||||||
|
meals: [meal({ id: 'lunch', nextFireAt: NOW + 30 * 60_000 })],
|
||||||
|
history: [done('pushups', NOW - HOUR, 10)]
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(plan.goalDone).toBe(10)
|
||||||
|
expect(plan.goalTarget).toBe(32)
|
||||||
|
expect(plan.goalRemaining).toBe(22)
|
||||||
|
expect(plan.dueCount).toBe(1)
|
||||||
|
expect(plan.nextItem?.id).toBe('pushups')
|
||||||
|
expect(plan.nextItem?.due).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('removes completed daily goals from the action list', () => {
|
||||||
|
const plan = computeTodayPlan({
|
||||||
|
now: NOW,
|
||||||
|
exercises: [
|
||||||
|
exercise({ id: 'squats', dailyGoal: 20, nextFireAt: NOW - HOUR })
|
||||||
|
],
|
||||||
|
meals: [],
|
||||||
|
history: [done('squats', NOW - HOUR, 20)]
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(plan.goalRemaining).toBe(0)
|
||||||
|
expect(plan.items).toHaveLength(0)
|
||||||
|
expect(plan.nextItem).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('tracks meal completion via meal history entries', () => {
|
||||||
|
const plan = computeTodayPlan({
|
||||||
|
now: NOW,
|
||||||
|
exercises: [],
|
||||||
|
meals: [
|
||||||
|
meal({ id: 'breakfast', nextFireAt: NOW - HOUR }),
|
||||||
|
meal({ id: 'lunch', nextFireAt: NOW + HOUR })
|
||||||
|
],
|
||||||
|
history: [done('meal:breakfast', NOW - 2 * HOUR, 1)]
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(plan.enabledMeals).toBe(2)
|
||||||
|
expect(plan.doneMeals).toBe(1)
|
||||||
|
expect(plan.remainingMeals).toBe(1)
|
||||||
|
expect(plan.items.map((item) => item.id)).toEqual(['lunch'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('enters recovery mode after two inactive days', () => {
|
||||||
|
const plan = computeTodayPlan({
|
||||||
|
now: NOW,
|
||||||
|
exercises: [exercise({ id: 'a' })],
|
||||||
|
meals: [],
|
||||||
|
history: [done('a', NOW - 3 * DAY)]
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(plan.recovery).toEqual({ kind: 'recovery', daysSinceDone: 3 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses first-run state when no done history exists', () => {
|
||||||
|
const plan = computeTodayPlan({
|
||||||
|
now: NOW,
|
||||||
|
exercises: [exercise({ id: 'a' })],
|
||||||
|
meals: [],
|
||||||
|
history: []
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(plan.recovery).toEqual({ kind: 'first-run' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignores disabled exercises and meals', () => {
|
||||||
|
const plan = computeTodayPlan({
|
||||||
|
now: NOW,
|
||||||
|
exercises: [exercise({ id: 'a', enabled: false, dailyGoal: 100 })],
|
||||||
|
meals: [meal({ id: 'm', enabled: false })],
|
||||||
|
history: []
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(plan.enabledExercises).toBe(0)
|
||||||
|
expect(plan.enabledMeals).toBe(0)
|
||||||
|
expect(plan.goalTarget).toBe(0)
|
||||||
|
expect(plan.items).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
187
src/renderer/src/lib/day-plan.ts
Normal file
187
src/renderer/src/lib/day-plan.ts
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
import type {
|
||||||
|
Exercise,
|
||||||
|
HistoryEntry,
|
||||||
|
Meal,
|
||||||
|
ReminderCategory
|
||||||
|
} from '@shared/types'
|
||||||
|
import { dayKey } from './history'
|
||||||
|
|
||||||
|
export type PlanItemKind = 'exercise' | 'meal'
|
||||||
|
|
||||||
|
export type PlanItem = {
|
||||||
|
kind: PlanItemKind
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
icon: string
|
||||||
|
nextFireAt: number
|
||||||
|
due: boolean
|
||||||
|
doneToday: boolean
|
||||||
|
category?: ReminderCategory
|
||||||
|
reps?: number
|
||||||
|
goal?: number
|
||||||
|
doneReps?: number
|
||||||
|
remainingReps?: number
|
||||||
|
time?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RecoveryState =
|
||||||
|
| { kind: 'first-run' }
|
||||||
|
| { kind: 'recovery'; daysSinceDone: number }
|
||||||
|
| { kind: 'steady'; daysSinceDone: number | null }
|
||||||
|
|
||||||
|
export type TodayPlan = {
|
||||||
|
goalDone: number
|
||||||
|
goalTarget: number
|
||||||
|
goalRemaining: number
|
||||||
|
enabledExercises: number
|
||||||
|
enabledMeals: number
|
||||||
|
doneMeals: number
|
||||||
|
remainingMeals: number
|
||||||
|
dueCount: number
|
||||||
|
items: PlanItem[]
|
||||||
|
nextItem?: PlanItem
|
||||||
|
recovery: RecoveryState
|
||||||
|
}
|
||||||
|
|
||||||
|
function localDayOrdinal(ts: number): number {
|
||||||
|
const d = new Date(ts)
|
||||||
|
return Math.floor(
|
||||||
|
Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) / 86_400_000
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function doneRepsForExercise(
|
||||||
|
entries: HistoryEntry[],
|
||||||
|
exercise: Exercise,
|
||||||
|
today: string
|
||||||
|
): number {
|
||||||
|
let sum = 0
|
||||||
|
for (const e of entries) {
|
||||||
|
if (e.action !== 'done') continue
|
||||||
|
if (e.exerciseId !== exercise.id) continue
|
||||||
|
if (dayKey(e.ts) !== today) continue
|
||||||
|
sum += e.actualReps ?? e.reps ?? exercise.reps
|
||||||
|
}
|
||||||
|
return sum
|
||||||
|
}
|
||||||
|
|
||||||
|
function mealDoneToday(
|
||||||
|
entries: HistoryEntry[],
|
||||||
|
meal: Meal,
|
||||||
|
today: string
|
||||||
|
): boolean {
|
||||||
|
const id = `meal:${meal.id}`
|
||||||
|
return entries.some(
|
||||||
|
(e) => e.action === 'done' && e.exerciseId === id && dayKey(e.ts) === today
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeRecovery(entries: HistoryEntry[], now: number): RecoveryState {
|
||||||
|
const latestDone = entries
|
||||||
|
.filter((e) => e.action === 'done' && e.ts <= now)
|
||||||
|
.reduce<number | null>((latest, e) => {
|
||||||
|
if (latest === null) return e.ts
|
||||||
|
return e.ts > latest ? e.ts : latest
|
||||||
|
}, null)
|
||||||
|
|
||||||
|
if (latestDone === null) return { kind: 'first-run' }
|
||||||
|
|
||||||
|
const daysSinceDone = Math.max(
|
||||||
|
0,
|
||||||
|
localDayOrdinal(now) - localDayOrdinal(latestDone)
|
||||||
|
)
|
||||||
|
return daysSinceDone >= 2
|
||||||
|
? { kind: 'recovery', daysSinceDone }
|
||||||
|
: { kind: 'steady', daysSinceDone }
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortPlanItems(a: PlanItem, b: PlanItem): number {
|
||||||
|
if (a.due !== b.due) return a.due ? -1 : 1
|
||||||
|
if (a.nextFireAt !== b.nextFireAt) return a.nextFireAt - b.nextFireAt
|
||||||
|
if (a.kind !== b.kind) return a.kind === 'exercise' ? -1 : 1
|
||||||
|
return a.name.localeCompare(b.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function computeTodayPlan({
|
||||||
|
exercises,
|
||||||
|
meals,
|
||||||
|
history,
|
||||||
|
now = Date.now()
|
||||||
|
}: {
|
||||||
|
exercises: Exercise[]
|
||||||
|
meals: Meal[]
|
||||||
|
history: HistoryEntry[]
|
||||||
|
now?: number
|
||||||
|
}): TodayPlan {
|
||||||
|
const today = dayKey(now)
|
||||||
|
const enabledExercises = exercises.filter((e) => e.enabled)
|
||||||
|
const enabledMeals = meals.filter((m) => m.enabled)
|
||||||
|
|
||||||
|
let goalDone = 0
|
||||||
|
let goalTarget = 0
|
||||||
|
|
||||||
|
const exerciseItems = enabledExercises
|
||||||
|
.map<PlanItem>((exercise) => {
|
||||||
|
const doneReps = doneRepsForExercise(history, exercise, today)
|
||||||
|
const goal =
|
||||||
|
exercise.dailyGoal !== undefined && exercise.dailyGoal > 0
|
||||||
|
? exercise.dailyGoal
|
||||||
|
: undefined
|
||||||
|
const remainingReps =
|
||||||
|
goal !== undefined ? Math.max(0, goal - doneReps) : undefined
|
||||||
|
const complete = goal !== undefined && remainingReps === 0
|
||||||
|
|
||||||
|
if (goal !== undefined) {
|
||||||
|
goalTarget += goal
|
||||||
|
goalDone += Math.min(doneReps, goal)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
kind: 'exercise',
|
||||||
|
id: exercise.id,
|
||||||
|
name: exercise.name,
|
||||||
|
icon: exercise.icon,
|
||||||
|
category: exercise.category ?? 'exercise',
|
||||||
|
reps: exercise.reps,
|
||||||
|
goal,
|
||||||
|
doneReps,
|
||||||
|
remainingReps,
|
||||||
|
doneToday: doneReps > 0,
|
||||||
|
due: !complete && exercise.nextFireAt <= now,
|
||||||
|
nextFireAt: exercise.nextFireAt
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((item) => item.remainingReps !== 0)
|
||||||
|
|
||||||
|
const mealItems = enabledMeals
|
||||||
|
.map<PlanItem>((meal) => {
|
||||||
|
const doneToday = mealDoneToday(history, meal, today)
|
||||||
|
return {
|
||||||
|
kind: 'meal',
|
||||||
|
id: meal.id,
|
||||||
|
name: meal.name,
|
||||||
|
icon: meal.icon,
|
||||||
|
time: meal.time,
|
||||||
|
doneToday,
|
||||||
|
due: !doneToday && meal.nextFireAt <= now,
|
||||||
|
nextFireAt: meal.nextFireAt
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((item) => !item.doneToday)
|
||||||
|
|
||||||
|
const items = [...exerciseItems, ...mealItems].sort(sortPlanItems)
|
||||||
|
|
||||||
|
return {
|
||||||
|
goalDone,
|
||||||
|
goalTarget,
|
||||||
|
goalRemaining: Math.max(0, goalTarget - goalDone),
|
||||||
|
enabledExercises: enabledExercises.length,
|
||||||
|
enabledMeals: enabledMeals.length,
|
||||||
|
doneMeals: enabledMeals.length - mealItems.length,
|
||||||
|
remainingMeals: mealItems.length,
|
||||||
|
dueCount: items.filter((item) => item.due).length,
|
||||||
|
items,
|
||||||
|
nextItem: items[0],
|
||||||
|
recovery: computeRecovery(history, now)
|
||||||
|
}
|
||||||
|
}
|
||||||
112
src/renderer/src/lib/momentum.test.ts
Normal file
112
src/renderer/src/lib/momentum.test.ts
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import type { Challenge, Exercise, HistoryEntry } from '@shared/types'
|
||||||
|
import { computeMomentumSummary } from './momentum'
|
||||||
|
|
||||||
|
const NOW = new Date(2026, 5, 10, 12, 0, 0, 0).getTime()
|
||||||
|
const DAY = 24 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
function exercise(partial: Partial<Exercise> & { id: string }): Exercise {
|
||||||
|
return {
|
||||||
|
id: partial.id,
|
||||||
|
name: partial.name ?? partial.id,
|
||||||
|
reps: partial.reps ?? 10,
|
||||||
|
icon: partial.icon ?? 'Activity',
|
||||||
|
intervalMinutes: partial.intervalMinutes ?? 30,
|
||||||
|
enabled: partial.enabled ?? true,
|
||||||
|
nextFireAt: partial.nextFireAt ?? NOW + 60_000,
|
||||||
|
category: partial.category,
|
||||||
|
dailyGoal: partial.dailyGoal,
|
||||||
|
adaptive: partial.adaptive
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function challenge(partial: Partial<Challenge> & { id: string }): Challenge {
|
||||||
|
return {
|
||||||
|
id: partial.id,
|
||||||
|
name: partial.name ?? partial.id,
|
||||||
|
gameId: 'dota2',
|
||||||
|
stat: partial.stat ?? 'deaths',
|
||||||
|
multiplier: partial.multiplier ?? 3,
|
||||||
|
exerciseName: partial.exerciseName ?? 'Squats',
|
||||||
|
icon: partial.icon ?? 'Dumbbell',
|
||||||
|
enabled: partial.enabled ?? true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function done(
|
||||||
|
exerciseId: string,
|
||||||
|
daysAgo: number,
|
||||||
|
reps: number,
|
||||||
|
source?: HistoryEntry['source']
|
||||||
|
): HistoryEntry {
|
||||||
|
return {
|
||||||
|
exerciseId,
|
||||||
|
ts: NOW - daysAgo * DAY,
|
||||||
|
action: 'done',
|
||||||
|
reps,
|
||||||
|
source
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('computeMomentumSummary', () => {
|
||||||
|
it('tracks weekly quests and match debt from history', () => {
|
||||||
|
const summary = computeMomentumSummary({
|
||||||
|
now: NOW,
|
||||||
|
exercises: [exercise({ id: 'pushups', reps: 15 })],
|
||||||
|
challenges: [challenge({ id: 'c1' })],
|
||||||
|
history: [
|
||||||
|
done('pushups', 0, 15),
|
||||||
|
done('pushups', 1, 20),
|
||||||
|
done('pushups', 2, 25),
|
||||||
|
done('challenge:c1', 0, 30, 'match'),
|
||||||
|
done('challenge:c1', 2, 45, 'match')
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(summary.todayReps).toBe(45)
|
||||||
|
expect(summary.weekReps).toBe(135)
|
||||||
|
expect(summary.weekActiveDays).toBe(3)
|
||||||
|
expect(summary.gameDebt.matchEntriesToday).toBe(1)
|
||||||
|
expect(summary.gameDebt.matchEntriesWeek).toBe(2)
|
||||||
|
expect(summary.gameDebt.matchRepsWeek).toBe(75)
|
||||||
|
expect(summary.weeklyQuests.map((quest) => quest.id)).toEqual([
|
||||||
|
'week_rhythm',
|
||||||
|
'week_reps',
|
||||||
|
'match_debt',
|
||||||
|
'today_anchor'
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hides match quest when there are no enabled challenge rules', () => {
|
||||||
|
const summary = computeMomentumSummary({
|
||||||
|
now: NOW,
|
||||||
|
exercises: [exercise({ id: 'pushups' })],
|
||||||
|
challenges: [challenge({ id: 'c1', enabled: false })],
|
||||||
|
history: [done('pushups', 0, 10)]
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(summary.gameDebt.activeRules).toBe(0)
|
||||||
|
expect(summary.weeklyQuests.map((quest) => quest.id)).toEqual([
|
||||||
|
'week_rhythm',
|
||||||
|
'week_reps',
|
||||||
|
'today_anchor'
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('computes a soft level from reps, active days and match activity', () => {
|
||||||
|
const summary = computeMomentumSummary({
|
||||||
|
now: NOW,
|
||||||
|
exercises: [exercise({ id: 'pushups' })],
|
||||||
|
challenges: [challenge({ id: 'c1' })],
|
||||||
|
history: [
|
||||||
|
done('pushups', 0, 100),
|
||||||
|
done('pushups', 1, 100),
|
||||||
|
done('challenge:c1', 0, 100, 'match')
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(summary.level.xp).toBe(425)
|
||||||
|
expect(summary.level.key).toBe('momentum.level.rhythm')
|
||||||
|
expect(summary.level.progressPct).toBeGreaterThan(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
216
src/renderer/src/lib/momentum.ts
Normal file
216
src/renderer/src/lib/momentum.ts
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
import type { Challenge, Exercise, HistoryEntry } from '@shared/types'
|
||||||
|
import { dayKey } from './history'
|
||||||
|
|
||||||
|
export type MomentumLevel = {
|
||||||
|
key: string
|
||||||
|
xp: number
|
||||||
|
levelIndex: number
|
||||||
|
current: number
|
||||||
|
target: number
|
||||||
|
progressPct: number
|
||||||
|
nextKey?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WeeklyQuest = {
|
||||||
|
id: 'week_rhythm' | 'week_reps' | 'match_debt' | 'today_anchor'
|
||||||
|
titleKey: string
|
||||||
|
descKey: string
|
||||||
|
current: number
|
||||||
|
target: number
|
||||||
|
progressPct: number
|
||||||
|
complete: boolean
|
||||||
|
tone: 'accent' | 'success' | 'warning' | 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GameDebtSummary = {
|
||||||
|
activeRules: number
|
||||||
|
matchRepsToday: number
|
||||||
|
matchRepsWeek: number
|
||||||
|
matchEntriesToday: number
|
||||||
|
matchEntriesWeek: number
|
||||||
|
lastMatchAt?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MomentumSummary = {
|
||||||
|
level: MomentumLevel
|
||||||
|
weeklyQuests: WeeklyQuest[]
|
||||||
|
gameDebt: GameDebtSummary
|
||||||
|
weekReps: number
|
||||||
|
weekActiveDays: number
|
||||||
|
todayReps: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const LEVELS = [
|
||||||
|
{ key: 'momentum.level.warmup', xp: 0 },
|
||||||
|
{ key: 'momentum.level.rhythm', xp: 120 },
|
||||||
|
{ key: 'momentum.level.steady', xp: 450 },
|
||||||
|
{ key: 'momentum.level.back', xp: 1000 },
|
||||||
|
{ key: 'momentum.level.machine', xp: 2500 },
|
||||||
|
{ key: 'momentum.level.legend', xp: 6000 }
|
||||||
|
] as const
|
||||||
|
|
||||||
|
function startOfDay(ts: number): Date {
|
||||||
|
const d = new Date(ts)
|
||||||
|
d.setHours(0, 0, 0, 0)
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
function startOfWeek(ts: number): Date {
|
||||||
|
const d = startOfDay(ts)
|
||||||
|
const day = d.getDay()
|
||||||
|
const delta = day === 0 ? -6 : 1 - day
|
||||||
|
d.setDate(d.getDate() + delta)
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
function entryReps(
|
||||||
|
entry: HistoryEntry,
|
||||||
|
exercisesById: Map<string, Exercise>
|
||||||
|
): number {
|
||||||
|
return (
|
||||||
|
entry.actualReps ??
|
||||||
|
entry.reps ??
|
||||||
|
exercisesById.get(entry.exerciseId)?.reps ??
|
||||||
|
0
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isMatchEntry(entry: HistoryEntry): boolean {
|
||||||
|
return entry.source === 'match' || entry.exerciseId.startsWith('challenge:')
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeLevel(xp: number): MomentumLevel {
|
||||||
|
let index = 0
|
||||||
|
for (let i = 0; i < LEVELS.length; i++) {
|
||||||
|
if (xp >= LEVELS[i].xp) index = i
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentLevel = LEVELS[index]
|
||||||
|
const nextLevel = LEVELS[index + 1]
|
||||||
|
const current = Math.max(0, xp - currentLevel.xp)
|
||||||
|
const target = nextLevel ? nextLevel.xp - currentLevel.xp : current || 1
|
||||||
|
const progressPct = nextLevel
|
||||||
|
? Math.min(100, Math.round((current / target) * 100))
|
||||||
|
: 100
|
||||||
|
|
||||||
|
return {
|
||||||
|
key: currentLevel.key,
|
||||||
|
xp,
|
||||||
|
levelIndex: index + 1,
|
||||||
|
current,
|
||||||
|
target,
|
||||||
|
progressPct,
|
||||||
|
nextKey: nextLevel?.key
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function quest(
|
||||||
|
id: WeeklyQuest['id'],
|
||||||
|
current: number,
|
||||||
|
target: number,
|
||||||
|
tone: WeeklyQuest['tone']
|
||||||
|
): WeeklyQuest {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
titleKey: `momentum.quest.${id}.title`,
|
||||||
|
descKey: `momentum.quest.${id}.desc`,
|
||||||
|
current,
|
||||||
|
target,
|
||||||
|
progressPct: Math.min(100, Math.round((current / target) * 100)),
|
||||||
|
complete: current >= target,
|
||||||
|
tone
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function computeMomentumSummary({
|
||||||
|
history,
|
||||||
|
exercises,
|
||||||
|
challenges,
|
||||||
|
now = Date.now()
|
||||||
|
}: {
|
||||||
|
history: HistoryEntry[]
|
||||||
|
exercises: Exercise[]
|
||||||
|
challenges: Challenge[]
|
||||||
|
now?: number
|
||||||
|
}): MomentumSummary {
|
||||||
|
const exercisesById = new Map(
|
||||||
|
exercises.map((exercise) => [exercise.id, exercise])
|
||||||
|
)
|
||||||
|
const today = dayKey(now)
|
||||||
|
const weekStart = startOfWeek(now).getTime()
|
||||||
|
|
||||||
|
let totalReps = 0
|
||||||
|
let todayReps = 0
|
||||||
|
let weekReps = 0
|
||||||
|
let matchRepsToday = 0
|
||||||
|
let matchRepsWeek = 0
|
||||||
|
let matchEntriesToday = 0
|
||||||
|
let matchEntriesWeek = 0
|
||||||
|
let lastMatchAt: number | undefined
|
||||||
|
const allActiveDays = new Set<string>()
|
||||||
|
const weekActiveDays = new Set<string>()
|
||||||
|
|
||||||
|
for (const entry of history) {
|
||||||
|
if (entry.action !== 'done') continue
|
||||||
|
|
||||||
|
const reps = entryReps(entry, exercisesById)
|
||||||
|
const key = dayKey(entry.ts)
|
||||||
|
const inWeek = entry.ts >= weekStart && entry.ts <= now
|
||||||
|
const match = isMatchEntry(entry)
|
||||||
|
|
||||||
|
totalReps += reps
|
||||||
|
allActiveDays.add(key)
|
||||||
|
|
||||||
|
if (key === today) todayReps += reps
|
||||||
|
if (inWeek) {
|
||||||
|
weekReps += reps
|
||||||
|
weekActiveDays.add(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
if (lastMatchAt === undefined || entry.ts > lastMatchAt) {
|
||||||
|
lastMatchAt = entry.ts
|
||||||
|
}
|
||||||
|
if (key === today) {
|
||||||
|
matchEntriesToday++
|
||||||
|
matchRepsToday += reps
|
||||||
|
}
|
||||||
|
if (inWeek) {
|
||||||
|
matchEntriesWeek++
|
||||||
|
matchRepsWeek += reps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeRules = challenges.filter((challenge) => challenge.enabled).length
|
||||||
|
const xp = totalReps + allActiveDays.size * 50 + matchEntriesWeek * 25
|
||||||
|
const weeklyQuests: WeeklyQuest[] = [
|
||||||
|
quest('week_rhythm', weekActiveDays.size, 5, 'success'),
|
||||||
|
quest('week_reps', weekReps, 1000, 'accent'),
|
||||||
|
quest('today_anchor', todayReps > 0 ? 1 : 0, 1, 'info')
|
||||||
|
]
|
||||||
|
|
||||||
|
if (activeRules > 0) {
|
||||||
|
weeklyQuests.splice(
|
||||||
|
2,
|
||||||
|
0,
|
||||||
|
quest('match_debt', matchEntriesWeek, 3, 'warning')
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
level: computeLevel(xp),
|
||||||
|
weeklyQuests,
|
||||||
|
gameDebt: {
|
||||||
|
activeRules,
|
||||||
|
matchRepsToday,
|
||||||
|
matchRepsWeek,
|
||||||
|
matchEntriesToday,
|
||||||
|
matchEntriesWeek,
|
||||||
|
lastMatchAt
|
||||||
|
},
|
||||||
|
weekReps,
|
||||||
|
weekActiveDays: weekActiveDays.size,
|
||||||
|
todayReps
|
||||||
|
}
|
||||||
|
}
|
||||||
32
src/renderer/src/lib/reporting.ts
Normal file
32
src/renderer/src/lib/reporting.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
function errorFields(err: unknown): { message: string; stack?: string } {
|
||||||
|
if (err instanceof Error) {
|
||||||
|
return {
|
||||||
|
message: err.message || err.name,
|
||||||
|
stack: err.stack
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (typeof err === 'string') return { message: err }
|
||||||
|
try {
|
||||||
|
return { message: JSON.stringify(err) }
|
||||||
|
} catch {
|
||||||
|
return { message: String(err) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function report(source: string, err: unknown): void {
|
||||||
|
const { message, stack } = errorFields(err)
|
||||||
|
if (!message) return
|
||||||
|
void window.api
|
||||||
|
?.reportRendererError?.({ source, message, stack })
|
||||||
|
.catch(() => undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function installRendererErrorReporting(): void {
|
||||||
|
window.addEventListener('error', (event) => {
|
||||||
|
report('window.error', event.error ?? event.message)
|
||||||
|
})
|
||||||
|
|
||||||
|
window.addEventListener('unhandledrejection', (event) => {
|
||||||
|
report('window.unhandledrejection', event.reason)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -5,6 +5,9 @@ import './styles/globals.css'
|
|||||||
import App from './App'
|
import App from './App'
|
||||||
import ReminderApp from './ReminderApp'
|
import ReminderApp from './ReminderApp'
|
||||||
import { ThemeProvider } from './providers/ThemeProvider'
|
import { ThemeProvider } from './providers/ThemeProvider'
|
||||||
|
import { installRendererErrorReporting } from './lib/reporting'
|
||||||
|
|
||||||
|
installRendererErrorReporting()
|
||||||
|
|
||||||
const params = new URLSearchParams(window.location.search)
|
const params = new URLSearchParams(window.location.search)
|
||||||
const which = params.get('window') ?? 'main'
|
const which = params.get('window') ?? 'main'
|
||||||
|
|||||||
@@ -7,7 +7,14 @@ import {
|
|||||||
Flame,
|
Flame,
|
||||||
Activity,
|
Activity,
|
||||||
TrendingUp,
|
TrendingUp,
|
||||||
Video
|
Video,
|
||||||
|
CalendarCheck,
|
||||||
|
Target,
|
||||||
|
RotateCcw,
|
||||||
|
Check,
|
||||||
|
Trophy,
|
||||||
|
Swords,
|
||||||
|
BadgeCheck
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { useAppStore } from '../store/appStore'
|
import { useAppStore } from '../store/appStore'
|
||||||
import { ExerciseCard } from '../components/ExerciseCard'
|
import { ExerciseCard } from '../components/ExerciseCard'
|
||||||
@@ -16,15 +23,31 @@ import { HistoryHeatmap } from '../components/HistoryHeatmap'
|
|||||||
import { AchievementsCard } from '../components/AchievementsCard'
|
import { AchievementsCard } from '../components/AchievementsCard'
|
||||||
import { Button } from '../components/ui/Button'
|
import { Button } from '../components/ui/Button'
|
||||||
import { ConfirmModal } from '../components/ui/ConfirmModal'
|
import { ConfirmModal } from '../components/ui/ConfirmModal'
|
||||||
import type { Exercise, GameStatus, HistoryEntry } from '@shared/types'
|
import type {
|
||||||
|
Exercise,
|
||||||
|
GameStatus,
|
||||||
|
HistoryEntry,
|
||||||
|
Language
|
||||||
|
} from '@shared/types'
|
||||||
import { formatCountdown } from '../lib/format'
|
import { formatCountdown } from '../lib/format'
|
||||||
import { useT } from '../i18n'
|
import { useT, type TFn } from '../i18n'
|
||||||
|
import { Icon } from '../lib/icon'
|
||||||
|
import {
|
||||||
|
computeTodayPlan,
|
||||||
|
type PlanItem,
|
||||||
|
type TodayPlan
|
||||||
|
} from '../lib/day-plan'
|
||||||
import {
|
import {
|
||||||
currentStreak,
|
currentStreak,
|
||||||
dailyReps,
|
dailyReps,
|
||||||
repsDoneTodayForExercise,
|
repsDoneTodayForExercise,
|
||||||
todayKey
|
todayKey
|
||||||
} from '../lib/history'
|
} from '../lib/history'
|
||||||
|
import {
|
||||||
|
computeMomentumSummary,
|
||||||
|
type MomentumSummary,
|
||||||
|
type WeeklyQuest
|
||||||
|
} from '../lib/momentum'
|
||||||
|
|
||||||
export default function Dashboard(): JSX.Element {
|
export default function Dashboard(): JSX.Element {
|
||||||
const state = useAppStore((s) => s.state)
|
const state = useAppStore((s) => s.state)
|
||||||
@@ -38,7 +61,10 @@ export default function Dashboard(): JSX.Element {
|
|||||||
// on every render — `state?.exercises ?? []` creates a fresh array each time
|
// on every render — `state?.exercises ?? []` creates a fresh array each time
|
||||||
// the parent re-renders even when nothing changed.
|
// the parent re-renders even when nothing changed.
|
||||||
const exercises = useMemo(() => state?.exercises ?? [], [state?.exercises])
|
const exercises = useMemo(() => state?.exercises ?? [], [state?.exercises])
|
||||||
|
const meals = useMemo(() => state?.meals ?? [], [state?.meals])
|
||||||
|
const challenges = useMemo(() => state?.challenges ?? [], [state?.challenges])
|
||||||
const settings = state?.settings
|
const settings = state?.settings
|
||||||
|
const [planActionKey, setPlanActionKey] = useState<string | null>(null)
|
||||||
|
|
||||||
// Игры: запрашиваем реальный статус (integrationActive + launchOption
|
// Игры: запрашиваем реальный статус (integrationActive + launchOption
|
||||||
// applied), а не просто `state.gamesEnabled`. Без этого badge показывал
|
// applied), а не просто `state.gamesEnabled`. Без этого badge показывал
|
||||||
@@ -51,13 +77,12 @@ export default function Dashboard(): JSX.Element {
|
|||||||
}, [])
|
}, [])
|
||||||
const gamesLive = games.some(
|
const gamesLive = games.some(
|
||||||
(g) =>
|
(g) =>
|
||||||
g.enabled &&
|
g.enabled && g.integrationActive && g.launchOptionStatus === 'applied'
|
||||||
g.integrationActive &&
|
|
||||||
g.launchOptionStatus === 'applied'
|
|
||||||
)
|
)
|
||||||
// «Включена, но не готова» — отдельное состояние, в badge другой tone.
|
// «Включена, но не готова» — отдельное состояние, в badge другой tone.
|
||||||
const gamesEnabledButNotLive = games.some(
|
const gamesEnabledButNotLive = games.some(
|
||||||
(g) => g.enabled && (!g.integrationActive || g.launchOptionStatus !== 'applied')
|
(g) =>
|
||||||
|
g.enabled && (!g.integrationActive || g.launchOptionStatus !== 'applied')
|
||||||
)
|
)
|
||||||
|
|
||||||
// Local history mirror. Перетягиваем (а) на mount, (б) при изменении
|
// Local history mirror. Перетягиваем (а) на mount, (б) при изменении
|
||||||
@@ -109,6 +134,15 @@ export default function Dashboard(): JSX.Element {
|
|||||||
}
|
}
|
||||||
}, [exercises, ticks])
|
}, [exercises, ticks])
|
||||||
|
|
||||||
|
const plan = useMemo(() => {
|
||||||
|
void ticks
|
||||||
|
return computeTodayPlan({ exercises, meals, history })
|
||||||
|
}, [exercises, meals, history, ticks])
|
||||||
|
const momentum = useMemo(
|
||||||
|
() => computeMomentumSummary({ history, exercises, challenges }),
|
||||||
|
[history, exercises, challenges]
|
||||||
|
)
|
||||||
|
|
||||||
const paused = !settings?.globalEnabled
|
const paused = !settings?.globalEnabled
|
||||||
|
|
||||||
function openCreate(): void {
|
function openCreate(): void {
|
||||||
@@ -137,6 +171,17 @@ export default function Dashboard(): JSX.Element {
|
|||||||
if (!settings) return
|
if (!settings) return
|
||||||
await window.api.updateSettings({ globalEnabled: !settings.globalEnabled })
|
await window.api.updateSettings({ globalEnabled: !settings.globalEnabled })
|
||||||
}
|
}
|
||||||
|
async function handlePlanItemDone(item: PlanItem): Promise<void> {
|
||||||
|
const key = `${item.kind}:${item.id}`
|
||||||
|
if (planActionKey !== null) return
|
||||||
|
setPlanActionKey(key)
|
||||||
|
try {
|
||||||
|
if (item.kind === 'meal') await window.api.markMealDone(item.id)
|
||||||
|
else await window.api.markDone(item.id)
|
||||||
|
} finally {
|
||||||
|
setPlanActionKey(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const today = new Date().toLocaleDateString(
|
const today = new Date().toLocaleDateString(
|
||||||
lang === 'en' ? 'en-US' : 'ru-RU',
|
lang === 'en' ? 'en-US' : 'ru-RU',
|
||||||
@@ -211,7 +256,11 @@ export default function Dashboard(): JSX.Element {
|
|||||||
/>
|
/>
|
||||||
<HeroStat
|
<HeroStat
|
||||||
tone={
|
tone={
|
||||||
gamesLive ? 'success' : gamesEnabledButNotLive ? 'warning' : 'muted'
|
gamesLive
|
||||||
|
? 'success'
|
||||||
|
: gamesEnabledButNotLive
|
||||||
|
? 'warning'
|
||||||
|
: 'muted'
|
||||||
}
|
}
|
||||||
label={t('dashboard.stat.tracking')}
|
label={t('dashboard.stat.tracking')}
|
||||||
value={
|
value={
|
||||||
@@ -239,13 +288,6 @@ export default function Dashboard(): JSX.Element {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{history.length > 0 && (
|
|
||||||
<div className="mb-8 space-y-3">
|
|
||||||
<HistoryHeatmap history={history} exercises={exercises} />
|
|
||||||
<AchievementsCard history={history} exercises={exercises} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{paused && (
|
{paused && (
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0, y: -4 }}
|
initial={{ opacity: 0, y: -4 }}
|
||||||
@@ -289,6 +331,30 @@ export default function Dashboard(): JSX.Element {
|
|||||||
</motion.div>
|
</motion.div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<TodayPlanPanel
|
||||||
|
plan={plan}
|
||||||
|
paused={paused}
|
||||||
|
lang={lang}
|
||||||
|
t={t}
|
||||||
|
actionBusy={planActionKey !== null}
|
||||||
|
onItemDone={(item) => void handlePlanItemDone(item)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<MomentumPanel
|
||||||
|
momentum={momentum}
|
||||||
|
gamesLive={gamesLive}
|
||||||
|
gamesEnabledButNotLive={gamesEnabledButNotLive}
|
||||||
|
lang={lang}
|
||||||
|
t={t}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{history.length > 0 && (
|
||||||
|
<div className="mb-8 space-y-3">
|
||||||
|
<HistoryHeatmap history={history} exercises={exercises} />
|
||||||
|
<AchievementsCard history={history} exercises={exercises} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 gap-4">
|
||||||
<AnimatePresence>
|
<AnimatePresence>
|
||||||
{exercises.map((ex) => (
|
{exercises.map((ex) => (
|
||||||
@@ -348,6 +414,588 @@ export default function Dashboard(): JSX.Element {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function MomentumPanel({
|
||||||
|
momentum,
|
||||||
|
gamesLive,
|
||||||
|
gamesEnabledButNotLive,
|
||||||
|
lang,
|
||||||
|
t
|
||||||
|
}: {
|
||||||
|
momentum: MomentumSummary
|
||||||
|
gamesLive: boolean
|
||||||
|
gamesEnabledButNotLive: boolean
|
||||||
|
lang: Language
|
||||||
|
t: TFn
|
||||||
|
}): JSX.Element {
|
||||||
|
const gameStatus = gamesLive
|
||||||
|
? t('momentum.game.live')
|
||||||
|
: gamesEnabledButNotLive
|
||||||
|
? t('momentum.game.setup')
|
||||||
|
: t('momentum.game.off')
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="mb-8 grid grid-cols-1 lg:grid-cols-[0.9fr_1.1fr_0.95fr] gap-4">
|
||||||
|
<div className="bg-surface rounded-3xl p-5 shadow-card dark:ring-0.5 dark:ring-hairline/30 min-w-0">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-2xl bg-warning text-white grid place-items-center shrink-0">
|
||||||
|
<Trophy size={19} strokeWidth={2.5} />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-[13px] text-text/55 font-semibold">
|
||||||
|
{t('momentum.level.title')}
|
||||||
|
</div>
|
||||||
|
<div className="font-display text-[22px] font-bold leading-tight truncate">
|
||||||
|
{t(momentum.level.key)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-5 flex items-end justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="text-[12px] text-text/55 font-semibold">
|
||||||
|
{t('momentum.level.number', {
|
||||||
|
n: momentum.level.levelIndex
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<div className="font-mono-num text-[28px] leading-none font-bold">
|
||||||
|
{momentum.level.xp}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-[13px] text-text/60 text-right">
|
||||||
|
{momentum.level.nextKey
|
||||||
|
? t('momentum.level.next', {
|
||||||
|
name: t(momentum.level.nextKey),
|
||||||
|
n: momentum.level.target - momentum.level.current
|
||||||
|
})
|
||||||
|
: t('momentum.level.max')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ProgressBar pct={momentum.level.progressPct} tone="warning" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-surface rounded-3xl p-5 shadow-card dark:ring-0.5 dark:ring-hairline/30 min-w-0">
|
||||||
|
<div className="flex items-start justify-between gap-3 mb-3">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-[13px] text-text/55 font-semibold">
|
||||||
|
{t('momentum.week.kicker')}
|
||||||
|
</div>
|
||||||
|
<h2 className="font-display text-[22px] font-bold leading-tight">
|
||||||
|
{t('momentum.week.title')}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<div className="text-[12px] text-text/55 font-mono-num font-semibold shrink-0">
|
||||||
|
{t('momentum.week.summary', {
|
||||||
|
days: momentum.weekActiveDays,
|
||||||
|
reps: momentum.weekReps
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="divide-y divide-hairline/35">
|
||||||
|
{momentum.weeklyQuests.map((quest) => (
|
||||||
|
<WeeklyQuestRow key={quest.id} quest={quest} t={t} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-surface rounded-3xl p-5 shadow-card dark:ring-0.5 dark:ring-hairline/30 min-w-0">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-2xl bg-accent-2 text-white grid place-items-center shrink-0">
|
||||||
|
<Swords size={19} strokeWidth={2.5} />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-[13px] text-text/55 font-semibold">
|
||||||
|
{t('momentum.game.kicker')}
|
||||||
|
</div>
|
||||||
|
<h2 className="font-display text-[22px] font-bold leading-tight">
|
||||||
|
{t('momentum.game.title')}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 rounded-2xl bg-surface-2 p-4">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div className="text-[13px] text-text/60 font-semibold">
|
||||||
|
{t('momentum.game.status')}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={[
|
||||||
|
'text-[12px] px-2.5 py-1 rounded-full font-semibold',
|
||||||
|
gamesLive
|
||||||
|
? 'bg-success/12 text-success'
|
||||||
|
: gamesEnabledButNotLive
|
||||||
|
? 'bg-warning/12 text-warning'
|
||||||
|
: 'bg-text/10 text-text/55'
|
||||||
|
].join(' ')}
|
||||||
|
>
|
||||||
|
{gameStatus}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{momentum.gameDebt.activeRules > 0 ? (
|
||||||
|
<>
|
||||||
|
<div className="mt-4 grid grid-cols-2 gap-3">
|
||||||
|
<GameDebtStat
|
||||||
|
label={t('momentum.game.today')}
|
||||||
|
value={t('momentum.game.reps', {
|
||||||
|
n: momentum.gameDebt.matchRepsToday
|
||||||
|
})}
|
||||||
|
hint={t('momentum.game.entries', {
|
||||||
|
n: momentum.gameDebt.matchEntriesToday
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
<GameDebtStat
|
||||||
|
label={t('momentum.game.week')}
|
||||||
|
value={t('momentum.game.reps', {
|
||||||
|
n: momentum.gameDebt.matchRepsWeek
|
||||||
|
})}
|
||||||
|
hint={t('momentum.game.entries', {
|
||||||
|
n: momentum.gameDebt.matchEntriesWeek
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 text-[13px] text-text/62 leading-relaxed">
|
||||||
|
{momentum.gameDebt.lastMatchAt
|
||||||
|
? t('momentum.game.last', {
|
||||||
|
date: new Date(
|
||||||
|
momentum.gameDebt.lastMatchAt
|
||||||
|
).toLocaleDateString(lang === 'en' ? 'en-US' : 'ru-RU', {
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'short'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
: t('momentum.game.no_matches')}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="mt-4 text-[14px] text-text/65 leading-relaxed">
|
||||||
|
{t('momentum.game.no_rules')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function WeeklyQuestRow({
|
||||||
|
quest,
|
||||||
|
t
|
||||||
|
}: {
|
||||||
|
quest: WeeklyQuest
|
||||||
|
t: TFn
|
||||||
|
}): JSX.Element {
|
||||||
|
const IconCmp =
|
||||||
|
quest.id === 'match_debt'
|
||||||
|
? Swords
|
||||||
|
: quest.id === 'today_anchor'
|
||||||
|
? BadgeCheck
|
||||||
|
: quest.id === 'week_rhythm'
|
||||||
|
? Flame
|
||||||
|
: TrendingUp
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="py-3 flex items-center gap-3 min-w-0">
|
||||||
|
<div
|
||||||
|
className={[
|
||||||
|
'w-9 h-9 rounded-xl grid place-items-center text-white shrink-0',
|
||||||
|
quest.complete
|
||||||
|
? 'bg-success'
|
||||||
|
: quest.tone === 'warning'
|
||||||
|
? 'bg-warning'
|
||||||
|
: quest.tone === 'info'
|
||||||
|
? 'bg-info'
|
||||||
|
: 'bg-accent'
|
||||||
|
].join(' ')}
|
||||||
|
>
|
||||||
|
<IconCmp size={16} strokeWidth={2.5} />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div className="font-semibold text-[15px] truncate">
|
||||||
|
{t(quest.titleKey)}
|
||||||
|
</div>
|
||||||
|
<div className="font-mono-num text-[12px] text-text/55 shrink-0">
|
||||||
|
{quest.current}/{quest.target}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-[12px] text-text/55 mt-1 truncate">
|
||||||
|
{quest.complete ? t('momentum.quest.complete') : t(quest.descKey)}
|
||||||
|
</div>
|
||||||
|
<ProgressBar pct={quest.progressPct} tone={quest.tone} compact />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function GameDebtStat({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
hint
|
||||||
|
}: {
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
hint: string
|
||||||
|
}): JSX.Element {
|
||||||
|
return (
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-[12px] text-text/55 font-semibold">{label}</div>
|
||||||
|
<div className="font-mono-num text-[20px] font-bold leading-tight mt-1 truncate">
|
||||||
|
{value}
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-text/50 mt-1 truncate">{hint}</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TodayPlanPanel({
|
||||||
|
plan,
|
||||||
|
paused,
|
||||||
|
lang,
|
||||||
|
t,
|
||||||
|
actionBusy,
|
||||||
|
onItemDone
|
||||||
|
}: {
|
||||||
|
plan: TodayPlan
|
||||||
|
paused: boolean
|
||||||
|
lang: Language
|
||||||
|
t: TFn
|
||||||
|
actionBusy: boolean
|
||||||
|
onItemDone: (item: PlanItem) => void
|
||||||
|
}): JSX.Element {
|
||||||
|
const nextItem = plan.nextItem
|
||||||
|
const upcoming = plan.items.slice(nextItem ? 1 : 0, nextItem ? 4 : 3)
|
||||||
|
const goalPct =
|
||||||
|
plan.goalTarget > 0
|
||||||
|
? Math.min(100, Math.round((plan.goalDone / plan.goalTarget) * 100))
|
||||||
|
: 0
|
||||||
|
const mealPct =
|
||||||
|
plan.enabledMeals > 0
|
||||||
|
? Math.min(100, Math.round((plan.doneMeals / plan.enabledMeals) * 100))
|
||||||
|
: 0
|
||||||
|
const recovery = recoveryCopy(plan, t)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="mb-8 bg-surface rounded-3xl p-5 shadow-card dark:ring-0.5 dark:ring-hairline/30">
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
||||||
|
<div className="flex items-center gap-3 min-w-0">
|
||||||
|
<div className="w-10 h-10 rounded-2xl bg-accent/12 text-accent grid place-items-center shrink-0">
|
||||||
|
<CalendarCheck size={19} strokeWidth={2.5} />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<h2 className="font-display text-[22px] font-bold leading-tight">
|
||||||
|
{t('dashboard.plan.title')}
|
||||||
|
</h2>
|
||||||
|
<div className="text-[14px] text-text/60 mt-0.5">
|
||||||
|
{t('dashboard.plan.subtitle')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={[
|
||||||
|
'self-start sm:self-auto h-8 px-3 rounded-full inline-flex items-center text-[13px] font-semibold',
|
||||||
|
plan.dueCount > 0
|
||||||
|
? 'bg-accent/12 text-accent'
|
||||||
|
: 'bg-success/12 text-success'
|
||||||
|
].join(' ')}
|
||||||
|
>
|
||||||
|
{plan.dueCount > 0
|
||||||
|
? t('dashboard.plan.due_count', { n: plan.dueCount })
|
||||||
|
: t('dashboard.plan.all_caught_up')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-5 grid grid-cols-1 lg:grid-cols-[1.35fr_0.95fr_0.95fr] border-y border-hairline/35 divide-y lg:divide-y-0 lg:divide-x divide-hairline/35">
|
||||||
|
<div className="py-4 lg:pr-5 min-w-0">
|
||||||
|
<div className="text-[13px] text-text/55 font-semibold">
|
||||||
|
{t('dashboard.plan.next_action')}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{nextItem ? (
|
||||||
|
<>
|
||||||
|
<div className="mt-3 flex items-center gap-3 min-w-0">
|
||||||
|
<PlanItemGlyph item={nextItem} />
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
|
<div className="font-display text-[20px] leading-tight font-bold truncate">
|
||||||
|
{nextItem.name}
|
||||||
|
</div>
|
||||||
|
{nextItem.due && (
|
||||||
|
<span className="shrink-0 w-2 h-2 rounded-full bg-accent" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="text-[13px] text-text/60 mt-1 truncate">
|
||||||
|
{t(`dashboard.plan.kind.${nextItem.kind}`)} ·{' '}
|
||||||
|
{planItemMeta(nextItem, t)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 flex flex-col sm:flex-row sm:items-center gap-3">
|
||||||
|
<div className="text-[14px] text-text/70 flex-1 min-w-0">
|
||||||
|
{planItemTiming(nextItem, paused, lang, t)}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant={nextItem.kind === 'meal' ? 'success' : 'filled'}
|
||||||
|
disabled={actionBusy}
|
||||||
|
onClick={() => onItemDone(nextItem)}
|
||||||
|
className="sm:w-auto w-full"
|
||||||
|
>
|
||||||
|
<Check size={14} strokeWidth={2.5} />
|
||||||
|
{nextItem.kind === 'meal'
|
||||||
|
? t('dashboard.plan.ate_now')
|
||||||
|
: t('dashboard.plan.done_now')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="mt-3 min-w-0">
|
||||||
|
<div className="font-display text-[20px] leading-tight font-bold">
|
||||||
|
{t('dashboard.plan.clear.title')}
|
||||||
|
</div>
|
||||||
|
<div className="text-[14px] text-text/60 mt-1">
|
||||||
|
{t('dashboard.plan.clear.hint')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="py-4 lg:px-5 min-w-0">
|
||||||
|
<div className="flex items-center gap-2 text-[13px] text-text/55 font-semibold">
|
||||||
|
<Target size={14} strokeWidth={2.5} />
|
||||||
|
{t('dashboard.plan.goals')}
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex items-end justify-between gap-3">
|
||||||
|
<div className="font-mono-num text-[24px] font-bold leading-none">
|
||||||
|
{plan.goalTarget > 0
|
||||||
|
? t('dashboard.plan.goals.progress', {
|
||||||
|
done: plan.goalDone,
|
||||||
|
goal: plan.goalTarget
|
||||||
|
})
|
||||||
|
: '—'}
|
||||||
|
</div>
|
||||||
|
{plan.goalTarget > 0 && (
|
||||||
|
<div className="text-[13px] text-text/60">
|
||||||
|
{t('dashboard.plan.goals.remaining', {
|
||||||
|
n: plan.goalRemaining
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ProgressBar pct={goalPct} tone="accent" />
|
||||||
|
<div className="text-[13px] text-text/58 mt-3">
|
||||||
|
{plan.goalTarget > 0
|
||||||
|
? t('dashboard.plan.goals.hint')
|
||||||
|
: t('dashboard.plan.goals.empty')}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{plan.enabledMeals > 0 && (
|
||||||
|
<div className="mt-5">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div className="text-[13px] text-text/55 font-semibold">
|
||||||
|
{t('dashboard.plan.meals')}
|
||||||
|
</div>
|
||||||
|
<div className="font-mono-num text-[14px] font-bold">
|
||||||
|
{t('dashboard.plan.meals.progress', {
|
||||||
|
done: plan.doneMeals,
|
||||||
|
total: plan.enabledMeals
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ProgressBar pct={mealPct} tone="success" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="py-4 lg:pl-5 min-w-0">
|
||||||
|
<div className="flex items-center gap-2 text-[13px] text-text/55 font-semibold">
|
||||||
|
<RotateCcw size={14} strokeWidth={2.5} />
|
||||||
|
{t('dashboard.plan.recovery')}
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex items-start gap-3">
|
||||||
|
<div
|
||||||
|
className={[
|
||||||
|
'w-9 h-9 rounded-xl grid place-items-center shrink-0',
|
||||||
|
recovery.tone
|
||||||
|
].join(' ')}
|
||||||
|
>
|
||||||
|
<RotateCcw size={17} strokeWidth={2.5} />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="font-display text-[20px] leading-tight font-bold">
|
||||||
|
{recovery.title}
|
||||||
|
</div>
|
||||||
|
<div className="text-[14px] text-text/60 mt-1">
|
||||||
|
{recovery.hint}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{upcoming.length > 0 && (
|
||||||
|
<div className="pt-4">
|
||||||
|
<div className="text-[13px] text-text/55 font-semibold mb-2">
|
||||||
|
{t('dashboard.plan.up_next')}
|
||||||
|
</div>
|
||||||
|
<div className="divide-y divide-hairline/35">
|
||||||
|
{upcoming.map((item) => (
|
||||||
|
<PlanListRow
|
||||||
|
key={`${item.kind}:${item.id}`}
|
||||||
|
item={item}
|
||||||
|
paused={paused}
|
||||||
|
lang={lang}
|
||||||
|
t={t}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PlanItemGlyph({ item }: { item: PlanItem }): JSX.Element {
|
||||||
|
const dueClass = item.due
|
||||||
|
? 'bg-accent text-white'
|
||||||
|
: item.kind === 'meal'
|
||||||
|
? 'bg-success/12 text-success'
|
||||||
|
: 'bg-accent/12 text-accent'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={[
|
||||||
|
'w-11 h-11 rounded-2xl grid place-items-center shrink-0',
|
||||||
|
dueClass
|
||||||
|
].join(' ')}
|
||||||
|
>
|
||||||
|
<Icon name={item.icon} size={20} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PlanListRow({
|
||||||
|
item,
|
||||||
|
paused,
|
||||||
|
lang,
|
||||||
|
t
|
||||||
|
}: {
|
||||||
|
item: PlanItem
|
||||||
|
paused: boolean
|
||||||
|
lang: Language
|
||||||
|
t: TFn
|
||||||
|
}): JSX.Element {
|
||||||
|
return (
|
||||||
|
<div className="py-3 flex items-center gap-3 min-w-0">
|
||||||
|
<PlanItemGlyph item={item} />
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="font-semibold text-[15px] leading-tight truncate">
|
||||||
|
{item.name}
|
||||||
|
</div>
|
||||||
|
<div className="text-[13px] text-text/58 mt-1 truncate">
|
||||||
|
{planItemMeta(item, t)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-[13px] text-text/62 shrink-0 max-w-[42%] truncate">
|
||||||
|
{planItemTiming(item, paused, lang, t)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProgressBar({
|
||||||
|
pct,
|
||||||
|
tone,
|
||||||
|
compact = false
|
||||||
|
}: {
|
||||||
|
pct: number
|
||||||
|
tone: 'accent' | 'success' | 'warning' | 'info'
|
||||||
|
compact?: boolean
|
||||||
|
}): JSX.Element {
|
||||||
|
const toneClass =
|
||||||
|
tone === 'accent'
|
||||||
|
? 'bg-accent'
|
||||||
|
: tone === 'success'
|
||||||
|
? 'bg-success'
|
||||||
|
: tone === 'warning'
|
||||||
|
? 'bg-warning'
|
||||||
|
: 'bg-info'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={[
|
||||||
|
'rounded-full bg-hairline/35 overflow-hidden',
|
||||||
|
compact ? 'mt-2 h-1.5' : 'mt-3 h-2'
|
||||||
|
].join(' ')}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={[
|
||||||
|
'h-full rounded-full transition-all duration-300',
|
||||||
|
toneClass
|
||||||
|
].join(' ')}
|
||||||
|
style={{ width: `${pct}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function planItemMeta(item: PlanItem, t: TFn): string {
|
||||||
|
if (item.kind === 'meal') {
|
||||||
|
return item.time
|
||||||
|
? t('dashboard.plan.meal_time', { time: item.time })
|
||||||
|
: t('dashboard.plan.kind.meal')
|
||||||
|
}
|
||||||
|
if (item.goal !== undefined) {
|
||||||
|
return t('dashboard.plan.item.remaining', {
|
||||||
|
n: item.remainingReps ?? 0
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return t('dashboard.plan.item.reps', { n: item.reps ?? 1 })
|
||||||
|
}
|
||||||
|
|
||||||
|
function planItemTiming(
|
||||||
|
item: PlanItem,
|
||||||
|
paused: boolean,
|
||||||
|
lang: Language,
|
||||||
|
t: TFn
|
||||||
|
): string {
|
||||||
|
if (item.due) return t('dashboard.plan.due_now')
|
||||||
|
if (paused) return t('dashboard.plan.paused')
|
||||||
|
return t('dashboard.plan.next_in', {
|
||||||
|
time: formatCountdown(item.nextFireAt - Date.now(), lang)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function recoveryCopy(
|
||||||
|
plan: TodayPlan,
|
||||||
|
t: TFn
|
||||||
|
): { title: string; hint: string; tone: string } {
|
||||||
|
if (plan.recovery.kind === 'first-run') {
|
||||||
|
return {
|
||||||
|
title: t('dashboard.plan.recovery.first.title'),
|
||||||
|
hint: t('dashboard.plan.recovery.first.hint'),
|
||||||
|
tone: 'bg-info/12 text-info'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (plan.recovery.kind === 'recovery') {
|
||||||
|
return {
|
||||||
|
title: t('dashboard.plan.recovery.return.title'),
|
||||||
|
hint: t('dashboard.plan.recovery.return.hint', {
|
||||||
|
n: plan.recovery.daysSinceDone
|
||||||
|
}),
|
||||||
|
tone: 'bg-warning/12 text-warning'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
title: t('dashboard.plan.recovery.steady.title'),
|
||||||
|
hint:
|
||||||
|
plan.recovery.daysSinceDone === 0
|
||||||
|
? t('dashboard.plan.recovery.steady.today')
|
||||||
|
: plan.recovery.daysSinceDone === 1
|
||||||
|
? t('dashboard.plan.recovery.steady.yesterday')
|
||||||
|
: t('dashboard.plan.recovery.steady.none'),
|
||||||
|
tone: 'bg-success/12 text-success'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function HeroStat({
|
function HeroStat({
|
||||||
tone,
|
tone,
|
||||||
label,
|
label,
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
|
import { Copy, FolderOpen, RefreshCw } from 'lucide-react'
|
||||||
import { useAppStore } from '../store/appStore'
|
import { useAppStore } from '../store/appStore'
|
||||||
import { Switch } from '../components/ui/Switch'
|
import { Switch } from '../components/ui/Switch'
|
||||||
|
import { Button } from '../components/ui/Button'
|
||||||
import { Card, Row, SectionHeader } from '../components/ui/Card'
|
import { Card, Row, SectionHeader } from '../components/ui/Card'
|
||||||
import { UpdaterCard } from '../components/UpdaterCard'
|
import { UpdaterCard } from '../components/UpdaterCard'
|
||||||
import { WhatsNewModal } from '../components/WhatsNewModal'
|
import { WhatsNewModal } from '../components/WhatsNewModal'
|
||||||
@@ -8,14 +10,16 @@ import { ConfirmModal } from '../components/ui/ConfirmModal'
|
|||||||
import { Skeleton } from '../components/ui/Skeleton'
|
import { Skeleton } from '../components/ui/Skeleton'
|
||||||
import { Spinner } from '../components/ui/Spinner'
|
import { Spinner } from '../components/ui/Spinner'
|
||||||
import { RELEASE_NOTES } from '@shared/release-notes'
|
import { RELEASE_NOTES } from '@shared/release-notes'
|
||||||
import { useT } from '../i18n'
|
import { translate, useT } from '../i18n'
|
||||||
import type {
|
import type {
|
||||||
|
DiagnosticsInfo,
|
||||||
Language,
|
Language,
|
||||||
NotificationMode,
|
NotificationMode,
|
||||||
QuietHours,
|
QuietHours,
|
||||||
Settings as SettingsType,
|
Settings as SettingsType,
|
||||||
Theme
|
Theme
|
||||||
} from '@shared/types'
|
} from '@shared/types'
|
||||||
|
import { parseHHMM } from '@shared/types'
|
||||||
|
|
||||||
export default function SettingsPage(): JSX.Element {
|
export default function SettingsPage(): JSX.Element {
|
||||||
const settings = useAppStore((s) => s.state?.settings)
|
const settings = useAppStore((s) => s.state?.settings)
|
||||||
@@ -192,6 +196,11 @@ export default function SettingsPage(): JSX.Element {
|
|||||||
<DataCard />
|
<DataCard />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-6">
|
||||||
|
<SectionHeader title={t('settings.section.diagnostics')} />
|
||||||
|
<DiagnosticsCard />
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
<SectionHeader title={t('settings.section.about')} />
|
<SectionHeader title={t('settings.section.about')} />
|
||||||
<AboutCard />
|
<AboutCard />
|
||||||
@@ -201,6 +210,153 @@ export default function SettingsPage(): JSX.Element {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function DiagnosticsCard(): JSX.Element {
|
||||||
|
const { t, lang } = useT()
|
||||||
|
const [info, setInfo] = useState<DiagnosticsInfo | null>(null)
|
||||||
|
const [busy, setBusy] = useState<'refresh' | 'copy' | 'logs' | null>(null)
|
||||||
|
const [toast, setToast] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const refresh = useCallback(async (): Promise<void> => {
|
||||||
|
setBusy('refresh')
|
||||||
|
try {
|
||||||
|
setInfo(await window.api.getDiagnostics())
|
||||||
|
} catch {
|
||||||
|
setToast(translate(lang, 'settings.diagnostics.err'))
|
||||||
|
} finally {
|
||||||
|
setBusy(null)
|
||||||
|
}
|
||||||
|
}, [lang])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void refresh()
|
||||||
|
}, [refresh])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!toast) return
|
||||||
|
const id = setTimeout(() => setToast(null), 4000)
|
||||||
|
return () => clearTimeout(id)
|
||||||
|
}, [toast])
|
||||||
|
|
||||||
|
async function copy(): Promise<void> {
|
||||||
|
setBusy('copy')
|
||||||
|
try {
|
||||||
|
setInfo(await window.api.copyDiagnostics())
|
||||||
|
setToast(t('settings.diagnostics.copy.ok'))
|
||||||
|
} catch {
|
||||||
|
setToast(t('settings.diagnostics.err'))
|
||||||
|
} finally {
|
||||||
|
setBusy(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openLogs(): Promise<void> {
|
||||||
|
setBusy('logs')
|
||||||
|
try {
|
||||||
|
const r = await window.api.openLogsFolder()
|
||||||
|
setToast(
|
||||||
|
r.ok
|
||||||
|
? t('settings.diagnostics.logs.ok')
|
||||||
|
: t('settings.diagnostics.logs.err')
|
||||||
|
)
|
||||||
|
} catch {
|
||||||
|
setToast(t('settings.diagnostics.logs.err'))
|
||||||
|
} finally {
|
||||||
|
setBusy(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const appLine = info
|
||||||
|
? `v${info.app.version} · Electron ${info.runtime.electron}`
|
||||||
|
: t('settings.diagnostics.loading')
|
||||||
|
const dataLine = info
|
||||||
|
? `${info.store.exercises}/${info.store.meals}/${info.store.challenges}/${info.store.history}`
|
||||||
|
: '—'
|
||||||
|
const gsiLine = info
|
||||||
|
? `${info.gsi.running ? 'live' : 'off'} · ${info.gsi.baseUrl}`
|
||||||
|
: '—'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Row>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="text-[15px] font-semibold leading-tight">
|
||||||
|
{t('settings.diagnostics.app.label')}
|
||||||
|
</div>
|
||||||
|
<div className="text-[13px] text-text/65 mt-1 leading-snug">
|
||||||
|
{appLine}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="plain"
|
||||||
|
onClick={refresh}
|
||||||
|
disabled={busy !== null}
|
||||||
|
title={t('settings.diagnostics.refresh')}
|
||||||
|
aria-label={t('settings.diagnostics.refresh')}
|
||||||
|
>
|
||||||
|
<RefreshCw size={16} />
|
||||||
|
</Button>
|
||||||
|
</Row>
|
||||||
|
<Row>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="text-[15px] font-semibold leading-tight">
|
||||||
|
{t('settings.diagnostics.data.label')}
|
||||||
|
</div>
|
||||||
|
<div className="text-[13px] text-text/65 mt-1 leading-snug">
|
||||||
|
{dataLine}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-[12px] text-text/50 font-semibold whitespace-nowrap">
|
||||||
|
{t('settings.diagnostics.data.legend')}
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
<Row>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="text-[15px] font-semibold leading-tight">
|
||||||
|
{t('settings.diagnostics.gsi.label')}
|
||||||
|
</div>
|
||||||
|
<div className="text-[13px] text-text/65 mt-1 leading-snug truncate">
|
||||||
|
{gsiLine}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
<Row last className="flex-wrap justify-end">
|
||||||
|
<div className="flex-1 min-w-[180px] text-[13px] text-text/65 leading-snug">
|
||||||
|
{t('settings.diagnostics.hint')}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="tinted"
|
||||||
|
onClick={openLogs}
|
||||||
|
disabled={busy !== null}
|
||||||
|
>
|
||||||
|
<FolderOpen size={16} />
|
||||||
|
{t('settings.diagnostics.logs.btn')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="filled"
|
||||||
|
onClick={copy}
|
||||||
|
disabled={busy !== null}
|
||||||
|
>
|
||||||
|
<Copy size={16} />
|
||||||
|
{t('settings.diagnostics.copy.btn')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
{toast && (
|
||||||
|
<div className="px-4 py-2.5 text-[13px] text-text/75 bg-accent/8 truncate font-medium">
|
||||||
|
{toast}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function AboutCard(): JSX.Element {
|
function AboutCard(): JSX.Element {
|
||||||
const { t } = useT()
|
const { t } = useT()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
@@ -399,11 +555,10 @@ function QuietTimesRow({
|
|||||||
}): JSX.Element {
|
}): JSX.Element {
|
||||||
const { t } = useT()
|
const { t } = useT()
|
||||||
// Local mirror of from/to so typing doesn't fire an IPC + disk write per
|
// Local mirror of from/to so typing doesn't fire an IPC + disk write per
|
||||||
// keystroke. We commit on blur (or when validation passes during typing).
|
// keystroke. We commit on blur and only send values accepted by the shared
|
||||||
// The HH:MM regex catches the moment the user has typed a full time.
|
// HH:MM parser.
|
||||||
const [from, setFrom] = useState(qh.from)
|
const [from, setFrom] = useState(qh.from)
|
||||||
const [to, setTo] = useState(qh.to)
|
const [to, setTo] = useState(qh.to)
|
||||||
const HHMM = /^\d{1,2}:\d{2}$/
|
|
||||||
|
|
||||||
// Sync from props when an external state change happens (lang switch,
|
// Sync from props when an external state change happens (lang switch,
|
||||||
// pause toggle), but only if user isn't mid-edit.
|
// pause toggle), but only if user isn't mid-edit.
|
||||||
@@ -417,7 +572,7 @@ function QuietTimesRow({
|
|||||||
const commit = (next: { from?: string; to?: string }): void => {
|
const commit = (next: { from?: string; to?: string }): void => {
|
||||||
const f = next.from ?? from
|
const f = next.from ?? from
|
||||||
const tt = next.to ?? to
|
const tt = next.to ?? to
|
||||||
if (!HHMM.test(f) || !HHMM.test(tt)) return
|
if (parseHHMM(f) === null || parseHHMM(tt) === null) return
|
||||||
if (f === qh.from && tt === qh.to) return
|
if (f === qh.from && tt === qh.to) return
|
||||||
onChange({ ...qh, from: f, to: tt })
|
onChange({ ...qh, from: f, to: tt })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ export const IPC = {
|
|||||||
getAccentColor: 'system:accentColor',
|
getAccentColor: 'system:accentColor',
|
||||||
getOsTheme: 'system:osTheme',
|
getOsTheme: 'system:osTheme',
|
||||||
getAppVersion: 'system:appVersion',
|
getAppVersion: 'system:appVersion',
|
||||||
|
getDiagnostics: 'system:diagnostics',
|
||||||
|
openLogsFolder: 'system:openLogsFolder',
|
||||||
|
copyDiagnostics: 'system:copyDiagnostics',
|
||||||
|
reportRendererError: 'system:reportRendererError',
|
||||||
|
|
||||||
pauseAll: 'app:pauseAll',
|
pauseAll: 'app:pauseAll',
|
||||||
resumeAll: 'app:resumeAll',
|
resumeAll: 'app:resumeAll',
|
||||||
|
|||||||
@@ -21,6 +21,60 @@ export type ReleaseNoteItem = {
|
|||||||
export type ReleaseNotes = Record<Language, ReleaseNoteItem[]>
|
export type ReleaseNotes = Record<Language, ReleaseNoteItem[]>
|
||||||
|
|
||||||
export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
|
export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
|
||||||
|
'0.6.3': {
|
||||||
|
ru: [
|
||||||
|
{
|
||||||
|
title: 'Новый главный экран “Не Залипай”',
|
||||||
|
detail:
|
||||||
|
'Сегодня теперь показывает не только план, но и недельный ритм, уровень и игровые долги.',
|
||||||
|
tag: 'new'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Мини-челленджи недели',
|
||||||
|
detail:
|
||||||
|
'5 дней без нуля, 1000 повторов, “сегодня не ноль” и закрытые катки считаются автоматически.',
|
||||||
|
tag: 'new'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Игровой долг после каток',
|
||||||
|
detail:
|
||||||
|
'На Dashboard видно, сколько Dota-долгов закрыто сегодня и за неделю.',
|
||||||
|
tag: 'new'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Мягкая система уровней',
|
||||||
|
detail:
|
||||||
|
'XP считается из повторов, активных дней и закрытых игровых челленджей.',
|
||||||
|
tag: 'new'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
en: [
|
||||||
|
{
|
||||||
|
title: 'New “Ne Zalipay” Today screen',
|
||||||
|
detail:
|
||||||
|
'Today now shows the day plan, weekly rhythm, level and game debts.',
|
||||||
|
tag: 'new'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Weekly mini-challenges',
|
||||||
|
detail:
|
||||||
|
'5 non-zero days, 1000 reps, “today is not zero” and closed matches are tracked automatically.',
|
||||||
|
tag: 'new'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Game debt after matches',
|
||||||
|
detail:
|
||||||
|
'Dashboard shows how many Dota debts were closed today and this week.',
|
||||||
|
tag: 'new'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Soft level system',
|
||||||
|
detail:
|
||||||
|
'XP comes from reps, active days and completed game challenges.',
|
||||||
|
tag: 'new'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
'0.5.8': {
|
'0.5.8': {
|
||||||
ru: [
|
ru: [
|
||||||
{
|
{
|
||||||
@@ -204,14 +258,12 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
|
|||||||
en: [
|
en: [
|
||||||
{
|
{
|
||||||
title: 'Reminder categories',
|
title: 'Reminder categories',
|
||||||
detail:
|
detail: 'Beyond exercises — hydration, eye rest (20-20-20), posture.',
|
||||||
'Beyond exercises — hydration, eye rest (20-20-20), posture.',
|
|
||||||
tag: 'new'
|
tag: 'new'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Voice prompts',
|
title: 'Voice prompts',
|
||||||
detail:
|
detail: 'Speaks the exercise name and count. Toggle in Settings.',
|
||||||
'Speaks the exercise name and count. Toggle in Settings.',
|
|
||||||
tag: 'new'
|
tag: 'new'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -255,7 +307,8 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
|
|||||||
ru: [
|
ru: [
|
||||||
{
|
{
|
||||||
title: 'Sandbox для окон',
|
title: 'Sandbox для окон',
|
||||||
detail: 'Окна изолированы на уровне OS — даже RCE в рендере не достанет main.',
|
detail:
|
||||||
|
'Окна изолированы на уровне OS — даже RCE в рендере не достанет main.',
|
||||||
tag: 'security'
|
tag: 'security'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -282,7 +335,8 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
|
|||||||
en: [
|
en: [
|
||||||
{
|
{
|
||||||
title: 'Window sandbox',
|
title: 'Window sandbox',
|
||||||
detail: 'OS-level isolation — even RCE in the renderer cannot reach main.',
|
detail:
|
||||||
|
'OS-level isolation — even RCE in the renderer cannot reach main.',
|
||||||
tag: 'security'
|
tag: 'security'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -311,24 +365,28 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
|
|||||||
ru: [
|
ru: [
|
||||||
{
|
{
|
||||||
title: 'Фоновое скачивание апдейта',
|
title: 'Фоновое скачивание апдейта',
|
||||||
detail: 'Можно уйти на Dashboard и заниматься — апдейт качается в фоне.',
|
detail:
|
||||||
|
'Можно уйти на Dashboard и заниматься — апдейт качается в фоне.',
|
||||||
tag: 'new'
|
tag: 'new'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Моментальный рестарт',
|
title: 'Моментальный рестарт',
|
||||||
detail: 'Кнопка «Рестарт» — ~1-2 сек до открытия новой версии, без диалогов NSIS.',
|
detail:
|
||||||
|
'Кнопка «Рестарт» — ~1-2 сек до открытия новой версии, без диалогов NSIS.',
|
||||||
tag: 'new'
|
tag: 'new'
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
en: [
|
en: [
|
||||||
{
|
{
|
||||||
title: 'Background update download',
|
title: 'Background update download',
|
||||||
detail: 'You can go to Dashboard and work — the update keeps downloading.',
|
detail:
|
||||||
|
'You can go to Dashboard and work — the update keeps downloading.',
|
||||||
tag: 'new'
|
tag: 'new'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Instant restart',
|
title: 'Instant restart',
|
||||||
detail: 'Restart button — ~1-2 sec to the new version, no NSIS dialogs.',
|
detail:
|
||||||
|
'Restart button — ~1-2 sec to the new version, no NSIS dialogs.',
|
||||||
tag: 'new'
|
tag: 'new'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -352,7 +410,9 @@ export function unseenVersions(
|
|||||||
// явный «What's new» из Settings.
|
// явный «What's new» из Settings.
|
||||||
return all.filter((v) => v === current)
|
return all.filter((v) => v === current)
|
||||||
}
|
}
|
||||||
return all.filter((v) => compareSemver(v, lastSeen) > 0 && compareSemver(v, current) <= 0)
|
return all.filter(
|
||||||
|
(v) => compareSemver(v, lastSeen) > 0 && compareSemver(v, current) <= 0
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseSemver(v: string): [number, number, number] {
|
function parseSemver(v: string): [number, number, number] {
|
||||||
|
|||||||
@@ -300,7 +300,7 @@ export const DEFAULT_SETTINGS: Settings = {
|
|||||||
const HHMM_RE = /^(\d{1,2}):(\d{2})$/
|
const HHMM_RE = /^(\d{1,2}):(\d{2})$/
|
||||||
|
|
||||||
/** Parse `HH:MM` into minutes-since-midnight, or `null` if malformed. */
|
/** Parse `HH:MM` into minutes-since-midnight, or `null` if malformed. */
|
||||||
function parseHHMM(s: string): number | null {
|
export function parseHHMM(s: string): number | null {
|
||||||
const m = HHMM_RE.exec(s)
|
const m = HHMM_RE.exec(s)
|
||||||
if (!m) return null
|
if (!m) return null
|
||||||
const h = Number(m[1])
|
const h = Number(m[1])
|
||||||
@@ -455,3 +455,45 @@ export type UpdaterStatus =
|
|||||||
}
|
}
|
||||||
| { kind: 'downloaded'; version: string }
|
| { kind: 'downloaded'; version: string }
|
||||||
| { kind: 'error'; message: string }
|
| { kind: 'error'; message: string }
|
||||||
|
|
||||||
|
export type DiagnosticsInfo = {
|
||||||
|
generatedAt: number
|
||||||
|
app: {
|
||||||
|
version: string
|
||||||
|
isPackaged: boolean
|
||||||
|
platform: string
|
||||||
|
arch: string
|
||||||
|
}
|
||||||
|
runtime: {
|
||||||
|
electron: string
|
||||||
|
chrome: string
|
||||||
|
node: string
|
||||||
|
}
|
||||||
|
paths: {
|
||||||
|
userData: string
|
||||||
|
store: string
|
||||||
|
logs: string
|
||||||
|
}
|
||||||
|
store: {
|
||||||
|
bytes: number | null
|
||||||
|
exercises: number
|
||||||
|
meals: number
|
||||||
|
challenges: number
|
||||||
|
history: number
|
||||||
|
}
|
||||||
|
updater: UpdaterStatus
|
||||||
|
games: GameStatus[]
|
||||||
|
gsi: {
|
||||||
|
running: boolean
|
||||||
|
port: number
|
||||||
|
baseUrl: string
|
||||||
|
}
|
||||||
|
meetingActive: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RendererErrorReport = {
|
||||||
|
message: string
|
||||||
|
stack?: string
|
||||||
|
componentStack?: string
|
||||||
|
source?: string
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user