@ywkrlerche/richardwho 1.0.32 → 1.0.34

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.
Files changed (61) hide show
  1. package/app.js +573 -71
  2. package/config.js +0 -1
  3. package/games.json +1 -1
  4. package/index.html +42 -4
  5. package/logos/kh-100ng.webp +0 -0
  6. package/logos/kh-2048-multitask.webp +0 -0
  7. package/logos/kh-adrenalinechallenge.webp +0 -0
  8. package/logos/kh-align-4.webp +0 -0
  9. package/logos/kh-amidst-the-clouds.webp +0 -0
  10. package/logos/kh-angry-sharks.webp +0 -0
  11. package/logos/kh-avalanche.webp +0 -0
  12. package/logos/kh-battleforgondor.webp +0 -0
  13. package/logos/kh-blacholesquare.webp +0 -0
  14. package/logos/kh-blackknight.webp +0 -0
  15. package/logos/kh-boxhead2play.webp +0 -0
  16. package/logos/kh-btd4.webp +0 -0
  17. package/logos/kh-burger-and-frights.webp +0 -0
  18. package/logos/kh-canyondefense.webp +0 -0
  19. package/logos/kh-championarcher.webp +0 -0
  20. package/logos/kh-creativekillchamber.webp +0 -0
  21. package/logos/kh-csgo-clicker.webp +0 -0
  22. package/logos/kh-dante.webp +0 -0
  23. package/logos/kh-deal-or-no-deal.webp +0 -0
  24. package/logos/kh-deepest-sword.webp +0 -0
  25. package/logos/kh-defend-the-tank.webp +0 -0
  26. package/logos/kh-doge2048.webp +0 -0
  27. package/logos/kh-edgenotfound.webp +0 -0
  28. package/logos/kh-endlesswar3.webp +0 -0
  29. package/logos/kh-evolution.webp +0 -0
  30. package/logos/kh-exo.webp +0 -0
  31. package/logos/kh-fairsquares.webp +0 -0
  32. package/logos/kh-flappy-2048.webp +0 -0
  33. package/logos/kh-flashtetris.webp +0 -0
  34. package/logos/kh-flippy-fish.webp +0 -0
  35. package/logos/kh-froggys-battle.webp +0 -0
  36. package/logos/kh-gachalife.webp +0 -0
  37. package/logos/kh-generic-fishing-game.webp +0 -0
  38. package/logos/kh-geojump.webp +0 -0
  39. package/logos/kh-gimme-the-airpod.webp +0 -0
  40. package/logos/kh-google-snake.webp +0 -0
  41. package/logos/kh-hardware-tycoon.webp +0 -0
  42. package/logos/kh-hba.webp +0 -0
  43. package/logos/kh-hexempire.webp +0 -0
  44. package/logos/kh-hexgl.webp +0 -0
  45. package/logos/kh-hextris.webp +0 -0
  46. package/logos/kh-just-one-boss.webp +0 -0
  47. package/logos/kh-kittencannon.webp +0 -0
  48. package/logos/kh-mario.webp +0 -0
  49. package/logos/kh-marvinspectrum.webp +0 -0
  50. package/logos/kh-matrixrampage.webp +0 -0
  51. package/logos/kh-meme2048.webp +0 -0
  52. package/logos/kh-my-rusty-submarine.webp +0 -0
  53. package/logos/kh-noob-steve-parkour.webp +0 -0
  54. package/logos/kh-ns-shaft.webp +0 -0
  55. package/logos/kh-offlineparadise.webp +0 -0
  56. package/logos/kh-out-of-ctrl.webp +0 -0
  57. package/logos/kh-pandemic2.webp +0 -0
  58. package/logos/kh-particle-clicker.webp +0 -0
  59. package/logos/kh-poom.webp +0 -0
  60. package/package.json +1 -1
  61. package/style.css +72 -9
package/app.js CHANGED
@@ -293,7 +293,7 @@
293
293
  function startGameHtml(game, html) {
294
294
  if (currentLoad?.id !== game.id) return;
295
295
  if (game.src === "gn" && !game.embed) html = stripTracking(html);
296
- html = guardHistory(html);
296
+ html = guardHistory(pinCdn(html), game.base);
297
297
  const doc = freshFrame().contentDocument;
298
298
  doc.open();
299
299
  doc.write(html);
@@ -354,6 +354,16 @@
354
354
  }
355
355
 
356
356
  // The extra collection's launch files embed Google Analytics; remove it so players aren't tracked
