"use client";import * as React from "react";import { X } from "lucide-react";import { NumberRoll } from "./number-roll";import { INTERACTION_FOCUS, INTERACTION_PRESS } from "./ui-interaction-motion";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * LASSO: select a loose group of things and see exactly what * got caught * * draw drag across the empty space round your items and a * band follows the hand; anything whose middle is * inside the loop is caught as you go: a ring and a * check pop onto it * tighten let go and the band pulls tight like an elastic * round exactly what it caught, bending in round * anything it didn't, and settles with a little give; * a chip riding the band says how many * add hold Shift (or start inside the band) to draw * another loop: both bands tighten round the lot * let go click empty space, press Esc or the chip's × and * the band snaps and is gone * * Your items are yours: mark them with data-lasso-id and read the * ids from onSelectedChange. The band is a small rope simulation * on one canvas over them; it sleeps once it's taut. * ───────────────────────────────────────────────────────── */export interface LassoProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange"> { children: React.ReactNode; /** Selected ids, controlled. Leave out to let the lasso keep them. */ selected?: string[]; defaultSelected?: string[]; onSelectedChange?: (ids: string[]) => void; /** What can be caught. Each must carry data-lasso-id. */ itemSelector?: string; /** The band and the rings: any CSS colour. */ color?: string; /** The chip's words. */ label?: (count: number) => string; /** A soft snap as the band tightens, off by default. */ sound?: boolean;}const N = 120; // points on the bandconst PAD = 5; // how far the band sits off what it wrapsconst SLIP = 2; // how close it may pass what it didn't catchconst LINK = 26; // items closer than this share a bandconst OVER = 18; // the canvas reaches past the container for the bandconst EASE = "cubic-bezier(0.16,1,0.3,1)";const NO_IDS: string[] = [];const reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => { const query = window.matchMedia(reducedQuery); query.addEventListener("change", onChange); return () => query.removeEventListener("change", onChange);};const useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);const clamp = (v: number, a: number, b: number) => (v < a ? a : v > b ? b : v);const backOut = (t: number) => 1 + 2.4 * (t - 1) ** 3 + 1.4 * (t - 1) ** 2;type RGB = [number, number, number];const mix = (a: RGB, b: RGB, t: number): RGB => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];const css = (c: RGB, alpha = 1) => `rgba(${Math.round(c[0])},${Math.round(c[1])},${Math.round(c[2])},${alpha})`;const lum = (c: RGB) => (0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]) / 255;let probe: CanvasRenderingContext2D | null = null;function toRgb(color: string, fallback: RGB): RGB { if (typeof document === "undefined" || !color) return fallback; probe ??= document.createElement("canvas").getContext("2d", { willReadFrequently: true }); if (!probe) return fallback; probe.clearRect(0, 0, 1, 1); probe.fillStyle = "#000"; probe.fillStyle = color; probe.fillRect(0, 0, 1, 1); const [r, g, b, a] = probe.getImageData(0, 0, 1, 1).data; return a === 0 ? fallback : [r, g, b];}/* ── geometry ── */type Item = { id: string; el: HTMLElement; x: number; y: number; w: number; h: number; r: number };/** Signed distance from a point to an item grown by pad: negative inside. */function sdItem(it: Item, px: number, py: number, pad = PAD) { const r = it.r + pad; const qx = Math.abs(px - (it.x + it.w / 2)) - it.w / 2 - pad + r; const qy = Math.abs(py - (it.y + it.h / 2)) - it.h / 2 - pad + r; return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;}function inside(xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, px: number, py: number) { let hit = false; for (let i = 0, j = n - 1; i < n; j = i++) { if (ys[i] > py !== ys[j] > py && px < ((xs[j] - xs[i]) * (py - ys[i])) / (ys[j] - ys[i]) + xs[i]) hit = !hit; } return hit;}/** Evenly spaced points round a closed path. */function resample(xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, count: number) { const len: number[] = [0]; for (let i = 1; i <= n; i++) { const a = i - 1; const b = i % n; len.push(len[a] + Math.hypot(xs[b] - xs[a], ys[b] - ys[a])); } const total = len[n] || 1; const ox = new Float32Array(count); const oy = new Float32Array(count); let seg = 0; for (let k = 0; k < count; k++) { const at = (k / count) * total; while (seg < n - 1 && len[seg + 1] < at) seg++; const a = seg; const b = (seg + 1) % n; const span = len[seg + 1] - len[seg] || 1; const t = (at - len[seg]) / span; ox[k] = xs[a] + (xs[b] - xs[a]) * t; oy[k] = ys[a] + (ys[b] - ys[a]) * t; } return { xs: ox, ys: oy, total };}/* ── the engine ── */type Band = { x: Float32Array; y: Float32Array; px: Float32Array; py: Float32Array; born: number; still: number; alpha: number; dying: boolean; ids: Set<string>; key: string };interface Engine { root: HTMLDivElement | null; canvas: HTMLCanvasElement | null; chip: HTMLDivElement | null; width: number; height: number; dpr: number; items: Item[]; path: { x: number[]; y: number[] } | null; // while drawing bands: Band[]; caught: Set<string>; // under the loop being drawn selected: Set<string>; badges: Map<string, { t: number; on: boolean }>; hold: { x: number; y: number; t: number } | null; // a touch held before drawing color: RGB; hi: RGB; dark: boolean; frame: number; last: number; reduced: boolean; sound: boolean;}function measure(e: Engine, selector: string) { const root = e.root; if (!root) return; const base = root.getBoundingClientRect(); e.width = base.width; e.height = base.height; e.dpr = Math.min(3, window.devicePixelRatio || 1); e.items = Array.from(root.querySelectorAll<HTMLElement>(selector)).map((el) => { const r = el.getBoundingClientRect(); const radius = parseFloat(getComputedStyle(el).borderTopLeftRadius) || 0; return { id: el.dataset.lassoId ?? "", el, x: r.left - base.left, y: r.top - base.top, w: r.width, h: r.height, r: Math.min(radius, r.width / 2, r.height / 2) }; });}function makeBand(xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, now: number, ids: Set<string>): Band { const { xs: x, ys: y } = resample(xs, ys, n, N); return { x, y, px: Float32Array.from(x), py: Float32Array.from(y), born: now, still: 0, alpha: 1, dying: false, ids, key: [...ids].sort().join("\u0000") };}/** Selected items that sit next to each other share a band; one far away gets its own. */function groups(e: Engine) { const its = e.items.filter((it) => e.selected.has(it.id)); const parent = its.map((_, i) => i); const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i]))); for (let i = 0; i < its.length; i++) { for (let j = i + 1; j < its.length; j++) { const a = its[i]; const b = its[j]; const gx = Math.max(0, Math.abs(a.x + a.w / 2 - (b.x + b.w / 2)) - (a.w + b.w) / 2); const gy = Math.max(0, Math.abs(a.y + a.h / 2 - (b.y + b.h / 2)) - (a.h + b.h) / 2); // Side by side (not just touching at a corner) and close: one band. if ((gx <= LINK && gy === 0) || (gy <= LINK && gx === 0)) parent[find(i)] = find(j); } } const out = new Map<number, Set<string>>(); its.forEach((it, i) => { const root = find(i); if (!out.has(root)) out.set(root, new Set()); out.get(root)!.add(it.id); }); return [...out.values()];}const DIRS = [ [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1],];/** A loop that follows a group's own outline at a distance (concave where the group is), traced on a coarse grid. */function outline(e: Engine, ids: Set<string>, extra: number) { const its = e.items.filter((it) => ids.has(it.id)); if (!its.length) return null; const S = 4; const margin = PAD + extra + 10; const x0 = Math.min(...its.map((i) => i.x)) - margin; const y0 = Math.min(...its.map((i) => i.y)) - margin; const W = Math.ceil((Math.max(...its.map((i) => i.x + i.w)) + margin - x0) / S) + 1; const H = Math.ceil((Math.max(...its.map((i) => i.y + i.h)) + margin - y0) / S) + 1; const grid = new Uint8Array(W * H); for (let gy = 0; gy < H; gy++) { for (let gx = 0; gx < W; gx++) { let d = Infinity; for (const it of its) d = Math.min(d, sdItem(it, x0 + gx * S, y0 + gy * S) - extra); grid[gy * W + gx] = d < 0 ? 1 : 0; } } const filled = (x: number, y: number) => x >= 0 && y >= 0 && x < W && y < H && grid[y * W + x] === 1; let sx = -1; let sy = -1; for (let i = 0; i < W * H && sx < 0; i++) if (grid[i]) [sx, sy] = [i % W, Math.floor(i / W)]; if (sx < 0) return null; // Moore-neighbour tracing, clockwise, starting with the outside cell to the west as the one we came from. const xs: number[] = []; const ys: number[] = []; let cx = sx; let cy = sy; let back = 4; for (let guard = 0; guard < W * H * 4; guard++) { xs.push(x0 + cx * S); ys.push(y0 + cy * S); let moved = false; for (let k = 1; k <= 8; k++) { const d = (back + k) % 8; const nx = cx + DIRS[d][0]; const ny = cy + DIRS[d][1]; if (filled(nx, ny)) { const pd = (d + 7) % 8; const bx = cx + DIRS[pd][0] - nx; const by = cy + DIRS[pd][1] - ny; back = DIRS.findIndex(([ax, ay]) => ax === bx && ay === by); cx = nx; cy = ny; moved = true; break; } } if (!moved || (cx === sx && cy === sy && xs.length > 2)) break; } // Smooth off the grid's steps. const n = xs.length; for (let pass = 0; pass < 4; pass++) { const ox = xs.slice(); const oy = ys.slice(); for (let i = 0; i < n; i++) { xs[i] = (ox[(i + n - 1) % n] + ox[i] * 2 + ox[(i + 1) % n]) / 4; ys[i] = (oy[(i + n - 1) % n] + oy[i] * 2 + oy[(i + 1) % n]) / 4; } } return { xs, ys };}/** Matches the bands to the selection's groups: a band that already holds a group stays; the loop just drawn becomes * the band of the group it caught; any other group gets a band that starts loose round its outline and tightens. */function rebuild(e: Engine, now: number, drawn?: { xs: number[]; ys: number[]; ids: Set<string> }) { const want = groups(e); const keys = new Set(want.map((g) => [...g].sort().join("\u0000"))); e.bands.forEach((b) => { if (!keys.has(b.key)) b.dying = true; }); for (const g of want) { const key = [...g].sort().join("\u0000"); if (e.bands.some((b) => !b.dying && b.key === key)) continue; const same = drawn && drawn.ids.size === g.size && [...g].every((id) => drawn.ids.has(id)); const loop = same ? drawn : outline(e, g, 20); if (loop && loop.xs.length > 2) e.bands.push(makeBand(loop.xs, loop.ys, loop.xs.length, now, g)); } if (e.reduced) { e.bands.forEach((b) => (b.dying ? (b.alpha = 0) : settleNow(e, b))); }}/** One step of a band (1/120 s): inertia, an elastic pull that shortens it, and every item pushing it out. */function stepBand(e: Engine, b: Band, solid: { item: Item; pad: number }[]) { const damp = 0.84; let move = 0; for (let i = 0; i < N; i++) { const vx = (b.x[i] - b.px[i]) * damp; const vy = (b.y[i] - b.py[i]) * damp; b.px[i] = b.x[i]; b.py[i] = b.y[i]; b.x[i] += vx; b.y[i] += vy; } let cx = 0; let cy = 0; for (let i = 0; i < N; i++) { cx += b.x[i]; cy += b.y[i]; } cx /= N; cy /= N; for (let it = 0; it < 3; it++) { for (let i = 0; i < N; i++) { const a = (i + N - 1) % N; const c = (i + 1) % N; // Tension only: each point moves towards the middle of its neighbours, which straightens and shortens the band // (a band with nothing inside it runs down to a point); nothing pulls it into the gaps between what it holds. const mx = (b.x[a] + b.x[c]) / 2 - b.x[i]; const my = (b.y[a] + b.y[c]) / 2 - b.y[i]; const pull = b.ids.size ? 0 : 0.25; const dx = cx - b.x[i]; const dy = cy - b.y[i]; const d = Math.hypot(dx, dy) || 1; b.x[i] += mx * 0.45 + (dx / d) * pull; b.y[i] += my * 0.45 + (dy / d) * pull; } // Items are solid: anything the band presses into pushes it back out to their edge. if (!b.dying) { for (let i = 0; i < N; i++) { for (const { item, pad } of solid) { const sd = sdItem(item, b.x[i], b.y[i], pad); if (sd >= 0) continue; const h = 0.5; const gx = sdItem(item, b.x[i] + h, b.y[i], pad) - sdItem(item, b.x[i] - h, b.y[i], pad); const gy = sdItem(item, b.x[i], b.y[i] + h, pad) - sdItem(item, b.x[i], b.y[i] - h, pad); const gl = Math.hypot(gx, gy) || 1; b.x[i] -= (gx / gl) * sd; b.y[i] -= (gy / gl) * sd; } } } } for (let i = 0; i < N; i++) move = Math.max(move, Math.abs(b.x[i] - b.px[i]) + Math.abs(b.y[i] - b.py[i])); b.still = move < 0.03 ? b.still + 1 : 0;}/** What the band can't pass through: what it caught, and anything outside it (so it bends in round what it didn't catch). */function solidFor(e: Engine, b: Band) { const out: { item: Item; pad: number }[] = []; for (const it of e.items) { if (b.ids.has(it.id)) out.push({ item: it, pad: PAD }); else if (!inside(b.x, b.y, N, it.x + it.w / 2, it.y + it.h / 2)) out.push({ item: it, pad: SLIP }); } return out;}function perimeter(b: Band) { let p = 0; for (let i = 0; i < N; i++) p += Math.hypot(b.x[(i + 1) % N] - b.x[i], b.y[(i + 1) % N] - b.y[i]); return p;}function strokeLoop(ctx: CanvasRenderingContext2D, xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, closed: boolean) { ctx.beginPath(); // A smooth curve through the points: midpoints joined by quadratic curves. const at = (k: number) => (closed ? ((k % n) + n) % n : clamp(k, 0, n - 1)); ctx.moveTo((xs[at(0)] + xs[at(1)]) / 2, (ys[at(0)] + ys[at(1)]) / 2); const end = closed ? n : n - 1; for (let k = 1; k < end; k++) { const a = at(k); const b = at(k + 1); ctx.quadraticCurveTo(xs[a], ys[a], (xs[a] + xs[b]) / 2, (ys[a] + ys[b]) / 2); } if (closed) ctx.closePath();}/** The band: a rubber cord in your colour with a lit top and a small contact shadow on the surface it lies on. */function drawBand(ctx: CanvasRenderingContext2D, e: Engine, xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, closed: boolean, alpha: number, width: number) { ctx.save(); ctx.globalAlpha = alpha; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.save(); ctx.shadowColor = css([0, 0, 0], e.dark ? 0.55 : 0.22); ctx.shadowBlur = 3; ctx.shadowOffsetY = 1.5; strokeLoop(ctx, xs, ys, n, closed); ctx.strokeStyle = css(mix(e.color, [0, 0, 0], 0.12)); ctx.lineWidth = width; ctx.stroke(); ctx.restore(); ctx.translate(-0.25, -0.6); strokeLoop(ctx, xs, ys, n, closed); ctx.strokeStyle = css(e.hi, 0.75); ctx.lineWidth = Math.max(0.8, width * 0.32); ctx.stroke(); ctx.restore();}function roundRectPath(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) { const rr = Math.max(0, Math.min(r, w / 2, h / 2)); ctx.beginPath(); ctx.moveTo(x + rr, y); ctx.arcTo(x + w, y, x + w, y + h, rr); ctx.arcTo(x + w, y + h, x, y + h, rr); ctx.arcTo(x, y + h, x, y, rr); ctx.arcTo(x, y, x + w, y, rr); ctx.closePath();}function draw(e: Engine, now: number) { const canvas = e.canvas; const ctx = canvas?.getContext("2d"); if (!canvas || !ctx) return false; const W = e.width + OVER * 2; const H = e.height + OVER * 2; if (canvas.width !== Math.round(W * e.dpr) || canvas.height !== Math.round(H * e.dpr)) { canvas.width = Math.round(W * e.dpr); canvas.height = Math.round(H * e.dpr); } ctx.setTransform(e.dpr, 0, 0, e.dpr, e.dpr * OVER, e.dpr * OVER); ctx.clearRect(-OVER, -OVER, W, H); let busy = false; // Rings and checks on what's caught (while drawing) or selected (after). const shown = e.path ? new Set([...e.selected, ...e.caught]) : e.selected; for (const it of e.items) { const want = shown.has(it.id); const badge = e.badges.get(it.id); if (want && (!badge || !badge.on)) e.badges.set(it.id, { t: now, on: true }); if (!want && badge?.on) e.badges.set(it.id, { t: now, on: false }); const b = e.badges.get(it.id); if (!b) continue; const k = clamp((now - b.t) / (b.on ? 260 : 160), 0, 1); if (k < 1) busy = true; const s = e.reduced ? (b.on ? 1 : 0) : b.on ? backOut(k) : 1 - k; if (s <= 0.01) { if (!b.on) e.badges.delete(it.id); continue; } ctx.save(); ctx.globalAlpha = clamp(s, 0, 1); // While drawing, a ring shows what's caught; once let go, the band itself outlines the selection. if (e.path) { roundRectPath(ctx, it.x - 3, it.y - 3, it.w + 6, it.h + 6, it.r + 3); ctx.strokeStyle = css(e.color); ctx.lineWidth = 2; ctx.stroke(); } const bx = it.x + it.w - 13; const by = it.y + 13; ctx.translate(bx, by); ctx.scale(s, s); ctx.beginPath(); ctx.arc(0, 0, 9.5, 0, Math.PI * 2); ctx.fillStyle = css([255, 255, 255]); ctx.fill(); ctx.beginPath(); ctx.arc(0, 0, 8, 0, Math.PI * 2); ctx.fillStyle = css(e.color); ctx.fill(); ctx.beginPath(); ctx.moveTo(-3.6, 0.2); ctx.lineTo(-1.1, 2.7); ctx.lineTo(3.8, -2.4); ctx.strokeStyle = css([255, 255, 255]); ctx.lineWidth = 1.9; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.stroke(); ctx.restore(); } // The loop being drawn: a slack cord from where it started to the hand, the closing gap shown faintly. if (e.path && e.path.x.length > 1) { const { x, y } = e.path; drawBand(ctx, e, x, y, x.length, false, 1, 3.4); ctx.save(); ctx.setLineDash([3, 5]); ctx.beginPath(); ctx.moveTo(x[x.length - 1], y[y.length - 1]); ctx.lineTo(x[0], y[0]); ctx.strokeStyle = css(e.color, 0.45); ctx.lineWidth = 1.5; ctx.stroke(); ctx.restore(); } // A touch held before drawing: a ring fills under the finger. if (e.hold) { const k = clamp((now - e.hold.t) / 280, 0, 1); busy = true; ctx.beginPath(); ctx.arc(e.hold.x, e.hold.y, 18, -Math.PI / 2, -Math.PI / 2 + k * Math.PI * 2); ctx.strokeStyle = css(e.color, 0.8); ctx.lineWidth = 3; ctx.stroke(); } for (const b of e.bands) drawBand(ctx, e, b.x, b.y, N, true, b.alpha, 3); return busy;}function frame(e: Engine, now: number, onSettle: () => void) { e.frame = 0; const steps = clamp(Math.round(((now - e.last) / 1000) * 120), 1, 6); e.last = now; let busy = false; for (const b of e.bands) { if (b.dying) { // Snapped: it shrinks to the middle and fades. b.alpha = Math.max(0, b.alpha - 0.09); for (let s = 0; s < steps; s++) stepBand(e, b, []); busy = busy || b.alpha > 0; continue; } for (let s = 0; s < steps; s++) stepBand(e, b, solidFor(e, b)); const age = now - b.born; // A band that caught nothing runs down to nothing. if (perimeter(b) < 14) { b.dying = true; busy = true; continue; } if (b.still < 30 && age < 2400) busy = true; } const before = e.bands.length; e.bands = e.bands.filter((b) => !(b.dying && b.alpha <= 0)); if (draw(e, now)) busy = true; placeChip(e); if (before && !busy) onSettle(); if (busy) e.frame = requestAnimationFrame((t) => frame(e, t, onSettle));}/** The chip sits centred above the bands. */function placeChip(e: Engine) { const chip = e.chip; if (!chip) return; let x0 = Infinity; let x1 = -Infinity; let y0 = Infinity; for (const b of e.bands) { if (b.dying) continue; for (let i = 0; i < N; i++) { if (b.x[i] < x0) x0 = b.x[i]; if (b.x[i] > x1) x1 = b.x[i]; if (b.y[i] < y0) y0 = b.y[i]; } } if (!isFinite(y0) || !e.selected.size || e.path) { chip.style.opacity = "0"; chip.style.pointerEvents = "none"; return; } const x = clamp((x0 + x1) / 2, 56, Math.max(56, e.width - 56)); chip.style.opacity = "1"; chip.style.pointerEvents = "auto"; chip.style.transform = `translate3d(${x}px, ${y0 - 8}px, 0) translate(-50%, -100%)`;}/* ── the component ── */export function Lasso({ children, selected, defaultSelected = NO_IDS, onSelectedChange, itemSelector = "[data-lasso-id]", color, label = () => "selected", sound = false, className = "", style, onPointerDown, onKeyDown, ...props}: LassoProps) { const reduced = useReducedMotion(); const rootRef = React.useRef<HTMLDivElement>(null); const canvasRef = React.useRef<HTMLCanvasElement>(null); const chipRef = React.useRef<HTMLDivElement>(null); const probes = React.useRef<(HTMLSpanElement | null)[]>([]); const engineRef = React.useRef<Engine | null>(null); const [own, setOwn] = React.useState<string[]>(defaultSelected); const ids = selected ?? own; const [announce, setAnnounce] = React.useState(""); const engine = React.useCallback((): Engine => { if (!engineRef.current) { engineRef.current = { root: null, canvas: null, chip: null, width: 0, height: 0, dpr: 1, items: [], path: null, bands: [], caught: new Set(), selected: new Set(), badges: new Map(), hold: null, color: [48, 93, 222], hi: [160, 185, 245], dark: false, frame: 0, last: 0, reduced: false, sound: false, }; } return engineRef.current; }, []); const live = React.useRef({ onSelectedChange, controlled: selected !== undefined, itemSelector }); React.useLayoutEffect(() => { live.current = { onSelectedChange, controlled: selected !== undefined, itemSelector }; }); const settle = React.useCallback(() => { const e = engine(); if (e.sound && e.bands.length) playSound("tick", 0.18); }, [engine]); const kick = React.useCallback(() => { const e = engine(); if (e.frame || !e.canvas) return; e.last = performance.now(); e.frame = requestAnimationFrame((t) => frame(e, t, settle)); }, [engine, settle]); const commit = React.useCallback( (next: Set<string>) => { const list = [...next]; if (!live.current.controlled) setOwn(list); live.current.onSelectedChange?.(list); setAnnounce(list.length ? `${list.length} selected` : "Selection cleared"); }, [], ); // Selection from the app (or a click on an item there): rings follow, and a band wraps the new set. React.useEffect(() => { const e = engine(); const next = new Set(ids); const same = next.size === e.selected.size && [...next].every((id) => e.selected.has(id)); if (same) return; e.selected = next; if (!e.path) { measure(e, live.current.itemSelector); rebuild(e, performance.now()); } kick(); }, [engine, ids, kick]); React.useEffect(() => { const e = engine(); e.reduced = reduced; e.sound = sound; }, [engine, reduced, sound]); React.useLayoutEffect(() => { const e = engine(); e.root = rootRef.current; e.canvas = canvasRef.current; e.chip = chipRef.current; const root = rootRef.current; if (!root) return; const remeasure = () => { measure(e, live.current.itemSelector); // Taut bands re-wrap the selection where it now is. if (e.selected.size && !e.path) { e.bands = []; rebuild(e, performance.now()); } kick(); }; remeasure(); const observer = new ResizeObserver(remeasure); observer.observe(root); // Touch: once a hold has started a loop, the page mustn't scroll under the finger. const block = (ev: TouchEvent) => { if (e.path) ev.preventDefault(); }; root.addEventListener("touchmove", block, { passive: false }); return () => { observer.disconnect(); root.removeEventListener("touchmove", block); cancelAnimationFrame(e.frame); e.frame = 0; }; }, [engine, kick]); // Theme colours, read again when the theme changes. React.useEffect(() => { const e = engine(); const read = () => { const c = toRgb(probes.current[0] ? getComputedStyle(probes.current[0]).color : "", [48, 93, 222]); const bg = toRgb(probes.current[1] ? getComputedStyle(probes.current[1]).color : "", [255, 255, 255]); e.color = c; e.hi = mix(c, [255, 255, 255], 0.55); e.dark = lum(bg) < 0.5; kick(); }; read(); const observer = new MutationObserver(read); observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme"] }); const media = window.matchMedia("(prefers-color-scheme: dark)"); media.addEventListener("change", read); return () => { observer.disconnect(); media.removeEventListener("change", read); }; }, [engine, color, kick]); /* ── the hand ── */ const gesture = React.useRef<{ id: number; x: number; y: number; started: boolean; add: boolean; timer: number } | null>(null); const local = (ev: { clientX: number; clientY: number }) => { const r = rootRef.current!.getBoundingClientRect(); return { x: ev.clientX - r.left, y: ev.clientY - r.top }; }; const begin = (x: number, y: number) => { const e = engine(); const g = gesture.current; if (!g) return; g.started = true; e.hold = null; e.path = { x: [x], y: [y] }; e.caught = new Set(); if (!g.add) { e.selected = new Set(); e.bands.forEach((b) => (b.dying = true)); } rootRef.current?.setPointerCapture(g.id); kick(); }; const handleDown = (ev: React.PointerEvent<HTMLDivElement>) => { onPointerDown?.(ev); if (ev.defaultPrevented || ev.button !== 0) return; const target = ev.target as HTMLElement; if (target.closest(itemSelector) || target.closest("button, a, input, textarea, select, [data-lasso-ignore]")) return; const e = engine(); measure(e, itemSelector); const p = local(ev); const insideBand = e.bands.some((b) => !b.dying && inside(b.x, b.y, N, p.x, p.y)); gesture.current = { id: ev.pointerId, x: p.x, y: p.y, started: false, add: ev.shiftKey || insideBand, timer: 0 }; if (ev.pointerType === "touch") { // On touch a short hold starts the loop, so a plain swipe still scrolls the page. e.hold = { x: p.x, y: p.y, t: performance.now() }; kick(); gesture.current.timer = window.setTimeout(() => begin(p.x, p.y), 280); } }; const handleMove = (ev: React.PointerEvent<HTMLDivElement>) => { const g = gesture.current; const e = engine(); if (!g || g.id !== ev.pointerId) return; const p = local(ev); if (!g.started) { if (Math.hypot(p.x - g.x, p.y - g.y) < 5) return; if (ev.pointerType === "touch") { // Moved before the hold finished: it's a scroll. window.clearTimeout(g.timer); e.hold = null; gesture.current = null; return; } begin(g.x, g.y); } const path = e.path; if (!path) return; const lx = path.x[path.x.length - 1]; const ly = path.y[path.y.length - 1]; if (Math.hypot(p.x - lx, p.y - ly) < 3) return; path.x.push(p.x); path.y.push(p.y); // Caught as you go: anything whose middle is inside the loop so far. const caught = new Set<string>(); if (path.x.length > 2) for (const it of e.items) if (inside(path.x, path.y, path.x.length, it.x + it.w / 2, it.y + it.h / 2)) caught.add(it.id); if (e.sound && caught.size > e.caught.size) playSound("pop", 0.15); e.caught = caught; kick(); }; const handleUp = (ev: React.PointerEvent<HTMLDivElement>) => { const g = gesture.current; const e = engine(); if (!g || g.id !== ev.pointerId) return; window.clearTimeout(g.timer); gesture.current = null; e.hold = null; const path = e.path; e.path = null; if (!g.started || !path) { // A plain click on empty space lets the selection go. if (ev.type === "pointerup" && e.selected.size) letGo(); kick(); return; } const caughtNow = e.caught; const next = g.add ? new Set([...e.selected, ...caughtNow]) : new Set(caughtNow); e.caught = new Set(); let area = 0; for (let i = 0, j = path.x.length - 1; i < path.x.length; j = i++) area += (path.x[j] + path.x[i]) * (path.y[j] - path.y[i]); if (Math.abs(area) / 2 < 400 || next.size === 0) { e.selected = next; rebuild(e, ev.timeStamp); commit(next); kick(); return; } e.selected = next; rebuild(e, ev.timeStamp, { xs: path.x, ys: path.y, ids: caughtNow }); commit(next); kick(); }; const letGo = () => { const e = engine(); e.selected = new Set(); e.bands.forEach((b) => { b.dying = true; if (e.reduced) b.alpha = 0; }); if (e.sound) playSound("tick", 0.2); commit(new Set()); kick(); }; const handleKey = (ev: React.KeyboardEvent<HTMLDivElement>) => { onKeyDown?.(ev); if (ev.key === "Escape" && engine().selected.size) { ev.stopPropagation(); letGo(); } }; // Selected items carry an attribute your styles can use. React.useEffect(() => { const root = rootRef.current; if (!root) return; const set = new Set(ids); root.querySelectorAll<HTMLElement>(itemSelector).forEach((el) => { if (set.has(el.dataset.lassoId ?? "")) el.setAttribute("data-lasso-selected", ""); else el.removeAttribute("data-lasso-selected"); }); }, [ids, itemSelector, children]); const count = ids.length; return ( <div ref={rootRef} className={`relative select-none ${className}`} style={style} onPointerDown={handleDown} onPointerMove={handleMove} onPointerUp={handleUp} onPointerCancel={handleUp} onKeyDown={handleKey} {...props} > <span ref={(el) => void (probes.current[0] = el)} hidden style={{ color: color ?? "var(--primary)" }} /> <span ref={(el) => void (probes.current[1] = el)} hidden className="text-background" /> {children} <canvas ref={canvasRef} aria-hidden className="pointer-events-none absolute z-10" style={{ left: -OVER, top: -OVER, width: `calc(100% + ${OVER * 2}px)`, height: `calc(100% + ${OVER * 2}px)` }} /> <div ref={chipRef} className="absolute left-0 top-0 z-20 flex h-8 items-center gap-1 rounded-full bg-foreground pl-3 pr-1 text-[12.5px] font-medium text-background" style={{ opacity: 0, pointerEvents: "none", transition: `opacity 220ms ${EASE}`, willChange: "transform" }} data-lasso-ignore > <span className="tabular-nums"> <NumberRoll value={count} /> </span> <span>{label(count)}</span> <button type="button" aria-label="Clear selection" onClick={letGo} className={`ml-1 grid size-6 cursor-pointer place-items-center rounded-full hover:bg-[color-mix(in_oklab,var(--background)_20%,var(--foreground))] ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <X className="size-3.5" aria-hidden /> </button> </div> <span className="sr-only" role="status" aria-live="polite"> {announce} </span> </div> );}/** Reduced motion: run the band to rest at once. */function settleNow(e: Engine, b: Band) { for (let k = 0; k < 600 && b.still < 30; k++) stepBand(e, b, solidFor(e, b)); b.px = Float32Array.from(b.x); b.py = Float32Array.from(b.y);}