File size: 11,892 Bytes
1187856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import React, { useCallback, useMemo, useRef, useState } from "react";
import { FaMedal } from "react-icons/fa";
import { contentValue, type LocalizedText } from "@/lib/i18n";
import {
  TRIWORLD_COLORS,
  TRIWORLD_TABLE_METRICS,
  type TriWorldBoardEntry,
} from "./metrics";
import { LocalizedMarkdown } from "./LocalizedMarkdown";

type MetricText = {
  code: string;
  label: LocalizedText;
  shortLabel: LocalizedText;
  title: LocalizedText;
  description?: LocalizedText;
};

type Props = {
  rows: TriWorldBoardEntry[];
  metricTexts: Record<string, MetricText>;
  descriptionText: LocalizedText;
};

const RANGE_SIZE = 20;

function DualText({ en, zh }: { en: React.ReactNode; zh: React.ReactNode }) {
  return (
    <>
      <span className="i18n-en">{en}</span>
      <span className="i18n-zh">{zh}</span>
    </>
  );
}

function displayScore(value: number | null | undefined): string {
  if (value === null || value === undefined || !Number.isFinite(Number(value))) return "TBA";
  return Number(value).toFixed(2);
}

function textFor(
  metricTexts: Record<string, MetricText>,
  code: string,
  fallback: string
): LocalizedText {
  return metricTexts[code]?.label || metricTexts[code]?.shortLabel || { en: fallback, zh: fallback };
}

function headerLines(value: string): string[] {
  const words = value.trim().split(/\s+/).filter(Boolean);
  if (words.length <= 2) return [value.trim()];
  const lines: string[] = [];
  for (let index = 0; index < words.length; index += 2) {
    lines.push(words.slice(index, index + 2).join(" "));
  }
  return lines;
}

function MetricHeaderText({ text }: { text: LocalizedText }) {
  const en = contentValue(text.en);
  const zh = contentValue(text.zh);
  return (
    <>
      {en ? (
        <span className="i18n-en twb-metric-header-text">
          {headerLines(en).map((line, index) => (
            <span className="twb-metric-header-line" key={`${line}-${index}`}>{line}</span>
          ))}
        </span>
      ) : null}
      {zh ? (
        <span className="i18n-zh twb-metric-header-text">
          {headerLines(zh).map((line, index) => (
            <span className="twb-metric-header-line" key={`${line}-${index}`}>{line}</span>
          ))}
        </span>
      ) : null}
    </>
  );
}

function valueFor(row: TriWorldBoardEntry, code: string): number | null {
  return code === "TWBScore" ? row.score : row.metrics[code] ?? null;
}

function isScore(value: number | null): value is number {
  return value !== null && Number.isFinite(value);
}

