File size: 16,581 Bytes
2471af3
 
 
 
 
0953253
 
2471af3
 
 
 
 
 
 
0953253
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0953253
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0953253
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0953253
2471af3
 
 
61db3dc
 
2471af3
 
 
61db3dc
 
 
2471af3
 
 
 
 
61db3dc
 
 
2471af3
 
 
 
61db3dc
 
2471af3
 
 
 
 
 
 
61db3dc
 
2471af3
 
 
 
 
 
 
 
 
61db3dc
2471af3
61db3dc
2471af3
 
 
 
 
 
 
61db3dc
2471af3
 
 
 
 
 
61db3dc
2471af3
61db3dc
2471af3
 
 
 
61db3dc
2471af3
61db3dc
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61db3dc
2471af3
61db3dc
2471af3
 
 
 
 
 
 
 
 
61db3dc
 
2471af3
 
 
 
 
61db3dc
2471af3
0953253
2471af3
 
 
 
 
 
61db3dc
2471af3
 
 
61db3dc
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
 
61db3dc
2471af3
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
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, isoDay, md, mdy, mon, num, toTime } from "@/lib/format"
import { catName, getLang, T } from "@/lib/i18n"

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", "PingFang SC", "Microsoft YaHei", "Noto Sans SC", 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) => (getLang() === "zh" ? (v >= 1e4 ? num(v) : String(v)) : 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()) : mon(isoDay(d.getTime())) })
    }
    // 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" ? T.chartModelsAria(value(g.top.at(-1) ?? 0)) : T.chartDownloadsAria(value(g.top.at(-1) ?? 0))}>
          <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) }} />
                  {catName(site.categories.find((x) => x.key === c) ?? { key: c, name: c })}
                </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>
  )
}