4 Commits

Author SHA1 Message Date
Codex
ea052f64b8 chore(release): v0.6.4 2026-06-07 14:18:34 +07:00
Codex
cde8334c73 feat(ui): refresh page summaries and brand 2026-06-07 14:17:24 +07:00
Codex
deb3483f94 chore(release): v0.6.3 2026-06-07 12:09:29 +07:00
Codex
5ed80d7122 feat(dashboard): add momentum and game debt 2026-06-07 12:08:21 +07:00
16 changed files with 1262 additions and 77 deletions

View File

@@ -6,6 +6,37 @@
## [Unreleased]
## [0.6.4] — 2026-06-07
### Added
- На страницах `Упражнения`, `Питание`, `Игры`, `Челленджи` и `Настройки`
добавлены верхние сводные карточки: активные элементы, нагрузка, цели,
ближайшее питание, состояние игровых интеграций и ключевые настройки.
- Добавлен общий `PageScaffold` для единых заголовков и insight-карточек в renderer.
### Changed
- Видимый бренд в интерфейсе сменен с “Не Залипай” на “Разомнись”.
- README, title, release notes и описание пакета обновлены под новое название.
## [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
@@ -48,13 +79,13 @@
history не перетягивалась. Heatmap стоял пока пользователь не
добавит/удалит упражнение. Сейчас новый event `evtHistoryChanged`
шлётся из main после `markDone/snooze/skip/markChallengeDone/
clearHistory/import`, Dashboard на него подписан.
clearHistory/import`, Dashboard на него подписан.
- **Rapid double-click больше не пишет в историю дважды.** В Match
Summary при быстром тыке ✓ дважды один и тот же challenge мог
записаться 2 раза → лишние +N reps в стрик. То же для кнопки
«Готово» в ExerciseCard. ref-based дедуп.
- **Native save/open dialogs локализованы.** Раньше title `«Сохранить
резервную копию»` показывался даже в EN-локали.
резервную копию»` показывался даже в EN-локали.
- **Default exerciseName в challenge editor — пустой** (было
«Приседания» — выглядело как недопереведённый русский в EN UI).
@@ -362,7 +393,7 @@
блокирует CSRF от browser-вкладок. Body cap 256 KB (OOM-вектор
закрыт). Require `application/json`. Generic 400 без error-echo.
- **`isQuietAt` wrap-around + day filter.** С `22:00 → 07:00,
days=[Mon..Fri]` теперь правильно проверяется день *начала* окна
days=[Mon..Fri]` теперь правильно проверяется день _начала_ окна
(старт Fri 22:00 → активно ночью Sat 02:00).
- **DST drift в `history.ts`.** Календарная арифметика (`setDate`)
вместо ms-арифметики — на границе DST дни больше не дублируются.
@@ -474,7 +505,9 @@
иконки), системный трей, автозапуск с Windows, native-уведомления,
NSIS-инсталлятор, auto-update через electron-updater.
[Unreleased]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/compare/v0.6.2...HEAD
[Unreleased]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/compare/v0.6.4...HEAD
[0.6.4]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/compare/v0.6.3...v0.6.4
[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.7]: https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/tag/v0.5.7

View File

@@ -1,9 +1,9 @@
# Laude — Exercise Reminder
# Разомнись — Exercise Reminder
Windows desktop приложение, которое напоминает делать упражнения во время работы за компьютером. Опционально подключается к Dota 2 и после каждого матча превращает статистику (смерти, убийства, ассисты) в количество повторений.
Windows desktop приложение, которое помогает делать короткие перерывы без потери фокуса: держит план дня, напоминает размяться, ведёт недельные челленджи и превращает Dota 2 статистику после матча в игровые долги.
[![release](https://img.shields.io/badge/release-v0.6.1-orange)](https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/latest)
[![tests](https://img.shields.io/badge/tests-238%20passing-green)]()
[![release](https://img.shields.io/badge/release-v0.6.4-orange)](https://git.xn--90adajar8af4h.xn--p1ai/AnRil/laude/releases/latest)
[![tests](https://img.shields.io/badge/tests-241%20passing-green)]()
[![platform](https://img.shields.io/badge/platform-Windows%2010%2F11-blue)]()
## Что внутри
@@ -11,6 +11,7 @@ Windows desktop приложение, которое напоминает дел
- **Гибкие напоминания** — любое количество упражнений, интервал от минуты до часов, разные иконки.
- **Питание** — отдельная вкладка с приёмами пищи по времени суток (завтрак/обед/ужин/перекусы), выбор дней недели, пресеты быстрого добавления. Напоминания по настенным часам, а не по интервалу.
- **История и стрики** — heatmap-календарь активности, ежедневный счётчик, серия дней подряд.
- **Сегодня** — главный экран с планом дня, уровнем, недельными мини-челленджами и игровым долгом.
- **Тихие часы** — окно времени когда напоминания подавляются (например `22:00 → 08:00`), с выбором дней недели.
- **Сделал частично** — степпер `/+` в окне напоминания: если ты сделал 5 из 10, в историю запишется честное число.
- **Игровая интеграция (Dota 2)** — Game State Integration читает статистику матча, после Победа/Поражение показывает экран с «причитающимися» повторениями (например `10 смертей × 3 = 30 приседаний`).
@@ -84,8 +85,9 @@ src/main/adaptive.test.ts (6)
src/renderer/src/lib/day-plan.test.ts (6)
src/shared/types.test.ts (4)
src/renderer/src/lib/icon-choices.test.ts (4)
src/renderer/src/lib/momentum.test.ts (3)
──────────────────────────────────────────
238
241
```
Покрытие: IPC-валидация (упражнения/челленджи/приёмы пищи), persistence (миграции, карантин битого JSON, history cap), scheduler-гейтинг (тихие часы, ВКС-пауза, daily-goal), планирование приёмов пищи по времени суток (DST-safe), детект ВКС, история/стрики (DST), тихие часы (wrap), парсер VDF для Steam-конфигов, достижения, i18n с плюрализацией RU/EN, дефолты shared-типов.

