GraphRAG Studio — initial commit: multimodal RAG system with KG visualization

Full-stack application for document-to-knowledge-graph pipeline:
- Backend: FastAPI + LangGraph ReAct agent + DeepSeek + MinerU parsing
- Frontend: React 19 + Vite + D3.js + shadcn/ui
- Pipeline: MinerU parsing → LangExtract entity extraction → KG building

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
plf
2026-06-07 17:30:04 +08:00
commit b02d3378fc
127 changed files with 37218 additions and 0 deletions

2
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
**/.git_embedded_backup/

3
frontend/ATTRIBUTIONS.md Normal file
View File

@@ -0,0 +1,3 @@
This Figma Make file includes components from [shadcn/ui](https://ui.shadcn.com/) used under [MIT license](https://github.com/shadcn-ui/ui/blob/main/LICENSE.md).
This Figma Make file includes photos from [Unsplash](https://unsplash.com) used under [license](https://unsplash.com/license).

33
frontend/CLAUDE.md Normal file
View File

@@ -0,0 +1,33 @@
# Frontend — 开发说明
## 路径
```
F:\GraphRAGAgent\frontend\
```
## 启动开发服务器
```bash
cd F:/GraphRAGAgent/frontend
pnpm dev
```
启动后访问http://localhost:5173
## 依赖安装
```bash
cd F:/GraphRAGAgent/frontend
pnpm install
pnpm rebuild @tailwindcss/oxide esbuild
```
> 注意:首次安装后需执行 `pnpm rebuild @tailwindcss/oxide esbuild`,否则 Vite 构建会因原生包未编译而失败。
## 构建生产包
```bash
cd F:/GraphRAGAgent/frontend
pnpm build
```

11
frontend/README.md Normal file
View File

@@ -0,0 +1,11 @@
# 构建产品原型
This is a code bundle for 构建产品原型. The original project is available at https://www.figma.com/design/Tt95Sj8nC3HvirV1Vw4cA7/%E6%9E%84%E5%BB%BA%E4%BA%A7%E5%93%81%E5%8E%9F%E5%9E%8B.
## Running the code
Run `npm i` to install the dependencies.
Run `npm run dev` to start the development server.

View File

@@ -0,0 +1,61 @@
**Add your own guidelines here**
<!--
System Guidelines
Use this file to provide the AI with rules and guidelines you want it to follow.
This template outlines a few examples of things you can add. You can add your own sections and format it to suit your needs
TIP: More context isn't always better. It can confuse the LLM. Try and add the most important rules you need
# General guidelines
Any general rules you want the AI to follow.
For example:
* Only use absolute positioning when necessary. Opt for responsive and well structured layouts that use flexbox and grid by default
* Refactor code as you go to keep code clean
* Keep file sizes small and put helper functions and components in their own files.
--------------
# Design system guidelines
Rules for how the AI should make generations look like your company's design system
Additionally, if you select a design system to use in the prompt box, you can reference
your design system's components, tokens, variables and components.
For example:
* Use a base font-size of 14px
* Date formats should always be in the format “Jun 10”
* The bottom toolbar should only ever have a maximum of 4 items
* Never use the floating action button with the bottom toolbar
* Chips should always come in sets of 3 or more
* Don't use a dropdown if there are 2 or fewer options
You can also create sub sections and add more specific details
For example:
## Button
The Button component is a fundamental interactive element in our design system, designed to trigger actions or navigate
users through the application. It provides visual feedback and clear affordances to enhance user experience.
### Usage
Buttons should be used for important actions that users need to take, such as form submissions, confirming choices,
or initiating processes. They communicate interactivity and should have clear, action-oriented labels.
### Variants
* Primary Button
* Purpose : Used for the main action in a section or page
* Visual Style : Bold, filled with the primary brand color
* Usage : One primary button per section to guide users toward the most important action
* Secondary Button
* Purpose : Used for alternative or supporting actions
* Visual Style : Outlined with the primary color, transparent background
* Usage : Can appear alongside a primary button for less important actions
* Tertiary Button
* Purpose : Used for the least important actions
* Visual Style : Text-only with no border, using primary color
* Usage : For actions that should be available but not emphasized
-->

15
frontend/index.html Normal file
View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>构建产品原型</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

6034
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

95
frontend/package.json Normal file
View File

@@ -0,0 +1,95 @@
{
"name": "@figma/my-make-file",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"dependencies": {
"@emotion/react": "11.14.0",
"@emotion/styled": "11.14.1",
"@mui/icons-material": "7.3.5",
"@mui/material": "7.3.5",
"@popperjs/core": "2.11.8",
"@radix-ui/react-accordion": "1.2.3",
"@radix-ui/react-alert-dialog": "1.1.6",
"@radix-ui/react-aspect-ratio": "1.1.2",
"@radix-ui/react-avatar": "1.1.3",
"@radix-ui/react-checkbox": "1.1.4",
"@radix-ui/react-collapsible": "1.1.3",
"@radix-ui/react-context-menu": "2.2.6",
"@radix-ui/react-dialog": "1.1.6",
"@radix-ui/react-dropdown-menu": "2.1.6",
"@radix-ui/react-hover-card": "1.1.6",
"@radix-ui/react-label": "2.1.2",
"@radix-ui/react-menubar": "1.1.6",
"@radix-ui/react-navigation-menu": "1.2.5",
"@radix-ui/react-popover": "1.1.6",
"@radix-ui/react-progress": "1.1.2",
"@radix-ui/react-radio-group": "1.2.3",
"@radix-ui/react-scroll-area": "1.2.3",
"@radix-ui/react-select": "2.1.6",
"@radix-ui/react-separator": "1.1.2",
"@radix-ui/react-slider": "1.2.3",
"@radix-ui/react-slot": "1.1.2",
"@radix-ui/react-switch": "1.1.3",
"@radix-ui/react-tabs": "1.1.3",
"@radix-ui/react-toggle": "1.1.2",
"@radix-ui/react-toggle-group": "1.1.2",
"@radix-ui/react-tooltip": "1.1.8",
"@types/d3": "^7.4.3",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
"cmdk": "1.1.1",
"d3": "^7.9.0",
"date-fns": "3.6.0",
"embla-carousel-react": "8.6.0",
"input-otp": "1.4.2",
"lucide-react": "0.487.0",
"marked": "^17.0.4",
"motion": "12.23.24",
"next-themes": "0.4.6",
"optional": "^0.1.4",
"react": "^19.2.5",
"react-day-picker": "8.10.1",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
"react-dom": "^19.2.5",
"react-hook-form": "7.55.0",
"react-popper": "2.3.0",
"react-resizable-panels": "2.1.7",
"react-responsive-masonry": "2.7.1",
"react-router": "7.13.0",
"react-slick": "0.31.0",
"recharts": "2.15.2",
"sonner": "2.0.3",
"tailwind-merge": "3.2.0",
"tw-animate-css": "1.3.8",
"vaul": "1.1.2"
},
"devDependencies": {
"@tailwindcss/vite": "4.1.12",
"@vitejs/plugin-react": "4.7.0",
"tailwindcss": "4.1.12",
"vite": "6.3.5"
},
"peerDependencies": {
"react": "18.3.1",
"react-dom": "18.3.1"
},
"peerDependenciesMeta": {
"react": {
"optional": true
},
"react-dom": {
"optional": true
}
},
"pnpm": {
"overrides": {
"vite": "6.3.5"
}
}
}

4676
frontend/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,15 @@
/**
* PostCSS Configuration
*
* Tailwind CSS v4 (via @tailwindcss/vite) automatically sets up all required
* PostCSS plugins — you do NOT need to include `tailwindcss` or `autoprefixer` here.
*
* This file only exists for adding additional PostCSS plugins, if needed.
* For example:
*
* import postcssNested from 'postcss-nested'
* export default { plugins: [postcssNested()] }
*
* Otherwise, you can leave this file empty.
*/
export default {}

7
frontend/src/app/App.tsx Normal file
View File

@@ -0,0 +1,7 @@
import { RouterProvider } from 'react-router';
import { router } from './routes';
import '../styles/app.css';
export default function App() {
return <RouterProvider router={router} />;
}

279
frontend/src/app/api.ts Normal file
View File

@@ -0,0 +1,279 @@
/**
* GraphRAG Studio — Backend API Client
* Base: http://localhost:8000/api/v1
* All functions return the `data` field; throw ApiError on code !== 0
*/
const BASE = 'http://localhost:8000/api/v1';
export class ApiError extends Error {
code: number;
constructor(code: number, msg: string) {
super(msg);
this.code = code;
}
}
async function request<T>(
method: string,
path: string,
options: {
body?: unknown;
formData?: FormData;
params?: Record<string, string | number | boolean | undefined | null>;
} = {}
): Promise<T> {
let url = BASE + path;
if (options.params) {
const parts = Object.entries(options.params)
.filter(([, v]) => v !== undefined && v !== null && v !== '')
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
if (parts.length) url += '?' + parts.join('&');
}
const init: RequestInit = { method };
if (options.formData) {
init.body = options.formData;
} else if (options.body !== undefined) {
init.headers = { 'Content-Type': 'application/json' };
init.body = JSON.stringify(options.body);
}
const res = await fetch(url, init);
const json = await res.json();
if (json.code !== 0) throw new ApiError(json.code, json.msg ?? 'Unknown error');
return json.data as T;
}
const get = <T>(path: string, params?: Record<string, string | number | boolean | undefined | null>) =>
request<T>('GET', path, { params });
const post = <T>(path: string, body?: unknown) => request<T>('POST', path, { body });
const postForm = <T>(path: string, fd: FormData) => request<T>('POST', path, { formData: fd });
const del = <T>(path: string) => request<T>('DELETE', path);
// ─── Response Types ───────────────────────────────────────────────────────────
export interface ApiDoc {
doc_id: string;
filename: string;
format: string;
pages: number | null;
status: 'uploaded' | 'indexing' | 'indexed' | 'failed';
upload_date: string;
job_id?: string | null;
file_size?: number;
error_msg?: string | null;
}
export interface ApiJobStatus {
job_id: string;
doc_id: string;
status: 'submitted' | 'queued' | 'parsing' | 'extracting' | 'indexing' | 'done' | 'failed' | 'cancelled';
stage: string;
progress: number; // 0.01.0
started_at?: string;
updated_at?: string;
error_msg?: string | null;
}
export interface ApiIndexResult {
job_id: string;
doc_id: string;
status: string;
nodes_added: number;
edges_added: number;
total_nodes: number;
total_edges: number;
pages_processed: number;
extractions_count: number;
duration_seconds: number;
}
export interface ApiKGNode {
id: string;
name: string;
type: string;
page: number;
confidence: string;
degree: number;
source_doc: string;
// Only present in detail endpoint:
degree_centrality?: number;
neighbor_count?: number;
}
export interface ApiKGEdge {
id: string;
source: string;
target: string;
relation: string;
doc_id: string;
page: number;
}
export interface ApiHealthData {
status: string;
version: string;
uptime_seconds: number;
components: {
mineru_venv: { status: string };
langextract_venv: { status: string };
deepseek_api: { status: string };
storage: { status: string };
};
}
export interface ApiStats {
total_documents: number;
indexed_documents: number;
failed_documents: number;
total_nodes: number;
total_edges: number;
total_queries: number;
active_jobs: number;
storage_used_mb: number;
}
export interface ApiToolCall {
step: number;
tool_name: string;
tool_input: string;
tool_output: string;
}
export interface ApiQueryResult {
id: string;
question: string;
answer: string;
tool_calls: ApiToolCall[];
cited_nodes: string[]; // node IDs
duration_seconds: number;
timestamp: string;
}
export interface ApiSearchResult {
query: string;
total: number;
items: ApiKGNode[];
}
export interface ApiPathResult {
from: { id: string; name: string; type: string };
to: { id: string; name: string; type: string };
max_hops: number;
total_paths: number;
paths: Array<{
length: number;
nodes: Array<{ id: string; name: string; type: string }>;
edges?: Array<{ source: string; target: string; relation: string }>;
}>;
}
export interface ApiGraphSearchResult {
query: string;
matched_nodes: ApiKGNode[];
subgraph_edges: ApiKGEdge[];
total_nodes: number;
}
// ─── API Functions ────────────────────────────────────────────────────────────
export const api = {
// A: Documents
listDocuments: (page = 1, pageSize = 100) =>
get<{ total: number; page: number; page_size: number; items: ApiDoc[] }>(
'/documents', { page, page_size: pageSize }
),
getDocument: (docId: string) => get<ApiDoc>(`/documents/${docId}`),
uploadDocument: (file: File) => {
const fd = new FormData();
fd.append('file', file);
return postForm<{ doc_id: string; filename: string; format: string; status: string }>(
'/documents/upload', fd
);
},
deleteDocument: (docId: string) =>
del<{ doc_id: string; removed_nodes: number; removed_edges: number }>(`/documents/${docId}`),
// B: Indexing
startIndexing: (docId: string) =>
post<{ job_id: string; doc_id: string; status: string }>('/index/start', { doc_id: docId }),
getJobStatus: (jobId: string) => get<ApiJobStatus>(`/index/status/${jobId}`),
getJobResult: (jobId: string) => get<ApiIndexResult>(`/index/result/${jobId}`),
cancelJob: (jobId: string) => del<{ job_id: string }>(`/index/jobs/${jobId}`),
// C: Knowledge Graph
getNodes: (params?: { page?: number; pageSize?: number; type?: string; docId?: string }) =>
get<{ total: number; page: number; page_size: number; items: ApiKGNode[] }>('/kg/nodes', {
page: params?.page,
page_size: params?.pageSize ?? 500,
type: params?.type,
doc_id: params?.docId,
}),
getEdges: (params?: { page?: number; pageSize?: number; docId?: string }) =>
get<{ total: number; page: number; page_size: number; items: ApiKGEdge[] }>('/kg/edges', {
page: params?.page,
page_size: params?.pageSize ?? 2000,
doc_id: params?.docId,
}),
getNodeDetail: (nodeId: string) => get<ApiKGNode>(`/kg/nodes/${nodeId}`),
getNodeNeighbors: (nodeId: string, hops = 1) =>
get<{
center: ApiKGNode;
hops: number;
neighbors_by_hop: Record<string, ApiKGNode[]>;
total_neighbors: number;
}>(`/kg/nodes/${nodeId}/neighbors`, { hops }),
getKGStats: () =>
get<{ total_nodes: number; total_edges: number; type_distribution: Record<string, number> }>('/kg/stats'),
exportKG: () => get<{ nodes: ApiKGNode[]; edges: ApiKGEdge[] }>('/kg/export'),
// D: QA Query
query: (question: string, history: { question: string; answer: string }[] = []) => {
// Transform {question, answer}[] to ChatMessage format expected by backend
const chatHistory = history.flatMap(h => [
{ role: 'human' as const, content: h.question },
{ role: 'ai' as const, content: h.answer },
]);
return post<ApiQueryResult>('/query', { question, history: chatHistory });
},
getQueryHistory: (page = 1, pageSize = 50) =>
get<{ total: number; page: number; page_size: number; items: ApiQueryResult[] }>(
'/query/history', { page, page_size: pageSize }
),
// E: Search
searchEntities: (q: string, type?: string, limit = 15) =>
get<ApiSearchResult>('/search/entities', {
q,
type: type && type !== '全部类型' ? type : undefined,
limit,
}),
searchPath: (fromId: string, toId: string, maxHops = 3) =>
get<ApiPathResult>('/search/path', { from: fromId, to: toId, max_hops: maxHops }),
searchGraph: (q: string, includeNeighbors = false) =>
get<ApiGraphSearchResult>('/search/graph', { q, include_neighbors: includeNeighbors }),
// F: System
getHealth: () => get<ApiHealthData>('/health'),
getSystemStats: () => get<ApiStats>('/system/stats'),
getDemoData: () =>
get<{ nodes: ApiKGNode[]; edges: ApiKGEdge[]; stats: Record<string, unknown> }>('/system/demo'),
};

View File

@@ -0,0 +1,27 @@
import React, { useState } from 'react'
const ERROR_IMG_SRC =
'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODgiIGhlaWdodD0iODgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgc3Ryb2tlPSIjMDAwIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBvcGFjaXR5PSIuMyIgZmlsbD0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIzLjciPjxyZWN0IHg9IjE2IiB5PSIxNiIgd2lkdGg9IjU2IiBoZWlnaHQ9IjU2IiByeD0iNiIvPjxwYXRoIGQ9Im0xNiA1OCAxNi0xOCAzMiAzMiIvPjxjaXJjbGUgY3g9IjUzIiBjeT0iMzUiIHI9IjciLz48L3N2Zz4KCg=='
export function ImageWithFallback(props: React.ImgHTMLAttributes<HTMLImageElement>) {
const [didError, setDidError] = useState(false)
const handleError = () => {
setDidError(true)
}
const { src, alt, style, className, ...rest } = props
return didError ? (
<div
className={`inline-block bg-gray-100 text-center align-middle ${className ?? ''}`}
style={style}
>
<div className="flex items-center justify-center w-full h-full">
<img src={ERROR_IMG_SRC} alt="Error loading image" {...rest} data-original-url={src} />
</div>
</div>
) : (
<img src={src} alt={alt} className={className} style={style} {...rest} onError={handleError} />
)
}

View File

@@ -0,0 +1,47 @@
import React from 'react';
import { Outlet } from 'react-router';
import { Toaster } from 'sonner';
import { Header } from './Header';
import { Sidebar } from './Sidebar';
import { StatusBar } from './StatusBar';
import { useAppState, AppProvider } from '../../store';
function AppLayoutInner() {
const { sidebarCollapsed } = useAppState();
return (
<div
style={{
display: 'grid',
gridTemplateAreas: '"header header" "sidebar main" "footer footer"',
gridTemplateColumns: `${sidebarCollapsed ? 72 : 220}px 1fr`,
gridTemplateRows: '56px 1fr 32px',
height: '100vh',
overflow: 'hidden',
transition: 'grid-template-columns 200ms ease',
}}
>
<Header />
<Sidebar />
<main
style={{
gridArea: 'main',
overflowY: 'auto',
background: 'var(--bg-base)',
}}
>
<Outlet />
</main>
<StatusBar />
</div>
);
}
export function AppLayout() {
return (
<AppProvider>
<AppLayoutInner />
<Toaster position="top-right" theme="dark" richColors />
</AppProvider>
);
}

View File

@@ -0,0 +1,145 @@
import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router';
import { Menu, Search, X } from 'lucide-react';
import { useAppState, type KGNode } from '../../store';
import { api } from '../../api';
import { TYPE_COLORS } from '../../mock-data';
export function Header() {
const { sidebarCollapsed, setSidebarCollapsed, health } = useAppState();
const [query, setQuery] = useState('');
const [showSuggestions, setShowSuggestions] = useState(false);
const [suggestions, setSuggestions] = useState<KGNode[]>([]);
const navigate = useNavigate();
const inputRef = useRef<HTMLInputElement>(null);
const timerRef = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => {
if (query.length >= 2) {
clearTimeout(timerRef.current);
timerRef.current = setTimeout(async () => {
try {
const res = await api.searchEntities(query, undefined, 5);
setSuggestions(res.items.map(n => ({
id: n.id, name: n.name, type: n.type as KGNode['type'],
page: n.page, confidence: n.confidence as KGNode['confidence'],
degree: n.degree, centrality: 0, doc_id: n.doc_id,
})));
setShowSuggestions(true);
} catch {
setSuggestions([]);
}
}, 300);
} else {
setSuggestions([]);
setShowSuggestions(false);
}
return () => clearTimeout(timerRef.current);
}, [query]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (query.trim()) {
setShowSuggestions(false);
navigate(`/search?q=${encodeURIComponent(query)}`);
}
};
const allOk = Object.values(health).every(v => v === 'ok');
return (
<header
className="flex items-center px-4 gap-4"
style={{
gridArea: 'header',
height: 56,
background: 'var(--bg-s1)',
borderBottom: '1px solid var(--border-main)',
position: 'sticky',
top: 0,
zIndex: 100,
}}
>
{/* Left */}
<button
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
className="p-1.5 rounded-md hover:opacity-80 cursor-pointer"
style={{ background: 'var(--bg-s2)', color: 'var(--text-3)' }}
aria-label="Toggle sidebar"
>
<Menu size={18} />
</button>
<span style={{ color: 'var(--blue)', fontSize: 16, fontWeight: 600, whiteSpace: 'nowrap' }}>
GraphRAG Studio
</span>
{/* Center - Search */}
<form onSubmit={handleSubmit} className="flex-1 flex justify-center relative" style={{ maxWidth: 400, margin: '0 auto' }}>
<div className="relative w-full">
<Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'var(--text-4)' }} />
<input
ref={inputRef}
value={query}
onChange={e => setQuery(e.target.value)}
onFocus={() => query.length >= 3 && setShowSuggestions(true)}
onBlur={() => setTimeout(() => setShowSuggestions(false), 200)}
placeholder="搜索实体..."
className="w-full pl-9 pr-8 py-1.5 rounded-md outline-none"
style={{
background: 'var(--bg-s2)',
border: '1px solid var(--border-main)',
color: 'var(--text-1)',
fontSize: 13,
}}
/>
{query && (
<button type="button" onClick={() => { setQuery(''); setShowSuggestions(false); }} className="absolute right-2 top-1/2 -translate-y-1/2 cursor-pointer" style={{ color: 'var(--text-4)' }}>
<X size={14} />
</button>
)}
</div>
{showSuggestions && suggestions.length > 0 && (
<div
className="absolute top-full mt-1 w-full rounded-md overflow-hidden"
style={{ background: 'var(--bg-s3)', border: '1px solid var(--border-main)', boxShadow: 'var(--shadow-md)', zIndex: 200 }}
>
{suggestions.map(s => (
<button
key={s.id}
type="button"
className="w-full flex items-center gap-2 px-3 py-2 hover:opacity-80 cursor-pointer text-left"
style={{ background: 'transparent', borderBottom: '1px solid var(--border-muted)' }}
onMouseDown={() => {
setShowSuggestions(false);
setQuery('');
navigate(`/graph?node=${s.id}`);
}}
>
<span style={{ color: 'var(--text-1)', fontSize: 13 }}>{s.name}</span>
<span
className="px-1.5 py-0.5 rounded"
style={{
fontSize: 10, fontWeight: 600,
background: `${TYPE_COLORS[s.type]}20`,
color: TYPE_COLORS[s.type],
}}
>
{s.type}
</span>
</button>
))}
</div>
)}
</form>
{/* Right */}
<div className="flex items-center gap-2" style={{ whiteSpace: 'nowrap' }}>
<span
className="inline-block w-2 h-2 rounded-full"
style={{ background: allOk ? 'var(--green)' : 'var(--red)' }}
/>
<span style={{ color: 'var(--text-3)', fontSize: 12 }}>API: localhost:8000</span>
</div>
</header>
);
}

