feat(dashboard): даты по всей оси X, легенда вниз, крупнее шрифты, запоминаемый выбор упражнения, сводка по упражнению с синергичными

This commit is contained in:
Иван Овчинников
2026-11-20 07:47:39 +03:00
parent 97176ed90e
commit 7343a950f8
8 changed files with 244 additions and 39 deletions
+1
View File
@@ -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();
+99
View File
@@ -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,
+10 -8
View File
@@ -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)
? `<text x="${x(i).toFixed(1)}" y="${H - 16}" text-anchor="middle" class="chart-label chart-count">×${p.sets.length}</text>`
? `<text x="${x(i).toFixed(1)}" y="${H - 16}" text-anchor="middle" class="chart-label chart-count">×${p.sets.length}</text>` +
`<text x="${x(i).toFixed(1)}" y="${H - 4}" text-anchor="middle" class="chart-label chart-date-lab">${fmt(p.date)}</text>`
: ''
).join('');
const fmt = d => new Date(d).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' });
showModal(`
<div class="modal-header"><span class="modal-title">📈 ${escapeHtml(exerciseName)}</span><button class="btn-icon" onclick="closeModal()">✕</button></div>
<div class="chart-sub">главное — рабочий максимум «вес × повторы»: <b class="chart-up">зелёный — прогресс</b> (вес выше или тот же вес и больше повторов), <b class="chart-down">красный — откат</b>; тусклые точки — остальные подходы, ×N — их число</div>
<svg class="chart-svg" viewBox="0 0 ${W} ${H}">
<line x1="${padL}" y1="${y(vMin).toFixed(1)}" x2="${W - padR}" y2="${y(vMin).toFixed(1)}" class="chart-axis"/>
<line x1="${padL}" y1="${y(vMax).toFixed(1)}" x2="${W - padR}" y2="${y(vMax).toFixed(1)}" class="chart-axis"/>
@@ -102,10 +102,8 @@ export function showChartDialog(exerciseName, clientId = null) {
${segs.join('')}
${verts}
${counts}
<text x="${padL}" y="${H - 4}" class="chart-label">${fmt(points[0].date)}</text>
${n > 1 && new Date(points[n - 1].date) - new Date(points[0].date) > 864e5
? `<text x="${W - padR}" y="${H - 4}" text-anchor="end" class="chart-label">${fmt(points[n - 1].date)}</text>` : ''}
</svg>
<div class="chart-sub chart-legend-bottom">линия — рабочий максимум «вес × повторы»: <b class="chart-up">зелёный — прогресс</b> (вес выше или тот же вес и больше повторов), <b class="chart-down">красный — откат</b>; тусклые точки — остальные подходы, ×N — их число</div>
<div class="chart-list">${points.slice(-5).reverse().map((p, k) => {
const i = points.length - 1 - k;
return `<div class="chart-row"><span class="chart-date">${new Date(p.date).toLocaleDateString('ru-RU')}</span>` +
@@ -113,6 +111,10 @@ export function showChartDialog(exerciseName, clientId = null) {
`<span class="chart-sets">${p.sets.map(s => byWeight ? s.weight + '×' + s.reps : s.reps).join(' ')}` +
` · <span class="chart-count-num">${p.sets.length}</span> подх.</span></div>`;
}).join('')}</div>
<div style="display:flex; gap:8px; margin-top:10px">
<button class="btn btn-small btn-secondary" data-ex="${escapeHtml(exerciseName)}"
onclick="EM.showSummaryFromBtn(this)">📋 Сводка по упражнению</button>
</div>
`);
}
+79
View File
@@ -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(`
<div class="modal-header"><span class="modal-title">${escapeHtml(exerciseName)}</span><button class="btn-icon" onclick="closeModal()">✕</button></div>
<div class="history-hint" style="margin:8px 0">Нет завершённых тренировок с этим упражнением.</div>
`);
return;
}
const card = (label, value, sub = '') =>
`<div class="sum-card"><div class="sum-value">${value}</div><div class="sum-label">${label}</div>` +
(sub ? `<div class="sum-sub">${sub}</div>` : '') + `</div>`;
const synergRows = s.synergic.slice(0, 8).map(x =>
`<div class="chart-row"><span class="chart-date">${x.count} трен.</span>` +
`<span class="chart-name">${escapeHtml(x.name)}</span>` +
`<span class="chart-val">${x.best ? x.best.weight + '×' + x.best.reps : '—'}</span></div>`
).join('') || '<div class="history-hint">Пока нет данных по соседним упражнениям.</div>';
showModal(`
<div class="modal-header">
<span class="modal-title">📋 ${escapeHtml(exerciseName)}</span>
<button class="btn-icon" onclick="closeModal()">✕</button>
</div>
<div class="chart-sub">
${s.days} тренир.` +
(s.period ? ` · ${fmtDate(s.period.from)} — ${fmtDate(s.period.to)}` : '') +
(s.variants.length > 1 ? ` · варианты: ${s.variants.map(escapeHtml).join(', ')}` : '') + `
</div>
<div class="sum-grid">
${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}` : ''))}
</div>
<h4 style="margin:12px 0 4px">🤝 Синергичные упражнения <span class="text-muted text-small">(делались в тот же день)</span></h4>
<div class="chart-list">${synergRows}</div>
${s.synergicBest ? `<div class="chart-sub" style="margin-top:6px">Максимум среди синергичных: <b>${escapeHtml(s.synergicBest.name)} ${s.synergicBest.weight}×${s.synergicBest.reps}</b> (${fmtDate(s.synergicBest.date)})</div>` : ''}
<div style="display:flex; gap:8px; margin-top:12px">
<button class="btn btn-small btn-secondary" data-ex="${escapeHtml(exerciseName)}"
onclick="EM.showChartFrom(this)">📈 График</button>
</div>
`);
}
// Кнопка «📋 Сводка» в графике: имя из 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),
};
+20 -3
View File
@@ -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() {
<label>Выберите упражнение</label>
<select id="dash-ex-select" onchange="DashboardLogic.updateExerciseChart()">
<option value="">— Выберите —</option>
${getUniqueExercises().map(ex => `<option value="${ex}">${ex}</option>`).join('')}
${getUniqueExercises().map(ex => `<option value="${escapeHtml(ex)}">${escapeHtml(ex)}</option>`).join('')}
</select>
</div>
<canvas id="chart-exercise" width="400" height="200" style="width:100%; background:#1e1e1e; border-radius:8px;"></canvas>
<canvas id="chart-exercise" width="400" height="250" style="width:100%; background:#1e1e1e; border-radius:8px;"></canvas>
<div style="margin-top:8px">
<button class="btn btn-small btn-secondary" onclick="DashboardLogic.showExSummary()">📋 Сводка по упражнению</button>
</div>
<p class="text-muted text-small mt-10">Главное — рабочий максимум «вес × повторы»: зелёный — прогресс (вес выше или тот же вес и больше повторов), красный — откат. Тусклые точки — остальные подходы, «×N» — их число. Последние 10 тренировок.</p>
</div>
@@ -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;
+20 -25
View File
@@ -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;
});
}