Compare commits

...
Author SHA1 Message Date
jheapsandClaude Opus 5 d66abda05a Make the dealer puck hittable without making it bigger
Ran the touch-target check that had been sitting in the audit unused. The dealer
puck is 22x22 — half what a fingertip needs — in ten places on the table, and
tapping it hands the button to that seat and re-posts the blinds. Not a cosmetic
control.

It stays 22x22. A puck should look like a puck sitting on the rim of its seat, and
growing it would take area from the seat itself, which a dealer taps far more
often. Instead an invisible pad around it catches the tap: 43x44 hittable on every
phone size, close to four times the area, with the pad pushed down and left away
from the seat the chip juts towards. Verified that no seat tap is stolen — the
occlusion audit is clean at every size.

Three things the check itself got wrong, all found before acting on them

It read element boxes, and boxes lie in both directions. A control padded out with
a transparent ::after responds well past its painted size, and a checkbox wrapped
in a label is hit by tapping anywhere on the label — so it reported the dedicated
dealer toggle as a 24px fault when it sits inside a 320x44 label that already
forwards the tap. It probes outward with elementFromPoint now, which is what a
finger actually experiences.

The probe walked a fixed 40px each way, so everything wider than 80px reported
exactly 80. Every header button came back a suspiciously round "80x42".

And it enforced 44px on desktop, where there is no fingertip. Those same header
buttons are 64px tall on a phone and 42px with a mouse, which is not a defect.
Keyed off hover:none now, the same signal used for the tablet field sizing.

Also removed a ::after pad on the dedicated-dealer checkbox that was both inert --
pseudo-elements don't render on replaced elements -- and unnecessary, since the
label already does the job.

The puck is the one documented exemption: it is deliberately small and "Give the
button" is in the seat menu at full size, so it's a shortcut rather than the only
way through. The reason sits in the code next to the exemption.

Phone sizes: dealer chip 22x22 drawn / 43x44 hittable, zero undersized controls
even with the exemption and the pointer rule forced off. Layout and contrast
audits clean at all seven sizes. 137 tests passing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 08:54:07 -06:00
jheapsandClaude Opus 5 6fa4532781 Fix the contrast the audit could finally measure
Contrast is the one check I've got wrong twice, both times by being clever about
backgrounds. The first version read only background-color, so text on any of the
gradient-painted sheets was measured against transparency and the dealer puck's
dark "D" was reported at 1.2:1 against nothing. The second over-corrected and
treated low-alpha gradient stops as opaque, scoring white-on-dark at 1.0:1.

So this one is built to be incapable of false positives rather than exact.
Backgrounds composite through alpha; where a gradient is involved every colour stop
is tried and the most flattering one used. A finding means the text fails even
under the reading most generous to it.

It's checked against known answers before being believed: black on white at 21:1,
white on white at 1:1, #767676 on white at the 4.54:1 AA boundary, white over a
dark gradient, dark text on that same gradient, white over a 6% white wash on a
near-black page. Nine cases, all correct — and building them found a real bug in
the check, which walked past an opaque gradient and offered the page background as
a candidate. That made it too lenient, which is as bad as the old false positives.

What it found:

Both blind badges failed against their own gradients, in 9px bold text a dealer
reads at a glance across a table. At the worst stop: small blind 3.52:1, big blind
2.15:1. The small blind keeps its blue and darkens to 4.77:1. The big blind flips
to dark text on brighter gold, 5.84:1 — how a gold chip is marked anyway, and it
makes the two badges far easier to tell apart at speed.

Quick Split's footnote names a control the dealer is told to reach for, and that
name inherited the muted grey of the surrounding aside: 3.39:1. Emphasised text
carrying an instruction gets its own colour now.

The felt watermark came back at 1.19:1 and is meant to. It's decoration; holding it
to a reading threshold would mean making it not a watermark. It's aria-hidden now,
which says the same thing where it also does some good, and the audit skips
aria-hidden subtrees.

32 contrast passes over the table, all five overlays and Quick Split at five
viewports: zero findings, zero unmeasured. Layout audit still clean. 137 tests pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 08:39:07 -06:00
jheapsandClaude Opus 5 2f6d63400a Stop re-typing the layout audit into a console every round
Last round I found a regression I'd shipped two rounds earlier: the standings
table's player-name column was zero pixels wide, at every viewport, and nobody
noticed because the audit that would have caught it only ever existed in a
previous session's scrollback. These checks have been re-written by hand at least
six times, and each time they covered only whatever had just changed.

So they're a file now. uiAudit.js runs in the page — no build step, no
package.json, no dependency — and checks touch-action and tap highlights, that
fields stay selectable and are big enough not to trigger iOS zoom, that nothing
important is covered or stranded off-screen, that no grid column has collapsed to
nothing, and that no text is painted outside its box. runUiAudit.js drives it over
the table, all five overlays and Quick Split at thirteen viewports. Deliberately
outside CI: the unit suite is dependency-free and runs in a second, this one needs
a browser and a running site.

Three real faults it found on its first run

Fields were 13.3px on every iPad. The 16px minimum that stops iOS zooming the page
on focus went in inside a max-width:700px block, and every iPad is wider than
that — so a dealer on a tablet, which is the device this is most likely to be
propped up on, got the table zoomed every time they touched the blind amount. The
reason for that rule was never "narrow screen", it was "iOS". Font size applies at
all widths now, and the 44px touch targets key off hover:none, which is what
actually distinguishes a finger from a mouse.

The seat menu couldn't be scrolled. It had no height limit and no overflow, so on
a phone held sideways its first two actions — Fold and All-in — sat below the
bottom of the screen with no way to reach them. A dealer in landscape could
long-press a seat and then not fold it.

The pot wizard sat under the action bar. Every other overlay is z-index 90-98; the
wizard alone was at 50, below both the action bar at 55 and the toast at 80. In
landscape one of its inputs was completely covered by the Fold button, and a toast
could sit over "Confirm Winner(s)". It was the odd one out rather than a decision.

Three faults in the audit itself, found by checking before acting

Worth recording, because each would have had me "fix" something that wasn't broken:

- an ellipsised name was reported as painting outside its seat. A Range measures
  laid-out text, which runs past the element while overflow:hidden quietly clips
  it. Only overflow that is actually visible can paint over a neighbour.
- every link below the fold was reported as off-screen. Something under the fold on
  a page that scrolls is reachable; the check now asks whether scrolling can bring
  it into view, which is the thing that actually matters.
- a button in the newly-scrollable seat menu came back "covered by null".
  elementFromPoint returns null for a point outside a scrollable ancestor's clip —
  scrolled out of view, not covered by anything.

A toast partly over a control is a warning rather than a failure now: it dismisses
itself and carries a close button, and on a desktop it necessarily lands over a
table that fills the content column. Fully covered by a toast is still a failure,
because that was a real bug once — a seat sat exactly under the Undo button.

Final sweep: 13 viewports, 65 overlay checks, 13 full-page audits, 4 Quick Split
audits, zero failures, one warning. 137 unit tests still passing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 08:31:35 -06:00
jheapsandClaude Opus 5 0d6e7e0b5a Give the standings table back its player names
Went looking for more rules bugs and didn't find any — the blind rotation is fair
over an orbit, nobody is double-charged or skipped when players come and go, and
the big blind's option is handled correctly including heads-up and when the blind
puts them all-in. Those probes are written up below.

What I did find was a regression I shipped two rounds ago.

The name column was zero pixels wide

Adding the "Cash out" column in the bank-audit round made five columns. Four of
them are numbers with a 4.5rem minimum, which with gaps needs 320px — and the
sidebar is about 290px. The name column is the only flexible one, so it absorbed
the shortfall and collapsed to nothing. Player names were not truncated, they
were entirely invisible, and the row quietly overflowed.

Measured at 360, 390, 1024, 1280 and 1600 alike, because the sidebar is narrow at
all of them — this was not a phone problem, it was everywhere except the tablet
layout where the sidebar goes full width. Names were already down to 50px with
four columns, so this had been getting worse before I finished it off.

The table earns its columns now instead of assuming them

Narrow: player, net, cash out — the two numbers a banker settles up from. Wide
enough: the per-hand In and Won as well. A container query rather than a viewport
one, because the sidebar is 290px at both 360px and 1600px viewports and the
thing that matters is the space the table actually has. Names get a real minimum
and ellipsis rather than being crushed. Everything stays in the CSV either way.

    360x640    name 0px -> 152px    Player | Net | Cash out
    390x844    name 0px -> 182px    Player | Net | Cash out
    768x1024   name    -> 389px     Player | In | Won | Net | Cash out
    1280x900   name 0px -> 151px    Player | Net | Cash out

Rules probes that came back clean, so nothing changed:

- blind rotation over 12 hands with 4 players: exactly 3 big blinds each
- a player leaving and rejoining mid-session never causes a double or a skip
- the big blind gets their option when everyone limps, can raise with it,
  and checking it ends the street
- a big blind left all-in by the blind itself gets no phantom option
- heads-up, the button acts first pre-flop and the big blind still has the option
- post-flop the minimum bet falls back to the big blind

Re-checked the guarantees from earlier rounds with the sidebar open: 0 of 50
controls on touch-action auto, 0 tap-highlighted, 0 occluded, stacks still inside
their pucks, no sideways scroll, bank panel still fits and reads correctly.
137 tests still passing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 08:07:51 -06:00
jheapsandClaude Opus 5 aeb02d023d A short all-in doesn't reopen the betting
Went looking at dealer procedure again and ended up checking the rule home games
argue about longest. The tool had it wrong.

Blinds 1/2. Seat 4 raises to 10 — a full raise of 8. Seat 1 calls. Seat 2 is
all-in for 13: three more, where a full raise would need eight. Under TDA rule 44
that does not reopen the betting to anyone who has already acted; they owe the
extra three or they fold. Seat 1 and seat 4 were both being handed another go.

Two things were wrong in raiseTo. Any increase at all reset hasActed for every
live player, so a short shove gave the whole table another chance to raise. And
lastRaiseSize was overwritten with the short amount, so the next legal raise was
computed off 3 instead of 8 and came out too small — a second, quieter error that
only shows up when somebody then tries to raise.

Both now key off whether the increase was actually a full raise. A player who had
not yet acted keeps full rights, which falls out naturally because their hasActed
is already false — that distinction is the part of the rule people get wrong in
the other direction.

Everyone still owes the difference: isStreetComplete already asks anyone with
chips left to call, so the short all-in is answered without being re-raiseable.

The rulings sheet now covers what the tool does for you

It had three entries. A dealer challenged on a payout couldn't look up why the
tool did what it did, even for the rules it enforces automatically. Added the
short all-in rule above, uncalled chips coming back rather than being announced
as a side pot, and the odd chip in a chopped pot going to the first player left
of the button — all three are things this tool already decides silently, and all
three are worth being able to point at when somebody objects.

10 tests (137 total): already-acted players aren't reopened but still owe the
difference, a player yet to act keeps full rights, the minimum raise isn't
shrunk, calling it ends the street, no chips are created, and — the other half of
the rule — a full-sized all-in, an ordinary raise, a raise exactly matching the
last one, and a full-sized opening bet all still reopen everyone.

Validated through the real action bar: after the short shove, lastRaiseSize stays
8 and the player who had already called stays settled, while the two who hadn't
acted keep their turn. The longer rulings sheet still fits a phone, scrolls, traps
focus and closes on Escape.

Sources: TDA rules via thelodgepokerclub.com/tda-rules/,
pokernews.com/strategy/deal-with-it-tips-for-mistake-free-dealing-in-home-games-30231.htm

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 07:52:08 -06:00
jheapsandClaude Opus 5 60d192a9ec Let the banker check the cash box against the chips on the table
Ran out of things I could find by auditing the UI, so I went and read what people
who run home games actually complain about. The recurring one isn't a dealing
mistake, it's a banking one: "the last two guys go to cash out at the end of some
all-night game and there isn't enough cash to cover the chips they have."

Every chip on the table is a promise to pay cash for it later. Nothing in here
checked that the promise could be kept, and there's no way to notice by eye —
it's always a rebuy nobody wrote down, or chips taken without paying, and it
stays silent until the box is empty and two people are still holding chips.

The books now add up, or say why not

HoldemState.bankReconciliation compares the cash taken in against every chip that
could be handed back — stacks, chips in front of players, and the pot waiting to
be won. The sidebar shows both numbers and what they mean:

    Balanced — the cash covers every chip on the table.
    $160 more in chips than cash taken. Someone's rebuy probably wasn't
      recorded — the box will be short at cash-out.
    $150 more cash than chips in play. Someone has paid for chips they
      haven't been given.

Money in the middle counts as chips in play, so an open pot isn't reported as a
shortfall — otherwise it would cry wolf during almost every hand.

Players who had bought in were missing from the settle-up

sessionStandings was built from the hand log, so anybody who hadn't yet been in a
recorded hand didn't appear at all. Somebody hands over $200, sits down, folds a
few, and the banker's own record doesn't mention them — then they turn up at
cash-out holding chips the list never accounted for. Anyone with money in the
game is in the list now, whether or not they've played a logged hand.

The settle-up number was already being computed and hidden

cashPosition — chips in front of them less the cash they handed over — was
calculated for every player and written to the CSV, but never shown on screen.
It's the number you read while counting out cash at the end of the night, so it's
a column now.

15 tests (127 total): a buy-in with no hands played still appears and reads as
level rather than a loss, empty chairs stay out, a player who cashed out shows
what they took, both directions of imbalance are caught, an open pot is not a
discrepancy, six played-and-settled hands never knock the books out, a proper
rebuy balances while a chip grab doesn't, and float dust isn't an alarm.

Validated with Playwright through real play — seated, blinds posted, pot open,
hand settled, rebuy — balanced at every step, plus the three seeded verdicts and
a fresh table where the panel stays hidden.

Sources: pokerlistings.com/blog/how-to-run-a-home-poker-game,
chipsoffury.com/learn/how-to-handle-poker-buy-ins-with-friends/

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 07:33:16 -06:00
jheapsandClaude Opus 5 cc6a1902bc Stop the tool from throwing a pot away without saying so
Two ways to lose a hand's money by accident, both found by walking the settle
flow and checking the chip count afterwards.

Next Hand destroyed an unresolved pot silently

Starting the next hand clears every seat's contribution, so money still in the
middle simply vanished. Measured at a four-handed table with $8 in the pot: the
table went from 800 chips to 792, and the toast said "Next hand — button on seat
3. Blinds posted." — not a word about the eight chips that had just left.

It now asks, names the amount, and says what will happen to it. Confirming still
works and the toast says what went. The undo was always there, but a dealer
can't undo something they were never told about.

The wizard's "Close" abandoned a payout that looked finished

After picking winners and confirming, the wizard shows "Final Payouts — Ann $8"
above two buttons: "Start Next Hand" and "Close". Close pays nobody. Under that
heading, with a name and an amount beside it, a dealer taps Close believing the
pot has been pushed — and walks away with the chips still in the middle and the
hand unlogged. The button now says "Cancel — don't pay yet", with a line
underneath spelling out that nothing has been paid.

The warning measures the right thing

The first version counted the pot badge, which was wrong in a way the tests
caught before it shipped: the table-wide base pot is a standing ante for dealers
who don't track stacks, and it re-applies to the next hand rather than being
lost. Quoting it would have put a confirmation in front of those dealers before
every single hand — a nag, on the simplest way to run a table, for money that
wasn't going anywhere.

HoldemState.unresolvedContributions() measures exactly the fields startNextHand
clears: banked contributions, chip counts, and whatever is still in front of
players on this street. Verified both ways in the browser — a base-pot table
showing a $100 pot is not asked at all, a stack-tracking table with $8 live is.

6 tests (115 total): the quoted number equals what actually leaves the table,
mid-street chips are included, a settled hand leaves nothing to warn about, five
settled hands conserve every chip, an empty table has no phantom pot, and a
standing ante is never warned about.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 04:39:51 -06:00
jheapsandClaude Opus 5 a488bbf832 Stop rebuilding the hand log after every fold, call and raise
Profiled a long night at a full table — 24 seats, 200 logged hands — because
that's the state the tool is slowest in and the one a dealer reaches at 2am.

A full re-render cost 30ms, and it runs after every single action. Broken down,
25.7ms of that was renderHandHistory: tearing down and rebuilding 200 rows of a
panel that hadn't changed and that nobody is looking at mid-hand. Everything
else on the table put together came to about 4ms.

The log only changes when a hand is settled or the history is cleared — maybe
once every thirty taps. It now carries a cheap signature (length, hand counter,
and the newest row) and is skipped when that hasn't moved. Entries are immutable
once written and only ever added at the front, so the signature catches a
recorded hand, a cleared history, and an undo that puts a hand back.

    renderAll, every action     30.07ms -> 4.18ms
    renderHandHistory, skipped  25.74ms -> 0ms
    renderHandHistory, rebuild  25.74ms -> 9.05ms

The rebuild got faster too, for the times it does run — once per hand, where
25ms of jank lands exactly on the "next hand" tap. toLocaleTimeString was the
single most expensive call in the loop and a logged hand's timestamp never
changes, so the formatted string is kept; and the rows are built into a fragment
so the panel lays out once instead of two hundred times.

A cache like this is only worth having if it can't go stale — a dealer reading
last hand's payouts while settling this one is worse than a slow panel. 10 tests
cover the invalidation directly: unchanged through a street of betting, changed
by settling, by clearing, by an undo back to a shorter log, by two hands that
differ only in the pot, and by the counter moving on.

Validated with Playwright against the real page: the rendered rows match the
stored history through settling a hand in the wizard, undoing it, clearing the
log and recording again. Touch and layout guarantees from the earlier rounds
still hold — 0 of 87 controls on touch-action auto, 0 tap-highlighted, every
stack still inside its own puck. 109 tests passing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 04:24:36 -06:00
jheapsandClaude Opus 5 9ee4816fa4 Make the overlays usable from a keyboard
Measured every overlay in the tool before touching anything. For a dealer running
this on a laptop, all six were broken in the same three ways.

- focus never moved into the dialog: 0 of 5 measured
- Tab walked straight out of the dialog into the page behind the scrim: 5 of 5
- Escape did nothing: only the rulings sheet handled it, 1 of 5
- the pot wizard — the dialog that pays people — had no role and no
  accessible name at all

So opening the pot wizard left focus on the button behind it, tabbing wandered
through a page nobody can see or click, and there was no way back out except the
mouse.

One implementation, not six

The overlays are opened and closed by five different modules, which is why they
each missed the same things. Rather than patch this into all of them, modal.js
watches the `hidden` attribute they already toggle: focus moves to the first real
control on open, Tab and Shift-Tab wrap inside the dialog, Escape closes it, and
focus returns to whatever opened it. `aria-modal` is set while open and removed
on close. An overlay added later gets all of it without anyone remembering to
wire it up, which is the failure being fixed.

Escape presses the dialog's own cancel button rather than just hiding the
overlay, so the confirm dialog still resolves its promise — verified: Escape
resolves it to false rather than leaving an await hanging forever.

Shortcuts.overlayOpen() had the same shape of bug, listing the six overlay ids by
hand. It asks the document now, so a sheet added later can't quietly start
letting "f" fold the table behind it.

Focus you can see

Three focus rules existed for the whole stylesheet, so tabbing relied on the
browser default ring, which on these dark custom-painted controls is close to
invisible. `:focus-visible` keeps it to keyboard use so a dealer tapping Fold
isn't left with a ring on it.

That surfaced something small: `.holdemBtn` used `transition: all`, so the new
outline faded in over 150ms and the ring lagged a step behind the Tab key. The
transition names its properties now. Measured after: 16 of 16 tab stops show a
ring immediately, and the press state from before still animates.

Also

- a mistyped negative stack read back as negative, and flowed into putIn() where
  Math.min(amount, -50) moves a negative amount and adds chips to the table.
  Clamped at zero.
- accessible names for the chip colour, chip value and notes fields, which had none

11 new tests (99 total), covering negative stacks, negative and unreadable
blinds, blinds nobody can cover, and a save that comes back corrupt, truncated,
or from before a field existed.

Playwright: all five overlays re-measured — focus moves in 5/5, Tab and
Shift-Tab trapped 5/5, Escape closes 5/5, focus restored 5/5, role and
aria-modal present 5/5. Shortcuts still fire when no dialog is open and are
still blocked when one is. Touch guarantees from the earlier round unchanged:
0 of 49 controls on touch-action auto, 0 tap-highlighted.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 04:12:55 -06:00
jheapsandClaude Opus 5 db208a1a86 Make big numbers readable, and make the export add up
Seeded a table that looks like a real game — "Mike from work", "Jean-Philippe",
stacks from $12 to $3,200,000 — and measured what the layout does with it.

".00" was costing a third of a seat puck

Every amount rendered with two forced decimal places. Measured, the trailing
".00" is ~22px, against the 64px a seat puck has to show a stack in. So
"$1,250,000.00" needed 102px of a 64px box — and because a number has no spaces
to break on, it neither wrapped nor ellipsised. It drew straight out over the
seat next to it.

Money now shows cents only when there are cents. A chip game deals in whole
numbers nearly all the time, and "$12" says exactly what "$12.00" said in half
the width. A quarter-blind game is untouched: $0.25, $12.50 and $0.75 pots all
still read as before, checked against a 25c/50c table.

That alone took "$1,250,000.00" down to "$1,250,000" — 102px to 80px, still
wider than the 64px puck. The remaining overflow is handled by stepping the font
down on long amounts, which keeps every digit. Abbreviating to "$1.25M" would
have fit more comfortably and was the obvious move, but a dealer reading a
rounded stack off the felt is a worse failure than a small one, and the exact
figure is the entire point of the tool. Measured after: every stack now paints
inside its own puck, nothing spills onto a neighbour.

Because Money.format is the single formatter all 47 call sites go through, this
lands on the seat pucks, action bar, pot breakdown, seat menu, standings and
history at once — the payoff from consolidating it earlier.

The CSV export couldn't be added up

The file exists so a house manager or a disputed chip count has something that
outlives the tab, and every money column in it was written as text:
"$1,250,000.00". The commas were quoted correctly so the file always parsed —
it just imported as strings, so the one thing anyone opens it to do, total a
column, needed every cell cleaned first.

Money columns now go in as bare numbers (1250000.00) with no symbol and no
separators. The columns meant for humans stay human: names are still names,
payouts still read "Alexandra: $1,250,000", and a name with a comma in it is
still quoted.

12 new tests (88 total, all passing), including the case that would be ruined by
dropping cents unconditionally, and a proper quote-aware CSV parser to check
every money cell parses as a number.

Re-ran the occlusion sweep from the previous round at 9 seats, 10 seats and
tournament stacks: still clean, no regression from the font changes.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 03:54:03 -06:00
jheapsandClaude Opus 5 3d63ba50ee Handle the messy table: people joining, leaving, and arguing about blinds
Home games don't run like a cardroom. People walk up mid-hand, storm off
mid-hand, and pass the button round three times before anyone deals. Probing
each of those found four problems, one of which loses chips.

A player taken out mid-hand took their chips with them

`computeContribution` opened with `if (!player.inHand) return 0`, so the moment
a dealer switched a seat off, everything that seat had already put in vanished
from the pot. Measured: four players in for $2 each, one taken out, pot drops
from $8 to $6. Their $2 was still sitting on the seat record — it just stopped
counting. A dealer following the tool would have paid out $6 of an $8 pot.

Chips already pushed into the middle are dead money. They stay in the pot and go
to whoever wins, whether or not the player is still in the hand, and it is not
theirs to take back. The `inHand` check now guards only the table-wide base-pot
default, which does have to stay tied to being dealt in or every empty chair
would be treated as having anted. The pot wizard counts a departed seat as
folded, so its chips are in the pot but it can never be picked as a winner.

Passing the button before the cards come out

Moving the button left the posted blinds where they were while everything
positional started reading off the new spot, so the money and the blind
positions silently disagreed. While nothing but the blinds are in, moving the
button now refunds them and re-posts from where it lands — pass it round six
times and the chip count is unchanged. Once anybody has acted the blinds are
settled and it stops offering.

Naming the blinds by hand

Blinds were purely positional with no way to overrule them. The seat menu now
offers "Make small blind" / "Make big blind" while only the blinds are in, and a
badge with a ring marks a blind that was named rather than dealt. Naming one
pins the other where it is. It's refused if it would put both blinds on one
player or post to somebody who isn't dealt in, and it lasts one hand — carrying
it forward would freeze the blinds on two people for the night.

The first hand, and a table that empties out

A fresh table puts the button on seat 1 whether or not anyone is sitting there,
and a table can empty out around it. The button is moved onto a real player
before a hand is dealt.

Joining mid-hand

A newcomer was added straight into the live seats and would be asked to act in a
hand they hadn't been paying into. They now sit the hand out and are a full
player from the next one.

Nothing is covered on a phone any more

Swept 13 viewport sizes with elementFromPoint, five points per control, on the
table and every overlay. Before: the action bar covered the bottom seats on
short screens (62px of felt at 360x640), the toast covered up to six seats at
once — Undo button included, so a tap meant for a player hit "Undo" — and in
landscape the table came out 765px tall in a 390px window, putting six of nine
seats off-screen entirely.

- the action bar's real height is published as `--actionBarHeight` and drives
  both the page's bottom padding and the toast, replacing a hardcoded 9rem that
  was wrong the moment the raise pad opened
- landscape sizes the felt from the height that's left, not from width. The
  first attempt did nothing: `padding-bottom` is a percentage of the containing
  block's *width*, so narrowing the wrap left it full height, and a
  `max-width: 900px` rule later in the file was overriding it anyway. It's set
  outright now and lives at the end of the sheet.
- on short screens the toast floats over the action bar's status readout rather
  than over the seats. Nowhere is clear of both; covering something you re-read
  beats covering something you tap.
- headers go compact on short screens, which is where the vertical room came from

13/13 sizes clean, 360x640 through 844x390, portrait and landscape.

Also fixes a marker that flickered: `classList.toggle(cls, undefined)` toggles
rather than clearing, and `manual` is undefined for positional blinds, so the
hand-picked ring appeared on alternate renders.

18 new tests (76 total, all passing).

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 03:40:02 -06:00
jheapsandClaude Opus 5 073ba9a252 Make every tap in the dealer land instantly on a phone
Four measured problems, all of which only show up under a thumb.

Every tap waited on the browser (53 of 53 controls)

Not one interactive element set `touch-action`, so a mobile browser held every
tap for ~300ms to see whether a second one was coming that would mean "zoom in".
That is on the fold button, the call button, every seat, every card slot.

Worse, this tool uses double-tap on a seat as the fold shortcut — which *is* the
browser's zoom gesture. The dealer's fastest shortcut was fighting the page
zooming under their thumb. A single seat tap cost ~300ms of browser hesitation
before the app's own 220ms double-tap window even started.

`touch-action: manipulation` everywhere keeps panning and pinch-zoom and drops
only double-tap-to-zoom, which is precisely the one that was in the way.

Press feedback was the OS grey box (1 `:active` rule in 2385 lines)

Only `.actionBtn` had a pressed state. Everything else — seats, header buttons,
card slots, picker cards, menu rows, toasts, wizard choices — relied on the
translucent grey rectangle the browser paints on tap. So the tap highlight
couldn't just be switched off; the controls needed real pressed states first.
They press down 1px and brighten, in 0.04s, matching the action bar that already
did. Then the grey box goes.

Hover stuck after every tap (21 unguarded rules)

`:hover` has no meaning on touch, but it still applies — and stays applied until
you tap elsewhere. Tapping "Next hand" left it lifted and lightened as though
still under a cursor, and it would have fought the new pressed states directly.
All of them are behind `@media (hover: hover)` now. The one rule that shared a
block with `:focus-visible` was split so keyboard focus survives.

The notes field zoomed the page (iOS)

`#tableNotes` was 13.3px. iOS zooms the viewport when a field under 16px takes
focus, and the dealer is then pinching back out to see the table. Every other
input here was already 16px; this was the straggler.

Seats deliberately have no `:active` rule

Worth writing down because it nearly went in. A seat's `transform` is what
positions it around the felt, so a pressed state setting `transform` drops the
`translate(-50%, -50%)` and throws every pressed seat ~38px off its spot.
Validation caught it: seats already dip via `.seatPressing`, which `pointerdown`
adds in render.js — earlier than `:active` resolves, and it restates the
translate correctly.

Validated with Playwright at 390x844: 53/53 controls off `touch-action: auto` and
0 tap-highlighted across the table, all four overlays and Quick Split; text
fields still selectable and buttons not; 14/14 hover rules gated; presses
measured live via mouse-down (fold reads translateY(1px)/brightness(1.3), a seat
holds its translate with 2px of drift from the shrink alone). Hand played through
the UI including a double-tap fold. No console errors. Unit tests 58/58.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 03:11:39 -06:00
jheapsandClaude Opus 5 c1a484b97a Pay down the Hold'em dealer's tech debt and give it a test suite
Every module in the dealer ends with a `module.exports` guard, so they were all
written to be testable, and none of them were ever tested. The correctness fixes
that went in recently were checked by hand in a browser console that has since
been closed. This puts a real safety net under them and clears out the
duplication that made those bugs possible in the first place.

Tests (58, ~300ms, no dependencies)

Node's built-in runner, no package.json and no install step: the modules are
plain script-tag files, so `load.js` just requires them and puts them on
globalThis under the names they use to find each other in the page.

The randomised suite is the part that matters. Every bug found in this tool so
far has been shape-dependent — blinds posted to empty chairs, the button
skipping players, heads-up acting out of order — and none of them show up on the
full six-handed table anyone would write a fixed example for. It deals 1000
hands per property across random seat counts, empty chairs, stack depths and
dealer input, checking that chips are never created or destroyed, that the pot
breakdown plus uncalled returns equals the money in, that paying out settles to
the cent, and that the button and blinds always land on real players. The
generator is seeded so a failure reproduces instead of flaking.

One implementation each

- `Math.round(x * 100) / 100` was written out 16 times across 6 files. It's
  `Money.round` / `toCents` / `fromCents` now, in the module both pages already
  load first.
- The chip epsilon was declared twice with the same value under two names
  (`PotCalculator.EPSILON`, `Betting.EPSILON_CHIPS`). Both now point at
  `Money.EPSILON`.
- `Betting.seatAt` and `HoldemState.nextSeatIndex` were the same modular
  arithmetic written twice. Walking the seats is exactly where the button, the
  blinds and the action drifted apart from each other before, so there is one
  of it now.
- The undo snapshot/restore dance appeared three times in main.js, each one
  re-deleting every key on `state` in place. It's `snapshotState` /
  `restoreState` once, with the reason it can't just reassign written down.

A bug the tests found

`layers()` and `uncalledReturns()` both decide what money was never contested,
separately, and disagreed. `uncalledReturns` measured each player against the
biggest live contribution *including their own*, which makes the biggest bet its
own yardstick — so the one case it exists for came back empty, and `layers()`
announced the overbet as a side pot only the bettor could win.

With Ann shoving 200 into Ben's 60, the dealer was told "main pot 4, side pot 3,
side pot 116, side pot 140" — four pots, one of them fictional. It now reads
"main pot 123, uncalled 140 back to Ann", which is what a dealer says out loud.
Layers are derived from contributions with the uncalled money already removed,
so the two can't disagree again. A band every payer folded out of is now merged
into the pot below rather than dropped, which was quietly shrinking the
announced pot in another edge case.

Validated with Playwright against a real hand on both surfaces — the table's
live pot readout and Quick Split's all-in mode — plus undo, with no console
errors.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 03:00:36 -06:00
jheaps ae8744672f Merge remote-tracking branch 'origin/feature/casino-quicksplit-side-pots' into feature/casino-holdem-dealer-batch 2026-09-01 02:38:01 -06:00
jheaps 328ef56af5 Merge remote-tracking branch 'origin/feature/casino-holdem-contrast' into feature/casino-holdem-dealer-batch 2026-09-01 02:38:01 -06:00
jheaps 7714e16547 Merge remote-tracking branch 'origin/feature/casino-holdem-touch-audit' into feature/casino-holdem-dealer-batch 2026-09-01 02:38:01 -06:00
jheaps cc31cd033b Merge remote-tracking branch 'origin/feature/casino-holdem-wizard-polish' into feature/casino-holdem-dealer-batch
# Conflicts:
#	JoshHeaps.Net/wwwroot/js/casino/holdem/potWizard.js
2026-09-01 02:38:01 -06:00
jheaps f324793732 Merge remote-tracking branch 'origin/feature/casino-holdem-seat-count-safety' into feature/casino-holdem-dealer-batch 2026-09-01 02:37:41 -06:00
jheaps 56d9d740b5 Merge remote-tracking branch 'origin/feature/casino-holdem-odd-chip' into feature/casino-holdem-dealer-batch 2026-09-01 02:37:41 -06:00
jheaps e5b02b00e4 Merge remote-tracking branch 'origin/feature/casino-holdem-button-moves' into feature/casino-holdem-dealer-batch 2026-09-01 02:37:41 -06:00
jheaps 34cd7dbc59 Merge remote-tracking branch 'origin/feature/casino-holdem-allin-runout' into feature/casino-holdem-dealer-batch
# Conflicts:
#	JoshHeaps.Net/wwwroot/js/casino/holdem/betting.js
2026-09-01 02:37:41 -06:00
jheapsandClaude Sonnet 5 4f72dda6fa Ask before a smaller table deletes the players sitting in it
Typing a smaller number into "Seats at table" silently threw away every seat past
the new count. Nine players down to six removed three of them — names, stacks and
buy-ins gone, no confirmation, no way back.

It also quietly falsified the settle-up. Those players keep their rows in the
session standings, because the hand log remembers who won what, but the seat they
were read from no longer exists — so a player who had just won a pot showed as
having bought in for nothing and holding nothing.

Shrinking now says who it is about to remove and asks, and either way the change
is undoable like the rest of the table's actions. Growing the table, and
shrinking onto chairs nobody is sitting in, still happen without a word.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 02:33:03 -06:00
jheapsandClaude Sonnet 5 cc1b5011a1 Give the odd chip to the player the rule says gets it
Quick Split tells the dealer a leftover chip goes "to the first player left of
the button". The pot wizard, on the same tool, handed it to whoever the dealer
happened to tick first. Two screens, same split, different answer.

The wizard now orders the winners around the table from the button before the
calculator shares the pot out, so the leftover lands where the instruction says
it does. The calculator itself is unchanged — it already gave leftovers to the
front of the list, it was just being handed the list in the order the checkboxes
were clicked.

It's pennies, but it's pennies in front of the person who didn't get them, and a
dealer who has just read the other screen's instruction out loud looks wrong.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 02:05:57 -06:00
jheapsandClaude Sonnet 5 18bb23ad6d Pass the button to the next player, not the next chair
The button moved one seat per hand regardless of whether anyone was sitting
there. At a ten-seat table with four players — an ordinary home game — it spent
five hands out of eight on an empty chair.

That reads as untidy, but the real problem is fairness. Position and the blinds
are meant to come round to each player at the same rate. Rotating past empty
chairs breaks that: a player with three empty seats to their right takes the
button far less often than one sitting in a cluster, while both pay blinds every
time the rotation reaches them.

The button now skips to the next seat that's actually dealt in, so with four
players it visits those four in turn and each takes it once every four hands.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 01:50:16 -06:00
jheapsandClaude Sonnet 5 ae591e4212 Stop asking all-in players to act
A player who is all-in is still in the hand and still wins pots, but has nothing
left to decide. The engine didn't know that: it picked the next player to act by
walking to whoever was still in the hand, chips or no chips.

So a dealer with three players all-in pre-flop was asked to check for each of
them on the flop, the turn and the river — nine taps to say nothing — and the
action could land mid-street on someone who'd already pushed their last chip in.

Now the action passes over players who are all-in, and once fewer than two
people have chips left the betting is simply over: the bar runs Deal Flop, Turn,
River, Showdown straight through, and says "All-in — running out the board" so
the absence of a question reads as deliberate rather than as a stuck screen.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 01:37:19 -06:00
jheapsandClaude Sonnet 5 89d79a0f7d Post the blinds to the players rather than to the chairs
Blinds were assigned by seat offset — always button+1 and button+2 — which is
only right when everyone is dealt in and there are three or more of them.

Heads-up it had the blinds backwards. The button posted the big blind and acted
second before the flop; the rule is the opposite on both counts. That's the end
of every home tournament, dealt wrong.

Worse, the offsets don't care whether anyone is sitting in those chairs. With
two players at a nine-handed table, or with the seats left of the button sitting
out, the blinds landed on empty seats and simply weren't posted — no money in
the middle, and SB/BB badges pointing at nobody.

Blinds now walk the players who are actually dealt in, starting from the button,
with heads-up as its own case: the button is the small blind, acts first
pre-flop, and the big blind acts first afterwards. The badges come from the same
function as the money, so what the table shows and what gets posted can't
disagree.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 01:22:15 -06:00
jheapsandClaude Sonnet 5 d0f75d0c14 Lift the faint greys to something readable in a dim room
This is a dark interface used in poker rooms and kitchens with the lights down,
and I'd been generous with grey-on-black. Measured every piece of text against
what's actually painted behind it: thirteen declarations came in under 4.5:1.

The worst was the empty card slot's "+" at 2.63:1 — an affordance telling the
dealer the slot is tappable, and the least legible thing on the screen. Then a
run of #777 labels around 3.9 to 4.1: the standings header, the time on a logged
hand, the currency mark in the add-chips field. The rulings source line sat at
3.62 and the rulings link itself at 4.39.

All of them move up just far enough to clear 4.5 rather than being flattened to
white, so the hierarchy between a heading, a value and a hint survives.

Worth recording what the measurement can't see: it reads background-color, so
text on a gradient — the pot badge, the dealer button, the blind badges — comes
back as a false result in both directions, and those were checked by eye
instead. The felt watermark is deliberately at 6% and stays that way.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 01:06:20 -06:00
jheapsandClaude Sonnet 5 6b3a7dc09d Bring every phone target up to size, not just the ones I happened to check
Last round I measured one screen and found the smallest targets in the tool were
on it. So I measured all of them: sixty-four controls at phone width, flagging
anything under 44px. Twenty-three came back.

The sidebar had never had the touch pass the seat form got — its inputs, selects
and small buttons sat at 26 to 30px, and the buttons that delete a chip colour
or a custom field were 28px wide, which is a bad size for something destructive.
The rulings link was a 14px-tall underlined word.

The seat form itself had drifted: its mobile sizing rule named five fields, and
the stack field added two rounds later wasn't one of them, so it sat at 28px
beside its 44px neighbours. Both that rule and the new sidebar one are now
written against the form and the panel rather than a list of field names, so the
next field added inherits the size instead of waiting to be noticed.

The dealer button keeps its 22px disc — it's a chip sitting on a seat, and
drawing it thumb-sized would swallow the puck — but takes taps through an
invisible 44px pad. Verified the seat underneath still gets its own taps.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 00:38:29 -06:00
jheapsandClaude Sonnet 5 38488f2978 Give the pot wizard the same tap targets as everything else
Measured the screen where the money actually gets decided and found the smallest
targets in the tool: 37px winner rows, 13px checkboxes, a 36px confirm. Every
other surface has been held to 44px and up for several rounds — the one place a
mis-tap pays the wrong player was the one place that hadn't been.

Winner rows are now 56px and up, with a 22px box and a green fill when chosen,
because a dealer confirms this with players watching and a small checkbox is
easy to misread across a table. The row already was the tap target; now it looks
like one.

Each row also splits into name, what they can win, and their cards as separate
pieces rather than one run-on sentence, so the hand can be read at a glance. The
confirm takes the full width, and on a phone the summary's buttons stack with
the one that ends the hand furthest from a stray thumb.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 00:22:14 -06:00
jheapsandClaude Sonnet 5 7c64749267 Let Quick Split handle the pot it used to send people away for
Quick Split answered the easy half of the question and printed a footnote for
the hard half: if somebody was all-in for less, go set up the full table. That's
the moment a dealer least wants to be setting up a table.

A second mode takes what each player put in and lists the main pot and each side
pot with who can win it, plus anything uncalled that goes back. Rows can be
marked folded, so dead money lands in the right pot without its owner being able
to win it. The running total is shown so the breakdown can be checked against
the chips actually on the table.

It reuses the same pot maths as the full table rather than growing a second
implementation, which means the two screens can't drift apart and Quick Split
inherits the uncalled-bet and everyone-folded handling that was fixed there.

Also fixes hiding: these sections carry a `display` declaration, which outranks
the browser's own [hidden] rule, so toggling `hidden` on them did nothing and
both modes' controls showed at once.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-09-01 00:07:37 -06:00
jheaps e8d6098d39 Merge pull request 'Add chips to a seat without leaving the table' (#32) from feature/casino-holdem-rebuys into master
Build and Deploy / build-deploy (push) Successful in 1m7s
Reviewed-on: #32
2026-08-31 23:57:01 -06:00
jheaps 5d1a6b7399 Merge branch 'master' into feature/casino-holdem-rebuys 2026-08-31 23:56:53 -06:00
jheaps a816b32426 Merge pull request 'A rulings reference for the calls that come up mid-hand' (#30) from feature/casino-holdem-rulings into master
Build and Deploy / build-deploy (push) Canceled after 31s
Reviewed-on: #30
2026-08-31 23:56:40 -06:00
jheaps 5271d5fbad Merge branch 'master' into feature/casino-holdem-rulings 2026-08-31 23:56:32 -06:00
jheapsandClaude Sonnet 5 552ec1a542 Add chips to a seat without leaving the table
Somebody rebuying is the most common interruption in a cash game, and the only
way to record it was to open the seat editor and retype a stack from memory.

Press and hold a seat and there's now "Add chips…": quick amounts off the
table's starting stack — half a buy-in, a buy-in, two — with a keypad for the
times it isn't one of those. It's undoable like every other seat action, and it
records cash handed over as well as chips added, because those answer different
questions. The stack moves every hand; what a player has paid in only moves
when they buy.

The export gains bought in, chips now, and up/down, so settling up at the end of
the night is reading a row rather than reconstructing it.

Getting that last column right needed care. Chips in front of a player disagree
with the hand log for as long as a hand is open — and since blinds post the
instant the previous hand settles, that window is almost always. Counting what a
player already has in the current pot as still theirs makes the cash position
agree with the hand log at any moment, including across a rebuy.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 23:53:15 -06:00
jheaps 5c807d1581 Merge pull request 'Feature/casino holdem sidebar polish' (#31) from feature/casino-holdem-sidebar-polish into master
Build and Deploy / build-deploy (push) Successful in 1m5s
Reviewed-on: #31
2026-08-31 23:36:45 -06:00
jheaps a5b9c26902 Merge branch 'master' into feature/casino-holdem-sidebar-polish 2026-08-31 23:36:37 -06:00
jheapsandClaude Sonnet 5 9a5b974fda Add a rulings reference for the calls that come up mid-hand
The tool handles the money; the other half of dealing is the calls. A home-game
dealer who isn't a pro has to rule on a misdeal or a prematurely turned board
card with a table watching, and the usual outcome is an argument settled by
whoever is loudest.

A "Common rulings" link under the table opens a reference for exactly the
situations that come up: what counts as a misdeal, what to do when the fourth
board card gets turned before the betting is finished, and how acting out of
turn is normally treated. It follows the Tournament Directors Association
rules, and says plainly that house rules win and that a dispute gets settled
between hands rather than during one.

It's a sheet rather than a sixth sidebar panel — a dealer consults this rarely
and needs it immediately, which is the opposite of what a panel is for.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 23:35:59 -06:00
jheaps b563a56563 Merge pull request 'Put bets on the felt as chips instead of numbers in a box' (#29) from feature/casino-holdem-bet-chips into feature/casino-holdem-sidebar-polish
Reviewed-on: #29
2026-08-31 23:35:28 -06:00
jheapsandClaude Sonnet 5 72ee2fb2b7 Put bets on the felt as chips instead of numbers in a box
The seat puck showed a green figure that meant "what this player just bet"
during a street and "what they've put in this hand" between streets — two
different numbers wearing the same badge, sitting directly above their stack
size. Easy to misread, and nothing on the table looked like money.

Bets now sit on the felt between their player and the pot, as a chip coloured
by the largest denomination in the chip legend that fits the amount: a $30 bet
shows green against a $25 chip, a $2 bet shows white. When a street closes the
chips come off the felt and the pot badge keeps the money, the way they'd be
swept in. The puck's figure now always means the same thing — this player's
total for the hand.

On a phone the bet clings to its own puck instead of sitting on its own ring.
That isn't a preference: sweeping every radius between the seat ring and the
pot badge at 390px showed each one collides with either the pucks or the pot,
because the felt has no room for a third ring at that size.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 23:24:39 -06:00
jheapsandClaude Sonnet 5 ae927983e7 Tidy the sidebar down from five panels to four
Each round added a panel, and the sidebar became five identical dark accordions
with no hierarchy between them — which is the polish debt I've been pointing at
for a while without paying it down.

Session Standings and Hand History were always two views of the same log, so
they're one Session panel now, with subheads and the export and clear buttons
at the bottom where they act on both. Base pot amount is the pre-live-betting
way of working, so it moves into a "Without live betting" disclosure inside
Table Setup rather than sitting between two settings a dealer actually touches.
Panels are ordered by how often they're opened, and the hints are shorter.

Also stops "Small blind" wrapping onto two lines beside its input, which made
the pair look like a mistake rather than a pair.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 23:06:30 -06:00
jheapsandClaude Sonnet 5 4ceeed71a2 Add keyboard control for a dealer working on a laptop
The phone got gestures a few rounds back; the desktop still had a mouse and
nothing else. On a bar that gets tapped thirty times a hand, moving a hand to
the trackpad between every decision is the slow part.

F folds, C checks or calls, R opens the raise pad, A shoves, Enter confirms a
raise or moves the hand on, Esc backs out, U takes the last action back. Each
button wears its key in the corner, hidden on touch devices where it would just
be clutter on a button being tapped anyway.

The shortcuts press the same buttons a dealer would tap rather than calling the
betting engine themselves, so there's no second code path to drift out of step
with what the bar is actually offering — if a button isn't on screen, its key
does nothing.

Nothing fires while a name, amount or note is being typed, or while an overlay
owns the keyboard. Typing "Francesca" into a seat name must not fold the table.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 22:52:52 -06:00
jheapsandClaude Sonnet 5 95c523738c Let the dealer take back an action from the bar
An audit of what's accumulated turned up an inconsistency worth fixing: double-
tapping a seat to fold someone was undoable, but tapping Fold in the action bar
— the button a dealer actually uses all hand — was not. Nor was Call, Raise, or
dealing a street. The safest path through the tool was the shortcut, and the
main one had no way back.

Every action taken from the bar now goes through one place that records it
first, and the bar carries a standing Undo naming what it will take back:
"Ben's fold", "dealing the flop". Twelve steps deep, because a misclick usually
gets noticed a beat late and one level of undo would only cover the luckiest
case.

It's a control rather than a toast per action. A dealer taps this bar
constantly, and a toast after every fold is noise they'd learn to ignore —
which is precisely when they'd miss the one that mattered.

The history is discarded whenever a hand starts or settles, because those
snapshots describe a hand that no longer exists. The whole-hand Undo on the
toast already covers that boundary.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 22:37:03 -06:00
jheapsandClaude Sonnet 5 1fcc058dd8 Show how long the current player has been thinking, and how many are left
Dealing guides put the biggest time sink not in shuffling or spreading cards
but in players who haven't noticed the action is on them — and they list the
per-street count of players remaining as part of what a dealer announces.

The action bar now carries both. A stopwatch runs on whoever is to act, going
amber at thirty seconds and red at a minute, so a dealer can see at a glance
whether someone is genuinely deciding or has stopped paying attention. Nothing
happens when it grows; it is a prompt for the dealer, not a clock on the
player. Beside it is the count of players still in the hand.

The timer restarts only when the action actually moves, so re-rendering for an
unrelated reason doesn't put a thinking player back to zero, and it ticks by
repainting its own text rather than rebuilding the buttons under the dealer's
thumb. It stops when the hand ends or the bar hides.

Also stops the side-pot breakdown from crying wolf: it now waits for someone to
actually be all-in. Unequal amounts in front of players are normal mid-street —
the blinds alone are unequal — and layering those announced a side pot on every
hand before anyone had acted.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 22:21:39 -06:00
jheapsandClaude Sonnet 5 ee25e2a4fa Show the side-pot breakdown before the showdown, not after
Dealing guides are consistent that the most common side-pot error isn't
miscounting the chips, it's failing to announce the breakdown clearly before
the showdown. The tool had the arithmetic right but only revealed it after the
hand, one layer at a time, as the wizard asked who won each.

The breakdown is now visible while the hand is still running: as soon as an
all-in splits the money, the action bar lists the main pot and each side pot
with the amount and who can win it, and the wizard repeats it under "Announce
before the showdown" before asking for a winner. A hand with a single
undivided pot shows nothing, so the line means something when it appears.

Chips nobody could call are called what they are. Money above the largest live
contribution was never contested — usually an overbet by someone who then
folded — so it's listed as "Uncalled, back to X" rather than padding a side
pot nobody can win. The wizard's leftover warning says the same thing instead
of telling the dealer to un-fold someone to win it, which was the wrong advice
for chips that should simply be pushed back.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 22:10:19 -06:00
jheapsandClaude Sonnet 5 dabf1100c9 Add double-tap and press-and-hold shortcuts to the seats
Folding someone meant opening their editor, finding the Fold box, ticking it,
and dismissing the sheet — four interactions for the thing that happens most
often in a hand.

Double-tap a seat to fold, and again to put them back. Press and hold for a
quick menu of everything else you do to one player: fold, all-in, sit out or
deal in, hand them the button, or open the full editor. Both are undoable the
same way the header buttons are, because a gesture is easier to fire by
accident than a button.

The single tap now waits out the double-tap window before opening the editor —
a fifth of a second of latency on opening a form, in exchange for a fold that
doesn't also fling a sheet up over the table. A press that moves is a drag, so
the hold is cancelled and swapping seats still works, and the puck shrinks
slightly while held so a press that's being counted looks different from one
that's being ignored.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 21:54:56 -06:00
jheapsandClaude Sonnet 5 0759d89d13 Pick hole cards from a grid instead of typing them
Typing "AH" into a two-character box is fine at a desk and miserable at a table:
it needs a keyboard, it accepts nonsense like "ZZ", and it happily deals the same
card to two players.

The two card fields become face-up card slots. Tapping one opens a 52-card grid
— four suit columns, thirteen rank rows, one tap per card — and picking the first
card moves straight on to the second, because a dealer picking hole cards is
always picking two. Cards already dealt elsewhere at the table are greyed out and
say who has them, so a duplicate is visibly out of play rather than silently
accepted.

Cards are still stored as the same two plain characters everything has always
read; the suit only becomes a symbol on its way to a human. That formatting is
now shared, so the table pucks, the seat editor, the pot wizard, the hand history
and the CSV all say A♥ K♦ rather than three of them saying AH KD.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 21:32:43 -06:00
jheaps 01a1728971 Merge pull request 'Live betting: tap the action instead of typing totals' (#21) from feature/casino-holdem-live-betting into master
Build and Deploy / build-deploy (push) Successful in 1m11s
Reviewed-on: #21
2026-08-31 19:19:16 -06:00
jheapsandClaude Sonnet 5 7bedee2934 Track the betting live so the dealer taps instead of types
Until now a dealer kept the money in their head and typed each player's total
into a form. This adds the running hand: blinds post themselves, every seat has
a stack, and one tap per decision moves the action on.

The bar sits at the bottom of the screen where a thumb already is, and shows
only what's true right now — Fold, then Check or Call with the amount owed, then
Bet or Raise. Calling more than a player has left says "Call all-in" rather than
quoting a number they can't cover. Raising offers min, half pot, pot and all-in
before it offers a keypad, because a dealer calling "raise to sixty" wants a
button. When everyone has answered, the bar becomes Deal Flop, then Turn, River,
and finally Showdown, which hands off to the pot wizard that already existed.
Winnings go straight back in front of the winner, so the next hand's stacks are
already right.

The money hooks into what was already there rather than running beside it: a
street's chips sweep into each seat's amountOverride, the same field the pot
badge, the pot wizard, the session standings and the CSV export all read. So
nothing downstream changed, and a dealer who prefers the old typed workflow
still has it.

Tables saved before this exist without any of these fields, so load() fills
them in rather than making someone reset a table mid-session.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 19:01:08 -06:00
jheaps 7143e4e701 Merge pull request 'Feature/casino holdem undo toasts' (#19) from feature/casino-holdem-undo-toasts into master
Build and Deploy / build-deploy (push) Successful in 1m15s
Reviewed-on: #19
2026-08-31 18:41:22 -06:00
jheaps e8797b8dc2 Merge branch 'master' into feature/casino-holdem-undo-toasts 2026-08-31 18:41:13 -06:00
jheaps 48bd3682f2 Merge pull request 'Make the four seat states readable across the table' (#18) from feature/casino-holdem-seat-legibility into feature/casino-holdem-undo-toasts
Reviewed-on: #18
2026-08-31 18:39:58 -06:00
jheapsandClaude Sonnet 5 1e1bdcccce Make the four seat states readable across the table
A seat could be live in the hand, folded, sitting out, or empty, and three of
those looked nearly the same: a plain dark puck, or a dimmed one. An unclaimed
chair was indistinguishable from a nameless player, and nothing positively said
"this player is in" — the dealer had to infer it from whether a dollar badge
happened to be showing.

Each state now has one look. Live gets a green edge. Folded gets a red edge and
a struck-through name, so it reads as out rather than merely faint. An empty
chair is the only dashed outline and says so. Sitting out just fades — and
fades less than it used to, since that player is still someone the dealer may
need to deal back in, and at 0.4 the name was nearly gone.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 18:36:54 -06:00
jheaps aee172a5cd Merge pull request 'Quick Split: chop a pot from your phone without setting up a table' (#15) from feature/casino-holdem-quick-split into master
Build and Deploy / build-deploy (push) Successful in 1m14s
Reviewed-on: #15
2026-08-31 18:33:05 -06:00
jheaps d206758729 Merge branch 'master' into feature/casino-holdem-quick-split 2026-08-31 18:32:56 -06:00
jheaps 4afc3649cc Merge pull request 'Make the dealer table usable on a phone' (#16) from feature/casino-holdem-mobile-table into feature/casino-holdem-quick-split
Reviewed-on: #16
2026-08-31 18:31:52 -06:00
jheaps 3866bdb335 Merge pull request 'Replace the browser confirm boxes with undo and in-page dialogs' (#17) from feature/casino-holdem-undo-toasts into feature/casino-holdem-mobile-table
Reviewed-on: #17
2026-08-31 18:31:40 -06:00
jheaps 71b33f8623 Merge pull request 'Give the Hold'em dealer a session record: hand history, CSV export and standings' (#14) from feature/casino-holdem-hand-history into master
Build and Deploy / build-deploy (push) Successful in 1m13s
Reviewed-on: #14
2026-08-31 18:31:19 -06:00
jheapsandClaude Sonnet 5 d01c67fc45 Replace the browser confirm boxes with undo and in-page dialogs
Three system confirm() dialogs sat in the middle of dealing. The worst was on
Next Hand — the most-pressed button in a session, asking "are you sure?" every
single time, stealing focus and, on a phone, taking over the screen.

Next Hand now just happens, and a toast says where the button landed with an
Undo beside it for the few seconds anyone would notice a misclick. The same
undo covers the pot wizard, which is the more valuable case: paying the wrong
player is a real mistake, and rolling it back restores the hand history entry
and the session standings along with the seats. The snapshot is in-memory only
— an undo is for the mistake you just made, not one from last night.

The two genuinely destructive actions keep a confirmation, but as an in-page
dialog that matches the table instead of the browser's own: Escape or the
backdrop cancels, Enter confirms, and on a phone the buttons go full width with
Cancel nearest the thumb.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 18:22:50 -06:00
jheapsandClaude Sonnet 5 a39675f975 Make the dealer table usable on a phone
Two things were broken on a narrow screen. The seat ring is drawn on a radius
measured from the table wrap, so at phone width the left- and right-most seats
hung off the edge of the viewport — at a ten-handed table two players were
simply not on screen. And tapping a seat opened an editor far enough down the
page that it looked like nothing had happened.

The ring is now inset by half a puck on phones, which keeps every seat on
screen, and the pucks are narrower there so neighbours stop overlapping where
the ring flattens out at the top and bottom. The seat editor becomes a bottom
sheet that slides up over the table: grip, Done button, tap the same seat again
to dismiss, table still visible above it. Its controls grow to thumb size, and
every field goes to 16px — below that iOS zooms the page on focus and the
dealer has to pinch back out mid-hand.

Header actions become full-width tap targets, and the page padding tightens to
give the table the width it needs. Nothing above 700px changes.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 18:11:09 -06:00
jheapsandClaude Sonnet 5 870dee4a29 Add a phone-first Quick Split screen for chopping a pot mid-hand
The dealer table is a two-handed, big-screen tool. A dealer standing over a
chopped pot with a phone in one hand and players waiting needs an answer in
seconds, not a table to set up first — so /casino/texasholdem/quicksplit is
the whole job on one screen: type the pot, tap how many ways, tap the
smallest chip in play, read the payout. Nothing to configure, nothing saved.

It splits in whole chips rather than raw arithmetic, because a dealer can't
push half a chip across the felt: everyone gets the same stack and the
remainder is called out as odd chips going one at a time to the first
players left of the button. A pot that doesn't divide into the chosen
denomination says so instead of quietly hiding the difference.

Money formatting moves out of render.js into its own file so this screen can
use it without pulling in the whole seat/chip UI.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 17:53:18 -06:00
jheapsandClaude Sonnet 5 bcfc1f2f52 Track session standings so the dealer can settle up at the end of the night
The hand log answered "what happened in hand 12"; it couldn't answer "what
does Alice owe". Each resolved pot now records a per-seat ledger (what that
player put in, what they took down) alongside the payouts, and a Session
Standings panel sums it into one row per player — paid in, won, net, sorted
by who's up. The CSV export carries the same table, so one file covers both
the hand-by-hand trail and the cash-out numbers.

Keyed by seat id rather than name, so renaming or reseating a player doesn't
split their totals. Hands recorded before this change have no ledger and are
skipped rather than counted wrong.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 17:37:48 -06:00
jheapsandClaude Sonnet 5 d168fedf1f Add a CSV export for the Texas Hold'em hand history log
A dedicated dealer needs a paper trail that outlives the browser tab, not
just a scrollable in-app panel — the Export CSV button downloads the full
resolved-pot log (hand #, time, pot, payouts) for recordkeeping or a
disputed chip count after the session ends.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
2026-08-31 17:26:11 -06:00
jheapsandClaude Sonnet 5 68e263f325 Add a persistent hand history log to the Texas Hold'em dealer tool
Give the dealer a running record of resolved pots — hand number, total
pot, who got paid what, and the time — instead of losing that
information the moment the pot wizard closes. It's the kind of audit
trail a real dealer needs when a chip count gets disputed after the
fact.

- state.js tracks state.handNumber and state.handHistory (capped at 200
  entries) and persists both through the existing localStorage save/load
  path, with backfill defaults for tables saved before this change.
- potWizard.js now hands its final payouts back to the caller instead of
  discarding them once "Start Next Hand" is clicked.
- main.js records a history entry (skipping hands where nobody actually
  won anything) before advancing to the next hand, and wires up a "Clear
  history" control that also resets the hand counter.
- A new sidebar panel lists history entries newest-first; the header
  shows a running "Hand #N" badge next to the existing subtitle.

Verified via Playwright MCP: seated two players, resolved a pot, and
confirmed the header's hand counter incremented, the history panel
listed the payout, the entry survived a full page reload (localStorage
persistence), and Clear History reset both the log and the counter. No
console errors during the flow.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01C3NiiUDimoKDJ8GjC3KL3x
2026-08-31 17:15:23 -06:00
jheaps 105a74bc51 Merge pull request 'Feature/casino texas holdem' (#13) from feature/casino-texas-holdem into master
Build and Deploy / build-deploy (push) Successful in 1m11s
Reviewed-on: #13
2026-08-31 16:06:56 -06:00
jheaps dce7e0f688 Merge pull request 'Add dedicated-dealer mode and redesign the Hold'em table' (#12) from feature/casino-holdem-dealer-mode-polish into feature/casino-texas-holdem
Reviewed-on: #12
2026-08-31 15:58:17 -06:00
jheapsandClaude Sonnet 5 3851786b90 Add dedicated-dealer mode and redesign the table's visuals
Add a "Dedicated dealer (not a seat)" toggle for tables run by someone
outside the game: it hides every seat's dealer button while blinds keep
rotating automatically off the same internal position each hand.

Also gave the table a real casino look, based on reference felt/rail and
seat-pod patterns found via web search (huggingface.co/spaces/Estazz/
PokerGameDesigner, github.com/Tehes/poker): a richer radial felt gradient,
a gold piping ring inside a wood-toned rail, a subtle center watermark, a
pill-shaped chip-well pot badge, softer seat pucks with a pill-badge total
and red/black suit coloring on cards, and casino-chip-styled dealer/blind
badges (the dealer chip now dims to a faint disc on other seats and only
lights up on hover, decluttering the ring of ten clickable buttons down to
one visible button on the actual dealer).

Verified via Playwright MCP: toggle hides/reveals dealer chips correctly,
SB/BB still track it, no console errors.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018CmAti1baCjidbJM2HeJfk
2026-08-31 15:26:32 -06:00
jheaps 8e7d94e6f9 Merge pull request 'Fix Texas Hold'em dealer page: script timing crash and seat overlap' (#11) from feature/casino-texas-holdem into master
Build and Deploy / build-deploy (push) Successful in 1m8s
Reviewed-on: #11
2026-08-31 15:03:37 -06:00
jheapsandClaude Sonnet 5 25bf67062a Fix Texas Hold'em dealer page: script timing crash and seat overlap
main.js ran an IIFE immediately, but the layout renders @section Scripts
inside <head> before <body> exists, so every getElementById() call hit
null. Wrapped init in DOMContentLoaded, matching the rest of the codebase
(e.g. ChessScripts/chessMain.js).

Separately, the original seat cards packed a full data-entry form (name,
toggles, 2 cards, 5 chip counters, $ override, custom fields) into each of
up to 24 positions around a circle — at any screen size, adjacent seats
overlapped badly. Replaced with compact seat "pucks" for the table view
(name, cards, total, blind/dealer badges) plus a dedicated seat editor
panel in the sidebar that opens for whichever seat is clicked.

Verified via Playwright MCP: load with no console errors, drag-and-drop
seat swap, and a 3-way side-pot resolution (short all-in capped correctly,
remainder awarded to the next-best hand) end to end.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018CmAti1baCjidbJM2HeJfk
2026-08-31 15:01:18 -06:00
jheaps 5d71572df6 Merge pull request 'Add Casino demo section with a Texas Hold'em dealer's pot-splitting assistant' (#10) from feature/casino-texas-holdem into master
Build and Deploy / build-deploy (push) Successful in 1m16s
Reviewed-on: #10
2026-08-31 14:39:02 -06:00
jheapsandClaude Sonnet 5 98f95df8fb Add Casino demo section with a Texas Hold'em dealer's pot-splitting assistant
New /casino hub page (Texas Hold'em live, other table games marked coming
soon) and /casino/texasholdem: a drag-and-drop seating table with
auto-rotating blinds, per-seat chip/dollar contribution tracking, and a
side-pot resolution wizard that asks who won and who's next until every
dollar in the pot (including dead money from folds) is assigned.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018CmAti1baCjidbJM2HeJfk
2026-08-31 14:25:44 -06:00
jheaps b7c9227bb8 Merge pull request 'Learn fractional win-rate advantage instead of unbounded plus/minus' (#9) from feature/fractional-learned-weights into master
Build and Deploy / build-deploy (push) Successful in 1m25s
2026-08-31 13:43:09 -06:00
45 changed files with 10913 additions and 1 deletions
+26
View File
@@ -0,0 +1,26 @@
# Unit tests for the Texas Hold'em dealer's money logic.
#
# The betting engine, the side-pot calculator and the table state are plain script-tag
# modules with no build step, so they run directly under Node's built-in test runner —
# no package.json, no install step, nothing to keep up to date.
name: Hold'em tests
on:
pull_request:
branches: [ "master" ]
push:
branches: [ "master" ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Run Hold'em unit tests
run: node --test tests/holdem/*.test.js
+58
View File
@@ -0,0 +1,58 @@
@page
@model JoshHeaps.Net.Pages.CasinoModel
@{
ViewData["Title"] = "Casino Games";
Layout = "_Layout";
}
<div class="casino-container">
<h1 class="casino-header">Casino Games</h1>
<p class="casino-subtitle">Tools for running table games without doing the math yourself</p>
<div class="games-grid">
<a href="/casino/texasholdem" class="game-card">
<div class="game-icon">🃏</div>
<div class="game-title">Texas Hold'em</div>
<div class="game-description">
A dealer's assistant: seat players around the table, track blinds, chips and
all-ins, then split main and side pots automatically.
</div>
</a>
<a href="/casino/texasholdem/quicksplit" class="game-card">
<div class="game-icon">➗</div>
<div class="game-title">Quick Split</div>
<div class="game-description">
Chop a pot in seconds on your phone — no table setup, just the amount,
how many players are splitting it, and the smallest chip in play.
</div>
</a>
<div class="game-card disabled">
<div class="game-icon">🎲</div>
<div class="game-title">Craps</div>
<div class="game-description">Payout calculator for the table.</div>
<div class="coming-soon">Coming soon...</div>
</div>
<div class="game-card disabled">
<div class="game-icon">🎡</div>
<div class="game-title">Roulette</div>
<div class="game-description">Bet tracking and payout reference.</div>
<div class="coming-soon">Coming soon...</div>
</div>
<div class="game-card disabled">
<div class="game-icon">🂡</div>
<div class="game-title">Blackjack</div>
<div class="game-description">Multi-hand dealer tracker.</div>
<div class="coming-soon">Coming soon...</div>
</div>
</div>
<a href="/" class="home-button">← Back to Home</a>
</div>
@section Styles {
<link href="/css/casino/page.css?v=@ViewData["cssVersion"]" rel="stylesheet" type="text/css" />
}
+11
View File
@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace JoshHeaps.Net.Pages
{
public class CasinoModel : PageModel
{
public void OnGet()
{
}
}
}
@@ -0,0 +1,430 @@
@page
@model JoshHeaps.Net.Pages.Casino.TexasHoldemModel
@{
ViewData["Title"] = "Texas Hold'em Dealer";
Layout = "_Layout";
}
<div id="holdemApp">
<header id="holdemHeader">
<div id="holdemHeaderLeft">
<h1>Texas Hold'em Dealer</h1>
<p class="holdemSubtitle">Seat your players, track the action, split the pot.</p>
<span id="handCounterBadge" class="handCounterBadge">Hand #1</span>
</div>
<div id="holdemHeaderActions">
<a href="/casino/texasholdem/quicksplit" class="holdemBtn" title="Chop a pot without setting up a table">Quick Split</a>
<button id="nextHandBtn" class="holdemBtn" title="Move the button, small blind and big blind to the next occupied seat">Next Hand ⟳</button>
<button id="resolvePotBtn" class="holdemBtn holdemBtnAccent">Resolve Pot</button>
<button id="resetTableBtn" class="holdemBtn holdemBtnDanger">Reset Table</button>
<a href="/casino" class="holdemBtn holdemBtnGhost">← Casino</a>
</div>
</header>
<div id="holdemLayout">
<section id="tableSection">
<div id="pokerTableWrap">
<div id="pokerTable">
<div id="tableWatermark" aria-hidden="true">Texas Hold'em</div>
<div id="potBadge">
<span id="potBadgeLabel">Pot</span>
<span id="potBadgeAmount">$0</span>
</div>
</div>
<div id="betsLayer" aria-hidden="true"></div>
<div id="seatsLayer"></div>
</div>
<p id="tableHint" class="tableHint"></p>
<p class="tableHintActions">
<button type="button" id="openRulingsBtn" class="linkBtn">Common rulings</button>
</p>
</section>
<aside id="holdemSidebar">
<section id="seatEditorPanel" class="sidebarPanel seatEditorPanel">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="seatEditorHeader">
<h2 id="seatEditorTitle">Select a seat</h2>
<button id="closeSeatEditorBtn" class="seatSheetClose" aria-label="Done editing this seat">Done</button>
</div>
<div id="seatEditorBody">
<p class="fieldHint">Click a seat at the table to edit their name, cards, chips and anything else.</p>
</div>
</section>
<details class="sidebarPanel" open>
<summary>Table Setup</summary>
<div class="panelBody">
<label class="fieldRow">
<span>Seats at table</span>
<input type="number" id="seatCountInput" min="2" max="24" value="10" />
</label>
<label class="fieldRow">
<span>Blinds move</span>
<select id="directionSelect">
<option value="clockwise" selected>Clockwise</option>
<option value="counterclockwise">Counterclockwise</option>
</select>
</label>
<label class="fieldRow">
<span>Dedicated dealer (not a seat)</span>
<input type="checkbox" id="dedicatedDealerToggle" />
</label>
<p class="fieldHint">Turn this on if a person outside the game deals — no seat shows the dealer button, but blinds still rotate automatically each hand.</p>
<div class="blindsRow">
<label class="fieldRow">
<span>Small blind</span>
<input type="number" id="smallBlindInput" min="0" step="0.5" />
</label>
<label class="fieldRow">
<span>Big blind</span>
<input type="number" id="bigBlindInput" min="0" step="0.5" />
</label>
</div>
<label class="fieldRow">
<span>Starting stack ($)</span>
<input type="number" id="defaultStackInput" min="0" step="1" placeholder="e.g. 200" />
</label>
<p class="fieldHint">Blinds post themselves each hand. Seats without their own stack start here.</p>
<details class="subPanel">
<summary>Without live betting</summary>
<div class="subPanelBody">
<label class="fieldRow">
<span>Base pot amount ($)</span>
<input type="number" id="basePotInput" min="0" step="1" placeholder="e.g. 500" />
</label>
<p class="fieldHint">For tracking a hand by hand instead of tapping the action: everyone is assumed to have put in this much, unless their seat says otherwise.</p>
</div>
</details>
</div>
</details>
<details class="sidebarPanel">
<summary>Session</summary>
<div class="panelBody">
<h3 class="panelSubhead">Standings</h3>
<div class="standingsTableWrap">
<div id="standingsTable">
<div class="standingsRow standingsHeader">
<span>Player</span>
<span class="standingsInHead">In</span>
<span class="standingsWonHead">Won</span>
<span>Net</span>
<span title="Chips in front of them, less the cash they handed over">Cash out</span>
</div>
<div id="standingsList"></div>
</div>
</div>
<p id="standingsEmptyHint" class="fieldHint">Everyone who has bought in shows up here, with what they'd be owed if the night ended now.</p>
<div id="bankReconcile" class="bankReconcile" hidden>
<div class="bankReconcileRow">
<span>Cash taken</span>
<span id="bankCashIn"></span>
</div>
<div class="bankReconcileRow">
<span>Chips in play</span>
<span id="bankChipsInPlay"></span>
</div>
<p id="bankReconcileVerdict" class="bankReconcileVerdict"></p>
</div>
<h3 class="panelSubhead">Hands</h3>
<div id="handHistoryList"></div>
<p id="handHistoryEmptyHint" class="fieldHint">Resolved pots are logged here, in case a chip count is disputed later.</p>
<div class="handHistoryActions">
<button id="exportHistoryBtn" class="holdemBtn holdemBtnSmall">Export CSV</button>
<button id="clearHistoryBtn" class="holdemBtn holdemBtnSmall holdemBtnDanger">Clear history</button>
</div>
</div>
</details>
<details class="sidebarPanel">
<summary>Chip Legend</summary>
<div class="panelBody">
<div id="chipLegendList"></div>
<button id="addChipColorBtn" class="holdemBtn holdemBtnSmall">+ Add chip color</button>
<p class="fieldHint">Give each chip color a value, then count chips on a seat instead of typing a total.</p>
</div>
</details>
<details class="sidebarPanel">
<summary>Table Notes</summary>
<div class="panelBody">
<textarea id="tableNotes" rows="4" aria-label="Table notes" placeholder="Anything else worth tracking — side bets, IOUs, running totals..."></textarea>
</div>
</details>
</aside>
</div>
</div>
<template id="seatTemplate">
<div class="seat" draggable="true">
<div class="seatChairNumber"></div>
<button class="dealerChip" title="Make this seat the dealer button">D</button>
<span class="blindBadge sbBadge">SB</span>
<span class="blindBadge bbBadge">BB</span>
<div class="seatPuckName"></div>
<div class="seatPuckCards"></div>
<div class="seatPuckTotal"></div>
<div class="seatPuckStack"></div>
</div>
</template>
<template id="seatEditorTemplate">
<div class="seatEditorForm">
<label class="fieldRow">
<span>Name</span>
<input type="text" class="seatNameInput" placeholder="Seat" maxlength="24" />
</label>
<div class="seatCardToggles">
<label class="inHandToggle" title="This seat is playing the current hand">
<input type="checkbox" class="inHandCheckbox" />
<span>In hand</span>
</label>
<label class="foldToggle" title="Folded">
<input type="checkbox" class="foldCheckbox" />
<span>Fold</span>
</label>
</div>
<div class="seatCards">
<button type="button" class="cardSlot card1Slot" aria-label="Choose first card"></button>
<button type="button" class="cardSlot card2Slot" aria-label="Choose second card"></button>
</div>
<label class="fieldRow stackRow">
<span>Stack</span>
<input type="number" class="stackInput" min="0" step="1" placeholder="table default" />
</label>
<div class="seatBuyIns" hidden></div>
<div class="seatContribution">
<div class="chipCounts"></div>
<label class="fieldRow amountOverrideRow">
<span>$ amount</span>
<input type="number" class="amountOverrideInput" min="0" step="1" placeholder="auto" />
</label>
<div class="seatTotal">Total: <span class="seatTotalAmount">$0</span></div>
</div>
<div class="customFields"></div>
<button class="holdemBtn holdemBtnSmall addFieldBtn">+ field</button>
</div>
</template>
<template id="chipLegendRowTemplate">
<div class="chipLegendRow">
<input type="color" class="chipColorInput" aria-label="Chip colour" />
<input type="number" class="chipValueInput" min="0" step="0.01" placeholder="value" aria-label="Chip value" />
<button class="holdemBtn holdemBtnSmall holdemBtnDanger removeChipColorBtn">×</button>
</div>
</template>
<template id="chipCountTemplate">
<label class="chipCountRow">
<span class="chipSwatch"></span>
<input type="number" class="chipCountInput" min="0" step="1" value="0" />
</label>
</template>
<template id="customFieldTemplate">
<div class="customFieldRow">
<input type="text" class="customFieldLabel" placeholder="Label" maxlength="20" />
<input type="text" class="customFieldValue" placeholder="Value" maxlength="40" />
<button class="holdemBtn holdemBtnSmall holdemBtnDanger removeFieldBtn">×</button>
</div>
</template>
<template id="standingsRowTemplate">
<div class="standingsRow">
<span class="standingsName"></span>
<span class="standingsIn"></span>
<span class="standingsWon"></span>
<span class="standingsNet"></span>
<span class="standingsCashOut"></span>
</div>
</template>
<template id="handHistoryRowTemplate">
<div class="handHistoryRow">
<div class="handHistoryRowHeader">
<span class="handHistoryHandNumber"></span>
<span class="handHistoryPot"></span>
<span class="handHistoryTime"></span>
</div>
<div class="handHistoryPayouts"></div>
</div>
</template>
<div id="addChipsOverlay" hidden>
<div id="addChipsSheet" role="dialog" aria-labelledby="addChipsTitle">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="addChipsHeader">
<h2 id="addChipsTitle"></h2>
<span id="addChipsSubtitle"></span>
</div>
<div id="addChipsQuick"></div>
<div class="addChipsEntry">
<span class="addChipsCurrency">$</span>
<input type="text" id="addChipsInput" inputmode="decimal" autocomplete="off" aria-label="Amount to add" />
</div>
<div class="addChipsActions">
<button id="addChipsConfirmBtn" class="holdemBtn holdemBtnAccent" type="button">Add to stack</button>
<button id="addChipsCancelBtn" data-modal-close class="holdemBtn holdemBtnGhost" type="button">Cancel</button>
</div>
</div>
</div>
<div id="rulingsOverlay" hidden>
<div id="rulingsSheet" role="dialog" aria-labelledby="rulingsTitle">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="rulingsHeader">
<h2 id="rulingsTitle">Common rulings</h2>
<button id="closeRulingsBtn" data-modal-close class="holdemBtn holdemBtnSmall holdemBtnGhost" type="button">Done</button>
</div>
<p class="rulingsIntro">
The conventions most rooms follow, for the calls that come up mid-hand.
Your house rules always win — and settle a dispute before the next hand,
not during it.
</p>
<section class="ruling">
<h3>Redeal it — misdeal</h3>
<ul>
<li>The first card goes to the wrong seat.</li>
<li>A seat entitled to a hand gets dealt out, or a seat that isn't entitled gets dealt in.</li>
<li>Two or more boxed cards turn up on the initial deal.</li>
<li>Either of the first two cards is exposed by dealer error.</li>
</ul>
</section>
<section class="ruling">
<h3>A board card turned too early</h3>
<p>
If the fourth board card gets turned before the betting round is finished,
that card is out of play for the round. Finish the betting, then burn and
turn what would have been the fifth card in the fourth card's place.
</p>
</section>
<section class="ruling">
<h3>Acting out of turn</h3>
<p>
A one-off is usually just backed up if no one has acted behind them.
Doing it repeatedly is what earns a penalty.
</p>
</section>
<section class="ruling">
<h3>A short all-in doesn't reopen the betting</h3>
<p>
Somebody shoving in less than a full raise — say $3 more when the last
raise was $8 — does not give the players behind them another go. Anyone
who has already acted owes the difference or folds; they don't get to
raise again because a short stack happened to land between them.
</p>
<p>
A player who hadn't acted yet keeps full rights and may still raise, and
the minimum raise stays measured off the last <em>full</em> raise, not
off the short one. The action bar follows this for you.
</p>
</section>
<section class="ruling">
<h3>Chips nobody called come back</h3>
<p>
Bet more than anyone was able to call and the excess is returned to you
before the showdown — it was never contested, so it isn't part of the
pot. The pot breakdown shows it as "uncalled" rather than pretending it's
a side pot you could win.
</p>
</section>
<section class="ruling">
<h3>The odd chip in a split pot</h3>
<p>
When a chopped pot won't divide evenly, the odd chip goes to the first
player left of the button, not to whoever the dealer happened to tick
first. Pot payouts here order the winners that way, so the leftover lands
on the right seat every time.
</p>
</section>
<p class="rulingsSource">
Follows the Tournament Directors Association rules, which most rooms and
home games take their lead from.
</p>
</div>
</div>
<div id="seatMenuOverlay" hidden>
<div id="seatMenuSheet" role="dialog" aria-labelledby="seatMenuTitle">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="seatMenuHeader">
<h2 id="seatMenuTitle"></h2>
<span id="seatMenuSubtitle"></span>
</div>
<div id="seatMenuActions"></div>
<button id="seatMenuCancelBtn" data-modal-close class="holdemBtn holdemBtnGhost" type="button">Cancel</button>
</div>
</div>
<div id="cardPickerOverlay" hidden>
<div id="cardPickerSheet" role="dialog" aria-labelledby="cardPickerTitle">
<div class="seatSheetGrip" aria-hidden="true"></div>
<div class="cardPickerHeader">
<h2 id="cardPickerTitle"></h2>
<button id="cardPickerClearBtn" class="holdemBtn holdemBtnSmall" type="button">Clear</button>
<button id="cardPickerCloseBtn" data-modal-close class="holdemBtn holdemBtnSmall holdemBtnGhost" type="button">Done</button>
</div>
<div id="cardPickerSlots"></div>
<div id="cardPickerGrid"></div>
</div>
</div>
<div id="actionBar" aria-live="polite" hidden></div>
<div id="toastHost" aria-live="polite"></div>
<div id="confirmOverlay" hidden>
<div id="confirmModal" role="alertdialog" aria-labelledby="confirmTitle" aria-describedby="confirmMessage" tabindex="-1">
<h2 id="confirmTitle"></h2>
<p id="confirmMessage"></p>
<div class="confirmActions">
<button id="confirmCancelBtn" data-modal-close class="holdemBtn holdemBtnGhost" type="button">Cancel</button>
<button id="confirmAcceptBtn" class="holdemBtn holdemBtnDanger" type="button">Confirm</button>
</div>
</div>
</div>
<div id="potWizardOverlay" hidden>
<div id="potWizardModal" role="dialog" aria-labelledby="potWizardTitle">
<div class="potWizardHeader">
<h2 id="potWizardTitle">Resolve the Pot</h2>
<button id="closePotWizardBtn" data-modal-close class="holdemBtn holdemBtnGhost">✕</button>
</div>
<div id="potWizardBody"></div>
</div>
</div>
@section Styles {
<link href="/css/casino/holdem.css?v=@ViewData["cssVersion"]" rel="stylesheet" type="text/css" />
}
@section Scripts {
<script src="~/js/casino/holdem/money.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/feedback.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/potCalculator.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/state.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/render.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/cardPicker.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/seatMenu.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/addChips.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/betting.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/actionBar.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/shortcuts.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/potWizard.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/handHistoryExport.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/modal.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/main.js?v=@ViewData["cssVersion"]"></script>
}
@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace JoshHeaps.Net.Pages.Casino
{
public class TexasHoldemModel : PageModel
{
public void OnGet()
{
}
}
}
@@ -0,0 +1,95 @@
@page
@model JoshHeaps.Net.Pages.Casino.TexasHoldem.QuickSplitModel
@{
ViewData["Title"] = "Quick Split";
Layout = "_Layout";
}
<div id="splitApp">
<header id="splitHeader">
<h1>Quick Split</h1>
<p class="splitSubtitle">Chop a pot without setting up a table.</p>
</header>
<div id="modeToggle" class="chipRow" role="group" aria-label="How the money went in">
<button type="button" id="modeEvenBtn" class="choiceChip selected">Everyone matched</button>
<button type="button" id="modeUnevenBtn" class="choiceChip">Someone's all-in</button>
</div>
<div id="splitResult" aria-live="polite">
<div id="splitResultLabel">Each player gets</div>
<div id="splitResultAmount">$0.00</div>
<div id="splitOddNote" hidden></div>
<div id="splitDustNote" hidden></div>
</div>
<div id="unevenResult" hidden aria-live="polite">
<div id="unevenPots"></div>
<p id="unevenEmpty" class="unevenEmpty">Enter what each player put in.</p>
</div>
<section class="splitField unevenOnly" hidden>
<span class="splitLabel">What each player put in</span>
<div id="unevenRows"></div>
<button type="button" id="addPlayerBtn" class="splitBtn splitBtnGhost">+ Add player</button>
</section>
<section class="splitField evenOnly">
<label for="potInput" class="splitLabel">Pot</label>
<div class="potInputWrap">
<span class="potCurrency">$</span>
<input type="text" id="potInput" inputmode="decimal" autocomplete="off"
placeholder="0" aria-label="Pot amount" />
<button type="button" id="clearPotBtn" class="clearPotBtn" aria-label="Clear pot amount" hidden>✕</button>
</div>
</section>
<section class="splitField evenOnly">
<span class="splitLabel" id="waysLabel">Split between</span>
<div id="waysChoices" class="chipRow" role="group" aria-labelledby="waysLabel"></div>
</section>
<section class="splitField evenOnly">
<span class="splitLabel" id="chipLabel">Smallest chip in play</span>
<div id="chipChoices" class="chipRow" role="group" aria-labelledby="chipLabel"></div>
</section>
<div id="splitActions">
<button type="button" id="resetSplitBtn" class="splitBtn splitBtnGhost">Clear</button>
<a href="/casino/texasholdem" class="splitBtn splitBtnGhost">Full dealer table →</a>
</div>
<p class="splitFootnote evenOnly">
If somebody was all-in for less than the others, switch to
<strong>Someone's all-in</strong> above.
</p>
<p class="splitFootnote unevenOnly" hidden>
Pots are listed with who can win each. Award them by hand strength, best hand
first. Nothing here is saved — the <a href="/casino/texasholdem">full table</a>
keeps a log.
</p>
</div>
<template id="unevenRowTemplate">
<div class="unevenRow">
<span class="unevenRowLabel"></span>
<div class="unevenAmountWrap">
<span class="unevenCurrency">$</span>
<input type="text" class="unevenAmount" inputmode="decimal" autocomplete="off" placeholder="0" />
</div>
<button type="button" class="unevenFoldBtn" aria-pressed="false">Folded</button>
<button type="button" class="unevenRemoveBtn" aria-label="Remove player">✕</button>
</div>
</template>
@section Styles {
<link href="/css/casino/quicksplit.css?v=@ViewData["cssVersion"]" rel="stylesheet" type="text/css" />
}
@section Scripts {
<script src="~/js/casino/holdem/money.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/splitCalculator.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/potCalculator.js?v=@ViewData["cssVersion"]"></script>
<script src="~/js/casino/holdem/quickSplit.js?v=@ViewData["cssVersion"]"></script>
}
@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace JoshHeaps.Net.Pages.Casino.TexasHoldem
{
public class QuickSplitModel : PageModel
{
public void OnGet()
{
}
}
}
+1
View File
@@ -64,6 +64,7 @@
<button class="demoButton" onclick="window.location.href='/watch'">Watch Live Chess</button>
<button class="demoButton" onclick="window.location.href='/particles'">Particle Simulator</button>
<button class="demoButton" onclick="window.location.href='/memorylane'">Memory Lane</button>
<button class="demoButton" onclick="window.location.href='/casino'">Casino Games</button>
<button class="demoButton" onclick="window.location.href='https://media.joshheaps.net'">Cloud Image Storage</button>
<button id="MoreFiller" class="demoButton">More coming soon...</button>
</div>
+1 -1
View File
@@ -1,6 +1,6 @@
@{
Layout = null;
ViewData["cssVersion"] = "1.0.7"; // <--- change this once to bust cache
ViewData["cssVersion"] = "1.0.8"; // <--- change this once to bust cache
}
<!DOCTYPE html>
File diff suppressed because it is too large Load Diff
+126
View File
@@ -0,0 +1,126 @@
body {
background: #1a1a1a;
min-height: 100vh;
margin: 0;
padding: 0;
}
.casino-container {
max-width: 1000px;
margin: 0 auto;
padding: 4rem 2rem;
text-align: center;
}
.casino-header {
color: #f5f5f5;
font-size: 2.5rem;
margin-bottom: 0.5rem;
font-weight: 300;
letter-spacing: 0.1em;
}
.casino-subtitle {
color: #a0a0a0;
font-size: 1rem;
margin-bottom: 4rem;
font-weight: 300;
}
.games-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
margin: 3rem auto;
max-width: 900px;
padding: 0 1rem;
}
.game-card {
background: #2a2a2a;
border: 1px solid #3a3a3a;
border-radius: 4px;
padding: 2rem 1.5rem;
transition: all 0.3s ease;
cursor: pointer;
text-decoration: none;
color: inherit;
display: flex;
flex-direction: column;
align-items: center;
}
.game-card:hover {
background: #2f2f2f;
border-color: #4a4a4a;
transform: translateY(-2px);
}
.game-card.disabled {
opacity: 0.4;
cursor: not-allowed;
}
.game-card.disabled:hover {
background: #2a2a2a;
border-color: #3a3a3a;
transform: none;
}
.game-icon {
font-size: 2.5rem;
margin-bottom: 1rem;
opacity: 0.9;
}
.game-title {
font-size: 1.2rem;
font-weight: 400;
color: #f5f5f5;
margin-bottom: 0.75rem;
letter-spacing: 0.05em;
}
.game-description {
font-size: 0.9rem;
color: #999;
line-height: 1.6;
font-weight: 300;
}
.coming-soon {
color: #666;
font-style: italic;
margin-top: 0.5rem;
font-size: 0.85rem;
}
.home-button {
margin-top: 4rem;
padding: 0.75rem 1.5rem;
font-size: 0.9rem;
background: transparent;
color: #f5f5f5;
border: 1px solid #3a3a3a;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s ease;
text-decoration: none;
display: inline-block;
letter-spacing: 0.05em;
}
.home-button:hover {
background: #2a2a2a;
border-color: #4a4a4a;
}
@media (max-width: 768px) {
.casino-header {
font-size: 2rem;
}
.games-grid {
grid-template-columns: 1fr;
}
}
@@ -0,0 +1,541 @@
/* Quick Split is phone-first: sized for one thumb at the table, then allowed to
breathe on a laptop. Palette matches the dealer table so the two read as one tool. */
body {
background: radial-gradient(ellipse at 50% -10%, #1c1c1c 0%, #101010 55%, #0a0a0a 100%);
min-height: 100vh;
margin: 0;
color: #e6e6e6;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
/* Same touch handling as the dealer table — see the note there. This page is the one
a dealer opens mid-hand to chop a pot, so the ~300ms the browser spends deciding
whether a tap was a double-tap-to-zoom is the last thing it needs. */
button,
[role="button"],
input,
select,
textarea,
a {
touch-action: manipulation;
}
button,
[role="button"],
input,
select,
textarea,
a {
-webkit-tap-highlight-color: transparent;
}
/* Not on the fields — a dealer typing a pot amount still needs to select it. */
button,
[role="button"] {
-webkit-user-select: none;
user-select: none;
}
.clearPotBtn:active:not(:disabled),
.choiceChip:active:not(:disabled),
.stepBtn:active:not(:disabled),
.splitBtn:active:not(:disabled),
.splitBtnGhost:active:not(:disabled),
.unevenFoldBtn:active:not(:disabled),
.unevenRemoveBtn:active:not(:disabled) {
transform: translateY(1px);
filter: brightness(1.25);
transition-duration: 0.04s;
}
@media (prefers-reduced-motion: reduce) {
.clearPotBtn:active:not(:disabled),
.choiceChip:active:not(:disabled),
.stepBtn:active:not(:disabled),
.splitBtn:active:not(:disabled),
.splitBtnGhost:active:not(:disabled),
.unevenFoldBtn:active:not(:disabled),
.unevenRemoveBtn:active:not(:disabled) {
transform: none;
}
}
#splitApp {
max-width: 480px;
margin: 0 auto;
padding: 1.25rem 1rem 3rem;
}
/* ---------- Header ---------- */
#splitHeader h1 {
margin: 0;
font-size: 1.5rem;
font-weight: 300;
letter-spacing: 0.04em;
color: #f5f5f5;
position: relative;
display: inline-block;
padding-bottom: 0.35rem;
}
#splitHeader h1::after {
content: "";
position: absolute;
left: 0;
bottom: 0;
width: 36px;
height: 3px;
border-radius: 2px;
background: linear-gradient(90deg, #d8b46a, #a9782f);
}
.splitSubtitle {
margin: 0.35rem 0 1.25rem;
color: #8f8f8f;
font-size: 0.85rem;
}
/* ---------- Mode toggle ---------- */
#modeToggle {
margin-bottom: 1.1rem;
}
/* ---------- Uneven amounts ---------- */
#unevenRows {
display: flex;
flex-direction: column;
gap: 0.45rem;
margin-bottom: 0.6rem;
}
.unevenRow {
display: flex;
align-items: center;
gap: 0.45rem;
}
.unevenRowLabel {
flex: none;
width: 2rem;
color: #8f8f8f;
font-size: 0.8rem;
font-weight: 600;
}
.unevenAmountWrap {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 0.3rem;
background: #141414;
border: 1px solid #3a3a3a;
border-radius: 10px;
padding: 0 0.6rem;
}
.unevenAmountWrap:focus-within {
border-color: #d8b46a;
}
.unevenCurrency {
color: #777;
}
.unevenAmount {
flex: 1;
min-width: 0;
background: none;
border: none;
outline: none;
color: #f2f2f2;
font-family: inherit;
font-size: 16px;
font-variant-numeric: tabular-nums;
padding: 0.6rem 0;
}
.unevenFoldBtn {
flex: none;
min-height: 44px;
padding: 0 0.6rem;
border-radius: 9px;
border: 1px solid #3a3a3a;
background: #232323;
color: #8f8f8f;
font-family: inherit;
font-size: 0.72rem;
cursor: pointer;
}
.unevenFoldBtn.selected {
background: linear-gradient(180deg, #3d1f1f, #2c1515);
border-color: #5b2626;
color: #ffd6d6;
}
.unevenRemoveBtn {
flex: none;
width: 30px;
height: 44px;
border: none;
background: none;
color: #6a6a6a;
font-size: 0.85rem;
cursor: pointer;
}
.unevenRemoveBtn:disabled {
opacity: 0.3;
cursor: not-allowed;
}
#unevenResult {
background: linear-gradient(160deg, #1f2a21, #161c17);
border: 1px solid #2c3a2f;
border-radius: 14px;
padding: 0.9rem 1rem;
margin-bottom: 1.5rem;
}
#unevenResult[hidden] {
display: none;
}
.unevenPot {
display: flex;
align-items: baseline;
gap: 0.6rem;
padding: 0.3rem 0;
font-size: 0.85rem;
}
.unevenPot + .unevenPot {
border-top: 1px solid rgba(255, 255, 255, 0.06);
}
.unevenPotLabel {
flex: none;
color: #d8b46a;
font-weight: 600;
}
.unevenPotAmount {
flex: none;
color: #f2f2f2;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.unevenPotWho {
flex: 1;
min-width: 0;
text-align: right;
color: #9a9a9a;
font-size: 0.78rem;
}
.unevenPotReturn .unevenPotLabel,
.unevenPotReturn .unevenPotAmount {
color: #9a9a9a;
font-weight: 500;
}
.unevenPotTotal {
margin-top: 0.15rem;
border-top: 1px solid rgba(255, 255, 255, 0.14) !important;
}
.unevenPotTotal .unevenPotLabel {
color: #8f9d92;
font-weight: 500;
}
.unevenEmpty {
margin: 0;
color: #8f9d92;
font-size: 0.82rem;
line-height: 1.45;
}
/* ---------- The answer ---------- */
#splitResult {
background: linear-gradient(160deg, #1f2a21, #161c17);
border: 1px solid #2c3a2f;
border-radius: 14px;
padding: 1.4rem 1.1rem;
text-align: center;
margin-bottom: 1.5rem;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
#splitResult.hasAmount {
border-color: #3c6b46;
box-shadow: 0 0 0 1px rgba(78, 201, 122, 0.08), 0 6px 20px rgba(0, 0, 0, 0.35);
}
#splitResultLabel {
color: #8f9d92;
font-size: 0.78rem;
letter-spacing: 0.06em;
text-transform: uppercase;
}
#splitResultAmount {
margin-top: 0.35rem;
font-size: clamp(2.6rem, 14vw, 3.4rem);
font-weight: 600;
line-height: 1.05;
color: #f2f2f2;
font-variant-numeric: tabular-nums;
letter-spacing: -0.01em;
}
#splitResult.hasAmount #splitResultAmount {
color: #7ee2a0;
}
#splitOddNote {
margin-top: 0.7rem;
color: #d8b46a;
font-size: 0.85rem;
line-height: 1.45;
}
#splitDustNote {
margin-top: 0.5rem;
color: #e0a1a1;
font-size: 0.8rem;
line-height: 1.4;
}
/* ---------- Inputs ---------- */
.splitField {
display: block;
margin-bottom: 1.35rem;
}
/* A `display` declaration outranks the browser's own [hidden] rule, so anything
given one has to opt back out explicitly or toggling `hidden` does nothing. */
[hidden] {
display: none !important;
}
.splitLabel {
display: block;
margin-bottom: 0.5rem;
color: #9a9a9a;
font-size: 0.75rem;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.potInputWrap {
display: flex;
align-items: center;
gap: 0.4rem;
background: #141414;
border: 1px solid #3a3a3a;
border-radius: 12px;
padding: 0.2rem 0.75rem;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
.potInputWrap:focus-within {
border-color: #d8b46a;
box-shadow: 0 0 0 3px rgba(216, 180, 106, 0.12);
}
.potCurrency {
color: #777;
font-size: 1.6rem;
font-weight: 300;
}
#potInput {
flex: 1;
min-width: 0;
background: none;
border: none;
outline: none;
color: #f2f2f2;
font-size: 2rem;
font-weight: 500;
font-variant-numeric: tabular-nums;
padding: 0.55rem 0;
font-family: inherit;
}
#potInput::placeholder {
color: #4a4a4a;
}
.clearPotBtn {
flex: none;
width: 34px;
height: 34px;
border-radius: 50%;
border: none;
background: #262626;
color: #999;
font-size: 0.85rem;
cursor: pointer;
}
@media (hover: hover) {
.clearPotBtn:hover {
background: #333;
color: #ddd;
}
}
/* ---------- Tap targets ---------- */
.chipRow {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.choiceChip {
flex: 1 1 auto;
min-width: 58px;
min-height: 52px;
padding: 0.5rem 0.7rem;
background: linear-gradient(180deg, #2e2e2e, #232323);
border: 1px solid #3a3a3a;
border-radius: 11px;
color: #ddd;
font-size: 1rem;
font-family: inherit;
cursor: pointer;
transition: all 0.15s ease;
}
@media (hover: hover) {
.choiceChip:hover {
border-color: #4a4a4a;
background: linear-gradient(180deg, #383838, #2a2a2a);
}
}
.choiceChip.selected {
background: linear-gradient(180deg, #3a2f18, #241d0f);
border-color: #d8b46a;
color: #f0d9a8;
font-weight: 600;
}
.waysStepper {
display: flex;
align-items: center;
gap: 0.35rem;
flex: 1 1 auto;
min-width: 150px;
background: #191919;
border: 1px solid #333;
border-radius: 11px;
padding: 0.2rem 0.4rem;
}
.stepBtn {
width: 40px;
height: 44px;
border: none;
border-radius: 8px;
background: #262626;
color: #ddd;
font-size: 1.25rem;
line-height: 1;
font-family: inherit;
cursor: pointer;
}
@media (hover: hover) {
.stepBtn:hover {
background: #333;
}
}
.waysReadout {
flex: 1;
text-align: center;
color: #999;
font-size: 0.8rem;
font-variant-numeric: tabular-nums;
}
/* ---------- Footer actions ---------- */
#splitActions {
display: flex;
gap: 0.6rem;
margin-top: 1.75rem;
}
.splitBtn {
flex: 1;
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 48px;
padding: 0.6rem 0.9rem;
border-radius: 10px;
border: 1px solid #3a3a3a;
background: linear-gradient(180deg, #2e2e2e, #232323);
color: #ddd;
font-size: 0.9rem;
font-family: inherit;
text-decoration: none;
cursor: pointer;
transition: all 0.15s ease;
}
@media (hover: hover) {
.splitBtn:hover {
border-color: #4a4a4a;
background: linear-gradient(180deg, #383838, #2a2a2a);
}
}
.splitBtnGhost {
background: transparent;
}
.splitFootnote {
margin-top: 1.5rem;
color: #6f6f6f;
font-size: 0.78rem;
line-height: 1.5;
text-align: center;
}
/* This footnote names a control the dealer is being told to reach for, so the name
itself has to be readable — it was 3.39:1 at its worst, inheriting the muted grey
the surrounding sentence is deliberately set in. Emphasised text carrying the
instruction gets its own colour rather than the aside's. */
.splitFootnote strong {
color: #a8a8a8;
font-weight: 600;
}
.splitFootnote a {
color: #a9782f;
}
/* Roomier once there's a real screen to work with. */
@media (min-width: 700px) {
#splitApp {
padding-top: 2.5rem;
}
#splitHeader h1 {
font-size: 1.8rem;
}
}
@@ -0,0 +1,417 @@
// The bar a dealer's thumb lives on while a hand is running: who's to act, what it
// costs them, and one tap per decision. Sits at the bottom of the screen on a phone
// so it's reachable without looking, and re-renders after every action because the
// next player's numbers are different.
const ActionBar = {
state: null,
hooks: null,
raiseOpen: false,
raiseDraft: null,
mount(state, hooks) {
this.state = state;
this.hooks = hooks;
this.watchHeight();
this.render();
},
// The bar is fixed to the bottom of the screen, so everything else has to know how
// tall it is or the table simply runs underneath it — on a 640px-tall phone the
// bottom seats of the oval were sitting behind the Fold button. Its height isn't a
// constant either: opening the raise pad grows it. Publishing the measured height
// as a custom property lets the layout and the toast both stay clear of it without
// anyone guessing a number.
watchHeight() {
const host = document.getElementById("actionBar");
if (!host || this.heightWatcher) return;
const publish = () => {
const visible = !host.hidden;
const height = visible ? host.getBoundingClientRect().height : 0;
document.documentElement.style.setProperty("--actionBarHeight", `${Math.round(height)}px`);
};
if (typeof ResizeObserver === "function") {
this.heightWatcher = new ResizeObserver(publish);
this.heightWatcher.observe(host);
}
window.addEventListener("resize", publish);
window.addEventListener("orientationchange", publish);
publish();
},
// Anything to act on? A hand with nobody dealt in doesn't get a bar.
isRunning() {
return Betting.liveSeats(this.state).length > 0;
},
render() {
const host = document.getElementById("actionBar");
if (!host) return;
host.innerHTML = "";
if (!this.isRunning()) {
host.hidden = true;
document.body.classList.remove("hasActionBar");
document.documentElement.style.setProperty("--actionBarHeight", "0px");
this.stopTankTimer();
this.tankSeatIndex = null;
return;
}
host.hidden = false;
document.body.classList.add("hasActionBar");
host.appendChild(this.renderStatus());
const breakdown = this.renderPotBreakdown();
if (breakdown) host.appendChild(breakdown);
if (Betting.isHandOver(this.state)) {
host.appendChild(this.renderHandOver());
} else if (this.state.actingSeatIndex === null || this.state.actingSeatIndex === undefined) {
host.appendChild(this.renderStreetDone());
} else if (this.raiseOpen) {
host.appendChild(this.renderRaisePad());
} else {
host.appendChild(this.renderActions());
}
this.syncTankTimer();
},
renderStatus() {
const row = document.createElement("div");
row.className = "actionStatus";
const street = document.createElement("span");
street.className = "actionStreet";
street.textContent = Betting.streetLabel(this.state.street);
row.appendChild(street);
const pot = document.createElement("span");
pot.className = "actionPot";
pot.textContent = `Pot ${Money.format(Betting.potSoFar(this.state))}`;
row.appendChild(pot);
// How many are still in the hand — part of the standard per-street
// announcement, and the number a dealer is asked for most often.
const remaining = Betting.liveSeats(this.state).length;
const players = document.createElement("span");
players.className = "actionPlayers";
players.textContent = `${remaining} ${remaining === 1 ? "player" : "players"}`;
row.appendChild(players);
// Nobody is being asked to act because nobody can — say so, or the bar just
// looks like it's waiting for something.
if (Betting.isRunningOut(this.state) && !Betting.isHandOver(this.state)) {
const runout = document.createElement("span");
runout.className = "actionRunout";
const stillIn = Betting.liveSeats(this.state).length;
runout.textContent = `All-in — running out the board (${stillIn} players)`;
row.appendChild(runout);
}
const index = this.state.actingSeatIndex;
if (index !== null && index !== undefined && !Betting.isHandOver(this.state)) {
const player = this.state.seats[index];
const who = document.createElement("span");
who.className = "actionWho";
who.textContent = `${HoldemState.displayName(player, index)} · ${Money.format(Betting.stackOf(this.state, player))} behind`;
row.appendChild(who);
const tank = document.createElement("span");
tank.className = "actionTank";
tank.id = "actionTank";
tank.title = "How long this player has been thinking";
tank.textContent = "0:00";
row.appendChild(tank);
}
// A standing control rather than a toast per action: a dealer taps this bar
// constantly, and a toast after every fold would be noise they'd learn to
// ignore — which is exactly when they'd miss the one that mattered.
const undoLabel = this.hooks.lastActionLabel();
if (undoLabel) {
const undo = document.createElement("button");
undo.type = "button";
undo.className = "actionUndo";
undo.title = `Undo ${undoLabel}`;
undo.textContent = `↶ ${undoLabel}`;
undo.addEventListener("click", () => this.hooks.undoLast());
row.appendChild(undo);
}
return row;
},
// ---- Think timer ----
//
// A player who hasn't noticed the action is on them costs more time than anything
// else a dealer does, so the bar shows how long the current player has been in the
// tank. It's a stopwatch, not a shot clock: nothing happens when it grows, it just
// tells the dealer when it's worth a nudge.
NUDGE_AFTER_S: 30,
SLOW_AFTER_S: 60,
tankSeatIndex: null,
tankStartedAt: null,
tankInterval: null,
// Restarts only when the action actually moves — a re-render for any other reason
// (a chip edit, a name change) must not put a thinking player back to zero.
syncTankTimer() {
const index = this.state.actingSeatIndex;
const running = index !== null && index !== undefined && !Betting.isHandOver(this.state);
if (!running) {
this.stopTankTimer();
this.tankSeatIndex = null;
return;
}
if (this.tankSeatIndex !== index) {
this.tankSeatIndex = index;
this.tankStartedAt = Date.now();
}
if (!this.tankInterval) {
this.tankInterval = setInterval(() => this.paintTank(), 1000);
}
this.paintTank();
},
stopTankTimer() {
if (this.tankInterval) {
clearInterval(this.tankInterval);
this.tankInterval = null;
}
},
// Updates only the timer's own text, so the seconds ticking over never rebuilds the
// buttons under the dealer's thumb.
paintTank() {
const el = document.getElementById("actionTank");
if (!el || this.tankStartedAt === null) return;
const seconds = Math.floor((Date.now() - this.tankStartedAt) / 1000);
const mins = Math.floor(seconds / 60);
el.textContent = `${mins}:${String(seconds % 60).padStart(2, "0")}`;
el.classList.toggle("tankNudge", seconds >= this.NUDGE_AFTER_S && seconds < this.SLOW_AFTER_S);
el.classList.toggle("tankSlow", seconds >= this.SLOW_AFTER_S);
},
// Shown only once someone is all-in and the money has actually split — a single
// undivided pot needs no announcement, and a line that's always there stops being
// read.
renderPotBreakdown() {
// Only worth showing once someone is actually all-in. Mid-street the amounts in
// front of players are unequal all the time — the blinds alone are unequal —
// and layering that would announce a side pot on every hand before anyone had
// even acted.
const someoneAllIn = this.state.seats.some(
player => player.inHand && Betting.handTotal(player) > 0 && Betting.stackOf(this.state, player) <= 0
);
if (!someoneAllIn) return null;
const contributions = this.state.seats.map((player, index) => ({
id: player.id,
index,
contribution: Betting.handTotal(player),
folded: player.folded,
}));
const nameById = new Map(
this.state.seats.map((player, index) => [player.id, HoldemState.displayName(player, index)])
);
return Render.buildPotBreakdown(
PotCalculator.layers(contributions),
PotCalculator.uncalledReturns(contributions),
id => nameById.get(id)
);
},
// Which key presses each button. Shown on the button itself and hidden on touch
// devices — a shortcut nobody can discover may as well not exist, and a key badge
// on a phone is just clutter.
KEY_HINTS: {
actionFold: "F",
actionCheck: "C",
actionCall: "C",
actionRaise: "R",
actionAdvance: "↵",
raiseConfirm: "↵",
raiseCancel: "esc",
},
button(label, className, onClick, sublabel) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = `actionBtn ${className}`;
const main = document.createElement("span");
main.className = "actionBtnLabel";
main.textContent = label;
btn.appendChild(main);
const hint = this.KEY_HINTS[className];
if (hint) {
const kbd = document.createElement("kbd");
kbd.className = "actionKey";
kbd.textContent = hint;
btn.appendChild(kbd);
}
if (sublabel) {
const sub = document.createElement("span");
sub.className = "actionBtnSub";
sub.textContent = sublabel;
btn.appendChild(sub);
}
btn.addEventListener("click", onClick);
return btn;
},
// Every action taken from the bar goes through here, which is also where it gets
// recorded so it can be taken back. A misclick on Fold is the one mistake in this
// tool a dealer can't talk their way out of.
commit(label, mutate) {
this.hooks.beginAction(label);
mutate();
this.hooks.save(this.state);
this.hooks.rerender();
},
renderActions() {
const index = this.state.actingSeatIndex;
const player = this.state.seats[index];
const owed = Betting.toCall(this.state, player);
const stack = Betting.stackOf(this.state, player);
const who = HoldemState.displayName(player, index);
const row = document.createElement("div");
row.className = "actionButtons";
row.appendChild(this.button("Fold", "actionFold", () => this.commit(`${who}'s fold`, () => Betting.fold(this.state, index))));
if (owed <= 0) {
row.appendChild(this.button("Check", "actionCheck", () => this.commit(`${who}'s check`, () => Betting.check(this.state, index))));
} else if (owed >= stack) {
// Calling would put them all-in, so say that rather than quoting a number
// they can't cover.
row.appendChild(this.button("Call all-in", "actionCall", () => this.commit(`${who}'s all-in`, () => Betting.allIn(this.state, index)), Money.format(stack)));
} else {
row.appendChild(this.button("Call", "actionCall", () => this.commit(`${who}'s call`, () => Betting.call(this.state, index)), Money.format(owed)));
}
if (stack > owed) {
row.appendChild(this.button(owed > 0 ? "Raise" : "Bet", "actionRaise", () => {
this.raiseOpen = true;
this.raiseDraft = Math.min(Betting.minRaiseTo(this.state), Betting.committed(player) + stack);
this.render();
}));
}
return row;
},
// Quick amounts first, keypad second — a dealer calling "raise to sixty" wants a
// button, and only reaches for digits when the table does something odd.
renderRaisePad() {
const index = this.state.actingSeatIndex;
const player = this.state.seats[index];
const stack = Betting.stackOf(this.state, player);
const maxTo = Betting.round(Betting.committed(player) + stack);
const pot = Betting.potSoFar(this.state);
const minTo = Math.min(Betting.minRaiseTo(this.state), maxTo);
const wrap = document.createElement("div");
wrap.className = "raisePad";
const quick = document.createElement("div");
quick.className = "raiseQuick";
const options = [
{ label: "Min", value: minTo },
{ label: "½ pot", value: Betting.round(this.state.currentBet + pot / 2) },
{ label: "Pot", value: Betting.round(this.state.currentBet + pot) },
{ label: "All-in", value: maxTo },
];
options.forEach(option => {
const value = Math.max(minTo, Math.min(option.value, maxTo));
const btn = this.button(option.label, "raiseQuickBtn", () => {
this.raiseDraft = value;
this.render();
}, Money.format(value));
if (Betting.round(this.raiseDraft) === value) btn.classList.add("selected");
quick.appendChild(btn);
});
wrap.appendChild(quick);
const entry = document.createElement("div");
entry.className = "raiseEntry";
const input = document.createElement("input");
input.type = "text";
input.inputMode = "decimal";
input.className = "raiseInput";
input.value = this.raiseDraft ?? minTo;
input.setAttribute("aria-label", "Raise to amount");
input.addEventListener("input", () => {
this.raiseDraft = input.value.replace(/[^0-9.]/g, "");
});
entry.appendChild(input);
entry.appendChild(this.button("Cancel", "raiseCancel", () => {
this.raiseOpen = false;
this.render();
}));
entry.appendChild(this.button("Raise to", "raiseConfirm", () => {
const target = Math.max(0, Math.min(Number(this.raiseDraft) || 0, maxTo));
this.raiseOpen = false;
const who = HoldemState.displayName(player, index);
this.commit(`${who}'s raise to ${Money.format(target)}`, () => Betting.raiseTo(this.state, index, target));
}));
wrap.appendChild(entry);
return wrap;
},
renderStreetDone() {
const row = document.createElement("div");
row.className = "actionButtons";
const isRiver = this.state.street === "river";
const label = isRiver ? "Showdown — resolve pot" : `Deal ${Betting.streetLabel(Betting.STREETS[Betting.STREETS.indexOf(this.state.street) + 1])}`;
row.appendChild(this.button(label, "actionAdvance", () => {
if (isRiver) {
this.hooks.resolvePot();
return;
}
this.commit(`dealing the ${Betting.streetLabel(Betting.STREETS[Betting.STREETS.indexOf(this.state.street) + 1]).toLowerCase()}`, () => Betting.closeStreet(this.state));
}));
return row;
},
renderHandOver() {
const row = document.createElement("div");
row.className = "actionButtons";
const live = Betting.liveSeats(this.state);
const winner = live.length === 1 ? HoldemState.displayName(live[0].player, live[0].index) : null;
row.appendChild(this.button(
winner ? `Award pot to ${winner}` : "Resolve pot",
"actionAdvance",
() => this.hooks.resolvePot()
));
return row;
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = ActionBar;
}
@@ -0,0 +1,92 @@
// "Add chips" — a rebuy, a top-up, or the first buy-in of the night.
//
// Quick amounts come off the table's starting stack, because a rebuy is almost
// always one buy-in, sometimes half or two. The keypad is there for the times it
// isn't. Recorded as cash in as well as chips, so at the end of the night the
// dealer can say what each player actually handed over.
const AddChips = {
state: null,
onConfirm: null,
seatIndex: null,
draft: "",
open(state, seatIndex, onConfirm) {
this.state = state;
this.seatIndex = seatIndex;
this.onConfirm = onConfirm;
this.draft = String(this.baseAmount());
this.render();
document.getElementById("addChipsOverlay").hidden = false;
},
close() {
document.getElementById("addChipsOverlay").hidden = true;
},
// The table's starting stack if there is one, otherwise something sane to nudge
// rather than an empty box.
baseAmount() {
const configured = Number(this.state.defaultStack);
if (!Number.isNaN(configured) && configured > 0) return configured;
const bb = Number(this.state.bigBlind) || 0;
return bb > 0 ? bb * 100 : 100;
},
quickAmounts() {
const base = this.baseAmount();
return [
{ label: "½ buy-in", value: Money.round(base / 2) },
{ label: "Buy-in", value: base },
{ label: "2 buy-ins", value: base * 2 },
];
},
render() {
const player = this.state.seats[this.seatIndex];
document.getElementById("addChipsTitle").textContent =
`Add chips — ${HoldemState.displayName(player, this.seatIndex)}`;
const stack = Betting.stackOf(this.state, player);
const boughtIn = Number(player.buyIns) || 0;
document.getElementById("addChipsSubtitle").textContent = boughtIn > 0
? `${Money.format(stack)} in front · ${Money.format(boughtIn)} in so far`
: `${Money.format(stack)} in front`;
const quick = document.getElementById("addChipsQuick");
quick.innerHTML = "";
this.quickAmounts().forEach(option => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "addChipsQuickBtn";
btn.classList.toggle("selected", Number(this.draft) === option.value);
const label = document.createElement("span");
label.className = "addChipsQuickLabel";
label.textContent = option.label;
const amount = document.createElement("span");
amount.className = "addChipsQuickAmount";
amount.textContent = Money.format(option.value);
btn.appendChild(label);
btn.appendChild(amount);
btn.addEventListener("click", () => {
this.draft = String(option.value);
this.render();
});
quick.appendChild(btn);
});
const input = document.getElementById("addChipsInput");
input.value = this.draft;
},
confirm() {
const amount = Math.max(0, Number(document.getElementById("addChipsInput").value) || 0);
this.close();
if (amount > 0) this.onConfirm(this.seatIndex, Money.round(amount));
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = AddChips;
}
@@ -0,0 +1,345 @@
// Live betting: who's to act, what it costs them, and where the money goes.
//
// This is bookkeeping, not a game — the dealer taps what the humans at the table
// actually did, and the tool keeps the arithmetic straight. It deliberately never
// blocks an action it thinks is "illegal"; a dealer overruling the maths is right
// more often than the maths is.
//
// Money model: `player.committed` is what a seat has put in on the current street.
// When a street closes it sweeps into `player.amountOverride`, which is the seat's
// total for the hand — the same field the pot badge, the pot wizard, the standings
// and the CSV already read. So the betting bar is a fast way to fill in a field
// that already existed, and nothing downstream had to change.
const Betting = {
STREETS: ["preflop", "flop", "turn", "river"],
streetLabel(street) {
return { preflop: "Pre-flop", flop: "Flop", turn: "Turn", river: "River" }[street] || "Pre-flop";
},
round(amount) {
return Money.round(amount);
},
// ---- Reading the table ----
liveSeats(state) {
return state.seats
.map((player, index) => ({ player, index }))
.filter(s => s.player.inHand && !s.player.folded);
},
committed(player) {
return this.round(player.committed || 0);
},
// Everything this seat has put in across the whole hand, including the street
// still in progress.
handTotal(player) {
return this.round((Number(player.amountOverride) || 0) + this.committed(player));
},
// Never below zero. A seat can't have negative chips in front of it, and a typo in
// the stack field used to come back as-is — which then flowed into putIn(), where
// `Math.min(amount, -50)` moves a negative amount and *adds* chips to the table.
stackOf(state, player) {
const own = player.stack;
if (own !== null && own !== undefined && String(own).trim() !== "") {
return Math.max(0, this.round(own));
}
const fallback = Number(state.defaultStack);
return Number.isNaN(fallback) ? 0 : Math.max(0, this.round(fallback));
},
toCall(state, player) {
return Math.max(0, this.round((state.currentBet || 0) - this.committed(player)));
},
// A raise has to at least match the last one; before any raise, the big blind
// is the yardstick.
minRaiseTo(state) {
const increment = this.round(state.lastRaiseSize || state.bigBlind || 0);
return this.round((state.currentBet || 0) + (increment || 1));
},
potSoFar(state) {
return this.round(
state.seats.reduce((sum, p) => sum + this.handTotal(p), 0)
);
},
// ---- Moving the action ----
nextLiveIndex(state, fromIndex) {
const count = state.seatCount;
for (let step = 1; step <= count; step++) {
const index = this.seatAt(state, fromIndex, step);
const player = state.seats[index];
if (player.inHand && !player.folded) return index;
}
return null;
},
// Who the dealer asks next. A player who is all-in is still in the hand and still
// wins pots, but has no decision left, so the action passes over them.
nextToAct(state, fromIndex) {
const count = state.seatCount;
for (let step = 1; step <= count; step++) {
const index = this.seatAt(state, fromIndex, step);
const player = state.seats[index];
if (player.inHand && !player.folded && this.stackOf(state, player) > this.EPSILON_CHIPS) return index;
}
return null;
},
// Which chair sits `step` places along in the direction of play. The table owns
// this — walking the seats is exactly where the button, the blinds and the action
// used to drift apart from each other, so there is one implementation of it.
seatAt(state, fromIndex, step) {
return HoldemState.nextSeatIndex(state, fromIndex, step);
},
// A street is done when everyone still live has either matched the bet or has
// no chips left to argue with, and everyone has had a turn since the last raise.
isStreetComplete(state) {
const live = this.liveSeats(state);
if (live.length <= 1) return true;
const unsettled = live.filter(s => {
const allIn = this.stackOf(state, s.player) <= 0;
const matched = this.toCall(state, s.player) <= 0;
return !allIn && (!matched || !s.player.hasActed);
});
return unsettled.length === 0;
},
// ---- Actions ----
// Moves `amount` from a seat's stack into the middle for this street. Returns
// what actually moved, which is less than asked for if it puts them all-in.
putIn(state, index, amount) {
const player = state.seats[index];
const stack = this.stackOf(state, player);
const moved = this.round(Math.min(Math.max(0, amount), stack));
player.stack = this.round(stack - moved);
player.committed = this.round(this.committed(player) + moved);
return moved;
},
fold(state, index) {
state.seats[index].folded = true;
state.seats[index].hasActed = true;
this.passAction(state, index);
},
check(state, index) {
state.seats[index].hasActed = true;
this.passAction(state, index);
},
call(state, index) {
const player = state.seats[index];
this.putIn(state, index, this.toCall(state, player));
player.hasActed = true;
this.passAction(state, index);
},
// `total` is what the seat's street commitment becomes — "raise to", the way a
// dealer says it out loud, not "raise by".
raiseTo(state, index, total) {
const player = state.seats[index];
const target = this.round(total);
const delta = this.round(target - this.committed(player));
const moved = this.putIn(state, index, delta);
const newBet = this.committed(player);
const previousBet = state.currentBet || 0;
if (newBet > previousBet) {
const increase = this.round(newBet - previousBet);
// What a full raise would have had to be: at least as much again as the
// last one, or the big blind if there hasn't been a raise yet.
const fullRaise = this.round(state.lastRaiseSize || state.bigBlind || 0);
const isFullRaise = increase >= fullRaise - this.EPSILON_CHIPS;
state.currentBet = newBet;
if (isFullRaise) {
state.lastRaiseSize = increase;
// A real raise reopens the action: everyone else owes a response again.
state.seats.forEach((p, i) => {
if (i !== index && p.inHand && !p.folded) p.hasActed = false;
});
}
// Otherwise this is a short all-in — somebody with less than a full raise
// left shoving it in. The most misread rule in poker: it does *not* reopen
// the betting to anyone who has already acted. They owe the difference or
// they fold; they don't get to raise again because a short stack happened
// to be between them. Players yet to act keep their full rights, which
// they do here because their hasActed is already false.
//
// lastRaiseSize deliberately isn't lowered either, or the next legal raise
// would be computed off the short amount and come out too small.
}
player.hasActed = true;
this.passAction(state, index);
return moved;
},
allIn(state, index) {
const player = state.seats[index];
return this.raiseTo(state, index, this.round(this.committed(player) + this.stackOf(state, player)));
},
passAction(state, index) {
state.actingSeatIndex = this.isStreetComplete(state) ? null : this.nextToAct(state, index);
},
// ---- Street and hand boundaries ----
// Pulls whatever is in front of the players into their hand totals. Anything that
// reads a seat's contribution — the pot wizard above all — has to run after this,
// or it will price the pot without the chips sitting on the current street.
sweepToHandTotals(state) {
state.seats.forEach(player => {
const moved = this.committed(player);
if (moved > 0) {
player.amountOverride = this.round((Number(player.amountOverride) || 0) + moved);
}
player.committed = 0;
player.hasActed = false;
});
},
// Sweeps the street's chips into each seat's hand total and opens the next one.
closeStreet(state) {
this.sweepToHandTotals(state);
state.currentBet = 0;
state.lastRaiseSize = 0;
const nextStreetIndex = this.STREETS.indexOf(state.street || "preflop") + 1;
state.street = this.STREETS[nextStreetIndex] || "river";
// It takes two players with chips to have a bet. Once everyone left is all-in
// the rest of the board is just dealt out.
if (!this.canStillBet(state)) {
state.actingSeatIndex = null;
return;
}
// After the flop the first live player left of the button acts — which heads-up
// is the big blind, since the button is the small blind. Naming the big blind
// directly also covers a button parked on a seat nobody is sitting in, and it
// still has to be someone with chips left to bet.
const { bbIndex, headsUp } = HoldemState.getBlindSeats(state);
const bigBlindCanAct =
headsUp &&
bbIndex !== null &&
!state.seats[bbIndex].folded &&
this.stackOf(state, state.seats[bbIndex]) > this.EPSILON_CHIPS;
state.actingSeatIndex = bigBlindCanAct
? bbIndex
: this.nextToAct(state, state.dealerSeatIndex);
},
isHandOver(state) {
return this.liveSeats(state).length <= 1;
},
// Players still in the hand who have chips left to put in. Fewer than two of them
// means the betting is finished even though the hand isn't.
seatsWithChips(state) {
return this.liveSeats(state).filter(s => this.stackOf(state, s.player) > this.EPSILON_CHIPS);
},
EPSILON_CHIPS: Money.EPSILON,
canStillBet(state) {
return this.liveSeats(state).length > 1 && this.seatsWithChips(state).length > 1;
},
// True when the hand is still live but nobody can bet again — the dealer is just
// running the board out.
isRunningOut(state) {
return this.liveSeats(state).length > 1 && !this.canStillBet(state);
},
// True while nothing has happened in this hand except the blinds going in. Up to
// that point the dealer can still move the button or rename the blinds and have
// it cost nothing — which is the state a home game spends a lot of time in,
// arguing about whose turn it is before the cards come out.
onlyBlindsIn(state) {
return (state.street || "preflop") === "preflop" && state.seats.every(p => !p.hasActed);
},
// Pulls the blinds back off the table and posts them again from wherever the
// button and the blind assignment now say they belong. Refunding first is what
// keeps the chip count straight when the button gets passed round three or four
// times before anybody is happy with it.
repostBlinds(state) {
state.seats.forEach(player => {
const back = this.committed(player);
if (back > 0) player.stack = this.round(this.stackOf(state, player) + back);
player.committed = 0;
player.hasActed = false;
});
this.beginHand(state);
},
// Deals a fresh betting round: blinds posted, action to the seat after the big
// blind, which is where a dealer expects to be looking when the cards go out.
beginHand(state) {
state.street = "preflop";
state.currentBet = 0;
state.lastRaiseSize = 0;
// Position is read off the button all through the hand, so it has to be on
// somebody before the blinds are worked out — not on the empty seat 1 a
// brand-new table starts on.
HoldemState.ensureButtonOnPlayer(state);
state.seats.forEach(player => {
player.committed = 0;
player.hasActed = false;
});
const sb = Number(state.smallBlind) || 0;
const bb = Number(state.bigBlind) || 0;
const { sbIndex, bbIndex, headsUp } = HoldemState.getBlindSeats(state);
if (sbIndex === null || bbIndex === null) {
state.currentBet = 0;
state.actingSeatIndex = null;
return;
}
if (sb > 0) this.putIn(state, sbIndex, sb);
if (bb > 0) this.putIn(state, bbIndex, bb);
state.currentBet = this.round(Math.max(this.committed(state.seats[sbIndex]), this.committed(state.seats[bbIndex])));
state.lastRaiseSize = bb || 0;
// Heads-up the button is the small blind and acts first before the flop; with
// three or more it's the seat after the big blind. Either way, a blind big
// enough to put that player all-in leaves them nothing to decide.
state.actingSeatIndex = headsUp
? (this.stackOf(state, state.seats[sbIndex]) > this.EPSILON_CHIPS ? sbIndex : this.nextToAct(state, sbIndex))
: this.nextToAct(state, bbIndex);
},
// Winners get their share put back in front of them.
creditWinnings(state, payouts) {
payouts.forEach(payout => {
const player = state.seats.find(p => p.id === payout.id);
if (!player) return;
player.stack = this.round(this.stackOf(state, player) + payout.amount);
});
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = Betting;
}
@@ -0,0 +1,131 @@
// Tap a card instead of typing it.
//
// Typing "AH" into a two-character box is fine at a desk and miserable at a table:
// it needs a keyboard, it accepts nonsense like "ZZ", and it happily lets the same
// card land in two players' hands. The picker is one tap per card, greys out cards
// already dealt somewhere else at the table, and stores exactly the same two-character
// string the rest of the tool has always read.
const CardPicker = {
RANKS: ["A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"],
SUITS: [
{ code: "S", symbol: "♠", red: false },
{ code: "H", symbol: "♥", red: true },
{ code: "D", symbol: "♦", red: true },
{ code: "C", symbol: "♣", red: false },
],
state: null,
hooks: null,
seatIndex: null,
cardIndex: 0,
open(state, hooks, seatIndex, cardIndex) {
this.state = state;
this.hooks = hooks;
this.seatIndex = seatIndex;
this.cardIndex = cardIndex;
this.render();
document.getElementById("cardPickerOverlay").hidden = false;
},
close() {
document.getElementById("cardPickerOverlay").hidden = true;
},
// Every card sitting in front of anyone else. The slot being edited is excluded,
// so re-picking the card that's already there isn't treated as a duplicate.
cardsInUse() {
const used = new Map();
this.state.seats.forEach((player, seat) => {
(player.cards || []).forEach((card, slot) => {
if (!card) return;
if (seat === this.seatIndex && slot === this.cardIndex) return;
used.set(card.toUpperCase(), HoldemState.displayName(player, seat));
});
});
return used;
},
assign(card) {
const player = this.state.seats[this.seatIndex];
player.cards[this.cardIndex] = card;
this.hooks.onPick(this.seatIndex, this.cardIndex, card);
// Straight on to the second card — a dealer picking hole cards is always
// picking two, and making them re-open the picker doubles the taps.
if (this.cardIndex === 0 && !player.cards[1]) {
this.cardIndex = 1;
this.render();
return;
}
this.close();
},
clearSlot() {
const player = this.state.seats[this.seatIndex];
player.cards[this.cardIndex] = "";
this.hooks.onPick(this.seatIndex, this.cardIndex, "");
this.render();
},
render() {
const player = this.state.seats[this.seatIndex];
const used = this.cardsInUse();
document.getElementById("cardPickerTitle").textContent =
`${HoldemState.displayName(player, this.seatIndex)} — card ${this.cardIndex + 1}`;
// Which slot the next tap fills, switchable without closing the sheet.
const slots = document.getElementById("cardPickerSlots");
slots.innerHTML = "";
[0, 1].forEach(slot => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "pickerSlot";
btn.classList.toggle("active", slot === this.cardIndex);
const value = player.cards[slot] || "";
btn.textContent = value || "—";
btn.classList.toggle("cardRed", /[HD]$/i.test(value));
btn.addEventListener("click", () => {
this.cardIndex = slot;
this.render();
});
slots.appendChild(btn);
});
const grid = document.getElementById("cardPickerGrid");
grid.innerHTML = "";
this.RANKS.forEach(rank => {
this.SUITS.forEach(suit => {
const card = `${rank}${suit.code}`;
const takenBy = used.get(card);
const btn = document.createElement("button");
btn.type = "button";
btn.className = "pickerCard";
btn.classList.toggle("cardRed", suit.red);
btn.disabled = !!takenBy;
if (takenBy) btn.title = `Already dealt to ${takenBy}`;
if ((player.cards[this.cardIndex] || "").toUpperCase() === card) {
btn.classList.add("selected");
}
const rankEl = document.createElement("span");
rankEl.className = "pickerRank";
rankEl.textContent = rank;
const suitEl = document.createElement("span");
suitEl.className = "pickerSuit";
suitEl.textContent = suit.symbol;
btn.appendChild(rankEl);
btn.appendChild(suitEl);
btn.addEventListener("click", () => this.assign(card));
grid.appendChild(btn);
});
});
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = CardPicker;
}
@@ -0,0 +1,115 @@
// Toasts and confirmation dialogs, so the table never has to fall back on the
// browser's own alert boxes. A system confirm() steals focus, looks nothing like
// the rest of the page, and on a phone it's a full-screen interruption — all of
// which is a bad trade for a dealer trying to keep a game moving.
// A short-lived message at the bottom of the screen, optionally with one action
// (in practice: Undo). Only one is ever on screen; a second replaces the first.
const Toast = {
DEFAULT_DURATION_MS: 8000,
timer: null,
show(message, options = {}) {
const host = document.getElementById("toastHost");
if (!host) return;
this.dismiss();
const toast = document.createElement("div");
toast.className = "toast";
toast.setAttribute("role", "status");
const text = document.createElement("span");
text.className = "toastText";
text.textContent = message;
toast.appendChild(text);
if (options.actionLabel && options.onAction) {
const action = document.createElement("button");
action.type = "button";
action.className = "toastAction";
action.textContent = options.actionLabel;
action.addEventListener("click", () => {
this.dismiss();
options.onAction();
});
toast.appendChild(action);
}
const close = document.createElement("button");
close.type = "button";
close.className = "toastClose";
close.setAttribute("aria-label", "Dismiss");
close.textContent = "✕";
close.addEventListener("click", () => this.dismiss());
toast.appendChild(close);
host.appendChild(toast);
// Next frame, so the entrance transition actually runs.
requestAnimationFrame(() => toast.classList.add("toastVisible"));
this.timer = setTimeout(
() => this.dismiss(),
options.duration || this.DEFAULT_DURATION_MS
);
},
dismiss() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
const host = document.getElementById("toastHost");
if (host) host.innerHTML = "";
},
};
// Styled stand-in for confirm(). Resolves true if the dealer goes through with it.
const Dialog = {
confirm({ title, message, confirmLabel = "Confirm", cancelLabel = "Cancel", danger = false }) {
return new Promise(resolve => {
const overlay = document.getElementById("confirmOverlay");
const modal = overlay.querySelector("#confirmModal");
overlay.querySelector("#confirmTitle").textContent = title;
overlay.querySelector("#confirmMessage").textContent = message;
const confirmBtn = overlay.querySelector("#confirmAcceptBtn");
const cancelBtn = overlay.querySelector("#confirmCancelBtn");
confirmBtn.textContent = confirmLabel;
cancelBtn.textContent = cancelLabel;
confirmBtn.classList.toggle("holdemBtnDanger", danger);
confirmBtn.classList.toggle("holdemBtnAccent", !danger);
const finish = result => {
overlay.hidden = true;
confirmBtn.removeEventListener("click", onAccept);
cancelBtn.removeEventListener("click", onCancel);
overlay.removeEventListener("click", onBackdrop);
document.removeEventListener("keydown", onKey);
resolve(result);
};
const onAccept = () => finish(true);
const onCancel = () => finish(false);
const onBackdrop = e => {
if (e.target === overlay) finish(false);
};
const onKey = e => {
if (e.key === "Escape") finish(false);
if (e.key === "Enter") finish(true);
};
confirmBtn.addEventListener("click", onAccept);
cancelBtn.addEventListener("click", onCancel);
overlay.addEventListener("click", onBackdrop);
document.addEventListener("keydown", onKey);
overlay.hidden = false;
modal.focus();
confirmBtn.focus();
});
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = { Toast, Dialog };
}
@@ -0,0 +1,84 @@
// Turns the in-memory hand history into a CSV file the dealer can download for a
// paper trail — a house manager or a disputed chip count needs something that
// outlives the browser tab, not just a scrollable panel in the sidebar.
const HandHistoryExport = {
csvField(value) {
const str = String(value ?? "");
return /[",\n]/.test(str) ? `"${str.replace(/"/g, '""')}"` : str;
},
formatTimestamp(timestamp) {
try {
return new Date(timestamp).toLocaleString();
} catch {
return "";
}
},
// Money columns go in as bare numbers. Written as "$1,250,000.00" they import as
// text, so the one thing anybody opens this file to do — total a column and see
// who owes what — doesn't work without cleaning every cell first. The commas were
// quoted correctly, so the file parsed; it just wouldn't add up.
toCsv(handHistory, standings = []) {
const rows = [["Hand #", "Time", "Pot", "Payouts"]];
// handHistory is stored newest-first; the export reads better oldest-first.
[...handHistory].reverse().forEach(entry => {
const payouts = (entry.payouts || [])
.map(p => `${p.label}: ${Money.format(p.amount)}`)
.join("; ");
rows.push([
entry.handNumber,
this.formatTimestamp(entry.timestamp),
Money.forSheet(entry.pot),
payouts,
]);
});
// The settle-up numbers go in the same file as the hands they came from, so a
// dealer handing over one export isn't asked for a second one at cash-out.
if (standings.length > 0) {
rows.push([]);
rows.push(["Session Standings"]);
// Bought in and chips now are what a cash-out is settled from; paid in and
// won describe the hands. Both belong in the file the dealer hands over.
rows.push(["Player", "Paid In", "Won", "Net", "Bought In", "Chips Now", "Up/Down"]);
standings.forEach(row => {
rows.push([
row.name,
Money.forSheet(row.in),
Money.forSheet(row.won),
Money.forSheet(row.net),
Money.forSheet(row.boughtIn || 0),
Money.forSheet(row.chipsNow || 0),
Money.forSheet(row.cashPosition || 0),
]);
});
}
return rows.map(row => row.map(f => this.csvField(f)).join(",")).join("\r\n");
},
fileName() {
const now = new Date();
const pad = n => String(n).padStart(2, "0");
const stamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
return `holdem-hand-history-${stamp}.csv`;
},
download(handHistory, standings = []) {
const csv = this.toCsv(handHistory, standings);
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = this.fileName();
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = HandHistoryExport;
}
@@ -0,0 +1,439 @@
document.addEventListener("DOMContentLoaded", () => {
const state = HoldemState.load();
// Focus, Tab-trapping and Escape for every overlay, wired once by watching the
// `hidden` attribute they all already toggle.
Modal.mount();
// Undo works by swapping the whole table back to a snapshot. `state` is handed out
// by reference to every module at mount time, so it has to be refilled in place —
// reassigning the variable would leave the renderer and the betting bar pointing at
// the old object and quietly ignoring the undo.
const snapshotState = () => JSON.parse(JSON.stringify(state));
const restoreState = snapshot => {
Object.keys(state).forEach(key => delete state[key]);
Object.assign(state, snapshot);
HoldemState.save(state);
Render.renderAll();
};
// A gesture on a seat is a shortcut for something the dealer could do the long
// way, so each one is undoable the same way the header buttons are.
const seatAction = (index, message, mutate) => {
const snapshot = snapshotState();
mutate(state.seats[index], index);
HoldemState.save(state);
Render.renderAll();
Toast.show(message, {
actionLabel: "Undo",
onAction: () => {
restoreState(snapshot);
Toast.show("Undone.", { duration: 2500 });
},
duration: 6000,
});
};
const nameOf = index => HoldemState.displayName(state.seats[index], index);
const hooks = {
save: s => HoldemState.save(s),
rerender: () => Render.renderAll(),
onSeatDoubleTap: index => {
const player = state.seats[index];
if (!player.inHand) return;
if (player.folded) {
seatAction(index, `${nameOf(index)} is back in the hand.`, p => { p.folded = false; });
return;
}
seatAction(index, `${nameOf(index)} folds.`, () => {
if (state.actingSeatIndex === index) Betting.fold(state, index);
else player.folded = true;
});
},
onSeatLongPress: index => SeatMenu.open(state, seatMenuHooks, index),
onGiveButton: index => seatMenuHooks.makeDealer(index),
};
const seatMenuHooks = {
fold: index => hooks.onSeatDoubleTap(index),
unfold: index => seatAction(index, `${nameOf(index)} is back in the hand.`, p => { p.folded = false; }),
allIn: index => seatAction(index, `${nameOf(index)} is all-in.`, () => Betting.allIn(state, index)),
toggleDealtIn: index => {
const player = state.seats[index];
const dealtIn = player.inHand;
const handRunning = !Betting.onlyBlindsIn(state) || Betting.potSoFar(state) > 0;
const alreadyIn = Betting.handTotal(player);
// Somebody walking away mid-hand doesn't get their chips back — they're
// dead money the winner collects. Say so, because the pot total pointedly
// does not go down and a dealer needs to know that's deliberate.
const message = dealtIn
? (alreadyIn > 0
? `${nameOf(index)} is out — their ${Money.format(alreadyIn)} stays in the pot.`
: `${nameOf(index)} sits out.`)
: (handRunning
? `${nameOf(index)} is in from the next hand.`
: `${nameOf(index)} is dealt in.`);
seatAction(index, message, p => {
p.inHand = !dealtIn;
if (!p.inHand) {
// Their chips stay put; only the fold flag is cleared, since being
// out of the hand already covers not winning it.
p.folded = false;
if (state.actingSeatIndex === index) Betting.passAction(state, index);
} else if (handRunning) {
// Joining a hand already in progress means sitting this one out —
// you can't buy into a pot you haven't been paying for. `folded`
// is exactly that state, and the next hand clears it.
p.folded = true;
}
});
},
makeDealer: index => seatAction(index, `Button on ${nameOf(index)}.`, () => {
state.dealerSeatIndex = index;
// Before anyone has acted the blinds are still just sitting there, so
// moving the button moves them too — a home game passes it round several
// times before the cards come out, and the posted chips have to follow.
if (Betting.onlyBlindsIn(state)) Betting.repostBlinds(state);
}),
assignBlind: (index, which) => {
const blinds = HoldemState.getBlindSeats(state);
const other = which === "sb" ? blinds.bbIndex : blinds.sbIndex;
// Naming one blind pins the other where it already is, so the dealer only
// has to state the part they're changing. If that would land both on one
// player, the other blind moves to the next seat along.
let partner = other !== null && other !== undefined && other !== index
? other
: Betting.nextLiveIndex(state, index);
if (partner === index || partner === null) partner = Betting.nextLiveIndex(state, index);
const label = which === "sb" ? "small blind" : "big blind";
seatAction(index, `${nameOf(index)} posts the ${label}.`, () => {
state.blindOverride = which === "sb"
? { sbIndex: index, bbIndex: partner }
: { sbIndex: partner, bbIndex: index };
if (Betting.onlyBlindsIn(state)) Betting.repostBlinds(state);
});
},
clearBlindOverride: () => seatAction(state.dealerSeatIndex, "Blinds follow the button again.", () => {
state.blindOverride = null;
if (Betting.onlyBlindsIn(state)) Betting.repostBlinds(state);
}),
editSeat: index => Render.toggleSeatEditor(index),
addChips: index => AddChips.open(state, index, (seatIndex, amount) => {
seatAction(seatIndex, `${nameOf(seatIndex)} added ${Money.format(amount)}.`, player => {
// Chips in front and cash in are different questions — the stack moves
// every hand, what they've handed over only moves when they buy.
player.stack = Money.round(Betting.stackOf(state, player) + amount);
player.buyIns = Money.round((Number(player.buyIns) || 0) + amount);
});
}),
};
Render.mount(state, hooks);
const openPotWizard = () => {
// Chips still in front of players belong in the pot being priced, so bank them
// before the wizard reads anyone's contribution.
Betting.sweepToHandTotals(state);
hooks.save(state);
Render.renderAll();
PotWizard.open(state, payouts => {
const paid = payouts.map(p => `${p.label} ${Money.format(p.amount)}`).join(", ");
runUndoable(paid ? `Paid ${paid}.` : "Hand closed with nothing to pay out.", () => {
if (payouts.length > 0) {
HoldemState.recordHand(state, payouts);
// Winnings go straight back in front of the player, so the next
// hand's stacks are already right.
Betting.creditWinnings(state, payouts);
}
HoldemState.startNextHand(state);
Betting.beginHand(state);
});
});
};
// A short history of actions taken from the bar, so a misclicked Fold can be taken
// back — and the one before it, since a dealer usually notices a beat late. Kept in
// memory only: this is for the mistake you just made, not last night's hand.
const MAX_UNDO_STEPS = 12;
const actionHistory = [];
ActionBar.mount(state, {
save: hooks.save,
rerender: hooks.rerender,
resolvePot: openPotWizard,
beginAction: label => {
actionHistory.push({ label, snapshot: snapshotState() });
if (actionHistory.length > MAX_UNDO_STEPS) actionHistory.shift();
},
lastActionLabel: () => (actionHistory.length ? actionHistory[actionHistory.length - 1].label : null),
undoLast: () => {
const step = actionHistory.pop();
if (!step) return;
restoreState(step.snapshot);
Toast.show(`Took back ${step.label}.`, { duration: 2500 });
},
});
// Anything that ends the hand makes the per-action history meaningless — the
// snapshots refer to a hand that no longer exists.
const clearActionHistory = () => { actionHistory.length = 0; };
// Keyboard shortcuts press the very same buttons a dealer would tap, rather than
// calling the betting engine themselves — there's no second code path to drift out
// of step with what the bar is actually offering right now.
const pressInBar = selector => {
const btn = document.querySelector(`#actionBar ${selector}`);
if (!btn || btn.disabled) return false;
btn.click();
return true;
};
const quickRaiseButton = label =>
[...document.querySelectorAll("#actionBar .raiseQuickBtn")]
.find(b => b.querySelector(".actionBtnLabel").textContent === label);
Shortcuts.mount({
fold: () => pressInBar(".actionFold"),
checkOrCall: () => pressInBar(".actionCheck") || pressInBar(".actionCall"),
raise: () => pressInBar(".actionRaise"),
allIn: () => {
// Open the raise pad first if it isn't already, then take its All-in amount.
if (!document.querySelector("#actionBar .raisePad") && !pressInBar(".actionRaise")) return false;
const quick = quickRaiseButton("All-in");
if (!quick) return false;
quick.click();
return true;
},
// Enter confirms a raise if one is being entered, otherwise moves the hand on.
advance: () => pressInBar(".raiseConfirm") || pressInBar(".actionAdvance"),
undo: () => pressInBar(".actionUndo"),
cancel: () => pressInBar(".raiseCancel"),
});
// Moving to the next hand used to ask "are you sure?" every single time —
// the most-pressed button in a session, gated behind a system dialog. It now
// just happens, and the toast offers the way back for the few seconds anyone
// would notice a misclick. The snapshot is deliberately in-memory only: an
// undo is for the mistake you just made, not one from last night's session.
const runUndoable = (message, mutate) => {
const snapshot = snapshotState();
mutate();
// Starting or settling a hand invalidates the per-action history: those
// snapshots describe a hand that's over. The whole-step Undo below replaces it.
clearActionHistory();
hooks.save(state);
Render.renderAll();
Toast.show(message, {
actionLabel: "Undo",
onAction: () => {
restoreState(snapshot);
Toast.show("Undone.", { duration: 2500 });
},
});
};
// A seat that has anything of a player in it — a name, chips, cash in, or a hand
// in progress. Shrinking the table throws these away permanently, and it also
// orphans them in the session standings, where they keep their winnings but lose
// the stack and buy-in the settle-up is worked out from.
const seatHasSomeoneIn = player =>
!!(player.name && player.name.trim()) ||
player.inHand ||
(Number(player.stack) || 0) > 0 ||
(Number(player.buyIns) || 0) > 0 ||
(Number(player.amountOverride) || 0) > 0;
document.getElementById("seatCountInput").addEventListener("change", async e => {
const requested = Math.max(2, Math.min(24, Math.floor(Number(e.target.value)) || state.seatCount));
const losing = state.seats.slice(requested).filter(seatHasSomeoneIn);
if (losing.length > 0) {
const who = losing
.map((p, i) => HoldemState.displayName(p, requested + state.seats.slice(requested).indexOf(p)))
.join(", ");
const ok = await Dialog.confirm({
title: `Remove ${losing.length} ${losing.length === 1 ? "player" : "players"}?`,
message: `Going down to ${requested} seats takes ${who} off the table along with their chips and buy-ins, and their session totals stop adding up.`,
confirmLabel: "Remove them",
danger: true,
});
if (!ok) {
e.target.value = state.seatCount;
return;
}
}
runUndoable(`Table set to ${requested} seats.`, () => HoldemState.resizeSeats(state, requested));
});
document.getElementById("directionSelect").addEventListener("change", e => {
state.direction = e.target.value;
hooks.save(state);
Render.renderSeats();
});
document.getElementById("basePotInput").addEventListener("input", e => {
state.basePotAmount = e.target.value === "" ? null : Number(e.target.value);
hooks.save(state);
Render.renderAll();
});
document.getElementById("dedicatedDealerToggle").addEventListener("change", e => {
state.dedicatedDealer = e.target.checked;
hooks.save(state);
Render.renderSeats();
Render.renderTableHint();
});
document.getElementById("tableNotes").addEventListener("input", e => {
state.notes = e.target.value;
hooks.save(state);
});
document.getElementById("addChipColorBtn").addEventListener("click", () => {
state.chipLegend.push({
id: HoldemState.makeId("chip"),
color: "#888888",
value: 1,
});
hooks.save(state);
Render.renderAll();
});
document.getElementById("nextHandBtn").addEventListener("click", async () => {
// Moving on wipes every seat's contribution, so an unresolved pot is simply
// destroyed — measured at a four-handed table, pressing this with $8 in the
// middle took the table from 800 chips to 792, and the toast said nothing
// about it. Chips only ever leave this tool because a dealer meant them to.
const unresolved = HoldemState.unresolvedContributions(state);
if (unresolved > Betting.EPSILON_CHIPS) {
const ok = await Dialog.confirm({
title: `Throw away ${Money.format(unresolved)}?`,
message: "There's still money in the middle from this hand. Starting the next one takes it off the table without paying anybody — use Resolve Pot if somebody won it.",
confirmLabel: "Throw it away",
danger: true,
});
if (!ok) return;
}
// startNextHand moves the button on by one; say where it landed so the
// dealer can confirm the rotation without hunting for the badge.
const nextDealer = HoldemState.nextSeatIndex(state, state.dealerSeatIndex, 1);
const where = state.dedicatedDealer
? `small blind on seat ${HoldemState.nextSeatIndex(state, nextDealer, 1) + 1}`
: `button on seat ${nextDealer + 1}`;
const discarded = unresolved > Betting.EPSILON_CHIPS
? ` ${Money.format(unresolved)} taken off the table.`
: "";
runUndoable(`Next hand — ${where}. Blinds posted.${discarded}`, () => {
HoldemState.startNextHand(state);
Betting.beginHand(state);
});
});
document.getElementById("resetTableBtn").addEventListener("click", async () => {
const ok = await Dialog.confirm({
title: "Reset the whole table?",
message: "Every seat, chip colour and note goes back to defaults. The hand history and session standings are cleared too.",
confirmLabel: "Reset table",
danger: true,
});
if (!ok) return;
HoldemState.clear();
Object.assign(state, HoldemState.createDefault());
clearActionHistory();
Render.mount(state, hooks);
Toast.show("Table reset.", { duration: 2500 });
});
document.getElementById("resolvePotBtn").addEventListener("click", openPotWizard);
[
["smallBlindInput", "smallBlind"],
["bigBlindInput", "bigBlind"],
["defaultStackInput", "defaultStack"],
].forEach(([id, key]) => {
document.getElementById(id).addEventListener("input", e => {
state[key] = e.target.value === "" ? null : Number(e.target.value);
hooks.save(state);
Render.renderAll();
});
});
document.getElementById("closeSeatEditorBtn").addEventListener("click", () => Render.closeSeatEditor());
document.getElementById("addChipsConfirmBtn").addEventListener("click", () => AddChips.confirm());
document.getElementById("addChipsCancelBtn").addEventListener("click", () => AddChips.close());
document.getElementById("addChipsOverlay").addEventListener("click", e => {
if (e.target.id === "addChipsOverlay") AddChips.close();
});
document.getElementById("addChipsInput").addEventListener("keydown", e => {
if (e.key === "Enter") AddChips.confirm();
});
// Escape is Modal's job now, for this sheet and the five others that never had it.
const rulingsOverlay = document.getElementById("rulingsOverlay");
const closeRulings = () => { rulingsOverlay.hidden = true; };
document.getElementById("openRulingsBtn").addEventListener("click", () => { rulingsOverlay.hidden = false; });
document.getElementById("closeRulingsBtn").addEventListener("click", closeRulings);
rulingsOverlay.addEventListener("click", e => {
if (e.target === rulingsOverlay) closeRulings();
});
document.getElementById("seatMenuCancelBtn").addEventListener("click", () => SeatMenu.close());
document.getElementById("seatMenuOverlay").addEventListener("click", e => {
if (e.target.id === "seatMenuOverlay") SeatMenu.close();
});
document.getElementById("cardPickerCloseBtn").addEventListener("click", () => CardPicker.close());
document.getElementById("cardPickerClearBtn").addEventListener("click", () => CardPicker.clearSlot());
document.getElementById("cardPickerOverlay").addEventListener("click", e => {
if (e.target.id === "cardPickerOverlay") CardPicker.close();
});
document.getElementById("closePotWizardBtn").addEventListener("click", () => PotWizard.close());
document.getElementById("potWizardOverlay").addEventListener("click", e => {
if (e.target.id === "potWizardOverlay") PotWizard.close();
});
document.getElementById("clearHistoryBtn").addEventListener("click", async () => {
const ok = await Dialog.confirm({
title: "Clear the hand history?",
message: "This wipes every logged hand and the session standings, and puts the hand counter back to #1. Export first if anyone might want the numbers.",
confirmLabel: "Clear history",
danger: true,
});
if (!ok) return;
HoldemState.clearHistory(state);
hooks.save(state);
Render.renderAll();
Toast.show("Hand history cleared.", { duration: 2500 });
});
document.getElementById("exportHistoryBtn").addEventListener("click", () => {
if ((state.handHistory || []).length === 0) return;
HandHistoryExport.download(state.handHistory, HoldemState.sessionStandings(state));
});
});
@@ -0,0 +1,147 @@
// Keyboard and screen-reader behaviour for every overlay in the tool, in one place.
//
// There are six of them — seat menu, card picker, add chips, rulings, pot wizard,
// confirm — opened and closed by five different modules, and each one was missing
// the same three things: focus never moved into the dialog, Tab walked straight out
// of it into the page behind the scrim, and Escape did nothing (only the rulings
// sheet handled it). Measured before this: 0 of 5 moved focus in, 5 of 5 leaked Tab,
// 1 of 5 closed on Escape.
//
// Rather than patch that into five modules, this watches the `hidden` attribute every
// overlay already toggles. Nothing else had to change, and an overlay added later
// gets the same behaviour without anyone remembering to wire it up — which is the
// failure this is fixing in the first place.
const Modal = {
// `:not([hidden])` matters — a sheet that is itself hidden inside an open overlay
// must not be a Tab stop.
FOCUSABLE: [
"a[href]",
"button:not([disabled])",
'input:not([disabled]):not([type="hidden"])',
"select:not([disabled])",
"textarea:not([disabled])",
'[tabindex]:not([tabindex="-1"])',
].join(","),
open: [],
mount() {
document.querySelectorAll('[id$="Overlay"]').forEach(overlay => this.watch(overlay));
// Capture phase: the dialog gets first refusal on Escape and Tab, before any
// table-level shortcut sees them.
document.addEventListener("keydown", e => this.onKeyDown(e), true);
},
watch(overlay) {
const sync = () => {
const isOpen = !overlay.hidden;
const known = this.open.some(entry => entry.overlay === overlay);
if (isOpen && !known) this.onOpened(overlay);
else if (!isOpen && known) this.onClosed(overlay);
};
new MutationObserver(sync).observe(overlay, { attributes: true, attributeFilter: ["hidden"] });
sync();
},
sheetOf(overlay) {
return overlay.querySelector('[role="dialog"], [role="alertdialog"]') || overlay.firstElementChild || overlay;
},
focusableIn(overlay) {
return [...overlay.querySelectorAll(this.FOCUSABLE)].filter(el => {
if (el.closest("[hidden]")) return false;
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
});
},
onOpened(overlay) {
const sheet = this.sheetOf(overlay);
// aria-modal is only true while the thing is actually open, so it's set here
// rather than baked into the markup.
if (sheet) sheet.setAttribute("aria-modal", "true");
this.open.push({ overlay, returnFocus: document.activeElement });
// Focus the first real control. A dialog that leaves focus on the button
// behind it reads, to a screen reader, as though nothing happened at all.
// Content-only sheets get focus on the sheet so the title is announced.
const focusable = this.focusableIn(overlay);
const target = focusable[0];
if (target) {
target.focus({ preventScroll: true });
} else if (sheet) {
if (!sheet.hasAttribute("tabindex")) sheet.setAttribute("tabindex", "-1");
sheet.focus({ preventScroll: true });
}
},
onClosed(overlay) {
const index = this.open.findIndex(entry => entry.overlay === overlay);
if (index === -1) return;
const [entry] = this.open.splice(index, 1);
const sheet = this.sheetOf(overlay);
if (sheet) sheet.removeAttribute("aria-modal");
// Put the dealer back where they were. Without this, closing the pot wizard
// drops focus to the top of the document and the next Tab starts from the
// page header.
const back = entry.returnFocus;
if (back && back.isConnected && typeof back.focus === "function") {
back.focus({ preventScroll: true });
}
},
topmost() {
return this.open.length ? this.open[this.open.length - 1] : null;
},
// Escape presses the dialog's own cancel/close button rather than just hiding the
// overlay, so whatever that button does — resolving the confirm promise, clearing
// the add-chips draft — still happens. Only if there isn't one does it hide the
// overlay directly.
dismiss(overlay) {
const closer = overlay.querySelector("[data-modal-close]");
if (closer) closer.click();
else overlay.hidden = true;
},
onKeyDown(event) {
const top = this.topmost();
if (!top) return;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
this.dismiss(top.overlay);
return;
}
if (event.key !== "Tab") return;
// Keep Tab inside the dialog. Everything behind the scrim is unreachable by
// mouse, so letting the keyboard wander back there is a trap with no way out.
const focusable = this.focusableIn(top.overlay);
if (focusable.length === 0) {
event.preventDefault();
return;
}
const first = focusable[0];
const last = focusable[focusable.length - 1];
const active = document.activeElement;
if (event.shiftKey && (active === first || !top.overlay.contains(active))) {
event.preventDefault();
last.focus({ preventScroll: true });
} else if (!event.shiftKey && (active === last || !top.overlay.contains(active))) {
event.preventDefault();
first.focus({ preventScroll: true });
}
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = Modal;
}
@@ -0,0 +1,63 @@
// Shared money handling for every casino surface. Kept apart from the table's
// rendering so the quick-split calculator can pull it in without dragging the whole
// seat/chip UI along with it.
//
// Everything the dealer touches is money, and money is decimal, so every module used
// to carry its own `Math.round(x * 100) / 100`. That's one rounding rule written out
// sixteen times in six files, which is sixteen chances for one of them to drift.
// It lives here now, and the modules that do arithmetic call these instead.
const Money = {
// Half a cent. Chip comparisons need a tolerance: a stack that lands on
// 0.0000000001 after a split is empty as far as a dealer is concerned, and an
// exact `> 0` would treat that player as still having chips to bet.
EPSILON: 0.004,
// All money maths goes through cents, so 0.1 + 0.2 never reaches a payout.
toCents(amount) {
return Math.round((Number(amount) || 0) * 100);
},
fromCents(cents) {
return cents / 100;
},
round(amount) {
return this.toCents(amount) / 100;
},
// Cents only when there are cents.
//
// A chip game deals in whole numbers nearly all the time, and a trailing ".00"
// is two characters that say nothing — measured at ~22px, against the 64px a
// seat puck has to show a stack in. "$1,250,000.00" doesn't fit and wraps;
// "$1,250,000" does. Amounts that genuinely carry cents still show them, so a
// 25c-blind game reads exactly as it did.
format(amount) {
const value = Number(amount) || 0;
const hasCents = this.toCents(value) % 100 !== 0;
return `$${value.toLocaleString(undefined, {
minimumFractionDigits: hasCents ? 2 : 0,
maximumFractionDigits: 2,
})}`;
},
// The same amount for a spreadsheet rather than for a person: no currency symbol
// and no thousands separators, because those are what make a column of money
// import as text and refuse to add up.
forSheet(amount) {
return (this.toCents(amount) / 100).toFixed(2);
},
// "+$40.00" / "-$40.00" rather than "$-40.00" — a standings column is read at a
// glance, and the sign belongs out front where the eye lands first.
formatSigned(amount) {
const value = Number(amount) || 0;
if (value > 0) return `+${this.format(value)}`;
if (value < 0) return `-${this.format(Math.abs(value))}`;
return this.format(0);
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = Money;
}
@@ -0,0 +1,173 @@
// Pure side-pot math. No DOM, no globals besides the PotCalculator namespace, so the
// dealer's payout logic can be reasoned about (and unit tested) on its own.
//
// A "contribution entry" is { id, remaining, folded }. `remaining` starts as the amount
// that player put in the pot and is whittled down round by round as money gets paid out.
const PotCalculator = {
EPSILON: Money.EPSILON,
// Builds the initial entry list from raw contributions, keeping folded players in
// (their chips are still "dead money" owed to whoever wins) while excluding anyone
// who put in nothing at all.
buildEntries(players) {
return players
.filter(p => p.contribution > this.EPSILON)
.map(p => ({ id: p.id, remaining: p.contribution, folded: !!p.folded }));
},
totalPot(entries) {
return entries.reduce((sum, e) => sum + e.remaining, 0);
},
// Players still eligible to be picked as a winner for the money that's left.
getContenders(entries) {
return entries.filter(e => !e.folded && e.remaining > this.EPSILON);
},
// Splits the money on the table into the main pot and any side pots, with who can
// win each. Read-only — this is what a dealer says out loud before the showdown
// ("main pot four-eighty, side pot ninety between seats 3 and 5"), which is the
// announcement that goes missing far more often than the arithmetic goes wrong.
//
// Every distinct all-in amount opens a new layer: each player pays into a layer up
// to their own contribution, and only players who reached that height can win it.
// Folded money stays in — it's dead money owed to whoever wins the layer it fell in.
layers(players) {
// Uncalled chips were never played for, so they come off the top before any
// pot is built. Deriving the pots from what's left is what keeps this function
// and uncalledReturns() from disagreeing about the same money — they used to
// decide "uncontested" separately, and an overbet that its own bettor was
// still live for got announced as a side pot only they could win.
const returned = new Map(this.uncalledReturns(players).map(r => [r.id, Money.toCents(r.amount)]));
const live = players
.map(p => ({ ...p, cents: Money.toCents(p.contribution) - (returned.get(p.id) || 0) }))
.filter(p => p.cents > 0);
if (live.length === 0) return [];
const heights = [...new Set(live.map(p => p.cents))].sort((a, b) => a - b);
const layers = [];
let floor = 0;
heights.forEach(height => {
const band = height - floor;
const payers = live.filter(p => p.cents >= height);
const amount = band * payers.length;
const eligible = payers.filter(p => !p.folded).map(p => p.id);
if (amount > 0) {
if (eligible.length > 0) {
layers.push({ amount: Money.fromCents(amount), eligible });
} else if (layers.length > 0) {
// Everyone who reached this height folded, so it isn't a pot of its
// own — it's dead money owed to whoever wins the layer underneath.
// Dropping it would quietly shrink the announced pot.
const below = layers[layers.length - 1];
below.amount = Money.round(below.amount + Money.fromCents(amount));
}
// With no layer underneath either, nobody in the hand is live at all.
// That's a fold flag the dealer needs to fix, not a payout to guess at.
}
floor = height;
});
// Consecutive layers with the same set of eligible players are one pot to a
// dealer — nobody announces two side pots between the same two people.
const merged = [];
layers.forEach(layer => {
const previous = merged[merged.length - 1];
const sameEligibility =
previous &&
previous.eligible.length === layer.eligible.length &&
previous.eligible.every(id => layer.eligible.includes(id));
if (sameEligibility) {
previous.amount = Money.round(previous.amount + layer.amount);
} else {
merged.push({ ...layer });
}
});
return merged.map((layer, index) => ({
...layer,
label: index === 0 ? "Main pot" : `Side pot ${index}`,
}));
},
// Chips nobody could call, which the dealer pushes back rather than into the pot.
//
// A bet is only called up to what somebody *else* was willing to put in, so the
// ceiling for each player is the largest contribution among everyone but them.
// Measuring against the whole table instead — including the bettor's own chips —
// makes the biggest bet its own yardstick, so the one case this exists for (you
// shove, a short stack calls for less) comes back empty.
uncalledReturns(players) {
const contributing = players.filter(p => p.contribution > this.EPSILON);
// Nobody live at all means the fold flags are wrong, not that every chip on
// the table was uncalled. That's a correction for the dealer to make, so say
// nothing here and let the wizard ask them to fix it.
if (contributing.filter(p => !p.folded).length === 0) return [];
const cents = contributing.map(p => Money.toCents(p.contribution));
return contributing
.map((p, index) => {
const others = cents.filter((_, i) => i !== index);
const cap = others.length > 0 ? Math.max(...others) : 0;
return { id: p.id, amount: Money.fromCents(cents[index] - cap) };
})
.filter(r => r.amount > this.EPSILON);
},
// Awards the current pot layer to `winnerIds` (one id, or several for a split/tie).
// The payout is capped at the smallest remaining contribution among the winners —
// that's the classic side-pot rule: an all-in player can only win what everyone at
// the table matched, and the excess rolls forward to the next round.
resolveRound(entries, winnerIds) {
const winners = entries.filter(e => winnerIds.includes(e.id) && e.remaining > this.EPSILON);
if (winners.length === 0) {
throw new Error("No valid winners selected for this round.");
}
const cap = Math.min(...winners.map(w => w.remaining));
let payoutPool = 0;
const updatedEntries = entries.map(e => {
if (e.remaining <= this.EPSILON) return e;
const used = Math.min(e.remaining, cap);
payoutPool += used;
return { ...e, remaining: Money.round(e.remaining - used) };
});
payoutPool = Money.round(payoutPool);
const baseShareCents = Math.floor(Money.toCents(payoutPool) / winners.length);
let leftoverCents = Money.toCents(payoutPool) - baseShareCents * winners.length;
const perWinner = winnerIds
.filter(id => winners.some(w => w.id === id))
.map(id => ({ id, amountCents: baseShareCents }));
// Odd cents (can't split evenly) go one at a time to the winners, in the order
// they were selected, so nothing is ever lost to rounding.
let i = 0;
while (leftoverCents > 0 && perWinner.length > 0) {
perWinner[i % perWinner.length].amountCents += 1;
leftoverCents--;
i++;
}
const result = perWinner.map(w => ({ id: w.id, amount: Money.fromCents(w.amountCents) }));
const remainingContenders = this.getContenders(updatedEntries);
return {
payoutPool,
capApplied: cap,
perWinner: result,
updatedEntries,
remainingContenders,
};
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = PotCalculator;
}
@@ -0,0 +1,302 @@
// Walks the dealer through awarding the pot: "who won?", and if that player was
// all-in for less than everyone else, "who's next?" — repeating until every dollar
// in the pot has been assigned. Built on PotCalculator's pure round-resolution math.
const PotWizard = {
state: null,
onFinished: null,
entries: [],
playerLabelById: new Map(),
log: [],
open(state, onFinished) {
this.state = state;
this.onFinished = onFinished;
const players = state.seats.filter(
p => HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount) > 0
);
this.playerLabelById = new Map(
players.map(p => [p.id, this.labelFor(p, state.seats.indexOf(p))])
);
this.seatIndexById = new Map(players.map(p => [p.id, state.seats.indexOf(p)]));
// The label carries name and cards together for the log and the payout lines;
// the choice rows want them separately so each can be styled and read on its own.
this.nameById = new Map(
players.map(p => [p.id, HoldemState.displayName(p, state.seats.indexOf(p))])
);
this.cardsById = new Map(
players.map(p => [p.id, (p.cards || []).filter(Boolean)])
);
const contributions = players.map(p => ({
id: p.id,
contribution: HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount),
// A seat switched off mid-hand still has its chips in the pot, but it
// can no more win them than a folded one can — same dead money, and the
// wizard must not offer it as a winner.
folded: p.folded || HoldemState.isDeadMoney(p),
}));
this.entries = PotCalculator.buildEntries(contributions);
// Kept so the wizard can show the whole breakdown up front, not just the layer
// it happens to be asking about.
this.layers = PotCalculator.layers(contributions);
this.returns = PotCalculator.uncalledReturns(contributions);
this.log = [];
this.totals = new Map();
document.getElementById("potWizardOverlay").hidden = false;
this.renderStep();
},
close() {
document.getElementById("potWizardOverlay").hidden = true;
},
labelFor(player, seatIndex) {
const name = HoldemState.displayName(player, seatIndex);
const cards = (player.cards || []).filter(Boolean).map(c => Render.formatCard(c)).join(" ");
return cards ? `${name} (${cards})` : name;
},
addToTotal(id, amount) {
this.totals.set(id, (this.totals.get(id) || 0) + amount);
},
// A chopped pot rarely divides exactly, and the odd chip goes to the first player
// left of the button — not to whoever the dealer happened to tick first. The
// calculator hands leftovers out in the order it's given the winners, so ordering
// them here is what makes the payout match the rule.
orderFromButton(ids) {
const distance = new Map();
for (let step = 1; step <= this.state.seatCount; step++) {
distance.set(HoldemState.nextSeatIndex(this.state, this.state.dealerSeatIndex, step), step);
}
return [...ids].sort((a, b) =>
(distance.get(this.seatIndexById.get(a)) ?? 0) - (distance.get(this.seatIndexById.get(b)) ?? 0)
);
},
renderStep() {
// Auto-resolve any round where only one player is left standing — nothing to ask.
let contenders = PotCalculator.getContenders(this.entries);
while (contenders.length === 1) {
const result = PotCalculator.resolveRound(this.entries, [contenders[0].id]);
this.recordRound(result);
this.entries = result.updatedEntries;
contenders = PotCalculator.getContenders(this.entries);
}
const body = document.getElementById("potWizardBody");
body.innerHTML = "";
if (this.log.length === 0) body.appendChild(this.renderBreakdown());
body.appendChild(this.renderLog());
const remaining = PotCalculator.totalPot(this.entries.filter(e => e.remaining > PotCalculator.EPSILON));
if (contenders.length === 0 && remaining > PotCalculator.EPSILON) {
const warning = document.createElement("p");
warning.className = "potWizardPrompt";
// Money left over because nobody could call it isn't a pot anyone won —
// it goes back to whoever put it in. Telling the dealer to un-fold someone
// to "win" it would be wrong.
const returned = (this.returns || []).reduce((sum, r) => sum + r.amount, 0);
if (Math.abs(returned - remaining) <= PotCalculator.EPSILON && returned > 0) {
const who = this.returns.map(r => this.playerLabelById.get(r.id)).join(", ");
warning.textContent = `${Money.format(remaining)} was never called — push it back to ${who} rather than paying it out.`;
} else {
warning.textContent = `${Money.format(remaining)} is still unassigned, but every remaining player is marked Folded. Uncheck Fold on whoever should win it.`;
}
body.appendChild(warning);
body.appendChild(this.renderSummary());
return;
}
if (contenders.length === 0 || remaining <= PotCalculator.EPSILON) {
body.appendChild(this.renderSummary());
return;
}
const round = document.createElement("div");
round.className = "potWizardRound";
const prompt = document.createElement("p");
prompt.className = "potWizardPrompt";
prompt.innerHTML = this.log.length === 0
? `Who won the hand? <strong>${Money.format(remaining)}</strong> is in play.`
: `That side pot still leaves <strong>${Money.format(remaining)}</strong> unassigned — who's next best?`;
round.appendChild(prompt);
const choices = document.createElement("div");
choices.className = "potWizardChoices";
contenders.forEach(c => {
const label = document.createElement("label");
label.className = "potWizardChoice";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = c.id;
// The row is the target, not the box — so the row has to look chosen too.
checkbox.addEventListener("change", () => {
label.classList.toggle("chosen", checkbox.checked);
});
label.appendChild(checkbox);
const text = document.createElement("span");
text.className = "potWizardChoiceText";
const name = document.createElement("span");
name.className = "potWizardChoiceName";
name.textContent = this.nameById.get(c.id);
text.appendChild(name);
const upTo = document.createElement("span");
upTo.className = "potWizardChoiceUpTo";
upTo.textContent = `up to ${Money.format(c.remaining)}`;
text.appendChild(upTo);
label.appendChild(text);
// Cards sit apart from the name rather than inside it, so a dealer reading
// a row across the table sees the hand, not a sentence.
const cards = this.cardsById.get(c.id) || [];
if (cards.length > 0) {
const cardsEl = document.createElement("span");
cardsEl.className = "potWizardChoiceCards";
cards.forEach((card, i) => {
if (i > 0) cardsEl.appendChild(document.createTextNode(" "));
const span = document.createElement("span");
if (/[HD]$/i.test(card)) span.className = "cardRed";
span.textContent = Render.formatCard(card);
cardsEl.appendChild(span);
});
label.appendChild(cardsEl);
}
choices.appendChild(label);
});
round.appendChild(choices);
const hint = document.createElement("p");
hint.className = "fieldHint";
hint.textContent = "Check more than one to split the pot on a tie.";
round.appendChild(hint);
const confirmBtn = document.createElement("button");
confirmBtn.className = "holdemBtn holdemBtnAccent";
confirmBtn.textContent = "Confirm Winner(s)";
confirmBtn.addEventListener("click", () => {
const selected = Array.from(choices.querySelectorAll("input:checked")).map(i => i.value);
if (selected.length === 0) return;
const result = PotCalculator.resolveRound(this.entries, this.orderFromButton(selected));
this.recordRound(result);
this.entries = result.updatedEntries;
this.renderStep();
});
round.appendChild(confirmBtn);
body.appendChild(round);
},
recordRound(result) {
result.perWinner.forEach(w => this.addToTotal(w.id, w.amount));
this.log.push({
amount: result.payoutPool,
winners: result.perWinner.map(w => `${this.playerLabelById.get(w.id)} (${Money.format(w.amount)})`),
});
},
// The announcement, spelled out before anyone is asked to pick a winner: what the
// main pot is worth, what each side pot is worth, and who can win each.
renderBreakdown() {
const node = Render.buildPotBreakdown(
this.layers || [],
this.returns || [],
id => this.playerLabelById.get(id),
"Announce before the showdown"
);
if (!node) return document.createDocumentFragment();
node.classList.add("potBreakdownWizard");
return node;
},
renderLog() {
const wrap = document.createElement("div");
wrap.className = "potWizardLog";
if (this.log.length === 0) return wrap;
this.log.forEach((entry, idx) => {
const line = document.createElement("p");
line.className = "potWizardLogLine";
line.textContent = `Pot ${idx + 1}: ${Money.format(entry.amount)} → ${entry.winners.join(", ")}`;
wrap.appendChild(line);
});
return wrap;
},
renderSummary() {
const wrap = document.createElement("div");
wrap.className = "potWizardSummary";
const heading = document.createElement("h3");
heading.textContent = "Final Payouts";
wrap.appendChild(heading);
if (this.totals.size === 0) {
const empty = document.createElement("p");
empty.className = "fieldHint";
empty.textContent = "Nobody has money in this pot yet — mark seats \"In hand\" and set contributions first.";
wrap.appendChild(empty);
} else {
const list = document.createElement("ul");
for (const [id, amount] of this.totals.entries()) {
const li = document.createElement("li");
li.textContent = `${this.playerLabelById.get(id)} — ${Money.format(amount)}`;
list.appendChild(li);
}
wrap.appendChild(list);
}
const actions = document.createElement("div");
actions.className = "potWizardActions";
const applyBtn = document.createElement("button");
applyBtn.className = "holdemBtn holdemBtnAccent";
applyBtn.textContent = "Start Next Hand";
applyBtn.addEventListener("click", () => {
const payouts = Array.from(this.totals.entries()).map(([id, amount]) => ({
id,
label: this.playerLabelById.get(id),
amount,
}));
this.close();
this.onFinished(payouts);
});
actions.appendChild(applyBtn);
// This button cancels — it does not pay anybody. Under a heading reading
// "Final Payouts" with an amount beside a name, "Close" reads like dismissing
// something already done, and a dealer who taps it walks away believing the
// pot has been pushed. It hasn't: the chips are still in the middle and the
// hand isn't logged. So it says what it does.
const cancelBtn = document.createElement("button");
cancelBtn.className = "holdemBtn holdemBtnGhost";
cancelBtn.textContent = "Cancel — don't pay yet";
cancelBtn.addEventListener("click", () => this.close());
actions.appendChild(cancelBtn);
if (this.totals.size > 0) {
const note = document.createElement("p");
note.className = "fieldHint potWizardPendingNote";
note.textContent = "Nothing has been paid out yet. Start Next Hand pushes the pot and logs the hand.";
wrap.appendChild(actions);
wrap.appendChild(note);
return wrap;
}
wrap.appendChild(actions);
return wrap;
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = PotWizard;
}
@@ -0,0 +1,287 @@
// The quick-split screen: pot in, payout out, nothing to set up and nothing saved.
// A dealer opens this one-handed with players waiting, so every control is a tap and
// the answer updates as they type rather than behind a "calculate" button.
const QuickSplit = {
WAY_CHOICES: [2, 3, 4, 5],
CHIP_CHOICES: [
{ value: 0.01, label: "1¢" },
{ value: 0.25, label: "25¢" },
{ value: 1, label: "$1" },
{ value: 5, label: "$5" },
{ value: 25, label: "$25" },
],
MAX_WAYS: 12,
ways: 2,
chip: 1,
// "even" is the common case — one pot, everyone matched. "uneven" is the one this
// screen used to send people back to the full table for: somebody all-in for less,
// so the money splits into a main pot and side pots.
mode: "even",
entries: [],
mount() {
this.potInput = document.getElementById("potInput");
this.clearPotBtn = document.getElementById("clearPotBtn");
this.entries = [{ amount: "", folded: false }, { amount: "", folded: false }, { amount: "", folded: false }];
this.renderWayChoices();
this.renderChipChoices();
this.renderUnevenRows();
document.getElementById("modeEvenBtn").addEventListener("click", () => this.setMode("even"));
document.getElementById("modeUnevenBtn").addEventListener("click", () => this.setMode("uneven"));
document.getElementById("addPlayerBtn").addEventListener("click", () => {
this.entries.push({ amount: "", folded: false });
this.renderUnevenRows();
this.update();
});
this.potInput.addEventListener("input", () => {
this.sanitizePotInput();
this.update();
});
this.clearPotBtn.addEventListener("click", () => {
this.potInput.value = "";
this.potInput.focus();
this.update();
});
document.getElementById("resetSplitBtn").addEventListener("click", () => {
this.potInput.value = "";
this.ways = 2;
this.chip = 1;
this.renderWayChoices();
this.renderChipChoices();
this.potInput.focus();
this.update();
});
this.update();
},
// Keeps the field to something parseable without fighting the typist: digits and a
// single decimal point, at most two places.
sanitizePotInput() {
const cleaned = this.potInput.value
.replace(/[^0-9.]/g, "")
.replace(/(\..*)\./g, "$1")
.replace(/(\.\d\d)\d+/, "$1");
if (cleaned !== this.potInput.value) this.potInput.value = cleaned;
},
makeChoiceButton(label, isSelected, onPick) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "choiceChip";
btn.textContent = label;
btn.setAttribute("aria-pressed", String(isSelected));
btn.classList.toggle("selected", isSelected);
btn.addEventListener("click", onPick);
return btn;
},
renderWayChoices() {
const row = document.getElementById("waysChoices");
row.innerHTML = "";
this.WAY_CHOICES.forEach(count => {
row.appendChild(
this.makeChoiceButton(String(count), this.ways === count, () => {
this.ways = count;
this.renderWayChoices();
this.update();
})
);
});
// Beyond a five-way chop it's rare enough to hide behind a stepper rather than
// spend a row of buttons on it.
const more = document.createElement("div");
more.className = "waysStepper";
const minus = this.makeStepButton("−", () => this.stepWays(-1));
const plus = this.makeStepButton("+", () => this.stepWays(1));
const readout = document.createElement("span");
readout.className = "waysReadout";
readout.textContent = `${this.ways} ways`;
more.appendChild(minus);
more.appendChild(readout);
more.appendChild(plus);
row.appendChild(more);
},
makeStepButton(label, onPick) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "stepBtn";
btn.textContent = label;
btn.addEventListener("click", onPick);
return btn;
},
stepWays(delta) {
this.ways = Math.max(2, Math.min(this.MAX_WAYS, this.ways + delta));
this.renderWayChoices();
this.update();
},
renderChipChoices() {
const row = document.getElementById("chipChoices");
row.innerHTML = "";
this.CHIP_CHOICES.forEach(choice => {
row.appendChild(
this.makeChoiceButton(choice.label, this.chip === choice.value, () => {
this.chip = choice.value;
this.renderChipChoices();
this.update();
})
);
});
},
setMode(mode) {
this.mode = mode;
document.getElementById("modeEvenBtn").classList.toggle("selected", mode === "even");
document.getElementById("modeUnevenBtn").classList.toggle("selected", mode === "uneven");
document.querySelectorAll(".evenOnly").forEach(el => { el.hidden = mode !== "even"; });
document.querySelectorAll(".unevenOnly").forEach(el => { el.hidden = mode !== "uneven"; });
document.getElementById("splitResult").hidden = mode !== "even";
document.getElementById("unevenResult").hidden = mode !== "uneven";
this.update();
},
renderUnevenRows() {
const host = document.getElementById("unevenRows");
const template = document.getElementById("unevenRowTemplate");
host.innerHTML = "";
this.entries.forEach((entry, index) => {
const row = template.content.firstElementChild.cloneNode(true);
row.querySelector(".unevenRowLabel").textContent = `P${index + 1}`;
const amount = row.querySelector(".unevenAmount");
amount.value = entry.amount;
amount.setAttribute("aria-label", `Player ${index + 1} amount`);
amount.addEventListener("input", () => {
entry.amount = amount.value.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
if (entry.amount !== amount.value) amount.value = entry.amount;
this.update();
});
// Folded money stays in the pot as dead money, but its owner can't win any
// of it — which is exactly the distinction that makes side pots tricky.
const fold = row.querySelector(".unevenFoldBtn");
fold.classList.toggle("selected", entry.folded);
fold.setAttribute("aria-pressed", String(entry.folded));
fold.addEventListener("click", () => {
entry.folded = !entry.folded;
this.renderUnevenRows();
this.update();
});
const remove = row.querySelector(".unevenRemoveBtn");
remove.disabled = this.entries.length <= 2;
remove.addEventListener("click", () => {
this.entries.splice(index, 1);
this.renderUnevenRows();
this.update();
});
host.appendChild(row);
});
},
updateUneven() {
const players = this.entries
.map((entry, index) => ({ id: `P${index + 1}`, contribution: Number(entry.amount) || 0, folded: entry.folded }))
.filter(p => p.contribution > 0);
const pots = PotCalculator.layers(players);
const returns = PotCalculator.uncalledReturns(players);
const host = document.getElementById("unevenPots");
const empty = document.getElementById("unevenEmpty");
host.innerHTML = "";
if (pots.length === 0 && returns.length === 0) {
empty.hidden = false;
empty.textContent = players.length === 0
? "Enter what each player put in."
: "Nobody left who can win — un-fold whoever should take it.";
return;
}
empty.hidden = true;
const addRow = (label, amount, who, className) => {
const row = document.createElement("div");
row.className = `unevenPot ${className || ""}`;
const name = document.createElement("span");
name.className = "unevenPotLabel";
name.textContent = label;
const value = document.createElement("span");
value.className = "unevenPotAmount";
value.textContent = Money.format(amount);
const eligible = document.createElement("span");
eligible.className = "unevenPotWho";
eligible.textContent = who;
row.appendChild(name);
row.appendChild(value);
row.appendChild(eligible);
host.appendChild(row);
};
pots.forEach(pot => addRow(pot.label, pot.amount, pot.eligible.join(", ")));
returns.forEach(ret => addRow("Uncalled", ret.amount, `back to ${ret.id}`, "unevenPotReturn"));
const total = players.reduce((sum, p) => sum + p.contribution, 0);
addRow("On the table", Money.round(total), "", "unevenPotTotal");
},
update() {
if (this.mode === "uneven") {
this.updateUneven();
return;
}
const potValue = Number(this.potInput.value);
const pot = Number.isNaN(potValue) ? 0 : potValue;
this.clearPotBtn.hidden = this.potInput.value === "";
const result = SplitCalculator.split(pot, this.ways, this.chip);
document.getElementById("splitResultLabel").textContent =
`Each of ${result.players} players gets`;
document.getElementById("splitResultAmount").textContent = Money.format(result.each);
const oddNote = document.getElementById("splitOddNote");
if (result.valid && result.oddChips > 0) {
oddNote.textContent = result.oddChips === 1
? `plus one odd ${Money.format(result.chip)} chip to the first player left of the button`
: `plus ${result.oddChips} odd ${Money.format(result.chip)} chips — one each to the ` +
`first ${result.oddChips} players left of the button`;
oddNote.hidden = false;
} else {
oddNote.hidden = true;
}
const dustNote = document.getElementById("splitDustNote");
if (result.valid && result.dust > 0) {
dustNote.textContent =
`${Money.format(result.dust)} doesn't divide into ${Money.format(result.chip)} chips — ` +
`pick a smaller denomination.`;
dustNote.hidden = false;
} else {
dustNote.hidden = true;
}
document.getElementById("splitResult").classList.toggle("hasAmount", result.valid && result.each > 0);
},
};
document.addEventListener("DOMContentLoaded", () => QuickSplit.mount());
@@ -0,0 +1,818 @@
// All DOM rendering + drag/drop for the table. Talks to the outside world only through
// the `hooks` object passed to mount(): hooks.save(state) persists, hooks.rerender()
// re-draws everything (used after structural changes like resizing seats or the chip
// legend).
//
// The table itself only shows compact seat "pucks" — name, cards, total, blind/dealer
// badges — because a full data-entry form (chip counts, custom fields, etc.) doesn't fit
// next to nine others arranged in a circle at any screen size. Clicking a puck opens the
// full form in the seat editor panel instead.
const Render = {
state: null,
hooks: null,
selectedSeatIndex: null,
mount(state, hooks) {
this.state = state;
this.hooks = hooks;
this.selectedSeatIndex = null;
// A reset hands over a different table entirely, so nothing cached about the
// last one still applies.
this.lastHistorySignature = null;
this.handTimeCache.clear();
this.renderAll();
},
renderAll() {
if (this.selectedSeatIndex !== null && this.selectedSeatIndex >= this.state.seatCount) {
this.selectedSeatIndex = null;
}
this.renderSeats();
this.renderSeatEditor();
this.renderChipLegend();
this.renderNotes();
this.updatePotBadge();
this.renderSetupFields();
this.renderTableHint();
this.renderStandings();
this.renderHandHistory();
if (typeof ActionBar !== "undefined" && ActionBar.state) ActionBar.render();
},
renderSetupFields() {
document.getElementById("seatCountInput").value = this.state.seatCount;
document.getElementById("directionSelect").value = this.state.direction;
document.getElementById("basePotInput").value = this.state.basePotAmount ?? "";
document.getElementById("dedicatedDealerToggle").checked = !!this.state.dedicatedDealer;
document.getElementById("smallBlindInput").value = this.state.smallBlind ?? "";
document.getElementById("bigBlindInput").value = this.state.bigBlind ?? "";
document.getElementById("defaultStackInput").value = this.state.defaultStack ?? "";
},
renderTableHint() {
const hint = document.getElementById("tableHint");
// Gestures are invisible until someone tells you about them, and this is the
// only place on the table with room to say so.
hint.textContent = "Tap a seat to edit · double-tap to fold · press and hold for quick actions · drag to swap seats.";
},
renderNotes() {
const notesEl = document.getElementById("tableNotes");
if (document.activeElement !== notesEl) notesEl.value = this.state.notes || "";
},
updatePotBadge() {
// Chips still sitting in front of players on the current street are part of
// the pot as far as anyone at the table is concerned, so count them — waiting
// until the street closes would show a stale number for most of every hand.
const swept = HoldemState.totalPot(this.state);
const onStreet = this.state.seats.reduce((sum, p) => sum + Betting.committed(p), 0);
document.getElementById("potBadgeAmount").textContent = Money.format(swept + onStreet);
},
// ---- Seats around the table (compact pucks) ----
seatPosition(index, count) {
return this.positionOnRing(index, count, 44, 42);
},
// Bets sit on the felt between their player and the pot, the way chips actually
// do — closer in than the seats, on the same spoke. The bets layer is inset to
// match the seat ring (see the CSS), so this one radius holds at every size.
betPosition(index, count) {
return this.positionOnRing(index, count, 27, 25);
},
positionOnRing(index, count, rx, ry) {
const angle = -90 + (360 / count) * index;
const radians = (angle * Math.PI) / 180;
return {
left: 50 + rx * Math.cos(radians),
top: 50 + ry * Math.sin(radians),
};
},
// Colour a bet by the biggest chip that fits it, so a table with a chip legend
// gets bets that look like the chips actually being pushed out.
chipColorFor(amount) {
const legend = [...(this.state.chipLegend || [])]
.filter(chip => Number(chip.value) > 0)
.sort((a, b) => Number(b.value) - Number(a.value));
const match = legend.find(chip => amount >= Number(chip.value));
return (match || legend[legend.length - 1] || {}).color || "#8a8a8a";
},
// ---- Bets on the felt ----
makeBetChip(bet) {
const chip = document.createElement("div");
chip.className = "betChip";
const disc = document.createElement("span");
disc.className = "betChipDisc";
disc.style.background = this.chipColorFor(bet);
const amount = document.createElement("span");
amount.className = "betChipAmount";
amount.textContent = Money.format(bet);
chip.appendChild(disc);
chip.appendChild(amount);
return chip;
},
// A phone's felt has no room for a third ring: measured every radius between the
// seats and the pot badge and each one collides with one or the other. So on a
// narrow screen the bet clings to its own puck instead — same chip, no ring —
// sitting on whichever side faces the middle of the table.
renderBets() {
const layer = document.getElementById("betsLayer");
if (!layer) return;
layer.innerHTML = "";
const anchorToSeat = window.matchMedia("(max-width: 700px)").matches;
this.state.seats.forEach((player, index) => {
const bet = Betting.committed(player);
if (bet <= 0) return;
const chip = this.makeBetChip(bet);
const pos = this.betPosition(index, this.state.seatCount);
if (anchorToSeat) {
const seat = document.querySelector(`.seat[data-seat-index="${index}"]`);
if (!seat) return;
const seatPos = this.seatPosition(index, this.state.seatCount);
chip.classList.add("betChipAnchored", seatPos.top > 50 ? "betChipAbove" : "betChipBelow");
seat.appendChild(chip);
return;
}
chip.style.left = `${pos.left}%`;
chip.style.top = `${pos.top}%`;
layer.appendChild(chip);
});
},
puckLabel(player, seatIndex) {
return HoldemState.displayName(player, seatIndex);
},
renderSeats() {
const layer = document.getElementById("seatsLayer");
layer.innerHTML = "";
const template = document.getElementById("seatTemplate");
const { dealerIndex, sbIndex, bbIndex, manual: manualBlinds } = HoldemState.getBlindSeats(this.state);
this.state.seats.forEach((player, index) => {
const node = template.content.firstElementChild.cloneNode(true);
const pos = this.seatPosition(index, this.state.seatCount);
node.style.left = `${pos.left}%`;
node.style.top = `${pos.top}%`;
node.dataset.seatIndex = String(index);
node.querySelector(".seatChairNumber").textContent = index + 1;
const dealerChip = node.querySelector(".dealerChip");
dealerChip.classList.toggle("active", index === dealerIndex);
dealerChip.classList.toggle("hidden", !!this.state.dedicatedDealer);
// Tapping the puck is the same act as "Give the button" in the seat menu,
// so it goes through the same hook — otherwise this one path would move
// the button without moving the blinds that follow it.
dealerChip.addEventListener("click", e => {
e.stopPropagation();
this.hooks.onGiveButton(index);
});
const sbBadge = node.querySelector(".sbBadge");
const bbBadge = node.querySelector(".bbBadge");
sbBadge.classList.toggle("visible", index === sbIndex);
bbBadge.classList.toggle("visible", index === bbIndex);
// A blind the dealer named by hand isn't where the button would have put
// it, so it's marked — otherwise the table looks like it's just wrong.
// The `!!` matters: getBlindSeats leaves `manual` undefined when the
// blinds are positional, and classList.toggle with an undefined second
// argument *flips* the class instead of clearing it, so the marker
// appeared and disappeared on alternate renders.
sbBadge.classList.toggle("blindManual", !!manualBlinds && index === sbIndex);
bbBadge.classList.toggle("blindManual", !!manualBlinds && index === bbIndex);
this.updatePuckContent(node, player, index);
node.classList.toggle("seatSelected", index === this.selectedSeatIndex);
this.wireSeatGestures(node, index);
this.wireDragAndDrop(node, index);
layer.appendChild(node);
});
this.renderBets();
},
isRedSuit(card) {
return /[HD]$/i.test(card || "");
},
SUIT_SYMBOLS: { S: "♠", H: "♥", D: "♦", C: "♣" },
// "KD" -> "K♦". Stored cards stay two plain characters so every existing reader
// keeps working; the suit only becomes a symbol on its way to a human.
formatCard(card) {
const value = (card || "").toUpperCase();
if (!value) return "";
return `${value[0]}${this.SUIT_SYMBOLS[value[1]] || value[1] || ""}`;
},
// An empty slot has to look like something you can tap, so it gets a placeholder
// rather than going blank.
paintCardSlot(slot, card) {
const value = (card || "").toUpperCase();
slot.classList.toggle("cardRed", this.isRedSuit(value));
slot.classList.toggle("cardSlotEmpty", !value);
slot.textContent = value ? this.formatCard(value) : "+";
},
// A chair nobody has claimed: no name typed, not dealt in, nothing in the pot.
// Worth calling out, because at a short-handed table the open seats are what
// the dealer is looking for.
isEmptySeat(player) {
const named = !!(player.name && player.name.trim());
const contributing =
HoldemState.computeContribution(player, this.state.chipLegend, this.state.basePotAmount) > 0;
return !named && !player.inHand && !contributing;
},
updatePuckContent(node, player, index) {
const empty = this.isEmptySeat(player);
const nameEl = node.querySelector(".seatPuckName");
nameEl.textContent = empty ? "Empty" : (player.name || "").trim();
nameEl.classList.toggle("seatEmptyLabel", empty);
const cardsEl = node.querySelector(".seatPuckCards");
cardsEl.innerHTML = "";
(player.cards || []).filter(Boolean).forEach((card, i) => {
if (i > 0) cardsEl.appendChild(document.createTextNode(" "));
const span = document.createElement("span");
if (this.isRedSuit(card)) span.className = "cardRed";
span.textContent = this.formatCard(card);
cardsEl.appendChild(span);
});
// Always this player's total for the hand. What they've just pushed out on this
// street is shown as a chip on the felt instead — the puck used to flip between
// the two meanings depending on the moment, which is a bad thing for a number
// sitting next to a stack size to do.
const handTotal = Betting.handTotal(player);
const total = handTotal > 0
? handTotal
: HoldemState.computeContribution(player, this.state.chipLegend, this.state.basePotAmount);
const totalEl = node.querySelector(".seatPuckTotal");
totalEl.textContent = total > 0 ? Money.format(total) : "";
this.fitAmount(totalEl);
const stackEl = node.querySelector(".seatPuckStack");
const stack = Betting.stackOf(this.state, player);
stackEl.textContent = !empty && stack > 0 ? Money.format(stack) : "";
this.fitAmount(stackEl);
node.classList.toggle("seatActing", index === this.state.actingSeatIndex);
node.classList.toggle("seatEmpty", empty);
node.classList.toggle("seatInactive", !player.inHand && !empty);
node.classList.toggle("seatFolded", player.folded);
node.classList.toggle("seatLive", player.inHand && !player.folded);
},
// A seat puck is 64px of usable width. A tournament stack doesn't fit in that and,
// because the number has no spaces to break on, it doesn't wrap or ellipsise
// either — it just draws straight out over the neighbouring seat. Stepping the
// font down keeps every digit, which matters: a dealer misreading a stack is a
// worse outcome than a small one, so this shrinks rather than abbreviating.
fitAmount(el) {
const length = (el.textContent || "").length;
el.classList.toggle("puckAmountLong", length >= 8 && length < 10);
el.classList.toggle("puckAmountHuge", length >= 10);
},
// Cheaper than a full renderSeats() — used after edits so the seat editor's inputs
// (which live in a separate panel) never lose focus.
refreshPuck(index) {
const node = document.querySelector(`.seat[data-seat-index="${index}"]`);
if (node) this.updatePuckContent(node, this.state.seats[index], index);
},
// ---- Seat gestures ----
//
// One puck, three intents: tap to edit, double-tap to fold, press and hold for
// the quick menu. The single tap waits out the double-tap window before it
// fires — a fifth of a second of latency on opening a form, in exchange for a
// fold that doesn't also fling a sheet up over the table.
LONG_PRESS_MS: 500,
DOUBLE_TAP_MS: 220,
DRAG_SLOP_PX: 8,
pendingTap: null,
wireSeatGestures(node, index) {
let longPressTimer = null;
let longPressFired = false;
let startX = 0;
let startY = 0;
const cancelLongPress = () => {
if (longPressTimer) {
clearTimeout(longPressTimer);
longPressTimer = null;
}
};
node.addEventListener("pointerdown", e => {
longPressFired = false;
startX = e.clientX;
startY = e.clientY;
cancelLongPress();
longPressTimer = setTimeout(() => {
longPressTimer = null;
longPressFired = true;
this.cancelPendingTap();
node.classList.remove("seatPressing");
this.hooks.onSeatLongPress(index);
}, this.LONG_PRESS_MS);
node.classList.add("seatPressing");
});
// Moving means they're dragging the seat, not holding it.
node.addEventListener("pointermove", e => {
if (Math.abs(e.clientX - startX) > this.DRAG_SLOP_PX || Math.abs(e.clientY - startY) > this.DRAG_SLOP_PX) {
cancelLongPress();
node.classList.remove("seatPressing");
}
});
["pointerup", "pointercancel", "pointerleave"].forEach(type => {
node.addEventListener(type, () => {
cancelLongPress();
node.classList.remove("seatPressing");
});
});
node.addEventListener("dragstart", () => {
cancelLongPress();
this.cancelPendingTap();
node.classList.remove("seatPressing");
});
node.addEventListener("click", e => {
// The long press already did something; don't also treat the release as a tap.
if (longPressFired) {
longPressFired = false;
e.preventDefault();
e.stopPropagation();
return;
}
this.handleSeatTap(index);
});
},
cancelPendingTap() {
if (this.pendingTap) {
clearTimeout(this.pendingTap.timer);
this.pendingTap = null;
}
},
handleSeatTap(index) {
if (this.pendingTap && this.pendingTap.index === index) {
this.cancelPendingTap();
this.hooks.onSeatDoubleTap(index);
return;
}
this.cancelPendingTap();
const timer = setTimeout(() => {
this.pendingTap = null;
this.toggleSeatEditor(index);
}, this.DOUBLE_TAP_MS);
this.pendingTap = { index, timer };
},
// Tapping the open seat again closes it — on a phone the editor is a sheet over
// the table, and the seat you just tapped is the closest thing to hand for
// dismissing it.
toggleSeatEditor(index) {
this.selectedSeatIndex = this.selectedSeatIndex === index ? null : index;
this.renderSeats();
this.renderSeatEditor();
},
wireDragAndDrop(node, index) {
node.addEventListener("dragstart", e => {
e.dataTransfer.setData("text/plain", String(index));
e.dataTransfer.effectAllowed = "move";
node.classList.add("dragging");
});
node.addEventListener("dragend", () => node.classList.remove("dragging"));
node.addEventListener("dragover", e => {
e.preventDefault();
node.classList.add("dropTarget");
});
node.addEventListener("dragleave", () => node.classList.remove("dropTarget"));
node.addEventListener("drop", e => {
e.preventDefault();
node.classList.remove("dropTarget");
const sourceIndex = Number(e.dataTransfer.getData("text/plain"));
const targetIndex = index;
if (Number.isNaN(sourceIndex) || sourceIndex === targetIndex) return;
const seats = this.state.seats;
[seats[sourceIndex], seats[targetIndex]] = [seats[targetIndex], seats[sourceIndex]];
this.hooks.save(this.state);
this.renderSeats();
if (this.selectedSeatIndex === sourceIndex || this.selectedSeatIndex === targetIndex) {
this.renderSeatEditor();
}
});
},
// ---- Seat editor panel (the full form for whichever seat is selected) ----
closeSeatEditor() {
this.selectedSeatIndex = null;
this.renderSeats();
this.renderSeatEditor();
},
renderSeatEditor() {
const title = document.getElementById("seatEditorTitle");
const body = document.getElementById("seatEditorBody");
// Drives the mobile bottom sheet: the panel only slides up over the table
// while a seat is actually being edited.
document.body.classList.toggle("seatSheetOpen", this.selectedSeatIndex !== null);
if (this.selectedSeatIndex === null) {
title.textContent = "Select a seat";
body.innerHTML = '<p class="fieldHint">Click a seat at the table to edit their name, cards, chips and anything else.</p>';
return;
}
const index = this.selectedSeatIndex;
const player = this.state.seats[index];
title.textContent = this.puckLabel(player, index);
body.innerHTML = "";
const template = document.getElementById("seatEditorTemplate");
const form = template.content.firstElementChild.cloneNode(true);
this.wireSeatFields(form, player, index);
this.renderChipCounts(form, player, index);
this.renderCustomFields(form, player, index);
this.renderSeatTotal(form, player);
body.appendChild(form);
},
renderSeatTotal(form, player) {
const total = HoldemState.computeContribution(player, this.state.chipLegend, this.state.basePotAmount);
form.querySelector(".seatTotalAmount").textContent = Money.format(total);
},
commitSeatChange(form, player, index) {
this.hooks.save(this.state);
this.updatePotBadge();
this.renderSeatTotal(form, player);
this.refreshPuck(index);
},
wireSeatFields(form, player, index) {
const nameInput = form.querySelector(".seatNameInput");
nameInput.value = player.name;
nameInput.addEventListener("input", () => {
player.name = nameInput.value;
document.getElementById("seatEditorTitle").textContent = this.puckLabel(player, index);
this.commitSeatChange(form, player, index);
});
const inHandCheckbox = form.querySelector(".inHandCheckbox");
inHandCheckbox.checked = player.inHand;
inHandCheckbox.addEventListener("change", () => {
player.inHand = inHandCheckbox.checked;
if (!player.inHand) player.folded = false;
foldCheckboxRef.checked = player.folded;
foldCheckboxRef.disabled = !player.inHand;
this.commitSeatChange(form, player, index);
});
const foldCheckboxRef = form.querySelector(".foldCheckbox");
foldCheckboxRef.checked = player.folded;
foldCheckboxRef.disabled = !player.inHand;
foldCheckboxRef.addEventListener("change", () => {
player.folded = foldCheckboxRef.checked;
this.commitSeatChange(form, player, index);
});
const slots = [form.querySelector(".card1Slot"), form.querySelector(".card2Slot")];
slots.forEach((slot, cardIdx) => {
this.paintCardSlot(slot, player.cards[cardIdx]);
slot.addEventListener("click", () => {
CardPicker.open(this.state, {
onPick: (seatIndex, pickedIdx, card) => {
this.paintCardSlot(slots[pickedIdx], card);
this.commitSeatChange(form, player, seatIndex);
},
}, index, cardIdx);
});
});
// What they've handed over tonight, shown next to what's in front of them so a
// cash-out is one subtraction rather than a memory test.
const boughtIn = Number(player.buyIns) || 0;
const boughtInEl = form.querySelector(".seatBuyIns");
boughtInEl.textContent = boughtIn > 0 ? `Bought in ${Money.format(boughtIn)}` : "";
boughtInEl.hidden = boughtIn <= 0;
const stackInput = form.querySelector(".stackInput");
stackInput.value = player.stack ?? "";
stackInput.addEventListener("input", () => {
player.stack = stackInput.value === "" ? null : Number(stackInput.value);
this.commitSeatChange(form, player, index);
});
const amountInput = form.querySelector(".amountOverrideInput");
amountInput.value = player.amountOverride ?? "";
amountInput.addEventListener("input", () => {
player.amountOverride = amountInput.value === "" ? null : amountInput.value;
this.commitSeatChange(form, player, index);
});
const addFieldBtn = form.querySelector(".addFieldBtn");
addFieldBtn.addEventListener("click", () => {
player.customFields.push({ label: "", value: "" });
this.renderCustomFields(form, player, index);
this.hooks.save(this.state);
});
},
renderChipCounts(form, player, index) {
const container = form.querySelector(".chipCounts");
container.innerHTML = "";
const template = document.getElementById("chipCountTemplate");
this.state.chipLegend.forEach(chip => {
const row = template.content.firstElementChild.cloneNode(true);
row.querySelector(".chipSwatch").style.background = chip.color;
row.title = `$${chip.value} chips`;
const input = row.querySelector(".chipCountInput");
input.value = player.chipCounts[chip.id] || 0;
input.addEventListener("input", () => {
const count = Math.max(0, Math.floor(Number(input.value)) || 0);
player.chipCounts[chip.id] = count;
this.commitSeatChange(form, player, index);
});
container.appendChild(row);
});
},
renderCustomFields(form, player, index) {
const container = form.querySelector(".customFields");
container.innerHTML = "";
const template = document.getElementById("customFieldTemplate");
player.customFields.forEach((field, fieldIdx) => {
const row = template.content.firstElementChild.cloneNode(true);
const labelInput = row.querySelector(".customFieldLabel");
const valueInput = row.querySelector(".customFieldValue");
labelInput.value = field.label;
valueInput.value = field.value;
labelInput.addEventListener("input", () => {
field.label = labelInput.value;
this.hooks.save(this.state);
});
valueInput.addEventListener("input", () => {
field.value = valueInput.value;
this.hooks.save(this.state);
});
row.querySelector(".removeFieldBtn").addEventListener("click", () => {
player.customFields.splice(fieldIdx, 1);
this.renderCustomFields(form, player, index);
this.hooks.save(this.state);
});
container.appendChild(row);
});
},
// ---- Chip legend ----
renderChipLegend() {
const list = document.getElementById("chipLegendList");
list.innerHTML = "";
const template = document.getElementById("chipLegendRowTemplate");
this.state.chipLegend.forEach(chip => {
const row = template.content.firstElementChild.cloneNode(true);
const colorInput = row.querySelector(".chipColorInput");
const valueInput = row.querySelector(".chipValueInput");
colorInput.value = chip.color;
valueInput.value = chip.value;
colorInput.addEventListener("input", () => {
chip.color = colorInput.value;
this.hooks.save(this.state);
});
valueInput.addEventListener("input", () => {
chip.value = Number(valueInput.value) || 0;
this.hooks.save(this.state);
this.renderSeats();
this.renderSeatEditor();
this.updatePotBadge();
});
row.querySelector(".removeChipColorBtn").addEventListener("click", () => {
this.state.chipLegend = this.state.chipLegend.filter(c => c.id !== chip.id);
this.hooks.save(this.state);
this.renderAll();
});
list.appendChild(row);
});
},
// ---- Pot breakdown ----
// Shared by the action bar (live, mid-hand) and the pot wizard (before winners are
// picked), because both are showing the dealer the same announcement.
buildPotBreakdown(pots, returns, nameFor, heading) {
if (pots.length < 2 && returns.length === 0) return null;
const wrap = document.createElement("div");
wrap.className = "potBreakdown";
if (heading) {
const title = document.createElement("p");
title.className = "potBreakdownHeading";
title.textContent = heading;
wrap.appendChild(title);
}
const addRow = (label, amount, who, className) => {
const row = document.createElement("div");
row.className = `potLayer ${className || ""}`;
const labelEl = document.createElement("span");
labelEl.className = "potLayerLabel";
labelEl.textContent = label;
const amountEl = document.createElement("span");
amountEl.className = "potLayerAmount";
amountEl.textContent = Money.format(amount);
const whoEl = document.createElement("span");
whoEl.className = "potLayerWho";
whoEl.textContent = who;
row.appendChild(labelEl);
row.appendChild(amountEl);
row.appendChild(whoEl);
wrap.appendChild(row);
};
pots.forEach(pot => addRow(pot.label, pot.amount, pot.eligible.map(nameFor).join(", ")));
returns.forEach(ret => addRow("Uncalled", ret.amount, `back to ${nameFor(ret.id)}`, "potLayerReturn"));
return wrap;
},
// ---- Session standings ----
renderStandings() {
const list = document.getElementById("standingsList");
const emptyHint = document.getElementById("standingsEmptyHint");
const table = document.getElementById("standingsTable");
const standings = HoldemState.sessionStandings(this.state);
list.innerHTML = "";
emptyHint.hidden = standings.length > 0;
table.hidden = standings.length === 0;
const template = document.getElementById("standingsRowTemplate");
standings.forEach(row => {
const node = template.content.firstElementChild.cloneNode(true);
node.querySelector(".standingsName").textContent = row.name;
node.querySelector(".standingsIn").textContent = Money.format(row.in);
node.querySelector(".standingsWon").textContent = Money.format(row.won);
const netEl = node.querySelector(".standingsNet");
netEl.textContent = Money.formatSigned(row.net);
netEl.classList.toggle("netUp", row.net > 0);
netEl.classList.toggle("netDown", row.net < 0);
// What they'd actually be handed if the night ended now: chips in front of
// them less the cash they gave the banker. This was computed and written to
// the CSV all along, but never shown to the person doing the paying out.
const cashEl = node.querySelector(".standingsCashOut");
cashEl.textContent = Money.formatSigned(row.cashPosition);
cashEl.classList.toggle("netUp", row.cashPosition > 0);
cashEl.classList.toggle("netDown", row.cashPosition < 0);
list.appendChild(node);
});
this.renderBankReconciliation();
},
// Does the cash box cover the chips on the table? Nothing asked this before, and
// it's the question that decides whether the last two players can be paid.
renderBankReconciliation() {
const host = document.getElementById("bankReconcile");
if (!host) return;
const bank = HoldemState.bankReconciliation(this.state);
// Nothing to reconcile before anybody has handed over money or taken a chip.
host.hidden = bank.cashIn === 0 && bank.chipsInPlay === 0;
if (host.hidden) return;
document.getElementById("bankCashIn").textContent = Money.format(bank.cashIn);
document.getElementById("bankChipsInPlay").textContent = Money.format(bank.chipsInPlay);
const verdict = document.getElementById("bankReconcileVerdict");
if (bank.balanced) {
verdict.textContent = "Balanced — the cash covers every chip on the table.";
} else if (bank.difference > 0) {
verdict.textContent =
`${Money.format(bank.difference)} more in chips than cash taken. Someone's rebuy probably wasn't recorded — the box will be short at cash-out.`;
} else {
verdict.textContent =
`${Money.format(Math.abs(bank.difference))} more cash than chips in play. Someone has paid for chips they haven't been given.`;
}
verdict.classList.toggle("bankBalanced", bank.balanced);
verdict.classList.toggle("bankOff", !bank.balanced);
},
// ---- Hand counter + history ----
// toLocaleTimeString is the single most expensive call in the history panel, and a
// logged hand's timestamp never changes, so the answer is worth keeping.
handTimeCache: new Map(),
formatHandTime(timestamp) {
if (this.handTimeCache.has(timestamp)) return this.handTimeCache.get(timestamp);
let formatted = "";
try {
formatted = new Date(timestamp).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
} catch {
formatted = "";
}
this.handTimeCache.set(timestamp, formatted);
return formatted;
},
// Cheap stand-in for "has the log changed". Entries are immutable once written and
// only ever added at the front, so the length, the counter and the newest row
// between them catch a recorded hand, a cleared history and an undo.
historySignature() {
const history = this.state.handHistory || [];
const newest = history[0];
return [
history.length,
this.state.handNumber || 1,
newest ? newest.handNumber : "",
newest ? newest.timestamp : "",
newest ? newest.pot : "",
].join("|");
},
// Rebuilding this panel measured 25.7ms of the 30ms a full re-render costs — and a
// full re-render runs after every fold, call and raise. The log only changes when a
// hand is settled or the history is cleared, perhaps once every thirty taps, so it
// is skipped unless it actually did change. Everything else on the table reflects
// the current hand and still redraws every time.
renderHandHistory(force = false) {
const signature = this.historySignature();
if (!force && signature === this.lastHistorySignature) return;
this.lastHistorySignature = signature;
document.getElementById("handCounterBadge").textContent = `Hand #${this.state.handNumber || 1}`;
const list = document.getElementById("handHistoryList");
const emptyHint = document.getElementById("handHistoryEmptyHint");
const history = this.state.handHistory || [];
emptyHint.hidden = history.length > 0;
document.getElementById("exportHistoryBtn").disabled = history.length === 0;
// Built off-document so the panel is laid out once instead of once per row.
const fragment = document.createDocumentFragment();
const template = document.getElementById("handHistoryRowTemplate");
history.forEach(entry => {
const row = template.content.firstElementChild.cloneNode(true);
row.querySelector(".handHistoryHandNumber").textContent = `Hand #${entry.handNumber}`;
row.querySelector(".handHistoryPot").textContent = Money.format(entry.pot);
row.querySelector(".handHistoryTime").textContent = this.formatHandTime(entry.timestamp);
const payoutsEl = row.querySelector(".handHistoryPayouts");
payoutsEl.textContent = entry.payouts.map(p => `${p.label} ${Money.format(p.amount)}`).join(", ");
fragment.appendChild(row);
});
list.innerHTML = "";
list.appendChild(fragment);
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = { Render };
}
@@ -0,0 +1,99 @@
// The long-press menu on a seat. Everything a dealer does to one player mid-hand,
// one press and one tap away, without opening the full editor and without hunting
// for whose turn it is in the action bar.
const SeatMenu = {
state: null,
hooks: null,
seatIndex: null,
open(state, hooks, seatIndex) {
this.state = state;
this.hooks = hooks;
this.seatIndex = seatIndex;
this.render();
document.getElementById("seatMenuOverlay").hidden = false;
},
close() {
document.getElementById("seatMenuOverlay").hidden = true;
},
// Only the actions that make sense for this seat right now — a folded player has
// nothing to go all-in with, and an empty chair has nothing to fold.
actionsFor(player, index) {
const actions = [];
const dealtIn = player.inHand;
const live = dealtIn && !player.folded;
if (live) {
actions.push({ label: "Fold", className: "menuDanger", run: () => this.hooks.fold(index) });
actions.push({ label: "All-in", className: "menuAccent", run: () => this.hooks.allIn(index) });
} else if (dealtIn && player.folded) {
actions.push({ label: "Un-fold", run: () => this.hooks.unfold(index) });
}
// The most common interruption in a cash game, and until now it meant opening
// the editor and retyping a stack from memory.
actions.push({ label: "Add chips…", run: () => this.hooks.addChips(index) });
actions.push({
label: dealtIn ? "Sit out" : "Deal in",
run: () => this.hooks.toggleDealtIn(index),
});
if (!this.state.dedicatedDealer && index !== this.state.dealerSeatIndex) {
actions.push({ label: "Give the button", run: () => this.hooks.makeDealer(index) });
}
// Naming a blind by hand. Only offered while nothing but the blinds are in —
// once somebody has called, moving a blind would mean unpicking a bet that
// has already been answered, and that's a decision for the dealer's mouth,
// not a menu item. Which blind a seat already has is shown rather than
// offered again.
if (dealtIn && Betting.onlyBlindsIn(this.state)) {
const blinds = HoldemState.getBlindSeats(this.state);
if (blinds.sbIndex !== index) {
actions.push({ label: "Make small blind", run: () => this.hooks.assignBlind(index, "sb") });
}
if (blinds.bbIndex !== index) {
actions.push({ label: "Make big blind", run: () => this.hooks.assignBlind(index, "bb") });
}
if (this.state.blindOverride) {
actions.push({ label: "Blinds follow the button again", run: () => this.hooks.clearBlindOverride() });
}
}
actions.push({ label: "Edit seat…", run: () => this.hooks.editSeat(index) });
return actions;
},
render() {
const player = this.state.seats[this.seatIndex];
document.getElementById("seatMenuTitle").textContent = HoldemState.displayName(player, this.seatIndex);
const stack = Betting.stackOf(this.state, player);
const owed = Betting.toCall(this.state, player);
const bits = [];
if (stack > 0) bits.push(`${Money.format(stack)} behind`);
if (owed > 0) bits.push(`${Money.format(owed)} to call`);
document.getElementById("seatMenuSubtitle").textContent = bits.join(" · ");
const list = document.getElementById("seatMenuActions");
list.innerHTML = "";
this.actionsFor(player, this.seatIndex).forEach(action => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = `seatMenuBtn ${action.className || ""}`;
btn.textContent = action.label;
btn.addEventListener("click", () => {
this.close();
action.run();
});
list.appendChild(btn);
});
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = SeatMenu;
}
@@ -0,0 +1,62 @@
// Keyboard control for a dealer running this on a laptop.
//
// The phone has gestures; the desktop had a mouse and nothing else. These are the
// same actions the bar already offers, reachable without moving a hand to the
// trackpad between every decision — which is the whole point when the bar is being
// tapped thirty times a hand.
const Shortcuts = {
// Deliberately single letters with no modifier: a dealer's spare hand rests on
// the keyboard, and a chord is slower than reaching for the button would be.
KEYS: {
f: "fold",
c: "checkOrCall",
r: "raise",
a: "allIn",
" ": "advance",
enter: "advance",
u: "undo",
escape: "cancel",
},
mount(handlers) {
this.handlers = handlers;
document.addEventListener("keydown", e => this.onKey(e));
},
// Nothing fires while the dealer is typing a name, an amount, or a note — the
// "c" in "Cass" must not fold the table.
isTyping() {
const el = document.activeElement;
if (!el) return false;
const tag = el.tagName;
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || el.isContentEditable;
},
// An overlay owns the keyboard while it's up. Asking the document which overlays
// are open, rather than listing them, means a sheet added later can't quietly
// start letting "f" fold the table behind it — the same reason Modal watches for
// them instead of being told about each one.
overlayOpen() {
return [...document.querySelectorAll('[id$="Overlay"]')].some(el => !el.hidden);
},
onKey(e) {
if (e.metaKey || e.ctrlKey || e.altKey) return;
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key.toLowerCase();
const action = this.KEYS[key];
if (!action) return;
// Escape is the exception: it should still close the raise pad even if focus
// happens to be sitting in its amount field.
if (this.isTyping() && !(action === "cancel")) return;
if (this.overlayOpen()) return;
const handled = this.handlers[action] && this.handlers[action]();
if (handled) e.preventDefault();
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = Shortcuts;
}
@@ -0,0 +1,53 @@
// Pure math for chopping one pot between tied players. No DOM.
//
// A dealer can't push half a chip across the felt, so this works in whole chips of
// whatever the smallest denomination in play is: everyone gets the same stack, and
// whatever won't divide is called out separately as odd chips. House rule for those
// is that they go to the first player left of the button, one at a time.
const SplitCalculator = {
// Everything is done in cents to keep 0.1 + 0.2 out of a payout.
toCents(amount) {
return Money.toCents(amount);
},
split(potAmount, ways, chipAmount) {
const potCents = this.toCents(potAmount);
const chipCents = Math.max(1, this.toCents(chipAmount));
const players = Math.max(1, Math.floor(Number(ways) || 0));
if (potCents <= 0) {
return { valid: false, each: 0, oddChips: 0, chip: chipCents / 100, dust: 0, players };
}
const wholeChips = Math.floor(potCents / chipCents);
// Left over when the pot itself isn't a whole number of the smallest chip —
// usually means the dealer picked the wrong denomination, so it's surfaced
// rather than silently rolled into someone's stack.
const dustCents = potCents - wholeChips * chipCents;
const chipsEach = Math.floor(wholeChips / players);
const oddChips = wholeChips - chipsEach * players;
return {
valid: true,
players,
each: (chipsEach * chipCents) / 100,
oddChips,
chip: chipCents / 100,
dust: dustCents / 100,
};
},
// Sanity check for the UI: what the split actually hands out has to equal the pot.
accountedFor(result) {
return Money.fromCents(
Money.toCents(result.each) * result.players +
Money.toCents(result.chip) * result.oddChips +
Money.toCents(result.dust)
);
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = SplitCalculator;
}
@@ -0,0 +1,463 @@
// Table state: seats, chips, blinds, notes. Persisted to localStorage so a dealer's
// browser refresh mid-game doesn't lose the table.
const HoldemState = {
STORAGE_KEY: "casino.holdem.state.v1",
DEFAULT_SEAT_COUNT: 10,
DEFAULT_CHIP_LEGEND: [
{ id: "white", color: "#f5f5f5", value: 1 },
{ id: "red", color: "#c0392b", value: 5 },
{ id: "green", color: "#1e8449", value: 25 },
{ id: "black", color: "#111111", value: 100 },
{ id: "purple", color: "#6c3483", value: 500 },
],
makeId(prefix) {
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
},
makePlayer() {
return {
id: this.makeId("player"),
name: "",
inHand: false,
folded: false,
cards: ["", ""],
chipCounts: {},
amountOverride: null,
customFields: [],
// Live-betting fields: chips in front of the player, chips they've put in
// on the current street, and whether they've answered the current bet.
stack: null,
committed: 0,
hasActed: false,
// Cash handed over tonight, which only moves when they buy chips.
buyIns: 0,
};
},
MAX_HISTORY_ENTRIES: 200,
createDefault() {
const seatCount = this.DEFAULT_SEAT_COUNT;
return {
seatCount,
direction: "clockwise",
basePotAmount: null,
dealerSeatIndex: 0,
dedicatedDealer: false,
chipLegend: this.DEFAULT_CHIP_LEGEND.map(c => ({ ...c })),
seats: Array.from({ length: seatCount }, () => this.makePlayer()),
notes: "",
handNumber: 1,
handHistory: [],
smallBlind: 1,
bigBlind: 2,
defaultStack: null,
street: "preflop",
currentBet: 0,
lastRaiseSize: 0,
actingSeatIndex: null,
// Set when the dealer names the blinds by hand instead of letting them
// follow the button — { sbIndex, bbIndex }. Home games do this constantly
// ("you had it last time", someone arriving late owing a blind), and the
// button order is the wrong answer often enough that it has to be
// overridable. Cleared at the start of every hand.
blindOverride: null,
};
},
load() {
try {
const raw = localStorage.getItem(this.STORAGE_KEY);
if (!raw) return this.createDefault();
const parsed = JSON.parse(raw);
if (!parsed || !Array.isArray(parsed.seats)) return this.createDefault();
if (typeof parsed.handNumber !== "number" || parsed.handNumber < 1) parsed.handNumber = 1;
if (!Array.isArray(parsed.handHistory)) parsed.handHistory = [];
// Tables saved before live betting existed are missing its fields; fill
// them in rather than making the dealer reset a table mid-session.
const defaults = this.createDefault();
["smallBlind", "bigBlind", "defaultStack", "street", "currentBet", "lastRaiseSize",
"actingSeatIndex", "blindOverride"]
.forEach(key => {
if (parsed[key] === undefined) parsed[key] = defaults[key];
});
parsed.seats.forEach(player => {
if (player.stack === undefined) player.stack = null;
if (player.committed === undefined) player.committed = 0;
if (player.hasActed === undefined) player.hasActed = false;
if (player.buyIns === undefined) player.buyIns = 0;
});
return parsed;
} catch {
return this.createDefault();
}
},
save(state) {
try {
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(state));
} catch {
// Storage full/unavailable (private browsing, etc.) — the table still works
// for the rest of the session, it just won't survive a refresh.
}
},
clear() {
try {
localStorage.removeItem(this.STORAGE_KEY);
} catch {
// ignore
}
},
resizeSeats(state, newCount) {
const count = Math.max(2, Math.min(24, Math.floor(newCount) || this.DEFAULT_SEAT_COUNT));
const seats = state.seats.slice(0, count);
while (seats.length < count) seats.push(this.makePlayer());
state.seats = seats;
state.seatCount = count;
if (state.dealerSeatIndex >= count) state.dealerSeatIndex = 0;
return state;
},
// What to call a seat in logs, payouts and standings when the dealer hasn't
// typed a name in yet.
displayName(player, seatIndex) {
return player.name && player.name.trim() ? player.name.trim() : `Seat ${seatIndex + 1}`;
},
// Contribution the table calculator will treat this player as having put in.
//
// Chips already pushed into the middle count whether or not the player is still
// in the hand. Someone who storms off, gets taken out by the dealer, or is
// dealt out mid-hand leaves their money on the felt — it's dead money owed to
// whoever wins, and it is not theirs to take back. Reading `inHand` first is
// how those chips used to disappear out of the pot the instant a seat was
// switched off, quietly shrinking the payout by whatever they had posted.
computeContribution(player, chipLegend, basePotAmount) {
const override = player.amountOverride;
if (override !== null && override !== undefined && String(override).trim() !== "") {
const parsed = Number(override);
if (!Number.isNaN(parsed)) return Math.max(0, parsed);
}
const chipTotal = chipLegend.reduce((sum, chip) => {
const count = Number(player.chipCounts[chip.id]) || 0;
return sum + count * Number(chip.value || 0);
}, 0);
if (chipTotal > 0) return chipTotal;
// The table-wide default is the one thing that stays tied to being dealt in:
// it's a stand-in for "everyone put the same amount in", so applying it to
// empty chairs would invent a contribution from every seat nobody is using.
if (!player.inHand) return 0;
const base = Number(basePotAmount);
return Number.isNaN(base) ? 0 : Math.max(0, base);
},
// Anyone whose chips are in the pot, whether or not they're still in the hand.
// A seat that's been switched off mid-hand is dead money: it counts towards the
// pot but can never be picked as a winner, exactly like a fold.
isDeadMoney(player) {
return !player.inHand;
},
// What starting the next hand would take off the table for good: exactly the
// fields startNextHand clears.
//
// Deliberately not totalPot(). The table-wide base pot is a standing ante — a
// stand-in for "everyone puts the same in every hand", used by a dealer who
// isn't tracking stacks — so it re-applies to the next hand rather than being
// lost with this one. Counting it would mean warning about money that isn't
// going anywhere, on every single hand, for exactly the dealers who chose the
// simplest way to run the table.
unresolvedContributions(state) {
const total = state.seats.reduce((sum, player) => {
const override = player.amountOverride;
let banked = 0;
if (override !== null && override !== undefined && String(override).trim() !== "") {
const parsed = Number(override);
if (!Number.isNaN(parsed)) banked = Math.max(0, parsed);
}
if (banked === 0) {
banked = (state.chipLegend || []).reduce((chips, chip) => {
const count = Number(player.chipCounts[chip.id]) || 0;
return chips + count * Number(chip.value || 0);
}, 0);
}
return sum + banked + Math.max(0, Number(player.committed) || 0);
}, 0);
return Money.round(total);
},
totalPot(state) {
return state.seats.reduce(
(sum, p) => sum + this.computeContribution(p, state.chipLegend, state.basePotAmount),
0
);
},
// Next occupied-by-index seat in the current blind direction. Every seat index
// counts (there's no separate "empty chair" concept) — a dealer running fewer
// players just keeps the seat count matched to who's actually sitting down.
nextSeatIndex(state, fromIndex, step = 1) {
const count = state.seatCount;
const delta = state.direction === "counterclockwise" ? -step : step;
return ((fromIndex + delta) % count + count) % count;
},
// The button passes to the next player, not the next chair. Moving it one seat at
// a time parks it on empty chairs — with four players spread around ten seats it
// sits on nobody most hands — and that isn't only untidy: position and blinds are
// supposed to come round to each player at the same rate, and they don't if the
// button is rotating past chairs nobody is sitting in.
advanceButton(state) {
for (let step = 1; step <= state.seatCount; step++) {
const index = this.nextSeatIndex(state, state.dealerSeatIndex, step);
if (state.seats[index].inHand) {
state.dealerSeatIndex = index;
return;
}
}
// Nobody is dealt in; move it along anyway so it doesn't look stuck.
state.dealerSeatIndex = this.nextSeatIndex(state, state.dealerSeatIndex, 1);
},
// Seats dealt into this hand, in blind order starting from the seat after the
// button. Blinds follow the players, not the chairs — the seats immediately left
// of the button are empty often enough that counting chairs posts them to nobody.
liveOrderFromButton(state) {
const order = [];
for (let step = 1; step <= state.seatCount; step++) {
const index = this.nextSeatIndex(state, state.dealerSeatIndex, step);
if (state.seats[index].inHand) order.push(index);
}
return order;
},
// A button sitting on an empty chair is only cosmetic until you try to read
// position off it. On the very first hand of a fresh table it starts on seat 1
// whether or not anybody is sitting there, and a table that empties out around it
// leaves it stranded. Move it to a real player before a hand is dealt.
ensureButtonOnPlayer(state) {
if (state.seats[state.dealerSeatIndex] && state.seats[state.dealerSeatIndex].inHand) return;
for (let step = 0; step < state.seatCount; step++) {
const index = this.nextSeatIndex(state, state.dealerSeatIndex, step);
if (state.seats[index].inHand) {
state.dealerSeatIndex = index;
return;
}
}
},
// A hand-picked blind is only usable if that seat is actually in the hand — a
// dealer who names a blind and then deals that player out shouldn't have the
// table quietly post to nobody.
validBlindOverride(state) {
const o = state.blindOverride;
if (!o) return null;
const ok = i => Number.isInteger(i) && i >= 0 && i < state.seatCount && state.seats[i] && state.seats[i].inHand;
if (!ok(o.sbIndex) || !ok(o.bbIndex) || o.sbIndex === o.bbIndex) return null;
return o;
},
// Who posts what. Heads-up is its own rule: with two players the button posts the
// small blind, which is the opposite of the usual order.
getBlindSeats(state) {
const live = this.liveOrderFromButton(state);
const dealerIndex = state.dealerSeatIndex;
// A blind the dealer named by hand wins over anything positional. Heads-up is
// still reported honestly so the betting order stays right — who posts what
// is the dealer's call, but two-handed play acting in reverse is a rule.
const override = this.validBlindOverride(state);
if (override) {
return {
dealerIndex,
sbIndex: override.sbIndex,
bbIndex: override.bbIndex,
headsUp: live.length === 2,
manual: true,
};
}
if (live.length < 2) {
return { dealerIndex, sbIndex: null, bbIndex: null, headsUp: false };
}
if (live.length === 2) {
const buttonIsPlaying = state.seats[dealerIndex].inHand;
const sbIndex = buttonIsPlaying ? dealerIndex : live[0];
const bbIndex = live.find(i => i !== sbIndex);
return { dealerIndex, sbIndex, bbIndex, headsUp: true };
}
return { dealerIndex, sbIndex: live[0], bbIndex: live[1], headsUp: false };
},
startNextHand(state) {
this.advanceButton(state);
// A hand-picked blind applies to the hand it was picked for. Carrying it into
// the next one would freeze the blinds on two players for the rest of the
// night, which is the opposite of what naming them once is for.
state.blindOverride = null;
state.seats.forEach(p => {
p.folded = false;
p.cards = ["", ""];
p.chipCounts = {};
p.amountOverride = null;
p.committed = 0;
p.hasActed = false;
});
// Anyone who joined mid-hand is a full player again from here.
this.ensureButtonOnPlayer(state);
},
// Appends a resolved-pot record to the running session log a dealer can point to
// for chip-count disputes, then advances the hand counter. `payouts` is
// [{ id, label, amount }, ...] — who got paid what out of this hand's pot(s).
//
// Must be called before startNextHand() clears the seats: the per-player `ledger`
// it stores alongside the payouts is what session standings are summed from later,
// and it needs this hand's contributions while they're still on the table.
recordHand(state, payouts) {
if (typeof state.handNumber !== "number") state.handNumber = 1;
if (!Array.isArray(state.handHistory)) state.handHistory = [];
const pot = payouts.reduce((sum, p) => sum + p.amount, 0);
const wonById = new Map(payouts.map(p => [p.id, p.amount]));
const ledger = state.seats
.map((player, index) => ({
id: player.id,
name: this.displayName(player, index),
in: this.computeContribution(player, state.chipLegend, state.basePotAmount),
won: wonById.get(player.id) || 0,
}))
.filter(row => row.in > 0 || row.won > 0);
state.handHistory.unshift({
handNumber: state.handNumber,
timestamp: Date.now(),
pot,
payouts,
ledger,
});
if (state.handHistory.length > this.MAX_HISTORY_ENTRIES) {
state.handHistory.length = this.MAX_HISTORY_ENTRIES;
}
state.handNumber += 1;
},
clearHistory(state) {
state.handHistory = [];
state.handNumber = 1;
},
// Running per-player totals for the whole session, so a dealer settling up at the
// end of the night reads one number per person instead of adding up every hand.
// Keyed by seat id, which survives renames and reseating; hands recorded before
// the ledger existed simply don't contribute to the totals.
sessionStandings(state) {
const totals = new Map();
(state.handHistory || []).forEach(entry => {
(entry.ledger || []).forEach(row => {
// History is newest-first, so the first name seen for an id is the
// most recent one the dealer typed.
const running = totals.get(row.id) || { id: row.id, name: row.name, in: 0, won: 0 };
running.in += row.in;
running.won += row.won;
totals.set(row.id, running);
});
});
// Cash bought in and chips currently in front don't come from the hand log at
// all, so they're read off the seat rather than summed — a rebuy isn't a hand.
const seatById = new Map(state.seats.map(p => [p.id, p]));
// Anyone who has money in the game belongs in the settle-up, whether or not
// they've been in a logged hand yet. Building the list from the hand log alone
// left a player who bought in and then sat through a few hands folding —
// or who just sat down — missing entirely, so the banker's own record didn't
// mention the cash they'd taken. They turn up at cash-out holding chips the
// list never accounted for.
state.seats.forEach((player, index) => {
if (totals.has(player.id)) return;
const hasMoneyInPlay =
(Number(player.buyIns) || 0) > 0 ||
(Number(player.stack) || 0) > 0 ||
(Number(player.amountOverride) || 0) > 0 ||
(Number(player.committed) || 0) > 0;
if (!hasMoneyInPlay) return;
totals.set(player.id, { id: player.id, name: this.displayName(player, index), in: 0, won: 0 });
});
return Array.from(totals.values())
.map(t => {
const seat = seatById.get(t.id);
const boughtIn = seat ? Money.round(Number(seat.buyIns) || 0) : 0;
const chipsNow = seat ? Money.round(Number(seat.stack) || 0) : 0;
// Chips already pushed into the hand in progress are still this
// player's money until it's won. Leaving them out makes the cash
// position disagree with the hand log for as long as a hand is open —
// and blinds are posted the instant the previous one settles, so that
// window is almost always.
const inFrontOfThem = seat ? (Number(seat.amountOverride) || 0) + (Number(seat.committed) || 0) : 0;
return {
...t,
in: Money.round(t.in),
won: Money.round(t.won),
net: Money.round(t.won - t.in),
boughtIn,
chipsNow,
cashPosition: Money.round(chipsNow + inFrontOfThem - boughtIn),
};
})
.sort((a, b) => b.net - a.net);
},
// The one check a banker actually needs, and the one nothing here did.
//
// Every chip on the table is a promise to pay cash for it later. If the chips in
// play add up to more than the cash that came in, that promise can't be kept —
// and the way you find out is the last two players cashing out and the box being
// empty. It's always someone taking chips without paying, a rebuy that never got
// recorded, or a miscount, and it's silent until it's too late to work out which.
//
// Chips in play counts everything a player could hand back: what's in front of
// them and what's in the middle waiting to be won.
bankReconciliation(state) {
const cashIn = state.seats.reduce((sum, p) => sum + Math.max(0, Number(p.buyIns) || 0), 0);
const chipsInPlay = state.seats.reduce(
(sum, p) =>
sum +
Math.max(0, Number(p.stack) || 0) +
Math.max(0, Number(p.committed) || 0) +
Math.max(0, Number(p.amountOverride) || 0),
0
);
const difference = Money.round(chipsInPlay - cashIn);
return {
cashIn: Money.round(cashIn),
chipsInPlay: Money.round(chipsInPlay),
difference,
// Half a cent of float dust isn't a discrepancy worth alarming anyone over.
balanced: Math.abs(difference) <= Money.EPSILON,
};
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = HoldemState;
}
+83
View File
@@ -0,0 +1,83 @@
# Hold'em dealer tests
Unit tests for the money logic behind `/Casino/TexasHoldem` — the betting engine, the
side-pot calculator, the split calculator and the table state.
```bash
node --test tests/holdem/*.test.js
```
No install step, no `package.json`, no dependencies. The browser modules are plain
script-tag files that each end with a `module.exports` guard, so Node can require them
as-is; `load.js` puts them on `globalThis` under the same names they use to find each
other in the page, in the load order from `TexasHoldem.cshtml`.
## What's covered
| File | Covers |
| --- | --- |
| `potCalculator.test.js` | Main and side pots, dead money, uncalled bets, odd-cent distribution |
| `betting.test.js` | Blinds, street completion, raises reopening the action, all-in run-outs |
| `state.test.js` | Button rotation, which seats post blinds, session standings |
| `splitCalculator.test.js` | Chopped pots, odd chips, unmakeable denominations |
| `invariants.test.js` | 1000 randomised hands per property (see below) |
## The layout audit
The unit tests above cover the money. `uiAudit.js` covers the thing you can only see
in a browser: whether a dealer can actually reach every control.
```bash
node tests/holdem/runUiAudit.js # needs Playwright and the site running
```
It checks WCAG AA contrast, touch target sizes, touch-action and tap highlights, that fields stay selectable and are large
enough not to trigger iOS zoom, that nothing important is covered or off-screen with
no way to scroll to it, that no grid column has collapsed to nothing, and that no
text is painted outside its box. It runs over the table, all five overlays and Quick
Split, at thirteen viewports from a 360px phone to a 1600px desktop and the same
phones on their side.
Deliberately not in CI: the unit suite is dependency-free and runs in a second, while
this one needs a browser and a running site. Run it after any change that adds or
resizes a control. With no Playwright to hand, paste `uiAudit.js` into devtools and
call `LayoutAudit.runAll()`.
The contrast check is built so it cannot report a false positive: backgrounds
composite through alpha, and where a gradient is involved every colour stop is tried
and the most flattering one used. A finding means the text fails even under the
reading most generous to it. Two earlier attempts at this got it wrong in both
directions — one read only `background-color` and scored text on a gradient against
nothing, the other treated low-alpha stops as opaque — so `uiAudit.js` is checked
against known-answer cases before it is believed.
Touch targets are measured by probing outward with `elementFromPoint` rather than by
reading the element box, because the box lies in both directions: a small control can
be padded out with a transparent `::after` and respond well beyond its painted size,
and a checkbox inside a label is hit by tapping the label. The 44px rule is only
enforced where `hover: none` says there's no mouse.
It exists because these checks were being re-typed into a console every time
something changed, and each time they only covered whatever had just been touched.
That is how the standings table shipped with a player-name column zero pixels wide
and kept it for two rounds.
## Why the randomised suite exists
Every correctness bug found in this tool so far has been shape-dependent: blinds posted
to empty chairs, the button skipping past players, heads-up acting out of order, an
overbet announced as a side pot. None of them show up on a full six-handed table with
equal stacks, which is the table anyone writes a fixed example for.
`invariants.test.js` deals a thousand hands across random seat counts, random empty
chairs, random stack depths and random dealer input, and checks the things a dealer
would notice being wrong:
- chips are never created or destroyed during play
- the pot breakdown plus the uncalled returns always equal the money that went in
- paying the pot out settles it to the cent
- once uncalled chips are handed back, nobody is still betting above the whole table
- the button and both blinds always land on players who are actually in the hand
The generator is seeded, so a failure reproduces from the seed printed in the message
rather than being a flake to re-run.
+169
View File
@@ -0,0 +1,169 @@
// The banker's job, which is a different job from the dealer's: every chip on the
// table is a promise to pay cash for it later, and somebody has to be able to check
// that the promise can be kept before the last two players try to cash out.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, HoldemState, Money, makeTable } = require("./load");
const seat = (state, index, name, cash, chips) => {
const p = state.seats[index];
p.name = name; p.inHand = true; p.buyIns = cash; p.stack = chips;
return p;
};
describe("everyone with money in the game is accounted for", () => {
test("a player who has bought in but played no logged hand still appears", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], stack: 0 });
seat(state, 0, "Ann", 100, 100);
seat(state, 1, "Ben", 100, 100);
seat(state, 2, "Cal", 200, 200); // just sat down
state.seats[0].amountOverride = 10;
state.seats[1].amountOverride = 10;
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "Ann", amount: 20 }]);
state.seats[0].amountOverride = null;
state.seats[1].amountOverride = null;
const names = HoldemState.sessionStandings(state).map(r => r.name);
assert.ok(names.includes("Cal"), `Cal handed over $200 and is missing: ${names.join(", ")}`);
});
test("their row reads as no hands played, not as a loss", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 100, 100);
seat(state, 1, "Ben", 200, 200);
const cal = HoldemState.sessionStandings(state).find(r => r.name === "Ben");
assert.equal(cal.in, 0);
assert.equal(cal.won, 0);
assert.equal(cal.net, 0);
assert.equal(cal.boughtIn, 200);
assert.equal(cal.cashPosition, 0, "level: they've bought chips and still hold them");
});
test("an empty chair is not dragged into the settle-up", () => {
const state = makeTable({ seatCount: 9, seated: [0], stack: 0 });
seat(state, 0, "Ann", 100, 100);
const rows = HoldemState.sessionStandings(state);
assert.equal(rows.length, 1);
});
test("somebody who has cashed out completely still shows what they took", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 100, 0); // handed every chip back
seat(state, 1, "Ben", 100, 200);
const ann = HoldemState.sessionStandings(state).find(r => r.name === "Ann");
assert.equal(ann.cashPosition, -100, "down the whole buy-in");
});
});
describe("does the cash box cover the chips on the table", () => {
test("a straight game balances", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], stack: 0 });
seat(state, 0, "Ann", 100, 60);
seat(state, 1, "Ben", 100, 140);
seat(state, 2, "Cal", 100, 100);
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.cashIn, 300);
assert.equal(bank.chipsInPlay, 300);
assert.equal(bank.difference, 0);
assert.equal(bank.balanced, true);
});
test("chips outrunning the cash box is caught before cash-out", () => {
// The 2am failure: the last players out can't be paid.
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], stack: 0 });
seat(state, 0, "Ann", 100, 100);
seat(state, 1, "Ben", 100, 100);
seat(state, 2, "Cal", 100, 260); // took chips for a rebuy nobody wrote down
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.cashIn, 300);
assert.equal(bank.chipsInPlay, 460);
assert.equal(bank.difference, 160);
assert.equal(bank.balanced, false);
});
test("cash taken for chips never handed over is caught too", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 200, 100); // paid 200, only got 100 in chips
seat(state, 1, "Ben", 100, 100);
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.difference, -100);
assert.equal(bank.balanced, false);
});
test("chips in the middle still count as chips in play", () => {
// Money in the pot is somebody's; it just hasn't been won yet. Leaving it out
// would report a shortfall every time a hand was open — which is nearly always.
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], dealerSeatIndex: 0 });
state.seats.forEach(p => { if (p.inHand) p.buyIns = 100; });
const before = HoldemState.bankReconciliation(state);
assert.equal(before.balanced, true);
Betting.beginHand(state); // blinds go in
Betting.raiseTo(state, 0, 25); // and a raise
Betting.sweepToHandTotals(state); // banked into the pot
const during = HoldemState.bankReconciliation(state);
assert.equal(during.balanced, true, "an open pot is not a discrepancy");
assert.equal(during.chipsInPlay, before.chipsInPlay);
});
test("a whole session of play never knocks the books out", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
state.seats.forEach(p => { if (p.inHand) p.buyIns = 100; });
for (let hand = 0; hand < 6; hand++) {
Betting.beginHand(state);
Betting.liveSeats(state).forEach(s => {
if (Betting.toCall(state, s.player) > 0) Betting.call(state, s.index);
});
Betting.sweepToHandTotals(state);
const pot = HoldemState.totalPot(state);
const winner = Betting.liveSeats(state)[0];
const payouts = [{ id: winner.player.id, label: "w", amount: pot }];
HoldemState.recordHand(state, payouts);
Betting.creditWinnings(state, payouts);
HoldemState.startNextHand(state);
assert.equal(HoldemState.bankReconciliation(state).balanced, true, `books off after hand ${hand + 1}`);
}
});
test("a rebuy keeps the books straight, a chip grab doesn't", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 100, 100);
seat(state, 1, "Ben", 100, 100);
// A proper rebuy: cash to the banker, chips to the player.
state.seats[0].buyIns += 100;
state.seats[0].stack += 100;
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
// Chips taken without paying.
state.seats[1].stack += 50;
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.balanced, false);
assert.equal(bank.difference, 50);
});
test("nothing to reconcile before anybody has bought in", () => {
const state = makeTable({ seatCount: 6, seated: [], stack: 0 });
const bank = HoldemState.bankReconciliation(state);
assert.equal(bank.cashIn, 0);
assert.equal(bank.chipsInPlay, 0);
assert.equal(bank.balanced, true);
});
test("float dust is not a discrepancy", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1], stack: 0 });
seat(state, 0, "Ann", 0.1 + 0.2, 0.3);
seat(state, 1, "Ben", 10, 10);
assert.equal(HoldemState.bankReconciliation(state).balanced, true);
});
});
+198
View File
@@ -0,0 +1,198 @@
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, makeTable, chipsOnTable } = require("./load");
describe("Betting.beginHand", () => {
test("blinds are posted and the seat after the big blind acts first", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0, smallBlind: 1, bigBlind: 2 });
Betting.beginHand(state);
assert.equal(state.seats[1].committed, 1, "small blind");
assert.equal(state.seats[2].committed, 2, "big blind");
assert.equal(state.currentBet, 2);
assert.equal(state.actingSeatIndex, 3, "under the gun");
});
test("heads-up, the button posts the small blind and acts first pre-flop", () => {
const state = makeTable({ seatCount: 6, seated: [2, 5], dealerSeatIndex: 2 });
Betting.beginHand(state);
assert.equal(state.seats[2].committed, 1, "the button is the small blind");
assert.equal(state.seats[5].committed, 2);
assert.equal(state.actingSeatIndex, 2, "the small blind acts first pre-flop heads-up");
});
test("heads-up, the big blind acts first once the flop is out", () => {
const state = makeTable({ seatCount: 6, seated: [2, 5], dealerSeatIndex: 2 });
Betting.beginHand(state);
Betting.call(state, 2);
Betting.check(state, 5);
Betting.closeStreet(state);
assert.equal(state.street, "flop");
assert.equal(state.actingSeatIndex, 5, "the big blind is first to act after the flop");
});
test("a blind bigger than a stack puts that player all-in without stalling the action", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1], dealerSeatIndex: 0, smallBlind: 50, bigBlind: 100 });
state.seats[0].stack = 10; // can't cover the small blind
Betting.beginHand(state);
assert.equal(state.seats[0].stack, 0, "all-in for what they had");
assert.equal(state.seats[0].committed, 10);
assert.notEqual(state.actingSeatIndex, 0, "a player with no chips has nothing to decide");
});
test("posting blinds never invents or destroys chips", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], stack: 100 });
const before = chipsOnTable(state);
Betting.beginHand(state);
assert.equal(chipsOnTable(state), before);
});
});
describe("Betting street completion", () => {
test("a street ends once everyone has matched the bet and had a turn", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3);
Betting.call(state, 0);
Betting.call(state, 1);
assert.equal(Betting.isStreetComplete(state), false, "the big blind still has an option");
Betting.check(state, 2);
assert.equal(Betting.isStreetComplete(state), true);
assert.equal(state.actingSeatIndex, null);
});
test("a raise reopens the action for everyone who had already called", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3);
Betting.call(state, 0);
assert.equal(state.seats[3].hasActed, true);
Betting.raiseTo(state, 1, 10);
assert.equal(state.seats[3].hasActed, false, "seat 3 owes a response again");
assert.equal(state.seats[0].hasActed, false);
assert.equal(state.currentBet, 10);
assert.equal(Betting.isStreetComplete(state), false);
});
test("the action skips a player who is all-in but still in the hand", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
state.seats[3].stack = 5;
Betting.beginHand(state);
Betting.allIn(state, 3);
assert.equal(state.seats[3].stack, 0);
assert.notEqual(state.actingSeatIndex, 3);
// They are still live and can still win the pot.
assert.ok(Betting.liveSeats(state).some(s => s.index === 3));
});
test("closing a street sweeps chips into hand totals and resets the bet", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3);
Betting.call(state, 0);
Betting.call(state, 1);
Betting.check(state, 2);
const before = chipsOnTable(state);
Betting.closeStreet(state);
assert.equal(state.currentBet, 0);
assert.equal(state.street, "flop");
assert.equal(chipsOnTable(state), before, "sweeping moves chips, it doesn't change the total");
state.seats.forEach(p => assert.equal(p.committed, 0));
assert.equal(Betting.handTotal(state.seats[2]), 2);
});
});
describe("Betting all-in run-outs", () => {
test("with everyone all-in there is nobody left to ask", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], stack: 20, dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.allIn(state, 2);
Betting.allIn(state, 0);
Betting.allIn(state, 1);
assert.equal(Betting.canStillBet(state), false);
assert.equal(Betting.isRunningOut(state), true, "the board just gets dealt out");
Betting.closeStreet(state);
assert.equal(state.actingSeatIndex, null, "no phantom action on the flop");
});
test("one player with chips against an all-in cannot bet alone", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], dealerSeatIndex: 0 });
state.seats[1].stack = 5;
Betting.beginHand(state);
Betting.fold(state, 2);
Betting.allIn(state, 0);
Betting.allIn(state, 1);
assert.equal(Betting.canStillBet(state), false);
assert.equal(Betting.isHandOver(state), false, "two players are still live for the showdown");
});
test("everyone folding to one player ends the hand", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.fold(state, 3);
Betting.fold(state, 0);
Betting.fold(state, 1);
assert.equal(Betting.isHandOver(state), true);
});
});
describe("Betting money handling", () => {
test("a player can never put in more than they have", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], stack: 30, dealerSeatIndex: 0 });
Betting.beginHand(state);
const moved = Betting.putIn(state, 0, 500);
assert.equal(moved, 30);
assert.equal(state.seats[0].stack, 0);
});
test("raise-to is what a dealer says out loud, not raise-by", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.raiseTo(state, 3, 10);
assert.equal(state.seats[3].committed, 10, "their street total is 10, not 10 on top");
assert.equal(state.seats[3].stack, 90);
});
test("the minimum raise has to match the last one", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
assert.equal(Betting.minRaiseTo(state), 4, "a big blind of 2 makes the first raise 4");
Betting.raiseTo(state, 3, 10);
assert.equal(Betting.minRaiseTo(state), 18, "an 8-chip raise means the next one is to 18");
});
test("winnings land back in front of the player", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.creditWinnings(state, [{ id: state.seats[0].id, amount: 42.5 }]);
assert.equal(state.seats[0].stack, 142.5, "the button posts nothing three-handed");
});
test("fractional blinds don't drift into floating-point dust", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], stack: 10, smallBlind: 0.1, bigBlind: 0.2 });
Betting.beginHand(state);
Betting.call(state, 0); // button limps
Betting.call(state, 1); // small blind completes
Betting.check(state, 2); // big blind is happy
Betting.closeStreet(state);
assert.equal(chipsOnTable(state), 30, "0.1 + 0.2 arithmetic didn't lose a chip");
assert.equal(Betting.potSoFar(state), 0.6);
state.seats.forEach(p => assert.equal(p.stack, 9.8));
});
});
+118
View File
@@ -0,0 +1,118 @@
// The hand-history panel is only rebuilt when its signature changes, which takes a
// full re-render from ~30ms to ~3ms. The whole saving depends on that signature
// noticing every way the log can actually change — a stale panel would have the
// dealer reading last hand's payouts while settling this one.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Render, HoldemState, makeTable } = require("./load");
// historySignature() reads Render.state, so point it at a table for each case.
const signatureOf = state => {
Render.state = state;
return Render.historySignature();
};
const tableWithHands = (count) => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2] });
for (let i = 0; i < count; i++) {
state.seats[0].amountOverride = 2;
state.seats[1].amountOverride = 2;
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "Ann", amount: 4 }]);
}
return state;
};
describe("the history panel knows when to redraw", () => {
test("nothing changes while a hand is being played", () => {
const state = tableWithHands(3);
const before = signatureOf(state);
// A whole street of betting touches no part of the log.
state.seats[0].committed = 5;
state.seats[1].folded = true;
state.actingSeatIndex = 2;
state.street = "flop";
assert.equal(signatureOf(state), before, "betting must not force a rebuild");
});
test("settling a hand changes it", () => {
const state = tableWithHands(3);
const before = signatureOf(state);
HoldemState.recordHand(state, [{ id: state.seats[1].id, label: "Ben", amount: 12 }]);
assert.notEqual(signatureOf(state), before);
});
test("clearing the history changes it", () => {
const state = tableWithHands(5);
const before = signatureOf(state);
HoldemState.clearHistory(state);
assert.notEqual(signatureOf(state), before);
});
test("undoing back to a shorter log changes it", () => {
const state = tableWithHands(2);
const snapshot = JSON.parse(JSON.stringify(state));
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "Ann", amount: 30 }]);
const afterRecord = signatureOf(state);
// The undo path swaps the state's contents in place.
Object.keys(state).forEach(k => delete state[k]);
Object.assign(state, snapshot);
assert.notEqual(signatureOf(state), afterRecord, "an undone hand must disappear from the panel");
});
test("two hands that differ only in payout are told apart", () => {
const a = tableWithHands(1);
const b = tableWithHands(1);
// Same count and hand number; different pot.
b.handHistory[0].pot = a.handHistory[0].pot + 25;
assert.notEqual(signatureOf(a), signatureOf(b));
});
test("the hand counter moving on changes it", () => {
// The counter badge is drawn by the same function, so a new hand number has
// to invalidate even when the log itself is untouched.
const state = tableWithHands(2);
const before = signatureOf(state);
state.handNumber += 1;
assert.notEqual(signatureOf(state), before);
});
test("an empty log has a stable signature of its own", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1] });
const first = signatureOf(state);
assert.equal(signatureOf(state), first);
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "Ann", amount: 4 }]);
assert.notEqual(signatureOf(state), first, "the first hand ever must draw the panel");
});
});
describe("the hand-time cache", () => {
test("the same timestamp is only formatted once, and formats the same", () => {
Render.handTimeCache.clear();
const stamp = Date.UTC(2026, 8, 1, 15, 4);
const first = Render.formatHandTime(stamp);
assert.equal(Render.handTimeCache.size, 1);
const second = Render.formatHandTime(stamp);
assert.equal(second, first);
assert.equal(Render.handTimeCache.size, 1, "not re-formatted");
});
test("different timestamps still format differently", () => {
Render.handTimeCache.clear();
const a = Render.formatHandTime(Date.UTC(2026, 8, 1, 15, 4));
const b = Render.formatHandTime(Date.UTC(2026, 8, 1, 18, 47));
assert.notEqual(a, b);
assert.equal(Render.handTimeCache.size, 2);
});
test("a nonsense timestamp doesn't throw", () => {
Render.handTimeCache.clear();
assert.doesNotThrow(() => Render.formatHandTime(undefined));
assert.doesNotThrow(() => Render.formatHandTime("not a date"));
});
});
+213
View File
@@ -0,0 +1,213 @@
// Randomised whole-hand play against the invariants a dealer would notice being broken.
//
// These ran once, by hand, in a browser console while the betting engine was being
// fixed, and then went away with the tab. The bugs they caught (blinds posted to empty
// chairs, the button skipping players, heads-up acting out of order) are all cases you
// only hit on a particular table shape, so a fixed set of examples misses them. Keeping
// the generator means the next change gets checked against the same thousand tables.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, PotCalculator, HoldemState, Money, makeTable, chipsOnTable, contributions } = require("./load");
// Deterministic PRNG: a failure has to be reproducible from the seed printed with it,
// otherwise a randomised suite is just a flaky one.
function rng(seed) {
let s = seed >>> 0;
return () => {
s = (s * 1664525 + 1013904223) >>> 0;
return s / 4294967296;
};
}
// Plays one hand to completion with random but legal-ish dealer input.
function playHand(random) {
const seatCount = 2 + Math.floor(random() * 9);
const seatIndexes = [...Array(seatCount).keys()];
const seated = seatIndexes.filter(() => random() < 0.7);
if (seated.length < 2) seated.push(...seatIndexes.filter(i => !seated.includes(i)).slice(0, 2 - seated.length));
const bigBlind = [2, 5, 0.5][Math.floor(random() * 3)];
const state = makeTable({
seatCount,
seated,
stack: 0,
smallBlind: bigBlind / 2,
bigBlind,
dealerSeatIndex: Math.floor(random() * seatCount),
});
// Varied stack depths, so short stacks and side pots actually happen.
seated.forEach(i => {
state.seats[i].stack = Money.round(bigBlind * (1 + Math.floor(random() * 60)));
});
const startingChips = chipsOnTable(state);
Betting.beginHand(state);
let guard = 0;
while (!Betting.isHandOver(state) && state.street !== "done" && guard++ < 400) {
if (state.actingSeatIndex === null) {
if (state.street === "river" || !Betting.canStillBet(state)) break;
Betting.closeStreet(state);
continue;
}
const index = state.actingSeatIndex;
const player = state.seats[index];
const toCall = Betting.toCall(state, player);
const roll = random();
if (roll < 0.15) Betting.fold(state, index);
else if (roll < 0.25) Betting.allIn(state, index);
else if (toCall > 0) Betting.call(state, index);
else if (roll < 0.75) Betting.check(state, index);
else Betting.raiseTo(state, index, Betting.minRaiseTo(state));
}
Betting.sweepToHandTotals(state);
return { state, startingChips, seated };
}
describe("randomised hands hold the dealer's invariants", () => {
const HANDS = 1000;
test(`${HANDS} hands never create or destroy a chip`, () => {
const random = rng(20260901);
for (let hand = 0; hand < HANDS; hand++) {
const { state, startingChips } = playHand(random);
assert.equal(
chipsOnTable(state),
startingChips,
`hand ${hand}: chips on the table changed during play`
);
}
});
test(`${HANDS} hands: pots plus uncalled returns always equal the money in`, () => {
const random = rng(778899);
let sidePotHands = 0;
let returnHands = 0;
for (let hand = 0; hand < HANDS; hand++) {
const { state } = playHand(random);
const players = contributions(state);
const inThePot = players.reduce((sum, p) => sum + p.contribution, 0);
if (inThePot <= 0) continue;
// Fold flags can leave nobody live, which the calculator deliberately
// refuses to guess at — that's a dealer correction, not an invariant.
if (players.every(p => p.folded)) continue;
const layered = PotCalculator.layers(players).reduce((s, l) => s + l.amount, 0);
const returned = PotCalculator.uncalledReturns(players).reduce((s, r) => s + r.amount, 0);
assert.equal(
Money.toCents(layered + returned),
Money.toCents(inThePot),
`hand ${hand}: pot breakdown doesn't add up to what went in`
);
if (PotCalculator.layers(players).length > 1) sidePotHands++;
if (returned > 0) returnHands++;
}
assert.ok(sidePotHands > 20, `expected side pots to occur; saw ${sidePotHands}`);
assert.ok(returnHands > 20, `expected uncalled bets to occur; saw ${returnHands}`);
});
test(`${HANDS} hands: what's left after returns is money somebody actually matched`, () => {
// The rule the pot breakdown rests on: you are only called up to what somebody
// else was willing to put in. Once the uncalled chips are handed back, no
// player should still be sitting above every other player at the table.
//
// A single-eligible pot is *not* the thing to look for here — that's legitimate
// when a player called and then folded, leaving dead money one contender
// collects. The bug this guards against is subtler: chips nobody ever matched
// being dressed up as a pot to play for.
const random = rng(13579);
for (let hand = 0; hand < HANDS; hand++) {
const { state } = playHand(random);
const players = contributions(state);
if (players.every(p => p.folded)) continue;
const returns = PotCalculator.uncalledReturns(players);
assert.ok(returns.length <= 1, `hand ${hand}: only the biggest bet can go uncalled`);
returns.forEach(r => {
const player = players.find(p => p.id === r.id);
assert.ok(r.amount <= player.contribution + 0.001, `hand ${hand}: returned more than was put in`);
});
const returned = new Map(returns.map(r => [r.id, r.amount]));
const capped = players.map(p => Money.toCents(p.contribution - (returned.get(p.id) || 0)));
capped.forEach((cents, index) => {
const others = capped.filter((_, i) => i !== index);
const mostAnyoneElsePaid = others.length ? Math.max(...others) : 0;
assert.ok(
cents <= mostAnyoneElsePaid,
`hand ${hand}: a player is still ${Money.fromCents(cents - mostAnyoneElsePaid)} ` +
`above everyone else after returns — that money was never matched`
);
});
}
});
test(`${HANDS} hands: paying the pot out settles it exactly`, () => {
const random = rng(24680);
for (let hand = 0; hand < HANDS; hand++) {
const { state } = playHand(random);
const players = contributions(state);
if (players.every(p => p.folded)) continue;
// Take the uncalled money off first, the way the dealer would.
const returned = new Map(PotCalculator.uncalledReturns(players).map(r => [r.id, r.amount]));
const contested = players.map(p => ({
...p,
contribution: Money.round(p.contribution - (returned.get(p.id) || 0)),
}));
let entries = PotCalculator.buildEntries(contested);
const potBefore = PotCalculator.totalPot(entries);
let paidOut = 0;
let rounds = 0;
while (PotCalculator.getContenders(entries).length > 0 && rounds++ < 30) {
const contenders = PotCalculator.getContenders(entries);
const winner = contenders[Math.floor(random() * contenders.length)];
const result = PotCalculator.resolveRound(entries, [winner.id]);
paidOut += result.perWinner.reduce((s, w) => s + w.amount, 0);
entries = result.updatedEntries;
}
assert.equal(
Money.toCents(paidOut),
Money.toCents(potBefore),
`hand ${hand}: paying out the pot left ${potBefore - paidOut} unaccounted for`
);
}
});
test(`${HANDS} hands: the button and blinds land on real players`, () => {
const random = rng(112233);
for (let hand = 0; hand < HANDS; hand++) {
const seatCount = 2 + Math.floor(random() * 9);
const seated = [...Array(seatCount).keys()].filter(() => random() < 0.6);
if (seated.length < 2) continue;
const state = makeTable({ seatCount, seated, dealerSeatIndex: Math.floor(random() * seatCount) });
HoldemState.advanceButton(state);
assert.ok(state.seats[state.dealerSeatIndex].inHand, `hand ${hand}: button on an empty chair`);
const { sbIndex, bbIndex, headsUp } = HoldemState.getBlindSeats(state);
assert.ok(state.seats[sbIndex].inHand, `hand ${hand}: small blind on an empty chair`);
assert.ok(state.seats[bbIndex].inHand, `hand ${hand}: big blind on an empty chair`);
assert.notEqual(sbIndex, bbIndex, `hand ${hand}: both blinds on one player`);
if (seated.length === 2) {
assert.ok(headsUp, `hand ${hand}: two players should be heads-up`);
assert.equal(sbIndex, state.dealerSeatIndex, `hand ${hand}: heads-up button posts the small blind`);
}
}
});
});
+85
View File
@@ -0,0 +1,85 @@
// Loads the dealer's browser modules into Node so they can be tested directly.
//
// The modules are plain script-tag files: each one declares a `const` namespace and
// ends with a `module.exports` guard. In the browser they find each other as globals,
// so the same names have to exist on `globalThis` here or `Betting` can't reach
// `HoldemState`. Load order matches the <script> order in TexasHoldem.cshtml.
const path = require("path");
const SRC = path.join(__dirname, "..", "..", "JoshHeaps.Net", "wwwroot", "js", "casino", "holdem");
function load(name) {
const mod = require(path.join(SRC, `${name}.js`));
globalThis[name.charAt(0).toUpperCase() + name.slice(1)] = mod;
return mod;
}
const Money = load("money");
const PotCalculator = load("potCalculator");
const SplitCalculator = load("splitCalculator");
const Betting = load("betting");
const HandHistoryExport = load("handHistoryExport");
// render.js exports { Render } rather than the namespace directly.
const Render = require(path.join(SRC, "render.js")).Render;
globalThis.Render = Render;
// state.js exports `HoldemState`, which doesn't match its filename.
const HoldemState = require(path.join(SRC, "state.js"));
globalThis.HoldemState = HoldemState;
// ---- Table builders ----------------------------------------------------------
// A table with `seatCount` chairs where `seated` (a list of seat indexes) are dealt
// in with `stack` chips each. Everything else is the app's own defaults, so a test
// that forgets to set a field gets whatever a real dealer would get.
function makeTable({ seatCount = 6, seated = null, stack = 100, smallBlind = 1, bigBlind = 2, dealerSeatIndex = 0 } = {}) {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, seatCount);
state.smallBlind = smallBlind;
state.bigBlind = bigBlind;
state.dealerSeatIndex = dealerSeatIndex;
const sitting = seated || state.seats.map((_, i) => i);
state.seats.forEach((player, index) => {
player.inHand = sitting.includes(index);
player.stack = sitting.includes(index) ? stack : null;
player.name = `P${index + 1}`;
});
return state;
}
// Total chips the table is accountable for: what's in front of everyone, plus what
// they've pushed in this street, plus what's already banked into the pot.
function chipsOnTable(state) {
return Money.round(
state.seats.reduce(
(sum, p) => sum + (Number(p.stack) || 0) + (Number(p.committed) || 0) + (Number(p.amountOverride) || 0),
0
)
);
}
// Contributions in the shape PotCalculator wants them.
function contributions(state) {
return state.seats
.filter(p => p.inHand)
.map(p => ({
id: p.id,
contribution: Betting.handTotal(p),
folded: p.folded,
}));
}
module.exports = {
Money,
Render,
HandHistoryExport,
PotCalculator,
SplitCalculator,
Betting,
HoldemState,
makeTable,
chipsOnTable,
contributions,
};
+260
View File
@@ -0,0 +1,260 @@
// Home games are messy. People walk up mid-hand, storm off mid-hand, argue about
// whose blind it is, and pass the button round three times before anyone deals.
// These are the cases the positional rules quietly get wrong.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, HoldemState, PotCalculator, Money, makeTable, chipsOnTable, contributions } = require("./load");
const potOf = state => HoldemState.totalPot(state);
describe("a player leaves in the middle of a hand", () => {
test("their chips stay in the pot", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3); Betting.call(state, 0); Betting.call(state, 1); Betting.check(state, 2);
Betting.sweepToHandTotals(state);
const before = potOf(state);
assert.equal(before, 8);
state.seats[1].inHand = false; // dealer takes them out
assert.equal(potOf(state), before, "the pot must not shrink when a player is taken out");
});
test("they cannot be paid out of a pot they walked away from", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 0); Betting.call(state, 1); Betting.check(state, 2);
Betting.sweepToHandTotals(state);
state.seats[1].inHand = false;
const players = state.seats
.filter(p => HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount) > 0)
.map(p => ({
id: p.id,
contribution: HoldemState.computeContribution(p, state.chipLegend, state.basePotAmount),
folded: p.folded || HoldemState.isDeadMoney(p),
}));
const layers = PotCalculator.layers(players);
assert.ok(!layers[0].eligible.includes(state.seats[1].id), "a departed player can't win");
assert.equal(layers.reduce((s, l) => s + l.amount, 0), 6, "but their money is still being played for");
});
test("taking out the player who is to act moves the action on", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
const acting = state.actingSeatIndex;
state.seats[acting].inHand = false;
Betting.passAction(state, acting);
assert.notEqual(state.actingSeatIndex, acting, "the table can't wait on somebody who left");
assert.ok(state.actingSeatIndex === null || state.seats[state.actingSeatIndex].inHand);
});
test("an empty chair still contributes nothing, base pot or not", () => {
// The table-wide default must not be read as an ante from seats nobody is in.
const state = makeTable({ seatCount: 6, seated: [0, 1], dealerSeatIndex: 0 });
state.basePotAmount = 25;
assert.equal(HoldemState.computeContribution(state.seats[4], state.chipLegend, 25), 0);
});
});
describe("a player joins in the middle of a hand", () => {
test("they sit the hand out rather than joining a pot they never paid into", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 0); Betting.call(state, 1); Betting.check(state, 2);
Betting.sweepToHandTotals(state);
// Walks up and is dealt in — the app marks them folded for this hand.
state.seats[4].inHand = true;
state.seats[4].stack = 100;
state.seats[4].folded = true;
assert.ok(!Betting.liveSeats(state).some(s => s.index === 4), "not live this hand");
assert.equal(HoldemState.computeContribution(state.seats[4], state.chipLegend, state.basePotAmount), 0);
});
test("they are a full player again on the next hand", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
state.seats[4].inHand = true;
state.seats[4].stack = 100;
state.seats[4].folded = true;
HoldemState.startNextHand(state);
Betting.beginHand(state);
assert.equal(state.seats[4].folded, false);
assert.ok(Betting.liveSeats(state).some(s => s.index === 4), "dealt in like anyone else");
});
});
describe("passing the button around before the cards come out", () => {
test("moving the button re-posts the blinds and keeps the chip count straight", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
const startingChips = chipsOnTable(state);
Betting.beginHand(state);
assert.equal(state.seats[1].committed, 1);
assert.equal(state.seats[2].committed, 2);
state.dealerSeatIndex = 2;
Betting.repostBlinds(state);
assert.equal(state.seats[1].committed, 0, "the old small blind got their chip back");
assert.equal(state.seats[3].committed, 1, "and the new one has posted");
assert.equal(state.seats[0].committed, 2);
assert.equal(chipsOnTable(state), startingChips, "no chips created or lost in the shuffle");
});
test("passing it round many times still balances", () => {
const state = makeTable({ seatCount: 8, seated: [0, 2, 3, 5, 7], dealerSeatIndex: 0 });
const startingChips = chipsOnTable(state);
Betting.beginHand(state);
[2, 5, 7, 3, 0, 5].forEach(seat => {
state.dealerSeatIndex = seat;
Betting.repostBlinds(state);
assert.equal(chipsOnTable(state), startingChips, `chips drifted after passing to seat ${seat}`);
});
const { sbIndex, bbIndex } = HoldemState.getBlindSeats(state);
assert.equal(Betting.committed(state.seats[sbIndex]), 1);
assert.equal(Betting.committed(state.seats[bbIndex]), 2);
});
test("once somebody has acted, the blinds are settled", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
assert.equal(Betting.onlyBlindsIn(state), true, "nothing but blinds so far");
Betting.call(state, 3);
assert.equal(Betting.onlyBlindsIn(state), false, "a call means the blinds are set where they are");
});
});
describe("naming the blinds by hand", () => {
test("a named blind wins over the button order", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
state.blindOverride = { sbIndex: 3, bbIndex: 0 };
const { sbIndex, bbIndex, manual } = HoldemState.getBlindSeats(state);
assert.equal(sbIndex, 3);
assert.equal(bbIndex, 0);
assert.equal(manual, true);
Betting.beginHand(state);
assert.equal(state.seats[3].committed, 1);
assert.equal(state.seats[0].committed, 2);
assert.equal(state.seats[1].committed, 0, "the positional small blind posts nothing");
});
test("a named blind on a player who isn't dealt in is ignored", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
state.blindOverride = { sbIndex: 4, bbIndex: 0 }; // seat 4 is an empty chair
const { sbIndex, manual } = HoldemState.getBlindSeats(state);
assert.ok(!manual, "falls back to the button order rather than posting to nobody");
assert.ok(state.seats[sbIndex].inHand);
});
test("both blinds on one player is refused", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2], dealerSeatIndex: 0 });
state.blindOverride = { sbIndex: 1, bbIndex: 1 };
const { sbIndex, bbIndex } = HoldemState.getBlindSeats(state);
assert.notEqual(sbIndex, bbIndex);
});
test("naming blinds heads-up still acts in the right order", () => {
const state = makeTable({ seatCount: 6, seated: [2, 5], dealerSeatIndex: 2 });
state.blindOverride = { sbIndex: 5, bbIndex: 2 }; // deliberately the reverse
Betting.beginHand(state);
assert.equal(state.seats[5].committed, 1);
assert.equal(state.seats[2].committed, 2);
assert.equal(state.actingSeatIndex, 5, "the small blind acts first pre-flop heads-up");
Betting.call(state, 5);
Betting.check(state, 2);
Betting.closeStreet(state);
assert.equal(state.actingSeatIndex, 2, "and the big blind leads after the flop");
});
test("the naming only lasts the hand it was made for", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
state.blindOverride = { sbIndex: 3, bbIndex: 0 };
Betting.beginHand(state);
HoldemState.startNextHand(state);
assert.equal(state.blindOverride, null, "blinds go back to following the button");
});
});
describe("the first hand on a fresh table", () => {
test("the button never starts on an empty chair", () => {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 9);
[4, 6, 7].forEach(i => { state.seats[i].inHand = true; state.seats[i].stack = 100; });
assert.equal(state.dealerSeatIndex, 0, "a fresh table starts the button on seat 1");
assert.equal(state.seats[0].inHand, false, "which nobody is sitting in");
Betting.beginHand(state);
assert.ok(state.seats[state.dealerSeatIndex].inHand, "the button moved to a real player");
const { sbIndex, bbIndex } = HoldemState.getBlindSeats(state);
assert.ok(state.seats[sbIndex].inHand);
assert.ok(state.seats[bbIndex].inHand);
assert.notEqual(sbIndex, bbIndex);
});
test("a table that empties out around the button recovers", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 3 });
state.seats[3].inHand = false; // the player holding the button leaves
HoldemState.ensureButtonOnPlayer(state);
assert.ok(state.seats[state.dealerSeatIndex].inHand);
});
test("two players left after everyone else walks is heads-up, blinds reversed", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
[2, 3].forEach(i => { state.seats[i].inHand = false; });
HoldemState.startNextHand(state);
Betting.beginHand(state);
const { sbIndex, headsUp } = HoldemState.getBlindSeats(state);
assert.equal(headsUp, true);
assert.equal(sbIndex, state.dealerSeatIndex, "heads-up the button posts the small blind");
});
});
describe("chips survive a messy table", () => {
test("joining, leaving and passing the button never changes the chip count", () => {
const state = makeTable({ seatCount: 8, seated: [0, 1, 2, 3], stack: 100, dealerSeatIndex: 0 });
state.seats[6].stack = 100; // sitting down but not dealt in yet
const startingChips = chipsOnTable(state);
Betting.beginHand(state);
state.dealerSeatIndex = 2;
Betting.repostBlinds(state);
state.seats[6].inHand = true; // walks up mid-hand
state.seats[6].folded = true;
assert.equal(chipsOnTable(state), startingChips);
Betting.call(state, state.actingSeatIndex);
state.seats[1].inHand = false; // and someone storms off
Betting.sweepToHandTotals(state);
assert.equal(chipsOnTable(state), startingChips, "every chip is still accounted for");
assert.equal(
Money.toCents(potOf(state) + state.seats.reduce((s, p) => s + (Number(p.stack) || 0), 0)),
Money.toCents(startingChips),
"and the pot plus the stacks is the whole table"
);
});
});
+126
View File
@@ -0,0 +1,126 @@
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Money, HandHistoryExport } = require("./load");
describe("Money.format", () => {
test("whole amounts drop the pointless cents", () => {
assert.equal(Money.format(12), "$12");
assert.equal(Money.format(450), "$450");
assert.equal(Money.format(1250000), "$1,250,000");
assert.equal(Money.format(0), "$0");
});
test("amounts that carry cents still show them", () => {
assert.equal(Money.format(12.5), "$12.50");
assert.equal(Money.format(0.25), "$0.25");
assert.equal(Money.format(3.01), "$3.01");
});
test("a quarter-blind game reads exactly as it did", () => {
// The case that would be ruined by dropping cents unconditionally.
[0.25, 0.5, 1.75, 12.05].forEach(v => {
assert.match(Money.format(v), /\.\d\d$/, `${v} lost its cents`);
});
});
test("floating-point dust doesn't invent cents", () => {
assert.equal(Money.format(0.1 + 0.2), "$0.30");
assert.equal(Money.format(1.0000000001), "$1");
});
test("signed amounts put the sign out front, both scales", () => {
assert.equal(Money.formatSigned(87500), "+$87,500");
assert.equal(Money.formatSigned(-87500), "-$87,500");
assert.equal(Money.formatSigned(-12.5), "-$12.50");
assert.equal(Money.formatSigned(0), "$0");
});
test("rubbish in doesn't produce rubbish out", () => {
assert.equal(Money.format(null), "$0");
assert.equal(Money.format(undefined), "$0");
assert.equal(Money.format("nonsense"), "$0");
});
});
describe("Money.forSheet", () => {
test("a bare number a spreadsheet will add up", () => {
assert.equal(Money.forSheet(1250000), "1250000.00");
assert.equal(Money.forSheet(12.5), "12.50");
assert.equal(Money.forSheet(-87500), "-87500.00");
});
test("no currency symbol and no thousands separators", () => {
const written = Money.forSheet(1234567.89);
assert.ok(!written.includes("$"), "a $ makes the cell text");
assert.ok(!written.includes(","), "a comma makes the cell text");
assert.equal(Number(written), 1234567.89, "and it parses straight back to a number");
});
});
describe("the exported CSV", () => {
const history = [
{ handNumber: 2, timestamp: 0, pot: 1250000, payouts: [{ id: "a", label: "Alexandra", amount: 1250000 }] },
{ handNumber: 1, timestamp: 0, pot: 24.5, payouts: [{ id: "b", label: "Bob", amount: 24.5 }] },
];
const standings = [
{ id: "a", name: "Alexandra", in: 1250000, won: 1250000, net: 0, boughtIn: 3200000, chipsNow: 3200000, cashPosition: 0 },
{ id: "b", name: "Bob", in: 24.5, won: 0, net: -24.5, boughtIn: 100, chipsNow: 75.5, cashPosition: -24.5 },
];
// Splitting on commas isn't good enough: the timestamp column legitimately holds
// one ("1/1/1970, 5:00:00 PM") and is quoted for exactly that reason.
const splitRow = line => {
const fields = [];
let field = "";
let quoted = false;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (quoted) {
if (c === '"' && line[i + 1] === '"') { field += '"'; i++; }
else if (c === '"') quoted = false;
else field += c;
} else if (c === '"') quoted = true;
else if (c === ",") { fields.push(field); field = ""; }
else field += c;
}
fields.push(field);
return fields;
};
test("every money cell parses as a number", () => {
const csv = HandHistoryExport.toCsv(history, standings);
const lines = csv.split("\r\n");
lines.slice(1, 3).forEach(line => {
const cell = splitRow(line)[2]; // Pot
assert.ok(cell !== "" && !Number.isNaN(Number(cell)), `pot cell "${cell}" isn't a number`);
});
// Standings rows: every column after the name has to be numeric.
const standingsStart = lines.findIndex(l => l.startsWith("Player,"));
lines.slice(standingsStart + 1).filter(Boolean).forEach(line => {
splitRow(line).slice(1).forEach(cell => {
assert.ok(cell !== "" && !Number.isNaN(Number(cell)), `standings cell "${cell}" isn't a number`);
});
});
});
test("a million-dollar pot doesn't need quoting any more", () => {
const csv = HandHistoryExport.toCsv(history, []);
assert.ok(csv.includes("1250000.00"), "written plainly");
assert.ok(!csv.includes('"$1,250,000'), "not as a quoted, unsummable string");
});
test("names and payout descriptions stay human", () => {
const csv = HandHistoryExport.toCsv(history, standings);
assert.ok(csv.includes("Alexandra"), "the name column is still a name");
assert.ok(csv.includes("Alexandra: $1,250,000"), "the payout column still reads like a sentence");
});
test("a name with a comma is still quoted properly", () => {
const csv = HandHistoryExport.toCsv([], [
{ id: "x", name: "Smith, John", in: 0, won: 0, net: 0, boughtIn: 0, chipsNow: 0, cashPosition: 0 },
]);
assert.ok(csv.includes('"Smith, John"'), "the CSV escaping still applies where it's needed");
});
});
+124
View File
@@ -0,0 +1,124 @@
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { PotCalculator } = require("./load");
const p = (id, contribution, folded = false) => ({ id, contribution, folded });
describe("PotCalculator.layers", () => {
test("one pot when everyone put in the same", () => {
const layers = PotCalculator.layers([p("a", 50), p("b", 50), p("c", 50)]);
assert.equal(layers.length, 1);
assert.equal(layers[0].amount, 150);
assert.equal(layers[0].label, "Main pot");
assert.deepEqual(layers[0].eligible.sort(), ["a", "b", "c"]);
});
test("a short all-in opens a side pot only the deeper players can win", () => {
// a is all-in for 20, b and c keep betting to 60.
const layers = PotCalculator.layers([p("a", 20), p("b", 60), p("c", 60)]);
assert.equal(layers.length, 2);
assert.equal(layers[0].amount, 60); // 20 x 3
assert.deepEqual(layers[0].eligible.sort(), ["a", "b", "c"]);
assert.equal(layers[1].amount, 80); // 40 x 2
assert.deepEqual(layers[1].eligible.sort(), ["b", "c"]);
assert.equal(layers[1].label, "Side pot 1");
});
test("folded money stays in the pot as dead money but wins nothing", () => {
const layers = PotCalculator.layers([p("a", 50), p("b", 50), p("folder", 50, true)]);
assert.equal(layers.length, 1);
assert.equal(layers[0].amount, 150, "the folder's chips are still in the middle");
assert.ok(!layers[0].eligible.includes("folder"));
});
test("layers with the same eligible players are announced as one pot", () => {
// Two folders at different heights would each open a band, but a dealer
// announces one pot between the two players who can actually win it.
const layers = PotCalculator.layers([
p("a", 100),
p("b", 100),
p("f1", 20, true),
p("f2", 40, true),
]);
const eligibleSets = layers.map(l => l.eligible.slice().sort().join(","));
assert.deepEqual(eligibleSets, ["a,b"], "one announceable pot, not three");
assert.equal(layers[0].amount, 260);
});
test("layer amounts always sum to the contested money", () => {
const players = [p("a", 12.5), p("b", 33.25), p("c", 33.25), p("d", 5, true)];
const total = players.reduce((s, x) => s + x.contribution, 0);
const uncalled = PotCalculator.uncalledReturns(players).reduce((s, r) => s + r.amount, 0);
const layered = PotCalculator.layers(players).reduce((s, l) => s + l.amount, 0);
assert.equal(Math.round((layered + uncalled) * 100), Math.round(total * 100));
});
test("nobody contributed means no pots, not an empty main pot", () => {
assert.deepEqual(PotCalculator.layers([p("a", 0), p("b", 0)]), []);
});
});
describe("PotCalculator.uncalledReturns", () => {
test("an overbet nobody called goes back to whoever bet it", () => {
// b shoves 200, a calls only 50 and everyone else folds.
const returns = PotCalculator.uncalledReturns([p("a", 50), p("b", 200)]);
assert.deepEqual(returns, [{ id: "b", amount: 150 }]);
});
test("a called bet leaves nothing to return", () => {
assert.deepEqual(PotCalculator.uncalledReturns([p("a", 50), p("b", 50)]), []);
});
test("the cap is the biggest live contribution, so a folder's overbet comes back", () => {
const returns = PotCalculator.uncalledReturns([p("live", 30), p("bully", 90, true)]);
assert.deepEqual(returns, [{ id: "bully", amount: 60 }]);
});
test("with nobody live it stays quiet rather than refunding the table", () => {
// Every fold flag set is a dealer mistake to correct, not a signal that
// every chip on the felt was uncalled.
assert.deepEqual(PotCalculator.uncalledReturns([p("a", 10, true), p("b", 20, true)]), []);
});
});
describe("PotCalculator.resolveRound", () => {
test("a single winner takes the layer they were matched for", () => {
const entries = PotCalculator.buildEntries([p("a", 50), p("b", 50)]);
const result = PotCalculator.resolveRound(entries, ["a"]);
assert.equal(result.payoutPool, 100);
assert.deepEqual(result.perWinner, [{ id: "a", amount: 100 }]);
assert.equal(result.remainingContenders.length, 0);
});
test("an all-in winner only takes what everyone matched, the rest rolls forward", () => {
const entries = PotCalculator.buildEntries([p("short", 20), p("b", 60), p("c", 60)]);
const result = PotCalculator.resolveRound(entries, ["short"]);
assert.equal(result.capApplied, 20);
assert.equal(result.payoutPool, 60, "20 from each of three players");
// b and c still have 40 each left to play for.
assert.deepEqual(result.remainingContenders.map(e => e.id).sort(), ["b", "c"]);
assert.equal(PotCalculator.totalPot(result.updatedEntries), 80);
});
test("a chopped pot splits evenly", () => {
const entries = PotCalculator.buildEntries([p("a", 30), p("b", 30)]);
const result = PotCalculator.resolveRound(entries, ["a", "b"]);
assert.deepEqual(result.perWinner, [{ id: "a", amount: 30 }, { id: "b", amount: 30 }]);
});
test("odd cents go to the winners in selection order and nothing is lost", () => {
// A $10.01 pot three ways doesn't divide: 3.34 / 3.34 / 3.33.
const entries = PotCalculator.buildEntries([p("a", 3.34), p("b", 3.34), p("c", 3.33)]);
const result = PotCalculator.resolveRound(entries, ["a", "b", "c"]);
const paid = result.perWinner.reduce((s, w) => s + w.amount, 0);
assert.equal(Math.round(paid * 100), Math.round(result.payoutPool * 100), "no chips lost to rounding");
assert.ok(result.perWinner[0].amount >= result.perWinner[2].amount, "odd cent goes to the first selected");
});
test("selecting nobody who can win is an error, not a silent no-op", () => {
const entries = PotCalculator.buildEntries([p("a", 50), p("b", 50)]);
assert.throws(() => PotCalculator.resolveRound(entries, ["ghost"]), /No valid winners/);
});
});
+103
View File
@@ -0,0 +1,103 @@
// Chips only ever leave this tool because a dealer meant them to. Starting the next
// hand clears every seat's contribution, so an unresolved pot is simply destroyed —
// the UI now asks first, and the number it quotes has to be exactly what goes.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, HoldemState, Money, makeTable, chipsOnTable } = require("./load");
// The same measure the confirmation uses.
const unresolvedPot = state => HoldemState.unresolvedContributions(state);
describe("what starting the next hand destroys", () => {
test("the quoted amount is exactly what leaves the table", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3); Betting.call(state, 0); Betting.call(state, 1); Betting.check(state, 2);
Betting.sweepToHandTotals(state);
const before = chipsOnTable(state);
const quoted = unresolvedPot(state);
assert.ok(quoted > 0, "there is a pot to warn about");
HoldemState.startNextHand(state);
assert.equal(
Money.toCents(chipsOnTable(state)),
Money.toCents(before - quoted),
"the dealer must be told the real number, not an approximation"
);
});
test("chips still in front of players on the current street are counted too", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state); // blinds are `committed`, not yet banked
Betting.raiseTo(state, 0, 25); // and so is a raise mid-street
const before = chipsOnTable(state);
const quoted = unresolvedPot(state);
HoldemState.startNextHand(state);
assert.equal(Money.toCents(chipsOnTable(state)), Money.toCents(before - quoted));
assert.ok(quoted >= 25, `a live raise has to be included; quoted ${quoted}`);
});
test("a hand that was paid out properly leaves nothing to warn about", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 0); Betting.call(state, 1); Betting.check(state, 2);
Betting.sweepToHandTotals(state);
const pot = HoldemState.totalPot(state);
const payouts = [{ id: state.seats[0].id, label: "Ann", amount: pot }];
HoldemState.recordHand(state, payouts);
Betting.creditWinnings(state, payouts);
HoldemState.startNextHand(state);
assert.equal(unresolvedPot(state), 0, "nothing left over after a settled hand");
});
test("settling then dealing on conserves every chip", () => {
const state = makeTable({ seatCount: 6, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
const start = chipsOnTable(state);
for (let hand = 0; hand < 5; hand++) {
Betting.beginHand(state);
const live = Betting.liveSeats(state);
live.forEach(s => { if (Betting.toCall(state, s.player) > 0) Betting.call(state, s.index); });
Betting.sweepToHandTotals(state);
const pot = HoldemState.totalPot(state);
const winner = Betting.liveSeats(state)[0];
const payouts = [{ id: winner.player.id, label: "w", amount: pot }];
HoldemState.recordHand(state, payouts);
Betting.creditWinnings(state, payouts);
HoldemState.startNextHand(state);
assert.equal(chipsOnTable(state), start, `chips drifted on hand ${hand + 1}`);
}
});
test("an empty table has no phantom pot to warn about", () => {
const state = makeTable({ seatCount: 6, seated: [] });
assert.equal(unresolvedPot(state), 0);
});
test("a standing ante is never warned about, because it isn't lost", () => {
// The table default is a stand-in for "everyone puts the same in every hand",
// used by a dealer not tracking stacks at all. It re-applies to the next hand
// rather than going anywhere, so counting it would nag this dealer before
// every single hand — which is why the warning measures the fields
// startNextHand actually clears rather than the pot badge.
const state = makeTable({ seatCount: 9, seated: [0, 1] });
state.basePotAmount = 25;
state.seats.forEach(p => { p.amountOverride = null; });
// The base pot carries into the next hand, so nothing is being thrown away
// and the dealer must not be asked to confirm anything.
assert.equal(HoldemState.totalPot(state), 50, "the badge still shows a pot");
assert.equal(unresolvedPot(state), 0, "but none of it is at risk, so no warning");
HoldemState.startNextHand(state);
assert.equal(HoldemState.totalPot(state), 50, "the standing ante applies to the new hand too");
});
});
+143
View File
@@ -0,0 +1,143 @@
// When does a bet reopen the action? The most misread rule in poker, and the one a
// home game argues about longest: a player shoving in less than a full raise does not
// give everybody behind them another go.
//
// TDA Rule 44 — an all-in wager of less than a full raise does not reopen the betting
// to a player who has already acted and is not facing a full raise.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, makeTable, chipsOnTable } = require("./load");
const actedFlags = state => state.seats
.map((p, i) => ({ seat: i, acted: p.hasActed, live: p.inHand && !p.folded }))
.filter(s => s.live);
describe("a short all-in does not reopen the betting", () => {
// Blinds 1/2. Seat 4 raises to 10 (a full raise of 8). Seat 1 calls.
// Seat 2 is all-in for 13 — three more, where a full raise needs eight.
const shortAllInTable = () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], stack: 100, dealerSeatIndex: 0 });
state.seats[1].stack = 13;
Betting.beginHand(state);
Betting.raiseTo(state, 3, 10);
Betting.call(state, 0);
return state;
};
test("players who already acted are not asked to act again", () => {
const state = shortAllInTable();
assert.equal(state.seats[0].hasActed, true, "seat 1 has called");
assert.equal(state.seats[3].hasActed, true, "seat 4 has raised");
Betting.allIn(state, 1);
assert.equal(state.seats[0].hasActed, true, "seat 1 must not be reopened");
assert.equal(state.seats[3].hasActed, true, "seat 4 must not be reopened");
});
test("but they do still owe the difference", () => {
const state = shortAllInTable();
Betting.allIn(state, 1);
assert.equal(Betting.toCall(state, state.seats[0]), 3, "seat 1 owes the extra 3");
assert.equal(Betting.isStreetComplete(state), false, "so the street isn't over");
});
test("a player who had not acted yet keeps full rights", () => {
const state = shortAllInTable();
assert.equal(state.seats[2].hasActed, false, "seat 3 hasn't acted");
Betting.allIn(state, 1);
assert.equal(state.seats[2].hasActed, false, "and still hasn't — they may still raise");
});
test("the minimum raise is not shrunk by the short all-in", () => {
const state = shortAllInTable();
assert.equal(state.lastRaiseSize, 8);
Betting.allIn(state, 1);
assert.equal(state.lastRaiseSize, 8, "still the last *full* raise");
assert.equal(Betting.minRaiseTo(state), 21, "13 to call plus a full raise of 8");
});
test("calling the short all-in ends the street", () => {
const state = shortAllInTable();
Betting.allIn(state, 1);
Betting.call(state, 2); // seat 3, who had full rights, just calls
Betting.call(state, 3);
Betting.call(state, 0);
assert.equal(Betting.isStreetComplete(state), true);
});
test("no chips are created or lost by any of it", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], stack: 100, dealerSeatIndex: 0 });
state.seats[1].stack = 13;
const start = chipsOnTable(state);
Betting.beginHand(state);
Betting.raiseTo(state, 3, 10);
Betting.call(state, 0);
Betting.allIn(state, 1);
Betting.call(state, 2);
Betting.call(state, 3);
Betting.call(state, 0);
assert.equal(chipsOnTable(state), start);
});
});
describe("a full raise still reopens the betting", () => {
test("an all-in that is a full raise or more reopens everyone", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], stack: 100, dealerSeatIndex: 0 });
state.seats[1].stack = 40;
Betting.beginHand(state);
Betting.raiseTo(state, 3, 10);
Betting.call(state, 0);
Betting.allIn(state, 1); // to 40: an increase of 30, well over the 8 needed
assert.equal(state.seats[0].hasActed, false, "seat 1 gets another go");
assert.equal(state.seats[3].hasActed, false, "and so does seat 4");
assert.equal(state.lastRaiseSize, 30);
assert.equal(Betting.minRaiseTo(state), 70);
});
test("an ordinary raise reopens everyone", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3);
Betting.call(state, 0);
assert.equal(state.seats[3].hasActed, true);
Betting.raiseTo(state, 1, 10);
assert.equal(state.seats[3].hasActed, false);
assert.equal(state.seats[0].hasActed, false);
});
test("a raise exactly the size of the last one counts as full", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], stack: 100, dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.raiseTo(state, 3, 10); // raise of 8
Betting.call(state, 0);
Betting.raiseTo(state, 1, 18); // exactly 8 more — a legal minimum raise
assert.equal(state.seats[0].hasActed, false, "a minimum raise still reopens");
assert.equal(state.lastRaiseSize, 8);
});
test("the first raise of a street is measured against the big blind", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2, 3], stack: 100, dealerSeatIndex: 0 });
Betting.beginHand(state);
Betting.call(state, 3);
Betting.call(state, 0);
Betting.call(state, 1);
Betting.check(state, 2);
Betting.closeStreet(state); // to the flop, no bet yet
const first = Betting.nextToAct(state, state.dealerSeatIndex);
Betting.raiseTo(state, first, 2); // a bet of exactly one big blind
const others = state.seats.filter((p, i) => p.inHand && !p.folded && i !== first);
assert.ok(others.every(p => p.hasActed === false), "a full-sized opening bet reopens everyone");
});
});
+144
View File
@@ -0,0 +1,144 @@
// Values a dealer can actually produce with a typo, and the ones a corrupted save
// can produce on its own. None of these should be able to move chips.
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { Betting, HoldemState, makeTable, chipsOnTable } = require("./load");
describe("a stack can never go negative", () => {
test("a mistyped negative stack reads as empty, not as owing chips", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2] });
state.seats[0].stack = -50;
assert.equal(Betting.stackOf(state, state.seats[0]), 0);
});
test("a negative stack can't be bet with", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2] });
state.seats[0].stack = -50;
const before = state.seats.reduce((s, p) => s + Math.max(0, Number(p.stack) || 0), 0);
const moved = Betting.putIn(state, 0, 25);
assert.equal(moved, 0, "nothing moves out of an empty stack");
assert.ok(Betting.stackOf(state, state.seats[0]) >= 0);
assert.equal(state.seats[0].committed, 0, "and nothing appears in front of them");
assert.ok(state.seats.reduce((s, p) => s + Math.max(0, Number(p.stack) || 0), 0) <= before);
});
test("a negative table default doesn't hand everyone a negative stack", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2] });
state.seats.forEach(p => { p.stack = null; });
state.defaultStack = -100;
state.seats.forEach(p => assert.equal(Betting.stackOf(state, p), 0));
});
test("a negative stack doesn't make a player look like they can still bet", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2] });
state.seats[0].stack = -50;
assert.ok(!Betting.seatsWithChips(state).some(s => s.index === 0));
});
});
describe("blinds that can't be posted", () => {
test("negative blinds post nothing rather than paying players to sit down", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2] });
state.smallBlind = -5;
state.bigBlind = -10;
const before = chipsOnTable(state);
Betting.beginHand(state);
state.seats.forEach(p => assert.equal(p.committed, 0));
assert.equal(chipsOnTable(state), before);
});
test("an unreadable blind doesn't wedge the hand", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2] });
state.bigBlind = NaN;
state.smallBlind = 1;
Betting.beginHand(state);
assert.ok(Number.isFinite(state.currentBet), "the bet to match is still a number");
assert.ok(!Number.isNaN(Betting.potSoFar(state)));
});
test("blinds nobody can cover put those players all-in and move on", () => {
const state = makeTable({ seatCount: 4, seated: [0, 1, 2], stack: 10 });
state.smallBlind = 500;
state.bigBlind = 1000;
const before = chipsOnTable(state);
Betting.beginHand(state);
assert.equal(chipsOnTable(state), before, "no chips invented covering a blind");
state.seats.forEach(p => assert.ok((Number(p.stack) || 0) >= 0));
assert.ok(state.actingSeatIndex === null || state.seats[state.actingSeatIndex].inHand);
});
});
describe("a saved table that comes back damaged", () => {
test("unreadable storage falls back to a fresh table", () => {
// load() has to survive whatever is in localStorage, because the alternative
// is a dealer opening the tool mid-session to a blank screen.
const original = globalThis.localStorage;
globalThis.localStorage = {
getItem: () => "{not json at all",
setItem: () => {},
removeItem: () => {},
};
const state = HoldemState.load();
globalThis.localStorage = original;
assert.equal(state.seats.length, HoldemState.DEFAULT_SEAT_COUNT);
assert.equal(state.handNumber, 1);
});
test("a save missing its seats is treated as no save at all", () => {
const original = globalThis.localStorage;
globalThis.localStorage = {
getItem: () => JSON.stringify({ handNumber: 7, smallBlind: 3 }),
setItem: () => {},
removeItem: () => {},
};
const state = HoldemState.load();
globalThis.localStorage = original;
assert.ok(Array.isArray(state.seats) && state.seats.length > 0);
});
test("a save from before a field existed gets the field, not undefined", () => {
const original = globalThis.localStorage;
globalThis.localStorage = {
getItem: () => JSON.stringify({
seats: [{ id: "a", name: "Ann", inHand: true }, { id: "b", name: "Ben", inHand: true }],
handNumber: 4,
}),
setItem: () => {},
removeItem: () => {},
};
const state = HoldemState.load();
globalThis.localStorage = original;
assert.equal(state.blindOverride, null);
assert.equal(state.street, "preflop");
state.seats.forEach(p => {
assert.equal(p.committed, 0);
assert.equal(p.hasActed, false);
assert.equal(p.buyIns, 0);
});
// And it has to be playable, not just parseable.
assert.doesNotThrow(() => Betting.beginHand(state));
});
test("storage that refuses to be written doesn't take the table down", () => {
const original = globalThis.localStorage;
globalThis.localStorage = {
getItem: () => null,
setItem: () => { throw new Error("QuotaExceededError"); },
removeItem: () => {},
};
const state = HoldemState.createDefault();
assert.doesNotThrow(() => HoldemState.save(state), "a full disk must not break the hand in progress");
globalThis.localStorage = original;
});
});
+134
View File
@@ -0,0 +1,134 @@
// Drives uiAudit.js over the dealer's surfaces at every viewport worth caring about.
//
// node tests/holdem/runUiAudit.js [baseUrl]
//
// Needs Playwright available (`npx playwright install chromium` once). It is
// deliberately NOT wired into the unit-test suite or CI, because that suite is
// dependency-free and runs in a second — this one needs a browser and a running
// site. Run it after any change that adds or resizes a control.
//
// No Playwright to hand? Open the page, paste tests/holdem/uiAudit.js into devtools,
// and call LayoutAudit.runAll(). Same checks, one viewport.
const path = require("path");
const BASE = process.argv[2] || "http://localhost:5299";
const AUDIT = path.join(__dirname, "uiAudit.js");
// Portrait phones, tablets, desktops, then the same phones on their side — landscape
// is where this layout has broken most often, because the table is sized from width
// and the action bar is fixed to a very short viewport.
const VIEWPORTS = [
[360, 640, "Galaxy S8"], [375, 667, "iPhone SE"], [390, 844, "iPhone 14"],
[412, 915, "Pixel 7"], [430, 932, "iPhone Pro Max"],
[768, 1024, "iPad"], [834, 1112, "iPad Air"], [1024, 1366, "iPad Pro"],
[1280, 900, "desktop"], [1600, 1000, "wide desktop"],
[640, 360, "S8 landscape"], [667, 375, "SE landscape"], [844, 390, "iPhone landscape"],
];
const OVERLAYS = [
["rulings", () => document.getElementById("openRulingsBtn").click()],
["seat menu", () => SeatMenu.open(HoldemState.load(), {}, 0)],
["card picker", () => { document.getElementById("cardPickerOverlay").hidden = false; }],
["add chips", () => AddChips.open(HoldemState.load(), 0, () => {})],
["pot wizard", () => document.getElementById("resolvePotBtn").click()],
];
// A table part-way through a real night: long names, uneven stacks, a hand log.
function seedTable() {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 9);
[["Christopher", 1200], ["Mike from work", 800], ["Alexandra", 1500], ["Bob", 250], ["Dee", 600]]
.forEach(([name, cash], i) => {
state.seats[i].name = name;
state.seats[i].inHand = true;
state.seats[i].buyIns = cash;
state.seats[i].stack = cash;
});
state.smallBlind = 5;
state.bigBlind = 10;
for (let hand = 1; hand <= 4; hand++) {
state.handHistory.push({
handNumber: hand, timestamp: Date.now(), pot: 120,
payouts: [{ id: state.seats[hand % 5].id, label: "P", amount: 120 }],
ledger: state.seats.slice(0, 5).map(p => ({ id: p.id, name: p.name, in: 30, won: 0 })),
});
}
state.handNumber = 5;
HoldemState.save(state);
}
async function main() {
let chromium;
try {
({ chromium } = require("playwright"));
} catch {
console.error("This script needs Playwright: npm i -D playwright && npx playwright install chromium");
console.error("Or paste tests/holdem/uiAudit.js into devtools and call LayoutAudit.runAll().");
process.exit(2);
}
const browser = await chromium.launch();
const page = await browser.newPage();
const failures = [];
const warnings = [];
let checks = 0;
for (const [width, height, label] of VIEWPORTS) {
await page.setViewportSize({ width, height });
await page.goto(`${BASE}/Casino/TexasHoldem`);
await page.evaluate(seedTable);
await page.goto(`${BASE}/Casino/TexasHoldem`);
await page.click("#nextHandBtn");
await page.waitForTimeout(300);
await page.evaluate(() => document.querySelectorAll("details.sidebarPanel").forEach(d => { d.open = true; }));
await page.addScriptTag({ path: AUDIT });
const table = await page.evaluate(() => LayoutAudit.runAll());
checks++;
if (!table.clean) failures.push({ where: `table · ${label} ${width}x${height}`, offenders: table.failed.flatMap(f => f.offenders) });
table.warnings.forEach(w => warnings.push(`${label}: ${w}`));
for (const [name, open] of OVERLAYS) {
await page.evaluate(open);
await page.waitForTimeout(180);
checks++;
const result = await page.evaluate(() => {
const overlay = [...document.querySelectorAll("[id$='Overlay']")].find(o => !o.hidden);
if (!overlay) return { offenders: [] };
return LayoutAudit.occlusion(`#${overlay.id} button, #${overlay.id} a, #${overlay.id} input`);
});
await page.evaluate(() => document.querySelectorAll("[id$='Overlay']").forEach(o => { o.hidden = true; }));
if (result.offenders.length) failures.push({ where: `${name} · ${label} ${width}x${height}`, offenders: result.offenders });
}
}
for (const [width, height, label] of VIEWPORTS.filter((_, i) => i % 4 === 0)) {
await page.setViewportSize({ width, height });
await page.goto(`${BASE}/Casino/TexasHoldem/QuickSplit`);
await page.evaluate(() => {
const button = [...document.querySelectorAll("button")].find(b => /all.?in/i.test(b.textContent));
if (button) button.click();
});
await page.addScriptTag({ path: AUDIT });
checks++;
const result = await page.evaluate(() => LayoutAudit.runAll({ occlusionSelector: "main button, main a, main input" }));
if (!result.clean) failures.push({ where: `quick split · ${label} ${width}x${height}`, offenders: result.failed.flatMap(f => f.offenders) });
}
await browser.close();
console.log(`${checks} audits across ${VIEWPORTS.length} viewports`);
warnings.forEach(w => console.log(` note: ${w}`));
if (failures.length === 0) {
console.log("clean");
return;
}
failures.forEach(f => {
console.log(`\nFAIL ${f.where}`);
f.offenders.forEach(o => console.log(` ${o}`));
});
process.exit(1);
}
main();
+65
View File
@@ -0,0 +1,65 @@
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { SplitCalculator, Money } = require("./load");
describe("SplitCalculator.split", () => {
test("an even chop hands everyone the same stack", () => {
const result = SplitCalculator.split(90, 3, 1);
assert.equal(result.each, 30);
assert.equal(result.oddChips, 0);
assert.equal(result.dust, 0);
assert.equal(SplitCalculator.accountedFor(result), 90);
});
test("what won't divide is called out as odd chips, not rolled into a stack", () => {
// $100 three ways in $5 chips: 20 chips, 6 each, 2 left over.
const result = SplitCalculator.split(100, 3, 5);
assert.equal(result.each, 30);
assert.equal(result.oddChips, 2);
assert.equal(SplitCalculator.accountedFor(result), 100);
});
test("a pot that isn't a whole number of chips surfaces the remainder", () => {
// $47 in $5 chips: 9 chips ($45) and $2 that no chip in play can pay.
const result = SplitCalculator.split(47, 2, 5);
assert.equal(result.dust, 2, "the dealer picked a denomination the pot can't make");
assert.equal(SplitCalculator.accountedFor(result), 47);
});
test("every split accounts for the whole pot", () => {
const chips = [0.25, 0.5, 1, 5, 25, 100];
for (let pot = 1; pot <= 400; pot += 7) {
for (let ways = 2; ways <= 6; ways++) {
chips.forEach(chip => {
const result = SplitCalculator.split(pot, ways, chip);
assert.equal(
Money.toCents(SplitCalculator.accountedFor(result)),
Money.toCents(pot),
`${pot} split ${ways} ways in ${chip} chips lost money`
);
});
}
}
});
test("odd chips are always fewer than the number of players", () => {
for (let pot = 1; pot <= 200; pot += 3) {
for (let ways = 2; ways <= 8; ways++) {
const result = SplitCalculator.split(pot, ways, 1);
assert.ok(result.oddChips < ways, "a whole extra chip each would have been dealt out");
}
}
});
test("an empty pot isn't a valid split", () => {
assert.equal(SplitCalculator.split(0, 3, 1).valid, false);
assert.equal(SplitCalculator.split(-5, 3, 1).valid, false);
});
test("nonsense inputs fall back to something a dealer can read", () => {
const result = SplitCalculator.split(50, 0, 0);
assert.equal(result.players, 1, "a split has to be at least one way");
assert.equal(result.chip, 0.01, "and at least one cent a chip");
assert.equal(SplitCalculator.accountedFor(result), 50);
});
});
+147
View File
@@ -0,0 +1,147 @@
const { test, describe } = require("node:test");
const assert = require("node:assert/strict");
const { HoldemState, makeTable } = require("./load");
describe("HoldemState.advanceButton", () => {
test("the button moves to the next player, not the next empty chair", () => {
// Four players spread around a ten-seat table: 0, 3, 4, 8.
const state = makeTable({ seatCount: 10, seated: [0, 3, 4, 8], dealerSeatIndex: 0 });
HoldemState.advanceButton(state);
assert.equal(state.dealerSeatIndex, 3, "skips the three empty chairs between");
HoldemState.advanceButton(state);
assert.equal(state.dealerSeatIndex, 4);
HoldemState.advanceButton(state);
assert.equal(state.dealerSeatIndex, 8);
HoldemState.advanceButton(state);
assert.equal(state.dealerSeatIndex, 0, "wraps back round to the first player");
});
test("every player gets the button once per orbit", () => {
const seated = [1, 2, 6, 7, 9];
const state = makeTable({ seatCount: 12, seated, dealerSeatIndex: 1 });
const visited = [];
for (let i = 0; i < seated.length; i++) {
visited.push(state.dealerSeatIndex);
HoldemState.advanceButton(state);
}
assert.deepEqual(visited.slice().sort((a, b) => a - b), seated);
});
test("it still moves when nobody is dealt in, rather than looking stuck", () => {
const state = makeTable({ seatCount: 6, seated: [], dealerSeatIndex: 2 });
HoldemState.advanceButton(state);
assert.equal(state.dealerSeatIndex, 3);
});
test("counterclockwise play runs the button the other way", () => {
const state = makeTable({ seatCount: 6, seated: [0, 2, 4], dealerSeatIndex: 4 });
state.direction = "counterclockwise";
HoldemState.advanceButton(state);
assert.equal(state.dealerSeatIndex, 2);
});
});
describe("HoldemState.getBlindSeats", () => {
test("blinds follow the players, not the chairs left of the button", () => {
// Seats 1 and 2 are empty, so the blinds belong on 3 and 7.
const state = makeTable({ seatCount: 9, seated: [0, 3, 7], dealerSeatIndex: 0 });
const { sbIndex, bbIndex, headsUp } = HoldemState.getBlindSeats(state);
assert.equal(headsUp, false);
assert.equal(sbIndex, 3);
assert.equal(bbIndex, 7);
});
test("heads-up, the button posts the small blind", () => {
const state = makeTable({ seatCount: 6, seated: [2, 5], dealerSeatIndex: 2 });
const { sbIndex, bbIndex, headsUp } = HoldemState.getBlindSeats(state);
assert.equal(headsUp, true);
assert.equal(sbIndex, 2, "the button is the small blind heads-up");
assert.equal(bbIndex, 5);
});
test("heads-up with the button on an empty chair still posts both blinds", () => {
const state = makeTable({ seatCount: 6, seated: [1, 4], dealerSeatIndex: 0 });
const { sbIndex, bbIndex, headsUp } = HoldemState.getBlindSeats(state);
assert.equal(headsUp, true);
assert.equal(sbIndex, 1);
assert.equal(bbIndex, 4);
assert.notEqual(sbIndex, bbIndex, "two blinds never land on one player");
});
test("fewer than two players means no blinds to post", () => {
const state = makeTable({ seatCount: 6, seated: [3], dealerSeatIndex: 0 });
const { sbIndex, bbIndex } = HoldemState.getBlindSeats(state);
assert.equal(sbIndex, null);
assert.equal(bbIndex, null);
});
});
describe("HoldemState.sessionStandings", () => {
test("a player's cash position counts chips in front plus chips in the pot", () => {
const state = makeTable({ seatCount: 3, seated: [0, 1, 2], stack: 0 });
const [a] = state.seats;
a.buyIns = 100;
a.stack = 60;
a.amountOverride = 25; // banked into the hand in progress
a.committed = 15; // still in front of them on this street
HoldemState.recordHand(state, [{ id: a.id, label: "P1", amount: 0 }]);
const standings = HoldemState.sessionStandings(state);
const row = standings.find(s => s.id === a.id);
// 60 in front + 40 in the pot - 100 bought in = level.
assert.equal(row.cashPosition, 0, "money in the pot is still theirs until it's won");
assert.equal(row.boughtIn, 100);
assert.equal(row.chipsNow, 60);
});
test("hand results accumulate across the session", () => {
const state = makeTable({ seatCount: 2, seated: [0, 1], stack: 0 });
const [a, b] = state.seats;
a.amountOverride = 10;
b.amountOverride = 10;
HoldemState.recordHand(state, [{ id: a.id, label: "P1", amount: 20 }]);
a.amountOverride = 5;
b.amountOverride = 5;
HoldemState.recordHand(state, [{ id: b.id, label: "P2", amount: 10 }]);
const standings = HoldemState.sessionStandings(state);
assert.equal(standings.find(s => s.id === a.id).net, 5);
assert.equal(standings.find(s => s.id === b.id).net, -5);
assert.equal(state.handNumber, 3, "the counter moved on twice");
});
test("the history is capped so a long session can still be saved", () => {
const state = makeTable({ seatCount: 2, seated: [0, 1], stack: 0 });
for (let i = 0; i < HoldemState.MAX_HISTORY_ENTRIES + 25; i++) {
HoldemState.recordHand(state, [{ id: state.seats[0].id, label: "P1", amount: 1 }]);
}
assert.equal(state.handHistory.length, HoldemState.MAX_HISTORY_ENTRIES);
assert.equal(state.handHistory[0].handNumber, HoldemState.MAX_HISTORY_ENTRIES + 25, "newest first");
});
});
describe("HoldemState.resizeSeats", () => {
test("the table is clamped to a size a dealer could actually run", () => {
const state = makeTable({ seatCount: 6 });
HoldemState.resizeSeats(state, 100);
assert.equal(state.seatCount, 24);
HoldemState.resizeSeats(state, 1);
assert.equal(state.seatCount, 2);
});
test("an unreadable seat count falls back to a standard table", () => {
// Empty or non-numeric input (and zero, which is equally meaningless)
// lands on the default rather than a two-seat table.
const state = makeTable({ seatCount: 6 });
HoldemState.resizeSeats(state, NaN);
assert.equal(state.seatCount, HoldemState.DEFAULT_SEAT_COUNT);
});
test("shrinking past the button brings it back onto the table", () => {
const state = makeTable({ seatCount: 9, dealerSeatIndex: 8 });
HoldemState.resizeSeats(state, 4);
assert.ok(state.dealerSeatIndex < 4);
});
});
+499
View File
@@ -0,0 +1,499 @@
// Layout and touch audits for the dealer, written once so they stop being written
// again every round.
//
// These checks have been re-typed into a browser console at least six times over
// the course of building this thing, and each time they only covered whatever had
// just been changed. That is exactly how the standings table shipped with a
// zero-pixel player-name column and survived two rounds: the audit that would have
// caught it existed only in a previous session's scrollback.
//
// This file is deliberately dependency-free and browser-side. It is injected into
// the page (see runUiAudit.js) rather than imported, so it needs no build step, no
// package.json, and no browser automation of its own — anyone can also paste it
// into devtools and call LayoutAudit.runAll().
const LayoutAudit = {
// Everything a dealer has to be able to hit.
CONTROL_SELECTOR: "button, a, input, select, textarea, [role='button'], .seat",
describe(el) {
if (!el) return "(nothing)";
const id = el.id ? `#${el.id}` : "";
const cls = (el.className || "").toString().trim().split(/\s+/).filter(Boolean).slice(0, 2).join(".");
const text = (el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 24);
return `${el.tagName.toLowerCase()}${id}${cls ? "." + cls : ""}${text ? ` "${text}"` : ""}`;
},
visibleControls() {
return [...document.querySelectorAll(this.CONTROL_SELECTOR)].filter(el => {
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return false;
const style = getComputedStyle(el);
return style.visibility !== "hidden" && style.display !== "none";
});
},
// ---- Touch (see the mobile round) ----
// Without touch-action: manipulation a mobile browser holds every tap for ~300ms
// deciding whether it was a double-tap-to-zoom. This tool uses double-tap on a
// seat as its fold shortcut, so that wait is on the critical path.
touchAction() {
const offenders = this.visibleControls()
.filter(el => getComputedStyle(el).touchAction === "auto")
.map(el => this.describe(el));
return { name: "touch-action", offenders, checked: this.visibleControls().length };
},
tapHighlight() {
const offenders = this.visibleControls()
.filter(el => {
const colour = getComputedStyle(el).webkitTapHighlightColor;
return colour && !/rgba\(0,\s*0,\s*0,\s*0\)|transparent/.test(colour);
})
.map(el => this.describe(el));
return { name: "tap-highlight", offenders, checked: this.visibleControls().length };
},
// Text selection must stay ON for anything a dealer types into.
textSelectable() {
const offenders = [...document.querySelectorAll("input[type='text'], input[type='number'], textarea")]
.filter(el => el.offsetParent !== null)
.filter(el => {
const style = getComputedStyle(el);
return (style.webkitUserSelect || style.userSelect) === "none";
})
.map(el => this.describe(el));
return { name: "fields stay selectable", offenders };
},
// ---- Reachability (see the occlusion round) ----
// A control covered by something else is unreachable however good it looks.
// Sampling several points matters: a button you can only hit in one corner is
// covered for practical purposes.
// Can this element be brought into view by scrolling? Something below the fold on
// a page that scrolls is perfectly reachable; something below the fold in a panel
// that *doesn't* scroll is lost. The first version of this check didn't make the
// distinction and reported every link under the fold as a fault.
reachableByScrolling(el) {
const rect = el.getBoundingClientRect();
if (getComputedStyle(el).position === "fixed") return false;
for (let node = el.parentElement; node; node = node.parentElement) {
const style = getComputedStyle(node);
const scrolls = /auto|scroll|overlay/.test(style.overflowY) || node === document.body;
if (!scrolls) continue;
const box = node === document.body ? { top: 0, bottom: innerHeight } : node.getBoundingClientRect();
const room = node === document.body
? document.documentElement.scrollHeight - innerHeight - scrollY
: node.scrollHeight - node.clientHeight - node.scrollTop;
if (rect.top >= box.bottom && room > 0) return true;
if (rect.bottom <= box.top && (node === document.body ? scrollY > 0 : node.scrollTop > 0)) return true;
}
return false;
},
occlusion(selector = "#actionBar button, #holdemHeader button, .seat") {
const offenders = [];
const warnings = [];
[...document.querySelectorAll(selector)].forEach(el => {
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return;
const outsideViewport = rect.bottom <= 0 || rect.top >= innerHeight ||
rect.right <= 0 || rect.left >= innerWidth;
if (outsideViewport) {
if (!this.reachableByScrolling(el)) {
offenders.push(`${this.describe(el)} :: off-screen and cannot be scrolled to`);
}
return;
}
const points = [
[rect.left + rect.width / 2, rect.top + rect.height / 2],
[rect.left + rect.width * 0.25, rect.top + rect.height * 0.3],
[rect.left + rect.width * 0.75, rect.top + rect.height * 0.3],
[rect.left + rect.width * 0.25, rect.top + rect.height * 0.7],
[rect.left + rect.width * 0.75, rect.top + rect.height * 0.7],
].filter(([x, y]) => x >= 0 && y >= 0 && x < innerWidth && y < innerHeight);
if (points.length === 0) return;
let blocked = 0;
let testable = 0;
let blockedBy = null;
points.forEach(([x, y]) => {
const top = document.elementFromPoint(x, y);
// A null result means the point isn't hit-testable — typically it sits
// inside the element but outside a scrollable ancestor's clip, i.e. the
// control is scrolled out of view rather than covered by anything.
// Counting that as "covered by null" was reporting a perfectly
// reachable button in a sheet that scrolls.
if (!top) return;
testable++;
if (el.contains(top) || top === el || top.contains(el)) return;
// Seats ring a round table and overlap each other at the rim by
// design; that is crowding, not an overlay hiding a control.
if (top.closest && top.closest(".seat")) return;
blocked++;
if (!blockedBy) blockedBy = this.describe(top);
});
if (testable === 0) {
if (!this.reachableByScrolling(el)) {
offenders.push(`${this.describe(el)} :: not hit-testable anywhere and cannot be scrolled to`);
}
return;
}
if (blocked === 0) return;
const note = `${this.describe(el)} :: ${blocked === testable ? "fully" : `${blocked}/${testable}`} covered by ${blockedBy}`;
// A toast is transient by design: it dismisses itself and carries a close
// button, and on a desktop it necessarily lands over a table that fills the
// content column. Partial overlap from one is a fact of the layout, not a
// fault. Being *fully* covered by a toast is still a failure though — that
// was a real bug once, where a seat sat exactly under the Undo button and a
// tap meant for a player took back the last action instead.
const transient = blockedBy && /toast/i.test(blockedBy);
if (transient && blocked < testable) warnings.push(note);
else offenders.push(note);
});
return { name: "nothing important is covered", offenders, warnings };
},
// ---- Layout (the check that would have caught the standings regression) ----
// A grid column squeezed to nothing doesn't truncate its text, it erases it.
// This is the one that was missing: the player-name column sat at 0px through
// two rounds because nothing ever asked whether a column had survived.
collapsedColumns() {
const offenders = [];
[...document.querySelectorAll("[class*='Row'], [class*='row']")].forEach(row => {
if (getComputedStyle(row).display !== "grid") return;
[...row.children].forEach(cell => {
if (getComputedStyle(cell).display === "none") return;
const hasText = (cell.textContent || "").trim().length > 0;
if (hasText && cell.getBoundingClientRect().width < 4) {
offenders.push(`${this.describe(row)} > ${this.describe(cell)} :: ${Math.round(cell.getBoundingClientRect().width)}px wide`);
}
});
});
return { name: "no column collapsed to nothing", offenders };
},
// Text actually painted outside the box meant to contain it — which on a table of
// overlapping seats means painted on top of a neighbour.
//
// The clipping check is the whole subtlety, and the first version of this got it
// wrong. A Range's bounding rect measures the *laid out* text, which happily runs
// past the element when `overflow: hidden` is quietly clipping it — so an
// ellipsised name was reported as spilling when nothing was drawn outside at all.
// Only overflow that is actually visible can paint over a neighbour.
textSpill(selector = ".seatPuckStack, .seatPuckTotal, .seatPuckName") {
const offenders = [];
[...document.querySelectorAll(selector)].forEach(el => {
const text = (el.textContent || "").trim();
if (!text) return;
const style = getComputedStyle(el);
const clipsItself = style.overflow !== "visible" || style.overflowX !== "visible";
if (clipsItself) return;
const container = el.closest(".seat") || el.parentElement;
if (!container) return;
const range = document.createRange();
range.selectNodeContents(el);
const drawn = range.getBoundingClientRect();
const bounds = container.getBoundingClientRect();
if (drawn.left < bounds.left - 1 || drawn.right > bounds.right + 1) {
offenders.push(`${this.describe(el)} "${text}" paints outside ${this.describe(container)}`);
}
});
return { name: "no text painted outside its box", offenders };
},
horizontalOverflow() {
const offenders = document.documentElement.scrollWidth > innerWidth + 1
? [`page scrolls sideways: ${document.documentElement.scrollWidth}px in a ${innerWidth}px viewport`]
: [];
return { name: "page never scrolls sideways", offenders };
},
// iOS zooms the whole page when a field under 16px takes focus, and the dealer
// is then pinching back out mid-hand.
fieldFontSize() {
const offenders = [...document.querySelectorAll("input, textarea, select")]
.filter(el => el.offsetParent !== null)
.filter(el => ["text", "number", "search", "tel", "url", "email", "password", ""].includes(el.type || ""))
.filter(el => parseFloat(getComputedStyle(el).fontSize) < 16)
.map(el => `${this.describe(el)} at ${getComputedStyle(el).fontSize}`);
return { name: "no field small enough to trigger iOS zoom", offenders };
},
// ---- Contrast ----
//
// This check has been got wrong twice before, both times by being too clever about
// backgrounds. The first version read only `background-color`, so every sheet
// painted with a gradient was measured against transparency and the dealer puck's
// dark "D" was reported at 1.2:1 against nothing. The second over-corrected and
// treated low-alpha gradient stops as opaque, scoring white-on-dark at 1.0:1.
//
// So it is built to be incapable of false positives instead of trying to be exact.
// Backgrounds composite properly through alpha, and where a gradient is involved
// every one of its colour stops is tried and the *most flattering* one is used. A
// finding therefore means the text fails even under the reading most generous to
// it, which is a claim worth making. Text that can't be resolved to any opaque
// background is reported separately as unmeasured rather than guessed at.
parseColour(value) {
const match = String(value).match(/rgba?\(([^)]+)\)/);
if (!match) return null;
const parts = match[1].split(/[,\s/]+/).filter(Boolean).map(Number);
if (parts.length < 3 || parts.some(Number.isNaN)) return null;
return { r: parts[0], g: parts[1], b: parts[2], a: parts.length > 3 ? parts[3] : 1 };
},
// Colour stops out of any gradient in a background-image.
gradientStops(backgroundImage) {
if (!backgroundImage || backgroundImage === "none") return [];
return (backgroundImage.match(/rgba?\([^)]+\)/g) || [])
.map(c => this.parseColour(c))
.filter(Boolean);
},
over(top, bottom) {
const a = top.a;
return {
r: top.r * a + bottom.r * (1 - a),
g: top.g * a + bottom.g * (1 - a),
b: top.b * a + bottom.b * (1 - a),
a: 1,
};
},
relativeLuminance({ r, g, b }) {
const channel = v => {
const s = v / 255;
return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
};
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
},
contrastRatio(fg, bg) {
const a = this.relativeLuminance(fg);
const b = this.relativeLuminance(bg);
return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
},
// Every background this text could actually be sitting on.
//
// Layers are collected from the element outwards and stop at the first fully
// opaque one, because nothing behind that is visible. Getting this wrong in the
// lenient direction is just as bad as the old false positives: an earlier version
// kept walking past an opaque gradient and offered the page background as a
// candidate, which scored white-on-a-mid-grey-panel as though it were
// white-on-near-black and would have waved real problems through.
//
// A gradient contributes one candidate per colour stop; translucent layers above
// the opaque one are composited onto each candidate in order.
backgroundCandidates(el) {
const translucent = []; // top-down, above the opaque layer
let base = null; // candidate colours for the first opaque layer
for (let node = el; node && !base; node = node.parentElement) {
const style = getComputedStyle(node);
const stops = this.gradientStops(style.backgroundImage);
const colour = this.parseColour(style.backgroundColor);
// A gradient whose stops are all opaque hides everything behind it.
if (stops.length > 0 && stops.every(s => s.a === 1)) {
base = stops;
break;
}
stops.forEach(s => { if (s.a > 0) translucent.push(s); });
if (colour && colour.a === 1) { base = [colour]; break; }
if (colour && colour.a > 0) translucent.push(colour);
}
if (!base) {
// Nothing opaque anywhere up the tree — fall back to the page's own colour
// so a finding is still measured against something real.
const page = this.parseColour(getComputedStyle(document.documentElement).backgroundColor);
base = [page && page.a === 1 ? page : { r: 10, g: 10, b: 10, a: 1 }];
}
// Fold the translucent layers back on, innermost last so it lands on top.
return base.map(candidate => {
let composed = candidate;
for (let i = translucent.length - 1; i >= 0; i--) composed = this.over(translucent[i], composed);
return composed;
});
},
contrast({ minimum = 4.5, largeMinimum = 3, selector = null } = {}) {
const offenders = [];
const unmeasured = [];
const nodes = selector
? [...document.querySelectorAll(selector)]
: [...document.querySelectorAll("*")];
nodes.forEach(el => {
if (el.children.length > 0) return; // leaf text only
const text = (el.textContent || "").trim();
if (!text) return;
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return;
const style = getComputedStyle(el);
if (style.visibility === "hidden" || style.display === "none") return;
if (parseFloat(style.opacity) < 0.99) return; // faded on purpose
// Decoration is exempt by definition: the watermark on the felt is meant
// to be barely there, and holding it to a reading threshold would mean
// making it not a watermark. Marked aria-hidden so screen readers skip it
// too, which is the same claim expressed where it also does some good.
if (el.closest("[aria-hidden='true']")) return;
const fgRaw = this.parseColour(style.color);
if (!fgRaw) return;
const candidates = this.backgroundCandidates(el);
if (candidates.length === 0) {
unmeasured.push(`${this.describe(el)} :: no opaque background found`);
return;
}
// The kindest reading available: best contrast across every candidate.
let best = 0;
candidates.forEach(bg => {
const fg = fgRaw.a === 1 ? fgRaw : this.over(fgRaw, bg);
best = Math.max(best, this.contrastRatio(fg, bg));
});
const sizePx = parseFloat(style.fontSize);
const weight = parseInt(style.fontWeight, 10) || 400;
const isLarge = sizePx >= 24 || (sizePx >= 18.66 && weight >= 700);
const required = isLarge ? largeMinimum : minimum;
if (best + 0.05 < required) {
offenders.push(`${this.describe(el)} :: ${best.toFixed(2)}:1 (needs ${required}:1) at ${Math.round(sizePx)}px`);
}
});
return { name: "text meets WCAG AA contrast", offenders, unmeasured };
},
// ---- Reach (touch target sizes) ----
// What a fingertip can actually hit, which is not the same as the element's box.
//
// Two things make the box misleading, and the first version of this check was
// fooled by both. A control can be padded out with a transparent ::after, so it
// responds well beyond its painted size — that's how a 22px dealer puck should
// stay 22px and still take a thumb. And a checkbox wrapped in a label is hit by
// tapping anywhere on the label, so a 24px box inside a 320x44 label is a
// perfectly good target. Measuring the box reported both as faults.
//
// So it probes outwards with elementFromPoint until the point stops landing on the
// control, which is the thing a finger actually experiences.
effectiveTarget(el, limit = 48) {
const rect = el.getBoundingClientRect();
const cx = rect.left + rect.width / 2;
const cy = rect.top + rect.height / 2;
// The probe walks outward a fixed distance, so it can only ever report
// 2 x limit. Anything already drawn larger than that reads as exactly the cap
// — which had every header button reporting a suspiciously round 80px. Give
// the reach room for the element itself plus the padding being looked for.
limit = Math.max(limit, rect.width / 2 + 24, rect.height / 2 + 24);
// A wrapping or associated label forwards the tap, so it counts as the target.
const label = el.closest("label") || (el.labels && el.labels[0]);
const lands = (x, y) => {
if (x < 0 || y < 0 || x >= innerWidth || y >= innerHeight) return false;
const hit = document.elementFromPoint(x, y);
if (!hit) return false;
if (hit === el || el.contains(hit)) return true;
return !!(label && (hit === label || label.contains(hit)));
};
if (!lands(cx, cy)) return null; // centre isn't even hittable; occlusion's problem
const reach = (dx, dy) => {
let far = 0;
for (let d = 1; d <= limit; d++) {
if (!lands(cx + dx * d, cy + dy * d)) break;
far = d;
}
return far;
};
return { width: reach(-1, 0) + reach(1, 0), height: reach(0, -1) + reach(0, 1) };
},
// The 44px guideline is about fingertips, so it only bites where there's no mouse.
// Enforcing it everywhere flagged the header buttons at 42px tall on a desktop,
// which is not a defect — the same buttons are 64px tall on a phone, where it
// matters. Same reasoning as the field sizing: `hover: none` is what actually
// distinguishes a finger from a pointer, not viewport width.
//
// `exempt` is for controls that are deliberately small *and* have a full-size path
// to the same action. The dealer puck is the only one: it's a 22px chip sitting on
// the rim of a seat, and growing it to 44px would take that area from the seat
// itself — which a dealer taps far more often. "Give the button" is in the seat
// menu at full size, so the puck is a shortcut, not the only way through.
touchTargets(minimum = 44, { exempt = ".dealerChip", enforceOnPointerDevices = false } = {}) {
const offenders = [];
if (!enforceOnPointerDevices && matchMedia("(hover: hover)").matches) {
return { name: `touch targets at least ${minimum}px`, offenders, skipped: "pointer device" };
}
this.visibleControls()
.filter(el => el.type !== "color")
.filter(el => !(exempt && el.matches(exempt)))
.forEach(el => {
const rect = el.getBoundingClientRect();
// Drawn big enough is big enough — no need to probe, and probing wide
// elements is where the cap above used to produce nonsense. Seats sit
// here: they're 76x72 and overlap each other at the rim by design, so
// measuring their reach would report the crowding as a fault.
if (rect.width >= minimum - 1 && rect.height >= minimum - 1) return;
const size = this.effectiveTarget(el);
if (!size) return;
if (size.width >= minimum - 1 && size.height >= minimum - 1) return;
offenders.push(
`${this.describe(el)} :: hittable ${size.width}x${size.height}` +
` (drawn ${Math.round(rect.width)}x${Math.round(rect.height)})`
);
});
return { name: `touch targets at least ${minimum}px`, offenders };
},
// ---- Runner ----
runAll(options = {}) {
const checks = [
this.touchAction(),
this.tapHighlight(),
this.textSelectable(),
this.occlusion(options.occlusionSelector),
this.collapsedColumns(),
this.textSpill(),
this.horizontalOverflow(),
this.fieldFontSize(),
];
if (options.includeTouchTargets) checks.push(this.touchTargets(options.minimumTarget));
return {
viewport: `${innerWidth}x${innerHeight}`,
failed: checks.filter(c => c.offenders.length > 0),
// Things worth knowing that aren't faults — see occlusion() on toasts.
warnings: checks.flatMap(c => c.warnings || []),
passed: checks.filter(c => c.offenders.length === 0).map(c => c.name),
clean: checks.every(c => c.offenders.length === 0),
};
},
};
if (typeof module !== "undefined" && module.exports) {
module.exports = LayoutAudit;
}