@ywkrlerche/richardwho 1.0.43 → 1.0.45

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
@@ -293,63 +293,182 @@
293
293
  return `<svg class="web ${flip ? "right" : "left"}" viewBox="0 0 270 270"><path d="${d}"/></svg>`;
294
294
  }
295
295
  // ---------- Themes (Settings → Theme): Holiday (the theme follows the calendar, Black between holidays), Black or White ----------
296
- // The holiday dates live in index.html's head script (window.rugHoliday) so the right look shows before this file loads.
297
- // The smaller holidays share one look (.fest): their colors live in style.css, the falling things and props here.
296
+ // The holiday dates live in index.html's head script (window.rugHoliday / rugHolidayDay) so the right look shows
297
+ // before this file loads. Halloween and Christmas have their own scenery; the rest share one look (.fest): colors
298
+ // in style.css, and here the falling things, ground props, a drawn scene, bunting and fireworks.
299
+ const seeded = (seed) => () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296); // repeatable "random" for drawings
300
+ const HILLS = `<path class="s-hill" d="M0 200C200 170 420 190 640 180S1100 165 1300 182 1520 186 1600 176V240H0Z"/>`;
301
+ // Scenes are drawn in a 1600 x 240 box whose bottom edge is the bottom of the page
302
+ const SCENES = {
303
+ skyline() {
304
+ const r = seeded(7);
305
+ let x = 0, towers = "", windows = "";
306
+ while (x < 1600) {
307
+ const w = 44 + r() * 60, h = 50 + r() * 120, y = 240 - h;
308
+ towers += `<rect x="${x.toFixed(0)}" y="${y.toFixed(0)}" width="${(w + 1).toFixed(0)}" height="${h.toFixed(0)}"/>`;
309
+ for (let wy = y + 10; wy < 226; wy += 16) for (let wx = x + 8; wx < x + w - 10; wx += 14) if (r() < .3) windows += `<rect x="${wx.toFixed(0)}" y="${wy.toFixed(0)}" width="6" height="8"/>`;
310
+ x += w;
311
+ }
312
+ return `<g class="s-dark">${towers}</g><g class="s-win">${windows}</g>`;
313
+ },
314
+ hearts() {
315
+ const heart = (x, y, s, c, delay) => `<g transform="translate(${x} ${y}) scale(${s})"><g class="s-float" style="animation-delay:${delay}s">` +
316
+ `<path d="M0 32q7 34-3 78" stroke="rgba(255,255,255,.28)" fill="none" stroke-width="1.2"/><path d="M0 9C-12-8-32 4 0 32 32 4 12-8 0 9Z" fill="${c}"/></g></g>`;
317
+ return HILLS + heart(560, 70, 1.5, "#fb7185", 0) + heart(690, 96, 1.1, "#f472b6", -1.2) + heart(1010, 60, 1.7, "#e11d48", -2.1) +
318
+ heart(1130, 104, 1, "#fda4af", -.6) + heart(1400, 80, 1.3, "#f472b6", -1.7);
319
+ },
320
+ rainbow() {
321
+ const bands = ["#ef4444", "#f97316", "#facc15", "#22c55e", "#3b82f6", "#8b5cf6"];
322
+ return `<g fill="none" stroke-width="11" opacity=".5">${bands.map((c, i) => `<circle cx="1120" cy="262" r="${236 - i * 11}" stroke="${c}"/>`).join("")}</g>` +
323
+ `<path fill="#0f3320" d="M0 190C260 150 520 196 800 178S1300 150 1600 184V240H0Z"/>` + HILLS;
324
+ },
325
+ eggs() {
326
+ const egg = (x, y, c1, c2, tilt) => `<g transform="translate(${x} ${y}) rotate(${tilt})"><ellipse rx="15" ry="20" fill="${c1}"/>` +
327
+ `<path d="M-14-4q7-7 14 0t14 0" stroke="${c2}" stroke-width="4" fill="none"/><path d="M-13 8q6.5 6 13 0t13 0" stroke="${c2}" stroke-width="3" fill="none"/></g>`;
328
+ return `<circle cx="1380" cy="64" r="58" fill="#fde68a" opacity=".12"/><circle cx="1380" cy="64" r="34" fill="#fde68a" opacity=".85"/>` +
329
+ `<path fill="#1d3a2a" d="M0 186C240 150 470 190 760 170S1280 146 1600 178V240H0Z"/><path fill="#234732" d="M0 206C200 184 420 204 640 196S1100 182 1300 198 1520 200 1600 192V240H0Z"/>` +
330
+ egg(540, 196, "#c4b5fd", "#f9a8d4", -8) + egg(620, 204, "#86efac", "#fde68a", 10) + egg(860, 194, "#f9a8d4", "#c4b5fd", 4) +
331
+ egg(1020, 200, "#fde68a", "#86efac", -12) + egg(1200, 192, "#93c5fd", "#f9a8d4", 8);
332
+ },
333
+ harvest() {
334
+ const tree = (x, s) => `<g transform="translate(${x} 0) scale(${s} 1)"><path d="M0 204V120M0 140l-50-40M0 125l45-45M-30 116l-26 4M25 96l24-6M0 160l40-12" stroke-width="9" stroke-linecap="round" fill="none"/></g>`;
335
+ const pumpkin = (x, y, r) => `<g transform="translate(${x} ${y})"><path d="M0 ${-r}v-9" stroke="#3f6212" stroke-width="5" stroke-linecap="round"/>` +
336
+ `<ellipse rx="${r * 1.15}" ry="${r}" fill="#ea580c"/><ellipse rx="${r * .5}" ry="${r}" fill="#f97316"/></g>`;
337
+ return `<circle cx="1080" cy="214" r="96" fill="#f59e0b" opacity=".16"/><circle cx="1080" cy="214" r="62" fill="#f59e0b" opacity=".2"/>` + HILLS +
338
+ `<g class="s-dark">${tree(520, 1)}${tree(1460, -1.1)}</g>` +
339
+ `<rect x="850" y="176" width="64" height="30" rx="5" fill="#b8892f"/><path d="M866 176v30M882 176v30M898 176v30" stroke="#8a6420" stroke-width="2"/>` +
340
+ pumpkin(700, 196, 17) + pumpkin(746, 202, 12) + pumpkin(990, 198, 15);
341
+ },
342
+ football() {
343
+ const lines = Array.from({ length: 9 }, (_, i) => `<path d="M${180 + i * 155} 240L${420 + i * 95} 168"/>`).join("");
344
+ const light = (x) => `<path d="M${x} 240V52" stroke="#1f2937" stroke-width="7"/><rect x="${x - 34}" y="30" width="68" height="26" rx="4" fill="#111827"/>` +
345
+ Array.from({ length: 4 }, (_, i) => `<circle cx="${x - 24 + i * 16}" cy="43" r="5" fill="#fef9c3"/>`).join("") + `<circle cx="${x}" cy="43" r="60" fill="#fef9c3" opacity=".07"/>`;
346
+ return light(140) + light(1470) + `<path fill="#14532d" d="M0 240L330 168H1270L1600 240Z"/><g stroke="rgba(255,255,255,.35)" stroke-width="2">${lines}</g>` +
347
+ `<path d="M1180 172V112M1136 112H1224M1136 112V52M1224 112V52" stroke="#facc15" stroke-width="6" stroke-linecap="round" fill="none"/>`;
348
+ },
349
+ beach() {
350
+ const palm = (x, s) => `<g transform="translate(${x} 0) scale(${s} 1)" class="s-dark"><path d="M0 214C6 170 2 130 18 92" stroke-width="10" stroke-linecap="round" fill="none"/>` +
351
+ `<path stroke="none" d="M18 92C-8 72-40 78-58 98-34 90-10 92 18 92ZM18 92C2 62-22 50-48 54-24 62-4 74 18 92ZM18 92C22 60 44 44 70 46 48 56 30 72 18 92ZM18 92C44 76 76 80 92 102 68 92 44 92 18 92ZM18 92C40 96 58 112 62 134 48 116 34 104 18 92Z"/></g>`;
352
+ return `<circle cx="1160" cy="176" r="74" fill="#fbbf24" opacity=".9"/><circle cx="1160" cy="176" r="110" fill="#fbbf24" opacity=".12"/>` +
353
+ `<path fill="#0e3a5c" d="M0 178q40-10 80 0t80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0 80 0V240H0Z"/>` +
354
+ `<path fill="#0b2c47" d="M0 200q50-9 100 0t100 0 100 0 100 0 100 0 100 0 100 0 100 0 100 0 100 0 100 0 100 0 100 0 100 0 100 0 100 0V240H0Z"/>` +
355
+ `<path fill="#3a2f1c" d="M0 214C140 196 300 204 470 226L520 240H0ZM1600 208C1480 196 1340 206 1220 232L1190 240H1600Z"/>` + palm(250, 1) + palm(1440, -1.15);
356
+ },
357
+ school() {
358
+ const windows = [690, 740, 860, 910].map((x) => `<rect x="${x}" y="150" width="26" height="30" rx="2"/>`).join("");
359
+ return HILLS + `<g class="s-dark"><rect x="660" y="128" width="300" height="80"/><path d="M640 130L810 76 980 130Z"/><rect x="786" y="44" width="48" height="50"/><path d="M776 46L810 22 844 46Z"/><path d="M1010 208V96" stroke-width="4"/></g>` +
360
+ `<g class="s-win">${windows}<circle cx="810" cy="66" r="9"/></g><rect x="792" y="160" width="36" height="48" rx="3" fill="#7c2d12"/><path d="M1012 98h44l-10 12 10 12h-44Z" fill="#f87171"/>` +
361
+ `<g transform="translate(1150 150)"><rect width="190" height="54" rx="10" fill="#facc15"/><rect x="150" y="10" width="32" height="22" rx="3" fill="#1e293b"/>` +
362
+ [14, 46, 78, 110].map((x) => `<rect x="${x}" y="10" width="24" height="20" rx="3" fill="#1e293b"/>`).join("") +
363
+ `<rect y="36" width="190" height="5" fill="#111827"/><circle cx="42" cy="56" r="13" fill="#111827"/><circle cx="148" cy="56" r="13" fill="#111827"/><circle cx="42" cy="56" r="5" fill="#9ca3af"/><circle cx="148" cy="56" r="5" fill="#9ca3af"/></g>`;
364
+ },
365
+ };
366
+ // items: what falls (up: floats upward instead). ground: emoji along the bottom. flags: bunting colors.
367
+ // fw: firework colors; they go off all holiday with fwAlways, otherwise only on the day itself.
368
+ const RWB = ["#ef4444", "#f8fafc", "#3b82f6"];
298
369
  const FESTS = {
299
- newyear: { color: "#0a0d1f", items: ["✨", "🎉", "🎊", "⭐"], ground: ["🥂", "🎆", "🍾", "🎇"], count: 70 },
300
- valentines: { color: "#1f0a14", items: ["💖", "💕", "❤️", "💗"], ground: ["🌹", "💝", "🧸", "💌"], count: 65 },
301
- stpatricks: { color: "#06170d", items: ["☘️", "🍀", "🪙"], ground: ["🌈", "💰", "🍀", "🎩"], count: 65 },
302
- easter: { color: "#160f24", items: ["🌸", "🌷", "🦋"], ground: ["🐣", "🧺", "🐰", "🥚"], count: 60 },
303
- july4: { color: "#070b1f", items: ["⭐", "✨", "🎆"], ground: ["🗽", "🎆", "🌭", "🎇"], count: 65 },
304
- thanksgiving: { color: "#1a0f06", items: ["🍂", "🍁", "🍃"], ground: ["🦃", "🥧", "🌽", "🍂"], count: 65 },
370
+ newyear: { color: "#0a0d1f", items: ["✨", "🎉", "🎊", "⭐"], ground: ["🥂", "🎆", "🍾", "🎇"], count: 60, scene: SCENES.skyline, flags: ["#facc15", "#f8fafc", "#818cf8"], fw: ["#facc15", "#f8fafc", "#818cf8", "#f472b6"], fwAlways: true },
371
+ valentines: { color: "#1f0a14", items: ["💖", "💕", "❤️", "💗"], ground: ["🌹", "💝", "🧸", "💌"], count: 65, scene: SCENES.hearts, flags: ["#f472b6", "#fb7185", "#ffe4ef"] },
372
+ stpatricks: { color: "#06170d", items: ["☘️", "🍀", "🪙"], ground: ["💰", "🎩", "🍀", "🪙"], count: 65, scene: SCENES.rainbow, flags: ["#22c55e", "#facc15", "#f8fafc"] },
373
+ easter: { color: "#160f24", items: ["🌸", "🌷", "🦋"], ground: ["🐰", "🧺", "🐣", "🌷"], count: 60, scene: SCENES.eggs, flags: ["#c4b5fd", "#f9a8d4", "#86efac", "#fde68a"] },
374
+ july4: { color: "#070b1f", items: ["⭐", "✨"], ground: ["🗽", "🌭", "🧨", "🎇"], count: 45, scene: SCENES.skyline, flags: RWB, fw: RWB, fwAlways: true },
375
+ thanksgiving: { color: "#1a0f06", items: ["🍂", "🍁", "🍃"], ground: ["🦃", "🥧", "🌽", "🍎"], count: 65, scene: SCENES.harvest },
376
+ superbowl: { color: "#07140c", items: ["🏈", "⭐", "🎉"], ground: ["🏆", "🏈", "🍕", "📣"], count: 45, scene: SCENES.football, flags: ["#fbbf24", "#f8fafc", "#4ade80"], fw: ["#fbbf24", "#f8fafc", "#4ade80"] },
377
+ aprilfools: { color: "#14101f", items: ["🤡", "🃏", "🙃", "🎈"], ground: ["🎩", "🐇", "🎪", "🃏"], count: 45, up: true, flags: ["#ef4444", "#facc15", "#22c55e", "#3b82f6", "#a78bfa"] },
378
+ summer: { color: "#0b1a2b", items: ["🫧", "✨"], ground: ["🏖️", "🍉", "🏄", "🍦"], count: 34, up: true, scene: SCENES.beach },
379
+ backtoschool: { color: "#101426", items: ["✏️", "📚", "🍎", "📐"], ground: ["🎒", "📓", "🍎", "🖍️"], count: 40, scene: SCENES.school, flags: ["#facc15", "#f87171", "#60a5fa"] },
305
380
  };