View File

@@ -0,0 +1,110 @@
import React from 'react';
import { useNavigate, useLocation } from 'react-router';
import { LayoutDashboard, FileText, Share2, MessageSquare, Search, Settings } from 'lucide-react';
import { useAppState } from '../../store';
const navItems = [
{ icon: LayoutDashboard, label: '仪表盘', path: '/dashboard', badge: null },
{ icon: FileText, label: '文档管理', path: '/documents', badgeKey: 'documents' as const },
{ icon: Share2, label: '知识图谱', path: '/graph', badge: null },
{ icon: MessageSquare, label: '智能问答', path: '/chat', badgeKey: 'queries' as const },
{ icon: Search, label: '搜索', path: '/search', badge: null },
];
export function Sidebar() {
const { sidebarCollapsed, stats } = useAppState();
const navigate = useNavigate();
const location = useLocation();
const width = sidebarCollapsed ? 72 : 220;
return (
<nav
className="flex flex-col py-3 overflow-hidden"
style={{
gridArea: 'sidebar',
width,
background: 'var(--bg-s1)',
borderRight: '1px solid var(--border-main)',
transition: 'width 200ms ease',
}}
>
<div className="flex flex-col gap-1 px-2">
{navItems.map(item => {
const active = location.pathname === item.path ||
(item.path === '/dashboard' && location.pathname === '/');
const Icon = item.icon;
const badgeValue = item.badgeKey ? stats[item.badgeKey] : null;
return (
<button
key={item.path}
onClick={() => navigate(item.path)}
className="flex items-center gap-3 rounded-md cursor-pointer relative"
style={{
padding: sidebarCollapsed ? '10px 0' : '10px 12px',
justifyContent: sidebarCollapsed ? 'center' : 'flex-start',
background: active ? 'rgba(88,166,255,0.1)' : 'transparent',
color: active ? 'var(--blue)' : 'var(--text-3)',
fontSize: 14,
fontWeight: active ? 500 : 400,
border: 'none',
transition: 'all 150ms ease',
}}
onMouseEnter={e => {
if (!active) (e.currentTarget as HTMLElement).style.background = 'var(--bg-s2)';
}}
onMouseLeave={e => {
if (!active) (e.currentTarget as HTMLElement).style.background = 'transparent';
}}
>
{active && (
<div
className="absolute left-0 top-2 bottom-2 rounded-r"
style={{ width: 2, background: 'var(--blue)' }}
/>
)}
<Icon size={18} />
{!sidebarCollapsed && (
<>
<span className="flex-1 text-left">{item.label}</span>
{badgeValue != null && (
<span
className="px-1.5 py-0.5 rounded-full"
style={{
fontSize: 11, fontWeight: 600,
background: 'var(--bg-s2)',
color: 'var(--text-3)',
minWidth: 20,
textAlign: 'center',
}}
>
{badgeValue}
</span>
)}
</>
)}
</button>
);
})}
</div>
<div className="mt-auto px-2">
<button
className="flex items-center gap-3 rounded-md w-full cursor-pointer"
style={{
padding: sidebarCollapsed ? '10px 0' : '10px 12px',
justifyContent: sidebarCollapsed ? 'center' : 'flex-start',
background: 'transparent',
color: 'var(--text-4)',
fontSize: 14,
border: 'none',
}}
>
<Settings size={18} />
{!sidebarCollapsed && <span></span>}
</button>
</div>
</nav>
);
}

View File

@@ -0,0 +1,34 @@
import React from 'react';
import { useAppState } from '../../store';
export function StatusBar() {
const { documents, health } = useAppState();
const indexingDoc = documents.find(d => d.status === 'indexing');
const allOk = Object.values(health).every(v => v === 'ok');
return (
<footer
className="flex items-center justify-between px-4"
style={{
gridArea: 'footer',
height: 32,
background: 'var(--bg-s1)',
borderTop: '1px solid var(--border-main)',
fontSize: 12,
color: 'var(--text-4)',
}}
>
<div>
{indexingDoc && (
<span style={{ color: 'var(--yellow)' }}>
{indexingDoc.filename}... {indexingDoc.progress ?? 0}%
</span>
)}
</div>
<div className="flex items-center gap-3">
<span>v1.0.0</span>
<span className="inline-block w-1.5 h-1.5 rounded-full" style={{ background: allOk ? 'var(--green)' : 'var(--red)' }} />
</div>
</footer>
);
}

View File

