/* ========================================================================== KittyRec Admin — Shared JS Library Provides: api(), toast(), modal helpers, drawer, command palette, shortcuts. Exposes everything on window.KR to avoid clobbering page-local helpers. ========================================================================== */ (function () { 'use strict'; const KR = window.KR = window.KR || {}; /* ── Toast ─────────────────────────────────────────────────────────── */ function ensureToastContainer() { let c = document.getElementById('toast-container'); if (!c) { c = document.createElement('div'); c.id = 'toast-container'; document.body.appendChild(c); } return c; } KR.toast = function (msg, type) { type = type || 'success'; const c = ensureToastContainer(); const t = document.createElement('div'); t.className = 'toast ' + type; t.textContent = msg; c.appendChild(t); setTimeout(() => { t.classList.add('fade'); setTimeout(() => t.remove(), 260); }, 3500); return t; }; if (!window.toast) window.toast = KR.toast; /* ── API wrappers ──────────────────────────────────────────────────── */ KR.apiPost = async function (url, data) { const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data || {}), }); try { return await r.json(); } catch { return { ok: false, error: 'bad_response' }; } }; KR.apiGet = async function (url) { const r = await fetch(url); try { return await r.json(); } catch { return null; } }; if (!window.api) window.api = KR.apiPost; /* ── Generic Modal ─────────────────────────────────────────────────── */ KR.openModal = function (id) { const el = document.getElementById(id); if (!el) return; el.classList.add('open'); const input = el.querySelector('input:not([type=hidden]), textarea'); if (input) setTimeout(() => input.focus(), 50); }; KR.closeModal = function (id) { const el = document.getElementById(id); if (el) el.classList.remove('open'); }; // Click-outside to close .kr-modal-backdrop document.addEventListener('click', (e) => { if (e.target.classList && e.target.classList.contains('kr-modal-backdrop')) { e.target.classList.remove('open'); } }); /* ── Utilities ─────────────────────────────────────────────────────── */ KR.debounce = function (fn, ms) { let t; return function () { clearTimeout(t); const args = arguments, ctx = this; t = setTimeout(() => fn.apply(ctx, args), ms); }; }; KR.escapeHtml = function (s) { if (s == null) return ''; return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }; KR.formatRelTime = function (ts) { if (!ts) return ''; const d = typeof ts === 'string' ? new Date(ts) : new Date(ts); const diff = (Date.now() - d.getTime()) / 1000; if (diff < 60) return Math.floor(diff) + 's ago'; if (diff < 3600) return Math.floor(diff/60) + 'm ago'; if (diff < 86400) return Math.floor(diff/3600) + 'h ago'; if (diff < 604800) return Math.floor(diff/86400) + 'd ago'; return d.toISOString().slice(0, 10); }; /* ── Player Drawer ─────────────────────────────────────────────────── */ function ensureDrawer() { let d = document.getElementById('kr-player-drawer'); if (d) return d; d = document.createElement('aside'); d.id = 'kr-player-drawer'; d.innerHTML = `
?
Loading…

Loading…