306
381
  const HOLIDAYS = ["halloween", "christmas", ...Object.keys(FESTS)];
307
382
  const SPOOKY_FALL = { items: ["🍂", "🍁", "🍬", "🦇"], count: 50 };
383
+ // [emoji, "N days until …", greeting on the day]; seasons without one big day just get a note
384
+ const HOLIDAY_DAYS = {
385
+ newyear: ["🎉", "New Year's Day", ""], valentines: ["💘", "Valentine's Day", "Happy Valentine's Day!"],
386
+ stpatricks: ["☘️", "St. Patrick's Day", "Happy St. Patrick's Day!"], easter: ["🐣", "Easter", "Happy Easter!"],
387
+ july4: ["🎆", "the Fourth of July", "Happy Fourth of July!"], halloween: ["🎃", "Halloween", "Happy Halloween!"],
388
+ thanksgiving: ["🦃", "Thanksgiving", "Happy Thanksgiving!"], christmas: ["🎄", "Christmas", "Merry Christmas!"],
389
+ superbowl: ["🏈", "the Super Bowl", "It's Super Bowl Sunday!"], aprilfools: ["🤡", "April Fools' Day", "Happy April Fools' Day! Nothing is broken. Probably."],
390
+ };
391
+ const SEASON_NOTES = { summer: "☀️ Summer break. Enjoy it!", backtoschool: "✏️ Welcome back to school!" };
308
392
  const THEMES = ["auto", "black", "white"];
309
393
  function resolveTheme(t) {
310
394
  return t === "black" || t === "white" ? t : (window.rugHoliday && window.rugHoliday()) || "black";
311
395
  }
312
- let shownTheme = null;
396
+ // days until this theme's big day (0 = today, negative = it has passed, null = it has none)
397
+ function daysToHoliday(t) {
398
+ const day = HOLIDAY_DAYS[t] && window.rugHolidayDay && window.rugHolidayDay(t);
399
+ if (!day) return null;
400
+ const n = new Date();
401
+ return Math.round((day - new Date(n.getFullYear(), n.getMonth(), n.getDate()).getTime()) / 864e5);
402
+ }
403
+ const themeKey = (t) => `${t}:${daysToHoliday(t)}`;
404
+ let shownTheme = null, shownKey = "";
313
405
  function applySiteTheme(choice) {
314
406
  const t = resolveTheme(choice);
315
407
  shownTheme = t;
408
+ shownKey = themeKey(t);
316
409
  const root = document.documentElement;
317
410
  root.dataset.theme = t === "white" ? "light" : "dark";
318
411
  for (const h of HOLIDAYS) root.classList.toggle(h, t === h);
319
412
  root.classList.toggle("fest", !!FESTS[t]);
413
+ root.classList.toggle("holiday", HOLIDAYS.includes(t)); // shared touches on every page (style.css)
320
414
  $("theme-color").content = { white: "#f6f6f8", halloween: "#110820", christmas: "#0b1424" }[t] || FESTS[t]?.color || "#000000";
321
415
  if (t === "halloween" && !document.querySelector(".spooky")) buildHalloween(); // scenery is only drawn once it's needed
322
416
  if (t === "christmas" && !document.querySelector(".xmas")) buildChristmas();
323
417
  if (FESTS[t]) buildFest(t);
324
418
  fallers.set(t);
419
+ renderHolidayBanner();
420
+ }
421
+ // Under the home page search: "12 days until Christmas", a greeting on the day, a countdown on New Year's Eve
422
+ function renderHolidayBanner() {
423
+ const t = shownTheme, info = HOLIDAY_DAYS[t], left = daysToHoliday(t);
424
+ let text = SEASON_NOTES[t] || "";
425
+ if (info && left === 0) text = t === "newyear" ? `🎉 Happy New Year ${new Date().getFullYear()}!` : `${info[0]} ${info[2]}`;
426
+ else if (info && left === 1 && t === "newyear") {
427
+ const ms = window.rugHolidayDay(t) - Date.now(), h = Math.floor(ms / 3600e3), m = Math.ceil((ms % 3600e3) / 60e3);
428
+ text = `🎉 New Year in ${h ? `${h}h ` : ""}${m}m`;
429
+ } else if (info && left > 0) text = `${info[0]} ${left} day${left === 1 ? "" : "s"} until ${info[1]}`;
430
+ $("holiday-banner").textContent = text;
431
+ $("holiday-banner").hidden = !text;
432
+ }
433
+ // a tab left open still switches when a holiday starts or ends or its big day arrives, and the countdown keeps up
434
+ setInterval(() => { if (themeKey(resolveTheme(settings.theme)) !== shownKey) applySiteTheme(settings.theme); else renderHolidayBanner(); }, 60e3);
435
+ function bunting(colors) {
436
+ const n = 30;
437
+ return `<div class="bunting"><svg viewBox="0 0 100 10" preserveAspectRatio="none"><path d="M0 2Q8 9 16 3T32 3 48 3 64 3 80 3 100 3"/></svg>` +
438
+ Array.from({ length: n }, (_, i) => `<i style="left:${(i + .5) * (100 / n)}%;top:${9 + Math.sin(i * 1.3) * 5}px;--c:${colors[i % colors.length]};animation-delay:${(i % 6) * -.5}s"></i>`).join("") + `</div>`;
325
439
  }
326
- // a tab left open overnight still switches when a holiday starts or ends
327
- setInterval(() => { if (resolveTheme(settings.theme) !== shownTheme) applySiteTheme(settings.theme); }, 10 * 60e3);
328
440
  function buildFest(t) {
329
441
  const old = document.querySelector(".festive");
330
442
  if (old?.dataset.fest === t) return;
331
443
  old?.remove();
444
+ const f = FESTS[t];
332
445
  const spots = ["right:4vw", "right:calc(4vw + 78px)", "right:calc(4vw + 150px)", "right:calc(4vw + 206px)"];
333
446
  $("view-home").insertAdjacentHTML("afterbegin", `<div class="festive" data-fest="${t}" aria-hidden="true">
334
- <svg class="festive-hills" viewBox="0 0 1600 240" preserveAspectRatio="xMidYMax slice"><path d="M0 200C200 170 420 190 640 180S1100 165 1300 182 1520 186 1600 176V240H0Z"/></svg>
335
- ${FESTS[t].ground.map((e, i) => `<span class="festive-prop" style="${spots[i]};--s:${i % 2 ? 40 : 54}px;animation-delay:${i * -1.3}s">${e}</span>`).join("")}
447
+ ${f.flags ? bunting(f.flags) : ""}
448
+ <svg class="festive-scene" viewBox="0 0 1600 240" preserveAspectRatio="xMidYMax slice">${f.scene ? f.scene() : HILLS}</svg>
449
+ ${f.ground.map((e, i) => `<span class="festive-prop" style="${spots[i]};--s:${i % 2 ? 40 : 54}px;animation-delay:${i * -1.3}s">${e}</span>`).join("")}
336
450
  </div>`);
337
451
  }
338
452
 
