@ywkrlerche/richardwho 1.0.28 โ†’ 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();
@@ -287,6 +301,7 @@
287
301
  els.loader.hidden = true;
288
302
  hookFrameKeys();
289
303
  try { els.frame.contentWindow.focus(); } catch {}
304
+ stats.startPlay(game);
290
305
  }
291
306
 
292
307
  // Saved copies of recently played games (browser Cache Storage), so replays start instantly.
@@ -358,6 +373,7 @@
358
373
  }
359
374
 
360
375
  function stopGame() {
376
+ stats.stopPlay();
361
377
  if (!currentLoad) return;
362
378
  currentLoad.controller.abort();
363
379
  currentLoad = null;
@@ -378,13 +394,30 @@
378
394
  }
379
395
 
380
396
  // ---------- Routing: "" home, #games, #recent, #play/<id> ----------
381
- 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() {
382
413
  const m = location.hash.match(/^#play\/(.+)$/);
383
414
  const game = m && byId.get(decodeURIComponent(m[1]));
384
415
  if (game) {
385
416
  els.player.hidden = false;
386
417
  document.body.classList.add("playing");
387
418
  addRecent(game.id);
419
+ placeChatBox();
420
+ if (dockOpen()) openChat();
388
421
  if (currentLoad?.id !== game.id) {
389
422
  loadGame(game);
390
423
  track(`Play: ${game.name}`, { name: "play_game", params: { game_name: game.name, game_category: game.tag } });
@@ -395,13 +428,16 @@
395
428
  els.player.hidden = true;
396
429
  document.body.classList.remove("playing");
397
430
  document.title = tabTitle();
398
- const h = location.hash;
399
- const view = h === "#games" || h === "#recent" ? "games" : h === "#settings" ? "settings" : h === "#chat" ? "chat" : "home";
431
+ const view = viewFor(location.hash);
400
432
  els.homeView.hidden = view !== "home";
401
433
  els.gamesView.hidden = view !== "games";
402
434
  $("view-settings").hidden = view !== "settings";
403
435
  $("view-chat").hidden = view !== "chat";
436
+ lastView = view;
437
+ $("view-stats").hidden = view !== "stats";
438
+ placeChatBox();
404
439
  if (view === "settings") { renderSettings(); renderAdmin(); }
440
+ if (view === "stats") renderStats();
405
441
  if (view === "chat") openChat();
406
442
  track(view[0].toUpperCase() + view.slice(1));
407
443
  document.querySelectorAll(".rail-btn[data-nav]").forEach((b) =>
@@ -413,8 +449,7 @@
413
449
  function go(view) {
414
450
  const target = view === "home" ? "" : `#${view}`;
415
451
  if (location.hash !== target) history.pushState(null, "", target || location.pathname + location.search);
416
- route();
417
- if (view !== "recent") window.scrollTo(0, 0);
452
+ route(() => { if (view !== "recent") window.scrollTo(0, 0); });
418
453
  }
419
454
  function goBack() {
420
455
  if (location.hash.startsWith("#play/")) history.length > 1 ? history.back() : (location.hash = "#games");
@@ -462,6 +497,152 @@
462
497
  applyTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark"));
463
498
  }
464
499
 
500
+ // ---------- Play stats + achievements (saved in this browser) ----------
501
+ // Time counts only while a game is open AND the tab is visible.
502
+ const STATS_KEY = "rug-stats";
503
+ const ACHIEVEMENTS = [
504
+ { id: "first", icon: "๐ŸŽฎ", name: "First Steps", desc: "Play your first game", goal: 1, of: (s) => s.unique },
505
+ { id: "ten", icon: "๐Ÿ”Ÿ", name: "Warming Up", desc: "Play 10 different games", goal: 10, of: (s) => s.unique },
506
+ { id: "25", icon: "๐Ÿงญ", name: "Explorer", desc: "Play 25 different games", goal: 25, of: (s) => s.unique },
507
+ { id: "50", icon: "๐Ÿ—บ๏ธ", name: "Adventurer", desc: "Play 50 different games", goal: 50, of: (s) => s.unique },
508
+ { id: "100", icon: "๐Ÿ’ฏ", name: "Collector", desc: "Play 100 different games", goal: 100, of: (s) => s.unique },
509
+ { id: "250", icon: "๐Ÿ‘‘", name: "Game Royalty", desc: "Play 250 different games", goal: 250, of: (s) => s.unique },
510
+ { id: "hour", icon: "โฑ๏ธ", name: "One More Game", desc: "Play for 1 hour in total", goal: 60, of: (s) => s.minutes, unit: "min" },
511
+ { id: "10h", icon: "๐Ÿ›‹๏ธ", name: "Couch Legend", desc: "Play for 10 hours in total", goal: 600, of: (s) => s.minutes, unit: "min" },
512
+ { id: "hooked", icon: "๐ŸŽฃ", name: "Hooked", desc: "Spend 30 minutes in one game", goal: 30, of: (s) => s.topMinutes, unit: "min" },
513
+ { id: "replay", icon: "๐Ÿ”", name: "Comfort Game", desc: "Open the same game 10 times", goal: 10, of: (s) => s.topPlays },
514
+ { id: "racing", icon: "๐ŸŽ๏ธ", name: "Speed Freak", desc: "Play 10 racing games", goal: 10, of: (s) => s.byTag.Racing || 0 },
515
+ { id: "racing-all", icon: "๐Ÿ", name: "Every Racetrack", desc: "Play every racing game", goal: () => tagTotal("Racing"), of: (s) => s.byTag.Racing || 0 },
516
+ { id: "horror", icon: "๐Ÿ‘ป", name: "Brave Soul", desc: "Play 5 horror games", goal: 5, of: (s) => s.byTag.Horror || 0 },
517
+ { id: "rhythm", icon: "๐ŸŽต", name: "Got Rhythm", desc: "Play 5 rhythm games", goal: 5, of: (s) => s.byTag.Rhythm || 0 },
518
+ { id: "papa", icon: "๐Ÿ•", name: "Papa's Apprentice", desc: "Play every Papa's game", goal: () => papasTotal(), of: (s) => s.papas },
519
+ { id: "allcats", icon: "๐ŸŒˆ", name: "Well-Rounded", desc: "Play a game from every category", goal: () => tagList().length, of: (s) => s.tags },
520
+ { id: "wheel", icon: "๐ŸŽก", name: "Feeling Lucky", desc: "Play a game the wheel picked", goal: 1, of: (s) => s.wheelPlays || 0 },
521
+ { id: "spins", icon: "๐ŸŒ€", name: "Spin Doctor", desc: "Spin the wheel 25 times", goal: 25, of: (s) => s.wheelSpins || 0 },
522
+ { id: "chat", icon: "๐Ÿ’ฌ", name: "Chatterbox", desc: "Send 10 chat messages", goal: 10, of: (s) => s.chatSent || 0 },
523
+ { id: "night", icon: "๐Ÿฆ‰", name: "Night Owl", desc: "Play a game between midnight and 4 AM", goal: 1, of: (s) => (s.night ? 1 : 0) },
524
+ ];
525
+ const tagList = () => [...new Set(games.filter((g) => g.tag !== "Tools").map((g) => g.tag))];
526
+ const tagTotal = (tag) => games.filter((g) => g.tag === tag).length;
527
+ const isPapas = (g) => /^papa'?s /i.test(g.name);
528
+ const papasTotal = () => games.filter(isPapas).length;
529
+
530
+ const stats = {
531
+ data: null,
532
+ current: null, // { id, since } while a game is open and visible
533
+ load() {
534
+ if (!this.data) this.data = { games: {}, wheelSpins: 0, wheelPlays: 0, chatSent: 0, night: false, unlocked: {}, ...store.get(STATS_KEY, {}) };
535
+ return this.data;
536
+ },
537
+ save() { store.set(STATS_KEY, this.data); },
538
+ bump(key) { this.load()[key] = (this.data[key] || 0) + 1; this.save(); checkAchievements(); },
539
+ startPlay(game) {
540
+ this.stopPlay();
541
+ const d = this.load();
542
+ const rec = d.games[game.id] || (d.games[game.id] = { plays: 0, ms: 0 });
543
+ rec.plays++;
544
+ rec.last = Date.now();
545
+ const h = new Date().getHours();
546
+ if (h < 4) d.night = true;
547
+ this.save();
548
+ this.current = { id: game.id, since: document.hidden ? null : Date.now() };
549
+ checkAchievements();
550
+ },
551
+ // Add the time since the last check to the open game (called on stop, tab hide, and every 30s)
552
+ flush() {
553
+ const c = this.current;
554
+ if (!c || !c.since) return;
555
+ const rec = this.load().games[c.id];
556
+ if (rec) rec.ms += Math.min(Date.now() - c.since, 60 * 60 * 1000); // cap any single gap at an hour
557
+ c.since = document.hidden ? null : Date.now();
558
+ this.save();
559
+ },
560
+ stopPlay() { this.flush(); this.current = null; },
561
+ summary() {
562
+ const d = this.load();
563
+ const entries = Object.entries(d.games).filter(([id]) => byId.has(id));
564
+ const byTag = {};
565
+ let papas = 0, ms = 0, topMs = 0, topPlays = 0;
566
+ for (const [id, r] of entries) {
567
+ const g = byId.get(id);
568
+ byTag[g.tag] = (byTag[g.tag] || 0) + 1;
569
+ if (isPapas(g)) papas++;
570
+ ms += r.ms;
571
+ topMs = Math.max(topMs, r.ms);
572
+ topPlays = Math.max(topPlays, r.plays);
573
+ }
574
+ return {
575
+ ...d, unique: entries.length, plays: entries.reduce((a, [, r]) => a + r.plays, 0),
576
+ minutes: Math.floor(ms / 60000), topMinutes: Math.floor(topMs / 60000), topPlays, byTag, papas,
577
+ tags: tagList().filter((t) => byTag[t]).length,
578
+ top: entries.sort((a, b) => b[1].ms - a[1].ms || b[1].plays - a[1].plays).slice(0, 5),
579
+ };
580
+ },
581
+ };
582
+ document.addEventListener("visibilitychange", () => {
583
+ if (!stats.current) return;
584
+ if (document.hidden) stats.flush();
585
+ else stats.current.since = Date.now();
586
+ });
587
+ addEventListener("pagehide", () => stats.flush());
588
+ setInterval(() => { stats.flush(); checkAchievements(); }, 30000);
589
+
590
+ const goalOf = (a) => (typeof a.goal === "function" ? a.goal() : a.goal);
591
+ function checkAchievements() {
592
+ if (!games.length) return;
593
+ const s = stats.summary(), d = stats.data;
594
+ for (const a of ACHIEVEMENTS) {
595
+ if (d.unlocked[a.id]) continue;
596
+ const goal = goalOf(a);
597
+ if (goal > 0 && a.of(s) >= goal) {
598
+ d.unlocked[a.id] = Date.now();
599
+ stats.save();
600
+ toast(`${a.icon} Achievement unlocked: ${a.name}`);
601
+ }
602
+ }
603
+ if (!$("view-stats").hidden) renderStats();
604
+ }
605
+
606
+ let toastTimer = 0;
607
+ function toast(text) {
608
+ const t = $("toast");
609
+ t.textContent = text;
610
+ t.classList.add("show");
611
+ clearTimeout(toastTimer);
612
+ toastTimer = setTimeout(() => t.classList.remove("show"), 4000);
613
+ }
614
+
615
+ function fmtTime(min) {
616
+ if (min < 1) return "<1 min";
617
+ const h = Math.floor(min / 60), m = min % 60;
618
+ return h ? `${h}h ${m}m` : `${m}m`;
619
+ }
620
+ function renderStats() {
621
+ if (!games.length) return;
622
+ const s = stats.summary(), d = stats.data;
623
+ const favTag = Object.entries(s.byTag).sort((a, b) => b[1] - a[1])[0];
624
+ $("stat-unique").textContent = s.unique;
625
+ $("stat-plays").textContent = s.plays;
626
+ $("stat-time").textContent = s.plays ? fmtTime(s.minutes) : "0 min";
627
+ $("stat-fav").textContent = favTag ? `${TAG_EMOJI[favTag[0]] || ""} ${favTag[0]}` : "โ€“";
628
+ $("stat-top").innerHTML = s.top.length
629
+ ? s.top.map(([id, r], i) => `<li><span>${i + 1}. ${escapeHtml(byId.get(id).name)}</span><span>${fmtTime(Math.floor(r.ms / 60000))} ยท ${r.plays} play${r.plays === 1 ? "" : "s"}</span></li>`).join("")
630
+ : `<li class="muted">Play some games and your favorites show up here.</li>`;
631
+ const done = ACHIEVEMENTS.filter((a) => d.unlocked[a.id]).length;
632
+ $("ach-count").textContent = `${done} of ${ACHIEVEMENTS.length} unlocked`;
633
+ $("achievements").innerHTML = ACHIEVEMENTS.map((a) => {
634
+ const goal = goalOf(a), have = Math.min(a.of(s), goal), got = !!d.unlocked[a.id];
635
+ const pct = goal ? Math.round((have / goal) * 100) : 0;
636
+ const prog = a.unit === "min" ? `${fmtTime(have)} / ${fmtTime(goal)}` : `${have} / ${goal}`;
637
+ return `<div class="ach${got ? " got" : ""}" title="${escapeHtml(a.desc)}">
638
+ <span class="ach-icon">${got ? a.icon : "๐Ÿ”’"}</span>
639
+ <div class="ach-body"><b>${escapeHtml(a.name)}</b><small>${escapeHtml(a.desc)}</small>
640
+ ${got ? `<small class="ach-done">Unlocked ${new Date(d.unlocked[a.id]).toLocaleDateString()}</small>`
641
+ : `<div class="ach-bar"><div style="width:${pct}%"></div></div><small>${prog}</small>`}
642
+ </div></div>`;
643
+ }).join("");
644
+ }
645
+
465
646
  // ---------- Settings (saved in this browser) ----------
466
647
  const SETTINGS_KEY = "rug-settings";
467
648
  const REAL_ICON = "data:image/svg+xml," + encodeURIComponent("<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect width='100' height='100' rx='22' fill='black'/><text x='50' y='70' font-size='62' text-anchor='middle' fill='white' font-family='Arial' font-weight='800'>r</text></svg>");
@@ -499,6 +680,33 @@
499
680
  const keys = CFG.panicKeys.map((k) => (k === " " ? "Space" : k)).join(" or ");
500
681
  $("panic-btn").title = `Panic (${keys})`;
501
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
+ }
502
710
  }
503
711
 
504
712
  function renderSettings() {
@@ -556,6 +764,12 @@
556
764
  $("set-per-row").addEventListener("change", (e) => setPerRow(Number(e.target.value)));
557
765
  $("set-typing").addEventListener("change", (e) => { settings.typing = e.target.checked; saveSettings(); startTypingPlaceholder(); });
558
766
  $("set-boot").addEventListener("change", (e) => { settings.boot = e.target.checked; saveSettings(); });
767
+ $("set-reset-stats").addEventListener("click", () => {
768
+ if (!confirm("Reset your stats and achievements on this device?")) return;
769
+ stats.data = null;
770
+ store.set(STATS_KEY, {});
771
+ renderStats();
772
+ });
559
773
  $("set-clear-recent").addEventListener("click", () => {
560
774
  store.set(RECENT_KEY, []);
561
775
  renderRecent();
@@ -612,6 +826,7 @@
612
826
  ctx.stroke();
613
827
  }
614
828
  function spinWheel(pool) {
829
+ stats.bump("wheelSpins");
615
830
  const picks = [...pool].sort(() => Math.random() - 0.5).slice(0, Math.min(12, pool.length));
616
831
  wheel.items = picks.length >= 2 ? picks : [...picks, ...picks];
617
832
  const n = wheel.items.length, a = (Math.PI * 2) / n;
@@ -668,7 +883,7 @@
668
883
  function bindWheel() {
669
884
  $("wheel-skip").addEventListener("click", finishWheel);
670
885
  $("wheel-again").addEventListener("click", () => spinWheel(wheelPool));
671
- $("wheel-play").addEventListener("click", () => { const g = wheel.winner; closeWheel(); play(g.id); });
886
+ $("wheel-play").addEventListener("click", () => { const g = wheel.winner; closeWheel(); stats.bump("wheelPlays"); play(g.id); });
672
887
  $("wheel-close").addEventListener("click", closeWheel);
673
888
  $("wheel-wrap").addEventListener("click", (e) => { if (e.target.id === "wheel-wrap") closeWheel(); });
674
889
  }
@@ -816,7 +1031,7 @@
816
1031
  return;
817
1032
  }
818
1033
  if (chat.admin) setAdminName();
819
- chatNote(chat.admin ? "You're admin: ๐Ÿ—‘ deletes a message, ๐Ÿšซ bans its sender." : "");
1034
+ chatNote("");
820
1035
  const log = $("chat-log");
821
1036
  log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
822
1037
  if (chat.ref) chat.ref.off(); // reconnecting (signed in/out): drop the old listener so messages don't double
@@ -833,24 +1048,91 @@
833
1048
  div.dataset.uid = m.uid || "";
834
1049
  // filter again on display, in case anything slipped past older rules
835
1050
  const shown = cleanMessage(m.text).text || "[removed]";
836
- 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>` +
837
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>`;
838
1056
  log.appendChild(div);
839
1057
  while (log.children.length > 80) log.firstChild.remove();
840
1058
  if (nearBottom || m.uid === chat.uid) log.scrollTop = log.scrollHeight;
1059
+ noteNewMessage(m, mention);
841
1060
  });
842
1061
  // Deleted by an admin: disappears for everyone
843
1062
  ref.on("child_removed", (snap) => {
844
1063
  log.querySelector(`[data-key="${CSS.escape(snap.key)}"]`)?.remove();
845
1064
  if (!log.querySelector(".chat-msg")) log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
846
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();
847
1127
  }
848
1128
 
849
1129
  // ---------- Admin tools (chat) ----------
850
1130
  async function adminAction(e) {
851
1131
  const btn = e.target.closest("[data-mod]");
852
- if (!btn || !chat.admin) return;
1132
+ if (!btn) return;
853
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
854
1136
  const db = (await getFirebase()).database();
855
1137
  try {
856
1138
  if (btn.dataset.mod === "delete") {
@@ -861,18 +1143,134 @@
861
1143
  chatNote("Banned. Their old messages stay until you delete them.");
862
1144
  }
863
1145
  } catch {
864
- chatNote("That didn't work. Are you still signed in as an admin?", true);
1146
+ chatNote("That didn't work.", true);
865
1147
  }
866
1148
  }
867
1149
 
1150
+ // The Tools section only exists for a browser that entered the code; everyone else never sees it
868
1151
  async function renderAdmin() {
869
1152
  const app = await getFirebase();
870
- $("admin-group").hidden = !app;
871
- if (!app) return;
872
- await ensureUser(app);
873
- $("admin-status").textContent = chat.admin ? "Admin on this browser โœ“" : "Not an admin on this browser";
874
- $("admin-leave").hidden = !chat.admin;
875
- $("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
+ });
876
1274
  }
877
1275
 
878
1276
  // "#code" as a nickname: the database compares it with the secret code (which visitors can't read).
@@ -917,7 +1315,7 @@
917
1315
  chat.triedName = rawName;
918
1316
  if (await claimAdmin(rawName)) {
919
1317
  setAdminName();
920
- chatNote("You're admin now โœ“ Your messages show as Richard, with ๐Ÿ—‘ delete and ๐Ÿšซ ban on every message.");
1318
+ chatNote("");
921
1319
  if (!$("chat-text").value.trim()) return;
922
1320
  }
923
1321
  }
@@ -939,12 +1337,55 @@
939
1337
  [`chat/last/${chat.uid}`]: TS,
940
1338
  });
