eatback / static-api.js
kritpakin's picture
Roles, principal report, five bins, purchase order for the kitchen, print fix
9aaa92e verified
Raw History Blame Contribute Delete
7.8 kB
// 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 = `<div style="max-width:420px">
<img src="/favicon.svg" alt="" width="84" height="84" style="border-radius:20px;box-shadow:0 8px 24px rgba(0,0,0,.08)">
<div style="font-weight:800;font-size:28px;margin-top:14px"><span style="color:#0f5132">Eat</span><span style="color:#f59e0b">Back</span></div>
<div id="eb-step" style="margin-top:10px;color:#4a5850;font-size:15px">${STEPS.start}</div>
<div style="margin:16px auto 0;width:220px;height:6px;border-radius:9px;background:#e3e9e2;overflow:hidden"><div style="width:40%;height:100%;background:#41b649;border-radius:9px;animation:ebbar 1.2s ease-in-out infinite"></div></div>
<p style="margin-top:18px;font-size:13px;color:#7d8981">${T('เดโมออนไลน์ทำงานในเบราว์เซอร์นี้ ข้อมูลที่กดเป็นของคุณคนเดียว เปิดหน้าครัวและหน้าภาพรวมในเบราว์เซอร์เดียวกันได้', 'This online demo runs in your browser. Your data is yours alone; open the kitchen and dashboard in the same browser.')}</p>
</div><style>@keyframes ebbar{0%{margin-left:-40%}100%{margin-left:100%}}</style>`;
(document.body || document.documentElement).appendChild(splash);
}
function stepSplash(step) { const el = document.getElementById('eb-step'); if (el && STEPS[step]) el.textContent = STEPS[step]; }
function hideSplash() { if (splash) { splash.remove(); splash = null; } }
function showError(text) {
showSplash();
const el = document.getElementById('eb-step');
if (el) el.innerHTML = `<b style="color:#b0281f">${T('เปิดเดโมไม่สำเร็จ', "Couldn't start the demo")}</b><br><span style="font-size:13px">${String(text).replace(/[<>&]/g, '')}</span><br><button onclick="location.reload()" style="margin-top:12px;padding:8px 16px;border-radius:10px;border:1px solid #cfd8ce;background:#fff;cursor:pointer">${T('ลองอีกครั้ง', 'Try again')}</button>`;
}
})();