339
- // Falling snow (Christmas) or hearts, leaves, clovers… (the other holidays) on the home page.
340
- // The pointer pushes them aside; clicking empty space (or the snowman) bursts out more.
453
+ // Falling snow (Christmas) or hearts, leaves, clovers… (the other holidays) on the home page, plus fireworks.
454
+ // The pointer pushes them aside; clicking empty space bursts out more (and sets off a firework when there are any).
341
455
  const fallers = {
342
456
  canvas: null, ctx: null, list: [], kind: null, items: [], sprites: {}, target: 0, raf: 0, last: 0, measured: 0,
343
- w: 0, h: 0, ox: 0, oy: 0, px: -1e4, py: -1e4,
457
+ w: 0, h: 0, ox: 0, oy: 0, px: -1e4, py: -1e4, dir: 1, fw: null, fwRate: 0, sparks: [], cost: 0, skip: false,
344
458
  still: matchMedia("(prefers-reduced-motion: reduce)").matches,
345
459
  set(theme) {
346
460
  const fall = theme === "halloween" ? SPOOKY_FALL : FESTS[theme];
347
461
  this.kind = theme === "christmas" ? "snow" : fall ? "emoji" : null;
348
462
  if (!this.kind) { cancelAnimationFrame(this.raf); this.raf = 0; if (this.canvas) this.canvas.hidden = true; return; }
349
463
  if (!this.canvas) this.init();
464
+ const big = daysToHoliday(theme) === 0; // the day itself: more of everything
350
465
  this.items = fall?.items || [];
466
+ this.dir = fall?.up ? -1 : 1;
467
+ this.fw = fall?.fw && (fall.fwAlways || big) ? fall.fw : null;
468
+ this.fwRate = big ? 1.1 : .3; // fireworks a second
469
+ this.sparks = [];
351
470
  const small = innerWidth < 720;
352
- this.target = this.kind === "snow" ? (small ? 150 : 320) : Math.round(fall.count * (small ? .5 : 1));
471
+ this.target = Math.round((this.kind === "snow" ? (small ? 150 : 320) : fall.count * (small ? .5 : 1)) * (big ? 1.6 : 1));
353
472
  this.list = Array.from({ length: this.target }, () => this.make(true));
354
473
  this.canvas.hidden = false;
355
474
  this.start();
@@ -367,10 +486,11 @@
367
486
  if (!this.kind || $("view-home").hidden) return;
368
487
  if (e.target.closest("a, button, input, select, textarea, label, [role=button], .rail, .quote-strip, .home-search")) return;
369
488
  this.burst(e.clientX, e.clientY, 18);
489
+ if (this.fw) this.firework(e.clientX - this.ox, e.clientY - this.oy);
370
490
  });
371
491
  },
372
492
  resize() {
373
- const r = this.canvas.getBoundingClientRect(), d = Math.min(devicePixelRatio || 1, 2);
493
+ const r = this.canvas.getBoundingClientRect(), d = Math.min(devicePixelRatio || 1, 1.5); // sharper than this isn't worth the extra drawing
374
494
  this.ox = r.left; this.oy = r.top;
375
495
  if (r.width === this.w && r.height === this.h) return;
376
496
  this.w = r.width; this.h = r.height;
@@ -381,7 +501,7 @@
381
501
  make(spread, x, y) {
382
502
  const snow = this.kind === "snow";
383
503
  return {
384
- x: x ?? Math.random() * this.w, y: y ?? (spread ? Math.random() * this.h : -30), vx: 0, vy: 0,
504
+ x: x ?? Math.random() * this.w, y: y ?? (spread ? Math.random() * this.h : this.dir < 0 ? this.h + 30 : -30), vx: 0, vy: 0,
385
505
  fall: snow ? .35 + Math.random() * .8 : .45 + Math.random() * .6,
386
506
  size: snow ? 1.2 + Math.random() * 2.8 : 16 + Math.random() * 14,
387
507
  phase: Math.random() * 6.28, sway: .4 + Math.random() * .8, rot: Math.random() * 6.28, spin: (Math.random() - .5) * .03,
@@ -397,6 +517,14 @@
397
517
  }
398
518
  this.start();
399
519
  },
520
+ firework(x, y) {
521
+ if (this.sparks.length > 700) return;
522
+ const c = this.fw[Math.floor(Math.random() * this.fw.length)], c2 = this.fw[Math.floor(Math.random() * this.fw.length)];
523
+ for (let i = 0; i < 54; i++) {
524
+ const a = Math.random() * Math.PI * 2, s = 1.2 + Math.random() * 3.6;
525
+ this.sparks.push({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, life: .7 + Math.random() * .4, c: i % 3 ? c : c2 });
526
+ }
527
+ },
400
528
  // each emoji is drawn once onto a small canvas and then stamped, much cheaper than drawing text every frame
401
529
  sprite(ch) {
402
530
  if (!this.sprites[ch]) {
@@ -418,11 +546,28 @@
418
546
  this.raf = 0;
419
547
  if (!this.kind || document.hidden) return;
420
548
  if ($("view-home").hidden) { setTimeout(() => this.start(), 500); return; }
549
+ // a slow computer (drawing takes over 5ms) gets 30 frames a second instead of 60; movement keeps the same speed
550
+ if (this.cost > 5 && (this.skip = !this.skip)) { this.raf = requestAnimationFrame((t2) => this.frame(t2)); return; }
551
+ const began = performance.now();
421
552
  const dt = Math.min(3, (t - this.last) / 16.7);
422
553
  this.last = t;
423
554
  if (t - this.measured > 1000) { this.measured = t; this.resize(); } // the side bar can slide in or out
424
- const ctx = this.ctx, snow = this.kind === "snow", R = 110, damp = Math.pow(.95, dt);
555
+ const ctx = this.ctx, snow = this.kind === "snow", R = 110, damp = Math.pow(.95, dt), px = this.canvas.width / this.w;
425
556
  ctx.clearRect(0, 0, this.w, this.h);
557
+ if (this.fw && !this.still && Math.random() < this.fwRate * dt / 60) this.firework(this.w * (.1 + Math.random() * .8), this.h * (.12 + Math.random() * .36));
558
+ if (this.sparks.length) {
559
+ const slow = Math.pow(.97, dt);
560
+ for (let i = this.sparks.length - 1; i >= 0; i--) {
561
+ const s = this.sparks[i];
562
+ s.life -= .012 * dt;
563
+ if (s.life <= 0) { this.sparks.splice(i, 1); continue; }
564
+ s.vx *= slow; s.vy = s.vy * slow + .035 * dt; s.x += s.vx * dt; s.y += s.vy * dt;
565
+ ctx.globalAlpha = Math.min(1, s.life * 1.6);
566
+ ctx.fillStyle = s.c;
567
+ ctx.fillRect(s.x - 1.5, s.y - 1.5, 3, 3);
568
+ }
569
+ ctx.globalAlpha = 1;
570
+ }
426
571
  if (snow) { ctx.fillStyle = "rgba(255, 255, 255, .85)"; ctx.beginPath(); } else ctx.globalAlpha = .85;
427
572
  for (let i = this.list.length - 1; i >= 0; i--) {
428
573
  const p = this.list[i];
@@ -430,16 +575,17 @@
430
575
  if (d2 < R * R) { const d = Math.sqrt(d2) || 1, f = (1 - d / R) * 1.6 * dt; p.vx += dx / d * f; p.vy += dy / d * f; }
431
576
  p.vx *= damp; p.vy *= damp; p.phase += .02 * dt; p.rot += p.spin * dt;
432
577
  p.x += (p.vx + Math.sin(p.phase) * p.sway * .5) * dt;
433
- p.y += (p.vy + p.fall) * dt;
434
- if (p.y > this.h + 30 || p.x < -40 || p.x > this.w + 40) {
578
+ p.y += (p.vy + p.fall * this.dir) * dt;
579
+ if (p.y > this.h + 40 || p.y < -40 || p.x < -40 || p.x > this.w + 40) {
435
580
  if (p.extra) { this.list.splice(i, 1); continue; }
436
581
  Object.assign(p, this.make(false));
437
582
  }
438
583
  if (snow) { ctx.moveTo(p.x + p.size, p.y); ctx.arc(p.x, p.y, p.size, 0, 6.283); }
439
- else { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.scale(this.canvas.width / this.w, this.canvas.height / this.h); ctx.translate(p.x, p.y); ctx.rotate(p.rot); ctx.drawImage(this.sprite(p.item), -p.size / 2, -p.size / 2, p.size, p.size); }
584
+ else { const c = Math.cos(p.rot) * px, s = Math.sin(p.rot) * px; ctx.setTransform(c, s, -s, c, p.x * px, p.y * px); ctx.drawImage(this.sprite(p.item), -p.size / 2, -p.size / 2, p.size, p.size); }
440
585
  }
441
586
  if (snow) ctx.fill();
442
- else { const d = this.canvas.width / this.w; ctx.setTransform(d, 0, 0, d, 0, 0); ctx.globalAlpha = 1; }
587
+ else { ctx.setTransform(px, 0, 0, px, 0, 0); ctx.globalAlpha = 1; }
588
+ this.cost = this.cost * .9 + (performance.now() - began) * .1;
443
589
  if (!this.still) this.raf = requestAnimationFrame((t2) => this.frame(t2));
444
590
  },
445
591
  };
@@ -714,11 +860,11 @@
714
860
  }
715
861
 
716
862
  // ---------- Routing: "" home, #games, #recent, #play/<id> ----------
717
- const VIEW_ORDER = ["home", "games", "trivia", "ai", "chat", "stats", "settings", "changelog"];
863
+ const VIEW_ORDER = ["home", "games", "trivia", "chat", "stats", "settings", "changelog"];
718
864
  let lastView = null;
719
865
  function viewFor(hash) {
720
866
  return hash === "#games" || hash === "#recent" ? "games" : hash === "#settings" ? "settings" : hash === "#chat" ? "chat"
721
- : hash === "#stats" ? "stats" : hash === "#changelog" ? "changelog" : hash === "#ai" ? "ai" : hash === "#trivia" ? "trivia" : "home";
867
+ : hash === "#stats" ? "stats" : hash === "#changelog" ? "changelog" : hash === "#trivia" ? "trivia" : "home";
722
868
  }
723
869
  // Switching pages: the old page slides out while the new one slides in (down the side bar = upward,
724
870
  // up the side bar = downward). Uses the browser's view transitions; older browsers just switch.
@@ -757,9 +903,9 @@
757
903
  $("view-settings").hidden = view !== "settings";
758
904
  $("view-chat").hidden = view !== "chat";
759
905
  lastView = view;
906
+ document.body.dataset.view = view; // page-specific styles key off this (cheaper than :has())
760
907
  $("view-stats").hidden = view !== "stats";
761
908
  $("view-changelog").hidden = view !== "changelog";
762
- $("view-ai").hidden = view !== "ai";
763
909
  $("view-trivia").hidden = view !== "trivia";
764
910
  if (view !== "trivia") { // leaving: stop the clock, close any puzzle site, and a half-done quiz starts over next time
765
911
  stopTriviaTimer();
@@ -769,7 +915,6 @@
769
915
  $("trivia-daily").hidden = false;
770
916
  renderDaily();
771
917
  }
772
- if (view === "ai") { renderAi(); setTimeout(() => $("ai-input").focus(), 50); }
773
918
  if (view === "changelog") renderChangelog();
774
919
  placeChatBox();
775
920
  if (view === "settings") { renderSettings(); renderAdmin(); }
@@ -784,15 +929,20 @@
784
929
  function play(id) { location.hash = `#play/${encodeURIComponent(id)}`; }
785
930
  // instant: switch right away, no slide (used when typing on the home search moves you to Games,
786
931
  // so the Games search box can take focus before the next key arrives)
932
+ // This page's own address. Inside the .svg version a <base> tag points relative links at the package folder,
933
+ // so a bare "#games" would turn the address into that folder: always build addresses from this instead.
934
+ const PAGE_URL = location.pathname + location.search;
787
935
  function go(view, { instant = false } = {}) {
788
936
  const target = view === "home" ? "" : `#${view}`;
789
- if (location.hash !== target) history.pushState(null, "", target || location.pathname + location.search);
937
+ if (location.hash !== target) history.pushState(null, "", PAGE_URL + target);
790
938
  const after = () => { if (view !== "recent") window.scrollTo(0, 0); };
791
939
  if (instant) { routeNow(); after(); } else route(after);
792
940
  }
793
941
  function goBack() {
794
- if (location.hash.startsWith("#play/")) history.length > 1 ? history.back() : (location.hash = "#games");
795
- else if (location.hash) go("home");
942
+ if (!location.hash.startsWith("#play/")) { if (location.hash) go("home"); return; }
943
+ // framed (.svg version): the frame's history is shared with the tab and the game, so go straight to the page
944
+ if (window.parent !== window) go(lastView || "games");
945
+ else history.length > 1 ? history.back() : (location.hash = "#games");
796
946
  }
797
947
 
798
948
  // ---------- Utilities ----------
@@ -836,6 +986,11 @@
836
986
  // Newest first. Add an entry here with every publish; its version should match package.json.
837
987
  // Each has: new (features), games (added/removed/fixed games), fixes (bugs). Leave a list out if empty.
838
988
  const CHANGELOG = [
989
+ { version: "1.0.45", date: "2026-11-13",
990
+ new: ["New game: 60 Seconds! Reatomized"], fixes: ["The whole site is faster and smoother, especially on Chromebooks: less work in the background on every page, and much smoother scrolling on the Games page", "The Google Classroom loading screen was removed", "The AI chat was removed"] },
991
+ { version: "1.0.44", date: "2026-11-12",
992
+ new: ["🔒 Private chat rooms: host a room, share its 6-character code, and chat with just the people who have it. Each room gets its own tab next to Public, with a dot when someone posts (rooms last 24 hours)", "🎨 Every holiday theme now has its own drawn scene, with fireworks on New Year's and the Fourth of July and a countdown to the big day", "🎉 New themes: Super Bowl weekend, April Fools' Day, summer break and back to school", "Holiday colors now show on every page, not just the home page", "💰 A Tycoon section on the Games page: Monkey Mart, Adventure Capitalist, Hardware Tycoon, OpenTTD and more"],
993
+ fixes: ["In the .svg version, Back from a game no longer lands on a list of files"] },
839
994
  { version: "1.0.43", date: "2026-11-10",
840
995
  new: [], fixes: ["The .svg version now shows your tab disguise (like Google Classroom) in the browser tab", "In the .svg version, the link back to the normal site is at the bottom of the Games page and opens its Games page"] },
841
996
  { version: "1.0.42", date: "2026-11-10",
@@ -1354,7 +1509,12 @@
1354
1509
  loadScript(`https://www.gstatic.com/firebasejs/${v}/firebase-database-compat.js`),
1355
1510
  loadScript(`https://www.gstatic.com/firebasejs/${v}/firebase-auth-compat.js`),
1356
1511
  ]);
1357
- return window.firebase.initializeApp(CFG.firebase, "rug");
1512
+ const app = window.firebase.initializeApp(CFG.firebase, "rug");
1513
+ if (CFG.firebaseEmulator) { // local testing only (see config.js)
1514
+ const [host, port] = String(CFG.firebaseEmulator).split(":");
1515
+ app.database().useEmulator(host, Number(port));
1516
+ }
1517
+ return app;
1358
1518
  })().catch((err) => { console.warn("Firebase unavailable:", err); return null; });
