Add Wakatime stats

This commit is contained in:
2026-02-27 01:24:59 +01:00
parent f5aa15e0f4
commit a93718b455
20 changed files with 1898 additions and 52 deletions

165
components/bar-chart.tsx Normal file
View File

@@ -0,0 +1,165 @@
"use client"
import { Bar, BarChart, LabelList, XAxis, YAxis, Cell } from "recharts"
import { cn } from "@/lib/utils"
import {
ChartContainer,
type ChartConfig,
} from "@/components/ui/chart"
const COLORS = [
"#4ade80",
"#60a5fa",
"#f87171",
"#fb923c",
"#c084fc",
]
const chartConfig = {
total_seconds: {
label: "Seconds",
},
} satisfies ChartConfig
type ChartData = {
language: string
total_seconds: number
label: string
}
interface MyBarChartProps {
data: ChartData[]
className?: string
}
interface MyBarChartSkeletonProps {
className?: string
}
export function MyBarChart({ data, className }: MyBarChartProps) {
return (
<ChartContainer
config={chartConfig}
className={cn("w-full overflow-visible", className)}
style={{ height: data.length * 28 }}
>
<BarChart
accessibilityLayer
data={data}
layout="vertical"
margin={{ right: 0, left: 0, top: 0, bottom: 0 }}
barSize={20}
barCategoryGap="10%"
style={{ overflow: "visible" }}
>
<YAxis dataKey="language" type="category" hide />
<XAxis dataKey="total_seconds" type="number" hide />
<Bar dataKey="total_seconds" layout="vertical" radius={4} isAnimationActive={false}>
{data.map((_, index) => (
<Cell key={index} fill={COLORS[index % COLORS.length]} />
))}
<LabelList
dataKey="label"
position="insideLeft"
offset={8}
fontSize={12}
content={({ x, y, height, value }) => (
<text
x={Number(x) + 10}
y={Number(y) + Number(height) / 2}
dominantBaseline="central"
fontSize={12}
className="fill-foreground"
style={{ whiteSpace: "nowrap" }}
>
{String(value)}
</text>
)}
/>
</Bar>
</BarChart>
</ChartContainer>
)
}
export function MyBarChartSkeleton({ className }: MyBarChartSkeletonProps) {
const fakeData = [
{ language: "a", total_seconds: 102000 },
{ language: "b", total_seconds: 59000 },
{ language: "c", total_seconds: 41000 },
{ language: "d", total_seconds: 28000 },
{ language: "e", total_seconds: 17000 },
]
return (
<ChartContainer
config={chartConfig}
className={cn("w-full overflow-visible animate-pulse", className)}
style={{ height: fakeData.length * 28 }}
>
<BarChart
data={fakeData}
layout="vertical"
margin={{ right: 0, left: 0, top: 0, bottom: 0 }}
barSize={20}
barCategoryGap="10%"
>
<YAxis dataKey="language" type="category" hide />
<XAxis dataKey="total_seconds" type="number" hide />
<Bar
dataKey="total_seconds"
layout="vertical"
fill="#6b7280"
radius={4}
opacity={0.3}
isAnimationActive={false}
/>
</BarChart>
</ChartContainer>
)
}
export function MyBarChartError({ className }: MyBarChartSkeletonProps) {
const fakeData = [
{ language: "a", total_seconds: 102000 },
{ language: "b", total_seconds: 59000 },
{ language: "c", total_seconds: 41000 },
{ language: "d", total_seconds: 28000 },
{ language: "e", total_seconds: 17000 },
]
return (
<div className={cn("relative w-full overflow-hidden", className)} style={{ height: fakeData.length * 28 }}>
<ChartContainer
config={chartConfig}
className="w-full overflow-visible"
style={{ height: fakeData.length * 28 }}
>
<BarChart
data={fakeData}
layout="vertical"
margin={{ right: 0, left: 0, top: 0, bottom: 0 }}
barSize={20}
barCategoryGap="10%"
>
<YAxis dataKey="language" type="category" hide />
<XAxis dataKey="total_seconds" type="number" hide />
<Bar
dataKey="total_seconds"
layout="vertical"
fill="#7f1d1d"
radius={4}
opacity={0.6}
isAnimationActive={false}
/>
</BarChart>
</ChartContainer>
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<span className="text-red-400 font-semibold text-sm select-none">
Failed to fetch Wakatime stats :/
</span>
</div>
</div>
)
}

36
components/code-block.tsx Normal file
View File

