import { useEffect, useRef, useState } from 'react'; 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' }, { mode: 'NORMAL', label: 'Normal', title: 'One d20' }, { mode: 'ADVANTAGE', label: 'Adv.', title: 'Advantage: roll two d20s and keep the higher' }, ]; function notation(count: number, sides: number, modifier: number): string { return `${count}d${sides}${modifier ? fmtMod(modifier) : ''}`; } // 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, ''); } // 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 }; } 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' }; } // 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('NORMAL'); const [hidden, setHidden] = useState(false); const [byHand, setByHand] = useState(() => { try { return localStorage.getItem(BY_HAND_KEY) === '1'; } catch { return false; } }); const [latest, setLatest] = useState(null); const [history, setHistory] = useState([]); // outside a campaign only // A roll waiting for real dice to be typed in, and what has been typed. const [pending, setPending] = useState(null); const [typed, setTyped] = useState([]); const [error, setError] = useState(null); // The id of somebody else's roll that has just arrived, while it is shown. const [incomingId, setIncomingId] = useState(null); // 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); 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(() => { current.current = { ask, mode }; }); useEffect( () => 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(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); window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, [open]); 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 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 settle = latest ? settleMs(latest.dice.length) : 0; return ( <> {incoming && !(open && tab === 'table') && ( )} {open && (
{campaignId ? (
) : (
Roll Dice
)}
{tab === 'table' && campaignId ? (

{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.'}

) : ( <>
{DICE.map((d) => ( ))}
Dice {count}
{/* For any single d20: one rolled here, and every check, save and attack clicked on a sheet. */}
{MODES.map((m) => ( ))}
{(diceMode === 'BOTH' || (isDM && campaignId)) && (
{diceMode === 'BOTH' && ( )} {isDM && campaignId && ( )}
)} {diceMode === 'PHYSICAL' &&

This campaign plays with real dice: roll at the table and enter what they show.

} {pending ? (
{ e.preventDefault(); if (typedOk) perform(pending, typedValues); }} >
{pending.label || 'Your roll'}

Roll {specNotation(pending)} {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'}:

{pendingDice.map((dieSides, i) => ( ))}
{diceMode === 'BOTH' && ( )}
) : ( )} {error &&

{error}

}
{latest ? ( // Keyed on the roll so the dice tumble again every time, even on a repeat result.
{latest.label &&
{latest.label}
} 6 ? 40 : 58} />
{latest.total}
{natural === 20 &&
Natural 20!
} {natural === 1 &&
Natural 1
}
{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'}
) : (

Pick a die and roll, or click a skill, save or attack on a sheet.

)}
{!campaignId && history.length > 1 && ( <>
Earlier rolls
{history.slice(1).map((r) => (
{r.label ? `${r.label} · ` : ''} {r.notation} {r.dice.length > 1 && ({r.dice.map((d) => d.value).join(', ')})} {r.total}
))} )} {campaignId && (

{isDM ? 'Your rolls are shown to the table unless hidden.' : campaign?.rollVisibility === 'OWN' ? 'Your DM sees this roll.' : 'The table sees this roll.'}

)} )}
)} ); }