wip: слияние прода-версии с портированными фичами (до merge iovi)

This commit is contained in:
Иван Овчинников
2026-11-20 01:06:17 +03:00
parent 83ff9ae6e4
commit c3a34192ab
13 changed files with 2557 additions and 728 deletions
+381
View File
@@ -0,0 +1,381 @@
// frontend/js/render/dashboard.js
import { state } from '../state.js';
import { formatDate } from '../utils.js';
/**
* Рисует линейный график прогресса упражнения
* @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 history = getCumulativeExerciseHistory(exerciseName);
if (history.length < 2) {
drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 тренировки");
return;
}
// Находим максимальный ИТОГОВЫЙ объем для масштабирования оси Y
const maxVolume = Math.max(...history.map(h => h.totalVolume));
const padding = { top: 20, right: 20, bottom: 30, left: 40 };
const chartW = width - padding.left - padding.right;
const chartH = height - padding.top - padding.bottom;
// Рисуем сетку (используем maxVolume для оси Y)
drawGridAndAxes(ctx, padding, chartW, chartH, maxVolume, 'Дата', 'Общий вес (кг)');
// Рисуем новый график со стеком
drawCumulativeVolumeChart(ctx, history, padding, chartW, chartH, maxVolume);
// Легенда (обновленная)
drawLegend(ctx, width, [
{ color: '#bb86fc', label: 'Итоговый объем' },
{ color: 'rgba(187, 134, 252, 0.4)', label: 'Накопление по подходам' }
]);
}
/**
* Рисует график динамики телесных замеров
* @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 getCumulativeExerciseHistory(name) {
const normalized = name.trim().toLowerCase();
const history = [];
state.workouts.forEach(w => {
w.exercises.forEach(ex => {
if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) {
let currentCumulativeWeight = 0;
const cumulativePoints = [];
ex.sets.forEach(s => {
// Учитываем вес подхода (для дроп-сетов можно брать средний или максимальный, здесь берем основной)
const setWeight = s.isDropset && s.subSets
? Math.max(...s.subSets.map(ss => ss.weight))
: s.weight;
// Объем подхода = вес * повторения (или просто вес, если вы считаете тоннаж)
// В вашем примере (15, 30, 45, 60) вы суммируете именно вес подходов.
// Если нужно суммировать тоннаж (вес * повторы), замените на: setWeight * s.reps
const volume = setWeight * s.reps;
currentCumulativeWeight += volume;
cumulativePoints.push(currentCumulativeWeight);
});
history.push({
date: new Date(w.startTime),
cumulativePoints: cumulativePoints, // [15, 30, 45, 60]
totalVolume: currentCumulativeWeight // 60
});
}
});
});
history.sort((a, b) => a.date - b.date);
return history.slice(-10); // Последние 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 drawCumulativeVolumeChart(ctx, data, pad, cw, ch, maxY) {
if (!data.length) return;
// 1. Сначала рисуем соединительную линию для ОБЩИХ итогов (тренд)
ctx.strokeStyle = '#bb86fc'; // Основной цвет (например, фиолетовый)
ctx.lineWidth = 2;
ctx.beginPath();
data.forEach((item, index) => {
const x = pad.left + (index / (data.length - 1 || 1)) * cw;
const y = pad.top + ch - (item.totalVolume / maxY) * ch;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
// 2. Рисуем вертикальные стеки точек для каждой даты
data.forEach((item, index) => {
const x = pad.left + (index / (data.length - 1 || 1)) * cw;
item.cumulativePoints.forEach((cumWeight, pointIndex) => {
const isLast = pointIndex === item.cumulativePoints.length - 1;
const y = pad.top + ch - (cumWeight / maxY) * ch;
ctx.beginPath();
if (isLast) {
// Финальная точка: крупная, непрозрачная, с белой обводкой для контраста
ctx.fillStyle = '#bb86fc';
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1.5;
ctx.stroke();
} else {
// Промежуточные точки: полупрозрачные, поменьше
ctx.fillStyle = 'rgba(187, 134, 252, 0.4)'; // Тот же цвет, но 40% непрозрачности
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
}
});
// Опционально: провести бледную вертикальную линию от 0 до итоговой точки,
// чтобы визуально связать подходы в один "столбик"
if (item.cumulativePoints.length > 1) {
const bottomY = pad.top + ch; // Ось X
const topY = pad.top + ch - (item.totalVolume / maxY) * ch;
ctx.strokeStyle = 'rgba(187, 134, 252, 0.15)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(x, bottomY);
ctx.lineTo(x, topY);
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' });
}