// Online demo (static hosting): answers the pages' /api/ requests from EatBack running inside this browser // (eatback-worker.js) instead of a laptop server. Loaded before the page's own scripts. (function () { const nativeFetch = window.fetch.bind(window); const pending = new Map(); let port = null; let seq = 0; let isReady = false; let failed = null; let resolveReady; const ready = new Promise((r) => { resolveReady = r; }); const en = (() => { try { return localStorage.getItem('eatback.lang') === 'en'; } catch { return false; } })(); const T = (th, e) => (en ? e : th); function start() { if (port) return; const url = '/eatback-worker.js'; if (window.SharedWorker) { const w = new SharedWorker(url, { name: 'eatback', type: 'module' }); port = w.port; port.start(); } else { port = new Worker(url, { type: 'module' }); } port.onmessage = (e) => { const m = e.data; if (m.type === 'res') { const done = pending.get(m.id); if (done) { pending.delete(m.id); done(m); } return; } if (m.type === 'ready') { isReady = true; resolveReady(); hideSplash(); return; } if (m.type === 'progress') { stepSplash(m.step); return; } if (m.type === 'error') { failed = m.text; showError(m.text); } }; window.addEventListener('pagehide', () => { try { port.postMessage({ type: 'bye' }); } catch { /* closing */ } }); setTimeout(() => { if (!isReady && !failed) showSplash(); }, 350); } // Sign-in: the online demo has no server to hold a session, so the role picked on /start is kept in this browser // (demo data needs no PIN). The screens then send other roles away exactly as on the school laptop. const ROLE_TH = { admin: 'ผู้ดูแล', kitchen: 'แม่ครัว', teacher: 'ครูประจำชั้น', viewer: 'ผู้บริหาร' }; const HOME = { admin: '/', viewer: '/', kitchen: '/kitchen.html', teacher: '/opinions.html' }; const store = { get: () => { try { return localStorage.getItem('eatback.role'); } catch { return null; } }, set: (r) => { try { if (r) localStorage.setItem('eatback.role', r); else localStorage.removeItem('eatback.role'); } catch { /* private mode */ } }, }; const me = () => { const role = ROLE_TH[store.get()] ? store.get() : null; return { required: false, role, role_th: ROLE_TH[role] ?? null, roles: ROLE_TH, home: HOME[role] ?? null }; }; const json = (status, obj) => new Response(JSON.stringify(obj), { status, headers: { 'Content-Type': 'application/json; charset=utf-8' } }); function auth(path, init) { if (path === '/api/auth/me') return json(200, me()); let body = {}; try { body = JSON.parse(init?.body || '{}'); } catch { /* empty */ } if (path === '/api/auth/login') { if (body.role != null && !ROLE_TH[body.role]) return json(400, { error: 'ไม่รู้จักบทบาทนี้' }); store.set(body.role || 'admin'); return json(200, { ...me(), ok: true }); } if (path === '/api/auth/logout') { store.set(null); return json(200, { ...me(), ok: true }); } return null; } window.fetch = async function (input, init) { const raw = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; const u = new URL(raw, location.href); if (u.origin !== location.origin || !u.pathname.startsWith('/api/')) return nativeFetch(input, init); if (u.pathname.startsWith('/api/auth/')) { const r = auth(u.pathname, init); if (r) return r; } start(); await ready; const method = (init?.method || (typeof input === 'object' && input.method) || 'GET').toUpperCase(); const body = typeof init?.body === 'string' ? init.body : null; const id = ++seq; const res = await new Promise((resolve) => { pending.set(id, resolve); port.postMessage({ type: 'req', id, method, path: u.pathname + u.search, body }); }); return new Response(res.body, { status: res.status, headers: { 'Content-Type': 'application/json; charset=utf-8' } }); }; // Only used when this build is tested on localhost; online the pages poll /api/live. window.EventSource = class { constructor() { this.closed = false; const loop = async () => { if (this.closed) return; try { const r = await window.fetch('/api/live'); const data = await r.text(); if (this.onmessage) this.onmessage({ data }); } catch { /* retry */ } if (!this.closed) setTimeout(loop, 400); }; loop(); } close() { this.closed = true; } }; // ---------------------------------------------------------------- loading screen let splash = null; const STEPS = { start: T('กำลังเริ่ม…', 'Starting…'), python: T('กำลังโหลดระบบ (ครั้งแรกประมาณ 10–20 วินาที)', 'Loading the app engine (about 10–20 s the first time)'), files: T('กำลังเตรียมโปรแกรม…', 'Preparing the app…'), data: T('กำลังเตรียมข้อมูลเดโม…', 'Setting up demo data…'), }; function showSplash() { if (splash || isReady) return; splash = document.createElement('div'); splash.id = 'eb-splash'; splash.setAttribute('role', 'status'); splash.style.cssText = 'position:fixed;inset:0;z-index:9999;display:grid;place-items:center;background:#f8faf7;font-family:"IBM Plex Sans Thai","Leelawadee UI",system-ui,sans-serif;color:#13211a;padding:24px;text-align:center'; splash.innerHTML = `
${T('เดโมออนไลน์ทำงานในเบราว์เซอร์นี้ ข้อมูลที่กดเป็นของคุณคนเดียว เปิดหน้าครัวและหน้าภาพรวมในเบราว์เซอร์เดียวกันได้', 'This online demo runs in your browser. Your data is yours alone; open the kitchen and dashboard in the same browser.')}