@@ -0,0 +1,210 @@
import React from 'react';
import { useNavigate } from 'react-router';
import { Share2, MessageSquare, Search, Zap, Upload, FileText, ExternalLink } from 'lucide-react';
import { useAppState } from '../../store';
const statCards = [
{ key: 'kg_nodes', label: '图谱节点', color: '#58a6ff', icon: '◈' },
{ key: 'kg_edges', label: '图谱边', color: '#8957e5', icon: '◇' },
{ key: 'documents', label: '文档数', color: '#3fb950', icon: '▤' },
{ key: 'queries', label: '查询次数', color: '#d29922', icon: '◆' },
] as const;
const statusStyles: Record<string, { bg: string; color: string }> = {
indexed: { bg: '#1a3a22', color: '#3fb950' },
indexing: { bg: '#2d2a16', color: '#d29922' },
uploaded: { bg: '#1c2128', color: '#8b949e' },
failed: { bg: '#3b1a1a', color: '#f85149' },
};
export function Dashboard() {
const { stats, health, documents } = useAppState();
const navigate = useNavigate();
const recentDocs = documents.slice(0, 5);
return (
<div className="p-6" style={{ maxWidth: 1200, margin: '0 auto' }}>
{/* Page Title + Upload Button */}
<div className="flex items-center justify-between mb-6">
<h1 style={{ color: 'var(--text-1)', fontSize: 20, fontWeight: 600 }}></h1>
<button
onClick={() => navigate('/documents')}
className="flex items-center gap-2 px-4 py-2 rounded-md cursor-pointer"
style={{ background: 'var(--green-btn)', color: '#fff', fontSize: 13, fontWeight: 500, border: 'none' }}
>
<Upload size={14} /> &
</button>
</div>
{/* Stat Cards */}
<div className="grid grid-cols-4 gap-4 mb-6" style={{ minWidth: 0 }}>
{statCards.map(c => (
<div
key={c.key}
className="rounded-lg p-4"
style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)' }}
>
<div className="flex items-center justify-between mb-2">
<span style={{ color: 'var(--text-3)', fontSize: 13 }}>{c.label}</span>
<span style={{ fontSize: 18, color: c.color }}>{c.icon}</span>
</div>
<div style={{ color: c.color, fontSize: 28, fontWeight: 700 }}>
{stats[c.key].toLocaleString()}
</div>
</div>
))}
</div>
<div className="grid grid-cols-3 gap-4">
{/* System Health */}
<div
className="rounded-lg p-4 col-span-1"
style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)' }}
>
<h2 className="mb-4" style={{ color: 'var(--text-1)', fontSize: 16, fontWeight: 600 }}></h2>
<div className="flex flex-col gap-3">
{[
{ name: 'MinerU venv', status: health.mineru },
{ name: 'LangExtract venv', status: health.langextract },
{ name: 'DeepSeek API', status: health.deepseek },
{ name: 'Storage', status: health.storage },
].map(s => (
<div key={s.name} className="flex items-center justify-between">
<span style={{ color: 'var(--text-2)', fontSize: 13 }}>{s.name}</span>
<span className="flex items-center gap-1.5">
<span className="inline-block w-2 h-2 rounded-full" style={{ background: s.status === 'ok' ? 'var(--green)' : 'var(--red)' }} />
<span style={{ color: s.status === 'ok' ? 'var(--green)' : 'var(--red)', fontSize: 12 }}>{s.status}</span>
</span>
</div>
))}
</div>
{/* Quick Actions */}
<h2 className="mt-6 mb-3" style={{ color: 'var(--text-1)', fontSize: 16, fontWeight: 600 }}></h2>
<div className="flex flex-col gap-2">
{[
{ icon: Share2, label: '浏览图谱', path: '/graph' },
{ icon: MessageSquare, label: '开始对话', path: '/chat' },
{ icon: Search, label: '搜索', path: '/search' },
{ icon: Zap, label: '演示', path: '/graph' },
].map(a => (
<button
key={a.label}
onClick={() => navigate(a.path)}
className="flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer w-full"
style={{
background: 'var(--bg-s2)',
border: '1px solid var(--border-main)',
color: 'var(--text-2)',
fontSize: 13,
}}
>
<a.icon size={14} style={{ color: 'var(--blue)' }} /> {a.label}
</button>
))}
</div>
</div>
{/* Recent Documents */}
<div
className="rounded-lg p-4 col-span-2"
style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)' }}
>
<div className="flex items-center justify-between mb-4">
<h2 style={{ color: 'var(--text-1)', fontSize: 16, fontWeight: 600 }}></h2>
<button
onClick={() => navigate('/documents')}
className="flex items-center gap-1 cursor-pointer"
style={{ color: 'var(--blue)', fontSize: 12, background: 'none', border: 'none' }}
>
<ExternalLink size={12} />
</button>
</div>
<div className="flex flex-col">
{/* Table header */}
<div
className="grid gap-4 px-3 py-2 rounded-t-md"
style={{ gridTemplateColumns: '1fr 60px 50px 90px 130px 100px', background: 'var(--bg-s2)', fontSize: 11, fontWeight: 600, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.5px' }}
>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
{recentDocs.map(doc => {
const st = statusStyles[doc.status];
return (
<div
key={doc.id}
className="grid gap-4 px-3 py-2.5 items-center"
style={{
gridTemplateColumns: '1fr 60px 50px 90px 130px 100px',
borderBottom: '1px solid var(--border-muted)',
fontSize: 13,
}}
>
<span className="flex items-center gap-2 truncate" style={{ color: 'var(--text-1)' }}>
<FileText size={14} style={{ color: 'var(--text-3)', flexShrink: 0 }} />
<span className="truncate">{doc.filename}</span>
</span>
<span style={{ color: 'var(--text-3)' }}>{doc.format}</span>
<span style={{ color: 'var(--text-3)' }}>{doc.pages}</span>
<span>
<span
className="px-2 py-0.5 rounded-full"
style={{ fontSize: 11, fontWeight: 600, background: st.bg, color: st.color }}
>
{doc.status}
</span>
</span>
<span style={{ color: 'var(--text-4)', fontSize: 12 }}>
{new Date(doc.upload_date).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', year: 'numeric' })}
</span>
<span>
{doc.status === 'indexed' && (
<button
onClick={() => navigate(`/graph?doc_id=${doc.id}`)}
className="px-2 py-1 rounded cursor-pointer"
style={{ fontSize: 11, background: 'rgba(88,166,255,0.1)', color: 'var(--blue)', border: 'none' }}
>
</button>
)}
{doc.status === 'uploaded' && (
<button
className="px-2 py-1 rounded cursor-pointer"
style={{ fontSize: 11, background: 'rgba(35,134,54,0.2)', color: 'var(--green)', border: 'none' }}
>
</button>
)}
{doc.status === 'indexing' && (
<div className="flex items-center gap-2">
<div style={{ flex: 1, height: 4, background: 'var(--bg-s2)', borderRadius: 2, overflow: 'hidden' }}>
<div style={{ width: `${doc.progress}%`, height: '100%', background: 'var(--yellow)', borderRadius: 2, transition: 'width 300ms' }} />
</div>
<span style={{ fontSize: 11, color: 'var(--yellow)' }}>{doc.progress}%</span>
</div>
)}
{doc.status === 'failed' && (
<button
className="px-2 py-1 rounded cursor-pointer"
style={{ fontSize: 11, background: 'rgba(248,81,73,0.1)', color: 'var(--red)', border: 'none' }}
>
</button>
)}
</span>
</div>
);
})}
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,439 @@
import React, { useState, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router';
import { toast } from 'sonner';
import { Upload, FileText, Trash2, Play, RotateCcw, X, ChevronDown, ChevronRight, Eye } from 'lucide-react';
import { useAppState } from '../../store';
import { api, ApiError } from '../../api';
const statusStyles: Record<string, { bg: string; color: string }> = {
indexed: { bg: '#1a3a22', color: '#3fb950' },
indexing: { bg: '#2d2a16', color: '#d29922' },
uploaded: { bg: '#1c2128', color: '#8b949e' },
failed: { bg: '#3b1a1a', color: '#f85149' },
};
export function Documents() {
const { documents, setDocuments, refreshDocuments, refreshKG } = useAppState();
const navigate = useNavigate();
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragOver, setDragOver] = useState(false);
const [formatFilter, setFormatFilter] = useState('All');
const [statusFilter, setStatusFilter] = useState('All');
const [searchTerm, setSearchTerm] = useState('');
const [expandedDoc, setExpandedDoc] = useState<string | null>(null);
const [showDeleteModal, setShowDeleteModal] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const filteredDocs = documents.filter(d => {
if (formatFilter !== 'All' && d.format !== formatFilter) return false;
if (statusFilter !== 'All' && d.status !== statusFilter) return false;
if (searchTerm && !d.filename.toLowerCase().includes(searchTerm.toLowerCase())) return false;
return true;
});
// ── Upload ──────────────────────────────────────────────────────────────────
const handleFiles = useCallback(async (files: FileList | File[]) => {
const fileArr = Array.from(files);
if (fileArr.length === 0) return;
setUploading(true);
for (const file of fileArr) {
try {
toast.loading(`上传 ${file.name}...`, { id: `upload-${file.name}` });
// 1. Upload
const uploaded = await api.uploadDocument(file);
const newDoc = {
id: uploaded.doc_id,
filename: uploaded.filename,
format: uploaded.format,
pages: 0,
status: 'uploaded' as const,
upload_date: new Date().toISOString(),
};
setDocuments(prev => [newDoc, ...prev]);
toast.success(`${file.name} 上传成功`, { id: `upload-${file.name}` });
// 2. Auto-start indexing
try {
toast.loading(`开始索引 ${file.name}...`, { id: `index-${uploaded.doc_id}` });
const job = await api.startIndexing(uploaded.doc_id);
setDocuments(prev =>
prev.map(d => d.id === uploaded.doc_id
? { ...d, status: 'indexing', job_id: job.job_id, progress: 0 }
: d
)
);
toast.success(`${file.name} 开始索引`, { id: `index-${uploaded.doc_id}` });
} catch (err) {
const msg = err instanceof ApiError ? err.message : '启动索引失败';
toast.error(msg, { id: `index-${uploaded.doc_id}` });
}
} catch (err) {
const msg = err instanceof ApiError ? err.message : '上传失败';
toast.error(`${file.name}: ${msg}`, { id: `upload-${file.name}` });
}
}
setUploading(false);
}, [setDocuments]);
const handleDragOver = useCallback((e: React.DragEvent) => { e.preventDefault(); setDragOver(true); }, []);
const handleDragLeave = useCallback(() => setDragOver(false), []);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
setDragOver(false);
handleFiles(e.dataTransfer.files);
}, [handleFiles]);
const handleBrowse = () => fileInputRef.current?.click();
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files) handleFiles(e.target.files);
e.target.value = '';
};
// ── Index / Retry ────────────────────────────────────────────────────────────
const handleStartIndex = useCallback(async (docId: string, filename: string) => {
try {
const job = await api.startIndexing(docId);
setDocuments(prev =>
prev.map(d => d.id === docId
? { ...d, status: 'indexing', job_id: job.job_id, progress: 0, error: undefined }
: d
)
);
toast.success(`${filename} 开始索引`);
} catch (err) {
const msg = err instanceof ApiError ? err.message : '启动索引失败';
toast.error(msg);
}
}, [setDocuments]);
// ── Cancel ───────────────────────────────────────────────────────────────────
const handleCancel = useCallback(async (docId: string, jobId: string) => {
try {
await api.cancelJob(jobId);
setDocuments(prev =>
prev.map(d => d.id === docId
? { ...d, status: 'uploaded', job_id: undefined, progress: undefined }
: d
)
);
toast.info('索引任务已取消');
} catch (err) {
const msg = err instanceof ApiError ? err.message : '取消失败';
toast.error(msg);
}
}, [setDocuments]);
// ── Delete ───────────────────────────────────────────────────────────────────
const handleDelete = useCallback(async () => {
if (!showDeleteModal) return;
try {
await api.deleteDocument(showDeleteModal);
setDocuments(prev => prev.filter(d => d.id !== showDeleteModal));
setShowDeleteModal(null);
toast.success('文档已删除');
refreshKG();
} catch (err) {
const msg = err instanceof ApiError ? err.message : '删除失败';
toast.error(msg);
}
}, [showDeleteModal, setDocuments, refreshKG]);
const deleteDoc = documents.find(d => d.id === showDeleteModal);
return (
<div className="p-6" style={{ maxWidth: 1200, margin: '0 auto' }}>
<h1 className="mb-6" style={{ color: 'var(--text-1)', fontSize: 20, fontWeight: 600 }}></h1>
{/* Hidden file input */}
<input
ref={fileInputRef}
type="file"
multiple
accept=".pdf,.docx,.doc,.pptx,.ppt,.png,.jpg,.jpeg,.html"
style={{ display: 'none' }}
onChange={handleFileChange}
/>
{/* Upload Area */}
<div
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={handleBrowse}
className="flex flex-col items-center justify-center gap-3 rounded-lg p-8 mb-6 cursor-pointer"
style={{
border: `2px dashed ${dragOver ? 'var(--blue)' : 'var(--border-main)'}`,
background: dragOver ? 'rgba(88,166,255,0.05)' : 'var(--bg-s1)',
transition: 'all 200ms ease',
opacity: uploading ? 0.6 : 1,
pointerEvents: uploading ? 'none' : 'auto',
}}
>
<Upload size={32} style={{ color: dragOver ? 'var(--blue)' : 'var(--text-4)' }} />
<div style={{ color: 'var(--text-2)', fontSize: 14 }}>
{uploading ? '正在上传...' : (
<>{' '}<span style={{ color: 'var(--blue)' }}></span></>
)}
</div>
<div style={{ color: 'var(--text-4)', fontSize: 12 }}>
PDF &middot; DOCX &middot; DOC &middot; PPTX &middot; PPT &middot; PNG &middot; JPG &middot; HTML &nbsp;|&nbsp; 200MB
</div>
</div>
{/* Toolbar */}
<div className="flex items-center gap-3 mb-4">
<select
value={formatFilter}
onChange={e => setFormatFilter(e.target.value)}
className="px-3 py-1.5 rounded-md cursor-pointer"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 13 }}
>
<option>All</option>
<option>PDF</option>
<option>DOCX</option>
<option>PPTX</option>
<option>PNG</option>
<option>JPG</option>
<option>HTML</option>
</select>
<select
value={statusFilter}
onChange={e => setStatusFilter(e.target.value)}
className="px-3 py-1.5 rounded-md cursor-pointer"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 13 }}
>
<option>All</option>
<option>indexed</option>
<option>indexing</option>
<option>uploaded</option>
<option>failed</option>
</select>
<input
value={searchTerm}
onChange={e => setSearchTerm(e.target.value)}
placeholder="搜索文档..."
className="px-3 py-1.5 rounded-md flex-1"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-1)', fontSize: 13, outline: 'none' }}
/>
</div>
{/* Document Table */}
<div className="rounded-lg overflow-hidden" style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)' }}>
{/* Header */}
<div
className="grid gap-4 px-4 py-2.5"
style={{
gridTemplateColumns: '24px 1fr 70px 50px 100px 140px 160px',
background: 'var(--bg-s2)', fontSize: 11, fontWeight: 600,
color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.5px',
}}
>
<span />
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
{/* Rows */}
{filteredDocs.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 gap-3">
<FileText size={40} style={{ color: 'var(--text-4)' }} />
<span style={{ color: 'var(--text-3)', fontSize: 14 }}>
{documents.length === 0 ? '暂无文档,请上传文件' : '未找到匹配文档'}
</span>
</div>
) : (
filteredDocs.map(doc => {
const st = statusStyles[doc.status];
const isExpanded = expandedDoc === doc.id;
return (
<React.Fragment key={doc.id}>
<div
className="grid gap-4 px-4 py-3 items-center"
style={{
gridTemplateColumns: '24px 1fr 70px 50px 100px 140px 160px',
borderBottom: '1px solid var(--border-muted)',
fontSize: 13,
}}
>
<button
onClick={() => setExpandedDoc(isExpanded ? null : doc.id)}
className="cursor-pointer"
style={{ background: 'none', border: 'none', color: 'var(--text-4)', padding: 0 }}
>
{doc.status === 'indexed'
? (isExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />)
: <span style={{ width: 14, display: 'inline-block' }} />}
</button>
<span className="flex items-center gap-2 truncate" style={{ color: 'var(--text-1)' }}>
<FileText size={14} style={{ color: 'var(--text-3)', flexShrink: 0 }} />
<span className="truncate">{doc.filename}</span>
</span>
<span style={{ color: 'var(--text-3)' }}>{doc.format}</span>
<span style={{ color: 'var(--text-3)' }}>{doc.pages || '—'}</span>
<span>
<span className="px-2 py-0.5 rounded-full inline-flex items-center gap-1" style={{ fontSize: 11, fontWeight: 600, background: st.bg, color: st.color }}>
{doc.status === 'indexing' && (
<span className="inline-block w-1.5 h-1.5 rounded-full animate-pulse" style={{ background: st.color }} />
)}
{doc.status}
</span>
</span>
<span style={{ color: 'var(--text-4)', fontSize: 12 }}>
{new Date(doc.upload_date).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', year: 'numeric' })}
</span>
<span className="flex items-center gap-2">
{doc.status === 'uploaded' && (
<button
onClick={() => handleStartIndex(doc.id, doc.filename)}
className="flex items-center gap-1 px-2 py-1 rounded cursor-pointer"
style={{ fontSize: 11, background: 'rgba(35,134,54,0.2)', color: 'var(--green)', border: 'none' }}
>
<Play size={10} />
</button>
)}
{doc.status === 'indexing' && (
<>
<div className="flex items-center gap-1.5 flex-1">
<div style={{ flex: 1, height: 4, background: 'var(--bg-s2)', borderRadius: 2, overflow: 'hidden', minWidth: 40 }}>
<div style={{ width: `${doc.progress ?? 0}%`, height: '100%', background: 'var(--yellow)', borderRadius: 2, transition: 'width 300ms' }} />
</div>
<span style={{ fontSize: 10, color: 'var(--yellow)', whiteSpace: 'nowrap' }}>{doc.progress ?? 0}%</span>
</div>
{doc.job_id && (
<button
onClick={() => handleCancel(doc.id, doc.job_id!)}
className="cursor-pointer"
style={{ background: 'none', border: 'none', color: 'var(--text-4)', padding: 2 }}
>
<X size={12} />
</button>
)}
</>
)}
{doc.status === 'indexed' && (
<button
onClick={() => navigate(`/graph?doc_id=${doc.id}`)}
className="flex items-center gap-1 px-2 py-1 rounded cursor-pointer"
style={{ fontSize: 11, background: 'rgba(88,166,255,0.1)', color: 'var(--blue)', border: 'none' }}
>
<Eye size={10} />
</button>
)}
{doc.status === 'failed' && (
<button
onClick={() => handleStartIndex(doc.id, doc.filename)}
className="flex items-center gap-1 px-2 py-1 rounded cursor-pointer"
style={{ fontSize: 11, background: 'rgba(248,81,73,0.1)', color: 'var(--red)', border: 'none' }}
>
<RotateCcw size={10} />
</button>
)}
{doc.status !== 'indexing' && (
<button
onClick={() => setShowDeleteModal(doc.id)}
className="cursor-pointer p-1 rounded"
style={{ background: 'none', border: 'none', color: 'var(--text-4)' }}
>
<Trash2 size={12} />
</button>
)}
</span>
</div>
{/* Expanded Result Row */}
{isExpanded && doc.result && (
<div className="px-12 py-3" style={{ background: 'var(--bg-s2)', borderBottom: '1px solid var(--border-muted)' }}>
<div className="flex items-center gap-4 mb-2" style={{ fontSize: 13, color: 'var(--text-2)' }}>
<span>{doc.result.nodes} </span>
<span style={{ color: 'var(--text-4)' }}>&middot;</span>
<span>{doc.result.edges} </span>
<span style={{ color: 'var(--text-4)' }}>&middot;</span>
<span>{doc.result.pages} </span>
<span style={{ color: 'var(--text-4)' }}>&middot;</span>
<span>{doc.result.extractions} </span>
<span style={{ color: 'var(--text-4)' }}>&middot;</span>
<span>{doc.result.duration.toFixed(1)}</span>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => navigate(`/graph?doc_id=${doc.id}`)}
className="flex items-center gap-1 px-2 py-1 rounded cursor-pointer"
style={{ fontSize: 11, background: 'rgba(88,166,255,0.1)', color: 'var(--blue)', border: 'none' }}
>
</button>
{/* 查看提取结果:后端暂未提供独立 API功能未开发 */}
<button
disabled
title="功能未开发:后端暂无提取记录独立查询接口"
className="flex items-center gap-1 px-2 py-1 rounded"
style={{ fontSize: 11, background: 'var(--bg-s1)', color: 'var(--text-4)', border: '1px solid var(--border-muted)', cursor: 'not-allowed', opacity: 0.5 }}
>
<span style={{ fontSize: 9, background: 'rgba(209,75,75,0.2)', color: '#f85149', padding: '1px 4px', borderRadius: 3, marginLeft: 4 }}></span>
</button>
</div>
</div>
)}
{/* Error message */}
{doc.status === 'failed' && doc.error && (
<div className="px-12 py-2" style={{ background: 'rgba(248,81,73,0.05)', borderBottom: '1px solid var(--border-muted)' }}>
<span style={{ fontSize: 12, color: 'var(--red)' }}>{doc.error}</span>
</div>
)}
</React.Fragment>
);
})
)}
</div>
{/* Delete Modal */}
{showDeleteModal && deleteDoc && (
<div
className="fixed inset-0 flex items-center justify-center"
style={{ background: 'rgba(0,0,0,0.6)', zIndex: 1000 }}
onClick={() => setShowDeleteModal(null)}
>
<div
className="rounded-xl p-6"
style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)', width: 360, boxShadow: 'var(--shadow-lg)' }}
onClick={e => e.stopPropagation()}
>
<h3 className="mb-3" style={{ color: 'var(--text-1)', fontSize: 16, fontWeight: 600 }}>
"{deleteDoc.filename}"
</h3>
<p className="mb-4" style={{ color: 'var(--text-2)', fontSize: 13 }}>
</p>
<div className="flex justify-end gap-2">
<button
onClick={() => setShowDeleteModal(null)}
className="px-4 py-2 rounded-md cursor-pointer"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 13 }}
>
</button>
<button
onClick={handleDelete}
className="px-4 py-2 rounded-md cursor-pointer"
style={{ background: 'rgba(248,81,73,0.15)', border: '1px solid var(--red)', color: 'var(--red)', fontSize: 13, fontWeight: 500 }}
>
</button>
</div>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,439 @@
import React, { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
import * as d3 from 'd3';
import { ZoomIn, ZoomOut, Maximize2, Search, Download, Image, X, MessageSquare, Upload, Share2 } from 'lucide-react';
import { useAppState, type KGNode } from '../../store';
import { TYPE_COLORS } from '../../mock-data';
const ENTITY_TYPES = ['TECHNOLOGY', 'CONCEPT', 'PERSON', 'ORGANIZATION', 'LOCATION'] as const;
const CONFIDENCE_LEVELS = ['match_exact', 'match_greater', 'match_lesser', 'match_fuzzy'] as const;
export function KGExplorer() {
const { nodes, edges, documents, selectedNode, setSelectedNode, getNeighbors } = useAppState();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const svgRef = useRef<SVGSVGElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const simulationRef = useRef<d3.Simulation<any, any>>();
const zoomRef = useRef<d3.ZoomBehavior<SVGSVGElement, unknown>>();
const [filterTypes, setFilterTypes] = useState<Set<string>>(new Set(ENTITY_TYPES));
const [filterConfidence, setFilterConfidence] = useState<Set<string>>(new Set(CONFIDENCE_LEVELS));
const [filterDoc, setFilterDoc] = useState<string>('all');
const [searchQuery, setSearchQuery] = useState('');
const [showFilter, setShowFilter] = useState(true);
const [tooltip, setTooltip] = useState<{ x: number; y: number; node: KGNode } | null>(null);
const indexedDocs = documents.filter(d => d.status === 'indexed');
// Filtered nodes/edges
const visibleNodes = nodes.filter(n => {
if (!filterTypes.has(n.type)) return false;
if (!filterConfidence.has(n.confidence)) return false;
if (filterDoc !== 'all' && n.doc_id !== filterDoc) return false;
if (searchQuery && !n.name.toLowerCase().includes(searchQuery.toLowerCase())) return false;
return true;
});
const visibleNodeIds = new Set(visibleNodes.map(n => n.id));
const visibleEdges = edges.filter(e => visibleNodeIds.has(e.source as string) && visibleNodeIds.has(e.target as string));
// Neighbors of selected
const neighborInfo = selectedNode ? getNeighbors(selectedNode.id) : null;
// D3 rendering
useEffect(() => {
if (!svgRef.current || !containerRef.current) return;
const svg = d3.select(svgRef.current);
svg.selectAll('*').remove();
if (visibleNodes.length === 0) return;
const rect = containerRef.current.getBoundingClientRect();
const width = rect.width;
const height = rect.height;
svg.attr('width', width).attr('height', height);
const g = svg.append('g');
const zoom = d3.zoom<SVGSVGElement, unknown>()
.scaleExtent([0.1, 8])
.on('zoom', (event) => g.attr('transform', event.transform));
zoomRef.current = zoom;
svg.call(zoom);
// Create simulation data copies
const simNodes = visibleNodes.map(n => ({ ...n, x: width / 2 + (Math.random() - 0.5) * 200, y: height / 2 + (Math.random() - 0.5) * 200 }));
const simEdges = visibleEdges.map(e => ({ ...e, source: e.source, target: e.target }));
const simulation = d3.forceSimulation(simNodes)
.force('link', d3.forceLink(simEdges).id((d: any) => d.id).distance(60).strength(0.3))
.force('charge', d3.forceManyBody().strength(-120))
.force('center', d3.forceCenter(width / 2, height / 2))
.force('collide', d3.forceCollide().radius((d: any) => getRadius(d.degree) + 4))
.alphaDecay(0.02);
simulationRef.current = simulation;
// Edges
const link = g.append('g')
.selectAll('line')
.data(simEdges)
.join('line')
.attr('stroke', '#30363d')
.attr('stroke-width', 1)
.attr('stroke-opacity', 0.25);
// Nodes
const node = g.append('g')
.selectAll('circle')
.data(simNodes)
.join('circle')
.attr('r', (d: any) => getRadius(d.degree))
.attr('fill', (d: any) => TYPE_COLORS[d.type] || '#8b949e')
.attr('stroke', '#0f1117')
.attr('stroke-width', 1.5)
.attr('opacity', 0.9)
.attr('cursor', 'pointer')
.on('mouseover', function(event, d: any) {
d3.select(this).attr('stroke', '#ffffff').attr('stroke-width', 2.5);
setTooltip({ x: event.clientX + 8, y: event.clientY + 8, node: d });
})
.on('mouseout', function() {
d3.select(this).attr('stroke', '#0f1117').attr('stroke-width', 1.5);
setTooltip(null);
})
.on('click', (_, d: any) => {
setSelectedNode(d);
// Highlight logic
node.attr('opacity', (n: any) => {
if (n.id === d.id) return 0.9;
const isNeighbor = simEdges.some((e: any) =>
(e.source.id === d.id && e.target.id === n.id) ||
(e.target.id === d.id && e.source.id === n.id)
);
return isNeighbor ? 0.9 : 0.1;
});
d3.select(node.nodes()[simNodes.indexOf(d)])
.attr('r', getRadius(d.degree) * 1.5);
link.attr('stroke-opacity', (e: any) =>
e.source.id === d.id || e.target.id === d.id ? 0.8 : 0.05
);
})
.call(d3.drag<SVGCircleElement, any>()
.on('start', (event, d: any) => {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x; d.fy = d.y;
})
.on('drag', (event, d: any) => { d.fx = event.x; d.fy = event.y; })
.on('end', (event, d: any) => {
if (!event.active) simulation.alphaTarget(0);
})
);
// Labels for high-degree nodes
const label = g.append('g')
.selectAll('text')
.data(simNodes.filter(n => n.degree >= 12))
.join('text')
.text((d: any) => d.name)
.attr('font-size', 10)
.attr('fill', 'var(--text-3)')
.attr('text-anchor', 'middle')
.attr('dy', (d: any) => -(getRadius(d.degree) + 6))
.attr('pointer-events', 'none');
// Click blank to reset
svg.on('click', (event) => {
if (event.target === svgRef.current) {
setSelectedNode(null);
node.attr('opacity', 0.9).attr('r', (d: any) => getRadius(d.degree));
link.attr('stroke-opacity', 0.25);
}
});
simulation.on('tick', () => {
link
.attr('x1', (d: any) => d.source.x)
.attr('y1', (d: any) => d.source.y)
.attr('x2', (d: any) => d.target.x)
.attr('y2', (d: any) => d.target.y);
node
.attr('cx', (d: any) => d.x)
.attr('cy', (d: any) => d.y);
label
.attr('x', (d: any) => d.x)
.attr('y', (d: any) => d.y);
});
// Handle URL params
const nodeParam = searchParams.get('node');
if (nodeParam) {
const target = simNodes.find(n => n.id === nodeParam);
if (target) {
setTimeout(() => {
const nd = nodes.find(n => n.id === nodeParam);
if (nd) setSelectedNode(nd);
}, 500);
}
}
const docParam = searchParams.get('doc_id');
if (docParam) {
setFilterDoc(docParam);
}
return () => { simulation.stop(); };
}, [visibleNodes.length, visibleEdges.length, searchQuery, filterDoc]);
const handleZoomIn = () => {
if (svgRef.current && zoomRef.current) {
d3.select(svgRef.current).transition().duration(300).call(zoomRef.current.scaleBy, 1.3);
}
};
const handleZoomOut = () => {
if (svgRef.current && zoomRef.current) {
d3.select(svgRef.current).transition().duration(300).call(zoomRef.current.scaleBy, 0.7);
}
};
const handleFitAll = () => {
if (svgRef.current && zoomRef.current) {
d3.select(svgRef.current).transition().duration(500).call(zoomRef.current.transform, d3.zoomIdentity);
}
};
const toggleType = (t: string) => {
const next = new Set(filterTypes);
if (next.has(t)) next.delete(t); else next.add(t);
setFilterTypes(next);
};
const toggleConfidence = (c: string) => {
const next = new Set(filterConfidence);
if (next.has(c)) next.delete(c); else next.add(c);
setFilterConfidence(next);
};
return (
<div className="flex h-full" style={{ background: 'var(--bg-base)' }}>
{/* Filter Panel */}
{showFilter && (
<div
className="flex flex-col p-4 overflow-y-auto"
style={{
width: 260,
background: 'var(--bg-s1)',
borderRight: '1px solid var(--border-main)',
flexShrink: 0,
}}
>
<h3 className="mb-3" style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px', color: 'var(--text-3)' }}></h3>
<select
value={filterDoc}
onChange={e => setFilterDoc(e.target.value)}
className="mb-4 px-2 py-1.5 rounded-md w-full"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 12 }}
>
<option value="all"></option>
{indexedDocs.map(d => (
<option key={d.id} value={d.id}>{d.filename}</option>
))}
</select>
<h3 className="mb-2" style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px', color: 'var(--text-3)' }}></h3>
<div className="flex flex-col gap-1.5 mb-4">
{ENTITY_TYPES.map(t => {
const count = nodes.filter(n => n.type === t).length;
return (
<label key={t} className="flex items-center gap-2 cursor-pointer" style={{ fontSize: 12, color: 'var(--text-2)' }}>
<input
type="checkbox"
checked={filterTypes.has(t)}
onChange={() => toggleType(t)}
className="cursor-pointer"
style={{ accentColor: TYPE_COLORS[t] }}
/>
<span className="inline-block w-2.5 h-2.5 rounded-full" style={{ background: TYPE_COLORS[t] }} />
<span className="flex-1">{t}</span>
<span style={{ color: 'var(--text-4)', fontSize: 11 }}>{count}</span>
</label>
);
})}
</div>
<h3 className="mb-2" style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px', color: 'var(--text-3)' }}></h3>
<div className="flex flex-col gap-1.5 mb-4">
{CONFIDENCE_LEVELS.map(c => (
<label key={c} className="flex items-center gap-2 cursor-pointer" style={{ fontSize: 12, color: 'var(--text-2)' }}>
<input type="checkbox" checked={filterConfidence.has(c)} onChange={() => toggleConfidence(c)} className="cursor-pointer" />
{c.replace('match_', '')}
</label>
))}
</div>
<div className="mt-auto flex flex-col gap-2">
<button className="flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer w-full" style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 12 }}>
<Image size={12} /> PNG
</button>
<button className="flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer w-full" style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 12 }}>
<Download size={12} /> JSON
</button>
</div>
</div>
)}
{/* Graph Area */}
<div ref={containerRef} className="flex-1 relative" style={{ overflow: 'hidden' }}>
{/* Toolbar */}
<div className="absolute top-3 left-3 flex items-center gap-1.5 rounded-md p-1" style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)', zIndex: 10 }}>
<button onClick={handleZoomIn} className="p-1.5 rounded cursor-pointer" style={{ background: 'transparent', border: 'none', color: 'var(--text-3)' }}><ZoomIn size={16} /></button>
<button onClick={handleZoomOut} className="p-1.5 rounded cursor-pointer" style={{ background: 'transparent', border: 'none', color: 'var(--text-3)' }}><ZoomOut size={16} /></button>
<button onClick={handleFitAll} className="p-1.5 rounded cursor-pointer" style={{ background: 'transparent', border: 'none', color: 'var(--text-3)' }}><Maximize2 size={16} /></button>
<div style={{ width: 1, height: 20, background: 'var(--border-main)' }} />
<div className="relative">
<Search size={12} className="absolute left-2 top-1/2 -translate-y-1/2" style={{ color: 'var(--text-4)' }} />
<input
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
placeholder="搜索..."
className="pl-7 pr-2 py-1 rounded"
style={{ width: 120, background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-1)', fontSize: 12, outline: 'none' }}
/>
</div>
</div>
{/* Legend */}
<div className="absolute bottom-3 left-3 flex flex-wrap gap-3 rounded-md px-3 py-2" style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)', zIndex: 10 }}>
{ENTITY_TYPES.map(t => (
<div key={t} className="flex items-center gap-1.5" style={{ fontSize: 11, color: 'var(--text-3)' }}>
<span className="inline-block w-2.5 h-2.5 rounded-full" style={{ background: TYPE_COLORS[t] }} />
{t}
</div>
))}
</div>
{/* Stats */}
<div className="absolute top-3 right-3 rounded-md px-3 py-1.5" style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)', zIndex: 10, fontSize: 11, color: 'var(--text-3)' }}>
{visibleNodes.length} &middot; {visibleEdges.length}
</div>
{visibleNodes.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full gap-3">
<Share2 size={48} style={{ color: 'var(--text-4)' }} />
<span style={{ color: 'var(--text-2)', fontSize: 16 }}></span>
<button
onClick={() => navigate('/documents')}
className="flex items-center gap-2 px-4 py-2 rounded-md cursor-pointer"
style={{ background: 'var(--green-btn)', color: '#fff', fontSize: 13, border: 'none' }}
>
<Upload size={14} /> &
</button>
</div>
) : (
<svg ref={svgRef} className="w-full h-full" />
)}
{/* Tooltip */}
{tooltip && (
<div
className="fixed rounded-md px-3 py-2 pointer-events-none"
style={{
left: tooltip.x, top: tooltip.y,
background: 'var(--bg-s3)', border: '1px solid var(--border-main)',
boxShadow: 'var(--shadow-md)', zIndex: 100, fontSize: 12,
}}
>
<div className="flex items-center gap-2 mb-1">
<span style={{ color: 'var(--text-1)', fontWeight: 600 }}>{tooltip.node.name}</span>
<span className="px-1.5 py-0.5 rounded" style={{ fontSize: 10, fontWeight: 600, background: `${TYPE_COLORS[tooltip.node.type]}20`, color: TYPE_COLORS[tooltip.node.type] }}>
{tooltip.node.type}
</span>
</div>
<div style={{ color: 'var(--text-3)' }}>: {tooltip.node.page}</div>
<div style={{ color: 'var(--text-3)' }}>: {tooltip.node.confidence}</div>
<div style={{ color: 'var(--text-3)' }}>: {tooltip.node.degree}</div>
</div>
)}
</div>
{/* Detail Panel */}
{selectedNode && (
<div
className="flex flex-col p-4 overflow-y-auto"
style={{
width: 300,
background: 'var(--bg-s1)',
borderLeft: '1px solid var(--border-main)',
flexShrink: 0,
}}
>
<div className="flex items-center justify-between mb-3">
<h2 style={{ color: 'var(--text-1)', fontSize: 18, fontWeight: 600 }}>{selectedNode.name}</h2>
<button onClick={() => setSelectedNode(null)} className="cursor-pointer" style={{ background: 'none', border: 'none', color: 'var(--text-4)' }}>
<X size={16} />
</button>
</div>
<span className="inline-block w-fit px-2 py-0.5 rounded mb-4" style={{ fontSize: 11, fontWeight: 600, background: `${TYPE_COLORS[selectedNode.type]}20`, color: TYPE_COLORS[selectedNode.type] }}>
{selectedNode.type}
</span>
{selectedNode.description && (
<p className="mb-4" style={{ color: 'var(--text-2)', fontSize: 13, lineHeight: 1.6 }}>
{selectedNode.description}
</p>
)}
<div className="flex flex-col gap-2 mb-4">
{[
{ label: '页码', value: selectedNode.page },
{ label: '置信度', value: selectedNode.confidence.replace('match_', '') },
{ label: '度数', value: selectedNode.degree },
{ label: '中心性', value: selectedNode.centrality.toFixed(2) },
].map(p => (
<div key={p.label} className="flex justify-between" style={{ fontSize: 13 }}>
<span style={{ color: 'var(--text-3)' }}>{p.label}</span>
<span style={{ color: 'var(--text-1)' }}>{p.value}</span>
</div>
))}
</div>
<h3 className="mb-2" style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px', color: 'var(--text-3)' }}>
({neighborInfo?.nodes.length ?? 0})
</h3>
<div className="flex flex-col gap-1 mb-4">
{neighborInfo?.nodes.slice(0, 5).map(n => (
<button
key={n.id}
onClick={() => setSelectedNode(n)}
className="flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer text-left"
style={{ background: 'var(--bg-s2)', border: 'none', fontSize: 12, color: 'var(--text-2)' }}
>
<span className="inline-block w-2 h-2 rounded-full" style={{ background: TYPE_COLORS[n.type] }} />
<span className="flex-1 truncate">{n.name}</span>
<span style={{ color: 'var(--text-4)', fontSize: 10 }}>{n.type}</span>
</button>
))}
{(neighborInfo?.nodes.length ?? 0) > 5 && (
<span style={{ color: 'var(--blue)', fontSize: 12, cursor: 'pointer' }}>
{neighborInfo?.nodes.length} &rarr;
</span>
)}
</div>
<button
onClick={() => navigate(`/chat?q=${encodeURIComponent(`Tell me about ${selectedNode.name}`)}`)}
className="flex items-center gap-2 px-3 py-2 rounded-md cursor-pointer w-full justify-center"
style={{ background: 'rgba(88,166,255,0.1)', border: '1px solid var(--blue)', color: 'var(--blue)', fontSize: 13 }}
>
<MessageSquare size={14} /> AI
</button>
</div>
)}
</div>
);
}
function getRadius(degree: number): number {
return Math.max(4, Math.log(degree + 1) * 4);
}

