Files
gym-bro/frontend/js/render/dashboard.js
T

368 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// frontend/js/render/dashboard.js
import { state } from '../state.js';
import { formatDate } from '../utils.js';
/**
* Рисует график прогресса упражнения: каждая точка — подход (вес по вертикали,
* размер — повторения), фиолетовая линия — максимальный вес за тренировку
* (силовая прогрессия), «×N» под осью — количество подходов (выносливость).
* @param {HTMLCanvasElement} canvas
* @param {string} exerciseName
*/
export function drawExerciseProgress(canvas, exerciseName) {
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
const days = getExerciseProgressData(exerciseName);
if (days.length === 0) {
drawEmptyState(ctx, width, height, "Нет завершённых тренировок\nс этим упражнением");
return;
}
const maxWeight = Math.max(...days.map(d => d.max), 1);
const padding = { top: 26, right: 14, bottom: 34, left: 44 };
const chartW = width - padding.left - padding.right;
const chartH = height - padding.top - padding.bottom;
drawGridAndAxes(ctx, padding, chartW, chartH, maxWeight, 'Дата', 'Вес (кг)');
const n = days.length;
const x = i => n === 1 ? padding.left + chartW / 2
: padding.left + (chartW * i) / (n - 1);
const y = v => padding.top + chartH - (v / maxWeight) * chartH;
const maxReps = Math.max(1, ...days.flatMap(d => d.sets.map(s => s.reps)));
// Соединительная линия максимальных весов (силовая прогрессия)
if (n > 1) {
ctx.strokeStyle = '#bb86fc';
ctx.lineWidth = 2;
ctx.beginPath();
days.forEach((d, i) => {
const px = x(i), py = y(d.max);
i === 0 ? ctx.moveTo(px, py) : ctx.lineTo(px, py);
});
ctx.stroke();
}
days.forEach((d, i) => {
const px = x(i);
// Подходы дня: точки по весу, разнесены вокруг колонки дня
const spread = d.sets.length > 1 ? Math.min(11, chartW / (3 * n)) : 0;
d.sets.forEach((s, k) => {
const dx = d.sets.length > 1 ? -spread + (2 * spread * k) / (d.sets.length - 1) : 0;
const r = 2.2 + 3.2 * Math.min(1, s.reps / maxReps);
ctx.beginPath();
ctx.fillStyle = s.weight === d.max ? '#bb86fc' : 'rgba(187, 134, 252, 0.45)';
ctx.arc(px + dx, y(s.weight), r, 0, Math.PI * 2);
ctx.fill();
if (s.weight === d.max) {
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1.2;
ctx.stroke();
}
});
// Количество подходов (выносливость)
if (n <= 12 || i % 2 === 0) {
ctx.fillStyle = '#b0b0b0';
ctx.font = '9px sans-serif';
ctx.textAlign = 'center';
ctx.fillText('×' + d.sets.length, px, height - padding.bottom + 12);
}
});
// Даты первой и последней тренировки
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: '#bb86fc', label: 'макс. вес за тренировку' },
{ color: 'rgba(187, 134, 252, 0.45)', label: 'точка = подход (размер = повторы)' },
]);
}
/**
* Данные графика: по каждой завершённой тренировке — список подходов
* (дроп-сеты развёрнуты), максимальный вес и общий объём.
* @returns {{date: Date, sets: {weight:number, reps:number}[], max:number, totalVolume:number}[]}
*/
export function getExerciseProgressData(exerciseName) {
const normalized = exerciseName.trim().toLowerCase();
const days = [];
state.workouts.forEach(w => {
if (!w.endTime) return; // активная тренировка — не результат
(w.exercises || []).forEach(ex => {
if (ex.name.trim().toLowerCase() !== normalized) return;
const sets = [];
(ex.sets || []).forEach(s => {
const parts = s.isDropset && s.subSets?.length ? s.subSets : [s];
parts.forEach(p => {
const weight = parseFloat(p.weight) || 0;
const reps = parseInt(p.reps) || 0;
if (weight > 0 || reps > 0) sets.push({ weight, reps });
});
});
if (sets.length === 0) return;
days.push({
date: new Date(w.startTime),
sets,
max: Math.max(...sets.map(s => s.weight)),
totalVolume: sets.reduce((a, s) => a + s.weight * s.reps, 0),
});
});
});
days.sort((a, b) => a.date - b.date);
return days.slice(-10);
}
/**
* Рисует график динамики телесных замеров
* @param {HTMLCanvasElement} canvas
* @param {number|null} clientId - null для личных замеров
* @param {number} metricTypeId - ID типа замера (например, вес)
*/
export function drawBodyMetricsGraph(canvas, clientId, metricTypeId) {
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
// Фильтруем замеры
const metrics = state.bodyMetrics
.filter(m => m.client_id == clientId)
.sort((a, b) => new Date(a.date) - new Date(b.date));
// Извлекаем значения конкретного типа
const dataPoints = [];
metrics.forEach(m => {
const valObj = m.values?.find(v => v.metric_type_id == metricTypeId);
if (valObj && valObj.value !== undefined && valObj.value !== null) {
dataPoints.push({ date: new Date(m.date), value: parseFloat(valObj.value) });
}
});
if (dataPoints.length < 2) {
drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 замера");
return;
}
const minVal = Math.min(...dataPoints.map(p => p.value));
const maxVal = Math.max(...dataPoints.map(p => p.value));
const range = maxVal - minVal || 1; // Защита от деления на ноль
const padding = { top: 20, right: 20, bottom: 30, left: 40 };
const chartW = width - padding.left - padding.right;
const chartH = height - padding.top - padding.bottom;
// Простая ось Y (значения)
ctx.strokeStyle = '#333';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding.left, padding.top);
ctx.lineTo(padding.left, height - padding.bottom);
ctx.stroke();
// Подписи осей Y
ctx.fillStyle = '#b0b0b0';
ctx.font = '10px sans-serif';
ctx.textAlign = 'right';
for (let i = 0; i <= 4; i++) {
const y = height - padding.bottom - (i / 4) * chartH;
const val = minVal + (range * i / 4);
ctx.fillText(val.toFixed(1), padding.left - 5, y + 3);
// Горизонтальная линия сетки
ctx.strokeStyle = '#2c2c2c';
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(width - padding.right, y);
ctx.stroke();
}
// Рисуем точку начала и конца по X (дата)
const firstDate = dataPoints[0].date.getTime();
const lastDate = dataPoints[dataPoints.length - 1].date.getTime();
const timeRange = lastDate - firstDate || 1;
ctx.strokeStyle = '#bb86fc'; // Цвет линии графика
ctx.lineWidth = 2;
ctx.beginPath();
dataPoints.forEach((p, index) => {
const x = padding.left + ((p.date.getTime() - firstDate) / timeRange) * chartW;
const y = height - padding.bottom - ((p.value - minVal) / range) * chartH;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
// Точки
ctx.fillStyle = '#fff';
ctx.fillRect(x - 2, y - 2, 4, 4);
});
ctx.stroke();
// Подпись даты слева и справа
ctx.fillStyle = '#b0b0b0';
ctx.textAlign = 'left';
ctx.fillText(formatShortDate(dataPoints[0].date.toISOString()), padding.left, height - 10);
ctx.textAlign = 'right';
ctx.fillText(formatShortDate(dataPoints[dataPoints.length-1].date.toISOString()), width - padding.right, height - 10);
}
// --- Вспомогательные функции ---
function getExerciseHistoryData(name) {
const normalized = name.trim().toLowerCase();
const history = [];
// Собираем из всех тренировок текущего пользователя (или клиента, если режим тренера реализован глобально)
// Здесь упрощение: берем все тренировки из state.workouts
state.workouts.forEach(w => {
w.exercises.forEach(ex => {
if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) {
history.push({
date: new Date(w.startTime),
sets: ex.sets
});
}
});
});
// Сортируем по дате
history.sort((a, b) => a.date - b.date);
return history.slice(-10); // Берем последние 10 тренировок для читаемости
}
function getMaxWeightInSet(historyItem) {
let max = 0;
historyItem.sets.forEach(s => {
if (s.isDropset && s.subSets) {
s.subSets.forEach(ss => { if (ss.weight > max) max = ss.weight; });
} else if (s.weight > max) {
max = s.weight;
}
});
return max;
}
function getMaxRepsInSet(historyItem) {
let max = 0;
historyItem.sets.forEach(s => {
if (s.isDropset && s.subSets) {
s.subSets.forEach(ss => { if (ss.reps > max) max = ss.reps; });
} else if (s.reps > max) {
max = s.reps;
}
});
return max;
}
function drawGridAndAxes(ctx, pad, cw, ch, maxY, maxXAxisLabel, yAxisLabel) {
ctx.strokeStyle = '#333';
ctx.lineWidth = 1;
// Ось Y
ctx.beginPath();
ctx.moveTo(pad.left, pad.top);
ctx.lineTo(pad.left, ch + pad.top);
ctx.stroke();
// Ось X
ctx.beginPath();
ctx.moveTo(pad.left, ch + pad.top);
ctx.lineTo(cw + pad.left, ch + pad.top);
ctx.stroke();
// Подписи Y
ctx.fillStyle = '#b0b0b0';
ctx.font = '10px sans-serif';
ctx.textAlign = 'right';
for(let i=0; i<=4; i++) {
const val = (maxY * i / 4).toFixed(0);
const y = ch + pad.top - (ch * i / 4);
ctx.fillText(val, pad.left - 5, y + 3);
// Сетка
ctx.strokeStyle = '#2c2c2c';
ctx.beginPath();
ctx.moveTo(pad.left, y);
ctx.lineTo(cw + pad.left, y);
ctx.stroke();
}
// Заголовок оси Y
ctx.save();
ctx.translate(15, ch/2 + pad.top);
ctx.rotate(-Math.PI/2);
ctx.textAlign = 'center';
ctx.fillText(yAxisLabel, 0, 0);
ctx.restore();
}
function drawLineChart(ctx, data, pad, cw, ch, maxY, getValueFn, color, lineWidth) {
if (!data.length) return;
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.beginPath();
data.forEach((item, index) => {
const val = getValueFn(item);
const x = pad.left + (index / (data.length - 1)) * cw;
const y = pad.top + ch - (val / maxY) * ch;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
// Точка
ctx.fillStyle = '#fff';
ctx.fillRect(x-2, y-2, 4, 4);
});
ctx.stroke();
}
function drawLegend(ctx, width, items) {
ctx.font = '10px sans-serif';
ctx.textAlign = 'left';
let xOffset = 10;
items.forEach(item => {
ctx.fillStyle = item.color;
ctx.fillRect(xOffset, 10, 10, 10);
ctx.fillStyle = '#fff';
ctx.fillText(item.label, xOffset + 15, 19);
xOffset += ctx.measureText(item.label).width + 30;
});
}
function drawEmptyState(ctx, w, h, text) {
ctx.fillStyle = '#666';
ctx.font = '14px sans-serif';
ctx.textAlign = 'center';
const lines = text.split('\n');
lines.forEach((line, i) => {
ctx.fillText(line, w/2, h/2 + (i * 20) - (lines.length*10)/2);
});
}
function formatShortDate(isoString) {
return new Date(isoString).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' });
}