@esmirnov.ai/sperm-lab 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,524 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { FACTORS, ANATOMY_SOURCES, DEFECT_CATALOG, cellMatchesDefect, getDefectCounts, getCellDefects, createSimulation, createDefectSimulation, stepSimulation, getMetrics, isSlow, } from "../core/index.js";
5
+ import { paintSimulation, hitTestCell, getCellAnchor } from "./renderer.js";
6
+ const groups = [
7
+ { title: "Exercise", ids: ["exercise", "endurance", "cycling"], side: "left" },
8
+ { title: "Habits", ids: ["smoking", "alcohol", "sleep", "stress"], side: "left" },
9
+ { title: "Body", ids: ["heat", "fever", "metabolic"], side: "right" },
10
+ { title: "Chemicals", ids: ["androgens", "pesticides"], side: "right" },
11
+ ];
12
+ const shortLabels = {
13
+ exercise: "Regular exercise", endurance: "Heavy running", cycling: "Long cycling", smoking: "Smoking", alcohol: "Heavy alcohol",
14
+ stress: "Chronic stress", sleep: "Poor sleep", heat: "Prolonged heat", fever: "Fever", metabolic: "Metabolic stress",
15
+ androgens: "External androgens", pesticides: "Certain pesticides",
16
+ };
17
+ function finite(value, fallback, min, max) {
18
+ return Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
19
+ }
20
+ function resolveFactors(input, initialFactor) {
21
+ return Object.fromEntries(FACTORS.map(factor => [factor.id, finite(input?.[factor.id], input ? 0 : factor.id === initialFactor ? .65 : 0, 0, 1)]));
22
+ }
23
+ function newWorld(seed, count, factors, progress, teachingPopulation) {
24
+ return createSimulation({ seed, count, factors, progress, teachingPopulation });
25
+ }
26
+ export function SpermLab({ seed = 42, count = 48, initialFactors, initialFactor, teachingPopulation = true, className = "", style, onMetrics } = {}) {
27
+ const [defaults] = useState(() => ({ seed: finite(seed, 42, 0, 0xffffffff), count: Math.round(finite(count, 48, teachingPopulation ? 18 : 8, 120)), factors: resolveFactors(initialFactors, initialFactor), teachingPopulation }));
28
+ const prefix = useId();
29
+ const [factors, setFactors] = useState(defaults.factors);
30
+ const [paused, setPaused] = useState(false);
31
+ const [slowMotion, setSlowMotion] = useState(false);
32
+ const [trails, setTrails] = useState(true);
33
+ const [dna, setDna] = useState(true);
34
+ const [selectedId, setSelectedId] = useState(null);
35
+ const [popupOpen, setPopupOpen] = useState(false);
36
+ const [popupHeight, setPopupHeight] = useState(0);
37
+ const [prepared, setPrepared] = useState(false);
38
+ const [status, setStatus] = useState("");
39
+ const [unavailable, setUnavailable] = useState(false);
40
+ const [metrics, setMetrics] = useState(() => getMetrics(newWorld(defaults.seed, defaults.count, defaults.factors, 1, defaults.teachingPopulation)));
41
+ const [defectCounts, setDefectCounts] = useState(() => getDefectCounts(newWorld(defaults.seed, defaults.count, defaults.factors, 1, defaults.teachingPopulation)));
42
+ const world = useRef(null);
43
+ const resetMotion = useRef(false);
44
+ const root = useRef(null);
45
+ const canvas = useRef(null);
46
+ const inspector = useRef(null);
47
+ const popup = useRef(null);
48
+ const popupClose = useRef(null);
49
+ const popupConnector = useRef(null);
50
+ const callback = useRef(onMetrics);
51
+ callback.current = onMetrics;
52
+ const settings = useRef({ paused, slowMotion, trails, dna, selectedId, popupOpen });
53
+ settings.current = { paused, slowMotion, trails, dna, selectedId, popupOpen };
54
+ const actions = useRef({ invalidate: () => { }, release: () => { } });
55
+ const flow = useRef(undefined);
56
+ const pointer = useRef(null);
57
+ const selected = world.current?.cells.find(cell => cell.id === selectedId);
58
+ const active = FACTORS.filter(factor => (factors[factor.id] ?? 0) > 0);
59
+ function publish(next, preserveMotion = false) {
60
+ const previous = world.current;
61
+ if (preserveMotion && previous) {
62
+ next.time = previous.time;
63
+ next.trailClock = previous.trailClock;
64
+ for (const cell of next.cells) {
65
+ const old = previous.cells.find(item => item.id === cell.id);
66
+ if (!old)
67
+ continue;
68
+ cell.x = old.x;
69
+ cell.y = old.y;
70
+ cell.angle = old.angle;
71
+ cell.phase = old.phase;
72
+ cell.trail = old.trail.map(point => ({ ...point }));
73
+ }
74
+ }
75
+ world.current = next;
76
+ const counts = getMetrics(next);
77
+ setMetrics(counts);
78
+ callback.current?.(counts);
79
+ setDefectCounts(getDefectCounts(next));
80
+ if (!preserveMotion || !next.cells.some(cell => cell.id === selectedId)) {
81
+ setSelectedId(null);
82
+ setPopupOpen(false);
83
+ }
84
+ actions.current.release();
85
+ actions.current.invalidate();
86
+ }
87
+ useEffect(() => {
88
+ publish(newWorld(defaults.seed, defaults.count, factors, 1, defaults.teachingPopulation), !resetMotion.current);
89
+ resetMotion.current = false;
90
+ setPrepared(false);
91
+ }, [defaults, factors]);
92
+ useEffect(() => {
93
+ const surface = canvas.current, context = surface.getContext("2d");
94
+ if (!context) {
95
+ setUnavailable(true);
96
+ return;
97
+ }
98
+ const media = window.matchMedia("(prefers-reduced-motion: reduce)");
99
+ if (media.matches) {
100
+ settings.current.paused = true;
101
+ setPaused(true);
102
+ }
103
+ let frame = 0, idleFrame = 0, last = 0, visible = true, destroyed = false, width = 0, height = 0;
104
+ let palette = { ink: "#303832", sage: "#6f897c", clay: "#a67769", accent: "#785448", paper: "#eff2ed", damage: "#b82735" };
105
+ function draw() {
106
+ if (!world.current)
107
+ return;
108
+ paintSimulation(context, world.current, width, height, palette, {
109
+ dna: settings.current.dna, trails: settings.current.trails, selected: settings.current.selectedId,
110
+ });
111
+ const current = flow.current;
112
+ if (current && current.strength > .04) {
113
+ const x = current.x * width, y = current.y * height;
114
+ context.save();
115
+ context.globalAlpha = Math.min(.7, current.strength * .6);
116
+ context.strokeStyle = palette.clay;
117
+ context.lineWidth = 1.2;
118
+ context.beginPath();
119
+ context.arc(x, y, 8 + (1 - Math.min(1, current.strength)) * 20, 0, Math.PI * 2);
120
+ context.moveTo(x, y);
121
+ context.lineTo(x + current.dx * 90, y + current.dy * 90);
122
+ context.stroke();
123
+ context.restore();
124
+ }
125
+ const panel = popup.current;
126
+ const selectedCell = world.current.cells.find(cell => cell.id === settings.current.selectedId);
127
+ if (settings.current.popupOpen && panel && selectedCell && width && height) {
128
+ const anchor = getCellAnchor(selectedCell, width, height);
129
+ const panelWidth = panel.offsetWidth, panelHeight = panel.offsetHeight, gap = 18, edge = 8;
130
+ const placeLeft = anchor.x + gap + panelWidth > width - edge;
131
+ let left = Math.max(edge, Math.min(width - panelWidth - edge, placeLeft ? anchor.x - gap - panelWidth : anchor.x + gap));
132
+ let top = Math.max(edge, Math.min(height - panelHeight - edge, anchor.y - Math.min(panelHeight * .35, 90)));
133
+ let placement = placeLeft ? "left" : "right";
134
+ if (width < 440) {
135
+ const below = anchor.y + gap + panelHeight <= height - edge;
136
+ left = Math.max(edge, Math.min(width - panelWidth - edge, anchor.x - panelWidth / 2));
137
+ top = Math.max(edge, Math.min(height - panelHeight - edge, below ? anchor.y + gap : anchor.y - gap - panelHeight));
138
+ placement = below ? "below" : "above";
139
+ }
140
+ panel.style.transform = `translate(${left.toFixed(1)}px, ${top.toFixed(1)}px)`;
141
+ panel.style.visibility = "visible";
142
+ panel.dataset.placement = placement;
143
+ const line = popupConnector.current;
144
+ if (line) {
145
+ line.setAttribute("x1", String(anchor.x));
146
+ line.setAttribute("y1", String(anchor.y));
147
+ line.setAttribute("x2", String(Math.max(left, Math.min(left + panelWidth, anchor.x))));
148
+ line.setAttribute("y2", String(Math.max(top + 8, Math.min(top + panelHeight - 8, anchor.y))));
149
+ }
150
+ }
151
+ }
152
+ function stop() { cancelAnimationFrame(frame); cancelAnimationFrame(idleFrame); frame = idleFrame = last = 0; surface.dataset.running = "false"; }
153
+ function release() {
154
+ const held = pointer.current;
155
+ pointer.current = null;
156
+ flow.current = undefined;
157
+ if (held && surface.hasPointerCapture(held.id))
158
+ surface.releasePointerCapture(held.id);
159
+ }
160
+ function run() {
161
+ if (destroyed || frame || settings.current.paused || !visible || document.hidden)
162
+ return;
163
+ last = 0;
164
+ surface.dataset.running = "true";
165
+ frame = requestAnimationFrame(tick);
166
+ }
167
+ function tick(now) {
168
+ frame = 0;
169
+ if (settings.current.paused || !visible || document.hidden || destroyed) {
170
+ stop();
171
+ return;
172
+ }
173
+ const dt = Math.min(last ? (now - last) / 1000 : 1 / 60, 1 / 30) * (settings.current.slowMotion ? .3 : 1);
174
+ last = now;
175
+ if (world.current)
176
+ stepSimulation(world.current, dt, flow.current);
177
+ if (flow.current) {
178
+ flow.current.strength *= Math.exp(-dt * 4.5);
179
+ if (flow.current.strength < .015)
180
+ flow.current = undefined;
181
+ }
182
+ draw();
183
+ frame = requestAnimationFrame(tick);
184
+ }
185
+ function invalidate() {
186
+ if (destroyed)
187
+ return;
188
+ if (settings.current.paused || !visible || document.hidden) {
189
+ if (!idleFrame && visible && !document.hidden)
190
+ idleFrame = requestAnimationFrame(() => { idleFrame = 0; draw(); });
191
+ }
192
+ else
193
+ run();
194
+ }
195
+ function resize() {
196
+ if (!root.current)
197
+ return;
198
+ const computed = getComputedStyle(root.current);
199
+ const token = (name, fallback) => computed.getPropertyValue(name).trim() || fallback;
200
+ palette = { ink: computed.color, sage: token("--sl-sage", "#6f897c"), clay: token("--sl-clay", "#a67769"), accent: token("--sl-accent", "#785448"), paper: token("--sl-paper", "#eff2ed"), damage: token("--sl-damage", "#b82735") };
201
+ width = surface.clientWidth;
202
+ height = surface.clientHeight;
203
+ if (!width || !height)
204
+ return;
205
+ const dpr = Math.min(window.devicePixelRatio || 1, 1.75, Math.sqrt(1_300_000 / (width * height)));
206
+ surface.width = Math.round(width * dpr);
207
+ surface.height = Math.round(height * dpr);
208
+ context.setTransform(dpr, 0, 0, dpr, 0, 0);
209
+ release();
210
+ draw();
211
+ }
212
+ function visibility() { release(); if (document.hidden)
213
+ stop();
214
+ else {
215
+ draw();
216
+ run();
217
+ } }
218
+ function motionChange() {
219
+ if (media.matches) {
220
+ settings.current.paused = true;
221
+ setPaused(true);
222
+ release();
223
+ stop();
224
+ }
225
+ draw();
226
+ }
227
+ const resizeObserver = new ResizeObserver(resize);
228
+ resizeObserver.observe(surface);
229
+ const observer = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(entries => {
230
+ visible = entries[0]?.isIntersecting ?? true;
231
+ if (visible) {
232
+ draw();
233
+ run();
234
+ }
235
+ else {
236
+ release();
237
+ stop();
238
+ }
239
+ }, { rootMargin: "100px" });
240
+ observer?.observe(surface);
241
+ document.addEventListener("visibilitychange", visibility);
242
+ window.addEventListener("blur", release);
243
+ media.addEventListener("change", motionChange);
244
+ actions.current = { invalidate, release };
245
+ resize();
246
+ run();
247
+ return () => {
248
+ destroyed = true;
249
+ release();
250
+ stop();
251
+ resizeObserver.disconnect();
252
+ observer?.disconnect();
253
+ document.removeEventListener("visibilitychange", visibility);
254
+ window.removeEventListener("blur", release);
255
+ media.removeEventListener("change", motionChange);
256
+ actions.current = { invalidate: () => { }, release: () => { } };
257
+ };
258
+ }, []);
259
+ useEffect(() => { if (paused)
260
+ actions.current.release(); actions.current.invalidate(); }, [paused, slowMotion, trails, dna, selectedId, prepared, popupOpen, popupHeight]);
261
+ useEffect(() => {
262
+ if (!popupOpen || !popup.current)
263
+ return;
264
+ const measure = () => setPopupHeight(Math.ceil(popup.current?.offsetHeight ?? 0) + ((canvas.current?.clientWidth ?? 600) < 440 ? 160 : 24));
265
+ const observer = new ResizeObserver(measure);
266
+ observer.observe(popup.current);
267
+ measure();
268
+ function escape(event) {
269
+ if (event.key !== "Escape")
270
+ return;
271
+ event.preventDefault();
272
+ const restoreFocus = popup.current?.contains(document.activeElement);
273
+ setPopupOpen(false);
274
+ if (restoreFocus)
275
+ canvas.current?.focus({ preventScroll: true });
276
+ }
277
+ window.addEventListener("keydown", escape);
278
+ return () => { observer.disconnect(); window.removeEventListener("keydown", escape); };
279
+ }, [popupOpen]);
280
+ function changeFactor(id, value) {
281
+ setFactors(previous => ({ ...previous, [id]: value }));
282
+ setStatus("The combined settings prepare a new illustrated cohort.");
283
+ }
284
+ function choose(id, openPopup = false) {
285
+ setSelectedId(id);
286
+ setPopupOpen(openPopup);
287
+ const cell = world.current?.cells.find(item => item.id === id);
288
+ if (cell)
289
+ setStatus(`Cell ${id + 1}. ${movementLabel(cell)}. ${traitLabels(cell).join(". ")}.`);
290
+ }
291
+ function nextCell() {
292
+ const cells = world.current?.cells;
293
+ if (!cells?.length)
294
+ return;
295
+ const index = cells.findIndex(cell => cell.id === selectedId);
296
+ choose(cells[(index + 1) % cells.length].id, true);
297
+ }
298
+ function explore() {
299
+ if (popupOpen) {
300
+ setPopupOpen(false);
301
+ setStatus("Cell exploration is off. Click Explore to follow a swimmer.");
302
+ return;
303
+ }
304
+ const cells = world.current?.cells;
305
+ const target = selected ?? cells?.find(cell => cell.alive && cell.speed > 0) ?? cells?.[0];
306
+ if (!target)
307
+ return;
308
+ choose(target.id, true);
309
+ requestAnimationFrame(() => canvas.current?.focus({ preventScroll: true }));
310
+ }
311
+ function inspectDefect(id) {
312
+ const cells = world.current?.cells.filter(cell => cellMatchesDefect(cell, id)) ?? [];
313
+ if (!cells.length)
314
+ return;
315
+ const target = cells.find(cell => cell.example === id) ?? cells[0];
316
+ choose(target.id);
317
+ if (id === "dna-fragmentation")
318
+ setDna(true);
319
+ requestAnimationFrame(() => inspector.current?.scrollIntoView({ block: "start", behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" }));
320
+ }
321
+ function prepareExamples() {
322
+ publish(createDefectSimulation({ seed: defaults.seed, count: defaults.count }));
323
+ setPrepared(true);
324
+ setDna(true);
325
+ setSelectedId(0);
326
+ setStatus("Prepared defect examples. These developmental traits do not represent a specific lifestyle exposure.");
327
+ }
328
+ function reset() {
329
+ resetMotion.current = true;
330
+ setFactors({ ...defaults.factors });
331
+ setPrepared(false);
332
+ setDna(true);
333
+ setTrails(true);
334
+ setSlowMotion(false);
335
+ setStatus("The sample and controls returned to their initial settings.");
336
+ }
337
+ function restore() {
338
+ publish(newWorld(defaults.seed, defaults.count, factors, 1, defaults.teachingPopulation));
339
+ setPrepared(false);
340
+ setStatus("The sample now uses all current factor settings.");
341
+ }
342
+ function current(dx, dy) {
343
+ if (paused) {
344
+ setStatus("Resume the sample to create a current.");
345
+ return;
346
+ }
347
+ flow.current = { x: .5, y: .5, dx, dy, strength: 1.4 };
348
+ setStatus("The current moves the cells. Their biological traits stay the same.");
349
+ actions.current.invalidate();
350
+ }
351
+ function point(event) {
352
+ const bounds = event.currentTarget.getBoundingClientRect();
353
+ return { x: finite((event.clientX - bounds.left) / bounds.width, .5, 0, 1), y: finite((event.clientY - bounds.top) / bounds.height, .5, 0, 1) };
354
+ }
355
+ function pointerDown(event) {
356
+ if (!event.isPrimary || event.button !== 0)
357
+ return;
358
+ const position = point(event);
359
+ pointer.current = { id: event.pointerId, ...position, startX: event.clientX, startY: event.clientY, dragged: false, type: event.pointerType };
360
+ if (event.pointerType !== "touch")
361
+ event.currentTarget.setPointerCapture(event.pointerId);
362
+ }
363
+ function pointerMove(event) {
364
+ const held = pointer.current;
365
+ if (!held || held.id !== event.pointerId)
366
+ return;
367
+ const position = point(event);
368
+ held.dragged ||= Math.hypot(event.clientX - held.startX, event.clientY - held.startY) > 5;
369
+ if (held.type !== "touch" && !paused)
370
+ flow.current = { ...position, dx: finite((position.x - held.x) * 9, 0, -.35, .35), dy: finite((position.y - held.y) * 9, 0, -.35, .35), strength: 1.4 };
371
+ held.x = position.x;
372
+ held.y = position.y;
373
+ }
374
+ function pointerUp(event) {
375
+ const held = pointer.current;
376
+ if (!held || held.id !== event.pointerId)
377
+ return;
378
+ if (!held.dragged && world.current) {
379
+ const position = point(event), width = event.currentTarget.clientWidth, height = event.currentTarget.clientHeight;
380
+ const cell = hitTestCell(world.current, position.x * width, position.y * height, width, height, held.type === "touch" ? 11 : 6);
381
+ if (cell)
382
+ choose(cell.id, true);
383
+ else {
384
+ setSelectedId(null);
385
+ setPopupOpen(false);
386
+ setStatus("No cell is selected.");
387
+ }
388
+ }
389
+ const remaining = flow.current;
390
+ actions.current.release();
391
+ flow.current = remaining;
392
+ }
393
+ function keyboard(event) {
394
+ if (event.altKey || event.ctrlKey || event.metaKey)
395
+ return;
396
+ const directions = { ArrowLeft: [-.3, 0], ArrowRight: [.3, 0], ArrowUp: [0, -.3], ArrowDown: [0, .3] };
397
+ if (directions[event.key]) {
398
+ event.preventDefault();
399
+ current(...directions[event.key]);
400
+ }
401
+ else if (event.key === "Enter") {
402
+ event.preventDefault();
403
+ nextCell();
404
+ }
405
+ else if (event.key === "Escape") {
406
+ event.preventDefault();
407
+ setPopupOpen(false);
408
+ }
409
+ else if (event.key === " ") {
410
+ event.preventDefault();
411
+ setPaused(value => !value);
412
+ }
413
+ }
414
+ function controlColumn(side) {
415
+ return _jsx("aside", { className: `sl-controls sl-controls-${side}`, "aria-label": `${side === "left" ? "Exercise and habits" : "Body and chemicals"} factors`, children: groups.filter(group => group.side === side).map(group => _jsxs("fieldset", { className: "sl-factor-group", children: [_jsx("legend", { children: group.title }), group.ids.map(id => {
416
+ const factor = FACTORS.find(item => item.id === id), value = Math.round((factors[id] ?? 0) * 100);
417
+ const rangeId = `${prefix}-${id}`;
418
+ return _jsxs("div", { className: "sl-factor", children: [_jsxs("div", { className: "sl-factor-row", children: [_jsx("label", { htmlFor: rangeId, children: shortLabels[id] }), _jsx("input", { id: rangeId, "data-factor": id, type: "range", min: "0", max: "100", step: "1", value: value, "aria-label": shortLabels[id] === factor.title ? factor.title : `${shortLabels[id]}: ${factor.title}`, "aria-valuetext": `${value} of 100, relative illustrative setting`, onChange: event => changeFactor(id, Number(event.target.value) / 100) }), _jsx("output", { htmlFor: rangeId, children: value })] }), _jsxs("details", { className: "sl-factor-help", children: [_jsxs("summary", { children: [_jsxs("span", { children: ["About ", shortLabels[id].toLowerCase()] }), _jsx("svg", { viewBox: "0 0 16 16", "aria-hidden": "true", children: _jsx("path", { d: "m5 6 3 3 3-3" }) })] }), _jsx("p", { children: factor.summary }), _jsx("p", { children: factor.mechanism }), _jsx("p", { className: "sl-evidence", children: factor.evidence }), _jsx("p", { children: factor.limits }), _jsx("p", { className: "sl-help-timescale", children: factor.timescale }), _jsx("ul", { children: factor.sources.map(source => _jsx("li", { children: _jsx("a", { href: source.url, target: "_blank", rel: "noopener noreferrer", children: source.title }) }, source.url)) })] })] }, id);
419
+ })] }, group.title)) });
420
+ }
421
+ return _jsxs("div", { ref: root, className: `sperm-lab sl-lab sl-lab-v3 ${className}`.trim(), style: style, children: [_jsxs("div", { className: "sl-intro-line", children: [_jsxs("p", { children: [_jsx("strong", { children: "Change the factors. Watch one sample." }), " Each slider acts independently."] }), _jsx("span", { children: "All 12 settings use relative scales." })] }), _jsxs("div", { className: "sl-workbench", children: [controlColumn("left"), _jsxs("section", { className: "sl-field", "aria-label": "Live sperm sample", children: [_jsxs("div", { className: "sl-sample-bar", children: [_jsxs("div", { children: [_jsx("h2", { children: prepared ? "Prepared defect examples" : defaults.teachingPopulation ? "Illustrative sample" : "Live sample" }), _jsxs("span", { children: [metrics.total, " fictional cells"] })] }), _jsxs("div", { className: "sl-actions", children: [_jsx("button", { className: "sl-explore", type: "button", "aria-pressed": popupOpen, "aria-controls": `${prefix}-sample`, onClick: explore, children: "Explore" }), _jsx("button", { type: "button", "aria-pressed": paused, onClick: () => setPaused(value => !value), children: paused ? "Resume" : "Pause" }), _jsx("button", { type: "button", onClick: reset, children: "Reset sample" })] })] }), _jsxs("div", { className: "sl-concentration", children: [_jsx("span", { id: `${prefix}-concentration`, children: "Concentration" }), _jsxs("output", { "data-concentration": metrics.total, "aria-labelledby": `${prefix}-concentration`, children: [metrics.total, " cells / model field"] }), _jsx("small", { children: "Synthetic model count. No clinical units." })] }), defaults.teachingPopulation && !prepared && _jsx("p", { className: "sl-teaching-population", children: "The teaching sample includes common defect examples. Counts do not show their frequency in people." }), unavailable && _jsx("p", { role: "status", children: "Canvas is unavailable. The sample counts, cell inspector, and factor explanations remain available." }), _jsxs("div", { id: `${prefix}-sample`, className: "sl-canvas-wrap", "data-popup": popupOpen && Boolean(selected), style: { "--sl-popup-min-height": `${popupHeight}px` }, children: [_jsx("canvas", { ref: canvas, tabIndex: 0, role: "group", "aria-label": "Interactive sperm sample. Use Explore to follow a swimmer. Drag to stir. Click a cell for details. Arrow keys create currents. Enter selects the next cell and opens its details. Escape closes details. Space pauses.", "aria-describedby": `${prefix}-help`, onPointerDown: pointerDown, onPointerMove: pointerMove, onPointerUp: pointerUp, onPointerCancel: () => actions.current.release(), onLostPointerCapture: () => { pointer.current = null; }, onKeyDown: keyboard, onContextMenu: event => event.preventDefault(), children: "The sample needs canvas support. Use the cell inspector and model counts for a text alternative." }), popupOpen && selected && _jsxs(_Fragment, { children: [_jsx("svg", { className: "sl-popup-connector", "aria-hidden": "true", children: _jsx("line", { ref: popupConnector }) }), _jsxs("div", { ref: popup, className: "sl-cell-popup", role: "dialog", "aria-modal": "false", "aria-labelledby": `${prefix}-popup-title`, "data-cell-popup": "true", "data-cell-id": selected.id, children: [_jsxs("header", { children: [_jsxs("h3", { id: `${prefix}-popup-title`, children: ["Cell ", selected.id + 1] }), _jsx("button", { ref: popupClose, className: "sl-popup-close", type: "button", "aria-label": "Close cell details", onClick: () => { setPopupOpen(false); canvas.current?.focus({ preventScroll: true }); }, children: _jsx("svg", { viewBox: "0 0 20 20", "aria-hidden": "true", children: _jsx("path", { d: "m5 5 10 10M15 5 5 15" }) }) })] }), _jsx(CellPopupDetails, { cell: selected, dna: dna }), _jsx("button", { className: "sl-popup-anatomy", type: "button", onClick: () => { setPopupOpen(false); requestAnimationFrame(() => inspector.current?.scrollIntoView({ block: "start", behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" })); }, children: "Full anatomy" })] })] })] }), _jsx("p", { id: `${prefix}-help`, className: "sl-canvas-help", children: "Use Explore to follow a swimmer. Click or tap another cell to switch. Drag to stir the sample." }), _jsxs("div", { className: "sl-sample-tools", children: [_jsx("button", { type: "button", onClick: () => current(.3, .1), disabled: paused, children: "Create a current" }), _jsx("button", { type: "button", onClick: () => nextCell(), children: "Next swimmer" }), _jsx("button", { type: "button", onClick: prepareExamples, children: "Inspect defect examples" })] }), _jsxs("div", { className: "sl-display", children: [_jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: dna, onChange: event => setDna(event.target.checked) }), "DNA overlay"] }), _jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: trails, onChange: event => setTrails(event.target.checked) }), "Trails"] }), _jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: slowMotion, onChange: event => setSlowMotion(event.target.checked) }), "Slow motion"] })] }), _jsx("p", { className: "sl-overlay-note", children: "Red marks illustrated abnormalities. Disconnected red pieces inside the nucleus show schematic DNA fragmentation. The overlay is not ordinary microscopy." }), _jsx("p", { className: "sl-model-note", children: "Sliders prepare an illustrative later cohort. Counts do not predict personal fertility." }), prepared && _jsxs("div", { className: "sl-prepared-note", children: [_jsx("p", { children: "These examples contain head, tail, midpiece, and DNA traits. They do not show the effects of a specific exposure." }), _jsx("button", { type: "button", onClick: restore, children: "Return to current settings" })] })] }), controlColumn("right"), _jsxs("section", { className: "sl-readouts", "aria-labelledby": `${prefix}-counts-title`, children: [_jsx("h2", { id: `${prefix}-counts-title`, children: "In this sample" }), _jsx("dl", { children: [
422
+ ["Cells", metrics.total], ["Active motion", metrics.motile], ["Forward", metrics.progressive], ["Slow", metrics.slow],
423
+ ["Nonprogressive", metrics.nonprogressive], ["Still", metrics.immotile], ["Alive", metrics.alive],
424
+ ].map(([label, value]) => _jsxs("div", { children: [_jsx("dt", { children: label }), _jsx("dd", { children: value })] }, label)) })] }), _jsxs("section", { className: "sl-catalog", "aria-labelledby": `${prefix}-catalog-title`, children: [_jsxs("header", { children: [_jsx("h2", { id: `${prefix}-catalog-title`, children: "Common examples" }), _jsx("p", { children: "These curated examples explain separate traits. Their frequency is not clinical prevalence. Select an example to inspect its cell." })] }), _jsx("div", { className: "sl-defect-catalog", children: DEFECT_CATALOG.map(defect => {
425
+ const example = world.current?.cells.find(cell => cell.example === defect.id && cellMatchesDefect(cell, defect.id))
426
+ ?? world.current?.cells.find(cell => cellMatchesDefect(cell, defect.id));
427
+ return _jsxs("button", { type: "button", "data-defect": defect.id, "data-count": defectCounts[defect.id], disabled: defectCounts[defect.id] === 0, onClick: () => inspectDefect(defect.id), "aria-describedby": `${prefix}-defect-${defect.id}`, children: [_jsx(SpecimenThumbnail, { id: defect.id, cell: example }), _jsxs("span", { className: "sl-catalog-copy", children: [_jsx("strong", { children: defect.title }), _jsx("span", { id: `${prefix}-defect-${defect.id}`, children: defect.description })] }), _jsx("b", { children: defect.id === "dna-fragmentation" && !dna ? "Hidden" : defectCounts[defect.id] })] }, defect.id);
428
+ }) }), _jsx("p", { className: "sl-legend-help", children: "Traits can overlap. Counts identify cells in this illustrative sample, not causes or diagnoses." })] }), _jsxs("section", { ref: inspector, className: "sl-inspector", "aria-labelledby": `${prefix}-inspect-title`, children: [_jsxs("header", { children: [_jsx("h2", { id: `${prefix}-inspect-title`, children: "Inside one cell" }), _jsx("p", { children: selected ? `Cell ${selected.id + 1}` : "Click a cell, or select a trait count." })] }), _jsxs("div", { className: "sl-inspector-content", children: [_jsx(Anatomy, { cell: selected, dna: dna }), _jsx("div", { className: "sl-cell-facts", children: selected ? _jsxs(_Fragment, { children: [_jsxs("dl", { children: [_jsxs("div", { children: [_jsx("dt", { children: "Movement" }), _jsx("dd", { children: movementLabel(selected) })] }), _jsxs("div", { children: [_jsx("dt", { children: "Relative speed" }), _jsxs("dd", { children: [selected.alive ? Math.round(selected.speed / .07 * 100) : 0, "/100"] })] }), _jsxs("div", { children: [_jsx("dt", { children: "Vitality" }), _jsx("dd", { children: selected.alive ? "Alive" : "Nonviable" })] }), _jsxs("div", { children: [_jsx("dt", { children: "Head" }), _jsx("dd", { children: selected.headCount === 2 ? "Two heads" : selected.headShape === "typical" ? "One typical head" : `${selected.headShape} head` })] }), _jsxs("div", { children: [_jsx("dt", { children: "Tail" }), _jsx("dd", { children: selected.tailCount === 0 ? "Absent tail" : selected.tailCount > 1 ? `${selected.tailCount} tails` : selected.tailShape === "typical" ? "One typical tail" : `${selected.tailShape} tail` })] }), _jsxs("div", { children: [_jsx("dt", { children: "Midpiece" }), _jsx("dd", { children: selected.midpieceShape !== "typical" ? `${selected.midpieceShape} midpiece` : selected.midpieceDamage ? "Damage in the model" : "No modeled damage" })] }), _jsxs("div", { children: [_jsx("dt", { children: "DNA" }), _jsx("dd", { children: dna ? selected.dnaDamage ? `${selected.dnaFragmentation} illustrated fragments` : "No modeled fragmentation" : "Hidden. Use DNA overlay." })] })] }), _jsx("p", { children: "Shape, vitality, movement, and DNA are separate traits. An immotile cell can remain alive." })] }) : _jsxs("p", { children: ["The head contains tightly packed DNA. The thin section behind the head is the midpiece. It contains mitochondria. Glycolysis along the tail also supplies energy.", _jsx("br", {}), "Select a trait to compare the head, tail, midpiece, DNA, and movement of one cell."] }) })] })] })] }), _jsxs("p", { className: "sl-anatomy-sources", children: ["Anatomy and energy: ", ANATOMY_SOURCES.map((source, index) => _jsxs("span", { children: [index > 0 ? ", " : "", _jsx("a", { href: source.url, target: "_blank", rel: "noopener noreferrer", children: source.title })] }, source.url))] }), _jsx("p", { className: "sl-status", role: "status", "aria-live": "polite", children: status || (active.length ? "The sample uses the initial factor settings. Change several sliders to explore their combined effects." : "All factors start at zero. Change several sliders to explore one combined example.") }), _jsxs("section", { className: "sl-mechanisms", "aria-labelledby": `${prefix}-mechanism-title`, children: [_jsx("h2", { id: `${prefix}-mechanism-title`, children: "What acts on this sample?" }), prepared ? _jsx("p", { children: "The prepared sample contains separate teaching examples. Its traits are not a prediction from the current factor settings." }) : active.length ? _jsx("ul", { children: active.map(factor => _jsxs("li", { children: [_jsx("strong", { children: factor.title }), _jsx("span", { children: factor.mechanism }), _jsxs("small", { children: [factor.evidence, ". ", factor.evidence === "Established mechanism" ? "The sample counts remain illustrative." : "Association does not prove cause."] })] }, factor.id)) }) : _jsx("p", { children: "No exposure scenario is active. The sample still contains authored variation in movement, shape, and DNA." }), _jsx("p", { className: "sl-final-note", children: "The model explains possible mechanisms. It does not predict fertility, diagnose a condition, or recommend a treatment." })] })] });
429
+ }
430
+ function movementLabel(cell) {
431
+ return !cell.alive || cell.speed === 0 ? "Still" : !cell.progressive ? "Nonprogressive movement" : isSlow(cell) ? "Slow forward movement" : "Forward movement";
432
+ }
433
+ function CellPopupDetails({ cell, dna }) {
434
+ const traits = getCellDefects(cell)
435
+ .filter(trait => dna || trait.id !== "dna-fragmentation")
436
+ .map(trait => ({ id: String(trait.id), title: trait.title, description: trait.description }));
437
+ if (cell.headShape === "irregular" || (cell.headDefect && cell.headCount === 1 && cell.headShape === "typical")) {
438
+ traits.push({ id: "irregular-head", title: "Irregular head", description: "The modeled head outline differs from a typical oval." });
439
+ }
440
+ if (cell.tailShape === "irregular" || (cell.tailDefect && cell.tailCount === 1 && cell.tailShape === "typical")) {
441
+ traits.push({ id: "irregular-tail", title: "Irregular tail", description: "The modeled tail has an irregular bend." });
442
+ }
443
+ if (!cell.alive)
444
+ traits.push({ id: "nonviable", title: "Nonviable", description: "This cell is not alive in the model. Vitality differs from movement." });
445
+ const head = cell.headCount > 1 ? `${cell.headCount} heads` : cell.headShape === "typical" ? "One typical head" : `${cell.headShape} head`;
446
+ const tail = cell.tailCount === 0 ? "Absent" : cell.tailCount > 1 ? `${cell.tailCount} tails` : cell.tailShape === "typical" ? "One typical tail" : `${cell.tailShape} tail`;
447
+ const midpiece = `${cell.midpieceShape === "typical" ? "Typical outline" : `${cell.midpieceShape} outline`}${cell.midpieceDamage ? ", modeled injury" : ", no modeled injury"}`;
448
+ return _jsxs("div", { className: "sl-popup-details", children: [_jsxs("dl", { children: [_jsxs("div", { children: [_jsx("dt", { children: "Movement" }), _jsx("dd", { children: movementLabel(cell) })] }), _jsxs("div", { children: [_jsx("dt", { children: "Vitality" }), _jsx("dd", { children: cell.alive ? "Alive" : "Nonviable" })] }), _jsxs("div", { children: [_jsx("dt", { children: "Head" }), _jsx("dd", { children: head })] }), _jsxs("div", { children: [_jsx("dt", { children: "Tail" }), _jsx("dd", { children: tail })] }), _jsxs("div", { children: [_jsx("dt", { children: "Midpiece" }), _jsx("dd", { children: midpiece })] }), _jsxs("div", { children: [_jsx("dt", { children: "DNA" }), _jsx("dd", { children: dna ? cell.dnaDamage ? `${cell.dnaFragmentation} illustrated fragments` : "No modeled fragmentation" : "Hidden. DNA overlay is off." })] }), _jsxs("div", { children: [_jsx("dt", { children: "Relative speed" }), _jsxs("dd", { children: [cell.alive ? Math.round(cell.speed / .07 * 100) : 0, "/100"] })] })] }), traits.length ? _jsx("ul", { className: "sl-popup-traits", children: traits.map(trait => _jsxs("li", { children: [_jsx("strong", { children: trait.title }), _jsx("span", { children: trait.description })] }, trait.id)) })
449
+ : _jsx("p", { className: "sl-popup-healthy", children: dna ? "No modeled defects." : "No other modeled defects. DNA is hidden." })] });
450
+ }
451
+ function traitLabels(cell) {
452
+ const labels = [cell.alive ? "Alive in the model" : "Nonviable in the model"];
453
+ if (cell.headCount === 2)
454
+ labels.push("Two heads");
455
+ else if (cell.headShape !== "typical")
456
+ labels.push(`${cell.headShape} head`);
457
+ if (cell.tailCount === 0)
458
+ labels.push("Absent tail");
459
+ else if (cell.tailCount > 1)
460
+ labels.push(`${cell.tailCount} tails`);
461
+ else if (cell.tailShape !== "typical")
462
+ labels.push(`${cell.tailShape} tail`);
463
+ if (cell.midpieceShape !== "typical")
464
+ labels.push(`${cell.midpieceShape} midpiece`);
465
+ if (cell.midpieceDamage)
466
+ labels.push("Midpiece damage");
467
+ return labels;
468
+ }
469
+ function phenotype(cell, id) {
470
+ return {
471
+ headCount: cell?.headCount ?? (id === "double-head" ? 2 : 1),
472
+ tailCount: cell?.tailCount ?? (id === "absent-tail" ? 0 : id === "double-tail" ? 2 : id === "triple-tail" ? 3 : 1),
473
+ headShape: cell?.headShape ?? (id === "small-head" ? "small" : id === "large-head" ? "large" : id === "tapered-head" ? "tapered" : id === "round-head" ? "round" : "typical"),
474
+ tailShape: cell?.tailShape ?? (id === "bent-tail" ? "bent" : id === "coiled-tail" ? "coiled" : id === "short-tail" ? "short" : id === "absent-tail" ? "absent" : "typical"),
475
+ midpieceShape: cell?.midpieceShape ?? (id === "bent-midpiece" ? "bent" : id === "thick-midpiece" ? "thick" : "typical"),
476
+ midpieceDamage: cell?.midpieceDamage ?? id === "midpiece-damage",
477
+ dnaDamage: cell?.dnaDamage ?? id === "dna-fragmentation",
478
+ dnaFragmentation: cell?.dnaFragmentation ?? (id === "dna-fragmentation" ? 4 : 0),
479
+ };
480
+ }
481
+ function SpecimenThumbnail({ cell, id }) {
482
+ if (id === "dna-fragmentation")
483
+ return _jsx("svg", { className: "sl-specimen-thumbnail sl-dna-thumbnail", viewBox: "335 150 130 90", "aria-hidden": "true", children: _jsx(HeadInset, { model: phenotype(cell, id), dna: true, label: false }) });
484
+ return _jsx("svg", { className: "sl-specimen-thumbnail", viewBox: "24 65 485 100", "aria-hidden": "true", children: _jsx(SpecimenDrawing, { model: phenotype(cell, id), dna: true }) });
485
+ }
486
+ function Anatomy({ cell, dna }) {
487
+ const model = phenotype(cell);
488
+ return _jsxs("svg", { className: "sl-anatomy", viewBox: "0 0 520 260", role: "img", "aria-label": `Enlarged cell: ${model.headCount} head${model.headCount === 2 ? "s" : ""}, ${model.tailCount} tail${model.tailCount === 1 ? "" : "s"}, ${model.headShape} head shape, ${model.tailShape} tail shape, ${model.midpieceShape} midpiece.${dna && model.dnaDamage ? ` DNA fragmentation with ${model.dnaFragmentation} illustrated red pieces. The DNA close-up shows these separate pieces inside the nucleus.` : ""}`, children: [_jsx("g", { className: "sl-anatomy-lines", children: _jsx("path", { d: "M60 96V36H27M109 111V171H161M359 108V36H420" }) }), _jsx("text", { x: "22", y: "24", children: "Head \u00B7 packed DNA" }), _jsx("text", { x: "128", y: "191", children: "Midpiece \u00B7 mitochondria" }), _jsx("text", { x: "377", y: "24", children: "Tail" }), _jsx(SpecimenDrawing, { model: model, dna: dna }), _jsx(HeadInset, { model: model, dna: dna, label: true }), _jsx("text", { className: "sl-diagram-caption", x: "22", y: "257", children: "Enlarged schematic. Red marks illustrated abnormalities and DNA fragmentation." })] });
489
+ }
490
+ function HeadInset({ model, dna, label }) {
491
+ return _jsxs("g", { className: "sl-head-inset", children: [_jsxs("g", { transform: "translate(400 190)", children: [_jsx("ellipse", { className: "sl-anatomy-head", cx: "0", cy: "0", rx: "46", ry: "31" }), _jsx("path", { className: "sl-acrosomal-cap", d: "M-8-28C-55-28-55 28-8 28C-23 12-23-12-8-28Z" }), _jsx("g", { transform: "scale(2.5) translate(-65 0)", children: _jsx(CompactNucleus, { cy: 0, damaged: Boolean(dna && model.dnaDamage), pieces: model.dnaFragmentation }) })] }), label && _jsx("text", { className: "sl-head-inset-label", x: "322", y: "241", children: "DNA \u00B7 enlarged schematic" })] });
492
+ }
493
+ function SpecimenDrawing({ model, dna }) {
494
+ const tailPaths = {
495
+ typical: "M125 111C174 111 196 114 230 109S281 97 316 108S368 127 405 113S461 96 499 110",
496
+ bent: "M125 111C164 111 189 108 214 111L244 139C259 151 273 124 300 111S356 109 389 117S453 99 499 111",
497
+ coiled: "M125 111C157 111 180 109 206 113C252 119 282 151 257 159C228 168 209 128 234 112C262 95 293 121 277 140C260 159 234 140 245 124C255 108 276 124 266 135",
498
+ short: "M125 111C155 111 179 124 210 113S244 103 262 112",
499
+ absent: "",
500
+ irregular: "M125 111C164 111 192 108 221 111C238 114 245 131 259 122C279 99 300 95 325 108S381 129 413 111S466 97 499 110",
501
+ };
502
+ const abnormalTail = model.tailShape !== "typical" || model.tailCount !== 1;
503
+ const midpieceBent = model.midpieceShape === "bent";
504
+ const midpiecePath = midpieceBent ? "M74 111Q100 102 112 119L127 112" : "M74 111H127";
505
+ return _jsxs(_Fragment, { children: [model.tailCount > 0 && _jsx("path", { className: `sl-anatomy-tail${abnormalTail ? " sl-trait-damage" : ""}`, d: tailPaths[model.tailShape] }), model.tailCount >= 2 && _jsx("path", { className: "sl-anatomy-tail sl-trait-damage", d: "M123 113C166 122 195 146 231 140S283 119 320 140S383 155 418 140S467 124 499 139" }), model.tailCount === 3 && _jsx("path", { className: "sl-anatomy-tail sl-trait-damage", d: "M123 109C164 99 195 81 232 88S283 100 320 83S383 68 418 86S467 101 499 82" }), model.tailCount > 0 && _jsx("path", { className: `sl-anatomy-midpiece-smooth${model.midpieceShape !== "typical" ? " sl-trait-damage" : ""}`, strokeWidth: model.midpieceShape === "thick" ? 10 : 6.5, d: midpiecePath }), model.tailCount > 0 && model.midpieceDamage && _jsx("path", { className: "sl-anatomy-midpiece-injury", d: midpieceBent ? "M102 113 114 118" : "M100 111H114" }), model.headCount === 2 && _jsx("g", { className: "sl-anatomy-fork", children: _jsx("path", { d: "M88 111 81 96M88 111 81 125" }) }), Array.from({ length: model.headCount }, (_, index) => {
506
+ const cy = model.headCount === 2 ? index === 0 ? 96 : 125 : 111;
507
+ const shape = model.headShape;
508
+ const sx = shape === "small" ? .74 : shape === "large" ? 1.32 : shape === "round" ? .78 : shape === "tapered" ? 1.13 : 1;
509
+ const sy = shape === "small" ? .72 : shape === "large" ? 1.28 : shape === "round" ? 1.3 : shape === "tapered" ? .64 : 1;
510
+ const irregular = String(shape) === "irregular";
511
+ const outline = shape === "round" ? `M85 ${cy}C84 ${cy - 17} 48 ${cy - 17} 45 ${cy}C48 ${cy + 17} 84 ${cy + 17} 85 ${cy}Z` : `M85 ${cy}C82 ${cy - 7} 74 ${cy - (irregular ? 17 : 12)} 62 ${cy - 12}C40 ${cy - 13} 40 ${cy + 13} 62 ${cy + 12}C74 ${cy + (irregular ? 8 : 12)} 82 ${cy + 7} 85 ${cy}Z`;
512
+ return _jsxs("g", { transform: `translate(65 ${cy}) scale(${sx} ${sy}) translate(-65 ${-cy})`, children: [_jsx("path", { className: `sl-anatomy-head${shape !== "typical" || model.headCount === 2 || model.tailCount === 0 ? " sl-trait-damage" : ""}`, d: outline }), _jsx("path", { className: "sl-acrosomal-cap", d: `M60 ${cy - 10}C43 ${cy - 12} 43 ${cy + 12} 60 ${cy + 10}C55 ${cy + 5} 55 ${cy - 5} 60 ${cy - 10}Z` }), _jsx(CompactNucleus, { cy: cy, damaged: Boolean(dna && model.dnaDamage), pieces: model.dnaFragmentation })] }, index);
513
+ })] });
514
+ }
515
+ function CompactNucleus({ cy, damaged, pieces }) {
516
+ const fragmentPaths = [
517
+ `M55 ${cy - 4}q2-2 5 0`, `M64 ${cy - 5}q2 2 5 0`, `M72 ${cy - 3}q2-1 4 1`,
518
+ `M56 ${cy + 3}q3 2 5 0`, `M65 ${cy + 2}q2-2 5 0`, `M70 ${cy + 6}q3-1 5-3`,
519
+ ];
520
+ return _jsxs("g", { className: "sl-compact-nucleus", children: [_jsx("ellipse", { className: "sl-nucleus-mass", cx: "65", cy: cy, rx: "13.5", ry: "8.2" }), !damaged && Array.from({ length: 17 }, (_, index) => {
521
+ const x = 65 + Math.sin(index * 2.4) * 10.5, y = cy + Math.cos(index * 1.8) * 5.8;
522
+ return _jsx("ellipse", { className: "sl-chromatin-speck", cx: x, cy: y, rx: ".8", ry: ".6" }, index);
523
+ }), damaged && _jsx("g", { className: "sl-chromatin-fragments", children: fragmentPaths.slice(0, Math.max(3, pieces)).map(path => _jsx("path", { d: path }, path)) })] });
524
+ }