View File

@@ -0,0 +1,377 @@
import React, { useState, useRef, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
import { Send, Plus, ChevronRight, Clock, ExternalLink, Info } from 'lucide-react';
import { toast } from 'sonner';
import { useAppState, type ChatMessage, type ToolCall } from '../../store';
import { api, ApiError } from '../../api';
import { TYPE_COLORS } from '../../mock-data';
export function QAChat() {
const { messages, setMessages, chatHistory, suggestedPrompts, nodes, refreshHistory } = useAppState();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const [input, setInput] = useState('');
const [isThinking, setIsThinking] = useState(false);
const [activeHistoryId, setActiveHistoryId] = useState<string | null>(null);
const [conversationHistory, setConversationHistory] = useState<{ question: string; answer: string }[]>([]);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
const q = searchParams.get('q');
if (q) {
setInput(q);
inputRef.current?.focus();
}
}, [searchParams]);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages, isThinking]);
// Build cited node objects from node IDs using local KG
function resolveCitedNodes(ids: string[]) {
return ids
.map(id => {
const n = nodes.find(n => n.id === id);
return n ? { id: n.id, name: n.name, type: n.type } : null;
})
.filter(Boolean) as { id: string; name: string; type: string }[];
}
const handleSend = async () => {
if (!input.trim() || isThinking) return;
const question = input.trim();
setInput('');
setIsThinking(true);
const userMsg: ChatMessage = {
id: `m${Date.now()}`,
role: 'human',
content: question,
timestamp: new Date().toISOString(),
};
setMessages(prev => [...prev, userMsg]);
try {
const result = await api.query(question, conversationHistory);
const aiMsg: ChatMessage = {
id: result.id ?? `m${Date.now() + 1}`,
role: 'ai',
content: result.answer,
timestamp: result.timestamp ?? new Date().toISOString(),
toolCalls: result.tool_calls.map((tc, i) => ({
step: tc.step ?? i + 1,
tool: tc.tool_name,
input: tc.tool_input,
output: tc.tool_output,
})),
citedNodes: resolveCitedNodes(result.cited_nodes ?? []),
duration: result.duration_seconds,
};
setMessages(prev => [...prev, aiMsg]);
setConversationHistory(prev => [...prev, { question, answer: result.answer }]);
// Refresh history sidebar
refreshHistory();
} catch (err) {
const msg = err instanceof ApiError ? err.message : '问答服务异常';
toast.error(msg);
setMessages(prev => [...prev, {
id: `err${Date.now()}`,
role: 'ai',
content: `⚠️ 请求失败:${msg}\n\n请确认\n1. 后端服务已启动localhost:8000\n2. 知识图谱已有数据(请先上传并索引文档)\n3. DeepSeek API Key 已配置`,
timestamp: new Date().toISOString(),
}]);
} finally {
setIsThinking(false);
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
const handleNewChat = () => {
setMessages([]);
setInput('');
setActiveHistoryId(null);
setConversationHistory([]);
};
// Load a history item as a single Q&A session
const handleLoadHistory = (h: typeof chatHistory[0]) => {
setActiveHistoryId(h.id);
const msgs: ChatMessage[] = [
{ id: `${h.id}-q`, role: 'human', content: h.question, timestamp: h.timestamp },
{
id: `${h.id}-a`, role: 'ai', content: h.answer, timestamp: h.timestamp,
toolCalls: h.toolCalls,
citedNodes: resolveCitedNodes(h.citedNodeIds ?? []),
duration: h.duration,
},
];
setMessages(msgs);
setConversationHistory([{ question: h.question, answer: h.answer }]);
};
const groupedHistory = {
'今天': chatHistory.filter(h => h.group === '今天'),
'昨天': chatHistory.filter(h => h.group === '昨天'),
'更早': chatHistory.filter(h => h.group === '更早'),
};
return (
<div className="flex h-full" style={{ background: 'var(--bg-base)' }}>
{/* History Sidebar */}
<div
className="flex flex-col"
style={{ width: 240, background: 'var(--bg-s1)', borderRight: '1px solid var(--border-main)', flexShrink: 0 }}
>
<div className="p-3">
<button
onClick={handleNewChat}
className="flex items-center gap-2 w-full px-3 py-2 rounded-md cursor-pointer"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 13 }}
>
<Plus size={14} />
</button>
</div>
{/* 历史会话管理说明 */}
<div className="mx-3 mb-2 px-2 py-1.5 rounded-md flex items-start gap-1.5" style={{ background: 'rgba(88,166,255,0.08)', border: '1px solid rgba(88,166,255,0.2)' }}>
<Info size={11} style={{ color: 'var(--blue)', flexShrink: 0, marginTop: 1 }} />
<span style={{ fontSize: 10, color: 'var(--text-4)', lineHeight: 1.4 }}>
<span style={{ background: 'rgba(248,81,73,0.15)', color: '#f85149', padding: '0 3px', borderRadius: 2, marginLeft: 2 }}></span>
</span>
</div>
<div className="flex-1 overflow-y-auto px-2">
{Object.entries(groupedHistory).map(([group, items]) => items.length > 0 && (
<div key={group} className="mb-3">
<div className="px-2 py-1" style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
{group}
</div>
{items.map(h => (
<button
key={h.id}
onClick={() => handleLoadHistory(h)}
className="w-full text-left px-2 py-1.5 rounded cursor-pointer truncate block"
style={{
background: activeHistoryId === h.id ? 'var(--bg-s2)' : 'transparent',
color: activeHistoryId === h.id ? 'var(--text-1)' : 'var(--text-3)',
fontSize: 12, border: 'none',
}}
>
{h.question.length > 28 ? h.question.slice(0, 28) + '...' : h.question}
</button>
))}
</div>
))}
{chatHistory.length === 0 && (
<div className="px-2 py-4 text-center" style={{ color: 'var(--text-4)', fontSize: 12 }}></div>
)}
</div>
</div>
{/* Chat Area */}
<div className="flex-1 flex flex-col">
{/* Messages */}
<div className="flex-1 overflow-y-auto p-6">
{messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full gap-4">
<div style={{ fontSize: 32 }}>
<span style={{ color: 'var(--blue)' }}>GraphRAG</span>{' '}
<span style={{ color: 'var(--text-3)' }}>Studio</span>
</div>
<p style={{ color: 'var(--text-3)', fontSize: 14, textAlign: 'center', maxWidth: 500 }}>
使
</p>
<div className="grid grid-cols-2 gap-3 mt-4" style={{ maxWidth: 600, width: '100%' }}>
{suggestedPrompts.map((p, i) => (
<button
key={i}
onClick={() => setInput(p)}
className="text-left p-3 rounded-lg cursor-pointer"
style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 13 }}
>
{p}
</button>
))}
</div>
</div>
) : (
<div className="flex flex-col gap-4 max-w-3xl mx-auto">
{messages.map(msg => (
<div key={msg.id}>
{msg.role === 'human' ? (
<div className="flex justify-end">
<div
className="rounded-lg px-4 py-3"
style={{ background: 'rgba(88,166,255,0.15)', color: 'var(--text-1)', fontSize: 14, maxWidth: '80%', lineHeight: 1.6 }}
>
{msg.content}
</div>
</div>
) : (
<div className="flex justify-start">
<div
className="rounded-lg px-4 py-3"
style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 14, maxWidth: '90%', lineHeight: 1.6 }}
>
<div
style={{ whiteSpace: 'pre-wrap' }}
dangerouslySetInnerHTML={{ __html: renderSimpleMarkdown(msg.content) }}
/>
{msg.toolCalls && msg.toolCalls.length > 0 && (
<ToolCallPanel toolCalls={msg.toolCalls} />
)}
{msg.citedNodes && msg.citedNodes.length > 0 && (
<div className="flex flex-wrap gap-2 mt-3 pt-3" style={{ borderTop: '1px solid var(--border-muted)' }}>
{msg.citedNodes.map(cn => (
<button
key={cn.id}
onClick={() => navigate(`/graph?node=${cn.id}`)}
className="flex items-center gap-1.5 px-2 py-1 rounded-full cursor-pointer"
style={{
background: `${TYPE_COLORS[cn.type] ?? '#8b949e'}15`,
border: `1px solid ${TYPE_COLORS[cn.type] ?? '#8b949e'}40`,
color: TYPE_COLORS[cn.type] ?? '#8b949e',
fontSize: 11, fontWeight: 500,
}}
>
<span className="inline-block w-1.5 h-1.5 rounded-full" style={{ background: TYPE_COLORS[cn.type] ?? '#8b949e' }} />
{cn.name}
<ExternalLink size={9} />
</button>
))}
</div>
)}
{msg.duration !== undefined && (
<div className="flex items-center gap-1 mt-2" style={{ color: 'var(--text-4)', fontSize: 11 }}>
<Clock size={10} /> {msg.duration.toFixed(1)}s
</div>
)}
</div>
</div>
)}
</div>
))}
{isThinking && (
<div className="flex justify-start">
<div
className="rounded-lg px-4 py-3 flex items-center gap-1.5"
style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)' }}
>
<span className="thinking-dot" />
<span className="thinking-dot" />
<span className="thinking-dot" />
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
)}
</div>
{/* Input Area */}
<div className="p-4" style={{ borderTop: '1px solid var(--border-main)', background: 'var(--bg-s1)' }}>
<div className="max-w-3xl mx-auto flex gap-2">
<textarea
ref={inputRef}
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="向知识图谱提问..."
disabled={isThinking}
rows={1}
className="flex-1 resize-none rounded-lg px-4 py-2.5 outline-none"
style={{
background: 'var(--bg-s2)', border: '1px solid var(--border-main)',
color: 'var(--text-1)', fontSize: 14, minHeight: 42, maxHeight: 120,
opacity: isThinking ? 0.5 : 1,
}}
/>
<button
onClick={handleSend}
disabled={isThinking || !input.trim()}
className="px-4 py-2 rounded-lg cursor-pointer flex items-center gap-2"
style={{
background: input.trim() ? 'var(--green-btn)' : 'var(--bg-s2)',
color: input.trim() ? '#fff' : 'var(--text-4)',
border: 'none', fontSize: 13, fontWeight: 500,
opacity: isThinking ? 0.5 : 1,
}}
>
<Send size={14} />
</button>
</div>
<div className="max-w-3xl mx-auto mt-1.5">
<span style={{ color: 'var(--text-4)', fontSize: 11 }}>
Enter Shift+Enter &nbsp;|&nbsp;
<span style={{ background: 'rgba(248,81,73,0.15)', color: '#f85149', padding: '0 3px', borderRadius: 2, marginLeft: 4, fontSize: 10 }}></span>
</span>
</div>
</div>
</div>
</div>
);
}
function ToolCallPanel({ toolCalls }: { toolCalls: ToolCall[] }) {
const [expanded, setExpanded] = useState(false);
return (
<div className="mt-3">
<button
onClick={() => setExpanded(!expanded)}
className="flex items-center gap-1.5 cursor-pointer"
style={{ background: 'none', border: 'none', color: 'var(--text-3)', fontSize: 12 }}
>
<ChevronRight
size={12}
style={{ transform: expanded ? 'rotate(90deg)' : 'none', transition: 'transform 150ms' }}
/>
({toolCalls.length} )
</button>
{expanded && (
<div className="mt-2 rounded-md overflow-hidden" style={{ background: 'var(--bg-s3)', border: '1px solid var(--border-muted)' }}>
{toolCalls.map(tc => (
<div key={tc.step} className="p-3" style={{ borderBottom: '1px solid var(--border-muted)' }}>
<div className="flex items-center gap-2 mb-2">
<span style={{ color: 'var(--text-4)', fontSize: 11 }}> {tc.step}</span>
<span style={{ color: 'var(--yellow)', fontSize: 12, fontFamily: 'monospace', fontWeight: 600 }}>{tc.tool}</span>
</div>
<div className="mb-1" style={{ fontSize: 11, color: 'var(--text-4)' }}>:</div>
<pre className="mb-2 p-2 rounded overflow-x-auto" style={{ background: 'var(--bg-base)', fontSize: 11, color: 'var(--text-3)', fontFamily: 'monospace', lineHeight: 1.5 }}>
{tc.input}
</pre>
<div className="mb-1" style={{ fontSize: 11, color: 'var(--text-4)' }}>:</div>
<pre className="p-2 rounded overflow-x-auto" style={{ background: 'var(--bg-base)', fontSize: 11, color: 'var(--text-3)', fontFamily: 'monospace', lineHeight: 1.5 }}>
{tc.output}
</pre>
</div>
))}
</div>
)}
</div>
);
}
function renderSimpleMarkdown(text: string): string {
return text
.replace(/\*\*(.*?)\*\*/g, '<strong style="color:var(--text-1)">$1</strong>')
.replace(/^## (.*$)/gm, '<div style="font-size:16px;font-weight:600;color:var(--text-1);margin:8px 0 4px">$1</div>')
.replace(/^### (.*$)/gm, '<div style="font-size:14px;font-weight:600;color:var(--text-1);margin:6px 0 4px">$1</div>')
.replace(/^> (.*$)/gm, '<div style="border-left:3px solid var(--blue);padding-left:12px;color:var(--text-3);margin:8px 0">$1</div>')
.replace(/^\d+\. (.*$)/gm, '<div style="padding-left:16px;margin:2px 0">$&</div>')
.replace(/^- (.*$)/gm, '<div style="padding-left:16px;margin:2px 0">&bull; $1</div>')
.replace(/\n/g, '<br/>');
}

View File

@@ -0,0 +1,469 @@
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
import * as d3 from 'd3';
import { Search, ExternalLink, MessageSquare, ArrowRight } from 'lucide-react';
import { useAppState, mapApiNode, mapApiEdge, type KGNode } from '../../store';
import { api, ApiError } from '../../api';
import { TYPE_COLORS } from '../../mock-data';
const ENTITY_TYPES_OPTIONS = ['全部类型', 'TECHNOLOGY', 'CONCEPT', 'PERSON', 'ORGANIZATION', 'LOCATION'];
export function SearchPage() {
const { nodes, edges, getNeighbors } = useAppState();
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const [query, setQuery] = useState(searchParams.get('q') || '');
const [typeFilter, setTypeFilter] = useState(searchParams.get('type') || '全部类型');
const [activeTab, setActiveTab] = useState<'entity' | 'path' | 'graph'>(
(searchParams.get('tab') as 'entity' | 'path' | 'graph') || 'entity'
);
const [results, setResults] = useState<KGNode[]>([]);
const [selectedResult, setSelectedResult] = useState<KGNode | null>(null);
const [hasSearched, setHasSearched] = useState(false);
const [searching, setSearching] = useState(false);
// Path search
const [pathFrom, setPathFrom] = useState('');
const [pathTo, setPathTo] = useState('');
const [maxHops, setMaxHops] = useState(3);
const [pathResult, setPathResult] = useState<KGNode[] | null>(null);
const [pathSearching, setPathSearching] = useState(false);
const [pathError, setPathError] = useState('');
// Graph search
const [graphQuery, setGraphQuery] = useState('');
const [includeNeighbors, setIncludeNeighbors] = useState(true);
const [graphResults, setGraphResults] = useState<KGNode[]>([]);
const [graphSearching, setGraphSearching] = useState(false);
const previewRef = useRef<SVGSVGElement>(null);
// Auto-search from URL
useEffect(() => {
const q = searchParams.get('q');
if (q) {
setQuery(q);
doEntitySearch(q, typeFilter);
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
// ── Entity Search ─────────────────────────────────────────────────────────
const doEntitySearch = async (q: string, type: string) => {
if (!q.trim()) return;
setSearching(true);
setHasSearched(true);
try {
const res = await api.searchEntities(q.trim(), type !== '全部类型' ? type : undefined, 50);
const mapped = res.items.map(mapApiNode);
setResults(mapped);
setSelectedResult(mapped[0] ?? null);
setSearchParams({ q: q.trim(), type, tab: 'entity' });
} catch {
setResults([]);
} finally {
setSearching(false);
}
};
const handleEntitySearch = () => doEntitySearch(query, typeFilter);
// ── Preview graph for selected entity ────────────────────────────────────
useEffect(() => {
if (!selectedResult || !previewRef.current) return;
const svg = d3.select(previewRef.current);
svg.selectAll('*').remove();
// Use local KG for preview (already loaded)
const { nodes: neighbors, edges: nEdges } = getNeighbors(selectedResult.id);
const allNodes = [selectedResult, ...neighbors];
const width = 380;
const height = 280;
svg.attr('width', width).attr('height', height);
const g = svg.append('g');
const simNodes = allNodes.map(n => ({ ...n, x: width / 2 + (Math.random() - 0.5) * 100, y: height / 2 + (Math.random() - 0.5) * 100 }));
const simEdges = nEdges.map(e => ({ ...e }));
const simulation = d3.forceSimulation(simNodes)
.force('link', d3.forceLink(simEdges).id((d: any) => d.id).distance(50).strength(0.5))
.force('charge', d3.forceManyBody().strength(-80))
.force('center', d3.forceCenter(width / 2, height / 2))
.alphaDecay(0.05);
const link = g.selectAll('line').data(simEdges).join('line')
.attr('stroke', '#30363d').attr('stroke-width', 1).attr('stroke-opacity', 0.4);
const node = g.selectAll('circle').data(simNodes).join('circle')
.attr('r', (d: any) => d.id === selectedResult.id ? 8 : 5)
.attr('fill', (d: any) => TYPE_COLORS[d.type] ?? '#8b949e')
.attr('stroke', (d: any) => d.id === selectedResult.id ? '#fff' : '#0f1117')
.attr('stroke-width', (d: any) => d.id === selectedResult.id ? 2 : 1);
g.selectAll('text').data(simNodes.filter(n => n.id === selectedResult.id || n.degree >= 10)).join('text')
.text((d: any) => d.name).attr('font-size', 9).attr('fill', 'var(--text-3)')
.attr('text-anchor', 'middle').attr('dy', -12).attr('pointer-events', 'none');
simulation.on('tick', () => {
link.attr('x1', (d: any) => d.source.x).attr('y1', (d: any) => d.source.y)
.attr('x2', (d: any) => d.target.x).attr('y2', (d: any) => d.target.y);
node.attr('cx', (d: any) => d.x).attr('cy', (d: any) => d.y);
});
return () => simulation.stop();
}, [selectedResult, getNeighbors]);
// ── Path Search ───────────────────────────────────────────────────────────
const handlePathSearch = async () => {
if (!pathFrom.trim() || !pathTo.trim()) return;
setPathError('');
setPathResult(null);
// Resolve names to node IDs from local KG
const fromNode = nodes.find(n => n.name.toLowerCase().includes(pathFrom.toLowerCase()));
const toNode = nodes.find(n => n.name.toLowerCase().includes(pathTo.toLowerCase()));
if (!fromNode) { setPathError(`未找到起点实体"${pathFrom}",请检查名称是否正确`); return; }
if (!toNode) { setPathError(`未找到终点实体"${pathTo}",请检查名称是否正确`); return; }
setPathSearching(true);
try {
const res = await api.searchPath(fromNode.id, toNode.id, maxHops);
if (!res.paths || res.paths.length === 0) {
setPathResult([]);
} else {
// Use the shortest path (first result)
const firstPath = res.paths[0];
const pathNodes = firstPath.nodes
.map(n => {
const local = nodes.find(ln => ln.id === n.id);
return local ?? { id: n.id, name: n.name, type: n.type as KGNode['type'], page: 0, confidence: 'match_exact' as const, degree: 0, centrality: 0, doc_id: '' };
});
setPathResult(pathNodes);
}
} catch (err) {
if (err instanceof ApiError && err.code === 3001) {
setPathResult([]);
} else {
setPathError(err instanceof ApiError ? err.message : '路径查找失败');
}
} finally {
setPathSearching(false);
}
};
// ── Graph Search ──────────────────────────────────────────────────────────
const handleGraphSearch = async () => {
if (!graphQuery.trim()) return;
setGraphSearching(true);
try {
const res = await api.searchGraph(graphQuery.trim(), includeNeighbors);
setGraphResults(res.matched_nodes.map(mapApiNode));
} catch {
setGraphResults([]);
} finally {
setGraphSearching(false);
}
};
return (
<div className="p-6" style={{ maxWidth: 1200, margin: '0 auto' }}>
<h1 className="mb-6" style={{ color: 'var(--text-1)', fontSize: 20, fontWeight: 600 }}></h1>
{/* Search Header */}
<div className="flex gap-3 mb-4">
<div className="relative flex-1">
<Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'var(--text-4)' }} />
<input
value={query}
onChange={e => setQuery(e.target.value)}
onKeyDown={e => e.key === 'Enter' && handleEntitySearch()}
placeholder="搜索实体..."
className="w-full pl-9 pr-4 py-2.5 rounded-lg outline-none"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-1)', fontSize: 14 }}
/>
</div>
<select
value={typeFilter}
onChange={e => setTypeFilter(e.target.value)}
className="px-3 py-2 rounded-lg cursor-pointer"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 13 }}
>
{ENTITY_TYPES_OPTIONS.map(t => <option key={t}>{t}</option>)}
</select>
<button
onClick={handleEntitySearch}
disabled={searching}
className="flex items-center gap-2 px-5 py-2 rounded-lg cursor-pointer"
style={{ background: 'var(--green-btn)', color: '#fff', fontSize: 13, fontWeight: 500, border: 'none', opacity: searching ? 0.7 : 1 }}
>
<Search size={14} /> {searching ? '搜索中...' : '搜索'}
</button>
</div>
{/* Tabs */}
<div className="flex gap-0 mb-6" style={{ borderBottom: '1px solid var(--border-main)' }}>
{([
{ key: 'entity' as const, label: '实体搜索' },
{ key: 'path' as const, label: '路径搜索' },
{ key: 'graph' as const, label: '图谱搜索' },
]).map(tab => (
<button
key={tab.key}
onClick={() => setActiveTab(tab.key)}
className="px-4 py-2.5 cursor-pointer relative"
style={{
background: 'transparent', border: 'none',
color: activeTab === tab.key ? 'var(--blue)' : 'var(--text-3)',
fontSize: 13, fontWeight: activeTab === tab.key ? 600 : 400,
}}
>
{tab.label}
{activeTab === tab.key && (
<div className="absolute bottom-0 left-0 right-0 h-0.5" style={{ background: 'var(--blue)' }} />
)}
</button>
))}
</div>
{/* Entity Search Tab */}
{activeTab === 'entity' && (
<div className="flex gap-4">
<div className="flex-1" style={{ minWidth: 0 }}>
{!hasSearched ? (
<div className="flex flex-col items-center justify-center py-16 gap-3">
<Search size={36} style={{ color: 'var(--text-4)' }} />
<span style={{ color: 'var(--text-3)', fontSize: 14 }}></span>
</div>
) : searching ? (
<div className="flex flex-col items-center justify-center py-16 gap-3">
<span style={{ color: 'var(--text-3)', fontSize: 14 }}>...</span>
</div>
) : results.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 gap-3">
<span style={{ color: 'var(--text-3)', fontSize: 14 }}> "{query}"</span>
<button
onClick={() => navigate('/graph')}
className="flex items-center gap-1 cursor-pointer"
style={{ color: 'var(--blue)', fontSize: 13, background: 'none', border: 'none' }}
>
<ExternalLink size={12} />
</button>
</div>
) : (
<div className="flex flex-col gap-2">
<div style={{ color: 'var(--text-4)', fontSize: 12, marginBottom: 4 }}>
{results.length}
</div>
{results.map(r => (
<button
key={r.id}
onClick={() => setSelectedResult(r)}
className="flex items-center gap-3 p-3 rounded-lg cursor-pointer text-left w-full"
style={{
background: selectedResult?.id === r.id ? 'var(--bg-s2)' : 'var(--bg-s1)',
border: `1px solid ${selectedResult?.id === r.id ? 'var(--blue)' : 'var(--border-main)'}`,
}}
>
<span className="inline-block w-3 h-3 rounded-full flex-shrink-0" style={{ background: TYPE_COLORS[r.type] ?? '#8b949e' }} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-0.5">
<span style={{ color: 'var(--text-1)', fontSize: 14, fontWeight: 500 }}>{r.name}</span>
<span className="px-1.5 py-0.5 rounded" style={{ fontSize: 10, fontWeight: 600, background: `${TYPE_COLORS[r.type] ?? '#8b949e'}20`, color: TYPE_COLORS[r.type] ?? '#8b949e' }}>
{r.type}
</span>
</div>
<div className="flex items-center gap-3" style={{ fontSize: 11, color: 'var(--text-4)' }}>
<span> {r.page}</span>
<span> {r.degree}</span>
<span>{r.confidence.replace('match_', '')}</span>
</div>
</div>
<div className="flex items-center gap-1.5 flex-shrink-0">
<button
onClick={e => { e.stopPropagation(); navigate(`/graph?node=${r.id}`); }}
className="px-2 py-1 rounded cursor-pointer"
style={{ fontSize: 10, background: 'rgba(88,166,255,0.1)', color: 'var(--blue)', border: 'none' }}
>
</button>
<button
onClick={e => { e.stopPropagation(); navigate(`/chat?q=${encodeURIComponent(`What is ${r.name}`)}`); }}
className="px-2 py-1 rounded cursor-pointer"
style={{ fontSize: 10, background: 'rgba(88,166,255,0.1)', color: 'var(--blue)', border: 'none' }}
>
<MessageSquare size={10} />
</button>
</div>
</button>
))}
</div>
)}
</div>
{/* Preview Graph */}
{selectedResult && (
<div
className="rounded-lg p-3 flex-shrink-0"
style={{ width: 400, background: 'var(--bg-s1)', border: '1px solid var(--border-main)' }}
>
<div className="flex items-center justify-between mb-2">
<span style={{ color: 'var(--text-1)', fontSize: 13, fontWeight: 600 }}>
: {selectedResult.name}
</span>
<span style={{ fontSize: 11, color: 'var(--text-4)' }}>1 </span>
</div>
<svg ref={previewRef} className="w-full" style={{ height: 280, background: 'var(--bg-base)', borderRadius: 6 }} />
</div>
)}
</div>
)}
{/* Path Search Tab */}
{activeTab === 'path' && (
<div>
<div className="flex items-end gap-3 mb-6">
<div className="flex-1">
<label style={{ fontSize: 12, color: 'var(--text-3)', display: 'block', marginBottom: 4 }}></label>
<input
value={pathFrom}
onChange={e => setPathFrom(e.target.value)}
placeholder="如: GraphRAG"
className="w-full px-3 py-2 rounded-md outline-none"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-1)', fontSize: 13 }}
/>
</div>
<div className="flex-1">
<label style={{ fontSize: 12, color: 'var(--text-3)', display: 'block', marginBottom: 4 }}></label>
<input
value={pathTo}
onChange={e => setPathTo(e.target.value)}
placeholder="如: LLM"
className="w-full px-3 py-2 rounded-md outline-none"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-1)', fontSize: 13 }}
/>
</div>
<div>
<label style={{ fontSize: 12, color: 'var(--text-3)', display: 'block', marginBottom: 4 }}></label>
<select
value={maxHops}
onChange={e => setMaxHops(Number(e.target.value))}
className="px-3 py-2 rounded-md cursor-pointer"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-2)', fontSize: 13 }}
>
{[1, 2, 3, 4, 5].map(n => <option key={n} value={n}>{n}</option>)}
</select>
</div>
<button
onClick={handlePathSearch}
disabled={pathSearching}
className="flex items-center gap-2 px-4 py-2 rounded-md cursor-pointer"
style={{ background: 'var(--green-btn)', color: '#fff', fontSize: 13, border: 'none', opacity: pathSearching ? 0.7 : 1 }}
>
{pathSearching ? '查找中...' : '查找路径'}
</button>
</div>
{pathError && (
<div className="mb-4 px-4 py-2 rounded-md" style={{ background: 'rgba(248,81,73,0.1)', border: '1px solid rgba(248,81,73,0.3)', color: 'var(--red)', fontSize: 13 }}>
{pathError}
</div>
)}
{pathResult !== null && (
pathResult.length === 0 ? (
<div className="text-center py-12" style={{ color: 'var(--text-3)', fontSize: 14 }}>
{maxHops}
</div>
) : (
<div className="flex items-center gap-2 flex-wrap p-6 rounded-lg" style={{ background: 'var(--bg-s1)', border: '1px solid var(--border-main)' }}>
<span style={{ fontSize: 12, color: 'var(--text-4)', marginBottom: 8, display: 'block', width: '100%' }}>
{pathResult.length - 1}
</span>
{pathResult.map((n, i) => (
<React.Fragment key={n.id}>
<button
onClick={() => navigate(`/graph?node=${n.id}`)}
className="flex items-center gap-2 px-3 py-2 rounded-lg cursor-pointer"
style={{ background: 'var(--bg-s2)', border: `1px solid ${TYPE_COLORS[n.type] ?? '#8b949e'}40` }}
>
<span className="w-2.5 h-2.5 rounded-full" style={{ background: TYPE_COLORS[n.type] ?? '#8b949e' }} />
<span style={{ color: 'var(--text-1)', fontSize: 13 }}>{n.name}</span>
<span style={{ fontSize: 10, color: TYPE_COLORS[n.type] ?? '#8b949e' }}>{n.type}</span>
</button>
{i < pathResult.length - 1 && (
<ArrowRight size={16} style={{ color: 'var(--text-4)' }} />
)}
</React.Fragment>
))}
</div>
)
)}
</div>
)}
{/* Graph Search Tab */}
{activeTab === 'graph' && (
<div>
<div className="flex items-end gap-3 mb-6">
<div className="flex-1">
<input
value={graphQuery}
onChange={e => setGraphQuery(e.target.value)}
onKeyDown={e => e.key === 'Enter' && handleGraphSearch()}
placeholder="搜索关键词..."
className="w-full px-3 py-2 rounded-md outline-none"
style={{ background: 'var(--bg-s2)', border: '1px solid var(--border-main)', color: 'var(--text-1)', fontSize: 13 }}
/>
</div>
<label className="flex items-center gap-2 cursor-pointer px-3 py-2">
<input
type="checkbox"
checked={includeNeighbors}
onChange={e => setIncludeNeighbors(e.target.checked)}
style={{ accentColor: 'var(--blue)' }}
/>
<span style={{ fontSize: 12, color: 'var(--text-2)' }}></span>
</label>
<button
onClick={handleGraphSearch}
disabled={graphSearching}
className="flex items-center gap-2 px-4 py-2 rounded-md cursor-pointer"
style={{ background: 'var(--green-btn)', color: '#fff', fontSize: 13, border: 'none', opacity: graphSearching ? 0.7 : 1 }}
>
{graphSearching ? '搜索中...' : '搜索'}
</button>
</div>
{graphResults.length > 0 && (
<>
<div style={{ color: 'var(--text-4)', fontSize: 12, marginBottom: 8 }}>
{graphResults.length}
</div>
<div className="flex flex-wrap gap-2">
{graphResults.map(n => (
<button
key={n.id}
onClick={() => navigate(`/graph?node=${n.id}`)}
className="flex items-center gap-2 px-3 py-1.5 rounded-full cursor-pointer"
style={{ background: `${TYPE_COLORS[n.type] ?? '#8b949e'}15`, border: `1px solid ${TYPE_COLORS[n.type] ?? '#8b949e'}40`, color: TYPE_COLORS[n.type] ?? '#8b949e', fontSize: 12 }}
>
<span className="w-2 h-2 rounded-full" style={{ background: TYPE_COLORS[n.type] ?? '#8b949e' }} />
{n.name}
</button>
))}
</div>
</>
)}
{graphSearching === false && graphQuery && graphResults.length === 0 && (
<div className="text-center py-12" style={{ color: 'var(--text-3)', fontSize: 14 }}>
"{graphQuery}"
</div>
)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,66 @@
"use client";
import * as React from "react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { ChevronDownIcon } from "lucide-react";
import { cn } from "./utils";
function Accordion({
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
}
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
);
}
function AccordionTrigger({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className,
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
);
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
);
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };

View File

@@ -0,0 +1,157 @@
"use client";
import * as React from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { cn } from "./utils";
import { buttonVariants } from "./button";
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
);
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
);
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
);
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
);
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
);
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
);
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};