941
1339
  $("chat-text").value = "";
1340
+ stopTyping();
1341
+ stats.bump("chatSent");
942
1342
  chatNote("");
943
1343
  } catch {
944
1344
  chatNote("Message blocked (filtered word, or sending too fast).", true);
945
1345
  }
946
1346
  }
947
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
+
948
1389
  // ---------- Arrow keys and controller move focus between tiles and buttons ----------
949
1390
  function focusables() {
950
1391
  const scope = els.player.hidden ? document : els.player;
@@ -976,12 +1417,14 @@
976
1417
  if (listeningForKey) return; // the Settings page is capturing a new panic key
977
1418
  const keys = CFG.panicKeys || ["`", "]"];
978
1419
  if (keys.includes(e.key)) { e.preventDefault(); panic(); return; }
1420
+ if (!$("report-wrap").hidden) { if (e.key === "Escape") closeReport(); return; }
979
1421
  if (!$("wheel-wrap").hidden) {
980
1422
  if (e.key === "Escape") closeWheel();
981
1423
  else if (e.key === " " && wheel.spinning) { e.preventDefault(); finishWheel(); } // space skips
982
1424
  return;
983
1425
  }
984
1426
  if (!els.player.hidden) {
1427
+ if (e.key === "Escape" && $("chat-dock").contains(document.activeElement)) { toggleDock(false); return; }
985
1428
  if (e.key === "Escape" && document.activeElement !== els.frame) goBack();
986
1429
  return;
987
1430
  }
@@ -1063,6 +1506,7 @@
1063
1506
  $("panic-btn").addEventListener("click", panic);
1064
1507
  $("panic-btn-2").addEventListener("click", panic);
1065
1508
  $("back-btn").addEventListener("click", goBack);
1509
+ $("dock-btn").addEventListener("click", () => toggleDock());
1066
1510
  $("reload-btn").addEventListener("click", () => {
1067
1511
  const g = currentLoad && byId.get(currentLoad.id);
1068
1512
  if (g) loadGame(g);
@@ -1072,8 +1516,29 @@
1072
1516
  const el = els.frame;
1073
1517
  (el.requestFullscreen || el.webkitRequestFullscreen)?.call(el);
1074
1518
  });
1075
- window.addEventListener("hashchange", route);
1076
- window.addEventListener("popstate", route);
1519
+ window.addEventListener("hashchange", () => route());
1520
+ window.addEventListener("popstate", () => route());
1521
+ }
1522
+
1523
+ // ---------- Logo hover: spotlight follows the mouse, logo tilts toward it ----------
1524
+ function bindWordmark() {
1525
+ const w = document.querySelector(".wordmark");
1526
+ if (!w || matchMedia("(hover: none), (prefers-reduced-motion: reduce)").matches) return;
1527
+ w.addEventListener("mousemove", (e) => {
1528
+ const r = w.getBoundingClientRect();
1529
+ const x = (e.clientX - r.left) / r.width, y = (e.clientY - r.top) / r.height;
1530
+ w.classList.add("hovering");
1531
+ w.style.setProperty("--mx", `${(x * 100).toFixed(1)}%`);
1532
+ w.style.setProperty("--my", `${(y * 100).toFixed(1)}%`);
1533
+ w.style.setProperty("--spot", `${Math.round(r.height * 1.1)}px`);
1534
+ w.style.setProperty("--ry", `${((x - 0.5) * 14).toFixed(2)}deg`);
1535
+ w.style.setProperty("--rx", `${((0.5 - y) * 12).toFixed(2)}deg`);
1536
+ w.style.setProperty("--sc", "1.03");
1537
+ });
1538
+ w.addEventListener("mouseleave", () => {
1539
+ w.classList.remove("hovering");
1540
+ ["--ry", "--rx", "--sc", "--spot"].forEach((p) => w.style.removeProperty(p));
1541
+ });
1077
1542
  }
1078
1543
 
1079
1544
  // ---------- Home search: placeholder that types itself ----------
@@ -1196,10 +1661,19 @@
1196
1661
  bind();
1197
1662
  bindSettings();
1198
1663
  bindWheel();
1664
+ bindWordmark();
1199
1665
  $("chat-form").addEventListener("submit", sendChat);
1666
+ $("chat-text").addEventListener("input", noteTyping);
1667
+ $("chat-text").addEventListener("blur", stopTyping);
1668
+ $("chat-log").addEventListener("click", mentionFromName);
1200
1669
  bindAdmin();
1670
+ bindReports();
1201
1671
  startAnalytics();
1202
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();
1203
1677
  // long enough to read a joke or two (skipped when the loading screen is off)
1204
1678
  const minShow = new Promise((r) => setTimeout(r, settings.boot !== false ? 1500 : 0));
1205
1679
  const update = newerVersionUrl(2500);