aboutsummaryrefslogtreecommitdiffstats
path: root/static/app.js
blob: d16bd805ba4d32511aea2c97a5aabb158ee74a2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// deck-it - the page shell: tabs and polling
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

// The shell: discover modules, sort them into tabs, mount each panel and poll
// its state. A module with a tab is static/modules/<name>.js exporting default
// {title, tab, interval, mount(el), update(state, el)}. The Dashboard tab is
// static/dashboard.js, which draws the modules without a tab.

const tabBar = document.getElementById("tabs");
document.getElementById("reload").onclick = () => location.reload();
const tabBody = document.getElementById("tab-body");
const refreshers = [];
const TAB_KEY = "deckit.tab";
const tabs = {};

// Tab icons, glyphs in the Nerd Font the server serves, or a brand logo from
// static/logos; a tab with neither shows its name. The name also shows next
// to the active one.
const TAB_ICONS = { Dashboard: "\uf0e4", Windows: "\uf2d2", Assistant: "\uf086", K1C: "\u{f0e5b}" };
const TAB_LOGOS = { OBS: "obs" };

function ensureTab(name) {
  if (tabs[name]) return tabs[name];
  const button = document.createElement("button");
  button.dataset.tab = name;
  button.setAttribute("aria-label", name);
  button.title = name;
  button.innerHTML = TAB_LOGOS[name] ? `<i class="brand ${TAB_LOGOS[name]}"></i><span></span>` : `<i class="nf"></i><span></span>`;
  button.firstElementChild.textContent = TAB_ICONS[name] ?? "";
  button.lastElementChild.textContent = name;
  if (!TAB_ICONS[name] && !TAB_LOGOS[name]) button.classList.add("named");
  button.onclick = () => showTab(name);
  tabBar.append(button);
  const section = document.createElement("section");
  section.className = "tab-panel";
  section.dataset.tab = name;
  section.hidden = true;
  tabBody.append(section);
  tabs[name] = { button, section };
  return tabs[name];
}

const TAB_ORDER = ["Dashboard", "Windows", "OBS"];

function sortTabs() {
  const rank = (name) => {
    const at = TAB_ORDER.indexOf(name);
    return at === -1 ? TAB_ORDER.length : at;
  };
  for (const name of Object.keys(tabs).sort((a, b) => rank(a) - rank(b))) {
    tabBar.append(tabs[name].button);
    tabBody.append(tabs[name].section);
  }
}

// The new tab slides in from the side it sits on in the bar.
const slide = matchMedia("(prefers-reduced-motion: reduce)");
function showTab(name) {
  keep();
  const order = [...tabBar.children].map((b) => b.dataset.tab);
  const from = order.findIndex((n) => !tabs[n]?.section.hidden);
  const to = order.indexOf(name);
  if (from !== -1 && from !== to && !slide.matches) {
    const dx = to > from ? "40px" : "-40px";
    tabs[name].section.animate([{ transform: `translateX(${dx})`, opacity: 0 }, { transform: "none", opacity: 1 }],
                               { duration: 220, easing: "cubic-bezier(.2, .8, .2, 1)" });
  }
  for (const [n, tab] of Object.entries(tabs)) {
    tab.section.hidden = n !== name;
    tab.button.classList.toggle("active", n === name);
  }
  try {
    localStorage.setItem(TAB_KEY, name);
  } catch {}
}

// A panel's peek(state) gives seconds when something new turned up: its tab
// comes forward that long, then the page goes back, unless touched first.
let peek = null;   // {back, timer} while a tab is shown on its own
function peekTab(name, seconds) {
  const now = Object.keys(tabs).find((n) => !tabs[n].section.hidden);
  if (now === name && !peek) return;   // already there by choice
  const back = peek?.back ?? now;
  showTab(name);
  peek = { back, timer: setTimeout(() => showTab(back), seconds * 1000) };
}
function keep() {
  if (peek) clearTimeout(peek.timer);
  peek = null;
}