View File

@@ -0,0 +1,66 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "./utils";
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
);
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className,
)}
{...props}
/>
);
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className,
)}
{...props}
/>
);
}
export { Alert, AlertTitle, AlertDescription };

View File

@@ -0,0 +1,11 @@
"use client";
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
function AspectRatio({
...props
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />;
}
export { AspectRatio };

View File

@@ -0,0 +1,53 @@
"use client";
import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "./utils";
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-10 shrink-0 overflow-hidden rounded-full",
className,
)}
{...props}
/>
);
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
);
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className,
)}
{...props}
/>
);
}
export { Avatar, AvatarImage, AvatarFallback };

View File

@@ -0,0 +1,46 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "./utils";
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span";
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };

View File

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

View File

@@ -0,0 +1,58 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "./utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9 rounded-md",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants };

View File

@@ -0,0 +1,75 @@
"use client";
import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "./utils";
import { buttonVariants } from "./button";
function Calendar({
className,
classNames,
showOutsideDays = true,
...props
}: React.ComponentProps<typeof DayPicker>) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row gap-2",
month: "flex flex-col gap-4",
caption: "flex justify-center pt-1 relative items-center w-full",
caption_label: "text-sm font-medium",
nav: "flex items-center gap-1",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"size-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-x-1",
head_row: "flex",
head_cell:
"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: cn(
"relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-range-end)]:rounded-r-md",
props.mode === "range"
? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
: "[&:has([aria-selected])]:rounded-md",
),
day: cn(
buttonVariants({ variant: "ghost" }),
"size-8 p-0 font-normal aria-selected:opacity-100",
),
day_range_start:
"day-range-start aria-selected:bg-primary aria-selected:text-primary-foreground",
day_range_end:
"day-range-end aria-selected:bg-primary aria-selected:text-primary-foreground",
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: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: ({ className, ...props }) => (
<ChevronLeft className={cn("size-4", className)} {...props} />
),
IconRight: ({ className, ...props }) => (
<ChevronRight className={cn("size-4", className)} {...props} />
),
}}
{...props}
/>
);
}
export { Calendar };

View File

@@ -0,0 +1,92 @@
import * as React from "react";
import { cn } from "./utils";
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",
className,
)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className,
)}
{...props}
/>
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<h4
data-slot="card-title"
className={cn("leading-none", className)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<p
data-slot="card-description"
className={cn("text-muted-foreground", className)}
{...props}
/>
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className,
)}
{...props}
/>
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6 [&:last-child]:pb-6", className)}
{...props}
/>
);
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 pb-6 [.border-t]:pt-6", className)}
{...props}
/>
);
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
};

View File

@@ -0,0 +1,241 @@
"use client";
import * as React from "react";
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { cn } from "./utils";
import { Button } from "./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;
}
function Carousel({
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
}: React.ComponentProps<"div"> & CarouselProps) {
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
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
}
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
const { carouselRef, orientation } = useCarousel();
return (
<div
ref={carouselRef}
className="overflow-hidden"
data-slot="carousel-content"
>
<div
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className,
)}
{...props}
/>
</div>
);
}
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
const { orientation } = useCarousel();
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className,
)}
{...props}
/>
);
}
function CarouselPrevious({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -left-12 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft />
<span className="sr-only">Previous slide</span>
</Button>
);
}
function CarouselNext({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -right-12 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight />
<span className="sr-only">Next slide</span>
</Button>
);
}
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
};

View File

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

View File

@@ -0,0 +1,33 @@
"use client";
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
function Collapsible({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return (
<CollapsiblePrimitive.CollapsibleTrigger
data-slot="collapsible-trigger"
{...props}
/>
);
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return (
<CollapsiblePrimitive.CollapsibleContent
data-slot="collapsible-content"
{...props}
/>
);
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent };

View File

@@ -0,0 +1,177 @@
"use client";
import * as React from "react";
import { Command as CommandPrimitive } from "cmdk";
import { SearchIcon } from "lucide-react";
import { cn } from "./utils";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "./dialog";
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className,
)}
{...props}
/>
);
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string;
description?: string;
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent className="overflow-hidden p-0">
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[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>
);
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
/>
</div>
);
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className,
)}
{...props}
/>
);
}
function CommandEmpty({
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
);
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
className,
)}
{...props}
/>
);
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
);
}
function CommandItem({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};

View File

@@ -0,0 +1,252 @@
"use client";
import * as React from "react";
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "./utils";
function ContextMenu({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />;
}
function ContextMenuTrigger({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
return (
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
);
}
function ContextMenuGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
return (
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
);
}
function ContextMenuPortal({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
return (
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
);
}
function ContextMenuSub({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />;
}
function ContextMenuRadioGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
return (
<ContextMenuPrimitive.RadioGroup
data-slot="context-menu-radio-group"
{...props}
/>
);
}
function ContextMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean;
}) {
return (
<ContextMenuPrimitive.SubTrigger
data-slot="context-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</ContextMenuPrimitive.SubTrigger>
);
}
function ContextMenuSubContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
return (
<ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content"
className={cn(
"bg-popover 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 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className,
)}
{...props}
/>
);
}
function ContextMenuContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
return (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
data-slot="context-menu-content"
className={cn(
"bg-popover 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 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className,
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
);
}
function ContextMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<ContextMenuPrimitive.Item
data-slot="context-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function ContextMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
return (
<ContextMenuPrimitive.CheckboxItem
data-slot="context-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
);
}
function ContextMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
return (
<ContextMenuPrimitive.RadioItem
data-slot="context-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
);
}
function ContextMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
inset?: boolean;
}) {
return (
<ContextMenuPrimitive.Label
data-slot="context-menu-label"
data-inset={inset}
className={cn(
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props}
/>
);
}
function ContextMenuSeparator({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
return (
<ContextMenuPrimitive.Separator
data-slot="context-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function ContextMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="context-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
};

View File

@@ -0,0 +1,135 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react";
import { cn } from "./utils";
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function DialogContent({
className,
children,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};

View File

@@ -0,0 +1,132 @@
"use client";
import * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "./utils";
function Drawer({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
}
function DrawerTrigger({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
}
function DrawerPortal({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
}
function DrawerClose({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
}
function DrawerOverlay({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
return (
<DrawerPrimitive.Overlay
data-slot="drawer-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function DrawerContent({
className,
children,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
return (
<DrawerPortal data-slot="drawer-portal">
<DrawerOverlay />
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
"group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
className,
)}
{...props}
>
<div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
);
}
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
);
}
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
);
}
function DrawerTitle({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
);
}
function DrawerDescription({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
return (
<DrawerPrimitive.Description
data-slot="drawer-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
};

View File

@@ -0,0 +1,257 @@
"use client";
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "./utils";
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
);
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
);
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover 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 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
);
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
);
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
);
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
);
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
);
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props}
/>
);
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
);
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover 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 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className,
)}
{...props}
/>
);
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
};

View File

