oss-ecosystem-data / code /web /src /components /community-chart.tsx
saladday1's picture
code: sync from git
61db3dc verified
Raw History Blame
16.5 kB
import { useEffect, useMemo, useRef, useState } from "react"
import { area, curveMonotoneX, line, stack } from "d3-shape"
import { scaleLinear } from "d3-scale"
import type { Release, Site } from "@/lib/types"
import { CAT_ORDER, catColor, shortName } from "@/lib/category"
import { DAY, full, md, mdy, num, toTime } from "@/lib/format"
type Row = { t: number } & Record<string, number>
export type Series = { rows: Row[]; cats: string[]; start: number; end: number }
export type Metric = "models" | "downloads"
/** A milestone: releases within three weeks share one pole. Names sit right of the pole, or
* left of it (`side`) when the right is taken; with no room either side only the pole shows. */
type Pin = { t: number; key: string; rels: Release[]; cat: string; side: "right" | "left" | "none" }
const NAME_FONT = '500 15px "Outfit Variable", system-ui, sans-serif'
let measurer: CanvasRenderingContext2D | null = null
const textWidth = (s: string) => {
measurer ??= document.createElement("canvas").getContext("2d")!
measurer.font = NAME_FONT
return measurer.measureText(s).width
}
const REVEAL = 2000 // ms for the curve to sweep in
/** A shared pin opens the release that has its own page, if one does. */
const pick = (rs: Release[]) => rs.find((r) => r.page) ?? rs[0]
const LINE_H = 24 // one release name in the milestone row
const ROW_TOP = 14 // centre of the first name, where every pole starts
/** Cumulative community models per modality, one point a week from our first release to today. */
export function useSeries(site: Site): Series {
return useMemo(() => {
const first = Math.min(...site.releases.map((r) => toTime(r.date)))
const d = new Date(first - 20 * DAY)
const start = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1)
const end = toTime(site.today)
const ts: number[] = []
for (let t = start; t < end; t += 7 * DAY) ts.push(t)
ts.push(end)
const cats = CAT_ORDER.filter((c) => site.categories.some((x) => x.key === c))
const rows: Row[] = ts.map((t) => ({ t }) as Row)
for (const c of cats) {
const ev = site.releases.filter((r) => r.cat === c).flatMap((r) => r.growth.map(([s, n]) => [toTime(s), n] as const))
.sort((a, b) => a[0] - b[0])
let i = 0, run = 0
for (const row of rows) {
while (i < ev.length && ev[i][0] <= row.t) run += ev[i++][1]
row[c] = run
}
}
return { rows, cats, start, end }
}, [site])
}
/** All-time downloads by modality, of MiniMax models and everything built on them, about
* weekly, on the same time axis as the models. */
export function useDownloadSeries(site: Site, base: Series): Series | null {
return useMemo(() => {
const d = site.dl_total
if (!d?.days.length) return null
const rows = d.days.map((day, i) => ({ t: toTime(day), ...Object.fromEntries(base.cats.map((c) => [c, d.cats[c]?.[i] ?? 0])) }) as Row)
rows.unshift({ t: base.start, ...Object.fromEntries(base.cats.map((c) => [c, 0])) } as Row)
return { rows, cats: base.cats, start: base.start, end: base.end }
}, [site, base])
}
/** The box sets the size (its height comes from the page, so the hero can fit the first screen). */
export function CommunityChart({ site, series, metric, hidden, onPick, className }: {
site: Site; series: Series; metric: Metric; hidden: Set<string>; onPick: (r: Release) => void; className: string
}) {
const box = useRef<HTMLDivElement>(null)
const [[W, H], setSize] = useState([0, 0])
const [hover, setHover] = useState<number | null>(null)
const pointer = useRef("mouse") // a tap previews; only a mouse click on the plot opens a release
useEffect(() => {
const el = box.current
if (!el) return
const ro = new ResizeObserver(() => setSize([el.clientWidth, el.clientHeight]))
ro.observe(el)
return () => ro.disconnect()
}, [])
const { rows, cats, start, end } = series
const last = rows.at(-1)!.t
const value = metric === "models" ? (v: number) => full(Math.round(v)) : (v: number) => num(v)
const tick = (v: number) => (v >= 1e6 ? num(v) : v >= 1000 ? `${v / 1000}K` : String(v))
const keys = cats.filter((c) => !hidden.has(c))
const narrow = W < 640
// Phones get the dots on the curve only; the release cards below carry the names.
const m = { l: 4, r: narrow ? 44 : 60, t: narrow ? 24 : ROW_TOP + LINE_H + 40, b: 40 }
const g = useMemo(() => {
if (!W || !H) return null
const x = scaleLinear().domain([start, end]).range([m.l, W - m.r])
const stacked = stack<Row>().keys(keys)(rows)
const top = rows.map((_, i) => (stacked.length ? stacked[stacked.length - 1][i][1] : 0))
const y = scaleLinear().domain([0, Math.max(10, ...top)]).nice(5).range([H - m.b, m.t])
const areaGen = area<[number, number] & { data: Row }>().x((d) => x(d.data.t)).y0((d) => y(d[0])).y1((d) => y(d[1]))
.curve(curveMonotoneX)
const edge = line<[number, number] & { data: Row }>().x((d) => x(d.data.t)).y((d) => y(d[1])).curve(curveMonotoneX)
const topLine = line<number>().x((_, i) => x(rows[i].t)).y((v) => y(v)).curve(curveMonotoneX)(top) ?? ""
const valueAt = (t: number) => {
const i = rows.findIndex((r) => r.t >= t)
if (i <= 0) return top[Math.max(0, i)] ?? 0
const a = rows[i - 1], b = rows[i]
return top[i - 1] + ((top[i] - top[i - 1]) * (t - a.t)) / (b.t - a.t)
}
// Releases within three weeks of each other share one pole, names stacked under each other.
const sorted = [...site.releases].sort((a, b) => a.date.localeCompare(b.date))
const groups: Release[][] = []
for (const r of sorted) {
const last = groups.at(-1)
if (last && toTime(r.date) - toTime(last[0].date) <= 21 * DAY) last.push(r)
else groups.push([r])
}
const width = (rs: Release[]) => Math.max(...rs.map((r) => textWidth(shortName(r.name)))) + 22
const pins: Pin[] = []
let taken = -Infinity // right edge of the last name block placed
groups.forEach((rs, i) => {
const t = toTime(rs[0].date), px = x(t), w = width(rs)
const next = i + 1 < groups.length ? x(toTime(groups[i + 1][0].date)) : Infinity
const prev = i > 0 ? x(toTime(groups[i - 1][0].date)) : -Infinity
let side: Pin["side"] = "none"
if (px - 5 + w < Math.min(next - 8, W + 8) && px - 5 > taken + 8) side = "right"
else if (px + 5 - w > Math.max(taken, prev) + 10) side = "left"
if (side === "right") taken = px - 5 + w
else if (side === "left") taken = Math.max(taken, px + 5)
pins.push({ t, key: rs.map((r) => r.key).join("+"), rels: rs, cat: rs[0].cat, side })
})
const ticksY = y.ticks(5)
const ticksX: { t: number; label: string }[] = []
for (let d = new Date(start); d.getTime() <= end; d.setUTCMonth(d.getUTCMonth() + 3)) {
const mo = d.getUTCMonth()
if (mo % 3) { d.setUTCMonth(mo - (mo % 3)); continue }
ticksX.push({ t: d.getTime(), label: mo === 0 ? String(d.getUTCFullYear()) : ["Jan", "Apr", "Jul", "Oct"][mo / 3] })
}
// Quarters when there is room, otherwise half-years; years always win a place.
const minGap = narrow ? 44 : 60
const xt: typeof ticksX = []
for (const tk of ticksX) {
const px = x(tk.t)
if (px < m.l + 12 || px > W - m.r - 10) continue
if (narrow && !["Jan", "Jul"].includes(new Date(tk.t).toUTCString().slice(8, 11))) continue
const prev = xt.at(-1)
if (prev && px - x(prev.t) < minGap) {
if (tk.label.length === 4) xt[xt.length - 1] = tk
continue
}
xt.push(tk)
}
return { x, y, stacked, top, areaGen, edge, topLine, valueAt, pins, ticksY, xt }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [W, H, rows, keys.join(), site, narrow])
useEffect(() => setHover(null), [metric])
const onMove = (e: React.PointerEvent) => {
if (!g) return
const rect = (e.currentTarget as SVGElement).getBoundingClientRect()
const t = g.x.invert(e.clientX - rect.left)
let best = 0
for (let i = 0; i < rows.length; i++) if (Math.abs(rows[i].t - t) < Math.abs(rows[best].t - t)) best = i
setHover(best)
}
const hr = hover != null ? rows[hover] : null
const near = hr && g ? g.pins.find((p) => p.rels.some((r) => Math.abs(toTime(r.date) - hr.t) <= 4 * DAY)) : null
const [lit, setLit] = useState<string | null>(null)
const plotW = W - m.l - m.r
return (
<div ref={box} className={`relative w-full select-none ${className}`}>
{g && H > 0 && (
<svg width={W} height={H} className="absolute inset-0 overflow-visible" role="img"
aria-label={metric === "models" ? `Community models built on MiniMax, ${value(g.top.at(-1) ?? 0)} today`
: `Downloads of MiniMax models and everything built on them, ${value(g.top.at(-1) ?? 0)} in all`}>
<defs>
{keys.map((c) => (
<linearGradient key={c} id={`fill-${c}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" style={{ stopColor: catColor(c), stopOpacity: 0.42 }} />
<stop offset="1" style={{ stopColor: catColor(c), stopOpacity: 0.05 }} />
</linearGradient>
))}
<linearGradient id="top-stroke" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stopColor="#171717" stopOpacity={0.35} />
<stop offset="0.7" stopColor="#171717" stopOpacity={0.85} />
<stop offset="1" stopColor="#171717" />
</linearGradient>
</defs>
{g.ticksY.map((v) => (
<g key={v}>
<line x1={m.l} x2={W - m.r} y1={g.y(v)} y2={g.y(v)} stroke="var(--foreground)" strokeOpacity={v === 0 ? 0.22 : 0.06} />
<text x={W - m.r + 12} y={g.y(v)} dy="0.35em" fontSize={14} fill="var(--muted-foreground)"
fillOpacity={Math.abs(g.y(v) - g.y(g.top.at(-1) ?? 0)) < 16 ? 0 : 1}
className="font-display tabular-nums">{tick(v)}</text>
</g>
))}
{g.xt.map((tk) => (
<text key={tk.t} x={g.x(tk.t)} y={H - m.b + 26} textAnchor="middle" fontSize={14}
fill={tk.label.length === 4 ? "var(--foreground)" : "var(--muted-foreground)"} className="font-display">{tk.label}</text>
))}
{/* the milestones: every pole starts on the same line at the top and ends on the curve */}
{!narrow && g.pins.map((p) => {
const px = g.x(p.t), py = g.y(g.valueAt(p.t))
const on = lit === p.key || near === p
return (
<line key={p.key} x1={px} x2={px} y1={ROW_TOP} y2={py - 8} stroke="var(--foreground)" strokeDasharray="2 5"
strokeOpacity={on ? 0.6 : 0.2} className="transition-[stroke-opacity] duration-200"
style={{ animation: `fade 500ms ease-out ${(REVEAL * (px - m.l)) / plotW}ms both` }} />
)
})}
<g key={metric} style={{ animation: `wipe ${REVEAL}ms cubic-bezier(.65,0,.35,1) both` }}>
{g.stacked.map((s) => (
<path key={s.key} d={g.areaGen(s as never) ?? ""} fill={`url(#fill-${s.key})`} />
))}
{g.stacked.map((s) => (
<path key={s.key} d={g.edge(s as never) ?? ""} fill="none" stroke={catColor(s.key)} strokeWidth={1.5} />
))}
<path d={g.topLine} fill="none" stroke="url(#top-stroke)" strokeWidth={2} strokeLinecap="round" />
</g>
{g.pins.map((p) => {
const px = g.x(p.t), py = g.y(g.valueAt(p.t))
const delay = (REVEAL * (px - m.l)) / plotW
return (
<g key={`${metric}:${p.key}`} style={{ animation: `pop 520ms cubic-bezier(.34,1.56,.64,1) ${delay}ms both`, transformOrigin: `${px}px ${py}px` }}>
<circle cx={px} cy={py} r={6.5} fill="#fff" stroke={catColor(p.cat)} strokeWidth={2.5} />
</g>
)
})}
{/* today */}
<g key={`now:${metric}`} style={{ animation: `fade 400ms ease-out ${REVEAL}ms both` }}>
<circle cx={g.x(last)} cy={g.y(g.top.at(-1) ?? 0)} r={14} fill="var(--brand)" opacity={0.22}
style={{ animation: "breathe 2.8s ease-in-out infinite", transformOrigin: `${g.x(last)}px ${g.y(g.top.at(-1) ?? 0)}px` }} />
<circle cx={g.x(last)} cy={g.y(g.top.at(-1) ?? 0)} r={5} fill="#171717" />
</g>
{hr && (
<g pointerEvents="none">
<line x1={g.x(hr.t)} x2={g.x(hr.t)} y1={m.t - 8} y2={H - m.b} stroke="var(--foreground)" strokeOpacity={0.3} />
{g.stacked.map((s) => (
<circle key={s.key} cx={g.x(hr.t)} cy={g.y(s[hover!][1])} r={4.5} fill={catColor(s.key)} stroke="#fff" strokeWidth={2} />
))}
</g>
)}
<rect x={m.l} y={m.t - 10} width={plotW} height={H - m.b - m.t + 10} fill="transparent"
onPointerMove={onMove} onPointerDown={(e) => { pointer.current = e.pointerType; onMove(e) }}
onPointerLeave={(e) => e.pointerType === "mouse" && setHover(null)}
onClick={() => near && pointer.current === "mouse" && onPick(pick(near.rels))}
style={{ cursor: near ? "pointer" : "crosshair" }} />
</svg>
)}
{/* names are HTML so they stay crisp, focusable and clickable; each dot sits on its pole */}
{g && !narrow && g.pins.map((p) => p.side !== "none" && (
<div key={p.key} className="absolute flex flex-col"
style={{ top: ROW_TOP - LINE_H / 2, height: LINE_H * p.rels.length,
...(p.side === "left" ? { right: W - g.x(p.t) - 5, alignItems: "flex-end" } : { left: g.x(p.t) - 5 }),
animation: `fade 500ms ease-out ${(REVEAL * (g.x(p.t) - m.l)) / plotW}ms both` }}
onPointerEnter={() => setLit(p.key)} onPointerLeave={() => setLit(null)}>
{p.rels.map((r) => (
<button key={r.key} type="button" onClick={() => onPick(r)}
className={`group inline-flex items-center gap-2.5 font-display text-[15px] leading-none font-medium whitespace-nowrap text-foreground/75 transition-colors hover:text-foreground ${p.side === "left" ? "flex-row-reverse" : ""}`}
style={{ height: LINE_H }}>
<span className="size-2.5 shrink-0 rounded-full ring-2 ring-white transition-transform group-hover:scale-125"
style={{ background: catColor(r.cat) }} />
{shortName(r.name)}
</button>
))}
</div>
))}
{g && hr && (
<Tip x={g.x(hr.t)} W={W} top={m.t}>
<div className="text-[15px] text-muted-foreground">{mdy(new Date(hr.t).toISOString())}</div>
<div className="mt-1 font-display text-[28px] leading-tight font-semibold tabular-nums">
{value(keys.reduce((a, c) => a + hr[c], 0))}
</div>
<div className="mt-2 space-y-1">
{[...keys].reverse().filter((c) => hr[c] > 0).map((c) => (
<div key={c} className="flex items-center justify-between gap-6 text-[15px]">
<span className="inline-flex items-center gap-2 text-foreground/75">
<span className="size-2.5 rounded-full" style={{ background: catColor(c) }} />
{site.categories.find((x) => x.key === c)?.name}
</span>
<span className="font-display tabular-nums">{value(hr[c])}</span>
</div>
))}
</div>
{near && (
<div className="mt-3 border-t border-border pt-2.5 text-[15px]">
{near.rels.map((r) => (
<div key={r.key} className="flex items-center justify-between gap-6">
<span className="font-medium">{r.name}</span>
<span className="text-muted-foreground">{md(r.date)}</span>
</div>
))}
</div>
)}
</Tip>
)}
</div>
)
}
function Tip({ x, W, top, children }: { x: number; W: number; top: number; children: React.ReactNode }) {
const w = 248
const left = x + 18 + w < W ? x + 18 : Math.max(0, x - 18 - w)
return (
<div className="pointer-events-none absolute z-10 rounded-2xl border border-border bg-white/95 p-4 text-foreground shadow-[0_18px_40px_-12px_rgba(23,23,23,0.25)] backdrop-blur-md"
style={{ left, top, width: w }}>
{children}
</div>
)
}