Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
202 changes: 202 additions & 0 deletions bifrost/app/stats/MarketShareChart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
"use client";

import { useMemo } from "react";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
} from "recharts";
import { ChartConfig, ChartContainer } from "@/components/ui/chart";
import { CHART_COLOR_PALETTE } from "@/lib/chartColors";
import { Skeleton } from "@/components/ui/skeleton";
import { formatTokens, formatTooltipDate } from "@/utils/formatters";

interface AuthorTokens {
author: string;
totalTokens: number;
percentage: number;
}

interface TimeSeriesDataPoint {
time: string;
authors: AuthorTokens[];
}

interface MarketShareChartProps {
data: TimeSeriesDataPoint[];
isLoading: boolean;
}

function formatTimeLabel(time: string): string {
const date = new Date(time);
return date.toLocaleDateString([], { month: "short", day: "numeric" });
}

interface CustomTooltipProps {
active?: boolean;
payload?: Array<{
dataKey: string;
value: number;
fill: string;
payload: Record<string, unknown>;
}>;
chartConfig: ChartConfig;
rawData: TimeSeriesDataPoint[];
}

function CustomTooltip({
active,
payload,
chartConfig,
rawData,
}: CustomTooltipProps) {
if (!active || !payload?.length) return null;

const rawTime = payload[0]?.payload?.rawTime as string | undefined;
const originalPoint = rawData.find((p) => p.time === rawTime);
const sortedPayload = [...payload]
.filter((item) => item.value > 0)
.sort((a, b) => b.value - a.value);

return (
<div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 shadow-lg rounded-lg p-3 min-w-[220px]">
<div className="mb-3">
<span className="text-sm font-medium text-foreground">
{rawTime ? formatTooltipDate(rawTime) : ""}
</span>
</div>
<div className="space-y-2">
{sortedPayload.map((item) => {
const author = chartConfig[item.dataKey]?.label || item.dataKey;
const originalAuthor = originalPoint?.authors.find(
(a) => a.author === author
);
const tokens = originalAuthor?.totalTokens ?? 0;
const percentage = item.value;

return (
<div
key={item.dataKey}
className="flex items-center justify-between gap-4"
>
<div className="flex items-center gap-2">
<div
className="w-1 h-4 rounded-sm"
style={{ backgroundColor: item.fill }}
/>
<span className="text-sm text-gray-700 dark:text-gray-300">
{author}
</span>
</div>
<span className="text-xs font-medium tabular-nums text-gray-900 dark:text-gray-100">
{formatTokens(tokens)} ({percentage.toFixed(1)}%)
</span>
</div>
);
})}
</div>
</div>
);
}

export function MarketShareChart({ data, isLoading }: MarketShareChartProps) {
const { chartData, authors, chartConfig } = useMemo(() => {
const authorSet = new Set<string>();
data.forEach((point) => {
point.authors.forEach((a) => authorSet.add(a.author));
});
const authors = Array.from(authorSet);

const chartData = data.map((point) => {
const entry: Record<string, string | number> = {
time: formatTimeLabel(point.time),
rawTime: point.time,
};

const totalPercentage = point.authors.reduce(
(sum, a) => sum + a.percentage,
0
);

authors.forEach((author) => {
const found = point.authors.find((a) => a.author === author);
const rawPercentage = found?.percentage ?? 0;
const normalizedPercentage =
totalPercentage > 0 ? (rawPercentage / totalPercentage) * 100 : 0;
entry[author] = normalizedPercentage;
Comment on lines +120 to +130
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Unnecessary normalization that could introduce rounding inconsistencies. Backend already returns percentages that sum to ~100%, so re-normalizing may cause the chart to display values that don't match the raw data shown in tooltips.

Prompt To Fix With AI
This is a comment left during a code review.
Path: bifrost/app/stats/MarketShareChart.tsx
Line: 120:130

Comment:
**style:** Unnecessary normalization that could introduce rounding inconsistencies. Backend already returns percentages that sum to ~100%, so re-normalizing may cause the chart to display values that don't match the raw data shown in tooltips.

How can I resolve this? If you propose a fix, please make it concise.

});
return entry;
});

const chartConfig: ChartConfig = {};
authors.forEach((author, index) => {
chartConfig[author] = {
label: author,
color: CHART_COLOR_PALETTE[index % CHART_COLOR_PALETTE.length],
};
});

return { chartData, authors, chartConfig };
}, [data]);

if (isLoading) {
return <Skeleton className="h-[400px] w-full" />;
}

if (data.length === 0) {
return (
<div className="flex h-[400px] items-center justify-center text-gray-500 dark:text-gray-400">
No data available for this time period
</div>
);
}

return (
<ChartContainer config={chartConfig} className="h-[400px] w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData} barGap={1} barCategoryGap="8%">
<CartesianGrid
vertical={false}
stroke="#e5e7eb"
strokeOpacity={0.5}
/>
<XAxis
dataKey="time"
tickLine={false}
axisLine={false}
tickMargin={8}
minTickGap={50}
tick={{ fill: "#9ca3af", fontSize: 12 }}
/>
<YAxis
tickLine={false}
axisLine={false}
tickFormatter={(value) => `${Math.round(value)}%`}
width={50}
tick={{ fill: "#9ca3af", fontSize: 12 }}
domain={[0, 100]}
allowDataOverflow={true}
ticks={[0, 25, 50, 75, 100]}
/>
<Tooltip
cursor={{ fill: "rgba(0, 0, 0, 0.03)" }}
content={<CustomTooltip chartConfig={chartConfig} rawData={data} />}
/>
{authors.map((author, index) => (
<Bar
key={author}
dataKey={author}
stackId="a"
fill={CHART_COLOR_PALETTE[index % CHART_COLOR_PALETTE.length]}
radius={0}
/>
))}
</BarChart>
</ResponsiveContainer>
</ChartContainer>
);
}
169 changes: 169 additions & 0 deletions bifrost/app/stats/MarketShareLeaderboard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
"use client";