@@ -0,0 +1,168 @@
"use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { Slot } from "@radix-ui/react-slot";
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form";
import { cn } from "./utils";
import { Label } from "./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 } = useFormContext();
const formState = useFormState({ name: fieldContext.name });
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,
);
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider>
);
}
function FormLabel({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField();
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn("data-[error=true]:text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
);
}
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
return (
<Slot
data-slot="form-control"
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
);
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId } = useFormField();
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message ?? "") : props.children;
if (!body) {
return null;
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn("text-destructive text-sm", className)}
{...props}
>
{body}
</p>
);
}
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
};

View File

@@ -0,0 +1,44 @@
"use client";
import * as React from "react";
import * as HoverCardPrimitive from "@radix-ui/react-hover-card";
import { cn } from "./utils";
function HoverCard({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />;
}
function HoverCardTrigger({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
return (
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
);
}
function HoverCardContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
return (
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
<HoverCardPrimitive.Content
data-slot="hover-card-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover 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 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className,
)}
{...props}
/>
</HoverCardPrimitive.Portal>
);
}
export { HoverCard, HoverCardTrigger, HoverCardContent };

View File

@@ -0,0 +1,77 @@
"use client";
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { MinusIcon } from "lucide-react";
import { cn } from "./utils";
function InputOTP({
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput> & {
containerClassName?: string;
}) {
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn(
"flex items-center gap-2 has-disabled:opacity-50",
containerClassName,
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
);
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-otp-group"
className={cn("flex items-center gap-1", className)}
{...props}
/>
);
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & {
index: number;
}) {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {};
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm bg-input-background transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
className,
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
</div>
);
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };

View File

@@ -0,0 +1,21 @@
import * as React from "react";
import { cn } from "./utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className,
)}
{...props}
/>
);
}
export { Input };

View File

@@ -0,0 +1,24 @@
"use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cn } from "./utils";
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className,
)}
{...props}
/>
);
}
export { Label };

View File

@@ -0,0 +1,276 @@
"use client";
import * as React from "react";
import * as MenubarPrimitive from "@radix-ui/react-menubar";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "./utils";
function Menubar({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
return (
<MenubarPrimitive.Root
data-slot="menubar"
className={cn(
"bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
className,
)}
{...props}
/>
);
}
function MenubarMenu({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />;
}
function MenubarGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />;
}
function MenubarPortal({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />;
}
function MenubarRadioGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
return (
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
);
}
function MenubarTrigger({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
return (
<MenubarPrimitive.Trigger
data-slot="menubar-trigger"
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
className,
)}
{...props}
/>
);
}
function MenubarContent({
className,
align = "start",
alignOffset = -4,
sideOffset = 8,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
return (
<MenubarPortal>
<MenubarPrimitive.Content
data-slot="menubar-content"
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground 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 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
className,
)}
{...props}
/>
</MenubarPortal>
);
}
function MenubarItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<MenubarPrimitive.Item
data-slot="menubar-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function MenubarCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
return (
<MenubarPrimitive.CheckboxItem
data-slot="menubar-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
);
}
function MenubarRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
return (
<MenubarPrimitive.RadioItem
data-slot="menubar-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
);
}
function MenubarLabel({
className,
inset,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
inset?: boolean;
}) {
return (
<MenubarPrimitive.Label
data-slot="menubar-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props}
/>
);
}
function MenubarSeparator({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
return (
<MenubarPrimitive.Separator
data-slot="menubar-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function MenubarShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="menubar-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
function MenubarSub({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />;
}
function MenubarSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean;
}) {
return (
<MenubarPrimitive.SubTrigger
data-slot="menubar-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
);
}
function MenubarSubContent({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
return (
<MenubarPrimitive.SubContent
data-slot="menubar-sub-content"
className={cn(
"bg-popover 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 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className,
)}
{...props}
/>
);
}
export {
Menubar,
MenubarPortal,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarGroup,
MenubarSeparator,
MenubarLabel,
MenubarItem,
MenubarShortcut,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarSub,
MenubarSubTrigger,
MenubarSubContent,
};

View File

@@ -0,0 +1,168 @@
import * as React from "react";
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu";
import { cva } from "class-variance-authority";
import { ChevronDownIcon } from "lucide-react";
import { cn } from "./utils";
function NavigationMenu({
className,
children,
viewport = true,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
viewport?: boolean;
}) {
return (
<NavigationMenuPrimitive.Root
data-slot="navigation-menu"
data-viewport={viewport}
className={cn(
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
className,
)}
{...props}
>
{children}
{viewport && <NavigationMenuViewport />}
</NavigationMenuPrimitive.Root>
);
}
function NavigationMenuList({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
return (
<NavigationMenuPrimitive.List
data-slot="navigation-menu-list"
className={cn(
"group flex flex-1 list-none items-center justify-center gap-1",
className,
)}
{...props}
/>
);
}
function NavigationMenuItem({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
return (
<NavigationMenuPrimitive.Item
data-slot="navigation-menu-item"
className={cn("relative", className)}
{...props}
/>
);
}
const navigationMenuTriggerStyle = cva(
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1",
);
function NavigationMenuTrigger({
className,
children,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
return (
<NavigationMenuPrimitive.Trigger
data-slot="navigation-menu-trigger"
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDownIcon
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
);
}
function NavigationMenuContent({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
return (
<NavigationMenuPrimitive.Content
data-slot="navigation-menu-content"
className={cn(
"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 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
className,
)}
{...props}
/>
);
}
function NavigationMenuViewport({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
return (
<div
className={cn(
"absolute top-full left-0 isolate z-50 flex justify-center",
)}
>
<NavigationMenuPrimitive.Viewport
data-slot="navigation-menu-viewport"
className={cn(
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
className,
)}
{...props}
/>
</div>
);
}
function NavigationMenuLink({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
return (
<NavigationMenuPrimitive.Link
data-slot="navigation-menu-link"
className={cn(
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function NavigationMenuIndicator({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
return (
<NavigationMenuPrimitive.Indicator
data-slot="navigation-menu-indicator"
className={cn(
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
className,
)}
{...props}
>
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
</NavigationMenuPrimitive.Indicator>
);
}
export {
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
navigationMenuTriggerStyle,
};

View File

@@ -0,0 +1,127 @@
import * as React from "react";
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from "lucide-react";
import { cn } from "./utils";
import { Button, buttonVariants } from "./button";
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
);
}
function PaginationContent({
className,
...props
}: React.ComponentProps<"ul">) {
return (
<ul
data-slot="pagination-content"
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
);
}
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
return <li data-slot="pagination-item" {...props} />;
}
type PaginationLinkProps = {
isActive?: boolean;
} & Pick<React.ComponentProps<typeof Button>, "size"> &
React.ComponentProps<"a">;
function PaginationLink({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) {
return (
<a
aria-current={isActive ? "page" : undefined}
data-slot="pagination-link"
data-active={isActive}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className,
)}
{...props}
/>
);
}
function PaginationPrevious({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
{...props}
>
<ChevronLeftIcon />
<span className="hidden sm:block">Previous</span>
</PaginationLink>
);
}
function PaginationNext({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
{...props}
>
<span className="hidden sm:block">Next</span>
<ChevronRightIcon />
</PaginationLink>
);
}
function PaginationEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
aria-hidden
data-slot="pagination-ellipsis"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontalIcon className="size-4" />
<span className="sr-only">More pages</span>
</span>
);
}
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
};

View File

@@ -0,0 +1,48 @@
"use client";
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "./utils";
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover 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 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
);
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };

View File

@@ -0,0 +1,31 @@
"use client";
import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "./utils";
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className,
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
);
}
export { Progress };

View File

@@ -0,0 +1,45 @@
"use client";
import * as React from "react";
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { CircleIcon } from "lucide-react";
import { cn } from "./utils";
function RadioGroup({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
return (
<RadioGroupPrimitive.Root
data-slot="radio-group"
className={cn("grid gap-3", className)}
{...props}
/>
);
}
function RadioGroupItem({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
return (
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<RadioGroupPrimitive.Indicator
data-slot="radio-group-indicator"
className="relative flex items-center justify-center"
>
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
}
export { RadioGroup, RadioGroupItem };

View File

@@ -0,0 +1,56 @@
"use client";
import * as React from "react";
import { GripVerticalIcon } from "lucide-react";
import * as ResizablePrimitive from "react-resizable-panels";
import { cn } from "./utils";
function ResizablePanelGroup({
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) {
return (
<ResizablePrimitive.PanelGroup
data-slot="resizable-panel-group"
className={cn(
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
className,
)}
{...props}
/>
);
}
function ResizablePanel({
...props
}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />;
}
function ResizableHandle({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean;
}) {
return (
<ResizablePrimitive.PanelResizeHandle
data-slot="resizable-handle"
className={cn(
"bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden 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="bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border">
<GripVerticalIcon className="size-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
);
}
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };

View File

@@ -0,0 +1,58 @@
"use client";
import * as React from "react";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import { cn } from "./utils";
function ScrollArea({
className,
children,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
);
}
function ScrollBar({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
return (
<ScrollAreaPrimitive.ScrollAreaScrollbar
data-slot="scroll-area-scrollbar"
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent",
className,
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb
data-slot="scroll-area-thumb"
className="bg-border relative flex-1 rounded-full"
/>
</ScrollAreaPrimitive.ScrollAreaScrollbar>
);
}
export { ScrollArea, ScrollBar };

View File

@@ -0,0 +1,189 @@
"use client";
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import {
CheckIcon,
ChevronDownIcon,
ChevronUpIcon,
} from "lucide-react";
import { cn } from "./utils";
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />;
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default";
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-full items-center justify-between gap-2 rounded-md border bg-input-background px-3 py-2 text-sm whitespace-nowrap transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
);
}
function SelectContent({
className,
children,
position = "popper",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover 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 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
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)] scroll-my-1",
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
);
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
);
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className,
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
);
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
);
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
);
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
};

View File

@@ -0,0 +1,28 @@
"use client";
import * as React from "react";
import * as SeparatorPrimitive from "@radix-ui/react-separator";
import { cn } from "./utils";
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator-root"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className,
)}
{...props}
/>
);
}
export { Separator };

View File

@@ -0,0 +1,139 @@
"use client";
import * as React from "react";
import * as SheetPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react";
import { cn } from "./utils";
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function SheetContent({
className,
children,
side = "right",
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left";
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className,
)}
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
);
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
);
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};

View File

