181 lines
4.5 KiB
JavaScript
181 lines
4.5 KiB
JavaScript
// frontend/js/state.js
|
|
|
|
const CURRENT_STORAGE_PREFIX = "gym_tracker_v7_user_";
|
|
const GUEST_STORAGE_KEY = "gym_tracker_v7_guest";
|
|
|
|
const LEGACY_KEYS = [
|
|
"gym_tracker_v6",
|
|
"gym_tracker_v5",
|
|
"gym_tracker_v4",
|
|
];
|
|
|
|
const MIGRATION_FLAG = "gym_tracker_legacy_migrated_to_user";
|
|
|
|
function freshState() {
|
|
return {
|
|
workouts: [],
|
|
exerciseRef: [],
|
|
bodyMetrics: [],
|
|
|
|
workoutTypes: [],
|
|
metricTypes: [],
|
|
clients: [],
|
|
|
|
expandedWorkoutId: null,
|
|
expandedExerciseId: null,
|
|
nextId: 1,
|
|
|
|
mode: "personal",
|
|
currentClientId: null,
|
|
};
|
|
}
|
|
|
|
export const state = freshState();
|
|
|
|
// Внутренняя переменная для хранения текущего пользователя (не сохраняется в localStorage напрямую)
|
|
let activeUser = null;
|
|
|
|
/**
|
|
* Установить текущего пользователя после логина
|
|
*/
|
|
export function setActiveUser(user) {
|
|
activeUser = user;
|
|
}
|
|
|
|
/**
|
|
* Получить данные текущего пользователя
|
|
*/
|
|
export function getActiveUser() {
|
|
return activeUser;
|
|
}
|
|
|
|
/**
|
|
* Сбросить состояние при логауте
|
|
*/
|
|
export function resetState() {
|
|
Object.assign(state, freshState());
|
|
activeUser = null;
|
|
}
|
|
|
|
function storageKey() {
|
|
return activeUser
|
|
? `${CURRENT_STORAGE_PREFIX}${activeUser.id}`
|
|
: GUEST_STORAGE_KEY;
|
|
}
|
|
|
|
export function migrateLegacyStateForUser() {
|
|
if (!activeUser) return;
|
|
|
|
// Уже мигрировали — не трогаем
|
|
if (localStorage.getItem(MIGRATION_FLAG)) return;
|
|
|
|
const key = storageKey();
|
|
|
|
// Если у пользователя уже есть данные — просто помечаем миграцию выполненной
|
|
if (localStorage.getItem(key)) {
|
|
localStorage.setItem(MIGRATION_FLAG, String(activeUser.id));
|
|
return;
|
|
}
|
|
|
|
// Ищем старые данные и переносим первому вошедшему пользователю
|
|
for (const legacyKey of LEGACY_KEYS) {
|
|
const raw = localStorage.getItem(legacyKey);
|
|
if (raw) {
|
|
localStorage.setItem(key, raw);
|
|
localStorage.setItem(MIGRATION_FLAG, String(activeUser.id));
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
export function loadState() {
|
|
migrateLegacyStateForUser();
|
|
|
|
const raw = localStorage.getItem(storageKey());
|
|
|
|
Object.assign(state, freshState());
|
|
|
|
if (raw) {
|
|
try {
|
|
const parsed = JSON.parse(raw);
|
|
Object.assign(state, parsed);
|
|
} catch (e) {
|
|
console.error("Failed to load state", e);
|
|
}
|
|
}
|
|
|
|
if (!Array.isArray(state.workouts)) state.workouts = [];
|
|
if (!Array.isArray(state.exerciseRef)) state.exerciseRef = [];
|
|
if (!Array.isArray(state.bodyMetrics)) state.bodyMetrics = [];
|
|
if (!Array.isArray(state.workoutTypes)) state.workoutTypes = [];
|
|
if (!Array.isArray(state.metricTypes)) state.metricTypes = [];
|
|
if (!Array.isArray(state.clients)) state.clients = [];
|
|
|
|
if (!state.mode) state.mode = "personal";
|
|
normalizeWorkouts();
|
|
}
|
|
|
|
// Допиваем поля, которых может не быть в сохранении старой версии
|
|
function normalizeWorkouts() {
|
|
for (const w of state.workouts || []) {
|
|
if (!Array.isArray(w.exercises)) w.exercises = [];
|
|
if (!Array.isArray(w.cardio)) w.cardio = [];
|
|
if (!Array.isArray(w.setGroups)) w.setGroups = [];
|
|
for (const ex of w.exercises) {
|
|
if (!Array.isArray(ex.sets)) ex.sets = [];
|
|
}
|
|
}
|
|
}
|
|
|
|
export function saveState() {
|
|
localStorage.setItem(storageKey(), JSON.stringify(state));
|
|
updateSyncStatus();
|
|
}
|
|
|
|
export function genId() {
|
|
return (state.nextId++).toString();
|
|
}
|
|
|
|
export function generateUUID() {
|
|
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
const r = (Math.random() * 16) | 0;
|
|
const v = c === "x" ? r : (r & 0x3) | 0x8;
|
|
return v.toString(16);
|
|
});
|
|
}
|
|
|
|
export function updateSyncStatus() {
|
|
const dirty = state.workouts.filter((w) => !w.synced);
|
|
const el = document.getElementById("sync-status");
|
|
if (!el) return;
|
|
|
|
if (dirty.length === 0) {
|
|
el.textContent = "● Всё синхронизировано";
|
|
el.className = "sync-status synced";
|
|
} else {
|
|
el.textContent = `● ${dirty.length} не сохран.`;
|
|
el.className = "sync-status pending";
|
|
}
|
|
}
|
|
|
|
export const CLIENT_COLORS = [
|
|
"#bb86fc",
|
|
"#03dac6",
|
|
"#fbbc04",
|
|
"#cf6679",
|
|
"#64b5f6",
|
|
"#81c784",
|
|
"#ffb74d",
|
|
"#ba68c8",
|
|
"#4dd0e1",
|
|
"#e57373",
|
|
"#aed581",
|
|
"#ffd54f",
|
|
"#9575cd",
|
|
"#4db6ac",
|
|
"#f06292",
|
|
"#7986cb",
|
|
];
|
|
|
|
export const DEFAULT_COLOR = CLIENT_COLORS[0];
|