@@ -0,0 +1,36 @@
import * as React from 'react'
import CodeEditorPrimitive from '@uiw/react-textarea-code-editor'
import { cn } from '@/lib/utils'
function CodeEditor({
className,
...props
}: React.ComponentProps<typeof CodeEditorPrimitive>) {
return (
<CodeEditorPrimitive
data-slot="textarea"
className={cn(
'bg-transparent!',
'text-base! md:text-sm! field-sizing-content!',
'text-foreground! overflow-visible!',
'[&>.w-tc-editor-preview]:px-3! [&>.w-tc-editor-preview]:py-2! [&>.w-tc-editor-preview]:m-0! [&>.w-tc-editor-preview]:min-h-16!',
'[&>.w-tc-editor-preview]:rounded-md! [&>.w-tc-editor-preview]:bg-transparent! [&>.w-tc-editor-preview]:dark:bg-input/30! [&>.w-tc-editor-preview]:shadow-xs! [&>.w-tc-editor-preview]:transition-[color,box-shadow]!',
'[&>.w-tc-editor-preview]:text-base! [&>.w-tc-editor-preview]:md:text-sm! [&>.w-tc-editor-preview]:field-sizing-content!',
'[&>.w-tc-editor-preview]:text-foreground! [&>.w-tc-editor-preview]:placeholder:text-muted-foreground!',
'[&>.w-tc-editor-preview]:outline-none!',
'[&>.w-tc-editor-preview]:border! [&>.w-tc-editor-preview]:border-input!',
'[&>.w-tc-editor-text]:px-3! [&>.w-tc-editor-text]:py-2! [&>.w-tc-editor-text]:m-0!',
'[&>.w-tc-editor-text]:text-base! [&>.w-tc-editor-text]:md:text-sm! [&>.w-tc-editor-text]:field-sizing-content!',
'[&>.w-tc-editor-text]:text-foreground! [&>.w-tc-editor-text]:placeholder:text-muted-foreground! [&>.w-tc-editor-text]:opacity-100!',
'[&>.w-tc-editor-text]:subpixel-antialiased!',
'[&>.w-tc-editor-text]:disabled:cursor-not-allowed! [&:has(>.w-tc-editor-text:disabled)]:opacity-50!',
'[&:has(>.w-tc-editor-text[aria-invalid="true"])]:[&>.w-tc-editor-preview]:ring-destructive/20! dark:[&:has(>.w-tc-editor-text[aria-invalid="true"])]:[&>.w-tc-editor-preview]:ring-destructive/40! [&:has(>.w-tc-editor-text[aria-invalid="true"])]:[&>.w-tc-editor-preview]:border-destructive!',
className,
)}
{...props}
/>
)
}
export { CodeEditor }

View File

@@ -4,8 +4,8 @@ import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
export function ThemeProvider({
children,
...props
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

353
components/ui/chart.tsx Normal file
View File

@@ -0,0 +1,353 @@
"use client"
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import { cn } from "@/lib/utils"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
}
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
function ChartContainer({
id,
className,
children,
config,
...props
}: React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
}) {
const uniqueId = React.useId()
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-slot="chart"
data-chart={chartId}
className={cn(
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme || config.color
)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
function ChartTooltipContent({
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
}) {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey || item?.dataKey || item?.name || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
? config[label as keyof typeof config]?.label || label
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
}
if (!value) {
return null
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
className={cn("border-border/50 bg-background gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl grid min-w-32 items-start", className)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color || item.payload.fill || item.color
return (
<div
key={item.dataKey}
className={cn(
"[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label || item.name}
</span>
</div>
{item.value && (
<span className="text-foreground font-mono font-medium tabular-nums">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
const ChartLegend = RechartsPrimitive.Legend
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = "bottom",
nameKey,
}: React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean
nameKey?: string
}) {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload
.filter((item) => item.type !== "none")
.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={item.value}
className={cn(
"[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string
) {
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
}
return configLabelKey in config
? config[configLabelKey]
: config[key as keyof typeof config]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
}

View File

@@ -0,0 +1,44 @@
"use client"
import * as React from "react"
import { HoverCard as HoverCardPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function HoverCard({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
}
function HoverCardTrigger({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
return (
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
)
}
function HoverCardContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
return (
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
<HoverCardPrimitive.Content
data-slot="hover-card-content"
align={align}
sideOffset={sideOffset}
className={cn(
"data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground w-64 rounded-lg p-2.5 text-sm shadow-md ring-1 duration-100 z-50 origin-(--radix-hover-card-content-transform-origin) outline-hidden",
className
)}
{...props}
/>
</HoverCardPrimitive.Portal>
)
}
export { HoverCard, HoverCardTrigger, HoverCardContent }

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-muted rounded-md animate-pulse", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@@ -0,0 +1,25 @@
"use client"
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";
import { CodeEditor } from "@/components/code-block";
import { CircleHelp } from "lucide-react";
export function WakatimeHint() {
return (
<HoverCard openDelay={100}>
<HoverCardTrigger asChild>
<button className="text-muted-foreground hover:text-foreground transition-colors leading-none">
<CircleHelp size={24} />
</button>
</HoverCardTrigger>
<HoverCardContent className="w-[560px] p-0 mt-2 border-none shadow-none" side="bottom" align="center">
<CodeEditor
value={`const response = await fetch(\n "https://wakatime.com/api/v1/users/alixz/stats/last_30_days"\n);\nconst res = await response.json();\nconst data = res.data.languages.slice(0, 5);`}
language="ts"
readOnly
padding={0}
/>
</HoverCardContent>
</HoverCard>
)
}

37
components/wakatime.tsx Normal file
View File

@@ -0,0 +1,37 @@
import { MyBarChart, MyBarChartError } from "./bar-chart";
type WakatimeLanguage = {
name: string
total_seconds: number
text: string
}
export async function Wakatime({ className }: { className?: string }) {
try {
const response = await fetch("https://wakatime.com/api/v1/users/alixz/stats/last_30_days", {
method: "GET",
headers: {
"Authorization": `Basic ${process.env.WAKATIME}`
},
next: { revalidate: 3600 }
});
if (!response.ok) return <MyBarChartError className={className} />;
const res = await response.json();
if (!res?.data?.languages?.length) {
return <MyBarChartError className={className} />;
}
const data = res.data.languages.slice(0, 5).map((lang: WakatimeLanguage) => ({
language: lang.name,
total_seconds: lang.total_seconds,
label: `${lang.name} (${lang.text})`,
}));
return <MyBarChart className={className} data={data} />;
} catch {
return <MyBarChartError className={className} />;
}
}