anvilsign in

collin/mahjong

1import { useRef, useState } from 'react';
2import type { Tile } from '../game/tiles';
3import { TileView } from './TileView';
4
5export interface Throw {
6 /** Where the tile was let go of, in table coordinates. */
7 x: number;
8 y: number;
9 /** How fast, px per second. */
10 vx: number;
11 vy: number;
12 spin: number;
13}
14
15interface Props {
16 tiles: Tile[];
17 /** Somebody else's hand: shown as backs, and not to be poked at. */
18 faceDown?: boolean;
19 /** Index of the tile held apart from the rest, if any. */
20 drawnIndex: number | null;
21 selected: number | null;
22 canDiscard: boolean;
23 onSelect: (i: number) => void;
24 onDiscard: (i: number) => void;
25 onMove: (from: number, to: number) => void;
26 /**
27 * Picking a tile up and carrying it out of the row. Absent means the hand
28 * cannot be thrown from — the phone layout, where there is no middle of the
29 * table to throw into — and the row only ever reorders.
30 */
31 carry?: {
32 /**
33 * Lifted out of the row: from here the canvas draws it, not the DOM. `size`
34 * is the width the tile had in the hand, so it can be drawn the size it just
35 * was and shrink to its size in the pool rather than popping.
36 */
37 onPickUp: (index: number, x: number, y: number, size: number) => void;
38 onMoveTo: (x: number, y: number) => void;
39 /** Let go of over the table. */
40 onThrow: (index: number, t: Throw) => void;
41 /** Put back — the throw was never committed to. */
42 onCancel: () => void;
43 };
44}
45
46/** How far a pointer must travel before a tap becomes a drag. */
47const DRAG_SLOP = 12;
48/**
49 * How far out of the row before the tile is genuinely picked up — in either
50 * direction, so it comes up whichever way you pull it off the row rather than
51 * only towards the table. It is put back down again at 0.6 of this, and the gap
52 * between the two is what stops it flickering when a finger rests on the line.
53 */
54const LIFT_OUT = 22;
55/**
56 * A release this fast is a throw whatever else is true. Below it, the tile has
57 * to have been carried well clear of the row to count — so a hesitant drag back
58 * over your own hand puts the tile back instead of playing it.
59 */
60const THROW_SPEED = 220;
61const COMMIT_OUT = 70;
62/** Samples kept for reading the speed of a flick. */
63const SAMPLES = 5;
64
65interface Sample {
66 x: number;
67 y: number;
68 t: number;
69}
70
71/**
72 * Finds the tile nearest the pointer. Works whatever the seat's rotation:
73 * bounding rects are always screen-axis-aligned, so we read the row's direction
74 * off the first two tiles rather than assuming it runs left-to-right.
75 */
76function nearestIndex(container: HTMLElement, x: number, y: number): number | null {
77 const centers = rowCenters(container);
78 if (!centers) return null;
79 const { points, horizontal } = centers;
80 const along = (p: { x: number; y: number }) => (horizontal ? p.x : p.y);
81 const p = along({ x, y });
82
83 let best = 0;
84 let bestD = Infinity;
85 points.forEach((c, i) => {
86 const d = Math.abs(along(c) - p);
87 if (d < bestD) {
88 bestD = d;
89 best = i;
90 }
91 });
92 return best;
93}
94
95function rowCenters(container: HTMLElement) {
96 const els = Array.from(container.querySelectorAll<HTMLElement>('[data-idx]'));
97 if (els.length < 2) return null;
98 const points = els.map((el) => {
99 const r = el.getBoundingClientRect();
100 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
101 });
102 const horizontal = Math.abs(points[1].x - points[0].x) >= Math.abs(points[1].y - points[0].y);
103 return { points, horizontal };
104}
105
106/**
107 * Which way is "out of the row, towards the middle of the table".
108 *
109 * Read off the elements rather than from the seat's rotation, the same way
110 * `nearestIndex` reads the row's direction: the hand and the centre are both on
111 * screen, so the line between them is the answer for any seat at any angle.
112 */
113function outwardOf(container: HTMLElement) {
114 const table = container.closest<HTMLElement>('.table');
115 const hand = container.getBoundingClientRect();
116 const from = { x: hand.left + hand.width / 2, y: hand.top + hand.height / 2 };
117 if (!table) return { x: 0, y: -1, from, base: { x: 0, y: 0 } };
118 const t = table.getBoundingClientRect();
119 const to = { x: t.left + t.width / 2, y: t.top + t.height / 2 };
120 const dx = to.x - from.x;
121 const dy = to.y - from.y;
122 const d = Math.hypot(dx, dy) || 1;
123 return { x: dx / d, y: dy / d, from, base: { x: t.left, y: t.top } };
124}
125
126/**
127 * How wide the tile is in the hand. A seat's strip is rotated by a right angle,
128 * which swaps its bounding box, and a tile is always taller than it is wide — so
129 * the narrower side is the width whichever edge the player is sitting at.
130 */
131function tileWidth(container: HTMLElement, index: number): number {
132 const el = container.querySelector<HTMLElement>(`[data-idx="${index}"] .tile`);
133 if (!el) return 0;
134 const r = el.getBoundingClientRect();
135 return Math.min(r.width, r.height);
136}
137
138type Mode = 'undecided' | 'sort' | 'carry';
139
140interface Drag {
141 from: number;
142 cur: number;
143 startX: number;
144 startY: number;
145 mode: Mode;
146 outward: ReturnType<typeof outwardOf>;
147 samples: Sample[];
148}
149
150export function Hand({
151 tiles,
152 faceDown,
153 drawnIndex,
154 selected,
155 canDiscard,
156 onSelect,
157 onDiscard,
158 onMove,
159 carry,
160}: Props) {
161 const ref = useRef<HTMLDivElement>(null);
162 const drag = useRef<Drag | null>(null);
163 const [sorting, setSorting] = useState<number | null>(null);
164 const [carrying, setCarrying] = useState<number | null>(null);
165
166 const down = (e: React.PointerEvent, i: number) => {
167 // Capture is what lets a tile keep following a finger once it has left the
168 // row — without it the events stop the moment the pointer is over something
169 // else. It throws if the pointer has already gone, which is not a reason to
170 // drop the whole gesture.
171 try {
172 (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
173 } catch {
174 // Carry on uncaptured; a drag inside the row still works.
175 }
176 if (!ref.current) return;
177 drag.current = {
178 from: i,
179 cur: i,
180 startX: e.clientX,
181 startY: e.clientY,
182 mode: 'undecided',
183 outward: outwardOf(ref.current),
184 samples: [{ x: e.clientX, y: e.clientY, t: e.timeStamp }],
185 };
186 };
187
188 const move = (e: React.PointerEvent) => {
189 const d = drag.current;
190 if (!d || !ref.current) return;
191
192 d.samples.push({ x: e.clientX, y: e.clientY, t: e.timeStamp });
193 if (d.samples.length > SAMPLES) d.samples.shift();
194
195 const dx = e.clientX - d.startX;
196 const dy = e.clientY - d.startY;
197 // Signed distance out of the row, and distance along it. Both measured off
198 // the elements, so this reads the same from any of the four edges.
199 const out = dx * d.outward.x + dy * d.outward.y;
200 const along = Math.abs(dx * -d.outward.y + dy * d.outward.x);
201 const lift = Math.abs(out);
202 const canLift = !!carry && canDiscard;
203
204 if (d.mode === 'undecided' && Math.hypot(dx, dy) < DRAG_SLOP) return;
205
206 // Which of the two the gesture is is asked *every* move, not decided once
207 // at the start and stuck with. Deciding once meant a drag that set off a few
208 // degrees along the row was welded to the row for the rest of its life, and
209 // the tile could never be got out of the hand at all.
210 if (canLift) {
211 if (lift > LIFT_OUT) {
212 if (d.mode !== 'carry') {
213 d.mode = 'carry';
214 setSorting(null);
215 setCarrying(d.from);
216 carry.onPickUp(
217 d.from,
218 e.clientX - d.outward.base.x,
219 e.clientY - d.outward.base.y,
220 tileWidth(ref.current, d.from),
221 );
222 }
223 carry.onMoveTo(e.clientX - d.outward.base.x, e.clientY - d.outward.base.y);
224 return;
225 }
226 // Brought back over your own hand: put it down, and it is a tile in a row
227 // again. The gap between the two thresholds is what stops it flickering
228 // between the two when a finger sits on the boundary.
229 if (d.mode === 'carry') {
230 if (lift > LIFT_OUT * 0.6) return;
231 carry.onCancel();
232 setCarrying(null);
233 } else if (d.mode === 'undecided' && lift >= along) {
234 // On its way out but not out yet. Nothing should shuffle in the row
235 // underneath a tile that is about to leave it.
236 return;
237 }
238 }
239
240 d.mode = 'sort';
241 const to = nearestIndex(ref.current, e.clientX, e.clientY);
242 if (to !== null && to !== d.cur) {
243 onMove(d.cur, to);
244 d.cur = to;
245 }
246 setSorting(d.cur);
247 };
248
249 const up = (e: React.PointerEvent) => {
250 const d = drag.current;
251 drag.current = null;
252 setSorting(null);
253 setCarrying(null);
254 if (!d) return;
255
256 if (d.mode === 'carry') {
257 const v = velocityOf(d.samples, e.timeStamp, e.clientX, e.clientY);
258 const dx = e.clientX - d.startX;
259 const dy = e.clientY - d.startY;
260 const out = dx * d.outward.x + dy * d.outward.y;
261 const speedOut = v.vx * d.outward.x + v.vy * d.outward.y;
262 // Thrown if it left the fingers moving towards the table, or if it was
263 // carried far enough out that letting go there plainly means playing it.
264 if (speedOut > THROW_SPEED || out > COMMIT_OUT) {
265 carry?.onThrow(d.from, {
266 x: e.clientX - d.outward.base.x,
267 y: e.clientY - d.outward.base.y,
268 vx: v.vx,
269 vy: v.vy,
270 // A flick that curves puts a turn on the tile, as a real one does.
271 spin: v.spin,
272 });
273 } else {
274 carry?.onCancel();
275 }
276 return;
277 }
278
279 if (d.mode === 'sort' || !canDiscard) return;
280 if (selected === d.from) onDiscard(d.from);
281 else onSelect(d.from);
282 };
283
284 if (faceDown) {
285 return (
286 <div className="hand">
287 {tiles.map((_, i) => (
288 <div key={i} className="hand-cell">
289 <TileView faceDown />
290 </div>
291 ))}
292 </div>
293 );
294 }
295
296 return (
297 <div className="hand" ref={ref} onPointerMove={move} onPointerUp={up} onPointerCancel={up}>
298 {tiles.map((t, i) => (
299 <div
300 key={i}
301 data-idx={i}
302 className={
303 'hand-cell' +
304 (i === drawnIndex ? ' drawn-slot' : '') +
305 (i === sorting ? ' dragging' : '') +
306 // Its slot stays, so the row does not shuffle under the tile you are
307 // holding and you can still put it back where it came from.
308 (i === carrying ? ' carrying' : '')
309 }
310 onPointerDown={(e) => down(e, i)}
311 >
312 {i === drawnIndex && <span className="drawn-tag">摸 Drew</span>}
313 <TileView tile={t} raised={selected === i} />
314 </div>
315 ))}
316 </div>
317 );
318}
319
320/**
321 * How fast the tile was moving when it was let go of, from the last few pointer
322 * positions rather than just the final one — a single event pair is noisy enough
323 * to turn a firm throw into a limp one.
324 */
325function velocityOf(samples: Sample[], t: number, x: number, y: number) {
326 const last = { x, y, t };
327 // Far enough back to be a measurement, near enough to still be the flick.
328 const first = samples.find((s) => last.t - s.t < 90) ?? samples[0];
329 const dt = (last.t - first.t) / 1000;
330 if (!first || dt <= 0.001) return { vx: 0, vy: 0, spin: 0 };
331
332 const vx = (last.x - first.x) / dt;
333 const vy = (last.y - first.y) / dt;
334 // Spin comes from how much the flick bent between its two halves.
335 const mid = samples[Math.floor(samples.length / 2)] ?? first;
336 const bend =
337 (mid.x - first.x) * (last.y - mid.y) - (mid.y - first.y) * (last.x - mid.x);
338 return { vx, vy, spin: Math.max(-9, Math.min(9, bend * 0.004)) };
339}