const dashboard = ensureTab("Dashboard");
dashboard.section.hidden = false;
dashboard.button.classList.add("active");

// Polls /api/<name> every `seconds` and hands the state to update. The first
// poll is not awaited: a slow source (the build VM over ssh, a printer that
// is off) must not hold back the others.
function poll(name, seconds, update) {
  const tick = async () => {
    try {
      const r = await fetch(`/api/${name}`);
      const why = r.headers.get("X-Deckit-Sleep");
      if (why) return goodnight(`The PC is ${why}`);
      awake();
      if (r.ok) update(await r.json());
    } catch {
      // keep the last state; the next tick retries
    }
  };
  refreshers.push(tick);
  tick();
  setInterval(tick, seconds * 1000);
}

function mountTab(name, panel, section) {
  const wrap = document.createElement("div");
  wrap.className = "tab-content";
  section.append(wrap);
  panel.mount?.(wrap);
  poll(name, panel.interval ?? 1, (st) => {
    panel.update?.(st, wrap);
    const seconds = panel.peek?.(st);
    if (seconds > 0) peekTab(panel.tab, seconds);
  });
}

// Modules with no panel file: dashboard.js draws them.
const DRAWN = ["stats", "tablet", "llm", "actions"];

async function boot() {
  const r = await fetch("/api/modules");
  if (!r.ok) return;
  // Every panel's code at once; then mount in the server's order, so the
  // tabs do not shuffle with whichever import lands first.
  const names = (await r.json()).map(({ name }) => name);
  const loaded = await Promise.all(names.map((name) => (DRAWN.includes(name) ? null
    : import(`./modules/${name}.js`).then((m) => m.default, () => null))));
  names.forEach((name, i) => {
    const panel = loaded[i];
    if (!panel?.tab) return;   // no tab: drawn by the Dashboard, if at all
    try {
      mountTab(name, panel, ensureTab(panel.tab).section);
    } catch {
      // a broken panel must not take down the rest of the page
    }
  });
  try {
    const { default: dash } = await import("./dashboard.js");
    dash.mount(dashboard.section, names, { poll, open: showTab });
  } catch {
    // the other tabs still work
  }
  sortTabs();
  const saved = localStorage.getItem(TAB_KEY);
  showTab(tabs[saved] ? saved : "Dashboard");
}

function stepTab(dir) {
  const names = [...tabBar.children].map((button) => button.dataset.tab);
  const at = names.findIndex((name) => !tabs[name]?.section.hidden);
  const next = at + dir;
  if (at !== -1 && next >= 0 && next < names.length) showTab(names[next]);
}

// Swipe the content sideways to change tab, from anywhere but sliders and
// text fields, whose sideways drags are theirs.
// #tab-body is `touch-action: pan-y`: otherwise the browser claims the moving
// finger as a pan and sends pointercancel, which is why swipes never worked.
// A swipe that started on a button must not also click it.
let swipe = null;
let swallowClick = false;
tabBody.addEventListener("pointerdown", (e) => {
  keep();
  if (e.pointerType === "mouse" && e.buttons !== 1) return;
  if (e.target.closest("input, select, textarea")) {
    swipe = null;
    return;
  }
  swipe = { x: e.clientX, y: e.clientY };
});
tabBody.addEventListener("pointerup", (e) => {
  if (!swipe) return;
  const dx = e.clientX - swipe.x;
  const dy = e.clientY - swipe.y;
  swipe = null;
  if (Math.abs(dx) < 70 || Math.abs(dx) < Math.abs(dy) * 1.5) return;
  swallowClick = true;
  setTimeout(() => { swallowClick = false; }, 0);
  stepTab(dx < 0 ? 1 : -1);
});
tabBody.addEventListener("click", (e) => {
  if (swallowClick) { e.stopPropagation(); e.preventDefault(); }
}, true);
tabBody.addEventListener("pointercancel", () => { swipe = null; });

