lots of work done, dashboards added
This commit is contained in:
+136
-57
@@ -1,88 +1,167 @@
|
||||
const STORAGE_KEY = 'gym_tracker_v6';
|
||||
// frontend/js/state.js
|
||||
|
||||
// Палитра из 16 контрастных цветов для клиентов
|
||||
export const CLIENT_COLORS = [
|
||||
'#bb86fc', // фиолетовый (дефолтный для личного режима)
|
||||
'#03dac6', // бирюзовый
|
||||
'#fbbc04', // жёлтый
|
||||
'#cf6679', // розовый
|
||||
'#64b5f6', // голубой
|
||||
'#81c784', // зелёный
|
||||
'#ffb74d', // оранжевый
|
||||
'#ba68c8', // светло-фиолетовый
|
||||
'#4dd0e1', // циан
|
||||
'#e57373', // красный
|
||||
'#aed581', // салатовый
|
||||
'#ffd54f', // янтарный
|
||||
'#9575cd', // пурпурный
|
||||
'#4db6ac', // тиловый
|
||||
'#f06292', // малиновый
|
||||
'#7986cb', // индиго
|
||||
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",
|
||||
];
|
||||
|
||||
export const DEFAULT_COLOR = CLIENT_COLORS[0];
|
||||
const MIGRATION_FLAG = "gym_tracker_legacy_migrated_to_user";
|
||||
|
||||
export const state = {
|
||||
function freshState() {
|
||||
return {
|
||||
workouts: [],
|
||||
exerciseRef: [],
|
||||
bodyMetrics: [],
|
||||
|
||||
workoutTypes: [],
|
||||
metricTypes: [],
|
||||
clients: [], // каждый клиент: {id, sync_id, full_name, birth_date, goal, color}
|
||||
clients: [],
|
||||
|
||||
expandedWorkoutId: null,
|
||||
expandedExerciseId: null,
|
||||
nextId: 1,
|
||||
|
||||
mode: 'personal',
|
||||
currentClientId: null, // больше не используется глобально, но оставим для совместимости
|
||||
};
|
||||
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() {
|
||||
const saved = localStorage.getItem(STORAGE_KEY);
|
||||
if (saved) {
|
||||
try {
|
||||
const parsed = JSON.parse(saved);
|
||||
// Объединяем, чтобы не потерять новые поля при обновлении версии
|
||||
Object.assign(state, parsed);
|
||||
if (!state.workoutTypes) state.workoutTypes = [];
|
||||
if (!state.metricTypes) state.metricTypes = [];
|
||||
if (!state.clients) state.clients = [];
|
||||
if (!state.mode) state.mode = 'personal';
|
||||
} catch (e) {
|
||||
console.error('Failed to load state', e);
|
||||
}
|
||||
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";
|
||||
}
|
||||
|
||||
export function saveState() {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
|
||||
updateSyncStatus();
|
||||
localStorage.setItem(storageKey(), JSON.stringify(state));
|
||||
updateSyncStatus();
|
||||
}
|
||||
|
||||
export function genId() {
|
||||
return (state.nextId++).toString();
|
||||
return (state.nextId++).toString();
|
||||
}
|
||||
|
||||
// Генерация UUID v4 для sync_id (идемпотентность на бэкенде)
|
||||
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);
|
||||
});
|
||||
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';
|
||||
}
|
||||
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];
|
||||
|
||||
Reference in New Issue
Block a user