saladday1's picture
code: sync from git
2471af3 verified
Raw History Blame
18.2 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 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<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
// 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<string, number[]>()
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<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: 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<Rel, number[]>()
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<string, string> = {}
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 (
<div ref={stageRef} className="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-1/2 left-1/2 -z-10 size-[70%] -translate-x-1/2 -translate-y-1/2 rounded-full opacity-20 blur-[120px]"
style={{ background: `radial-gradient(circle, ${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 select-none" style={{ width: size, height: size }}
onPointerMove={(e) => 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 && (
<div aria-hidden className="pointer-events-none absolute rounded-full blur-[30px]"
style={{ left: size / 2 - icon, top: size / 2 - icon, width: icon * 2, height: icon * 2,
background: `radial-gradient(circle, ${catTo(cat)}, ${catFrom(cat)} 45%, transparent 70%)`,
opacity: 0.8, animation: "breathe 4s ease-in-out infinite" }} />
)}
{/* the entrance turns the canvas as one composited layer */}
<div className="absolute inset-0" style={{ animation: "unfold 1500ms cubic-bezier(.22,.61,.36,1) both", transformOrigin: "50% 50%" }}>
<canvas ref={canvas} className="absolute inset-0" style={{ width: size, height: size }} />
</div>
{size > 0 && (
<div className="pointer-events-none absolute" title={name}
style={{ left: size / 2 - icon / 2, top: size / 2 - icon / 2, opacity: hover && !center ? 0.5 : 1,
animation: "pop 900ms cubic-bezier(.34,1.56,.64,1) 300ms both" }}>
<Octopus size={icon} />
</div>
)}
{layout?.rings.map((g) => size >= 480 && (
<span key={g.ring} className="pointer-events-none absolute -translate-x-1/2 rounded-full border border-white/10 bg-[var(--stage)] px-3 py-0.5 text-sm whitespace-nowrap text-white/60"
style={{ left: size / 2, top: toPx(-g.outer - 8) - 12, animation: "fade 600ms ease-out 900ms both" }}>
{RING_NAME[g.ring]}
</span>
))}
{!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: size / 2, y: size / 2, r: icon / 2 } : { x: hpos!.x, y: hpos!.y, r: hp!.r * k }} size={size}>
{center ? <Official L={L} authors={authors} kidsN={L.n_models} /> : <Model p={hp!} authors={authors} />}
</Card>
)}
</div>
</div>
</div>
)
}
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 (
<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>
</>
)
}