saladday1's picture
code: sync from git
61db3dc verified
Raw History Blame
21.5 kB
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 TILT = 1.02 // the disc leans back this far (radians from facing the camera)
const DIST = 3.4 // camera distance in disc radii: enough perspective to read depth, no fisheye
const SPIN = 0.045 // radians a second when left alone, a turn every two and a half minutes
const R_NEAR = 44 // the largest bubble, for headroom at the near rim
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. The rings lie on a disc seen in perspective: it turns slowly by itself (drag sideways to
* turn it), far bubbles recede and dim, and the biggest show their names as they come round to
* the front. Bubbles also drift a little while neighbouring rings sway against each other; all of
* it pauses while something is hovered or the picture is off screen, and the disc only moves by
* hand 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<string, Author>; name: string; cat: string
}) {
const [layout, setLayout] = useState<Layout | null>(null)
const [hover, setHover] = useState<string | null>(null)
const box = useRef<HTMLDivElement>(null)
const stageRef = useRef<HTMLDivElement>(null)
const canvas = useRef<HTMLCanvasElement>(null)
const tapRef = useRef<string | null>(null) // what was showing before this tap
const typeRef = useRef("mouse")
const hoverRef = useRef<string | null>(null)
const cur = useRef<Float32Array>(new Float32Array(0)) // current x, y of every bubble on the disc
const proj = useRef<Float32Array>(new Float32Array(0)) // where each lands on screen: x, y, scale
const view = useRef({ psi: 0, vel: 0, drag: false }) // the disc's turn, and a flick's speed
// 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, 1040)
const E = (layout?.extent ?? 300) + 8
// The disc seen from above at TILT, a camera DIST world-extents away: its far rim rises less
// than its near rim falls, so the centre sits above the middle of a wide, low picture; and the
// near half spreads wider than the disc itself, so the scale leaves room for that.
const sinT = Math.sin(TILT), cosT = Math.cos(TILT)
const sNear = DIST / (DIST - sinT), sFar = DIST / (DIST + sinT)
const spread = Math.max(...Array.from({ length: 90 }, (_, q) => Math.cos(q / 57.3) * DIST / (DIST - Math.sin(q / 57.3) * sinT)))
const k = size / (2 * E * spread + 2 * R_NEAR) // world -> px
const top = 34 + cosT * sFar * E * k
const height = Math.round(top + cosT * sNear * E * k + 16 + R_NEAR * sNear * k)
const cx = size / 2, cy = top
const index = useMemo(() => new Map(layout?.pos.map((p, i) => [p.id, i]) ?? []), [layout])
const kids = useMemo(() => {
const m = new Map<string, number[]>()
layout?.pos.forEach((p, i) => m.set(p.repo.up, [...(m.get(p.repo.up) ?? []), i]))
return m
}, [layout])
// The biggest bubbles carry their names while they are on the near half of the disc.
const labels = useMemo(() => {
if (!layout || size < 560) return []
const ctx = document.createElement("canvas").getContext("2d")!
ctx.font = LABEL_FONT
return layout.pos.map((p, i) => [p, i] as const).sort((x, y) => y[0].r - x[0].r).slice(0, 7)
.filter(([p]) => p.r * k >= 7).map(([p, i]) => ({ i, w: ctx.measureText(p.id).width + 22 }))
}, [layout, size, k])
const lit = useMemo(() => {
if (!hover || !layout) return null
const s = new Set<number>()
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<Set<number> | null>(null)
useEffect(() => {
hoverRef.current = hover
litRef.current = lit
}, [hover, lit])
// The animation loop: bubbles drift on the disc by a clock that runs while the picture is on
// screen and nothing is hovered; the disc turns slowly on its own and follows a drag.
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(height * dpr)
const ctx = cv.getContext("2d")!
const n = layout.pos.length
if (cur.current.length !== 2 * n) cur.current = new Float32Array(2 * n)
if (proj.current.length !== 3 * n) proj.current = new Float32Array(3 * n)
const order = Array.from({ length: n }, (_, i) => i)
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 still = matchMedia("(prefers-reduced-motion: reduce)").matches
let visible = true
const io = new IntersectionObserver(([e]) => (visible = e.isIntersecting))
io.observe(cv)
const cs = getComputedStyle(stage)
const colors = Object.fromEntries(ORDER.map((r) => [r, cs.getPropertyValue(`--rel-${r}`).trim() || "#888"]))
let clock = 0, last = performance.now(), raf = 0, born = -1
const v = view.current
const D = DIST * E
const frame = (now: number) => {
raf = requestAnimationFrame(frame)
const dt = Math.min(0.05, (now - last) / 1000)
last = now
if (!visible) return
if (born < 0) born = now
const hovering = hoverRef.current != null
if (!still && !hovering) clock += dt
if (!v.drag) {
v.psi += dt * ((still || hovering ? 0 : SPIN) + v.vel)
v.vel *= Math.pow(0.04, dt) // a flick coasts to a stop in about a second
}
// entrance: the disc swings round into place while it fades in
const e = still ? 1 : Math.min(1, (now - born) / 2200)
const ease = 1 - Math.pow(1 - e, 3)
const psi = v.psi - 1.4 * (1 - ease)
const cP = Math.cos(psi), sP = Math.sin(psi)
const t = clock
const c = cur.current, P = proj.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
const x = rho[i] * Math.cos(a) + amp[i] * Math.sin(t * fq[i] + ph[i])
const y = rho[i] * Math.sin(a) + amp[i] * Math.cos(t * fq[i] * 0.83 + ph[i] * 1.7)
c[2 * i] = x
c[2 * i + 1] = y
const xr = x * cP - y * sP, yr = x * sP + y * cP
const sc = D / (D - yr * sinT)
P[3 * i] = cx + xr * sc * k
P[3 * i + 1] = cy + yr * cosT * sc * k
P[3 * i + 2] = sc
}
order.sort((i, j) => P[3 * i + 2] - P[3 * j + 2]) // far first
const depth = (sc: number) => 0.3 + 0.7 * Math.min(1, Math.max(0, (sc - sFar) / (sNear - sFar)))
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
ctx.clearRect(0, 0, size, height)
ctx.globalAlpha = ease
// the orbits: each generation's band and its dashed rim, in perspective
const orbit = (R: number) => {
ctx.beginPath()
for (let s = 0; s <= 120; s++) {
const q = (s / 120) * Math.PI * 2, yr = R * Math.sin(q), sc = D / (D - yr * sinT)
const X = cx + R * Math.cos(q) * sc * k, Y = cy + yr * cosT * sc * k
if (s) ctx.lineTo(X, Y)
else ctx.moveTo(X, Y)
}
}
for (const g of layout.rings) {
orbit((g.inner + g.outer) / 2)
ctx.strokeStyle = "rgba(255,255,255,0.03)"
ctx.lineWidth = (g.outer - g.inner + 16) * k * cosT
ctx.setLineDash([])
ctx.stroke()
orbit(g.outer + 8)
ctx.strokeStyle = "rgba(255,255,255,0.16)"
ctx.lineWidth = 1
ctx.setLineDash([2, 6])
ctx.stroke()
}
ctx.setLineDash([])
const L2 = litRef.current
const hv = hoverRef.current
const hi = hv ? index.get(hv) : undefined
if (hv && L2) {
const ax = hi == null ? cx : P[3 * hi], ay = hi == null ? cy : P[3 * hi + 1]
ctx.strokeStyle = "rgba(255,255,255,0.6)"
ctx.lineWidth = 1.3
ctx.beginPath()
const link = (bx: number, by: number) => {
ctx.moveTo(ax, ay)
ctx.quadraticCurveTo(cx + ((ax + bx) / 2 - cx) * 0.82, cy + ((ay + by) / 2 - cy) * 0.82, bx, by)
}
for (const j of L2) if (j !== hi) link(P[3 * j], P[3 * j + 1])
if (hi != null && index.get(layout.pos[hi].repo.up) == null) link(cx, cy) // built on the official model
ctx.stroke()
}
for (const i of order) {
const sc = P[3 * i + 2]
ctx.globalAlpha = ease * depth(sc) * (L2 && !L2.has(i) ? 0.14 : 1)
ctx.fillStyle = colors[layout.pos[i].repo.rel]
ctx.beginPath()
ctx.arc(P[3 * i], P[3 * i + 1], Math.max(0.6, layout.pos[i].r * k * sc), 0, Math.PI * 2)
ctx.fill()
}
ctx.globalAlpha = ease
if (hi != null) {
ctx.beginPath()
ctx.arc(P[3 * hi], P[3 * hi + 1], layout.pos[hi].r * k * P[3 * hi + 2] + 1.5, 0, Math.PI * 2)
ctx.strokeStyle = "#fff"
ctx.lineWidth = 2
ctx.stroke()
}
// generation names on the far rim of each orbit, bubble names on the near half
ctx.font = LABEL_FONT
ctx.textAlign = "center"
ctx.textBaseline = "middle"
const pill = (text: string, x: number, y: number, lw: number, ink: string) => {
ctx.beginPath()
ctx.roundRect(x - lw / 2, y, lw, 26, 13)
ctx.fillStyle = "rgba(10,10,12,0.86)"
ctx.fill()
ctx.strokeStyle = "rgba(255,255,255,0.12)"
ctx.lineWidth = 1
ctx.stroke()
ctx.fillStyle = ink
ctx.fillText(text, x, y + 13.5)
}
if (size >= 480)
for (const g of layout.rings) {
const R = g.outer + 8, sc = D / (D + R * sinT)
const text = RING_NAME[g.ring]
ctx.globalAlpha = ease * 0.9
pill(text, cx, cy - R * cosT * sc * k - 13, ctx.measureText(text).width + 24, "rgba(255,255,255,0.62)")
}
const placed: number[][] = []
for (const { i, w: lw } of labels) {
const sc = P[3 * i + 2]
const front = (sc - 1) / (sNear - 1) // 0 at the sides, 1 at the near rim
if (front <= 0.05) continue
const x = P[3 * i], y = P[3 * i + 1] + layout.pos[i].r * k * sc + 6
const box = [x - lw / 2 - 6, x + lw / 2 + 6, y - 4, y + 30]
if (placed.some((q) => box[0] < q[1] && box[1] > q[0] && box[2] < q[3] && box[3] > q[2])) continue
placed.push(box)
ctx.globalAlpha = ease * Math.min(1, front * 2.5) * (L2 && !L2.has(i) ? 0.2 : 1)
pill(layout.pos[i].id, x, y, lw, "#fff")
}
ctx.globalAlpha = 1
}
raf = requestAnimationFrame(frame)
return () => {
cancelAnimationFrame(raf)
io.disconnect()
}
}, [layout, size, height, k, labels, index, cx, cy, sinT, cosT, sNear, sFar, E])
// Nearest bubble under the pointer, front ones first; the middle is the official model.
const hit = (e: React.PointerEvent) => {
if (!layout) return
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
const px = e.clientX - rect.left, py = e.clientY - rect.top
const P = proj.current
let best = -1, bs = -1
for (let i = 0; i < layout.pos.length; i++) {
const sc = P[3 * i + 2]
if (Math.hypot(P[3 * i] - px, P[3 * i + 1] - py) < layout.pos[i].r * k * sc + 4 && sc > bs) { best = i; bs = sc }
}
if (best >= 0) return setHover(layout.pos[best].id)
setHover(Math.hypot((px - cx) / 1, (py - cy) / cosT) < CENTER_R * k ? L.base : null)
}
// Dragging sideways turns the disc; a flick keeps it turning for a moment.
const drag = useRef({ x: 0, t: 0, moved: 0, down: false })
const onDown = (e: React.PointerEvent) => {
drag.current = { x: e.clientX, t: performance.now(), moved: 0, down: true }
view.current.drag = true
view.current.vel = 0
}
const onDrag = (e: React.PointerEvent) => {
const d = drag.current
if (!d.down) return false
const dx = e.clientX - d.x, now = performance.now()
d.moved += Math.abs(dx)
if (d.moved > 4) {
view.current.psi += dx * 0.006
view.current.vel = (dx * 0.006) / Math.max(0.008, (now - d.t) / 1000)
}
d.x = e.clientX
d.t = now
return d.moved > 4
}
const onUp = () => {
drag.current.down = false
view.current.drag = false
view.current.vel = Math.max(-2, Math.min(2, view.current.vel))
}
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: proj.current[3 * hi], y: proj.current[3 * hi + 1], s: proj.current[3 * hi + 2] } : null
const icon = Math.max(30, CENTER_R * k * 1.6)
return (
<div ref={stageRef} className="dark stage relative isolate overflow-hidden rounded-[28px] px-4 pt-8 pb-6 sm:px-8 sm:pt-10">
<div aria-hidden className="pointer-events-none absolute top-[55%] left-1/2 -z-10 h-[60%] w-[80%] -translate-x-1/2 -translate-y-1/2 rounded-full opacity-25 blur-[120px]"
style={{ background: `radial-gradient(ellipse, ${catTo(cat)}, transparent 70%)` }} />
<DownloadButton target={stageRef} name={`${name} galaxy`} tone="stage" className="absolute top-[26px] right-4 z-20 sm:top-[34px] sm:right-8" />
<RelLegend rels={present} className="pr-12 text-white/70" />
<div ref={box} className="w-full">
<div className="relative mx-auto touch-pan-y select-none" style={{ width: size, height, cursor: hover ? "pointer" : "grab" }}
onPointerMove={(e) => {
if (onDrag(e)) return setHover(null)
if (e.pointerType === "mouse") hit(e)
}}
onPointerDown={(e) => {
typeRef.current = e.pointerType
onDown(e)
if (e.pointerType !== "mouse") { tapRef.current = hover; hit(e) }
}}
onPointerUp={onUp}
onPointerCancel={onUp}
onPointerLeave={(e) => { onUp(); if (e.pointerType === "mouse") setHover(null) }}
onClick={() => {
if (drag.current.moved > 4) return
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 && (
<div aria-hidden className="pointer-events-none absolute rounded-full blur-[30px]"
style={{ left: cx - icon, top: cy - icon * 0.8, width: icon * 2, height: icon * 1.6,
background: `radial-gradient(ellipse, ${catTo(cat)}, ${catFrom(cat)} 45%, transparent 70%)`,
opacity: 0.8, animation: "breathe 4s ease-in-out infinite" }} />
)}
<canvas ref={canvas} className="absolute inset-0" style={{ width: size, height }} />
{size > 0 && (
<div className="pointer-events-none absolute" title={name}
style={{ left: cx - icon / 2, top: cy - icon * 0.62, opacity: hover && !center ? 0.5 : 1,
animation: "pop 900ms cubic-bezier(.34,1.56,.64,1) 300ms both" }}>
<Octopus size={icon} />
</div>
)}
{!layout && size > 0 && (
<div className="absolute inset-0 grid place-items-center text-[15px] text-white/60">Placing {full(repos.length)} models…</div>
)}
{hover && (center || (hp && hpos)) && (
<Card pos={center ? { x: cx, y: cy, r: icon / 2 } : { x: hpos!.x, y: hpos!.y, r: hp!.r * k * hpos!.s }} size={size} height={height}>
{center ? <Official L={L} authors={authors} kidsN={L.n_models} /> : <Model p={hp!} authors={authors} />}
</Card>
)}
</div>
</div>
</div>
)
}
function Card({ pos, size, height, children }: { pos: { x: number; y: number; r: number }; size: number; height: 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), Math.max(0, height - 250))
return (
<div className="pointer-events-none absolute z-10 rounded-2xl border border-white/12 bg-[#15151c]/92 p-4 text-[15px] text-white shadow-[0_18px_40px_rgba(0,0,0,0.5)] backdrop-blur-md"
style={{ left, top, width: W }}>
{children}
</div>
)
}
function Row({ k, v }: { k: string; v: React.ReactNode }) {
return (
<div className="flex justify-between gap-4">
<span className="text-white/55">{k}</span>
<span className="text-right tabular-nums">{v}</span>
</div>
)
}
function Model({ p, authors }: { p: P; authors: Record<string, Author> }) {
const r = p.repo
const [owner, name] = r.id.split("/")
return (
<>
<div className="mb-3 flex items-center gap-3">
<Who name={owner} authors={authors} size="size-11" />
<div className="min-w-0">
<div className="font-semibold break-all leading-snug">{name}</div>
<div className="truncate text-white/55">{authors[owner]?.n ?? owner}</div>
</div>
</div>
<div className="space-y-1.5">
<Row k="Type" v={<span className="inline-flex items-center gap-2"><RelDot rel={r.rel} />{REL_NAME[r.rel]}</span>} />
<Row k="Built on" v={<span className="break-all">{r.up.startsWith("MiniMaxAI/") ? `${r.up.split("/")[1]} (official)` : r.up}</span>} />
<Row k="Downloads" v={fmt(r.dlall)} />
<Row k="Last 30 days" v={fmt(r.dl30)} />
<Row k="Likes" v={full(r.likes)} />
<Row k="Created" v={r.created ? mdy(r.created) : "–"} />
</div>
</>
)
}
function Official({ L, authors, kidsN }: { L: Lineage; authors: Record<string, Author>; kidsN: number }) {
return (
<>
<div className="mb-3 flex items-center gap-3">
<Who name="MiniMaxAI" authors={authors} size="size-11" />
<div className="min-w-0">
<div className="font-semibold">{L.base.split("/")[1]}</div>
<div className="text-white/55">MiniMax official</div>
</div>
</div>
<div className="space-y-1.5">
<Row k="Downloads" v={fmt(L.official.dlall)} />
<Row k="Last 30 days" v={fmt(L.official.dl30)} />
<Row k="Likes" v={full(L.official.likes)} />
<Row k="Community models" v={full(kidsN)} />
</div>
</>
)
}