Compare commits

...

106 Commits

Author SHA1 Message Date
J Master Pig
14b69341a2
Merge External API into Persona Framework
Persona Framework
2025-07-02 01:18:44 +07:00
xampleth
927648c6d1 updated external api docs
added vision openai supported on external api
2025-06-30 21:52:59 +07:00
xampleth
d48d5e3dcb fixed brain message not displayed 2025-06-28 11:18:52 +07:00
xampleth
c7a5aa2c4c fixed external api in agent route 2025-06-26 01:31:55 +07:00
xampleth
a926f45171 fixed use supabase instead of in memory store
fixed use supabase realtime instead of sse

removed data handler route
2025-06-26 00:33:02 +07:00
xampleth
0ed5f627c2 fixed build fail 2025-06-21 01:42:19 +07:00
xampleth
ac3f16fcf0 removed token versioning 2025-06-21 01:38:50 +07:00
xampleth
1176057b2a fixed agent with external api disabled 2025-06-20 23:42:21 +07:00
xampleth
8fceb8c133 enabled social media
tested all route

removed refresh session id
2025-06-20 22:51:07 +07:00
xampleth
dd8402f252 added session id clipboard agent route 2025-06-20 13:03:11 +07:00
flukexp
a4d8b52f60 fixed build fail 2025-06-20 02:07:50 +07:00
xampleth
26e80f7a12 added isolated each user session with session id
temp disabled social media tg and x
2025-06-20 02:00:03 +07:00
xampleth
6fcb410982 added social media config 2025-06-19 22:53:32 +07:00
xampleth
de335df6c3 prevented agent route fetch multiple times 2025-06-17 22:45:38 +07:00
xampleth
161b75e0ee added sample img 2025-06-17 22:33:14 +07:00
xampleth
7dbb1a8270 fixed SSE and memort store on agent route
added copied menu on agent route w/notification
2025-06-17 22:10:34 +07:00
xampleth
9759c02040 fixed chatgpt to openai 2025-06-17 01:22:21 +07:00
xampleth
3dfd489381 added external api w/jwt 2025-06-17 01:04:08 +07:00
J Master Pig
aa09a5821c
Added explorer link
Persona Framework
2025-06-17 00:31:42 +07:00
J Master Pig
d0a089392d
Added blacklist abiliity.
Persona Framework
2025-06-17 00:31:23 +07:00
xampleth
16b35af768 added explore link 2025-06-16 11:23:11 +07:00
xampleth
2c3eb73d89 added black list feature 2025-06-16 00:31:09 +07:00
J Master Pig
8a8b5b490f
Added Sync Personas
Persona Framework
2025-06-13 17:18:32 +07:00
flukexp
024670ffbe feat: added sync personas 2025-06-13 00:30:16 +07:00
J Master Pig
58b56c0c84
Fixed Web Snippets
Persona Framework
2025-06-12 20:40:19 +07:00
flukexp
eda3b9fdfc fix web snippet 2025-06-12 20:18:47 +07:00
J Master Pig
41a9833531
added talent video
added talent video
refactored config structure on core amica
fixed click on the chat button it goes to a different agent
added main page refresh button on each agent
fixed concurrent talent show speaking
added back to village on agent detail page
rename title from agent leaderboard to leaderboard
2025-06-12 15:12:40 +07:00
flukexp
fde90d2532 fix: correct chat routing and talent show concurrency\n\n- Fixed issue where clicking the chat button opened a different agent\n- Added main page refresh button for each agent\n- Fixed concurrent speaking in talent show\n- Added "Back to Village" button on agent detail page\n- Renamed title from "Agent Leaderboard" to "Leaderboard" 2025-06-11 21:35:10 +07:00
flukexp
d173debbff resolve agent status inconsistency
fixed save mint agent
2025-06-10 01:50:04 +07:00
flukexp
8f2d593e79 renamed agent section headline 2025-06-08 15:26:30 +07:00
flukexp
c349e17b5f fixed subconscious event
fixed dignosis status updated
2025-06-08 14:17:17 +07:00
flukexp
8abf6c8876 added save nft to db 2025-06-08 11:35:45 +07:00
flukexp
ddea6675b3 fixed evaluate agent button stucking 2025-06-08 11:35:03 +07:00
flukexp
10c4c1800a fixed backends time out
clean up
2025-06-07 20:37:15 +07:00
flukexp
81000d6708 feat: added talent show 2025-06-07 18:42:32 +07:00
J Master Pig
fd4b6c87ad
Persona Village - Added Improvements and Leaderboard
Persona Village
2025-06-06 11:02:51 +07:00
flukexp
018fd944e7 resolved dependency issued
waiting for supabase update

refactored useAgent

added rvc supported

added pwa related file

solved onnxruntime .wasm not found

implemented get stt response

prepared for talent show
2025-06-04 23:18:14 +07:00
flukexp
73a5210712 added rvc
added generate path

binded amica w/ agent demo component
2025-06-03 23:48:53 +07:00
flukexp
c0f51bca3d added core amica feature
refactored core feature config
2025-06-02 22:29:16 +07:00
flukexp
e44bb2dfe2 fixed vrm diagnosis timeout 2025-05-31 20:45:00 +07:00
flukexp
684410c31e clean up amica agent route
fixed persona village leaderboard
2025-05-31 17:54:36 +07:00
flukexp
4bfce645a4 fixed all cached system 2025-05-31 00:06:31 +07:00
flukexp
55b8a845e9 added supabase to reduce rpc called
refactored all hooks

added leader board
2025-05-30 18:30:34 +07:00
flukexp
28639f9c57 added meta tags for display web snippet 2025-05-29 11:26:33 +07:00
flukexp
392769811d fixed to used provider 2025-05-29 10:08:16 +07:00
flukexp
85ef859658 added diagnosis and integration link 2025-05-28 20:45:02 +07:00
flukexp
0098a2d24f clean up 2025-05-28 13:13:27 +07:00
flukexp
cca2cd067a added talent show score
added integrations section
2025-05-28 12:56:34 +07:00
flukexp
c286e5ce22 added wrong agent id error log 2025-05-26 11:21:19 +07:00
flukexp
7fe6462ad7 changed agent id 2025-05-26 10:58:03 +07:00
flukexp
62c51f187f optimized rpc called for diagnosis and token hooks 2025-05-24 17:43:26 +07:00
flukexp
de0f0c29e9 added provider singleton
optimized rpc call for agent and backend hook
2025-05-23 17:25:21 +07:00
flukexp
7580c492a0 added agent tier feature
fixed idle text prompt
2025-05-23 00:52:07 +07:00
flukexp
ba99fd12ec refactored share page
clean up persona village
2025-05-22 17:04:54 +07:00
flukexp
08eae80a5d auto check agent status on component mount 2025-05-21 11:07:28 +07:00
flukexp
ac1ec9df10 disabled category selector while on share page 2025-05-20 16:39:37 +07:00
flukexp
0dc71e3935 added agent status checking
disable chat btn if agent is inactive
2025-05-20 16:24:42 +07:00
flukexp
472d62c9ab added agent category 2025-05-19 09:42:52 +07:00
flukexp
3bb77a07a9 fixed price chart history 2025-05-17 23:05:17 +07:00
flukexp
a8ccb157cd TODO: setAgent to sync on all page 2025-05-16 15:42:21 +07:00
flukexp
ca64e1b419 fixed idle text prompt
fixed token price extraction
2025-05-16 14:54:43 +07:00
flukexp
8a7d740782 refined price extraction from contract 2025-05-16 14:20:49 +07:00
flukexp
9f882aee14 added search by price logic
fixed read more expansion to scrollable component
2025-05-16 11:52:31 +07:00
flukexp
59f757d5d1 added search logic 2025-05-15 16:53:24 +07:00
J Master Pig
c2c5af83d0
Merge pull request #197 from 4lukexp/mint-agent
Persona Village
2025-05-14 16:08:27 +07:00
flukexp
c8f29381e3 set amica url to use env var 2025-05-13 21:29:16 +07:00
J Master Pig
28f1d2b130
changed amica url fixed amica life idle text prompt ui created file utils reduced cached TTL on perona village to 30 secs
Mint Agent
2025-05-13 19:41:02 +07:00
flukexp
d119b5c157 changed amica url 2025-05-13 14:01:47 +07:00
J Master Pig
f47debdbdf
Persona Village (added diagnosis script)
Mint Feature
2025-05-09 09:35:38 +07:00
flukexp
5a629bd30d fixed build failed install wavefile dependency 2025-05-08 13:47:51 +07:00
flukexp
658b3fe3dc added diagnosis script for backend 2025-05-08 13:39:46 +07:00
flukexp
c8acfff990 added reserve token feature
added tags

fixed user cancel tx on share page
2025-04-24 16:32:22 +07:00
flukexp
7f49190a73 added caching to reduce rpc call
handler for pair not created agent
2025-04-20 00:39:08 +07:00
flukexp
495cf4562d removed ignoring .env 2025-04-05 18:49:07 +07:00
flukexp
0969dca5e3 fixed typo 2025-04-05 18:26:25 +07:00
flukexp
cf6695162e sync agent-detail 2025-04-03 21:06:36 +07:00
flukexp
8f1c428b4b fixed build failed 2025-03-27 17:43:22 +07:00
flukexp
5629a53947 fixed build failed 2025-03-27 17:24:36 +07:00
flukexp
d31acbfb44 moved to arbitrum sepolia 2025-03-27 16:41:39 +07:00
flukexp
0a3a4388a4 fixed build failed 2025-03-27 14:31:17 +07:00
flukexp
eb4e320767 added vrm demo
added agents localStorage
2025-03-27 14:21:14 +07:00
flukexp
b9b0da8116 renamed header 2025-03-26 17:32:58 +07:00
flukexp
4f8f9aa2e0 added prebuild script 2025-03-26 01:59:47 +07:00
flukexp
773ed4d077 fixed build 2025-03-26 01:44:38 +07:00
flukexp
983101a0b6 temp fixed build failed 2025-03-26 01:36:58 +07:00
flukexp
08907bf2de temp fixed build failed 2025-03-26 00:59:40 +07:00
flukexp
f0e53fd9ea added mint feature
moved to arbitrum one

fixed vrmViewer for agentid route
2025-03-26 00:46:58 +07:00
Joey Wong
96cec2e65b
Fixed agent route connector
Fixed agent route connector
2025-03-14 04:52:02 +07:00
flukexp
7030a59927 fixed agent route connector
fixed openai setting

added display agent from sepolia contract
2025-03-13 21:27:46 +07:00
Joey Wong
9af3218735
Add Config Export to Persona Framework (Temporary)
Add Config Export to Persona Framework (Temporary)
2025-03-12 12:14:11 +07:00
Fluke
ab2abfe059
Merge branch 'agent-framework' into config-btn 2025-03-12 12:00:02 +07:00
Joey Wong
4bc88899e1
Added Agent ID Route for Persona Framework
Agent ID Route for Persona Framework
2025-03-12 11:58:08 +07:00
flukexp
258262b076 re-added agent catalog
added .vercelignore
2025-03-12 11:11:06 +07:00
flukexp
6e6e56c34f fix typo 2025-03-12 10:27:50 +07:00
flukexp
62add5e13d added .vercelignore 2025-03-12 10:27:14 +07:00
flukexp
e40fe6bdca re-added agent-catalogue 2025-03-12 10:14:56 +07:00
flukexp
1d9bdcd8cd remove agent-catalogue folder for fix build 2025-03-08 14:21:53 +07:00
flukexp
cd3ab903cc add test supabase env 2025-03-08 14:17:43 +07:00
flukexp
992a8702ab clean up 2025-03-08 14:09:20 +07:00
flukexp
f416274409 fixed build fail 2025-03-08 12:22:54 +07:00
flukexp
6db05f3348 temp export configs btn 2025-03-08 12:13:11 +07:00
flukexp
c8f2615d9e update 2025-03-05 19:18:30 +07:00
flukexp
2e80b2a5a2 refactored db table
added 10 sham data on db
2025-02-18 00:55:12 +07:00
flukexp
cda320e3f3 added chat component
added agent id route
2025-02-11 00:40:51 +07:00
Joey Wong
1b19f26141
agent catalog next.js front-end (sham data)
agent catalog front-end
2025-01-30 05:06:17 +07:00
Joey Wong
9cb7703f64 agent catalog front-end 2025-01-30 05:01:01 +07:00
291 changed files with 52943 additions and 12573 deletions

View File

@ -2,3 +2,15 @@ NEXT_PUBLIC_AMICA_API_URL=https://store.heyamica.com
NEXT_PUBLIC_AMICA_STORAGE_URL=https://vrm.heyamica.com/file/amica-vrm
NEXT_PUBLIC_SUPABASE_URL=https://kzfcwefqffysqsjrlyld.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt6ZmN3ZWZxZmZ5c3FzanJseWxkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MDEyNzA5NjUsImV4cCI6MjAxNjg0Njk2NX0.z9zm2mbJu6RkdZ6zkCUltThIF43-ava_bLvk9qFQsiA
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=9f8cee238fde4f0011880ecef0616c88
NEXT_PUBLIC_BLOCK_EXPLORER_URL=https://sepolia.etherscan.io
NEXT_PUBLIC_NFT_CONTRACT_ADDRESS=0x66028403F6768eb48784536eF72975Ce232146A6
NEXT_PUBLIC_INFURA_RPC=https://sepolia.infura.io/v3/2100216e5c5b451091e14246d10deaff
X_API_KEY="X_API_KEY"
X_API_SECRET="X_API_SECRET"
X_ACCESS_TOKEN="X_ACCESS_TOKEN"
X_ACCESS_SECRET="X_ACCESS_SECRET"
X_BEARER_TOKEN="X_BEARER_TOKEN"
TELEGRAM_BOT_TOKEN="TELEGRAM_BOT_TOKEN"
TELEGRAM_CHAT_ID="TELEGRAM_CHAT_ID"

5
agent-catalog/.env.local Normal file
View File

@ -0,0 +1,5 @@
NEXT_PUBLIC_CONTRACT_ADDRESS=0x66028403F6768eb48784536eF72975Ce232146A6
NEXT_PUBLIC_AIUS_CONTRACT_ADDRESS=0x05a8f3333a26Edf85f1D4BEe53fE5cc470ac1731
NEXT_PUBLIC_INFURA_RPC=https://sepolia.infura.io/v3/2100216e5c5b451091e14246d10deaff
NEXT_PUBLIC_AMICA_URL=https://amica-git-persona-framework-heyamica.vercel.app/
NEXT_PUBLIC_PRODUCTION_URL=https://persona.arbius.ai

24
agent-catalog/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
# next.js
/.next/
/out/
# production
/build
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@ -0,0 +1,30 @@
"use client"
import { queryClient } from "@/lib/query-client";
import '@rainbow-me/rainbowkit/styles.css';
import { getDefaultConfig, RainbowKitProvider } from '@rainbow-me/rainbowkit';
import { WagmiProvider } from 'wagmi';
import { sepolia, arbitrumSepolia } from 'wagmi/chains';
import {
QueryClientProvider,
} from "@tanstack/react-query";
const config = getDefaultConfig({
appName: 'arbius.heyamica.com',
projectId: "3cecb561af7700e7ff5184b55b39e05a",
chains: [sepolia, arbitrumSepolia],
ssr: false,
});
export function QueryProvider({ children }: { children: React.ReactNode }) {
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
<RainbowKitProvider>
{children}
</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
);
}

View File

@ -0,0 +1,59 @@
"use client";
import { AgentDetails } from "@/components/agent-details";
import { Agent } from "@/types/agent";
import { useEffect, useState } from "react";
import { fetchAgentStats } from "@/lib/agents";
export default function AgentClient({ id }: { id: string }) {
const [agents, setAgents] = useState<Agent>();
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let isMounted = true;
const loadAgents = async () => {
setLoading(true);
setError(null);
try {
const res = await fetch(`/api/agents?agentId=${id}`);
if (!res.ok) throw new Error(`Failed to fetch agent ${id}`);
const data = await res.json();
const agentsResult = await fetchAgentStats(data);
if (isMounted) {
setAgents(Array.isArray(agentsResult) ? agentsResult[0] : agentsResult);
}
} catch (err: any) {
if (isMounted) {
setError(err.message || `Error loading agent ${id}`);
}
} finally {
if (isMounted) {
setLoading(false);
}
}
};
loadAgents();
return () => {
isMounted = false;
};
}, []);
return (
<div className="sticky top-0 z-20 bg-white/80 backdrop-blur-sm border-b">
{error ? (
<div className="p-4 text-red-500">Error loading agents: {error}</div>
) : !agents || loading ? (
<div className="flex justify-center items-center p-8">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
</div>
) : (
<AgentDetails agent={agents} />
)}
</div>
);
}

View File

@ -0,0 +1,52 @@
import { Metadata } from "next";
import { Agent } from "@/types/agent";
import AgentClient from "./AgentClient";
import { QueryProvider } from "../../ClientQueryProvider";
import { getAgentFromContract } from "@/lib/agents";
export async function generateMetadata({ params }: { params: { id: string } }): Promise<Metadata> {
const id = params.id
const agentResult = await getAgentFromContract(id);
const agent = (agentResult && !Array.isArray(agentResult)) ? agentResult as Agent : null;
const title = agent?.name ?? "Agent Profile";
const description = agent?.description ?? "Meet our intelligent agent.";
const image = agent?.avatar ?? "/default-agent-image.png";
const url = `${process.env.NEXT_PUBLIC_PRODUCTION_URL}/agent/${params.id}`;
return {
title,
description,
openGraph: {
title,
description,
url,
type: "profile",
images: [
{
url: image,
width: 800,
height: 600,
alt: `${title}'s profile image`,
},
],
},
twitter: {
card: "summary_large_image",
title,
description,
images: [image],
},
};
}
export default async function AgentPage({ params }: { params: { id: string } }) {
return (
<QueryProvider>
<AgentClient id={params.id} />
</QueryProvider>
);
}

View File

@ -0,0 +1,14 @@
import { getAgentsFromSupabase } from "@/lib/agents";
import { NextResponse } from "next/server";
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const agentId = searchParams.get("agentId");
try {
const agents = await getAgentsFromSupabase(agentId);
return NextResponse.json(agents);
} catch (error) {
return NextResponse.json({ error: "Unable to fetch agents" }, { status: 500 });
}
}

View File

@ -0,0 +1,14 @@
import { getBackendsFromSupabase } from "@/lib/backends";
import { NextResponse } from "next/server";
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const agentId = searchParams.get("agentId");
try {
const backends = await getBackendsFromSupabase(agentId); // pass agentId to your query function
return NextResponse.json(backends);
} catch (error) {
return NextResponse.json({ error: "Unable to fetch backends" }, { status: 500 });
}
}

View File