357
+ // Many games load their files from other people's GitHub repos through jsDelivr using a branch
358
+ // (@main). jsDelivr refuses branch links into repos over 50 MB unless the file happens to be cached,
359
+ // so those games break at random. games.json's cdnPins maps "owner/repo@branch" to a fixed commit.
360
+ let cdnPins = {};
361
+ function pinCdn(html) {
362
+ return html.replace(/(cdn|fastly)\.jsdelivr\.net\/gh\/([\w.-]+\/[\w.-]+?)(?:@([\w.-]+))?\//g, (all, host, repo, ref) => {
363
+ const sha = cdnPins[`${repo}@${ref || ""}`];
364
+ return sha ? `${host}.jsdelivr.net/gh/${repo}@${sha}/` : all;
365
+ });
366
+ }
357
367
  function stripTracking(html) {
358
368
  return html
359
369
  .replace(/<script\b[^>]*googletagmanager\.com[^>]*>\s*<\/script>/gi, "")
@@ -367,9 +377,11 @@
367
377
  // Insert only at the very top of the file (after an optional doctype and <html> tag). Searching for the
368
378
  // first "<head>" anywhere is unsafe: many self-unpacking games keep their whole page inside a script string,
369
379
  // and inserting there cuts that string in half.
370
- function guardHistory(html) {
380
+ // Folder games (game.base): a <base> tag makes the page's images, scripts and sounds load from its folder
381
+ function guardHistory(html, base) {
371
382
  const top = html.match(/^(?\s*(?:<!--[\s\S]*?-->\s*)*(?:<!doctype[^>]*>)?\s*(?:<html\b[^>]*>)?)/i)[1];
372
- return top + HISTORY_GUARD + html.slice(top.length);
383
+ const baseTag = base ? `<base href="${base.replace(/"/g, "&quot;")}">` : "";
384
+ return top + baseTag + HISTORY_GUARD + html.slice(top.length);
373
385
  }
374
386
 
375
387
  function stopGame() {
@@ -394,10 +406,11 @@
394
406
  }
395
407
 
396
408
  // ---------- Routing: "" home, #games, #recent, #play/<id> ----------
397
- const VIEW_ORDER = ["home", "games", "chat", "stats", "settings"];
409
+ const VIEW_ORDER = ["home", "games", "chat", "stats", "settings", "changelog"];
398
410
  let lastView = null;
399
411
  function viewFor(hash) {
400
- return hash === "#games" || hash === "#recent" ? "games" : hash === "#settings" ? "settings" : hash === "#chat" ? "chat" : hash === "#stats" ? "stats" : "home";
412
+ return hash === "#games" || hash === "#recent" ? "games" : hash === "#settings" ? "settings" : hash === "#chat" ? "chat"
413
+ : hash === "#stats" ? "stats" : hash === "#changelog" ? "changelog" : "home";
401
414
  }
402
415
  // Switching pages: the old page slides out while the new one slides in (down the side bar = upward,
403
416
  // up the side bar = downward). Uses the browser's view transitions; older browsers just switch.
@@ -435,6 +448,8 @@
435
448
  $("view-chat").hidden = view !== "chat";
436
449
  lastView = view;
437
450
  $("view-stats").hidden = view !== "stats";
451
+ $("view-changelog").hidden = view !== "changelog";
452
+ if (view === "changelog") renderChangelog();
438
453
  placeChatBox();
439
454
  if (view === "settings") { renderSettings(); renderAdmin(); }
440
455
  if (view === "stats") renderStats();
@@ -499,6 +514,66 @@
499
514
  applyTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark"));
500
515
  }
501
516
 
517
+ // ---------- What's new (changelog) ----------
518
+ // Newest first. Add an entry here with every publish; its version should match package.json.
519
+ // Each has: new (features), games (added/removed/fixed games), fixes (bugs). Leave a list out if empty.
520
+ const CHANGELOG = [
521
+ { version: "1.0.34", date: "2026-10-27",
522
+ new: ["Send photos in chat: drag and drop, paste, or tap 📷", "Emoji picker and 230 animated stickers (😊 button)",
523
+ "🚩 Report messages: 3 reports hides a message", "Slow mode and chat lock when chat gets busy"],
524
+ games: ["55 new games, including Battle for Gondor, Black Knight, Deepest Sword, HexGL, Gacha Life, Pandemic 2, Kitten Cannon and Super Mario Bros"],
525
+ fixes: ["Much stronger chat filter: blocked messages aren't sent at all", "Nicknames can't use links or teacher titles (Mr., Ms., Teacher…)",
526
+ "Explicit photos are blocked automatically",
527
+ "Games that randomly said “won't load” (like Scratch Inc, Recoil and Cubefield) now load reliably",
528
+ "Smaller logo and search bar on the home page"] },
529
+ { version: "1.0.33", date: "2026-10-23",
530
+ new: ["What's new page: see every update, new games and bug fixes (you're on it!)"] },
531
+ { version: "1.0.32", date: "2026-10-23",
532
+ new: ["Phone browsers now match the site's color at the top of the screen", "Keyboard users get a “Skip to content” button on the first Tab press"],
533
+ fixes: ["Search boxes and game tiles show a clear ring when picked with the keyboard",
534
+ "Scrolling to the end of chat or a pop-up no longer scrolls the page behind it",
535
+ "Taps on touch screens respond right away (no double-tap zoom delay)",
536
+ "The green online dot stops pulsing when your device is set to reduce motion"] },
537
+ { version: "1.0.31", date: "2026-10-23",
538
+ games: ["Fixed Recoil: now runs a working copy", "Fixed Gunspin: now runs a working copy",
539
+ "Removed Five Nights at Epstein's and Get Yoked (they relied on sites that schools block)"] },
540
+ { version: "1.0.30", date: "2026-10-23",
541
+ new: ["Chat beside your game: hit 💬 Chat in the game bar", "A dot on the chat button when someone posts",
542
+ "@mentions: type @name to ping someone (their dot turns pink)", "See when someone is typing",
543
+ "Delete your own chat messages with 🗑", "⚠ Report a broken game, or request a new one from the Games page",
544
+ "Pages slide when you switch between them", "Drag-to-bookmark button and a ⟳ Latest version button on the home page"],
545
+ games: ["Tested all 840 games; removed 48 that only showed a blank screen"],
546
+ fixes: ["Opening the Games page is much smoother"] },
547
+ { version: "1.0.29", new: ["Stats & achievements page (🏆 in the side bar)", "New blue look and an animated logo that reacts to your mouse"] },
548
+ { version: "Earlier", new: ["Settings page, tab disguises and panic button", "Random game wheel", "Live online count and the chat room",
549
+ "Funny loading screen", "Recently played and search", "The site updates itself to the newest version"],
550
+ games: ["Hundreds of games added, including a second big collection"],
551
+ fixes: ["Games that said “failed to fetch” now retry backup servers", "Games can no longer kick you back out of the player"] },
552
+ ];
553
+ const SITE_VERSION = CHANGELOG[0].version;
554
+ const CHANGELOG_SEEN_KEY = "rug-changelog-seen";
555
+ const CHANGE_KINDS = [["new", "✨ Updates"], ["games", "🎮 Games"], ["fixes", "🐛 Bug fixes"]];
556
+ function renderChangelog() {
557
+ const fmt = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric", year: "numeric" });
558
+ $("changelog-list").innerHTML = CHANGELOG.map((c, i) => {
559
+ const date = c.date ? `<span class="cl-date">${fmt.format(new Date(c.date + "T12:00:00"))}</span>` : "";
560
+ const tag = i === 0 ? `<span class="cl-latest">Latest</span>` : "";
561
+ const lists = CHANGE_KINDS.filter(([k]) => c[k]?.length).map(([k, label]) =>
562
+ `<div class="cl-kind cl-${k}"><h3>${label}</h3><ul>${c[k].map((x) => `<li>${escapeHtml(x)}</li>`).join("")}</ul></div>`).join("");
563
+ return `<article class="set-group cl-entry"><h2>${/\d/.test(c.version) ? "v" : ""}${escapeHtml(c.version)} ${tag}${date}</h2>${lists}</article>`;
564
+ }).join("");
565
+ store.set(CHANGELOG_SEEN_KEY, SITE_VERSION);
566
+ $("whats-new-link").classList.remove("has-unread");
567
+ }
568
+ function initChangelog() {
569
+ $("home-version").textContent = `v${SITE_VERSION}`;
570
+ $("set-version").textContent = `v${SITE_VERSION}`;
571
+ // A dot on the home link until you've looked at this version's notes (not on your very first visit)
572
+ const seen = store.get(CHANGELOG_SEEN_KEY, null);
573
+ if (seen === null) store.set(CHANGELOG_SEEN_KEY, SITE_VERSION);
574
+ else if (seen !== SITE_VERSION) $("whats-new-link").classList.add("has-unread");
575
+ }
576
+
502
577
  // ---------- Play stats + achievements (saved in this browser) ----------
503
578
  // Time counts only while a game is open AND the tab is visible.
504
579
  const STATS_KEY = "rug-stats";
@@ -953,49 +1028,89 @@
953
1028
  }
954
1029
 
955
1030
  // ---------- Censored chat room ----------