export function TriWorldLeaderboard({ rows, metricTexts, descriptionText }: Props) {
  const [query, setQuery] = useState("");
  const [highlightedName, setHighlightedName] = useState<string | null>(null);
  const [message, setMessage] = useState("");
  const rangeMenuRef = useRef<HTMLDetailsElement>(null);
  const rowRefs = useRef(new Map<string, HTMLTableRowElement>());

  const ranges = useMemo(() => {
    const total = Math.ceil(rows.length / RANGE_SIZE);
    return Array.from({ length: total }, (_, index) => {
      const start = index * RANGE_SIZE;
      const end = Math.min(start + RANGE_SIZE, rows.length);
      return { index, start, end, label: start === 0 ? `Top ${end}` : `Ranks ${start + 1}-${end}` };
    });
  }, [rows.length]);

  const metricRanks = useMemo(() => {
    const ranksByMetric = new Map<string, Map<TriWorldBoardEntry, number>>();

    for (const metric of TRIWORLD_TABLE_METRICS) {
      const rankedRows = rows
        .map((row) => ({ row, value: valueFor(row, metric.code) }))
        .filter((entry): entry is { row: TriWorldBoardEntry; value: number } => isScore(entry.value))
        .sort((left, right) => right.value - left.value);
      const ranks = new Map<TriWorldBoardEntry, number>();
      let previousValue: number | null = null;
      let previousRank = 0;

      rankedRows.forEach((entry, index) => {
        const rank = previousValue !== null && entry.value === previousValue ? previousRank : index + 1;
        ranks.set(entry.row, rank);
        previousValue = entry.value;
        previousRank = rank;
      });
      ranksByMetric.set(metric.code, ranks);
    }

    return ranksByMetric;
  }, [rows]);

  const locate = useCallback((name = query) => {
    const normalized = name.trim().toLocaleLowerCase();
    if (!normalized) {
      setHighlightedName(null);
      setMessage("");
      return;
    }
    const matched =
      rows.find((row) => row.modelName.toLocaleLowerCase() === normalized) ||
      rows.find((row) => row.modelName.toLocaleLowerCase().includes(normalized));
    if (!matched) {
      setHighlightedName(null);
      setMessage(`No published model matches "${name.trim()}".`);
      return;
    }
    setHighlightedName(matched.modelName);
    setMessage(`Located ${matched.modelName} at rank ${matched.rank}.`);
    window.requestAnimationFrame(() => {
      rowRefs.current.get(matched.modelName)?.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
    });
  }, [query, rows]);

  const jumpToRange = (start: number) => {
    const row = rows[start];
    if (!row) return;
    setHighlightedName(null);
    setMessage("");
    rangeMenuRef.current?.removeAttribute("open");
    window.requestAnimationFrame(() => {
      rowRefs.current.get(row.modelName)?.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
    });
  };

  return (
    <article className="twb-rich-card twb-overall twb-leaderboard-card">
      <p className="twb-board-note">
        <LocalizedMarkdown text={descriptionText} inline />
      </p>

      <div className="twb-leaderboard-controls">
        <details className="twb-rank-range-menu" ref={rangeMenuRef}>
          <summary>
            <DualText en={ranges[0]?.label || "Published ranks"} zh={ranges[0] ? ` ${ranges[0].end} ` : "已发布排名"} />
          </summary>
          <div className="twb-rank-range-options">
            {ranges.map((range) => (
              <button type="button" key={range.index} onClick={() => jumpToRange(range.start)}>
                <DualText
                  en={range.label}
                  zh={range.start === 0 ? ` ${range.end} ` : ` ${range.start + 1}-${range.end} `}
                />
              </button>
            ))}
          </div>
        </details>
        <form
          className="twb-model-locator"
          onSubmit={(event) => {
            event.preventDefault();
            locate();
          }}
        >
          <label htmlFor="leaderboard-model-locator"><DualText en="Locate model" zh="定位模型" /></label>
          <input
            id="leaderboard-model-locator"
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder="Model name"
            autoComplete="off"
          />
          <button type="submit"><DualText en="Locate" zh="定位" /></button>
        </form>
      </div>
      {message ? <p className="twb-locator-message" role="status">{message}</p> : null}

      <div className="twb-table-wrap" tabIndex={0} aria-label="TriWorldBench leaderboard">
        <table
          className="twb-dense-table"
          style={{ "--twb-score-column-count": TRIWORLD_TABLE_METRICS.length } as React.CSSProperties}
        >
          <thead>
            <tr>
              <th className="twb-model-col twb-sticky-col"><DualText en="Model" zh="模型" /></th>
              <th className="twb-col-rank twb-sticky-rank"><DualText en="#" zh="名次" /></th>
              {TRIWORLD_TABLE_METRICS.map((metric) => {
                const label = textFor(metricTexts, metric.code, metric.code);
                return (
                  <th
                    className={`${metric.className}${metric.isCategory ? " is-category" : ""}${metric.isOverall ? " is-overall" : ""} twb-metric-header`}
                    data-metric-code={metric.code}
                    key={metric.code}
                    style={{ "--metric-accent": metric.color } as React.CSSProperties}
                    title={metricTexts[metric.code]?.description?.en || label.en}
                  >
                    <MetricHeaderText text={label} />
                  </th>
                );
              })}
            </tr>
          </thead>
          <tbody>
            {rows.flatMap((row, index) => {
              const color = TRIWORLD_COLORS[index % TRIWORLD_COLORS.length];
              const range = ranges.find((item) => item.start === index);
              const isHighlighted = highlightedName === row.modelName;
              const entry = (
                <tr
                  key={row.modelName}
                  ref={(node) => {
                    if (node) rowRefs.current.set(row.modelName, node);
                    else rowRefs.current.delete(row.modelName);
                  }}
                  data-highlighted={isHighlighted ? "true" : undefined}
                  style={{ "--model-highlight": color } as React.CSSProperties}
                >
                  <td className="twb-model-col twb-sticky-col">
                    <b>{row.modelName}</b>
                    {row.teamName ? <small>{row.teamName}</small> : null}
                  </td>
                  <td className="twb-col-rank twb-sticky-rank"><span className="twb-rank-badge">{row.rank}</span></td>
                  {TRIWORLD_TABLE_METRICS.map((metric) => {
                    const value = valueFor(row, metric.code);
                    const metricRank = metricRanks.get(metric.code)?.get(row) ?? null;
                    return (
                      <td
                        className={`${metric.className} twb-metric-cell${metric.isCategory ? " twb-category-score" : ""}${metric.isOverall ? " twb-overall-score" : ""}`}
                        data-metric-code={metric.code}
                        data-metric-rank={metricRank ?? undefined}
                        key={metric.code}
                      >
                        <div className="twb-score-cell">
                          {metricRank !== null ? (
                            <span
                              className={`twb-cell-rank rank-${metricRank <= 3 ? metricRank : "other"}`}
                              aria-label={`Rank ${metricRank}`}
                            >
                              {metricRank <= 3 ? (
                                <FaMedal
                                  aria-hidden="true"
                                  className={`twb-cell-medal medal-${metricRank}`}
                                />
                              ) : null}
                              #{metricRank}
                            </span>
                          ) : null}
                          <span className="twb-score-value">{displayScore(value)}</span>
                        </div>
                      </td>
                    );
                  })}
                </tr>
              );
              return range
                ? [
                    <tr className="twb-subchart-row" key={`range-${range.index}`} id={`leaderboard-range-${range.index}`}>
                      <td className="twb-model-col twb-sticky-col twb-range-label-cell">
                        <DualText
                          en={range.label}
                          zh={range.start === 0 ? ` ${range.end} ` : ` ${range.start + 1}-${range.end} `}
                        />
                      </td>
                      <td className="twb-col-rank twb-sticky-rank twb-range-rank-cell" aria-hidden="true" />
                      <td className="twb-range-metric-cell" colSpan={TRIWORLD_TABLE_METRICS.length} aria-hidden="true" />
                    </tr>,
                    entry,
                  ]
                : [entry];
            })}
          </tbody>
        </table>
      </div>
    </article>
  );
}