foxygit / infodisplay Log in
commits tags

/kiosk/static/addons/emulator/panel.js · 6.31 KB

raw
/* Emulator admin-panel */
(function () {

  let _roms        = [];   // alla hittade ROMs
  let _selectedRom = null; // { name, path, core, core_label }

  // --- Init ---

  async function emuInit() {
    const s = await fetch('/api/emulator/status').then(r => r.json());
    document.getElementById('emu-rom-dir').value  = s.rom_dir  || '';
    document.getElementById('emu-ejs-path').value = s.ejs_path || '';
    if (s.active) {
      _showNowPlaying(s.rom, s.core_label);
    }
  }

  // --- Bläddra efter ROM-mapp ---

  function emuBrowseFolder() {
    openBrowser(function (path) {
      // openBrowser väljer fil; ta dess mapp
      const dir = path.includes('/') ? path.substring(0, path.lastIndexOf('/')) : path;
      document.getElementById('emu-rom-dir').value = dir;
      emuScanRoms();
    });
  }

  // --- Skanna ROM-mapp ---

  async function emuScanRoms() {
    const dir = document.getElementById('emu-rom-dir').value.trim();
    if (!dir) return;

    _setStatus('Skannar...');
    await fetch('/api/emulator/settings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ rom_dir: dir }),
    });

    const roms = await fetch(`/api/emulator/roms?path=${encodeURIComponent(dir)}`).then(r => r.json());
    _roms = roms;
    _renderRomList(roms);
    _setStatus('');
  }

  // --- Filtrera ROM-lista ---

  function emuFilterRoms(query) {
    const q = query.toLowerCase();
    _renderRomList(q ? _roms.filter(r => r.name.toLowerCase().includes(q)) : _roms);
  }

  // --- Rendera ROM-lista ---

  function _renderRomList(roms) {
    const wrap = document.getElementById('emu-rom-wrap');
    const list = document.getElementById('emu-rom-list');
    const none = document.getElementById('emu-no-roms');

    if (!roms.length) {
      wrap.style.display = 'none';
      none.style.display = 'block';
      return;
    }

    none.style.display = 'none';
    wrap.style.display = 'block';

    // Gruppera per system
    const byCore = {};
    roms.forEach(r => {
      (byCore[r.core_label] = byCore[r.core_label] || []).push(r);
    });

    list.innerHTML = Object.entries(byCore).map(([label, group]) => `
      <div style="padding:.35rem .6rem;font-size:.72rem;font-weight:700;color:#555;
                  text-transform:uppercase;letter-spacing:.06em;background:#0a0a0a;
                  border-bottom:1px solid #1a1a1a">${label}</div>
      ${group.map(r => `
        <div class="emu-rom-item" data-path="${_esc(r.path)}" data-core="${_esc(r.core)}"
             data-name="${_esc(r.name)}" data-core-label="${_esc(r.core_label)}"
             onclick="emuSelectRom(this)"
             style="padding:.45rem .75rem;cursor:pointer;font-size:.88rem;
                    display:flex;align-items:center;justify-content:space-between;
                    border-bottom:1px solid #1a1a1a;transition:background .1s">
          <span style="font-family:monospace;white-space:nowrap;overflow:hidden;
                       text-overflow:ellipsis;max-width:80%">${_esc(r.name)}</span>
          <span style="color:#444;font-size:.75rem;flex-shrink:0">${r.size_mb} MB</span>
        </div>
      `).join('')}
    `).join('');

    // Hover-effekt
    list.querySelectorAll('.emu-rom-item').forEach(el => {
      el.addEventListener('mouseenter', () => el.style.background = '#1a1a1a');
      el.addEventListener('mouseleave', () => {
        el.style.background = _selectedRom && el.dataset.path === _selectedRom.path
          ? '#1e1b4b' : '';
      });
    });
  }

  // --- Välj ROM ---

  function emuSelectRom(el) {
    _selectedRom = {
      path:       el.dataset.path,
      core:       el.dataset.core,
      name:       el.dataset.name,
      core_label: el.dataset.coreLabel,
    };

    // Markera vald rad
    document.querySelectorAll('.emu-rom-item').forEach(e => {
      e.style.background = e === el ? '#1e1b4b' : '';
    });

    document.getElementById('emu-selected-name').textContent       = _selectedRom.name;
    document.getElementById('emu-selected-core-label').textContent = _selectedRom.core_label;
    document.getElementById('emu-selected-wrap').style.display     = 'block';
    document.getElementById('emu-launch-btn').disabled             = false;
    _setStatus('');
  }

  // --- Starta spel ---

  async function emuLaunch() {
    if (!_selectedRom) return;
    _setStatus('Startar...');
    const r = await fetch('/api/emulator/launch', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body:    JSON.stringify({ rom: _selectedRom.path, core: _selectedRom.core }),
    });
    if (r.ok) {
      _showNowPlaying(_selectedRom.name, _selectedRom.core_label);
      _setStatus('');
    } else {
      _setStatus('Kunde inte starta spelet');
    }
  }

  // --- Stoppa ---

  async function emuStop() {
    await fetch('/api/emulator/stop', { method: 'POST' });
    document.getElementById('emu-now-playing').style.display = 'none';
    _setStatus('');
  }

  // --- Spara avancerade inställningar ---

  async function emuSaveSettings() {
    const ejs_path = document.getElementById('emu-ejs-path').value.trim();
    await fetch('/api/emulator/settings', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body:    JSON.stringify({ ejs_path }),
    });
    _setStatus('Sparat');
    setTimeout(() => _setStatus(''), 2000);
  }

  // --- Helpers ---

  function _showNowPlaying(rom, coreLabel) {
    document.getElementById('emu-now-playing').style.display     = 'flex';
    document.getElementById('emu-now-playing-text').textContent  =
      `${coreLabel ? coreLabel + ' — ' : ''}${rom}`;
  }

  function _setStatus(msg) {
    document.getElementById('emu-status').textContent = msg;
  }

  function _esc(s) {
    return String(s)
      .replace(/&/g, '&amp;')
      .replace(/"/g, '&quot;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;');
  }

  // --- Exponera till global scope (anropas från panel.html) ---

  window.emuScanRoms     = emuScanRoms;
  window.emuBrowseFolder = emuBrowseFolder;
  window.emuFilterRoms   = emuFilterRoms;
  window.emuSelectRom    = emuSelectRom;
  window.emuLaunch       = emuLaunch;
  window.emuStop         = emuStop;
  window.emuSaveSettings = emuSaveSettings;

  // Init när DOM är redo
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', emuInit);
  } else {
    emuInit();
  }

})();