primordial-soup/viewer/water-preview.js

121 lines
5.9 KiB
JavaScript

import "./water-preview.css";
import { mountGame } from "./ui.js";
import { prepared } from "./tutorials.js";
import { stripSecret } from "../engine/index.js";
// These alternatives are only loaded by the local preview entry point.
const styles = [
["bubbles", "Bubbles only", "Just the drifting bubbles."],
["light", "Soft light", "Broad, gentle reflections."],
["trails", "Fine trails", "Short strokes carried by the current."],
["ripples", "Ripples", "Paired, curved wavelets."],
];
export function mountWaterPreview(target, params) {
const state = prepared({ players: 6, round: 3 });
state.players.forEach((p, i) => {
p.name = ["You", "Maya", "Leo", "Nina", "Sam", "Alex"][i];
p.score = 6 - i;
});
state.amoebas = [[6, 21], [8, 16], [18], [23], [7], [14]].flatMap(
(cells, p) =>
cells.map((cell, i) => ({
id: `${p}-${i + 1}`,
p,
n: i + 1,
cell,
hp: 0,
})),
);
const requestedDirection = Number(params.get("direction") ?? 2);
state.environment.direction = [0, 1, 2, 3, 4].includes(requestedDirection)
? requestedDirection
: 2;
const ui = mountGame(target);
ui.setPlayer(0);
ui.setEnabled(false);
const root = target.querySelector(".soup");
root.classList.add("water-study");
root.dataset.waterOrientation =
params.get("orientation") === "perpendicular"
? "perpendicular"
: "horizontal";
const controls = document.createElement("section");
controls.className = "water-controls";
controls.setAttribute("aria-label", "Water animation comparison");
controls.innerHTML = `<div class="water-controls-heading"><div><h2>Water motion</h2><p>Same bubbles, four finishes. Select one to compare.</p></div><div class="water-playback"><label>Current <select aria-label="Preview current">${["← West", "↑ North", "→ East", "↓ South", "· Still"].map((label, i) => `<option value="${i}" ${i === state.environment.direction ? "selected" : ""}>${label}</option>`).join("")}</select></label><label>Orientation <select aria-label="Water orientation"><option value="perpendicular">Perpendicular to current</option><option value="horizontal">Always horizontal</option></select></label><button type="button" data-pause aria-pressed="false">Pause motion</button></div></div><div class="water-options" role="group" aria-label="Water style">${styles.map(([id, title, description], i) => `<button type="button" data-water-choice="${id}" aria-pressed="false"><span class="water-option-number">${i + 1}</span><span><strong>${title}</strong><small>${description}</small></span></button>`).join("")}</div><p class="water-reduced-note">Your reduced-motion setting is on, so the animation is stopped.</p>`;
const orientationSelect = controls.querySelector(
'[aria-label="Water orientation"]',
);
orientationSelect.value = root.dataset.waterOrientation;
root.querySelector(".topbar").after(controls);
function render() {
ui.render(stripSecret(state, 0));
}
render();
const svg = root.querySelector("#pond-art");
svg.querySelectorAll(".pond-flow").forEach((flow) => flow.remove());
svg
.querySelector("defs")
.insertAdjacentHTML(
"beforeend",
`<linearGradient id="water-preview-trail"><stop stop-color="#f0ffe9" stop-opacity="0"/><stop offset=".65" stop-color="#f0ffe9" stop-opacity=".8"/><stop offset="1" stop-color="#f0ffe9" stop-opacity="0"/></linearGradient>`,
);
const reflections = document.createElementNS(
"http://www.w3.org/2000/svg",
"g",
);
reflections.innerHTML = Array.from({ length: 14 }, (_, n) => {
const x = 100 + ((n * 193) % 730),
y = 90 + ((n * 127) % 470);
const timing = `--delay:-${n * 1.7}s;--flow-duration:${18 + (n % 4) * 2}s`;
return `<g transform="translate(${x} ${y})"><g class="pond-flow water-light" style="${timing}"><ellipse class="pond-ripple" rx="${70 + (n % 3) * 12}" ry="32" fill="url(#soup-light)"/></g><g class="pond-flow water-trail" style="${timing}"><path class="pond-ripple" d="M-25 1Q-2-4 26 0" fill="none" stroke="url(#water-preview-trail)" stroke-width="1.5" stroke-linecap="round"/></g><g class="pond-flow water-ripple" style="${timing}"><path class="pond-ripple" d="M-16 1q8-4 16 0t16 0M-6 6q6-2 12 0" fill="none" stroke="#f0ffe9" stroke-width="1.3" stroke-linecap="round"/></g></g>`;
}).join("");
const water = svg.querySelector('g[clip-path="url(#soup-pond-clip)"]');
water.insertBefore(reflections, water.querySelector(".grid-lines"));
function updateUrl() {
const url = new URL(location.href);
url.searchParams.set("style", root.dataset.waterStyle);
url.searchParams.set("direction", state.environment.direction);
url.searchParams.set("orientation", root.dataset.waterOrientation);
history.replaceState(null, "", url);
}
function selectStyle(style) {
root.dataset.waterStyle = style;
for (const button of controls.querySelectorAll("[data-water-choice]"))
button.setAttribute(
"aria-pressed",
String(button.dataset.waterChoice === style),
);
updateUrl();
}
selectStyle(
styles.some(([id]) => id === params.get("style"))
? params.get("style")
: "light",
);
controls.addEventListener("click", (event) => {
const choice = event.target.closest("[data-water-choice]");
if (choice) selectStyle(choice.dataset.waterChoice);
const pause = event.target.closest("[data-pause]");
if (pause) {
const paused = root.dataset.motion !== "paused";
root.dataset.motion = paused ? "paused" : "playing";
pause.setAttribute("aria-pressed", String(paused));
pause.textContent = paused ? "Resume motion" : "Pause motion";
}
});
controls
.querySelector('[aria-label="Preview current"]')
.addEventListener("change", (event) => {
state.environment.direction = Number(event.target.value);
render();
updateUrl();
});
orientationSelect.addEventListener("change", () => {
root.dataset.waterOrientation = orientationSelect.value;
updateUrl();
});
}