V1.26.0: dice that tumble, rolled by the server, seen by the DM

- Each die is drawn as its own shape, tumbles in and lands on its result;
  a natural 20 glows, a natural 1 shakes; respects reduced motion
- In a campaign the server makes every digital roll and keeps it
- The DM sees each roll as it lands: an "Everyone's rolls" tab in the
  roller, a pop-up beside the dice button, and a list on the encounter page
- Players see everyone's rolls or only their own, by the campaign setting;
  the DM can roll hidden
- Physical dice are typed in, one box per die, and checked; with "both",
  each person chooses in the roller
- game/dice.js: parsing, rolling, checking typed dice, critical damage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 08:46:22 +02:00
co-authored by Claude Opus 5.5
parent c3f2b0dfa7
commit 8811f14732
22 changed files with 1345 additions and 167 deletions
+361 -145
View File
@@ -1,10 +1,21 @@
import { useEffect, useRef, useState } from 'react';
import { fmtMod } from '../lib/format';
import { useCampaign, useRoll, useRolls } from '../api/queries';
import { useAuth } from '../auth/useAuth';
import { useLastCampaignId } from '../lib/lastCampaign';
import { extractErrorMessage, fmtMod } from '../lib/format';
import { onRollRequest, parseDice, rollD20, rollDie, type RollMode, type RollRequest } from '../lib/diceRoller';
import { DiceRow } from './dice/Die';
import { settleMs } from '../lib/diceAnimation';
import { RollFeed, RollLine } from './RollFeed';
import { NumberInput } from './NumberInput';
import type { DiceRollRecord, RollSpec, RolledDie } from '../api/types';
const DICE = [4, 6, 8, 10, 12, 20, 100];
const MAX_DICE = 20;
const HISTORY_LENGTH = 8;
// How long another player's roll stays up beside the dice button.
const INCOMING_MS = 6000;
const BY_HAND_KEY = 'dice-by-hand';
const MODES: { mode: RollMode; label: string; title: string }[] = [
{ mode: 'DISADVANTAGE', label: 'Disadv.', title: 'Disadvantage: roll two d20s and keep the lower' },
@@ -12,77 +23,164 @@ const MODES: { mode: RollMode; label: string; title: string }[] = [
{ mode: 'ADVANTAGE', label: 'Adv.', title: 'Advantage: roll two d20s and keep the higher' },
];
interface Roll {
id: number;
label?: string; // what it was for, when it was asked for from a sheet
notation: string; // "1d20+3", "1d8+1d6+2"
dice: number[]; // every die rolled, in order
modifier: number;
total: number;
// The d20 that counted, for a roll of a single d20 (a natural 20 or 1 means something).
natural: number | null;
mode: RollMode; // how a single d20 was rolled
}
function notation(count: number, sides: number, modifier: number): string {
return `${count}d${sides}${modifier ? fmtMod(modifier) : ''}`;
}
// A d20 plus a bonus, with advantage or disadvantage as chosen.
function d20Roll(modifier: number, mode: RollMode, label?: string): Omit<Roll, 'id'> {
const { kept, dice } = rollD20(mode);
return { label, notation: notation(1, 20, modifier), dice, modifier, total: kept + modifier, natural: kept, mode };
// What a spec is written as: "1d20+3", "2d6+1".
function specNotation(spec: RollSpec): string {
return spec.kind === 'check' ? notation(1, 20, spec.modifier ?? 0) : (spec.expression ?? '').replace(/\s+/g, '');
}
// What a request from a sheet comes to; null for dice that cannot be read.
function answer(request: RollRequest, mode: RollMode): Omit<Roll, 'id'> | null {
if (request.kind === 'check') return d20Roll(request.modifier, mode, request.label);
const parsed = parseDice(request.expression);
if (!parsed) return null;
const dice: number[] = [];
let total = parsed.flat;
for (const term of parsed.dice) {
for (let i = 0; i < term.count; i++) {
const die = rollDie(term.sides);
dice.push(die);
total += term.sign * die;
}
// The size of each die a spec rolls, in order; null for dice that cannot be read.
function specDice(spec: RollSpec): number[] | null {
if (spec.kind === 'check') return spec.mode && spec.mode !== 'NORMAL' ? [20, 20] : [20];
const parsed = parseDice(spec.expression ?? '');
return parsed ? parsed.dice.flatMap((term) => Array.from({ length: term.count }, () => term.sides)) : null;
}
let localId = 0;
// A roll made in the browser, in the shape the server gives: used outside a
// campaign, where there is no table to show it to. `values` are dice typed in.
function localRoll(spec: RollSpec, rollerName: string, values?: number[]): DiceRollRecord | null {
const base = { id: `local-${++localId}`, userId: 'local', rollerName, label: spec.label ?? null, physical: Boolean(values), hidden: false, encounterId: null, createdAt: new Date().toISOString() };
if (spec.kind === 'check') {
const mode = spec.mode ?? 'NORMAL';
const rolled = values ?? rollD20(mode).dice;
const natural = mode === 'ADVANTAGE' ? Math.max(...rolled) : mode === 'DISADVANTAGE' ? Math.min(...rolled) : rolled[0];
const keptAt = rolled.indexOf(natural);
const dice: RolledDie[] = rolled.map((value, i) => ({ sides: 20, value, kept: i === keptAt, sign: 1 }));
return { ...base, notation: specNotation(spec), dice, modifier: spec.modifier ?? 0, total: natural + (spec.modifier ?? 0), natural, mode };
}
return { label: request.label, notation: request.expression.replace(/\s+/g, ''), dice, modifier: parsed.flat, total, natural: null, mode: 'NORMAL' };
const parsed = parseDice(spec.expression ?? '');
if (!parsed) return null;
let at = 0;
const dice: RolledDie[] = parsed.dice.flatMap((term) =>
Array.from({ length: term.count }, () => ({ sides: term.sides, value: values ? values[at++] : rollDie(term.sides), kept: true, sign: term.sign }))
);
return { ...base, notation: specNotation(spec), dice, modifier: parsed.flat, total: dice.reduce((sum, d) => sum + d.sign * d.value, 0) + parsed.flat, natural: null, mode: 'NORMAL' };
}
// A table-side dice roller, reachable from every page. It rolls what is set
// up here, and whatever is clicked on a sheet or an encounter card (a skill,
// a save, an attack, damage: lib/diceRoller.ts), with the bonus already in.
// These rolls are for the table: they are not sent to the server and do not
// feed the character builder, whose dice stay locked in server-side.
// The table's dice roller, reachable from every page. It rolls what is set up
// here, and whatever is clicked on a sheet or an encounter card (a skill, a
// save, an attack, damage: lib/diceRoller.ts), with the bonus already in.
//
// In a campaign the server makes every digital roll, keeps it and tells the
// table: the DM sees each roll as it lands, and players see what the
// campaign's "who sees a roll" setting allows. The campaign's dice setting
// decides how a roll is made: by the app, by real dice typed in, or either.
// Outside a campaign the dice are rolled here and go nowhere.
export function DiceRoller() {
const { user } = useAuth();
const lastCampaignId = useLastCampaignId();
const { data: campaignData } = useCampaign(user && lastCampaignId ? lastCampaignId : undefined);
const campaign = campaignData?.campaign;
const campaignId = campaign ? campaign.id : null;
const isDM = campaign?.role === 'DM';
const diceMode = campaign?.diceMode ?? 'DIGITAL';
const { data: feed = [] } = useRolls(campaignId);
const send = useRoll(campaignId);
const [open, setOpen] = useState(false);
const [tab, setTab] = useState<'roll' | 'table'>('roll');
const [sides, setSides] = useState(20);
const [count, setCount] = useState(1);
const [modifier, setModifier] = useState(0);
const [mode, setMode] = useState<RollMode>('NORMAL');
const [history, setHistory] = useState<Roll[]>([]);
const [hidden, setHidden] = useState(false);
const [byHand, setByHand] = useState(() => {
try {
return localStorage.getItem(BY_HAND_KEY) === '1';
} catch {
return false;
}
});
const [latest, setLatest] = useState<DiceRollRecord | null>(null);
const [history, setHistory] = useState<DiceRollRecord[]>([]); // outside a campaign only
// A roll waiting for real dice to be typed in, and what has been typed.
const [pending, setPending] = useState<RollSpec | null>(null);
const [typed, setTyped] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
// The id of somebody else's roll that has just arrived, while it is shown.
const [incomingId, setIncomingId] = useState<string | null>(null);
const push = (roll: Omit<Roll, 'id'>) => setHistory((prev) => [{ ...roll, id: (prev[0]?.id ?? 0) + 1 }, ...prev].slice(0, HISTORY_LENGTH));
// Real dice are typed in when the campaign plays with them, or allows both and the roller prefers them.
const typing = diceMode === 'PHYSICAL' || (diceMode === 'BOTH' && byHand);
// A roll asked for from elsewhere on the page: rolled, and shown. It is
// rolled the way the roller is set at that moment.
const currentMode = useRef(mode);
async function perform(spec: RollSpec, values?: number[]) {
setError(null);
let roll: DiceRollRecord | null;
if (campaignId) {
try {
roll = await send.mutateAsync({ ...spec, values, hidden: isDM && hidden });
} catch (err) {
setError(extractErrorMessage(err));
return;
}
} else {
roll = localRoll(spec, 'You', values);
if (!roll) return;
setHistory((prev) => [roll!, ...prev].slice(0, HISTORY_LENGTH));
}
setLatest(roll);
setPending(null);
setTyped([]);
}
// A roll to make: straight away, or held until its dice are typed in.
function ask(spec: RollSpec) {
if (!specDice(spec)) return;
setTab('roll');
setOpen(true);
if (typing) {
setPending(spec);
setTyped([]);
setError(null);
} else {
perform(spec);
}
}
// A roll asked for from elsewhere on the page, rolled the way the roller is set at that moment.
const current = useRef({ ask, mode });
useEffect(() => {
currentMode.current = mode;
current.current = { ask, mode };
});
useEffect(
() =>
onRollRequest((request) => {
const roll = answer(request, currentMode.current);
if (!roll) return;
push(roll);
setOpen(true);
onRollRequest((request: RollRequest) => {
const { ask: askNow, mode: modeNow } = current.current;
askNow(request.kind === 'check' ? { kind: 'check', label: request.label, modifier: request.modifier, mode: modeNow } : { kind: 'dice', label: request.label, expression: request.expression });
}),
[]
);
// Somebody else's roll arriving: shown beside the dice button for a moment,
// so the DM sees each roll without opening anything. What the feed held
// when it first loaded is not news.
const newest = feed[0];
const newestId = newest?.id ?? null;
const newestIsMine = newest?.userId === user?.id;
const seen = useRef<string | null | undefined>(undefined);
useEffect(() => {
if (!campaignId) return;
if (seen.current === undefined) {
seen.current = newestId;
return;
}
if (!newestId || newestId === seen.current) return;
seen.current = newestId;
// One's own roll is not news, and takes down whatever was showing.
const show = setTimeout(() => setIncomingId(newestIsMine ? null : newestId), 0);
const hide = setTimeout(() => setIncomingId((shown) => (shown === newestId ? null : shown)), INCOMING_MS);
return () => {
clearTimeout(show);
clearTimeout(hide);
};
}, [campaignId, newestId, newestIsMine]);
const incoming = incomingId ? (feed.find((roll) => roll.id === incomingId) ?? null) : null;
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
@@ -90,17 +188,29 @@ export function DiceRoller() {
return () => window.removeEventListener('keydown', onKey);
}, [open]);
const latest = history[0];
const singleD20 = sides === 20 && count === 1;
const setup: RollSpec = singleD20 ? { kind: 'check', modifier, mode } : { kind: 'dice', expression: notation(count, sides, modifier) };
const pendingDice = pending ? (specDice(pending) ?? []) : [];
const typedValues = pendingDice.map((_, i) => Number(typed[i]));
const typedOk = pendingDice.length > 0 && pendingDice.every((dieSides, i) => typed[i] && Number.isInteger(typedValues[i]) && typedValues[i] >= 1 && typedValues[i] <= dieSides);
function roll() {
if (singleD20) return push(d20Roll(modifier, mode));
const dice = Array.from({ length: count }, () => rollDie(sides));
push({ notation: notation(count, sides, modifier), dice, modifier, total: dice.reduce((sum, d) => sum + d, 0) + modifier, natural: null, mode: 'NORMAL' });
function chooseByHand(value: boolean) {
setByHand(value);
try {
localStorage.setItem(BY_HAND_KEY, value ? '1' : '0');
} catch {
// Private browsing: the choice lasts as long as the page.
}
if (!value && pending) {
// "Let the app roll" with a roll waiting: it is rolled now.
const spec = pending;
setPending(null);
perform(spec);
}
}
const natural = latest?.natural ?? null;
const modeNote = (r: Roll) => (r.mode === 'ADVANTAGE' ? 'advantage' : r.mode === 'DISADVANTAGE' ? 'disadvantage' : '');
const settle = latest ? settleMs(latest.dice.length) : 0;
return (
<>
@@ -114,111 +224,217 @@ export function DiceRoller() {
🎲
</button>
{incoming && !(open && tab === 'table') && (
<button className="dice-incoming" onClick={() => {
setTab('table');
setOpen(true);
setIncomingId(null);
}} title="Open the table's rolls">
<RollLine roll={incoming} mine={false} rolling size={30} />
</button>
)}
{open && (
<div className="dice-panel" role="dialog" aria-label="Dice roller">
<div className="flex-between">
<div className="card-title" style={{ margin: 0 }}>
Roll Dice
</div>
{campaignId ? (
<div className="dice-tabs" role="tablist">
<button role="tab" aria-selected={tab === 'roll'} className={`die-btn${tab === 'roll' ? ' is-selected' : ''}`} onClick={() => setTab('roll')}>
Roll
</button>
<button role="tab" aria-selected={tab === 'table'} className={`die-btn${tab === 'table' ? ' is-selected' : ''}`} onClick={() => setTab('table')}>
{isDM ? 'Everyone’s rolls' : 'Table'} {feed.length > 0 && <span className="combatant-sub">({feed.length})</span>}
</button>
</div>
) : (
<div className="card-title" style={{ margin: 0 }}>
Roll Dice
</div>
)}
<button className="btn btn-ghost" onClick={() => setOpen(false)} aria-label="Close the dice roller">
✕
</button>
</div>
<div className="dice-choices mt-sm" role="group" aria-label="Which die">
{DICE.map((d) => (
<button key={d} className={`die-btn${d === sides ? ' is-selected' : ''}`} aria-pressed={d === sides} onClick={() => setSides(d)}>
d{d}
</button>
))}
</div>
<div className="flex-between mt-sm">
<div className="flex-row gap-sm">
<span className="dice-label">Dice</span>
<button className="btn" aria-label="One fewer die" disabled={count <= 1} onClick={() => setCount(count - 1)}>
−
</button>
<span className="mono" aria-live="polite" style={{ minWidth: '1.5ch', textAlign: 'center' }}>
{count}
</span>
<button className="btn" aria-label="One more die" disabled={count >= MAX_DICE} onClick={() => setCount(count + 1)}>
+
</button>
</div>
<label className="flex-row gap-sm">
<span className="dice-label">Bonus</span>
<input
type="number"
min={-99}
max={99}
value={modifier}
onChange={(e) => setModifier(Math.max(-99, Math.min(99, Math.trunc(Number(e.target.value)) || 0)))}
style={{ width: 70 }}
/>
</label>
</div>
{/* For any single d20: one rolled here, and every check, save and attack clicked on a sheet. */}
<div className="dice-choices mt-sm" role="group" aria-label="How a d20 is rolled">
{MODES.map((m) => (
<button key={m.mode} className={`die-btn${m.mode === mode ? ' is-selected' : ''}`} aria-pressed={m.mode === mode} title={m.title} onClick={() => setMode(m.mode)}>
{m.label}
</button>
))}
</div>
<button className="btn btn-primary btn-block btn-lg mt-sm" onClick={roll}>
🎲 Roll {notation(count, sides, modifier)}
{singleD20 && mode !== 'NORMAL' && ` (${modeNote({ mode } as Roll)})`}
</button>
<div className="dice-result" aria-live="polite">
{latest ? (
<>
{latest.label && <div className="dice-label roll-label">{latest.label}</div>}
{/* Keyed on the roll so the pop animation replays every time, even on a repeat result. */}
<div key={latest.id} className={`roll-result animate${natural === 20 ? ' is-crit' : natural === 1 ? ' is-fumble' : ''}`}>
{latest.total}
</div>
{natural === 20 && <div className="dice-callout">Natural 20!</div>}
{natural === 1 && <div className="dice-callout is-fumble">Natural 1</div>}
{(latest.dice.length > 1 || latest.modifier !== 0 || latest.label) && (
<div className="dice-breakdown mono">
{latest.natural != null && latest.dice.length > 1
? `${latest.dice.join(' / ')} → ${latest.natural} (${modeNote(latest)})`
: latest.natural != null
? latest.natural
: `${latest.notation}: ${latest.dice.join(', ')}`}
{latest.modifier !== 0 && ` ${latest.modifier > 0 ? '+' : '−'} ${Math.abs(latest.modifier)}`} = {latest.total}
</div>
)}
</>
) : (
<p className="subtitle" style={{ margin: 0 }}>
Pick a die and roll, or click a skill, save or attack on a sheet.
{tab === 'table' && campaignId ? (
<div className="mt-sm">
<p className="combatant-sub" style={{ marginTop: 0 }}>
{isDM
? 'Every roll made at this table, as it lands. Hidden ones are yours alone.'
: campaign?.rollVisibility === 'OWN'
? 'Your rolls. This campaign keeps each player’s rolls between them and the DM.'
: 'Rolls made at this table.'}
</p>
)}
</div>
{history.length > 1 && (
<RollFeed rolls={feed} userId={user?.id} empty="Nobody has rolled yet." />
</div>
) : (
<>
<div className="flex-between">
<span className="dice-label">Earlier rolls</span>
<button className="btn btn-ghost" onClick={() => setHistory([])}>
Clear
</button>
<div className="dice-choices mt-sm" role="group" aria-label="Which die">
{DICE.map((d) => (
<button key={d} className={`die-btn${d === sides ? ' is-selected' : ''}`} aria-pressed={d === sides} onClick={() => setSides(d)}>
d{d}
</button>
))}
</div>
{history.slice(1).map((r) => (
<div key={r.id} className="flex-between dice-history-row">
<span>
{r.label ? `${r.label} · ` : ''}
{r.notation}
{r.dice.length > 1 && <span className="dice-history-dice"> ({r.dice.join(', ')})</span>}
<div className="flex-between mt-sm">
<div className="flex-row gap-sm">
<span className="dice-label">Dice</span>
<button className="btn" aria-label="One fewer die" disabled={count <= 1} onClick={() => setCount(count - 1)}>
−
</button>
<span className="mono" aria-live="polite" style={{ minWidth: '1.5ch', textAlign: 'center' }}>
{count}
</span>
<strong className="mono">{r.total}</strong>
<button className="btn" aria-label="One more die" disabled={count >= MAX_DICE} onClick={() => setCount(count + 1)}>
+
</button>
</div>
))}
<label className="flex-row gap-sm">
<span className="dice-label">Bonus</span>
<input
type="number"
min={-99}
max={99}
value={modifier}
onChange={(e) => setModifier(Math.max(-99, Math.min(99, Math.trunc(Number(e.target.value)) || 0)))}
style={{ width: 70 }}
/>
</label>
</div>
{/* For any single d20: one rolled here, and every check, save and attack clicked on a sheet. */}
<div className="dice-choices mt-sm" role="group" aria-label="How a d20 is rolled">
{MODES.map((m) => (
<button key={m.mode} className={`die-btn${m.mode === mode ? ' is-selected' : ''}`} aria-pressed={m.mode === mode} title={m.title} onClick={() => setMode(m.mode)}>
{m.label}
</button>
))}
</div>
{(diceMode === 'BOTH' || (isDM && campaignId)) && (
<div className="flex-row flex-wrap gap-sm mt-sm">
{diceMode === 'BOTH' && (
<label className="checkbox-row" title="Roll real dice at the table and type in what they show">
<input type="checkbox" checked={byHand} onChange={(e) => chooseByHand(e.target.checked)} />
🎯 I roll real dice
</label>
)}
{isDM && campaignId && (
<label className="checkbox-row" title="Only you see a hidden roll">
<input type="checkbox" checked={hidden} onChange={(e) => setHidden(e.target.checked)} />
🙈 Roll hidden
</label>
)}
</div>
)}
{diceMode === 'PHYSICAL' && <p className="combatant-sub mt-sm" style={{ marginBottom: 0 }}>This campaign plays with real dice: roll at the table and enter what they show.</p>}
{pending ? (
<form
className="dice-entry mt-sm"
onSubmit={(e) => {
e.preventDefault();
if (typedOk) perform(pending, typedValues);
}}
>
<div className="dice-label roll-label">{pending.label || 'Your roll'}</div>
<p style={{ margin: '0.2rem 0 0.4rem' }}>
Roll <strong className="mono">{specNotation(pending)}</strong>
{pending.kind === 'check' && pending.mode && pending.mode !== 'NORMAL' ? ` with ${pending.mode.toLowerCase()} (both d20s)` : ''} and enter what{' '}
{pendingDice.length === 1 ? 'it shows' : 'each die shows'}:
</p>
<div className="flex-row flex-wrap gap-sm">
{pendingDice.map((dieSides, i) => (
<label key={i} className="dice-entry-die">
<span className="dice-label">d{dieSides}</span>
<NumberInput
min={1}
max={dieSides}
placeholder={`1–${dieSides}`}
value={typed[i] ?? ''}
autoFocus={i === 0}
onChange={(e) => setTyped((prev) => Object.assign([...prev], { [i]: e.target.value }))}
style={{ width: 64 }}
/>
</label>
))}
</div>
<div className="flex-row gap-sm mt-sm">
<button type="submit" className="btn btn-primary" disabled={!typedOk || send.isPending}>
Enter roll
</button>
<button type="button" className="btn btn-ghost" onClick={() => setPending(null)}>
Cancel
</button>
{diceMode === 'BOTH' && (
<button type="button" className="btn btn-ghost" onClick={() => chooseByHand(false)}>
Let the app roll
</button>
)}
</div>
</form>
) : (
<button className="btn btn-primary btn-block btn-lg mt-sm" onClick={() => ask(setup)} disabled={send.isPending}>
{typing ? '🎯' : '🎲'} Roll {notation(count, sides, modifier)}
{singleD20 && mode !== 'NORMAL' && ` (${mode === 'ADVANTAGE' ? 'advantage' : 'disadvantage'})`}
</button>
)}
{error && <p className="dice-error">{error}</p>}
<div className="dice-result" aria-live="polite">
{latest ? (
// Keyed on the roll so the dice tumble again every time, even on a repeat result.
<div key={latest.id} className="dice-stage">
{latest.label && <div className="dice-label roll-label">{latest.label}</div>}
<DiceRow dice={latest.dice} rolling size={latest.dice.length > 6 ? 40 : 58} />
<div className={`roll-result roll-reveal${natural === 20 ? ' is-crit' : natural === 1 ? ' is-fumble' : ''}`} style={{ animationDelay: `${settle}ms` }}>
{latest.total}
</div>
<div className="roll-reveal" style={{ animationDelay: `${settle}ms` }}>
{natural === 20 && <div className="dice-callout">Natural 20!</div>}
{natural === 1 && <div className="dice-callout is-fumble">Natural 1</div>}
<div className="dice-breakdown mono">
{latest.notation}
{latest.mode !== 'NORMAL' && ` (${latest.mode === 'ADVANTAGE' ? 'advantage' : 'disadvantage'})`}
{latest.modifier !== 0 && `: dice ${latest.total - latest.modifier} ${latest.modifier > 0 ? '+' : '−'} ${Math.abs(latest.modifier)}`} = {latest.total}
{latest.hidden && ' · hidden'}
</div>
</div>
</div>
) : (
<p className="subtitle" style={{ margin: 0 }}>
Pick a die and roll, or click a skill, save or attack on a sheet.
</p>
)}
</div>
{!campaignId && history.length > 1 && (
<>
<div className="flex-between">
<span className="dice-label">Earlier rolls</span>
<button className="btn btn-ghost" onClick={() => setHistory([])}>
Clear
</button>
</div>
{history.slice(1).map((r) => (
<div key={r.id} className="flex-between dice-history-row">
<span>
{r.label ? `${r.label} · ` : ''}
{r.notation}
{r.dice.length > 1 && <span className="dice-history-dice"> ({r.dice.map((d) => d.value).join(', ')})</span>}
</span>
<strong className="mono">{r.total}</strong>
</div>
))}
</>
)}
{campaignId && (
<p className="combatant-sub" style={{ margin: 0 }}>
{isDM ? 'Your rolls are shown to the table unless hidden.' : campaign?.rollVisibility === 'OWN' ? 'Your DM sees this roll.' : 'The table sees this roll.'}
</p>
)}
</>
)}
</div>
+53
View File
@@ -0,0 +1,53 @@
import { DiceRow } from './dice/Die';
import type { DiceRollRecord } from '../api/types';
const MODE_NOTE = { NORMAL: '', ADVANTAGE: 'advantage', DISADVANTAGE: 'disadvantage' } as const;
function timeOf(iso: string): string {
return new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// One roll as a line: who, what for, the dice as they fell, and the total.
export function RollLine({ roll, mine, rolling = false, size = 34 }: { roll: DiceRollRecord; mine: boolean; rolling?: boolean; size?: number }) {
const crit = roll.natural === 20;
const fumble = roll.natural === 1;
return (
<div className={`roll-line${crit ? ' is-crit' : fumble ? ' is-fumble' : ''}`}>
<div className="roll-line-head">
<span>
<strong>{mine ? 'You' : roll.rollerName}</strong>
{roll.label && <span> · {roll.label}</span>}
</span>
<span className="combatant-sub">{timeOf(roll.createdAt)}</span>
</div>
<div className="roll-line-body">
<DiceRow dice={roll.dice} rolling={rolling} size={size} />
<span className="roll-line-math mono">
{roll.modifier !== 0 && `${roll.modifier > 0 ? '+' : '−'} ${Math.abs(roll.modifier)} `}=
</span>
<strong className="roll-line-total mono">{roll.total}</strong>
</div>
<div className="roll-line-tags">
<span className="combatant-sub mono">{roll.notation}</span>
{roll.mode !== 'NORMAL' && <span className="badge">{MODE_NOTE[roll.mode]}</span>}
{crit && <span className="badge badge-friendly">Natural 20</span>}
{fumble && <span className="badge badge-hostile">Natural 1</span>}
{roll.physical && <span className="badge" title="Rolled with real dice and typed in">🎯 at the table</span>}
{roll.hidden && <span className="badge badge-dm" title="Only you see this roll">🙈 hidden</span>}
</div>
</div>
);
}
// The table's rolls, newest first: every roll this member may see. For the
// DM that is every roll anyone makes.
export function RollFeed({ rolls, userId, empty }: { rolls: DiceRollRecord[]; userId: string | undefined; empty: string }) {
if (rolls.length === 0) return <p className="subtitle">{empty}</p>;
return (
<div className="roll-feed">
{rolls.map((roll) => (
<RollLine key={roll.id} roll={roll} mine={roll.userId === userId} />
))}
</div>
);
}
+92
View File
@@ -0,0 +1,92 @@
import { useEffect, useState } from 'react';
import { STAGGER_MS, TUMBLE_MS, prefersStill } from '../../lib/diceAnimation';
import type { RolledDie } from '../../api/types';
// The outline of each die, seen face on, in a 100 × 100 box: the shape that
// says which die it is, and the lines that give it facets.
const SHAPES: Record<number, { outline: string; facets?: string[] }> = {
4: { outline: '50,8 94,86 6,86', facets: ['50,8 50,86'] },
6: { outline: '14,14 86,14 86,86 14,86' },
8: { outline: '50,4 94,50 50,96 6,50', facets: ['6,50 94,50'] },
10: { outline: '50,4 92,40 50,96 8,40', facets: ['8,40 50,58 92,40', '50,58 50,96'] },
12: { outline: '50,4 93,35 77,90 23,90 7,35', facets: ['50,4 50,28', '93,35 72,42', '77,90 64,70', '23,90 36,70', '7,35 28,42', '50,28 72,42 64,70 36,70 28,42 50,28'] },
20: { outline: '50,3 91,26 91,74 50,97 9,74 9,26', facets: ['50,22 80,70 20,70 50,22', '50,3 50,22', '91,74 80,70', '9,74 20,70', '9,26 50,22 91,26', '20,70 50,97 80,70'] },
};
// Where the number sits: lower in a triangle, whose middle is below its centre.
const TEXT_Y: Record<number, number> = { 4: 66, 10: 46, 20: 58 };
const randomFace = (sides: number) => Math.floor(Math.random() * sides) + 1;
// One die, drawn as its own shape with the number it shows. With `rolling` it
// tumbles in, flickering through faces, and lands on its value; `order` is
// its place among the dice rolled with it. A die that was dropped (the lower
// d20 with advantage) is faded; a natural 20 or 1 on a d20 is marked.
export function Die({ die, rolling = false, order = 0, size = 56 }: { die: RolledDie; rolling?: boolean; order?: number; size?: number }) {
const animate = rolling && !prefersStill();
const [landed, setLanded] = useState(!animate);
const [face, setFace] = useState(animate ? randomFace(die.sides) : die.value);
useEffect(() => {
if (!animate) return;
const flicker = setInterval(() => setFace(randomFace(die.sides)), 70);
const land = setTimeout(
() => {
clearInterval(flicker);
setFace(die.value);
setLanded(true);
},
TUMBLE_MS + order * STAGGER_MS
);
return () => {
clearInterval(flicker);
clearTimeout(land);
};
}, [animate, die.sides, die.value, order]);
const shape = SHAPES[die.sides];
const shown = landed ? die.value : face;
const crit = landed && die.sides === 20 && die.kept && die.value === 20;
const fumble = landed && die.sides === 20 && die.kept && die.value === 1;
const classes = ['die', `die-d${shape ? die.sides : 'x'}`, landed ? 'is-landed' : 'is-rolling', die.kept ? '' : 'is-dropped', crit ? 'is-crit' : '', fumble ? 'is-fumble' : '', die.sign < 0 ? 'is-minus' : '']
.filter(Boolean)
.join(' ');
return (
<span
className={classes}
style={{ width: size, height: size, animationDelay: animate ? `${order * STAGGER_MS}ms` : undefined, animationDuration: animate ? `${TUMBLE_MS}ms` : undefined }}
title={`d${die.sides}: ${die.value}${die.kept ? '' : ' (dropped)'}${die.maxed ? ' (at its most, for the critical hit)' : ''}`}
aria-label={`d${die.sides} showing ${landed ? die.value : 'rolling'}`}
>
<svg viewBox="0 0 100 100" width={size} height={size} aria-hidden="true">
{shape ? (
<>
<polygon className="die-body" points={shape.outline} strokeLinejoin="round" />
{shape.facets?.map((points) => (
<polyline key={points} className="die-facet" points={points} fill="none" />
))}
</>
) : (
// Any other die (a d100, a d3...): a plain round one.
<circle className="die-body" cx="50" cy="50" r="44" />
)}
<text className="die-face" x="50" y={TEXT_Y[die.sides] ?? 52} textAnchor="middle" dominantBaseline="middle" fontSize={shown > 99 ? 26 : shown > 9 ? 34 : 40}>
{shown}
</text>
</svg>
<span className="die-kind">d{die.sides}</span>
</span>
);
}
// A roll's dice in a row, landing one after another.
export function DiceRow({ dice, rolling = false, size = 56 }: { dice: RolledDie[]; rolling?: boolean; size?: number }) {
return (
<span className="dice-row">
{dice.map((die, i) => (
<Die key={i} die={die} rolling={rolling} order={i} size={size} />
))}
</span>
);
}