anvilsign in

collin/mahjong

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