diff --git a/frontend/chart-preview.html b/frontend/chart-preview.html index 91282db..24b112e 100644 --- a/frontend/chart-preview.html +++ b/frontend/chart-preview.html @@ -20,13 +20,15 @@

📈 Жим штанги лёжа — рабочий максимум важнее числа подходов

Вершина линии — главный вес дня «вес × повторы». 12.11: 100×1 (шесть подходов), 19.11: 100×2 (пять подходов, разминочных меньше) — вершина зелёная: вес тот же, повторов больше, это прогресс, хотя подходов меньше. Тусклые точки — разминочные и остальные подходы.

- + +

📈 Жим гантелей на лавке (30/45 — одна группа вариантов)

Прогрессия 20→28 кг; 17.11 после паузы — красный откат, это тоже видно.

- + +
@@ -42,6 +44,7 @@ localStorage.setItem('gym_tracker_v7_guest', JSON.stringify(window.GYM_DEMO_SEED import { loadState } from './js/state.js'; import { drawExerciseProgress } from './js/render/dashboard.js'; import './js/modals/chart-modal.js'; +import './js/modals/exercise-summary.js'; loadState(); // state наполняется из localStorage только этим вызовом (как в app.js) drawExerciseProgress(document.getElementById('chart-barbell'), 'Жим штанги лёжа'); diff --git a/frontend/js/app.js b/frontend/js/app.js index 545e940..68cb558 100644 --- a/frontend/js/app.js +++ b/frontend/js/app.js @@ -40,6 +40,7 @@ import "./modals/edit-workout-date-modal.js"; import "./modals/client-select-modal.js"; import "./modals/group-modal.js"; import "./modals/chart-modal.js"; +import "./modals/exercise-summary.js"; function renderHeader() { const user = getActiveUser(); diff --git a/frontend/js/logic/exercise.js b/frontend/js/logic/exercise.js index 82624d4..d111086 100644 --- a/frontend/js/logic/exercise.js +++ b/frontend/js/logic/exercise.js @@ -195,6 +195,105 @@ export function getExerciseChart(exerciseName, clientId = null) { return points; } +/** + * Сводка по упражнению (все завершённые тренировки): рекорды, средние за + * тренировку и за всё время, синергичные упражнения (делались в тот же день) + * и максимальный вес среди них. Варианты из одной группы считаются вместе. + */ +export function getExerciseSummary(exerciseName, clientId = null) { + const variantNames = refVariantNames(exerciseName); + const targetClient = normalizeClientId(clientId); + + let best = null; // {weight, reps, date, variant} + let maxSetsDay = null; // {count, date} + let totalSets = 0, totalVolume = 0, totalReps = 0, totalRating = 0; + let sumTopWeight = 0, days = 0; + let from = null, to = null; + const variantsSeen = new Set(); + const synergic = new Map(); // нормализованное имя -> {name, count, best} + + for (const w of state.workouts) { + if (!isSameClient(w.client_id, targetClient)) continue; + if (!w.endTime) continue; + const hits = (w.exercises || []).filter(ex => variantNames.has(normalizeName(ex.name))); + if (!hits.length) continue; + + days++; + if (!from || new Date(w.startTime) < new Date(from)) from = w.startTime; + if (!to || new Date(w.startTime) > new Date(to)) to = w.startTime; + + let daySets = 0, dayVolume = 0, dayTop = 0; + for (const ex of hits) { + variantsSeen.add(ex.name); + for (const s of ex.sets || []) { + const parts = s.isDropset && s.subSets?.length ? s.subSets : [s]; + for (const p of parts) { + const wgt = parseFloat(p.weight) || 0; + const rps = parseInt(p.reps) || 0; + if (!wgt && !rps) continue; + daySets++; totalSets++; + dayVolume += wgt * rps; totalVolume += wgt * rps; + totalReps += rps; + if ((parseFloat(s.rating) || 5) > 0) totalRating += (parseFloat(s.rating) || 5); + if (wgt > dayTop) dayTop = wgt; + if (!best || wgt > best.weight || (wgt === best.weight && rps > best.reps)) { + best = { weight: wgt, reps: rps, date: w.startTime, variant: ex.name }; + } + } + } + } + sumTopWeight += dayTop; + if (!maxSetsDay || daySets > maxSetsDay.count) maxSetsDay = { count: daySets, date: w.startTime }; + + // Синергичные: другие упражнения этих же тренировок + for (const ex of w.exercises || []) { + if (variantNames.has(normalizeName(ex.name))) continue; + const key = normalizeName(ex.name); + const rec = synergic.get(key) || { name: ex.name, count: 0, best: null }; + rec.count++; + for (const s of ex.sets || []) { + const parts = s.isDropset && s.subSets?.length ? s.subSets : [s]; + for (const p of parts) { + const wgt = parseFloat(p.weight) || 0; + const rps = parseInt(p.reps) || 0; + if (!wgt) continue; + if (!rec.best || wgt > rec.best.weight || (wgt === rec.best.weight && rps > rec.best.reps)) { + rec.best = { weight: wgt, reps: rps, date: w.startTime }; + } + } + } + synergic.set(key, rec); + } + } + + const synergicList = Array.from(synergic.values()) + .sort((a, b) => b.count - a.count || (b.best?.weight || 0) - (a.best?.weight || 0)); + let synergicBest = null; + for (const s of synergicList) { + if (s.best && (!synergicBest || s.best.weight > synergicBest.weight)) { + synergicBest = { ...s.best, name: s.name }; + } + } + + return { + days, + variants: Array.from(variantsSeen), + period: from ? { from, to } : null, + best, + maxSetsDay, + totals: { sets: totalSets, volume: totalVolume, reps: totalReps }, + avg: days ? { + topWeight: Math.round(sumTopWeight / days * 10) / 10, + sets: Math.round(totalSets / days * 10) / 10, + volume: Math.round(totalVolume / days), + reps: Math.round(totalReps / days), + rating: Math.round(totalRating / totalSets * 10) / 10 || 0, + } : null, + synergic: synergicList, + synergicBest, + }; +} + window.EL = { addExercise, toggleExercise, diff --git a/frontend/js/modals/chart-modal.js b/frontend/js/modals/chart-modal.js index 793ffc3..12b21ed 100644 --- a/frontend/js/modals/chart-modal.js +++ b/frontend/js/modals/chart-modal.js @@ -39,7 +39,7 @@ export function showChartDialog(exerciseName, clientId = null) { const classes = points.map((_, i) => cls(i)); const topLabel = p => byWeight ? `${dayTop(p)}×${dayTopReps(p)}` : `${dayTop(p)}`; - const W = 320, H = 200, padL = 32, padR = 12, padT = 22, padB = 34; + const W = 320, H = 210, padL = 32, padR = 12, padT = 22, padB = 42; const n = points.length; const x = i => n === 1 ? (padL + W - padR) / 2 : padL + (W - padL - padR) * i / (n - 1); @@ -82,17 +82,17 @@ export function showChartDialog(exerciseName, clientId = null) { : '') ).join(''); + const fmt = d => new Date(d).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }); + const counts = points.map((p, i) => (n <= 12 || i % 2 === 0) - ? `×${p.sets.length}` + ? `×${p.sets.length}` + + `${fmt(p.date)}` : '' ).join(''); - const fmt = d => new Date(d).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }); - showModal(` -
главное — рабочий максимум «вес × повторы»: зелёный — прогресс (вес выше или тот же вес и больше повторов), красный — откат; тусклые точки — остальные подходы, ×N — их число
@@ -102,10 +102,8 @@ export function showChartDialog(exerciseName, clientId = null) { ${segs.join('')} ${verts} ${counts} - ${fmt(points[0].date)} - ${n > 1 && new Date(points[n - 1].date) - new Date(points[0].date) > 864e5 - ? `${fmt(points[n - 1].date)}` : ''} +
линия — рабочий максимум «вес × повторы»: зелёный — прогресс (вес выше или тот же вес и больше повторов), красный — откат; тусклые точки — остальные подходы, ×N — их число
${points.slice(-5).reverse().map((p, k) => { const i = points.length - 1 - k; return `
${new Date(p.date).toLocaleDateString('ru-RU')}` + @@ -113,6 +111,10 @@ export function showChartDialog(exerciseName, clientId = null) { `${p.sets.map(s => byWeight ? s.weight + '×' + s.reps : s.reps).join(' ')}` + ` · ${p.sets.length} подх.
`; }).join('')}
+
+ +
`); } diff --git a/frontend/js/modals/exercise-summary.js b/frontend/js/modals/exercise-summary.js new file mode 100644 index 0000000..9fd46d2 --- /dev/null +++ b/frontend/js/modals/exercise-summary.js @@ -0,0 +1,79 @@ +import { state } from '../state.js'; +import { escapeHtml } from '../utils.js'; +import { showModal, closeModal } from './modal-base.js'; +import { getExerciseSummary } from '../logic/exercise.js'; +import { showChartDialog } from './chart-modal.js'; + +const fmtDate = d => new Date(d).toLocaleDateString('ru-RU'); + +/** + * Страница-сводка по упражнению: рекорды, средние за тренировку и за всё + * время, синергичные упражнения и максимальный вес среди них. + */ +export function showExerciseSummary(exerciseName, clientId = null) { + const s = getExerciseSummary(exerciseName, clientId); + + if (!s.days) { + showModal(` + +
Нет завершённых тренировок с этим упражнением.
+ `); + return; + } + + const card = (label, value, sub = '') => + `
${value}
${label}
` + + (sub ? `
${sub}
` : '') + `
`; + + const synergRows = s.synergic.slice(0, 8).map(x => + `
${x.count} трен.` + + `${escapeHtml(x.name)}` + + `${x.best ? x.best.weight + '×' + x.best.reps : '—'}
` + ).join('') || '
Пока нет данных по соседним упражнениям.
'; + + showModal(` + +
+ ${s.days} тренир.` + + (s.period ? ` · ${fmtDate(s.period.from)} — ${fmtDate(s.period.to)}` : '') + + (s.variants.length > 1 ? ` · варианты: ${s.variants.map(escapeHtml).join(', ')}` : '') + ` +
+ +
+ ${card('рабочий максимум', s.best ? `${s.best.weight}×${s.best.reps}` : '—', + s.best ? `${fmtDate(s.best.date)} · ${escapeHtml(s.best.variant)}` : '')} + ${card('максимум подходов за тренировку', s.maxSetsDay ? `×${s.maxSetsDay.count}` : '—', + s.maxSetsDay ? fmtDate(s.maxSetsDay.date) : '')} + ${card('средний рабочий вес', s.avg ? `${s.avg.topWeight} кг` : '—', 'за тренировку')} + ${card('средне подходов', s.avg ? `×${s.avg.sets}` : '—', `и ${s.avg ? s.avg.reps : 0} повт. за тренировку`)} + ${card('средний объём', s.avg ? `${s.avg.volume} кг` : '—', 'за тренировку')} + ${card('за всё время', `${s.totals.volume} кг`, `${s.totals.sets} подх. · ${s.totals.reps} повт.` + + (s.avg && s.avg.rating ? ` · средняя оценка ${s.avg.rating}` : ''))} +
+ +

🤝 Синергичные упражнения (делались в тот же день)

+
${synergRows}
+ ${s.synergicBest ? `
Максимум среди синергичных: ${escapeHtml(s.synergicBest.name)} ${s.synergicBest.weight}×${s.synergicBest.reps} (${fmtDate(s.synergicBest.date)})
` : ''} + +
+ +
+ `); +} + +// Кнопка «📋 Сводка» в графике: имя из data-атрибута +export function showSummaryFromBtn(btn) { + const name = btn.dataset.ex; + const w = state.workouts.find(w => (w.exercises || []).some(e => e.name === name)); + showExerciseSummary(name, w ? w.client_id : null); +} + +window.EM = { + showSummaryDialog: (name) => showExerciseSummary(name), + showSummaryFromBtn, + showChartFrom: (btn) => showChartDialog(btn.dataset.ex), +}; diff --git a/frontend/js/render/dashboard-screen.js b/frontend/js/render/dashboard-screen.js index 7eb520a..38de9b2 100644 --- a/frontend/js/render/dashboard-screen.js +++ b/frontend/js/render/dashboard-screen.js @@ -1,7 +1,11 @@ // frontend/js/render/dashboard-screen.js import { state } from '../state.js'; +import { escapeHtml } from '../utils.js'; import { drawExerciseProgress, drawBodyMetricsGraph } from './dashboard.js'; +import { showExerciseSummary } from '../modals/exercise-summary.js'; + +const CHART_EX_KEY = 'gym_dash_char…ise'; export function renderDashboard() { const app = document.getElementById('app'); @@ -20,10 +24,13 @@ export function renderDashboard() { - + +
+ +

Главное — рабочий максимум «вес × повторы»: зелёный — прогресс (вес выше или тот же вес и больше повторов), красный — откат. Тусклые точки — остальные подходы, «×N» — их число. Последние 10 тренировок.

@@ -53,6 +60,8 @@ export function renderDashboard() { updateExerciseChart: () => { const select = document.getElementById('dash-ex-select'); const canvas = document.getElementById('chart-exercise'); + // Выбор упражнения запоминается и восстанавливается при следующем открытии + localStorage.setItem(CHART_EX_KEY, select.value); if (select.value) { drawExerciseProgress(canvas, select.value); } else { @@ -63,6 +72,11 @@ export function renderDashboard() { ctx.fillText('Выберите упражнение выше', canvas.width/2, canvas.height/2); } }, + showExSummary: () => { + const select = document.getElementById('dash-ex-select'); + if (!select.value) { alert('Сначала выберите упражнение'); return; } + showExerciseSummary(select.value); + }, updateBodyChart: () => { const clientSel = document.getElementById('dash-client-select'); const metricSel = document.getElementById('dash-metric-select'); @@ -77,7 +91,10 @@ export function renderDashboard() { } }; - // Первичная отрисовка (пустые состояния) + // Первичная отрисовка: восстанавливаем закреплённый выбор упражнения + const saved = localStorage.getItem(CHART_EX_KEY); + const exSelect = document.getElementById('dash-ex-select'); + if (saved && Array.from(exSelect.options).some(o => o.value === saved)) exSelect.value = saved; DashboardLogic.updateExerciseChart(); if(state.metricTypes.length > 0) { document.getElementById('dash-metric-select').value = state.metricTypes[0].id; diff --git a/frontend/js/render/dashboard.js b/frontend/js/render/dashboard.js index 9378b1a..fdca462 100644 --- a/frontend/js/render/dashboard.js +++ b/frontend/js/render/dashboard.js @@ -27,7 +27,7 @@ export function drawExerciseProgress(canvas, exerciseName) { const maxWeight = Math.max(...days.map(d => d.max), 1); - const padding = { top: 26, right: 14, bottom: 34, left: 44 }; + const padding = { top: 14, right: 14, bottom: 58, left: 44 }; const chartW = width - padding.left - padding.right; const chartH = height - padding.top - padding.bottom; @@ -88,34 +88,28 @@ export function drawExerciseProgress(canvas, exerciseName) { ctx.stroke(); if (n <= 10 || i >= n - 4 || classes[i] !== 'flat') { ctx.fillStyle = COLORS[classes[i]]; - ctx.font = 'bold 11px sans-serif'; + ctx.font = 'bold 12px sans-serif'; ctx.textAlign = 'center'; - ctx.fillText(`${d.max}×${d.topReps || ''}`, px, y(d.max) - 7); + ctx.fillText(`${d.max}×${d.topReps || ''}`, px, y(d.max) - 8); } - // Количество подходов (выносливость) - if (n <= 12 || i % 2 === 0) { - ctx.fillStyle = '#b0b0b0'; - ctx.font = '9px sans-serif'; + // Дата под каждой точкой оси X и количество подходов (выносливость) + if (n <= 10 || i % 2 === 0) { + ctx.fillStyle = '#d5d5d5'; + ctx.font = '10px sans-serif'; ctx.textAlign = 'center'; - ctx.fillText('×' + d.sets.length, px, height - padding.bottom + 12); + ctx.fillText(formatShortDate(d.date.toISOString()), px, height - padding.bottom + 15); + ctx.fillStyle = '#b0b0b0'; + ctx.font = '10px sans-serif'; + ctx.fillText('×' + d.sets.length, px, height - padding.bottom + 29); } }); - // Даты первой и последней тренировки - ctx.fillStyle = '#b0b0b0'; - ctx.font = '10px sans-serif'; - ctx.textAlign = 'left'; - ctx.fillText(formatShortDate(days[0].date.toISOString()), padding.left, height - 6); - if (n > 1) { - ctx.textAlign = 'right'; - ctx.fillText(formatShortDate(days[n - 1].date.toISOString()), width - padding.right, height - 6); - } - + // Легенда — внизу, под датами drawLegend(ctx, width, [ { color: '#3ddc55', label: 'рабочий максимум: зелёный — прогресс, красный — откат' }, { color: 'rgba(199, 146, 255, 0.55)', label: 'тусклая точка = подход (размер = повторы)' }, - ]); + ], height - 8); } /** @@ -291,8 +285,8 @@ function drawGridAndAxes(ctx, pad, cw, ch, maxY, maxXAxisLabel, yAxisLabel) { ctx.stroke(); // Подписи Y - ctx.fillStyle = '#b0b0b0'; - ctx.font = '10px sans-serif'; + ctx.fillStyle = '#c9c9c9'; + ctx.font = '11px sans-serif'; ctx.textAlign = 'right'; for(let i=0; i<=4; i++) { const val = (maxY * i / 4).toFixed(0); @@ -339,15 +333,16 @@ function drawLineChart(ctx, data, pad, cw, ch, maxY, getValueFn, color, lineWidt } -function drawLegend(ctx, width, items) { - ctx.font = '10px sans-serif'; +function drawLegend(ctx, width, items, y) { + // y — базовая линия текста (легенда внизу); квадрат чуть выше текста + ctx.font = '11px sans-serif'; ctx.textAlign = 'left'; let xOffset = 10; items.forEach(item => { ctx.fillStyle = item.color; - ctx.fillRect(xOffset, 10, 10, 10); + ctx.fillRect(xOffset, y - 9, 10, 10); ctx.fillStyle = '#fff'; - ctx.fillText(item.label, xOffset + 15, 19); + ctx.fillText(item.label, xOffset + 15, y); xOffset += ctx.measureText(item.label).width + 30; }); } diff --git a/frontend/styles/components.css b/frontend/styles/components.css index 89e7b27..cd79fa6 100644 --- a/frontend/styles/components.css +++ b/frontend/styles/components.css @@ -159,5 +159,14 @@ textarea { resize: vertical; min-height: 60px; } .chart-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .chart-sets { flex: 1; min-width: 0; text-align: right; color: var(--text-secondary, #888); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .chart-val { font-weight: 600; flex: 0 0 auto; } -.chart-count { fill: #c9c9c9; font-size: 9.5px; } +.chart-count { fill: #c9c9c9; font-size: 10px; } +.chart-date-lab { fill: #d5d5d5; font-size: 10px; } .chart-count-num { color: var(--accent); } +/* Сводка по упражнению */ +.sum-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; margin-top: 10px; } +@media (min-width: 480px) { .sum-grid { grid-template-columns: repeat(3, 1fr); } } +.sum-card { background: var(--card-bg, rgba(255,255,255,0.04)); border: 1px solid var(--border); border-radius: 10px; padding: 8px 10px; } +.sum-value { font-size: 1.05rem; font-weight: 700; } +.sum-label { font-size: 0.72rem; color: var(--text-secondary, #888); margin-top: 2px; } +.sum-sub { font-size: 0.68rem; color: var(--text-secondary, #888); margin-top: 2px; } +.chart-legend-bottom { margin-top: 2px; }