368 lines
13 KiB
JavaScript
368 lines
13 KiB
JavaScript
// frontend/js/render/dashboard.js
|
||
|
||
import { state } from '../state.js';
|
||
import { formatDate } from '../utils.js';
|
||
import { getExerciseChart } from '../logic/exercise.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)));
|
||
|
||
// Прогресс вершины относительно прошлой тренировки: вес выше — или тот же
|
||
// вес и больше повторов => зелёный; меньше => красный; ровно => фиолетовый.
|
||
const COLORS = { up: '#4caf50', down: '#e57373', flat: '#bb86fc' };
|
||
const cls = i => {
|
||
if (i === 0) return 'flat';
|
||
const a = days[i - 1], b = days[i];
|
||
if (b.max > a.max) return 'up';
|
||
if (b.max < a.max) return 'down';
|
||
if ((b.topReps || 0) > (a.topReps || 0)) return 'up';
|
||
if ((b.topReps || 0) < (a.topReps || 0)) return 'down';
|
||
return 'flat';
|
||
};
|
||
const classes = days.map((_, i) => cls(i));
|
||
|
||
// Линия рабочего максимума: отрезки окрашены по прогрессу конца отрезка
|
||
for (let i = 1; i < n; i++) {
|
||
ctx.strokeStyle = COLORS[classes[i]];
|
||
ctx.lineWidth = 2.5;
|
||
ctx.beginPath();
|
||
ctx.moveTo(x(i - 1), y(days[i - 1].max));
|
||
ctx.lineTo(x(i), y(days[i].max));
|
||
ctx.stroke();
|
||
}
|
||
|
||
days.forEach((d, i) => {
|
||
const px = x(i);
|
||
|
||
// Подходы дня ниже максимума — тусклые фоновые точки
|
||
const below = d.sets.filter(s => s.weight !== d.max);
|
||
const spread = below.length > 1 ? Math.min(11, chartW / (3 * n)) : 0;
|
||
below.forEach((s, k) => {
|
||
const dx = below.length > 1 ? -spread + (2 * spread * k) / (below.length - 1) : 0;
|
||
const r = 1.8 + 2.4 * Math.min(1, s.reps / maxReps);
|
||
ctx.beginPath();
|
||
ctx.fillStyle = 'rgba(187, 134, 252, 0.35)';
|
||
ctx.arc(px + dx, y(s.weight), r, 0, Math.PI * 2);
|
||
ctx.fill();
|
||
});
|
||
|
||
// Вершина: рабочий максимум «вес × повторы» с цветом прогресса
|
||
ctx.beginPath();
|
||
ctx.fillStyle = COLORS[classes[i]];
|
||
ctx.arc(px, y(d.max), 4.2, 0, Math.PI * 2);
|
||
ctx.fill();
|
||
ctx.strokeStyle = '#ffffff';
|
||
ctx.lineWidth = 1.2;
|
||
ctx.stroke();
|
||
if (n <= 10 || i >= n - 4 || classes[i] !== 'flat') {
|
||
ctx.fillStyle = COLORS[classes[i]];
|
||
ctx.font = 'bold 10px sans-serif';
|
||
ctx.textAlign = 'center';
|
||
ctx.fillText(`${d.max}×${d.topReps || ''}`, px, y(d.max) - 7);
|
||
}
|
||
|
||
// Количество подходов (выносливость)
|
||
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: '#4caf50', label: 'рабочий максимум: зелёный — прогресс, красный — откат' },
|
||
{ color: 'rgba(187, 134, 252, 0.45)', label: 'тусклая точка = подход (размер = повторы)' },
|
||
]);
|
||
}
|
||
|
||
/**
|
||
* Данные графика: по каждой завершённой тренировке — список подходов
|
||
* (дроп-сеты развёрнуты) и максимальный вес. Варианты упражнения из одной
|
||
* группы справочника объединяются в одну линию (общий источник —
|
||
* getExerciseChart из logic/exercise.js).
|
||
*/
|
||
export function getExerciseProgressData(exerciseName, clientId = null) {
|
||
return getExerciseChart(exerciseName, clientId)
|
||
.map(p => ({ date: new Date(p.date), sets: p.sets, max: p.maxWeight, topReps: p.topReps }))
|
||
.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' });
|
||
}
|