956
- // Two layers: this filter (stars out swears, refuses links/personal info) and the database's own
957
- // rules (see SETUP.md), which reject the same things even if someone skips this page's code.
1031
+ // Two layers: this filter (anything it catches is refused, never starred out and sent) and the
1032
+ // database's rules (tools/build-rules.js), which repeat the core checks for anyone who skips this page.
1033
+ // The owner can add more words from Settings → Tools; they arrive in chat.settings.words.
958
1034
  const BAD_ANYWHERE = ["fuck", "shit", "bitch", "cunt", "nigg", "faggot", "fagot", "whore", "slut", "pussy",
959
1035
  "penis", "vagina", "porn", "retard", "asshole", "bastard", "molest", "pedo", "dildo", "boob", "nazi", "hitler",
960
- "kill yourself", "killyourself"];
961
- const BAD_WHOLE_WORD = ["ass", "fag", "cum", "tit", "tits", "hoe", "kys", "sex", "nig", "dick", "cock", "rape",
962
- "raped", "rapist", "raping", "damn", "piss", "crap", "wank", "twat", "prick"];
963
- const LEET = { 0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t", 8: "b", "@": "a", $: "s", "!": "i", "|": "i" };
1036
+ "kill yourself", "killyourself", "neck yourself", "chink", "chingchong", "kike", "wetback", "tranny", "raghead",
1037
+ "towelhead", "beaner", "jigaboo", "porch monkey", "heil", "white power", "whitepower", "kkk", "1488", "horny",
1038
+ "nudes", "onlyfans", "blowjob", "handjob", "masturbat", "orgasm", "boner", "hentai", "rule34", "jerk off",
1039
+ "jack off", "motherfuck", "dumbass", "jackass", "shoot up the school", "bomb the school"];
1040
+ const BAD_WHOLE_WORD = ["ass", "fag", "fags", "cum", "tit", "tits", "hoe", "hoes", "kys", "sex", "sexy", "nig", "dick",
1041
+ "dicks", "cock", "rape", "raped", "rapist", "raping", "damn", "piss", "crap", "wank", "twat", "prick", "spic",
1042
+ "gook", "coon", "nude", "naked", "thot", "milf", "r34", "stfu", "wtf", "gtfo", "slur", "simp"];
1043
+ // "I hate <group>" and similar: checked on the whole message
1044
+ const BAD_PHRASES = [
1045
+ /\bhate\s+(all\s+)?(the\s+)?(jews?|jewish|blacks?|black people|gays?|muslims?|mexicans?|asians?|chinese|indians?|whites?|white people|trans|lgbt\w*|immigrants?|arabs?|christians?)\b/,
1046
+ /\b(jews?|blacks?|gays?|muslims?|mexicans?|asians?|trans)\s+(are|r)\s+(bad|evil|trash|garbage|disgusting|animals|stupid|the worst|not human)\b/,
1047
+ /\b(go back to|deport)\s+(your|ur)\s+country\b/, /\bgas\s+the\b/, /\bdid nothing wrong\b/, /\bkill\s+(all|every)\b/,
1048
+ ];
1049
+ const LEET = { 0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t", 8: "b", "@": "a", $: "s", "!": "i", "|": "i", "€": "e" };
1050
+ // Look-alike letters from other alphabets ("fυck", "ѕhit") folded to plain a–z
1051
+ const HOMOGLYPHS = { "а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "у": "y", "х": "x", "і": "i", "ј": "j", "ѕ": "s",
1052
+ "к": "k", "м": "m", "н": "h", "т": "t", "в": "b", "ℓ": "l", "α": "a", "ε": "e", "ι": "i", "κ": "k", "ν": "v", "ο": "o",
1053
+ "ρ": "p", "τ": "t", "υ": "u", "χ": "x" };
964
1054
  // Real words that happen to contain a filtered one
965
- const SAFE_WORDS = ["scunthorpe", "shiitake", "cockpit", "peacock", "hancock", "dickens", "assassin", "cocktail", "therapist"];
966
- const plain = (s) => s.toLowerCase().replace(/[0134578@$!|]/g, (c) => LEET[c] || c).replace(/[^a-z ]/g, "");
1055
+ const SAFE_WORDS = ["scunthorpe", "shiitake", "cockpit", "peacock", "hancock", "dickens", "assassin", "cocktail",
1056
+ "therapist", "raccoon", "cocoon", "tycoon", "class", "pass", "grass", "glass", "bass", "mass", "brass", "assist",
1057
+ "assignment", "assume", "classic", "cumulative", "document", "titan", "title", "titles", "sextant", "essex",
1058
+ "middlesex", "shitake", "hello", "night", "nigeria", "niger", "snigger", "analysis", "therapist"];
1059
+ const fold = (s) => s.normalize("NFKD").replace(/[̀-ͯ​-‏⁠]/g, "")
1060
+ .replace(/./gu, (c) => HOMOGLYPHS[c] || HOMOGLYPHS[c.toLowerCase()] || c);
1061
+ const plain = (s) => fold(s).toLowerCase().replace(/[0134578@$!|€]/g, (c) => LEET[c] || c).replace(/[^a-z ]/g, "");
967
1062
  const squash = (s) => plain(s).replace(/(.)\1+/g, "$1"); // "fuuuck" -> "fuck"
1063
+ const tight = (s) => squash(s).replace(/ /g, "");
1064
+ function extraWords() {
1065
+ return String(chat.settings.words || "").split(/[\n,]+/).map((w) => plain(w).trim()).filter((w) => w.length >= 2);
1066
+ }
968
1067
  function isBadWord(word) {
969
- const p = plain(word).replace(/ /g, ""), w = squash(word).replace(/ /g, "");
1068
+ const p = plain(word).replace(/ /g, ""), w = tight(word);
970
1069
  if (!w || SAFE_WORDS.includes(p)) return false;
971
1070
  // whole-word list: check before and after squashing, since squashing turns "ass" into "as"
972
1071
  return BAD_WHOLE_WORD.includes(p) || BAD_WHOLE_WORD.includes(w) ||
973
- BAD_ANYWHERE.some((b) => w.includes(squash(b).replace(/ /g, "")));
1072
+ [...BAD_ANYWHERE, ...extraWords()].some((b) => w.includes(tight(b)));
974
1073
  }
975
- // Returns { text } (with swears starred out) or { error } when the message can't be sent at all
1074
+ // Blocked content just says this, in red: no hints about which word tripped the filter
1075
+ const NOT_ALLOWED = "Not allowed";
1076
+ // Returns { text } or { error } when the message can't be sent. Nothing is ever starred out.
976
1077
  function cleanMessage(raw) {
977
- const text = raw.replace(/\s+/g, " ").trim();
1078
+ const text = String(raw).replace(/\s+/g, " ").trim();
978
1079
  if (!text) return { error: "Type a message first." };
979
- if (/(https?:|www\.|discord\.gg|\b[a-z0-9-]+\.(com|net|org|io|gg|xyz|co|me|tv|ly|app|dev|link)\b)/i.test(text)) return { error: "Links aren't allowed in chat." };
980
- if (/\S+@\S+\.\S+/.test(text)) return { error: "Don't share email addresses." };
981
- if (/(\d[\s().-]*){7,}/.test(text)) return { error: "Don't share phone numbers." };
982
- const masked = text.split(" ").map((w) => (isBadWord(w) ? "*".repeat(w.length) : w)).join(" ");
1080
+ const folded = fold(text);
1081
+ if (/(https?:|www\.|discord\.gg|\b[a-z0-9-]+\s*(\.|dot)\s*(com|net|org|io|gg|xyz|co|me|tv|ly|app|dev|link|ru|us)\b)/i.test(folded)) return { error: NOT_ALLOWED };
1082
+ if (/\S+@\S+\.\S+/.test(folded)) return { error: NOT_ALLOWED };
1083
+ if (/(\d[\s().-]*){7,}/.test(folded)) return { error: NOT_ALLOWED };
1084
+ if (text.split(" ").some(isBadWord)) return { error: NOT_ALLOWED };
983
1085
  // spaced-out tricks like "f u c k" survive word-by-word checks; catch them on the whole line
984
- const joined = squash(masked.split(" ").filter((w) => !SAFE_WORDS.includes(plain(w))).join(" ")).replace(/ /g, "");
985
- if (BAD_ANYWHERE.some((b) => joined.includes(squash(b).replace(/ /g, "")))) return { error: "That message was blocked." };
986
- return { text: masked };
987
- }
1086
+ const joined = tight(text.split(" ").filter((w) => !SAFE_WORDS.includes(plain(w))).join(" "));
1087
+ if ([...BAD_ANYWHERE, ...extraWords()].some((b) => joined.includes(tight(b)))) return { error: NOT_ALLOWED };
1088
+ const sentence = plain(text).replace(/\s+/g, " ");
1089
+ if (BAD_PHRASES.some((re) => re.test(sentence))) return { error: NOT_ALLOWED };
1090
+ return { text };
1091
+ }
1092
+ // Teacher titles and staff-sounding names aren't allowed (people were posing as teachers)
1093
+ const NAME_TITLES = /^(mr|mrs|ms|miss|mx|dr|sir|madam|coach|prof|professor|principal|teacher|dean|admin|mod|moderator|owner|staff|system)( |_|-|$)/i;
988
1094
  function cleanName(raw) {
989
1095
  // Refuse (don't silently strip) other characters: a wrong or not-yet-saved admin code like "Code123!"
990
1096
  // must never be posted as a nickname
991
- if (/[^\w .-]/.test(raw)) return { error: "Nicknames can only use letters, numbers, spaces, . _ and -." };
992
- const name = raw.replace(/\s+/g, " ").trim().slice(0, 16);
993
- if (name.length < 2) return { error: "Pick a nickname (2–16 letters)." };
994
- if (name.split(/[ ._-]/).some(isBadWord) || isBadWord(name.replace(/[ ._-]/g, ""))) return { error: "Pick a different nickname." };
1097
+ if (/[^A-Za-z0-9 _-]/.test(raw)) return { error: "Nicknames can only use letters, numbers, spaces, _ and -." };
1098
+ // (the box allows 40 characters so the admin code fits; real nicknames stop at 16)
1099
+ const name = raw.replace(/\s+/g, " ").trim();
1100
+ if (name.length < 2 || name.length > 16) return { error: "Pick a nickname (2–16 letters)." };
1101
+ if (NAME_TITLES.test(name)) return { error: "Nicknames can't use titles like Mr., Ms. or Teacher." };
1102
+ if (name.split(/[ _-]/).some(isBadWord) || isBadWord(name.replace(/[ _-]/g, ""))) return { error: NOT_ALLOWED };
995
1103
  return { name };
996
1104
  }
997
1105
 
998
- const chat = { started: false, uid: null, lastSent: 0, admin: false, triedName: "" };
1106
+ const chat = {
1107
+ started: false, uid: null, lastSent: 0, admin: false, triedName: "",
1108
+ settings: {}, // owner's live settings: slowMode (s), locked, words
1109
+ mutedUntil: 0, banned: false,
1110
+ flags: {}, // message key -> number of people who reported it
1111
+ lastText: "", lastTextAt: 0, strikes: [],
1112
+ };
1113
+ const HIDE_AFTER_REPORTS = 3;
999
1114
  const ADMIN_NAME = "Richard"; // what the admin's messages show as (reserved: the database refuses it from non-admins)
