wip: session changes (circuits, variant groups, sync-all, stepper UX) — pre-refactor base

This commit is contained in:
Иван Овчинников
2026-11-20 00:40:15 +03:00
parent e05ff1449b
commit d017a757d6
4 changed files with 602 additions and 169 deletions
+300 -64
View File
@@ -23,8 +23,15 @@ const App = {
if (saved) {
try {
this.state = JSON.parse(saved);
if (!Array.isArray(this.state.workouts)) this.state.workouts = [];
if (!this.state.exerciseRef) this.state.exerciseRef = [];
if (!this.state.bodyMetrics) this.state.bodyMetrics = [];
// Добиваем поля, которых может не быть в старых сохранениях
this.state.workouts.forEach(w => {
if (!Array.isArray(w.exercises)) w.exercises = [];
if (!Array.isArray(w.cardio)) w.cardio = [];
if (!Array.isArray(w.setGroups)) w.setGroups = [];
});
} catch (e) {
console.error('Failed to load state', e);
}
@@ -60,16 +67,18 @@ const App = {
},
async sync() {
const dirty = this.getDirtyWorkouts();
if (dirty.length === 0) {
// Отправляем ВСЕ тренировки, включая уже синхронизированные:
// синхронизация возможна в разгар тренировки, и данные после неё меняются
const all = this.state.workouts;
if (all.length === 0) {
alert('Нет данных для синхронизации');
return;
}
console.log('Syncing:', JSON.stringify(dirty, null, 2));
dirty.forEach(w => w.synced = true);
console.log('Syncing:', JSON.stringify(all, null, 2));
all.forEach(w => w.synced = true);
this.save();
this.render();
alert(`Отправлено тренировок: ${dirty.length}`);
alert(`Отправлено тренировок: ${all.length}`);
},
// ============================================================
@@ -83,6 +92,7 @@ const App = {
type: '',
exercises: [],
cardio: [],
setGroups: [],
notes: '',
synced: false,
};
@@ -153,7 +163,7 @@ const App = {
});
},
_addToExerciseRef(name, workoutType = '') {
_addToExerciseRef(name, workoutType = '', group = '') {
const normalizedName = name.trim().toLowerCase();
const exists = this.state.exerciseRef.find(
e => e.name.trim().toLowerCase() === normalizedName
@@ -163,10 +173,12 @@ const App = {
id: this.genId(),
name: name.trim(),
workoutType: workoutType,
group: group.trim(),
});
} else if (!exists.workoutType && workoutType) {
// Обновляем тип, если он был пуст
exists.workoutType = workoutType;
} else {
// Дополняем пустые поля, существующие значения не перетираем
if (!exists.workoutType && workoutType) exists.workoutType = workoutType;
if (!exists.group && group) exists.group = group.trim();
}
},
@@ -180,27 +192,83 @@ const App = {
if (!confirm('Удалить упражнение?')) return;
const w = this.getWorkout(workoutId);
w.exercises = w.exercises.filter(e => e.id !== exerciseId);
// Упражнение удалилось — чистим сеты, где оно состояло
w.setGroups = (w.setGroups || [])
.map(g => ({ ...g, exerciseIds: g.exerciseIds.filter(id => id !== exerciseId) }))
.filter(g => g.exerciseIds.length >= 2);
this.save();
this.render();
},
// ============================================================
// СЕТЫ (суперсеты): упражнения, подходы которых идут по очереди
// ============================================================
showGroupDialog(workoutId, groupId) {
const w = this.getWorkout(workoutId);
if (!w) return;
if (!Array.isArray(w.setGroups)) w.setGroups = [];
const group = groupId ? w.setGroups.find(g => g.id === groupId) : null;
if (groupId && !group) return;
Modal.showGroupDialog(w, group, (data) => {
if (!data) return;
if (group) {
group.name = data.name;
group.exerciseIds = data.exerciseIds;
} else {
w.setGroups.push({ id: this.genId(), name: data.name, exerciseIds: data.exerciseIds });
}
this.save();
this.render();
});
},
removeGroup(workoutId, groupId) {
if (!confirm('Разъединить сет? Упражнения останутся в тренировке.')) return;
const w = this.getWorkout(workoutId);
if (!w) return;
w.setGroups = (w.setGroups || []).filter(g => g.id !== groupId);
this.save();
this.render();
},
// Имена вариантов того же упражнения: справочная запись с непустой
// «группой вариантов» объединяет упражнения в одну статистику
_refVariantNames(exerciseName) {
const norm = s => (s || '').trim().toLowerCase();
const names = new Set([norm(exerciseName)]);
const self = this.state.exerciseRef.find(e => norm(e.name) === norm(exerciseName));
if (self && self.group) {
const g = norm(self.group);
this.state.exerciseRef.forEach(e => {
if (!e.group || norm(e.group) !== g) return;
// в рамках одного типа тренировки (пустой тип у одной из записей — не препятствие)
if (self.workoutType && e.workoutType && self.workoutType !== e.workoutType) return;
names.add(norm(e.name));
});
}
return names;
},
getExerciseHistory(exerciseName) {
const normalizedName = exerciseName.trim().toLowerCase();
const norm = s => (s || '').trim().toLowerCase();
const names = this._refVariantNames(exerciseName);
const history = [];
for (const w of this.state.workouts) {
for (const ex of w.exercises) {
if (ex.name.trim().toLowerCase() === normalizedName && ex.sets.length > 0) {
if (names.has(norm(ex.name)) && ex.sets.length > 0) {
history.push({
date: w.startTime,
name: ex.name,
sets: ex.sets,
});
}
}
}
history.sort((a, b) => new Date(b.date) - new Date(a.date));
return history.slice(0, 3);
return history.slice(0, 5);
},
// ============================================================
@@ -211,15 +279,16 @@ const App = {
const ex = w.exercises.find(e => e.id === exerciseId);
const lastSet = ex.sets[ex.sets.length - 1];
const history = this.getExerciseHistory(ex.name);
Modal.showSetDialog(lastSet, history, (setData) => {
// lastSet передаём как предзаполнение (не как редактирование)
Modal.showSetDialog(null, history, (setData) => {
if (!setData) return;
setData.id = this.genId();
setData.timestamp = new Date().toISOString();
ex.sets.push(setData);
this.save();
this.render();
});
}, { prefill: lastSet, historyLabel: ex.name });
},
editSet(workoutId, exerciseId, setId) {
@@ -227,12 +296,15 @@ const App = {
const ex = w.exercises.find(e => e.id === exerciseId);
const set = ex.sets.find(s => s.id === setId);
const history = this.getExerciseHistory(ex.name);
Modal.showSetDialog(set, history, (setData) => {
if (!setData) return;
Object.assign(set, setData);
this.save();
this.render();
}, {
historyLabel: ex.name,
onDelete: () => this.deleteSet(workoutId, exerciseId, setId),
});
},
@@ -281,13 +353,8 @@ const App = {
// BODY METRICS
// ============================================================
showBodyMetrics() {
Modal.showBodyMetricsDialog(this.state.bodyMetrics, (newMetric, isEdit) => {
Modal.showBodyMetricsDialog(this.state.bodyMetrics, (newMetric) => {
if (!newMetric) return;
if (isEdit) {
// При редактировании — ищем по временной метке исходного замера
// (передаём через замыкание)
return;
}
newMetric.id = this.genId();
this.state.bodyMetrics.unshift(newMetric);
// Сортируем по дате (новые сверху)
@@ -302,7 +369,7 @@ const App = {
const metric = this.state.bodyMetrics.find(m => m.id === metricId);
if (!metric) return;
Modal.showBodyMetricsDialog(this.state.bodyMetrics, (updatedData, isEdit) => {
Modal.showBodyMetricsDialog(this.state.bodyMetrics, (updatedData) => {
if (!updatedData) return;
Object.assign(metric, updatedData);
this.state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date));
@@ -343,7 +410,11 @@ const App = {
<option value="силовая">силовая</option>
<option value="многоповторная">многоповторная</option>
</select>
<button class="btn btn-small" style="width:auto; padding: 0 20px;"
</div>
<div style="display:flex; gap:6px; margin-top:6px;">
<input type="text" id="new-ref-group" list="ref-groups-list"
placeholder="Группа вариантов — общая статистика (необязательно)">
<button class="btn btn-small" style="width:auto; padding: 0 20px; flex-shrink:0;"
onclick="App.addRefExercise()">+</button>
</div>
</div>
@@ -369,12 +440,14 @@ const App = {
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;
this._addToExerciseRef(name, typeSelect.value);
this._addToExerciseRef(name, typeSelect.value, groupInput.value.trim());
this.save();
input.value = '';
typeSelect.value = '';
groupInput.value = '';
this._renderRefExercises();
},
@@ -393,6 +466,15 @@ const App = {
}
},
updateRefExerciseGroup(id, newGroup) {
const ex = this.state.exerciseRef.find(e => e.id === id);
if (ex) {
ex.group = newGroup.trim();
this.save();
this._renderRefExercises(); // пересортировать: варианты должны стоять вместе
}
},
editRefExercise(id) {
const ex = this.state.exerciseRef.find(e => e.id === id);
if (!ex) return;
@@ -408,20 +490,41 @@ const App = {
_renderRefExercises() {
const list = document.getElementById('ref-exercises-list');
if (!list) return;
if (this.state.exerciseRef.length === 0) {
list.innerHTML = '<p class="text-muted text-small">Справочник пуст</p>';
return;
}
const esc = s => Modal.esc(s);
const types = ['', 'грудь-руки', 'ноги', 'спина-плечи', 'круговая', 'силовая', 'многоповторная'];
const groupNames = [...new Set(this.state.exerciseRef.map(e => e.group).filter(Boolean))].sort();
// Сортировка: тип → группа вариантов → имя (варианты стоят вместе)
const sorted = [...this.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);
});
list.innerHTML = sorted.map(ex => {
let html = `<datalist id="ref-groups-list">${
groupNames.map(g => `<option value="${esc(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 ? esc(curType) : 'без типа'}</div>`;
}
if ((ex.group || '') !== curGroup) {
curGroup = ex.group || '';
html += curGroup ? `<div class="ref-group-head">🧩 ${esc(curGroup)}</div>` : '';
}
let count = 0;
this.state.workouts.forEach(w => {
w.exercises.forEach(e => {
@@ -430,30 +533,33 @@ const App = {
}
});
});
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">${esc(ex.name)}</span>
<span class="count">(${count}×)</span>
</div>
<div style="display:flex; gap:4px; align-items:center;">
<button class="icon-btn" onclick="App.editRefExercise('${ex.id}')">✎</button>
<button class="icon-btn danger" onclick="App.deleteRefExercise('${ex.id}')">✕</button>
</div>
</div>
<div style="display:flex; gap:4px; align-items:center;">
<select onchange="App.updateRefExerciseType('${ex.id}', this.value)"
style="width:auto; min-width:100px; padding:6px; font-size:0.8rem;">
<div class="ref-item-controls">
<select onchange="App.updateRefExerciseType('${ex.id}', this.value)">
<option value="">тип...</option>
<option value="грудь-руки" ${ex.workoutType==='грудь-руки'?'selected':''}>грудь-руки</option>
<option value="ноги" ${ex.workoutType==='ноги'?'selected':''}>ноги</option>
<option value="спина-плечи" ${ex.workoutType==='спина-плечи'?'selected':''}>спина-плечи</option>
<option value="круговая" ${ex.workoutType==='круговая'?'selected':''}>круговая</option>
<option value="силовая" ${ex.workoutType==='силовая'?'selected':''}>силовая</option>
<option value="многоповторная" ${ex.workoutType==='многоповторная'?'selected':''}>многоповторная</option>
${types.slice(1).map(t => `<option value="${t}" ${ex.workoutType === t ? 'selected' : ''}>${t}</option>`).join('')}
</select>
<button class="icon-btn" onclick="App.editRefExercise('${ex.id}')">✎</button>
<button class="icon-btn danger" onclick="App.deleteRefExercise('${ex.id}')">✕</button>
<input type="text" list="ref-groups-list" value="${esc(ex.group || '')}"
placeholder="группа вариантов"
onchange="App.updateRefExerciseGroup('${ex.id}', this.value)">
</div>
</div>
`;
}).join('');
});
list.innerHTML = html;
},
_renderBodyMetricsList() {
@@ -645,6 +751,7 @@ const App = {
addSection.innerHTML = `
<button class="btn btn-secondary" onclick="App.addExercise('${w.id}')">+ Упражнение</button>
<button class="btn btn-secondary" onclick="App.addCardio('${w.id}')">+ Кардио</button>
${w.exercises.length >= 2 ? `<button class="btn btn-secondary" onclick="App.showGroupDialog('${w.id}')">🔗 Сет</button>` : ''}
`;
wrap.appendChild(addSection);
}
@@ -664,12 +771,38 @@ const App = {
});
}
// Упражнения
const sortedExercises = [...w.exercises].reverse();
sortedExercises.forEach(ex => {
wrap.appendChild(this.renderExercise(w, ex, isReadOnly));
// Упражнения: обычные + объединённые в сеты (по очереди)
const groups = (w.setGroups || [])
.map(g => ({
g,
members: g.exerciseIds
.map(id => w.exercises.find(e => e.id === id))
.filter(Boolean),
}))
.filter(x => x.members.length >= 2);
const seenGroups = new Set();
[...w.exercises].reverse().forEach(ex => {
const owner = groups.find(x => x.g.exerciseIds.includes(ex.id));
if (owner) {
if (!seenGroups.has(owner.g.id)) {
seenGroups.add(owner.g.id);
wrap.appendChild(this.renderCircuit(w, owner.g, owner.members, isReadOnly));
}
} else {
wrap.appendChild(this.renderExercise(w, ex, isReadOnly));
}
});
if (!isReadOnly && w.exercises.length >= 2) {
const groupBtn = document.createElement('button');
groupBtn.className = 'btn btn-ghost mt-10';
groupBtn.style.width = '100%';
groupBtn.textContent = '🔗 Объединить упражнения в сет';
groupBtn.onclick = () => this.showGroupDialog(w.id);
wrap.appendChild(groupBtn);
}
// Заминка — в самом низу (перед комментарием)
if (cardioCooldown.length > 0) {
const title = document.createElement('h4');
@@ -681,9 +814,6 @@ const App = {
});
}
// Отдельное кардио (если было — уже показано в разминке, но на всякий случай)
// (уже обработано выше)
// Комментарий
const notesCard = document.createElement('div');
notesCard.className = 'card mt-10';
@@ -715,12 +845,14 @@ const App = {
finishBlock.innerHTML = `
<h3>🔒 Архив</h3>
<p class="text-muted text-small">Тренировка синхронизирована и завершена. Редактирование недоступно.</p>
<button class="btn btn-danger" onclick="App.deleteWorkout('${w.id}')">🗑 Удалить тренировку</button>
`;
} else if (isActive) {
finishBlock.innerHTML = `
<h3>Завершение тренировки</h3>
<p class="text-muted text-small">После завершения данные останутся локально до синхронизации</p>
<button class="btn btn-danger" onclick="App.finishWorkout('${w.id}')">⏹ Закончить тренировку</button>
<button class="btn btn-ghost mt-10" style="width:100%;" onclick="App.deleteWorkout('${w.id}')">🗑 Удалить тренировку</button>
`;
} else {
finishBlock.innerHTML = `
@@ -734,6 +866,106 @@ const App = {
return wrap;
},
// Карточка сета: подходы участников выполняются по очереди (раундами)
renderCircuit(w, group, members, isReadOnly) {
const card = document.createElement('div');
card.className = 'circuit-card';
const header = document.createElement('div');
header.className = 'circuit-header';
header.innerHTML = `
<div>
<span class="circuit-name"></span>
<div class="circuit-members"></div>
</div>
`;
if (!isReadOnly) {
const controls = document.createElement('div');
controls.className = 'circuit-controls';
const editBtn = document.createElement('button');
editBtn.className = 'btn btn-small btn-secondary';
editBtn.textContent = '✎ состав';
editBtn.onclick = () => this.showGroupDialog(w.id, group.id);
const unlinkBtn = document.createElement('button');
unlinkBtn.className = 'btn btn-small btn-danger';
unlinkBtn.textContent = '✕ разъединить';
unlinkBtn.onclick = () => this.removeGroup(w.id, group.id);
controls.appendChild(editBtn);
controls.appendChild(unlinkBtn);
header.appendChild(controls);
}
// Текст — через textContent, чтобы кавычки и скобки в названиях ломали разметку
header.querySelector('.circuit-name').textContent = '🔗 ' + group.name;
header.querySelector('.circuit-members').textContent = members.map(m => m.name).join(' + ');
card.appendChild(header);
const maxLen = Math.max(0, ...members.map(m => m.sets.length));
const roundsWrap = document.createElement('div');
roundsWrap.className = 'circuit-rounds';
for (let k = 0; k < maxLen; k++) {
const row = document.createElement('div');
row.className = 'circuit-round';
const num = document.createElement('span');
num.className = 'round-num';
num.textContent = k + 1;
row.appendChild(num);
members.forEach(ex => {
const set = ex.sets[k];
const chip = document.createElement('span');
if (!set) {
chip.className = 'circuit-chip empty';
chip.textContent = ex.name + ': —';
} else {
chip.className = 'circuit-chip';
chip.innerHTML = '<b></b> <span class="circuit-val"></span> <span class="circuit-stars"></span>';
chip.querySelector('b').textContent = ex.name;
chip.querySelector('.circuit-val').textContent =
(set.isDropset && set.subSets && set.subSets.length)
? '🔥' + set.subSets.map(s => `${s.weight}×${s.reps}`).join('→')
: `${set.weight}×${set.reps}`;
chip.querySelector('.circuit-stars').textContent = '★'.repeat(set.rating || 5);
if (!isReadOnly) {
chip.onclick = () => this.editSet(w.id, ex.id, set.id);
}
}
row.appendChild(chip);
});
roundsWrap.appendChild(row);
}
if (maxLen === 0) {
const p = document.createElement('p');
p.className = 'text-muted text-small';
p.style.padding = '10px 12px';
p.textContent = 'Пока нет подходов';
roundsWrap.appendChild(p);
}
card.appendChild(roundsWrap);
if (!isReadOnly) {
const footRow = document.createElement('div');
footRow.className = 'circuit-add';
if (!w.endTime) {
members.forEach(ex => {
const b = document.createElement('button');
b.className = 'btn btn-small btn-secondary';
b.textContent = `+ ${ex.name}`;
b.onclick = () => this.addSet(w.id, ex.id);
footRow.appendChild(b);
});
}
const unlinkFoot = document.createElement('button');
unlinkFoot.className = 'btn btn-small btn-ghost';
unlinkFoot.textContent = '⛓️ Разъединить сет';
unlinkFoot.onclick = () => this.removeGroup(w.id, group.id);
footRow.appendChild(unlinkFoot);
card.appendChild(footRow);
}
return card;
},
renderExercise(w, ex, isReadOnly = false) {
const isExpanded = this.state.expandedExerciseId === ex.id;
const totalSets = ex.sets.length;
@@ -795,23 +1027,27 @@ const App = {
renderSetRow(workoutId, exerciseId, set, index, isReadOnly = false) {
const row = document.createElement('div');
const timeStr = set.timestamp
? new Date(set.timestamp).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })
: '';
const timeHtml = timeStr ? `<div class="set-time">${timeStr}</div>` : '';
const actionsHtml = isReadOnly ? '' : `
<div class="set-actions">
<button class="icon-btn" onclick="App.editSet('${workoutId}', '${exerciseId}', '${set.id}')">✎</button>
<button class="icon-btn danger" onclick="App.deleteSet('${workoutId}', '${exerciseId}', '${set.id}')">✕</button>
</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-number">${index + 1}</div>
<div class="set-cell dropset">🔥 ${subsText}</div>
<div class="set-rating">${ratingStars}</div>
<div class="set-rating">${ratingStars}${timeHtml}</div>
${actionsHtml}
</div>
`;
@@ -821,7 +1057,7 @@ const App = {
<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>
<div class="set-rating">${'★'.repeat(set.rating || 5)}${timeHtml}</div>
${actionsHtml}
</div>
`;