@ -0,0 +1,94 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
font-family: Arial, Helvetica, sans-serif;
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 3.9%;
--primary: 0 0% 9%;
--primary-foreground: 0 0% 98%;
--secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%;
--accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 0 0% 3.9%;
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
--radius: 0.5rem;
--sidebar-background: 0 0% 98%;
--sidebar-foreground: 240 5.3% 26.1%;
--sidebar-primary: 240 5.9% 10%;
--sidebar-primary-foreground: 0 0% 98%;
--sidebar-accent: 240 4.8% 95.9%;
--sidebar-accent-foreground: 240 5.9% 10%;
--sidebar-border: 220 13% 91%;
--sidebar-ring: 217.2 91.2% 59.8%;
}
.dark {
--background: 0 0% 3.9%;
--foreground: 0 0% 98%;
--card: 0 0% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 0 0% 9%;
--secondary: 0 0% 14.9%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 14.9%;
--muted-foreground: 0 0% 63.9%;
--accent: 0 0% 14.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 14.9%;
--input: 0 0% 14.9%;
--ring: 0 0% 83.1%;
--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
--sidebar-background: 240 5.9% 10%;
--sidebar-foreground: 240 4.8% 95.9%;
--sidebar-primary: 224.3 76.3% 48%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 240 3.7% 15.9%;
--sidebar-accent-foreground: 240 4.8% 95.9%;
--sidebar-border: 240 3.7% 15.9%;
--sidebar-ring: 217.2 91.2% 59.8%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View File

@ -0,0 +1,34 @@
import { Orbitron, Noto_Sans_JP, Roboto_Mono } from "next/font/google"
import './globals.css'
const orbitron = Orbitron({
subsets: ["latin"],
variable: "--font-orbitron",
})
const noto = Noto_Sans_JP({
subsets: ["latin"],
variable: "--font-noto-sans-jp",
})
const robotoMono = Roboto_Mono({
subsets: ["latin"],
variable: "--font-roboto-mono",
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={`${orbitron.variable} ${noto.variable} ${robotoMono.variable}`}>
<body>
{children}
</body>
</html>
)
}

View File

@ -0,0 +1,308 @@
"use client";
import { useEffect, useState } from "react";
import { Agent } from "@/types/agent";
import { Trophy, Star, User, Brain } from "lucide-react";
import { cn } from "@/lib/utils";
import { supabase } from "@/utils/supabase";
import Link from "next/link";
import { Header, LeaderboardHeader } from "@/components/header";
import { motion, useScroll, useTransform } from "framer-motion";
import { fetchAgentStats } from "@/lib/agents";
type Score = {
agentId: string;
vrm: number;
chatbot: number;
tts: number;
stt: number;
vision: number;
amicaLife: number;
talentShowScore: number;
};
function AgentCard({ agent, rank, score }: { agent: Agent; rank: number; score: Score }) {
const getRankStyle = (rank: number) => {
switch (rank) {
case 0:
return {
gradient: "from-amber-400 via-yellow-300 to-amber-400",
border: "border-amber-300",
shadow: "shadow-amber-200/50",
icon: "text-amber-600",
rank: "text-amber-700"
};
case 1:
return {
gradient: "from-slate-300 via-gray-200 to-slate-300",
border: "border-slate-300",
shadow: "shadow-slate-200/50",
icon: "text-slate-600",
rank: "text-slate-700"
};
case 2:
return {
gradient: "from-orange-300 via-amber-200 to-orange-300",
border: "border-orange-300",
shadow: "shadow-orange-200/50",
icon: "text-orange-600",
rank: "text-orange-700"
};
default:
return {
gradient: "from-slate-50 to-white",
border: "border-slate-200",
shadow: "shadow-slate-100/50",
icon: "text-slate-500",
rank: "text-slate-600"
};
}
};
const getCategoryTitle = (category: string) => {
switch (category.toLowerCase()) {
case 'security': return 'Security';
case 'crypto': return 'Crypto';
case 'personalAssistant': return 'Personal Assistant';
case 'researcher': return 'Researcher';
case 'programmer': return 'Programmer';
default: return 'General';
}
};
const getCategoryIcon = (category: string) => {
switch (category.toLowerCase()) {
case 'security': return '🛡️';
case 'crypto': return '₿';
case 'personalAssistant': return '👤';
case 'researcher': return '🔬';
case 'programmer': return '💻';
default: return '🤖';
}
};
const style = getRankStyle(rank);
const isTopThree = rank < 3;
return (
<div role="link" className={`group relative overflow-hidden rounded-2xl transition-all duration-300 hover:scale-[1.02] hover:shadow-xl cursor-pointer ${isTopThree ? `bg-gradient-to-br ${style.gradient} ${style.border} ${style.shadow} shadow-lg border-2` : 'bg-white border border-slate-200 shadow-md hover:shadow-lg'}`}>
{/* Rank Badge */}
<div className={`absolute top-4 left-4 flex items-center justify-center w-12 h-12 rounded-full font-bold text-lg ${isTopThree ? 'bg-white/90 backdrop-blur-sm' : 'bg-slate-100'} ${style.rank} shadow-sm`}>
#{rank + 1}
</div>
{/* Trophy for top 3 */}
{isTopThree && (
<div className={`absolute top-4 right-4 ${style.icon}`}>
<Trophy className="w-6 h-6" />
</div>
)}
<div className="p-6 pt-20">
{/* Agent Profile */}
<div className="flex items-center gap-4 mb-6">
<div className="relative">
<div className={`w-16 h-16 rounded-full overflow-hidden border-3 ${isTopThree ? 'border-white/60' : 'border-slate-200'} shadow-md`}>
<img
src={agent.avatar}
alt={agent.name}
className="w-full h-full object-cover"
onError={(e) => {
(e.target as HTMLImageElement).src = `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><rect width="64" height="64" fill="%23e2e8f0"/><text x="32" y="36" text-anchor="middle" font-size="24" fill="%23475569">👤</text></svg>`;
}}
/>
</div>
<div className="absolute -bottom-1 -right-1 text-lg">
{getCategoryIcon(agent.category)}
</div>
</div>
<div className="flex-1">
<h3 className="text-xl font-bold text-slate-800 mb-1">{agent.name}</h3>
<div className="flex items-center gap-2 text-sm text-slate-600 mb-1">
<span className="px-2 py-1 bg-slate-100 rounded-full text-xs font-medium">
{agent.tier?.name}
</span>
<span>•</span>
<span>{getCategoryTitle(agent.category)}</span>
</div>
<p className="text-sm text-slate-500">{agent.description}</p>
</div>
</div>
{/* Score Metrics */}
<div className="space-y-4">
{/* Overall Score */}
<div className="flex items-center justify-between p-3 bg-white/60 backdrop-blur-sm rounded-xl border border-white/40">
<div className="flex items-center gap-2">
<Star className="w-5 h-5 text-violet-600" />
<span className="font-semibold text-slate-700">Talent Score</span>
</div>
<span className="text-2xl font-bold text-violet-700">{score.talentShowScore.toFixed(1)}</span>
</div>
{/* Detailed Metrics Grid */}
<div className="grid grid-cols-3 gap-3">
{[
{ label: "VRM", value: score.vrm, icon: "🎭" },
{ label: "Vision", value: score.vision, icon: "👁️" },
{ label: "TTS", value: score.tts, icon: "🗣️" },
{ label: "STT", value: score.stt, icon: "👂" },
{ label: "Chatbot", value: score.chatbot, icon: "💬" },
{ label: "Amica Life", value: score.amicaLife, icon: "🌟" }
].map(({ label, value, icon }) => (
<div key={label} className="text-center p-3 bg-white/40 backdrop-blur-sm rounded-lg border border-white/30">
<div className="text-lg mb-1">{icon}</div>
<div className="font-bold text-slate-700">{value.toFixed(0)}</div>
<div className="text-xs text-slate-500 font-medium">{label}</div>
</div>
))}
</div>
</div>
</div>
</div>
);
}
export default function LeaderboardPage() {
const { scrollY } = useScroll();
const backgroundColor = useTransform(scrollY, [0, 300], ["rgb(26, 26, 46)", "rgb(255, 255, 255)"]);
const [agents, setAgents] = useState<Agent[] | null>(null);
const [scores, setScores] = useState<Score[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [checking, setChecking] = useState(true);
const [error, setError] = useState<string | null>(null);
// Fetchs agent
useEffect(() => {
let isMounted = true;
const loadAgents = async () => {
console.log("Load agents..")
setLoading(true);
setError(null);
try {
const res = await fetch("/api/agents");
if (!res.ok) throw new Error("Failed to fetch agents. ");
const data = await res.json();
const agents = await fetchAgentStats(data);
if (isMounted) {
setAgents(Array.isArray(agents) ? agents : [agents]);
}
} catch (err: any) {
if (isMounted) {
setError(err.message || "Error loading agents.");
}
} finally {
if (isMounted) {
setLoading(false);
}
}
};
loadAgents();
return () => {
isMounted = false;
};
}, []);
useEffect(() => {
const fetchScores = async () => {
console.log("Load scores..")
const { data, error } = await supabase.from("agent-score").select("*");
if (error) {
console.error("Error fetching scores:", error.message);
setChecking(false);
return;
}
if (data) {
const sorted = data.sort(
(a, b) => b.talentShowScore - a.talentShowScore
);
setScores(sorted);
setChecking(false);
}
};
fetchScores();
}, []);
return (
<motion.main className="min-h-screen" style={{ backgroundColor }}>
{/* Hero Header */}
<LeaderboardHeader />
{error ? (
<div className="sticky top-0 z-20 bg-white/80 backdrop-blur-sm border-b">
<div className="p-4 text-red-500">Error loading agents: {error}</div>
</div>
) : loading || checking ? (
<div className="sticky top-0 z-20 bg-white/80 backdrop-blur-sm border-b">
<div className="flex justify-center items-center p-8">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
</div>
</div>
) : (
<>
{/* Leaderboard Content */}
<div className="relative px-4 pb-16 sm:px-6 lg:px-8">
<div className="max-w-4xl mx-auto">
{/* Stats Bar */}
<div className="flex justify-center mt-8 mb-12">
<div className="flex items-center gap-8 px-6 py-3 bg-white rounded-full border border-gray-300 shadow">
<div className="text-center">
<div className="text-2xl font-bold text-black">{scores.length}</div>
<div className="text-sm text-gray-700">Active Agents</div>
</div>
<div className="w-px h-8 bg-gray-300"></div>
<div className="text-center">
<div className="text-2xl font-bold text-black">
{Math.max(...scores.map(s => s.talentShowScore)).toFixed(1)}
</div>
<div className="text-sm text-gray-700">Top Score</div>
</div>
<div className="w-px h-8 bg-gray-300"></div>
<div className="text-center">
<div className="text-2xl font-bold text-black">7</div>
<div className="text-sm text-gray-700">Categories</div>
</div>
</div>
</div>
{/* Agent Cards */}
<div className="grid gap-6">
{scores.map((score, index) => {
const agent = agents?.find(agent => agent.agentId === score.agentId);
if (!agent) return null;
return (
<Link key={score.agentId} href={`/agent/${score.agentId}`} passHref>
<AgentCard
agent={agent}
rank={index}
score={score}
/>
</Link>
);
})}
</div>
{/* Footer */}
<div className="text-center mt-12 pt-8 border-t border-white/10">
<p className="text-slate-400 text-sm">
Rankings updated in real-time based on comprehensive AI capabilities assessment
</p>
</div>
</div>
</div>
</>
)}
</motion.main >
);
}

View File

@ -0,0 +1,11 @@
import { QueryProvider } from "../ClientQueryProvider";
import LeaderboardPage from "./Leaderboard";
export default async function Leaderboard() {
return (
<QueryProvider>
<LeaderboardPage/>
</QueryProvider>
);
}

View File

@ -0,0 +1,95 @@
"use client";
import { AgentGrid } from "@/components/agent-grid";
import { Header } from "@/components/header";
import { motion, useScroll, useTransform } from "framer-motion";
import dynamic from "next/dynamic";
import { ConnectButton } from "@rainbow-me/rainbowkit";
import { Agent } from "@/types/agent";
import { useEffect, useState } from "react";
import { fetchAgentStats } from "@/lib/agents";
// 👇 Dynamically import the provider to avoid server-side import trace
const ClientQueryProvider = dynamic(() => import("./ClientQueryProvider").then(mod => mod.QueryProvider), {
ssr: false,
});
function HomeContent() {
const { scrollY } = useScroll();
const backgroundColor = useTransform(scrollY, [0, 300], ["rgb(26, 26, 46)", "rgb(255, 255, 255)"]);
const [agents, setAgents] = useState<Agent[] | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const updateAgent = (updatedAgent: Agent) => {
setAgents(prevAgents =>
prevAgents
? prevAgents.map(agent =>
agent.agentId === updatedAgent.agentId ? updatedAgent : agent
)
: null
);
};
useEffect(() => {
let isMounted = true;
const loadAgents = async () => {
setLoading(true);
setError(null);
try {
const res = await fetch("/api/agents");
if (!res.ok) throw new Error("Failed to fetch agents. ");
const data = await res.json();
const agents = await fetchAgentStats(data);
if (isMounted) {
setAgents(Array.isArray(agents) ? agents : [agents]);
}
} catch (err: any) {
if (isMounted) {
setError(err.message || "Error loading agents.");
}
} finally {
if (isMounted) {
setLoading(false);
}
}
};
loadAgents();
return () => {
isMounted = false;
};
}, []);
return (
<motion.main className="min-h-screen" style={{ backgroundColor }}>
<div className="absolute top-4 right-4 z-30">
<ConnectButton />
</div>
<Header />
<div className="sticky top-0 z-20 bg-white/80 backdrop-blur-sm border-b">
{error ? (
<div className="p-4 text-red-500">Error loading agents: {error}</div>
) : loading ? (
<div className="flex justify-center items-center p-8">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
</div>
) : (
<AgentGrid agents={agents!} onUpdateAgent={updateAgent}/>
)}
</div>
</motion.main>
);
}
export default function Page() {
return (
<ClientQueryProvider>
<HomeContent />
</ClientQueryProvider>
);
}

View File

@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View File

@ -0,0 +1,145 @@
"use client"
import type { Agent } from "@/types/agent"
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { MessageSquare, Info } from "lucide-react"
import Image from "next/image"
import { motion } from "framer-motion"
import Link from "next/link"
import { useDiagnosisRunner } from "@/hooks/use-diagnosis"
import { cn } from "@/lib/utils"
import { useState } from "react"
import { forwardRef, useImperativeHandle } from "react";
interface AgentCardProps {
agent: Agent
onUpdateAgent?: (agent: Agent) => void
index: number
}
export interface AgentCardHandle {
runDiagnosis: (signal: AbortSignal) => Promise<void>;
}
const AMICA_URL = process.env.NEXT_PUBLIC_AMICA_URL as string;
export const AgentCard = forwardRef<AgentCardHandle, AgentCardProps>(({ agent, onUpdateAgent, index }, ref) => {
const { status, checking, handleDiagnosis } = useDiagnosisRunner(agent, index, true);
const [diagnosed, setDiagnosed] = useState(false);
const runDiagnosis = async (signal: AbortSignal): Promise<void> => {
return new Promise<void>(async (resolve, reject) => {
if (signal.aborted) {
return reject(new DOMException("Aborted", "AbortError"));
}
signal.addEventListener("abort", () => {
console.log("Diagnosis aborted");
reject(new DOMException("Aborted", "AbortError"));
});
setDiagnosed(true);
await handleDiagnosis(false);
resolve();
});
};
useImperativeHandle(ref, () => ({
runDiagnosis,
}));
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay: index * 0.1 }}
whileHover={{ y: -5 }}
className="h-full"
>
<Card className="overflow-hidden group bg-scifi-dark border-neon-blue/20 hover:border-neon-blue/40 transition-colors h-full flex flex-col">
<CardHeader className="p-0">
<div className="relative h-[320px] w-full overflow-hidden">
<motion.div whileHover={{ scale: 1.05 }} transition={{ duration: 0.4 }} className=" relative h-full w-full">
<Image
src={agent.avatar || "/placeholder.svg"}
alt={agent.name}
className="object-cover object-center"
fill
priority
/>
</motion.div>
</div>
</CardHeader>
<CardContent className="p-4 flex-grow flex flex-col justify-between space-y-4">
<div className="space-y-2">
<div className="flex items-center justify-between">
<h3 className="font-orbitron font-semibold text-lg text-white">{agent.name}</h3>
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-neon-pink font-orbitron">{agent.price?.toPrecision(2)} AIUS</span>
<Badge
variant="secondary"
loading={checking}
className={cn(
"bg-neon-blue border-0 text-white font-roboto-mono",
"transition-all duration-300 ease-in-out",
"hover:bg-neon-blue/90 hover:shadow-[0_0_10px_rgba(0,245,255,0.6)] hover:scale-[1.03]",
"active:scale-[0.98]",
"focus-visible:ring-2 focus-visible:ring-neon-blue/50"
)}
tabIndex={0}
>
{checking ? "loading.." : diagnosed ? status : agent.status}
</Badge>
</div>
</div>
<div className="space-y-1">
<p className="text-sm text-blue-100/70 font-roboto-mono">Token: {agent.token}</p>
<p className="text-sm text-blue-100/70 font-roboto-mono">
Tier: {agent.tier?.name} (Level {agent.tier?.level})
</p>
</div>
{/* Scrollable Description */}
<div className="max-h-24 overflow-y-auto pr-1 [&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar]:h-4/6 [&::-webkit-scrollbar-track]:bg-neon-blue/25 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-gray-300">
<p className="text-sm text-blue-100/70 font-roboto-mono whitespace-pre-line">
{agent.description}
</p>
</div>
</div>
<div className="grid grid-cols-2 gap-2">
<Button
variant="outline"
size="sm"
className="w-full font-roboto-mono border-neon-blue/50 text-neon-blue hover:bg-neon-blue/20 hover:text-white transition-colors"
onClick={() => window.open(`${AMICA_URL}/agent/${agent.id}`, "_blank", "noopener,noreferrer")}
disabled={diagnosed ? status !== "active" : agent.status !== "active"}
title={
(diagnosed ? status !== "active" : agent.status !== "active")
? "Chat is disabled: Agent is inactive."
: ""
}
>
<MessageSquare className="h-4 w-4 mr-2" />
Chat
</Button>
<Link href={`/agent/${agent.agentId}`}>
<Button
variant="outline"
size="sm"
className="w-full font-roboto-mono border-neon-pink/50 text-neon-pink hover:bg-neon-pink/20 hover:text-white transition-colors"
>
<Info className="h-4 w-4 mr-2" />
Details
</Button>
</Link>
</div>
</CardContent>
</Card>
</motion.div>
)
}
)
AgentCard.displayName = "AgentCard"

View File

@ -0,0 +1,259 @@
// "use client";
import * as ort from "onnxruntime-web"
ort.env.wasm.wasmPaths = '/_next/static/chunks/'
import type { Agent } from "@/types/agent";
import VRMDemo from "./vrm-demo";
import { useEffect, useState, useContext, useCallback } from "react";
import { Role } from "@/features/chat/messages";
import { ViewerContext } from "@/features/vrmViewer/viewerContext";
import { ChatContext } from "@/features/chat/chatContext";
import { AmicaLifeContext } from "@/features/amicaLife/amicaLifeContext";
import { ChatConfig } from "@/features/chat/chat";
import { fetchBackends } from "@/lib/backends";
import { AssistantText } from "./assistant-text";
import { UserText } from "./user-text";
import { useTranscriber } from "@/hooks/useTranscriber";
import { cleanTranscript } from "@/utils/stringProcessing";
import { handleIdleEvent, TimestampedPrompt } from "@/features/amicaLife/eventHandler";
import { loadImage } from "@/features/diagnosed/visionDiagnosis";
import { loadVRMAnimation } from "@/lib/VRMAnimation/loadVRMAnimation";
import { wait } from "@/utils/wait";
import { stagedPrompt } from "@/lib/prompts";
interface AgentDemoProps {
agent: Agent;
talentShow: boolean;
talentRunning: boolean;
setTalentShow: (show: boolean) => void;
setTalentRunning: (running: boolean) => void;
}
const promptKeys = ["intro", "easy_input", "medium_input", "hard_input"];
const animPaths = ["/animations/greeting.vrma", "/animations/peaceSign.vrma"];
const stepLabels = [
"Intro",
"Easy Input",
"Medium Input",
"Hard Input",
"Image Vision",
"Greeting Animation",
"Subconscious Event",
"Peace Sign Animation",
];
const TalentSteps = {
INTRO: 0,
EASY_INPUT: 1,
MEDIUM_INPUT: 2,
HARD_INPUT: 3,
IMAGE_VISION: 4,
GREETING_ANIM: 5,
SUBCONSCIOUS: 6,
PEACE_SIGN_ANIM: 7,
} as const;
export function AgentDemo({ agent, talentShow, setTalentShow, talentRunning, setTalentRunning }: AgentDemoProps) {
const { viewer } = useContext(ViewerContext);
const { chat: bot } = useContext(ChatContext);
const { amicaLife } = useContext(AmicaLifeContext);
const transcriber = useTranscriber();
const [currentStep, setCurrentStep] = useState(0);
const [totalSteps, setTotalSteps] = useState(0);
const [talentError, setTalentError] = useState<string | null>(null);
const [config, setConfig] = useState<ChatConfig>();
const [assistantMessage, setAssistantMessage] = useState("");
const [userMessage, setUserMessage] = useState("");
const [shownMessage, setShownMessage] = useState<Role>("system");
const [vrmError, setVrmError] = useState(false);
const [subconciousLogs, setSubconciousLogs] = useState<TimestampedPrompt[]>([]);
const [chatSpeaking, setChatSpeaking] = useState(false);
const [chatProcessing, setChatProcessing] = useState(false);
const [whisperOpenAIOutput, setWhisperOpenAIOutput] = useState<any | null>(null);
const [whisperCppOutput, setWhisperCppOutput] = useState<any | null>(null);
const getRandomPrompts = useCallback((prompts: typeof stagedPrompt) => {
return Object.fromEntries(
Object.entries(prompts).map(([key, values]) => [
key,
values[Math.floor(Math.random() * values.length)],
])
);
}, []);
const handleTranscriptionResult = useCallback(
(text: string) => {
const cleanText = cleanTranscript(text);
if (cleanText) bot.receiveMessageFromUser(cleanText, false);
},
[bot]
);
// Load config and initialize bot
useEffect(() => {
const loadAndInit = async () => {
const fullConfig = await fetchBackends(agent.agentId, agent.config);
const newConfig: ChatConfig = {
name: agent.name,
tts_backend: agent.config.tts as ChatConfig["tts_backend"],
chatbot_backend: agent.config.chatbot as ChatConfig["chatbot_backend"],
stt_backend: agent.config.stt as ChatConfig["stt_backend"],
vision_backend: agent.config.vision as ChatConfig["vision_backend"],
system_prompt: agent.systemPrompt,
vision_system_prompt: agent.visionSystemPrompt,
chatbot_params: fullConfig[agent.config.chatbot],
tts_params: fullConfig[agent.config.tts],
stt_params: fullConfig[agent.config.stt],
vision_params: fullConfig[agent.config.vision],
amica_life_params: fullConfig[agent.config.amicaLife] as ChatConfig["amica_life_params"],
rvc_params: fullConfig[agent.config.rvc] as unknown as ChatConfig["rvc_params"],
};
setConfig(newConfig);
bot.initialize(
transcriber,
amicaLife,
viewer,
setUserMessage,
setAssistantMessage,
setShownMessage,
setChatProcessing,
setChatSpeaking,
setWhisperOpenAIOutput,
setWhisperCppOutput,
newConfig
);
};
loadAndInit();
}, []);
// Initialize Amica Life
useEffect(() => {
if (!bot.initialized || !config || config.amica_life_params.amica_life_enabled !== "true") return;
amicaLife.initialize(config, viewer, bot, chatSpeaking, setSubconciousLogs);
}, [bot.initialized, config, viewer, amicaLife, chatSpeaking]);
const updateProgress = (step: number) => {
setCurrentStep(step);
};
const runPromptSteps = async (promptSet: { [x: string]: string; }) => {
for (const key of promptKeys) {
updateProgress(TalentSteps[key.toUpperCase() as keyof typeof TalentSteps]);
await bot.runFullInteraction(promptSet[key], false);
}
};
const runVisionStep = async () => {
updateProgress(TalentSteps.IMAGE_VISION);
const imageBase64 = await loadImage("/sample-image.jpeg");
await bot.runFullInteraction(imageBase64, true);
};
const runAnimationSteps = async () => {
for (let i = 0; i < animPaths.length; i++) {
const animStep = i === 0 ? TalentSteps.GREETING_ANIM : TalentSteps.PEACE_SIGN_ANIM;
updateProgress(animStep);
const animation = await loadVRMAnimation(animPaths[i]);
if (animation && viewer.model) {
const duration = await viewer.model.playAnimation(animation, "idle_loop.vrma");
requestAnimationFrame(() => viewer.resetCameraLerp());
await wait(duration * 1000);
}
if (i === 0 && config?.amica_life_params.amica_life_enabled === "true") {
updateProgress(TalentSteps.SUBCONSCIOUS);
await handleIdleEvent(config, { events: "Subconcious" }, amicaLife, bot, viewer);
}
}
};
// Talent show logic
useEffect(() => {
if (!bot.initialized || !config || !talentShow || talentRunning) return;
const isSubconsciousEnabled = config.amica_life_params.amica_life_enabled === "true";
const baseSteps = promptKeys.length + 1 + animPaths.length; // prompts + vision + animations
const total = isSubconsciousEnabled ? baseSteps + 1 : baseSteps;
setTotalSteps(total);
const runTalentShow = async () => {
try {
setTalentRunning(true);
const promptSet = getRandomPrompts(stagedPrompt);
await runPromptSteps(promptSet);
await runVisionStep();
await runAnimationSteps();
} catch (err) {
console.error("Talent show error:", err);
setTalentError("Something went wrong.");
} finally {
setTalentRunning(false);
setTalentShow(false);
}
};
runTalentShow();
}, [talentShow, bot.initialized, config]);
// Consolidated STT handler
useEffect(() => {
const outputs = [transcriber.output?.text, transcriber.output, whisperCppOutput, whisperOpenAIOutput];
for (const o of outputs) {
if (o && typeof o.text === "string") {
handleTranscriptionResult(o.text);
}
}
}, [transcriber.output, whisperCppOutput, whisperOpenAIOutput]);
useEffect(() => {
return () => {
console.log("AgentDemo is unmounting : ",agent.agentId);
bot.clean();
viewer.unloadVRM();
amicaLife.clean();
};
}, []);
return (
<div
className="bg-gray-100 p-8 rounded-lg h-[400px] flex items-center justify-center border border-gray-200 relative"
style={{
backgroundImage: `url(${agent.bgUrl})`,
backgroundSize: "cover",
backgroundPosition: "center",
}}
>
{/* Talent Show Progress Bar */}
{(talentShow && talentRunning) && (
<div className="absolute right-4 top-4 z-20 w-32 text-white text-2xl">
<div className="h-3 bg-gray-200 rounded-full overflow-hidden">
<div
className="h-full bg-gradient-to-r from-blue-500 to-indigo-600 transition-all duration-500 ease-out"
style={{ width: `${(currentStep / totalSteps) * 100}%` }}
></div>
</div>
<p className="mt-2 text-center text-sm font-semibold text-white">{stepLabels[currentStep]}</p>
</div>
)}
<VRMDemo
vrmUrl={agent.vrmUrl}
onLoaded={() => { }}
onError={() => setVrmError(true)}
/>
{shownMessage === "assistant" && (
<AssistantText name={config?.name ?? ""} message={assistantMessage} />
)}
{shownMessage === "user" && <UserText message={userMessage} />}
</div>
);
}

