Files
org_web/assets/scripts/pages/play.js
gitea-actions 7afc554f5d
All checks were successful
Build Org Website / build (push) Successful in 44s
Refactor org web content and simplify shared UI
2026-07-29 15:17:17 +01:00

463 lines
18 KiB
JavaScript
Executable File

(function () {
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
const shuffle = (items) => items.map((value) => ({ value, sort: Math.random() })).sort((a, b) => a.sort - b.sort).map((item) => item.value);
const quips = [
"A margin note blinks, then pretends it did not.",
"Somewhere, a bookmark changes its mind.",
"The archive is pleased by unnecessary curiosity.",
"A tiny bell rings in a room you have not built yet.",
"The page remembers that you came here."
];
document.addEventListener("DOMContentLoaded", () => {
const root = $(".play-root[data-play-page]");
if (!root) return;
const page = root.dataset.playPage;
const inits = { hub, memory, constellation, poem, bookshelf, ink, terminal, study, sigil };
if (inits[page]) inits[page](root);
});
function hub(root) {
const links = $$(".play-grid a", root);
const nodes = $$(".play-orbit__node", root);
const title = $("#play-hub-title", root);
const kind = $("#play-hub-kind", root);
const desc = $("#play-hub-desc", root);
const cta = $("#play-hub-link", root);
const whisper = document.createElement("p");
let active = 0;
whisper.className = "play-whisper";
whisper.setAttribute("aria-live", "polite");
$(".play-console__screen", root).appendChild(whisper);
nodes.forEach((node, index) => {
const angle = (index / nodes.length) * Math.PI * 2 - Math.PI / 2;
node.style.left = `${50 + Math.cos(angle) * 43}%`;
node.style.top = `${50 + Math.sin(angle) * 43}%`;
node.addEventListener("click", () => setActive(index));
});
function setActive(index) {
active = (index + links.length) % links.length;
const link = links[active];
links.forEach((item, i) => item.classList.toggle("is-active", i === active));
nodes.forEach((item, i) => item.classList.toggle("is-active", i === active));
title.textContent = link.querySelector("strong").textContent;
kind.textContent = link.dataset.kind;
desc.textContent = link.dataset.desc;
cta.href = link.href;
whisper.textContent = quips[active % quips.length];
}
links.forEach((link, index) => {
link.addEventListener("mouseenter", () => setActive(index));
link.addEventListener("focus", () => setActive(index));
});
$("[data-play-prev]", root).addEventListener("click", () => setActive(active - 1));
$("[data-play-next]", root).addEventListener("click", () => setActive(active + 1));
$("[data-play-random]", root).addEventListener("click", () => setActive(Math.floor(Math.random() * links.length)));
$(".play-orbit", root).addEventListener("dblclick", () => {
whisper.textContent = "You knocked twice. The cabinet knocked once back.";
root.classList.toggle("is-odd");
});
root.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") setActive(active - 1);
if (event.key === "ArrowRight") setActive(active + 1);
});
setActive(0);
}
function memory(root) {
const symbols = ["Ink", "Lamp", "Tea", "Book", "Map", "Key"];
const board = $("[data-memory-board]", root);
const turnsEl = $("[data-memory-turns]", root);
const matchesEl = $("[data-memory-matches]", root);
const messageEl = $("[data-memory-message]", root);
let open = [];
let turns = 0;
let matches = 0;
let deck = [];
function render() {
board.innerHTML = "";
open = [];
turns = 0;
matches = 0;
deck = shuffle([...symbols, ...symbols]);
turnsEl.textContent = "0";
matchesEl.textContent = "0";
messageEl.textContent = "Cards are shuffled.";
deck.forEach((symbol, index) => {
const card = document.createElement("button");
card.type = "button";
card.className = "memory-card";
card.dataset.symbol = symbol;
card.textContent = "?";
card.style.setProperty("--tilt", `${(index % 5) - 2}deg`);
card.setAttribute("aria-label", "Hidden card");
card.addEventListener("click", () => flip(card));
board.appendChild(card);
});
}
function flip(card) {
if (card.classList.contains("is-open") || card.classList.contains("is-matched") || open.length === 2) return;
card.classList.add("is-open");
card.textContent = card.dataset.symbol;
card.setAttribute("aria-label", card.dataset.symbol);
open.push(card);
if (open.length !== 2) return;
turns += 1;
turnsEl.textContent = String(turns);
const [a, b] = open;
if (a.dataset.symbol === b.dataset.symbol) {
a.classList.add("is-matched");
b.classList.add("is-matched");
open = [];
matches += 1;
matchesEl.textContent = String(matches);
messageEl.textContent = matches === symbols.length ? `Cabinet solved in ${turns} turns.` : "A drawer clicks open.";
} else {
messageEl.textContent = "No match. The cabinet quietly re-files them.";
setTimeout(() => {
a.classList.remove("is-open");
b.classList.remove("is-open");
a.textContent = "?";
b.textContent = "?";
a.setAttribute("aria-label", "Hidden card");
b.setAttribute("aria-label", "Hidden card");
open = [];
}, 650);
}
}
$("[data-memory-reset]", root).addEventListener("click", render);
$("[data-memory-peek]", root).addEventListener("click", () => {
const hidden = $$(".memory-card:not(.is-open):not(.is-matched)", root);
hidden.forEach((card) => {
card.textContent = card.dataset.symbol;
card.classList.add("is-peeking");
});
messageEl.textContent = "A very brief lapse in scholarly discipline.";
setTimeout(() => {
hidden.forEach((card) => {
if (!card.classList.contains("is-open") && !card.classList.contains("is-matched")) card.textContent = "?";
card.classList.remove("is-peeking");
});
}, 900);
});
render();
}
function constellation(root) {
const canvas = $("[data-star-canvas]", root);
const ctx = canvas.getContext("2d");
const linesEl = $("[data-star-lines]", root);
const nameEl = document.createElement("strong");
const stars = Array.from({ length: 18 }, () => ({ x: 50 + Math.random() * 800, y: 45 + Math.random() * 430 }));
const lines = [];
let selected = null;
nameEl.className = "play-live-note";
linesEl.closest(".play-scorebar").appendChild(nameEl);
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#18130f";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "rgba(219, 184, 104, 0.65)";
ctx.lineWidth = 2;
lines.forEach(([a, b]) => {
ctx.beginPath();
ctx.moveTo(stars[a].x, stars[a].y);
ctx.lineTo(stars[b].x, stars[b].y);
ctx.stroke();
});
stars.forEach((star, index) => {
ctx.beginPath();
ctx.fillStyle = index === selected ? "#f6d889" : "#fff8e8";
ctx.arc(star.x, star.y, index === selected ? 7 : 4, 0, Math.PI * 2);
ctx.fill();
});
linesEl.textContent = String(lines.length);
if (lines.length >= 3) nameEl.textContent = `Named: ${pick(["The Patient Spoon", "The South Window", "The Tired Comet", "The Fifth Errand"])}`;
}
canvas.addEventListener("click", (event) => {
const rect = canvas.getBoundingClientRect();
const x = ((event.clientX - rect.left) / rect.width) * canvas.width;
const y = ((event.clientY - rect.top) / rect.height) * canvas.height;
const hit = stars.findIndex((star) => Math.hypot(star.x - x, star.y - y) < 22);
if (hit < 0) return;
if (selected === null) selected = hit;
else if (selected !== hit) {
lines.push([selected, hit]);
selected = hit;
}
draw();
});
$("[data-star-reset]", root).addEventListener("click", () => {
lines.length = 0;
selected = null;
nameEl.textContent = "";
draw();
});
draw();
}
function poem(root) {
const output = $("[data-poem-output]", root);
const a = ["In the margin", "By the kettle", "Under the desk lamp", "Between two errands", "After the house quiets"];
const b = ["a careful thought", "an old joke", "a stubborn question", "a useful mistake", "a bright scrap"];
const c = ["learns to wait.", "asks for a second reading.", "finds its proper shelf.", "becomes tomorrow's note.", "keeps the page warm."];
let count = 0;
function make() {
count += 1;
output.innerHTML = `${pick(a)}<br>${pick(b)}<br>${pick(c)}`;
output.dataset.stamp = count % 5 === 0 ? "approved by the margin" : "";
}
$("[data-poem-generate]", root).addEventListener("click", make);
make();
}
function bookshelf(root) {
const titles = ["Algebra at Breakfast", "Cabinet of Weather", "Domestic Orbits", "Evening Margins", "Household Engines", "Zettels and Tea"];
const shelf = $("[data-bookshelf]", root);
const status = $("[data-bookshelf-status]", root);
let sortedOnce = false;
setupSortable(shelf, render, check);
$("[data-bookshelf-shuffle]", root).addEventListener("click", () => render(shuffle(titles)));
render(shuffle(titles));
function render(items) {
shelf.innerHTML = "";
items.forEach((title) => {
const book = document.createElement("div");
book.className = "book-spine";
book.draggable = true;
book.dataset.value = title;
book.textContent = title;
shelf.appendChild(book);
});
check();
}
function check() {
const current = $$(".book-spine", shelf).map((book) => book.dataset.value);
const sorted = current.join("|") === titles.join("|");
status.textContent = sorted ? "Shelf sorted. A secret pamphlet slides out." : "Unsorted";
if (sorted && !sortedOnce) {
sortedOnce = true;
const pamphlet = document.createElement("div");
pamphlet.className = "booklet";
pamphlet.textContent = "Pamphlet: On the Correct Order of Small Things";
shelf.appendChild(pamphlet);
}
}
}
function ink(root) {
const canvas = $("[data-ink-canvas]", root);
const ctx = canvas.getContext("2d");
const drops = [];
let moon = false;
function addDrop(x, y, heavy) {
drops.push({ x, y, r: heavy ? 18 : 8, life: heavy ? 1.8 : 1, hue: 28 + Math.random() * 35 });
}
function pointer(event, heavy) {
const rect = canvas.getBoundingClientRect();
addDrop(((event.clientX - rect.left) / rect.width) * canvas.width, ((event.clientY - rect.top) / rect.height) * canvas.height, heavy);
}
canvas.addEventListener("pointermove", (event) => pointer(event, false));
canvas.addEventListener("click", (event) => pointer(event, true));
canvas.addEventListener("dblclick", () => {
moon = !moon;
});
function frame() {
ctx.fillStyle = "rgba(24, 19, 15, 0.16)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (moon) {
ctx.beginPath();
ctx.fillStyle = "rgba(246, 216, 137, 0.72)";
ctx.arc(760, 88, 34, 0, Math.PI * 2);
ctx.fill();
}
drops.forEach((drop) => {
drop.r += 0.7;
drop.life -= 0.012;
ctx.beginPath();
ctx.strokeStyle = `hsla(${drop.hue}, 65%, 68%, ${Math.max(drop.life, 0)})`;
ctx.lineWidth = 2;
ctx.arc(drop.x, drop.y, drop.r, 0, Math.PI * 2);
ctx.stroke();
});
for (let i = drops.length - 1; i >= 0; i -= 1) if (drops[i].life <= 0) drops.splice(i, 1);
requestAnimationFrame(frame);
}
frame();
}
function terminal(root) {
const log = $("[data-terminal-log]", root);
const form = $("[data-terminal-form]", root);
const input = $("[data-terminal-input]", root);
let kindness = 0;
const responses = {
help: "Commands: help, look, map, open drawer, read note, brew tea, hum, knock, save, inventory, clear",
look: "A narrow archive room. A lamp hums. A drawer is labelled MAYBE IMPORTANT.",
map: "You are between the reading desk, the family shelf, and the door back to Play.",
"open drawer": "Inside: a brass key, a receipt, and a note folded twice.",
"read note": "The note says: keep the site useful, but leave a few doors ajar.",
"brew tea": "The room smells briefly of cardamom. Nothing else changes, which is enough.",
hum: "You hum four careful notes. Something behind the wall hums five back.",
knock: "Knock. Knock. ... A polite pause. Knock.",
save: "You save your place in the archive. The archive saves its place in you.",
inventory: "You are carrying: a brass key, a warm cup, and one unreasonable hope."
};
function write(text) {
log.textContent += `${text}\n`;
log.scrollTop = log.scrollHeight;
}
form.addEventListener("submit", (event) => {
event.preventDefault();
const cmd = input.value.trim().toLowerCase();
if (!cmd) return;
input.value = "";
if (cmd === "clear") {
log.textContent = "";
return;
}
write(`> ${cmd}`);
if (cmd === "pet book") {
kindness += 1;
write(kindness > 2 ? "The book follows you for exactly three pages." : "The book accepts this with suspicious dignity.");
} else {
write(responses[cmd] || "The archive declines to understand that command.");
}
});
write("Archive terminal ready. Type help. The cursor is listening.");
input.focus();
}
function study(root) {
const time = $("[data-study-time]", root);
const scene = $("[data-study-scene]", root);
let total = 300;
let left = total;
let timer = null;
const note = document.createElement("div");
note.className = "play-live-note";
note.textContent = "The lamp is cold.";
time.insertAdjacentElement("afterend", note);
function draw() {
const done = 1 - left / total;
scene.style.setProperty("--lamp", String(0.18 + done * 0.72));
scene.style.setProperty("--glow", `${done * 70}px`);
const m = String(Math.floor(left / 60)).padStart(2, "0");
const s = String(left % 60).padStart(2, "0");
time.textContent = `${m}:${s}`;
if (left === 0) note.textContent = "Focus complete. The desk looks proud.";
else if (done > 0.66) note.textContent = "The page has warmed through.";
else if (done > 0.33) note.textContent = "The lamp has settled into its work.";
}
function start() {
if (timer) return;
timer = setInterval(() => {
left = Math.max(0, left - 1);
draw();
if (left === 0) pause();
}, 1000);
}
function pause() {
clearInterval(timer);
timer = null;
}
$("[data-study-start]", root).addEventListener("click", start);
$("[data-study-pause]", root).addEventListener("click", pause);
$("[data-study-reset]", root).addEventListener("click", () => {
pause();
left = total;
draw();
});
draw();
}
function sigil(root) {
const canvas = $("[data-sigil-canvas]", root);
const ctx = canvas.getContext("2d");
const initials = $("[data-sigil-initials]", root);
const motto = $("[data-sigil-motto]", root);
let wax = "#9c6b2f";
const waxButton = document.createElement("button");
waxButton.type = "button";
waxButton.textContent = "New wax";
$("[data-sigil-form]", root).appendChild(waxButton);
function draw() {
const text = (initials.value || "ZXH").toUpperCase();
const phrase = motto.value || "Learn, make, remember";
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#fbf7ec";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.translate(260, 260);
ctx.strokeStyle = wax;
ctx.lineWidth = 10;
ctx.beginPath();
ctx.arc(0, 0, 190, 0, Math.PI * 2);
ctx.stroke();
ctx.lineWidth = 2;
for (let i = 0; i < 12; i += 1) {
ctx.rotate(Math.PI / 6);
ctx.beginPath();
ctx.moveTo(0, -150);
ctx.lineTo(0, -185);
ctx.stroke();
}
ctx.rotate(-Math.PI * 2);
ctx.fillStyle = "#2a2118";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "900 94px Georgia, serif";
ctx.fillText(text.slice(0, 4), 0, -10);
ctx.font = "700 22px Georgia, serif";
ctx.fillText(phrase.slice(0, 34), 0, 88);
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
waxButton.addEventListener("click", () => {
wax = pick(["#9c6b2f", "#8a3f3f", "#486b57", "#3e5f8a", "#5f4b8b"]);
draw();
});
$("[data-sigil-form]", root).addEventListener("submit", (event) => {
event.preventDefault();
draw();
});
initials.addEventListener("input", draw);
motto.addEventListener("input", draw);
draw();
}
function setupSortable(container, _render, after) {
let dragged = null;
container.addEventListener("dragstart", (event) => {
dragged = event.target.closest("[draggable='true']");
if (dragged) event.dataTransfer.effectAllowed = "move";
});
container.addEventListener("dragover", (event) => {
event.preventDefault();
const target = event.target.closest("[draggable='true']");
if (!dragged || !target || target === dragged) return;
const rect = target.getBoundingClientRect();
const before = event.clientY < rect.top + rect.height / 2 || event.clientX < rect.left + rect.width / 2;
container.insertBefore(dragged, before ? target : target.nextSibling);
after();
});
container.addEventListener("dragend", () => {
dragged = null;
after();
});
}
function pick(items) {
return items[Math.floor(Math.random() * items.length)];
}
})();