diff --git a/README.md b/README.md index a340956..1c3d8d9 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ sentence traces back to a cited field. No language model decides or phrases a ve | Framework | Next.js 15 (App Router) · React 19 | | Language | TypeScript, strict | | Styling | Tailwind CSS v4 | -| Helix | Hand-drawn SVG, depth-sorted and CSS-animated | +| 3D | three.js, loaded only when a 3D view is on screen; every shape is generated in code, with no model or image files. The hand-drawn SVG helix stands in until WebGL is ready, and wherever it is unavailable | | Icons | lucide-react | | Evidence | NCBI ClinVar and PubMed via E-utilities | @@ -179,6 +179,7 @@ variant, classification, frequency and catalogue reading is public and cited. | **Current evidence** | Live NCBI ClinVar, one batched E-utilities request per sync | `src/lib/clinvar.ts` | | **Offline fallback** | A saved ClinVar snapshot, verified identical to a live read (15 of 15 records) when it was imported | `src/data/evidence-snapshot.json` | | **Regional evidence** | gnomAD v4 allele counts for the Middle Eastern genetic ancestry group and all samples, for every variant; and, for three variants, the reading of the Catalogue for Transmission Genetics in Arabs (CTGA, Centre for Arab Genomic Studies), quoted and attributed | `src/data/regional.ts` | +| **Genome map** | GRCh38 chromosome lengths (UCSC hg38) and centromeres (the p11/q11 boundary in the hg38 cytoBand table), fixed properties of the assembly. Each variant stands at the GRCh38 position its ClinVar record gives; a test checks every one against ClinVar's own cytogenetic band | `src/lib/genome.ts` | With the bundled snapshot, `npm run verify:data` computes: **11 reclassifications** (10 against the January 2023 release, 1 against the modelled hospital report), **1 consensus conflict**, **2 regional @@ -333,11 +334,13 @@ One synthetic patient from historical result to documented review, then how a pa evaluate it. The same path is linked step by step at the foot of `/pilot`. 1. **Home**. A historical synthetic patient, VP-10247: BRCA1 c.5056C>T, reported in 2023 as - uncertain significance, which is what ClinVar said in its January 2023 release. + uncertain significance, which is what ClinVar said in its January 2023 release. Each bead on + the helix is a monitored finding, coloured by what its evidence did: drag to turn it, and hover + or tab to a bead to see the change (arrow keys move between them). 2. **Run evidence sync**. Reads current ClinVar live (or the verified snapshot offline), compares - classifications, walks the 26 synthetic records and compares regional evidence. It ends on the - highest-priority change: uncertain significance → likely pathogenic, four synthetic patients, - one clinical review case. + classifications, walks the 26 synthetic records and compares regional evidence; a ring scans + along the helix as it runs. It ends on the highest-priority change: uncertain significance → + likely pathogenic, four synthetic patients, one clinical review case. 3. **Open the case**. *What changed?* shows ClinVar's reading then and now, the archived checkpoints, how the four records were matched, and what limits the evidence. 4. **Take ownership and decide**. Open the review, write a rationale, choose *Refer to genetics*, @@ -350,6 +353,10 @@ evaluate it. The same path is linked step by step at the foot of `/pilot`. `/oversight`, and download the governance package from `/governance`. 8. **Audit trail**. Every action above, with who, which role and when, exportable as CSV or JSON. +`/variants` stands every monitored variant on a to-scale map of the 24 chromosomes; the filters +and the list are linked to it both ways. Each variant's page shows its own chromosome, with the +band and position. + Global search is on `Ctrl`/`Cmd` + `K` and covers record IDs, gene symbols, HGVS strings, ClinVar accessions and case numbers. @@ -370,8 +377,9 @@ account that owns the zone first. To enable AI drafting, add the key as a Worker ## Credits -The helix on the home screen is drawn by VariantPulse itself. An earlier 3D model, licensed for -non-commercial use only, has been removed from the repository. +The helix and the genome map are generated in code by VariantPulse itself: no model, texture or +image file is shipped or fetched. An earlier 3D model, licensed for non-commercial use only, has +been removed from the repository. --- diff --git a/package-lock.json b/package-lock.json index f038b1f..4fa2b4b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,8 @@ "react": "19.1.0", "react-dom": "19.1.0", "server-only": "^0.0.1", - "tailwind-merge": "^3.7.0" + "tailwind-merge": "^3.7.0", + "three": "^0.186.1" }, "devDependencies": { "@eslint/eslintrc": "^3", @@ -23,6 +24,7 @@ "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", + "@types/three": "^0.186.0", "esbuild": "^0.28.2", "eslint": "^9", "eslint-config-next": "15.5.26", @@ -1273,6 +1275,13 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/@dotenvx/dotenvx": { "version": "1.31.0", "resolved": "https://registry.npmjs.org/@dotenvx/dotenvx/-/dotenvx-1.31.0.tgz", @@ -4622,6 +4631,13 @@ "integrity": "sha512-RbwvSJQsuN9TB04AQbGULYfOGE/RnSFk/FLQ5b0NmDf5Kx2q/lABZbHQPKCO1vZ6Fiwkplu+yb9pGdLy1iGseQ==", "license": "MIT" }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "dev": true, + "license": "MIT" + }, "node_modules/@tybys/wasm-util": { "version": "0.10.4", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", @@ -4711,6 +4727,35 @@ "@types/react": "^19.3.0" } }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.186.0", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.186.0.tgz", + "integrity": "sha512-mxYSBpDC+D0pLfSP6sW4WZTcT+nrtmZcimMqnVmy36Hte3XpeYSrvgg4TRdaM1GemGog1AWzI5qL2VoIfMXbJQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": ">=0.5.17", + "fflate": "~0.8.3", + "meshoptimizer": "~1.1.1" + } + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "dev": true, + "license": "MIT" + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.70.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.70.1.tgz", @@ -7412,6 +7457,13 @@ "reusify": "^1.0.4" } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -9136,6 +9188,13 @@ "node": ">= 8" } }, + "node_modules/meshoptimizer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz", + "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==", + "dev": true, + "license": "MIT" + }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", @@ -10929,6 +10988,12 @@ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "license": "MIT" }, + "node_modules/three": { + "version": "0.186.1", + "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz", + "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==", + "license": "MIT" + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", diff --git a/package.json b/package.json index 8ca750f..48b9f6d 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,8 @@ "react": "19.1.0", "react-dom": "19.1.0", "server-only": "^0.0.1", - "tailwind-merge": "^3.7.0" + "tailwind-merge": "^3.7.0", + "three": "^0.186.1" }, "devDependencies": { "@eslint/eslintrc": "^3", @@ -35,6 +36,7 @@ "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", + "@types/three": "^0.186.0", "esbuild": "^0.28.2", "eslint": "^9", "eslint-config-next": "15.5.26", diff --git a/src/app/page.tsx b/src/app/page.tsx index 8967b1e..3485d6f 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -17,7 +17,7 @@ import { Users, } from "lucide-react"; -import { HeroHelix } from "@/components/hero-helix"; +import { EvidenceHelix } from "@/components/evidence-helix"; import { ImpactPanel } from "@/components/impact-panel"; import { evidenceModeMeta } from "@/components/story/mode"; import { SyncButton } from "@/components/sync"; @@ -31,7 +31,7 @@ import { cn, formatDate } from "@/lib/utils"; import { useWorkspace } from "@/state/workspace"; export default function HomePage() { - const { analysis, scanMs } = useWorkspace(); + const { analysis, scanMs, sync } = useWorkspace(); // The headline change the story tests pin down, else the top-ranked case, so // the page always shows a change the dataset really holds. const lead = @@ -39,7 +39,7 @@ export default function HomePage() { return (
- + +