`; document.body.appendChild(d); return d; } KR.openDrawer = async function (pid) { const d = ensureDrawer(); d.classList.add('open'); d.dataset.pid = pid; document.getElementById('kr-drawer-name').textContent = 'Loading…'; document.getElementById('kr-drawer-sub').textContent = '#' + pid; document.getElementById('kr-drawer-body').innerHTML = '

Loading…

'; (function() { var av = document.getElementById('kr-drawer-avatar'); av.textContent = '?'; var img = new Image(); img.style.cssText = 'width:100%;height:100%;object-fit:cover;border-radius:50%'; img.onload = function() { av.textContent = ''; av.appendChild(img); }; img.src = '/alt/' + pid; })(); try { const p = await KR.apiGet('/admin/api/player_status/' + pid); if (!p || p.error) { document.getElementById('kr-drawer-body').innerHTML = '

Error: ' + (p && p.error || 'not found') + '

'; return; } document.getElementById('kr-drawer-name').textContent = p.username || '#' + pid; (function() { var av = document.getElementById('kr-drawer-avatar'); if (av.textContent === '?') av.textContent = (p.username || String(pid)).charAt(0).toUpperCase(); })(); document.getElementById('kr-drawer-sub').textContent = p.display_name ? p.display_name + ' · #' + pid : '#' + pid; const badges = []; if (p.online) badges.push(' Online'); else badges.push('Offline'); if (p.banned) badges.push('Banned'); if (p.developer) badges.push('Dev'); const ptSecs = p.playtime_seconds || 0; const ptH = Math.floor(ptSecs / 3600); const ptM = Math.floor((ptSecs % 3600) / 60); const ptStr = ptH > 0 ? ptH + 'h ' + ptM + 'm' : (ptM > 0 ? ptM + 'm' : '< 1m'); document.getElementById('kr-drawer-body').innerHTML = `
${badges.join(' ')}
${p.ban_reason ? '
Ban: ' + KR.escapeHtml(p.ban_reason) + '
' : ''}
Level
${p.level ?? '—'}
ID
#${p.id}
Playtime
${ptStr}
Sessions
${p.session_count || 0}
Full Profile ${p.banned ? '' : ''}
`; } catch (e) { document.getElementById('kr-drawer-body').innerHTML = '

Fetch error

'; } }; KR.closeDrawer = function () { const d = document.getElementById('kr-player-drawer'); if (d) d.classList.remove('open'); }; KR.drawerDisconnect = async function (pid) { const r = await KR.apiPost('/admin/api/disconnect/' + pid); KR.toast(r.ok ? 'Disconnected' : (r.error || 'Error'), r.ok ? 'success' : 'error'); if (r.ok) KR.openDrawer(pid); }; KR.drawerUnban = async function (pid) { if (!confirm('Unban this player?')) return; const r = await KR.apiPost('/admin/api/unban/' + pid); KR.toast(r.ok ? 'Unbanned' : (r.error || 'Error'), r.ok ? 'success' : 'error'); if (r.ok) KR.openDrawer(pid); }; KR.drawerToggleDev = async function (pid) { const r = await KR.apiPost('/admin/api/toggle_dev/' + pid); if (r.developer !== undefined) { KR.toast(r.developer ? 'Dev granted' : 'Dev revoked'); KR.openDrawer(pid); } else KR.toast(r.error || 'Error', 'error'); }; KR.drawerBan = function (pid, username) { if (window.openBanModal) { window.openBanModal(pid, username); return; } const reason = prompt('Ban reason:'); if (reason === null) return; const hours = parseInt(prompt('Duration hours (0 = permanent):', '24')) || 0; KR.apiPost('/admin/api/ban/' + pid, { reason: reason || 'Admin ban', duration_hours: hours, drop_ws: true }) .then(r => { KR.toast(r.ok ? 'Banned' : (r.error || 'Error'), r.ok ? 'success' : 'error'); if (r.ok) KR.openDrawer(pid); }); }; KR.drawerGift = function (pid, username) { if (window.openGiftModal) { window.openGiftModal(pid, username); return; } const xp = parseInt(prompt('XP amount:', '1000')); if (!xp || isNaN(xp)) return; KR.apiPost('/admin/api/gift_player/' + pid, { xp, rarity: 10, message: 'From the KittyRec team!' }) .then(r => { KR.toast(r.error ? r.error : 'Gift sent', r.error ? 'error' : 'success'); }); }; /* ── Command Palette ───────────────────────────────────────────────── */ const commands = []; KR.registerCommand = function (section, label, run, hint) { commands.push({ section: section || 'Actions', label, run, hint: hint || '' }); }; function ensurePalette() { let p = document.getElementById('kr-cmd-palette'); if (p) return p; p = document.createElement('div'); p.id = 'kr-cmd-palette'; p.innerHTML = `
`; document.body.appendChild(p); const input = p.querySelector('#kr-cmd-input'); const results = p.querySelector('#kr-cmd-results'); let active = 0; let current = []; const renderResults = KR.debounce(async () => { const q = input.value.trim().toLowerCase(); current = []; let html = ''; // Commands section const matching = commands.filter(c => !q || c.label.toLowerCase().includes(q) || c.section.toLowerCase().includes(q)); if (matching.length) { const bySec = {}; matching.forEach(c => { (bySec[c.section] = bySec[c.section] || []).push(c); }); Object.keys(bySec).forEach(sec => { html += '
' + KR.escapeHtml(sec) + '
'; bySec[sec].forEach(c => { const idx = current.length; current.push({ kind: 'cmd', run: c.run }); html += '
' + KR.escapeHtml(c.label) + (c.hint ? '' + KR.escapeHtml(c.hint) + '' : '') + '
'; }); }); } // Player search section if (q && q.length >= 2) { try { const players = await KR.apiGet('/admin/api/search_players?q=' + encodeURIComponent(q)); if (Array.isArray(players) && players.length) { html += '
Players
'; players.slice(0, 8).forEach(p => { const idx = current.length; current.push({ kind: 'player', pid: p.id }); const onl = p.online ? 'Online' : ''; html += '
' + KR.escapeHtml(p.username) + ' Lv ' + (p.level || 0) + '' + onl + '#' + p.id + '
'; }); } } catch {} } if (!html) html = '
No results
'; results.innerHTML = html; active = 0; highlight(); }, 150); function highlight() { results.querySelectorAll('.kr-cmd-item').forEach((el, i) => el.classList.toggle('active', i === active)); const cur = results.querySelector('.kr-cmd-item.active'); if (cur) cur.scrollIntoView({ block: 'nearest' }); } function runIdx(i) { const item = current[i]; if (!item) return; KR.closePalette(); if (item.kind === 'cmd') item.run(); if (item.kind === 'player') KR.openDrawer(item.pid); } input.addEventListener('input', renderResults); input.addEventListener('keydown', (e) => { const items = results.querySelectorAll('.kr-cmd-item'); if (e.key === 'ArrowDown') { e.preventDefault(); active = Math.min(active + 1, items.length - 1); highlight(); } else if (e.key === 'ArrowUp') { e.preventDefault(); active = Math.max(active - 1, 0); highlight(); } else if (e.key === 'Enter') { e.preventDefault(); runIdx(active); } else if (e.key === 'Escape') { KR.closePalette(); } }); results.addEventListener('click', (e) => { const el = e.target.closest('.kr-cmd-item'); if (el) runIdx(parseInt(el.dataset.idx)); }); p.addEventListener('click', (e) => { if (e.target === p) KR.closePalette(); }); // Trigger first render so commands show immediately renderResults(); return p; } KR.openPalette = function () { const p = ensurePalette(); p.classList.add('open'); const input = p.querySelector('#kr-cmd-input'); input.value = ''; input.dispatchEvent(new Event('input')); setTimeout(() => input.focus(), 30); }; KR.closePalette = function () { const p = document.getElementById('kr-cmd-palette'); if (p) p.classList.remove('open'); }; /* ── Keyboard Shortcuts ────────────────────────────────────────────── */ const shortcuts = []; KR.registerShortcut = function (combo, fn, label) { shortcuts.push({ combo: combo.toLowerCase(), fn, label: label || combo }); }; let gSequence = null, gTimer = null; document.addEventListener('keydown', (e) => { const tag = (e.target && e.target.tagName) || ''; const inField = tag === 'INPUT' || tag === 'TEXTAREA' || e.target.isContentEditable; // Cmd+K / Ctrl+K if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); KR.openPalette(); return; } if (e.key === 'Escape') { KR.closePalette(); KR.closeDrawer(); document.querySelectorAll('.kr-modal-backdrop.open, .modal-backdrop.open').forEach(m => m.classList.remove('open')); return; } if (inField) return; // '?' help if (e.key === '?') { e.preventDefault(); KR.toggleShortcutHelp(); return; } // '/' focus a search input if one exists if (e.key === '/') { const search = document.querySelector('input[type=search], input#search, input[placeholder*="earch"]'); if (search) { e.preventDefault(); search.focus(); return; } } // Two-key 'g X' navigation if (e.key === 'g') { gSequence = 'g'; clearTimeout(gTimer); gTimer = setTimeout(() => gSequence = null, 900); return; } if (gSequence === 'g') { const go = { d: '/admin/', p: '/admin/players', b: '/admin/bans', s: '/admin/sessions', g: '/admin/gifts' }; const target = go[e.key.toLowerCase()]; if (target) { e.preventDefault(); window.location.href = target; } gSequence = null; clearTimeout(gTimer); return; } // Single-key shortcuts for (const s of shortcuts) { if (s.combo === e.key.toLowerCase()) { e.preventDefault(); s.fn(); return; } } }); KR.toggleShortcutHelp = function () { let h = document.getElementById('kr-shortcut-help'); if (!h) { h = document.createElement('div'); h.id = 'kr-shortcut-help'; h.innerHTML = `

Keyboard Shortcuts

Open command palette⌘ K
Go to Dashboardg d
Go to Playersg p
Go to Bansg b
Go to Sessionsg s
Go to Giftsg g
Focus search/
Close / cancelEsc
This help?
`; document.body.appendChild(h); h.addEventListener('click', (e) => { if (e.target === h) h.classList.remove('open'); }); } h.classList.toggle('open'); }; /* ── Default commands ──────────────────────────────────────────────── */ KR.registerCommand('Go', 'Dashboard', () => location.href = '/admin/', 'g d'); KR.registerCommand('Go', 'Players', () => location.href = '/admin/players', 'g p'); KR.registerCommand('Go', 'Bans', () => location.href = '/admin/bans', 'g b'); KR.registerCommand('Go', 'Sessions', () => location.href = '/admin/sessions', 'g s'); KR.registerCommand('Go', 'Gifts', () => location.href = '/admin/gifts', 'g g'); KR.registerCommand('Go', 'Weekly Challenges', () => location.href = '/admin/live/weekly'); KR.registerCommand('Go', 'Store', () => location.href = '/admin/live/store'); KR.registerCommand('Go', 'Rooms', () => location.href = '/admin/live/rooms'); KR.registerCommand('Go', 'Events', () => location.href = '/admin/live/events'); KR.registerCommand('Go', 'Console', () => location.href = '/admin/live/console'); KR.registerCommand('Go', 'Analytics', () => location.href = '/admin/analytics'); KR.registerCommand('Go', 'Avatar Items', () => location.href = '/admin/live/avatar_items'); KR.registerCommand('Go', 'Swatches', () => location.href = '/admin/live/swatches'); KR.registerCommand('Go', 'UGC Avatar', () => location.href = '/admin/live/ugc_items'); KR.registerCommand('Go', 'Game Assets', () => location.href = '/admin/live/textures'); KR.registerCommand('Go', 'Music', () => location.href = '/admin/live/music'); KR.registerCommand('Go', 'CDN', () => location.href = '/admin/live/cdn'); KR.registerCommand('Go', 'Downloads', () => location.href = '/admin/live/downloads'); KR.registerCommand('Go', 'Videos', () => location.href = '/admin/videos'); KR.registerCommand('Go', 'KittyRec Mod', () => location.href = '/admin/kittyrec/mod'); KR.registerCommand('Go', 'DLL Archive', () => location.href = '/admin/live/dll_archive'); KR.registerCommand('Go', 'Gifts DB', () => location.href = '/admin/admin_gifts/'); KR.registerCommand('Go', 'Ban Log DB', () => location.href = '/admin/admin_bans/'); KR.registerCommand('Go', 'Leaderboard', () => location.href = '/admin/leaderboard'); KR.registerCommand('Go', 'Chat Moderation', () => location.href = '/admin/chat'); KR.registerCommand('Go', 'Todos', () => location.href = '/admin/admin_todos/'); KR.registerCommand('Go', 'Issues', () => location.href = '/admin/admin_issues/'); KR.registerCommand('Action', 'Reroll Store', async () => { const r = await KR.apiPost('/admin/api/reroll_store'); KR.toast(r.ok ? 'Store rerolled' : (r.error || 'Error'), r.ok ? 'success' : 'error'); }); KR.registerCommand('Action', 'Git Sync', async () => { KR.toast('Syncing…', 'info'); const r = await KR.apiPost('/admin/api/git_sync'); KR.toast(r.ok ? 'Git synced' : (r.error || 'Error'), r.ok ? 'success' : 'error'); }); KR.registerCommand('Action', 'Toggle Maintenance',async () => { const cur = await KR.apiGet('/admin/api/maintenance'); const next = !cur.maintenance; const r = await KR.apiPost('/admin/api/maintenance', { enabled: next, exempt_ids: cur.exempt_ids || [] }); KR.toast(r.ok ? ('Maintenance ' + (next ? 'ON' : 'OFF')) : (r.error || 'Error'), r.ok ? 'success' : 'error'); }); KR.registerCommand('Action', 'Reboot Server', async () => { if (!confirm('Reboot server?')) return; const r = await KR.apiPost('/admin/api/reboot'); KR.toast(r.ok ? 'Reboot scheduled' : (r.error || 'Error'), r.ok ? 'success' : 'error'); }); KR.registerCommand('Help', 'Keyboard Shortcuts',() => KR.toggleShortcutHelp(), '?'); /* ── Admin WebSocket ───────────────────────────────────────────────── */ KR._adminWsHandlers = []; KR.onAdminMsg = function (handler) { KR._adminWsHandlers.push(handler); }; KR.connectAdminWS = function () { const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; const url = proto + '//' + location.host + '/admin/ws'; let retryDelay = 1000; let ws; function dispatch(msg) { KR._adminWsHandlers.forEach(function (h) { try { h(msg); } catch (e) {} }); if (msg.type === 'online_count') { const el = document.getElementById('sb-online-count'); if (el) el.textContent = msg.count; } } function connect() { ws = new WebSocket(url); ws.onopen = function () { retryDelay = 1000; }; ws.onmessage = function (e) { try { dispatch(JSON.parse(e.data)); } catch (err) {} }; ws.onclose = function () { setTimeout(connect, retryDelay); retryDelay = Math.min(retryDelay * 2, 30000); }; ws.onerror = function () { ws.close(); }; } connect(); }; })();