1359
1519
  }
1360
1520
  return firebaseApp;
@@ -1473,7 +1633,10 @@
1473
1633
  };
1474
1634
  const HIDE_AFTER_REPORTS = Infinity;
1475
1635
  // Each room keeps its own messages, typing and "in chat" list; names, bans, mutes and settings are shared
1476
- function roomPath(x) { return chat.room === "live" ? `live/chat/${x}` : `chat/${x}`; } // reports are switched off: nothing is hidden automatically
1636
+ // A private room is "room:<CODE>": everything in it lives under rooms/<CODE> (see "Private chat rooms" below)
1637
+ function roomCode() { return chat.room.startsWith("room:") ? chat.room.slice(5) : null; }
1638
+ function roomPath(x) { const c = roomCode(); return c ? `rooms/${c}/${x}` : chat.room === "live" ? `live/chat/${x}` : `chat/${x}`; } // reports are switched off: nothing is hidden automatically
1639
+ function flagsPath() { const c = roomCode(); return c ? `roomFlags/${c}` : "chat/flags"; }
1477
1640
  const ADMIN_NAME = "Richard"; // what the admin's messages show as (reserved: the database refuses it from non-admins)
1478
1641
  function setAdminName() {
1479
1642
  $("chat-name").value = ADMIN_NAME;
@@ -1516,6 +1679,7 @@
1516
1679
  log.innerHTML = `<p class="chat-empty" id="chat-empty">No messages yet. Say hi!</p>`;
1517
1680
  const db = app.database();
1518
1681
  watchChatState(db);
1682
+ await restoreRoom(db); // back into the private room this browser was in, if it's still open
1519
1683
  listenRoom(db);
1520
1684
  watchChatReset(db);
1521
1685
  }
@@ -1548,14 +1712,33 @@
1548
1712
  }
1549
1713
  }