The same DNA. @@ -108,12 +116,17 @@ function Hero({ lead }: { lead: VariantAssessment | undefined }) {

- + - {/* Narrower screens show this card at the foot of the sidebar instead. */} + {/* Only the widest screens have room for this card beside the helix. */} @@ -305,8 +318,15 @@ function RealExample({ lead }: { lead: VariantAssessment }) { note={`Reported ${formatDate(variant.recordedOn)}`} />
- - + {/* The knowledge-change moment: vermilion, and the one pulse on the page. */} + + + + + Science diff --git a/src/app/variants/[key]/page.tsx b/src/app/variants/[key]/page.tsx index efc592e..77837c5 100644 --- a/src/app/variants/[key]/page.tsx +++ b/src/app/variants/[key]/page.tsx @@ -5,6 +5,7 @@ import { notFound, useParams } from "next/navigation"; import { ArrowRight, ExternalLink } from "lucide-react"; import { ThenNow } from "@/components/domain"; +import { GenomeMap } from "@/components/genome-map"; import { PageHeader, PageShell } from "@/components/page-header"; import { EvidenceComparison, @@ -27,6 +28,7 @@ import { SectionHeading, } from "@/components/ui"; import { CHANGE_TYPES } from "@/lib/classification"; +import { formatPosition, locusOf } from "@/lib/genome"; import { caseStage } from "@/lib/workflow"; import { WhatChanged } from "@/components/what-changed"; import { composeRecommendation } from "@/lib/narrative"; @@ -42,6 +44,7 @@ export default function VariantPage() { const { variant, evidence, changeType, impactedPatients, caseId } = assessment; const byKey = new Map(analysis.assessments.map((a) => [a.variant.key, a])); + const locus = locusOf(evidence); return ( @@ -130,6 +133,22 @@ export default function VariantPage() {
+ {locus ? ( + + + + + ) : null} {caseId ? : null} diff --git a/src/app/variants/page.tsx b/src/app/variants/page.tsx index 8e6c138..6d0a3e1 100644 --- a/src/app/variants/page.tsx +++ b/src/app/variants/page.tsx @@ -4,35 +4,34 @@ import * as React from "react"; import { Search } from "lucide-react"; import { VariantRow } from "@/components/domain"; +import { GenomeMap } from "@/components/genome-map"; import { PageHeader, PageShell } from "@/components/page-header"; import { SyncButton } from "@/components/sync"; import { Card, EmptyState } from "@/components/ui"; import { CHANGE_TYPES, type ChangeType } from "@/lib/classification"; +import { locusOf } from "@/lib/genome"; +import { SIGNALS, SIGNAL_OF, type Signal } from "@/lib/signal"; import { cn } from "@/lib/utils"; import { useWorkspace } from "@/state/workspace"; type Filter = "all" | "changed" | "conflict" | "stable"; -const FILTERS: { id: Filter; label: string; matches: (type: ChangeType) => boolean }[] = [ - { id: "all", label: "All", matches: () => true }, - { - id: "changed", - label: "Reclassified", - matches: (t) => - t === "CLASSIFICATION_DRIFT" || t === "EVIDENCE_STRENGTHENED" || t === "EVIDENCE_WEAKENED", - }, - { - id: "conflict", - label: "Conflict or regional", - matches: (t) => t === "REGIONAL_CONFLICT" || t === "CONSENSUS_CONFLICT", - }, - { id: "stable", label: "Unchanged", matches: (t) => t === "NO_MATERIAL_CHANGE" }, +/** The filters are the map's three signals, so a filter and its colour always agree. */ +const bySignal = (signal: Signal) => (type: ChangeType) => SIGNAL_OF[type] === signal; + +const FILTERS: { id: Filter; label: string; signal: Signal | null; matches: (type: ChangeType) => boolean }[] = [ + { id: "all", label: "All", signal: null, matches: () => true }, + { id: "changed", label: SIGNALS.changed.label, signal: "changed", matches: bySignal("changed") }, + { id: "conflict", label: SIGNALS.review.label, signal: "review", matches: bySignal("review") }, + { id: "stable", label: SIGNALS.quiet.label, signal: "quiet", matches: bySignal("quiet") }, ]; export default function VariantsPage() { const { analysis } = useWorkspace(); const [filter, setFilter] = React.useState("all"); const [query, setQuery] = React.useState(""); + // The variant under the pointer, in the list or on the map; each highlights it in the other. + const [activeKey, setActiveKey] = React.useState(null); const rows = React.useMemo(() => { const active = FILTERS.find((f) => f.id === filter)!; @@ -49,6 +48,16 @@ export default function VariantsPage() { ); }, [analysis, filter, query]); + const visibleKeys = React.useMemo(() => new Set(rows.map((a) => a.variant.key)), [rows]); + // The map can only draw what the evidence places on GRCh38; say so if that is not everything. + const mapLabel = React.useMemo(() => { + const loci = analysis.assessments.map((a) => locusOf(a.evidence)).filter((l) => l !== null); + const total = analysis.assessments.length; + const chromosomes = new Set(loci.map((l) => l.chromosome.name)).size; + const drawn = loci.length === total ? `${total}` : `${loci.length} of ${total}`; + return `Genome map: ${drawn} monitored variants on ${chromosomes} chromosome${chromosomes === 1 ? "" : "s"}, each at its GRCh38 position from ClinVar. The list below holds every variant.`; + }, [analysis]); + const counts = React.useMemo( () => Object.fromEntries( @@ -68,7 +77,10 @@ export default function VariantsPage() {
-
+
{FILTERS.map((option) => ( @@ -101,6 +116,16 @@ export default function VariantsPage() {
+ +
Variant On record → current @@ -117,7 +142,14 @@ export default function VariantsPage() { ) : (
{rows.map((assessment) => ( - + + setActiveKey((key) => (hovering ? assessment.variant.key : key === assessment.variant.key ? null : key)) + } + /> ))}
)} diff --git a/src/components/domain.tsx b/src/components/domain.tsx index 65ebd5a..b706d22 100644 --- a/src/components/domain.tsx +++ b/src/components/domain.tsx @@ -328,13 +328,29 @@ export function EvidenceAlert({ /* -- Compact row used in dense lists --------------------------------------- */ -export function VariantRow({ assessment }: { assessment: VariantAssessment }) { +export function VariantRow({ + assessment, + active = false, + onHoverChange, +}: { + assessment: VariantAssessment; + /** Highlighted from elsewhere, such as the genome map. */ + active?: boolean; + onHoverChange?: (hovering: boolean) => void; +}) { const { variant, changeType, impactedRecordCount, priority, caseId } = assessment; return ( onHoverChange?.(true)} + onPointerLeave={() => onHoverChange?.(false)} + onFocus={() => onHoverChange?.(true)} + onBlur={() => onHoverChange?.(false)} + className={cn( + "flex items-center gap-4 px-5 py-3.5 transition-colors hover:bg-surface-2", + active && "vp-selected hover:bg-selected-bg", + )} > ({ + key: assessment.variant.key, + assessment, + signal: SIGNAL_OF[assessment.changeType], + locus: locusOf(assessment.evidence), + })) + .sort((a, b) => { + if (a.locus && b.locus) return compareLoci(a.locus, b.locus); + // Anything the evidence cannot place goes last, in its original order. + return a.locus ? -1 : b.locus ? 1 : 0; + }) + .map(({ locus, ...finding }) => ({ ...finding, band: locus?.band ?? null })); +} + +const TIP_WIDTH = 262; +const TIP_GAP = 16; + +export function EvidenceHelix({ + assessments, + leadKey, + scanning, + className, +}: { + assessments: VariantAssessment[]; + leadKey: string | null; + scanning: boolean; + className?: string; +}) { + const findings = React.useMemo(() => orderFindings(assessments), [assessments]); + const [status, setStatus] = React.useState<"loading" | "ready" | "failed">("loading"); + const [dragging, setDragging] = React.useState(false); + const [hoverKey, setHoverKey] = React.useState(null); + const [focusKey, setFocusKey] = React.useState(null); + const [roving, setRoving] = React.useState(0); + + const activeKey = dragging ? null : (hoverKey ?? focusKey); + const active = findings.find((f) => f.key === activeKey) ?? null; + + const stageRef = React.useRef(null); + const interactiveRef = React.useRef(null); + const tipRef = React.useRef(null); + const controllerRef = React.useRef(null); + const spotRefs = React.useRef(new Map()); + const points = React.useRef(new Map()); + const activeRef = React.useRef(null); + activeRef.current = activeKey; + // Hidden below the md breakpoint: nothing is loaded until the column is on screen. + const displayed = useDisplayed(interactiveRef); + + const sceneFindings = React.useMemo( + () => findings.map(({ key, signal }) => ({ key, signal })), + [findings], + ); + const latest = React.useRef({ sceneFindings, leadKey }); + latest.current = { sceneFindings, leadKey }; + + /** Lays the tooltip beside its finding, inside the stage, flipping below near the top. */ + const placeTip = React.useCallback(() => { + const tip = tipRef.current; + const stage = stageRef.current; + const key = activeRef.current; + const point = key ? points.current.get(key) : undefined; + if (!tip || !stage || !point) return; + const width = stage.clientWidth; + const height = tip.offsetHeight; + const x = Math.min(Math.max(point.x - TIP_WIDTH / 2, -12), width - TIP_WIDTH + 12); + const above = point.y - height - TIP_GAP; + // Above the finding when it fits inside the stage, otherwise below it. + const y = above < 0 ? point.y + TIP_GAP : above; + tip.style.transform = `translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0)`; + }, []); + + const placeSpot = (key: string, element: HTMLAnchorElement) => { + const point = points.current.get(key); + if (!point) return; + element.style.transform = `translate3d(${point.x}px, ${point.y}px, 0)`; + // Round the back of the helix a nucleotide is hidden, so it cannot be picked there. + element.dataset.front = String(point.front); + }; + + // Mount the scene once; later changes reach it through the controller. + React.useEffect(() => { + const stageHost = stageRef.current; + const interactive = interactiveRef.current; + if (!displayed || !stageHost || !interactive) return; + + let cancelled = false; + let controller: HelixController | null = null; + + import("./three/helix-scene").then( + ({ mountHelix }) => { + if (cancelled) return; + try { + controller = mountHelix(stageHost, interactive, { + findings: latest.current.sceneFindings, + leadKey: latest.current.leadKey, + onProject(projected) { + for (const point of projected) { + points.current.set(point.key, point); + const spot = spotRefs.current.get(point.key); + if (spot) placeSpot(point.key, spot); + } + placeTip(); + }, + onReady: () => setStatus("ready"), + onLost: () => { + // Nothing is drawn again after a lost context: free it and keep the illustration. + controller?.dispose(); + controller = null; + controllerRef.current = null; + setStatus("failed"); + }, + onDragChange: setDragging, + }); + controllerRef.current = controller; + } catch { + setStatus("failed"); + } + }, + () => { + if (!cancelled) setStatus("failed"); + }, + ); + + return () => { + cancelled = true; + controller?.dispose(); + controllerRef.current = null; + }; + }, [displayed, placeTip]); + + React.useEffect(() => { + controllerRef.current?.setFindings(sceneFindings, leadKey); + }, [sceneFindings, leadKey]); + + React.useEffect(() => { + controllerRef.current?.setActive(activeKey, hoverKey === null && focusKey !== null); + }, [activeKey, hoverKey, focusKey]); + + React.useEffect(() => { + controllerRef.current?.setScanning(scanning); + }, [scanning, status]); + + React.useLayoutEffect(() => { + placeTip(); + }, [activeKey, placeTip]); + + const onKeyDown = (event: React.KeyboardEvent) => { + const moves: Record = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }; + let next: number | null = null; + if (event.key in moves) next = (roving + moves[event.key] + findings.length) % findings.length; + if (event.key === "Home") next = 0; + if (event.key === "End") next = findings.length - 1; + if (next === null) return; + event.preventDefault(); + setRoving(next); + spotRefs.current.get(findings[next].key)?.focus(); + }; + + const counts = SIGNAL_ORDER.map((signal) => ({ + signal, + count: findings.filter((f) => f.signal === signal).length, + })).filter((c) => c.count > 0); + + const ready = status === "ready"; + + return ( +
+
+ {/* The illustration holds the column until the 3D helix has drawn its first frame. */} + + + {/* A soft blush behind the form, as on the illustration. */} +
+
+ + {ready ? ( +
+ {findings.map((finding, index) => { + const { variant, recordedCode, currentCode } = finding.assessment; + return ( + { + if (element) { + spotRefs.current.set(finding.key, element); + placeSpot(finding.key, element); + } else { + spotRefs.current.delete(finding.key); + } + }} + tabIndex={index === roving ? 0 : -1} + draggable={false} + aria-label={`${variant.gene} ${variant.hgvsCoding}: ${meta(recordedCode).label} on record, ${meta(currentCode).label} now. ${SIGNALS[finding.signal].label}.`} + onPointerEnter={() => setHoverKey(finding.key)} + onPointerLeave={() => setHoverKey((key) => (key === finding.key ? null : key))} + onFocus={(event) => { + setRoving(index); + // Only keyboard focus turns the helix; a press that starts a drag also focuses the link. + if (event.currentTarget.matches(":focus-visible")) setFocusKey(finding.key); + }} + onBlur={() => setFocusKey((key) => (key === finding.key ? null : key))} + className="absolute left-0 top-0 -ml-3 -mt-3 h-6 w-6 cursor-pointer rounded-full focus-visible:outline-offset-0 data-[front=false]:pointer-events-none" + /> + ); + })} +
+ ) : null} + + {active ? ( +
+

+ + {active.assessment.variant.gene}{" "} + {active.assessment.variant.hgvsCoding} + + {active.band ? ( + {active.band} + ) : null} +

+ + + + + + + + {CHANGE_TYPES[active.assessment.changeType].label} + · + + {active.assessment.impactedRecordCount} record + {active.assessment.impactedRecordCount === 1 ? "" : "s"} + + +
+ ) : null} +
+ +
+ + {counts.map(({ signal, count }) => ( + + + {count} + {SIGNALS[signal].label.toLowerCase()} + + ))} + + + Genome order, not to scale · drag to turn + +
+
+ ); +} diff --git a/src/components/genome-map.tsx b/src/components/genome-map.tsx new file mode 100644 index 0000000..db22a7f --- /dev/null +++ b/src/components/genome-map.tsx @@ -0,0 +1,370 @@ +"use client"; + +/** + * Where the monitored variants sit on the genome, drawn in three dimensions. + * + * The drawing is three.js (see `three/genome-scene`), loaded only in the + * browser. Chromosome lengths are the GRCh38 sizes and every marker stands at + * the position ClinVar gives for that variant, so the figure is a map, not an + * illustration. Where WebGL is unavailable the figure is simply left out: every + * fact it shows is also in the text and tables around it. + * + * The markers are links for pointer users. They are hidden from assistive + * technology and the tab order because the list or page beside the map already + * carries the same links; the figure describes itself in one sentence instead. + */ + +import * as React from "react"; +import Link from "next/link"; + +import { ClassificationBadge } from "@/components/ui"; +import { useDisplayed } from "@/components/use-displayed"; +import type { VariantAssessment } from "@/lib/analysis"; +import { CHANGE_TYPES } from "@/lib/classification"; +import { GRCH38, formatPosition, locusOf, type Locus } from "@/lib/genome"; +import { SIGNALS, SIGNAL_OF, SIGNAL_ORDER, type Signal } from "@/lib/signal"; +import { cn } from "@/lib/utils"; + +import type { GenomeController, GenomeLabel, GenomePoint } from "./three/genome-scene"; + +interface Placed { + key: string; + assessment: VariantAssessment; + signal: Signal; + locus: Locus; +} + +const TIP_WIDTH = 262; + +export function GenomeMap({ + assessments, + mode = "karyotype", + focusKey = null, + visibleKeys = null, + activeKey = null, + onActiveChange, + label, + className, + stageClassName, +}: { + assessments: VariantAssessment[]; + mode?: "karyotype" | "locus"; + /** Locus mode: the variant the figure is about. */ + focusKey?: string | null; + /** Keys the page's filter keeps; null keeps every variant. */ + visibleKeys?: ReadonlySet | null; + /** A variant highlighted from outside the map, such as a hovered table row. */ + activeKey?: string | null; + onActiveChange?: (key: string | null) => void; + /** One sentence describing the figure for assistive technology. */ + label: string; + className?: string; + stageClassName?: string; +}) { + const placed = React.useMemo(() => { + const list: Placed[] = []; + for (const assessment of assessments) { + const locus = locusOf(assessment.evidence); + if (locus) list.push({ key: assessment.variant.key, assessment, signal: SIGNAL_OF[assessment.changeType], locus }); + } + return list; + }, [assessments]); + + const shownPlaced = React.useMemo(() => { + if (mode !== "locus") return placed; + const chromosome = placed.find((p) => p.key === focusKey)?.locus.chromosome.name; + return placed.filter((p) => p.locus.chromosome.name === chromosome); + }, [placed, mode, focusKey]); + + const [status, setStatus] = React.useState<"loading" | "ready" | "failed">("loading"); + const [dragging, setDragging] = React.useState(false); + const [hoverKey, setHoverKey] = React.useState(null); + + const stageRef = React.useRef(null); + const interactiveRef = React.useRef(null); + const tipRef = React.useRef(null); + const focusTagRef = React.useRef(null); + const controllerRef = React.useRef(null); + const spotRefs = React.useRef(new Map()); + const labelRefs = React.useRef(new Map()); + const points = React.useRef(new Map()); + const labelsAt = React.useRef(new Map()); + const hoverRef = React.useRef(null); + hoverRef.current = hoverKey; + const displayed = useDisplayed(interactiveRef); + + // Remount only when what is drawn changes: which variants, and their signals. + const signature = shownPlaced.map((p) => `${p.key}:${p.signal}`).join("|"); + const latest = React.useRef({ shownPlaced, mode, focusKey, visibleKeys, activeKey }); + latest.current = { shownPlaced, mode, focusKey, visibleKeys, activeKey }; + + const placeTip = React.useCallback(() => { + const tip = tipRef.current; + const stage = stageRef.current; + const key = hoverRef.current; + const point = key ? points.current.get(key) : undefined; + if (!tip || !stage || !point) return; + const width = stage.clientWidth; + const x = Math.min(Math.max(point.x - TIP_WIDTH / 2, 4), width - TIP_WIDTH - 4); + const above = point.y - tip.offsetHeight - 14; + const y = above < 0 ? point.y + 14 : above; + tip.style.transform = `translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0)`; + }, []); + + const placeSpot = (key: string, element: HTMLElement) => { + const point = points.current.get(key); + if (!point) return; + element.style.transform = `translate3d(${point.x}px, ${point.y}px, 0)`; + element.dataset.live = String(point.front && point.shown); + }; + + const placeFocusTag = () => { + const tag = focusTagRef.current; + const point = latest.current.focusKey ? points.current.get(latest.current.focusKey) : undefined; + if (tag && point) tag.style.transform = `translate3d(${Math.round(point.x)}px, ${Math.round(point.y)}px, 0)`; + }; + + const placeLabel = (id: string, element: HTMLElement) => { + const at = labelsAt.current.get(id); + if (!at) return; + element.style.transform = `translate3d(${Math.round(at.x)}px, ${Math.round(at.y)}px, 0)`; + element.dataset.shown = String(at.shown); + }; + + React.useEffect(() => { + const stageHost = stageRef.current; + const interactive = interactiveRef.current; + if (!displayed || !stageHost || !interactive) return; + + let cancelled = false; + let controller: GenomeController | null = null; + setStatus("loading"); + + import("./three/genome-scene").then( + ({ mountGenome }) => { + if (cancelled) return; + const current = latest.current; + try { + controller = mountGenome(stageHost, interactive, { + findings: current.shownPlaced.map((p) => ({ + key: p.key, + signal: p.signal, + chromosome: p.locus.chromosome.name, + position: p.locus.position, + })), + mode: current.mode, + focusKey: current.focusKey, + onProject(projected, labels) { + for (const point of projected) { + points.current.set(point.key, point); + const spot = spotRefs.current.get(point.key); + if (spot) placeSpot(point.key, spot); + } + for (const at of labels) { + labelsAt.current.set(at.id, at); + const element = labelRefs.current.get(at.id); + if (element) placeLabel(at.id, element); + } + placeFocusTag(); + placeTip(); + }, + onReady: () => setStatus("ready"), + onLost: () => { + // Nothing is drawn again after a lost context: free it and leave the figure out. + controller?.dispose(); + controller = null; + controllerRef.current = null; + setStatus("failed"); + }, + onDragChange: setDragging, + }); + controller.setVisible(current.visibleKeys); + controller.setActive(current.activeKey); + controllerRef.current = controller; + } catch { + setStatus("failed"); + } + }, + () => { + if (!cancelled) setStatus("failed"); + }, + ); + + return () => { + cancelled = true; + controller?.dispose(); + controllerRef.current = null; + }; + }, [displayed, signature, mode, focusKey, placeTip]); + + React.useEffect(() => { + controllerRef.current?.setVisible(visibleKeys); + }, [visibleKeys]); + + React.useEffect(() => { + controllerRef.current?.setActive(hoverKey ?? activeKey); + }, [hoverKey, activeKey]); + + React.useLayoutEffect(() => { + placeTip(); + }, [hoverKey, placeTip]); + + const hover = (key: string | null) => { + setHoverKey(key); + onActiveChange?.(key); + }; + + const hovered = dragging ? null : (shownPlaced.find((p) => p.key === hoverKey) ?? null); + const focus = shownPlaced.find((p) => p.key === focusKey) ?? null; + const carriers = new Set(shownPlaced.map((p) => p.locus.chromosome.name)); + const labels = + mode === "locus" + ? [ + { id: "p", text: "p arm", carrier: false }, + { id: "q", text: "q arm", carrier: false }, + ] + : GRCH38.map((c) => ({ id: c.name, text: c.name, carrier: carriers.has(c.name) })); + + if (status === "failed") return null; + + const counts = SIGNAL_ORDER.map((signal) => ({ + signal, + count: shownPlaced.filter((p) => p.signal === signal).length, + })).filter((c) => c.count > 0); + + return ( +
+
+
+ {/* The drawing speaks for itself in one sentence; the links laid over it are + a pointer convenience that the list beside the map already provides. */} +
+ + {status === "ready" ? ( +
+ {labels.map((item) => ( + { + if (element) { + labelRefs.current.set(item.id, element); + placeLabel(item.id, element); + } else { + labelRefs.current.delete(item.id); + } + }} + className={cn( + "pointer-events-none absolute left-0 top-0 -translate-x-1/2 -translate-y-1/2 whitespace-nowrap text-[10.5px] vp-num data-[shown=false]:hidden", + item.carrier ? "font-semibold text-ink-2" : "text-faint", + )} + > + {item.text} + + ))} + + {shownPlaced.map((item) => ( + { + if (element) { + spotRefs.current.set(item.key, element); + placeSpot(item.key, element); + } else { + spotRefs.current.delete(item.key); + } + }} + onPointerEnter={() => hover(item.key)} + onPointerLeave={() => hover(hoverRef.current === item.key ? null : hoverRef.current)} + className="absolute left-0 top-0 -ml-2.5 -mt-2.5 h-5 w-5 cursor-pointer rounded-full data-[live=false]:pointer-events-none" + /> + ))} +
+ ) : null} + + {mode === "locus" && status === "ready" && focus ? ( + // The band and position of the variant the page is about, standing over its marker. + { + focusTagRef.current = element; + placeFocusTag(); + }} + aria-hidden + className="pointer-events-none absolute left-0 top-0 z-10 whitespace-nowrap" + > + + {focus.locus.band ?? `chr${focus.locus.chromosome.name}`} + + + ) : null} + + {hovered ? ( +
+

+ + {hovered.assessment.variant.gene}{" "} + {hovered.assessment.variant.hgvsCoding} + + {hovered.locus.band} +

+ + + → + + + + + {CHANGE_TYPES[hovered.assessment.changeType].label} + + + GRCh38 chr{hovered.locus.chromosome.name}:{formatPosition(hovered.locus.position)} + +
+ ) : null} +
+ +
+ {counts.map(({ signal, count }) => ( + + + {count} + {SIGNALS[signal].label.toLowerCase()} + + ))} + + GRCh38 positions from ClinVar · lengths to scale · drag to turn + +
+
+ ); +} diff --git a/src/components/three/genome-scene.ts b/src/components/three/genome-scene.ts new file mode 100644 index 0000000..b566bf2 --- /dev/null +++ b/src/components/three/genome-scene.ts @@ -0,0 +1,607 @@ +/** + * The genome map: chromosomes drawn to scale, with every monitored variant + * pinned where ClinVar places it. + * + * Two arrangements share one scene: + * - `karyotype` stands all 24 chromosomes side by side, centromeres aligned as + * a cytogeneticist lays them out, on a shallow arc so the row has depth. On a + * narrow view only the chromosomes that carry a monitored variant are kept, + * so the figure stays legible on a phone. + * - `locus` lays one chromosome on its side, p arm to the left, to show where + * a single variant sits. + * + * Each variant is a lollipop, as in a mutation plot: a stalk out of the + * chromosome at its GRCh38 position, a head coloured by its signal, and a ring + * round the chromosome marking the locus. Variants a few megabases apart share + * a ring and fan out, since at this scale they are the same place. + * + * Lengths and centromeres come from `lib/genome`; positions from the evidence. + * Nothing on the figure is placed by hand. + * + * Dragging turns the figure within a range that keeps it readable; the pointer + * tilts it slightly, and at rest it sways a little so it reads as solid. All of + * that stops under reduced motion except dragging. + */ + +import { + BufferAttribute, + Color, + CylinderGeometry, + DirectionalLight, + Fog, + Group, + HemisphereLight, + LatheGeometry, + Mesh, + MeshBasicMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + SphereGeometry, + Sprite, + SpriteMaterial, + TorusGeometry, + Vector2, + Vector3, +} from "three"; + +import { GRCH38, type Chromosome } from "@/lib/genome"; +import { SIGNALS, type Signal } from "@/lib/signal"; + +import { approach, attachPointer, createStage, softTexture, toScreen } from "./stage"; + +/** Scene units for the longest chromosome, chr1. */ +const TALLEST = 4.2; +const SCALE = TALLEST / GRCH38[0].length; +const RADIUS = 0.15; +const SPACING = 0.62; +/** Radius of the arc the row stands on; smaller bends it more. */ +const ARC = 15; +/** Loci closer than this (scene units) share a ring and fan out. */ +const CLUSTER = 0.14; +/** How far a stalk leans off the line of sight, so it reads as a stalk and not a dot. */ +const STALK_LEAN = { karyotype: 0.7, locus: 0.95 } as const; +/** Stalk length, shorter in the karyotype so a marker never reaches the next chromosome. */ +const STALK_LENGTH = { karyotype: 0.3, locus: 0.3 } as const; +/** Angle between neighbouring stalks when several variants share a locus. */ +const FAN = 0.5; +const HEAD = 0.072; +const FOV = 22; +/** Below this width (CSS px) the karyotype keeps only chromosomes with variants. */ +const COMPACT_BELOW = 560; + +const YAW_LIMIT = 0.55; +const PITCH_LIMIT = 0.28; +const SWAY = 0.05; + +const BONE = "#F7F4ED"; +const PORCELAIN_P = "#F4EEE6"; +const PORCELAIN_Q = "#EAE1D6"; +const CENTROMERE = "#C98C9C"; +const CARRIER = "#EDC9D2"; +const RING = "#7A263A"; + +export interface GenomeFinding { + key: string; + signal: Signal; + chromosome: string; + position: number; +} + +export interface GenomePoint { + key: string; + x: number; + y: number; + front: boolean; + shown: boolean; +} + +export interface GenomeLabel { + id: string; + text: string; + x: number; + y: number; + shown: boolean; + /** Whether a monitored variant sits on this chromosome. */ + carrier: boolean; +} + +export interface GenomeOptions { + findings: GenomeFinding[]; + mode: "karyotype" | "locus"; + /** Locus mode: the variant the figure is about. */ + focusKey: string | null; + onProject(points: GenomePoint[], labels: GenomeLabel[]): void; + onReady(): void; + onLost(): void; + onDragChange(dragging: boolean): void; +} + +export interface GenomeController { + /** Keys the current filter keeps; null keeps everything. */ + setVisible(keys: ReadonlySet | null): void; + setActive(key: string | null): void; + dispose(): void; +} + +/** The lathe profile of one chromosome: rounded ends and a constriction at the centromere. */ +function chromosomeGeometry(chromosome: Chromosome): LatheGeometry { + const top = chromosome.centromere * SCALE; + const bottom = -(chromosome.length - chromosome.centromere) * SCALE; + const length = top - bottom; + const cap = Math.min(RADIUS, length / 3); + const points: Vector2[] = []; + + const pinch = (y: number) => 1 - 0.45 * Math.exp(-((y / (RADIUS * 0.85)) ** 2)); + const add = (y: number, r: number) => points.push(new Vector2(Math.max(r * pinch(y), 1e-4), y)); + + const CAP_STEPS = 10; + for (let k = 0; k <= CAP_STEPS; k += 1) { + const angle = (k / CAP_STEPS) * (Math.PI / 2); + add(bottom + cap * (1 - Math.cos(angle)), RADIUS * Math.sin(angle)); + } + const body = Math.max(2, Math.ceil((length - cap * 2) / 0.035)); + for (let k = 1; k < body; k += 1) add(bottom + cap + ((length - cap * 2) * k) / body, RADIUS); + for (let k = CAP_STEPS; k >= 0; k -= 1) { + const angle = (k / CAP_STEPS) * (Math.PI / 2); + add(top - cap * (1 - Math.cos(angle)), RADIUS * Math.sin(angle)); + } + + const geometry = new LatheGeometry(points, 40); + + // p arm, q arm and the centromere each get their own tone. + const position = geometry.getAttribute("position"); + const colours = new Float32Array(position.count * 3); + const p = new Color(PORCELAIN_P); + const q = new Color(PORCELAIN_Q); + const cen = new Color(CENTROMERE); + const tone = new Color(); + for (let i = 0; i < position.count; i += 1) { + const y = position.getY(i); + tone.copy(y > 0 ? p : q).lerp(cen, Math.exp(-((y / (RADIUS * 0.7)) ** 2)) * 0.85); + tone.toArray(colours, i * 3); + } + geometry.setAttribute("color", new BufferAttribute(colours, 3)); + return geometry; +} + +interface ChromosomeView { + chromosome: Chromosome; + group: Group; + material: MeshPhysicalMaterial; + carrier: boolean; + /** 0…1, eased: how strongly it is tinted as holding shown variants. */ + tint: number; + label: Vector3; +} + +interface FindingView { + finding: GenomeFinding; + chromosome: ChromosomeView; + head: Mesh; + stalk: Mesh; + halo: Sprite; + ring: Mesh | null; + /** Height of the locus on its chromosome, in the chromosome's own frame. */ + y: number; + /** Eased 0…1 values. */ + shown: number; + emphasis: number; +} + +export function mountGenome(stageHost: HTMLElement, interactive: HTMLElement, options: GenomeOptions): GenomeController { + const stage = createStage(stageHost, { fov: FOV, onLost: options.onLost }); + const { scene, camera } = stage; + const locus = options.mode === "locus"; + + scene.fog = new Fog(BONE, 10, 40); + scene.environmentIntensity = 0.55; + scene.add(new HemisphereLight("#FFFAF4", "#E4D6CC", 1.1)); + const key = new DirectionalLight("#FFF2E6", 1.7); + key.position.set(-4, 6, 9); + scene.add(key); + const rim = new DirectionalLight("#F0BAC6", 0.9); + rim.position.set(5, 2, -6); + scene.add(rim); + + // root: pointer and drag · figure: the arrangement (laid on its side in locus mode) + const root = new Group(); + const figure = new Group(); + root.add(figure); + scene.add(root); + + const focus = options.findings.find((f) => f.key === options.focusKey) ?? null; + const carriers = new Set(options.findings.map((f) => f.chromosome)); + + /* -- Chromosomes -- */ + + const chromosomes = new Map(); + const drawn = locus + ? GRCH38.filter((c) => c.name === (focus?.chromosome ?? options.findings[0]?.chromosome)) + : GRCH38; + + for (const chromosome of drawn) { + const material = new MeshPhysicalMaterial({ + vertexColors: true, + roughness: 0.48, + clearcoat: 0.45, + clearcoatRoughness: 0.35, + sheen: 0.35, + sheenColor: new Color("#F6D8DF"), + }); + const group = new Group(); + group.add(new Mesh(chromosomeGeometry(chromosome), material)); + figure.add(group); + const bottom = -(chromosome.length - chromosome.centromere) * SCALE; + chromosomes.set(chromosome.name, { + chromosome, + group, + material, + carrier: carriers.has(chromosome.name), + tint: 0, + label: new Vector3(0, bottom - 0.3, 0), + }); + } + + if (locus) figure.rotation.z = Math.PI / 2; + + // Locus mode names the two arms beneath the laid-down chromosome (local -x is down once turned). + const armLabels: { id: string; text: string; group: Group; at: Vector3 }[] = []; + if (locus) { + const only = [...chromosomes.values()][0]; + if (only) { + const { length, centromere } = only.chromosome; + const below = -(RADIUS + 0.11); + armLabels.push( + { id: "p", text: "p arm", group: only.group, at: new Vector3(below, (centromere * SCALE) / 2, 0) }, + { id: "q", text: "q arm", group: only.group, at: new Vector3(below, (-(length - centromere) * SCALE) / 2, 0) }, + ); + } + } + + /* -- Variants -- */ + + const headGeometry = new SphereGeometry(HEAD, 20, 14); + const stalkGeometry = new CylinderGeometry(0.011, 0.011, 1, 6); + stalkGeometry.translate(0, 0.5, 0); + stalkGeometry.rotateX(Math.PI / 2); + const ringTexture = softTexture({ ring: true }); + + const findings: FindingView[] = []; + const byChromosome = new Map(); + for (const finding of options.findings) { + if (!chromosomes.has(finding.chromosome)) continue; + byChromosome.set(finding.chromosome, [...(byChromosome.get(finding.chromosome) ?? []), finding]); + } + + for (const [name, list] of byChromosome) { + const view = chromosomes.get(name)!; + const sorted = [...list].sort((a, b) => a.position - b.position); + // Group loci that sit on the same spot at this scale. + const clusters: GenomeFinding[][] = []; + for (const finding of sorted) { + const last = clusters.at(-1); + const y = (view.chromosome.centromere - finding.position) * SCALE; + if (last && Math.abs((view.chromosome.centromere - last[0].position) * SCALE - y) < CLUSTER) last.push(finding); + else clusters.push([finding]); + } + + for (const cluster of clusters) { + const y = (view.chromosome.centromere - cluster[0].position) * SCALE; + const ring = new Mesh( + new TorusGeometry(RADIUS * 1.04, 0.014, 8, 48), + new MeshStandardMaterial({ color: RING, roughness: 0.4, transparent: true }), + ); + ring.rotation.x = Math.PI / 2; + ring.position.y = y; + view.group.add(ring); + + cluster.forEach((finding, index) => { + // Out toward the reader and leaning to one side (upward once the chromosome is + // laid down in locus mode). Variants sharing a locus fan along the chromosome. + const lean = STALK_LEAN[options.mode]; + // Sorted by position, so the first sits nearest the p end, which is +y. + const elevation = ((cluster.length - 1) / 2 - index) * FAN; + const direction = new Vector3( + Math.sin(lean) * Math.cos(elevation), + Math.sin(elevation), + Math.cos(lean) * Math.cos(elevation), + ); + const length = STALK_LENGTH[options.mode]; + const colour = new Color(SIGNALS[finding.signal].color); + + const stalk = new Mesh( + stalkGeometry, + new MeshBasicMaterial({ color: "#B98E99", transparent: true }), + ); + stalk.position.copy(direction).multiplyScalar(RADIUS); + stalk.position.y += y; + stalk.lookAt(stalk.position.clone().add(direction)); + stalk.scale.set(1, 1, length); + + const head = new Mesh( + headGeometry, + new MeshStandardMaterial({ + color: colour, + emissive: colour, + emissiveIntensity: finding.signal === "quiet" ? 0.08 : 0.3, + roughness: 0.3, + transparent: true, + }), + ); + head.position.copy(direction).multiplyScalar(RADIUS + length); + head.position.y += y; + + const halo = new Sprite( + new SpriteMaterial({ map: ringTexture, color: colour, transparent: true, opacity: 0, depthTest: false, depthWrite: false }), + ); + halo.renderOrder = 10; + halo.position.copy(head.position); + halo.visible = false; + + view.group.add(stalk, head, halo); + findings.push({ + finding, + chromosome: view, + head, + stalk, + halo, + ring: index === 0 ? ring : null, + y, + shown: 1, + emphasis: 0, + }); + }); + } + } + + /* -- Layout -- */ + + let compact = false; + + const layout = () => { + if (locus) { + const only = [...chromosomes.values()][0]; + if (only) { + // Centre the chromosome's length on the origin before it is laid down. + const { length, centromere } = only.chromosome; + only.group.position.y = (length / 2 - centromere) * SCALE; + } + return; + } + const row = [...chromosomes.values()].filter((c) => !compact || c.carrier); + const middle = (row.length - 1) / 2; + const spacing = compact ? SPACING * 1.25 : SPACING; + for (const view of chromosomes.values()) view.group.visible = false; + row.forEach((view, index) => { + const x = (index - middle) * spacing; + view.group.visible = true; + view.group.position.set(x, 0, -(x * x) / (2 * ARC)); + // Each chromosome turns to face the middle of the arc. + view.group.rotation.y = -Math.atan2(x, ARC); + }); + }; + + /* -- Framing -- */ + + let framed = false; + + const frame = (width: number, height: number) => { + const nextCompact = !locus && width < COMPACT_BELOW; + if (nextCompact !== compact || !framed) { + compact = nextCompact; + layout(); + } + framed = true; + + const aspect = width / height; + const tan = Math.tan((FOV * Math.PI) / 360); + // Frame the rest pose, then give back the reader's turn and tilt. + const pose = root.rotation.clone(); + root.rotation.set(0, 0, 0); + root.updateMatrixWorld(true); + + // Frame every visible chromosome end, head and label anchor. + const corners: Vector3[] = []; + const p = new Vector3(); + for (const view of chromosomes.values()) { + if (!view.group.visible) continue; + const { length, centromere } = view.chromosome; + for (const y of [centromere * SCALE + RADIUS, -(length - centromere) * SCALE - RADIUS - (locus ? 0 : 0.34)]) { + for (const x of [-RADIUS * 1.2, RADIUS * 1.2]) corners.push(p.set(x, y, 0).applyMatrix4(view.group.matrixWorld).clone()); + } + } + for (const view of findings) { + if (!view.head.parent?.visible) continue; + const head = view.head.getWorldPosition(p).clone(); + corners.push(head); + // Room above each marker for its halo, and in locus mode for the band tag. + corners.push(head.clone().add(new Vector3(0, locus ? 0.32 : 0.12, 0))); + } + + const box = { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity }; + for (const c of corners) { + box.minX = Math.min(box.minX, c.x); + box.maxX = Math.max(box.maxX, c.x); + box.minY = Math.min(box.minY, c.y); + box.maxY = Math.max(box.maxY, c.y); + } + const centre = new Vector3((box.minX + box.maxX) / 2, (box.minY + box.maxY) / 2, 0); + figure.position.x -= centre.x; + figure.position.y -= centre.y; + root.updateMatrixWorld(true); + + const fill = locus ? 0.8 : 0.92; + let distance = 0; + for (const c of corners) { + const x = c.x - centre.x; + const y = c.y - centre.y; + distance = Math.max(distance, c.z + Math.abs(x) / (fill * tan * aspect), c.z + Math.abs(y) / (fill * tan)); + } + camera.position.set(0, locus ? 0.3 : 0.6, distance); + camera.lookAt(0, 0, 0); + camera.near = Math.max(0.1, distance - 10); + camera.far = distance + 30; + camera.updateProjectionMatrix(); + (scene.fog as Fog).near = distance; + (scene.fog as Fog).far = distance + 9; + root.rotation.copy(pose); + root.updateMatrixWorld(true); + }; + + /* -- Interaction -- */ + + let visible: ReadonlySet | null = null; + let activeKey: string | null = locus ? options.focusKey : null; + let yaw = 0; + let pitch = 0; + let hovering = false; + const pointer = { x: 0, y: 0 }; + let dragging = false; + + const detachPointer = attachPointer(interactive, { + hover(x, y) { + pointer.x = x; + pointer.y = y; + hovering = true; + stage.invalidate(); + }, + leave() { + hovering = false; + pointer.x = 0; + pointer.y = 0; + stage.invalidate(); + }, + drag(dx, dy) { + const clamp = (value: number, limit: number) => Math.max(-limit, Math.min(limit, value)); + yaw = clamp(yaw + (dx / Math.max(stage.width, 1)) * 2.2, YAW_LIMIT); + pitch = clamp(pitch + (dy / Math.max(stage.height, 1)) * 1.2, PITCH_LIMIT); + stage.invalidate(); + }, + dragChange(next) { + dragging = next; + options.onDragChange(next); + stage.invalidate(); + }, + }); + + /* -- Loop -- */ + + const world = new Vector3(); + const white = new Color("#FFFFFF"); + const carrierColour = new Color(CARRIER); + const shownOn = new Set(); + const camSpace = new Vector3(); + const axisSpace = new Vector3(); + let ready = false; + let swayTime = 0; + + stage.run({ + resize: frame, + update(delta) { + const still = stage.reducedMotion; + let moved = dragging; + + // Pose: the reader's drag, a pointer tilt and, at rest, a slow sway. + if (!still && !dragging && !hovering) swayTime += delta; + const sway = still ? 0 : Math.sin(swayTime * 0.35) * SWAY; + const targetYaw = yaw + (still ? 0 : pointer.x * 0.08) + sway; + const targetPitch = pitch + (still ? 0 : pointer.y * 0.05) + (locus ? 0 : 0.06); + const nextYaw = still ? targetYaw : approach(root.rotation.y, targetYaw, 5, delta); + const nextPitch = still ? targetPitch : approach(root.rotation.x, targetPitch, 5, delta); + if (Math.abs(nextYaw - root.rotation.y) > 1e-4 || Math.abs(nextPitch - root.rotation.x) > 1e-4) moved = true; + if (!still && !hovering && !dragging) moved = true; + root.rotation.y = nextYaw; + root.rotation.x = nextPitch; + + // Chromosomes holding a shown variant take a blush tint, the active one most. + shownOn.clear(); + for (const view of findings) { + if (!visible || visible.has(view.finding.key)) shownOn.add(view.finding.chromosome); + } + const activeChromosome = findings.find((f) => f.finding.key === activeKey)?.finding.chromosome; + for (const view of chromosomes.values()) { + const name = view.chromosome.name; + const target = locus ? 0.4 : name === activeChromosome ? 1 : shownOn.has(name) ? 0.55 : 0; + const next = still ? target : approach(view.tint, target, 8, delta); + if (Math.abs(next - view.tint) > 1e-3) moved = true; + view.tint = next; + view.material.color.copy(white).lerp(carrierColour, view.tint); + } + + for (const view of findings) { + const shown = !visible || visible.has(view.finding.key) ? 1 : 0; + const active = view.finding.key === activeKey ? 1 : 0; + const nextShown = still ? shown : approach(view.shown, shown, 9, delta); + const nextEmphasis = still ? active : approach(view.emphasis, active, 10, delta); + if (Math.abs(nextShown - view.shown) > 1e-3 || Math.abs(nextEmphasis - view.emphasis) > 1e-3) moved = true; + view.shown = nextShown; + view.emphasis = nextEmphasis; + + view.head.scale.setScalar((0.5 + 0.5 * view.shown) * (1 + 0.65 * view.emphasis) * (locus && active ? 1.25 : 1)); + view.head.material.opacity = 0.18 + 0.82 * view.shown; + view.stalk.material.opacity = 0.15 + 0.85 * view.shown; + if (view.ring) view.ring.material.opacity = 0.2 + 0.8 * view.shown; + + view.halo.visible = view.emphasis > 0.02; + view.halo.scale.setScalar(HEAD * 6); + view.halo.material.opacity = 0.6 * view.emphasis; + } + return moved; + }, + afterRender() { + const inverse = camera.matrixWorldInverse; + const points = findings.map((view) => { + view.head.getWorldPosition(world); + camSpace.copy(world).applyMatrix4(inverse); + // The axis at the marker's own locus: a tilted chromosome's ends sit at other depths. + axisSpace.set(0, view.y, 0).applyMatrix4(view.chromosome.group.matrixWorld).applyMatrix4(inverse); + const { x, y } = toScreen(stage, world); + return { + key: view.finding.key, + x, + y, + front: camSpace.z > axisSpace.z - RADIUS, + shown: view.chromosome.group.visible && (!visible || visible.has(view.finding.key)), + }; + }); + const labels: GenomeLabel[] = locus + ? armLabels.map((arm) => { + const { x, y } = toScreen(stage, arm.group.localToWorld(world.copy(arm.at))); + return { id: arm.id, text: arm.text, x, y, shown: true, carrier: false }; + }) + : [...chromosomes.values()].map((view) => { + const { x, y } = toScreen(stage, view.group.localToWorld(world.copy(view.label))); + return { + id: view.chromosome.name, + text: view.chromosome.name, + x, + y, + shown: view.group.visible, + carrier: view.carrier, + }; + }); + options.onProject(points, labels); + if (!ready) { + ready = true; + options.onReady(); + } + }, + }); + + return { + setVisible(keys) { + visible = keys; + stage.invalidate(); + }, + setActive(key) { + activeKey = key ?? (locus ? options.focusKey : null); + stage.invalidate(); + }, + dispose() { + detachPointer(); + ringTexture.dispose(); + stage.dispose(); + }, + }; +} + diff --git a/src/components/three/helix-scene.ts b/src/components/three/helix-scene.ts new file mode 100644 index 0000000..4467f54 --- /dev/null +++ b/src/components/three/helix-scene.ts @@ -0,0 +1,711 @@ +/** + * The evidence helix on the home page. + * + * A B-form double helix built from primitives: two backbones, a bead at every + * nucleotide and a split rung for every base pair. The proportions are the + * real ones (a turn every 10.5 base pairs, a rise of 0.34 against a radius of + * 1, and the two backbones 150 degrees apart, which is what opens the major and + * minor grooves), so it reads as DNA rather than as a twisted ladder. + * + * Each monitored finding is one nucleotide on the leading strand, in genome + * order along the helix, coloured by what happened to its evidence (see + * `lib/signal`), with its base pair tinted to match. The positions + * are illustrative, not to scale: fifteen findings on six chromosomes cannot + * sit on one short stretch of DNA, and the page says so. + * + * Interaction: + * - dragging turns the helix about its own axis, with inertia; + * - the pointer tilts the whole form slightly (parallax); + * - an active finding (hovered or focused) swells and rings, and focusing one + * turns the helix until that nucleotide faces the reader; + * - while an evidence sync runs, a ring scans along the axis and each finding + * pings as the scan passes it. + * + * Reduced motion: no idle spin, parallax, drift or pulsing; a focused finding + * is brought round in one step. Dragging still works, since the reader is + * moving it themselves. + */ + +import { + CapsuleGeometry, + CircleGeometry, + Color, + Curve, + DirectionalLight, + DoubleSide, + Fog, + Group, + HemisphereLight, + InstancedMesh, + Matrix4, + Mesh, + MeshBasicMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + Points, + PointsMaterial, + BufferAttribute, + BufferGeometry, + Quaternion, + SphereGeometry, + Sprite, + SpriteMaterial, + TorusGeometry, + TubeGeometry, + Vector3, +} from "three"; + +import { SIGNALS, type Signal } from "@/lib/signal"; + +import { approach, attachPointer, createStage, softTexture, toScreen } from "./stage"; + +/* -- Geometry: B-DNA proportions ------------------------------------------ */ + +const RADIUS = 1; +const RISE = 0.34; +const TWIST = (Math.PI * 2) / 10.5; +/** Angle from strand A to strand B across one base pair: the minor groove. */ +const GROOVE = (150 / 180) * Math.PI; +const PAIRS = 30; +const LENGTH = (PAIRS - 1) * RISE; +const TUBE = 0.085; +const BEAD = 0.14; +const BASE = 0.066; +/** Space left between the two halves of a pair, where the hydrogen bonds would be. */ +const GAP = 0.045; +/** A finding's nucleotide, drawn larger than its neighbours. */ +const NODE = 0.19; +/** The first and last base pair a finding may take, clear of the faded ends. */ +const FIRST_FINDING = 3; +const LAST_FINDING = PAIRS - 4; + +/* -- Composition ----------------------------------------------------------- */ + +/** Clockwise lean of the axis from vertical, so it rises gently to the right. */ +const LEAN = (62 / 180) * Math.PI; +/** Tips the upper end away, so the rungs are seen slightly from above. */ +const TIP = 0.32; +const FOV = 26; +/** How much of the view the helix may fill, edge to edge. */ +const FILL = 1.08; + +/* -- Motion ---------------------------------------------------------------- */ + +/** One turn every 40 seconds. */ +const SPIN = (Math.PI * 2) / 40; +const PARALLAX_YAW = 0.16; +const PARALLAX_PITCH = 0.1; +/** How quickly a released drag coasts to a stop. */ +const FRICTION = 2.6; +const SCAN_SECONDS = 1.7; +const LEAD_PERIOD = 2.8; +const PULSE_SECONDS = 1.1; + +/* -- Colour ---------------------------------------------------------------- */ + +const GARNET = "#7A263A"; +const ROSE = "#A24A60"; +const PORCELAIN = "#F2E8DD"; +const BLUSH = "#E8C3CC"; +const BONE = "#F7F4ED"; +const VERMILION = "#E85D4A"; + +export interface HelixFinding { + key: string; + signal: Signal; +} + +export interface HelixPoint { + key: string; + /** CSS pixels from the stage's top left. */ + x: number; + y: number; + /** False while the nucleotide is round the back of the helix, where it cannot be picked. */ + front: boolean; +} + +export interface HelixOptions { + /** Already in genome order. */ + findings: HelixFinding[]; + leadKey: string | null; + /** Receives every finding's screen position after each drawn frame. */ + onProject(points: HelixPoint[]): void; + onReady(): void; + onLost(): void; + onDragChange(dragging: boolean): void; +} + +export interface HelixController { + setFindings(findings: HelixFinding[], leadKey: string | null): void; + /** `face` turns the helix until the pair faces the reader (keyboard focus). */ + setActive(key: string | null, face: boolean): void; + setScanning(scanning: boolean): void; + dispose(): void; +} + +class StrandCurve extends Curve { + private readonly phase: number; + + constructor(phase: number) { + super(); + this.phase = phase; + } + + getPoint(t: number, target = new Vector3()): Vector3 { + const pair = t * (PAIRS - 1); + return strandPoint(pair, this.phase, target); + } +} + +function strandPoint(pair: number, phase: number, target = new Vector3()): Vector3 { + const angle = pair * TWIST + phase; + return target.set(RADIUS * Math.sin(angle), -LENGTH / 2 + pair * RISE, RADIUS * Math.cos(angle)); +} + +/** Spreads the findings evenly over the pairs between the faded ends. */ +export function findingPairs(count: number): number[] { + if (count <= 0) return []; + if (count === 1) return [Math.round((FIRST_FINDING + LAST_FINDING) / 2)]; + const step = (LAST_FINDING - FIRST_FINDING) / (count - 1); + return Array.from({ length: count }, (_, i) => Math.round(FIRST_FINDING + i * step)); +} + +interface FindingView { + key: string; + signal: Signal; + pair: number; + node: Mesh; + halo: Sprite; + /** 0…1, eased toward whether the finding is active. */ + emphasis: number; + /** Seconds since the last ping (negative while one is scheduled), or Infinity. */ + since: number; + /** The scan sweep that last pinged this finding. */ + swept: number; +} + +export function mountHelix(stageHost: HTMLElement, interactive: HTMLElement, options: HelixOptions): HelixController { + const stage = createStage(stageHost, { fov: FOV, onLost: options.onLost }); + const { scene, camera } = stage; + + scene.fog = new Fog(BONE, 10, 30); + scene.environmentIntensity = 0.5; + + scene.add(new HemisphereLight("#FFF9F2", "#E6D6CD", 0.9)); + const key = new DirectionalLight("#FFF1E4", 1.9); + key.position.set(-5, 7, 9); + scene.add(key); + const rim = new DirectionalLight("#F3B6C3", 1.3); + rim.position.set(6, -3, -7); + scene.add(rim); + + // root: parallax · lean: diagonal on screen · tip: seen from above · spin: about the axis + const root = new Group(); + const lean = new Group(); + lean.rotation.z = -LEAN; + const tip = new Group(); + tip.rotation.x = TIP; + const spin = new Group(); + root.add(lean); + lean.add(tip); + tip.add(spin); + scene.add(root); + + /* -- Backbones and nucleotides -- */ + + const strandMaterial = (color: string) => + new MeshPhysicalMaterial({ + color, + roughness: 0.36, + clearcoat: 0.85, + clearcoatRoughness: 0.3, + sheen: 0.6, + sheenColor: new Color("#F4CDD5"), + sheenRoughness: 0.55, + }); + const strandA = strandMaterial(GARNET); + const strandB = strandMaterial(ROSE); + + spin.add(new Mesh(new TubeGeometry(new StrandCurve(0), PAIRS * 14, TUBE, 14, false), strandA)); + spin.add(new Mesh(new TubeGeometry(new StrandCurve(GROOVE), PAIRS * 14, TUBE, 14, false), strandB)); + + const beadGeometry = new SphereGeometry(BEAD, 20, 14); + const beadsA = new InstancedMesh(beadGeometry, strandA, PAIRS); + const beadsB = new InstancedMesh(beadGeometry.clone(), strandB, PAIRS); + + const halfLength = strandPoint(0, 0).distanceTo(strandPoint(0, GROOVE)) / 2; + const capsule = halfLength - GAP - BASE * 2; + const baseMaterial = new MeshPhysicalMaterial({ + color: "#FFFFFF", + roughness: 0.46, + clearcoat: 0.5, + clearcoatRoughness: 0.4, + }); + const bases = new InstancedMesh(new CapsuleGeometry(BASE, capsule, 6, 12), baseMaterial, PAIRS * 2); + + const a = new Vector3(); + const b = new Vector3(); + const mid = new Vector3(); + const direction = new Vector3(); + const centre = new Vector3(); + const up = new Vector3(0, 1, 0); + const rotation = new Quaternion(); + const unit = new Vector3(1, 1, 1); + const matrix = new Matrix4(); + const hidden = new Matrix4().makeScale(0, 0, 0); + const leading: Vector3[] = []; + + for (let pair = 0; pair < PAIRS; pair += 1) { + strandPoint(pair, 0, a); + strandPoint(pair, GROOVE, b); + beadsA.setMatrixAt(pair, matrix.makeTranslation(a.x, a.y, a.z)); + beadsB.setMatrixAt(pair, matrix.makeTranslation(b.x, b.y, b.z)); + + leading.push(a.clone()); + mid.addVectors(a, b).multiplyScalar(0.5); + + // Each half runs from its backbone to just short of the middle. + for (const [index, from, sign] of [ + [pair * 2, a, 1], + [pair * 2 + 1, b, -1], + ] as const) { + direction.subVectors(b, a).normalize().multiplyScalar(sign); + const end = mid.clone().addScaledVector(direction, -GAP); + centre.addVectors(from, end).multiplyScalar(0.5); + rotation.setFromUnitVectors(up, direction); + bases.setMatrixAt(index, matrix.compose(centre, rotation, unit)); + } + } + spin.add(beadsA, beadsB, bases); + + /* -- Findings -- */ + + const nodeGeometry = new SphereGeometry(NODE, 24, 16); + const ringTexture = softTexture({ ring: true }); + let findings: FindingView[] = []; + let leadKey: string | null = null; + let activeKey: string | null = null; + + const porcelain = new Color(PORCELAIN); + const blush = new Color(BLUSH); + const tint = new Color(); + + const signalColour = new Color(); + + /** Tints each finding's base pair toward its signal and hands its nucleotide to the finding. */ + const paintBases = () => { + const byPair = new Map(findings.map((f) => [f.pair, f])); + for (let pair = 0; pair < PAIRS; pair += 1) { + const finding = byPair.get(pair); + if (finding) { + signalColour.set(SIGNALS[finding.signal].color); + bases.setColorAt(pair * 2, tint.copy(porcelain).lerp(signalColour, 0.6)); + bases.setColorAt(pair * 2 + 1, tint.copy(blush).lerp(signalColour, 0.3)); + beadsA.setMatrixAt(pair, hidden); + } else { + bases.setColorAt(pair * 2, porcelain); + bases.setColorAt(pair * 2 + 1, blush); + const at = leading[pair]; + beadsA.setMatrixAt(pair, matrix.makeTranslation(at.x, at.y, at.z)); + } + } + if (bases.instanceColor) bases.instanceColor.needsUpdate = true; + beadsA.instanceMatrix.needsUpdate = true; + }; + + const buildFindings = (list: HelixFinding[]) => { + for (const finding of findings) { + spin.remove(finding.node, finding.halo); + finding.node.material.dispose(); + finding.halo.material.dispose(); + } + const pairs = findingPairs(list.length); + findings = list.map((finding, index) => { + const color = new Color(SIGNALS[finding.signal].color); + const node = new Mesh( + nodeGeometry, + new MeshStandardMaterial({ + color, + emissive: color, + emissiveIntensity: finding.signal === "quiet" ? 0.05 : 0.32, + roughness: 0.28, + }), + ); + node.position.copy(leading[pairs[index]]); + const halo = new Sprite( + new SpriteMaterial({ + map: ringTexture, + color, + transparent: true, + opacity: 0, + depthTest: false, + depthWrite: false, + }), + ); + halo.renderOrder = 10; + halo.position.copy(node.position); + halo.visible = false; + spin.add(node, halo); + return { ...finding, pair: pairs[index], node, halo, emphasis: 0, since: Infinity, swept: -1 }; + }); + paintBases(); + }; + + /* -- Scan ring, shown while an evidence sync runs -- */ + + const scan = new Group(); + const scanRing = new Mesh( + new TorusGeometry(RADIUS + 0.42, 0.014, 8, 128), + new MeshBasicMaterial({ color: "#B55A70", transparent: true, opacity: 0, depthWrite: false }), + ); + const scanGlow = new Mesh( + new CircleGeometry(RADIUS + 0.9, 64), + new MeshBasicMaterial({ + map: softTexture(), + color: "#E8B4C0", + transparent: true, + opacity: 0, + depthWrite: false, + side: DoubleSide, + }), + ); + scanRing.rotation.x = Math.PI / 2; + scanGlow.rotation.x = Math.PI / 2; + scan.add(scanGlow, scanRing); + // In the tip frame, so it slides along the axis without turning. + tip.add(scan); + + /* -- Dust, as on the illustrated hero -- */ + + const DUST = 70; + const dustPositions = new Float32Array(DUST * 3); + const dustColors = new Float32Array(DUST * 3); + const dustSeeds: { x: number; y: number; z: number; phase: number; speed: number }[] = []; + const vermilion = new Color(VERMILION); + const rose = new Color("#C98C9C"); + let seed = 7; + const random = () => { + // Deterministic, so the dust never jumps between mounts. + seed = (seed * 16807) % 2147483647; + return (seed - 1) / 2147483646; + }; + for (let i = 0; i < DUST; i += 1) { + dustSeeds.push({ + x: (random() - 0.5) * 14, + y: (random() - 0.5) * 8, + z: (random() - 0.5) * 6 - 1, + phase: random() * Math.PI * 2, + speed: 0.2 + random() * 0.35, + }); + (random() > 0.35 ? vermilion : rose).toArray(dustColors, i * 3); + } + const dustGeometry = new BufferGeometry(); + dustGeometry.setAttribute("position", new BufferAttribute(dustPositions, 3)); + dustGeometry.setAttribute("color", new BufferAttribute(dustColors, 3)); + const dust = new Points( + dustGeometry, + new PointsMaterial({ + // Attenuated point size is in world units per unit of depth: about 4 px here. + size: 1.1, + map: softTexture(), + vertexColors: true, + transparent: true, + opacity: 0.5, + depthWrite: false, + sizeAttenuation: true, + }), + ); + root.add(dust); + + const placeDust = (time: number) => { + for (let i = 0; i < DUST; i += 1) { + const s = dustSeeds[i]; + dustPositions[i * 3] = s.x + Math.sin(time * s.speed * 0.6 + s.phase) * 0.25; + dustPositions[i * 3 + 1] = s.y + Math.sin(time * s.speed + s.phase) * 0.35; + dustPositions[i * 3 + 2] = s.z; + } + dustGeometry.attributes.position.needsUpdate = true; + }; + placeDust(0); + + /* -- Framing -- */ + + // The helix never leaves its bounding cylinder as it turns, so framing that + // cylinder, leaned and tipped as it is on screen, frames every pose. + const envelope: Vector3[] = []; + for (const y of [-LENGTH / 2 - BEAD, LENGTH / 2 + BEAD]) { + for (let k = 0; k < 24; k += 1) { + const angle = (k / 24) * Math.PI * 2; + envelope.push(new Vector3(Math.sin(angle) * (RADIUS + BEAD), y, Math.cos(angle) * (RADIUS + BEAD))); + } + } + let pixelsPerUnit = 1; + + const frame = (width: number, height: number) => { + const aspect = width / height; + const tan = Math.tan((FOV * Math.PI) / 360); + // Frame the rest pose, then give back whatever tilt the pointer had given it. + const pose = root.rotation.clone(); + root.rotation.set(0, 0, 0); + root.updateMatrixWorld(true); + let distance = 0; + const point = new Vector3(); + for (const corner of envelope) { + point.copy(corner).applyMatrix4(tip.matrixWorld); + // Solves |p| / (d - p.z) = FILL · tan (· aspect) for d, per axis. + distance = Math.max( + distance, + point.z + Math.abs(point.x) / (FILL * tan * aspect), + point.z + Math.abs(point.y) / (FILL * tan), + ); + } + camera.position.set(0, 0, distance); + camera.lookAt(0, 0, 0); + camera.near = Math.max(0.1, distance - 12); + camera.far = distance + 20; + camera.updateProjectionMatrix(); + // Far strands fade toward the page colour, as they do on the illustration. + (scene.fog as Fog).near = distance - 0.5; + (scene.fog as Fog).far = distance + 5.5; + pixelsPerUnit = height / (2 * distance * tan); + root.rotation.copy(pose); + root.updateMatrixWorld(true); + }; + + /* -- Interaction -- */ + + let angle = 0; + let velocity = 0; + let target: number | null = null; + let scanning = false; + let scanTime = 0; + let scanFade = 0; + let hovering = false; + const pointer = { x: 0, y: 0 }; + let dragging = false; + + // Screen direction in which the near surface moves as the angle grows. + const surfaceX = Math.cos(LEAN); + const surfaceY = Math.sin(LEAN); + + const detachPointer = attachPointer(interactive, { + hover(x, y) { + pointer.x = x; + pointer.y = y; + hovering = true; + stage.invalidate(); + }, + leave() { + hovering = false; + pointer.x = 0; + pointer.y = 0; + stage.invalidate(); + }, + drag(dx, dy, seconds) { + // The near surface follows the pointer: the drag's component across the axis, in radians. + const step = (dx * surfaceX + dy * surfaceY) / (RADIUS * pixelsPerUnit); + angle += step; + velocity = step / seconds; + stage.invalidate(); + }, + dragChange(next, rested) { + dragging = next; + if (next) target = null; + // Let go after holding still: the helix stays where it was put. + else if (rested) velocity = 0; + options.onDragChange(next); + stage.invalidate(); + }, + }); + + /* -- Loop -- */ + + const world = new Vector3(); + const near = new Vector3(); + const axis = new Vector3(); + let ready = false; + + const faceAngle = (pair: number) => { + // Brings the pair's leading nucleotide round to +z, toward the reader. + const facing = -(pair * TWIST); + const turns = Math.round((angle - facing) / (Math.PI * 2)); + return facing + turns * Math.PI * 2; + }; + + buildFindings(options.findings); + leadKey = options.leadKey; + const lead = findings.find((f) => f.key === leadKey); + // Open on the lead finding, facing the reader. + angle = lead ? faceAngle(lead.pair) + 0.5 : 0; + + stage.run({ + resize: frame, + update(delta, time) { + const still = stage.reducedMotion; + let moved = false; + + // Turning. + if (target !== null) { + const next = still ? target : approach(angle, target, 5, delta); + moved ||= Math.abs(next - angle) > 1e-4; + angle = next; + if (Math.abs(angle - target) < 1e-3) angle = target; + } else if (!dragging) { + if (Math.abs(velocity) > 1e-3) { + angle += velocity * delta; + velocity *= Math.exp(-FRICTION * delta); + moved = true; + } else { + velocity = 0; + } + if (!still && activeKey === null) { + angle += SPIN * (hovering ? 0.35 : 1) * delta; + moved = true; + } + } else { + moved = true; + } + spin.rotation.y = angle; + + // Parallax. + const yaw = still ? 0 : pointer.x * PARALLAX_YAW; + const pitch = still ? 0 : pointer.y * PARALLAX_PITCH; + const nextYaw = approach(root.rotation.y, yaw, 4, delta); + const nextPitch = approach(root.rotation.x, pitch, 4, delta); + moved ||= Math.abs(nextYaw - root.rotation.y) > 1e-4 || Math.abs(nextPitch - root.rotation.x) > 1e-4; + root.rotation.y = nextYaw; + root.rotation.x = nextPitch; + + // Dust. + if (!still) { + placeDust(time); + moved = true; + } + + // Scan. + const fadeTo = scanning ? 1 : 0; + const nextFade = approach(scanFade, fadeTo, 6, delta); + if (Math.abs(nextFade - scanFade) > 1e-3 || scanning) moved = true; + scanFade = nextFade; + if (scanFade > 0.01) { + scanTime += still ? 0 : delta; + const sweep = Math.floor(scanTime / SCAN_SECONDS); + const y = -LENGTH / 2 - 0.6 + ((scanTime % SCAN_SECONDS) / SCAN_SECONDS) * (LENGTH + 1.2); + scan.position.y = still ? 0 : y; + scanRing.material.opacity = 0.75 * scanFade; + scanGlow.material.opacity = 0.32 * scanFade; + // Ping each finding once per sweep, the moment the ring reaches it. + if (scanning && !still) { + for (const finding of findings) { + if (finding.swept !== sweep && y >= leading[finding.pair].y) { + finding.swept = sweep; + finding.since = 0; + } + } + } + } else { + scanRing.material.opacity = 0; + scanGlow.material.opacity = 0; + } + scan.visible = scanFade > 0.01; + + // Findings. + for (const finding of findings) { + const active = finding.key === activeKey; + const nextEmphasis = still ? (active ? 1 : 0) : approach(finding.emphasis, active ? 1 : 0, 10, delta); + if (Math.abs(nextEmphasis - finding.emphasis) > 1e-3) moved = true; + finding.emphasis = nextEmphasis; + + finding.since += delta; + const ping = finding.since >= 0 && finding.since < PULSE_SECONDS ? finding.since / PULSE_SECONDS : null; + // A scheduled ping keeps the loop awake until it has played. + if (finding.since < PULSE_SECONDS) moved = true; + + const bump = ping === null || still ? 0 : Math.sin(ping * Math.PI) * 0.45; + finding.node.scale.setScalar(1 + finding.emphasis * 0.7 + bump); + + const material = finding.halo.material; + if (ping !== null && !still) { + finding.halo.visible = true; + finding.halo.scale.setScalar(NODE * (3 + 9 * ping)); + material.opacity = 0.7 * Math.pow(1 - ping, 1.6); + } else if (finding.emphasis > 0.02) { + finding.halo.visible = true; + finding.halo.scale.setScalar(NODE * 5.4); + material.opacity = 0.62 * finding.emphasis; + } else if (finding.key === leadKey) { + finding.halo.visible = true; + if (still) { + finding.halo.scale.setScalar(NODE * 5); + material.opacity = 0.35; + } else { + const phase = (time % LEAD_PERIOD) / LEAD_PERIOD; + finding.halo.scale.setScalar(NODE * (3 + 8 * phase)); + material.opacity = 0.55 * Math.pow(1 - phase, 1.8); + moved = true; + } + } else { + finding.halo.visible = false; + } + } + + return moved; + }, + afterRender() { + options.onProject( + findings.map((finding) => { + finding.node.getWorldPosition(world); + // Compare depth with the axis at the same height: nearer than it is the front half. + axis.set(0, finding.node.position.y, 0).applyMatrix4(spin.matrixWorld); + const front = + near.copy(world).applyMatrix4(camera.matrixWorldInverse).z > + axis.applyMatrix4(camera.matrixWorldInverse).z - RADIUS * 0.25; + const { x, y } = toScreen(stage, world); + return { key: finding.key, x, y, front }; + }), + ); + if (!ready) { + ready = true; + options.onReady(); + } + }, + }); + + return { + setFindings(list, nextLead) { + // A resync usually returns the same findings; rebuilding them would cut short any ping in flight. + const same = + list.length === findings.length && + list.every((finding, index) => finding.key === findings[index].key && finding.signal === findings[index].signal); + if (!same) buildFindings(list); + leadKey = nextLead; + stage.invalidate(); + }, + setActive(key, face) { + activeKey = key; + const finding = findings.find((f) => f.key === key); + target = finding && face ? faceAngle(finding.pair) : null; + if (target !== null) velocity = 0; + stage.invalidate(); + }, + setScanning(next) { + if (next === scanning) return; + scanning = next; + if (next) { + scanTime = 0; + for (const finding of findings) finding.swept = -1; + } else { + // The sync is over: every finding with something to review pings once, in order. + findings.forEach((finding, index) => { + if (finding.signal !== "quiet") finding.since = -index * 0.07; + }); + } + stage.invalidate(); + }, + dispose() { + detachPointer(); + ringTexture.dispose(); + stage.dispose(); + }, + }; +} diff --git a/src/components/three/stage.ts b/src/components/three/stage.ts new file mode 100644 index 0000000..d1d4249 --- /dev/null +++ b/src/components/three/stage.ts @@ -0,0 +1,411 @@ +/** + * The shared WebGL stage behind every three.js view. + * + * It owns what each scene would otherwise repeat: the renderer, a camera, a + * studio environment generated in code (no HDR or model file is fetched, so + * the views keep working offline like the rest of the workspace), and a render + * loop that only runs while there is something to see. The loop stops when the + * view scrolls out of sight or the tab is hidden, and it sleeps whenever the + * scene reports that nothing moved, so a still view costs no GPU time at all. + * + * This module imports three, so it is only ever loaded with a dynamic import + * from an effect. Server rendering never evaluates it. + */ + +import { + CanvasTexture, + NeutralToneMapping, + PerspectiveCamera, + PMREMGenerator, + Scene, + SRGBColorSpace, + Vector3, + WebGLRenderer, + type BufferGeometry, + type Material, + type Object3D, + type Texture, +} from "three"; +import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js"; + +/** A frame may not step further than this, so a tab returning from the background does not lurch. */ +const MAX_STEP = 0.1; +/** Frames with nothing moving before the loop goes to sleep. */ +const IDLE_FRAMES = 3; +/** Movement, in CSS pixels, that turns a press into a drag rather than a click. */ +const DRAG_THRESHOLD = 5; +/** A pointer held still this long before release has let go, not thrown. */ +const REST_MS = 80; + +export interface StageHooks { + /** Advances the scene by `delta` seconds; returns whether anything moved. */ + update(delta: number, time: number): boolean; + /** The drawing area changed, in CSS pixels. */ + resize(width: number, height: number): void; + /** Runs after each drawn frame, with the camera current. */ + afterRender?(): void; +} + +export interface Stage { + readonly renderer: WebGLRenderer; + readonly scene: Scene; + readonly camera: PerspectiveCamera; + readonly canvas: HTMLCanvasElement; + /** Current size in CSS pixels. */ + readonly width: number; + readonly height: number; + /** Read live: the reader can change the setting while the page is open. */ + readonly reducedMotion: boolean; + /** Draws at least one more frame, waking the loop if it slept. */ + invalidate(): void; + run(hooks: StageHooks): void; + dispose(): void; +} + +export function createStage( + host: HTMLElement, + { fov, onLost }: { fov: number; onLost: () => void }, +): Stage { + // Throws where WebGL is unavailable; the caller keeps its fallback. + const renderer = new WebGLRenderer({ antialias: true, alpha: true, powerPreference: "low-power" }); + renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); + renderer.outputColorSpace = SRGBColorSpace; + // Neutral tone mapping keeps brand colours close to their hex values. + renderer.toneMapping = NeutralToneMapping; + renderer.setClearColor(0x000000, 0); + // Validating shaders stalls the first frame and only helps while developing. + renderer.debug.checkShaderErrors = process.env.NODE_ENV !== "production"; + + const canvas = renderer.domElement; + Object.assign(canvas.style, { display: "block", width: "100%", height: "100%" }); + canvas.setAttribute("aria-hidden", "true"); + host.appendChild(canvas); + + const scene = new Scene(); + const pmrem = new PMREMGenerator(renderer); + const room = new RoomEnvironment(); + const environment = pmrem.fromScene(room, 0.04).texture; + pmrem.dispose(); + disposeTree(room); + scene.environment = environment; + + const camera = new PerspectiveCamera(fov, 1, 0.1, 200); + const motion = window.matchMedia("(prefers-reduced-motion: reduce)"); + + let width = 0; + let height = 0; + let hooks: StageHooks | null = null; + let frame = 0; + let last = 0; + let idle = 0; + let invalid = true; + let inView = true; + let lost = false; + let disposed = false; + + const active = () => + !disposed && !lost && hooks !== null && inView && !document.hidden && width > 0 && height > 0; + + const tick = (now: number) => { + frame = 0; + if (!active() || !hooks) { + last = 0; + return; + } + const delta = last ? Math.min((now - last) / 1000, MAX_STEP) : 0; + last = now; + + const moved = hooks.update(delta, now / 1000); + if (moved || invalid) { + renderer.render(scene, camera); + hooks.afterRender?.(); + invalid = false; + idle = 0; + } else { + idle += 1; + } + + if (idle < IDLE_FRAMES) frame = requestAnimationFrame(tick); + else last = 0; + }; + + const wake = () => { + if (frame || !active()) return; + idle = 0; + frame = requestAnimationFrame(tick); + }; + + const measure = () => { + const rect = host.getBoundingClientRect(); + const w = Math.round(rect.width); + const h = Math.round(rect.height); + if (w === width && h === height) return; + width = w; + height = h; + if (!w || !h) return; + renderer.setSize(w, h, false); + camera.aspect = w / h; + camera.updateProjectionMatrix(); + if (hooks && !lost && !disposed) { + hooks.resize(w, h); + // Resizing clears the canvas; draw now, before the browser paints it blank. + renderer.render(scene, camera); + hooks.afterRender?.(); + } + invalid = true; + wake(); + }; + + const resizeObserver = new ResizeObserver(measure); + resizeObserver.observe(host); + + const intersection = new IntersectionObserver( + ([entry]) => { + inView = entry?.isIntersecting ?? true; + wake(); + }, + { rootMargin: "80px" }, + ); + intersection.observe(host); + + const onVisibility = () => wake(); + document.addEventListener("visibilitychange", onVisibility); + + const onMotion = () => { + invalid = true; + wake(); + }; + motion.addEventListener("change", onMotion); + + // A lost context is not waited on: the loop stops at once and the caller + // disposes the stage and falls back, as it would without WebGL at all. + const onContextLost = () => { + lost = true; + if (frame) cancelAnimationFrame(frame); + frame = 0; + onLost(); + }; + canvas.addEventListener("webglcontextlost", onContextLost); + + return { + renderer, + scene, + camera, + canvas, + get width() { + return width; + }, + get height() { + return height; + }, + get reducedMotion() { + return motion.matches; + }, + invalidate() { + invalid = true; + wake(); + }, + run(next) { + hooks = next; + measure(); + // A size known before the hooks arrived still has to reach them. + if (width && height) next.resize(width, height); + invalid = true; + wake(); + }, + dispose() { + if (disposed) return; + disposed = true; + if (frame) cancelAnimationFrame(frame); + resizeObserver.disconnect(); + intersection.disconnect(); + document.removeEventListener("visibilitychange", onVisibility); + motion.removeEventListener("change", onMotion); + canvas.removeEventListener("webglcontextlost", onContextLost); + disposeTree(scene); + environment.dispose(); + renderer.dispose(); + // Browsers cap live WebGL contexts; give this one back now rather than at collection. + if (!lost) renderer.forceContextLoss(); + canvas.remove(); + }, + }; +} + +export interface PointerHandlers { + /** The pointer moved over the view; each axis runs -1…1 across it. */ + hover(x: number, y: number): void; + leave(): void; + /** A drag moved by (dx, dy) CSS pixels over `seconds`. */ + drag(dx: number, dy: number, seconds: number): void; + /** + * A drag started (true) or ended (false). On the end, `rested` says the + * pointer was held still before release, so nothing should coast. + */ + dragChange(dragging: boolean, rested: boolean): void; +} + +/** + * Press, drag and hover on a 3D view, shared by every scene. + * + * Capture starts only once a press has moved far enough to be a drag, so a + * plain click still reaches the link under it; a click that ends a drag is + * swallowed. A press whose release happened outside the view is dropped as + * soon as the pointer comes back with no button held, so it can never turn + * into a drag nobody is making. Returns a function that detaches everything. + */ +export function attachPointer(interactive: HTMLElement, handlers: PointerHandlers): () => void { + let press: { id: number; x: number; y: number; lastX: number; lastY: number; lastT: number } | null = null; + let dragging = false; + let swallowClick = false; + + const finish = (event: PointerEvent) => { + if (!press || event.pointerId !== press.id) return; + const rested = event.timeStamp - press.lastT > REST_MS; + press = null; + if (!dragging) return; + dragging = false; + swallowClick = true; + // A drag that ends away from any link produces no click to swallow. + setTimeout(() => (swallowClick = false), 0); + if (interactive.hasPointerCapture(event.pointerId)) interactive.releasePointerCapture(event.pointerId); + handlers.dragChange(false, rested); + }; + + const onDown = (event: PointerEvent) => { + if (event.button !== 0) return; + const { clientX: x, clientY: y, timeStamp } = event; + press = { id: event.pointerId, x, y, lastX: x, lastY: y, lastT: timeStamp }; + }; + + const onMove = (event: PointerEvent) => { + const rect = interactive.getBoundingClientRect(); + handlers.hover( + ((event.clientX - rect.left) / rect.width) * 2 - 1, + ((event.clientY - rect.top) / rect.height) * 2 - 1, + ); + if (!press || event.pointerId !== press.id) return; + if ((event.buttons & 1) === 0) { + finish(event); + return; + } + if (!dragging && Math.hypot(event.clientX - press.x, event.clientY - press.y) > DRAG_THRESHOLD) { + dragging = true; + try { + interactive.setPointerCapture(event.pointerId); + } catch { + // The pointer is already gone; the drag still runs on the moves that reach the view. + } + handlers.dragChange(true, false); + } + if (dragging) { + const seconds = Math.max((event.timeStamp - press.lastT) / 1000, 1 / 240); + handlers.drag(event.clientX - press.lastX, event.clientY - press.lastY, seconds); + } + press.lastX = event.clientX; + press.lastY = event.clientY; + press.lastT = event.timeStamp; + }; + + const onLeave = () => handlers.leave(); + + const onClick = (event: MouseEvent) => { + if (!swallowClick) return; + event.preventDefault(); + event.stopPropagation(); + swallowClick = false; + }; + + interactive.addEventListener("pointerdown", onDown); + interactive.addEventListener("pointermove", onMove); + interactive.addEventListener("pointerup", finish); + interactive.addEventListener("pointercancel", finish); + // Capture can end without a pointerup, for instance when the element is torn down. + interactive.addEventListener("lostpointercapture", finish); + interactive.addEventListener("pointerleave", onLeave); + interactive.addEventListener("click", onClick, true); + + return () => { + interactive.removeEventListener("pointerdown", onDown); + interactive.removeEventListener("pointermove", onMove); + interactive.removeEventListener("pointerup", finish); + interactive.removeEventListener("pointercancel", finish); + interactive.removeEventListener("lostpointercapture", finish); + interactive.removeEventListener("pointerleave", onLeave); + interactive.removeEventListener("click", onClick, true); + }; +} + +/** Frees every geometry, material and texture under `root`. */ +export function disposeTree(root: Object3D) { + const textures = new Set(); + const materials = new Set(); + root.traverse((object) => { + // Meshes, instanced meshes, points and sprites all carry these two. + const drawable = object as Object3D & { geometry?: BufferGeometry; material?: Material | Material[] }; + drawable.geometry?.dispose(); + if (drawable.material) { + for (const material of Array.isArray(drawable.material) ? drawable.material : [drawable.material]) { + materials.add(material); + } + } + }); + for (const material of materials) { + for (const value of Object.values(material)) { + if (value && typeof value === "object" && (value as Texture).isTexture) textures.add(value as Texture); + } + material.dispose(); + } + for (const texture of textures) texture.dispose(); +} + +/** + * A soft round sprite drawn on a small canvas: a filled dot, or a ring when + * `ring` is set. Used for dust, halos and the scan glow, so no image is fetched. + */ +export function softTexture({ ring = false, size = 128 } = {}): CanvasTexture { + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + const context = canvas.getContext("2d"); + if (context) { + const half = size / 2; + const gradient = context.createRadialGradient(half, half, 0, half, half, half); + if (ring) { + gradient.addColorStop(0, "rgba(255,255,255,0)"); + gradient.addColorStop(0.62, "rgba(255,255,255,0)"); + gradient.addColorStop(0.78, "rgba(255,255,255,1)"); + gradient.addColorStop(0.9, "rgba(255,255,255,0.35)"); + gradient.addColorStop(1, "rgba(255,255,255,0)"); + } else { + gradient.addColorStop(0, "rgba(255,255,255,1)"); + gradient.addColorStop(0.45, "rgba(255,255,255,0.55)"); + gradient.addColorStop(1, "rgba(255,255,255,0)"); + } + context.fillStyle = gradient; + context.fillRect(0, 0, size, size); + } + const texture = new CanvasTexture(canvas); + texture.colorSpace = SRGBColorSpace; + return texture; +} + +const scratch = new Vector3(); + +/** Projects a world position to CSS pixels in the stage. */ +export function toScreen( + stage: Pick, + world: Vector3, +): { x: number; y: number; depth: number } { + scratch.copy(world).project(stage.camera); + return { + x: (scratch.x * 0.5 + 0.5) * stage.width, + y: (-scratch.y * 0.5 + 0.5) * stage.height, + depth: scratch.z, + }; +} + +/** Exponential ease toward a target that is frame-rate independent. */ +export function approach(current: number, target: number, rate: number, delta: number): number { + return target + (current - target) * Math.exp(-rate * delta); +} diff --git a/src/components/use-displayed.ts b/src/components/use-displayed.ts new file mode 100644 index 0000000..1b70aea --- /dev/null +++ b/src/components/use-displayed.ts @@ -0,0 +1,30 @@ +"use client"; + +import * as React from "react"; + +/** + * True once the element has been laid out with a size. + * + * A 3D view hidden by a breakpoint (the home helix on a phone) still mounts, + * and without this it would download three.js and open a WebGL context for a + * box nobody can see. The observer also catches a view that appears later, on + * a rotated tablet or a widened window. + */ +export function useDisplayed(ref: React.RefObject): boolean { + const [displayed, setDisplayed] = React.useState(false); + + React.useEffect(() => { + const element = ref.current; + if (!element || displayed) return; + const check = () => { + const { width, height } = element.getBoundingClientRect(); + if (width > 0 && height > 0) setDisplayed(true); + }; + check(); + const observer = new ResizeObserver(check); + observer.observe(element); + return () => observer.disconnect(); + }, [ref, displayed]); + + return displayed; +} diff --git a/src/lib/genome.ts b/src/lib/genome.ts new file mode 100644 index 0000000..3e2160d --- /dev/null +++ b/src/lib/genome.ts @@ -0,0 +1,103 @@ +/** + * The human genome at the scale the visual layer draws it. + * + * Lengths are the GRCh38 primary-assembly chromosome sizes (UCSC hg38 + * chrom.sizes). Each centromere is the boundary between the p11 and q11 `acen` + * bands in the UCSC hg38 cytoBand table, which is where an ideogram draws the + * constriction. Neither is fetched: they are fixed properties of the assembly + * ClinVar reports positions against. + * + * Variant positions are never modelled here. They come from ClinVar's own + * GRCh38 location for each record, so a marker sits exactly where the evidence + * says the variant is. + */ + +import type { EvidenceRecord } from "./clinvar"; + +export interface Chromosome { + /** `1`–`22`, `X` or `Y`, as ClinVar writes it. */ + name: string; + /** Length in base pairs. */ + length: number; + /** Centromere position in base pairs from the p-arm end. */ + centromere: number; +} + +export const GRCH38: readonly Chromosome[] = [ + { name: "1", length: 248_956_422, centromere: 123_400_000 }, + { name: "2", length: 242_193_529, centromere: 93_900_000 }, + { name: "3", length: 198_295_559, centromere: 90_900_000 }, + { name: "4", length: 190_214_555, centromere: 50_000_000 }, + { name: "5", length: 181_538_259, centromere: 48_800_000 }, + { name: "6", length: 170_805_979, centromere: 59_800_000 }, + { name: "7", length: 159_345_973, centromere: 60_100_000 }, + { name: "8", length: 145_138_636, centromere: 45_200_000 }, + { name: "9", length: 138_394_717, centromere: 43_000_000 }, + { name: "10", length: 133_797_422, centromere: 39_800_000 }, + { name: "11", length: 135_086_622, centromere: 53_400_000 }, + { name: "12", length: 133_275_309, centromere: 35_500_000 }, + { name: "13", length: 114_364_328, centromere: 17_700_000 }, + { name: "14", length: 107_043_718, centromere: 17_200_000 }, + { name: "15", length: 101_991_189, centromere: 19_000_000 }, + { name: "16", length: 90_338_345, centromere: 36_800_000 }, + { name: "17", length: 83_257_441, centromere: 25_100_000 }, + { name: "18", length: 80_373_285, centromere: 18_500_000 }, + { name: "19", length: 58_617_616, centromere: 26_200_000 }, + { name: "20", length: 64_444_167, centromere: 28_100_000 }, + { name: "21", length: 46_709_983, centromere: 12_000_000 }, + { name: "22", length: 50_818_468, centromere: 15_000_000 }, + { name: "X", length: 156_040_895, centromere: 61_000_000 }, + { name: "Y", length: 57_227_415, centromere: 10_400_000 }, +]; + +export const CHROMOSOME_BY_NAME = new Map(GRCH38.map((c) => [c.name, c])); + +/** A variant's place on the genome, read from its evidence record. */ +export interface Locus { + chromosome: Chromosome; + /** GRCh38 start, in base pairs. */ + position: number; + /** Cytogenetic band as ClinVar gives it, e.g. `17q21.31`. */ + band: string | null; + /** Which arm the position falls on, from the centromere above. */ + arm: "p" | "q"; +} + +/** + * Where the evidence places a variant, or null when the record carries no + * GRCh38 location this table can draw (another assembly, or an unplaced + * contig). A chromosome written `chr17` is read as `17`. + */ +export function locusOf(evidence: Pick): Locus | null { + const location = evidence.location; + if (!location || location.assembly !== "GRCh38") return null; + + const chromosome = CHROMOSOME_BY_NAME.get(location.chr.replace(/^chr/i, "").toUpperCase()); + const position = Number(location.start); + if (!chromosome || !Number.isInteger(position) || position < 1 || position > chromosome.length) { + return null; + } + + return { + chromosome, + position, + band: location.band?.trim() || null, + arm: position < chromosome.centromere ? "p" : "q", + }; +} + +/** Karyotype order: 1–22, then X and Y. */ +export function chromosomeRank(name: string): number { + const index = GRCH38.findIndex((c) => c.name === name); + return index === -1 ? GRCH38.length : index; +} + +/** Orders loci the way the genome reads: by chromosome, then by position. */ +export function compareLoci(a: Locus, b: Locus): number { + return chromosomeRank(a.chromosome.name) - chromosomeRank(b.chromosome.name) || a.position - b.position; +} + +/** `43067626` as `43,067,626`. */ +export function formatPosition(position: number): string { + return new Intl.NumberFormat("en-US").format(position); +} diff --git a/src/lib/signal.ts b/src/lib/signal.ts new file mode 100644 index 0000000..a2116ee --- /dev/null +++ b/src/lib/signal.ts @@ -0,0 +1,39 @@ +/** + * The three signals the visual layer draws, collapsed from the six change + * types the engine reports. They carry the colour system's meanings and + * nothing else: vermilion when the science changed, amber when evidence is + * unresolved and a person has to weigh it, slate when the reading on record + * still holds. The groups are the same ones the variant list filters by. + */ + +import type { ChangeType } from "./classification"; + +export type Signal = "changed" | "review" | "quiet"; + +export const SIGNAL_OF: Record = { + CLASSIFICATION_DRIFT: "changed", + EVIDENCE_STRENGTHENED: "changed", + EVIDENCE_WEAKENED: "changed", + CONSENSUS_CONFLICT: "review", + REGIONAL_CONFLICT: "review", + NO_MATERIAL_CHANGE: "quiet", +}; + +export interface SignalMeta { + label: string; + /** Hex, for canvases and WebGL; the palette tokens it mirrors are named beside it. */ + color: string; + /** Tailwind background class for legend dots in HTML. */ + dot: string; +} + +export const SIGNALS: Record = { + // Vermilion, the colour system's "something changed". + changed: { label: "Reclassified", color: "#E85D4A", dot: "bg-vermilion" }, + // Amber, "unresolved context". + review: { label: "Conflict or regional", color: "#D99A28", dot: "bg-amber" }, + // Palette slate, the historical, quiet state. + quiet: { label: "Unchanged", color: "#74777D", dot: "bg-slate" }, +}; + +export const SIGNAL_ORDER: readonly Signal[] = ["changed", "review", "quiet"]; diff --git a/tests/genome.test.ts b/tests/genome.test.ts new file mode 100644 index 0000000..1d0fd82 --- /dev/null +++ b/tests/genome.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; + +import snapshot from "@/data/evidence-snapshot.json"; +import { MONITORED_VARIANTS } from "@/data/workspace"; +import { CHANGE_TYPES, type ChangeType } from "@/lib/classification"; +import type { EvidenceRecord } from "@/lib/clinvar"; +import { GRCH38, compareLoci, formatPosition, locusOf } from "@/lib/genome"; +import { SIGNAL_OF } from "@/lib/signal"; + +const records = snapshot.records as unknown as Record; + +describe("the genome table", () => { + it("holds the 24 GRCh38 chromosomes in karyotype order, each centromere inside its chromosome", () => { + expect(GRCH38.map((c) => c.name)).toEqual([ + ...Array.from({ length: 22 }, (_, i) => String(i + 1)), + "X", + "Y", + ]); + for (const chromosome of GRCH38) { + expect(chromosome.centromere, chromosome.name).toBeGreaterThan(0); + expect(chromosome.centromere, chromosome.name).toBeLessThan(chromosome.length); + } + }); + + it("places every monitored variant on the arm ClinVar's cytogenetic band names", () => { + for (const variant of MONITORED_VARIANTS) { + const locus = locusOf(records[variant.key]); + expect(locus, variant.key).not.toBeNull(); + // `17q21.31` names the q arm of chromosome 17; the centromere table has to agree. + expect(locus!.band, variant.key).toMatch(new RegExp(`^${locus!.chromosome.name}${locus!.arm}`)); + } + }); + + it("refuses a location it cannot draw rather than guessing one", () => { + const at = (location: EvidenceRecord["location"]) => locusOf({ location }); + expect(at(null)).toBeNull(); + expect(at({ assembly: "GRCh37", chr: "17", band: "17q21.31", start: "41215920", stop: "41215920" })).toBeNull(); + expect(at({ assembly: "GRCh38", chr: "MT", band: "", start: "8993", stop: "8993" })).toBeNull(); + expect(at({ assembly: "GRCh38", chr: "21", band: "", start: "90000000", stop: "90000000" })).toBeNull(); + expect(at({ assembly: "GRCh38", chr: "chrX", band: " ", start: "100", stop: "100" })).toMatchObject({ + chromosome: { name: "X" }, + band: null, + arm: "p", + }); + }); + + it("orders loci by chromosome, then position", () => { + const loci = MONITORED_VARIANTS.map((v) => locusOf(records[v.key])!).sort(compareLoci); + expect(loci.map((l) => l.chromosome.name)).toEqual( + [...loci.map((l) => l.chromosome.name)].sort((a, b) => Number(a) - Number(b)), + ); + expect(loci[0].chromosome.name).toBe("7"); + expect(formatPosition(43067626)).toBe("43,067,626"); + }); +}); + +describe("signals", () => { + it("gives every change type exactly one signal, and only material changes a loud one", () => { + for (const type of Object.keys(CHANGE_TYPES) as ChangeType[]) { + expect(SIGNAL_OF[type] === "quiet", type).toBe(!CHANGE_TYPES[type].material); + } + }); +}); diff --git a/tests/pointer.test.ts b/tests/pointer.test.ts new file mode 100644 index 0000000..cb2ee89 --- /dev/null +++ b/tests/pointer.test.ts @@ -0,0 +1,147 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { attachPointer, type PointerHandlers } from "@/components/three/stage"; + +type Listener = (event: never) => void; + +/** Just enough of an element for the pointer rules: listeners, a box and capture. */ +function fakeView() { + const listeners = new Map>(); + const captured = new Set(); + return { + captured, + addEventListener(type: string, listener: Listener) { + if (!listeners.has(type)) listeners.set(type, new Set()); + listeners.get(type)!.add(listener); + }, + removeEventListener(type: string, listener: Listener) { + listeners.get(type)?.delete(listener); + }, + getBoundingClientRect: () => ({ left: 0, top: 0, width: 200, height: 100 }), + setPointerCapture: (id: number) => captured.add(id), + hasPointerCapture: (id: number) => captured.has(id), + releasePointerCapture: (id: number) => captured.delete(id), + fire(type: string, init: Record = {}) { + const event = { + pointerId: 1, + button: 0, + buttons: 1, + clientX: 0, + clientY: 0, + timeStamp: 0, + defaultPrevented: false, + propagationStopped: false, + preventDefault() { + this.defaultPrevented = true; + }, + stopPropagation() { + this.propagationStopped = true; + }, + ...init, + }; + for (const listener of listeners.get(type) ?? []) (listener as (e: typeof event) => void)(event); + return event; + }, + count: () => [...listeners.values()].reduce((sum, set) => sum + set.size, 0), + }; +} + +function recorder() { + const calls: string[] = []; + const handlers: PointerHandlers = { + hover: () => undefined, + leave: () => calls.push("leave"), + drag: (dx, dy) => calls.push(`drag ${dx},${dy}`), + dragChange: (dragging, rested) => calls.push(dragging ? "start" : rested ? "end rested" : "end thrown"), + }; + return { calls, handlers }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("pointer handling on a 3D view", () => { + it("leaves a click alone when the press barely moves", () => { + const view = fakeView(); + const { calls, handlers } = recorder(); + attachPointer(view as unknown as HTMLElement, handlers); + + view.fire("pointerdown", { clientX: 10, clientY: 10 }); + view.fire("pointermove", { clientX: 13, clientY: 11, timeStamp: 10 }); + view.fire("pointerup", { clientX: 13, clientY: 11, timeStamp: 20, buttons: 0 }); + const click = view.fire("click"); + + expect(calls).toEqual([]); + expect(view.captured.size).toBe(0); + expect(click.defaultPrevented).toBe(false); + }); + + it("turns a moving press into a drag, captures it, and swallows the click that ends it", () => { + vi.useFakeTimers(); + const view = fakeView(); + const { calls, handlers } = recorder(); + attachPointer(view as unknown as HTMLElement, handlers); + + view.fire("pointerdown", { clientX: 10, clientY: 10 }); + view.fire("pointermove", { clientX: 30, clientY: 10, timeStamp: 16 }); + expect(view.captured.has(1)).toBe(true); + view.fire("pointerup", { clientX: 30, clientY: 10, timeStamp: 30, buttons: 0 }); + const click = view.fire("click"); + + expect(calls).toEqual(["start", "drag 20,0", "end thrown"]); + expect(click.defaultPrevented && click.propagationStopped).toBe(true); + expect(view.captured.size).toBe(0); + + // The next click, after the drag, is a real one. + vi.runAllTimers(); + expect(view.fire("click").defaultPrevented).toBe(false); + }); + + it("lets go without a throw when the pointer rested before release", () => { + const view = fakeView(); + const { calls, handlers } = recorder(); + attachPointer(view as unknown as HTMLElement, handlers); + + view.fire("pointerdown", { clientX: 10, clientY: 10 }); + view.fire("pointermove", { clientX: 40, clientY: 10, timeStamp: 16 }); + view.fire("pointerup", { clientX: 40, clientY: 10, timeStamp: 400, buttons: 0 }); + + expect(calls.at(-1)).toBe("end rested"); + }); + + it("drops a press released outside the view instead of dragging with no button held", () => { + const view = fakeView(); + const { calls, handlers } = recorder(); + attachPointer(view as unknown as HTMLElement, handlers); + + // Pressed near the edge and flicked out: the release never reached the view. + view.fire("pointerdown", { clientX: 195, clientY: 50 }); + // Back over the view later with no button down. + view.fire("pointermove", { clientX: 100, clientY: 50, timeStamp: 900, buttons: 0 }); + view.fire("pointermove", { clientX: 60, clientY: 50, timeStamp: 916, buttons: 0 }); + + expect(calls).toEqual([]); + expect(view.captured.size).toBe(0); + }); + + it("ends a drag whose capture is lost without a release", () => { + const view = fakeView(); + const { calls, handlers } = recorder(); + attachPointer(view as unknown as HTMLElement, handlers); + + view.fire("pointerdown", { clientX: 10, clientY: 10 }); + view.fire("pointermove", { clientX: 40, clientY: 10, timeStamp: 16 }); + view.fire("lostpointercapture", { timeStamp: 20 }); + + expect(calls).toEqual(["start", "drag 30,0", "end thrown"]); + }); + + it("removes every listener it added", () => { + const view = fakeView(); + const detach = attachPointer(view as unknown as HTMLElement, recorder().handlers); + expect(view.count()).toBeGreaterThan(0); + detach(); + expect(view.count()).toBe(0); + }); +});