import { useEffect, useMemo, useRef, useState } from "react" import { REL_NAME, type Author, type Lineage, type Rel, type Repo } from "@/lib/types" import { num as fmt, full, hfUrl, mdy } from "@/lib/format" import { catFrom, catTo } from "@/lib/category" import type { Ring } from "@/lib/galaxy" import { RelDot, RelLegend } from "@/components/rel" import { Who } from "@/components/who" import { Octopus } from "@/components/octopus" import { DownloadButton } from "@/components/download-button" type P = { id: string; x: number; y: number; r: number; ring: number; repo: Repo } type Layout = { pos: P[]; rings: Ring[]; extent: number } const RING_NAME = ["", "Built on it directly", "Second generation", "Third generation and on"] const ORDER: Rel[] = ["adapter", "finetune", "quantized", "repackage", "merge", "mirror", "component"] const CENTER_R = 64 const LABEL_FONT = '500 14px "DM Sans Variable", system-ui, sans-serif' /** Deterministic 0..1 from a string, so every bubble keeps its own rhythm across loads. */ function hash(s: string): number { let h = 2166136261 for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619) return ((h >>> 0) % 100000) / 100000 } /** * The official model in the middle (the MiniMax Code octopus), every community model around it: * one ring per generation, each bubble near the model it is built on, bigger bubble for more * downloads. Bubbles are painted in exactly the relation colours used everywhere else on the * page. They drift a little on their own while neighbouring rings sway against each other; the * motion pauses while something is hovered, when the picture is off screen, and entirely under * reduced motion. Drawn on a canvas: 1,000+ moving circles would choke SVG. */ export function Galaxy({ lineageKey, repos, L, authors, name, cat }: { lineageKey: string; repos: Repo[]; L: Lineage; authors: Record; name: string; cat: string }) { const [layout, setLayout] = useState(null) const [hover, setHover] = useState(null) const box = useRef(null) const stageRef = useRef(null) const canvas = useRef(null) const tapRef = useRef(null) // what was showing before this tap const typeRef = useRef("mouse") const hoverRef = useRef(null) const cur = useRef(new Float32Array(0)) // current x, y of every bubble // A first guess from the window, so the picture has its size before the observer reports. const [w, setW] = useState(() => Math.min(window.innerWidth - 64, 1072)) useEffect(() => { const worker = new Worker(new URL("../lib/galaxy.worker.ts", import.meta.url), { type: "module" }) const byId = new Map(repos.map((r) => [r.id, r])) worker.onmessage = (e) => { const { pos, rings, extent } = e.data as { pos: [string, number, number, number, number][]; rings: Ring[]; extent: number } setLayout({ pos: pos.map(([id, x, y, r, ring]) => ({ id, x, y, r, ring, repo: byId.get(id)! })), rings, extent }) worker.terminate() } worker.postMessage({ key: lineageKey, repos, base: L.base, officialDl: L.official.dlall ?? 0 }) return () => worker.terminate() }, [lineageKey, repos, L]) useEffect(() => { const el = box.current if (!el) return const ro = new ResizeObserver(() => setW(el.clientWidth)) ro.observe(el) return () => ro.disconnect() }, []) const size = Math.min(w, 980) const E = (layout?.extent ?? 300) + 8 const k = size / (2 * E) // world -> px const toPx = (x: number) => size / 2 + x * k const index = useMemo(() => new Map(layout?.pos.map((p, i) => [p.id, i]) ?? []), [layout]) const kids = useMemo(() => { const m = new Map() layout?.pos.forEach((p, i) => m.set(p.repo.up, [...(m.get(p.repo.up) ?? []), i])) return m }, [layout]) // Names for the biggest bubbles, skipping any that would collide with one already placed. const labels = useMemo(() => { if (!layout || size < 560) return [] const ctx = document.createElement("canvas").getContext("2d")! ctx.font = LABEL_FONT const placed: { x0: number; x1: number; y0: number; y1: number }[] = [] const out: { i: number; w: number }[] = [] const order = layout.pos.map((p, i) => [p, i] as const).sort((a, b) => b[0].r - a[0].r).slice(0, 24) for (const [p, i] of order) { if (p.r * k < 9 || out.length >= 6) break const wpx = ctx.measureText(p.id).width + 22 const x = toPx(p.x), y = toPx(p.y) + p.r * k + 6 const rect = { x0: x - wpx / 2 - 6, x1: x + wpx / 2 + 6, y0: y - 4, y1: y + 30 } if (placed.some((q) => rect.x0 < q.x1 && rect.x1 > q.x0 && rect.y0 < q.y1 && rect.y1 > q.y0)) continue placed.push(rect) out.push({ i, w: wpx }) } return out // eslint-disable-next-line react-hooks/exhaustive-deps }, [layout, size]) const lit = useMemo(() => { if (!hover || !layout) return null const s = new Set() const hi = index.get(hover) if (hi != null) { s.add(hi) const up = index.get(layout.pos[hi].repo.up) if (up != null) s.add(up) } for (const c of kids.get(hover) ?? []) s.add(c) return s }, [hover, layout, index, kids]) const litRef = useRef | null>(null) useEffect(() => { hoverRef.current = hover litRef.current = lit }, [hover, lit]) // The animation loop: positions are a function of a clock that only runs while the picture // is visible and nothing is hovered. useEffect(() => { const cv = canvas.current, stage = stageRef.current if (!cv || !stage || !layout || !size) return const dpr = Math.min(2, window.devicePixelRatio || 1) cv.width = Math.round(size * dpr) cv.height = Math.round(size * dpr) const ctx = cv.getContext("2d")! const n = layout.pos.length if (cur.current.length !== 2 * n) cur.current = new Float32Array(2 * n) const rho = new Float32Array(n), theta = new Float32Array(n) const ph = new Float32Array(n), fq = new Float32Array(n), amp = new Float32Array(n) const maxR = Math.max(1, ...layout.pos.map((p) => p.r)) layout.pos.forEach((p, i) => { rho[i] = Math.hypot(p.x, p.y) theta[i] = Math.atan2(p.y, p.x) ph[i] = hash(p.id) * Math.PI * 2 fq[i] = 0.55 + hash(p.id + "f") * 0.6 // radians per second amp[i] = (1.2 + 2.6 * (1 - p.r / maxR)) / k // small bubbles wander more }) const byColor = new Map() layout.pos.forEach((p, i) => byColor.set(p.repo.rel, [...(byColor.get(p.repo.rel) ?? []), i])) const still = matchMedia("(prefers-reduced-motion: reduce)").matches let visible = true const io = new IntersectionObserver(([e]) => (visible = e.isIntersecting)) io.observe(cv) let colors: Record = {} let colorsAt = -1e9 let clock = 0, last = performance.now(), raf = 0 const frame = (now: number) => { raf = requestAnimationFrame(frame) const dt = Math.min(0.05, (now - last) / 1000) last = now const hovering = hoverRef.current != null if (!visible) return if (!still && !hovering) clock += dt if (now - colorsAt > 1000) { // follows a light/dark switch within a second const cs = getComputedStyle(stage) colors = Object.fromEntries(ORDER.map((r) => [r, cs.getPropertyValue(`--rel-${r}`).trim() || "#888"])) colorsAt = now } const t = clock const c = cur.current for (let i = 0; i < n; i++) { const ring = layout.pos[i].ring const sway = 0.022 * (ring % 2 ? 1 : -1) * Math.sin((t * 2 * Math.PI) / 16 + ring * 0.9) const a = theta[i] + sway c[2 * i] = rho[i] * Math.cos(a) + amp[i] * Math.sin(t * fq[i] + ph[i]) c[2 * i + 1] = rho[i] * Math.sin(a) + amp[i] * Math.cos(t * fq[i] * 0.83 + ph[i] * 1.7) } ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, cv.width, cv.height) ctx.setTransform(dpr * k, 0, 0, dpr * k, (dpr * size) / 2, (dpr * size) / 2) for (const g of layout.rings) { ctx.beginPath() ctx.arc(0, 0, (g.inner + g.outer) / 2, 0, Math.PI * 2) ctx.strokeStyle = "rgba(255,255,255,0.035)" ctx.lineWidth = g.outer - g.inner + 16 ctx.setLineDash([]) ctx.stroke() ctx.beginPath() ctx.arc(0, 0, g.outer + 8, 0, Math.PI * 2) ctx.strokeStyle = "rgba(255,255,255,0.14)" ctx.lineWidth = 1 / k ctx.setLineDash([2 / k, 6 / k]) ctx.stroke() } ctx.setLineDash([]) const L2 = litRef.current const hv = hoverRef.current if (hv && L2) { const hi = index.get(hv) const ax = hi == null ? 0 : c[2 * hi], ay = hi == null ? 0 : c[2 * hi + 1] ctx.strokeStyle = "rgba(255,255,255,0.55)" ctx.lineWidth = 1.3 / k ctx.beginPath() const link = (bx: number, by: number) => { ctx.moveTo(ax, ay) ctx.quadraticCurveTo(((ax + bx) / 2) * 0.82, ((ay + by) / 2) * 0.82, bx, by) } for (const j of L2) if (j !== hi) link(c[2 * j], c[2 * j + 1]) if (hi != null && index.get(layout.pos[hi].repo.up) == null) link(0, 0) // built on the official model ctx.stroke() } for (const pass of [0, 1]) { // dimmed bubbles first, so the lit ones sit on top if (pass === 1 && !L2) break for (const [rel, idx] of byColor) { ctx.fillStyle = colors[rel] ctx.globalAlpha = L2 ? (pass === 0 ? 0.14 : 1) : 1 ctx.beginPath() for (const i of idx) { if (L2 && (pass === 0) === L2.has(i)) continue const x = c[2 * i], y = c[2 * i + 1], r = layout.pos[i].r ctx.moveTo(x + r, y) ctx.arc(x, y, r, 0, Math.PI * 2) } ctx.fill() } } ctx.globalAlpha = 1 const hi = hv ? index.get(hv) : undefined if (hi != null) { ctx.beginPath() ctx.arc(c[2 * hi], c[2 * hi + 1], layout.pos[hi].r + 1.5 / k, 0, Math.PI * 2) ctx.strokeStyle = "#fff" ctx.lineWidth = 2 / k ctx.stroke() } // names of the biggest bubbles ride along with them ctx.setTransform(dpr, 0, 0, dpr, 0, 0) ctx.font = LABEL_FONT ctx.textAlign = "center" ctx.textBaseline = "middle" for (const { i, w: lw } of labels) { const x = size / 2 + c[2 * i] * k, y = size / 2 + c[2 * i + 1] * k + layout.pos[i].r * k + 6 ctx.globalAlpha = L2 && !L2.has(i) ? 0.2 : 1 ctx.beginPath() ctx.roundRect(x - lw / 2, y, lw, 26, 13) ctx.fillStyle = "rgba(21,21,28,0.86)" ctx.fill() ctx.strokeStyle = "rgba(255,255,255,0.12)" ctx.lineWidth = 1 ctx.stroke() ctx.fillStyle = "#fff" ctx.fillText(layout.pos[i].id, x, y + 13.5) } ctx.globalAlpha = 1 } raf = requestAnimationFrame(frame) return () => { cancelAnimationFrame(raf) io.disconnect() } }, [layout, size, k, labels, index]) const hit = (e: React.PointerEvent) => { if (!layout) return const rect = (e.currentTarget as HTMLElement).getBoundingClientRect() const wx = (e.clientX - rect.left - size / 2) / k, wy = (e.clientY - rect.top - size / 2) / k if (Math.hypot(wx, wy) < CENTER_R) return setHover(L.base) const c = cur.current let best = -1, bd = Infinity for (let i = 0; i < layout.pos.length; i++) { const d = Math.hypot(c[2 * i] - wx, c[2 * i + 1] - wy) - layout.pos[i].r if (d < bd) { bd = d; best = i } } setHover(best >= 0 && bd < 10 / k ? layout.pos[best].id : null) } const present = ORDER.filter((r) => repos.some((x) => x.rel === r)) const center = hover === L.base const hi = hover && !center ? index.get(hover) : undefined const hp = hi != null ? layout!.pos[hi] : null const hpos = hi != null ? { x: toPx(cur.current[2 * hi]), y: toPx(cur.current[2 * hi + 1]) } : null const icon = Math.max(30, CENTER_R * k * 1.8) return (
e.pointerType === "mouse" && hit(e)} onPointerDown={(e) => { typeRef.current = e.pointerType; if (e.pointerType !== "mouse") { tapRef.current = hover; hit(e) } }} onPointerLeave={(e) => e.pointerType === "mouse" && setHover(null)} onClick={() => { const touch = typeRef.current !== "mouse" if (hover && (!touch || tapRef.current === hover)) window.open(hfUrl(hover), "_blank", "noopener") }} role="img" aria-label={`${full(L.n_models)} community models around ${name}`}> {size > 0 && (
)} {/* the entrance turns the canvas as one composited layer */}
{size > 0 && (
)} {layout?.rings.map((g) => size >= 480 && ( {RING_NAME[g.ring]} ))} {!layout && size > 0 && (
Placing {full(repos.length)} models…
)} {hover && (center || (hp && hpos)) && ( {center ? : } )}
) } function Card({ pos, size, children }: { pos: { x: number; y: number; r: number }; size: number; children: React.ReactNode }) { const W = 300 const right = pos.x + pos.r + 14 + W < size const left = right ? pos.x + pos.r + 14 : Math.max(0, pos.x - pos.r - 14 - W) const top = Math.min(Math.max(0, pos.y - 70), size - 250) return (
{children}
) } function Row({ k, v }: { k: string; v: React.ReactNode }) { return (
{k} {v}
) } function Model({ p, authors }: { p: P; authors: Record }) { const r = p.repo const [owner, name] = r.id.split("/") return ( <>
{name}
{authors[owner]?.n ?? owner}
{REL_NAME[r.rel]}} /> {r.up.startsWith("MiniMaxAI/") ? `${r.up.split("/")[1]} (official)` : r.up}} />
) } function Official({ L, authors, kidsN }: { L: Lineage; authors: Record; kidsN: number }) { return ( <>
{L.base.split("/")[1]}
MiniMax official
) }