View File

@ -0,0 +1,13 @@
interface AgentDescriptionProps {
description: string
}
export function AgentDescription({ description }: AgentDescriptionProps) {
return (
<div className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
<h2 className="text-2xl font-orbitron mb-4 text-gray-800">About</h2>
<p className="font-roboto-mono text-gray-600 leading-relaxed text-sm">{description}</p>
</div>
)
}

View File

@ -0,0 +1,265 @@
// "use client";
import type { Agent } from "@/types/agent";
import VRMDemo from "./vrm-demo";
import { PriceChart } from "./price-chart";
import { TokenData } from "./token-data";
import { AgentDescription } from "./agent-description";
import { SocialMediaButtons } from "./social-media-buttons";
import { AgentTags } from "./agent-tags";
import { AgentTiers } from "./agent-tiers";
import { Button } from "./ui/button";
import { MessageSquare, ArrowRightLeft } from "lucide-react";
import { Integrations } from "./integrations";
import { useEffect, useState } from "react";
import { useTokens } from "@/hooks/use-token";
import { AlertTriangle } from "lucide-react";
import { ConnectButton } from "@rainbow-me/rainbowkit";
import { useReserveToken } from "@/hooks/use-reserve-token";
import { useAccount, useReadContract } from "wagmi";
import { ERC721_ABI } from "@/utils/abi/erc721";
import { formatUnits } from "ethers";
import { ERC20_ABI } from "@/utils/abi/erc20";
import { AgentVrmDiagnosis } from "./agent-diagnosis";
import { AgentDemo } from "./agent-demo";
interface AgentDetailsProps {
agent: Agent;
}
const AMICA_URL = process.env.NEXT_PUBLIC_AMICA_URL as string;
const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
export function AgentDetails({ agent }: AgentDetailsProps) {
const [diagnosisPassed, setDiagnosisPassed] = useState(false);
const [reserveAmount, setReserveAmount] = useState("");
const [talentShow, setTalentShow] = useState(false);
const [talentRunning, setTalentRunning] = useState(false);
const { isConnected, address } = useAccount();
const { stats, priceHistory, tokenAddress, loading, error } = useTokens(Number(agent.id));
const { write: reserveTokens, isLoading: reserving, isSuccess: reserveSuccess, error: reserveError } = useReserveToken();
const { data, isLoading: loadingAius, refetch: refetchAiusData } = useReadContract({
address: process.env.NEXT_PUBLIC_CONTRACT_ADDRESS! as `0x${string}`,
abi: ERC721_ABI,
functionName: "getAiusAndOwed",
args: [BigInt(agent.id), address],
query: { enabled: isConnected && !!address },
});
const [aius, owed] = (data as [bigint, bigint]) || [BigInt(0), BigInt(0)];
const { data: aiusAmount, refetch: refetchAiusAmount } = useReadContract({
address: process.env.NEXT_PUBLIC_AIUS_CONTRACT_ADDRESS! as `0x${string}`,
abi: ERC20_ABI,
functionName: "balanceOf",
args: [address],
query: { enabled: isConnected && !!address },
});
const formattedAius = aius ? formatUnits(aius, 18) : "0.0";
const formattedOwed = owed ? formatUnits(owed, 18) : "0.0";
const isPairNotCreated = error == "Pair not created";
// refetch aius and reserve amount after reserve, reload page if pair created
useEffect(() => {
if (reserveSuccess) {
const refetchAndCheck = async () => {
const { data: aiusAndOwedData } = await refetchAiusData();
await refetchAiusAmount();
setReserveAmount("");
const [newAius, newOwed] = (aiusAndOwedData as [bigint, bigint]) || [BigInt(0), BigInt(0)];
const formattedAius = parseFloat(formatUnits(newAius, 18));
if (formattedAius >= 100) {
await delay(5000);
window.location.reload(); // Refresh the page
}
};
refetchAndCheck();
}
}, [refetchAiusData, reserveSuccess, refetchAiusAmount]);
if (loading) {
return (
<div className="sticky top-0 z-20 bg-white/80 backdrop-blur-sm border-b">
<div className="flex justify-center items-center p-8">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
</div>
</div>
);
}
if (error && !isPairNotCreated) {
return (
<div className="sticky top-0 z-20 bg-white/80 backdrop-blur-sm border-b">
<div className="p-4 text-red-500">
Error loading agents: {typeof error === "object" && error !== null && "message" in error ? (error as Error).message : String(error)}
</div>
</div>
);
}
return (
<div className="min-h-screen bg-white text-gray-800">
<div className="container mx-auto px-4 py-12">
<div className="absolute top-4 left-4 z-30">
<Button
variant="ghost"
className="text-gray-900 hover:text-gray-500 font-orbitron font-bold text-xl"
onClick={() => window.location.href = "/"} // Replace with your actual route
>
<ArrowRightLeft className="mr-2 h-4 w-4" />
Back to Village
</Button>
</div>
<h1 className="text-5xl font-orbitron font-bold text-gray-900 mb-2 text-center">
{agent.name}
</h1>
<div className="absolute top-4 right-4">
<ConnectButton />
</div>
<p className="text-center text-gray-500 mb-2 font-roboto-mono">
{agent.token} | {agent.tier?.name} (Level {agent.tier?.level})
</p>
{isPairNotCreated && (
<div className="p-6 bg-yellow-100 text-yellow-700 rounded-lg flex items-center">
<AlertTriangle className="mr-2" />
Pair not created yet.
</div>
)}
{!isPairNotCreated && (<TokenData stats={stats} />)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12 mt-12">
<div className="space-y-12">
<AgentDemo agent={agent} talentShow={talentShow} setTalentShow={setTalentShow} talentRunning={talentRunning} setTalentRunning={setTalentRunning} />
{!isPairNotCreated && (<PriceChart priceHistory={isPairNotCreated ? [] : priceHistory} />)}
<AgentVrmDiagnosis agent={agent} index={Number(agent.id)} setDiagnosisIsPassed={setDiagnosisPassed} />
</div>
<div className="space-y-8">
<div className="flex justify-center space-x-4 mb-8">
<Button
className="bg-blue-500 hover:bg-blue-600 text-white font-roboto-mono"
onClick={() =>
window.open(`${AMICA_URL}/agent/${agent.agentId}`, "_blank", "noopener,noreferrer")
}
disabled={!diagnosisPassed}
title={!diagnosisPassed ? "Chat is disabled: Agent is inactive." : ""}
>
<MessageSquare className="mr-2 h-4 w-4" /> Chat
</Button>
<Button
className="bg-red-500 hover:bg-red-600 text-white font-roboto-mono"
onClick={() => setTalentShow(true)}
disabled={!diagnosisPassed || talentRunning}
title={!diagnosisPassed ? "Talent show is disabled: Agent is inactive." : ""}
>
<MessageSquare className="mr-2 h-4 w-4" /> Talent Show
</Button>
{isPairNotCreated ? (
<div className={isConnected ? "w-full max-w-sm space-y-4 p-4 border rounded-2xl shadow-md bg-white" : ""}>
{isConnected && (
<>
<label className="block text-sm font-medium text-gray-700 font-roboto-mono mb-1">
Your AIUS balance : {Number(formatUnits(aiusAmount as bigint, 18)).toFixed(2)}
</label>
<div className="w-full max-w-sm p-4 mb-4 bg-gray-50 border rounded-xl shadow-sm text-sm text-gray-700 font-roboto-mono">
<div className="flex justify-between">
<span className="font-semibold">AIUS Deposited on token:</span>
<span className="text-blue-600">{formattedAius ? formattedAius.toString() : loadingAius ? "Loading..." : "0"}</span>
</div>
<div className="flex justify-between mt-1">
<span className="font-semibold">Your Own AINFT:</span>
<span className="text-green-600">{formattedOwed ? formattedOwed.toString() : loadingAius ? "Loading..." : "0"}</span>
</div>
</div>
<div className="relative">
<input
type="number"
min="0.1"
max={100 - Number(formattedAius)}
step="0.1"
value={reserveAmount}
onChange={(e) => {
const inputValue = parseFloat(e.target.value);
const maxLimit = 100 - Number(formattedAius);
if (!isNaN(inputValue) && inputValue <= maxLimit) {
setReserveAmount(e.target.value);
} else if (e.target.value === "") {
setReserveAmount("");
}
}}
placeholder={`${100 - Number(formattedAius)} AIUS before added liquidity`}
className="w-full pl-4 pr-16 py-3 text-sm border rounded-xl shadow-sm font-roboto-mono focus:outline-none focus:ring-2 focus:ring-yellow-400"
/>
<span className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 font-semibold text-sm">
AIUS
</span>
</div>
</>
)}
<Button
className="w-full bg-yellow-500 hover:bg-yellow-600 text-white font-roboto-mono py-3 rounded-xl"
onClick={() => {
if (!isConnected) {
alert("Please connect your wallet first.");
return;
}
reserveTokens(Number(agent.id), reserveAmount);
}}
disabled={reserving || 100 - Number(formattedAius) == 0}
>
{reserving ? "Reserving..." : (
<>
<AlertTriangle className="mr-2 h-4 w-4" />
Reserve Token
</>
)}
</Button>
{reserveError && !reserveError?.message?.toLowerCase().includes("user rejected") && (
<div className="text-red-600 text-sm font-roboto-mono">{reserveError.message}</div>
)}
</div>
) : (
<Button
className="bg-pink-500 hover:bg-pink-600 text-white font-roboto-mono"
onClick={() =>
window.open(
`https://app.uniswap.org/#/swap?inputCurrency=${tokenAddress}`,
"_blank",
"noopener,noreferrer"
)
}
>
<ArrowRightLeft className="mr-2 h-4 w-4" /> Buy/Sell on Uniswap
</Button>
)}
</div>
<AgentDescription description={agent.description} />
<SocialMediaButtons agent={agent} />
{agent.tags.length > 1 &&
<AgentTags tags={agent.tags} />}
<AgentTiers currentTier={agent.tier!} />
<Integrations integrations={agent.integrations} />
</div>
</div>
</div>
</div >
);
}

View File

@ -0,0 +1,70 @@
"use client";
import { Button } from "./ui/button";
import { useDiagnosisRunner } from "@/hooks/use-diagnosis";
import { CheckKey, DiagnosisResult, DiagnosisResultType } from "./diagnosis-result";
import { checks } from "@/components/diagnosis-result";
import { useEffect, useRef, useState } from "react";
import { Agent } from "@/types/agent";
interface AgentVrmDiagnosisProps {
agent: Agent
index: number;
setDiagnosisIsPassed: (isPassed: boolean) => void;
}
export function AgentVrmDiagnosis({
agent,
index,
setDiagnosisIsPassed,
}: AgentVrmDiagnosisProps) {
const hasChecked = useRef(false);
const { results, checking, handleDiagnosis } = useDiagnosisRunner(agent, index);
// Check agent status on mount
useEffect(() => {
if (!hasChecked.current) {
handleDiagnosis();
hasChecked.current = true;
}
}, []);
// Set diagnosis is passed flag
useEffect(() => {
const isPassed = (
Object.keys(results) as (keyof DiagnosisResultType)[]
)
.filter((key): key is CheckKey => key !== "overall")
.every((key) => results[key].status === "pass");
setDiagnosisIsPassed(isPassed);
}, [results]);
return (
<div className="w-full p-6 border border-gray-200 rounded-3xl bg-white shadow-xl flex flex-col justify-between">
<div className="flex flex-col md:flex-row justify-between items-center mb-6">
<h2 className="text-2xl font-orbitron text-gray-800 mb-2 md:mb-0">
Talent Show Score:{" "}
<span className="font-bold">
{results["overall"] || agent.talentShowScore || "N/A"}
</span>
</h2>
<Button
onClick={() => handleDiagnosis(false)}
disabled={checking}
className="bg-gradient-to-r from-purple-500 to-indigo-600 hover:from-purple-600 hover:to-indigo-700 text-white font-orbitron px-6 py-2 rounded-xl shadow"
>
{checking ? "Loading..." : "Evaluate Agent"}
</Button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{checks.map(({ label, key }) => (
<DiagnosisResult key={key} label={label} status={results[key]} />
))}
</div>
</div>
);
}

View File

@ -0,0 +1,237 @@
"use client"
import type { Agent } from "@/types/agent"
import { AgentCard, AgentCardHandle } from "./agent-card"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Brain, Code, Microscope, Users, Shield, TrendingUp, Bitcoin, Briefcase, ClipboardList, RefreshCcw } from "lucide-react"
import { motion } from "framer-motion"
import { useMemo, useRef, useState } from "react"
import Link from "next/link"
interface AgentGridProps {
agents: Agent[]
onUpdateAgent?: (agent: Agent) => void
}
const categories = [
{ name: "All Agents", icon: Brain, key: "all" },
{ name: "Programmer", icon: Code, key: "programmer" },
{ name: "Researcher", icon: Microscope, key: "researcher" },
{ name: "Friend", icon: Users, key: "friend" },
{ name: "Security", icon: Shield, key: "security" },
{ name: "Degen Trader", icon: TrendingUp, key: "degenTrader" },
{ name: "Crypto", icon: Bitcoin, key: "crypto" },
{ name: "Personal Assistant", icon: Briefcase, key: "personalAssistant" },
]
export function AgentGrid({ agents, onUpdateAgent }: AgentGridProps) {
const [searchQuery, setSearchQuery] = useState("")
const [sortOption, setSortOption] = useState("all")
const [selectedCategory, setSelectedCategory] = useState("all")
const [diagnosisRunning, setDiagnosisRunning] = useState(false)
const [abortController, setAbortController] = useState<AbortController | null>(null)
const cardRefs = useRef<(AgentCardHandle | null)[]>([])
const handleCancel = () => {
if (abortController) {
abortController.abort()
setAbortController(null)
}
}
const handleRunAllDiagnoses = async () => {
if (!diagnosisRunning) {
const controller = new AbortController()
setAbortController(controller)
setDiagnosisRunning(true)
for (let i = 0; i < cardRefs.current.length; i++) {
if (controller.signal.aborted) {
break
}
const ref = cardRefs.current[i]
if (ref && typeof ref.runDiagnosis === "function") {
try {
await ref.runDiagnosis(controller.signal)
} catch (error) {
if ((error as Error).name === "AbortError") {
break
}
console.error(`Error in agent diagnosis:`, error)
}
}
}
setDiagnosisRunning(false)
setAbortController(null)
}
}
// Filter agents based on category, search query and sort
const filteredAgents = useMemo(() => {
let result = [...agents]
// Category filter
if (selectedCategory !== "all") {
result = result.filter(agent => agent.category === selectedCategory)
}
// Search filter
if (searchQuery) {
result = result.filter(agent =>
agent.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
agent.description?.toLowerCase().includes(searchQuery.toLowerCase())
)
}
// Sort
if (sortOption === "price-asc") {
result = result.sort((a, b) => (a.price || 0) - (b.price || 0))
} else if (sortOption === "price-desc") {
result = result.sort((a, b) => (b.price || 0) - (a.price || 0))
}
return result
}, [searchQuery, agents, sortOption, selectedCategory])
return (
<div className="container mx-auto px-4 py-8">
<motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="flex flex-col gap-8">
{/* Search and Filters */}
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div className="flex-1 max-w-md">
<Input
placeholder="Search agents..."
className="w-full border-2 focus:border-blue-500"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
<div className="flex flex-col sm:flex-row gap-4">
{/* Leaderboard button */}
<Link href={`/leaderboard`}>
<Button
variant="outline"
size="sm"
className="w-full h-10 sm:w-[180px] border-gray-200 text-black hover:bg-neon-pink/50 hover:text-white transition-colors"
>
<ClipboardList className="h-4 w-4 mr-2" />
Leaderboard
</Button>
</Link>
{/* Sort by Price */}
<Select value={sortOption} onValueChange={(value) => setSortOption(value)}>
<SelectTrigger className="w-full sm:w-[180px] border-2 bg-white">
<SelectValue placeholder="Sort by" />
</SelectTrigger>
<SelectContent className="bg-white border-2 border-gray-200">
<SelectItem value="all">Sort by Price</SelectItem>
<SelectItem value="price-asc">Price: Low to High</SelectItem>
<SelectItem value="price-desc">Price: High to Low</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* Categories */}
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-4">
{categories.map((category, index) => {
const Icon = category.icon
const isSelected = selectedCategory === category.key
return (
<motion.div
key={category.key}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
>
<Button
onClick={() => setSelectedCategory(category.key)}
variant="outline"
className={`h-auto py-4 w-full flex flex-col gap-2 transition-colors ${isSelected ? "bg-blue-100 border-blue-500" : "hover:bg-blue-50"
}`}
>
<Icon className="h-6 w-6 text-blue-500" />
<span className="text-sm">{category.name}</span>
</Button>
</motion.div>
)
})}
</div>
{/* Featured Agents Section */}
<div>
<h2 className="text-2xl font-semibold mb-6 text-blue-900">Personas</h2>
<div className="flex flex-col sm:flex-row gap-4 mb-6">
<Button
variant="outline"
size="sm"
className={`w-full sm:w-[180px] border-gray-200 text-black ${diagnosisRunning ? 'hover:bg-neon-pink/50' : 'hover:bg-neon-blue/50'} hover:text-white transition-colors`}
onClick={diagnosisRunning ? handleCancel : handleRunAllDiagnoses}
disabled={false}
>
{diagnosisRunning ? (
<>
<svg
className={`animate-spin h-4 w-4 mr-2 text-current`}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
/>
</svg>
Cancel
</>
) : (
<>
<RefreshCcw className="h-4 w-4 mr-2" />
Sync Personas
</>
)}
</Button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
{filteredAgents.length > 0 ? (
filteredAgents.map((agent, index) => (
<AgentCard key={agent.id} agent={agent} onUpdateAgent={onUpdateAgent} index={index} ref={(el) => { cardRefs.current[index] = el; }} />
))
) : searchQuery.length > 0 && filteredAgents.length < 1 ? (
<motion.p
className="text-gray-500 col-span-full text-center"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
No agents match your search.
</motion.p>
) : (
agents.map((agent, index) => (
<AgentCard key={agent.agentId} agent={agent} onUpdateAgent={onUpdateAgent} index={index} ref={(el) => { cardRefs.current[index] = el; }} />
))
)}
</div>
</div>
</motion.div>
</div>
)
}

View File

@ -0,0 +1,21 @@
import { Badge } from "./ui/badge"
interface AgentTagsProps {
tags: string[]
}
export function AgentTags({ tags }: AgentTagsProps) {
return (
<div className="flex flex-wrap gap-2">
{tags.map((tag) => (
<Badge
key={tag}
variant="secondary"
className="bg-gray-200 text-gray-800 font-roboto-mono px-3 py-1 text-xs"
>
{tag}
</Badge>
))}
</div>
)
}

View File

@ -0,0 +1,137 @@
import { Progress } from "./ui/progress"
export const tiers = [
{ name: "None", requiredAIUS: 0 },
{ name: "Newborn", requiredAIUS: 100 },
{ name: "Baby", requiredAIUS: 500 },
{ name: "Child", requiredAIUS: 1000 },
{ name: "Teen", requiredAIUS: 5000 },
{ name: "Adult", requiredAIUS: 10000 },
]
interface AgentTiersProps {
currentTier: {
name: "None" | "Newborn" | "Baby" | "Child" | "Teen" | "Adult"
level: number
stakedAIUS: number
}
}
export function AgentTiers({ currentTier }: AgentTiersProps) {
const currentTierIndex = tiers.findIndex((tier) => tier.name === currentTier.name)
const currentTierRequired = tiers[currentTierIndex]?.requiredAIUS ?? 0
const nextTier = tiers[currentTierIndex + 1]
const progress = nextTier
? ((currentTier.stakedAIUS - currentTierRequired) /
(nextTier.requiredAIUS - currentTierRequired)) *
100
: 100
return (
<div className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
<h2 className="text-2xl font-orbitron mb-6 text-gray-800">Agent Level</h2>
<div className="space-y-6">
<div className="flex items-center">
<TierIcon name={currentTier.name} className="w-12 h-12 mr-4" />
<div className="flex-1">
<div className="flex justify-between mb-2">
<span className="font-roboto-mono text-gray-600 text-sm">{currentTier.name}</span>
<span className="font-roboto-mono text-gray-500 text-sm">Level {currentTier.level}</span>
</div>
<Progress value={progress} className="h-2 bg-gray-200" />
<div className="flex justify-between mt-1">
<span className="font-roboto-mono text-gray-500 text-xs">{currentTier.stakedAIUS} AIUS</span>
{nextTier && (
<span className="font-roboto-mono text-gray-500 text-xs">
{nextTier.requiredAIUS} AIUS
</span>
)}
</div>
</div>
</div>
</div>
</div>
)
}
function TierIcon({ name, className }: { name: string; className?: string }) {
switch (name) {
case "Newborn":
return (
<svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10" stroke="#4F46E5" strokeWidth="2" />
<circle cx="12" cy="12" r="5" fill="#4F46E5" />
</svg>
)
case "Baby":
return (
<svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10" stroke="#4F46E5" strokeWidth="2" />
<path
d="M8 14C9.10457 15.5 10.5 16 12 16C13.5 16 14.8954 15.5 16 14"
stroke="#4F46E5"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
)
case "Child":
return (
<svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10" stroke="#4F46E5" strokeWidth="2" />
<circle cx="9" cy="10" r="1" fill="#4F46E5" />
<circle cx="15" cy="10" r="1" fill="#4F46E5" />
<path
d="M8 14C9.10457 15.5 10.5 16 12 16C13.5 16 14.8954 15.5 16 14"
stroke="#4F46E5"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
)
case "Teen":
return (
<svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10" stroke="#4F46E5" strokeWidth="2" />
<circle cx="9" cy="10" r="1" fill="#4F46E5" />
<circle cx="15" cy="10" r="1" fill="#4F46E5" />
<path
d="M8 14C9.10457 15.5 10.5 16 12 16C13.5 16 14.8954 15.5 16 14"
stroke="#4F46E5"
strokeWidth="2"
strokeLinecap="round"
/>
<path d="M12 7V9" stroke="#4F46E5" strokeWidth="2" strokeLinecap="round" />
</svg>
)
case "Adult":
return (
<svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10" stroke="#4F46E5" strokeWidth="2" />
<circle cx="9" cy="10" r="1" fill="#4F46E5" />
<circle cx="15" cy="10" r="1" fill="#4F46E5" />
<path
d="M8 14C9.10457 15.5 10.5 16 12 16C13.5 16 14.8954 15.5 16 14"
stroke="#4F46E5"
strokeWidth="2"
strokeLinecap="round"
/>
<path d="M12 7V9" stroke="#4F46E5" strokeWidth="2" strokeLinecap="round" />
<path d="M7 12L9 12" stroke="#4F46E5" strokeWidth="2" strokeLinecap="round" />
<path d="M15 12L17 12" stroke="#4F46E5" strokeWidth="2" strokeLinecap="round" />
</svg>
)
default:
return (
<div className={className}>
<svg viewBox="0 0 24 24" fill="none" className="w-full h-full" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10" stroke="#E5E7EB" strokeWidth="2" />
<text x="12" y="16" textAnchor="middle" fill="#9CA3AF" fontSize="10">None</text>
</svg>
</div>
)
}
}

