7 Commits
v1.0.7 ... main

Author SHA1 Message Date
s
a5688f124c chore: release v1.1.0
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 18:16:08 +02:00
s
cf43ada948 feat: système de profils — historiques et drop stats séparés par profil
- Profils stockés dans profiles.json (userData), profil "Défaut" rétro-compatible
- Chaque profil a son propre historique de sessions et app state (fichiers suffixés par id)
- Drop stats : mode Privé (fichier propre) ou Partagé (pool dropstats-shared.json commun)
- Bouton 👤 dans la topbar ouvre une modal de gestion des profils
- Créer, renommer (double-clic), supprimer, activer un profil
- Basculer le mode de drop stats (Privé ↔ Partagé) par profil
- timers et alertes isolés par profil via clés localStorage préfixées par profil id
- Switch de profil = rechargement de page (données propres sans état résiduel)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 18:15:42 +02:00
s
4ce8b41a4c chore: release v1.0.9
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 18:04:41 +02:00
s
0562b326c8 fix: volume slider par alerte, défaut 10%, suppression du pre-cache au démarrage
- Chaque alerte a son propre slider volume (0–100%, step 1, défaut 10%)
- Volume très bas possible (0%) — pas de minimum forcé
- Slider volume aussi dans le formulaire d'ajout pour setter dès la création
- Supprime le pre-cache IndexedDB au démarrage qui ralentissait le lancement
- Supprime le slider volume global (remplacé par le per-alerte)
- Migration automatique des anciennes alertes vers volume=10

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 17:40:35 +02:00
s
857a8477d7 feat: système de sons Minecraft configurable par alerte + volume global
- Volume global réglable (slider, défaut 25%) persisté dans localStorage
- Catalogue de 10 sons Minecraft officiels (Level Up, XP Orb, Item Pop, Pling, Bell, Toast, Challenge, Coffre, Hit, Click)
- Sons téléchargés à la demande depuis le CDN Mojang et cachés en IndexedDB
- Chaque alerte de drop a son propre son sélectionnable via dropdown
- Bouton ▶ preview par alerte et dans la bibliothèque (auto-download si pas en cache)
- Bibliothèque de sons repliable : cards avec preview + statut téléchargé
- Lecture via Web Audio API (AudioContext + GainNode) pour contrôle précis du volume
- Migration automatique des anciennes alertConfigs sans soundId (défaut: levelup)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 17:31:20 +02:00
s
fdbf57a6d6 chore: release v1.0.8
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 17:14:16 +02:00
s
4f7aab646b feat: son Minecraft lvl-up réel pour alertes de drop + diverses améliorations UI
- Remplace le son synthétique Web Audio par le vrai levelup.ogg Minecraft (extrait du CDN Mojang)
- Ajout d'un écran de détail par session dans l'historique (mobs + items avec bars + rates)
- Tooltip interactif sur les graphes en direct et historique (valeur au survol)
- Alertes de drop : suggestions d'items depuis la session et les stats
- Timers : suggestions de mobs depuis session et historique
- Hover highlight sur les lignes du tableau sessions
- Drop board et modal mob : affiche xp/kill et cols/kill quand disponible
- lib/dropstats.js : merge preserve totalExp et totalCols

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 17:14:01 +02:00
7 changed files with 961 additions and 150 deletions

3
.gitignore vendored
View File

@@ -22,5 +22,8 @@ Thumbs.db
.vscode/
.idea/
# Token local (jamais commité)
.gitea-token
# Claude Code
.claude/

View File

