anvilsign in

collin/mahjong

1import { useLayoutEffect, useRef, useState } from 'react';
2import {
3 ringCell,
4 ringLayout,
5 ringOpening,
6 RING,
7 WALL_SIDES,
8 wallStacks,
9 type RingCapacity,
10 type WallProgress,
11} from '../game/wall';
12
13import { useT } from './lang';
14
15/**
16 * What is left of the wall, built as a square in the middle of the table.
17 *
18 * Four staggered sides like a #, with the corners open — but a square the size
19 * of the wall *as it is dealt*, not of 144 tiles. Eighteen full-size stacks a
20 * side is longer than the middle of any ordinary window is tall, and by the
21 * time anyone is looking there is nothing like that much wall left, so it is
22 * rebuilt smaller and the tiles stay the size of the ones in your hand. What
23 * goes where is `RING` and `ringLayout` in `game/wall.ts`; this measures the
24 * middle for them and puts the answer on screen.
25 *
26 * Every stack carries its index, and that is load-bearing — `table/geometry.ts`
27 * measures these elements to build the colliders rather than restating the CSS
28 * that sizes them.
29 */
30export function WallRing({ state }: { state: WallProgress }) {
31 const t = useT();
32 const ring = useRef<HTMLDivElement>(null);
33 const { cap, opening, cell } = useSquare(ring);
34 const sides = ringLayout(wallStacks(state), cap);
35
36 return (
37 <div
38 className="wall-ring"
39 ref={ring}
40 aria-label={t('牌牆', 'The wall')}
41 style={
42 opening
43 ? // `--ws` is set from here rather than from the tile, because the
44 // square is the fixed thing now and the tile is what gives.
45 ({ width: opening.w, height: opening.h, '--ws': `${cell}px` } as React.CSSProperties)
46 : undefined
47 }
48 >
49 {/* One cell, never drawn: the ring is measured in stacks, so something has
50 to be the size of a stack before any of them have been placed. */}
51 <i className="wall-probe" />
52 {WALL_SIDES.map((cls, side) => (
53 <div className={`wall-side ${cls}`} key={cls}>
54 {sides[side].map(({ index, stack }) => (
55 <div
56 key={index}
57 data-stack={index}
58 // The 16-tile 底牌 tail is not marked out. It is still the tail —
59 // `Stack.dead` says so and the engine ends the hand on it — but a
60 // wall on a table is one wall, not a wall with the end greyed off.
61 className={`wall-stack s${stack.count}${stack.next ? ' next' : ''}`}
62 >
63 <i />
64 </div>
65 ))}
66 </div>
67 ))}
68 </div>
69 );
70}
71
72interface Square {
73 cap: RingCapacity;
74 /** The opening the square leaves, once there is a middle to measure. */
75 opening: { w: number; h: number } | null;
76 /** How big a stack came out — the wall's own tile size, in px. */
77 cell: number;
78}
79
80/**
81 * How big to build the square, measured rather than worked out twice: how big a
82 * tile is is CSS's business, so one cell is rendered and asked how it came out,
83 * and the middle is whatever the four strips have left. Nothing here depends on
84 * the state of the hand — the square is built once for the window it is in and
85 * then eaten, so it does not close in on the discards lying inside it.
86 */
87function useSquare(ring: React.RefObject<HTMLDivElement | null>): Square {
88 const [square, setSquare] = useState<Square>({ cap: RING, opening: null, cell: 0 });
89
90 useLayoutEffect(() => {
91 const el = ring.current;
92 const middle = el?.parentElement;
93 const probe = el?.querySelector<HTMLElement>('.wall-probe');
94 if (!el || !middle || !probe) return;
95
96 const read = () => {
97 const box = probe.getBoundingClientRect();
98 if (box.width <= 0) return;
99 // What shape a stack is, is CSS's business — read it, don't restate it.
100 const ratio = box.height / box.width;
101 // Stood on its corner, a square needs its *diagonal* where it used to
102 // need its side — so the room it has to be built in shrinks by however
103 // much the turn costs. Square on that is 1 and nothing changes; at 45° it
104 // is √2 and the square comes out about seven tenths the size, which is
105 // what keeps its arms on the table rather than off the edge of it.
106 const style = getComputedStyle(el);
107 const turn = (parseFloat(style.getPropertyValue('--wall-turn')) || 0) * (Math.PI / 180);
108 const spread = Math.abs(Math.cos(turn)) + Math.abs(Math.sin(turn));
109 const room = parseFloat(style.getPropertyValue('--wall-room')) || 1;
110 // How far a wall runs past its corner, as a share of a stack's short side.
111 const lapOf = parseFloat(style.getPropertyValue('--wall-lap'));
112 const lap = ratio * (Number.isFinite(lapOf) ? lapOf : 1);
113 // Eighteen stacks and one depth of overlap is `(18 + ratio) * s` across,
114 // and turned that covers `spread` times as much — so the room it has to
115 // be solved in is the middle divided by the turn.
116 const s = ringCell(
117 {
118 w: (middle.clientWidth * room) / spread,
119 h: (middle.clientHeight * room) / spread,
120 },
121 ratio,
122 lap,
123 );
124 // The square is always eighteen a side; what fits it is the tile.
125 const cell = { s, d: s * ratio };
126 const opening = ringOpening(RING, cell, s * lap);
127 setSquare((was) =>
128 was.cell === s && was.opening?.w === opening.w && was.opening?.h === opening.h
129 ? was
130 : { cap: RING, opening, cell: s },
131 );
132 };
133
134 read();
135 // The middle, not the square: the square's own size is this effect's doing,
136 // and watching it would be watching itself.
137 const observer = new ResizeObserver(read);
138 observer.observe(middle);
139 observer.observe(probe);
140 return () => observer.disconnect();
141 }, [ring]);
142
143 return square;
144}