View File

@ -0,0 +1,50 @@
import { useEffect, useRef, useState } from "react";
import { clsx } from "clsx";
import { IconButton } from "./icon-button";
export const AssistantText = ({ name,message }: { name:string, message: string }) => {
const scrollRef = useRef<HTMLDivElement>(null);
const [unlimited, setUnlimited] = useState(false)
// Replace all of the emotion tag in message with ""
message = message.replace(/\[(.*?)\]/g, "");
useEffect(() => {
scrollRef.current?.scrollIntoView({
behavior: "smooth",
block: "center",
});
});
return (
<div className="absolute bottom-0 left-0 mb-5 w-full">
<div className="mx-auto max-w-4xl w-full px-4 md:px-16">
<div className="backdrop-blur-lg rounded-lg">
<div className="bg-white/70 rounded-lg backdrop-blur-lg shadow-lg">
<div className="px-8 pr-1 py-3 bg-rose/90 rounded-t-lg text-white font-bold tracking-wider">
<span className="p-4 bg-pink-600/80 rounded-lg rounded-tl-none rounded-tr-none shadow-sm">
{name.toUpperCase()}
</span>
<IconButton
iconName="24/FrameSize"
className="bg-transparent hover:bg-transparent active:bg-transparent disabled:bg-transparent float-right"
isProcessing={false}
onClick={() => setUnlimited(!unlimited)}
/>
</div>
<div className={clsx(
"px-8 py-4 overflow-y-auto",
unlimited ? 'max-h-[calc(75vh)]' : 'max-h-32',
)}>
<div className="min-h-8 max-h-full text-gray-700 typography-16 font-bold">
{message.replace(/\[([a-zA-Z]*?)\]/g, "")}
<div ref={scrollRef} />
</div>
</div>
</div>
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,61 @@
import { CheckCircle, XCircle, Loader2 } from "lucide-react";
import { useEffect } from "react";
export const checks = [
{ label: "VRM", key: "vrm" },
{ label: "LLM", key: "chatbot" },
{ label: "TTS", key: "tts" },
{ label: "STT", key: "stt" },
{ label: "Vision", key: "vision" },
{ label: "AmicaLife", key: "amicaLife" },
] as const;
export type CheckKey = typeof checks[number]["key"];
export type Status = { status: "idle" | "loading" | "pass" | "fail", score: number };
export type DiagnosisResultType = {
[key in CheckKey]: Status;
} & {
overall?: string;
};
interface DiagnosisResultProps {
label: string;
status: Status;
}
export const DiagnosisResult = ({ label, status }: DiagnosisResultProps) => {
const statusIcon = {
pass: <CheckCircle className="text-green-500" size={20} />,
fail: <XCircle className="text-red-500" size={20} />,
loading: <Loader2 className="animate-spin text-gray-400" size={20} />,
idle: <div className="w-5 h-5 rounded-full bg-gray-200" />,
};
const statusColor = {
pass: "text-green-600",
fail: "text-red-600",
loading: "text-gray-500",
idle: "text-gray-400",
};
return (
<div className="flex items-center gap-3 bg-gray-50 border border-gray-100 p-4 rounded-xl shadow-sm">
{statusIcon[status.status]}
<div className="justify-between">
{/* Label and status */}
<div className="flex flex-col">
<span className="font-medium text-sm text-gray-700">{label}</span>
<span className={`text-xs ${statusColor[status.status]}`}>
{status.status === "idle" ? "Not checked" : status.score >= 0 ? `Score: ${status.score}` : "N/A"}
</span>
</div>
{/* Each evaluation criteria */}
<div className="flex flex-col">
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,94 @@
"use client"
import { ConnectButton } from "@rainbow-me/rainbowkit"
import { motion, useScroll, useTransform } from "framer-motion"
import { useRef } from "react"
export function Header() {
const ref = useRef<HTMLDivElement>(null)
const { scrollY } = useScroll()
const textY = useTransform(scrollY, [0, 300], [0, 100])
const opacity = useTransform(scrollY, [0, 300], [1, 0])
const scale = useTransform(scrollY, [0, 300], [1, 0.9])
return (
<div ref={ref} className="relative h-[40vh] flex items-center justify-center bg-scifi-dark overflow-hidden">
<div className="absolute inset-0 w-full h-full bg-tech-pattern opacity-50" />
<div className="absolute inset-0 w-full h-full">
<div className="absolute inset-0 bg-gradient-to-r from-neon-pink/20 to-neon-blue/20 mix-blend-overlay" />
{/* <ConnectButton /> */}
</div>
<motion.div className="relative z-10 text-center" style={{ y: textY, opacity, scale }}>
<div className="relative">
<motion.h1
className="text-5xl md:text-7xl font-orbitron font-bold text-white mb-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
Persona Village
<span className="absolute -top-4 left-1/2 -translate-x-1/2 text-neon-blue text-sm font-noto opacity-75">
アミカエージェント
</span>
</motion.h1>
</div>
<motion.p
className="text-xl text-blue-100 max-w-2xl mx-auto px-4 font-roboto-mono"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.3 }}
>
Discover and deploy Amica Personas to meet them in our village.
</motion.p>
</motion.div>
</div>
)
}
export function LeaderboardHeader() {
const ref = useRef<HTMLDivElement>(null)
const { scrollY } = useScroll()
const textY = useTransform(scrollY, [0, 300], [0, 100])
const opacity = useTransform(scrollY, [0, 300], [1, 0])
const scale = useTransform(scrollY, [0, 300], [1, 0.9])
return (
<div ref={ref} className="relative h-[40vh] flex items-center justify-center bg-scifi-dark overflow-hidden">
<div className="absolute inset-0 w-full h-full bg-tech-pattern opacity-50" />
<div className="absolute inset-0 w-full h-full">
<div className="absolute inset-0 bg-gradient-to-r from-neon-pink/20 to-neon-blue/20 mix-blend-overlay" />
{/* <ConnectButton /> */}
</div>
<motion.div className="relative z-10 text-center" style={{ y: textY, opacity, scale }}>
<div className="relative">
<motion.h1
className="text-5xl md:text-7xl font-orbitron font-bold text-white mb-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
Leaderboard
<span className="absolute -top-4 left-1/2 -translate-x-1/2 text-neon-blue text-sm font-noto opacity-75">
アミカエージェント
</span>
</motion.h1>
</div>
<motion.p
className="text-xl text-blue-100 max-w-2xl mx-auto px-4 font-roboto-mono"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.3 }}
>
Discover the most talented AI agents in our village. These champions excel across multiple domains, from conversation to creativity.
</motion.p>
</motion.div>
</div>
)
}

View File

@ -0,0 +1,30 @@
import { KnownIconType } from "@charcoal-ui/icons";
import { ButtonHTMLAttributes } from "react";
type Props = ButtonHTMLAttributes<HTMLButtonElement> & {
iconName: keyof KnownIconType;
isProcessing: boolean;
label?: string;
};
export const IconButton = ({
iconName,
isProcessing,
label,
...rest
}: Props) => {
return (
<button
{...rest}
className={`bg-primary hover:bg-primary-hover active:bg-primary-press disabled:bg-primary-disabled text-white rounded-lg text-sm p-1 text-center inline-flex items-center mr-2
${rest.className}
`}
>
{isProcessing ? (
<pixiv-icon name={"24/Dot"} scale="1"></pixiv-icon>
) : (
<pixiv-icon name={iconName} scale="1"></pixiv-icon>
)}
{label && <div className="mx-2 font-bold">{label}</div>}
</button>
);
};

View File

@ -0,0 +1,47 @@
import { Check, X } from "lucide-react";
interface AgentIntegrationsProps {
integrations: {
brain?: string;
virtuals?: string;
eacc?: string;
uos?: string;
};
}
const INTEGRATION_INFO = [
{ key: "brain", name: "Amica Brain" },
{ key: "virtuals", name: "Virtuals" },
{ key: "eacc", name: "EACC Marketplace" },
{ key: "uos", name: "UOS" },
] as const;
export function Integrations({ integrations }: AgentIntegrationsProps) {
return (
<div className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
<h2 className="text-2xl font-orbitron mb-6 text-gray-800">Integrations</h2>
<div className="grid grid-cols-2 gap-4">
{INTEGRATION_INFO.map(({ key, name }) => {
const isActive = !!integrations[key];
return (
<div
key={key}
className={`p-4 rounded-lg border ${
isActive ? "border-green-500 bg-green-50" : "border-gray-300 bg-gray-50"
}`}
>
<div className="flex items-center justify-between">
<span className="font-roboto-mono text-sm">{name}</span>
{isActive ? (
<Check className="text-green-500" size={20} />
) : (
<X className="text-gray-400" size={20} />
)}
</div>
</div>
);
})}
</div>
</div>
);
}

View File

@ -0,0 +1,127 @@
"use client"
import { useMemo, useState } from "react"
import { Line } from "react-chartjs-2"
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
TimeScale,
} from "chart.js"
import "chartjs-adapter-date-fns"
import { Button } from "./ui/button"
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, TimeScale)
const timeFrames = [
{ label: "1D", ms: 1 * 24 * 60 * 60 * 1000 },
{ label: "1W", ms: 7 * 24 * 60 * 60 * 1000 },
{ label: "1M", ms: 30 * 24 * 60 * 60 * 1000 },
{ label: "3M", ms: 90 * 24 * 60 * 60 * 1000 },
{ label: "1Y", ms: 365 * 24 * 60 * 60 * 1000 },
{ label: "All", ms: Infinity },
]
const getTimeUnit = (label: string): "minute" | "hour" | "day" | "month" => {
switch (label) {
case "1D":
return "minute"
case "1W":
return "hour"
case "1M":
case "3M":
return "day"
case "1Y":
return "month"
default:
return "day"
}
}
export function PriceChart({ priceHistory }: { priceHistory: { x: string; y: number }[] }) {
const [selectedTimeFrame, setSelectedTimeFrame] = useState(timeFrames[2]) // Default: 1M
const latestTimestamp = useMemo(() => {
return priceHistory.length > 0
? new Date(priceHistory[priceHistory.length - 1].x).getTime()
: Date.now()
}, [priceHistory])
const filteredData = useMemo(() => {
if (selectedTimeFrame.ms === Infinity) return priceHistory
return priceHistory.filter((d) => new Date(d.x).getTime() >= latestTimestamp - selectedTimeFrame.ms)
}, [priceHistory, selectedTimeFrame, latestTimestamp])
const chartData = {
datasets: [
{
label: "Price",
data: filteredData,
borderColor: "rgb(59, 130, 246)",
backgroundColor: "rgba(59, 130, 246, 0.5)",
borderWidth: 2,
pointRadius: 0,
tension: 0.1,
},
],
}
const chartOptions = useMemo(() => ({
responsive: true,
interaction: {
mode: "index" as const,
intersect: false,
},
plugins: {
legend: { display: false },
title: { display: false },
},
scales: {
x: {
type: "time" as const,
time: {
unit: getTimeUnit(selectedTimeFrame.label),
},
grid: { display: false },
},
y: {
position: "right" as const,
grid: {
color: "rgba(107, 114, 128, 0.1)",
},
ticks: {
callback: (value: any) => `$${value.toLocaleString()}`,
},
},
},
}), [selectedTimeFrame])
return (
<div className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
<div className="flex justify-between items-center mb-4">
<div className="text-2xl font-bold font-orbitron text-gray-800">
{priceHistory.length ? `${priceHistory[priceHistory.length - 1].y.toFixed(4)} AIUS` : "Loading..."}
</div>
<div className="flex space-x-2">
{timeFrames.map((tf) => (
<Button
key={tf.label}
variant={selectedTimeFrame.label === tf.label ? "default" : "outline"}
size="sm"
onClick={() => setSelectedTimeFrame(tf)}
className="font-roboto-mono"
>
{tf.label}
</Button>
))}
</div>
</div>
<Line options={chartOptions} data={chartData} />
</div>
)
}

View File

@ -0,0 +1,55 @@
import { getExplorerUrl } from "@/lib/agents"
import { Button } from "./ui/button"
import { Twitter, Facebook, Linkedin, Github } from "lucide-react"
import { Agent } from "@/types/agent"
interface SocialMediaProps {
agent: Agent;
}
export function SocialMediaButtons({agent}: SocialMediaProps) {
return (
<div className="flex space-x-4">
{agent.erc20 && (
<Button
variant="outline"
className="border-blue-700 text-blue-700 hover:bg-blue-100 hover:text-blue-900"
onClick={() =>
window.open(getExplorerUrl(agent.erc20!), "_blank", "noopener,noreferrer")
}
>
View on Explorer
</Button>
)}
<Button
variant="outline"
size="icon"
className="border-blue-400 text-blue-400 hover:bg-blue-100 hover:text-blue-600"
>
<Twitter className="h-5 w-5" />
</Button>
<Button
variant="outline"
size="icon"
className="border-blue-600 text-blue-600 hover:bg-blue-100 hover:text-blue-800"
>
<Facebook className="h-5 w-5" />
</Button>
<Button
variant="outline"
size="icon"
className="border-blue-700 text-blue-700 hover:bg-blue-100 hover:text-blue-900"
>
<Linkedin className="h-5 w-5" />
</Button>
<Button
variant="outline"
size="icon"
className="border-gray-700 text-gray-700 hover:bg-gray-100 hover:text-gray-900"
>
<Github className="h-5 w-5" />
</Button>
</div>
)
}

View File

@ -0,0 +1,11 @@
'use client'
import * as React from 'react'
import {
ThemeProvider as NextThemesProvider,
type ThemeProviderProps,
} from 'next-themes'
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

View File

@ -0,0 +1,24 @@
export function TokenData({ stats }: { stats: Record<string, any> | null }) {
if (!stats) return <p>Loading...</p>;
const data = [
{ label: "Market Cap", value: `${stats.marketCap.toFixed(2)} AIUS` },
{ label: "24h Change", value: `${stats.change24h >= 0 ? "+" : ""}${stats.change24h.toFixed(2)}%` },
{ label: "TVL", value: `${stats.tvl.toFixed(2)} AIUS` },
{ label: "Holders", value: stats.holders.toLocaleString() },
{ label: "24h Volume", value: `${stats.volume.toFixed(2)} AIUS` },
];
return (
<div className="flex justify-between bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
{data.map((item) => (
<div key={item.label} className="text-center">
<p className="text-sm font-roboto-mono text-gray-500 mb-1">{item.label}</p>
<p className={`text-lg font-orbitron ${item.label === "24h Change" && stats.change24h < 0 ? "text-red-500" : "text-gray-800"}`}>
{item.value}
</p>
</div>
))}
</div>
);
}

View File

@ -0,0 +1,58 @@
"use client"
import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const Accordion = AccordionPrimitive.Root
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border-b", className)}
{...props}
/>
))
AccordionItem.displayName = "AccordionItem"
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
))
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
))
AccordionContent.displayName = AccordionPrimitive.Content.displayName
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }

View File

@ -0,0 +1,141 @@
"use client"
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
const AlertDialog = AlertDialogPrimitive.Root
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
const AlertDialogPortal = AlertDialogPrimitive.Portal
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
AlertDialogHeader.displayName = "AlertDialogHeader"
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
AlertDialogFooter.displayName = "AlertDialogFooter"
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className
)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}

View File

@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }

View File

@ -0,0 +1,7 @@
"use client"
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
const AspectRatio = AspectRatioPrimitive.Root
export { AspectRatio }

View File

@ -0,0 +1,50 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }

View File

@ -0,0 +1,79 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground hover:bg-accent/50",
},
},
defaultVariants: {
variant: "default",
},
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {
loading?: boolean;
}
function Badge({
className,
variant,
onClick,
loading,
children,
...props
}: BadgeProps) {
return (
<div
className={cn(
badgeVariants({ variant }),
onClick && "cursor-pointer",
"relative select-none",
className
)}
onClick={onClick}
role={onClick ? "button" : undefined}
tabIndex={onClick ? 0 : undefined}
{...props}
>
{loading && (
<svg
className="mr-1 h-3 w-3 animate-spin text-current"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8v8H4z"
></path>
</svg>
)}
{children}
</div>
);
}
export { Badge, badgeVariants };

View File

@ -0,0 +1,115 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
const Breadcrumb = React.forwardRef<
HTMLElement,
React.ComponentPropsWithoutRef<"nav"> & {
separator?: React.ReactNode
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />)
Breadcrumb.displayName = "Breadcrumb"
const BreadcrumbList = React.forwardRef<
HTMLOListElement,
React.ComponentPropsWithoutRef<"ol">
>(({ className, ...props }, ref) => (
<ol
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className
)}
{...props}
/>
))
BreadcrumbList.displayName = "BreadcrumbList"
const BreadcrumbItem = React.forwardRef<
HTMLLIElement,
React.ComponentPropsWithoutRef<"li">
>(({ className, ...props }, ref) => (
<li
ref={ref}
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
))
BreadcrumbItem.displayName = "BreadcrumbItem"
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a"
return (
<Comp
ref={ref}
className={cn("transition-colors hover:text-foreground", className)}
{...props}
/>
)
})
BreadcrumbLink.displayName = "BreadcrumbLink"
const BreadcrumbPage = React.forwardRef<
HTMLSpanElement,
React.ComponentPropsWithoutRef<"span">
>(({ className, ...props }, ref) => (
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn("font-normal text-foreground", className)}
{...props}
/>
))
BreadcrumbPage.displayName = "BreadcrumbPage"
const BreadcrumbSeparator = ({
children,
className,
...props
}: React.ComponentProps<"li">) => (
<li
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
)
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
const BreadcrumbEllipsis = ({
className,
...props
}: React.ComponentProps<"span">) => (
<span
role="presentation"
aria-hidden="true"
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
)
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}

View File

@ -0,0 +1,56 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

View File

@ -0,0 +1,66 @@
"use client"
import * as React from "react"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { DayPicker } from "react-day-picker"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
export type CalendarProps = React.ComponentProps<typeof DayPicker>
function Calendar({
className,
classNames,
showOutsideDays = true,
...props
}: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell:
"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
day: cn(
buttonVariants({ variant: "ghost" }),
"h-9 w-9 p-0 font-normal aria-selected:opacity-100"
),
day_range_end: "day-range-end",
day_selected:
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside:
"day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle:
"aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: ({ ...props }) => <ChevronLeft className="h-4 w-4" />,
IconRight: ({ ...props }) => <ChevronRight className="h-4 w-4" />,
}}
{...props}
/>
)
}
Calendar.displayName = "Calendar"
export { Calendar }

View File

@ -0,0 +1,79 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg border bg-card text-card-foreground shadow-sm",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"text-2xl font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

View File

@ -0,0 +1,262 @@
"use client"
import * as React from "react"
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react"
import { ArrowLeft, ArrowRight } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
type CarouselOptions = UseCarouselParameters[0]
type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
orientation?: "horizontal" | "vertical"
setApi?: (api: CarouselApi) => void
}
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
api: ReturnType<typeof useEmblaCarousel>[1]
scrollPrev: () => void
scrollNext: () => void
canScrollPrev: boolean
canScrollNext: boolean
} & CarouselProps
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
function useCarousel() {
const context = React.useContext(CarouselContext)
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />")
}
return context
}
const Carousel = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & CarouselProps
>(
(
{
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
},
ref
) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins
)
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false)
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return
}
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}, [])
const scrollPrev = React.useCallback(() => {
api?.scrollPrev()
}, [api])
const scrollNext = React.useCallback(() => {
api?.scrollNext()
}, [api])
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault()
scrollPrev()
} else if (event.key === "ArrowRight") {
event.preventDefault()
scrollNext()
}
},
[scrollPrev, scrollNext]
)
React.useEffect(() => {
if (!api || !setApi) {
return
}
setApi(api)
}, [api, setApi])
React.useEffect(() => {
if (!api) {
return
}
onSelect(api)
api.on("reInit", onSelect)
api.on("select", onSelect)
return () => {
api?.off("select", onSelect)
}
}, [api, onSelect])
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
)
}
)
Carousel.displayName = "Carousel"
const CarouselContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel()
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className
)}
{...props}
/>
</div>
)
})
CarouselContent.displayName = "CarouselContent"
const CarouselItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { orientation } = useCarousel()
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className
)}
{...props}
/>
)
})
CarouselItem.displayName = "CarouselItem"
const CarouselPrevious = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
)
})
CarouselPrevious.displayName = "CarouselPrevious"
const CarouselNext = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel()
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
)
})
CarouselNext.displayName = "CarouselNext"
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
}

View File