1550
1714
  function listenRoom(db) {
1551
- const log = $("chat-log"), room = chat.room;
1715
+ const log = $("chat-log"), room = chat.room, tab = activeTab();
1716
+ tabUnread.delete(tab);
1552
1717
  log.innerHTML = `<p class="chat-empty" id="chat-empty">${room === "live" ? "No messages yet. Say hi to the stream!" : "No messages yet. Say hi!"}</p>`;
1553
- $("chat-text").placeholder = room === "live" ? "Chat with the stream…" : "Say something… (drop a photo here)";
1718
+ $("chat-text").placeholder = room === "live" ? "Chat with the stream…" : roomCode() ? "Say something in this room…" : "Say something… (drop a photo here)";
1554
1719
  if (chat.ref) chat.ref.off(); // reconnecting (signed in/out): drop the old listener so messages don't double
1555
1720
  chat.resetAt = lastChatReset();
1556
- const ref = chat.ref = db.ref(roomPath("messages")).orderByChild("ts").startAt(chat.resetAt).limitToLast(60);
1721
+ // poll votes and report counts belong to the room being shown
1722
+ chat.votesRef?.off();
1723
+ chat.flagsRef?.off();
1724
+ chat.votes = {};
1725
+ chat.flags = {};
1726
+ chat.votesRef = db.ref(roomPath("votes"));
1727
+ chat.votesRef.on("value", (s) => { chat.votes = s.val() || {}; updatePolls(); }, () => {});
1728
+ chat.flagsRef = db.ref(flagsPath());
1729
+ chat.flagsRef.on("value", (s) => {
1730
+ chat.flags = {};
1731
+ s.forEach((c) => { chat.flags[c.key] = c.numChildren(); });
1732
+ log.querySelectorAll(".chat-msg").forEach(applyFlags);
1733
+ if (chat.admin && !roomCode()) renderReported();
1734
+ }, () => {});
1735
+ watchRoomMeta(db);
1736
+ syncTabWatchers(db);
1737
+ // the main chat starts fresh each day; a private room shows everything since it was made (it only lasts a day)
1738
+ const ref = chat.ref = db.ref(roomPath("messages")).orderByChild("ts").startAt(roomCode() ? 0 : chat.resetAt).limitToLast(60);
1557
1739
  ref.on("child_added", (snap) => {
1558
1740
  const m = snap.val();
1741
+ if (m && Number(m.ts)) markTabSeen(tab, Number(m.ts));
1559
1742
  const div = renderMessage(snap.key, m);
1560
1743
  if (!div) return;
1561
1744
  $("chat-empty")?.remove();
@@ -1578,6 +1761,7 @@
1578
1761
  }
1579
1762
  async function switchRoom(room) {
1580
1763
  if (room === chat.room) return;
1764
+ markTabSeen(activeTab()); // everything in the tab you're leaving counts as read
1581
1765
  stopTyping();
1582
1766
  typing.ref = null;
1583
1767
  if (hereOn && hereRef) hereRef.remove().catch(() => {});
@@ -1589,6 +1773,226 @@
1589
1773
  if (app) listenRoom(app.database());
1590
1774
  }
1591
1775
 
1776
+ // ---------- Private chat rooms ----------
1777
+ // Host a room and get a 6-character code; anyone who types the code joins it. A room is rooms/<CODE> in the
1778
+ // database (readable only by people who know the code), with roomMeta/<CODE> = { host, ts }. Rooms stop
1779
+ // working 24 hours after they're made. The same word filter, bans and mutes apply, the host can delete any
1780
+ // message in the room or close it, and the site owner can open any room (Settings lists them).
1781
+ const ROOM_LIFE = 24 * 60 * 60e3, ROOM_KEY = "rug-room", ROOMS_KEY = "rug-rooms";
1782
+ const ROOM_LETTERS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; // no I, L, O, 0 or 1: they get misread
1783
+ const cleanRoomCode = (s) => String(s || "").toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 6);
1784
+ function isRoomHost() { return !!roomCode() && !!chat.roomMeta && chat.roomMeta.host === chat.uid; }
1785
+ function serverNow() { return Date.now() + (typing.offset || 0); }
1786
+ function roomMsg(text) { $("room-msg").textContent = text || ""; }
1787
+ // every room this browser has been in (code -> when it was made), so expired ones can be cleaned up later
1788
+ function rememberRoom(code, ts) {
1789
+ const all = store.get(ROOMS_KEY, {});
1790
+ if (ts) all[code] = ts; else delete all[code];
1791
+ store.set(ROOMS_KEY, all);
1792
+ }
1793
+ function deleteRoom(db, code) {
1794
+ return db.ref().update({ [`rooms/${code}`]: null, [`roomMeta/${code}`]: null, [`roomFlags/${code}`]: null });
1795
+ }
1796
+ function sweepMyRooms(db) {
1797
+ for (const [code, ts] of Object.entries(store.get(ROOMS_KEY, {}))) {
1798
+ if (serverNow() - ts < ROOM_LIFE) continue;
1799
+ rememberRoom(code, null);
1800
+ deleteRoom(db, code).catch(() => {});
1801
+ }
1802
+ }
1803
+ async function restoreRoom(db) {
1804
+ sweepMyRooms(db);
1805
+ const code = cleanRoomCode(store.get(ROOM_KEY, ""));
1806
+ if (code.length !== 6) return;
1807
+ try {
1808
+ const meta = (await db.ref(`roomMeta/${code}`).once("value")).val();
1809
+ if (meta && serverNow() - meta.ts < ROOM_LIFE) { chat.room = `room:${code}`; return; }
1810
+ } catch { /* older rules, or offline */ }
1811
+ store.set(ROOM_KEY, "");
1812
+ }
1813
+ async function hostRoom() {
1814
+ const app = await getFirebase();
1815
+ if (!app || !chat.uid) return roomMsg("Chat isn't connected yet.");
1816
+ if (chat.banned) return roomMsg("You're banned from chat.");
1817
+ const db = app.database(), TS = window.firebase.database.ServerValue.TIMESTAMP;
1818
+ const code = [...crypto.getRandomValues(new Uint32Array(6))].map((n) => ROOM_LETTERS[n % ROOM_LETTERS.length]).join("");
1819
+ try {
1820
+ await db.ref().update({ [`roomMeta/${code}`]: { host: chat.uid, ts: TS }, [`roomLast/${chat.uid}`]: TS });
1821
+ } catch {
1822
+ return roomMsg("Couldn't make a room. You can make one a minute, so wait a bit and try again.");
1823
+ }
1824
+ rememberRoom(code, serverNow());
1825
+ enterRoom(code);
1826
+ toast(`Room ${code} is open. Share the code to let people in.`);
1827
+ }
1828
+ async function joinRoom(raw) {
1829
+ const code = cleanRoomCode(raw);
1830
+ if (code.length !== 6) return roomMsg("Room codes are 6 letters and numbers.");
1831
+ const app = await getFirebase();
1832
+ if (!app || !chat.uid) return roomMsg("Chat isn't connected yet.");
1833
+ const db = app.database();
1834
+ let meta = null;
1835
+ try { meta = (await db.ref(`roomMeta/${code}`).once("value")).val(); } catch { return roomMsg("Couldn't check that code. Try again."); }
1836
+ if (!meta) return roomMsg("No room has that code. Check it and try again.");
1837
+ if (serverNow() - meta.ts >= ROOM_LIFE) { deleteRoom(db, code).catch(() => {}); return roomMsg("That room has closed. Rooms last 24 hours."); }
1838
+ rememberRoom(code, meta.ts);
1839
+ enterRoom(code);
1840
+ }
1841
+ function enterRoom(code) {
1842
+ store.set(ROOM_KEY, code);
1843
+ $("room-panel").hidden = true;
1844
+ $("room-code").value = "";
1845
+ roomMsg("");
1846
+ switchRoom(`room:${code}`);
1847
+ }
1848
+ function leaveRoom(note) {
1849
+ const code = roomCode();
1850
+ if (code) { rememberRoom(code, null); tabUnread.delete(code); }
1851
+ store.set(ROOM_KEY, "");
1852
+ switchRoom("main");
1853
+ if (note) chatNote(note);
1854
+ }
1855
+ // ---------- Chat tabs: Public, then every room this browser is in, then "+ Room" ----------
1856
+ // Tabs you're not looking at keep a light watch (their newest message) to show a dot when someone posts there.
1857
+ const TAB_SEEN_KEY = "rug-tab-seen", pageOpenedAt = Date.now();
1858
+ const tabSeen = store.get(TAB_SEEN_KEY, {}), tabUnread = new Set(), tabWatch = {};
1859
+ const activeTab = () => roomCode() || "main";
1860
+ function myRooms() {
1861
+ return Object.entries(store.get(ROOMS_KEY, {}))
1862
+ .filter(([c, ts]) => cleanRoomCode(c) === c && c.length === 6 && serverNow() - ts < ROOM_LIFE)
1863
+ .sort((a, b) => a[1] - b[1]).map(([c]) => c);
1864
+ }
1865
+ function markTabSeen(tab, ts) {
1866
+ tabSeen[tab] = Math.max(tabSeen[tab] || 0, ts || serverNow());
1867
+ store.set(TAB_SEEN_KEY, tabSeen);
1868
+ }
1869
+ function renderTabs() {
1870
+ const bar = $("chat-tabs"), active = activeTab();
1871
+ bar.hidden = chat.room === "live";
1872
+ const tab = (id, label, title) => `<button class="chat-tab${tabUnread.has(id) ? " unread" : ""}" type="button" role="tab" data-tab="${id}" aria-selected="${id === active}" title="${title}">${label}</button>`;
1873
+ bar.innerHTML = tab("main", "Public", "The public chat") +
1874
+ myRooms().map((c) => tab(c, `🔒 ${c}`, `Private room ${c}`)).join("") +
1875
+ `<button class="chat-tab add" type="button" id="room-open" aria-expanded="${!$("room-panel").hidden}" title="Host or join a private room">+ Room</button>`;
1876
+ }
1877
+ function syncTabWatchers(db) {
1878
+ const want = new Set(chat.room === "live" ? [] : ["main", ...myRooms()]);
1879
+ want.delete(activeTab());
1880
+ for (const id of Object.keys(tabWatch)) if (!want.has(id)) { tabWatch[id].off(); delete tabWatch[id]; }
1881
+ for (const id of want) {
1882
+ if (tabWatch[id]) continue;
1883
+ tabWatch[id] = db.ref(id === "main" ? "chat/messages" : `rooms/${id}/messages`).orderByChild("ts").limitToLast(1);
1884
+ tabWatch[id].on("child_added", (s) => {
1885
+ const m = s.val();
1886
+ if (!m || m.uid === chat.uid || !(Number(m.ts) > (tabSeen[id] || pageOpenedAt))) return;
1887
+ if (id === "main") noteNewMessage(m, false); // the side bar's chat dot
1888
+ if (activeTab() !== id) { tabUnread.add(id); renderTabs(); }
1889
+ }, () => { // the room closed or ran out: drop its tab
1890
+ delete tabWatch[id];
1891
+ if (id === "main") return;
1892
+ rememberRoom(id, null);
1893
+ tabUnread.delete(id);
1894
+ renderTabs();
1895
+ });
1896
+ }
1897
+ }
1898
+ async function closeRoom() {
1899
+ const code = roomCode();
1900
+ if (!code || !(isRoomHost() || chat.admin)) return;
1901
+ if (!confirm("Close this room for everyone? All its messages are deleted.")) return;
1902
+ try { await deleteRoom((await getFirebase()).database(), code); } // everyone's page then sees the room is gone and leaves
1903
+ catch { chatNote("Couldn't close the room. Try again.", true); }
1904
+ }
1905
+ // Follows the open room's entry: fills the strip above the messages, and leaves when the room closes or runs out
1906
+ function watchRoomMeta(db) {
1907
+ chat.metaRef?.off();
1908
+ chat.metaRef = null;
1909
+ chat.roomMeta = null;
1910
+ clearInterval(chat.roomTimer);
1911
+ const code = roomCode();
1912
+ renderRoomStrip();
1913
+ if (!code) return;
1914
+ const gone = (note) => { rememberRoom(code, null); if (roomCode() === code) leaveRoom(note); };
1915
+ chat.metaRef = db.ref(`roomMeta/${code}`);
1916
+ chat.metaRef.on("value", (s) => {
1917
+ const meta = s.val();
1918
+ if (!meta || serverNow() - meta.ts >= ROOM_LIFE) { gone("That private room has closed."); return; }
1919
+ chat.roomMeta = meta;
1920
+ rememberRoom(code, meta.ts);
1921
+ renderRoomStrip();
1922
+ }, () => gone("That private room has closed."));
1923
+ chat.roomTimer = setInterval(() => {
1924
+ if (chat.roomMeta && serverNow() - chat.roomMeta.ts >= ROOM_LIFE) { deleteRoom(db, code).catch(() => {}); gone("That private room has closed. Rooms last 24 hours."); }
1925
+ else renderRoomStrip();
1926
+ }, 30000);
1927
+ }
1928
+ function renderRoomStrip() {
1929
+ const code = roomCode();
1930
+ $("room-strip").hidden = !code;
1931
+ $("chat-log").classList.toggle("host", isRoomHost());
1932
+ renderTabs();
1933
+ if (!code) return;
1934
+ $("room-strip-code").textContent = code;
1935
+ $("room-strip-left").textContent = chat.roomMeta ? `closes in ${fmtWait(chat.roomMeta.ts + ROOM_LIFE - serverNow())}` : "";
1936
+ $("room-close").hidden = !(isRoomHost() || chat.admin);
1937
+ }
1938
+ // Owner: every open room (Settings → Tools), with how many reports each has. Expired ones are deleted here too.
1939
+ let roomsAdminWatched = false;
1940
+ function watchRoomsAdmin(db) {
1941
+ if (roomsAdminWatched) return;
1942
+ roomsAdminWatched = true;
1943
+ let metas = {}, flags = {};
1944
+ const draw = () => {
1945
+ const rows = Object.entries(metas).filter(([, m]) => m && serverNow() - m.ts < ROOM_LIFE).sort((a, b) => b[1].ts - a[1].ts);
1946
+ $("rooms-count").textContent = rows.length ? `(${rows.length})` : "";
1947
+ $("rooms-list").innerHTML = !rows.length ? `<p class="none">No private rooms open.</p>` : rows.map(([code, m]) => {
1948
+ const n = Object.keys(flags[code] || {}).length;
1949
+ return `<div class="report" data-code="${escapeHtml(code)}">${n ? `<span class="kind broken">🚩 ${n}</span>` : ""}` +
1950
+ `<div class="body"><span class="game">${escapeHtml(code)}</span><div class="meta">Closes in ${fmtWait(m.ts + ROOM_LIFE - serverNow())}</div></div>` +
1951
+ `<button class="mod" type="button" data-room="open">Open</button><button class="mod" type="button" data-room="close">Close</button></div>`;
1952
+ }).join("");
1953
+ };
1954
+ db.ref("roomMeta").on("value", (s) => {
1955
+ metas = s.val() || {};
1956
+ for (const [code, m] of Object.entries(metas)) if (!m || serverNow() - m.ts >= ROOM_LIFE) deleteRoom(db, code).catch(() => {});
1957
+ draw();
1958
+ }, () => { roomsAdminWatched = false; });
1959
+ db.ref("roomFlags").on("value", (s) => { flags = s.val() || {}; draw(); }, () => {});
1960
+ }
1961
+ function bindRooms() {
1962
+ $("chat-tabs").addEventListener("click", (e) => {
1963
+ const b = e.target.closest(".chat-tab");
1964
+ if (!b) return;
1965
+ if (b.id === "room-open") {
1966
+ $("room-panel").hidden = !$("room-panel").hidden;
1967
+ roomMsg("");
1968
+ renderTabs();
1969
+ if (!$("room-panel").hidden) $("room-code").focus();
1970
+ return;
1971
+ }
1972
+ const id = b.dataset.tab;
1973
+ $("room-panel").hidden = true;
1974
+ store.set(ROOM_KEY, id === "main" ? "" : id);
1975
+ switchRoom(id === "main" ? "main" : `room:${id}`);
1976
+ if (id === activeTab()) renderTabs();
1977
+ });
1978
+ $("room-host").addEventListener("click", hostRoom);
1979
+ $("room-join").addEventListener("submit", (e) => { e.preventDefault(); joinRoom($("room-code").value); });
1980
+ $("room-code").addEventListener("input", () => { $("room-code").value = cleanRoomCode($("room-code").value); });
1981
+ $("room-leave").addEventListener("click", () => leaveRoom());
1982
+ $("room-close").addEventListener("click", closeRoom);
1983
+ $("room-copy").addEventListener("click", async () => {
1984
+ try { await navigator.clipboard.writeText(roomCode()); toast("Room code copied ✓"); } catch { toast(`Room code: ${roomCode()}`); }
1985
+ });
1986
+ $("rooms-list").addEventListener("click", async (e) => {
1987
+ const b = e.target.closest("[data-room]"), code = b?.closest(".report")?.dataset.code;
1988
+ if (!code || !chat.admin) return;
1989
+ if (b.dataset.room === "open") { enterRoom(code); go("chat"); return; }
1990
+ if (confirm(`Close room ${code} for everyone? All its messages are deleted.`)) {
1991
+ try { await deleteRoom((await getFirebase()).database(), code); } catch {}
1992
+ }
1993
+ });
1994
+ }
1995
+
1592
1996
  // One chat row: text, a sticker or a photo, plus its buttons (shown by CSS for who may use them)
1593
1997
  function renderMessage(key, m) {
1594
1998
  if (!m || typeof m.name !== "string") return null;
@@ -1672,7 +2076,6 @@
1672
2076
 
1673
2077
  // Live chat state: owner settings (slow mode, lock, extra words), my mute/ban, and report counts
1674
2078
  function watchChatState(db) {
1675
- db.ref("chat/votes").on("value", (s) => { chat.votes = s.val() || {}; updatePolls(); });
1676
2079
  db.ref("chat/settings").on("value", (s) => {
1677
2080
  chat.settings = s.val() || {};
1678
2081
  updateChatStatus();
@@ -1684,12 +2087,6 @@
1684
2087
  }, () => {});
1685
2088
  db.ref(`chat/mutes/${chat.uid}`).on("value", (s) => { chat.mutedUntil = Number(s.val()?.until) || 0; updateChatStatus(); }, () => {});
1686
2089
  db.ref(`chat/banned/${chat.uid}`).on("value", (s) => { chat.banned = s.exists(); updateChatStatus(); }, () => {});
1687
- db.ref("chat/flags").on("value", (s) => {
1688
- chat.flags = {};
1689
- s.forEach((c) => { chat.flags[c.key] = c.numChildren(); });
1690
- $("chat-log").querySelectorAll(".chat-msg").forEach(applyFlags);
1691
- if (chat.admin) renderReported();
1692
- }, () => {});
1693
2090
  clearInterval(chat.statusTimer);
1694
2091
  chat.statusTimer = setInterval(updateChatStatus, 15000); // mutes run out on their own
1695
2092
  }
@@ -1792,7 +2189,7 @@
1792
2189
  if (act === "vote") {
1793
2190
  if (!chat.uid) return;
1794
2191
  const i = Number(btn.dataset.i), mineNow = (chat.votes[key] || {})[chat.uid];
1795
- try { await (await getFirebase()).database().ref(`chat/votes/${key}/${chat.uid}`).set(mineNow === i ? null : i); }
2192
+ try { await (await getFirebase()).database().ref(roomPath(`votes/${key}/${chat.uid}`)).set(mineNow === i ? null : i); }
1796
2193
  catch { chatNote(blockedReason() || "Your vote didn't count. Try again.", true); }
1797
2194
  return;
1798
2195
  }
@@ -1800,10 +2197,10 @@
1800
2197
  const db = (await getFirebase()).database();
1801
2198
  try {
1802
2199
  if (act === "report" && !mine) {
1803
- await db.ref(`chat/flags/${key}/${chat.uid}`).set(true);
1804
- chatNote(`Reported. Messages with ${HIDE_AFTER_REPORTS} reports are hidden until the owner looks at them.`);
1805
- } else if (act === "delete" && (mine || chat.admin)) {
1806
- await db.ref().update({ [roomPath(`messages/${key}`)]: null, ...(row.dataset.media ? { [`chat/media/${row.dataset.media}`]: null } : {}) });
2200
+ await db.ref(`${flagsPath()}/${key}/${chat.uid}`).set(true);
2201
+ chatNote("Reported. The site owner will take a look.");
2202
+ } else if (act === "delete" && (mine || chat.admin || isRoomHost())) {
2203
+ await db.ref().update({ [roomPath(`messages/${key}`)]: null, ...(row.dataset.media ? { [roomPath(`media/${row.dataset.media}`)]: null } : {}) });
1807
2204
  } else if (!chat.admin || mine) {
1808
2205
  return;
1809
2206
  } else if (act === "purge") {
@@ -1884,7 +2281,7 @@
1884
2281
  $("admin-chat-tools").hidden = !on;
1885
2282
  $("admin-quotes").hidden = !on;
1886
2283
  if (on) { watchQuoteAdmin(); renderQuoteAdmin(); }
1887
- if (on) { watchReports(); watchPunished(app.database()); fillChatTools(); renderReported(); }
2284
+ if (on) { watchReports(); watchPunished(app.database()); watchRoomsAdmin(app.database()); fillChatTools(); renderReported(); }
1888
2285
  else unwatchReports();
1889
2286
  }
1890
2287
 
@@ -1905,7 +2302,7 @@
1905
2302
  }
1906
2303
  // Messages people reported, newest reports first, with keep / delete / delete-all buttons
1907
2304
  async function renderReported() {
1908
- if (!chat.admin) return;
2305
+ if (!chat.admin || roomCode()) return; // this list is the main chat's; rooms with reports show under "Private rooms"
1909
2306
  const keys = Object.keys(chat.flags).filter((k) => chat.flags[k] > 0);
1910
2307
  $("reported-count").textContent = keys.length ? `(${keys.length})` : "";
1911
2308
  if (!keys.length) { $("reported-list").innerHTML = `<p class="none">Nothing reported.</p>`; return; }
@@ -2991,7 +3388,6 @@
2991
3388
  [".rail-btn[data-nav=games]", "Games", "Every game, by category. There's a Game of the day and the most played games at the top."],
2992
3389
  [".rail-btn[data-nav=trivia]", "Trivia", "Quick quizzes, NFL, NBA and MLB team trivia, and a daily challenge with a leaderboard."],
2993
3390
  ["#soundboard-btn", "Soundboard", "Meme sounds and effects, one click away."],
2994
- [".rail-btn[data-nav=ai]", "AI chat", "Ask anything: homework help, game ideas, or just questions."],
2995
3391
  [".rail-btn[data-nav=chat]", "Chat", "Talk with everyone on the site. Be nice, and you can post polls too."],
2996
3392
  ["#panic-btn", "Panic button", "Jumps straight to Google Classroom. The ` and ] keys do it too."],
2997
3393
  [".rail-btn[data-nav=settings]", "Settings", "Themes, the tab disguise, the panic page and more. You can replay this tour there."],
@@ -3014,6 +3410,7 @@
3014
3410
  const r = target && target.offsetParent !== null ? target.getBoundingClientRect() : null;
3015
3411
  const spot = $("tour-spot"), card = $("tour-card");
3016
3412
  spot.hidden = !r;
3413
+ $("tour").classList.toggle("spot-on", !!r);
3017
3414
  if (r) Object.assign(spot.style, { left: `${r.left - 6}px`, top: `${r.top - 6}px`, width: `${r.width + 12}px`, height: `${r.height + 12}px` });
3018
3415
  $("tour-step").textContent = `${tour.i + 1} of ${TOUR_STEPS.length}`;
3019
3416
  $("tour-title").textContent = title;
@@ -3040,255 +3437,6 @@
3040
3437
  addEventListener("resize", () => { if (!$("tour").hidden) tourStep(); });
3041
3438
  }
3042
3439
 
3043
- // ---------- AI chat ----------
3044
- // One chatbot backed by several free AI services. It tries them in order (Gemini, Groq, OpenRouter,
3045
- // Mistral); when one is out of free messages, down or missing a key, it moves to the next.
3046
- // Keys go in config.js (ai: { gemini, groq, openrouter, mistral }). Models are picked from each service's
3047
- // own current list, so renamed models don't break it. The conversation is kept in this browser only.
3048
- const AI_KEY = "rug-ai-chat";
3049
- const AI_SYSTEM = "You are the helpful AI on richardwho, a games site used by students. Be friendly, clear and fairly short. " +
3050
- "Help with homework by explaining how to solve things, not just giving answers. Keep everything appropriate for school: " +
3051
- "no sexual content, no graphic violence, nothing hateful, nothing dangerous or illegal. Use Markdown for lists and code. " +
3052
- "Never use LaTeX; write math in plain text (like CO2, x^2, 6CO2 + 6H2O -> C6H12O6 + 6O2).";
3053
- const ai = { busy: false, models: {}, chats: [], currentId: null, pendingImg: null };
3054
- const aiKeys = () => CFG.ai || {};
3055
- const AI_SERVICES = [
3056
- { id: "gemini", name: "Gemini",
3057
- async pickModel(key) {
3058
- const r = await fetch("https://generativelanguage.googleapis.com/v1beta/models?pageSize=200", { headers: { "x-goog-api-key": key } });
3059
- const list = (await r.json()).models || [];
3060
- const ok = list.filter((m) => (m.supportedGenerationMethods || []).includes("generateContent") && /gemini/.test(m.name) && !/(image|tts|audio|embedding|live|preview-tts|robotics)/.test(m.name));
3061
- // newest first, full flash before lite; the newest often has no free messages, so ask() walks down the list
3062
- const rank = (m) => (/flash/.test(m.name) ? 0 : 2) + (/lite/.test(m.name) ? 1 : 0);
3063
- const names = ok.filter((m) => !/preview|latest|omni/.test(m.name))
3064
- .sort((a, b) => rank(a) - rank(b) || b.name.localeCompare(a.name, undefined, { numeric: true })).map((m) => m.name);
3065
- // the model that worked last time goes first, so only the very first visit has to search
3066
- let good = null;
3067
- try { good = localStorage.getItem("rug-ai-gemini"); } catch {}
3068
- // the model set in config.js first, then the one that worked last time, then the rest
3069
- for (const want of [good, aiKeys().geminiModel && "models/" + aiKeys().geminiModel]) {
3070
- if (want && names.includes(want)) names.unshift(...names.splice(names.indexOf(want), 1));
3071
- }
3072
- return names.length ? names : null;
3073
- },
3074
- async ask(key, models, msgs) {
3075
- let good = null;
3076
- try { good = localStorage.getItem("rug-ai-gemini"); } catch {}
3077
- for (const model of [...models]) {
3078
- // an untested model gets 8s (overloaded ones just hang); a known-good one gets time for long answers
3079
- const r = await fetch(`https://generativelanguage.googleapis.com/v1beta/${model}:generateContent`, {
3080
- method: "POST", headers: { "Content-Type": "application/json", "x-goog-api-key": key }, signal: AbortSignal.timeout(model === good ? 45000 : 8000),
3081
- body: JSON.stringify({ systemInstruction: { parts: [{ text: AI_SYSTEM }] },
3082
- contents: msgs.map((m) => ({ role: m.role === "assistant" ? "model" : "user", parts: [{ text: m.text },
3083
- ...(m.img ? [{ inline_data: { mime_type: m.img.slice(5, m.img.indexOf(";")), data: m.img.slice(m.img.indexOf(",") + 1) } }] : [])] })) }),
3084
- }).catch(() => ({ ok: false, status: "timeout" }));
3085
- if (!r.ok) { models.splice(models.indexOf(model), 1); continue; } // out of free messages for this model: next one
3086
- try { localStorage.setItem("rug-ai-gemini", model); } catch {}
3087
- const d = await r.json();
3088
- return (d.candidates?.[0]?.content?.parts || []).map((p) => p.text || "").join("").trim();
3089
- }
3090
- throw new Error("gemini: no model with free messages left");
3091
- } },
3092
- { id: "groq", name: "Groq", base: "https://api.groq.com/openai/v1",
3093
- prefer: [/llama.*70b/, /llama/, /qwen/, /gpt-oss/], avoid: /(whisper|guard|tts|vision|embed)/ },
3094
- { id: "openrouter", name: "OpenRouter", base: "https://openrouter.ai/api/v1",
3095
- prefer: [/llama/, /gemma/, /qwen/, /mistral/, /nemotron.*super/, /./], avoid: /(content-safety|code|coder|guard|vision|vl|embed)/, freeOnly: true },
3096
- { id: "mistral", name: "Mistral", base: "https://api.mistral.ai/v1",
3097
- prefer: [/mistral-small-latest/, /mistral-medium-latest/, /mistral-large-latest/, /mistral/], avoid: /(embed|ocr|moderation|codestral|pixtral)/ },
3098
- ];
3099
- // Groq, OpenRouter and Mistral all speak the same (OpenAI-style) format
3100
- const openAiStyle = {
3101
- async pickModel(key, svc) {
3102
- const r = await fetch(`${svc.base}/models`, { headers: { Authorization: `Bearer ${key}` } });
3103
- let ids = ((await r.json()).data || []).map((m) => m.id).filter((id) => !svc.avoid.test(id));
3104
- if (svc.freeOnly) ids = ids.filter((id) => id.endsWith(":free"));
3105
- for (const re of svc.prefer) { const hit = ids.find((id) => re.test(id)); if (hit) return hit; }
3106
- return ids[0];
3107
- },
3108
- async ask(key, model, msgs, svc) {
3109
- const r = await fetch(`${svc.base}/chat/completions`, {
3110
- method: "POST",
3111
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}`, ...(svc.id === "openrouter" ? { "X-Title": "richardwho" } : {}) },
3112
- body: JSON.stringify({ model, messages: [{ role: "system", content: AI_SYSTEM }, ...msgs.map((m) => ({ role: m.role, content: m.img ? m.text + "\n\n(The user attached a picture, but you can't see pictures. Say so if it matters.)" : m.text }))], max_tokens: 1200 }),
3113
- });
3114
- if (!r.ok) throw new Error(`${svc.id} ${r.status}`);
3115
- const d = await r.json();
3116
- return (d.choices?.[0]?.message?.content || "").trim();
3117
- },
3118
- };
3119
- function aiReady() { return AI_SERVICES.some((s) => aiKeys()[s.id]); }
3120
- async function askAi(msgs) {
3121
- const order = msgs.some((m) => m.img) ? [...AI_SERVICES].sort((x) => (x.id === "gemini" ? -1 : 0)) : AI_SERVICES;
3122
- for (const svc of order) {
3123
- const key = aiKeys()[svc.id];
3124
- if (!key) continue;
3125
- const impl = svc.ask ? svc : openAiStyle;
3126
- try {
3127
- ai.models[svc.id] ||= (aiKeys().models || {})[svc.id] || await impl.pickModel(key, svc);
3128
- if (!ai.models[svc.id]) throw new Error("no model");
3129
- const text = await impl.ask(key, ai.models[svc.id], msgs, svc);
3130
- if (text) return { text, by: svc.name };
3131
- } catch (err) {
3132
- console.warn("AI service skipped:", svc.name, err.message); // out of free messages, down, or bad key: try the next
3133
- }
3134
- }
3135
- throw new Error("all busy");
3136
- }
3137
- // Light Markdown: code blocks, inline code, bold, italics, lists, links (everything escaped first)
3138
- function aiFormat(text) {
3139
- const blocks = [];
3140
- let h = escapeHtml(text).replace(/```[a-z0-9+-]*\n?([\s\S]*?)```/gi, (m, code) => { blocks.push(code.replace(/\n$/, "")); return `\u0000${blocks.length - 1}\u0000`; });
3141
- h = h.replace(/`([^`\n]+)`/g, "<code>$1</code>")
3142
- .replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
3143
- .replace(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,!?:;]|$)/g, "$1<em>$2</em>")
3144
- .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
3145
- // line by line; runs of "- item" become a bullet list, runs of "1. item" a numbered list
3146
- const out = [];
3147
- let list = null;
3148
- for (const line of h.split("\n")) {
3149
- const bullet = line.match(/^\s*[-*•] (.*)/), num = line.match(/^\s*\d+[.)] (.*)/);
3150
- const kind = bullet ? "ul" : num ? "ol" : null;
3151
- if (list && list !== kind) { out.push(`</${list}>`); list = null; }
3152
- if (kind) { if (!list) { out.push(`<${kind}>`); list = kind; } out.push(`<li>${(bullet || num)[1]}</li>`); continue; }
3153
- if (/^\s*([-*_])\1{2,}\s*$/.test(line)) out.push("<hr>");
3154
- else if (/^#{1,6} /.test(line)) out.push(`<p class="ai-h">${line.replace(/^#+ /, "")}</p>`);
3155
- else if (line.trim()) out.push(`<p>${line}</p>`);
3156
- }
3157
- if (list) out.push(`</${list}>`);
3158
- return out.join("").replace(/\u0000(\d+)\u0000/g, (m, i) => `<pre><code>${blocks[i]}</code></pre>`);
3159
- }
3160
- // -- AI page: several saved chats (this browser only), search, suggestions, pictures, daily usage --
3161
- const AI_CHATS_KEY = "rug-ai-chats", AI_USAGE_KEY = "rug-ai-usage", AI_DAILY = 100;
3162
- const AI_SUGGESTIONS = [
3163
- ["🍝", "What should I make for dinner?"], ["😂", "Tell me a joke"],
3164
- ["🎬", "Recommend a movie to watch"], ["💡", "Give me a fun fact"],
3165
- ];
3166
- function aiLoadChats() {
3167
- const old = store.get(AI_KEY, null); // the first version kept one chat; bring it over
3168
- let chats = store.get(AI_CHATS_KEY, []);
3169
- if (Array.isArray(old) && old.length && !chats.length) chats = [{ id: Date.now().toString(36), title: aiTitle(old[0].text), ts: Date.now(), messages: old }];
3170
- store.set(AI_KEY, null);
3171
- return Array.isArray(chats) ? chats : [];
3172
- }
3173
- function aiTitle(text) { const t = String(text || "").replace(/\s+/g, " ").trim(); return t.length > 40 ? t.slice(0, 40) + "…" : t || "New chat"; }
3174
- function aiSave() {
3175
- // pictures are kept for this visit only (they'd fill the browser's storage)
3176
- const slim = ai.chats.slice(0, 50).map((c) => ({ ...c, messages: c.messages.slice(-60).map(({ img, ...m }) => (img ? { ...m, hadImg: true } : m)) }));
3177
- store.set(AI_CHATS_KEY, slim);
3178
- }
3179
- const aiCurrent = () => ai.chats.find((c) => c.id === ai.currentId) || null;
3180
- // Usage: AI_DAILY messages a day on this device, starting fresh at midnight
3181
- function aiUsage() {
3182
- const today = new Date().toDateString(), u = store.get(AI_USAGE_KEY, {});
3183
- return u.day === today ? u : { day: today, used: 0 };
3184
- }
3185
- function renderAiUsage() {
3186
- const u = aiUsage(), left = Math.max(0, AI_DAILY - u.used);
3187
- $("ai-usage-used").textContent = `${u.used}/${AI_DAILY}`;
3188
- $("ai-usage-left").textContent = `${left} left`;
3189
- $("ai-usage-fill").style.width = `${Math.min(100, (u.used / AI_DAILY) * 100)}%`;
3190
- $("ai-foot").textContent = `${u.used}/${AI_DAILY} today · ${left} remaining · resets at midnight`;
3191
- }
3192
- function aiGroup(ts) {
3193
- const d = new Date(ts), now = new Date(), day = 86400000;
3194
- const start = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
3195
- return ts >= start ? "Today" : ts >= start - day ? "Yesterday" : ts >= start - 7 * day ? "Last 7 days" : "Older";
3196
- }
3197
- function renderAiChats() {
3198
- const q = $("ai-search").value.trim().toLowerCase();
3199
- const list = ai.chats.filter((c) => !q || c.title.toLowerCase().includes(q) || c.messages.some((m) => m.text.toLowerCase().includes(q)));
3200
- let html = "", last = "";
3201
- for (const c of list) {
3202
- const g = aiGroup(c.ts);
3203
- if (g !== last) { html += `<p class="ai-group">${g}</p>`; last = g; }
3204
- html += `<button class="ai-chat-item${c.id === ai.currentId ? " on" : ""}" type="button" data-chat="${escapeHtml(c.id)}">💬 <span>${escapeHtml(c.title)}</span></button>`;
3205
- }
3206
- $("ai-chats").innerHTML = html || `<p class="ai-group">${q ? "No chats match." : "No chats yet."}</p>`;
3207
- }
3208
- function renderAi() {
3209
- const ready = aiReady(), c = aiCurrent(), msgs = c?.messages || [];
3210
- $("ai-off").hidden = ready;
3211
- $("ai-form").hidden = !ready;
3212
- $("ai-title").textContent = c ? c.title : "New chat";
3213
- $("ai-delete").hidden = !c;
3214
- const log = $("ai-log");
3215
- if (!msgs.length) {
3216
- log.innerHTML = ready ? `<div class="ai-welcome"><h2>What can I help you with today?</h2><div class="ai-suggest">` +
3217
- AI_SUGGESTIONS.map(([icon, text]) => `<button type="button" data-suggest="${escapeHtml(text)}"><span aria-hidden="true">${icon}</span>${escapeHtml(text)}</button>`).join("") + `</div></div>` : "";
3218
- } else {
3219
- log.innerHTML = msgs.map((m) => m.role === "assistant"
3220
- ? `<div class="ai-msg assistant">${aiFormat(m.text)}${m.by ? `<span class="ai-by">${escapeHtml(m.by)}</span>` : ""}</div>`
3221
- : `<div class="ai-msg user">${m.img ? `<img class="ai-msg-img" src="${m.img}" alt="Picture you sent">` : m.hadImg ? `<p class="ai-img-note">📷 picture</p>` : ""}<p>${escapeHtml(m.text)}</p></div>`).join("");
3222
- if (ai.busy) log.insertAdjacentHTML("beforeend", `<div class="ai-msg assistant thinking"><span></span><span></span><span></span></div>`);
3223
- }
3224
- log.scrollTop = log.scrollHeight;
3225
- renderAiChats();
3226
- renderAiUsage();
3227
- }
3228
- async function sendAi(e, preset) {
3229
- e?.preventDefault();
3230
- const box = $("ai-input"), text = (preset ?? box.value).trim();
3231
- if ((!text && !ai.pendingImg) || ai.busy) return;
3232
- const u = aiUsage();
3233
- if (u.used >= AI_DAILY) { toast(`You've used all ${AI_DAILY} AI messages today. They reset at midnight.`); return; }
3234
- let c = aiCurrent();
3235
- if (!c) { c = { id: Date.now().toString(36), title: aiTitle(text || "Picture"), ts: Date.now(), messages: [] }; ai.chats.unshift(c); ai.currentId = c.id; }
3236
- c.messages.push({ role: "user", text: text.slice(0, 4000) || "What's in this picture?", ...(ai.pendingImg ? { img: ai.pendingImg } : {}) });
3237
- c.ts = Date.now();
3238
- ai.chats = [c, ...ai.chats.filter((x) => x !== c)]; // most recent chat on top
3239
- box.value = "";
3240
- clearAiPicture();
3241
- store.set(AI_USAGE_KEY, { day: u.day, used: u.used + 1 });
3242
- ai.busy = true;
3243
- renderAi();
3244
- try {
3245
- const reply = await askAi(c.messages.slice(-16)); // the last few turns, so it remembers the conversation
3246
- c.messages.push({ role: "assistant", text: reply.text, by: reply.by });
3247
- } catch {
3248
- c.messages.push({ role: "assistant", text: "The AI is busy right now (the free limits ran out). Try again in a bit." });
3249
- }
3250
- ai.busy = false;
3251
- aiSave();
3252
- renderAi();
3253
- box.focus();
3254
- }
3255
- async function pickAiPicture(file) {
3256
- if (!file || !/^image\//.test(file.type)) return;
3257
- try {
3258
- ai.pendingImg = await shrinkPhoto(await createImageBitmap(file));
3259
- $("ai-attach-img").src = ai.pendingImg;
3260
- $("ai-attach").hidden = false;
3261
- $("ai-input").focus();
3262
- } catch { toast("Couldn't read that picture."); }
3263
- }
3264
- function clearAiPicture() { ai.pendingImg = null; $("ai-attach").hidden = true; $("ai-attach-img").removeAttribute("src"); $("ai-pic-input").value = ""; }
3265
- function bindAi() {
3266
- ai.chats = aiLoadChats();
3267
- ai.currentId = null;
3268
- $("ai-form").addEventListener("submit", (e) => sendAi(e));
3269
- $("ai-input").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); $("ai-form").requestSubmit(); } });
3270
- $("ai-input").addEventListener("input", () => { const t = $("ai-input"); t.style.height = "auto"; t.style.height = Math.min(t.scrollHeight, 180) + "px"; });
3271
- $("ai-input").addEventListener("paste", (e) => { const f = [...(e.clipboardData?.files || [])].find((x) => x.type.startsWith("image/")); if (f) { e.preventDefault(); pickAiPicture(f); } });
3272
- $("ai-new").addEventListener("click", () => { ai.currentId = null; renderAi(); $("ai-input").focus(); });
3273
- $("ai-chats").addEventListener("click", (e) => { const b = e.target.closest("[data-chat]"); if (b) { ai.currentId = b.dataset.chat; renderAi(); } });
3274
- $("ai-search").addEventListener("input", renderAiChats);
3275
- $("ai-delete").addEventListener("click", () => {
3276
- const c = aiCurrent();
3277
- if (!c || !confirm(`Delete “${c.title}”?`)) return;
3278
- ai.chats = ai.chats.filter((x) => x !== c); ai.currentId = null; aiSave(); renderAi();
3279
- });
3280
- $("ai-log").addEventListener("click", (e) => { const b = e.target.closest("[data-suggest]"); if (b) sendAi(null, b.dataset.suggest); });
3281
- $("ai-pic").addEventListener("click", () => $("ai-pic-input").click());
3282
- $("ai-pic-input").addEventListener("change", () => pickAiPicture($("ai-pic-input").files[0]));
3283
- $("ai-attach-x").addEventListener("click", clearAiPicture);
3284
- const phone = () => innerWidth <= 800; // on phones the list slides over the chat, so it starts closed
3285
- const side = (open) => { $("ai-app").classList.toggle("side-closed", !open); if (!phone()) store.set("rug-ai-side", open); };
3286
- $("ai-collapse").addEventListener("click", () => side(false));
3287
- $("ai-expand").addEventListener("click", () => side(true));
3288
- for (const id of ["ai-new", "ai-chats"]) $(id).addEventListener("click", (e) => { if (phone() && e.target.closest("button")) side(false); });
3289
- side(!phone() && store.get("rug-ai-side", true));
3290
- }
3291
-
3292
3440
  // ---------- Emoji picker ----------
