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