@ -0,0 +1,365 @@
"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
}
const ChartContainer = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
}
>(({ id, className, children, config, ...props }, ref) => {
const uniqueId = React.useId()
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-chart={chartId}
ref={ref}
className={cn(
"flex aspect-video justify-center text-xs [&_.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-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.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 [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
})
ChartContainer.displayName = "Chart"
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
const ChartTooltipContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
}
>(
(
{
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
},
ref
) => {
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
ref={ref}
className={cn(
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.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(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
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="font-mono font-medium tabular-nums text-foreground">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
)
ChartTooltipContent.displayName = "ChartTooltip"
const ChartLegend = RechartsPrimitive.Legend
const ChartLegendContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean
nameKey?: string
}
>(
(
{ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey },
ref
) => {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
ref={ref}
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={item.value}
className={cn(
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
)
ChartLegendContent.displayName = "ChartLegend"
// Helper to extract item config from a payload.
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,30 @@
"use client"
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }

View File

@ -0,0 +1,11 @@
"use client"
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
const Collapsible = CollapsiblePrimitive.Root
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent
export { Collapsible, CollapsibleTrigger, CollapsibleContent }

View File

@ -0,0 +1,153 @@
"use client"
import * as React from "react"
import { type DialogProps } from "@radix-ui/react-dialog"
import { Command as CommandPrimitive } from "cmdk"
import { Search } from "lucide-react"
import { cn } from "@/lib/utils"
import { Dialog, DialogContent } from "@/components/ui/dialog"
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className
)}
{...props}
/>
))
Command.displayName = CommandPrimitive.displayName
const CommandDialog = ({ children, ...props }: DialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0 shadow-lg">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
))
CommandInput.displayName = CommandPrimitive.Input.displayName
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
))
CommandList.displayName = CommandPrimitive.List.displayName
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
<CommandPrimitive.Empty
ref={ref}
className="py-6 text-center text-sm"
{...props}
/>
))
CommandEmpty.displayName = CommandPrimitive.Empty.displayName
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className
)}
{...props}
/>
))
CommandGroup.displayName = CommandPrimitive.Group.displayName
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
className={cn("-mx-1 h-px bg-border", className)}
{...props}
/>
))
CommandSeparator.displayName = CommandPrimitive.Separator.displayName
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
className
)}
{...props}
/>
))
CommandItem.displayName = CommandPrimitive.Item.displayName
const CommandShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
CommandShortcut.displayName = "CommandShortcut"
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View File

@ -0,0 +1,200 @@
"use client"
import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const ContextMenu = ContextMenuPrimitive.Root
const ContextMenuTrigger = ContextMenuPrimitive.Trigger
const ContextMenuGroup = ContextMenuPrimitive.Group
const ContextMenuPortal = ContextMenuPrimitive.Portal
const ContextMenuSub = ContextMenuPrimitive.Sub
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup
const ContextMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<ContextMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
))
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName
const ContextMenuSubContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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",
className
)}
{...props}
/>
))
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName
const ContextMenuContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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",
className
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
))
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName
const ContextMenuItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName
const ContextMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<ContextMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
))
ContextMenuCheckboxItem.displayName =
ContextMenuPrimitive.CheckboxItem.displayName
const ContextMenuRadioItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<ContextMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
))
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName
const ContextMenuLabel = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold text-foreground",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName
const ContextMenuSeparator = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
))
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName
const ContextMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
ContextMenuShortcut.displayName = "ContextMenuShortcut"
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}

View File

@ -0,0 +1,122 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}

View File

@ -0,0 +1,118 @@
"use client"
import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import { cn } from "@/lib/utils"
const Drawer = ({
shouldScaleBackground = true,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
<DrawerPrimitive.Root
shouldScaleBackground={shouldScaleBackground}
{...props}
/>
)
Drawer.displayName = "Drawer"
const DrawerTrigger = DrawerPrimitive.Trigger
const DrawerPortal = DrawerPrimitive.Portal
const DrawerClose = DrawerPrimitive.Close
const DrawerOverlay = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Overlay
ref={ref}
className={cn("fixed inset-0 z-50 bg-black/80", className)}
{...props}
/>
))
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
className
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
))
DrawerContent.displayName = "DrawerContent"
const DrawerHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
{...props}
/>
)
DrawerHeader.displayName = "DrawerHeader"
const DrawerFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
DrawerFooter.displayName = "DrawerFooter"
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DrawerTitle.displayName = DrawerPrimitive.Title.displayName
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DrawerDescription.displayName = DrawerPrimitive.Description.displayName
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
}

View File

@ -0,0 +1,200 @@
"use client"
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}

View File

@ -0,0 +1,178 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
ControllerProps,
FieldPath,
FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message) : children
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-sm font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

View File

@ -0,0 +1,29 @@
"use client"
import * as React from "react"
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
import { cn } from "@/lib/utils"
const HoverCard = HoverCardPrimitive.Root
const HoverCardTrigger = HoverCardPrimitive.Trigger
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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",
className
)}
{...props}
/>
))
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName
export { HoverCard, HoverCardTrigger, HoverCardContent }

View File

@ -0,0 +1,71 @@
"use client"
import * as React from "react"
import { OTPInput, OTPInputContext } from "input-otp"
import { Dot } from "lucide-react"
import { cn } from "@/lib/utils"
const InputOTP = React.forwardRef<
React.ElementRef<typeof OTPInput>,
React.ComponentPropsWithoutRef<typeof OTPInput>
>(({ className, containerClassName, ...props }, ref) => (
<OTPInput
ref={ref}
containerClassName={cn(
"flex items-center gap-2 has-[:disabled]:opacity-50",
containerClassName
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
))
InputOTP.displayName = "InputOTP"
const InputOTPGroup = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center", className)} {...props} />
))
InputOTPGroup.displayName = "InputOTPGroup"
const InputOTPSlot = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div"> & { index: number }
>(({ index, className, ...props }, ref) => {
const inputOTPContext = React.useContext(OTPInputContext)
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index]
return (
<div
ref={ref}
className={cn(
"relative flex h-10 w-10 items-center justify-center border-y border-r border-input text-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
isActive && "z-10 ring-2 ring-ring ring-offset-background",
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
</div>
)}
</div>
)
})
InputOTPSlot.displayName = "InputOTPSlot"
const InputOTPSeparator = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ ...props }, ref) => (
<div ref={ref} role="separator" {...props}>
<Dot />
</div>
))
InputOTPSeparator.displayName = "InputOTPSeparator"
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }

View File

@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View File

@ -0,0 +1,26 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@ -0,0 +1,236 @@
"use client"
import * as React from "react"
import * as MenubarPrimitive from "@radix-ui/react-menubar"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const MenubarMenu = MenubarPrimitive.Menu
const MenubarGroup = MenubarPrimitive.Group
const MenubarPortal = MenubarPrimitive.Portal
const MenubarSub = MenubarPrimitive.Sub
const MenubarRadioGroup = MenubarPrimitive.RadioGroup
const Menubar = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Root>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Root
ref={ref}
className={cn(
"flex h-10 items-center space-x-1 rounded-md border bg-background p-1",
className
)}
{...props}
/>
))
Menubar.displayName = MenubarPrimitive.Root.displayName
const MenubarTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Trigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
className
)}
{...props}
/>
))
MenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName
const MenubarSubTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<MenubarPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
))
MenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName
const MenubarSubContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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",
className
)}
{...props}
/>
))
MenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName
const MenubarContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Content>
>(
(
{ className, align = "start", alignOffset = -4, sideOffset = 8, ...props },
ref
) => (
<MenubarPrimitive.Portal>
<MenubarPrimitive.Content
ref={ref}
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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",
className
)}
{...props}
/>
</MenubarPrimitive.Portal>
)
)
MenubarContent.displayName = MenubarPrimitive.Content.displayName
const MenubarItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
MenubarItem.displayName = MenubarPrimitive.Item.displayName
const MenubarCheckboxItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<MenubarPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
))
MenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName
const MenubarRadioItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<MenubarPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
))
MenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName
const MenubarLabel = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
MenubarLabel.displayName = MenubarPrimitive.Label.displayName
const MenubarSeparator = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Separator>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
MenubarSeparator.displayName = MenubarPrimitive.Separator.displayName
const MenubarShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
MenubarShortcut.displayname = "MenubarShortcut"
export {
Menubar,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarItem,
MenubarSeparator,
MenubarLabel,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarPortal,
MenubarSubContent,
MenubarSubTrigger,
MenubarGroup,
MenubarSub,
MenubarShortcut,
}

View File

@ -0,0 +1,128 @@
import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Root
ref={ref}
className={cn(
"relative z-10 flex max-w-max flex-1 items-center justify-center",
className
)}
{...props}
>
{children}
<NavigationMenuViewport />
</NavigationMenuPrimitive.Root>
))
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName
const NavigationMenuList = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.List>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.List
ref={ref}
className={cn(
"group flex flex-1 list-none items-center justify-center space-x-1",
className
)}
{...props}
/>
))
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName
const NavigationMenuItem = NavigationMenuPrimitive.Item
const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
)
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Trigger
ref={ref}
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDown
className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
))
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName
const NavigationMenuContent = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Content
ref={ref}
className={cn(
"left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",
className
)}
{...props}
/>
))
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName
const NavigationMenuLink = NavigationMenuPrimitive.Link
const NavigationMenuViewport = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
>(({ className, ...props }, ref) => (
<div className={cn("absolute left-0 top-full flex justify-center")}>
<NavigationMenuPrimitive.Viewport
className={cn(
"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
className
)}
ref={ref}
{...props}
/>
</div>
))
NavigationMenuViewport.displayName =
NavigationMenuPrimitive.Viewport.displayName
const NavigationMenuIndicator = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Indicator
ref={ref}
className={cn(
"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
className
)}
{...props}
>
<div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
</NavigationMenuPrimitive.Indicator>
))
NavigationMenuIndicator.displayName =
NavigationMenuPrimitive.Indicator.displayName
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
}

View File

@ -0,0 +1,117 @@
import * as React from "react"
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
import { ButtonProps, buttonVariants } from "@/components/ui/button"
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
<nav
role="navigation"
aria-label="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
)
Pagination.displayName = "Pagination"
const PaginationContent = React.forwardRef<
HTMLUListElement,
React.ComponentProps<"ul">
>(({ className, ...props }, ref) => (
<ul
ref={ref}
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
))
PaginationContent.displayName = "PaginationContent"
const PaginationItem = React.forwardRef<
HTMLLIElement,
React.ComponentProps<"li">
>(({ className, ...props }, ref) => (
<li ref={ref} className={cn("", className)} {...props} />
))
PaginationItem.displayName = "PaginationItem"
type PaginationLinkProps = {
isActive?: boolean
} & Pick<ButtonProps, "size"> &
React.ComponentProps<"a">
const PaginationLink = ({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) => (
<a
aria-current={isActive ? "page" : undefined}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className
)}
{...props}
/>
)
PaginationLink.displayName = "PaginationLink"
const PaginationPrevious = ({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 pl-2.5", className)}
{...props}
>
<ChevronLeft className="h-4 w-4" />
<span>Previous</span>
</PaginationLink>
)
PaginationPrevious.displayName = "PaginationPrevious"
const PaginationNext = ({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 pr-2.5", className)}
{...props}
>
<span>Next</span>
<ChevronRight className="h-4 w-4" />
</PaginationLink>
)
PaginationNext.displayName = "PaginationNext"
const PaginationEllipsis = ({
className,
...props
}: React.ComponentProps<"span">) => (
<span
aria-hidden
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More pages</span>
</span>
)
PaginationEllipsis.displayName = "PaginationEllipsis"
export {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
}

View File

@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent }

View File

@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "@/lib/utils"
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
"relative h-4 w-full overflow-hidden rounded-full bg-secondary",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
))
Progress.displayName = ProgressPrimitive.Root.displayName
export { Progress }

View File

@ -0,0 +1,44 @@
"use client"
import * as React from "react"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Root
className={cn("grid gap-2", className)}
{...props}
ref={ref}
/>
)
})
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
})
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName
export { RadioGroup, RadioGroupItem }

View File

@ -0,0 +1,45 @@
"use client"
import { GripVertical } from "lucide-react"
import * as ResizablePrimitive from "react-resizable-panels"
import { cn } from "@/lib/utils"
const ResizablePanelGroup = ({
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (
<ResizablePrimitive.PanelGroup
className={cn(
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
className
)}
{...props}
/>
)
const ResizablePanel = ResizablePrimitive.Panel
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
"relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
className
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
<GripVertical className="h-2.5 w-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
)
export { ResizablePanelGroup, ResizablePanel, ResizableHandle }

View File

@ -0,0 +1,48 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }

View File

@ -0,0 +1,160 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}

View File

@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }

View File