1000
1115
  function setAdminName() {
1001
1116
  $("chat-name").value = ADMIN_NAME;
@@ -1036,36 +1151,116 @@
1036
1151
  chatNote("");
1037
1152
  const log = $("chat-log");
1038
1153
  log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
1154
+ const db = app.database();
1155
+ watchChatState(db);
1039
1156
  if (chat.ref) chat.ref.off(); // reconnecting (signed in/out): drop the old listener so messages don't double
1040
- const ref = chat.ref = app.database().ref("chat/messages").orderByChild("ts").limitToLast(60);
1157
+ const ref = chat.ref = db.ref("chat/messages").orderByChild("ts").limitToLast(60);
1041
1158
  ref.on("child_added", (snap) => {
1042
1159
  const m = snap.val();
1043
- if (!m || typeof m.text !== "string") return;
1160
+ const div = renderMessage(snap.key, m);
1161
+ if (!div) return;
1044
1162
  $("chat-empty")?.remove();
1045
1163
  const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 60;
1046
- const t = new Date(m.ts || Date.now());
1047
- const div = document.createElement("div");
1048
- div.className = "chat-msg" + (m.uid === chat.uid ? " me" : "");
1049
- div.dataset.key = snap.key;
1050
- div.dataset.uid = m.uid || "";
1051
- // filter again on display, in case anything slipped past older rules
1052
- const shown = cleanMessage(m.text).text || "[removed]";
1053
- const mention = m.uid !== chat.uid && mentionsMe(m.text);
1054
- if (mention) div.classList.add("mention");
1055
- const body = escapeHtml(shown).replace(/(^|\s)@([\w.-]{2,16})/g, '$1<span class="at">@$2</span>');
1056
- 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>` +
1057
- `<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>`;
1058
1164
  log.appendChild(div);
1059
1165
  while (log.children.length > 80) log.firstChild.remove();
1060
1166
  if (nearBottom || m.uid === chat.uid) log.scrollTop = log.scrollHeight;
1061
- noteNewMessage(m, mention);
1167
+ // pictures load after they're added; keep the view pinned to the bottom when they do
1168
+ div.querySelector("img")?.addEventListener("load", () => { if (nearBottom || m.uid === chat.uid) log.scrollTop = log.scrollHeight; }, { once: true });
1169
+ noteNewMessage(m, div.classList.contains("mention"));
1062
1170
  });
1063
- // Deleted by an admin: disappears for everyone
1171
+ // Deleted (by its sender or the owner): disappears for everyone
1064
1172
  ref.on("child_removed", (snap) => {
1065
1173
  log.querySelector(`[data-key="${CSS.escape(snap.key)}"]`)?.remove();
1066
1174
  if (!log.querySelector(".chat-msg")) log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
1067
1175
  });
1068
- startTypingWatch(app.database());
1176
+ startTypingWatch(db);
1177
+ }
1178
+
1179
+ // One chat row: text, a sticker or a photo, plus its buttons (shown by CSS for who may use them)
1180
+ const STICKER_URL = (code) => `https://fonts.gstatic.com/s/e/notoemoji/latest/${code}/512.webp`;
1181
+ function renderMessage(key, m) {
1182
+ if (!m || typeof m.name !== "string") return null;
1183
+ let body;
1184
+ if (typeof m.text === "string") {
1185
+ // filter again on display: older messages and newly blocked words disappear
1186
+ const shown = cleanMessage(m.text).text;
1187
+ if (!shown) return null;
1188
+ body = escapeHtml(shown).replace(/(^|\s)@([\w-]{2,16})/g, '$1<span class="at">@$2</span>');
1189
+ } else if (typeof m.sticker === "string" && STICKERS.includes(m.sticker)) {
1190
+ body = `<img class="chat-sticker" src="${STICKER_URL(m.sticker)}" alt="sticker" width="96" height="96" loading="lazy">`; } else if (typeof m.img === "string" && /^data:image\/(webp|jpeg);base64,[A-Za-z0-9+/=]+$/.test(m.img)) {
1191
+ body = `<button class="chat-photo-btn" type="button" data-act="view" title="Open photo"><img class="chat-photo" src="${m.img}" alt="Photo from ${escapeHtml(m.name)}" loading="lazy"></button>`;
1192
+ } else return null;
1193
+ const t = new Date(m.ts || Date.now());
1194
+ const div = document.createElement("div");
1195
+ const mine = m.uid === chat.uid;
1196
+ div.className = "chat-msg" + (mine ? " me" : "") + (m.img ? " photo" : "") + (m.sticker ? " sticker" : "");
1197
+ div.dataset.key = key;
1198
+ div.dataset.uid = m.uid || "";
1199
+ div.dataset.name = m.name;
1200
+ if (typeof m.text === "string") div.dataset.text = m.text;
1201
+ if (!mine && typeof m.text === "string" && mentionsMe(m.text)) div.classList.add("mention");
1202
+ div.innerHTML = `${m.admin ? `<span class="badge-admin">⭐ ADMIN</span>` : ""}<span class="who" title="Mention">${escapeHtml(m.name)}</span>` +
1203
+ `${body}<span class="when">${t.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}</span>` +
1204
+ `<span class="msg-acts">` +
1205
+ (mine ? "" : `<button class="mod act-report" type="button" data-act="report" title="Report this message">🚩</button>`) +
1206
+ `<button class="mod act-delete" type="button" data-act="delete" title="Delete message">🗑</button>` +
1207
+ (mine ? "" : `<button class="mod owner-only" type="button" data-act="purge" title="Delete everything this person sent">🧹</button>` +
1208
+ `<button class="mod owner-only" type="button" data-act="mute" title="Mute this person">🔇</button>` +
1209
+ `<button class="mod owner-only" type="button" data-act="ban" title="Ban this person">🚫</button>`) +
1210
+ `<span class="flag-count owner-only" title="Reports"></span></span>`;
1211
+ applyFlags(div);
1212
+ return div;
1213
+ }
1214
+ function applyFlags(div) {
1215
+ const n = chat.flags[div.dataset.key] || 0;
1216
+ div.classList.toggle("flagged", n >= HIDE_AFTER_REPORTS);
1217
+ const c = div.querySelector(".flag-count");
1218
+ if (c) c.textContent = n ? `🚩${n}` : "";
1219
+ }
1220
+
1221
+ // Live chat state: owner settings (slow mode, lock, extra words), my mute/ban, and report counts
1222
+ function watchChatState(db) {
1223
+ db.ref("chat/settings").on("value", (s) => {
1224
+ chat.settings = s.val() || {};
1225
+ updateChatStatus();
1226
+ if (chat.admin) fillChatTools();
1227
+ $("chat-log").querySelectorAll(".chat-msg").forEach((row) => { // newly blocked words: hide those messages now
1228
+ const t = row.dataset.text;
1229
+ if (t && !cleanMessage(t).text) row.remove();
1230
+ });
1231
+ }, () => {});
1232
+ db.ref(`chat/mutes/${chat.uid}`).on("value", (s) => { chat.mutedUntil = Number(s.val()?.until) || 0; updateChatStatus(); }, () => {});
1233
+ db.ref(`chat/banned/${chat.uid}`).on("value", (s) => { chat.banned = s.exists(); updateChatStatus(); }, () => {});
1234
+ db.ref("chat/flags").on("value", (s) => {
1235
+ chat.flags = {};
1236
+ s.forEach((c) => { chat.flags[c.key] = c.numChildren(); });
1237
+ $("chat-log").querySelectorAll(".chat-msg").forEach(applyFlags);
1238
+ if (chat.admin) renderReported();
1239
+ }, () => {});
1240
+ clearInterval(chat.statusTimer);
1241
+ chat.statusTimer = setInterval(updateChatStatus, 15000); // mutes run out on their own
1242
+ }
1243
+ // Why this browser can't post right now (or "" if it can)
1244
+ function blockedReason() {
1245
+ if (chat.admin) return "";
1246
+ if (chat.banned) return "You've been banned from sending messages. You can still read.";
1247
+ if (chat.mutedUntil > Date.now()) return `You're muted for ${fmtWait(chat.mutedUntil - Date.now())}.`;
1248
+ if (chat.settings.locked) return "Chat is locked right now. You can still read.";
1249
+ const strike = chat.strikes.filter((t) => Date.now() - t < 120000);
1250
+ if (strike.length >= 3) return `Too many blocked messages. Wait ${fmtWait(120000 - (Date.now() - strike[0]))}.`;
1251
+ return "";
1252
+ }
1253
+ function fmtWait(ms) {
1254
+ const m = Math.ceil(ms / 60000);
1255
+ return m >= 60 * 24 ? `${Math.round(m / 1440)} day${m >= 2880 ? "s" : ""}` : m >= 60 ? `${Math.round(m / 60)} hour${m >= 120 ? "s" : ""}` : `${m} minute${m === 1 ? "" : "s"}`;
1256
+ }
1257
+ function slowSeconds() { return chat.admin ? 0 : Math.max(3, Number(chat.settings.slowMode) || 0); }
1258
+ function updateChatStatus() {
1259
+ const why = blockedReason();
1260
+ ["chat-text", "chat-send", "emoji-btn", "photo-btn"].forEach((id) => { if ($(id)) $(id).disabled = !!why; });
1261
+ const slow = Number(chat.settings.slowMode) || 0;
1262
+ $("chat-status").textContent = why || (chat.settings.locked ? "🔒 Chat is locked (only you can post)" : slow ? `🐢 Slow mode: one message every ${slow}s` : "");
1263
+ $("chat-status").classList.toggle("err", !!why);
1069
1264
  }
1070
1265
 
1071
1266
  // ---------- "X is typing…" ----------
@@ -1128,26 +1323,88 @@
1128
1323
  box.focus();
1129
1324
  }
1130
1325
 
1131
- // ---------- Admin tools (chat) ----------
1132
- async function adminAction(e) {
1133
- const btn = e.target.closest("[data-mod]");
1326
+ // ---------- Message buttons: report (everyone), delete (yours, or any for the owner), owner tools ----------
1327
+ const MUTE_CHOICES = [["10 minutes", 10 * 60e3], ["1 hour", 60 * 60e3], ["1 day", 24 * 60 * 60e3], ["1 week", 7 * 24 * 60 * 60e3]];
1328
+ async function chatAction(e) {
1329
+ const btn = e.target.closest("[data-act]");
1134
1330
  if (!btn) return;
1135
1331
  const row = btn.closest(".chat-msg");
1136
- const mine = row.dataset.uid && row.dataset.uid === chat.uid;
1137
- if (!chat.admin && !(mine && btn.dataset.mod === "delete")) return; // everyone may delete their own
1332
+ const act = btn.dataset.act, uid = row.dataset.uid, name = row.dataset.name, key = row.dataset.key;
1333
+ if (act === "view") { openPhoto(row.querySelector("img").src); return; }
1334
+ const mine = uid && uid === chat.uid;
1138
1335
  const db = (await getFirebase()).database();
1139
1336
  try {
1140
- if (btn.dataset.mod === "delete") {
1141
- await db.ref(`chat/messages/${row.dataset.key}`).remove();
1142
- } else if (btn.dataset.mod === "ban" && row.dataset.uid && row.dataset.uid !== chat.uid) {
1143
- if (!confirm("Ban this person from chat? They'll still be able to read.")) return;
1144
- await db.ref(`chat/banned/${row.dataset.uid}`).set(true);
1145
- chatNote("Banned. Their old messages stay until you delete them.");
1337
+ if (act === "report" && !mine) {
1338
+ await db.ref(`chat/flags/${key}/${chat.uid}`).set(true);
1339
+ chatNote(`Reported. Messages with ${HIDE_AFTER_REPORTS} reports are hidden until the owner looks at them.`);
1340
+ } else if (act === "delete" && (mine || chat.admin)) {
1341
+ await db.ref().update({ [`chat/messages/${key}`]: null, ...(chat.admin ? { [`chat/flags/${key}`]: null } : {}) });
1342
+ } else if (!chat.admin || mine) {
1343
+ return;
1344
+ } else if (act === "purge") {
1345
+ if (!confirm(`Delete every message from “${name}”? This can't be undone.`)) return;
1346
+ const n = await purgeUser(db, uid);
1347
+ chatNote(`Deleted ${n} message${n === 1 ? "" : "s"} from ${name}.`);
1348
+ } else if (act === "mute") {
1349
+ const ms = await pickMute(btn, name);
1350
+ if (!ms) return;
1351
+ await db.ref(`chat/mutes/${uid}`).set({ until: Date.now() + ms, name });
1352
+ chatNote(`${name} is muted for ${fmtWait(ms)}.`);
1353
+ } else if (act === "ban") {
1354
+ if (!confirm(`Ban “${name}” from chat? They can still read. You can unban them in Settings → Tools.`)) return;
1355
+ const alsoDelete = confirm(`Also delete everything “${name}” sent?`);
1356
+ await db.ref(`chat/banned/${uid}`).set({ name, ts: Date.now() });
1357
+ const n = alsoDelete ? await purgeUser(db, uid) : 0;
1358
+ chatNote(`Banned ${name}${alsoDelete ? ` and deleted ${n} message${n === 1 ? "" : "s"}` : ""}.`);
1146
1359
  }
1147
1360
  } catch {
1148
- chatNote("That didn't work.", true);
1361
+ chatNote("That didn't work. Try again.", true);
1149
1362
  }
1150
1363
  }
1364
+ // Every message a person sent (and the reports on them), gone in one write
1365
+ async function purgeUser(db, uid) {
1366
+ const snap = await db.ref("chat/messages").orderByChild("uid").equalTo(uid).once("value");
1367
+ const changes = {};
1368
+ snap.forEach((c) => { changes[`chat/messages/${c.key}`] = null; changes[`chat/flags/${c.key}`] = null; });
1369
+ if (Object.keys(changes).length) await db.ref().update(changes);
1370
+ return snap.numChildren();
1371
+ }
1372
+ // Small menu under the 🔇 button: how long to mute
1373
+ function pickMute(anchor, name) {
1374
+ document.querySelector(".mute-menu")?.remove();
1375
+ return new Promise((done) => {
1376
+ const menu = document.createElement("div");
1377
+ menu.className = "mute-menu";
1378
+ menu.setAttribute("role", "menu");
1379
+ menu.innerHTML = `<p>Mute ${escapeHtml(name)} for…</p>` + MUTE_CHOICES.map(([label, ms]) => `<button type="button" role="menuitem" data-ms="${ms}">${label}</button>`).join("") +
1380
+ `<button type="button" role="menuitem" data-ms="0" class="cancel">Cancel</button>`;
1381
+ document.body.appendChild(menu);
1382
+ const r = anchor.getBoundingClientRect();
1383
+ menu.style.left = `${Math.min(innerWidth - menu.offsetWidth - 8, Math.max(8, r.left - 60))}px`;
1384
+ menu.style.top = `${Math.min(innerHeight - menu.offsetHeight - 8, r.bottom + 6)}px`;
1385
+ menu.querySelector("button").focus();
1386
+ const close = (ms) => { menu.remove(); document.removeEventListener("pointerdown", outside, true); done(ms); };
1387
+ const outside = (ev) => { if (!menu.contains(ev.target)) close(0); };
1388
+ menu.addEventListener("click", (ev) => { const b = ev.target.closest("[data-ms]"); if (b) close(Number(b.dataset.ms)); });
1389
+ menu.addEventListener("keydown", (ev) => { if (ev.key === "Escape") close(0); });
1390
+ setTimeout(() => document.addEventListener("pointerdown", outside, true));
1391
+ });
1392
+ }
1393
+ // Full-size photo viewer
1394
+ function openPhoto(src) {
1395
+ const wrap = document.createElement("div");
1396
+ wrap.className = "photo-viewer";
1397
+ wrap.setAttribute("role", "dialog");
1398
+ wrap.setAttribute("aria-label", "Photo");
1399
+ wrap.innerHTML = `<img alt="Chat photo"><button class="wheel-x" type="button" aria-label="Close">✕</button>`;
1400
+ wrap.querySelector("img").src = src;
1401
+ const close = () => { wrap.remove(); document.removeEventListener("keydown", esc, true); };
1402
+ const esc = (ev) => { if (ev.key === "Escape") { ev.stopPropagation(); close(); } };
1403
+ wrap.addEventListener("click", (ev) => { if (ev.target === wrap || ev.target.closest(".wheel-x")) close(); });
1404
+ document.addEventListener("keydown", esc, true);
1405
+ document.body.appendChild(wrap);
1406
+ wrap.querySelector(".wheel-x").focus();
1407
+ }
1151
1408
 
1152
1409
  // The Tools section only exists for a browser that entered the code; everyone else never sees it
1153
1410
  async function renderAdmin() {
@@ -1159,7 +1416,86 @@
1159
1416
  $("admin-leave").hidden = !on;
1160
1417
  $("admin-tools-row").hidden = !on;
1161
1418
  $("admin-reports").hidden = !on;
1162
- if (on) watchReports(); else unwatchReports();
1419
+ $("admin-chat-tools").hidden = !on;
1420
+ if (on) { watchReports(); watchPunished(app.database()); fillChatTools(); renderReported(); }
1421
+ else unwatchReports();
1422
+ }
1423
+
1424
+ // ---------- Owner chat tools (Settings → Tools) ----------
1425
+ function fillChatTools() {
1426
+ const slow = String(Number(chat.settings.slowMode) || 0);
1427
+ $("mod-slow").value = [...$("mod-slow").options].some((o) => o.value === slow) ? slow : "0";
1428
+ $("mod-lock").checked = !!chat.settings.locked;
1429
+ if (document.activeElement !== $("mod-words")) $("mod-words").value = chat.settings.words || "";
1430
+ }
1431
+ async function saveChatSetting(field, value, okMsg) {
1432
+ try {
1433
+ await (await getFirebase()).database().ref(`chat/settings/${field}`).set(value);
1434
+ if (okMsg) $("mod-words-msg").textContent = okMsg;
1435
+ } catch {
1436
+ $("mod-words-msg").textContent = "Couldn't save. Are the new database rules published?";
1437
+ }
1438
+ }
1439
+ // Messages people reported, newest reports first, with keep / delete / delete-all buttons
1440
+ async function renderReported() {
1441
+ if (!chat.admin) return;
1442
+ const keys = Object.keys(chat.flags).filter((k) => chat.flags[k] > 0);
1443
+ $("reported-count").textContent = keys.length ? `(${keys.length})` : "";
1444
+ if (!keys.length) { $("reported-list").innerHTML = `<p class="none">Nothing reported.</p>`; return; }
1445
+ const db = (await getFirebase()).database();
1446
+ const rows = await Promise.all(keys.map(async (k) => ({ key: k, m: (await db.ref(`chat/messages/${k}`).once("value")).val() })));
1447
+ const stale = rows.filter((r) => !r.m).map((r) => r.key);
1448
+ if (stale.length) db.ref().update(Object.fromEntries(stale.map((k) => [`chat/flags/${k}`, null]))).catch(() => {}); // message already gone
1449
+ const live = rows.filter((r) => r.m);
1450
+ $("reported-list").innerHTML = !live.length ? `<p class="none">Nothing reported.</p>` : live.map(({ key, m }) => {
1451
+ const what = m.text ? escapeHtml(m.text) : m.sticker ? "[sticker]" : `<img class="report-thumb" src="${m.img}" alt="Reported photo">`;
1452
+ return `<div class="report" data-key="${escapeHtml(key)}" data-uid="${escapeHtml(m.uid || "")}" data-name="${escapeHtml(m.name)}"><span class="kind broken">🚩 ${chat.flags[key]}</span>` +
1453
+ `<div class="body"><span class="game">${escapeHtml(m.name)}</span><div class="note">${what}</div></div>` +
1454
+ `<button class="mod" type="button" data-rep="keep" title="Keep it: clear the reports">Keep</button>` +
1455
+ `<button class="mod" type="button" data-rep="delete" title="Delete this message">🗑</button>` +
1456
+ `<button class="mod" type="button" data-rep="purge" title="Delete everything this person sent">🧹</button></div>`;
1457
+ }).join("");
1458
+ }
1459
+ // Muted and banned people, with undo buttons
1460
+ let punishedWatched = false;
1461
+ function watchPunished(db) {
1462
+ if (punishedWatched) return;
1463
+ punishedWatched = true;
1464
+ const lists = { mutes: {}, banned: {} };
1465
+ const draw = () => {
1466
+ const rows = [
1467
+ ...Object.entries(lists.banned).map(([uid, v]) => ({ uid, kind: "banned", name: v?.name || "Someone", note: "Banned" })),
1468
+ ...Object.entries(lists.mutes).filter(([, v]) => v?.until > Date.now())
1469
+ .map(([uid, v]) => ({ uid, kind: "mutes", name: v.name || "Someone", note: `Muted for ${fmtWait(v.until - Date.now())} more` })),
1470
+ ];
1471
+ $("punished-list").innerHTML = !rows.length ? `<p class="none">Nobody.</p>` : rows.map((r) =>
1472
+ `<div class="report" data-uid="${escapeHtml(r.uid)}" data-kind="${r.kind}"><div class="body"><span class="game">${escapeHtml(r.name)}</span><div class="meta">${r.note}</div></div>` +
1473
+ `<button class="mod" type="button" data-undo>${r.kind === "banned" ? "Unban" : "Unmute"}</button></div>`).join("");
1474
+ };
1475
+ ["mutes", "banned"].forEach((k) => db.ref(`chat/${k}`).on("value", (s) => { lists[k] = s.val() || {}; draw(); }, () => { punishedWatched = false; }));
1476
+ }
1477
+ function bindChatTools() {
1478
+ $("mod-slow").addEventListener("change", () => saveChatSetting("slowMode", Number($("mod-slow").value)));
1479
+ $("mod-lock").addEventListener("change", () => saveChatSetting("locked", $("mod-lock").checked));
1480
+ $("mod-words-save").addEventListener("click", () => {
1481
+ const words = $("mod-words").value.split(/[\n,]+/).map((w) => w.trim()).filter(Boolean).join("\n").slice(0, 4000);
1482
+ saveChatSetting("words", words, `Saved ${words ? words.split("\n").length : 0} word${words.split("\n").length === 1 ? "" : "s"} ✓`);
1483
+ });
1484
+ $("reported-list").addEventListener("click", async (e) => {
1485
+ const b = e.target.closest("[data-rep]"), row = b?.closest(".report");
1486
+ if (!row || !chat.admin) return;
1487
+ const db = (await getFirebase()).database(), key = row.dataset.key;
1488
+ try {
1489
+ if (b.dataset.rep === "keep") await db.ref(`chat/flags/${key}`).remove();
1490
+ if (b.dataset.rep === "delete") await db.ref().update({ [`chat/messages/${key}`]: null, [`chat/flags/${key}`]: null });
1491
+ if (b.dataset.rep === "purge" && confirm(`Delete every message from “${row.dataset.name}”?`)) await purgeUser(db, row.dataset.uid);
1492
+ } catch {}
1493
+ renderReported();
1494
+ });
1495
+ $("punished-list").addEventListener("click", async (e) => {
1496
+ const row = e.target.closest("[data-undo]")?.closest(".report");
1497
+ if (row && chat.admin) try { await (await getFirebase()).database().ref(`chat/${row.dataset.kind}/${row.dataset.uid}`).remove(); } catch {}
1498
+ });
1163
1499
  }
1164
1500
 
1165
1501
  // ---------- Report a broken game / request a game ----------
@@ -1291,7 +1627,7 @@
1291
1627
  }
1292
1628
 
1293
1629
  function bindAdmin() {
1294
- $("chat-log").addEventListener("click", adminAction);
1630
+ $("chat-log").addEventListener("click", chatAction);
1295
1631
  $("admin-leave").addEventListener("click", async () => {
1296
1632
  try { await (await getFirebase()).database().ref(`chat/admins/${chat.uid}`).remove(); } catch {}
1297
1633
  chat.admin = false;
@@ -1322,13 +1658,37 @@
1322
1658
  if (!$("chat-text").value.trim()) return;
1323
1659
  }
1324
1660
  }
1325
- const n = chat.admin ? { name: ADMIN_NAME } : cleanName(rawName);
1326
- if (n.error) { chatNote(n.error, true); $("chat-name").focus(); return; }
1327
- if (!chat.admin && n.name.toLowerCase() === ADMIN_NAME.toLowerCase()) { chatNote("That name is taken.", true); return; }
1328
1661
  const m = cleanMessage($("chat-text").value);
1329
- if (m.error) { chatNote(m.error, true); return; }
1330
- const wait = 3000 - (Date.now() - chat.lastSent);
1331
- if (wait > 0) { chatNote(`Slow down. Wait ${Math.ceil(wait / 1000)}s.`, true); return; }
1662
+ if (m.error) {
1663
+ if (m.error !== "Type a message first.") chat.strikes.push(Date.now()); // 3 blocked tries in 2 minutes = short time-out
1664
+ chatNote(m.error, true);
1665
+ updateChatStatus();
1666
+ return;
1667
+ }
1668
+ if (!chat.admin && m.text.toLowerCase() === chat.lastText && Date.now() - chat.lastTextAt < 60000) { chatNote("You just sent that. No spamming.", true); return; }
1669
+ if (await postMessage({ text: m.text })) {
1670
+ chat.lastText = m.text.toLowerCase();
1671
+ chat.lastTextAt = Date.now();
1672
+ $("chat-text").value = "";
1673
+ stopTyping();
1674
+ }
1675
+ }
1676
+ // Checks shared by text, stickers and photos; returns { name } or null (after showing why)
1677
+ function chatSender() {
1678
+ const why = blockedReason();
1679
+ if (why) { chatNote(why, true); return null; }
1680
+ const n = chat.admin ? { name: ADMIN_NAME } : cleanName($("chat-name").value.trim());
1681
+ if (n.error) { chatNote(n.error, true); $("chat-name").focus(); return null; }
1682
+ if (!chat.admin && n.name.toLowerCase() === ADMIN_NAME.toLowerCase()) { chatNote("That name is taken.", true); return null; }
1683
+ const wait = slowSeconds() * 1000 - (Date.now() - chat.lastSent);
1684
+ if (wait > 0) { chatNote(`Slow down. Wait ${Math.ceil(wait / 1000)}s.`, true); return null; }
1685
+ return n;
1686
+ }
1687
+ async function postMessage(fields) {
1688
+ const app = await getFirebase();
1689
+ if (!app || !chat.uid) return false;
1690
+ const n = chatSender();
1691
+ if (!n) return false;
1332
1692
  if (!chat.admin) store.set("rug-chat-name", n.name); // never save the admin code as a remembered name
1333
1693
  const db = app.database();
1334
1694
  const key = db.ref("chat/messages").push().key;
@@ -1336,16 +1696,154 @@
1336
1696
  chat.lastSent = Date.now();
1337
1697
  try {
1338
1698
  await db.ref().update({
1339
- [`chat/messages/${key}`]: { name: n.name, text: m.text, ts: TS, uid: chat.uid, ...(chat.admin ? { admin: true } : {}) },
1699
+ [`chat/messages/${key}`]: { name: n.name, ts: TS, uid: chat.uid, ...fields, ...(chat.admin ? { admin: true } : {}) },
1340
1700
  [`chat/last/${chat.uid}`]: TS,
1701
+ ...(fields.img ? { [`chat/photoLast/${chat.uid}`]: TS } : {}),
1341
1702
  });
1342
- $("chat-text").value = "";
1343
- stopTyping();
1344
1703
  stats.bump("chatSent");
1345
1704
  chatNote("");
1705
+ return true;
1706
+ } catch {
1707
+ chatNote(blockedReason() || (fields.img ? "Photo didn't send. You can send one photo every 30 seconds." : NOT_ALLOWED), true);
1708
+ return false;
1709
+ }
1710
+ }
1711
+
1712
+ // ---------- Emoji picker and stickers ----------
1713
+ // Stickers are Google's Noto animated emoji (CC BY 4.0), sent by code so only these can ever appear.
1714
+ // Grouped into tabs in the picker; every code here was checked to exist on Google's server
1715
+ const STICKER_GROUPS = [
1716
+ ["😂", ["1f602", "1f923", "1f62d", "1f480", "1f973", "1f921", "1f60e", "1f92f", "1f97a", "1f911", "1f644", "1f60d", "1f622", "1f624", "1f976", "1f975", "1f60b", "1f634", "1f47b", "1f600", "1f601", "1f604", "1f605", "1f606", "1f609", "1f60a", "1f607", "1f970", "1f618", "1f61c", "1f92a", "1f92d", "1f92b", "1f914", "1f928", "1f610", "1f611", "1f636", "1f60f", "1f612", "1f62c", "1f925", "1f60c", "1f614", "1f62a", "1f924", "1f637", "1f912", "1f915", "1f922", "1f927", "1f635", "1f920", "1f913", "1f9d0", "1f615", "1f61f", "1f641", "1f62e", "1f62f", "1f632", "1f633", "1f628", "1f630", "1f625", "1f631", "1f616", "1f623", "1f61e", "1f613", "1f629", "1f62b", "1f971", "1f620", "1f621", "1f92c", "1f608", "1f47f", "1f4a9", "1f47d", "1f916", "1f63a", "1f638", "1f639", "1f63b", "1f63f", "1f640", "1f648", "1f649", "1f64a"]],
1717
+ ["👍", ["1f44d", "1f44f", "1f64f", "1f4aa", "1f918", "2764_fe0f", "1f9e0", "1f440", "1f48b", "1f498", "1f494", "1f4a5", "1f4ab", "1f44b", "1f44c", "1f90c", "270c_fe0f", "1f91e", "1f91f", "1f919", "1f44a", "1f91b", "1f64c", "1f450", "1f932", "1f91d", "1f485", "1f933", "1f441_fe0f", "1f483"]],
1718
+ ["🐶", ["1f40d", "1f431", "1f98a", "1f43b", "1f43c", "1f981", "1f42e", "1f438", "1f427", "1f426", "1f985", "1f989", "1f987", "1f43a", "1f984", "1f41d", "1f98b", "1f40c", "1f41e", "1f422", "1f996", "1f995", "1f419", "1f988", "1f42c", "1f433", "1f40a", "1f998", "1f415", "1f413", "1f9a9", "1f407", "1f43f_fe0f", "1f994"]],
1719
+ ["🌈", ["1f340", "1f335", "1f339", "1f337", "1f308", "26a1", "2744_fe0f", "2603_fe0f", "1f30a", "1f30b", "1f30d", "2b50", "2604_fe0f", "1f30c"]],
1720
+ ["🍕", ["1f34e", "1f349", "1f353", "1f951", "1f33d", "1f37f", "1f354", "1f355", "1f32d", "1f32e", "1f942", "1f37e", "1f379", "2615", "1f382", "1f369", "1f36a"]],
1721
+ ["🏆", ["1f3c6", "1f389", "26bd", "1f3c0", "26be", "1f3be", "1f3b3", "1f3af", "1f3b2", "1f3b8", "1f3b7", "1f941", "1f3ac", "1f388", "1f381", "1f38a", "1f386", "1f383", "1f947", "1f3c1"]],
1722
+ ["🚀", ["1f680", "1f525", "1f4af", "1f31f", "1f697", "1f6b2", "1f6f8", "2708_fe0f", "1f6a8", "1f4bb", "1f4f8", "1f48e", "1f514", "1f4a1", "1f50b", "23f0", "231b", "2705", "274c", "2757", "2753", "1f198", "1f4ac", "1f5ff", "1f47e"]],
1723
+ ];
1724
+ const STICKERS = STICKER_GROUPS.flatMap(([, list]) => list);
1725
+ const EMOJI_GROUPS = [
1726
+ ["😀", "😀😃😄😁😆😅😂🤣🥲😊😇🙂🙃😉😌😍🥰😘😋😛😜🤪😝🤑🤗🤭🤫🤔🤐🤨😐😑😶😏😒🙄😬😮‍💨🤥😴🤤😪😮😯😲🥱😳🥺😢😭😤😠😡🤯😱😨😰🥶🥵😵‍💫🤠🥳😎🤓🧐😈👻💀☠️🤡💩🤖👽"],
1727
+ ["👍", "👍👎👏🙌👐🤝🙏✌️🤞🤟🤘👌🤌🤏👈👉👆👇☝️✋🤚🖐️👋🤙💪🫡🫶"],
1728
+ ["❤️", "❤️🧡💛💚💙💜🖤🤍🤎💔❣️💕💞💓💗💖💘💝💯💢💥💫💦💨🔥✨⭐🌟⚡"],
1729
+ ["🎮", "🎮🕹️🏆🥇🥈🥉🎯🎲🧩♟️⚽🏀🏈⚾🎾🏐🏉🎱🏓🏒⛳🛹🏁🚗🏎️🚀✈️👾"],
1730
+ ["🍕", "🍕🍔🍟🌭🌮🌯🍿🍩🍪🎂🍰🧁🍫🍬🍭🍦🍉🍓🍌🍎🥤🧃☕🧋"],
1731
+ ["🐶", "🐶🐱🐭🐹🐰🦊🐻🐼🐨🐯🦁🐮🐷🐸🐵🙈🙉🙊🐔🐧🐦🐤🦆🦅🦉🐺🐗🐴🦄🐝🐛🦋🐌🐞🐢🐍🦖🐙🦈🐬🐳"],
1732
+ ];
1733
+ function buildPicker() {
1734
+ const seg = (s) => [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(s)].map((x) => x.segment);
1735
+ $("picker-tabs").innerHTML = EMOJI_GROUPS.map(([icon], i) => `<button type="button" role="tab" data-tab="${i}" aria-selected="${i === 0}" title="Emoji">${icon}</button>`).join("") +
1736
+ `<button type="button" role="tab" data-tab="stickers" aria-selected="false" class="tab-stickers">Stickers</button>`;
1737
+ const showTab = (tab) => {
1738
+ $("picker-tabs").querySelectorAll("[data-tab]").forEach((b) => b.setAttribute("aria-selected", b.dataset.tab === String(tab)));
1739
+ $("picker-grid").className = "picker-grid" + (tab === "stickers" ? " stickers" : "");
1740
+ $("picker-grid").innerHTML = tab === "stickers"
1741
+ ? STICKER_GROUPS.map(([icon, list]) => `<p class="picker-head">${icon}</p>` +
1742
+ list.map((c) => `<button type="button" data-sticker="${c}" title="Send sticker"><img src="${STICKER_URL(c)}" alt="" width="56" height="56" loading="lazy"></button>`).join("")).join("")
1743
+ : seg(EMOJI_GROUPS[tab][1]).map((e) => `<button type="button" data-emoji="${e}">${e}</button>`).join("");
1744
+ };
1745
+ showTab(0);
1746
+ $("picker-tabs").addEventListener("click", (e) => { const b = e.target.closest("[data-tab]"); if (b) showTab(/^\d+$/.test(b.dataset.tab) ? Number(b.dataset.tab) : b.dataset.tab); });
1747
+ $("picker-grid").addEventListener("click", async (e) => {
1748
+ const em = e.target.closest("[data-emoji]"), st = e.target.closest("[data-sticker]");
1749
+ if (em) insertAtCursor($("chat-text"), em.dataset.emoji);
1750
+ if (st && await postMessage({ sticker: st.dataset.sticker })) togglePicker(false);
1751
+ });
1752
+ }
1753
+ function insertAtCursor(input, text) {
1754
+ const s = input.selectionStart ?? input.value.length, e = input.selectionEnd ?? s;
1755
+ if (input.value.length + text.length > input.maxLength) return;
1756
+ input.value = input.value.slice(0, s) + text + input.value.slice(e);
1757
+ input.selectionStart = input.selectionEnd = s + text.length;
1758
+ input.focus();
1759
+ }
1760
+ function togglePicker(open = $("picker").hidden) {
1761
+ if (open && !$("picker-grid").children.length) buildPicker();
1762
+ $("picker").hidden = !open;
1763
+ $("emoji-btn").setAttribute("aria-expanded", open);
1764
+ }
1765
+
1766
+ // ---------- Photos: drag and drop, paste, or 📷 ----------
1767
+ // Posted straight away (no review). Before sending, a nudity detector (NSFW.js, runs in this browser)
1768
+ // checks the picture; the photo is re-drawn, which also strips hidden data like location, and shrunk to ≤ ~100 KB.
1769
+ let nsfwModel = null;
1770
+ function loadNsfw() {
1771
+ if (!nsfwModel) {
1772
+ nsfwModel = (async () => {
1773
+ await loadScript("https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.22.0/dist/tf.min.js");
1774
+ await loadScript("https://cdn.jsdelivr.net/npm/nsfwjs@4.2.1/dist/browser/nsfwjs.min.js");
1775
+ return window.nsfwjs.load("https://cdn.jsdelivr.net/gh/infinitered/nsfwjs@v4.2.1/models/mobilenet_v2/model.json", { size: 224 });
1776
+ })().catch((err) => { nsfwModel = null; throw err; });
1777
+ }
1778
+ return nsfwModel;
1779
+ }
1780
+ async function sendPhoto(file) {
1781
+ if (!file || !/^image\//.test(file.type)) { chatNote("That isn't a picture.", true); return; }
1782
+ if (file.size > 20 * 1048576) { chatNote("That picture is too big (20 MB max).", true); return; }
1783
+ if (!chatSender()) return; // banned, muted, locked, no nickname, too fast: say so before the slow part
1784
+ chatNote("Checking photo…");
1785
+ $("photo-btn").disabled = true;
1786
+ try {
1787
+ const bmp = await createImageBitmap(file);
1788
+ let verdict;
1789
+ try {
1790
+ const model = await loadNsfw();
1791
+ const c = document.createElement("canvas");
1792
+ c.width = c.height = 224;
1793
+ c.getContext("2d").drawImage(bmp, 0, 0, 224, 224);
1794
+ verdict = Object.fromEntries((await model.classify(c)).map((p) => [p.className, p.probability]));
1795
+ } catch {
1796
+ chatNote("Couldn't check that photo, so it wasn't sent. Try again in a moment.", true);
1797
+ return;
1798
+ }
1799
+ if ((verdict.Porn || 0) > 0.35 || (verdict.Hentai || 0) > 0.35 || (verdict.Sexy || 0) > 0.6) {
1800
+ chat.strikes.push(Date.now());
1801
+ chatNote(NOT_ALLOWED, true);
1802
+ updateChatStatus();
1803
+ return;
1804
+ }
1805
+ const img = await shrinkPhoto(bmp);
1806
+ if (await postMessage({ img })) chatNote("");
1346
1807
  } catch {
1347
- chatNote("Message blocked (filtered word, or sending too fast).", true);
1808
+ chatNote("Couldn't read that picture.", true);
1809
+ } finally {
1810
+ $("photo-btn").disabled = !!blockedReason();
1811
+ $("photo-input").value = "";
1812
+ }
1813
+ }
1814
+ async function shrinkPhoto(bmp) {
1815
+ for (const [side, q] of [[720, 0.72], [600, 0.62], [480, 0.55], [360, 0.5]]) {
1816
+ const k = Math.min(1, side / Math.max(bmp.width, bmp.height));
1817
+ const c = document.createElement("canvas");
1818
+ c.width = Math.round(bmp.width * k); c.height = Math.round(bmp.height * k);
1819
+ c.getContext("2d").drawImage(bmp, 0, 0, c.width, c.height);
1820
+ let url = c.toDataURL("image/webp", q);
1821
+ if (!url.startsWith("data:image/webp")) url = c.toDataURL("image/jpeg", q); // Safari: no WebP encoder
1822
+ if (url.length <= 140000) return url;
1348
1823
  }
1824
+ throw new Error("too big");
1825
+ }
1826
+ function bindChatExtras() {
1827
+ $("emoji-btn").addEventListener("click", () => togglePicker());
1828
+ document.addEventListener("pointerdown", (e) => {
1829
+ if (!$("picker").hidden && !e.target.closest("#picker, #emoji-btn")) togglePicker(false);
1830
+ });
1831
+ $("picker").addEventListener("keydown", (e) => { if (e.key === "Escape") { togglePicker(false); $("emoji-btn").focus(); } });
1832
+ $("photo-btn").addEventListener("click", () => $("photo-input").click());
1833
+ $("photo-input").addEventListener("change", () => sendPhoto($("photo-input").files[0]));
1834
+ const box = $("chat-box");
1835
+ let depth = 0;
1836
+ box.addEventListener("dragenter", (e) => { if ([...e.dataTransfer.types].includes("Files")) { e.preventDefault(); depth++; box.classList.add("dropping"); } });
1837
+ box.addEventListener("dragover", (e) => { if ([...e.dataTransfer.types].includes("Files")) e.preventDefault(); });
1838
+ box.addEventListener("dragleave", () => { if (--depth <= 0) { depth = 0; box.classList.remove("dropping"); } });
1839
+ box.addEventListener("drop", (e) => {
1840
+ e.preventDefault(); depth = 0; box.classList.remove("dropping");
1841
+ sendPhoto([...e.dataTransfer.files].find((f) => f.type.startsWith("image/")));
1842
+ });
1843
+ $("chat-text").addEventListener("paste", (e) => {
1844
+ const f = [...(e.clipboardData?.files || [])].find((x) => x.type.startsWith("image/"));
1845
+ if (f) { e.preventDefault(); sendPhoto(f); }
1846
+ });
1349
1847
  }
1350
1848
 
1351
1849
  // ---------- Chat beside a game, and the unread dot ----------
@@ -1665,11 +2163,14 @@
1665
2163
  bindSettings();
1666
2164
  bindWheel();
1667
2165
  bindWordmark();
2166
+ initChangelog();
1668
2167
  $("chat-form").addEventListener("submit", sendChat);
1669
2168
  $("chat-text").addEventListener("input", noteTyping);
1670
2169
  $("chat-text").addEventListener("blur", stopTyping);
1671
2170
  $("chat-log").addEventListener("click", mentionFromName);
1672
2171
  bindAdmin();
2172
+ bindChatTools();
2173
+ bindChatExtras();
1673
2174
  bindReports();
1674
2175
  startAnalytics();
1675
2176
  startPresence();
@@ -1685,6 +2186,7 @@
1685
2186
  const data = await res.json();
1686
2187
  games = data.games.slice().sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
1687
2188
  byId = new Map(games.map((g) => [g.id, g]));
2189
+ cdnPins = data.cdnPins || {};
1688
2190
  } catch (err) {
1689
2191
  console.error(err);
1690
2192
  els.homeSub.textContent = "Couldn't load the game list. Try refreshing.";