View File

@@ -1,7 +1,7 @@
{
"name": "laude",
"version": "0.6.2",
"description": "Exercise reminder — Windows desktop app",
"version": "0.6.4",
"description": "Разомнись — Windows desktop break and exercise reminder",
"main": "out/main/index.js",
"author": "AnRil",
"private": true,

View File

@@ -9,8 +9,11 @@
для Tailwind utility-классов и инлайн-стилей framer-motion. font-src
включает data: на случай если кто-то вставит base64 SVG-glyph.
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:; script-src 'self'; connect-src 'self'; base-uri 'self'; frame-ancestors 'none'" />
<title>Exercise Reminder</title>
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:; script-src 'self'; connect-src 'self'; base-uri 'self'; frame-ancestors 'none'"
/>
<title>Разомнись</title>
</head>
<body>
<div id="root"></div>

View File

@@ -0,0 +1,103 @@
import type { ReactNode } from 'react'
type Tone = 'accent' | 'success' | 'warning' | 'info' | 'muted'
export function PageHeader({
kicker,
title,
subtitle,
action
}: {
kicker: string
title: string
subtitle?: string
action?: ReactNode
}): JSX.Element {
return (
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-6">
<div className="min-w-0">
<div className="text-[14px] text-text/65 font-semibold">{kicker}</div>
<h1 className="font-serif text-[34px] sm:text-[40px] leading-[1.02] tracking-tight mt-1 font-bold">
{title}
</h1>
{subtitle && (
<p className="text-[15px] text-text/65 mt-2 font-medium leading-relaxed max-w-2xl">
{subtitle}
</p>
)}
</div>
{action && <div className="shrink-0">{action}</div>}
</div>
)
}
export function InsightGrid({
children,
className = ''
}: {
children: ReactNode
className?: string
}): JSX.Element {
return (
<div
className={['grid grid-cols-1 sm:grid-cols-3 gap-3 mb-8', className].join(
' '
)}
>
{children}
</div>
)
}
export function InsightCard({
icon,
label,
value,
hint,
tone = 'accent'
}: {
icon: ReactNode
label: string
value: string
hint?: string
tone?: Tone
}): JSX.Element {
const iconClass =
tone === 'accent'
? 'bg-accent text-white'
: tone === 'success'
? 'bg-success text-white'
: tone === 'warning'
? 'bg-warning text-white'
: tone === 'info'
? 'bg-info text-white'
: 'bg-text/12 text-text/55'
return (
<div className="bg-surface rounded-2xl p-4 shadow-card dark:ring-0.5 dark:ring-hairline/30 min-w-0">
<div className="flex items-start gap-3">
<div
className={[
'w-9 h-9 rounded-xl grid place-items-center shrink-0',
iconClass
].join(' ')}
>
{icon}
</div>
<div className="min-w-0">
<div className="text-[12px] uppercase tracking-[0.06em] text-text/50 font-bold truncate">
{label}
</div>
<div className="font-display text-[22px] font-bold leading-none mt-1 truncate">
{value}
</div>
{hint && (
<div className="text-[13px] text-text/58 mt-2 leading-snug">
{hint}
</div>
)}
</div>
</div>
</div>
)
}

View File

@@ -162,7 +162,7 @@ function SidebarContent({ onNav }: { onNav?: () => void }): JSX.Element {
<>
<div className="px-5 pt-7 pb-6">
<div className="font-serif text-[36px] leading-none tracking-tight font-bold">
Laude
Разомнись
</div>
<div className="text-[13px] text-text/55 mt-2 font-medium">
{t('sidebar.slogan')}

View File

@@ -18,7 +18,7 @@ export const ru: Dict = {
'nav.games': 'Игры',
'nav.challenges': 'Челленджи',
'nav.settings': 'Настройки',
'sidebar.slogan': 'Двигайся осознанно',
'sidebar.slogan': 'Лёгкий перерыв без потери фокуса',
'sidebar.status_tracking': 'Активность отслеживается',
'titlebar.menu_aria': 'Меню',
'titlebar.minimize_aria': 'Свернуть',
@@ -26,7 +26,7 @@ export const ru: Dict = {
'titlebar.restore_aria': 'Восстановить размер',
'titlebar.tray_aria': 'В трей',
'titlebar.close_aria': 'Закрыть',
'titlebar.app_title': 'Exercise Reminder',
'titlebar.app_title': 'Разомнись',
// Common buttons / actions
'btn.add': 'Добавить',
@@ -124,9 +124,56 @@ export const ru: Dict = {
'dashboard.empty.title': 'Программа пуста',
'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.kicker': 'Программа',
'exercises.title': 'Упражнения',
'exercises.subtitle':
'Собери короткие действия, которые легко сделать между задачами.',
'exercises.insight.active': 'Активно',
'exercises.insight.active.hint': 'Напоминания, которые сейчас работают',
'exercises.insight.load': 'Нагрузка',
'exercises.insight.load.value': '{n} раз',
'exercises.insight.load.hint': 'Сумма повторов за один полный круг',
'exercises.insight.goals': 'Цели',
'exercises.insight.goals.hint': 'Упражнения с дневной нормой',
'exercises.section.active': 'Активные · {n}',
'exercises.section.disabled': 'Выключенные · {n}',
'exercises.row.meta': '{reps} раз · {interval}',
@@ -135,6 +182,13 @@ export const ru: Dict = {
// Meals (приёмы пищи)
'meals.kicker': 'Режим питания',
'meals.title': 'Питание',
'meals.subtitle': 'Держи еду в расписании, чтобы не выпадать из ритма.',
'meals.insight.active': 'Активно',
'meals.insight.active.hint': 'Приёмы пищи с включённым напоминанием',
'meals.insight.next': 'Следующее',
'meals.insight.next.hint': 'Ближайшее время сегодня',
'meals.insight.presets': 'Пресеты',
'meals.insight.presets.hint': 'Быстрые варианты для старта',
'meals.presets': 'Быстрое добавление',
'meals.schedule': 'Расписание',
'meals.section.active': 'Активные · {n}',
@@ -176,6 +230,13 @@ export const ru: Dict = {
'challenges.title': 'Челленджи',
'challenges.subtitle': 'Повторов = {formula}',
'challenges.subtitle.formula': 'статистика × коэффициент',
'challenges.insight.active': 'Активно',
'challenges.insight.active.hint': 'Правила, которые начисляют долг',
'challenges.insight.games': 'Игры',
'challenges.insight.games.hint': 'Включённые игровые интеграции',
'challenges.insight.debt': 'Тест долга',
'challenges.insight.debt.value': '{n} раз',
'challenges.insight.debt.hint': 'Если каждое правило поймает 5 событий',
'challenges.warning.no_games':
'Челленджи срабатывают после матча. Подключи игру во вкладке «Игры».',
'challenges.section.all': 'Все · {n}',
@@ -201,6 +262,13 @@ export const ru: Dict = {
'games.subtitle': 'Подключи игру — челленджи сработают сразу после матча',
'games.subtitle.live': '{n} live',
'games.section.supported': 'Поддерживаемые',
'games.insight.supported': 'Поддержка',
'games.insight.supported.hint': 'Игры, которые умеет отслеживать приложение',
'games.insight.connected': 'Подключено',
'games.insight.connected.hint': 'Интеграции с установленной GSI',
'games.insight.live': 'Сигнал',
'games.insight.live.hint': 'Live или ожидание перезапуска Steam',
'games.insight.queued': '{n} в очереди',
'games.scanning': 'Сканируем установленные игры…',
'games.queued.body':
'Steam запущен. Параметр {opt} пропишется автоматически при следующем закрытии Steam.',
@@ -217,6 +285,12 @@ export const ru: Dict = {
// Settings
'settings.kicker': 'Конфигурация',
'settings.title': 'Настройки',
'settings.insight.mode': 'Уведомления',
'settings.insight.mode.hint': 'Как приложение говорит о перерыве',
'settings.insight.theme': 'Тема',
'settings.insight.theme.hint': 'Визуальный режим интерфейса',
'settings.insight.language': 'Язык',
'settings.insight.language.hint': 'Применяется без перезапуска',
'settings.section.reminders': 'Напоминания',
'settings.section.quiet': 'Тихие часы',
'settings.section.window': 'Окно и трей',
@@ -433,7 +507,7 @@ export const en: Dict = {
'nav.games': 'Games',
'nav.challenges': 'Challenges',
'nav.settings': 'Settings',
'sidebar.slogan': 'Move with intention',
'sidebar.slogan': 'A small break without losing focus',
'sidebar.status_tracking': 'Activity tracking is on',
'titlebar.menu_aria': 'Menu',
'titlebar.minimize_aria': 'Minimize',
@@ -441,7 +515,7 @@ export const en: Dict = {
'titlebar.restore_aria': 'Restore size',
'titlebar.tray_aria': 'To tray',
'titlebar.close_aria': 'Close',
'titlebar.app_title': 'Exercise Reminder',
'titlebar.app_title': 'Razomnis',
// Common buttons
'btn.add': 'Add',
@@ -538,9 +612,56 @@ export const en: Dict = {
'dashboard.empty.title': 'Program is empty',
'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.kicker': 'Program',
'exercises.title': 'Exercises',
'exercises.subtitle':
'Build short actions that are easy to do between tasks.',
'exercises.insight.active': 'Active',
'exercises.insight.active.hint': 'Reminders currently running',
'exercises.insight.load': 'Load',
'exercises.insight.load.value': '{n} reps',
'exercises.insight.load.hint': 'Total reps in one full cycle',
'exercises.insight.goals': 'Goals',
'exercises.insight.goals.hint': 'Exercises with a daily target',
'exercises.section.active': 'Active · {n}',
'exercises.section.disabled': 'Disabled · {n}',
'exercises.row.meta': '{reps} reps · {interval}',
@@ -549,6 +670,13 @@ export const en: Dict = {
// Meals
'meals.kicker': 'Eating schedule',
'meals.title': 'Meals',
'meals.subtitle': 'Keep food on the schedule so the day stays steady.',
'meals.insight.active': 'Active',
'meals.insight.active.hint': 'Meals with enabled reminders',
'meals.insight.next': 'Next',
'meals.insight.next.hint': 'Closest time today',
'meals.insight.presets': 'Presets',
'meals.insight.presets.hint': 'Fast starter options',
'meals.presets': 'Quick add',
'meals.schedule': 'Schedule',
'meals.section.active': 'Active · {n}',
@@ -590,6 +718,13 @@ export const en: Dict = {
'challenges.title': 'Challenges',
'challenges.subtitle': 'Reps = {formula}',
'challenges.subtitle.formula': 'stat × multiplier',
'challenges.insight.active': 'Active',
'challenges.insight.active.hint': 'Rules that can add debt',
'challenges.insight.games': 'Games',
'challenges.insight.games.hint': 'Enabled game integrations',
'challenges.insight.debt': 'Debt test',
'challenges.insight.debt.value': '{n} reps',
'challenges.insight.debt.hint': 'If each rule catches 5 events',
'challenges.warning.no_games':
'Challenges trigger after a match. Connect a game in the Games tab.',
'challenges.section.all': 'All · {n}',
@@ -615,6 +750,13 @@ export const en: Dict = {
'games.subtitle': 'Connect a game — challenges fire right after the match',
'games.subtitle.live': '{n} live',
'games.section.supported': 'Supported',
'games.insight.supported': 'Support',
'games.insight.supported.hint': 'Games this app knows how to track',
'games.insight.connected': 'Connected',
'games.insight.connected.hint': 'Integrations with installed GSI',
'games.insight.live': 'Signal',
'games.insight.live.hint': 'Live or waiting for Steam restart',
'games.insight.queued': '{n} queued',
'games.scanning': 'Scanning installed games…',
'games.queued.body':
'Steam is running. The {opt} option will be added automatically next time Steam closes.',
@@ -631,6 +773,12 @@ export const en: Dict = {
// Settings
'settings.kicker': 'Configuration',
'settings.title': 'Settings',
'settings.insight.mode': 'Notifications',
'settings.insight.mode.hint': 'How the app talks about a break',
'settings.insight.theme': 'Theme',
'settings.insight.theme.hint': 'Visual interface mode',
'settings.insight.language': 'Language',
'settings.insight.language.hint': 'Applied without restart',
'settings.section.reminders': 'Reminders',
'settings.section.quiet': 'Quiet hours',
'settings.section.window': 'Window & tray',

View 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)
})
})

View 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
}
}

View File

@@ -1,7 +1,15 @@
import { useEffect, useState } from 'react'
import { Plus, ChevronRight, AlertTriangle, Gamepad2 } from 'lucide-react'
import {
AlertTriangle,
BadgeCheck,
ChevronRight,
Gamepad2,
Plus,
Swords
} from 'lucide-react'
import { useAppStore } from '../store/appStore'
import { Button } from '../components/ui/Button'
import { InsightCard, InsightGrid } from '../components/PageScaffold'
import { Switch } from '../components/ui/Switch'
import { Modal } from '../components/ui/Modal'
import { Card, Row, SectionHeader } from '../components/ui/Card'
@@ -49,6 +57,12 @@ export default function ChallengesPage(): JSX.Element {
}, [])
const noGamesActive = games.length > 0 && !games.some((g) => g.enabled)
const activeChallenges = challenges.filter((c) => c.enabled)
const enabledGames = games.filter((g) => g.enabled).length
const previewDebt = activeChallenges.reduce(
(sum, challenge) => sum + Math.round(5 * challenge.multiplier),
0
)
return (
<div className="h-full overflow-y-auto">
@@ -88,6 +102,30 @@ export default function ChallengesPage(): JSX.Element {
</div>
)}
<InsightGrid>
<InsightCard
icon={<BadgeCheck size={17} strokeWidth={2.5} />}
label={t('challenges.insight.active')}
value={`${activeChallenges.length}/${challenges.length}`}
hint={t('challenges.insight.active.hint')}
tone={activeChallenges.length > 0 ? 'success' : 'muted'}
/>
<InsightCard
icon={<Gamepad2 size={17} strokeWidth={2.5} />}
label={t('challenges.insight.games')}
value={`${enabledGames}`}
hint={t('challenges.insight.games.hint')}
tone={enabledGames > 0 ? 'info' : 'warning'}
/>
<InsightCard
icon={<Swords size={17} strokeWidth={2.5} />}
label={t('challenges.insight.debt')}
value={t('challenges.insight.debt.value', { n: previewDebt })}
hint={t('challenges.insight.debt.hint')}
tone={previewDebt > 0 ? 'warning' : 'muted'}
/>
</InsightGrid>
{challenges.length > 0 ? (
<>
<SectionHeader

View File

@@ -11,7 +11,10 @@ import {
CalendarCheck,
Target,
RotateCcw,
Check
Check,
Trophy,
Swords,
BadgeCheck
} from 'lucide-react'
import { useAppStore } from '../store/appStore'
import { ExerciseCard } from '../components/ExerciseCard'
@@ -40,6 +43,11 @@ import {
repsDoneTodayForExercise,
todayKey
} from '../lib/history'
import {
computeMomentumSummary,
type MomentumSummary,
type WeeklyQuest
} from '../lib/momentum'
export default function Dashboard(): JSX.Element {
const state = useAppStore((s) => s.state)
@@ -54,6 +62,7 @@ export default function Dashboard(): JSX.Element {
// the parent re-renders even when nothing changed.
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 [planActionKey, setPlanActionKey] = useState<string | null>(null)
@@ -129,6 +138,10 @@ export default function Dashboard(): JSX.Element {
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
@@ -327,6 +340,14 @@ export default function Dashboard(): JSX.Element {
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} />
@@ -393,6 +414,238 @@ 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,
@@ -650,17 +903,33 @@ function PlanListRow({
function ProgressBar({
pct,
tone
tone,
compact = false
}: {
pct: number
tone: 'accent' | 'success'
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="mt-3 h-2 rounded-full bg-hairline/35 overflow-hidden">
<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',
tone === 'accent' ? 'bg-accent' : 'bg-success'
toneClass
].join(' ')}
style={{ width: `${pct}%` }}
/>

View File

@@ -1,7 +1,12 @@
import { useState } from 'react'
import { Plus, ChevronRight } from 'lucide-react'
import { Activity, ChevronRight, Dumbbell, Plus, Target } from 'lucide-react'
import { useAppStore } from '../store/appStore'
import { ExerciseEditor } from '../components/ExerciseEditor'
import {
InsightCard,
InsightGrid,
PageHeader
} from '../components/PageScaffold'
import { Button } from '../components/ui/Button'
import { Switch } from '../components/ui/Switch'
import { Card, Row, SectionHeader } from '../components/ui/Card'
@@ -18,28 +23,51 @@ export default function Exercises(): JSX.Element {
const enabled = exercises.filter((e) => e.enabled)
const disabled = exercises.filter((e) => !e.enabled)
const goalCount = exercises.filter((e) => e.dailyGoal !== undefined).length
const totalReps = enabled.reduce((sum, e) => sum + e.reps, 0)
return (
<div className="h-full overflow-y-auto">
<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-10 pt-8 pb-12">
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-8">
<div>
<div className="text-[14px] text-text/65 font-semibold">
{t('exercises.kicker')}
</div>
<h1 className="font-serif text-[34px] sm:text-[40px] leading-[1.02] tracking-tight mt-1 font-bold">
{t('exercises.title')}
</h1>
</div>
<Button
onClick={() => {
setEditing(null)
setEditorOpen(true)
}}
>
<Plus size={15} strokeWidth={2.5} /> {t('btn.add')}
</Button>
</div>
<PageHeader
kicker={t('exercises.kicker')}
title={t('exercises.title')}
subtitle={t('exercises.subtitle')}
action={
<Button
onClick={() => {
setEditing(null)
setEditorOpen(true)
}}
>
<Plus size={15} strokeWidth={2.5} /> {t('btn.add')}
</Button>
}
/>
<InsightGrid>
<InsightCard
icon={<Activity size={17} strokeWidth={2.5} />}
label={t('exercises.insight.active')}
value={`${enabled.length}/${exercises.length}`}
hint={t('exercises.insight.active.hint')}
tone={enabled.length > 0 ? 'success' : 'muted'}
/>
<InsightCard
icon={<Dumbbell size={17} strokeWidth={2.5} />}
label={t('exercises.insight.load')}
value={t('exercises.insight.load.value', { n: totalReps })}
hint={t('exercises.insight.load.hint')}
tone="accent"
/>
<InsightCard
icon={<Target size={17} strokeWidth={2.5} />}
label={t('exercises.insight.goals')}
value={`${goalCount}`}
hint={t('exercises.insight.goals.hint')}
tone={goalCount > 0 ? 'info' : 'muted'}
/>
</InsightGrid>
{enabled.length > 0 && (
<>

View File

@@ -9,6 +9,7 @@ import {
AlertTriangle
} from 'lucide-react'
import { motion } from 'framer-motion'
import { InsightCard, InsightGrid } from '../components/PageScaffold'
import { Button } from '../components/ui/Button'
import { Switch } from '../components/ui/Switch'
import { Spinner } from '../components/ui/Spinner'
@@ -55,7 +56,14 @@ export default function GamesPage(): JSX.Element {
}
}
const liveCount = games.filter((g) => g.enabled && g.integrationActive).length
const connectedCount = games.filter((g) => g.integrationActive).length
const liveCount = games.filter(
(g) =>
g.enabled && g.integrationActive && g.launchOptionStatus === 'applied'
).length
const queuedCount = games.filter(
(g) => g.integrationActive && g.launchOptionStatus === 'queued'
).length
return (
<div className="h-full overflow-y-auto">
@@ -85,6 +93,36 @@ export default function GamesPage(): JSX.Element {
</Button>
</div>
<InsightGrid>
<InsightCard
icon={<Gamepad2 size={17} strokeWidth={2.5} />}
label={t('games.insight.supported')}
value={`${games.length}`}
hint={t('games.insight.supported.hint')}
tone="info"
/>
<InsightCard
icon={<CheckCircle2 size={17} strokeWidth={2.5} />}
label={t('games.insight.connected')}
value={`${connectedCount}`}
hint={t('games.insight.connected.hint')}
tone={connectedCount > 0 ? 'success' : 'muted'}
/>
<InsightCard
icon={<Hourglass size={17} strokeWidth={2.5} />}
label={t('games.insight.live')}
value={
queuedCount > 0
? t('games.insight.queued', { n: queuedCount })
: t('games.subtitle.live', { n: liveCount })
}
hint={t('games.insight.live.hint')}
tone={
liveCount > 0 ? 'success' : queuedCount > 0 ? 'warning' : 'muted'
}
/>
</InsightGrid>
<SectionHeader title={t('games.section.supported')} />
<div className="space-y-4">
{games.map((g, i) => (
@@ -109,7 +147,11 @@ export default function GamesPage(): JSX.Element {
className="px-5 py-12 flex flex-col items-center gap-3 text-center text-text/55 text-[14px]"
role="status"
>
<Spinner size={22} className="text-accent" label={t('games.scanning')} />
<Spinner
size={22}
className="text-accent"
label={t('games.scanning')}
/>
{t('games.scanning')}
</div>
</Card>
@@ -221,7 +263,11 @@ function GameCard({
disabled={busy}
size="sm"
>
{busy ? <Spinner size={14} /> : <Trash2 size={14} strokeWidth={2.5} />}{' '}
{busy ? (
<Spinner size={14} />
) : (
<Trash2 size={14} strokeWidth={2.5} />
)}{' '}
{t('btn.disconnect')}
</Button>
)}

View File

@@ -1,8 +1,19 @@
import { useState } from 'react'
import { Plus, ChevronRight, UtensilsCrossed } from 'lucide-react'
import {
CalendarDays,
ChevronRight,
Clock,
Plus,
UtensilsCrossed
} from 'lucide-react'
import { AnimatePresence, motion } from 'framer-motion'
import { useAppStore } from '../store/appStore'
import { MealEditor, type MealDraft } from '../components/MealEditor'
import {
InsightCard,
InsightGrid,
PageHeader
} from '../components/PageScaffold'
import { Button } from '../components/ui/Button'
import { Switch } from '../components/ui/Switch'
import { Card, Row, SectionHeader } from '../components/ui/Card'
@@ -37,6 +48,8 @@ export default function Meals(): JSX.Element {
const ordered = [...meals].sort((a, b) =>
a.enabled === b.enabled ? 0 : a.enabled ? -1 : 1
)
const activeMeals = meals.filter((m) => m.enabled)
const nextMeal = getNextMealLabel(activeMeals)
async function addPreset(
preset: (typeof MEAL_PRESETS)[number]
@@ -53,24 +66,45 @@ export default function Meals(): JSX.Element {
return (
<div className="h-full overflow-y-auto">
<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-10 pt-8 pb-12">
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-8">
<div>
<div className="text-[14px] text-text/65 font-semibold">
{t('meals.kicker')}
</div>
<h1 className="font-serif text-[34px] sm:text-[40px] leading-[1.02] tracking-tight mt-1 font-bold">
{t('meals.title')}
</h1>
</div>
<Button
onClick={() => {
setEditing(null)
setEditorOpen(true)
}}
>
<Plus size={15} strokeWidth={2.5} /> {t('btn.add')}
</Button>
</div>
<PageHeader
kicker={t('meals.kicker')}
title={t('meals.title')}
subtitle={t('meals.subtitle')}
action={
<Button
onClick={() => {
setEditing(null)
setEditorOpen(true)
}}
>
<Plus size={15} strokeWidth={2.5} /> {t('btn.add')}
</Button>
}
/>
<InsightGrid>
<InsightCard
icon={<UtensilsCrossed size={17} strokeWidth={2.5} />}
label={t('meals.insight.active')}
value={`${activeMeals.length}/${meals.length}`}
hint={t('meals.insight.active.hint')}
tone={activeMeals.length > 0 ? 'success' : 'muted'}
/>
<InsightCard
icon={<Clock size={17} strokeWidth={2.5} />}
label={t('meals.insight.next')}
value={nextMeal ?? '—'}
hint={t('meals.insight.next.hint')}
tone={nextMeal ? 'accent' : 'muted'}
/>
<InsightCard
icon={<CalendarDays size={17} strokeWidth={2.5} />}
label={t('meals.insight.presets')}
value={`${MEAL_PRESETS.length}`}
hint={t('meals.insight.presets.hint')}
tone="info"
/>
</InsightGrid>
{/* Пресеты быстрого добавления */}
<SectionHeader title={t('meals.presets')} />
@@ -148,6 +182,25 @@ export default function Meals(): JSX.Element {
)
}
function getNextMealLabel(meals: Meal[]): string | null {
const today = new Date().getDay()
const now = new Date()
const nowMinutes = now.getHours() * 60 + now.getMinutes()
const candidates = meals
.filter((meal) => meal.days.length === 0 || meal.days.includes(today))
.map((meal) => {
const [hh, mm] = meal.time.split(':').map(Number)
return {
meal,
minutes: (hh || 0) * 60 + (mm || 0)
}
})
.filter((item) => item.minutes >= nowMinutes)
.sort((a, b) => a.minutes - b.minutes)
return candidates[0]?.meal.time ?? null
}
function MealRow({
meal,
last,

View File

@@ -1,8 +1,16 @@
import { useCallback, useEffect, useState } from 'react'
import { Copy, FolderOpen, RefreshCw } from 'lucide-react'
import {
Bell,
Copy,
FolderOpen,
Languages,
Palette,
RefreshCw
} from 'lucide-react'
import { useAppStore } from '../store/appStore'
import { Switch } from '../components/ui/Switch'
import { Button } from '../components/ui/Button'
import { InsightCard, InsightGrid } from '../components/PageScaffold'
import { Card, Row, SectionHeader } from '../components/ui/Card'
import { UpdaterCard } from '../components/UpdaterCard'
import { WhatsNewModal } from '../components/WhatsNewModal'
@@ -54,6 +62,30 @@ export default function SettingsPage(): JSX.Element {
</h1>
</div>
<InsightGrid>
<InsightCard
icon={<Bell size={17} strokeWidth={2.5} />}
label={t('settings.insight.mode')}
value={t(`settings.notification_mode.${settings.notificationMode}`)}
hint={t('settings.insight.mode.hint')}
tone={settings.soundEnabled ? 'success' : 'info'}
/>
<InsightCard
icon={<Palette size={17} strokeWidth={2.5} />}
label={t('settings.insight.theme')}
value={t(`settings.theme.${settings.theme}`)}
hint={t('settings.insight.theme.hint')}
tone="accent"
/>
<InsightCard
icon={<Languages size={17} strokeWidth={2.5} />}
label={t('settings.insight.language')}
value={t(`settings.language.${settings.language}`)}
hint={t('settings.insight.language.hint')}
tone="info"
/>
</InsightGrid>
<SectionHeader title={t('settings.section.language')} />
<Card className="mb-6">
<SelectRow

View File

@@ -21,6 +21,102 @@ export type ReleaseNoteItem = {
export type ReleaseNotes = Record<Language, ReleaseNoteItem[]>
export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
'0.6.4': {
ru: [
{
title: 'Новый видимый бренд “Разомнись”',
detail:
'Название стало короче и понятнее для русской аудитории: действие видно сразу.',
tag: 'new'
},
{
title: 'Сводки на каждом экране',
detail:
'Упражнения, питание, игры, челленджи и настройки теперь быстрее сканируются сверху.',
tag: 'new'
},
{
title: 'Улучшена структура вторичных страниц',
detail:
'Важные статусы вынесены выше списков, чтобы сразу видеть активность и проблемные места.',
tag: 'new'
}
],
en: [
{
title: 'New visible “Razomnis” brand',
detail:
'The name is shorter and more action-focused for the Russian audience.',
tag: 'new'
},
{
title: 'Overview cards on every screen',
detail:
'Exercises, meals, games, challenges and settings are easier to scan from the top.',
tag: 'new'
},
{
title: 'Secondary pages are more structured',
detail:
'Important statuses moved above long lists so active and risky areas are visible immediately.',
tag: 'new'
}
]
},
'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': {
ru: [
{
@@ -204,14 +300,12 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
en: [
{
title: 'Reminder categories',
detail:
'Beyond exercises — hydration, eye rest (20-20-20), posture.',
detail: 'Beyond exercises — hydration, eye rest (20-20-20), posture.',
tag: 'new'
},
{
title: 'Voice prompts',
detail:
'Speaks the exercise name and count. Toggle in Settings.',
detail: 'Speaks the exercise name and count. Toggle in Settings.',
tag: 'new'
},
{
@@ -255,7 +349,8 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
ru: [
{
title: 'Sandbox для окон',
detail: 'Окна изолированы на уровне OS — даже RCE в рендере не достанет main.',
detail:
'Окна изолированы на уровне OS — даже RCE в рендере не достанет main.',
tag: 'security'
},
{
@@ -282,7 +377,8 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
en: [
{
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'
},
{
@@ -311,24 +407,28 @@ export const RELEASE_NOTES: Record<string, ReleaseNotes> = {
ru: [
{
title: 'Фоновое скачивание апдейта',
detail: 'Можно уйти на Dashboard и заниматься — апдейт качается в фоне.',
detail:
'Можно уйти на Dashboard и заниматься — апдейт качается в фоне.',
tag: 'new'
},
{
title: 'Моментальный рестарт',
detail: 'Кнопка «Рестарт» — ~1-2 сек до открытия новой версии, без диалогов NSIS.',
detail:
'Кнопка «Рестарт» — ~1-2 сек до открытия новой версии, без диалогов NSIS.',
tag: 'new'
}
],
en: [
{
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'
},
{
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'
}
]
@@ -352,7 +452,9 @@ export function unseenVersions(
// явный «What's new» из Settings.
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] {