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