@@ -21,12 +21,14 @@ function mergeDropStatsInto(target, source) {
for (const [mobName, mobData] of Object.entries(sourceMobs)) {
if (!mobName) continue;
if (!target.mobs[mobName]) target.mobs[mobName] = { kills: 0, items: {} };
if (!target.mobs[mobName]) target.mobs[mobName] = { kills: 0, totalExp: 0, totalCols: 0, items: {} };
const t = target.mobs[mobName];
const kills = Number(mobData.kills) || 0;
t.kills += kills;
addedKills += kills;
t.totalExp = (t.totalExp || 0) + (Number(mobData.totalExp) || 0);
t.totalCols = (t.totalCols || 0) + (Number(mobData.totalCols) || 0);
const items = mobData.items || {};
for (const [key, item] of Object.entries(items)) {

320
main.js
View File

@@ -4,24 +4,25 @@ const fs = require('fs');
const fsp = fs.promises;
const { emptyDropStats, mergeDropStatsInto } = require('./lib/dropstats');
// Stocké automatiquement dans ~/.config/farm-tracker/ sur Linux (géré par Electron).
const userDataDir = app.getPath('userData');
const APP_STATE_FILE = path.join(userDataDir, 'app-state.json');
const DROPSTATS_FILE = path.join(userDataDir, 'dropstats.json');
// Fichiers globaux (non liés à un profil)
const COMMUNITY_DROPSTATS_FILE = path.join(userDataDir, 'community-dropstats.json');
const SESSION_HISTORY_FILE = path.join(userDataDir, 'session-history.json');
const UPDATE_PREFS_FILE = path.join(userDataDir, 'update-prefs.json');
const UPDATE_PREFS_FILE = path.join(userDataDir, 'update-prefs.json');
const PROFILES_FILE = path.join(userDataDir, 'profiles.json');
// Fichiers legacy (profil "default")
const LEGACY_APP_STATE_FILE = path.join(userDataDir, 'app-state.json');
const LEGACY_DROPSTATS_FILE = path.join(userDataDir, 'dropstats.json');
const LEGACY_SESSION_HISTORY_FILE= path.join(userDataDir, 'session-history.json');
const RELEASES_API = 'https://git.shamiiow.com/api/v1/repos/shamiiow/farm-tracker-sao/releases/latest';
// ---------- Lecture / écriture disque (JSON indenté = facilement lisible) ----------
// ---------- Lecture / écriture disque ----------
function readJsonSafe(filePath, fallback) {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (e) {
return fallback;
}
try { return JSON.parse(fs.readFileSync(filePath, 'utf8')); }
catch { return fallback; }
}
function writeJsonAtomic(filePath, obj) {
@@ -37,22 +38,82 @@ function writeJsonAtomic(filePath, obj) {
}
}
function loadAppState() { return readJsonSafe(APP_STATE_FILE, null); }
function saveAppState(obj) { return writeJsonAtomic(APP_STATE_FILE, obj); }
function loadDropStats() { return readJsonSafe(DROPSTATS_FILE, emptyDropStats()); }
function saveDropStats(obj) { return writeJsonAtomic(DROPSTATS_FILE, obj); }
function loadCommunityDropStats() { return readJsonSafe(COMMUNITY_DROPSTATS_FILE, null); }
function tryUnlink(filePath) { try { fs.unlinkSync(filePath); } catch (_) {} }
function generateId() {
return Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
}
// ---------- Profils ----------
function emptyProfilesData() {
return {
activeProfileId: 'default',
profiles: [{
id: 'default',
name: 'Défaut',
dropStatsMode: 'private',
createdAt: new Date().toISOString()
}]
};
}
function loadProfilesData() {
const data = readJsonSafe(PROFILES_FILE, null);
if (!data) {
const def = emptyProfilesData();
writeJsonAtomic(PROFILES_FILE, def);
return def;
}
// compat : s'assurer que le profil default existe toujours
if (!data.profiles.find(p => p.id === 'default')) {
data.profiles.unshift({ id: 'default', name: 'Défaut', dropStatsMode: 'private', createdAt: new Date().toISOString() });
writeJsonAtomic(PROFILES_FILE, data);
}
return data;
}
function getActiveProfile() {
const data = loadProfilesData();
return data.profiles.find(p => p.id === data.activeProfileId) || data.profiles[0];
}
// ---------- Chemins de fichiers dynamiques selon profil ----------
function profileAppStateFile(p) {
if (!p || p.id === 'default') return LEGACY_APP_STATE_FILE;
return path.join(userDataDir, `app-state-${p.id}.json`);
}
function profileDropStatsFile(p) {
if (!p || p.id === 'default') return LEGACY_DROPSTATS_FILE;
if (p.dropStatsMode === 'shared') return path.join(userDataDir, 'dropstats-shared.json');
return path.join(userDataDir, `dropstats-${p.id}.json`);
}
function profileSessionHistoryFile(p) {
if (!p || p.id === 'default') return LEGACY_SESSION_HISTORY_FILE;
return path.join(userDataDir, `session-history-${p.id}.json`);
}
// ---------- Load / save avec profil actif ----------
function loadAppState() { return readJsonSafe(profileAppStateFile(getActiveProfile()), null); }
function saveAppState(obj) { return writeJsonAtomic(profileAppStateFile(getActiveProfile()), obj); }
function loadDropStats() { return readJsonSafe(profileDropStatsFile(getActiveProfile()), emptyDropStats()); }
function saveDropStats(obj) { return writeJsonAtomic(profileDropStatsFile(getActiveProfile()), obj); }
function loadSessionHistory() { return readJsonSafe(profileSessionHistoryFile(getActiveProfile()), { type: 'farm-tracker-session-history', version: 1, sessions: [] }); }
function saveSessionHistory(o) { return writeJsonAtomic(profileSessionHistoryFile(getActiveProfile()), o); }
function loadCommunityDropStats() { return readJsonSafe(COMMUNITY_DROPSTATS_FILE, null); }
function saveCommunityDropStats(obj) { return writeJsonAtomic(COMMUNITY_DROPSTATS_FILE, obj); }
function loadSessionHistory() { return readJsonSafe(SESSION_HISTORY_FILE, { type: 'farm-tracker-session-history', version: 1, sessions: [] }); }
function saveSessionHistory(obj) { return writeJsonAtomic(SESSION_HISTORY_FILE, obj); }
function loadUpdatePrefs() { return readJsonSafe(UPDATE_PREFS_FILE, { snoozedUntil: null }); }
function saveUpdatePrefs(obj) { return writeJsonAtomic(UPDATE_PREFS_FILE, obj); }
function loadUpdatePrefs() { return readJsonSafe(UPDATE_PREFS_FILE, { snoozedUntil: null }); }
function saveUpdatePrefs(obj) { return writeJsonAtomic(UPDATE_PREFS_FILE, obj); }
function resolveLogPath(folderPath) {
const candidate1 = path.join(folderPath, 'logs', 'latest.log');
const candidate2 = path.join(folderPath, 'latest.log');
if (fs.existsSync(candidate1)) return candidate1;
if (fs.existsSync(candidate2)) return candidate2;
const c1 = path.join(folderPath, 'logs', 'latest.log');
const c2 = path.join(folderPath, 'latest.log');
if (fs.existsSync(c1)) return c1;
if (fs.existsSync(c2)) return c2;
return null;
}
@@ -138,11 +199,7 @@ function downloadFileWithProgress(url, destPath, onProgress) {
async function downloadAndInstall(downloadUrl, version) {
if (!app.isPackaged) {
dialog.showMessageBox(mainWindow, {
type: 'info', title: 'Mode développement',
message: 'Auto-install non disponible en mode dev.',
buttons: ['OK']
});
dialog.showMessageBox(mainWindow, { type: 'info', title: 'Mode développement', message: 'Auto-install non disponible en mode dev.', buttons: ['OK'] });
return;
}
const ext = process.platform === 'win32' ? '.exe' : '.AppImage';
@@ -169,44 +226,28 @@ async function downloadAndInstall(downloadUrl, version) {
async function showUpdateDialog(version, downloadUrl, ignoreSnooze = false) {
const current = app.getVersion();
if (!isNewerVersion(version, current)) return false;
if (!ignoreSnooze) {
const prefs = loadUpdatePrefs();
if (prefs.snoozedUntil === 'indefinite') return false;
if (prefs.snoozedUntil && new Date(prefs.snoozedUntil) > new Date()) return false;
}
const { response } = await dialog.showMessageBox(mainWindow, {
type: 'info',
title: 'Mise à jour disponible',
message: `Version ${version} disponible`,
type: 'info', title: 'Mise à jour disponible', message: `Version ${version} disponible`,
detail: `Version actuelle : ${current}\nL'application se relancera automatiquement après la mise à jour.`,
buttons: ['Installer maintenant', 'Me rappeler dans...'],
defaultId: 0,
cancelId: 1
buttons: ['Installer maintenant', 'Me rappeler dans...'], defaultId: 0, cancelId: 1
});
if (response === 0) {
downloadAndInstall(downloadUrl, version);
return true;
}
if (response === 0) { downloadAndInstall(downloadUrl, version); return true; }
const { response: snoozeResponse } = await dialog.showMessageBox(mainWindow, {
type: 'question',
title: 'Me rappeler dans...',
type: 'question', title: 'Me rappeler dans...',
message: 'Ne plus afficher cette mise à jour pendant :',
buttons: SNOOZE_OPTIONS.map(o => o.label),
defaultId: 0,
cancelId: SNOOZE_OPTIONS.length - 1
buttons: SNOOZE_OPTIONS.map(o => o.label), defaultId: 0, cancelId: SNOOZE_OPTIONS.length - 1
});
const chosen = SNOOZE_OPTIONS[snoozeResponse];
if (chosen.days === -1) return false;
if (chosen.days === null) {
saveUpdatePrefs({ snoozedUntil: 'indefinite' });
} else {
const until = new Date();
until.setDate(until.getDate() + chosen.days);
const until = new Date(); until.setDate(until.getDate() + chosen.days);
saveUpdatePrefs({ snoozedUntil: until.toISOString() });
}
return false;
@@ -219,25 +260,18 @@ async function checkForUpdates(ignoreSnooze = false) {
const downloadUrl = resolveAssetUrl(release);
if (!version || !downloadUrl) return false;
return await showUpdateDialog(version, downloadUrl, ignoreSnooze);
} catch (_) {
return false;
}
} catch (_) { return false; }
}
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1180,
height: 880,
minWidth: 760,
minHeight: 600,
backgroundColor: '#0B0F0C',
autoHideMenuBar: true,
width: 1180, height: 880, minWidth: 760, minHeight: 600,
backgroundColor: '#0B0F0C', autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
contextIsolation: true, nodeIntegration: false
}
});
mainWindow.setMenuBarVisibility(false);
@@ -265,7 +299,7 @@ app.whenReady().then(() => {
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
// ---------- IPC : sélection et lecture du dossier Minecraft ----------
// ---------- IPC : dossier Minecraft ----------
ipcMain.handle('pick-folder', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
@@ -275,18 +309,13 @@ ipcMain.handle('pick-folder', async () => {
if (result.canceled || !result.filePaths.length) return { canceled: true };
const folder = result.filePaths[0];
const logPath = resolveLogPath(folder);
if (!logPath) {
return {
canceled: false,
error: 'Impossible de trouver "latest.log" dans ce dossier ni dans son sous-dossier "logs". Sélectionne ton dossier .minecraft, ou le dossier logs directement.'
};
}
if (!logPath) return { canceled: false, error: 'Impossible de trouver "latest.log" dans ce dossier ni dans son sous-dossier "logs". Sélectionne ton dossier .minecraft, ou le dossier logs directement.' };
return { canceled: false, logPath };
});
ipcMain.handle('check-log-path', async (event, logPath) => {
try { await fsp.access(logPath, fs.constants.R_OK); return { ok: true }; }
catch (e) { return { ok: false }; }
catch { return { ok: false }; }
});
ipcMain.handle('get-file-size', async (event, logPath) => {
@@ -303,52 +332,38 @@ ipcMain.handle('read-chunk', async (event, logPath, start, end) => {
const buffer = Buffer.alloc(length);
await fd.read(buffer, 0, length, start);
return { text: buffer.toString('utf8') };
} catch (e) {
return { text: '', error: e.message };
} finally {
if (fd) await fd.close().catch(() => {});
}
} catch (e) { return { text: '', error: e.message }; }
finally { if (fd) await fd.close().catch(() => {}); }
});
// ---------- IPC : état général de l'appli ----------
// ---------- IPC : état application (par profil) ----------
ipcMain.handle('load-app-state', async () => loadAppState());
ipcMain.handle('save-app-state', async (event, obj) => saveAppState(obj));
ipcMain.handle('load-app-state', async () => loadAppState());
ipcMain.handle('save-app-state', async (_, obj) => saveAppState(obj));
// ---------- IPC : stats de chance de drop personnelles ----------
// ---------- IPC : drop stats (par profil) ----------
ipcMain.handle('load-drop-stats', async () => loadDropStats());
ipcMain.handle('save-drop-stats', async (event, obj) => saveDropStats(obj));
ipcMain.handle('save-drop-stats', async (_, obj) => saveDropStats(obj));
ipcMain.handle('export-drop-stats', async () => {
const current = loadDropStats();
const defaultName = 'farm-tracker-dropstats-' + new Date().toISOString().slice(0, 10) + '.json';
const result = await dialog.showSaveDialog(mainWindow, {
title: 'Exporter mes stats de chance de drop',
defaultPath: defaultName,
filters: [{ name: 'JSON', extensions: ['json'] }]
});
const result = await dialog.showSaveDialog(mainWindow, { title: 'Exporter mes stats de chance de drop', defaultPath: defaultName, filters: [{ name: 'JSON', extensions: ['json'] }] });
if (result.canceled || !result.filePath) return { canceled: true };
fs.writeFileSync(result.filePath, JSON.stringify(current, null, 2));
return { canceled: false, filePath: result.filePath };
});
ipcMain.handle('import-merge-drop-stats', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
title: 'Importer et fusionner des fichiers de stats de drop (plusieurs fichiers possibles)',
properties: ['openFile', 'multiSelections'],
filters: [{ name: 'JSON', extensions: ['json'] }]
});
const result = await dialog.showOpenDialog(mainWindow, { title: 'Importer et fusionner des fichiers de stats de drop', properties: ['openFile', 'multiSelections'], filters: [{ name: 'JSON', extensions: ['json'] }] });
if (result.canceled || !result.filePaths.length) return { canceled: true };
const current = loadDropStats();
const details = [];
let totalAdded = 0;
for (const filePath of result.filePaths) {
try {
const raw = fs.readFileSync(filePath, 'utf8');
const data = JSON.parse(raw);
const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
const added = mergeDropStatsInto(current, data);
totalAdded += added;
details.push({ file: path.basename(filePath), addedKills: added, ok: true });
@@ -356,23 +371,82 @@ ipcMain.handle('import-merge-drop-stats', async () => {
details.push({ file: path.basename(filePath), ok: false, error: e.message });
}
}
current.updatedAt = new Date().toISOString();
saveDropStats(current);
return { canceled: false, totalAdded, details, dropStats: current };
});
// ---------- IPC : stats communautaires (reçues du serveur de sync) ----------
// ---------- IPC : stats communautaires (globales) ----------
ipcMain.handle('load-community-drop-stats', async () => loadCommunityDropStats());
ipcMain.handle('save-community-drop-stats', async (event, obj) => saveCommunityDropStats(obj));
ipcMain.handle('get-file-paths', () => ({ dropStats: DROPSTATS_FILE, communityDropStats: COMMUNITY_DROPSTATS_FILE }));
ipcMain.handle('load-community-drop-stats', async () => loadCommunityDropStats());
ipcMain.handle('save-community-drop-stats', async (_, obj) => saveCommunityDropStats(obj));
ipcMain.handle('get-file-paths', () => ({
dropStats: profileDropStatsFile(getActiveProfile()),
communityDropStats: COMMUNITY_DROPSTATS_FILE
}));
// ---------- IPC : historique des sessions ----------
// ---------- IPC : historique des sessions (par profil) ----------
ipcMain.handle('load-session-history', async () => loadSessionHistory());
ipcMain.handle('save-session-history', async (event, obj) => saveSessionHistory(obj));
ipcMain.handle('save-session-history', async (_, obj) => saveSessionHistory(obj));
// ---------- IPC : profils ----------
ipcMain.handle('get-profiles', () => loadProfilesData());
ipcMain.handle('create-profile', (_, { name, dropStatsMode }) => {
const data = loadProfilesData();
const newProfile = {
id: generateId(),
name: (name || 'Nouveau profil').trim().slice(0, 40),
dropStatsMode: dropStatsMode === 'shared' ? 'shared' : 'private',
createdAt: new Date().toISOString()
};
data.profiles.push(newProfile);
writeJsonAtomic(PROFILES_FILE, data);
return data;
});
ipcMain.handle('switch-profile', (_, id) => {
const data = loadProfilesData();
if (!data.profiles.find(p => p.id === id)) return { ok: false, error: 'Profil introuvable' };
data.activeProfileId = id;
writeJsonAtomic(PROFILES_FILE, data);
return { ok: true };
});
ipcMain.handle('rename-profile', (_, { id, name }) => {
const data = loadProfilesData();
const profile = data.profiles.find(p => p.id === id);
if (!profile) return { ok: false };
profile.name = (name || '').trim().slice(0, 40) || profile.name;
writeJsonAtomic(PROFILES_FILE, data);
return { ok: true, profile };
});
ipcMain.handle('delete-profile', (_, id) => {
if (id === 'default') return { ok: false, error: 'Le profil Défaut ne peut pas être supprimé.' };
const data = loadProfilesData();
const profile = data.profiles.find(p => p.id === id);
if (!profile) return { ok: false, error: 'Profil introuvable' };
data.profiles = data.profiles.filter(p => p.id !== id);
if (data.activeProfileId === id) data.activeProfileId = 'default';
// supprimer les fichiers du profil
tryUnlink(path.join(userDataDir, `app-state-${id}.json`));
tryUnlink(path.join(userDataDir, `dropstats-${id}.json`));
tryUnlink(path.join(userDataDir, `session-history-${id}.json`));
writeJsonAtomic(PROFILES_FILE, data);
return { ok: true, newActiveId: data.activeProfileId };
});
ipcMain.handle('set-drop-stats-mode', (_, { id, mode }) => {
const data = loadProfilesData();
const profile = data.profiles.find(p => p.id === id);
if (!profile) return { ok: false };
profile.dropStatsMode = mode === 'shared' ? 'shared' : 'private';
writeJsonAtomic(PROFILES_FILE, data);
return { ok: true };
});
// ---------- IPC : mise à jour ----------
@@ -382,28 +456,20 @@ ipcMain.handle('check-update-manual', async () => {
const version = (release.tag_name || '').replace(/^v/, '');
const downloadUrl = resolveAssetUrl(release);
const current = app.getVersion();
if (!version || !downloadUrl || !isNewerVersion(version, current)) {
return { checked: true, hasUpdate: false, current };
}
if (!version || !downloadUrl || !isNewerVersion(version, current)) return { checked: true, hasUpdate: false, current };
await showUpdateDialog(version, downloadUrl, true);
return { checked: true, hasUpdate: true };
} catch (e) {
return { checked: false, error: e.message };
}
} catch (e) { return { checked: false, error: e.message }; }
});
// ---------- IPC : sync avec le serveur VPS ----------
// ---------- IPC : sync VPS ----------
ipcMain.handle('fetch-community-stats', async (event, { serverUrl }) => {
ipcMain.handle('fetch-community-stats', async (_, { serverUrl }) => {
return new Promise((resolve) => {
try {
const url = new URL('/stats', serverUrl);
const mod = url.protocol === 'https:' ? require('https') : require('http');
const req = mod.get({
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: '/stats'
}, (res) => {
const req = mod.get({ hostname: url.hostname, port: url.port || (url.protocol === 'https:' ? 443 : 80), path: '/stats' }, (res) => {
let data = '';
res.on('data', chunk => { data += chunk; });
res.on('end', () => {
@@ -413,27 +479,20 @@ ipcMain.handle('fetch-community-stats', async (event, { serverUrl }) => {
});
req.setTimeout(15000, () => { req.destroy(); resolve({ ok: false, error: 'Timeout (15s)' }); });
req.on('error', (e) => resolve({ ok: false, error: e.message }));
} catch (e) {
resolve({ ok: false, error: e.message });
}
} catch (e) { resolve({ ok: false, error: e.message }); }
});
});
ipcMain.handle('sync-drop-stats', async (event, { serverUrl, clientId, dropStats }) => {
ipcMain.handle('sync-drop-stats', async (_, { serverUrl, clientId, dropStats }) => {
return new Promise((resolve) => {
try {
const url = new URL('/sync', serverUrl);
const body = JSON.stringify({ clientId, dropStats });
const mod = url.protocol === 'https:' ? require('https') : require('http');
const options = {
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: '/sync',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body)
}
hostname: url.hostname, port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: '/sync', method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }
};
const req = mod.request(options, (res) => {
let data = '';
@@ -445,10 +504,7 @@ ipcMain.handle('sync-drop-stats', async (event, { serverUrl, clientId, dropStats
});
req.setTimeout(15000, () => { req.destroy(); resolve({ ok: false, error: 'Timeout (15s)' }); });
req.on('error', (e) => resolve({ ok: false, error: e.message }));
req.write(body);
req.end();
} catch (e) {
resolve({ ok: false, error: e.message });
}
req.write(body); req.end();
} catch (e) { resolve({ ok: false, error: e.message }); }
});
});

View File

@@ -1,6 +1,6 @@
{
"name": "farm-tracker",
"version": "1.0.7",
"version": "1.1.0",
"description": "Suivi de loot Minecraft en direct, avec sauvegarde automatique des stats et des chances de drop.",
"main": "main.js",
"scripts": {

View File

@@ -25,5 +25,12 @@ contextBridge.exposeInMainWorld('api', {
saveSessionHistory: (obj) => ipcRenderer.invoke('save-session-history', obj),
checkUpdateManual: () => ipcRenderer.invoke('check-update-manual'),
onUpdateProgress: (cb) => ipcRenderer.on('update-progress', (_, data) => cb(data))
onUpdateProgress: (cb) => ipcRenderer.on('update-progress', (_, data) => cb(data)),
getProfiles: () => ipcRenderer.invoke('get-profiles'),
createProfile: (name, mode) => ipcRenderer.invoke('create-profile', { name, dropStatsMode: mode }),
switchProfile: (id) => ipcRenderer.invoke('switch-profile', id),
renameProfile: (id, name) => ipcRenderer.invoke('rename-profile', { id, name }),
deleteProfile: (id) => ipcRenderer.invoke('delete-profile', id),
setDropStatsMode: (id, mode) => ipcRenderer.invoke('set-drop-stats-mode', { id, mode }),
});

View File

@@ -290,6 +290,7 @@
.sessions-table td.hl{font-family:var(--font-mono);color:var(--text);}
.sessions-table td.dim{font-size:12px;color:var(--text-dim);}
.hist-empty{padding:40px 0;text-align:center;color:var(--text-dim);font-size:14px;line-height:1.8;}
.sessions-table tbody tr:hover td{background:rgba(255,255,255,.03);}
@media(max-width:760px){.charts-2col{grid-template-columns:1fr;}}
/* ---------- Graphes en direct ---------- */
@@ -325,6 +326,49 @@
.timer-card-bar{height:3px;background:var(--border);margin-top:10px;overflow:hidden;}
.timer-card-bar-fill{height:100%;transition:width .9s linear;}
.timer-empty-msg{color:var(--text-dim);font-size:13px;padding:20px 0;}
/* --- Volume slider --- */
input[type=range]{-webkit-appearance:none;height:3px;background:var(--border);outline:none;cursor:pointer;flex:1;}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:11px;height:11px;background:var(--moss);cursor:pointer;}
input[type=range]::-moz-range-thumb{width:11px;height:11px;background:var(--moss);cursor:pointer;border:none;}
/* --- Alert config rows --- */
.alert-cfg-row{display:flex;align-items:center;gap:8px;padding:7px 0;border-bottom:1px solid var(--border);}
.alert-cfg-row:last-child{border-bottom:none;}
.alert-cfg-name{flex:1;font-size:12px;font-weight:600;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.alert-cfg-sound{font-size:11px;background:var(--bg);border:1px solid var(--border);color:var(--text);
padding:2px 5px;cursor:pointer;max-width:140px;}
/* --- Sound library --- */
.sound-lib-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;margin-top:10px;}
.sound-card{background:var(--bg);border:1px solid var(--border);padding:10px 12px;
display:flex;flex-direction:column;gap:5px;}
.sound-card-name{font-size:12px;font-weight:600;}
.sound-card-desc{font-size:11px;color:var(--text-dim);}
.sound-card-actions{display:flex;gap:6px;align-items:center;margin-top:2px;}
.sound-card-status{font-size:10px;font-family:var(--font-mono);color:var(--moss);margin-left:auto;}
/* --- Profils --- */
#profileBtn{font-size:11px;max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.profile-modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.65);z-index:900;display:flex;align-items:center;justify-content:center;}
.profile-modal-overlay[hidden]{display:none;}
.profile-modal-box{background:var(--bg-panel);border:1px solid var(--border);padding:22px 24px;width:460px;max-width:95vw;max-height:80vh;overflow-y:auto;display:flex;flex-direction:column;gap:14px;}
.profile-modal-box h3{font-size:14px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;margin:0;}
.profile-list{display:flex;flex-direction:column;gap:6px;}
.profile-row{display:flex;align-items:center;gap:8px;padding:8px 10px;border:1px solid var(--border);background:var(--bg);}
.profile-row.active{border-color:var(--moss);}
.profile-row-name{flex:1;font-size:13px;font-weight:600;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.profile-row-mode{font-size:10px;font-family:var(--font-mono);padding:2px 6px;border:1px solid var(--border);color:var(--text-dim);cursor:pointer;white-space:nowrap;}
.profile-row-mode.shared{color:var(--corrupt);border-color:var(--corrupt);}
.profile-create-form{display:flex;flex-direction:column;gap:8px;padding:10px;border:1px solid var(--border);background:var(--bg);}
.profile-create-form input[type=text]{width:100%;box-sizing:border-box;}
.profile-mode-row{display:flex;gap:16px;font-size:12px;color:var(--text-dim);}
.profile-mode-row label{display:flex;align-items:center;gap:5px;cursor:pointer;}
.profile-mode-desc{font-size:11px;color:var(--text-dim);line-height:1.5;}
#chartTip{position:fixed;z-index:1001;background:var(--bg-panel);border:1px solid var(--border);
padding:4px 10px;font-family:var(--font-mono);font-size:11px;color:var(--text);
pointer-events:none;display:none;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,.5);}
</style>
</head>
<body>
@@ -333,11 +377,39 @@
<div class="shell-topbar">
<div class="brand" id="brandHome"><span class="brand-mark"></span><span class="brand-text">FARM TRACKER</span></div>
<div class="spacer"></div>
<button class="btn-ghost small" id="profileBtn">👤 …</button>
<button class="btn-ghost" id="homeBtn" hidden>🏠 Accueil</button>
<button class="btn-ghost" id="changeFolderBtn" hidden>Changer de dossier</button>
<button class="btn-ghost small" id="checkUpdateBtn" title="Vérifier les mises à jour">Mises à jour</button>
</div>
<!-- Modal profils -->
<div class="profile-modal-overlay" id="profileModal" hidden>
<div class="profile-modal-box">
<div style="display:flex;justify-content:space-between;align-items:center;">
<h3>Profils</h3>
<button class="btn-ghost small" id="profileModalClose"></button>
</div>
<div class="profile-list" id="profileList"></div>
<div class="profile-create-form" id="profileCreateForm" hidden>
<input type="text" id="profileNewName" placeholder="Nom du profil" maxlength="40">
<div class="profile-mode-row">
<label><input type="radio" name="newProfileMode" value="private" checked> Stats de drop privées</label>
<label><input type="radio" name="newProfileMode" value="shared"> Stats de drop partagées</label>
</div>
<p class="profile-mode-desc" id="profileModeDesc">
<strong>Privé :</strong> ce profil a ses propres chances de drop, indépendantes des autres.<br>
<strong>Partagé :</strong> ce profil partage le même pool de drop stats que tous les autres profils en mode partagé.
</p>
<div style="display:flex;gap:8px;">
<button class="btn-ghost small" id="profileCreateCancel">Annuler</button>
<button class="btn-ghost accent small" id="profileCreateConfirm">Créer le profil</button>
</div>
</div>
<button class="btn-ghost small" id="profileNewBtn" style="align-self:flex-start;">+ Nouveau profil</button>
</div>
</div>
<!-- ============ ÉCRAN 1 : choix du dossier (une seule fois, global) ============ -->
<section class="connect-screen" id="folderScreen">
<div class="connect-card">
@@ -640,6 +712,47 @@
</section>
<!-- ============ ÉCRAN 6 : Détail session ============ -->
<section class="app-screen" id="appSessionDetail" hidden>
<div style="display:flex;align-items:center;gap:12px;margin-bottom:4px;">
<button class="btn-ghost small" id="sessionDetailBackBtn">← Historique</button>
<span id="sessionDetailTitle" style="font-size:13px;color:var(--text-dim);"></span>
</div>
<div class="hero" id="sessionDetailHero">
<div class="hero-stat">
<p class="eyebrow">Durée</p>
<p class="hero-number" id="sdDur"></p>
</div>
<div class="hero-stat">
<p class="eyebrow">Kills</p>
<p class="hero-number" id="sdKills"></p>
<p class="hero-sub" id="sdKillsRate"></p>
</div>
<div class="hero-stat">
<p class="eyebrow">Exp</p>
<p class="hero-number" id="sdExp"></p>
<p class="hero-sub" id="sdExpRate"></p>
</div>
<div class="hero-stat">
<p class="eyebrow">Kamas</p>
<p class="hero-number" id="sdKamas"></p>
<p class="hero-sub" id="sdCols"></p>
</div>
</div>
<div class="charts-2col" id="sessionDetailPanels">
<div class="panel">
<h2>Mobs tués</h2>
<div id="sdMobList" class="bars" style="max-height:none;"></div>
</div>
<div class="panel">
<h2>Top items lootés</h2>
<div id="sdItemList" class="bars" style="max-height:none;"></div>
</div>
</div>
</section>
<!-- ============ ÉCRAN 4 : Drop Board ============ -->
<section class="app-screen" id="appDropBoard" hidden>
@@ -661,7 +774,8 @@
<h2>Ajouter un timer</h2>
</div>
<div class="timer-add-row">
<input type="text" id="timerMobInput" placeholder="Nom du mob (ex: Skeleton)" style="flex:2;">
<input type="text" id="timerMobInput" placeholder="Nom du mob (ex: Skeleton)" style="flex:2;" list="timerMobSuggestions" autocomplete="off">
<datalist id="timerMobSuggestions"></datalist>
<input type="text" id="timerDurInput" placeholder="Durée (ex: 5:00 ou 90)" style="flex:1;max-width:130px;">
<button class="btn-ghost" id="timerAddBtn">Ajouter</button>
</div>
@@ -677,6 +791,38 @@
<div id="timerActiveGrid" class="timer-active-grid"></div>
</div>
<div class="panel">
<div class="panel-head-row">
<h2>Alertes de drop</h2>
</div>
<div class="timer-add-row" style="flex-wrap:wrap;gap:6px;">
<input type="text" id="alertItemInput" placeholder="Nom de l'item (ex: Diamond)" style="flex:2;min-width:140px;" list="alertItemSuggestions" autocomplete="off">
<datalist id="alertItemSuggestions"></datalist>
<select id="alertSoundSelect" class="alert-cfg-sound"></select>
<div style="display:flex;align-items:center;gap:5px;">
<span style="font-size:10px;color:var(--text-dim);">Vol</span>
<input type="range" id="alertVolumeInput" min="0" max="100" step="1" value="10" style="width:64px;">
<span id="alertVolumeVal" style="font-size:10px;font-family:var(--font-mono);color:var(--text-dim);min-width:26px;">10%</span>
</div>
<button class="btn-ghost" id="alertAddBtn">Ajouter</button>
</div>
<p style="font-size:11.5px;color:var(--text-dim);margin:6px 0 4px;">Chaque alerte a son propre son et volume.</p>
<div id="alertConfigList"></div>
</div>
<div class="panel">
<div class="panel-head-row" id="soundLibToggle" style="cursor:pointer;user-select:none;">
<h2>Bibliothèque de sons Minecraft</h2>
<span id="soundLibArrow" style="margin-left:auto;font-size:11px;color:var(--text-dim);">▶ ouvrir</span>
</div>
<div id="soundLibContent" hidden>
<p style="font-size:11.5px;color:var(--text-dim);margin:0 0 8px;">
Sons téléchargés depuis le CDN officiel Mojang. Clic ▶ pour prévisualiser, ⬇ pour télécharger.
</p>
<div class="sound-lib-grid" id="soundLibGrid"></div>
</div>
</div>
</section>
</div>
@@ -731,6 +877,8 @@
</div>
</div>
<div id="chartTip"></div>
<!-- Menu contextuel "qui drop cet item ?" -->
<div class="item-ctx-menu" id="itemCtxMenu">
<div class="item-ctx-title">Qui drop cet item ?</div>
@@ -799,6 +947,148 @@
const $ = (id) => document.getElementById(id);
// ======================================================================
// PROFILS
// ======================================================================
let _profiles = null; // { activeProfileId, profiles: [...] }
let _activeProfile = null; // profil actif
async function loadProfiles() {
_profiles = await window.api.getProfiles();
_activeProfile = _profiles.profiles.find(p => p.id === _profiles.activeProfileId) || _profiles.profiles[0];
renderProfileBtn();
}
function renderProfileBtn() {
const btn = $('profileBtn');
if (btn && _activeProfile) btn.textContent = '👤 ' + _activeProfile.name;
}
// Clé localStorage préfixée par profil (compat : profil "default" = clé sans préfixe)
function lsKey(key) {
if (!_activeProfile || _activeProfile.id === 'default') return key;
return _activeProfile.id + ':' + key;
}
function renderProfileModal() {
const list = $('profileList');
if (!list || !_profiles) return;
list.innerHTML = _profiles.profiles.map(p => {
const isActive = p.id === _profiles.activeProfileId;
const modeLabel = p.dropStatsMode === 'shared' ? 'Partagé' : 'Privé';
const modeClass = p.dropStatsMode === 'shared' ? 'shared' : '';
return '<div class="profile-row' + (isActive ? ' active' : '') + '" data-profile-id="' + escHtml(p.id) + '">' +
'<span class="profile-row-name">' + (isActive ? '● ' : '') + escHtml(p.name) + '</span>' +
'<button class="profile-row-mode ' + modeClass + '" data-toggle-mode="' + escHtml(p.id) + '" title="Cliquer pour changer le mode de drop stats">' + modeLabel + '</button>' +
(isActive ? '' : '<button class="btn-ghost small" data-switch-profile="' + escHtml(p.id) + '">Activer</button>') +
(p.id !== 'default' && !isActive ? '<button class="btn-ghost small danger" data-delete-profile="' + escHtml(p.id) + '">✕</button>' : '') +
'</div>';
}).join('');
}
$('profileBtn').addEventListener('click', () => {
renderProfileModal();
$('profileModal').hidden = false;
$('profileCreateForm').hidden = true;
});
$('profileModalClose').addEventListener('click', () => { $('profileModal').hidden = true; });
$('profileModal').addEventListener('click', e => { if (e.target === $('profileModal')) $('profileModal').hidden = true; });
$('profileNewBtn').addEventListener('click', () => {
$('profileCreateForm').hidden = false;
$('profileNewBtn').hidden = true;
$('profileNewName').value = '';
$('profileNewName').focus();
});
$('profileCreateCancel').addEventListener('click', () => {
$('profileCreateForm').hidden = true;
$('profileNewBtn').hidden = false;
});
$('profileCreateConfirm').addEventListener('click', async () => {
const name = $('profileNewName').value.trim();
if (!name) return;
const mode = document.querySelector('input[name="newProfileMode"]:checked')?.value || 'private';
_profiles = await window.api.createProfile(name, mode);
_activeProfile = _profiles.profiles.find(p => p.id === _profiles.activeProfileId) || _profiles.profiles[0];
$('profileCreateForm').hidden = true;
$('profileNewBtn').hidden = false;
renderProfileModal();
});
$('profileList').addEventListener('click', async e => {
const switchId = e.target.dataset.switchProfile;
if (switchId) {
await window.api.switchProfile(switchId);
location.reload();
return;
}
const deleteId = e.target.dataset.deleteProfile;
if (deleteId) {
if (!confirm('Supprimer ce profil ? L\'historique et les stats de drop privées seront effacés définitivement.')) return;
const res = await window.api.deleteProfile(deleteId);
if (res.ok) {
_profiles = await window.api.getProfiles();
renderProfileModal();
}
return;
}
const toggleId = e.target.dataset.toggleMode;
if (toggleId) {
const p = _profiles.profiles.find(pr => pr.id === toggleId);
if (!p) return;
const newMode = p.dropStatsMode === 'shared' ? 'private' : 'shared';
await window.api.setDropStatsMode(toggleId, newMode);
_profiles = await window.api.getProfiles();
_activeProfile = _profiles.profiles.find(pr => pr.id === _profiles.activeProfileId) || _profiles.profiles[0];
renderProfileModal();
// si c'est le profil actif, reload pour recharger les drop stats
if (toggleId === _profiles.activeProfileId) {
if (confirm('Mode de drop stats changé. Recharger pour appliquer ?')) location.reload();
}
}
});
// Renommage double-clic sur le nom
$('profileList').addEventListener('dblclick', async e => {
const row = e.target.closest('.profile-row');
if (!row) return;
const id = row.dataset.profileId;
const nameEl = row.querySelector('.profile-row-name');
if (!nameEl) return;
const current = _profiles.profiles.find(p => p.id === id);
if (!current) return;
const newName = prompt('Renommer le profil :', current.name);
if (!newName || !newName.trim()) return;
await window.api.renameProfile(id, newName.trim());
_profiles = await window.api.getProfiles();
_activeProfile = _profiles.profiles.find(p => p.id === _profiles.activeProfileId) || _profiles.profiles[0];
renderProfileBtn();
renderProfileModal();
});
// ---------- Tooltip pour les graphes ----------
const chartTip = $('chartTip');
function showChartTip(text, cx, cy){
chartTip.textContent = text;
chartTip.style.display = 'block';
chartTip.style.left = Math.min(cx + 14, window.innerWidth - 170) + 'px';
chartTip.style.top = Math.min(cy - 30, window.innerHeight - 44) + 'px';
}
function hideChartTip(){ chartTip.style.display = 'none'; }
function attachChartTip(svg){
if (!svg) return;
svg.addEventListener('mouseover', e => { if (e.target.dataset.tip) showChartTip(e.target.dataset.tip, e.clientX, e.clientY); });
svg.addEventListener('mouseout', e => { if (e.target.dataset.tip) hideChartTip(); });
svg.addEventListener('mousemove', e => {
if (e.target.dataset.tip){
chartTip.style.left = Math.min(e.clientX + 14, window.innerWidth - 170) + 'px';
chartTip.style.top = Math.min(e.clientY - 30, window.innerHeight - 44) + 'px';
}
});
svg.addEventListener('mouseleave', hideChartTip);
}
// ======================================================================
// SHELL : navigation entre écrans (dossier -> accueil -> outils)
// ======================================================================
@@ -809,7 +1099,8 @@
farmTracker: $('appFarmTracker'),
dropBoard: $('appDropBoard'),
history: $('appHistory'),
timers: $('appTimers')
timers: $('appTimers'),
sessionDetail: $('appSessionDetail')
};
const homeBtn = $('homeBtn');
const changeFolderBtn = $('changeFolderBtn');
@@ -895,7 +1186,7 @@
for (const [key, it] of entry.items.entries()){
items[key] = {name: mcPlain(it.rawName) || it.name || '', rawName: it.rawName, occurrences: it.occurrences, totalQty: it.totalQty};
}
mobs[mobName] = {kills: entry.kills, items};
mobs[mobName] = {kills: entry.kills, totalExp: entry.totalExp || 0, totalCols: entry.totalCols || 0, items};
}
return {type: 'farm-tracker-dropstats', version: 1, updatedAt: new Date().toISOString(), mobs};
}
@@ -906,7 +1197,7 @@
for (const [key, it] of Object.entries(mobData.items || {})){
items.set(key, {rawName: it.rawName || it.name || '', occurrences: it.occurrences || 0, totalQty: it.totalQty || 0});
}
map.set(mobName, {kills: mobData.kills || 0, items});
map.set(mobName, {kills: mobData.kills || 0, totalExp: mobData.totalExp || 0, totalCols: mobData.totalCols || 0, items});
}
return map;
}
@@ -1280,9 +1571,11 @@
state.killCols += col;
triggerTimer(mobPlain);
if (!state.dropStats.has(mobPlain)) state.dropStats.set(mobPlain, {kills: 0, items: new Map()});
if (!state.dropStats.has(mobPlain)) state.dropStats.set(mobPlain, {kills: 0, totalExp: 0, totalCols: 0, items: new Map()});
const dropEntry = state.dropStats.get(mobPlain);
dropEntry.kills += 1;
dropEntry.totalExp = (dropEntry.totalExp || 0) + exp;
dropEntry.totalCols = (dropEntry.totalCols || 0) + col;
const items = Array.isArray(data.items) ? data.items : [];
const feedItems = [];
@@ -1303,6 +1596,12 @@
dropEntry.items.set(key, dropItem);
feedItems.push({rawName: it.name || '', qty: amt, key});
if (alertConfigs.length){
const pn = mcPlain(it.name || '').toLowerCase();
for (const alert of alertConfigs){
if (pn && alert.nameLower && pn.includes(alert.nameLower)){ playAlert(alert); break; }
}
}
}
state.feedEntries.unshift({time: Date.now(), mobRaw, mobPlain, exp, col, items: feedItems});
@@ -1370,7 +1669,7 @@
if (state.timelineTimer){ clearInterval(state.timelineTimer); state.timelineTimer = null; }
}
function drawLiveChart(container, rates, colorHex){
function drawLiveChart(container, rates, colorHex, unit){
if (rates.length < 2){
container.innerHTML = '<p class="chart-empty" style="font-size:11px;padding:6px 0;">En attente…</p>';
return;
@@ -1386,12 +1685,19 @@
const y=(padT+plotH*(1-pct)).toFixed(1);
return '<line x1="'+padL+'" y1="'+y+'" x2="'+(W-padR)+'" y2="'+y+'" stroke="#26301F" stroke-width="1"/>';
}).join('');
const dots=xs.map((x,i)=>{
const label=fmt(rates[i],1)+(unit?' '+unit:'');
return '<circle cx="'+x.toFixed(1)+'" cy="'+ys[i].toFixed(1)+'" r="2" fill="'+colorHex+'" opacity="0.8"/>'
+'<circle cx="'+x.toFixed(1)+'" cy="'+ys[i].toFixed(1)+'" r="12" fill="transparent" data-tip="'+escAttr(label)+'"/>';
}).join('');
container.innerHTML=
'<svg viewBox="0 0 '+W+' '+H+'" width="100%" height="'+H+'" xmlns="http://www.w3.org/2000/svg">'
+grid
+'<path d="'+areaPath+'" fill="'+colorHex+'" fill-opacity="0.13"/>'
+'<path d="'+linePath+'" stroke="'+colorHex+'" fill="none" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round"/>'
+dots
+'</svg>';
attachChartTip(container.querySelector('svg'));
}
function fmtHHMM(ts){ const d=new Date(ts); return pad(d.getHours())+':'+pad(d.getMinutes()); }
@@ -1411,9 +1717,9 @@
colRates.push((snap[i].cols-snap[i-1].cols)/dt);
}
drawLiveChart($('liveChartKills'), killRates, '#6B8F5C');
drawLiveChart($('liveChartExp'), expRates, '#F2C94C');
drawLiveChart($('liveChartCols'), colRates, '#C97B4A');
drawLiveChart($('liveChartKills'), killRates, '#6B8F5C', 'kills/min');
drawLiveChart($('liveChartExp'), expRates, '#F2C94C', 'xp/min');
drawLiveChart($('liveChartCols'), colRates, '#C97B4A', 'cols/min');
const last = arr => arr.length ? arr[arr.length-1] : 0;
$('liveChartKillsVal').textContent = fmt(last(killRates),1)+'/min';
@@ -1652,6 +1958,19 @@
body.innerHTML = '<p class="feed-empty">Pas encore de drop enregistré pour ce mob.</p>';
return;
}
const totalExp = entry.totalExp || 0;
const totalCols = entry.totalCols || 0;
const statDiv = document.createElement('div');
statDiv.style.cssText = 'font-family:var(--font-mono);font-size:11px;color:var(--text-dim);margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid var(--border);display:flex;gap:18px;flex-wrap:wrap;';
if (totalExp > 0){
statDiv.innerHTML += '<span><span style="color:var(--gold)">XP</span> ~'+fmt(totalExp/kills,1)+' / kill · '+fmt(Math.round(totalExp))+' total</span>';
} else {
statDiv.innerHTML += '<span><span style="color:var(--gold)">XP</span> <span style="opacity:.5">— non disponible</span></span>';
}
if (totalCols > 0){
statDiv.innerHTML += '<span><span style="color:var(--copper)">Cols</span> ~'+fmt(totalCols/kills,2)+' / kill · '+fmt(Math.round(totalCols))+' total</span>';
}
body.appendChild(statDiv);
const itemEntries = Array.from(entry.items.entries()).sort((a,b) => (b[1].occurrences/kills) - (a[1].occurrences/kills));
for (const [key, it] of itemEntries){
const pct = kills > 0 ? (it.occurrences/kills*100) : 0;
@@ -1794,9 +2113,12 @@
const header = document.createElement('div');
header.className = 'drop-board-mob-header';
const xpPerKill = entry.kills > 0 && (entry.totalExp || 0) > 0 ? fmt((entry.totalExp||0)/entry.kills,1)+' xp/kill' : null;
const colPerKill = entry.kills > 0 && (entry.totalCols || 0) > 0 ? fmt((entry.totalCols||0)/entry.kills,2)+' col/kill' : null;
const xpColParts = [xpPerKill, colPerKill].filter(Boolean).join(' · ');
header.innerHTML =
'<span class="drop-board-mob-name">'+escHtml(mobName)+'</span>'+
'<span class="drop-board-mob-kills">'+fmt(entry.kills)+' kills</span>';
'<span class="drop-board-mob-kills">'+fmt(entry.kills)+' kills'+(xpColParts ? ' · '+xpColParts : '')+'</span>';
section.appendChild(header);
const cardsGrid = document.createElement('div');
@@ -1874,8 +2196,9 @@
const d=new Date(sessions[i].startedAt);
const dateStr=d.toLocaleDateString('fr-FR',{day:'2-digit',month:'2-digit'});
const valStr=labelFn?labelFn(val):Math.round(val).toLocaleString('fr-FR');
const title=escHtml('Session '+(i+1)+' ('+dateStr+') : '+valStr);
return '<circle cx="'+x.toFixed(1)+'" cy="'+ys[i].toFixed(1)+'" r="'+r+'" fill="'+colorHex+'" stroke="#0B0F0C" stroke-width="1.5"><title>'+title+'</title></circle>';
const tip=escAttr('Session '+(i+1)+' ('+dateStr+') : '+valStr);
return '<circle cx="'+x.toFixed(1)+'" cy="'+ys[i].toFixed(1)+'" r="'+r+'" fill="'+colorHex+'" stroke="#0B0F0C" stroke-width="1.5"/>'
+'<circle cx="'+x.toFixed(1)+'" cy="'+ys[i].toFixed(1)+'" r="10" fill="transparent" data-tip="'+tip+'"/>';
}).join('');
container.innerHTML=
'<svg viewBox="0 0 '+W+' '+H+'" width="100%" height="'+H+'" xmlns="http://www.w3.org/2000/svg">'
@@ -1884,6 +2207,7 @@
+'<path d="'+linePath+'" stroke="'+colorHex+'" fill="none" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>'
+dots
+'</svg>';
attachChartTip(container.querySelector('svg'));
if (labelContainer&&sessions.length>=2){
const d1=new Date(sessions[0].startedAt);
const d2=new Date(sessions[sessions.length-1].startedAt);
@@ -1957,6 +2281,9 @@
const colsPerMin=minElapsed>0?Math.round((s.killCols||0)/minElapsed*10)/10:0;
const topItemName=s.topItems&&s.topItems.length?s.topItems[0].name+' ×'+s.topItems[0].qty:'—';
const tr=document.createElement('tr');
tr.style.cursor='pointer';
tr.title='Clic pour voir le détail';
tr.dataset.sessionId=s.id;
tr.innerHTML=
'<td>'+escHtml(dateStr)+'</td>'+
'<td class="r mono">'+escHtml(durStr)+'</td>'+
@@ -1967,11 +2294,83 @@
'<td class="r mono">'+(s.sellTotal?fmtShort(Math.round(s.sellTotal)):'—')+'</td>'+
'<td class="r mono">'+fmt(colsPerMin,1)+'/min</td>'+
'<td class="dim">'+escHtml(s.topMob||'—')+'</td>'+
'<td class="dim" title="'+escHtml(topItemName)+'">'+escHtml(topItemName.length>22?topItemName.slice(0,20)+'…':topItemName)+'</td>';
'<td class="dim" title="'+escHtml(topItemName)+'">'+escHtml(topItemName.length>22?topItemName.slice(0,20)+'…':topItemName)+'</td>'+
'<td style="color:var(--text-dim);font-size:11px;padding-left:8px;">→</td>';
tbody.appendChild(tr);
}
}
function renderSessionDetail(s){
const d = new Date(s.startedAt);
const dateStr = d.toLocaleDateString('fr-FR',{weekday:'long',day:'2-digit',month:'long',year:'numeric'})
+ ' à ' + d.toLocaleTimeString('fr-FR',{hour:'2-digit',minute:'2-digit'});
$('sessionDetailTitle').textContent = dateStr;
const minElapsed = s.durationMs / 60000;
const dH = Math.floor(s.durationMs/3600000), dM = Math.floor((s.durationMs%3600000)/60000), dS = Math.floor((s.durationMs%60000)/1000);
$('sdDur').textContent = dH > 0 ? dH+'h'+String(dM).padStart(2,'0')+'m' : dM+'min '+String(dS).padStart(2,'0')+'s';
$('sdKills').textContent = fmt(s.totalKills);
$('sdKillsRate').textContent = minElapsed > 0 ? fmt(s.totalKills/minElapsed,1)+' kills/min' : '—';
$('sdExp').textContent = fmtShort(s.totalExp||0);
$('sdExpRate').textContent = minElapsed > 0 ? fmtShort(Math.round((s.totalExp||0)/minElapsed))+'/min' : '—';
$('sdKamas').textContent = s.sellTotal ? fmtShort(Math.round(s.sellTotal)) : '—';
$('sdCols').textContent = minElapsed > 0 ? fmt((s.killCols||0)/minElapsed,1)+' cols/min' : '—';
// Mobs
const mobEl = $('sdMobList');
const mobEntries = Object.entries(s.mobCounts||{}).sort((a,b)=>b[1]-a[1]);
if (!mobEntries.length){
mobEl.innerHTML = '<p style="color:var(--text-dim);font-size:13px;">Aucun mob enregistré.</p>';
} else {
const maxCount = mobEntries[0][1];
const colors = ['#9B5DE5','#5DB7E5','#F2C94C','#E05563','#5DE5A0','#E5955D'];
mobEl.innerHTML = mobEntries.map(([name, count], i) => {
const pct = (count / maxCount * 100).toFixed(1);
const color = colors[i % colors.length];
const perMin = minElapsed > 0 ? (count/minElapsed).toFixed(1) : '—';
return '<div class="bar-row">' +
'<div class="bar-label"><span>'+escHtml(name)+'</span>' +
'<span class="bar-count">'+fmt(count)+' <span style="color:var(--text-dim);font-size:11px;">('+perMin+'/min)</span></span></div>' +
'<div class="bar-track"><div class="bar-fill" style="width:'+pct+'%;background:'+color+'"></div></div>' +
'</div>';
}).join('');
}
// Items
const itemEl = $('sdItemList');
const items = s.topItems||[];
if (!items.length){
itemEl.innerHTML = '<p style="color:var(--text-dim);font-size:13px;">Aucun item enregistré.</p>';
} else {
const maxQty = items[0].qty;
const colors = ['#F2C94C','#9B5DE5','#5DB7E5','#E05563','#5DE5A0'];
itemEl.innerHTML = items.map(({name, qty}, i) => {
const pct = (qty / maxQty * 100).toFixed(1);
const color = colors[i % colors.length];
const perMin = minElapsed > 0 ? (qty/minElapsed).toFixed(2) : '—';
return '<div class="bar-row">' +
'<div class="bar-label"><span>'+escHtml(name)+'</span>' +
'<span class="bar-count">×'+fmt(qty)+' <span style="color:var(--text-dim);font-size:11px;">('+perMin+'/min)</span></span></div>' +
'<div class="bar-track"><div class="bar-fill" style="width:'+pct+'%;background:'+color+'"></div></div>' +
'</div>';
}).join('');
}
}
$('sessionDetailBackBtn').addEventListener('click', () => {
showScreen('history');
renderHistoryScreen();
});
$('histSessionsBody').addEventListener('click', e => {
const tr = e.target.closest('tr[data-session-id]');
if (!tr) return;
const session = sessionHistory.sessions.find(s => s.id === tr.dataset.sessionId);
if (!session) return;
renderSessionDetail(session);
showScreen('sessionDetail');
});
$('clearHistoryBtn').addEventListener('click', async () => {
if (!sessionHistory.sessions.length) return;
if (!window.confirm('Effacer tout l\'historique des sessions ? Cette action est irréversible.')) return;
@@ -1984,13 +2383,134 @@
// TIMERS
// ======================================================================
let timerConfigs = JSON.parse(localStorage.getItem('timerConfigs') || '[]');
let timerConfigs = JSON.parse(localStorage.getItem(lsKey('timerConfigs')) || '[]');
// ---- Sound catalog ----
const SOUND_CATALOG = [
{ id:'levelup', label:'Level Up XP', desc:'Montée de niveau', hash:'19034765ba8ba5389b35804ab213537ab5cf706f' },
{ id:'orb', label:'XP Orb', desc:'Ramassage d\'orbe XP', hash:'8a04a60d5c28fc60df472a877ca57f37eabc78d7' },
{ id:'pop', label:'Item Pop', desc:'Ramassage d\'item', hash:'d6ae1c04d0a7376a33d1df12e1b8057cfbab6bc2' },
{ id:'pling', label:'Pling', desc:'Note de bloc Pling', hash:'774ae41e86f0b62a5cc961d1bc2e3d0aef9d229c' },
{ id:'bell', label:'Bell', desc:'Note de bloc Bell', hash:'a1e833dec61595dc79d0c672fcd7838579ca4b14' },
{ id:'toast', label:'Toast Avancement', desc:'Notification avancement', hash:'506f2fdb1b7530df66134aa04c71e66513df0c93' },
{ id:'challenge', label:'Défi Terminé', desc:'Challenge complété', hash:'bd01dff39a7bd1e0e7f6847f7aee981f157e4f94' },
{ id:'chestopen', label:'Coffre', desc:'Ouverture de coffre', hash:'186d5d9481d59cc99bc4be1b5fbb98d0ef877b8e' },
{ id:'hit', label:'Hit', desc:'Coup réussi', hash:'57f50076e7b91b12595a17cf0d38303f979f862b' },
{ id:'click', label:'Click', desc:'Clic de bouton', hash:'3455ca942556c7d5eac7dd5e458e7fb3bad564c9' },
];
// ---- IndexedDB cache pour sons téléchargés ----
let _soundDb = null;
function openSoundDb(){
if (_soundDb) return Promise.resolve(_soundDb);
return new Promise((res, rej) => {
const req = indexedDB.open('FarmTrackerSounds', 1);
req.onupgradeneeded = e => e.target.result.createObjectStore('sounds', { keyPath: 'id' });
req.onsuccess = e => { _soundDb = e.target.result; res(_soundDb); };
req.onerror = e => rej(e.target.error);
});
}
async function isSoundCached(soundId){
try {
const db = await openSoundDb();
return new Promise(res => {
const req = db.transaction('sounds','readonly').objectStore('sounds').get(soundId);
req.onsuccess = () => res(!!req.result);
req.onerror = () => res(false);
});
} catch { return false; }
}
async function getSoundBytes(soundId){
const db = await openSoundDb();
return new Promise((res, rej) => {
const req = db.transaction('sounds','readonly').objectStore('sounds').get(soundId);
req.onsuccess = () => res(req.result ? req.result.buffer : null);
req.onerror = () => rej(req.error);
});
}
async function saveSoundBytes(soundId, buffer){
const db = await openSoundDb();
return new Promise((res, rej) => {
const tx = db.transaction('sounds','readwrite');
tx.objectStore('sounds').put({ id: soundId, buffer });
tx.oncomplete = res;
tx.onerror = () => rej(tx.error);
});
}
async function downloadSound(soundId, onProgress){
const entry = SOUND_CATALOG.find(s => s.id === soundId);
if (!entry) throw new Error('Unknown sound: ' + soundId);
const prefix = entry.hash.slice(0, 2);
const url = `https://resources.download.minecraft.net/${prefix}/${entry.hash}`;
const resp = await fetch(url);
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const buffer = await resp.arrayBuffer();
await saveSoundBytes(soundId, buffer);
_audioBufferCache.delete(soundId);
return buffer;
}
// ---- Web Audio playback ----
const _audioBufferCache = new Map();
let _audioCtx = null;
function getAudioCtx(){
if (!_audioCtx) _audioCtx = new (window.AudioContext || window.webkitAudioContext)();
return _audioCtx;
}
async function _getDecodedBuffer(soundId){
if (_audioBufferCache.has(soundId)) return _audioBufferCache.get(soundId);
let bytes = await getSoundBytes(soundId);
if (!bytes && soundId === 'levelup'){
// fallback : fichier bundlé dans renderer/
const r = await fetch('levelup.ogg');
bytes = await r.arrayBuffer();
await saveSoundBytes('levelup', bytes);
}
if (!bytes) return null;
const ctx = getAudioCtx();
const decoded = await ctx.decodeAudioData(bytes.slice(0));
_audioBufferCache.set(soundId, decoded);
return decoded;
}
async function playAlert(cfg){
try {
const soundId = cfg ? (cfg.soundId || 'levelup') : 'levelup';
const vol = Math.max(0, Math.min(1, ((cfg && cfg.volume != null) ? cfg.volume : 10) / 100));
const buf = await _getDecodedBuffer(soundId);
if (!buf){ console.warn('Sound not cached:', soundId); return; }
const ctx = getAudioCtx();
const src = ctx.createBufferSource();
const gain = ctx.createGain();
src.buffer = buf;
src.connect(gain);
gain.connect(ctx.destination);
gain.gain.value = vol;
src.start();
} catch(e){ console.warn('playAlert failed', e); }
}
// migration : ajoute soundId et volume si absents
let alertConfigs = JSON.parse(localStorage.getItem(lsKey('alertConfigs')) || '[]').map(c => ({
soundId: 'levelup', volume: 10, ...c
}));
function saveAlertConfigs(){
localStorage.setItem(lsKey('alertConfigs'), JSON.stringify(alertConfigs));
}
// activeTimers : Map<configId, { endsAt: number, durationSec: number, mobName: string }>
const activeTimers = new Map();
let timerClockId = null;
function saveTimerConfigs(){
localStorage.setItem('timerConfigs', JSON.stringify(timerConfigs));
localStorage.setItem(lsKey('timerConfigs'), JSON.stringify(timerConfigs));
updateTimerTileStatus();
}
@@ -2073,9 +2593,34 @@
}).join('');
}
function populateTimerMobSuggestions(){
const dl = $('timerMobSuggestions');
if (!dl) return;
const seen = new Set();
// mobs de la session courante
if (ft && ft.state && ft.state.mobCounts){
for (const name of ft.state.mobCounts.keys()) seen.add(name);
}
// mobs de l'historique
for (const sess of sessionHistory.sessions){
if (sess.mobCounts) for (const name of Object.keys(sess.mobCounts)) seen.add(name);
}
// exclure ceux déjà configurés
const configured = new Set(timerConfigs.map(c => c.mobName.toLowerCase()));
dl.innerHTML = Array.from(seen)
.filter(n => !configured.has(n.toLowerCase()))
.sort((a,b) => a.localeCompare(b))
.map(n => '<option value="'+escHtml(n)+'"></option>')
.join('');
}
function renderTimerScreen(){
renderTimerConfigList();
renderTimerActiveGrid();
populateTimerMobSuggestions();
renderAlertConfigList();
populateAlertItemSuggestions();
populateAddSoundSelect();
startTimerClock();
}
@@ -2088,6 +2633,7 @@
$('timerMobInput').value = '';
$('timerDurInput').value = '';
renderTimerConfigList();
populateTimerMobSuggestions();
});
$('timerMobInput').addEventListener('keydown', e => { if (e.key === 'Enter') $('timerAddBtn').click(); });
@@ -2101,6 +2647,196 @@
saveTimerConfigs();
renderTimerConfigList();
renderTimerActiveGrid();
populateTimerMobSuggestions();
});
// ---- Alert config list ----
function buildSoundOptions(selectedId){
return SOUND_CATALOG.map(s =>
'<option value="'+escHtml(s.id)+'"'+(s.id === selectedId ? ' selected' : '')+'>'+escHtml(s.label)+'</option>'
).join('');
}
async function renderAlertConfigList(){
const list = $('alertConfigList');
if (!list) return;
if (!alertConfigs.length){ list.innerHTML = ''; return; }
const cachedIds = new Set();
for (const s of SOUND_CATALOG){
if (await isSoundCached(s.id)) cachedIds.add(s.id);
}
list.innerHTML = alertConfigs.map(cfg => {
const sid = cfg.soundId || 'levelup';
const opts = SOUND_CATALOG.map(s => {
const notCached = !cachedIds.has(s.id) && s.id !== 'levelup';
const label = s.label + (notCached ? ' (⬇)' : '');
return '<option value="'+escHtml(s.id)+'"'+(s.id === sid ? ' selected' : '')+'>'+escHtml(label)+'</option>';
}).join('');
const vol = cfg.volume != null ? cfg.volume : 10;
return '<div class="alert-cfg-row">'+
'<span class="alert-cfg-name">'+escHtml(cfg.itemName)+'</span>'+
'<select class="alert-cfg-sound" data-alert-sound="'+escHtml(cfg.id)+'">'+opts+'</select>'+
'<input type="range" min="0" max="100" step="1" value="'+vol+'" data-alert-vol="'+escHtml(cfg.id)+'" style="width:64px;" title="Volume: '+vol+'%">'+
'<span data-alert-vol-label="'+escHtml(cfg.id)+'" style="font-size:10px;font-family:var(--font-mono);color:var(--text-dim);min-width:26px;">'+vol+'%</span>'+
'<button class="btn-ghost small" data-preview-alert="'+escHtml(cfg.id)+'" title="Prévisualiser">▶</button>'+
'<button class="btn-ghost small danger" data-del-alert="'+escHtml(cfg.id)+'">✕</button>'+
'</div>';
}).join('');
}
function populateAlertItemSuggestions(){
const dl = $('alertItemSuggestions');
if (!dl) return;
const seen = new Set();
if (ft && ft.state && ft.state.itemCounts){
for (const it of ft.state.itemCounts.values()){
const n = mcPlain(it.rawName); if (n) seen.add(n);
}
}
if (ft && ft.state && ft.state.dropStats){
for (const [, entry] of ft.state.dropStats){
for (const [, it] of entry.items){ const n = mcPlain(it.rawName); if (n) seen.add(n); }
}
}
const configured = new Set(alertConfigs.map(c => c.itemName.toLowerCase()));
dl.innerHTML = Array.from(seen)
.filter(n => !configured.has(n.toLowerCase()))
.sort((a,b) => a.localeCompare(b))
.map(n => '<option value="'+escHtml(n)+'"></option>')
.join('');
}
function populateAddSoundSelect(){
const sel = $('alertSoundSelect');
if (!sel) return;
sel.innerHTML = buildSoundOptions('levelup');
}
// slider volume dans le formulaire d'ajout
$('alertVolumeInput').addEventListener('input', () => {
$('alertVolumeVal').textContent = $('alertVolumeInput').value + '%';
});
$('alertAddBtn').addEventListener('click', () => {
const itemName = $('alertItemInput').value.trim();
if (!itemName) return;
const soundId = $('alertSoundSelect').value || 'levelup';
const volume = parseInt($('alertVolumeInput').value, 10);
alertConfigs.push({ id: generateUUID(), itemName, nameLower: itemName.toLowerCase(), soundId, volume });
saveAlertConfigs();
$('alertItemInput').value = '';
renderAlertConfigList();
populateAlertItemSuggestions();
if (soundId !== 'levelup') isSoundCached(soundId).then(ok => { if (!ok) downloadSound(soundId).catch(()=>{}); });
});
$('alertItemInput').addEventListener('keydown', e => { if (e.key === 'Enter') $('alertAddBtn').click(); });
$('alertConfigList').addEventListener('click', async e => {
const delId = e.target.dataset.delAlert;
if (delId){
alertConfigs = alertConfigs.filter(c => c.id !== delId);
saveAlertConfigs();
await renderAlertConfigList();
populateAlertItemSuggestions();
return;
}
const prevId = e.target.dataset.previewAlert;
if (prevId){
const cfg = alertConfigs.find(c => c.id === prevId);
if (cfg){
const soundId = cfg.soundId || 'levelup';
const cached = await isSoundCached(soundId) || soundId === 'levelup';
if (!cached){
e.target.textContent = '⬇';
await downloadSound(soundId).catch(err => console.warn('Download failed', err));
await renderAlertConfigList();
renderSoundLibrary();
}
playAlert(cfg);
}
}
});
$('alertConfigList').addEventListener('change', e => {
const soundId = e.target.dataset.alertSound;
if (soundId){
const cfg = alertConfigs.find(c => c.id === soundId);
if (!cfg) return;
cfg.soundId = e.target.value;
saveAlertConfigs();
if (cfg.soundId !== 'levelup') isSoundCached(cfg.soundId).then(ok => { if (!ok) downloadSound(cfg.soundId).catch(()=>{}); });
return;
}
});
$('alertConfigList').addEventListener('input', e => {
const id = e.target.dataset.alertVol;
if (!id) return;
const cfg = alertConfigs.find(c => c.id === id);
if (!cfg) return;
cfg.volume = parseInt(e.target.value, 10);
saveAlertConfigs();
const label = document.querySelector('[data-alert-vol-label="'+id+'"]');
if (label) label.textContent = cfg.volume + '%';
});
// ---- Sound library ----
$('soundLibToggle').addEventListener('click', () => {
const content = $('soundLibContent');
const arrow = $('soundLibArrow');
const open = content.hidden;
content.hidden = !open;
arrow.textContent = open ? '▼ fermer' : '▶ ouvrir';
if (open) renderSoundLibrary();
});
async function renderSoundLibrary(){
const grid = $('soundLibGrid');
if (!grid) return;
const cards = await Promise.all(SOUND_CATALOG.map(async s => {
const cached = await isSoundCached(s.id) || s.id === 'levelup';
return '<div class="sound-card" data-sound-id="'+escHtml(s.id)+'">'+
'<span class="sound-card-name">'+escHtml(s.label)+'</span>'+
'<span class="sound-card-desc">'+escHtml(s.desc)+'</span>'+
'<div class="sound-card-actions">'+
'<button class="btn-ghost small" data-preview-sound="'+escHtml(s.id)+'" title="Prévisualiser">▶ Preview</button>'+
(cached
? '<span class="sound-card-status">✓ Téléchargé</span>'
: '<button class="btn-ghost small" data-dl-sound="'+escHtml(s.id)+'">⬇ Télécharger</button>')+
'</div>'+
'</div>';
}));
grid.innerHTML = cards.join('');
}
$('soundLibGrid').addEventListener('click', async e => {
const dlId = e.target.dataset.dlSound;
if (dlId){
e.target.textContent = '…';
e.target.disabled = true;
try {
await downloadSound(dlId);
await renderSoundLibrary();
await renderAlertConfigList();
populateAddSoundSelect();
} catch(err){
e.target.textContent = '✗ Erreur';
console.warn('Sound download failed', err);
}
return;
}
const prevId = e.target.dataset.previewSound;
if (prevId){
const cached = await isSoundCached(prevId) || prevId === 'levelup';
if (!cached){
e.target.textContent = '⬇…';
await downloadSound(prevId).catch(err => console.warn('dl failed', err));
await renderSoundLibrary();
await renderAlertConfigList();
}
playAlert({ soundId: prevId });
}
});
updateTimerTileStatus();
@@ -2191,6 +2927,13 @@
// ======================================================================
(async () => {
// Charger les profils en premier (nécessaire avant lsKey et les données)
await loadProfiles();
// Re-lire timerConfigs et alertConfigs maintenant que lsKey est disponible
timerConfigs = JSON.parse(localStorage.getItem(lsKey('timerConfigs')) || '[]');
alertConfigs = JSON.parse(localStorage.getItem(lsKey('alertConfigs')) || '[]').map(c => ({ soundId: 'levelup', volume: 10, ...c }));
let appState = null, dropStatsPlain = null, communityDropStatsPlain = null;
try{ appState = await window.api.loadAppState(); }catch(e){}
try{ dropStatsPlain = await window.api.loadDropStats(); }catch(e){}

BIN
renderer/levelup.ogg Normal file

Binary file not shown.