anvilsign in

collin/mahjong

1import { useLayoutEffect, useRef, useState } from 'react';
2import { STACKS_PER_SIDE } from '../game/tiles';
3import {
4 rhombus,
5 ringLayout,
6 RING,
7 WALL_SIDES,
8 wallStacks,
9 type Placed,
10 type Rhombus,
11 type WallProgress,
12} from '../game/wall';
13
14import { useT } from './lang';
15
16/**
17 * What is left of the wall, built as a square in the middle of the table.
18 *
19 * Four staggered sides like a #, with the corners open — but a square the size
20 * of the wall *as it is dealt*, not of 144 tiles. Eighteen full-size stacks a
21 * side is longer than the middle of any ordinary window is tall, and by the
22 * time anyone is looking there is nothing like that much wall left, so it is
23 * rebuilt smaller and the tiles stay the size of the ones in your hand. What
24 * goes where is `RING` and `ringLayout` in `game/wall.ts`; this measures the
25 * middle for them and puts the answer on screen.
26 *
27 * Every stack carries its index, and that is load-bearing — `table/geometry.ts`
28 * measures these elements to build the colliders rather than restating the CSS
29 * that sizes them.
30 */
31export function WallRing({ state }: { state: WallProgress }) {
32 const t = useT();
33 const ring = useRef<HTMLDivElement>(null);
34 const { opening, cell, shape } = useSquare(ring);
35 const sides = ringLayout(wallStacks(state), RING);
36 const { slide, take } = useSliding(ring, shape, cell, sides);
37
38 return (
39 <div
40 className="wall-ring"
41 ref={ring}
42 aria-label={t('牌牆', 'The wall')}
43 style={
44 opening
45 ? // `--ws` is set from here rather than from the tile, because the
46 // square is the fixed thing now and the tile is what gives.
47 ({
48 width: opening.w,
49 height: opening.h,
50 '--ws': `${cell}px`,
51 // A side is its stacks and nothing else, so there is no sum for
52 // the corners to come out of by a pixel.
53 '--wall-len': `${RING.h * cell}px`,
54 } as React.CSSProperties)
55 : undefined
56 }
57 >
58 {/* One cell, never drawn: the ring is measured in stacks, so something has
59 to be the size of a stack before any of them have been placed. */}
60 <i className="wall-probe" />
61 {WALL_SIDES.map((cls, side) => (
62 <div
63 className={`wall-side ${cls}`}
64 key={cls}
65 onPointerDown={take(side)}
66 style={
67 shape
68 ? ({
69 '--vx': `${shape.places[side].x}px`,
70 '--vy': `${shape.places[side].y}px`,
71 '--dir': `${shape.places[side].dir}deg`,
72 '--slide': `${slide[side]}px`,
73 } as React.CSSProperties)
74 : undefined
75 }
76 >
77 {sides[side].map(({ index, stack }) => (
78 <div
79 key={index}
80 data-stack={index}
81 // The 16-tile 底牌 tail is not marked out. It is still the tail —
82 // `Stack.dead` says so and the engine ends the hand on it — but a
83 // wall on a table is one wall, not a wall with the end greyed off.
84 className={`wall-stack s${stack.count}${stack.next ? ' next' : ''}`}
85 // The layout already knows which way this stack is lying, so the
86 // physics is told rather than left to work it out off a box that
87 // has been turned. See table/geometry.ts.
88 data-angle={shape ? shape.places[side].dir : 0}
89 >
90 <i />
91 </div>
92 ))}
93 </div>
94 ))}
95 </div>
96 );
97}
98
99/**
100 * Pushing a wall along its own line.
101 *
102 * What everybody does to a wall as it is eaten: the stacks are drawn from one
103 * end, a gap opens where the drawing is happening, and somebody shoves what is
104 * left along to close it up and keep it in reach. It moves the tiles and
105 * nothing else — the wall is the same wall in the same order and the next draw
106 * is still the next draw, exactly as washing the discards about moves no
107 * tile that anybody is counting.
108 *
109 * A wall slides only into the room it has: from where it was built to where its
110 * own stacks run out. It cannot leave its line, and it cannot climb over the
111 * one beside it.
112 *
113 * The pool is told, because a wall that has moved is a wall a thrown tile
114 * bounces off somewhere else, and the pool only re-measures when it has reason
115 * to — `invalidate` in table/pool.ts, and the listener in ui/Pool.tsx.
116 */
117function useSliding(
118 ring: React.RefObject<HTMLDivElement | null>,
119 shape: Rhombus | null,
120 cell: number,
121 sides: Placed[][],
122) {
123 const [slide, setSlide] = useState<number[]>([0, 0, 0, 0]);
124 const drag = useRef<{ side: number; ax: number; ay: number; from: number; at: number } | null>(
125 null,
126 );
127 // What the drag needs to know, kept current without the listeners below
128 // having to be torn down and put back on every render to see it.
129 const now = useRef({ shape, cell, sides, slide });
130 now.current = { shape, cell, sides, slide };
131
132 // A wall that has lost stacks has exactly that much line to be pushed along.
133 const roomOn = (side: number) =>
134 Math.max(0, (STACKS_PER_SIDE - now.current.sides[side].length) * now.current.cell);
135
136 const moved = () => ring.current?.dispatchEvent(new CustomEvent('wallmoved', { bubbles: true }));
137
138 const take = (side: number) => (e: React.PointerEvent<HTMLDivElement>) => {
139 const place = now.current.shape?.places[side];
140 if (!place || e.button !== 0 || roomOn(side) <= 0) return;
141 // A wall being pushed, not the table being reached into.
142 e.stopPropagation();
143 e.preventDefault();
144 const rad = (place.dir * Math.PI) / 180;
145 const ax = Math.cos(rad);
146 const ay = Math.sin(rad);
147 try {
148 e.currentTarget.setPointerCapture?.(e.pointerId);
149 } catch {
150 // Uncaptured still works while the pointer stays over the wall.
151 }
152 drag.current = {
153 side,
154 ax,
155 ay,
156 from: e.clientX * ax + e.clientY * ay,
157 at: now.current.slide[side],
158 };
159 };
160
161 // Put on once and left alone. Registering these per render was three
162 // listeners torn down and rebuilt on every state change, for nothing.
163 useLayoutEffect(() => {
164 const move = (e: PointerEvent) => {
165 const d = drag.current;
166 if (!d) return;
167 // Only what the finger did *along* the wall counts; across it, nothing.
168 const along = e.clientX * d.ax + e.clientY * d.ay;
169 const to = Math.min(0, Math.max(-roomOn(d.side), d.at + (along - d.from)));
170 let changed = false;
171 setSlide((was) => {
172 if (was[d.side] === to) return was;
173 changed = true;
174 return was.map((v, i) => (i === d.side ? to : v));
175 });
176 if (changed) moved();
177 };
178 const up = () => {
179 if (!drag.current) return;
180 drag.current = null;
181 moved();
182 };
183 window.addEventListener('pointermove', move);
184 window.addEventListener('pointerup', up);
185 window.addEventListener('pointercancel', up);
186 return () => {
187 window.removeEventListener('pointermove', move);
188 window.removeEventListener('pointerup', up);
189 window.removeEventListener('pointercancel', up);
190 };
191 // eslint-disable-next-line react-hooks/exhaustive-deps
192 }, []);
193
194 return { slide, take };
195}
196
197interface Square {
198 /** The opening the square leaves, once there is a middle to measure. */
199 opening: { w: number; h: number } | null;
200 /** How big a stack came out — the wall's own tile size, in px. */
201 cell: number;
202 /** Where the four walls stand, from `rhombus`. */
203 shape: Rhombus | null;
204}
205
206/**
207 * How big to build the square, measured rather than worked out twice: how big a
208 * tile is is CSS's business, so one cell is rendered and asked how it came out,
209 * and the middle is whatever the four strips have left. Nothing here depends on
210 * the state of the hand — the square is built once for the window it is in and
211 * then eaten, so it does not close in on the discards lying inside it.
212 */
213function useSquare(ring: React.RefObject<HTMLDivElement | null>): Square {
214 const [square, setSquare] = useState<Square>({ opening: null, cell: 0, shape: null });
215
216 useLayoutEffect(() => {
217 const el = ring.current;
218 const middle = el?.parentElement;
219 const probe = el?.querySelector<HTMLElement>('.wall-probe');
220 if (!el || !middle || !probe) return;
221
222 // Everything the square is worked out *from*. Both observers below can be
223 // set off by this effect's own output — the probe is sized by the `--ws` it
224 // writes, and the ring's style attribute is where it writes it — so the
225 // guard is not a nicety: without it, one recompute schedules the next and
226 // the tab stops answering. Same inputs, nothing to do.
227 let last = '';
228
229 const read = () => {
230 const box = probe.getBoundingClientRect();
231 if (box.width <= 0) return;
232 // What shape a stack is, is CSS's business — read it, don't restate it.
233 // Scale-free, so this is the same number however big the square came out.
234 const ratio = box.height / box.width;
235 const style = getComputedStyle(el);
236 // The corner it turns, how far round it is set, and how much daylight is
237 // left where two walls meet — in tiles, and under one of them.
238 const angle = parseFloat(style.getPropertyValue('--wall-angle')) || 90;
239 const turn = parseFloat(style.getPropertyValue('--wall-turn')) || 0;
240 const gap = parseFloat(style.getPropertyValue('--wall-gap')) || 0;
241
242 // Sized off the tight way across the table, not the room between the four
243 // strips. Height is what a table is short of — 765 against 1396 — so that
244 // is what eighteen stacks have to fit, and the tile is whatever that comes
245 // to. It is the whole table because the square is bigger than the middle
246 // and always was; where it goes from here is a separate question.
247 const fit = (el.closest('.table') as HTMLElement | null) ?? middle;
248 const room = fit.clientHeight;
249 const from = `${room}/${ratio}/${angle}/${turn}/${gap}`;
250 if (from === last) return;
251 last = from;
252
253 // Linear in the stack, so it is asked once at a stack of one and scaled.
254 const unit = rhombus(STACKS_PER_SIDE, ratio, angle, turn, gap);
255 const s = Math.max(1, room / unit.box.h);
256 const shape = rhombus(STACKS_PER_SIDE * s, ratio * s, angle, turn, gap);
257 setSquare({ opening: { w: shape.open.w, h: shape.open.h }, cell: s, shape });
258 };
259
260 read();
261 // The middle, not the square: the square's own size is this effect's doing,
262 // and watching it would be watching itself. The probe is not watched for
263 // the same reason — it is `--ws` wearing a box, and `--ws` is the answer.
264 const observer = new ResizeObserver(read);
265 observer.observe(middle);
266 // The shape is three numbers on the element and none of them changes
267 // anything that has a size, so the observer above would never hear about
268 // one. `/wall.html` sets them on the ring itself, so that is what is
269 // watched — and this effect writes to that same attribute, which is what
270 // `last` is there to absorb.
271 const styled = new MutationObserver(read);
272 styled.observe(el, { attributes: true, attributeFilter: ['style'] });
273 return () => {
274 observer.disconnect();
275 styled.disconnect();
276 };
277 }, [ring]);
278
279 return square;
280}