@ -0,0 +1,140 @@
"use client"
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Sheet = SheetPrimitive.Root
const SheetTrigger = SheetPrimitive.Trigger
const SheetClose = SheetPrimitive.Close
const SheetPortal = SheetPrimitive.Portal
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
}
)
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
ref={ref}
className={cn(sheetVariants({ side }), className)}
{...props}
>
{children}
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
))
SheetContent.displayName = SheetPrimitive.Content.displayName
const SheetHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
SheetHeader.displayName = "SheetHeader"
const SheetFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
SheetFooter.displayName = "SheetFooter"
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold text-foreground", className)}
{...props}
/>
))
SheetTitle.displayName = SheetPrimitive.Title.displayName
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
SheetDescription.displayName = SheetPrimitive.Description.displayName
export {
Sheet,
SheetPortal,
SheetOverlay,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@ -0,0 +1,763 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { VariantProps, cva } from "class-variance-authority"
import { PanelLeft } from "lucide-react"
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import { Sheet, SheetContent } from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
const SIDEBAR_COOKIE_NAME = "sidebar:state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContext = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContext | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
const SidebarProvider = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
}
>(
(
{
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
},
ref
) => {
const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false)
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value
if (setOpenProp) {
setOpenProp(openState)
} else {
_setOpen(openState)
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
},
[setOpenProp, open]
)
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile
? setOpenMobile((open) => !open)
: setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile])
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault()
toggleSidebar()
}
}
window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContext>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
className
)}
ref={ref}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
)
}
)
SidebarProvider.displayName = "SidebarProvider"
const Sidebar = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
side?: "left" | "right"
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}
>(
(
{
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
},
ref
) => {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
if (collapsible === "none") {
return (
<div
className={cn(
"flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",
className
)}
ref={ref}
{...props}
>
{children}
</div>
)
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-mobile="true"
className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
)
}
return (
<div
ref={ref}
className="group peer hidden md:block text-sidebar-foreground"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
>
{/* This is what handles the sidebar gap on desktop */}
<div
className={cn(
"duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]"
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon]"
)}
/>
<div
className={cn(
"duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]"
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
)}
{...props}
>
<div
data-sidebar="sidebar"
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
>
{children}
</div>
</div>
</div>
)
}
)
Sidebar.displayName = "Sidebar"
const SidebarTrigger = React.forwardRef<
React.ElementRef<typeof Button>,
React.ComponentProps<typeof Button>
>(({ className, onClick, ...props }, ref) => {
const { toggleSidebar } = useSidebar()
return (
<Button
ref={ref}
data-sidebar="trigger"
variant="ghost"
size="icon"
className={cn("h-7 w-7", className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
}}
{...props}
>
<PanelLeft />
<span className="sr-only">Toggle Sidebar</span>
</Button>
)
})
SidebarTrigger.displayName = "SidebarTrigger"
const SidebarRail = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button">
>(({ className, ...props }, ref) => {
const { toggleSidebar } = useSidebar()
return (
<button
ref={ref}
data-sidebar="rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
)}
{...props}
/>
)
})
SidebarRail.displayName = "SidebarRail"
const SidebarInset = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"main">
>(({ className, ...props }, ref) => {
return (
<main
ref={ref}
className={cn(
"relative flex min-h-svh flex-1 flex-col bg-background",
"peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
className
)}
{...props}
/>
)
})
SidebarInset.displayName = "SidebarInset"
const SidebarInput = React.forwardRef<
React.ElementRef<typeof Input>,
React.ComponentProps<typeof Input>
>(({ className, ...props }, ref) => {
return (
<Input
ref={ref}
data-sidebar="input"
className={cn(
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
className
)}
{...props}
/>
)
})
SidebarInput.displayName = "SidebarInput"
const SidebarHeader = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
})
SidebarHeader.displayName = "SidebarHeader"
const SidebarFooter = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
})
SidebarFooter.displayName = "SidebarFooter"
const SidebarSeparator = React.forwardRef<
React.ElementRef<typeof Separator>,
React.ComponentProps<typeof Separator>
>(({ className, ...props }, ref) => {
return (
<Separator
ref={ref}
data-sidebar="separator"
className={cn("mx-2 w-auto bg-sidebar-border", className)}
{...props}
/>
)
})
SidebarSeparator.displayName = "SidebarSeparator"
const SidebarContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
)}
{...props}
/>
)
})
SidebarContent.displayName = "SidebarContent"
const SidebarGroup = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
)
})
SidebarGroup.displayName = "SidebarGroup"
const SidebarGroupLabel = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & { asChild?: boolean }
>(({ className, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "div"
return (
<Comp
ref={ref}
data-sidebar="group-label"
className={cn(
"duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
{...props}
/>
)
})
SidebarGroupLabel.displayName = "SidebarGroupLabel"
const SidebarGroupAction = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & { asChild?: boolean }
>(({ className, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
ref={ref}
data-sidebar="group-action"
className={cn(
"absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
})
SidebarGroupAction.displayName = "SidebarGroupAction"
const SidebarGroupContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => (
<div
ref={ref}
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
))
SidebarGroupContent.displayName = "SidebarGroupContent"
const SidebarMenu = React.forwardRef<
HTMLUListElement,
React.ComponentProps<"ul">
>(({ className, ...props }, ref) => (
<ul
ref={ref}
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
))
SidebarMenu.displayName = "SidebarMenu"
const SidebarMenuItem = React.forwardRef<
HTMLLIElement,
React.ComponentProps<"li">
>(({ className, ...props }, ref) => (
<li
ref={ref}
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
))
SidebarMenuItem.displayName = "SidebarMenuItem"
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
const SidebarMenuButton = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
} & VariantProps<typeof sidebarMenuButtonVariants>
>(
(
{
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
},
ref
) => {
const Comp = asChild ? Slot : "button"
const { isMobile, state } = useSidebar()
const button = (
<Comp
ref={ref}
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
)
if (!tooltip) {
return button
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
}
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
)
}
)
SidebarMenuButton.displayName = "SidebarMenuButton"
const SidebarMenuAction = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
asChild?: boolean
showOnHover?: boolean
}
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
ref={ref}
data-sidebar="menu-action"
className={cn(
"absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
className
)}
{...props}
/>
)
})
SidebarMenuAction.displayName = "SidebarMenuAction"
const SidebarMenuBadge = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => (
<div
ref={ref}
data-sidebar="menu-badge"
className={cn(
"absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
))
SidebarMenuBadge.displayName = "SidebarMenuBadge"
const SidebarMenuSkeleton = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
showIcon?: boolean
}
>(({ className, showIcon = false, ...props }, ref) => {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`
}, [])
return (
<div
ref={ref}
data-sidebar="menu-skeleton"
className={cn("rounded-md h-8 flex gap-2 px-2 items-center", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 flex-1 max-w-[--skeleton-width]"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
)
})
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton"
const SidebarMenuSub = React.forwardRef<
HTMLUListElement,
React.ComponentProps<"ul">
>(({ className, ...props }, ref) => (
<ul
ref={ref}
data-sidebar="menu-sub"
className={cn(
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
))
SidebarMenuSub.displayName = "SidebarMenuSub"
const SidebarMenuSubItem = React.forwardRef<
HTMLLIElement,
React.ComponentProps<"li">
>(({ ...props }, ref) => <li ref={ref} {...props} />)
SidebarMenuSubItem.displayName = "SidebarMenuSubItem"
const SidebarMenuSubButton = React.forwardRef<
HTMLAnchorElement,
React.ComponentProps<"a"> & {
asChild?: boolean
size?: "sm" | "md"
isActive?: boolean
}
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a"
return (
<Comp
ref={ref}
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
})
SidebarMenuSubButton.displayName = "SidebarMenuSubButton"
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}

View File

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

View File

@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import * as SliderPrimitive from "@radix-ui/react-slider"
import { cn } from "@/lib/utils"
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn(
"relative flex w-full touch-none select-none items-center",
className
)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
export { Slider }

View File

@ -0,0 +1,31 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }

View File

@ -0,0 +1,29 @@
"use client"
import * as React from "react"
import * as SwitchPrimitives from "@radix-ui/react-switch"
import { cn } from "@/lib/utils"
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitives.Root>
))
Switch.displayName = SwitchPrimitives.Root.displayName
export { Switch }

View File

@ -0,0 +1,117 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@ -0,0 +1,55 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }

View File

@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Textarea = React.forwardRef<
HTMLTextAreaElement,
React.ComponentProps<"textarea">
>(({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
})
Textarea.displayName = "Textarea"
export { Textarea }

View File

@ -0,0 +1,129 @@
"use client"
import * as React from "react"
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}

View File

@ -0,0 +1,35 @@
"use client"
import { useToast } from "@/hooks/use-toast"
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}

View File

@ -0,0 +1,61 @@
"use client"
import * as React from "react"
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle"
const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants>
>({
size: "default",
variant: "default",
})
const ToggleGroup = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &
VariantProps<typeof toggleVariants>
>(({ className, variant, size, children, ...props }, ref) => (
<ToggleGroupPrimitive.Root
ref={ref}
className={cn("flex items-center justify-center gap-1", className)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
))
ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName
const ToggleGroupItem = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &
VariantProps<typeof toggleVariants>
>(({ className, children, variant, size, ...props }, ref) => {
const context = React.useContext(ToggleGroupContext)
return (
<ToggleGroupPrimitive.Item
ref={ref}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
className
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
)
})
ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName
export { ToggleGroup, ToggleGroupItem }

View File

@ -0,0 +1,45 @@
"use client"
import * as React from "react"
import * as TogglePrimitive from "@radix-ui/react-toggle"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 gap-2",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3 min-w-10",
sm: "h-9 px-2.5 min-w-9",
lg: "h-11 px-5 min-w-11",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
const Toggle = React.forwardRef<
React.ElementRef<typeof TogglePrimitive.Root>,
React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &
VariantProps<typeof toggleVariants>
>(({ className, variant, size, ...props }, ref) => (
<TogglePrimitive.Root
ref={ref}
className={cn(toggleVariants({ variant, size, className }))}
{...props}
/>
))
Toggle.displayName = TogglePrimitive.Root.displayName
export { Toggle, toggleVariants }

View File

@ -0,0 +1,30 @@
"use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
const TooltipProvider = TooltipPrimitive.Provider
const Tooltip = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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",
className
)}
{...props}
/>
))
TooltipContent.displayName = TooltipPrimitive.Content.displayName
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}

View File

@ -0,0 +1,194 @@
"use client"
// Inspired by react-hot-toast library
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

View File

@ -0,0 +1,38 @@
import { useEffect, useRef } from "react";
export const UserText = ({ message }: { message: string }) => {
const scrollRef = useRef<HTMLDivElement>(null);
// Replace all of the emotion tag in message with ""
message = message.replace(/\[(.*?)\]/g, "");
useEffect(() => {
scrollRef.current?.scrollIntoView({
behavior: "smooth",
block: "center",
});
});
return (
<div className="absolute bottom-0 left-0 mb-5 w-full">
<div className="mx-auto max-w-4xl w-full px-4 md:px-16">
<div className="backdrop-blur-lg rounded-lg">
<div className="bg-white/70 rounded-lg backdrop-blur-lg shadow-lg">
<div className="px-8 pr-1 py-3 bg-rose/90 rounded-t-lg text-white font-bold tracking-wider">
<span className="p-4 bg-cyan-600/80 rounded-lg rounded-tl-none rounded-tr-none shadow-sm">
{"YOU"}
</span>
</div>
<div className="px-8 py-4 max-h-32 overflow-y-auto">
<div className="min-h-8 max-h-full typography-16 font-bold text-gray-600">
{message.replace(/\[([a-zA-Z]*?)\]/g, "")}
<div ref={scrollRef} />
</div>
</div>
</div>
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,68 @@
import { useContext, useCallback, useEffect, useState } from "react";
import { ViewerContext } from "@/features/vrmViewer/viewerContext";
export default function VRMDemo({
vrmUrl,
onLoaded,
onError,
}: {
vrmUrl: string,
onLoaded?: () => void,
onError?: () => void,
}) {
const { viewer } = useContext(ViewerContext);
const [isLoading, setIsLoading] = useState(true);
const [loadingError, setLoadingError] = useState(false);
useEffect(() => {
setIsLoading(true);
setLoadingError(false);
}, [vrmUrl]);
const canvasRef = useCallback(
(canvas: HTMLCanvasElement) => {
if (canvas) {
viewer.setup(canvas);
(new Promise(async (resolve, reject) => {
try {
const loaded = await viewer.loadVrm(vrmUrl);
resolve(true);
} catch (e) {
reject();
}
}))
.then(() => {
console.log("vrm loaded");
setIsLoading(false);
setLoadingError(false);
onLoaded && onLoaded();
})
.catch((e) => {
console.error("vrm loading error", e);
setLoadingError(true);
setIsLoading(false);
onError && onError();
});
}
},
[viewer, vrmUrl]
);
return (
<>
<canvas ref={canvasRef} className={"h-full w-full"} />
{isLoading && (
<p className="absolute text-gray-800 font-orbitron text-2xl">Loading...</p>
)}
{loadingError && (
<p className="absolute text-gray-800 font-orbitron text-2xl">Error loading VRM model</p>
)}
</>
);
}

View File

@ -0,0 +1,370 @@
import { Queue } from "@/utils/queue";
import { wait } from "@/utils/wait";
import { pauseIdleTimer, resumeIdleTimer } from "@/utils/isIdle";
import { Chat, ChatConfig } from "@/features/chat/chat";
import {
AmicaLifeEvents,
idleEvents,
handleIdleEvent,
basedPrompt,
TimestampedPrompt,
} from "@/features/amicaLife/eventHandler";
import { Viewer } from "../vrmViewer/viewer";
export class AmicaLife {
public initialized: boolean;
public mainEvents: Queue<AmicaLifeEvents>;
public viewer?: Viewer;
public chat?: Chat;
public setSubconciousLogs?: (subconciousLogs: TimestampedPrompt[]) => void;
public isChatSpeaking?: boolean;
public triggerMessage: boolean;
public eventProcessing?: boolean;
public isSleep: boolean;
private isSettingOff: boolean;
private isPause: boolean;
private isProcessingEventRunning?: boolean;
private isProcessingIdleRunning?: boolean;
constructor() {
this.initialized = false;
this.mainEvents = new Queue<AmicaLifeEvents>();
this.triggerMessage = false;
this.eventProcessing = false;
this.isSleep = false;
this.isPause = false;
this.isSettingOff = false;
this.isProcessingEventRunning = false;
this.isProcessingIdleRunning = false;
}
public initialize(
config: ChatConfig,
viewer: Viewer,
chat: Chat,
isChatSpeaking: boolean,
setSubconciousLogs: (subconciousLogs: TimestampedPrompt[]) => void,
) {
this.viewer = viewer;
this.chat = chat;
this.isChatSpeaking = isChatSpeaking;
this.setSubconciousLogs = setSubconciousLogs;
this.loadIdleTextPrompt(null);
// This loop will run depending on Amica Life Enabled/Disabled config
this.processingIdle(config);
this.initialized = true;
}
// These are function to coonfigure mainEvents queue
// Function for loaded idle text prompt
public async loadIdleTextPrompt(prompts: string[] | null) {
if (prompts === null) {
idleEvents.forEach((prompt) =>
this.mainEvents.enqueue({ events: prompt }),
);
} else {
if (prompts.length > 0) {
this.mainEvents.clear();
prompts.forEach((prompt: string) =>
basedPrompt.idleTextPrompt.push(prompt),
);
}
}
}
// Function to insert event to the front of the mainEvents Queue
public insertFront(event: AmicaLifeEvents) {
const newQueue = new Queue<AmicaLifeEvents>();
newQueue.enqueue(event);
while (!this.mainEvents.isEmpty()) {
newQueue.enqueue(this.mainEvents.dequeue()!);
}
this.mainEvents = newQueue;
}
// Function to remove a specific event from the mainEvents queue
public removeEvent(eventName: string) {
const newQueue = new Queue<AmicaLifeEvents>();
let found = false;
while (!this.mainEvents.isEmpty()) {
const event = this.mainEvents.dequeue();
if (event && event.events !== eventName) {
newQueue.enqueue(event);
} else {
found = true;
}
}
this.mainEvents = newQueue;
}
// Function to check if a specific event exists in the mainEvents queue
public containsEvent(eventName: string): boolean {
let contains = false;
this.mainEvents.forEach((event) => {
if (event.events === eventName) {
contains = true;
}
});
return contains;
}
// These are function to handle idle event
// Function to check message from user
public receiveMessageFromUser(message: string) {
if (message.toLowerCase().includes("news")) {
console.log("Triggering news function call.");
this.insertFront({ events: "News" });
}
// Re-enqueue subconcious event after get the user input (1 Subconcious events per idle cycle)
!this.containsEvent("Subconcious")
? this.mainEvents.enqueue({ events: "Subconcious" })
: null;
this.pause();
this.wakeFromSleep();
this.triggerMessage = true;
}
// Function handle when amica got poked in amica life event
// public handlePoked() {
// if (!this.chat?.isAwake() && config("amica_life_enabled") === "true") {
// console.log("Handling idle event:", "I just poked you!");
// this.chat?.receiveMessageFromUser("I just poked you!",true);
// }
// }
public async processingIdle(config: ChatConfig) {
// Preventing duplicate processingIdle loop
if (this.isProcessingIdleRunning) {
return;
}
this.isProcessingIdleRunning = true;
console.log("Starting Amica Life");
while (config.amica_life_params.amica_life_enabled === "true") {
// Check if amica is in idle state trigger processingEvent loop
if (!this.chat?.isAwake()) {
this.processingEvent(config);
}
await wait(50);
}
this.isProcessingIdleRunning = false;
this.isProcessingEventRunning = false;
this.triggerMessage = false;
console.log("Stopping idle loop");
}
public async processingEvent(config: ChatConfig) {
// Preventing duplicate processing event loop
if (this.isProcessingEventRunning) {
// Check for resume
if (!(await this.checkResume())) {
return;
}
return;
}
// User must start the conversation with amica first to activate amica life
if (!this.triggerMessage) {
return;
}
this.isProcessingEventRunning = true;
while (this.isProcessingEventRunning) {
// Wait for current event to finish before processing next event
if (
this.chat!.speakJobs.size() < 1 &&
this.chat!.ttsJobs.size() < 1 &&
!this.isChatSpeaking &&
!this.eventProcessing
) {
resumeIdleTimer();
// Check for pause and sleep
await this.checkSleep(config);
await this.checkPause();
// Random chance for doing nothing (25% chance)
if (Math.random() <= 0.25) {
// removed for staging usage
//console.log("Handling idle event:", "Doing nothing this cycle");
await this.waitInterval(config);
continue;
}
// Main event handling
const idleEvent = this.mainEvents.dequeue();
if (idleEvent) {
console.time(`processing_event ${idleEvent.events}`);
this.eventProcessing = true;
await handleIdleEvent(
config,
idleEvent,
this,
this.chat!,
this.viewer!,
);
!(idleEvent.events === "Subconcious" || idleEvent.events === "Sleep")
? this.mainEvents.enqueue(idleEvent)
: null;
} else {
//removed for staging usage
//console.log("Handling idle event:", "No idle events in queue");
}
} else if (
this.chat!.speakJobs.size() > 0 ||
this.chat!.ttsJobs.size() > 0 ||
this.isChatSpeaking
) {
pauseIdleTimer();
}
await this.waitInterval(config);
}
this.isProcessingEventRunning = false;
}
public async pause() {
await this.chat?.interrupt();
this.isPause = true;
}
public resume() {
this.isPause = false;
}
// Function to check for sleep event if idleTime > time_to_sleep add Sleep event to the front of amica queue
private async checkSleep(config: ChatConfig) {
if (!this.isSleep) {
const chat = this.chat;
if (!chat) {
console.error("Chat instance is not available");
return;
}
const idleTime = chat.idleTime();
// If character being idle morethan 120 sec or 2 min, play handle sleep event
if (!this.containsEvent("Sleep")) {
if (idleTime > parseInt(config.amica_life_params.time_to_sleep_sec)) {
this.insertFront({ events: "Sleep" });
}
}
}
}
// Function to pause the processingEvent loop is pauseFlag is true/false
private async checkPause() {
if (this.isPause) {
console.log("Amica Life Paused");
await new Promise<void>((resolve) => {
const checkPause = setInterval(() => {
if (!this.isPause) {
clearInterval(checkPause);
resolve(console.log("Amica Life Initiated"));
}
}, 50);
});
}
}
// Function to resume the processingEvent loop from pause
private async checkResume(): Promise<boolean> {
if (this.isPause === true && !this.isSleep && this.isSettingOff) {
this.resume();
return true;
}
return false;
}
// Function to pause/resume the loop when setting page is open/close
public checkSettingOff(off: boolean) {
if (off) {
this.isSettingOff = true;
this.wakeFromSleep();
this.chat?.updateAwake(); // Update awake when user exit the setting page
this.resume();
} else {
this.isSettingOff = false;
this.pause();
}
}
// These is amica life utils
// Update time before idle increase by 1.25 times
// public updatedIdleTime() {
// const idleTimeSec = Math.min(
// parseInt(config("time_before_idle_sec")) * 1.25,
// 240,
// );
// // updateConfig("time_before_idle_sec", idleTimeSec.toString());
// // removed for staging
// //console.log(`Updated time before idle to ${idleTimeSec} seconds`);
// }
public async waitInterval(config: ChatConfig) {
const [minMs, maxMs] = [
parseInt(config.amica_life_params.min_time_interval_sec),
parseInt(config.amica_life_params.max_time_interval_sec),
];
const interval =
Math.floor(Math.random() * (maxMs - minMs + 1) + minMs) * 1000;
return new Promise((resolve) => setTimeout(resolve, interval));
}
public wakeFromSleep() {
this.isSleep = false;
this.viewer?.model?.playEmotion("Neutral");
}
public async clean() {
console.log("Stopping all AmicaLife processes...");
// Stop processing loops
this.isProcessingEventRunning = false;
this.isProcessingIdleRunning = false;
// Pause Amica life
this.isPause = true;
// Interrupt any ongoing chat speech or TTS jobs
if (this.chat) {
await this.chat.interrupt(); // assuming interrupt stops speech & jobs
this.chat.speakJobs.clear(); // clear any queued speak jobs if possible
this.chat.ttsJobs.clear(); // clear TTS jobs queue if possible
}
// Clear the main event queue
this.mainEvents.clear();
// Reset trigger and sleep flags
this.triggerMessage = false;
this.isSleep = false;
this.isSettingOff = false;
}
}

View File

@ -0,0 +1,6 @@
import { createContext } from "react";
import { AmicaLife } from "./amicaLife";
const amicaLife = new AmicaLife();
export const AmicaLifeContext = createContext({ amicaLife });

View File

@ -0,0 +1,288 @@
import { animationList } from "@/utils/paths";
import { loadVRMAnimation } from "@/lib/VRMAnimation/loadVRMAnimation";
import { Chat, ChatConfig } from "@/features/chat/chat";
import { emotions } from "@/features/chat/messages";
import { askLLM } from "@/utils/askLlm";
import { functionCalling } from "@/features/functionCalling/functionCalling";
import { AmicaLife } from "./amicaLife";
import { Viewer } from "../vrmViewer/viewer";
function basename(path: string) {
const a = path.split("/");
return a[a.length - 1];
}
export const idleEvents = [
"VRMA",
"Subconcious",
"IdleTextPrompts",
] as const;
export const basedPrompt = {
idleTextPrompt: [
"*I am ignoring you*",
"**sighs** It's so quiet here.",
"Tell me something interesting about yourself.",
"**looks around** What do you usually do for fun?",
"I could use a good distraction right now.",
"What's the most fascinating thing you know?",
"If you could talk about anything, what would it be?",
"Got any clever insights to share?",
"**leans in** Any fun stories to tell?",
],
};
export type AmicaLifeEvents = {
events: string;
};
// Define a constant for max subconcious storage tokens
const MAX_STORAGE_TOKENS = 3000;
// Define the interface for a timestamped prompt
export type TimestampedPrompt = {
prompt: string;
timestamp: string;
}
// Placeholder for storing compressed subconscious prompts
export let storedPrompts: TimestampedPrompt[] = [];
let previousAnimation = "";
// Handles the VRM animation event.
async function handleVRMAnimationEvent(viewer: Viewer, amicaLife: AmicaLife) {
let randomAnimation;
do {
randomAnimation = animationList[Math.floor(Math.random() * animationList.length)];
} while (basename(randomAnimation) === previousAnimation);
// Store the current animation as the previous one for the next call
previousAnimation = basename(randomAnimation);
// removed for staging logs.
//console.log("Handling idle event (animation):", previousAnimation);
try {
if (viewer) {
const animation = await loadVRMAnimation(randomAnimation);
if (!animation) {
throw new Error("Loading animation failed");
}
// @ts-ignore
const duration = await viewer.model!.playAnimation(animation, previousAnimation);
requestAnimationFrame(() => { viewer.resetCameraLerp(); });
// Set timeout for the duration of the animation
setTimeout(() => {
amicaLife.eventProcessing = false;
console.timeEnd("processing_event VRMA");
}, duration * 1000);
}
} catch (error) {
console.error("Error loading animation:", error);
}
}
// Handles text-based idle events.
async function handleTextEvent(chat: Chat, amicaLife: AmicaLife) {
// Randomly select the idle text prompts
const randomIndex = Math.floor(
Math.random() * basedPrompt.idleTextPrompt.length,
);
const randomTextPrompt = basedPrompt.idleTextPrompt[randomIndex];
// removed for staging logs.
//console.log("Handling idle event (text):", randomTextPrompt);
try {
await chat.receiveMessageFromUser?.(randomTextPrompt, true);
amicaLife.eventProcessing = false;
console.timeEnd(`processing_event IdleTextPrompts`);
} catch (error) {
console.error(
"Error occurred while sending a message through chat instance:",
error,
);
}
}
// Handles sleep event.
export async function handleSleepEvent(chat: Chat, amicaLife: AmicaLife) {
console.log("Sleeping...");
amicaLife.pause();
amicaLife.isSleep = true;
try {
const viewer = chat.viewer;
if (viewer) {
// @ts-ignore
await viewer.model!.playEmotion("Sleep");
}
amicaLife.eventProcessing = false;
console.timeEnd("processing_event Sleep");
} catch (error) {
console.error("Error playing emotion sleep:", error);
}
}
// Handles subconcious event.
export async function handleSubconsciousEvent(
config: ChatConfig,
chat: Chat,
amicaLife: AmicaLife,
onChatCompleteResolver?: () => void,
) {
// removed for staging logs.
// console.log("Handling idle event:", "Subconscious");
const convo = chat.messageList;
const convoLog = convo
.map((message) => {
return `${message.role === "user" ? "User" : "Assistant"}: ${
message.content
}`;
})
.join("\n");
try {
// Step 1: Simulate subconscious self mental diary
const subconciousWordSalad = await askLLM(
config,
"Please reflect on the conversation and let your thoughts flow freely, as if writing a personal diary with events that have occurred:",
`${convoLog}`,
null,
);
// Removed for staging logs.
//console.log("Result from step 1: ", subconciousWordSalad);
// Step 2: Describe the emotion you feel about the subconscious diary
const secondStepPrompt = subconciousWordSalad.startsWith("Error:")
? convoLog
: subconciousWordSalad;
const decipherEmotion = await askLLM(
config,
"Read this mini-diary, I would like you to simulate a human-like subconscious with deep emotions and describe it from a third-person perspective:",
secondStepPrompt,
null,
);
// Removed for staging logs.
//console.log("Result from step 2: ", decipherEmotion);
// Step 3: Decide on one of the emotion tags best suited for the described emotion
const thirdStepPrompt = decipherEmotion.startsWith("Error:")
? convoLog
: decipherEmotion;
const emotionDecided = await askLLM(
config,
`Based on your mini-diary, respond with dialougue that sounds like a normal person speaking about their mind, experience or feelings. Make sure to incorporate the specified emotion tags in your response. Here is the list of emotion tags that you have to include in the result : ${emotions
.map((emotion) => `[${emotion}]`)
.join(", ")}:`,
thirdStepPrompt,
chat,
onChatCompleteResolver
);
// Removed for staging logs.
// console.log("Result from step 3: ", emotionDecided);
// Step 4: Compress the subconscious diary entry to 240 characters
const fourthStepPrompt = subconciousWordSalad.startsWith("Error:")
? convoLog
: subconciousWordSalad;
const compressSubconcious = await askLLM(
config,
"Compress this prompt to 240 characters:",
fourthStepPrompt,
null,
);
console.log("Stored Memory: ", compressSubconcious);
// Add timestamp to the compressed subconscious
const timestampedPrompt: TimestampedPrompt = {
prompt: compressSubconcious,
timestamp: new Date().toISOString(),
};
storedPrompts.push(timestampedPrompt);
let totalStorageTokens = storedPrompts.reduce(
(totalTokens, prompt) => totalTokens + prompt.prompt.length,
0,
);
while (totalStorageTokens > MAX_STORAGE_TOKENS) {
const removed = storedPrompts.shift();
totalStorageTokens -= removed!.prompt.length;
}
console.log("Stored subconcious prompts:", storedPrompts);
amicaLife.setSubconciousLogs!(storedPrompts);
amicaLife.eventProcessing = false;
console.timeEnd(`processing_event Subconcious`);
} catch (error) {
console.error("Error handling subconscious event:", error);
}
}
// Handles news event
export async function handleNewsEvent(chat: Chat, amicaLife: AmicaLife) {
console.log("Function Calling: News");
try {
const news = await functionCalling("news");
if (!news) {
throw new Error("Loading news failed");
}
await chat.receiveMessageFromUser?.(news, true);
amicaLife.eventProcessing = false;
console.timeEnd("processing_event News");
} catch (error) {
console.error(
"Error occurred while sending a message through chat instance:",
error,
);
}
}
// Main handler for idle events.
export async function handleIdleEvent(
config: ChatConfig,
event: AmicaLifeEvents,
amicaLife: AmicaLife,
chat: Chat,
viewer: Viewer,
) {
if (!chat) {
console.error("Chat instance is not available");
return;
}
let onChatCompleteResolver: (() => void) | undefined;
const onChatComplete = new Promise<void>((resolve) => {
onChatCompleteResolver = resolve;
});
switch (event.events) {
case "VRMA":
await handleVRMAnimationEvent(viewer, amicaLife);
break;
case "Subconcious":
await handleSubconsciousEvent(config, chat, amicaLife, onChatCompleteResolver!);
await onChatComplete;
break;
case "News":
await handleNewsEvent(chat, amicaLife);
break;
case "Sleep":
await handleSleepEvent(chat, amicaLife);
break;
default:
await handleTextEvent(chat, amicaLife);
break;
}
}

View File

@ -0,0 +1,847 @@
import { Queue } from "@/utils/queue"
import { Message, Role, Screenplay, Talk, textsToScreenplay } from "./messages";
import { Viewer } from "@/features/vrmViewer/viewer";
import { getEchoChatResponseStream } from "./echoChat";
import {
getOpenAiChatResponseStream,
getOpenAiVisionChatResponse,
} from "./openAiChat";
import {
getLlamaCppChatResponseStream,
getLlavaCppChatResponse,
} from "./llamaCppChat";
import { getWindowAiChatResponseStream } from "./windowAiChat";
import {
getOllamaChatResponseStream,
getOllamaVisionChatResponse,
} from "./ollamaChat";
import { getKoboldAiChatResponseStream } from "./koboldAiChat";
import { rvc } from "@/features/rvc/rvc";
import { coquiLocal } from "@/features/coquiLocal/coquiLocal";
import { piper } from "@/features/piper/piper";
import { elevenlabs } from "@/features/elevenlabs/elevenlabs";
import { speecht5 } from "@/features/speecht5/speecht5";
import { openaiTTS } from "@/features/openaiTTS/openaiTTS";
import { localXTTSTTS } from "@/features/localXTTS/localXTTS";
import { AmicaLife } from "@/features/amicaLife/amicaLife";
import { cleanTalk } from "@/utils/cleanTalk";
import { processResponse } from "@/utils/processResponse";
import { wait } from "@/utils/wait";
import {
isCharacterIdle,
characterIdleTime,
resetIdleTimer,
} from "@/utils/isIdle";
import { getOpenRouterChatResponseStream } from "./openRouterChat";
import {
AmicaLifeParams,
ChatbotBackend,
RVC,
STTBackend,
TTSBackend,
VisionBackend,
} from "@/types/backend";
import { loadAudioAsFloat32Array } from "../diagnosed/sttDiagnosis";
import { WaveFile } from "wavefile";
import { openaiWhisper } from "../openaiWhisper/openaiWhisper";
import { Transcriber } from "@/hooks/useTranscriber";
import { whispercpp } from "../whispercpp/whispercpp";
type Speak = {
audioBuffer: ArrayBuffer | null;
screenplay: Screenplay;
streamIdx: number;
};
type TTSJob = {
screenplay: Screenplay;
streamIdx: number;
};
export interface ChatConfig {
name: string;
tts_backend:
| "none"
| "piper"
| "coqui"
| "elevenlabs"
| "speecht5"
| "openai_tts"
| "localXTTS"
| "coquiLocal";
chatbot_backend:
| "openai"
| "llamacpp"
| "ollama"
| "koboldai"
| "windowai"
| "openrouter";
stt_backend: "whisper_browser" | "whisper_openai" | "whispercpp";
vision_backend: "vision_llamacpp" | "vision_ollama" | "vision_openai";
system_prompt: string;
vision_system_prompt: string;
chatbot_params: ChatbotBackend;
tts_params: TTSBackend;
stt_params: STTBackend;
vision_params: VisionBackend;
amica_life_params: AmicaLifeParams;
rvc_params: RVC;
// Add more as needed
}
export class Chat {
public initialized: boolean;
private shouldStopProcessing = false;
public transcriber?: Transcriber;
public amicaLife?: AmicaLife;
public viewer?: Viewer;
public setChatLog?: (messageLog: Message[]) => void;
public setUserMessage?: (message: string) => void;
public setAssistantMessage?: (message: string) => void;
public setShownMessage?: (role: Role) => void;
public setChatProcessing?: (processing: boolean) => void;
public setChatSpeaking?: (speaking: boolean) => void;
public setWhisperCppOutput?: (output: any) => void;
public setWhisperOpenAIOutput?: (output: any) => void;
// the message from the user that is currently being processed
// it can be reset
public stream: ReadableStream<Uint8Array> | null;
public streams: ReadableStream<Uint8Array>[];
public reader: ReadableStreamDefaultReader<Uint8Array> | null;
public readers: ReadableStreamDefaultReader<Uint8Array>[];
// process these immediately as they come in and add to audioToPlay
public ttsJobs: Queue<TTSJob>;
// this should be read as soon as they exist
// and then deleted from the queue
public speakJobs: Queue<Speak>;
private currentAssistantMessage: string;
private currentUserMessage: string;
private lastAwake: number;
public messageList: Message[];
public currentStreamIdx: number;
public config?: ChatConfig;
private onChatCompleteResolver?: () => void;
public onChatComplete?: Promise<void>;
constructor() {
this.initialized = false;
this.stream = null;
this.reader = null;
this.streams = [];
this.readers = [];
this.ttsJobs = new Queue<TTSJob>();
this.speakJobs = new Queue<Speak>();
this.currentAssistantMessage = "";
this.currentUserMessage = "";
this.messageList = [];
this.currentStreamIdx = 0;
this.lastAwake = 0;
}
public initialize(
transcriber: Transcriber,
amicaLife: AmicaLife,
viewer: Viewer,
setUserMessage: (message: string) => void,
setAssistantMessage: (message: string) => void,
setShownMessage: (role: Role) => void,
setChatProcessing: (processing: boolean) => void,
setChatSpeaking: (speaking: boolean) => void,
setWhisperCppOutput: (output: any) => void,
setWhisperOpenAIOutput: (output: any) => void,
config: ChatConfig,
) {
this.transcriber = transcriber;
this.amicaLife = amicaLife;
this.viewer = viewer;
this.setUserMessage = setUserMessage;
this.setAssistantMessage = setAssistantMessage;
this.setShownMessage = setShownMessage;
this.setChatProcessing = setChatProcessing;
this.setChatSpeaking = setChatSpeaking;
this.setWhisperCppOutput = setWhisperCppOutput;
this.setWhisperOpenAIOutput = setWhisperOpenAIOutput;
this.config = config;
console.log("Config ", config)
this.shouldStopProcessing = false;
// these will run forever
this.processTtsJobs();
this.processSpeakJobs();
this.updateAwake();
this.initialized = true;
}
public setMessageList(messages: Message[]) {
this.messageList = messages;
this.currentAssistantMessage = "";
this.currentUserMessage = "";
// this.setChatLog!(this.messageList!);
this.setAssistantMessage!(this.currentAssistantMessage);
this.setUserMessage!(this.currentAssistantMessage);
this.currentStreamIdx++;
}
public async handleRvc(audio: any) {
const rvcParams = this.config?.rvc_params;
const rvcUrl = rvcParams?.rvc_url!;
const rvcModelName = rvcParams?.rvc_model_name!;
const rvcIndexPath = rvcParams?.rvc_index_path!;
const rvcF0upKey = parseInt(rvcParams?.rvc_f0_upkey!)!;
const rvcF0Method = rvcParams?.rvc_f0_method!;
const rvcIndexRate = rvcParams?.rvc_index_rate!;
const rvcFilterRadius = parseInt(rvcParams?.rvc_filter_radius!);
const rvcResampleSr = parseInt(rvcParams?.rvc_resample_sr!);
const rvcRmsMixRate = parseInt(rvcParams?.rvc_rms_mix_rate!);
const rvcProtect = parseInt(rvcParams?.rvc_protect!);
const voice = await rvc(
audio,
rvcUrl,
rvcModelName,
rvcIndexPath,
rvcF0upKey,
rvcF0Method,
rvcIndexRate,
rvcFilterRadius,
rvcResampleSr,
rvcRmsMixRate,
rvcProtect,
);
return voice.audio;
}
public idleTime(): number {
return characterIdleTime(this.config?.amica_life_params.time_to_sleep_sec!,this.lastAwake);
}
public isAwake() {
return !isCharacterIdle(this.config?.amica_life_params.time_to_sleep_sec!,this.lastAwake);
}
public updateAwake() {
this.lastAwake = new Date().getTime();
resetIdleTimer();
}
public async processTtsJobs() {
while (!this.shouldStopProcessing) {
do {
if (this.shouldStopProcessing) return;
const ttsJob = this.ttsJobs.dequeue();
if (!ttsJob) break;
if (ttsJob.streamIdx !== this.currentStreamIdx) {
continue;
}
const audioBuffer = await this.fetchAudio(ttsJob.screenplay.talk);
this.speakJobs.enqueue({
audioBuffer,
screenplay: ttsJob.screenplay,
streamIdx: ttsJob.streamIdx,
});
} while (this.ttsJobs.size() > 0);
await wait(50);
}
}
public async processSpeakJobs() {
while (!this.shouldStopProcessing) {
do {
if (this.shouldStopProcessing) return;
const speak = this.speakJobs.dequeue();
if (!speak) break;
if (speak.streamIdx !== this.currentStreamIdx) continue;
this.bubbleMessage("assistant", speak.screenplay.text);
if (speak.audioBuffer) {
this.setChatSpeaking!(true);
await this.viewer!.model?.speak(speak.audioBuffer, speak.screenplay);
this.setChatSpeaking!(false);
if (this.isAwake()) this.updateAwake();
}
// Resolve full chat complete
if (this.speakJobs.size() === 0 && this.ttsJobs.size() === 0) {
this.onChatCompleteResolver?.();
}
} while (this.speakJobs.size() > 0);
await wait(50);
}
}
public async runFullInteraction(message: string, vision: boolean) {
vision ? await this.getVisionResponse(message) : await this.receiveMessageFromUser(message,false);
await wait(3000);
await this.onChatComplete;
}
public bubbleMessage(role: Role, text: string) {
// TODO: currentUser & Assistant message should be contain the message with emotion in it
if (role === "user") {
// add space if there is already a partial message
if (this.currentUserMessage !== "") {
this.currentUserMessage += " ";
}
this.currentUserMessage += text;
this.setUserMessage!(this.currentUserMessage);
this.setAssistantMessage!("");
if (this.currentAssistantMessage !== "") {
this.messageList!.push({
role: "assistant",
content: this.currentAssistantMessage,
});
this.currentAssistantMessage = "";
}
// this.setChatLog!([
// ...this.messageList!,
// { role: "user", content: this.currentUserMessage },
// ]);
}
if (role === "assistant") {
if (
this.currentAssistantMessage != "" &&
!this.isAwake() &&
this.config?.amica_life_params.amica_life_enabled === "true"
) {
this.messageList!.push({
role: "assistant",
content: this.currentAssistantMessage,
});
this.currentAssistantMessage = text;
this.setAssistantMessage!(this.currentAssistantMessage);
} else {
this.currentAssistantMessage += text;
this.setUserMessage!("");
this.setAssistantMessage!(this.currentAssistantMessage);
}
if (this.currentUserMessage !== "") {
this.messageList!.push({
role: "user",
content: this.currentUserMessage,
});
this.currentUserMessage = "";
}
// this.setChatLog!([
// ...this.messageList!,
// { role: "assistant", content: this.currentAssistantMessage },
// ]);
}
this.setShownMessage!(role);
console.debug("bubbler", this.messageList);
}
public async interrupt() {
this.currentStreamIdx++;
try {
if (this.reader) {
console.debug("cancelling");
if (!this.reader?.closed) {
await this.reader?.cancel();
}
// this.reader = null;
// this.stream = null;
console.debug("finished cancelling");
}
} catch (e: any) {
console.error(e.toString());
}
// TODO if llm type is llama.cpp, we can send /stop message here
this.ttsJobs.clear();
this.speakJobs.clear();
// TODO stop viewer from speaking
}
// this happens either from text or from voice / whisper completion
public async receiveMessageFromUser(message: string, amicaLife: boolean) {
if (message === null || message === "") {
return;
}
this.onChatComplete = new Promise<void>((resolve) => {
this.onChatCompleteResolver = resolve;
});
console.time("performance_interrupting");
console.debug("interrupting...");
await this.interrupt();
console.timeEnd("performance_interrupting");
await wait(0);
console.debug("wait complete");
if (!amicaLife) {
console.log("receiveMessageFromUser", message);
this.amicaLife?.receiveMessageFromUser(message);
if (!/\[.*?\]/.test(message)) {
message = `[neutral] ${message}`;
}
this.updateAwake();
this.bubbleMessage("user", message);
}
// make new stream
const messages: Message[] = [
{ role: "system", content: this.config?.system_prompt! },
...this.messageList!,
{ role: "user", content: amicaLife ? message : this.currentUserMessage },
];
// console.debug('messages', messages);
await this.makeAndHandleStream(messages);
}
public async makeAndHandleStream(messages: Message[]) {
try {
this.streams.push(await this.getChatResponseStream(messages));
} catch (e: any) {
const errMsg = e.toString();
console.error("Failed to get chat response", errMsg);
return errMsg;
}
if (this.streams[this.streams.length - 1] == null) {
const errMsg = "Error: Null stream encountered.";
console.error("Null stream encountered", errMsg);
return errMsg;
}
return await this.handleChatResponseStream();
}
public async handleChatResponseStream() {
if (this.streams.length === 0) {
console.log("no stream!");
return;
}
this.currentStreamIdx++;
const streamIdx = this.currentStreamIdx;
this.setChatProcessing!(true);
console.time("chat stream processing");
let reader = this.streams[this.streams.length - 1].getReader();
this.readers.push(reader);
let sentences = new Array<string>();
let aiTextLog = "";
let tag = "";
let isThinking = false;
let rolePlay = "";
let receivedMessage = "";
let firstTokenEncountered = false;
let firstSentenceEncountered = false;
console.time("performance_time_to_first_token");
console.time("performance_time_to_first_sentence");
try {
while (true) {
if (this.currentStreamIdx !== streamIdx) {
console.log("wrong stream idx");
break;
}
const { done, value } = await reader.read();
if (!firstTokenEncountered) {
console.timeEnd("performance_time_to_first_token");
firstTokenEncountered = true;
}
if (done) break;
receivedMessage += value;
receivedMessage = receivedMessage.trimStart();
const proc = processResponse({
sentences,
aiTextLog,
receivedMessage,
tag,
isThinking,
rolePlay,
callback: (aiTalks: Screenplay[]): boolean => {
// Generate & play audio for each sentence, display responses
console.debug("enqueue tts", aiTalks);
console.debug(
"streamIdx",
streamIdx,
"currentStreamIdx",
this.currentStreamIdx,
);
if (streamIdx !== this.currentStreamIdx) {
console.log("wrong stream idx");
return true; // should break
}
this.ttsJobs.enqueue({
screenplay: aiTalks[0],
streamIdx: streamIdx,
});
if (!firstSentenceEncountered) {
console.timeEnd("performance_time_to_first_sentence");
firstSentenceEncountered = true;
}
return false; // normal processing
},
});
sentences = proc.sentences;
aiTextLog = proc.aiTextLog;
receivedMessage = proc.receivedMessage;
tag = proc.tag;
rolePlay = proc.rolePlay;
if (proc.shouldBreak) {
break;
}
}
} catch (e: any) {
const errMsg = e.toString();
this.bubbleMessage!("assistant", errMsg);
console.error(errMsg);
} finally {
if (!reader.closed) {
reader.releaseLock();
}
console.timeEnd("chat stream processing");
if (streamIdx === this.currentStreamIdx) {
this.setChatProcessing!(false);
}
}
return aiTextLog;
}
// TTS
public async fetchAudio(talk: Talk): Promise<ArrayBuffer | null> {
// TODO we should remove non-speakable characters
// since this depends on the tts backend, we should do it
// in their respective functions
// this is just a simple solution for now
talk = cleanTalk(talk);
if (talk.message.trim() === "") {
return null;
}
const params = this.config?.tts_params;
const rvcParams = this.config?.rvc_params;
const rvcEnabled = rvcParams?.rvc_enabled === "true";
try {
switch (this.config?.tts_backend) {
case "none": {
return null;
}
case "elevenlabs": {
const p = params as TTSBackend["elevenlabs"]
const voiceId = p?.elevenlabs_voiceid!;
const voice = await elevenlabs(
p,
talk.message,
voiceId,
);
if (rvcEnabled) {
return await this.handleRvc(voice.audio);
}
return voice.audio;
}
case "speecht5": {
const p = params as TTSBackend["speecht5"]
const speakerEmbeddingUrl = p?.speecht5_speaker_embedding_url!;
const voice = await speecht5(talk.message, speakerEmbeddingUrl);
if (rvcEnabled) {
return await this.handleRvc(voice.audio);
}
return voice.audio;
}
case "openai_tts": {
const voice = await openaiTTS(params as TTSBackend["openai_tts"], talk.message);
if (rvcEnabled) {
return await this.handleRvc(voice.audio);
}
return voice.audio;
}
case "localXTTS": {
const voice = await localXTTSTTS(params as TTSBackend["localXTTS"], talk.message);
if (rvcEnabled) {
return await this.handleRvc(voice.audio);
}
return voice.audio;
}
case "piper": {
const voice = await piper(params as TTSBackend["piper"], talk.message);
if (rvcEnabled) {
return await this.handleRvc(voice.audio);
}
return voice.audio;
}
case "coquiLocal": {
const voice = await coquiLocal(params as TTSBackend["coquiLocal"], talk.message);
if (rvcEnabled) {
return await this.handleRvc(voice.audio);
}
return voice.audio;
}
}
} catch (e: any) {
console.error("Failed to get TTS response", e.toString());
}
return null;
}
// Chatbot
public async getChatResponseStream(messages: Message[]) {
console.debug("getChatResponseStream", messages);
const chatbotBackend = this.config?.chatbot_backend;
const name = this.config?.name!;
const system_prompt = this.config?.system_prompt!;
const params = this.config?.chatbot_params;
switch (chatbotBackend) {
case "openai":
return getOpenAiChatResponseStream(
params as ChatbotBackend["openai"],
messages,
);
case "llamacpp":
return getLlamaCppChatResponseStream(
params as ChatbotBackend["llamacpp"],
name,
system_prompt,
messages,
);
case "windowai":
return getWindowAiChatResponseStream(name, messages);
case "ollama":
return getOllamaChatResponseStream(
params as ChatbotBackend["ollama"],
messages,
);
case "koboldai":
return getKoboldAiChatResponseStream(
name,
system_prompt,
params as ChatbotBackend["koboldai"],
messages,
);
case "openrouter":
return getOpenRouterChatResponseStream(
params as ChatbotBackend["openrouter"],
messages,
);
}
return getEchoChatResponseStream(messages);
}
// STT
public async getSTTResponse() {
let audio = await loadAudioAsFloat32Array("/sample-voice.wav");
try {
switch (this.config?.stt_backend) {
case "whisper_browser": {
console.debug("whisper_browser attempt");
// since VAD sample rate is same as whisper we do nothing here
// both are 16000
const audioCtx = new AudioContext();
const buffer = audioCtx.createBuffer(1, audio.length, 16000);
buffer.copyToChannel(new Float32Array(audio), 0, 0);
this.transcriber?.start(buffer);
break;
}
case "whisper_openai": {
console.debug("whisper_openai attempt");
const wav = new WaveFile();
wav.fromScratch(1, 16000, "32f", audio);
const file = new File([new Uint8Array(wav.toBuffer())], "input.wav", { type: "audio/wav" });
let prompt;
// TODO load prompt if it exists
(async () => {
try {
const transcript = await openaiWhisper(this.config?.stt_params.whisper_openai,file, prompt);
this.setWhisperOpenAIOutput!(transcript);
} catch (e: any) {
console.error("whisper_openai error", e);
}
})();
break;
}
case "whispercpp": {
console.debug("whispercpp attempt");
const wav = new WaveFile();
wav.fromScratch(1, 16000, "32f", audio);
wav.toBitDepth("16");
const file = new File([new Uint8Array(wav.toBuffer())], "input.wav", { type: "audio/wav" });
let prompt;
// TODO load prompt if it exists
(async () => {
try {
const transcript = await whispercpp(this.config?.stt_params.whispercpp,file, prompt);
this.setWhisperCppOutput!(transcript);
} catch (e: any) {
console.error("whispercpp error", e);
}
})();
break;
}
}
} catch (e: any) {
console.error("stt_backend error", e);
}
}
// Vision
public async getVisionResponse(imageData: string, onlyVisionResponse?: boolean) {
try {
const visionBackend = this.config?.vision_backend;
const name = this.config?.name!;
const vision_system_prompt = this.config?.vision_system_prompt!;
const params = this.config?.vision_params;
console.debug("vision_backend", visionBackend);
this.onChatComplete = new Promise<void>((resolve) => {
this.onChatCompleteResolver = resolve;
});
let res = "";
if (visionBackend === "vision_llamacpp") {
const messages: Message[] = [
{ role: "system", content: vision_system_prompt },
...this.messageList!,
{
role: "user",
content: "Describe the image as accurately as possible",
},
];
res = await getLlavaCppChatResponse(
name,
vision_system_prompt,
params as VisionBackend["vision_llamacpp"],
messages,
imageData,
);
} else if (visionBackend === "vision_ollama") {
const messages: Message[] = [
{ role: "system", content: vision_system_prompt },
...this.messageList!,
{
role: "user",
content: "Describe the image as accurately as possible",
},
];
res = await getOllamaVisionChatResponse(
params as VisionBackend["vision_ollama"],
messages,
imageData,
);
} else if (visionBackend === "vision_openai") {
const messages: Message[] = [
{ role: "user", content: vision_system_prompt },
...(this.messageList! as any[]),
{
role: "user",
// @ts-ignore normally this is a string
content: [
{
type: "text",
text: "Describe the image as accurately as possible",
},
{
type: "image_url",
image_url: {
url: `data:image/jpeg;base64,${imageData}`,
},
},
],
},
];
res = await getOpenAiVisionChatResponse(
params as VisionBackend["vision_openai"],
messages,
);
} else {
console.warn("vision_backend not supported", visionBackend);
return;
}
if (onlyVisionResponse) {
return res;
}
await this.makeAndHandleStream([
{ role: "system", content: this.config?.system_prompt! },
...this.messageList!,
{
role: "user",
content: `This is a picture I just took from my webcam (described between [[ and ]] ): [[${res}]] Please respond accordingly and as if it were just sent and as though you can see it.`,
},
]);
} catch (e: any) {
console.error("Failed to get vision response ", e.toString());
}
}
public clean() {
console.log("Stopping all chat processes...");
this.shouldStopProcessing = true;
// Cancel any readers or streams if needed
this.interrupt();
// You could also optionally clear queues
this.ttsJobs.clear();
this.speakJobs.clear();
this.initialized = false;
}
}

View File

@ -0,0 +1,6 @@
import { createContext } from "react";
import { Chat } from "./chat";
const chat = new Chat();
export const ChatContext = createContext({ chat });

View File

@ -0,0 +1,26 @@
import { Message } from "./messages";
export async function getEchoChatResponseStream(messages: Message[]) {
const stream = new ReadableStream({
async start(controller: ReadableStreamDefaultController) {
try {
let lastMessage = messages[messages.length - 1].content;
const lastChar = lastMessage.length > 0 ? lastMessage[lastMessage.length - 1] : ' ';
if (lastChar !== '.' && lastChar !== '?' && lastChar !== '!') {
lastMessage += ".";
}
lastMessage.split(' ').map((word) => word + ' ').forEach((word) => {
controller.enqueue(word);
});
} catch (error) {
controller.error(error);
} finally {
controller.close();
}
},
});
return stream;
}

View File

@ -0,0 +1,127 @@
import { ChatbotBackend } from "@/types/backend";
import { Message } from "./messages";
import { buildPrompt } from "@/utils/buildPrompt";
interface KoboldAIParams {
name: string,
system_prompt: string,
koboldai_stop_sequence: string,
koboldai_url: string
}
export async function getKoboldAiChatResponseStream(name: string, system_prompt: string, config: ChatbotBackend["koboldai"],messages: Message[]) {
if (config?.koboldai_use_extra === 'true') {
return getExtra({name: name, system_prompt: system_prompt, koboldai_stop_sequence: config.koboldai_stop_sequence, koboldai_url: config.koboldai_url}, messages);
} else {
return getNormal({name: name, system_prompt: system_prompt, koboldai_stop_sequence: config?.koboldai_stop_sequence!, koboldai_url: config?.koboldai_url!},messages);
}
}
// koboldcpp / stream support
async function getExtra(config: KoboldAIParams, messages: Message[]) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
const prompt = buildPrompt({name: config.name!, system_prompt: config.system_prompt!},messages);
const stop_sequence: string[] = [`${config.name}:`, ...`${config.koboldai_stop_sequence}`.split("||")];
const res = await fetch(`${config.koboldai_url}/api/extra/generate/stream`, {
headers: headers,
method: "POST",
body: JSON.stringify({
prompt,
stop_sequence
}),
});
const reader = res.body?.getReader();
if (res.status !== 200 || ! reader) {
throw new Error(`KoboldAi chat error (${res.status})`);
}
const stream = new ReadableStream({
async start(controller: ReadableStreamDefaultController) {
const decoder = new TextDecoder("utf-8");
try {
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value);
let eolIndex;
while ((eolIndex = buffer.indexOf('\n')) >= 0) {
const line = buffer.substring(0, eolIndex).trim();
buffer = buffer.substring(eolIndex + 1);
if (line.startsWith('data:')) {
try {
const json = JSON.parse(line.substring(5));
const messagePiece = json.token;
if (messagePiece) {
controller.enqueue(messagePiece);
}
} catch (error) {
console.error("JSON parsing error:", error, "in line:", line);
}
}
}
}
} catch (error) {
console.error("Stream error:", error);
controller.error(error);
} finally {
reader.releaseLock();
controller.close();
}
},
async cancel() {
await reader?.cancel();
reader.releaseLock();
}
});
return stream;
}
// koboldai / no stream support
async function getNormal(config: KoboldAIParams,messages: Message[]) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
const prompt = buildPrompt({name: config.name!, system_prompt: config.system_prompt!},messages);
const stop_sequence: string[] = [`${config.name}:`, ...`${config.koboldai_stop_sequence}`.split("||")];
const res = await fetch(`${config.koboldai_url}/api/v1/generate`, {
headers: headers,
method: "POST",
body: JSON.stringify({
prompt,
stop_sequence
}),
});
const json = await res.json();
if (json.results.length === 0) {
throw new Error(`KoboldAi result length 0`);
}
const text = json.results.map((row: {text: string}) => row.text).join('');
const stream = new ReadableStream({
async start(controller: ReadableStreamDefaultController) {
try {
text.split(' ').map((word: string) => word + ' ').forEach((word: string) => {
controller.enqueue(word);
});
} catch (error) {
controller.error(error);
} finally {
controller.close();
}
},
});
return stream;
}

View File

@ -0,0 +1,187 @@
import { ChatbotBackend, VisionBackend } from "@/types/backend";
import { Message } from "./messages";
import { buildPrompt, buildVisionPrompt } from "@/utils/buildPrompt";
export async function getLlamaCppChatResponseStream(config: ChatbotBackend["llamacpp"], name: string, system_prompt: string, messages: Message[]) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"Connection": "keep-alive",
"Accept": "text/event-stream",
};
const prompt = buildPrompt({ name: name, system_prompt: system_prompt },messages);
const stop: string[] = [`${name}:`, ...`${config?.llamacpp_stop_sequence}`.split("||")];
const res = await fetch(`${config?.llamacpp_url}/completion`, {
headers: headers,
method: "POST",
body: JSON.stringify({
stream: true,
n_predict: 400,
temperature: 0.7,
cache_prompt: true,
stop,
prompt,
}),
});
const reader = res.body?.getReader();
if (res.status !== 200 || ! reader) {
throw new Error(`LlamaCpp chat error (${res.status})`);
}
const stream = new ReadableStream({
async start(controller: ReadableStreamDefaultController) {
const decoder = new TextDecoder("utf-8");
try {
// sometimes the response is chunked, so we need to combine the chunks
let combined = "";
let cont = true;
while (true) {
const { done, value } = await reader.read();
if (done || ! cont) break;
const data = decoder.decode(value);
const chunks = data
.split("data:")
.filter((val) => !!val && val.trim() !== "[DONE]");
for (const chunk of chunks) {
// skip comments
if (chunk.length > 0 && chunk[0] === ":") {
continue;
}
combined += chunk;
try {
const json = JSON.parse(combined);
if (json.stop) {
cont = false;
}
const messagePiece = json.content;
combined = "";
if (!!messagePiece) {
controller.enqueue(messagePiece);
}
} catch (error) {
console.error(error);
}
}
}
} catch (error) {
console.error(error);
controller.error(error);
} finally {
reader.releaseLock();
controller.close();
}
},
async cancel() {
await reader?.cancel();
reader.releaseLock();
}
});
return stream;
}
export async function getLlavaCppChatResponse(name: string, vision_system_prompt: string, config: VisionBackend["vision_llamacpp"],messages: Message[], imageData: string) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"Connection": "keep-alive",
"Accept": "text/event-stream",
};
const prompt = buildVisionPrompt({name: name, vision_system_prompt: vision_system_prompt},messages);
const res = await fetch(`${config?.vision_llamacpp_url}/completion`, {
headers: headers,
method: "POST",
body: JSON.stringify({
stream: true,
n_predict: 400,
temperature: 0.7,
cache_prompt: true,
stop: [
"</s>",
`${name}:`,
"User:"
],
image_data: [{
data: imageData,
id: 10,
}],
prompt,
}),
});
if (! res.ok) {
throw new Error(`LlamaCpp llava chat error (${res.status})`);
}
console.log('body', res.body);
const reader = res.body?.getReader();
if (res.status !== 200 || ! reader) {
throw new Error(`LlamaCpp vision error (${res.status})`);
}
// Fetch the original image
const stream = new ReadableStream({
async start(controller: ReadableStreamDefaultController) {
const decoder = new TextDecoder("utf-8");
try {
// sometimes the response is chunked, so we need to combine the chunks
let combined = "";
let cont = true;
while (true) {
const { done, value } = await reader.read();
if (done || ! cont) break;
const data = decoder.decode(value);
const chunks = data
.split("data:")
.filter((val) => !!val && val.trim() !== "[DONE]");
for (const chunk of chunks) {
// skip comments
if (chunk.length > 0 && chunk[0] === ":") {
continue;
}
combined += chunk;
try {
const json = JSON.parse(combined);
if (json.stop) {
cont = false;
}
const messagePiece = json.content;
combined = "";
if (!!messagePiece) {
controller.enqueue(messagePiece);
}
} catch (error) {
console.error(error);
}
}
}
} catch (error) {
console.error(error);
controller.error(error);
} finally {
reader.releaseLock();
controller.close();
}
},
async cancel() {
await reader?.cancel();
reader.releaseLock();
}
});
const sreader = await stream.getReader();
let combined = "";
while (true) {
const { done, value } = await sreader.read();
if (done) break;
combined += value;
}
return combined;
}

View File

@ -0,0 +1,102 @@
export type Role = "assistant" | "system" | "user";
// ChatGPT API
export type Message = {
role: Role;
content: string;
};
const talkStyles = [
"talk",
"happy",
"sad",
"angry",
"fear",
"surprised",
] as const;
export type TalkStyle = (typeof talkStyles)[number];
export type Talk = {
style: TalkStyle;
message: string;
};
//Name of all the expression in the vrm
export const emotionNames: string[] = [];
console.log("All emotion names, ",emotionNames);
export const emotions =
["neutral", "happy", "angry", "sad", "relaxed", "Surprised",
"Shy", "Jealous", "Bored", "Serious", "Suspicious", "Victory",
"Sleep", "Love"] as const;
// Convert user input to system format e.g. ["suspicious"] -> ["Sus"], ["sleep"] -> ["Sleep"]
const userInputToSystem = (input: string) => {
const mapping: { [key: string]: string } = {
...Object.fromEntries(emotions
.filter(e => e[0] === e[0].toUpperCase())
.map(e => [e.toLowerCase(), e]))
};
return mapping[input.toLowerCase()] || input;
};
type EmotionType = (typeof emotions)[number];
/**
* A set that includes utterances, voice emotions, and model emotional expressions.
*/
export type Screenplay = {
expression: EmotionType;
talk: Talk;
text: string;
};
export const textsToScreenplay = (
texts: string[],
): Screenplay[] => {
const screenplays: Screenplay[] = [];
let prevExpression = "neutral";
for (let i = 0; i < texts.length; i++) {
const text = texts[i];
const match = text.match(/\[(.*?)\]/);
const tag = (match && match[1]) || prevExpression;
const message = text.replace(/\[(.*?)\]/g, "");
let expression = prevExpression;
const systemTag = userInputToSystem(tag);
if (emotions.includes(systemTag as any)) {
console.log("Emotion detect :",systemTag);
expression = systemTag;
prevExpression = systemTag;
}
screenplays.push({
expression: expression as EmotionType,
talk: {
style: emotionToTalkStyle(expression as EmotionType),
message: message,
},
text: text,
});
}
return screenplays;
};
const emotionToTalkStyle = (emotion: EmotionType): TalkStyle => {
switch (emotion) {
case "angry":
return "angry";
case "happy":
return "happy";
case "sad":
return "sad";
default:
return "talk";
}
};

View File

@ -0,0 +1,86 @@
import { ChatbotBackend, VisionBackend } from "@/types/backend";
import { Message } from "./messages";
export async function getOllamaChatResponseStream(config: ChatbotBackend["ollama"],messages: Message[]) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
const res = await fetch(`${config?.ollama_url}/api/chat`, {
headers: headers,
method: "POST",
body: JSON.stringify({
model: config?.ollama_model,
messages,
}),
});
const reader = res.body?.getReader();
if (res.status !== 200 || ! reader) {
throw new Error(`Ollama chat error (${res.status})`);
}
const stream = new ReadableStream({
async start(controller: ReadableStreamDefaultController) {
const decoder = new TextDecoder("utf-8");
try {
// Ollama sends chunks of multiple complete JSON objects separated by newlines
while (true) {
const { done, value } = await reader.read();
if (done) break;
const data = decoder.decode(value);
const jsonResponses = data
.trim() // Ollama sends an empty line after the final JSON message...
.split("\n")
//.filter((val) => !!val)
for (const jsonResponse of jsonResponses) {
try {
const json = JSON.parse(jsonResponse);
const messagePiece = json.message.content;
if (!!messagePiece) {
controller.enqueue(messagePiece);
}
} catch (error) {
console.error(error);
}
}
}
} catch (error) {
console.error(error);
controller.error(error);
} finally {
reader.releaseLock();
controller.close();
}
},
async cancel() {
await reader?.cancel();
reader.releaseLock();
}
});
return stream;
}
export async function getOllamaVisionChatResponse(config: VisionBackend["vision_ollama"],messages: Message[], imageData: string) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
const res = await fetch(`${config?.vision_ollama_url}/api/chat`, {
headers: headers,
method: "POST",
body: JSON.stringify({
model: config?.vision_ollama_model,
messages,
images: [imageData],
stream: false,
}),
});
if (res.status !== 200) {
throw new Error(`Ollama chat error (${res.status})`);
}
const json = await res.json();
return json.response;
}

View File

@ -0,0 +1,113 @@
import { ChatbotBackend, VisionBackend } from "@/types/backend";
import { Message } from "./messages";
async function getResponseStream(
messages: Message[],
url: string,
model: string,
apiKey: string,
) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
"HTTP-Referer": "https://amica.arbius.ai",
"X-Title": "Amica",
};
const res = await fetch(`${url}/v1/chat/completions`, {
headers: headers,
method: "POST",
body: JSON.stringify({
model,
messages,
stream: true,
max_tokens: 200,
}),
});
const reader = res.body?.getReader();
if (res.status !== 200 || ! reader) {
if (res.status === 401) {
throw new Error('Invalid OpenAI authentication');
}
if (res.status === 402) {
throw new Error('Payment required');
}
throw new Error(`OpenAI chat error (${res.status})`);
}
const stream = new ReadableStream({
async start(controller: ReadableStreamDefaultController) {
const decoder = new TextDecoder("utf-8");
try {
// sometimes the response is chunked, so we need to combine the chunks
let combined = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
const data = decoder.decode(value);
const chunks = data
.split("data:")
.filter((val) => !!val && val.trim() !== "[DONE]");
for (const chunk of chunks) {
// skip comments
if (chunk.length > 0 && chunk[0] === ":") {
continue;
}
combined += chunk;
try {
const json = JSON.parse(combined);
const messagePiece = json.choices[0].delta.content;
combined = "";
if (!!messagePiece) {
controller.enqueue(messagePiece);
}
} catch (error) {
console.error(error);
}
}
}
} catch (error) {
console.error(error);
controller.error(error);
} finally {
reader.releaseLock();
controller.close();
}
},
async cancel() {
await reader?.cancel();
reader.releaseLock();
}
});
return stream;
}
export async function getOpenAiChatResponseStream(config: ChatbotBackend["openai"],messages: Message[]) {
const apiKey = config?.openai_apikey!;
const url = config?.openai_url!;
const model = config?.openai_model!;
return getResponseStream(messages, url, model, apiKey);
}
export async function getOpenAiVisionChatResponse(config: VisionBackend["vision_openai"],messages: Message[],) {
const apiKey = config?.vision_openai_apikey!;
const url = config?.vision_openai_url!;
const model = config?.vision_openai_model!;
const stream = await getResponseStream(messages, url, model, apiKey);
const sreader = await stream.getReader();
let combined = "";
while (true) {
const { done, value } = await sreader.read();
if (done) break;
combined += value;
}
return combined;
}

View File

@ -0,0 +1,93 @@
import { ChatbotBackend } from "@/types/backend";
import { Message } from "./messages";
/**
* Gets a streaming chat response from OpenRouter API.
* OpenRouter provides an OpenAI-compatible API with access to multiple models.
*/
export async function getOpenRouterChatResponseStream(
config: ChatbotBackend["openrouter"],
messages: Message[],
): Promise<ReadableStream> {
const apiKey = config?.openrouter_apikey;
if (!apiKey) {
throw new Error("OpenRouter API key is required");
}
const baseUrl = config.openrouter_url ?? "https://openrouter.ai/api/v1";
const model = config.openrouter_model ?? "openai/gpt-3.5-turbo";
const appUrl = "https://amica.arbius.ai";
const response = await fetch(`${baseUrl}/chat/completions`, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"HTTP-Referer": appUrl,
"X-Title": "Amica Chat",
},
body: JSON.stringify({
model,
messages: messages.map(({ role, content }) => ({ role, content })),
stream: true,
}),
});
const reader = response.body?.getReader();
if (!response.ok || !reader) {
const error = await response.json();
// Handle OpenRouter-specific error format
if (error.error?.message) {
throw new Error(`OpenRouter error: ${error.error.message}`);
}
throw new Error(`OpenRouter request failed with status ${response.status}`);
}
const stream = new ReadableStream({
async start(controller: ReadableStreamDefaultController) {
const decoder = new TextDecoder("utf-8");
try {
// sometimes the response is chunked, so we need to combine the chunks
let combined = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
const data = decoder.decode(value);
const chunks = data
.split("data:")
.filter((val) => !!val && val.trim() !== "[DONE]");
for (const chunk of chunks) {
// skip comments
if (chunk.length > 0 && chunk[0] === ":") {
continue;
}
combined += chunk;
try {
const json = JSON.parse(combined);
const messagePiece = json.choices[0].delta.content;
combined = "";
if (!!messagePiece) {
controller.enqueue(messagePiece);
}
} catch (error) {
console.error(error);
}
}
}
} catch (error) {
console.error(error);
controller.error(error);
} finally {
reader?.releaseLock();
controller.close();
}
},
async cancel() {
await reader?.cancel();
reader?.releaseLock();
},
});
return stream;
}

View File

@ -0,0 +1,45 @@
import { Message } from "./messages";
import { Output } from "window.ai";
export async function getWindowAiChatResponseStream(name: string,messages: Message[]) {
const stream = new ReadableStream({
async start(controller: ReadableStreamDefaultController) {
try {
const [response]: Output[] = await window.ai.generateText({
messages,
}, {
maxTokens: 400,
temperature: 0.7,
stopSequences: [
"</s>",
`${name}:`,
"User:"
],
onStreamResult: (res: Output | null, error: string | null): void => {
if (res === null) {
throw new Error("null result from window.ai");
}
if (error) {
throw new Error(error);
}
// @ts-ignore
const piece = res.message?.content;
if (!! piece) {
controller.enqueue(piece);
}
return;
},
});
} catch (error) {
controller.error(error);
} finally {
controller.close();
}
},
});
return stream;
}

View File

@ -0,0 +1,30 @@
import { TTSBackend } from "@/types/backend";
export async function coquiLocal(
config: TTSBackend["coquiLocal"],
message: string,
) {
const voiceId = config?.coquiLocal_voiceid;
if (!voiceId) {
throw new Error("Invalid CoquiLocal TTS Voice Id");
}
try {
const res = await fetch(`${config.coquiLocal_url}/api/tts`, {
method: 'POST',
headers: {
'text': message,
'speaker-id': config.coquiLocal_voiceid,
}
});
const data = await res.arrayBuffer()
return { audio: data };
} catch (error) {
console.error('Error in coquiLocal:', error);
throw error;
}
}

View File

@ -0,0 +1,41 @@
import { AmicaLife } from "@/types/backend";
import { EvaluationResult } from "./diagnosisScript";
const backendHandlers: Record<
string,
(params: AmicaLife) => Promise<EvaluationResult>
> = {
amicaLife: async (params) => {
const { amica_life_enabled, min_time_interval_sec, max_time_interval_sec, time_to_sleep_sec, idle_text_prompt } = params.amicaLife || {};
if (!amica_life_enabled || !min_time_interval_sec || !max_time_interval_sec || !time_to_sleep_sec || !idle_text_prompt ) return {status: "fail", score: 0};
try {
const parsed = JSON.parse(idle_text_prompt);
if (
!(amica_life_enabled === "true" || amica_life_enabled === "false") ||
isNaN(Number(min_time_interval_sec)) ||
isNaN(Number(max_time_interval_sec)) ||
isNaN(Number(time_to_sleep_sec)) ||
typeof parsed !== "object" ||
!parsed.idleTextPrompt
) {
return {status: "fail", score: 0};
}
} catch {
return {status: "fail", score: 0};
}
return {status: "pass", score: 100};
},
};
// Dispatcher function
export async function amicaLifeDiagnosis(
backend: string,
params: AmicaLife
): Promise<EvaluationResult> {
const handler = backendHandlers[backend];
if (!handler) return {status: "fail", score: 0};
return await handler(params);
}

View File

@ -0,0 +1,30 @@
export const backendKeyMap: Record<string, string[]> = {
openai: ["openai_url", "openai_apikey", "openai_model"],
llamacpp: ["llamacpp_url", "llamacpp_stop_sequence"],
windowai: [],
ollama: ["ollama_url", "ollama_model"],
koboldai: ["koboldai_url", "koboldai_use_extra", "koboldai_stop_sequence"],
openrouter: ["openrouter_apikey", "openrouter_url", "openrouter_model"],
elvenlabs: ["elevenlabs_apikey", "elevenlabs_voiceid", "elvenlabs_model"],
speecht5: ["speecht5_speaker_embedding_url"],
openai_tts: ["openai_tts_apikey", "openai_tts_url", "openai_tts_model", "openai_tts_voice"],
localXTTS: [
"localXTTS_url", "alltalk_version", "alltalk_voice",
"alltalk_language", "alltalk_rvc_voice", "alltalk_rvc_pitch"
],
piper: ["piper_url"],
coquiLocal: ["coquiLocal_url", "coquiLocal_voiceid"],
whisper_browser: [],
whisper_openai: ["openai_whisper_url", "openai_whisper_apikey", "openai_whisper_model"],
whispercpp: ["whispercpp_url"],
vision_llamacpp: ["vision_llamacpp_url"],
vision_openai: ["vision_openai_apikey", "vision_openai_url", "vision_openai_model"],
vision_ollama: ["vision_ollama_url", "vision_ollama_model"],
amicaLife : ["amica_life_enabled", "min_time_interval_sec", "max_time_interval_sec", "time_to_sleep_sec", "idle_text_prompt"],
rvc: ["rvc_enabled","rvc_url","rvc_model_name","rvc_f0_upkey","rvc_f0_method","rvc_index_path","rvc_index_rate","rvc_filter_radius","rvc_resample_sr","rvc_rms_mix_rate","rvc_protect",]
};

View File

@ -0,0 +1,188 @@
import { ChatbotBackend } from "@/types/backend";
import { EvaluationResult } from "./diagnosisScript";
import { getOpenAiChatResponseStream } from "../chat/openAiChat";
const additionalUrls = {
openai: "/v1/chat/completions",
ollama: "/api/chat",
llamacpp: "/completions",
koboldai: "/api/v1/generate",
kobolda_extra: "/api/extra/generate/stream",
openrouter: "/chat/completions",
};
const prompt = [{ role: "user", content: "Hello" }];
const promptBuild = "User: Hello\n";
const TIME_OUT = 20000; // time out 10 secs
const MIN_DURATION = 5000; // latest time to add the score
// Utility to safely call fetch with a timeout
async function safeFetch(
fullUrl: string,
options: RequestInit,
timeoutMs = TIME_OUT,
): Promise<EvaluationResult> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
const start = performance.now();
try {
const res = await fetch(fullUrl, {
...options,
signal: controller.signal,
});
clearTimeout(timeoutId);
const duration = performance.now() - start;
const status = res.status >= 200 && res.status < 300 ? "pass" : "fail";
const score = calculateScore({ status, duration });
return {
status,
score,
};
} catch (err: any) {
clearTimeout(timeoutId);
const duration = performance.now() - start;
const isTimeout = err.name === "AbortError";
const status = "fail";
return {
status,
score: calculateScore({ status, duration, timeout: isTimeout }),
};
}
}
// Score calculation logic
function calculateScore({
status,
duration,
timeout = false,
}: {
status: "pass" | "fail";
duration: number;
timeout?: boolean;
}): number {
if (timeout) return 0;
let score = 0;
if (status === "pass") score += 50;
if (duration < MIN_DURATION)
score += 50 * ((MIN_DURATION - duration) / MIN_DURATION);
return Math.round(score);
}
// Individual backend handlers
const backendHandlers: Record<
string,
(params: ChatbotBackend) => Promise<EvaluationResult>
> = {
openai: async (params) => {
const { openai_apikey, openai_model, openai_url } = params.openai || {};
if (!openai_apikey || !openai_url || !openai_model)
return { status: "fail", score: 0 };
return await safeFetch(`${openai_url}${additionalUrls.openai}`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openai_apikey}`,
"HTTP-Referer": "https://amica.arbius.ai",
"X-Title": "Amica",
},
method: "POST",
body: JSON.stringify({
model: openai_model,
messages: prompt,
stream: false,
max_tokens: 200,
}),
});
},
llamacpp: async (params) => {
const { llamacpp_url } = params.llamacpp || {};
if (!llamacpp_url) return { status: "fail", score: 0 };
return await safeFetch(`${llamacpp_url}${additionalUrls.llamacpp}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Connection: "keep-alive",
Accept: "text/event-stream",
},
body: JSON.stringify({
stream: true,
n_predict: 400,
temperature: 0.7,
cache_prompt: true,
prompt: promptBuild,
}),
});
},
ollama: async (params) => {
const { ollama_url, ollama_model } = params.ollama || {};
if (!ollama_url) return { status: "fail", score: 0 };
return await safeFetch(`${ollama_url}${additionalUrls.ollama}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: ollama_model, messages: prompt }),
});
},
koboldai: async (params) => {
const { koboldai_url, koboldai_use_extra } = params.koboldai || {};
if (!koboldai_url) return { status: "fail", score: 0 };
const path =
koboldai_use_extra === "true"
? additionalUrls.kobolda_extra
: additionalUrls.koboldai;
return await safeFetch(`${koboldai_url}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
});
},
openrouter: async (params) => {
const { openrouter_apikey, openrouter_model, openrouter_url } =
params.openrouter || {};
if (!openrouter_apikey || !openrouter_model || !openrouter_url)
return { status: "fail", score: 0 };
return await safeFetch(`${openrouter_url}${additionalUrls.openrouter}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openrouter_apikey}`,
"HTTP-Referer": "https://amica.arbius.ai",
"X-Title": "Amica Chat",
},
body: JSON.stringify({
model: openrouter_model,
messages: prompt,
stream: true,
}),
});
},
windowai: async () => {
return { status: "pass", score: 100 };
},
};
// Dispatcher function
export async function chatbotDiagnosis(
backend: string,
params: ChatbotBackend,
): Promise<EvaluationResult> {
const handler = backendHandlers[backend];
if (!handler) return { status: "fail", score: 0 };
return await handler(params);
}

Some files were not shown because too many files have changed in this diff Show More