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 ({
46 width: opening.w,
47 height: opening.h,
48 '--ws': `${cell}px`,
49 // A side is its stacks and nothing else, so there is no sum for
50 // the corners to come out of by a pixel.
51 '--wall-len': `${RING.h * cell}px`,
52 } as React.CSSProperties)
53 : undefined
54 }
55 >
56 {/* One cell, never drawn: the ring is measured in stacks, so something has
57 to be the size of a stack before any of them have been placed. */}
58 <i className="wall-probe" />
59 {WALL_SIDES.map((cls, side) => (
60 <div className={`wall-side ${cls}`} key={cls}>
61 {sides[side].map(({ index, stack }) => (
62 <div
63 key={index}
64 data-stack={index}
65 // The 16-tile 底牌 tail is not marked out. It is still the tail —
66 // `Stack.dead` says so and the engine ends the hand on it — but a
67 // wall on a table is one wall, not a wall with the end greyed off.
68 className={`wall-stack s${stack.count}${stack.next ? ' next' : ''}`}
69 >
70 <i />
71 </div>
72 ))}
73 </div>
74 ))}
75 </div>
76 );
77}
78
79interface Square {
80 cap: RingCapacity;
81 /** The opening the square leaves, once there is a middle to measure. */
82 opening: { w: number; h: number } | null;
83 /** How big a stack came out — the wall's own tile size, in px. */
84 cell: number;
85}
86
87/**
88 * How big to build the square, measured rather than worked out twice: how big a
89 * tile is is CSS's business, so one cell is rendered and asked how it came out,
90 * and the middle is whatever the four strips have left. Nothing here depends on
91 * the state of the hand — the square is built once for the window it is in and
92 * then eaten, so it does not close in on the discards lying inside it.
93 */
94function useSquare(ring: React.RefObject<HTMLDivElement | null>): Square {
95 const [square, setSquare] = useState<Square>({ cap: RING, opening: null, cell: 0 });
96
97 useLayoutEffect(() => {
98 const el = ring.current;
99 const middle = el?.parentElement;
100 const probe = el?.querySelector<HTMLElement>('.wall-probe');
101 if (!el || !middle || !probe) return;
102
103 const read = () => {
104 const box = probe.getBoundingClientRect();
105 if (box.width <= 0) return;
106 // What shape a stack is, is CSS's business — read it, don't restate it.
107 const ratio = box.height / box.width;
108 // Stood on its corner, a square needs its *diagonal* where it used to
109 // need its side — so the room it has to be built in shrinks by however
110 // much the turn costs. Square on that is 1 and nothing changes; at 45° it
111 // is √2 and the square comes out about seven tenths the size, which is
112 // what keeps its arms on the table rather than off the edge of it.
113 const style = getComputedStyle(el);
114 const turn = (parseFloat(style.getPropertyValue('--wall-turn')) || 0) * (Math.PI / 180);
115 const spread = Math.abs(Math.cos(turn)) + Math.abs(Math.sin(turn));
116 const room = parseFloat(style.getPropertyValue('--wall-room')) || 1;
117 // Eighteen stacks and one depth of overlap is `(18 + ratio) * s` across,
118 // and turned that covers `spread` times as much — so the room it has to
119 // be solved in is the middle divided by the turn.
120 const s = ringCell(
121 {
122 w: (middle.clientWidth * room) / spread,
123 h: (middle.clientHeight * room) / spread,
124 },
125 ratio,
126 );
127 // The square is always eighteen a side; what fits it is the tile.
128 const cell = { s, d: s * ratio };
129 const opening = ringOpening(RING, cell);
130 setSquare((was) =>
131 was.cell === s && was.opening?.w === opening.w && was.opening?.h === opening.h
132 ? was
133 : { cap: RING, opening, cell: s },
134 );
135 };
136
137 read();
138 // The middle, not the square: the square's own size is this effect's doing,
139 // and watching it would be watching itself.
140 const observer = new ResizeObserver(read);
141 observer.observe(middle);
142 observer.observe(probe);
143 return () => observer.disconnect();
144 }, [ring]);
145
146 return square;
147}