import { Skeleton } from "@/components/ui/skeleton";
import { CHART_COLOR_PALETTE } from "@/lib/chartColors";
import { ChevronUp, ChevronDown } from "lucide-react";
import { formatTokens } from "@/utils/formatters";

interface LeaderboardEntry {
rank: number;
author: string;
totalTokens: number;
marketShare: number;
rankChange: number | null;
marketShareChange: number | null;
}

interface MarketShareLeaderboardProps {
data: LeaderboardEntry[];
isLoading: boolean;
}

function RankChangeIndicator({ rankChange }: { rankChange: number | null }) {
if (rankChange === null || rankChange === 0 || !isFinite(rankChange)) {
return null;
}

if (rankChange > 0) {
return (
<span className="flex items-center text-green-600 dark:text-green-400">
<ChevronUp className="h-4 w-4" />
<span className="text-xs tabular-nums">{rankChange}</span>
</span>
);
}

return (
<span className="flex items-center text-red-600 dark:text-red-400">
<ChevronDown className="h-4 w-4" />
<span className="text-xs tabular-nums">{Math.abs(rankChange)}</span>
</span>
);
}

function MarketShareChangeIndicator({ change }: { change: number | null }) {
if (change === null || !isFinite(change) || isNaN(change)) {
return null;
}

if (Math.abs(change) < 0.05) {
return <span className="text-xs text-gray-400 tabular-nums">0.0%</span>;
}

const isPositive = change > 0;
const displayValue = Math.abs(change).toFixed(1);

return (
<span
className={`text-xs tabular-nums ${
isPositive
? "text-green-600 dark:text-green-400"
: "text-red-600 dark:text-red-400"
}`}
>
{isPositive ? "+" : "-"}
{displayValue}%
</span>
);
}

function LeaderboardItem({
entry,
colorIndex,
}: {
entry: LeaderboardEntry;
colorIndex: number;
}) {
const isOther = entry.author.toLowerCase() === "others";
const color = CHART_COLOR_PALETTE[colorIndex % CHART_COLOR_PALETTE.length];
const marketShare = isFinite(entry.marketShare) ? entry.marketShare : 0;
const totalTokens = isFinite(entry.totalTokens) ? entry.totalTokens : 0;

return (
<div className="flex items-start gap-3 py-3">
<span className="text-sm text-gray-500 dark:text-gray-400 w-6 text-right tabular-nums">
{entry.rank}.
</span>
<div
className="w-3 h-3 rounded-full mt-1 flex-shrink-0"
style={{ backgroundColor: color }}
/>
<div className="flex-1 min-w-0">
<span className="text-sm font-medium text-gray-900 dark:text-gray-100">
{entry.author}
</span>
</div>
<div className="w-10 flex justify-end">
{!isOther && <RankChangeIndicator rankChange={entry.rankChange} />}
</div>
<div className="text-right min-w-[70px]">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100 tabular-nums">
{marketShare.toFixed(1)}%
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 tabular-nums">
{formatTokens(totalTokens)}
</div>
<MarketShareChangeIndicator change={entry.marketShareChange} />
</div>
</div>
);
}

function LoadingSkeleton() {
return (
<div className="grid grid-cols-2 gap-x-8">
{[...Array(10)].map((_, i) => (
<div key={i} className="flex items-center gap-3 py-3">
<Skeleton className="w-6 h-4" />
<Skeleton className="w-3 h-3 rounded-full" />
<Skeleton className="flex-1 h-4" />
<Skeleton className="w-10 h-4" />
<div className="text-right">
<Skeleton className="w-12 h-4 mb-1" />
<Skeleton className="w-10 h-3 mb-1" />
<Skeleton className="w-8 h-3" />
</div>
</div>
))}
</div>
);
}

export function MarketShareLeaderboard({
data,
isLoading,
}: MarketShareLeaderboardProps) {
if (isLoading) {
return <LoadingSkeleton />;
}

if (data.length === 0) {
return (
<div className="flex h-[200px] items-center justify-center text-gray-500 dark:text-gray-400">
No data available
</div>
);
}

const leftColumn = data.slice(0, 5);
const rightColumn = data.slice(5, 10);

return (
<div className="grid grid-cols-2 gap-x-8">
<div className="divide-y divide-gray-100 dark:divide-gray-800">
{leftColumn.map((entry, index) => (
<LeaderboardItem key={entry.author} entry={entry} colorIndex={index} />
))}
</div>
<div className="divide-y divide-gray-100 dark:divide-gray-800">
{rightColumn.map((entry, index) => (
<LeaderboardItem
key={entry.author}
entry={entry}
colorIndex={index + 5}
/>
))}
</div>
</div>
);
}
Loading
Loading