@@ -0,0 +1,726 @@
"use client";
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { VariantProps, cva } from "class-variance-authority";
import { PanelLeftIcon } from "lucide-react";
import { useIsMobile } from "./use-mobile";
import { cn } from "./utils";
import { Button } from "./button";
import { Input } from "./input";
import { Separator } from "./separator";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "./sheet";
import { Skeleton } from "./skeleton";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "./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 SidebarContextProps = {
state: "expanded" | "collapsed";
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
setOpenMobile: (open: boolean) => void;
isMobile: boolean;
toggleSidebar: () => void;
};
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.");
}
return context;
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
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<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
);
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className,
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
);
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none";
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className,
)}
{...props}
>
{children}
</div>
);
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
);
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 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)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 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)+(--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"
data-slot="sidebar-inner"
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
);
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar();
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
onClick={(event) => {
onClick?.(event);
toggleSidebar();
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
);
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar();
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className,
)}
{...props}
/>
);
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className,
)}
{...props}
/>
);
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
{...props}
/>
);
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props}
/>
);
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
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}
/>
);
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
);
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div";
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 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}
/>
);
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
);
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
);
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
);
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden 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",
},
},
);
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean;
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button";
const { isMobile, state } = useSidebar();
const button = (
<Comp
data-slot="sidebar-menu-button"
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>
);
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean;
showOnHover?: boolean;
}) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after: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 &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className,
)}
{...props}
/>
);
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-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}
/>
);
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean;
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`;
}, []);
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
);
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
);
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean;
size?: "sm" | "md";
isActive?: boolean;
}) {
const Comp = asChild ? Slot : "a";
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 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",
"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}
/>
);
}
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,13 @@
import { cn } from "./utils";
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
);
}
export { Skeleton };

View File

@@ -0,0 +1,63 @@
"use client";
import * as React from "react";
import * as SliderPrimitive from "@radix-ui/react-slider";
import { cn } from "./utils";
function Slider({
className,
defaultValue,
value,
min = 0,
max = 100,
...props
}: React.ComponentProps<typeof SliderPrimitive.Root>) {
const _values = React.useMemo(
() =>
Array.isArray(value)
? value
: Array.isArray(defaultValue)
? defaultValue
: [min, max],
[value, defaultValue, min, max],
);
return (
<SliderPrimitive.Root
data-slot="slider"
defaultValue={defaultValue}
value={value}
min={min}
max={max}
className={cn(
"relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
className,
)}
{...props}
>
<SliderPrimitive.Track
data-slot="slider-track"
className={cn(
"bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-4 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",
)}
>
<SliderPrimitive.Range
data-slot="slider-range"
className={cn(
"bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",
)}
/>
</SliderPrimitive.Track>
{Array.from({ length: _values.length }, (_, index) => (
<SliderPrimitive.Thumb
data-slot="slider-thumb"
key={index}
className="border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
/>
))}
</SliderPrimitive.Root>
);
}
export { Slider };

View File

@@ -0,0 +1,25 @@
"use client";
import { useTheme } from "next-themes";
import { Toaster as Sonner, ToasterProps } from "sonner";
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
} as React.CSSProperties
}
{...props}
/>
);
};
export { Toaster };

View File

@@ -0,0 +1,31 @@
"use client";
import * as React from "react";
import * as SwitchPrimitive from "@radix-ui/react-switch";
import { cn } from "./utils";
function Switch({
className,
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
return (
<SwitchPrimitive.Root
data-slot="switch"
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-switch-background focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0",
)}
/>
</SwitchPrimitive.Root>
);
}
export { Switch };

View File

@@ -0,0 +1,116 @@
"use client";
import * as React from "react";
import { cn } from "./utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className,
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};

View File

@@ -0,0 +1,66 @@
"use client";
import * as React from "react";
import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cn } from "./utils";
function Tabs({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
);
}
function TabsList({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",
className,
)}
{...props}
/>
);
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
);
}
export { Tabs, TabsList, TabsTrigger, TabsContent };

View File

@@ -0,0 +1,18 @@
import * as React from "react";
import { cn } from "./utils";
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"resize-none border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-input-background px-3 py-2 text-base transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className,
)}
{...props}
/>
);
}
export { Textarea };

View File

@@ -0,0 +1,73 @@
"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 "./utils";
import { toggleVariants } from "./toggle";
const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants>
>({
size: "default",
variant: "default",
});
function ToggleGroup({
className,
variant,
size,
children,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<ToggleGroupPrimitive.Root
data-slot="toggle-group"
data-variant={variant}
data-size={size}
className={cn(
"group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
className,
)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
);
}
function ToggleGroupItem({
className,
children,
variant,
size,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
VariantProps<typeof toggleVariants>) {
const context = React.useContext(ToggleGroupContext);
return (
<ToggleGroupPrimitive.Item
data-slot="toggle-group-item"
data-variant={context.variant || variant}
data-size={context.size || size}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
className,
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
);
}
export { ToggleGroup, ToggleGroupItem };

View File

@@ -0,0 +1,47 @@
"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 "./utils";
const toggleVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-9 px-2 min-w-9",
sm: "h-8 px-1.5 min-w-8",
lg: "h-10 px-2.5 min-w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Toggle({
className,
variant,
size,
...props
}: React.ComponentProps<typeof TogglePrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<TogglePrimitive.Root
data-slot="toggle"
className={cn(toggleVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Toggle, toggleVariants };

View File

@@ -0,0 +1,61 @@
"use client";
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "./utils";
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
);
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
);
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-primary text-primary-foreground 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 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className,
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
);
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };

View File

@@ -0,0 +1,21 @@
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,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

View File

@@ -0,0 +1,286 @@
// Mock data for GraphRAG Studio
export interface KGNode {
id: string;
name: string;
type: 'TECHNOLOGY' | 'CONCEPT' | 'PERSON' | 'ORGANIZATION' | 'LOCATION';
page: number;
confidence: 'match_exact' | 'match_greater' | 'match_lesser' | 'match_fuzzy';
degree: number;
centrality: number;
doc_id: string;
description?: string;
}
export interface KGEdge {
id: string;
source: string;
target: string;
relation: string;
weight: number;
}
export interface Document {
id: string;
filename: string;
format: string;
pages: number;
status: 'uploaded' | 'indexing' | 'indexed' | 'failed';
upload_date: string;
job_id?: string;
index_stage?: string;
progress?: number;
error?: string;
result?: {
nodes: number;
edges: number;
pages: number;
extractions: number;
duration: number;
};
}
export interface ChatMessage {
id: string;
role: 'human' | 'ai';
content: string;
timestamp: string;
toolCalls?: ToolCall[];
citedNodes?: { id: string; name: string; type: string }[];
duration?: number;
}
export interface ToolCall {
step: number;
tool: string;
input: string;
output: string;
}
export interface HistoryItem {
id: string;
question: string;
timestamp: string;
group: '今天' | '昨天' | '更早';
}
// Entity type colors
export const TYPE_COLORS: Record<string, string> = {
TECHNOLOGY: '#58a6ff',
CONCEPT: '#bc8cff',
PERSON: '#3fb950',
ORGANIZATION: '#ff7b72',
LOCATION: '#ffa657',
};
// Mock KG Nodes
export const mockNodes: KGNode[] = [
{ id: 'n1', name: 'GraphRAG', type: 'TECHNOLOGY', page: 0, confidence: 'match_exact', degree: 39, centrality: 0.92, doc_id: 'd1', description: 'A knowledge graph enhanced retrieval-augmented generation system that combines structured graph data with LLM capabilities.' },
{ id: 'n2', name: 'Knowledge Graph', type: 'CONCEPT', page: 1, confidence: 'match_exact', degree: 35, centrality: 0.88, doc_id: 'd1', description: 'A structured representation of real-world entities and their relationships.' },
{ id: 'n3', name: 'LLM', type: 'TECHNOLOGY', page: 0, confidence: 'match_exact', degree: 28, centrality: 0.85, doc_id: 'd1', description: 'Large Language Models - neural networks trained on vast text corpora.' },
{ id: 'n4', name: 'RAG', type: 'TECHNOLOGY', page: 1, confidence: 'match_exact', degree: 24, centrality: 0.82, doc_id: 'd1', description: 'Retrieval-Augmented Generation - combining retrieval with generation.' },
{ id: 'n5', name: 'Entity Extraction', type: 'CONCEPT', page: 2, confidence: 'match_exact', degree: 18, centrality: 0.72, doc_id: 'd1' },
{ id: 'n6', name: 'DeepSeek', type: 'TECHNOLOGY', page: 3, confidence: 'match_exact', degree: 15, centrality: 0.68, doc_id: 'd1' },
{ id: 'n7', name: 'LangChain', type: 'TECHNOLOGY', page: 2, confidence: 'match_exact', degree: 14, centrality: 0.65, doc_id: 'd1' },
{ id: 'n8', name: 'Vector Search', type: 'CONCEPT', page: 1, confidence: 'match_greater', degree: 12, centrality: 0.60, doc_id: 'd1' },
{ id: 'n9', name: 'Transformer', type: 'TECHNOLOGY', page: 3, confidence: 'match_exact', degree: 20, centrality: 0.78, doc_id: 'd2' },
{ id: 'n10', name: 'Attention Mechanism', type: 'CONCEPT', page: 2, confidence: 'match_exact', degree: 16, centrality: 0.70, doc_id: 'd2' },
{ id: 'n11', name: 'BERT', type: 'TECHNOLOGY', page: 1, confidence: 'match_exact', degree: 13, centrality: 0.62, doc_id: 'd2' },
{ id: 'n12', name: 'GPT', type: 'TECHNOLOGY', page: 0, confidence: 'match_exact', degree: 22, centrality: 0.80, doc_id: 'd2' },
{ id: 'n13', name: 'Microsoft Research', type: 'ORGANIZATION', page: 0, confidence: 'match_exact', degree: 8, centrality: 0.45, doc_id: 'd1' },
{ id: 'n14', name: 'OpenAI', type: 'ORGANIZATION', page: 1, confidence: 'match_exact', degree: 10, centrality: 0.52, doc_id: 'd2' },
{ id: 'n15', name: 'ReAct Framework', type: 'CONCEPT', page: 3, confidence: 'match_exact', degree: 9, centrality: 0.48, doc_id: 'd1' },
{ id: 'n16', name: 'MinerU', type: 'TECHNOLOGY', page: 2, confidence: 'match_exact', degree: 7, centrality: 0.40, doc_id: 'd1' },
{ id: 'n17', name: 'NetworkX', type: 'TECHNOLOGY', page: 3, confidence: 'match_greater', degree: 6, centrality: 0.35, doc_id: 'd1' },
{ id: 'n18', name: 'Prompt Engineering', type: 'CONCEPT', page: 2, confidence: 'match_exact', degree: 11, centrality: 0.55, doc_id: 'd2' },
{ id: 'n19', name: 'Semantic Search', type: 'CONCEPT', page: 1, confidence: 'match_exact', degree: 14, centrality: 0.64, doc_id: 'd1' },
{ id: 'n20', name: 'NLP', type: 'CONCEPT', page: 0, confidence: 'match_exact', degree: 25, centrality: 0.83, doc_id: 'd2' },
{ id: 'n21', name: 'Fine-tuning', type: 'CONCEPT', page: 3, confidence: 'match_greater', degree: 10, centrality: 0.50, doc_id: 'd2' },
{ id: 'n22', name: 'Embedding', type: 'CONCEPT', page: 2, confidence: 'match_exact', degree: 17, centrality: 0.71, doc_id: 'd1' },
{ id: 'n23', name: 'Document Parsing', type: 'CONCEPT', page: 1, confidence: 'match_exact', degree: 8, centrality: 0.42, doc_id: 'd1' },
{ id: 'n24', name: 'Google', type: 'ORGANIZATION', page: 2, confidence: 'match_exact', degree: 9, centrality: 0.47, doc_id: 'd2' },
{ id: 'n25', name: 'Beijing', type: 'LOCATION', page: 0, confidence: 'match_fuzzy', degree: 3, centrality: 0.20, doc_id: 'd1' },
{ id: 'n26', name: 'San Francisco', type: 'LOCATION', page: 1, confidence: 'match_fuzzy', degree: 4, centrality: 0.25, doc_id: 'd2' },
{ id: 'n27', name: 'Multi-hop Reasoning', type: 'CONCEPT', page: 3, confidence: 'match_exact', degree: 11, centrality: 0.56, doc_id: 'd1' },
{ id: 'n28', name: 'Graph Neural Network', type: 'TECHNOLOGY', page: 2, confidence: 'match_greater', degree: 8, centrality: 0.44, doc_id: 'd2' },
{ id: 'n29', name: 'Yann LeCun', type: 'PERSON', page: 1, confidence: 'match_exact', degree: 5, centrality: 0.30, doc_id: 'd2' },
{ id: 'n30', name: 'Ilya Sutskever', type: 'PERSON', page: 0, confidence: 'match_exact', degree: 6, centrality: 0.33, doc_id: 'd2' },
{ id: 'n31', name: 'Community Detection', type: 'CONCEPT', page: 3, confidence: 'match_exact', degree: 7, centrality: 0.38, doc_id: 'd1' },
{ id: 'n32', name: 'Summarization', type: 'CONCEPT', page: 2, confidence: 'match_exact', degree: 9, centrality: 0.46, doc_id: 'd1' },
{ id: 'n33', name: 'FAISS', type: 'TECHNOLOGY', page: 1, confidence: 'match_exact', degree: 8, centrality: 0.43, doc_id: 'd1' },
{ id: 'n34', name: 'Chunking', type: 'CONCEPT', page: 2, confidence: 'match_greater', degree: 10, centrality: 0.51, doc_id: 'd1' },
{ id: 'n35', name: 'Token', type: 'CONCEPT', page: 0, confidence: 'match_exact', degree: 13, centrality: 0.61, doc_id: 'd2' },
{ id: 'n36', name: 'Inference', type: 'CONCEPT', page: 3, confidence: 'match_exact', degree: 12, centrality: 0.58, doc_id: 'd2' },
{ id: 'n37', name: 'Co-occurrence', type: 'CONCEPT', page: 1, confidence: 'match_exact', degree: 6, centrality: 0.34, doc_id: 'd1' },
{ id: 'n38', name: 'Pipeline', type: 'CONCEPT', page: 2, confidence: 'match_exact', degree: 11, centrality: 0.54, doc_id: 'd1' },
{ id: 'n39', name: 'API', type: 'TECHNOLOGY', page: 3, confidence: 'match_exact', degree: 9, centrality: 0.49, doc_id: 'd1' },
{ id: 'n40', name: 'Hallucination', type: 'CONCEPT', page: 1, confidence: 'match_exact', degree: 7, centrality: 0.39, doc_id: 'd2' },
];
// Mock KG Edges
export const mockEdges: KGEdge[] = [
{ id: 'e1', source: 'n1', target: 'n2', relation: 'CO_OCCURS_IN', weight: 0.95 },
{ id: 'e2', source: 'n1', target: 'n3', relation: 'CO_OCCURS_IN', weight: 0.92 },
{ id: 'e3', source: 'n1', target: 'n4', relation: 'CO_OCCURS_IN', weight: 0.98 },
{ id: 'e4', source: 'n2', target: 'n5', relation: 'CO_OCCURS_IN', weight: 0.88 },
{ id: 'e5', source: 'n3', target: 'n6', relation: 'CO_OCCURS_IN', weight: 0.85 },
{ id: 'e6', source: 'n3', target: 'n7', relation: 'CO_OCCURS_IN', weight: 0.82 },
{ id: 'e7', source: 'n4', target: 'n8', relation: 'CO_OCCURS_IN', weight: 0.80 },
{ id: 'e8', source: 'n1', target: 'n15', relation: 'CO_OCCURS_IN', weight: 0.78 },
{ id: 'e9', source: 'n1', target: 'n16', relation: 'CO_OCCURS_IN', weight: 0.75 },
{ id: 'e10', source: 'n2', target: 'n17', relation: 'CO_OCCURS_IN', weight: 0.72 },
{ id: 'e11', source: 'n9', target: 'n10', relation: 'CO_OCCURS_IN', weight: 0.94 },
{ id: 'e12', source: 'n9', target: 'n11', relation: 'CO_OCCURS_IN', weight: 0.90 },
{ id: 'e13', source: 'n9', target: 'n12', relation: 'CO_OCCURS_IN', weight: 0.93 },
{ id: 'e14', source: 'n12', target: 'n14', relation: 'CO_OCCURS_IN', weight: 0.88 },
{ id: 'e15', source: 'n1', target: 'n13', relation: 'CO_OCCURS_IN', weight: 0.70 },
{ id: 'e16', source: 'n3', target: 'n9', relation: 'CO_OCCURS_IN', weight: 0.86 },
{ id: 'e17', source: 'n4', target: 'n19', relation: 'CO_OCCURS_IN', weight: 0.84 },
{ id: 'e18', source: 'n3', target: 'n20', relation: 'CO_OCCURS_IN', weight: 0.91 },
{ id: 'e19', source: 'n12', target: 'n18', relation: 'CO_OCCURS_IN', weight: 0.80 },
{ id: 'e20', source: 'n3', target: 'n21', relation: 'CO_OCCURS_IN', weight: 0.77 },
{ id: 'e21', source: 'n4', target: 'n22', relation: 'CO_OCCURS_IN', weight: 0.89 },
{ id: 'e22', source: 'n16', target: 'n23', relation: 'CO_OCCURS_IN', weight: 0.82 },
{ id: 'e23', source: 'n9', target: 'n24', relation: 'CO_OCCURS_IN', weight: 0.70 },
{ id: 'e24', source: 'n6', target: 'n25', relation: 'CO_OCCURS_IN', weight: 0.55 },
{ id: 'e25', source: 'n14', target: 'n26', relation: 'CO_OCCURS_IN', weight: 0.58 },
{ id: 'e26', source: 'n1', target: 'n27', relation: 'CO_OCCURS_IN', weight: 0.85 },
{ id: 'e27', source: 'n2', target: 'n28', relation: 'CO_OCCURS_IN', weight: 0.75 },
{ id: 'e28', source: 'n20', target: 'n29', relation: 'CO_OCCURS_IN', weight: 0.65 },
{ id: 'e29', source: 'n14', target: 'n30', relation: 'CO_OCCURS_IN', weight: 0.68 },
{ id: 'e30', source: 'n2', target: 'n31', relation: 'CO_OCCURS_IN', weight: 0.78 },
{ id: 'e31', source: 'n1', target: 'n32', relation: 'CO_OCCURS_IN', weight: 0.76 },
{ id: 'e32', source: 'n8', target: 'n33', relation: 'CO_OCCURS_IN', weight: 0.88 },
{ id: 'e33', source: 'n23', target: 'n34', relation: 'CO_OCCURS_IN', weight: 0.80 },
{ id: 'e34', source: 'n3', target: 'n35', relation: 'CO_OCCURS_IN', weight: 0.90 },
{ id: 'e35', source: 'n12', target: 'n36', relation: 'CO_OCCURS_IN', weight: 0.87 },
{ id: 'e36', source: 'n5', target: 'n37', relation: 'CO_OCCURS_IN', weight: 0.72 },
{ id: 'e37', source: 'n1', target: 'n38', relation: 'CO_OCCURS_IN', weight: 0.83 },
{ id: 'e38', source: 'n6', target: 'n39', relation: 'CO_OCCURS_IN', weight: 0.79 },
{ id: 'e39', source: 'n3', target: 'n40', relation: 'CO_OCCURS_IN', weight: 0.74 },
{ id: 'e40', source: 'n22', target: 'n8', relation: 'CO_OCCURS_IN', weight: 0.86 },
{ id: 'e41', source: 'n19', target: 'n22', relation: 'CO_OCCURS_IN', weight: 0.84 },
{ id: 'e42', source: 'n7', target: 'n15', relation: 'CO_OCCURS_IN', weight: 0.77 },
{ id: 'e43', source: 'n5', target: 'n7', relation: 'CO_OCCURS_IN', weight: 0.81 },
{ id: 'e44', source: 'n20', target: 'n10', relation: 'CO_OCCURS_IN', weight: 0.88 },
{ id: 'e45', source: 'n11', target: 'n20', relation: 'CO_OCCURS_IN', weight: 0.85 },
{ id: 'e46', source: 'n2', target: 'n19', relation: 'CO_OCCURS_IN', weight: 0.82 },
{ id: 'e47', source: 'n27', target: 'n15', relation: 'CO_OCCURS_IN', weight: 0.79 },
{ id: 'e48', source: 'n34', target: 'n22', relation: 'CO_OCCURS_IN', weight: 0.76 },
{ id: 'e49', source: 'n32', target: 'n3', relation: 'CO_OCCURS_IN', weight: 0.80 },
{ id: 'e50', source: 'n38', target: 'n16', relation: 'CO_OCCURS_IN', weight: 0.74 },
];
// Mock Documents
export const mockDocuments: Document[] = [
{
id: 'd1',
filename: 'graphrag_paper.pdf',
format: 'PDF',
pages: 4,
status: 'indexed',
upload_date: '2026-03-04T10:23:00Z',
job_id: 'j1',
result: { nodes: 25, edges: 38, pages: 4, extractions: 45, duration: 42.1 },
},
{
id: 'd2',
filename: 'transformer_survey.pdf',
format: 'PDF',
pages: 8,
status: 'indexed',
upload_date: '2026-03-03T14:15:00Z',
job_id: 'j2',
result: { nodes: 15, edges: 12, pages: 8, extractions: 32, duration: 68.5 },
},
{
id: 'd3',
filename: 'rag_techniques.docx',
format: 'DOCX',
pages: 12,
status: 'indexing',
upload_date: '2026-03-05T08:45:00Z',
job_id: 'j3',
index_stage: 'extracting',
progress: 52,
},
{
id: 'd4',
filename: 'llm_benchmark.pptx',
format: 'PPTX',
pages: 24,
status: 'uploaded',
upload_date: '2026-03-05T09:10:00Z',
},
{
id: 'd5',
filename: 'kg_construction_guide.pdf',
format: 'PDF',
pages: 6,
status: 'failed',
upload_date: '2026-03-02T16:30:00Z',
job_id: 'j5',
error: 'MinerU failed: timeout after 600s',
},
];
// Mock Chat History
export const mockChatHistory: HistoryItem[] = [
{ id: 'h1', question: '给我一个知识图谱的概览', timestamp: '2026-03-05T09:30:00Z', group: '今天' },
{ id: 'h2', question: 'GraphRAG 与知识图谱的关系?', timestamp: '2026-03-05T08:15:00Z', group: '今天' },
{ id: 'h3', question: '列出所有 TECHNOLOGY 实体', timestamp: '2026-03-04T14:20:00Z', group: '昨天' },
{ id: 'h4', question: '什么是检索增强生成?', timestamp: '2026-03-04T10:00:00Z', group: '昨天' },
{ id: 'h5', question: '对比 BERT 和 GPT 架构', timestamp: '2026-03-02T16:45:00Z', group: '更早' },
];
// Mock Chat Messages
export const mockMessages: ChatMessage[] = [
{
id: 'm1',
role: 'human',
content: '给我一个知识图谱的概览',
timestamp: '2026-03-05T09:30:00Z',
},
{
id: 'm2',
role: 'ai',
content: `## 知识图谱概览\n\n当前知识图谱包含 **40 个节点**和 **50 条边**,从 2 份文档中提取。\n\n### 关键统计\n- **实体类型:** TECHNOLOGY (10), CONCEPT (18), PERSON (2), ORGANIZATION (3), LOCATION (2)\n- **最高连接度节点:** GraphRAG度数39\n- **已索引文档:** graphrag_paper.pdf, transformer_survey.pdf\n\n### 核心主题\n知识图谱揭示了 **GraphRAG**、**知识图谱**和 **LLM** 技术之间的强关联。中心簇聚焦于检索增强生成技术,卫星簇围绕 Transformer 架构和 NLP 概念展开。\n\n### 主要关系\n1. GraphRAG 与 RAG、知识图谱和多跳推理紧密相连\n2. LLM 作为 GraphRAG 簇和 Transformer 簇之间的桥梁\n3. 实体提取将文档处理MinerU、文档解析与知识表示连接起来`,
timestamp: '2026-03-05T09:30:08Z',
toolCalls: [
{ step: 1, tool: 'search_entities', input: '{"query": "knowledge graph", "limit": 10}', output: '{"entities": [{"name": "Knowledge Graph", "type": "CONCEPT", "degree": 35}, ...]}' },
{ step: 2, tool: 'get_kg_stats', input: '{}', output: '{"nodes": 40, "edges": 50, "types": {"TECHNOLOGY": 10, "CONCEPT": 18, "PERSON": 2, "ORGANIZATION": 3, "LOCATION": 2}}' },
{ step: 3, tool: 'get_neighbors', input: '{"node_id": "n1", "hops": 1}', output: '{"neighbors": [{"name": "Knowledge Graph"}, {"name": "LLM"}, {"name": "RAG"}, ...]}' },
],
citedNodes: [
{ id: 'n1', name: 'GraphRAG', type: 'TECHNOLOGY' },
{ id: 'n2', name: 'Knowledge Graph', type: 'CONCEPT' },
{ id: 'n3', name: 'LLM', type: 'TECHNOLOGY' },
{ id: 'n4', name: 'RAG', type: 'TECHNOLOGY' },
],
duration: 8.4,
},
];
// Suggested prompts
export const suggestedPrompts = [
'给我一个知识图谱的概览',
'列出所有 TECHNOLOGY 实体',
'GraphRAG 与知识图谱有什么关系?',
'什么是检索增强生成?',
];
// Health status
export const mockHealth = {
mineru: 'ok' as const,
langextract: 'ok' as const,
deepseek: 'ok' as const,
storage: 'ok' as const,
};
// System stats
export const mockStats = {
kg_nodes: 40,
kg_edges: 50,
documents: 5,
queries: 12,
};

View File

@@ -0,0 +1,22 @@
import { createBrowserRouter, Navigate } from 'react-router';
import { AppLayout } from './components/layout/AppLayout';
import { Dashboard } from './components/pages/Dashboard';
import { Documents } from './components/pages/Documents';
import { KGExplorer } from './components/pages/KGExplorer';
import { QAChat } from './components/pages/QAChat';
import { SearchPage } from './components/pages/SearchPage';
export const router = createBrowserRouter([
{
path: '/',
Component: AppLayout,
children: [
{ index: true, element: <Navigate to="/dashboard" replace /> },
{ path: 'dashboard', Component: Dashboard },
{ path: 'documents', Component: Documents },
{ path: 'graph', Component: KGExplorer },
{ path: 'chat', Component: QAChat },
{ path: 'search', Component: SearchPage },
],
},
]);

404
frontend/src/app/store.tsx Normal file
View File