3293
3441
  const EMOJI_GROUPS = [
3294
3442
  ["😀", "😀😃😄😁😆😅😂🤣🥲😊😇🙂🙃😉😌😍🥰😘😋😛😜🤪😝🤑🤗🤭🤫🤔🤐🤨😐😑😶😏😒🙄😬😮‍💨🤥😴🤤😪😮😯😲🥱😳🥺😢😭😤😠😡🤯😱😨😰🥶🥵😵‍💫🤠🥳😎🤓🧐😈👻💀☠️🤡💩🤖👽"],
@@ -3411,9 +3559,9 @@
3411
3559
  const app = await getFirebase();
3412
3560
  if (!app || !chat.uid || !chatSender()) return false;
3413
3561
  const db = app.database(), TS = window.firebase.database.ServerValue.TIMESTAMP;
3414
- const id = db.ref("chat/media").push().key;
3562
+ const id = db.ref(roomPath("media")).push().key;
3415
3563
  try {
3416
- await db.ref().update({ [`chat/media/${id}`]: { data, uid: chat.uid, ts: TS }, [`chat/mediaLast/${chat.uid}`]: TS });
3564
+ await db.ref().update({ [roomPath(`media/${id}`)]: { data, uid: chat.uid, ts: TS }, [`chat/mediaLast/${chat.uid}`]: TS });
3417
3565
  } catch {
3418
3566
  chatNote(blockedReason() || "Wait a few seconds between videos and voice notes.", true);
3419
3567
  return false;
@@ -3511,7 +3659,7 @@
3511
3659
  async function playMedia(btn, kind) {
3512
3660
  btn.disabled = true;
3513
3661
  try {
3514
- const snap = await (await getFirebase()).database().ref(`chat/media/${btn.dataset.media}`).once("value");
3662
+ const snap = await (await getFirebase()).database().ref(roomPath(`media/${btn.dataset.media}`)).once("value");
3515
3663
  const data = snap.val()?.data;
3516
3664
  if (typeof data !== "string" || !/^data:(video|audio)\/(webm|mp4|ogg)/.test(data)) throw new Error("gone");
3517
3665
  const el = document.createElement(kind === "voice" ? "audio" : "video");
@@ -3872,6 +4020,14 @@
3872
4020
  const el = els.frame;
3873
4021
  (el.requestFullscreen || el.webkitRequestFullscreen)?.call(el);
3874
4022
  });
4023
+ // "#…" links: with a <base> tag (.svg version) the browser would open the package folder instead
4024
+ document.addEventListener("click", (e) => {
4025
+ const link = e.target.closest?.('a[href^="#"]');
4026
+ if (!link || link.dataset.nav || e.defaultPrevented) return;
4027
+ e.preventDefault();
4028
+ const hash = link.getAttribute("href");
4029
+ if (hash.length > 1) location.hash = hash;
4030
+ });
3875
4031
  window.addEventListener("hashchange", () => route());
3876
4032
  window.addEventListener("popstate", () => route());
3877
4033
  }
@@ -3953,6 +4109,7 @@
3953
4109
  boot.fill.style.width = "100%";
3954
4110
  if (text) boot.msg.textContent = text;
3955
4111
  setTimeout(() => boot.el.classList.add("done"), 120);
4112
+ setTimeout(() => { boot.el.hidden = true; }, 600); // gone for good once it has faded, so nothing in it keeps running
3956
4113
  }
3957
4114
 
3958
4115
  // When opened from a versioned unpkg link (e.g. an old bookmark), jump to the newest version.
@@ -4007,11 +4164,11 @@
4007
4164
  $("chat-log").addEventListener("click", mentionFromName);
4008
4165
  bindAdmin();
4009
4166
  bindChatTools();
4167
+ bindRooms();
4010
4168
  bindChatExtras();
4011
4169
  bindChatMedia();
4012
4170
  bindPolls();
4013
4171
  bindQuotes();
4014
- bindAi();
4015
4172
  bindTrivia();
4016
4173
  bindReports();
4017
4174
  startAnalytics();