// theme.css is rendered per request from UDT's live files, so re-reading it
// carries a scheme, wallpaper or font-size change to an open page. The <style>
// comes after the <link>, so it wins once filled.
const themeStyle = document.head.appendChild(document.createElement("style"));
const themeColor = document.querySelector('meta[name="theme-color"]');

async function refreshTheme() {
  try {
    const r = await fetch("theme.css", { cache: "no-store" });
    if (!r.ok) return;
    const text = await r.text();
    if (text !== themeStyle.textContent) themeStyle.textContent = text;
  } catch {
    // keep the current theme; the next tick retries
  }
  const base = getComputedStyle(document.documentElement).getPropertyValue("--udt-base").trim();
  if (base) themeColor.content = base;
}
refreshers.push(refreshTheme);
refreshTheme();
setInterval(refreshTheme, 5000);

// Keep the tablet's screen on while the dashboard is in front, so it never
// dims or starts its screensaver. The lock drops whenever the page is hidden
// and is taken again when it comes back. 127.0.0.1 is a secure context, which
// the Wake Lock API requires.
const asleep = document.getElementById("asleep");
let wakeLock = null;
async function keepAwake() {
  try {
    if (document.visibilityState === "visible" && asleep.hidden && !wakeLock) {
      wakeLock = (await navigator.wakeLock?.request("screen")) ?? null;
      wakeLock?.addEventListener("release", () => { wakeLock = null; });
    }
  } catch {
    // refused (battery saver): the screen just follows its own timeout
  }
}
keepAwake();

// The server marks its answers for a moment before the PC suspends
// (deckit/sleep.py), so the page says "asleep" at once; a PC that stops
// answering without saying so (a crash, a dropped tunnel) gets the same
// overlay after 15 s. Either way the wake lock goes, so the tablet sleeps
// too, and the first plain answer takes both back.
const ASLEEP_AFTER = 15000;
function goodnight(title) {
  document.getElementById("asleep-title").textContent = title;
  asleep.hidden = false;
  wakeLock?.release();
}
let lastAnswer = Date.now();
function awake() {
  lastAnswer = Date.now();
  if (!asleep.hidden) {
    asleep.hidden = true;
    keepAwake();
  }
}
setInterval(() => {
  if (asleep.hidden && Date.now() - lastAnswer > ASLEEP_AFTER) goodnight("The PC is not answering");
}, 2000);

// After [tablet] dim_after seconds with no touch the server lowers the
// tablet's backlight and a dark layer covers the page; the touch that lands
// on that layer only brings the brightness back.
const dimmer = document.getElementById("dimmer");
let dimAfter = 0, dimTimer = null;
const tablet = (action) => fetch(`/api/tablet/${action}`, {
  method: "POST", headers: { "Content-Type": "application/json" }, body: "{}",
}).catch(() => {});
function touched() {
  clearTimeout(dimTimer);
  if (dimAfter > 0) dimTimer = setTimeout(() => { dimmer.hidden = false; tick(); tablet("dim"); }, dimAfter * 1000);
}
dimmer.addEventListener("click", () => { dimmer.hidden = true; tablet("undim"); });
// A clock on the cover, so the dim tablet still tells the time at a glance.
function tick() {
  if (dimmer.hidden) return;
  const now = new Date();
  dimmer.querySelector(".dim-time").textContent = now.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
  dimmer.querySelector(".dim-date").textContent = now.toLocaleDateString([], { weekday: "long", day: "numeric", month: "long" });
}
setInterval(tick, 1000);
document.addEventListener("pointerdown", touched, true);
// A fresh page is not dimmed, so a dim left by an earlier server goes too.
fetch("/api/tablet").then((r) => r.json()).then((t) => { dimAfter = t.dim_after ?? 0; tablet("undim"); touched(); }).catch(() => {});

document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "visible") {
    lastAnswer = Math.max(lastAnswer, Date.now() - ASLEEP_AFTER + 5000);   // a moment for the refresh below
    refreshers.forEach((fn) => fn());
  }
  keepAwake();
});

boot();