@@ -0,0 +1,404 @@
import React, { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from 'react';
import { api, type ApiDoc, type ApiKGNode, type ApiKGEdge, ApiError } from './api';
// ─── Domain Types ─────────────────────────────────────────────────────────────
export interface KGNode {
id: string;
name: string;
type: 'TECHNOLOGY' | 'CONCEPT' | 'PERSON' | 'ORGANIZATION' | 'LOCATION';
page: number;
confidence: 'match_exact' | 'match_greater' | 'match_lesser' | 'match_fuzzy';
degree: number;
centrality: number;
doc_id: string;
description?: string;
}
export interface KGEdge {
id: string;
source: string;
target: string;
relation: string;
weight: number;
}
export interface Document {
id: string;
filename: string;
format: string;
pages: number;
status: 'uploaded' | 'indexing' | 'indexed' | 'failed';
upload_date: string;
job_id?: string;
index_stage?: string;
progress?: number;
error?: string;
result?: {
nodes: number;
edges: number;
pages: number;
extractions: number;
duration: number;
};
}
export interface ChatMessage {
id: string;
role: 'human' | 'ai';
content: string;
timestamp: string;
toolCalls?: ToolCall[];
citedNodes?: { id: string; name: string; type: string }[];
duration?: number;
}
export interface ToolCall {
step: number;
tool: string;
input: string;
output: string;
}
export interface HistoryItem {
id: string;
question: string;
answer: string;
timestamp: string;
group: '今天' | '昨天' | '更早';
toolCalls?: ToolCall[];
citedNodeIds?: string[];
duration?: number;
}
export interface HealthStatus {
mineru: 'ok' | 'error';
langextract: 'ok' | 'error';
deepseek: 'ok' | 'error';
storage: 'ok' | 'error';
}
export interface StatsData {
kg_nodes: number;
kg_edges: number;
documents: number;
queries: number;
}
// ─── Mappers ──────────────────────────────────────────────────────────────────
function mapApiDoc(d: ApiDoc): Document {
return {
id: d.doc_id,
filename: d.filename,
format: d.format,
pages: d.pages ?? 0,
status: d.status,
upload_date: d.upload_date,
job_id: d.job_id ?? undefined,
error: d.error_msg ?? undefined,
};
}
export function mapApiNode(n: ApiKGNode): KGNode {
return {
id: n.id,
name: n.name,
type: n.type as KGNode['type'],
page: n.page,
confidence: n.confidence as KGNode['confidence'],
degree: n.degree,
centrality: n.degree_centrality ?? 0,
doc_id: n.source_doc,
};
}
export function mapApiEdge(e: ApiKGEdge): KGEdge {
return {
id: e.id,
source: e.source,
target: e.target,
relation: e.relation,
weight: 1,
};
}
function getHistoryGroup(ts: string): HistoryItem['group'] {
const diffDays = (Date.now() - new Date(ts).getTime()) / 86_400_000;
if (diffDays < 1) return '今天';
if (diffDays < 2) return '昨天';
return '更早';
}
// ─── Context ──────────────────────────────────────────────────────────────────
interface AppState {
sidebarCollapsed: boolean;
setSidebarCollapsed: (v: boolean) => void;
nodes: KGNode[];
edges: KGEdge[];
kgLoading: boolean;
refreshKG: () => void;
documents: Document[];
docsLoading: boolean;
refreshDocuments: () => Promise<void>;
setDocuments: React.Dispatch<React.SetStateAction<Document[]>>;
messages: ChatMessage[];
setMessages: React.Dispatch<React.SetStateAction<ChatMessage[]>>;
chatHistory: HistoryItem[];
refreshHistory: () => Promise<void>;
health: HealthStatus;
stats: StatsData;
suggestedPrompts: string[];
selectedNode: KGNode | null;
setSelectedNode: (n: KGNode | null) => void;
getNeighbors: (nodeId: string) => { nodes: KGNode[]; edges: KGEdge[] };
}
const AppContext = createContext<AppState | null>(null);
const DEFAULT_HEALTH: HealthStatus = { mineru: 'error', langextract: 'error', deepseek: 'error', storage: 'error' };
const DEFAULT_STATS: StatsData = { kg_nodes: 0, kg_edges: 0, documents: 0, queries: 0 };
const SUGGESTED_PROMPTS = [
'给我一个知识图谱的概览',
'列出所有 TECHNOLOGY 实体',
'GraphRAG 与知识图谱有什么关系?',
'什么是检索增强生成?',
];
// ─── Provider ─────────────────────────────────────────────────────────────────
export function AppProvider({ children }: { children: ReactNode }) {
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const [nodes, setNodes] = useState<KGNode[]>([]);
const [edges, setEdges] = useState<KGEdge[]>([]);
const [kgLoading, setKgLoading] = useState(true);
const [documents, setDocuments] = useState<Document[]>([]);
const [docsLoading, setDocsLoading] = useState(true);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [chatHistory, setChatHistory] = useState<HistoryItem[]>([]);
const [health, setHealth] = useState<HealthStatus>(DEFAULT_HEALTH);
const [stats, setStats] = useState<StatsData>(DEFAULT_STATS);
const [selectedNode, setSelectedNode] = useState<KGNode | null>(null);
// ── KG data ──────────────────────────────────────────────────────────────
const refreshKG = useCallback(async () => {
try {
setKgLoading(true);
const [nr, er] = await Promise.all([
api.getNodes({ pageSize: 500 }),
api.getEdges({ pageSize: 2000 }),
]);
setNodes(nr.items.map(mapApiNode));
setEdges(er.items.map(mapApiEdge));
} catch (err) {
// code=3002 means empty KG — that's fine
if (!(err instanceof ApiError && err.code === 3002)) {
console.error('KG load error:', err);
}
setNodes([]);
setEdges([]);
} finally {
setKgLoading(false);
}
}, []);
// ── Documents ─────────────────────────────────────────────────────────────
const refreshDocuments = useCallback(async () => {
try {
const res = await api.listDocuments(1, 100);
setDocuments(res.items.map(mapApiDoc));
} catch (err) {
console.error('Docs load error:', err);
} finally {
setDocsLoading(false);
}
}, []);
// ── Query history ─────────────────────────────────────────────────────────
const refreshHistory = useCallback(async () => {
try {
const res = await api.getQueryHistory(1, 50);
setChatHistory(
res.items.map(item => ({
id: item.id,
question: item.question,
answer: item.answer,
timestamp: item.timestamp,
group: getHistoryGroup(item.timestamp),
toolCalls: item.tool_calls.map((tc, i) => ({
step: tc.step ?? i + 1,
tool: tc.tool_name,
input: tc.tool_input,
output: tc.tool_output,
})),
citedNodeIds: item.cited_nodes,
duration: item.duration_seconds,
}))
);
} catch (err) {
console.error('History load error:', err);
setChatHistory([]);
}
}, []);
// ── Health & Stats ────────────────────────────────────────────────────────
const refreshHealthStats = useCallback(async () => {
try {
const [h, s] = await Promise.all([api.getHealth(), api.getSystemStats()]);
setHealth({
mineru: h.components.mineru_venv.status === 'ok' ? 'ok' : 'error',
langextract: h.components.langextract_venv.status === 'ok' ? 'ok' : 'error',
deepseek: h.components.deepseek_api.status === 'ok' ? 'ok' : 'error',
storage: h.components.storage.status === 'ok' ? 'ok' : 'error',
});
setStats({
kg_nodes: s.total_nodes,
kg_edges: s.total_edges,
documents: s.total_documents,
queries: s.total_queries,
});
} catch (err) {
console.error('Health/stats error:', err);
}
}, []);
// ── Initial load ──────────────────────────────────────────────────────────
useEffect(() => {
refreshKG();
refreshDocuments();
refreshHistory();
refreshHealthStats();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
// ── Poll health/stats every 10 s ──────────────────────────────────────────
useEffect(() => {
const id = setInterval(refreshHealthStats, 10_000);
return () => clearInterval(id);
}, [refreshHealthStats]);
// ── Poll active indexing jobs every 3 s ───────────────────────────────────
useEffect(() => {
const indexingDocs = documents.filter(d => d.status === 'indexing' && d.job_id);
if (indexingDocs.length === 0) return;
const id = setInterval(async () => {
const updates: (Partial<Document> & { id: string })[] = [];
for (const doc of indexingDocs) {
if (!doc.job_id) continue;
try {
const status = await api.getJobStatus(doc.job_id);
if (status.status === 'done') {
try {
const result = await api.getJobResult(doc.job_id);
updates.push({
id: doc.id,
status: 'indexed',
progress: 100,
result: {
nodes: result.nodes_added,
edges: result.edges_added,
pages: result.pages_processed,
extractions: result.extractions_count,
duration: result.duration_seconds,
},
});
} catch {
updates.push({ id: doc.id, status: 'indexed', progress: 100 });
}
} else if (status.status === 'failed') {
updates.push({ id: doc.id, status: 'failed', error: status.error_msg ?? 'Indexing failed' });
} else if (status.status === 'cancelled') {
updates.push({ id: doc.id, status: 'uploaded', progress: undefined });
} else {
// still running
updates.push({
id: doc.id,
status: 'indexing',
index_stage: status.stage,
progress: Math.round(status.progress * 100),
});
}
} catch {
// job not found doc may have been cleaned up
}
}
if (updates.length === 0) return;
setDocuments(prev =>
prev.map(d => {
const u = updates.find(u => u.id === d.id);
return u ? { ...d, ...u } : d;
})
);
if (updates.some(u => u.status === 'indexed')) {
refreshKG();
refreshHealthStats();
refreshHistory();
}
}, 3000);
return () => clearInterval(id);
}, [documents, refreshKG, refreshHealthStats, refreshHistory]);
// ── Neighbor helper ───────────────────────────────────────────────────────
const getNeighbors = useCallback(
(nodeId: string) => {
const connectedEdges = edges.filter(e => e.source === nodeId || e.target === nodeId);
const neighborIds = new Set<string>();
connectedEdges.forEach(e => {
if (e.source !== nodeId) neighborIds.add(e.source);
if (e.target !== nodeId) neighborIds.add(e.target);
});
return {
nodes: nodes.filter(n => neighborIds.has(n.id)),
edges: connectedEdges,
};
},
[nodes, edges]
);
return (
<AppContext.Provider
value={{
sidebarCollapsed, setSidebarCollapsed,
nodes, edges, kgLoading, refreshKG,
documents, docsLoading, refreshDocuments, setDocuments,
messages, setMessages,
chatHistory, refreshHistory,
health, stats,
suggestedPrompts: SUGGESTED_PROMPTS,
selectedNode, setSelectedNode,
getNeighbors,
}}
>
{children}
</AppContext.Provider>
);
}
export function useAppState() {
const ctx = useContext(AppContext);
if (!ctx) throw new Error('useAppState must be used within AppProvider');
return ctx;
}

File diff suppressed because it is too large Load Diff

7
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,7 @@
import { createRoot } from "react-dom/client";
import App from "./app/App.tsx";
import "./styles/index.css";
createRoot(document.getElementById("root")!).render(<App />);

View File

@@ -0,0 +1,96 @@
/* GraphRAG Studio - Dark Theme */
:root {
--bg-base: #0f1117;
--bg-s1: #161b22;
--bg-s2: #21262d;
--bg-s3: #1c2128;
--border-main: #30363d;
--border-muted: #21262d;
--text-1: #f0f6fc;
--text-2: #c9d1d9;
--text-3: #8b949e;
--text-4: #484f58;
--blue: #58a6ff;
--green: #3fb950;
--green-btn: #238636;
--green-hover: #2ea043;
--red: #f85149;
--yellow: #d29922;
--purple: #8957e5;
--type-tech: #58a6ff;
--type-concept: #bc8cff;
--type-person: #3fb950;
--type-org: #ff7b72;
--type-loc: #ffa657;
--shadow-sm: 0 1px 3px rgba(0,0,0,0.4);
--shadow-md: 0 4px 16px rgba(0,0,0,0.5);
--shadow-lg: 0 8px 32px rgba(0,0,0,0.6);
}
body {
background: var(--bg-base) !important;
color: var(--text-2) !important;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
/* Skeleton shimmer */
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
.skeleton {
background: linear-gradient(90deg, var(--bg-s2) 25%, var(--bg-s1) 50%, var(--bg-s2) 75%);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
border-radius: 4px;
}
/* Thinking dots animation */
@keyframes dot-bounce {
0%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-6px); }
}
.thinking-dot {
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--text-3);
animation: dot-bounce 1.4s ease-in-out infinite;
}
.thinking-dot:nth-child(2) { animation-delay: 0.16s; }
.thinking-dot:nth-child(3) { animation-delay: 0.32s; }
/* Progress bar */
@keyframes indeterminate {
0% { transform: translateX(-100%); }
100% { transform: translateX(200%); }
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--bg-s2);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--border-main);
}
/* Toast styles */
@keyframes slide-in {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes fade-out {
from { opacity: 1; }
to { opacity: 0; }
}

View File

View File

@@ -0,0 +1,3 @@
@import './fonts.css';
@import './tailwind.css';
@import './theme.css';

View File

@@ -0,0 +1,4 @@
@import 'tailwindcss' source(none);
@source '../**/*.{js,ts,jsx,tsx}';
@import 'tw-animate-css';

View File

@@ -0,0 +1,181 @@
@custom-variant dark (&:is(.dark *));
:root {
--font-size: 16px;
--background: #ffffff;
--foreground: oklch(0.145 0 0);
--card: #ffffff;
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: #030213;
--primary-foreground: oklch(1 0 0);
--secondary: oklch(0.95 0.0058 264.53);
--secondary-foreground: #030213;
--muted: #ececf0;
--muted-foreground: #717182;
--accent: #e9ebef;
--accent-foreground: #030213;
--destructive: #d4183d;
--destructive-foreground: #ffffff;
--border: rgba(0, 0, 0, 0.1);
--input: transparent;
--input-background: #f3f3f5;
--switch-background: #cbced4;
--font-weight-medium: 500;
--font-weight-normal: 400;
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: #030213;
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.145 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.145 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.985 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.396 0.141 25.723);
--destructive-foreground: oklch(0.637 0.237 25.331);
--border: oklch(0.269 0 0);
--input: oklch(0.269 0 0);
--ring: oklch(0.439 0 0);
--font-weight-medium: 500;
--font-weight-normal: 400;
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(0.269 0 0);
--sidebar-ring: oklch(0.439 0 0);
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-input-background: var(--input-background);
--color-switch-background: var(--switch-background);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
/**
* Default typography styles for HTML elements (h1-h4, p, label, button, input).
* These are in @layer base, so Tailwind utility classes (like text-sm, text-lg) automatically override them.
*/
html {
font-size: var(--font-size);
}
h1 {
font-size: var(--text-2xl);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
h2 {
font-size: var(--text-xl);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
h3 {
font-size: var(--text-lg);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
h4 {
font-size: var(--text-base);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
label {
font-size: var(--text-base);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
button {
font-size: var(--text-base);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
input {
font-size: var(--text-base);
font-weight: var(--font-weight-normal);
line-height: 1.5;
}
}

View File

@@ -0,0 +1,266 @@
"""
Frontend-Backend Integration Test
Tests every API call that the frontend components make.
Run with: python tests/integration_test.py
Requires: backend running on localhost:8000
"""
import json
import sys
import urllib.request
import urllib.error
BASE = "http://localhost:8000/api/v1"
PASS = "\033[92m[PASS]\033[0m"
FAIL = "\033[91m[FAIL]\033[0m"
INFO = "\033[94m[INFO]\033[0m"
SECTION = "\033[95m[====]\033[0m"
results = {"passed": 0, "failed": 0}
def req(method, path, body=None, params=None):
url = BASE + path
if params:
url += "?" + "&".join(f"{k}={v}" for k, v in params.items() if v is not None)
try:
if body is not None:
data = json.dumps(body).encode()
r = urllib.request.Request(url, data=data, method=method,
headers={"Content-Type": "application/json"})
else:
r = urllib.request.Request(url, method=method)
resp = urllib.request.urlopen(r, timeout=30)
return json.loads(resp.read().decode())
except urllib.error.HTTPError as e:
return json.loads(e.read().decode())
def check(name, condition, detail=""):
if condition:
results["passed"] += 1
print(f" {PASS} {name}")
else:
results["failed"] += 1
print(f" {FAIL} {name} {detail}")
# ─────────────────────────────────────────────────────────────────────────────
# store.tsx — Initial load (AppProvider useEffect)
# ─────────────────────────────────────────────────────────────────────────────
print(f"\n{SECTION} store.tsx — AppProvider initial data load")
# refreshKG: GET /kg/nodes?page_size=500
r = req("GET", "/kg/nodes", params={"page_size": 500})
check("GET /kg/nodes?page_size=500 → code 0 or 3002", r.get("code") in (0, 3002))
if r.get("code") == 0:
d = r.get("data", {})
check("nodes response has items array", "items" in d)
print(f" {INFO} KG nodes: {d.get('total', 0)}")
# refreshKG: GET /kg/edges?page_size=2000
r = req("GET", "/kg/edges", params={"page_size": 2000})
check("GET /kg/edges?page_size=2000 → code=0", r.get("code") == 0)
# refreshDocuments: GET /documents?page=1&page_size=100
r = req("GET", "/documents", params={"page": 1, "page_size": 100})
check("GET /documents?page=1&page_size=100 → code=0", r.get("code") == 0)
d = r.get("data", {})
check("documents has items + total", "items" in d and "total" in d)
# refreshHistory: GET /query/history?page=1&page_size=50
r = req("GET", "/query/history", params={"page": 1, "page_size": 50})
check("GET /query/history?page=1&page_size=50 → code=0", r.get("code") == 0)
d = r.get("data", {})
check("history has items + total", "items" in d and "total" in d)
# refreshHealthStats: GET /health
r = req("GET", "/health")
check("GET /health → code=0", r.get("code") == 0)
d = r.get("data", {})
check("health has components", "components" in d)
check("health.components has mineru_venv", "mineru_venv" in d.get("components", {}))
check("health.components has langextract_venv", "langextract_venv" in d.get("components", {}))
check("health.components has deepseek_api", "deepseek_api" in d.get("components", {}))
check("health.components has storage", "storage" in d.get("components", {}))
# refreshHealthStats: GET /system/stats
r = req("GET", "/system/stats")
check("GET /system/stats → code=0", r.get("code") == 0)
d = r.get("data", {})
check("stats has total_nodes", "total_nodes" in d)
check("stats has total_edges", "total_edges" in d)
check("stats has total_documents", "total_documents" in d)
check("stats has total_queries", "total_queries" in d)
# ─────────────────────────────────────────────────────────────────────────────
# Header.tsx — Real-time entity typeahead
# ─────────────────────────────────────────────────────────────────────────────
print(f"\n{SECTION} Header.tsx — entity typeahead search")
r = req("GET", "/search/entities", params={"q": "graph", "limit": 5})
check("GET /search/entities?q=graph&limit=5 → code=0", r.get("code") == 0)
d = r.get("data", {})
check("search result has items array", "items" in d)
check("search result has query field", "query" in d)
print(f" {INFO} 'graph' suggestions: {d.get('total', 0)} results")
# ─────────────────────────────────────────────────────────────────────────────
# Dashboard.tsx — Stats + health (same as store, already tested)
# ─────────────────────────────────────────────────────────────────────────────
print(f"\n{SECTION} Dashboard.tsx — stats cards + health panel")
print(f" {INFO} Dashboard uses store data (already tested above)")
# ─────────────────────────────────────────────────────────────────────────────
# Documents.tsx — Upload, Index, Cancel, Delete
# ─────────────────────────────────────────────────────────────────────────────
print(f"\n{SECTION} Documents.tsx — document lifecycle APIs")
# Upload validation (unsupported format)
boundary = "boundary123"
body = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file"; filename="test.xyz"\r\n'
f"Content-Type: application/octet-stream\r\n\r\n"
f"dummy\r\n"
f"--{boundary}--\r\n"
).encode()
upload_req = urllib.request.Request(
BASE + "/documents/upload", data=body, method="POST",
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}
)
try:
urllib.request.urlopen(upload_req, timeout=10)
r_up = {}
except urllib.error.HTTPError as e:
r_up = json.loads(e.read().decode())
check("Upload .xyz → code=1002 (unsupported format)", r_up.get("code") == 1002)
# Start indexing nonexistent doc → 2001
r = req("POST", "/index/start", body={"doc_id": "nonexistent"})
check("POST /index/start nonexistent doc → code=2001", r.get("code") == 2001)
# Get job status nonexistent → 2002
r = req("GET", "/index/status/fakejob")
check("GET /index/status/fakejob → code=2002", r.get("code") == 2002)
# Get job result nonexistent → 2002
r = req("GET", "/index/result/fakejob")
check("GET /index/result/fakejob → code=2002", r.get("code") == 2002)
# Cancel nonexistent job → 2002
r = req("DELETE", "/index/jobs/fakejob")
check("DELETE /index/jobs/fakejob → code=2002", r.get("code") == 2002)
# Delete nonexistent doc → 2001
r = req("DELETE", "/documents/nonexistent_doc")
check("DELETE /documents/nonexistent_doc → code=2001", r.get("code") == 2001)
# ─────────────────────────────────────────────────────────────────────────────
# KGExplorer.tsx — Node list, edges, node detail, neighbors
# ─────────────────────────────────────────────────────────────────────────────
print(f"\n{SECTION} KGExplorer.tsx — KG data loading")
r = req("GET", "/kg/nodes", params={"page_size": 500})
check("GET /kg/nodes → code 0 or 3002", r.get("code") in (0, 3002))
nodes_loaded = []
if r.get("code") == 0:
nodes_loaded = r["data"].get("items", [])
print(f" {INFO} Loaded {len(nodes_loaded)} nodes for KG Explorer")
r = req("GET", "/kg/edges", params={"page_size": 2000})
check("GET /kg/edges → code=0", r.get("code") == 0)
edges_loaded = r.get("data", {}).get("items", []) if r.get("code") == 0 else []
print(f" {INFO} Loaded {len(edges_loaded)} edges for KG Explorer")
# Node detail (invalid)
r = req("GET", "/kg/nodes/definitely_fake_node_id")
check("GET /kg/nodes/fake_id → code=3001", r.get("code") == 3001)
# If nodes exist, test detail + neighbors
if nodes_loaded:
node_id = nodes_loaded[0]["id"]
r = req("GET", f"/kg/nodes/{node_id}")
check(f"GET /kg/nodes/{node_id} → code=0", r.get("code") == 0)
r = req("GET", f"/kg/nodes/{node_id}/neighbors", params={"hops": 1})
check(f"GET /kg/nodes/{node_id}/neighbors?hops=1 → code=0", r.get("code") == 0)
d = r.get("data", {})
check("neighbors has center + neighbors_by_hop", "center" in d and "neighbors_by_hop" in d)
# KG export
r = req("GET", "/kg/export")
check("GET /kg/export → code=0", r.get("code") == 0)
# ─────────────────────────────────────────────────────────────────────────────
# SearchPage.tsx — Entity, Path, Graph search
# ─────────────────────────────────────────────────────────────────────────────
print(f"\n{SECTION} SearchPage.tsx — search APIs")
# Entity search (no type filter)
r = req("GET", "/search/entities", params={"q": "graph", "limit": 50})
check("GET /search/entities?q=graph&limit=50 → code=0", r.get("code") == 0)
d = r.get("data", {})
check("entity search has query, total, items", all(k in d for k in ("query", "total", "items")))
entity_items = d.get("items", [])
print(f" {INFO} Entity search 'graph': {d.get('total', 0)} results")
# Entity search with type filter
r = req("GET", "/search/entities", params={"q": "graph", "type": "TECHNOLOGY", "limit": 15})
check("GET /search/entities?type=TECHNOLOGY → code=0", r.get("code") == 0)
# Path search — missing from/to → code=1001
r = req("GET", "/search/path", params={"max_hops": 2})
check("GET /search/path (no from/to) → code=1001", r.get("code") == 1001)
# Path search — with node IDs from KG
if len(nodes_loaded) >= 2:
n1 = nodes_loaded[0]["id"]
n2 = nodes_loaded[1]["id"]
r = req("GET", "/search/path", params={"from": n1, "to": n2, "max_hops": 3})
check(f"GET /search/path?from={n1[:8]}...&to={n2[:8]}... → code 0 or 3001",
r.get("code") in (0, 3001))
if r.get("code") == 0:
d = r.get("data", {})
check("path result has paths array", "paths" in d)
total = d.get("total_paths", 0)
hops = d["paths"][0]["length"] if d.get("paths") else "?"
print(f" {INFO} Paths found: {total} paths, shortest={hops} hops")
else:
print(f" {INFO} Skipping path search — KG empty")
# Graph search
r = req("GET", "/search/graph", params={"q": "knowledge", "include_neighbors": "true"})
check("GET /search/graph?q=knowledge&include_neighbors=true → code=0", r.get("code") == 0)
d = r.get("data", {})
check("graph search has matched_nodes + subgraph_edges", "matched_nodes" in d and "subgraph_edges" in d)
print(f" {INFO} Graph search 'knowledge': {d.get('total_nodes', 0)} nodes")
# ─────────────────────────────────────────────────────────────────────────────
# QAChat.tsx — Query + history
# ─────────────────────────────────────────────────────────────────────────────
print(f"\n{SECTION} QAChat.tsx — query history")
# Query history load
r = req("GET", "/query/history", params={"page": 1, "page_size": 50})
check("GET /query/history → code=0", r.get("code") == 0)
d = r.get("data", {})
check("history has items + total + page + page_size",
all(k in d for k in ("items", "total", "page", "page_size")))
print(f" {INFO} Query history: {d.get('total', 0)} records")
# POST /query — not tested here to avoid consuming DeepSeek API tokens
# (It requires KG data + DeepSeek API to be working)
print(f" {INFO} POST /query skipped (requires KG data + DeepSeek API)")
# ─────────────────────────────────────────────────────────────────────────────
# Summary
# ─────────────────────────────────────────────────────────────────────────────
total = results["passed"] + results["failed"]
print(f"\n{'='*60}")
print(f"Frontend Integration Test Results: {results['passed']}/{total} passed")
if results["failed"] == 0:
print(f"{PASS} All integration tests passed!")
else:
print(f"{FAIL} {results['failed']} test(s) failed")
print(f"{'='*60}")
sys.exit(0 if results["failed"] == 0 else 1)

22
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,22 @@
import { defineConfig } from 'vite'
import path from 'path'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
// The React and Tailwind plugins are both required for Make, even if
// Tailwind is not being actively used do not remove them
react(),
tailwindcss(),
],
resolve: {
alias: {
// Alias @ to the src directory
'@': path.resolve(__dirname, './src'),
},
},
// File types to support raw imports. Never add .css, .tsx, or .ts files to this.
assetsInclude: ['**/*.svg', '**/*.csv'],
})