Files
threshing-atlas/dice.js
T

98 lines
5.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* Rolls of the dice. Wherever the page shows a step the game decides at random (not the rider's choice), a pair of
* dice sits next to it. Clicking the dice shows the odds of every outcome of that roll.
*
* Dice.html(roll) an inline button for HTML text
* Dice.svg(parent, x, y, roll) the same glyph inside an SVG map
* Dice.legend(text?) the legend line ("a roll: the game decides ...")
*
* roll = { title, options: [[label, p], ...], note?, n? } (p between 0 and 1; options may be empty with a note)
*/
(function () {
"use strict";
const NS = "http://www.w3.org/2000/svg";
// two dice, the back one showing two, the front one five
const GLYPH = `<svg class="dice-glyph" viewBox="0 0 22 16" width="22" height="16" aria-hidden="true">
<rect x="1" y="1.5" width="10" height="10" rx="2.2" transform="rotate(-12 6 6.5)" fill="var(--raised)" stroke="currentColor" stroke-width="1.2"/>
<circle cx="4" cy="4.8" r="1.05" fill="currentColor" transform="rotate(-12 6 6.5)"/><circle cx="8" cy="8.6" r="1.05" fill="currentColor" transform="rotate(-12 6 6.5)"/>
<rect x="9.5" y="4.5" width="10.5" height="10.5" rx="2.2" fill="var(--raised)" stroke="currentColor" stroke-width="1.2"/>
<circle cx="12.4" cy="7.4" r="1.05" fill="currentColor"/><circle cx="17.1" cy="7.4" r="1.05" fill="currentColor"/>
<circle cx="14.75" cy="9.75" r="1.05" fill="currentColor"/>
<circle cx="12.4" cy="12.1" r="1.05" fill="currentColor"/><circle cx="17.1" cy="12.1" r="1.05" fill="currentColor"/></svg>`;
const TIP = "A roll: the game decides, not you. Click for the odds of each outcome.";
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const pack = (roll) => encodeURIComponent(JSON.stringify(roll || {}));
const pct = (p) => (p == null ? "–" : p < 0.001 && p > 0 ? "<0.1%" : `${(100 * p).toFixed(p < 0.1 ? 1 : 0)}%`);
function html(roll) {
return `<button type="button" class="dice" data-roll="${pack(roll)}" title="${TIP}" aria-label="${esc((roll && roll.title) || "A roll")}: show the odds">${GLYPH}</button>`;
}
function svg(parent, x, y, roll) {
const g = document.createElementNS(NS, "g");
g.setAttribute("class", "dice dice-svg");
g.setAttribute("data-roll", pack(roll));
g.setAttribute("transform", `translate(${x - 11},${y - 8})`);
g.setAttribute("tabindex", "0");
g.setAttribute("role", "button");
g.setAttribute("aria-label", `${(roll && roll.title) || "A roll"}: show the odds`);
const t = document.createElementNS(NS, "title");
t.textContent = TIP;
g.appendChild(t);
const halo = document.createElementNS(NS, "rect");
for (const [k, v] of Object.entries({ x: -3, y: -3, width: 28, height: 22, rx: 6, fill: "var(--map-halo, var(--bg))", "fill-opacity": 0.9 })) halo.setAttribute(k, v);
g.appendChild(halo);
g.insertAdjacentHTML("beforeend", GLYPH.replace(/^<svg[^>]*>/, "").replace(/<\/svg>$/, ""));
parent.appendChild(g);
return g;
}
function legend(text) {
return `<span class="dice-legend">${GLYPH.replace('class="dice-glyph"', 'class="dice-glyph legend" style="display:inline-block;vertical-align:-3px"')} ${text || "= a roll: the game decides at random, not your choice. Click any dice for the odds of each outcome."}</span>`;
}
// ---- the popover
let pop = null;
function hide() { if (pop) pop.hidden = true; }
function show(roll, x, y) {
if (!pop) {
pop = document.createElement("div");
pop.id = "dice-pop";
pop.setAttribute("role", "dialog");
document.body.appendChild(pop);
}
const opts = (roll.options || []).filter(([, p]) => p != null).sort((a, b) => b[1] - a[1]);
pop.innerHTML = `<b>${esc(roll.title || "A roll")}</b>
${opts.length ? `<ul>${opts.map(([k, p]) => `<li><span>${esc(k)}</span><span class="bar"><i style="width:${Math.max(1, 100 * p).toFixed(1)}%"></i></span><span class="p">${pct(p)}</span></li>`).join("")}</ul>` : ""}
<p>${esc(roll.note || "The game decides this at random. Your earlier choices can change the odds, but not the outcome.")}${roll.n ? ` From ${Number(roll.n).toLocaleString()} runs.` : ""}</p>`;
pop.hidden = false;
const r = pop.getBoundingClientRect();
pop.style.left = `${Math.max(8, Math.min(window.innerWidth - r.width - 8, x - r.width / 2))}px`;
pop.style.top = `${y + 14 + r.height > window.innerHeight ? Math.max(8, y - r.height - 14) : y + 14}px`;
}
function open(e, t) {
e.preventDefault();
e.stopPropagation();
let roll = {};
try { roll = JSON.parse(decodeURIComponent(t.getAttribute("data-roll"))); } catch { /* an empty roll */ }
const b = t.getBoundingClientRect();
show(roll, b.left + b.width / 2, b.bottom - 6);
}
// capture phase: a dice inside a map or a card must not also select what is under it
document.addEventListener("click", (e) => {
const t = e.target.closest && e.target.closest("[data-roll]");
if (t) return open(e, t);
if (pop && !pop.hidden && !pop.contains(e.target)) hide();
}, true);
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") return hide();
const t = (e.key === "Enter" || e.key === " ") && e.target.closest && e.target.closest(".dice-svg[data-roll]");
if (t) open(e, t);
}, true);
window.addEventListener("scroll", hide, { passive: true });
window.Dice = { html, svg, legend };
})();