feat(exercise-ref): группировка вариантов упражнения с общей историей
Поле group в справочнике, заголовки типа и группы в списке, автодополнение названий групп, объединение прошлых подходов вариантов в статистике упражнения.
This commit is contained in:
@@ -2,6 +2,7 @@ import { state, saveState, CLIENT_COLORS, DEFAULT_COLOR, genId, generateUUID } f
|
||||
import { showEditExerciseDialog } from '../modals/edit-exercise-modal.js';
|
||||
import { showBodyMetricsDialog } from '../modals/metrics-modal.js';
|
||||
import { showModal } from '../modals/modal-base.js';
|
||||
import { escapeHtml } from '../utils.js';
|
||||
|
||||
export function showSettings() {
|
||||
const app = document.getElementById('app');
|
||||
@@ -34,6 +35,8 @@ export function showSettings() {
|
||||
</select>
|
||||
<button class="btn btn-small" style="width:auto; padding: 0 20px;" onclick="SettingsLogic.addRefExercise()">+</button>
|
||||
</div>
|
||||
<input type="text" id="new-ref-group" list="ref-groups-list" style="margin-top:6px;"
|
||||
placeholder="Группа вариантов — общая статистика (необязательно)">
|
||||
</div>
|
||||
<div id="ref-exercises-list"></div>
|
||||
</div>
|
||||
@@ -96,6 +99,7 @@ export function _renderPersonalMetricsList() {
|
||||
export function addRefExercise() {
|
||||
const input = document.getElementById('new-ref-exercise');
|
||||
const typeSelect = document.getElementById('new-ref-type');
|
||||
const groupInput = document.getElementById('new-ref-group');
|
||||
const name = input.value.trim();
|
||||
if (!name) return;
|
||||
const normalizedName = name.trim().toLowerCase();
|
||||
@@ -107,11 +111,13 @@ export function addRefExercise() {
|
||||
id: (state.nextId++).toString(),
|
||||
name: name.trim(),
|
||||
workoutType: typeSelect.value,
|
||||
group: groupInput.value.trim(),
|
||||
});
|
||||
}
|
||||
saveState();
|
||||
input.value = '';
|
||||
typeSelect.value = '';
|
||||
groupInput.value = '';
|
||||
_renderRefExercises();
|
||||
}
|
||||
|
||||
@@ -127,6 +133,16 @@ export function updateRefExerciseType(id, newType) {
|
||||
if (ex) {
|
||||
ex.workoutType = newType;
|
||||
saveState();
|
||||
_renderRefExercises(); // пересортировать: тип поменялся
|
||||
}
|
||||
}
|
||||
|
||||
export function updateRefExerciseGroup(id, newGroup) {
|
||||
const ex = state.exerciseRef.find(e => e.id === id);
|
||||
if (ex) {
|
||||
ex.group = newGroup.trim();
|
||||
saveState();
|
||||
_renderRefExercises(); // пересортировать: варианты должны стоять вместе
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,42 +171,67 @@ export function _renderRefExercises() {
|
||||
list.innerHTML = '<p class="text-muted text-small">Справочник пуст</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
const groupNames = [...new Set(state.exerciseRef.map(e => e.group).filter(Boolean))].sort();
|
||||
|
||||
// Сортировка: тип → группа вариантов → имя (варианты стоят вместе)
|
||||
const sorted = [...state.exerciseRef].sort((a, b) => {
|
||||
if (a.workoutType !== b.workoutType) return (a.workoutType || '').localeCompare(b.workoutType || '');
|
||||
const t = (a.workoutType || '').localeCompare(b.workoutType || '');
|
||||
if (t !== 0) return t;
|
||||
const g = (a.group || '').localeCompare(b.group || '');
|
||||
if (g !== 0) return g;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
// Генерируем опции для select динамически из state.workoutTypes
|
||||
const typeOptions = state.workoutTypes.map(wt =>
|
||||
`<option value="${wt.name}" ${a => a.workoutType === wt.name ? 'selected' : ''}>${wt.name}</option>`
|
||||
).join('');
|
||||
let html = `<datalist id="ref-groups-list">${
|
||||
groupNames.map(g => `<option value="${escapeHtml(g)}"></option>`).join('')
|
||||
}</datalist>`;
|
||||
|
||||
let curType = null, curGroup = null;
|
||||
sorted.forEach(ex => {
|
||||
if ((ex.workoutType || '') !== curType) {
|
||||
curType = ex.workoutType || '';
|
||||
curGroup = null;
|
||||
html += `<div class="ref-type-head">${curType ? escapeHtml(curType) : 'без типа'}</div>`;
|
||||
}
|
||||
if ((ex.group || '') !== curGroup) {
|
||||
curGroup = ex.group || '';
|
||||
html += curGroup ? `<div class="ref-group-head">🧩 ${escapeHtml(curGroup)}</div>` : '';
|
||||
}
|
||||
|
||||
list.innerHTML = sorted.map(ex => {
|
||||
let count = 0;
|
||||
state.workouts.forEach(w => {
|
||||
w.exercises.forEach(e => {
|
||||
(w.exercises || []).forEach(e => {
|
||||
if (e.name.trim().toLowerCase() === ex.name.trim().toLowerCase()) count++;
|
||||
});
|
||||
});
|
||||
return `
|
||||
<div class="exercise-ref-item">
|
||||
<div style="flex:1;">
|
||||
<span class="name">${ex.name}</span>
|
||||
<span class="count">(${count}×)</span>
|
||||
${ex.workoutType ? `<span class="type-badge">${ex.workoutType}</span>` : ''}
|
||||
|
||||
html += `
|
||||
<div class="exercise-ref-item exercise-ref-grouped">
|
||||
<div class="ref-item-top">
|
||||
<div>
|
||||
<span class="name">${escapeHtml(ex.name)}</span>
|
||||
<span class="count">(${count}×)</span>
|
||||
</div>
|
||||
<div style="display:flex; gap:4px; align-items:center;">
|
||||
<button class="icon-btn" onclick="SettingsLogic.editRefExercise('${ex.id}')">✎</button>
|
||||
<button class="icon-btn danger" onclick="SettingsLogic.deleteRefExercise('${ex.id}')">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex; gap:4px; align-items:center;">
|
||||
<select onchange="SettingsLogic.updateRefExerciseType('${ex.id}', this.value)"
|
||||
style="width:auto; min-width:100px; padding:6px; font-size:0.8rem;">
|
||||
<div class="ref-item-controls">
|
||||
<select onchange="SettingsLogic.updateRefExerciseType('${ex.id}', this.value)">
|
||||
<option value="">тип...</option>
|
||||
${state.workoutTypes.map(wt => `<option value="${wt.name}" ${ex.workoutType === wt.name ? 'selected' : ''}>${wt.name}</option>`).join('')}
|
||||
${state.workoutTypes.map(wt => `<option value="${escapeHtml(wt.name)}" ${ex.workoutType === wt.name ? 'selected' : ''}>${escapeHtml(wt.name)}</option>`).join('')}
|
||||
</select>
|
||||
<button class="icon-btn" onclick="SettingsLogic.editRefExercise('${ex.id}')">✎</button>
|
||||
<button class="icon-btn danger" onclick="SettingsLogic.deleteRefExercise('${ex.id}')">✕</button>
|
||||
<input type="text" list="ref-groups-list" value="${escapeHtml(ex.group || '')}"
|
||||
placeholder="группа вариантов"
|
||||
onchange="SettingsLogic.updateRefExerciseGroup('${ex.id}', this.value)">
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
});
|
||||
|
||||
list.innerHTML = html;
|
||||
}
|
||||
|
||||
export function _renderMetricTypes() {
|
||||
@@ -484,7 +525,7 @@ export function deleteClientMetric(metricId, clientId) {
|
||||
// Обновляем экспорт
|
||||
window.SettingsLogic = {
|
||||
show: showSettings,
|
||||
addRefExercise, deleteRefExercise, updateRefExerciseType,
|
||||
addRefExercise, deleteRefExercise, updateRefExerciseType, updateRefExerciseGroup,
|
||||
editRefExercise, clearAllData,
|
||||
_renderRefExercises, _renderBodyMetricsList,
|
||||
// Клиенты:
|
||||
|
||||
@@ -1,28 +1,41 @@
|
||||
import { showModal, closeModal } from './modal-base.js';
|
||||
import { state } from '../state.js';
|
||||
import { escapeHtml } from '../utils.js';
|
||||
|
||||
let _cb = null;
|
||||
|
||||
export function showEditExerciseDialog(exercise, callback) {
|
||||
_cb = callback;
|
||||
const groups = [...new Set(state.exerciseRef.map(e => e.group).filter(Boolean))].sort();
|
||||
|
||||
showModal(`
|
||||
<div class="modal-content">
|
||||
<h3 class="modal-title">Редактировать упражнение</h3>
|
||||
<div class="field-group">
|
||||
<label>Название</label>
|
||||
<input type="text" id="m-edit-ex-name" value="${exercise.name}">
|
||||
<input type="text" id="m-edit-ex-name" value="${escapeHtml(exercise.name)}">
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<label>Тип тренировки</label>
|
||||
<select id="m-edit-ex-type">
|
||||
<option value="">тип не указан</option>
|
||||
<option value="грудь-руки" ${exercise.workoutType==='грудь-руки'?'selected':''}>грудь-руки</option>
|
||||
<option value="ноги" ${exercise.workoutType==='ноги'?'selected':''}>ноги</option>
|
||||
<option value="спина-плечи" ${exercise.workoutType==='спина-плечи'?'selected':''}>спина-плечи</option>
|
||||
<option value="круговая" ${exercise.workoutType==='круговая'?'selected':''}>круговая</option>
|
||||
<option value="силовая" ${exercise.workoutType==='силовая'?'selected':''}>силовая</option>
|
||||
<option value="многоповторная" ${exercise.workoutType==='многоповторная'?'selected':''}>многоповторная</option>
|
||||
${state.workoutTypes.map(wt =>
|
||||
`<option value="${escapeHtml(wt.name)}" ${exercise.workoutType === wt.name ? 'selected' : ''}>${escapeHtml(wt.name)}</option>`
|
||||
).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<label>Группа вариантов (общая статистика)</label>
|
||||
<input type="text" id="m-edit-ex-group" list="m-edit-groups-list"
|
||||
value="${escapeHtml(exercise.group || '')}"
|
||||
placeholder="Например: жим гантелей на лавке">
|
||||
<datalist id="m-edit-groups-list">${
|
||||
groups.map(g => `<option value="${escapeHtml(g)}"></option>`).join('')
|
||||
}</datalist>
|
||||
<p class="text-muted text-small" style="margin-top:4px;">
|
||||
Упражнения с одинаковой группой показывают историю друг друга
|
||||
</p>
|
||||
</div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-secondary" onclick="ModalBase.close()">Отмена</button>
|
||||
<button class="btn btn-success" onclick="EditExModal.submit()">Сохранить</button>
|
||||
@@ -34,9 +47,10 @@ export function showEditExerciseDialog(exercise, callback) {
|
||||
export function submit() {
|
||||
const name = document.getElementById('m-edit-ex-name').value.trim();
|
||||
const type = document.getElementById('m-edit-ex-type').value;
|
||||
const group = document.getElementById('m-edit-ex-group').value.trim();
|
||||
if (!name) { alert('Название не может быть пустым'); return; }
|
||||
closeModal();
|
||||
if (_cb) _cb({ name, workoutType: type });
|
||||
if (_cb) _cb({ name, workoutType: type, group });
|
||||
}
|
||||
|
||||
window.EditExModal = { submit };
|
||||
|
||||
@@ -1,20 +1,43 @@
|
||||
import { showModal, closeModal, stepperHtml } from './modal-base.js';
|
||||
import { formatShortDate, formatSet } from '../utils.js';
|
||||
import { showModal, closeModal, stepperHtml, weightStep } from './modal-base.js';
|
||||
import { formatSet, escapeHtml } from '../utils.js';
|
||||
|
||||
let _data = {};
|
||||
let _cb = null;
|
||||
|
||||
export function showSetDialog(existingSet, history, callback) {
|
||||
function formatHistoryDate(iso) {
|
||||
const d = new Date(iso);
|
||||
return d.toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit', weekday: 'short' });
|
||||
}
|
||||
|
||||
function formatHistoryRow(h, historyLabel) {
|
||||
const sets = h.sets.map((s, i) =>
|
||||
`<span class="history-hint-set">${i + 1}) ${escapeHtml(formatSet(s))}</span>`).join('');
|
||||
const isVariant = historyLabel &&
|
||||
String(h.name || '').trim().toLowerCase() !== String(historyLabel).trim().toLowerCase();
|
||||
const nameLabel = isVariant
|
||||
? `<div class="history-hint-name">${escapeHtml(h.name)}</div>` : '';
|
||||
return `<div class="history-hint-row">
|
||||
<span class="history-hint-date">${formatHistoryDate(h.date)}</span>
|
||||
<span class="history-hint-sets">${nameLabel}${sets}</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object|null} existingSet - редактируемый подход
|
||||
* @param {Array} history - прошлые выполнения [{date, name, sets}]
|
||||
* @param {Function} callback
|
||||
* @param {object} options - { prefill - скопировать значения прошлого подхода,
|
||||
* historyLabel - имя текущего упражнения для подписи вариантов }
|
||||
*/
|
||||
export function showSetDialog(existingSet, history, callback, options = {}) {
|
||||
_cb = callback;
|
||||
const isEdit = !!existingSet;
|
||||
const isDropset = existingSet?.isDropset || false;
|
||||
const source = existingSet || options.prefill || null; // «+ подход» стартует с прошлого веса
|
||||
const isDropset = source?.isDropset || false;
|
||||
|
||||
let historyHtml = '';
|
||||
if (history?.length) {
|
||||
const rows = history.map(h => `<div class="history-hint-row">
|
||||
<span class="history-hint-date">${formatShortDate(h.date)}</span>
|
||||
<span class="history-hint-sets">${h.sets.map(formatSet).join(', ')}</span>
|
||||
</div>`).join('');
|
||||
const rows = history.map(h => formatHistoryRow(h, options.historyLabel)).join('');
|
||||
historyHtml = `<div class="history-hint"><div class="history-hint-title">📊 Прошлые тренировки</div>${rows}</div>`;
|
||||
}
|
||||
|
||||
@@ -26,15 +49,15 @@ export function showSetDialog(existingSet, history, callback) {
|
||||
Это дроп-сет</label></div>
|
||||
<div id="m-set-normal" class="${isDropset ? 'hidden' : ''}">
|
||||
<div class="field-row">
|
||||
<div class="field-group"><label>Вес (кг)</label>${stepperHtml('m-set-weight', existingSet?.weight ?? '', 0.5, 'Вес')}</div>
|
||||
<div class="field-group"><label>Повторения</label>${stepperHtml('m-set-reps', existingSet?.reps ?? '', 1, 'Повт.', 'numeric')}</div>
|
||||
<div class="field-group"><label>Вес (кг)</label>${stepperHtml('m-set-weight', source?.weight ?? '', 0.5, 'Вес', 'decimal', true)}</div>
|
||||
<div class="field-group"><label>Повторения</label>${stepperHtml('m-set-reps', source?.reps ?? '', 1, 'Повт.', 'numeric')}</div>
|
||||
</div></div>
|
||||
<div id="m-set-dropset-block" class="${isDropset ? '' : 'hidden'}">
|
||||
<div id="m-subsets-list"></div>
|
||||
<button class="btn btn-ghost mt-10" style="width:100%;" onclick="SetModal.addSubset()">+ Сбрасывание</button></div>
|
||||
<div class="field-group"><label>Оценка (1-5)</label>
|
||||
<div class="rating-grid" id="m-rating-grid">
|
||||
${[1,2,3,4,5].map(r => `<button class="rating-btn ${existingSet?.rating===r?'active':''}" data-rating="${r}" onclick="SetModal.rating(${r})">${r}</button>`).join('')}
|
||||
${[1,2,3,4,5].map(r => `<button class="rating-btn" data-rating="${r}" onclick="SetModal.rating(${r})">${r}</button>`).join('')}
|
||||
</div></div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-secondary" onclick="ModalBase.closeOnBg({target:document.querySelector('.modal-overlay')})">Отмена</button>
|
||||
@@ -42,8 +65,8 @@ export function showSetDialog(existingSet, history, callback) {
|
||||
</div>`);
|
||||
|
||||
_data = {
|
||||
isDropset, rating: existingSet?.rating || 3,
|
||||
subSets: existingSet?.subSets ? JSON.parse(JSON.stringify(existingSet.subSets)) : [],
|
||||
isDropset, rating: source?.rating || 5,
|
||||
subSets: source?.subSets ? JSON.parse(JSON.stringify(source.subSets)) : [],
|
||||
};
|
||||
if (isDropset) { if (!_data.subSets.length) addSubset(); else renderSubsets(); }
|
||||
rating(_data.rating);
|
||||
@@ -64,33 +87,38 @@ export function addSubset() {
|
||||
}
|
||||
|
||||
export function renderSubsets() {
|
||||
document.getElementById('m-subsets-list').innerHTML = _data.subSets.map((s, i) => `
|
||||
document.getElementById('m-subsets-list').innerHTML = _data.subSets.map((s, i) => {
|
||||
const wStep = weightStep(s.weight);
|
||||
return `
|
||||
<div class="stepper-row">
|
||||
<div class="stepper-field">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'weight', -0.5)">−</button>
|
||||
<input type="number" id="m-sw-${i}" step="0.5" value="${s.weight || ''}" placeholder="Вес" inputmode="decimal" oninput="SetModal.updateSubset(${i}, 'weight', this.value)">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'weight', 0.5)">+</button>
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'weight', -1)">−</button>
|
||||
<input type="number" id="m-sw-${i}" step="${wStep}" value="${s.weight || ''}" placeholder="Вес" inputmode="decimal"
|
||||
onfocus="ModalBase.focusInput(this)" oninput="SetModal.updateSubset(${i}, 'weight', this.value)">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'weight', 1)">+</button>
|
||||
</div>
|
||||
<div class="stepper-field">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'reps', -1)">−</button>
|
||||
<input type="number" id="m-sr-${i}" step="1" value="${s.reps || ''}" placeholder="Повт." inputmode="numeric" oninput="SetModal.updateSubset(${i}, 'reps', this.value)">
|
||||
<input type="number" id="m-sr-${i}" step="1" value="${s.reps || ''}" placeholder="Повт." inputmode="numeric"
|
||||
onfocus="ModalBase.focusInput(this)" oninput="SetModal.updateSubset(${i}, 'reps', this.value)">
|
||||
<button type="button" class="stepper-btn" onclick="SetModal.stepSubset(${i}, 'reps', 1)">+</button>
|
||||
</div>
|
||||
<button class="icon-btn danger" onclick="SetModal.removeSubset(${i})">✕</button>
|
||||
</div>
|
||||
`).join('');
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
export function updateSubset(i, field, value) {
|
||||
_data.subSets[i][field] = value;
|
||||
}
|
||||
|
||||
export function stepSubset(i, field, delta) {
|
||||
export function stepSubset(i, field, dir) {
|
||||
const current = parseFloat(_data.subSets[i][field]) || 0;
|
||||
const step = field === 'weight' ? 0.5 : 1;
|
||||
const newVal = Math.max(0, current + delta);
|
||||
// Вес в сбрасываниях — тоже адаптивный шаг
|
||||
const step = field === 'weight' ? weightStep(current) : 1;
|
||||
const newVal = Math.max(0, current + (dir > 0 ? step : -step));
|
||||
_data.subSets[i][field] = parseFloat((Math.round(newVal / step) * step).toFixed(4));
|
||||
renderSubsets(); // Перерисовываем, чтобы обновить значение в input
|
||||
renderSubsets(); // Перерисовываем, чтобы обновить значение и шаг в input
|
||||
}
|
||||
|
||||
export function removeSubset(i) {
|
||||
@@ -115,7 +143,8 @@ export function submit() {
|
||||
} else {
|
||||
const w = parseFloat(document.getElementById('m-set-weight').value);
|
||||
const r = parseInt(document.getElementById('m-set-reps').value);
|
||||
if (!w && !r) { alert('Укажите вес и повторения'); return; }
|
||||
// Пустой или нулевой должен быть и вес, и повторы — например «вес 0, 15 раз» с собой легитимен
|
||||
if (!(w > 0) && !(r > 0)) { alert('Укажите вес и повторения'); return; }
|
||||
closeModal(); _cb?.({ isDropset: false, weight: w||0, reps: r||0, rating: _data.rating });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,14 +8,19 @@ export function renderSetRow(workoutId, exerciseId, set, index, isReadOnly = fal
|
||||
</div>
|
||||
`;
|
||||
|
||||
const setTime = set.timestamp
|
||||
? `<div class="set-time">${new Date(set.timestamp).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}</div>`
|
||||
: '<div class="set-time"></div>';
|
||||
|
||||
if (set.isDropset && set.subSets && set.subSets.length > 0) {
|
||||
row.className = 'dropset-group';
|
||||
const subsText = set.subSets.map(s => `${s.weight}×${s.reps}`).join(' → ');
|
||||
const ratingStars = '★'.repeat(set.rating || 3);
|
||||
const ratingStars = '★'.repeat(set.rating || 5);
|
||||
row.innerHTML = `
|
||||
<div class="set-row" style="grid-template-columns: 30px 1fr auto ${isReadOnly ? '0' : 'auto'};">
|
||||
<div class="set-row dropset-row">
|
||||
<div class="set-number">${index + 1}</div>
|
||||
<div class="set-cell dropset">🔥 ${subsText}</div>
|
||||
${setTime}
|
||||
<div class="set-rating">${ratingStars}</div>
|
||||
${actionsHtml}
|
||||
</div>
|
||||
@@ -26,7 +31,8 @@ export function renderSetRow(workoutId, exerciseId, set, index, isReadOnly = fal
|
||||
<div class="set-number">${index + 1}</div>
|
||||
<div class="set-cell">${set.weight || '—'} кг</div>
|
||||
<div class="set-cell">${set.reps || '—'}</div>
|
||||
<div class="set-rating">${'★'.repeat(set.rating || 3)}</div>
|
||||
${setTime}
|
||||
<div class="set-rating">${'★'.repeat(set.rating || 5)}</div>
|
||||
${actionsHtml}
|
||||
</div>
|
||||
`;
|
||||
|
||||
Reference in New Issue
Block a user