@ywkrlerche/richardwho 1.0.29 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/app.js CHANGED
@@ -221,6 +221,14 @@
221
221
  }
222
222
  };
223
223
 
224
+ // Hosted elsewhere as a working page (not a single file we can fetch): frame that page directly
225
+ if (game.embed) {
226
+ els.barFill.style.width = "100%";
227
+ els.loaderStatus.textContent = "Starting…";
228
+ startGameHtml(game, embedHtml(game.embed));
229
+ return;
230
+ }
231
+
224
232
  try {
225
233
  // Played before? Start straight from the browser's saved copy, no download
226
234
  const cached = await gameCache.get(urls[0]);
@@ -276,9 +284,15 @@
276
284
  }
277
285
  }
278
286
 
287
+ function embedHtml(url) {
288
+ const safe = url.replace(/[&"<>]/g, (c) => ({ "&": "&amp;", '"': "&quot;", "<": "&lt;", ">": "&gt;" }[c]));
289
+ return `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000;overflow:hidden}iframe{display:block;width:100%;height:100%;border:0}</style></head>` +
290
+ `<body><iframe src="${safe}" allow="autoplay; fullscreen; gamepad; pointer-lock" allowfullscreen></iframe></body></html>`;
291
+ }
292
+
279
293
  function startGameHtml(game, html) {
280
294
  if (currentLoad?.id !== game.id) return;
281
- if (game.src === "gn") html = stripTracking(html);
295
+ if (game.src === "gn" && !game.embed) html = stripTracking(html);
282
296
  html = guardHistory(html);
283
297
  const doc = freshFrame().contentDocument;
284
298
  doc.open();
@@ -380,13 +394,30 @@
380
394
  }
381
395
 
382
396
  // ---------- Routing: "" home, #games, #recent, #play/<id> ----------
383
- function route() {
397
+ const VIEW_ORDER = ["home", "games", "chat", "stats", "settings"];
398
+ let lastView = null;
399
+ function viewFor(hash) {
400
+ return hash === "#games" || hash === "#recent" ? "games" : hash === "#settings" ? "settings" : hash === "#chat" ? "chat" : hash === "#stats" ? "stats" : "home";
401
+ }
402
+ // Switching pages: the old page slides out while the new one slides in (down the side bar = upward,
403
+ // up the side bar = downward). Uses the browser's view transitions; older browsers just switch.
404
+ function route(after) {
405
+ const next = location.hash.startsWith("#play/") ? null : viewFor(location.hash);
406
+ const animate = next && lastView && next !== lastView && els.player.hidden && document.startViewTransition &&
407
+ !matchMedia("(prefers-reduced-motion: reduce)").matches;
408
+ if (!animate) { routeNow(); after?.(); return; }
409
+ document.documentElement.dataset.navDir = VIEW_ORDER.indexOf(next) < VIEW_ORDER.indexOf(lastView) ? "up" : "down";
410
+ document.startViewTransition(() => { routeNow(); after?.(); });
411
+ }
412
+ function routeNow() {
384
413
  const m = location.hash.match(/^#play\/(.+)$/);
385
414
  const game = m && byId.get(decodeURIComponent(m[1]));
386
415
  if (game) {
387
416
  els.player.hidden = false;
388
417
  document.body.classList.add("playing");
389
418
  addRecent(game.id);
419
+ placeChatBox();
420
+ if (dockOpen()) openChat();
390
421
  if (currentLoad?.id !== game.id) {
391
422
  loadGame(game);
392
423
  track(`Play: ${game.name}`, { name: "play_game", params: { game_name: game.name, game_category: game.tag } });
@@ -397,13 +428,14 @@
397
428
  els.player.hidden = true;
398
429
  document.body.classList.remove("playing");
399
430
  document.title = tabTitle();
400
- const h = location.hash;
401
- const view = h === "#games" || h === "#recent" ? "games" : h === "#settings" ? "settings" : h === "#chat" ? "chat" : h === "#stats" ? "stats" : "home";
431
+ const view = viewFor(location.hash);
402
432
  els.homeView.hidden = view !== "home";
403
433
  els.gamesView.hidden = view !== "games";
404
434
  $("view-settings").hidden = view !== "settings";
405
435
  $("view-chat").hidden = view !== "chat";
436
+ lastView = view;
406
437
  $("view-stats").hidden = view !== "stats";
438
+ placeChatBox();
407
439
  if (view === "settings") { renderSettings(); renderAdmin(); }
408
440
  if (view === "stats") renderStats();
409
441
  if (view === "chat") openChat();
@@ -417,8 +449,7 @@
417
449
  function go(view) {
418
450
  const target = view === "home" ? "" : `#${view}`;
419
451
  if (location.hash !== target) history.pushState(null, "", target || location.pathname + location.search);
420
- route();
421
- if (view !== "recent") window.scrollTo(0, 0);
452
+ route(() => { if (view !== "recent") window.scrollTo(0, 0); });
422
453
  }
423
454
  function goBack() {
424
455
  if (location.hash.startsWith("#play/")) history.length > 1 ? history.back() : (location.hash = "#games");
@@ -649,6 +680,33 @@
649
680
  const keys = CFG.panicKeys.map((k) => (k === " " ? "Space" : k)).join(" or ");
650
681
  $("panic-btn").title = `Panic (${keys})`;
651
682
  document.querySelector(".corner-links span").innerHTML = `${CFG.panicKeys.map((k) => `<kbd>${escapeHtml(k === " " ? "Space" : k)}</kbd>`).join(" or ")} panic`;
683
+ renderBookmark();
684
+ }
685
+
686
+ // Home page bookmark chip: the no-version link, which unpkg always sends to the newest version
687
+ const LATEST_URL = `https://unpkg.com/${CFG.npmPackage || "@ywkrlerche/richardwho"}/index.html`;
688
+ function renderBookmark() {
689
+ $("bookmark-link").href = LATEST_URL;
690
+ $("bookmark-name").textContent = "richardwho";
691
+ $("bookmark-icon").src = REAL_ICON;
692
+ }
693
+ // "Latest version" button: look up the newest version and open it (or say you're already on it)
694
+ async function goLatest() {
695
+ const pkg = CFG.npmPackage || "@ywkrlerche/richardwho";
696
+ const btn = $("latest-btn");
697
+ btn.disabled = true;
698
+ try {
699
+ const res = await fetch(`https://unpkg.com/${pkg}/package.json?t=${Date.now()}`, { cache: "no-store" });
700
+ const latest = (await res.json()).version;
701
+ if (location.hostname === "unpkg.com" && location.pathname.includes(`@${latest}/`)) {
702
+ toast(`You're already on the latest version (v${latest}) ✓`);
703
+ btn.disabled = false;
704
+ return;
705
+ }
706
+ location.href = `https://unpkg.com/${pkg}@${latest}/index.html`;
707
+ } catch {
708
+ location.href = LATEST_URL; // couldn't check: the no-version link still lands on the newest
709
+ }
652
710
  }
653
711
 
654
712
  function renderSettings() {
@@ -973,7 +1031,7 @@
973
1031
  return;
974
1032
  }
975
1033
  if (chat.admin) setAdminName();
976
- chatNote(chat.admin ? "You're admin: 🗑 deletes a message, 🚫 bans its sender." : "");
1034
+ chatNote("");
977
1035
  const log = $("chat-log");
978
1036
  log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
979
1037
  if (chat.ref) chat.ref.off(); // reconnecting (signed in/out): drop the old listener so messages don't double
@@ -990,24 +1048,91 @@
990
1048
  div.dataset.uid = m.uid || "";
991
1049
  // filter again on display, in case anything slipped past older rules
992
1050
  const shown = cleanMessage(m.text).text || "[removed]";
993
- div.innerHTML = `${m.admin ? `<span class="badge-admin">⭐ ADMIN</span>` : ""}<span class="who">${escapeHtml(m.name || "?")}</span>${escapeHtml(shown)}<span class="when">${t.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}</span>` +
1051
+ const mention = m.uid !== chat.uid && mentionsMe(m.text);
1052
+ if (mention) div.classList.add("mention");
1053
+ const body = escapeHtml(shown).replace(/(^|\s)@([\w.-]{2,16})/g, '$1<span class="at">@$2</span>');
1054
+ div.innerHTML = `${m.admin ? `<span class="badge-admin">⭐ ADMIN</span>` : ""}<span class="who" title="Mention">${escapeHtml(m.name || "?")}</span>${body}<span class="when">${t.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}</span>` +
994
1055
  `<button class="mod" type="button" data-mod="delete" title="Delete message">🗑</button><button class="mod" type="button" data-mod="ban" title="Ban this person">🚫</button>`;
995
1056
  log.appendChild(div);
996
1057
  while (log.children.length > 80) log.firstChild.remove();
997
1058
  if (nearBottom || m.uid === chat.uid) log.scrollTop = log.scrollHeight;
1059
+ noteNewMessage(m, mention);
998
1060
  });
999
1061
  // Deleted by an admin: disappears for everyone
1000
1062
  ref.on("child_removed", (snap) => {
1001
1063
  log.querySelector(`[data-key="${CSS.escape(snap.key)}"]`)?.remove();
1002
1064
  if (!log.querySelector(".chat-msg")) log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
1003
1065
  });
1066
+ startTypingWatch(app.database());
1067
+ }
1068
+
1069
+ // ---------- "X is typing…" ----------
1070
+ // Each person typing writes chat/typing/<their id> = { name, ts } every few seconds; entries older
1071
+ // than 6s are ignored, and the entry is removed on send, when the box is emptied, or on disconnect.
1072
+ const typing = { others: {}, sentAt: 0, offset: 0, timer: null, ref: null };
1073
+ function myChatName() {
1074
+ if (chat.admin) return ADMIN_NAME;
1075
+ const n = cleanName($("chat-name").value);
1076
+ return n.error || n.name.toLowerCase() === ADMIN_NAME.toLowerCase() ? null : n.name;
1077
+ }
1078
+ function startTypingWatch(db) {
1079
+ db.ref(".info/serverTimeOffset").on("value", (s) => { typing.offset = s.val() || 0; });
1080
+ db.ref("chat/typing").on("value", (snap) => { typing.others = snap.val() || {}; renderTyping(); }, () => {});
1081
+ clearInterval(typing.timer);
1082
+ typing.timer = setInterval(renderTyping, 1000);
1083
+ }
1084
+ function renderTyping() {
1085
+ const now = Date.now() + typing.offset;
1086
+ const names = Object.entries(typing.others)
1087
+ .filter(([uid, t]) => uid !== chat.uid && t && typeof t.name === "string" && now - t.ts < 6000)
1088
+ .map(([, t]) => t.name);
1089
+ const text = !names.length ? "" : names.length === 1 ? `${names[0]} is typing…`
1090
+ : names.length === 2 ? `${names[0]} and ${names[1]} are typing…` : "Several people are typing…";
1091
+ if ($("chat-typing").textContent !== text) $("chat-typing").textContent = text;
1092
+ }
1093
+ async function noteTyping() {
1094
+ if (!$("chat-text").value.trim()) { stopTyping(); return; }
1095
+ if (!chat.uid || Date.now() - typing.sentAt < 2500) return;
1096
+ const name = myChatName();
1097
+ const app = name && (await getFirebase());
1098
+ if (!app) return;
1099
+ typing.sentAt = Date.now();
1100
+ if (!typing.ref) {
1101
+ typing.ref = app.database().ref(`chat/typing/${chat.uid}`);
1102
+ typing.ref.onDisconnect().remove();
1103
+ }
1104
+ typing.ref.set({ name, ts: window.firebase.database.ServerValue.TIMESTAMP }).catch(() => {});
1105
+ }
1106
+ function stopTyping() {
1107
+ if (!typing.sentAt) return;
1108
+ typing.sentAt = 0;
1109
+ typing.ref?.remove().catch(() => {});
1110
+ }
1111
+
1112
+ // ---------- @mentions ----------
1113
+ function mentionsMe(text) {
1114
+ const name = chat.admin ? ADMIN_NAME : store.get("rug-chat-name", "");
1115
+ if (!name || typeof text !== "string") return false;
1116
+ const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1117
+ return new RegExp(`(^|\\s)@${esc}(?![\\w])`, "i").test(text);
1118
+ }
1119
+ // Clicking a name starts an @mention of them
1120
+ function mentionFromName(e) {
1121
+ const who = e.target.closest(".chat-msg .who");
1122
+ if (!who) return;
1123
+ const box = $("chat-text");
1124
+ const tag = `@${who.textContent} `;
1125
+ if (!box.value.includes(tag)) box.value = (box.value.trim() ? box.value.trimEnd() + " " : "") + tag;
1126
+ box.focus();
1004
1127
  }
1005
1128
 
1006
1129
  // ---------- Admin tools (chat) ----------
1007
1130
  async function adminAction(e) {
1008
1131
  const btn = e.target.closest("[data-mod]");
1009
- if (!btn || !chat.admin) return;
1132
+ if (!btn) return;
1010
1133
  const row = btn.closest(".chat-msg");
1134
+ const mine = row.dataset.uid && row.dataset.uid === chat.uid;
1135
+ if (!chat.admin && !(mine && btn.dataset.mod === "delete")) return; // everyone may delete their own
1011
1136
  const db = (await getFirebase()).database();
1012
1137
  try {
1013
1138
  if (btn.dataset.mod === "delete") {
@@ -1018,18 +1143,134 @@
1018
1143
  chatNote("Banned. Their old messages stay until you delete them.");
1019
1144
  }
1020
1145
  } catch {
1021
- chatNote("That didn't work. Are you still signed in as an admin?", true);
1146
+ chatNote("That didn't work.", true);
1022
1147
  }
1023
1148
  }
1024
1149
 
1150
+ // The Tools section only exists for a browser that entered the code; everyone else never sees it
1025
1151
  async function renderAdmin() {
1026
1152
  const app = await getFirebase();
1027
- $("admin-group").hidden = !app;
1028
- if (!app) return;
1029
- await ensureUser(app);
1030
- $("admin-status").textContent = chat.admin ? "Admin on this browser ✓" : "Not an admin on this browser";
1031
- $("admin-leave").hidden = !chat.admin;
1032
- $("admin-tools-row").hidden = !chat.admin;
1153
+ if (app) await ensureUser(app);
1154
+ const on = !!app && chat.admin;
1155
+ $("admin-group").hidden = !on;
1156
+ $("admin-status").textContent = on ? "Moderation is on for this browser ✓" : "";
1157
+ $("admin-leave").hidden = !on;
1158
+ $("admin-tools-row").hidden = !on;
1159
+ $("admin-reports").hidden = !on;
1160
+ if (on) watchReports(); else unwatchReports();
1161
+ }
1162
+
1163
+ // ---------- Report a broken game / request a game ----------
1164
+ // Anyone can send one; only the site owner (the moderation code) can read them, in Settings.
1165
+ const REPORT_REASONS = ["Black screen", "Won't load", "Crashes or freezes", "Controls don't work", "Other"];
1166
+ const report = { type: null, game: null, reason: "", sentAt: 0 };
1167
+ function openReport(type, game = null, prefill = "") {
1168
+ Object.assign(report, { type, game, reason: "" });
1169
+ const broken = type === "broken";
1170
+ $("report-title").textContent = broken ? "Report a broken game" : "Request a game";
1171
+ $("report-sub").textContent = broken ? `${game.name}: what's wrong?` : "Tell us what game to add.";
1172
+ $("report-reasons").innerHTML = broken
1173
+ ? REPORT_REASONS.map((r) => `<button type="button" role="radio" aria-checked="false" data-reason="${escapeHtml(r)}">${escapeHtml(r)}</button>`).join("")
1174
+ : "";
1175
+ $("report-game").hidden = broken;
1176
+ $("report-game").value = broken ? "" : prefill;
1177
+ $("report-note").value = "";
1178
+ $("report-msg").textContent = "";
1179
+ $("report-msg").classList.remove("err");
1180
+ $("report-send").disabled = false;
1181
+ $("report-wrap").hidden = false;
1182
+ (broken ? $("report-reasons").querySelector("button") : $("report-game")).focus();
1183
+ }
1184
+ function closeReport() {
1185
+ $("report-wrap").hidden = true;
1186
+ if (!els.player.hidden) try { els.frame.contentWindow.focus(); } catch {}
1187
+ }
1188
+ function reportMsg(text, err) { $("report-msg").textContent = text; $("report-msg").classList.toggle("err", !!err); }
1189
+ async function sendReport(e) {
1190
+ e.preventDefault();
1191
+ const broken = report.type === "broken";
1192
+ if (broken && !report.reason) return reportMsg("Pick what's wrong.", true);
1193
+ const name = broken ? report.game.name : $("report-game").value.replace(/\s+/g, " ").trim();
1194
+ if (!broken && name.length < 2) return reportMsg("Type the game's name.", true);
1195
+ if (!broken && name.split(" ").some(isBadWord)) return reportMsg("That name was blocked.", true);
1196
+ const rawNote = $("report-note").value.trim();
1197
+ const note = rawNote ? cleanMessage(rawNote) : { text: "" };
1198
+ if (note.error) return reportMsg(note.error, true);
1199
+ const wait = 20000 - (Date.now() - report.sentAt);
1200
+ if (wait > 0) return reportMsg(`You just sent one. Wait ${Math.ceil(wait / 1000)}s.`, true);
1201
+ const app = await getFirebase();
1202
+ if (!app) return reportMsg("Reports aren't switched on for this site.", true);
1203
+ $("report-send").disabled = true;
1204
+ reportMsg("Sending…");
1205
+ try {
1206
+ const user = chat.uid ? { uid: chat.uid } : await ensureUser(app);
1207
+ const db = app.database();
1208
+ const TS = window.firebase.database.ServerValue.TIMESTAMP;
1209
+ const item = { type: report.type, game: name.slice(0, 80), uid: user.uid, ts: TS };
1210
+ if (broken) Object.assign(item, { gameId: report.game.id, reason: report.reason });
1211
+ if (note.text) item.note = note.text;
1212
+ await db.ref().update({ [`reports/items/${db.ref("reports/items").push().key}`]: item, [`reports/last/${user.uid}`]: TS });
1213
+ report.sentAt = Date.now();
1214
+ closeReport();
1215
+ toast(broken ? "Thanks! We'll look at it." : "Thanks! Request sent.");
1216
+ } catch {
1217
+ $("report-send").disabled = false;
1218
+ reportMsg("Couldn't send. Wait a bit and try again.", true);
1219
+ }
1220
+ }
1221
+
1222
+ let reportsRef = null;
1223
+ async function watchReports() {
1224
+ const app = await getFirebase();
1225
+ if (!app || !chat.admin || reportsRef) return;
1226
+ reportsRef = app.database().ref("reports/items").orderByChild("ts").limitToLast(200);
1227
+ reportsRef.on("value", (snap) => {
1228
+ const list = [];
1229
+ snap.forEach((c) => { list.push({ key: c.key, ...c.val() }); });
1230
+ renderReports(list.reverse());
1231
+ }, () => { reportsRef = null; $("reports-list").innerHTML = `<p class="none">Couldn't load reports.</p>`; });
1232
+ }
1233
+ function unwatchReports() { reportsRef?.off(); reportsRef = null; }
1234
+ function renderReports(list) {
1235
+ $("reports-count").textContent = list.length ? `(${list.length})` : "";
1236
+ $("reports-list").innerHTML = !list.length ? `<p class="none">Nothing yet.</p>` : list.map((r) => {
1237
+ const g = r.gameId && byId.get(r.gameId);
1238
+ const game = g ? `<a class="game" href="#play/${encodeURIComponent(g.id)}">${escapeHtml(r.game)}</a>` : `<span class="game">${escapeHtml(r.game)}</span>`;
1239
+ const when = new Date(r.ts).toLocaleString([], { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
1240
+ return `<div class="report" data-key="${escapeHtml(r.key)}"><span class="kind ${r.type === "broken" ? "broken" : "request"}">${r.type === "broken" ? "Broken" : "Request"}</span>` +
1241
+ `<div class="body">${game}${r.reason ? ` · ${escapeHtml(r.reason)}` : ""}${r.note ? `<div class="note">${escapeHtml(r.note)}</div>` : ""}<div class="meta">${when}</div></div>` +
1242
+ `<button class="mod" type="button" data-del title="Delete">🗑</button></div>`;
1243
+ }).join("");
1244
+ }
1245
+ function bindReports() {
1246
+ $("bookmark-link").addEventListener("click", (e) => {
1247
+ e.preventDefault(); // it's for dragging; a click just explains
1248
+ toast(`Drag it up to your bookmarks bar, or press ${/Mac/.test(navigator.platform) ? "⌘" : "Ctrl"}+D`);
1249
+ });
1250
+ $("latest-btn").addEventListener("click", goLatest);
1251
+ $("report-btn").addEventListener("click", () => { const g = currentLoad && byId.get(currentLoad.id); if (g) openReport("broken", g); });
1252
+ $("request-btn").addEventListener("click", () => openReport("request"));
1253
+ $("request-btn-2").addEventListener("click", () => openReport("request", null, els.search.value.trim()));
1254
+ $("report-form").addEventListener("submit", sendReport);
1255
+ $("report-close").addEventListener("click", closeReport);
1256
+ $("report-cancel").addEventListener("click", closeReport);
1257
+ $("report-wrap").addEventListener("click", (e) => { if (e.target === $("report-wrap")) closeReport(); });
1258
+ $("report-reasons").addEventListener("click", (e) => {
1259
+ const b = e.target.closest("[data-reason]");
1260
+ if (!b) return;
1261
+ report.reason = b.dataset.reason;
1262
+ $("report-reasons").querySelectorAll("button").forEach((x) => x.setAttribute("aria-checked", x === b));
1263
+ reportMsg("");
1264
+ });
1265
+ $("reports-list").addEventListener("click", async (e) => {
1266
+ const row = e.target.closest("[data-del]")?.closest(".report");
1267
+ if (!row || !chat.admin) return;
1268
+ try { await (await getFirebase()).database().ref(`reports/items/${row.dataset.key}`).remove(); } catch {}
1269
+ });
1270
+ $("reports-clear").addEventListener("click", async () => {
1271
+ if (!chat.admin || !confirm("Delete every report and request?")) return;
1272
+ try { await (await getFirebase()).database().ref("reports/items").remove(); } catch {}
1273
+ });
1033
1274
  }
1034
1275
 
1035
1276
  // "#code" as a nickname: the database compares it with the secret code (which visitors can't read).
@@ -1074,7 +1315,7 @@
1074
1315
  chat.triedName = rawName;
1075
1316
  if (await claimAdmin(rawName)) {
1076
1317
  setAdminName();
1077
- chatNote("You're admin now ✓ Your messages show as Richard, with 🗑 delete and 🚫 ban on every message.");
1318
+ chatNote("");
1078
1319
  if (!$("chat-text").value.trim()) return;
1079
1320
  }
1080
1321
  }
@@ -1096,6 +1337,7 @@
1096
1337
  [`chat/last/${chat.uid}`]: TS,
1097
1338
  });
1098
1339
  $("chat-text").value = "";
1340
+ stopTyping();
1099
1341
  stats.bump("chatSent");
1100
1342
  chatNote("");
1101
1343
  } catch {
@@ -1103,6 +1345,47 @@
1103
1345
  }
1104
1346
  }
1105
1347
 
1348
+ // ---------- Chat beside a game, and the unread dot ----------
1349
+ // There's one chat box: it sits on the Chat page, or in the player's side dock while that's open.
1350
+ const CHAT_SEEN_KEY = "rug-chat-seen", CHAT_DOCK_KEY = "rug-chat-dock";
1351
+ function dockOpen() { return !els.player.hidden && store.get(CHAT_DOCK_KEY, false); }
1352
+ function chatShowing() { return dockOpen() || (els.player.hidden && !$("view-chat").hidden); }
1353
+ function placeChatBox() {
1354
+ const docked = dockOpen();
1355
+ $("chat-dock").hidden = !docked;
1356
+ $("dock-btn").setAttribute("aria-pressed", docked);
1357
+ const home = docked ? $("chat-dock") : $("view-chat");
1358
+ if ($("chat-box").parentNode !== home) home.appendChild($("chat-box"));
1359
+ if (chatShowing()) markChatSeen();
1360
+ }
1361
+ function toggleDock(open = !store.get(CHAT_DOCK_KEY, false)) {
1362
+ store.set(CHAT_DOCK_KEY, open);
1363
+ placeChatBox();
1364
+ if (open) { openChat(); $("chat-log").scrollTop = $("chat-log").scrollHeight; $("chat-text").focus(); }
1365
+ else try { els.frame.contentWindow.focus(); } catch {}
1366
+ }
1367
+ function setUnread(on, mention = false) {
1368
+ document.querySelectorAll('.rail-btn[data-nav="chat"], #dock-btn').forEach((b) => {
1369
+ b.classList.toggle("has-unread", on);
1370
+ if (!on) b.classList.remove("has-mention");
1371
+ else if (mention) b.classList.add("has-mention");
1372
+ });
1373
+ }
1374
+ function markChatSeen() {
1375
+ if (chat.newest) store.set(CHAT_SEEN_KEY, chat.newest);
1376
+ setUnread(false);
1377
+ }
1378
+ // Called for every message as it arrives (including the recent ones loaded at start)
1379
+ function noteNewMessage(m, mention) {
1380
+ const ts = Number(m.ts) || 0;
1381
+ chat.newest = Math.max(chat.newest || 0, ts);
1382
+ if (chatShowing()) markChatSeen();
1383
+ else if (m.uid !== chat.uid && ts > store.get(CHAT_SEEN_KEY, 0)) {
1384
+ setUnread(true, mention);
1385
+ if (mention) toast(`💬 ${m.name} mentioned you: ${cleanMessage(m.text).text || ""}`.slice(0, 120));
1386
+ }
1387
+ }
1388
+
1106
1389
  // ---------- Arrow keys and controller move focus between tiles and buttons ----------
1107
1390
  function focusables() {
1108
1391
  const scope = els.player.hidden ? document : els.player;
@@ -1134,12 +1417,14 @@
1134
1417
  if (listeningForKey) return; // the Settings page is capturing a new panic key
1135
1418
  const keys = CFG.panicKeys || ["`", "]"];
1136
1419
  if (keys.includes(e.key)) { e.preventDefault(); panic(); return; }
1420
+ if (!$("report-wrap").hidden) { if (e.key === "Escape") closeReport(); return; }
1137
1421
  if (!$("wheel-wrap").hidden) {
1138
1422
  if (e.key === "Escape") closeWheel();
1139
1423
  else if (e.key === " " && wheel.spinning) { e.preventDefault(); finishWheel(); } // space skips
1140
1424
  return;
1141
1425
  }
1142
1426
  if (!els.player.hidden) {
1427
+ if (e.key === "Escape" && $("chat-dock").contains(document.activeElement)) { toggleDock(false); return; }
1143
1428
  if (e.key === "Escape" && document.activeElement !== els.frame) goBack();
1144
1429
  return;
1145
1430
  }
@@ -1221,6 +1506,7 @@
1221
1506
  $("panic-btn").addEventListener("click", panic);
1222
1507
  $("panic-btn-2").addEventListener("click", panic);
1223
1508
  $("back-btn").addEventListener("click", goBack);
1509
+ $("dock-btn").addEventListener("click", () => toggleDock());
1224
1510
  $("reload-btn").addEventListener("click", () => {
1225
1511
  const g = currentLoad && byId.get(currentLoad.id);
1226
1512
  if (g) loadGame(g);
@@ -1230,8 +1516,8 @@
1230
1516
  const el = els.frame;
1231
1517
  (el.requestFullscreen || el.webkitRequestFullscreen)?.call(el);
1232
1518
  });
1233
- window.addEventListener("hashchange", route);
1234
- window.addEventListener("popstate", route);
1519
+ window.addEventListener("hashchange", () => route());
1520
+ window.addEventListener("popstate", () => route());
1235
1521
  }
1236
1522
 
1237
1523
  // ---------- Logo hover: spotlight follows the mouse, logo tilts toward it ----------
@@ -1377,9 +1663,17 @@
1377
1663
  bindWheel();
1378
1664
  bindWordmark();
1379
1665
  $("chat-form").addEventListener("submit", sendChat);
1666
+ $("chat-text").addEventListener("input", noteTyping);
1667
+ $("chat-text").addEventListener("blur", stopTyping);
1668
+ $("chat-log").addEventListener("click", mentionFromName);
1380
1669
  bindAdmin();
1670
+ bindReports();
1381
1671
  startAnalytics();
1382
1672
  startPresence();
1673
+ // Listen to chat from the start so the chat buttons can show a dot for new messages.
1674
+ // First visit: only messages from now on count as new.
1675
+ if (store.get(CHAT_SEEN_KEY, null) === null) store.set(CHAT_SEEN_KEY, Date.now());
1676
+ if (CFG.firebase) openChat();
1383
1677
  // long enough to read a joke or two (skipped when the loading screen is off)
1384
1678
  const minShow = new Promise((r) => setTimeout(r, settings.boot !== false ? 1500 : 0));
1385
1679
  const update = newerVersionUrl(2500);