mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-19 06:45:50 +00:00
style: 完成所有文件的lint
This commit is contained in:
@@ -1,25 +1,21 @@
|
||||
import { useState, useEffect, useLayoutEffect, useCallback, useRef } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button } from "./ui/button";
|
||||
import { StatusDot } from "./ui/connection-status";
|
||||
import { ThemeToggle } from "./ui/theme-toggle";
|
||||
import { Label } from "./ui/label";
|
||||
import {
|
||||
InputGroup,
|
||||
InputGroupAddon,
|
||||
InputGroupInput,
|
||||
} from "./ui/input-group";
|
||||
import { ACPClient, DEFAULT_SETTINGS, DisconnectRequestedError } from "../src/acp";
|
||||
import type { ACPSettings, ConnectionState, BrowserToolParams, BrowserToolResult } from "../src/acp";
|
||||
import { ChevronDown, FolderOpen, Globe, Image, KeyRound, ScanLine, X } from "lucide-react";
|
||||
import { useQRScanner, type QRCodeData } from "../src/hooks";
|
||||
import { useState, useEffect, useLayoutEffect, useCallback, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Button } from './ui/button';
|
||||
import { StatusDot } from './ui/connection-status';
|
||||
import { ThemeToggle } from './ui/theme-toggle';
|
||||
import { Label } from './ui/label';
|
||||
import { InputGroup, InputGroupAddon, InputGroupInput } from './ui/input-group';
|
||||
import { ACPClient, DEFAULT_SETTINGS, DisconnectRequestedError } from '../src/acp';
|
||||
import type { ACPSettings, ConnectionState, BrowserToolParams, BrowserToolResult } from '../src/acp';
|
||||
import { ChevronDown, FolderOpen, Globe, Image, KeyRound, ScanLine, X } from 'lucide-react';
|
||||
import { useQRScanner, type QRCodeData } from '../src/hooks';
|
||||
|
||||
// Get token from the URL fragment so it is not sent in HTTP requests.
|
||||
function getTokenFromUrl(): string | undefined {
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ""));
|
||||
return hashParams.get("token") || undefined;
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ''));
|
||||
return hashParams.get('token') || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -30,12 +26,12 @@ function getTokenFromUrl(): string | undefined {
|
||||
function inferProxyUrlFromPage(): string | undefined {
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ""));
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ''));
|
||||
// Only infer if we have a fragment token (indicates user came from server-printed URL)
|
||||
if (!hashParams.has("token")) {
|
||||
if (!hashParams.has('token')) {
|
||||
return undefined;
|
||||
}
|
||||
const protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
||||
const protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return `${protocol}//${url.host}/ws`;
|
||||
} catch {
|
||||
return undefined;
|
||||
@@ -45,15 +41,15 @@ function inferProxyUrlFromPage(): string | undefined {
|
||||
function scrubTokenFromUrl(): void {
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ""));
|
||||
if (!hashParams.has("token")) {
|
||||
const hashParams = new URLSearchParams(url.hash.replace(/^#/, ''));
|
||||
if (!hashParams.has('token')) {
|
||||
return;
|
||||
}
|
||||
|
||||
hashParams.delete("token");
|
||||
hashParams.delete('token');
|
||||
const nextHash = hashParams.toString();
|
||||
url.hash = nextHash ? `#${nextHash}` : "";
|
||||
window.history.replaceState(null, "", url.toString());
|
||||
url.hash = nextHash ? `#${nextHash}` : '';
|
||||
window.history.replaceState(null, '', url.toString());
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
@@ -102,11 +98,11 @@ export function ACPConnect({
|
||||
browserToolHandler,
|
||||
showTokenInput = false,
|
||||
inferFromUrl = false,
|
||||
placeholder = "Proxy server URL",
|
||||
placeholder = 'Proxy server URL',
|
||||
showScanButton = false,
|
||||
}: ACPConnectProps) {
|
||||
const [settings, setSettings] = useState<ACPSettings>(() => getInitialSettings(inferFromUrl));
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>("disconnected");
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShaking, setIsShaking] = useState(false);
|
||||
const [client, setClient] = useState<ACPClient | null>(null);
|
||||
@@ -122,7 +118,7 @@ export function ACPConnect({
|
||||
// Mark for auto-connect (will be triggered by settings useEffect)
|
||||
pendingAutoConnectRef.current = true;
|
||||
// Update settings - this will trigger auto-connect via useEffect
|
||||
setSettings((prev) => ({
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
proxyUrl: data.url,
|
||||
token: data.token,
|
||||
@@ -163,9 +159,9 @@ export function ACPConnect({
|
||||
stopScanning(); // Close the scanner overlay after album scan
|
||||
}
|
||||
// Reset input to allow re-selecting the same file
|
||||
e.target.value = "";
|
||||
e.target.value = '';
|
||||
},
|
||||
[scanFromFile, stopScanning]
|
||||
[scanFromFile, stopScanning],
|
||||
);
|
||||
|
||||
// Open file picker
|
||||
@@ -203,7 +199,7 @@ export function ACPConnect({
|
||||
// Auto-connect after QR scan (when pendingAutoConnectRef is set)
|
||||
if (pendingAutoConnectRef.current) {
|
||||
pendingAutoConnectRef.current = false;
|
||||
client.connect().catch((e) => {
|
||||
client.connect().catch(e => {
|
||||
// Ignore disconnect requested - user cancelled intentionally
|
||||
if (e instanceof DisconnectRequestedError) {
|
||||
return;
|
||||
@@ -219,7 +215,7 @@ export function ACPConnect({
|
||||
|
||||
// Notify parent when client is ready and auto-collapse on connect
|
||||
useEffect(() => {
|
||||
const isConnected = connectionState === "connected";
|
||||
const isConnected = connectionState === 'connected';
|
||||
onClientReady?.(isConnected ? client : null);
|
||||
|
||||
// Auto-collapse when connected for the first time
|
||||
@@ -229,14 +225,14 @@ export function ACPConnect({
|
||||
}
|
||||
|
||||
// Reset auto-collapse flag when disconnected
|
||||
if (connectionState === "disconnected") {
|
||||
if (connectionState === 'disconnected') {
|
||||
hasAutoCollapsedRef.current = false;
|
||||
}
|
||||
}, [connectionState, client, onClientReady, onExpandedChange]);
|
||||
|
||||
const handleConnect = useCallback(async () => {
|
||||
// Prevent duplicate connect calls if already connecting or connected
|
||||
if (!client || connectionState === "connecting" || connectionState === "connected") {
|
||||
if (!client || connectionState === 'connecting' || connectionState === 'connected') {
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
@@ -263,7 +259,7 @@ export function ACPConnect({
|
||||
}, [client]);
|
||||
|
||||
const updateSetting = <K extends keyof ACPSettings>(key: K, value: ACPSettings[K]) => {
|
||||
setSettings((prev) => ({ ...prev, [key]: value }));
|
||||
setSettings(prev => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
// Clear error when starting to scan
|
||||
@@ -272,107 +268,93 @@ export function ACPConnect({
|
||||
startScanning();
|
||||
}, [startScanning]);
|
||||
|
||||
const isConnected = connectionState === "connected";
|
||||
const isConnecting = connectionState === "connecting";
|
||||
const isConnected = connectionState === 'connected';
|
||||
const isConnecting = connectionState === 'connecting';
|
||||
|
||||
const handleInputKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !isConnected && !isConnecting) {
|
||||
e.preventDefault();
|
||||
handleConnect();
|
||||
}
|
||||
}, [isConnected, isConnecting, handleConnect]);
|
||||
const handleInputKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !isConnected && !isConnecting) {
|
||||
e.preventDefault();
|
||||
handleConnect();
|
||||
}
|
||||
},
|
||||
[isConnected, isConnecting, handleConnect],
|
||||
);
|
||||
|
||||
// Format URL for display
|
||||
const displayUrl = settings.proxyUrl.replace(/^wss?:\/\//, "").replace(/\/ws$/, "");
|
||||
const displayUrl = settings.proxyUrl.replace(/^wss?:\/\//, '').replace(/\/ws$/, '');
|
||||
|
||||
// Get status label
|
||||
const statusLabels: Record<ConnectionState, string> = {
|
||||
disconnected: "Disconnected",
|
||||
connecting: "Connecting...",
|
||||
connected: "Connected",
|
||||
error: "Error",
|
||||
disconnected: 'Disconnected',
|
||||
connecting: 'Connecting...',
|
||||
connected: 'Connected',
|
||||
error: 'Error',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-background/80 backdrop-blur-sm">
|
||||
<div className="max-w-md mx-auto border-b">
|
||||
{/* Status Bar - Always visible */}
|
||||
<button
|
||||
onClick={() => onExpandedChange(!expanded)}
|
||||
className="w-full flex items-center justify-between px-3 py-2 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusDot state={connectionState} />
|
||||
<span className="text-sm font-medium">{statusLabels[connectionState]}</span>
|
||||
{isConnected && displayUrl && (
|
||||
<span className="text-xs text-muted-foreground">• {displayUrl}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<ThemeToggle />
|
||||
{/* Status Bar - Always visible */}
|
||||
<button
|
||||
onClick={() => onExpandedChange(!expanded)}
|
||||
className="w-full flex items-center justify-between px-3 py-2 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusDot state={connectionState} />
|
||||
<span className="text-sm font-medium">{statusLabels[connectionState]}</span>
|
||||
{isConnected && displayUrl && <span className="text-xs text-muted-foreground">• {displayUrl}</span>}
|
||||
</div>
|
||||
<ChevronDown
|
||||
className={`w-4 h-4 text-muted-foreground transition-transform duration-200 ${
|
||||
expanded ? "rotate-180" : ""
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
<div className="flex items-center gap-1">
|
||||
<div onClick={e => e.stopPropagation()}>
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
<ChevronDown
|
||||
className={`w-4 h-4 text-muted-foreground transition-transform duration-200 ${
|
||||
expanded ? 'rotate-180' : ''
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Expandable Settings Panel */}
|
||||
<div
|
||||
className="overflow-hidden transition-all duration-200 ease-out"
|
||||
style={{
|
||||
maxHeight: expanded ? maxHeight : 0,
|
||||
opacity: expanded ? 1 : 0,
|
||||
}}
|
||||
>
|
||||
<div ref={contentRef} className={`px-3 pb-3 pt-1 space-y-3 ${isShaking ? "animate-shake" : ""}`}>
|
||||
{/* Hidden file input for album scanning */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleFileSelect}
|
||||
className="hidden"
|
||||
/>
|
||||
{/* Expandable Settings Panel */}
|
||||
<div
|
||||
className="overflow-hidden transition-all duration-200 ease-out"
|
||||
style={{
|
||||
maxHeight: expanded ? maxHeight : 0,
|
||||
opacity: expanded ? 1 : 0,
|
||||
}}
|
||||
>
|
||||
<div ref={contentRef} className={`px-3 pb-3 pt-1 space-y-3 ${isShaking ? 'animate-shake' : ''}`}>
|
||||
{/* Hidden file input for album scanning */}
|
||||
<input ref={fileInputRef} type="file" accept="image/*" onChange={handleFileSelect} className="hidden" />
|
||||
|
||||
{/* QR Scanner View - Portal to body to escape backdrop-blur containing block */}
|
||||
{isScanning && createPortal(
|
||||
<div className="fixed inset-0 z-50 bg-black flex flex-col">
|
||||
<video
|
||||
ref={videoRef}
|
||||
className="flex-1 w-full object-cover"
|
||||
/>
|
||||
<Button
|
||||
onClick={stopScanning}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute top-4 right-4 h-10 w-10 p-0 bg-black/50 hover:bg-black/70 text-white rounded-full"
|
||||
>
|
||||
<X className="h-5 w-5" />
|
||||
</Button>
|
||||
<div className="absolute bottom-16 left-0 right-0 flex flex-col items-center gap-3">
|
||||
<Button
|
||||
onClick={handleSelectFromAlbum}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="h-9 px-4"
|
||||
>
|
||||
<Image className="h-4 w-4 mr-2" />
|
||||
Select from Album
|
||||
</Button>
|
||||
<span className="text-sm text-white/80">
|
||||
or point camera at QR code
|
||||
</span>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
{/* QR Scanner View - Portal to body to escape backdrop-blur containing block */}
|
||||
{isScanning &&
|
||||
createPortal(
|
||||
<div className="fixed inset-0 z-50 bg-black flex flex-col">
|
||||
<video ref={videoRef} className="flex-1 w-full object-cover" />
|
||||
<Button
|
||||
onClick={stopScanning}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute top-4 right-4 h-10 w-10 p-0 bg-black/50 hover:bg-black/70 text-white rounded-full"
|
||||
>
|
||||
<X className="h-5 w-5" />
|
||||
</Button>
|
||||
<div className="absolute bottom-16 left-0 right-0 flex flex-col items-center gap-3">
|
||||
<Button onClick={handleSelectFromAlbum} variant="secondary" size="sm" className="h-9 px-4">
|
||||
<Image className="h-4 w-4 mr-2" />
|
||||
Select from Album
|
||||
</Button>
|
||||
<span className="text-sm text-white/80">or point camera at QR code</span>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
|
||||
{/* Connection Settings - use invisible (not hidden) to preserve scrollHeight for animation */}
|
||||
<div className={`space-y-3 ${isScanning ? "invisible" : ""}`}>
|
||||
{/* Connection Settings - use invisible (not hidden) to preserve scrollHeight for animation */}
|
||||
<div className={`space-y-3 ${isScanning ? 'invisible' : ''}`}>
|
||||
{/* Server URL */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-url">Server</Label>
|
||||
@@ -396,7 +378,7 @@ export function ACPConnect({
|
||||
<InputGroupInput
|
||||
id="proxy-url"
|
||||
value={settings.proxyUrl}
|
||||
onChange={(e) => updateSetting("proxyUrl", e.target.value)}
|
||||
onChange={e => updateSetting('proxyUrl', e.target.value)}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
placeholder={placeholder}
|
||||
disabled={isConnected || isConnecting}
|
||||
@@ -411,7 +393,7 @@ export function ACPConnect({
|
||||
className="h-9 px-4"
|
||||
type="button"
|
||||
>
|
||||
{isConnecting ? "..." : "Connect"}
|
||||
{isConnecting ? '...' : 'Connect'}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
@@ -440,8 +422,8 @@ export function ACPConnect({
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput
|
||||
id="auth-token"
|
||||
value={settings.token || ""}
|
||||
onChange={(e) => updateSetting("token", e.target.value || undefined)}
|
||||
value={settings.token || ''}
|
||||
onChange={e => updateSetting('token', e.target.value || undefined)}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
placeholder="For remote access"
|
||||
disabled={isConnected || isConnecting}
|
||||
@@ -465,8 +447,8 @@ export function ACPConnect({
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput
|
||||
id="working-dir"
|
||||
value={settings.cwd || ""}
|
||||
onChange={(e) => updateSetting("cwd", e.target.value || undefined)}
|
||||
value={settings.cwd || ''}
|
||||
onChange={e => updateSetting('cwd', e.target.value || undefined)}
|
||||
onKeyDown={handleInputKeyDown}
|
||||
placeholder="/path/to/project"
|
||||
disabled={isConnected || isConnecting}
|
||||
@@ -475,17 +457,13 @@ export function ACPConnect({
|
||||
/>
|
||||
</InputGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<div className="text-xs text-destructive bg-destructive/10 px-2 py-1.5 rounded">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Message */}
|
||||
{error && <div className="text-xs text-destructive bg-destructive/10 px-2 py-1.5 rounded">{error}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useState, useCallback, useEffect, useMemo } from "react";
|
||||
import type { ACPClient } from "../src/acp/client";
|
||||
import type { AgentSessionInfo } from "../src/acp/types";
|
||||
import { ChatInterface } from "./ChatInterface";
|
||||
import { cn } from "../src/lib/utils";
|
||||
import { MessageSquare, Plus, PanelLeftClose, PanelLeft } from "lucide-react";
|
||||
import { useState, useCallback, useEffect, useMemo } from 'react';
|
||||
import type { ACPClient } from '../src/acp/client';
|
||||
import type { AgentSessionInfo } from '../src/acp/types';
|
||||
import { ChatInterface } from './ChatInterface';
|
||||
import { cn } from '../src/lib/utils';
|
||||
import { MessageSquare, Plus, PanelLeftClose, PanelLeft } from 'lucide-react';
|
||||
|
||||
interface ACPMainProps {
|
||||
client: ACPClient;
|
||||
@@ -18,35 +18,40 @@ export function ACPMain({ client, agentId }: ACPMainProps) {
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||
|
||||
// Handle session selection
|
||||
const handleSelectSession = useCallback(async (session: AgentSessionInfo) => {
|
||||
try {
|
||||
if (client.supportsLoadSession) {
|
||||
await client.loadSession({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
} else if (client.supportsResumeSession) {
|
||||
await client.resumeSession({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
} else {
|
||||
throw new Error("Loading or resuming sessions is not supported by this agent.");
|
||||
const handleSelectSession = useCallback(
|
||||
async (session: AgentSessionInfo) => {
|
||||
try {
|
||||
if (client.supportsLoadSession) {
|
||||
await client.loadSession({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
} else if (client.supportsResumeSession) {
|
||||
await client.resumeSession({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
} else {
|
||||
throw new Error('Loading or resuming sessions is not supported by this agent.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load/resume session:', error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load/resume session:", error);
|
||||
}
|
||||
}, [client]);
|
||||
},
|
||||
[client],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full">
|
||||
{/* 侧边栏 — Anthropic warm sidebar, hidden on mobile */}
|
||||
<div
|
||||
className={cn(
|
||||
"hidden md:flex flex-col border-r border-border/60 bg-surface-1/50 transition-all duration-200 flex-shrink-0",
|
||||
sidebarCollapsed ? "w-12" : "w-64",
|
||||
'hidden md:flex flex-col border-r border-border/60 bg-surface-1/50 transition-all duration-200 flex-shrink-0',
|
||||
sidebarCollapsed ? 'w-12' : 'w-64',
|
||||
)}
|
||||
>
|
||||
{/* 头部 */}
|
||||
<div className="flex items-center justify-between px-3 py-4">
|
||||
{!sidebarCollapsed && (
|
||||
<span className="text-xs font-display font-semibold text-text-muted uppercase tracking-widest px-1">会话</span>
|
||||
<span className="text-xs font-display font-semibold text-text-muted uppercase tracking-widest px-1">
|
||||
会话
|
||||
</span>
|
||||
)}
|
||||
<div className={cn("flex items-center gap-0.5", sidebarCollapsed && "mx-auto")}>
|
||||
<div className={cn('flex items-center gap-0.5', sidebarCollapsed && 'mx-auto')}>
|
||||
{!sidebarCollapsed && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -64,11 +69,7 @@ export function ACPMain({ client, agentId }: ACPMainProps) {
|
||||
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
|
||||
className="h-7 w-7 flex items-center justify-center rounded-lg text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors"
|
||||
>
|
||||
{sidebarCollapsed ? (
|
||||
<PanelLeft className="h-4 w-4" />
|
||||
) : (
|
||||
<PanelLeftClose className="h-4 w-4" />
|
||||
)}
|
||||
{sidebarCollapsed ? <PanelLeft className="h-4 w-4" /> : <PanelLeftClose className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -114,21 +115,21 @@ function SidebarSessionList({
|
||||
const response = await client.listSessions();
|
||||
setSessions(response.sessions);
|
||||
} catch (err) {
|
||||
console.warn("[SidebarSessionList] Failed to load:", err);
|
||||
console.warn('[SidebarSessionList] Failed to load:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [client]);
|
||||
|
||||
useEffect(() => {
|
||||
if (client.getState() === "connected" && client.supportsSessionList) {
|
||||
if (client.getState() === 'connected' && client.supportsSessionList) {
|
||||
loadSessions();
|
||||
}
|
||||
}, [client, loadSessions]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (state: string) => {
|
||||
if (state === "connected") {
|
||||
if (state === 'connected') {
|
||||
setTimeout(loadSessions, 200);
|
||||
}
|
||||
};
|
||||
@@ -180,7 +181,7 @@ function SidebarSessionList({
|
||||
{group.label}
|
||||
</span>
|
||||
</div>
|
||||
{group.sessions.map((session) => (
|
||||
{group.sessions.map(session => (
|
||||
<button
|
||||
key={session.sessionId}
|
||||
type="button"
|
||||
@@ -189,16 +190,16 @@ function SidebarSessionList({
|
||||
onSelectSession(session);
|
||||
}}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2.5 px-4 py-2 text-left transition-colors rounded-none",
|
||||
'w-full flex items-center gap-2.5 px-4 py-2 text-left transition-colors rounded-none',
|
||||
session.sessionId === activeId
|
||||
? "bg-brand/8 text-text-primary"
|
||||
: "text-text-secondary hover:bg-surface-2/60 hover:text-text-primary",
|
||||
? 'bg-brand/8 text-text-primary'
|
||||
: 'text-text-secondary hover:bg-surface-2/60 hover:text-text-primary',
|
||||
)}
|
||||
title={session.title || session.sessionId}
|
||||
>
|
||||
<MessageSquare className="h-3.5 w-3.5 flex-shrink-0 opacity-50" />
|
||||
<span className="text-[13px] font-display truncate leading-snug">
|
||||
{session.title && session.title.trim() ? session.title : "新会话"}
|
||||
{session.title && session.title.trim() ? session.title : '新会话'}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
@@ -223,9 +224,9 @@ function groupByRecency(sessions: AgentSessionInfo[]): SessionGroup[] {
|
||||
const yesterday = new Date(today.getTime() - 86400000);
|
||||
|
||||
const groups: SessionGroup[] = [
|
||||
{ label: "今天", sessions: [] },
|
||||
{ label: "昨天", sessions: [] },
|
||||
{ label: "更早", sessions: [] },
|
||||
{ label: '今天', sessions: [] },
|
||||
{ label: '昨天', sessions: [] },
|
||||
{ label: '更早', sessions: [] },
|
||||
];
|
||||
|
||||
for (const session of sessions) {
|
||||
@@ -239,5 +240,5 @@ function groupByRecency(sessions: AgentSessionInfo[]): SessionGroup[] {
|
||||
}
|
||||
}
|
||||
|
||||
return groups.filter((g) => g.sessions.length > 0);
|
||||
return groups.filter(g => g.sessions.length > 0);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,47 @@
|
||||
import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import imageCompression from "browser-image-compression";
|
||||
import type { ACPClient } from "../src/acp/client";
|
||||
import type { SessionUpdate, PermissionRequestPayload, PermissionOption, ContentBlock, ImageContent } from "../src/acp/types";
|
||||
import type { ThreadEntry, ToolCallStatus, ToolCallData, UserMessageImage, UserMessageEntry, AssistantMessageEntry, ToolCallEntry, ChatInputMessage, PendingPermission, PlanDisplayEntry } from "../src/lib/types";
|
||||
import { ChatView } from "./chat/ChatView";
|
||||
import { ChatInput } from "./chat/ChatInput";
|
||||
import { PermissionPanel } from "./chat/PermissionPanel";
|
||||
import { ModelSelectorPopover } from "./model-selector";
|
||||
import { useCommands } from "../src/hooks/useCommands";
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import imageCompression from 'browser-image-compression';
|
||||
import type { ACPClient } from '../src/acp/client';
|
||||
import type {
|
||||
SessionUpdate,
|
||||
PermissionRequestPayload,
|
||||
PermissionOption,
|
||||
ContentBlock,
|
||||
ImageContent,
|
||||
} from '../src/acp/types';
|
||||
import type {
|
||||
ThreadEntry,
|
||||
ToolCallStatus,
|
||||
ToolCallData,
|
||||
UserMessageImage,
|
||||
UserMessageEntry,
|
||||
AssistantMessageEntry,
|
||||
ToolCallEntry,
|
||||
ChatInputMessage,
|
||||
PendingPermission,
|
||||
PlanDisplayEntry,
|
||||
} from '../src/lib/types';
|
||||
import { ChatView } from './chat/ChatView';
|
||||
import { ChatInput } from './chat/ChatInput';
|
||||
import { PermissionPanel } from './chat/PermissionPanel';
|
||||
import { ModelSelectorPopover } from './model-selector';
|
||||
import { useCommands } from '../src/hooks/useCommands';
|
||||
|
||||
// Image compression options
|
||||
// Claude API has a 5MB limit, so we target 2MB to be safe
|
||||
const IMAGE_COMPRESSION_OPTIONS = {
|
||||
maxSizeMB: 2, // Max output size in MB
|
||||
maxSizeMB: 2, // Max output size in MB
|
||||
maxWidthOrHeight: 2048, // Max dimension (scales proportionally, no cropping)
|
||||
useWebWorker: true, // Non-blocking compression
|
||||
fileType: "image/jpeg" as const, // Convert to JPEG for better compression
|
||||
useWebWorker: true, // Non-blocking compression
|
||||
fileType: 'image/jpeg' as const, // Convert to JPEG for better compression
|
||||
};
|
||||
|
||||
// Convert data URL to Blob without using fetch()
|
||||
// This is critical for Chrome extensions where fetch(dataUrl) violates CSP
|
||||
function dataUrlToBlob(dataUrl: string): Blob {
|
||||
// Parse the data URL: data:[<mediatype>][;base64],<data>
|
||||
const commaIndex = dataUrl.indexOf(",");
|
||||
const commaIndex = dataUrl.indexOf(',');
|
||||
if (commaIndex === -1) {
|
||||
throw new Error("Invalid data URL: missing comma separator");
|
||||
throw new Error('Invalid data URL: missing comma separator');
|
||||
}
|
||||
|
||||
const header = dataUrl.slice(0, commaIndex);
|
||||
@@ -32,7 +49,7 @@ function dataUrlToBlob(dataUrl: string): Blob {
|
||||
|
||||
// Extract MIME type from header (e.g., "data:image/png;base64")
|
||||
const mimeMatch = header.match(/^data:([^;,]+)/);
|
||||
const mimeType = mimeMatch ? mimeMatch[1] : "application/octet-stream";
|
||||
const mimeType = mimeMatch ? mimeMatch[1] : 'application/octet-stream';
|
||||
|
||||
// Decode base64 to binary
|
||||
const binaryString = atob(base64Data);
|
||||
@@ -44,14 +61,10 @@ function dataUrlToBlob(dataUrl: string): Blob {
|
||||
return new Blob([bytes], { type: mimeType });
|
||||
}
|
||||
|
||||
import { Plus, Shield, ChevronDown, ChevronUp, Check } from "lucide-react";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "./ui/tooltip";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
|
||||
import { Plus, Shield, ChevronDown, ChevronUp, Check } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
|
||||
|
||||
// =============================================================================
|
||||
// Type Definitions - imported from shared types module
|
||||
@@ -67,43 +80,29 @@ interface ChatInterfaceProps {
|
||||
// =============================================================================
|
||||
|
||||
const PERMISSION_MODES = [
|
||||
{ value: "default", label: "默认", description: "手动审批权限请求" },
|
||||
{ value: "acceptEdits", label: "自动接受编辑", description: "自动允许文件编辑操作" },
|
||||
{ value: "bypassPermissions", label: "跳过权限", description: "跳过所有权限检查" },
|
||||
{ value: "plan", label: "规划模式", description: "仅规划,不执行工具" },
|
||||
{ value: "dontAsk", label: "不询问", description: "不弹出询问,自动拒绝" },
|
||||
{ value: "auto", label: "自动判断", description: "AI 自动判断是否批准" },
|
||||
{ value: 'default', label: '默认', description: '手动审批权限请求' },
|
||||
{ value: 'acceptEdits', label: '自动接受编辑', description: '自动允许文件编辑操作' },
|
||||
{ value: 'bypassPermissions', label: '跳过权限', description: '跳过所有权限检查' },
|
||||
{ value: 'plan', label: '规划模式', description: '仅规划,不执行工具' },
|
||||
{ value: 'dontAsk', label: '不询问', description: '不弹出询问,自动拒绝' },
|
||||
{ value: 'auto', label: '自动判断', description: 'AI 自动判断是否批准' },
|
||||
] as const;
|
||||
|
||||
function PermissionModeSelector({
|
||||
mode,
|
||||
onModeChange,
|
||||
}: {
|
||||
mode: string;
|
||||
onModeChange: (mode: string) => void;
|
||||
}) {
|
||||
function PermissionModeSelector({ mode, onModeChange }: { mode: string; onModeChange: (mode: string) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const current = PERMISSION_MODES.find((m) => m.value === mode) ?? PERMISSION_MODES[0];
|
||||
const current = PERMISSION_MODES.find(m => m.value === mode) ?? PERMISSION_MODES[0];
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-1.5 text-muted-foreground hover:text-foreground h-7 px-2"
|
||||
>
|
||||
<Button variant="ghost" size="sm" className="gap-1.5 text-muted-foreground hover:text-foreground h-7 px-2">
|
||||
<Shield className="h-3 w-3" />
|
||||
<span className="max-w-24 truncate">{current.label}</span>
|
||||
{open ? (
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
)}
|
||||
{open ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-64 p-1" align="start">
|
||||
{PERMISSION_MODES.map((m) => (
|
||||
{PERMISSION_MODES.map(m => (
|
||||
<button
|
||||
key={m.value}
|
||||
type="button"
|
||||
@@ -133,16 +132,16 @@ function PermissionModeSelector({
|
||||
|
||||
// Map ACP status string to our status type
|
||||
function mapToolStatus(status: string): ToolCallStatus {
|
||||
if (status === "completed") return "complete";
|
||||
if (status === "failed") return "error";
|
||||
return "running";
|
||||
if (status === 'completed') return 'complete';
|
||||
if (status === 'failed') return 'error';
|
||||
return 'running';
|
||||
}
|
||||
|
||||
// Find tool call index in entries (search from end, like Zed)
|
||||
function findToolCallIndex(entries: ThreadEntry[], toolCallId: string): number {
|
||||
for (let i = entries.length - 1; i >= 0; i--) {
|
||||
const entry = entries[i];
|
||||
if (entry && entry.type === "tool_call" && entry.toolCall.id === toolCallId) {
|
||||
if (entry && entry.type === 'tool_call' && entry.toolCall.id === toolCallId) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
@@ -162,7 +161,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
const activeSessionIdRef = useRef<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const errorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [permissionMode, setPermissionMode] = useState(() => localStorage.getItem("acp_permission_mode") || "default");
|
||||
const [permissionMode, setPermissionMode] = useState(() => localStorage.getItem('acp_permission_mode') || 'default');
|
||||
// Reference: Zed's supports_images() checks prompt_capabilities.image
|
||||
const [supportsImages, setSupportsImages] = useState(false);
|
||||
const { commands: availableCommands } = useCommands(client);
|
||||
@@ -179,21 +178,26 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
const storageKey = agentId ? `acp_last_session_${agentId}` : null;
|
||||
|
||||
const activateSession = useCallback((sessionId: string, options?: { resetEntries?: boolean }) => {
|
||||
const shouldResetEntries = options?.resetEntries ?? true;
|
||||
if (shouldResetEntries) {
|
||||
setEntries([]);
|
||||
setIsLoading(false);
|
||||
}
|
||||
setActiveSessionId(sessionId);
|
||||
setSessionReady(true);
|
||||
setSupportsImages(client.supportsImages);
|
||||
// Persist session ID for restoration on remount
|
||||
if (storageKey) {
|
||||
try { localStorage.setItem(storageKey, sessionId); } catch {}
|
||||
}
|
||||
console.log("[ChatInterface] Active session:", sessionId, "supportsImages:", client.supportsImages);
|
||||
}, [client, storageKey]);
|
||||
const activateSession = useCallback(
|
||||
(sessionId: string, options?: { resetEntries?: boolean }) => {
|
||||
const shouldResetEntries = options?.resetEntries ?? true;
|
||||
if (shouldResetEntries) {
|
||||
setEntries([]);
|
||||
setIsLoading(false);
|
||||
}
|
||||
setActiveSessionId(sessionId);
|
||||
setSessionReady(true);
|
||||
setSupportsImages(client.supportsImages);
|
||||
// Persist session ID for restoration on remount
|
||||
if (storageKey) {
|
||||
try {
|
||||
localStorage.setItem(storageKey, sessionId);
|
||||
} catch {}
|
||||
}
|
||||
console.log('[ChatInterface] Active session:', sessionId, 'supportsImages:', client.supportsImages);
|
||||
},
|
||||
[client, storageKey],
|
||||
);
|
||||
|
||||
// =============================================================================
|
||||
// Permission Request Handler
|
||||
@@ -202,9 +206,9 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
if (activeSessionIdRef.current && request.sessionId !== activeSessionIdRef.current) {
|
||||
return;
|
||||
}
|
||||
console.log("[ChatInterface] Permission request:", request);
|
||||
console.log('[ChatInterface] Permission request:', request);
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
// Find matching tool call (search from end)
|
||||
const toolCallIndex = findToolCallIndex(prev, request.toolCall.toolCallId);
|
||||
|
||||
@@ -212,14 +216,14 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Update existing tool call's status
|
||||
return prev.map((entry, index) => {
|
||||
if (index !== toolCallIndex) return entry;
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.toolCall.status !== "running") return entry;
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
if (entry.toolCall.status !== 'running') return entry;
|
||||
|
||||
return {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: "waiting_for_confirmation" as const,
|
||||
status: 'waiting_for_confirmation' as const,
|
||||
permissionRequest: {
|
||||
requestId: request.requestId,
|
||||
options: request.options,
|
||||
@@ -229,14 +233,14 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
});
|
||||
} else {
|
||||
// No matching tool call - create standalone permission request as new entry
|
||||
console.log("[ChatInterface] No matching tool call, creating standalone permission request");
|
||||
console.log('[ChatInterface] No matching tool call, creating standalone permission request');
|
||||
|
||||
const permissionToolCall: ToolCallEntry = {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
id: request.toolCall.toolCallId,
|
||||
title: request.toolCall.title || "Permission Request",
|
||||
status: "waiting_for_confirmation",
|
||||
title: request.toolCall.title || 'Permission Request',
|
||||
status: 'waiting_for_confirmation',
|
||||
permissionRequest: {
|
||||
requestId: request.requestId,
|
||||
options: request.options,
|
||||
@@ -259,27 +263,24 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
}
|
||||
|
||||
// Handle agent message chunk
|
||||
if (update.sessionUpdate === "agent_message_chunk") {
|
||||
const text = update.content.type === "text" && update.content.text ? update.content.text : "";
|
||||
if (update.sessionUpdate === 'agent_message_chunk') {
|
||||
const text = update.content.type === 'text' && update.content.text ? update.content.text : '';
|
||||
if (!text) return;
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
const lastEntry = prev[prev.length - 1];
|
||||
|
||||
// If last entry is AssistantMessage, append to it
|
||||
if (lastEntry?.type === "assistant_message") {
|
||||
if (lastEntry?.type === 'assistant_message') {
|
||||
const lastChunk = lastEntry.chunks[lastEntry.chunks.length - 1];
|
||||
|
||||
// If last chunk is same type (message), append text
|
||||
if (lastChunk?.type === "message") {
|
||||
if (lastChunk?.type === 'message') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [
|
||||
...lastEntry.chunks.slice(0, -1),
|
||||
{ type: "message", text: lastChunk.text + text },
|
||||
],
|
||||
chunks: [...lastEntry.chunks.slice(0, -1), { type: 'message', text: lastChunk.text + text }],
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -289,42 +290,39 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [...lastEntry.chunks, { type: "message", text }],
|
||||
chunks: [...lastEntry.chunks, { type: 'message', text }],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// Create new AssistantMessage entry
|
||||
const newEntry: AssistantMessageEntry = {
|
||||
type: "assistant_message",
|
||||
type: 'assistant_message',
|
||||
id: `assistant-${Date.now()}`,
|
||||
chunks: [{ type: "message", text }],
|
||||
chunks: [{ type: 'message', text }],
|
||||
};
|
||||
return [...prev, newEntry];
|
||||
});
|
||||
}
|
||||
// Handle agent thought chunk (NEW - was missing before)
|
||||
else if (update.sessionUpdate === "agent_thought_chunk") {
|
||||
const text = update.content.type === "text" && update.content.text ? update.content.text : "";
|
||||
else if (update.sessionUpdate === 'agent_thought_chunk') {
|
||||
const text = update.content.type === 'text' && update.content.text ? update.content.text : '';
|
||||
if (!text) return;
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
const lastEntry = prev[prev.length - 1];
|
||||
|
||||
// If last entry is AssistantMessage, append to it
|
||||
if (lastEntry?.type === "assistant_message") {
|
||||
if (lastEntry?.type === 'assistant_message') {
|
||||
const lastChunk = lastEntry.chunks[lastEntry.chunks.length - 1];
|
||||
|
||||
// If last chunk is same type (thought), append text
|
||||
if (lastChunk?.type === "thought") {
|
||||
if (lastChunk?.type === 'thought') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [
|
||||
...lastEntry.chunks.slice(0, -1),
|
||||
{ type: "thought", text: lastChunk.text + text },
|
||||
],
|
||||
chunks: [...lastEntry.chunks.slice(0, -1), { type: 'thought', text: lastChunk.text + text }],
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -334,30 +332,30 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...lastEntry,
|
||||
chunks: [...lastEntry.chunks, { type: "thought", text }],
|
||||
chunks: [...lastEntry.chunks, { type: 'thought', text }],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// Create new AssistantMessage entry with thought
|
||||
const newEntry: AssistantMessageEntry = {
|
||||
type: "assistant_message",
|
||||
type: 'assistant_message',
|
||||
id: `assistant-${Date.now()}`,
|
||||
chunks: [{ type: "thought", text }],
|
||||
chunks: [{ type: 'thought', text }],
|
||||
};
|
||||
return [...prev, newEntry];
|
||||
});
|
||||
}
|
||||
// Handle user message chunk (NEW - was missing before)
|
||||
else if (update.sessionUpdate === "user_message_chunk") {
|
||||
const text = update.content.type === "text" && update.content.text ? update.content.text : "";
|
||||
else if (update.sessionUpdate === 'user_message_chunk') {
|
||||
const text = update.content.type === 'text' && update.content.text ? update.content.text : '';
|
||||
if (!text) return;
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
const lastEntry = prev[prev.length - 1];
|
||||
|
||||
// If last entry is UserMessage, append to it
|
||||
if (lastEntry?.type === "user_message") {
|
||||
if (lastEntry?.type === 'user_message') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
@@ -369,7 +367,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
// Create new UserMessage entry
|
||||
const newEntry: UserMessageEntry = {
|
||||
type: "user_message",
|
||||
type: 'user_message',
|
||||
id: `user-${Date.now()}`,
|
||||
content: text,
|
||||
};
|
||||
@@ -377,7 +375,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
});
|
||||
}
|
||||
// Handle tool call (UPSERT - update if exists, create if not)
|
||||
else if (update.sessionUpdate === "tool_call") {
|
||||
else if (update.sessionUpdate === 'tool_call') {
|
||||
const toolCallData: ToolCallData = {
|
||||
id: update.toolCallId,
|
||||
title: update.title,
|
||||
@@ -387,7 +385,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
rawOutput: update.rawOutput,
|
||||
};
|
||||
|
||||
setEntries((prev) => {
|
||||
setEntries(prev => {
|
||||
// UPSERT: Check if tool call already exists
|
||||
const existingIndex = findToolCallIndex(prev, update.toolCallId);
|
||||
|
||||
@@ -395,10 +393,10 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// UPDATE existing tool call
|
||||
return prev.map((entry, index) => {
|
||||
if (index !== existingIndex) return entry;
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
|
||||
return {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
...toolCallData,
|
||||
@@ -409,27 +407,27 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
// CREATE new tool call entry
|
||||
const newEntry: ToolCallEntry = {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: toolCallData,
|
||||
};
|
||||
return [...prev, newEntry];
|
||||
});
|
||||
}
|
||||
// Handle tool call update (partial update)
|
||||
else if (update.sessionUpdate === "tool_call_update") {
|
||||
setEntries((prev) => {
|
||||
else if (update.sessionUpdate === 'tool_call_update') {
|
||||
setEntries(prev => {
|
||||
const existingIndex = findToolCallIndex(prev, update.toolCallId);
|
||||
|
||||
if (existingIndex < 0) {
|
||||
// Tool call not found - create a failed tool call entry (like Zed)
|
||||
console.warn(`[ChatInterface] Tool call not found for update: ${update.toolCallId}`);
|
||||
const failedEntry: ToolCallEntry = {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
id: update.toolCallId,
|
||||
title: update.title || "Tool call not found",
|
||||
status: "error",
|
||||
content: [{ type: "content", content: { type: "text", text: "Tool call not found" } }],
|
||||
title: update.title || 'Tool call not found',
|
||||
status: 'error',
|
||||
content: [{ type: 'content', content: { type: 'text', text: 'Tool call not found' } }],
|
||||
},
|
||||
};
|
||||
return [...prev, failedEntry];
|
||||
@@ -437,7 +435,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
return prev.map((entry, index) => {
|
||||
if (index !== existingIndex) return entry;
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
|
||||
const newStatus = update.status ? mapToolStatus(update.status) : entry.toolCall.status;
|
||||
const mergedContent = update.content
|
||||
@@ -445,7 +443,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
: entry.toolCall.content;
|
||||
|
||||
return {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: newStatus,
|
||||
@@ -459,31 +457,24 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
});
|
||||
}
|
||||
// Handle plan update (replace entire plan)
|
||||
else if (update.sessionUpdate === "plan") {
|
||||
setEntries((prev) => {
|
||||
else if (update.sessionUpdate === 'plan') {
|
||||
setEntries(prev => {
|
||||
// Empty entries → remove existing plan
|
||||
if (update.entries.length === 0) {
|
||||
return prev.filter((e) => e.type !== "plan");
|
||||
return prev.filter(e => e.type !== 'plan');
|
||||
}
|
||||
|
||||
// Find last plan entry
|
||||
const lastPlanIndex = prev.reduce(
|
||||
(acc, entry, i) => (entry.type === "plan" ? i : acc),
|
||||
-1,
|
||||
);
|
||||
const lastPlanIndex = prev.reduce((acc, entry, i) => (entry.type === 'plan' ? i : acc), -1);
|
||||
|
||||
if (lastPlanIndex >= 0) {
|
||||
// Update existing plan in place
|
||||
return prev.map((entry, index) =>
|
||||
index === lastPlanIndex
|
||||
? { ...entry, entries: update.entries }
|
||||
: entry,
|
||||
);
|
||||
return prev.map((entry, index) => (index === lastPlanIndex ? { ...entry, entries: update.entries } : entry));
|
||||
}
|
||||
|
||||
// Create new plan entry
|
||||
const newPlanEntry: PlanDisplayEntry = {
|
||||
type: "plan",
|
||||
type: 'plan',
|
||||
id: `plan-${Date.now()}`,
|
||||
entries: update.entries,
|
||||
};
|
||||
@@ -496,18 +487,18 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Setup Effect
|
||||
// =============================================================================
|
||||
useEffect(() => {
|
||||
client.setSessionCreatedHandler((sessionId) => {
|
||||
console.log("[ChatInterface] Session created:", sessionId);
|
||||
client.setSessionCreatedHandler(sessionId => {
|
||||
console.log('[ChatInterface] Session created:', sessionId);
|
||||
activateSession(sessionId);
|
||||
});
|
||||
|
||||
client.setSessionLoadedHandler((sessionId) => {
|
||||
console.log("[ChatInterface] Session loaded/resumed:", sessionId);
|
||||
client.setSessionLoadedHandler(sessionId => {
|
||||
console.log('[ChatInterface] Session loaded/resumed:', sessionId);
|
||||
activateSession(sessionId, { resetEntries: false });
|
||||
});
|
||||
|
||||
client.setSessionSwitchingHandler((sessionId) => {
|
||||
console.log("[ChatInterface] Switching to session:", sessionId);
|
||||
client.setSessionSwitchingHandler(sessionId => {
|
||||
console.log('[ChatInterface] Switching to session:', sessionId);
|
||||
setActiveSessionId(sessionId);
|
||||
resetThreadState();
|
||||
});
|
||||
@@ -516,8 +507,8 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
handleSessionUpdate(sessionId, update);
|
||||
});
|
||||
|
||||
client.setPromptCompleteHandler((stopReason) => {
|
||||
console.log("[ChatInterface] Prompt complete:", stopReason);
|
||||
client.setPromptCompleteHandler(stopReason => {
|
||||
console.log('[ChatInterface] Prompt complete:', stopReason);
|
||||
// Always set isLoading=false when prompt completes
|
||||
// This includes stopReason="cancelled" (which is the expected response after client.cancel())
|
||||
// Note: Tool calls are already marked as "canceled" in handleCancel before this fires
|
||||
@@ -526,8 +517,8 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
client.setPermissionRequestHandler(handlePermissionRequest);
|
||||
|
||||
client.setErrorMessageHandler((msg) => {
|
||||
console.error("[ChatInterface] Agent error:", msg);
|
||||
client.setErrorMessageHandler(msg => {
|
||||
console.error('[ChatInterface] Agent error:', msg);
|
||||
setErrorMessage(msg);
|
||||
// Clear any existing timer
|
||||
if (errorTimerRef.current) clearTimeout(errorTimerRef.current);
|
||||
@@ -538,7 +529,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Restore last session or create a new one
|
||||
const lastSessionId = storageKey ? localStorage.getItem(storageKey) : null;
|
||||
if (lastSessionId && (client.supportsLoadSession || client.supportsResumeSession)) {
|
||||
console.log("[ChatInterface] Restoring session:", lastSessionId);
|
||||
console.log('[ChatInterface] Restoring session:', lastSessionId);
|
||||
const restore = async () => {
|
||||
try {
|
||||
if (client.supportsLoadSession) {
|
||||
@@ -547,7 +538,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
await client.resumeSession({ sessionId: lastSessionId });
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("[ChatInterface] Failed to restore session, creating new one:", err);
|
||||
console.warn('[ChatInterface] Failed to restore session, creating new one:', err);
|
||||
client.createSession(undefined, permissionMode);
|
||||
}
|
||||
};
|
||||
@@ -575,7 +566,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Creates a new session by clearing current state and calling new_session
|
||||
// This is the core of Zed's NewThread action
|
||||
const handleNewSession = useCallback(() => {
|
||||
console.log("[ChatInterface] Creating new session...");
|
||||
console.log('[ChatInterface] Creating new session...');
|
||||
|
||||
// Reference: Zed's set_server_state() calls close_all_sessions() before setting new state
|
||||
// Cancel any ongoing request before creating new session
|
||||
@@ -597,26 +588,25 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// 2. Send cancel notification to agent
|
||||
// 3. Do NOT set isLoading=false here - wait for prompt_complete with stopReason="cancelled"
|
||||
const handleCancel = () => {
|
||||
console.log("[ChatInterface] Cancel requested");
|
||||
console.log('[ChatInterface] Cancel requested');
|
||||
|
||||
// Like Zed: iterate all entries, mark Pending/WaitingForConfirmation/InProgress tool calls as Canceled
|
||||
setEntries((prev) =>
|
||||
prev.map((entry) => {
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
setEntries(prev =>
|
||||
prev.map(entry => {
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
|
||||
// Check if status should be canceled (matches Zed's logic)
|
||||
const shouldCancel =
|
||||
entry.toolCall.status === "running" ||
|
||||
entry.toolCall.status === "waiting_for_confirmation";
|
||||
entry.toolCall.status === 'running' || entry.toolCall.status === 'waiting_for_confirmation';
|
||||
|
||||
if (!shouldCancel) return entry;
|
||||
|
||||
console.log("[ChatInterface] Marking tool call as canceled:", entry.toolCall.id);
|
||||
console.log('[ChatInterface] Marking tool call as canceled:', entry.toolCall.id);
|
||||
return {
|
||||
type: "tool_call",
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: "canceled" as ToolCallStatus,
|
||||
status: 'canceled' as ToolCallStatus,
|
||||
permissionRequest: undefined, // Clear any pending permission request
|
||||
},
|
||||
};
|
||||
@@ -629,42 +619,45 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
// Wait for prompt_complete with stopReason="cancelled" from the agent
|
||||
};
|
||||
|
||||
const handlePermissionResponse = useCallback((requestId: string, optionId: string | null, optionKind: PermissionOption["kind"] | null) => {
|
||||
console.log("[ChatInterface] Permission response:", { requestId, optionId, optionKind });
|
||||
client.respondToPermission(requestId, optionId);
|
||||
const handlePermissionResponse = useCallback(
|
||||
(requestId: string, optionId: string | null, optionKind: PermissionOption['kind'] | null) => {
|
||||
console.log('[ChatInterface] Permission response:', { requestId, optionId, optionKind });
|
||||
client.respondToPermission(requestId, optionId);
|
||||
|
||||
// Determine new status based on option kind
|
||||
const isRejected = optionKind === "reject_once" || optionKind === "reject_always" || optionId === null;
|
||||
// Determine new status based on option kind
|
||||
const isRejected = optionKind === 'reject_once' || optionKind === 'reject_always' || optionId === null;
|
||||
|
||||
// Update the tool call status in entries
|
||||
setEntries((prev) =>
|
||||
prev.map((entry) => {
|
||||
if (entry.type !== "tool_call") return entry;
|
||||
if (entry.toolCall.permissionRequest?.requestId !== requestId) return entry;
|
||||
// Update the tool call status in entries
|
||||
setEntries(prev =>
|
||||
prev.map(entry => {
|
||||
if (entry.type !== 'tool_call') return entry;
|
||||
if (entry.toolCall.permissionRequest?.requestId !== requestId) return entry;
|
||||
|
||||
// For standalone permission requests, mark as complete immediately when approved
|
||||
// For regular tool calls, mark as running (agent will update to complete later)
|
||||
let newStatus: ToolCallStatus;
|
||||
if (isRejected) {
|
||||
newStatus = "rejected";
|
||||
} else if (entry.toolCall.isStandalonePermission) {
|
||||
newStatus = "complete";
|
||||
} else {
|
||||
newStatus = "running";
|
||||
}
|
||||
// For standalone permission requests, mark as complete immediately when approved
|
||||
// For regular tool calls, mark as running (agent will update to complete later)
|
||||
let newStatus: ToolCallStatus;
|
||||
if (isRejected) {
|
||||
newStatus = 'rejected';
|
||||
} else if (entry.toolCall.isStandalonePermission) {
|
||||
newStatus = 'complete';
|
||||
} else {
|
||||
newStatus = 'running';
|
||||
}
|
||||
|
||||
return {
|
||||
type: "tool_call",
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: newStatus,
|
||||
permissionRequest: undefined,
|
||||
isStandalonePermission: undefined,
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
}, [client]);
|
||||
return {
|
||||
type: 'tool_call',
|
||||
toolCall: {
|
||||
...entry.toolCall,
|
||||
status: newStatus,
|
||||
permissionRequest: undefined,
|
||||
isStandalonePermission: undefined,
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
[client],
|
||||
);
|
||||
|
||||
// =============================================================================
|
||||
// Render
|
||||
@@ -672,8 +665,11 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
|
||||
// Collect pending permissions from tool call entries
|
||||
const pendingPermissions: PendingPermission[] = entries
|
||||
.filter((e): e is ToolCallEntry => e.type === "tool_call" && e.toolCall.status === "waiting_for_confirmation" && !!e.toolCall.permissionRequest)
|
||||
.map((e) => ({
|
||||
.filter(
|
||||
(e): e is ToolCallEntry =>
|
||||
e.type === 'tool_call' && e.toolCall.status === 'waiting_for_confirmation' && !!e.toolCall.permissionRequest,
|
||||
)
|
||||
.map(e => ({
|
||||
requestId: e.toolCall.permissionRequest!.requestId,
|
||||
toolName: e.toolCall.title,
|
||||
toolInput: e.toolCall.rawInput || {},
|
||||
@@ -682,120 +678,128 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
}));
|
||||
|
||||
// Handle permission respond for unified PermissionPanel
|
||||
const handlePermissionPanelRespond = useCallback((requestId: string, approved: boolean) => {
|
||||
// Find the matching permission request to get the real optionId
|
||||
const perm = pendingPermissions.find((p) => p.requestId === requestId);
|
||||
let optionId: string | null = null;
|
||||
let optionKind: PermissionOption["kind"] | null = null;
|
||||
const handlePermissionPanelRespond = useCallback(
|
||||
(requestId: string, approved: boolean) => {
|
||||
// Find the matching permission request to get the real optionId
|
||||
const perm = pendingPermissions.find(p => p.requestId === requestId);
|
||||
let optionId: string | null = null;
|
||||
let optionKind: PermissionOption['kind'] | null = null;
|
||||
|
||||
if (perm?.options && perm.options.length > 0) {
|
||||
if (approved) {
|
||||
// Pick the first allow option (prefer allow_once, then allow_always)
|
||||
const allowOpt = perm.options.find((o) => o.kind === "allow_once") ?? perm.options.find((o) => o.kind === "allow_always");
|
||||
if (allowOpt) {
|
||||
optionId = allowOpt.optionId;
|
||||
optionKind = allowOpt.kind;
|
||||
}
|
||||
} else {
|
||||
// Pick the first reject option
|
||||
const rejectOpt = perm.options.find((o) => o.kind === "reject_once") ?? perm.options.find((o) => o.kind === "reject_always");
|
||||
if (rejectOpt) {
|
||||
optionId = rejectOpt.optionId;
|
||||
optionKind = rejectOpt.kind;
|
||||
if (perm?.options && perm.options.length > 0) {
|
||||
if (approved) {
|
||||
// Pick the first allow option (prefer allow_once, then allow_always)
|
||||
const allowOpt =
|
||||
perm.options.find(o => o.kind === 'allow_once') ?? perm.options.find(o => o.kind === 'allow_always');
|
||||
if (allowOpt) {
|
||||
optionId = allowOpt.optionId;
|
||||
optionKind = allowOpt.kind;
|
||||
}
|
||||
} else {
|
||||
// Pick the first reject option
|
||||
const rejectOpt =
|
||||
perm.options.find(o => o.kind === 'reject_once') ?? perm.options.find(o => o.kind === 'reject_always');
|
||||
if (rejectOpt) {
|
||||
optionId = rejectOpt.optionId;
|
||||
optionKind = rejectOpt.kind;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: if no matching option found, use null (cancelled)
|
||||
if (!optionId) {
|
||||
optionKind = approved ? "allow_once" : "reject_once";
|
||||
}
|
||||
// Fallback: if no matching option found, use null (cancelled)
|
||||
if (!optionId) {
|
||||
optionKind = approved ? 'allow_once' : 'reject_once';
|
||||
}
|
||||
|
||||
handlePermissionResponse(requestId, optionId, optionKind);
|
||||
}, [handlePermissionResponse, pendingPermissions]);
|
||||
handlePermissionResponse(requestId, optionId, optionKind);
|
||||
},
|
||||
[handlePermissionResponse, pendingPermissions],
|
||||
);
|
||||
|
||||
// Handle ChatInput submit — convert ChatInputMessage to ContentBlock[]
|
||||
const handleChatInputSubmit = useCallback(async (message: ChatInputMessage) => {
|
||||
const text = message.text.trim();
|
||||
const images = message.images || [];
|
||||
const handleChatInputSubmit = useCallback(
|
||||
async (message: ChatInputMessage) => {
|
||||
const text = message.text.trim();
|
||||
const images = message.images || [];
|
||||
|
||||
if ((!text && images.length === 0) || isLoading || !sessionReady) return;
|
||||
if ((!text && images.length === 0) || isLoading || !sessionReady) return;
|
||||
|
||||
const contentBlocks: ContentBlock[] = [];
|
||||
const contentBlocks: ContentBlock[] = [];
|
||||
|
||||
if (text) {
|
||||
contentBlocks.push({ type: "text", text });
|
||||
}
|
||||
|
||||
// Convert images to ContentBlock
|
||||
const userImages: UserMessageImage[] = [];
|
||||
|
||||
for (const img of images) {
|
||||
try {
|
||||
const dataUrl = `data:${img.mimeType};base64,${img.data}`;
|
||||
let blob: Blob;
|
||||
if (dataUrl.startsWith("data:")) {
|
||||
blob = dataUrlToBlob(dataUrl);
|
||||
} else {
|
||||
const response = await fetch(dataUrl);
|
||||
blob = await response.blob();
|
||||
}
|
||||
|
||||
let finalBlob: Blob = blob;
|
||||
let finalMimeType = img.mimeType;
|
||||
|
||||
if (blob.size > 2 * 1024 * 1024) {
|
||||
const imageFile = new File([blob], "image.jpg", { type: blob.type });
|
||||
finalBlob = await imageCompression(imageFile, IMAGE_COMPRESSION_OPTIONS);
|
||||
finalMimeType = "image/jpeg";
|
||||
}
|
||||
|
||||
const base64Data = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const result = reader.result as string;
|
||||
const commaIndex = result.indexOf(",");
|
||||
resolve(commaIndex >= 0 ? result.slice(commaIndex + 1) : result);
|
||||
};
|
||||
reader.onerror = () => reject(new Error("FileReader error: " + reader.error?.message));
|
||||
reader.readAsDataURL(finalBlob);
|
||||
});
|
||||
|
||||
const imageContent: ImageContent = {
|
||||
type: "image",
|
||||
mimeType: finalMimeType,
|
||||
data: base64Data,
|
||||
};
|
||||
contentBlocks.push(imageContent);
|
||||
|
||||
userImages.push({
|
||||
mimeType: finalMimeType,
|
||||
data: base64Data,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[ChatInterface] Failed to process image:", error);
|
||||
if (text) {
|
||||
contentBlocks.push({ type: 'text', text });
|
||||
}
|
||||
}
|
||||
|
||||
if (contentBlocks.length === 0) return;
|
||||
// Convert images to ContentBlock
|
||||
const userImages: UserMessageImage[] = [];
|
||||
|
||||
// Add user message entry
|
||||
const userEntry: UserMessageEntry = {
|
||||
type: "user_message",
|
||||
id: `user-${Date.now()}`,
|
||||
content: text,
|
||||
images: userImages.length > 0 ? userImages : undefined,
|
||||
};
|
||||
setEntries((prev) => [...prev, userEntry]);
|
||||
setIsLoading(true);
|
||||
for (const img of images) {
|
||||
try {
|
||||
const dataUrl = `data:${img.mimeType};base64,${img.data}`;
|
||||
let blob: Blob;
|
||||
if (dataUrl.startsWith('data:')) {
|
||||
blob = dataUrlToBlob(dataUrl);
|
||||
} else {
|
||||
const response = await fetch(dataUrl);
|
||||
blob = await response.blob();
|
||||
}
|
||||
|
||||
try {
|
||||
await client.sendPrompt(contentBlocks);
|
||||
} catch (error) {
|
||||
console.error("[ChatInterface] Failed to send prompt:", error);
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isLoading, sessionReady, client]);
|
||||
let finalBlob: Blob = blob;
|
||||
let finalMimeType = img.mimeType;
|
||||
|
||||
if (blob.size > 2 * 1024 * 1024) {
|
||||
const imageFile = new File([blob], 'image.jpg', { type: blob.type });
|
||||
finalBlob = await imageCompression(imageFile, IMAGE_COMPRESSION_OPTIONS);
|
||||
finalMimeType = 'image/jpeg';
|
||||
}
|
||||
|
||||
const base64Data = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const result = reader.result as string;
|
||||
const commaIndex = result.indexOf(',');
|
||||
resolve(commaIndex >= 0 ? result.slice(commaIndex + 1) : result);
|
||||
};
|
||||
reader.onerror = () => reject(new Error('FileReader error: ' + reader.error?.message));
|
||||
reader.readAsDataURL(finalBlob);
|
||||
});
|
||||
|
||||
const imageContent: ImageContent = {
|
||||
type: 'image',
|
||||
mimeType: finalMimeType,
|
||||
data: base64Data,
|
||||
};
|
||||
contentBlocks.push(imageContent);
|
||||
|
||||
userImages.push({
|
||||
mimeType: finalMimeType,
|
||||
data: base64Data,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[ChatInterface] Failed to process image:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (contentBlocks.length === 0) return;
|
||||
|
||||
// Add user message entry
|
||||
const userEntry: UserMessageEntry = {
|
||||
type: 'user_message',
|
||||
id: `user-${Date.now()}`,
|
||||
content: text,
|
||||
images: userImages.length > 0 ? userImages : undefined,
|
||||
};
|
||||
setEntries(prev => [...prev, userEntry]);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
await client.sendPrompt(contentBlocks);
|
||||
} catch (error) {
|
||||
console.error('[ChatInterface] Failed to send prompt:', error);
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[isLoading, sessionReady, client],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
@@ -804,17 +808,14 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
entries={entries}
|
||||
isLoading={isLoading && !sessionReady ? false : isLoading}
|
||||
onPermissionRespond={(requestId, optionId, optionKind) => {
|
||||
handlePermissionResponse(requestId, optionId, optionKind as PermissionOption["kind"] | null);
|
||||
handlePermissionResponse(requestId, optionId, optionKind as PermissionOption['kind'] | null);
|
||||
}}
|
||||
emptyTitle={sessionReady ? "开始对话" : undefined}
|
||||
emptyDescription={sessionReady ? "输入消息开始与 ACP agent 聊天" : undefined}
|
||||
emptyTitle={sessionReady ? '开始对话' : undefined}
|
||||
emptyDescription={sessionReady ? '输入消息开始与 ACP agent 聊天' : undefined}
|
||||
/>
|
||||
|
||||
{/* Permission panel — fixed above input */}
|
||||
<PermissionPanel
|
||||
requests={pendingPermissions}
|
||||
onRespond={handlePermissionPanelRespond}
|
||||
/>
|
||||
<PermissionPanel requests={pendingPermissions} onRespond={handlePermissionPanelRespond} />
|
||||
|
||||
{/* Error banner */}
|
||||
{errorMessage && (
|
||||
@@ -826,7 +827,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
onClick={() => setErrorMessage(null)}
|
||||
className="ml-2 text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-200 flex-shrink-0"
|
||||
>
|
||||
{"\u00D7"}
|
||||
{'\u00D7'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -836,7 +837,13 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
<div className="flex-shrink-0">
|
||||
<div className="max-w-3xl mx-auto w-full px-4 sm:px-8 pb-1 flex items-center justify-between">
|
||||
<div className="flex items-center gap-1">
|
||||
<PermissionModeSelector mode={permissionMode} onModeChange={(m: string) => { setPermissionMode(m); localStorage.setItem("acp_permission_mode", m); }} />
|
||||
<PermissionModeSelector
|
||||
mode={permissionMode}
|
||||
onModeChange={(m: string) => {
|
||||
setPermissionMode(m);
|
||||
localStorage.setItem('acp_permission_mode', m);
|
||||
}}
|
||||
/>
|
||||
<ModelSelectorPopover client={client} />
|
||||
</div>
|
||||
{entries.length > 0 && (
|
||||
@@ -861,7 +868,7 @@ export function ChatInterface({ client, agentId }: ChatInterfaceProps) {
|
||||
isLoading={isLoading}
|
||||
onInterrupt={handleCancel}
|
||||
disabled={!sessionReady}
|
||||
placeholder={sessionReady ? "给 Claude 发送消息…" : "等待会话..."}
|
||||
placeholder={sessionReady ? '给 Claude 发送消息…' : '等待会话...'}
|
||||
supportsImages={supportsImages}
|
||||
commands={availableCommands.length > 0 ? availableCommands : undefined}
|
||||
/>
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { cn } from "../src/lib/utils";
|
||||
import { User, Bot, Wrench, Loader2 } from "lucide-react";
|
||||
import { cn } from '../src/lib/utils';
|
||||
import { User, Bot, Wrench, Loader2 } from 'lucide-react';
|
||||
|
||||
export interface ToolCall {
|
||||
id: string;
|
||||
title: string;
|
||||
status: "running" | "complete" | "error";
|
||||
status: 'running' | 'complete' | 'error';
|
||||
}
|
||||
|
||||
export interface ChatMessageData {
|
||||
id: string;
|
||||
role: "user" | "agent";
|
||||
role: 'user' | 'agent';
|
||||
content: string;
|
||||
toolCalls?: ToolCall[];
|
||||
isStreaming?: boolean;
|
||||
@@ -20,36 +20,27 @@ interface ChatMessageProps {
|
||||
}
|
||||
|
||||
export function ChatMessage({ message }: ChatMessageProps) {
|
||||
const isUser = message.role === "user";
|
||||
const isUser = message.role === 'user';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex gap-3 p-4 rounded-lg",
|
||||
isUser ? "bg-muted/50" : "bg-background"
|
||||
)}
|
||||
>
|
||||
<div className={cn('flex gap-3 p-4 rounded-lg', isUser ? 'bg-muted/50' : 'bg-background')}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center",
|
||||
isUser ? "bg-primary text-primary-foreground" : "bg-secondary"
|
||||
'flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center',
|
||||
isUser ? 'bg-primary text-primary-foreground' : 'bg-secondary',
|
||||
)}
|
||||
>
|
||||
{isUser ? <User className="w-4 h-4" /> : <Bot className="w-4 h-4" />}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<div className="text-sm font-medium">
|
||||
{isUser ? "You" : "Agent"}
|
||||
</div>
|
||||
<div className="text-sm font-medium">{isUser ? 'You' : 'Agent'}</div>
|
||||
<div className="text-sm whitespace-pre-wrap break-words">
|
||||
{message.content}
|
||||
{message.isStreaming && (
|
||||
<span className="inline-block w-1.5 h-4 ml-0.5 bg-foreground animate-pulse" />
|
||||
)}
|
||||
{message.isStreaming && <span className="inline-block w-1.5 h-4 ml-0.5 bg-foreground animate-pulse" />}
|
||||
</div>
|
||||
{message.toolCalls && message.toolCalls.length > 0 && (
|
||||
<div className="space-y-1.5 pt-2">
|
||||
{message.toolCalls.map((tool) => (
|
||||
{message.toolCalls.map(tool => (
|
||||
<ToolCallDisplay key={tool.id} toolCall={tool} />
|
||||
))}
|
||||
</div>
|
||||
@@ -67,31 +58,34 @@ function ToolCallDisplay({ toolCall }: ToolCallDisplayProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-xs px-2 py-1.5 rounded border",
|
||||
toolCall.status === "running" && "bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800",
|
||||
toolCall.status === "complete" && "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800",
|
||||
toolCall.status === "error" && "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"
|
||||
'flex items-center gap-2 text-xs px-2 py-1.5 rounded border',
|
||||
toolCall.status === 'running' && 'bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800',
|
||||
toolCall.status === 'complete' && 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800',
|
||||
toolCall.status === 'error' && 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800',
|
||||
)}
|
||||
>
|
||||
{toolCall.status === "running" ? (
|
||||
{toolCall.status === 'running' ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin text-yellow-600 dark:text-yellow-400" />
|
||||
) : (
|
||||
<Wrench className={cn(
|
||||
"w-3 h-3",
|
||||
toolCall.status === "complete" && "text-green-600 dark:text-green-400",
|
||||
toolCall.status === "error" && "text-red-600 dark:text-red-400"
|
||||
)} />
|
||||
<Wrench
|
||||
className={cn(
|
||||
'w-3 h-3',
|
||||
toolCall.status === 'complete' && 'text-green-600 dark:text-green-400',
|
||||
toolCall.status === 'error' && 'text-red-600 dark:text-red-400',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<span className="truncate">{toolCall.title}</span>
|
||||
<span className={cn(
|
||||
"ml-auto text-[10px] uppercase font-medium",
|
||||
toolCall.status === "running" && "text-yellow-600 dark:text-yellow-400",
|
||||
toolCall.status === "complete" && "text-green-600 dark:text-green-400",
|
||||
toolCall.status === "error" && "text-red-600 dark:text-red-400"
|
||||
)}>
|
||||
<span
|
||||
className={cn(
|
||||
'ml-auto text-[10px] uppercase font-medium',
|
||||
toolCall.status === 'running' && 'text-yellow-600 dark:text-yellow-400',
|
||||
toolCall.status === 'complete' && 'text-green-600 dark:text-green-400',
|
||||
toolCall.status === 'error' && 'text-red-600 dark:text-red-400',
|
||||
)}
|
||||
>
|
||||
{toolCall.status}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from "react";
|
||||
import { Search, Clock, RefreshCw } from "lucide-react";
|
||||
import type { ACPClient } from "../src/acp/client";
|
||||
import type { AgentSessionInfo } from "../src/acp/types";
|
||||
import { Input } from "./ui/input";
|
||||
import { ScrollArea } from "./ui/scroll-area";
|
||||
import { Button } from "./ui/button";
|
||||
import { cn } from "../src/lib/utils";
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { Search, Clock, RefreshCw } from 'lucide-react';
|
||||
import type { ACPClient } from '../src/acp/client';
|
||||
import type { AgentSessionInfo } from '../src/acp/types';
|
||||
import { Input } from './ui/input';
|
||||
import { ScrollArea } from './ui/scroll-area';
|
||||
import { Button } from './ui/button';
|
||||
import { cn } from '../src/lib/utils';
|
||||
|
||||
// Reference: Zed's TimeBucket in thread_history.rs
|
||||
type TimeBucket = "today" | "yesterday" | "thisWeek" | "pastWeek" | "all";
|
||||
type TimeBucket = 'today' | 'yesterday' | 'thisWeek' | 'pastWeek' | 'all';
|
||||
|
||||
// Reference: Zed's Display impl for TimeBucket
|
||||
const BUCKET_LABELS: Record<TimeBucket, string> = {
|
||||
today: "Today",
|
||||
yesterday: "Yesterday",
|
||||
thisWeek: "This Week",
|
||||
pastWeek: "Past Week",
|
||||
all: "All", // Zed uses "All", not "Older"
|
||||
today: 'Today',
|
||||
yesterday: 'Yesterday',
|
||||
thisWeek: 'This Week',
|
||||
pastWeek: 'Past Week',
|
||||
all: 'All', // Zed uses "All", not "Older"
|
||||
};
|
||||
|
||||
// Reference: Zed's TimeBucket::from_dates (line 1028-1051)
|
||||
@@ -29,14 +29,14 @@ function getTimeBucket(date: Date): TimeBucket {
|
||||
|
||||
const entryDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
|
||||
if (entryDate.getTime() === today.getTime()) return "today";
|
||||
if (entryDate.getTime() === yesterday.getTime()) return "yesterday";
|
||||
if (entryDate.getTime() === today.getTime()) return 'today';
|
||||
if (entryDate.getTime() === yesterday.getTime()) return 'yesterday';
|
||||
|
||||
// This week: same ISO week AND year
|
||||
const todayIsoWeek = getISOWeekYear(today);
|
||||
const entryIsoWeek = getISOWeekYear(entryDate);
|
||||
if (todayIsoWeek.year === entryIsoWeek.year && todayIsoWeek.week === entryIsoWeek.week) {
|
||||
return "thisWeek";
|
||||
return 'thisWeek';
|
||||
}
|
||||
|
||||
// Past week: (reference - 7days).iso_week()
|
||||
@@ -44,10 +44,10 @@ function getTimeBucket(date: Date): TimeBucket {
|
||||
lastWeekDate.setDate(lastWeekDate.getDate() - 7);
|
||||
const lastWeekIsoWeek = getISOWeekYear(lastWeekDate);
|
||||
if (lastWeekIsoWeek.year === entryIsoWeek.year && lastWeekIsoWeek.week === entryIsoWeek.week) {
|
||||
return "pastWeek";
|
||||
return 'pastWeek';
|
||||
}
|
||||
|
||||
return "all";
|
||||
return 'all';
|
||||
}
|
||||
|
||||
// Returns ISO week number AND ISO week year (important for year boundaries)
|
||||
@@ -57,13 +57,13 @@ function getISOWeekYear(date: Date): { week: number; year: number } {
|
||||
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
|
||||
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
|
||||
const week = Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
|
||||
return { week, year: d.getUTCFullYear() }; // ISO week year, not calendar year
|
||||
return { week, year: d.getUTCFullYear() }; // ISO week year, not calendar year
|
||||
}
|
||||
|
||||
// Reference: Zed's formatted_time in HistoryEntryElement (line 904-921)
|
||||
// Exact format: Xd, Xh ago, Xm ago, Just now, Unknown
|
||||
function formatRelativeTime(date: Date | null): string {
|
||||
if (!date) return "Unknown"; // Zed uses "Unknown" for missing updatedAt
|
||||
if (!date) return 'Unknown'; // Zed uses "Unknown" for missing updatedAt
|
||||
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
@@ -74,7 +74,7 @@ function formatRelativeTime(date: Date | null): string {
|
||||
if (diffDays > 0) return `${diffDays}d`;
|
||||
if (diffHours > 0) return `${diffHours}h ago`;
|
||||
if (diffMinutes > 0) return `${diffMinutes}m ago`;
|
||||
return "Just now";
|
||||
return 'Just now';
|
||||
}
|
||||
|
||||
interface ThreadHistoryProps {
|
||||
@@ -90,7 +90,7 @@ interface GroupedSessions {
|
||||
|
||||
export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
const [sessions, setSessions] = useState<AgentSessionInfo[]>([]);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
// Start with isLoading=true to prevent flash of "no threads" message
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -103,7 +103,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
|
||||
const loadSessions = useCallback(async () => {
|
||||
if (!client.supportsSessionList) {
|
||||
setError("Session list not supported by this agent");
|
||||
setError('Session list not supported by this agent');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
@@ -139,7 +139,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
if (searchQuery.trim()) {
|
||||
const query = searchQuery.toLowerCase();
|
||||
filtered = sessions.filter(
|
||||
(s) => s.title?.toLowerCase().includes(query) || s.sessionId.toLowerCase().includes(query)
|
||||
s => s.title?.toLowerCase().includes(query) || s.sessionId.toLowerCase().includes(query),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
const sorted = [...filtered].sort((a, b) => {
|
||||
const dateA = a.updatedAt ? new Date(a.updatedAt).getTime() : 0;
|
||||
const dateB = b.updatedAt ? new Date(b.updatedAt).getTime() : 0;
|
||||
return dateB - dateA; // Descending
|
||||
return dateB - dateA; // Descending
|
||||
});
|
||||
|
||||
// Group by time bucket (preserving sort order within each bucket)
|
||||
@@ -161,10 +161,8 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
}
|
||||
|
||||
// Return in chronological bucket order
|
||||
const bucketOrder: TimeBucket[] = ["today", "yesterday", "thisWeek", "pastWeek", "all"];
|
||||
return bucketOrder
|
||||
.filter((b) => groups.has(b))
|
||||
.map((bucket) => ({ bucket, sessions: groups.get(bucket)! }));
|
||||
const bucketOrder: TimeBucket[] = ['today', 'yesterday', 'thisWeek', 'pastWeek', 'all'];
|
||||
return bucketOrder.filter(b => groups.has(b)).map(bucket => ({ bucket, sessions: groups.get(bucket)! }));
|
||||
}, [sessions, searchQuery]);
|
||||
|
||||
const handleSelectSession = useCallback(
|
||||
@@ -179,7 +177,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
setLoadingSessionId(null);
|
||||
}
|
||||
},
|
||||
[onSelectSession, loadingSessionId]
|
||||
[onSelectSession, loadingSessionId],
|
||||
);
|
||||
|
||||
if (!supportsHistory) {
|
||||
@@ -191,7 +189,7 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
);
|
||||
}
|
||||
|
||||
const flatItems = groupedSessions.flatMap((g) => g.sessions);
|
||||
const flatItems = groupedSessions.flatMap(g => g.sessions);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
@@ -201,25 +199,17 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
<Input
|
||||
placeholder="Search threads..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onChange={e => setSearchQuery(e.target.value)}
|
||||
className="h-8 border-0 focus-visible:ring-0 shadow-none"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={loadSessions}
|
||||
disabled={isLoading}
|
||||
className="shrink-0"
|
||||
>
|
||||
<RefreshCw className={cn("h-4 w-4", isLoading && "animate-spin")} />
|
||||
<Button variant="ghost" size="sm" onClick={loadSessions} disabled={isLoading} className="shrink-0">
|
||||
<RefreshCw className={cn('h-4 w-4', isLoading && 'animate-spin')} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Session list */}
|
||||
<ScrollArea className="flex-1 min-h-0">
|
||||
{error && (
|
||||
<div className="p-4 text-center text-destructive text-sm">{error}</div>
|
||||
)}
|
||||
{error && <div className="p-4 text-center text-destructive text-sm">{error}</div>}
|
||||
|
||||
{!error && isLoading && sessions.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
|
||||
@@ -230,17 +220,13 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
|
||||
{!error && !isLoading && sessions.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You don't have any past threads yet.
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">You don't have any past threads yet.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!error && sessions.length > 0 && groupedSessions.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
No threads match your search.
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">No threads match your search.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -249,14 +235,12 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
{groupedSessions.map((group, groupIndex) => (
|
||||
<div key={group.bucket}>
|
||||
{/* Bucket separator - Reference: Zed's BucketSeparator */}
|
||||
<div className={cn("px-2 pb-1", groupIndex > 0 && "pt-3")}>
|
||||
<span className="text-xs text-muted-foreground font-medium">
|
||||
{BUCKET_LABELS[group.bucket]}
|
||||
</span>
|
||||
<div className={cn('px-2 pb-1', groupIndex > 0 && 'pt-3')}>
|
||||
<span className="text-xs text-muted-foreground font-medium">{BUCKET_LABELS[group.bucket]}</span>
|
||||
</div>
|
||||
|
||||
{/* Session entries */}
|
||||
{group.sessions.map((session) => {
|
||||
{group.sessions.map(session => {
|
||||
const globalIdx = flatItems.indexOf(session);
|
||||
const isSelected = globalIdx === selectedIndex;
|
||||
const isLoadingThis = loadingSessionId === session.sessionId;
|
||||
@@ -273,23 +257,19 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
}}
|
||||
className={cn(
|
||||
// min-w-0 is required for truncate to work in flex containers
|
||||
"w-full min-w-0 flex items-center gap-2 px-3 py-2 rounded-md text-left transition-colors",
|
||||
"hover:bg-accent",
|
||||
isSelected && "bg-accent",
|
||||
isAnyLoading && !isLoadingThis && "opacity-50 cursor-not-allowed",
|
||||
isLoadingThis && "bg-accent"
|
||||
'w-full min-w-0 flex items-center gap-2 px-3 py-2 rounded-md text-left transition-colors',
|
||||
'hover:bg-accent',
|
||||
isSelected && 'bg-accent',
|
||||
isAnyLoading && !isLoadingThis && 'opacity-50 cursor-not-allowed',
|
||||
isLoadingThis && 'bg-accent',
|
||||
)}
|
||||
>
|
||||
{/* min-w-0 + truncate ensures long titles are clipped with ellipsis */}
|
||||
<span className="text-sm truncate flex-1 min-w-0">
|
||||
{session.title && session.title.trim() ? session.title : "New Thread"}
|
||||
{session.title && session.title.trim() ? session.title : 'New Thread'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0 whitespace-nowrap">
|
||||
{isLoadingThis ? (
|
||||
<RefreshCw className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
formatRelativeTime(date)
|
||||
)}
|
||||
{isLoadingThis ? <RefreshCw className="h-3 w-3 animate-spin" /> : formatRelativeTime(date)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
@@ -301,4 +281,3 @@ export function ThreadHistory({ client, onSelectSession }: ThreadHistoryProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { Button } from "../ui/button";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
type ComponentProps,
|
||||
createContext,
|
||||
type HTMLAttributes,
|
||||
useContext,
|
||||
useState,
|
||||
} from "react";
|
||||
import { Button } from '../ui/button';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { CheckIcon, CopyIcon } from 'lucide-react';
|
||||
import { type ComponentProps, createContext, type HTMLAttributes, useContext, useState } from 'react';
|
||||
|
||||
type CodeBlockProps = HTMLAttributes<HTMLDivElement> & {
|
||||
code: string;
|
||||
@@ -22,7 +16,7 @@ type CodeBlockContextType = {
|
||||
};
|
||||
|
||||
const CodeBlockContext = createContext<CodeBlockContextType>({
|
||||
code: "",
|
||||
code: '',
|
||||
});
|
||||
|
||||
export const CodeBlock = ({
|
||||
@@ -33,14 +27,14 @@ export const CodeBlock = ({
|
||||
children,
|
||||
...props
|
||||
}: CodeBlockProps) => {
|
||||
const lines = code.split("\n");
|
||||
const lines = code.split('\n');
|
||||
|
||||
return (
|
||||
<CodeBlockContext.Provider value={{ code }}>
|
||||
<div
|
||||
className={cn(
|
||||
"group relative w-full overflow-hidden rounded-md border bg-background text-foreground",
|
||||
className
|
||||
'group relative w-full overflow-hidden rounded-md border bg-background text-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -57,7 +51,7 @@ export const CodeBlock = ({
|
||||
)}
|
||||
<td className="p-0">
|
||||
<pre className="m-0 p-0 text-sm whitespace-pre font-mono">
|
||||
<code className="text-sm">{line || "\u00A0"}</code>
|
||||
<code className="text-sm">{line || '\u00A0'}</code>
|
||||
</pre>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -65,11 +59,7 @@ export const CodeBlock = ({
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{children && (
|
||||
<div className="absolute top-2 right-2 flex items-center gap-2">
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
{children && <div className="absolute top-2 right-2 flex items-center gap-2">{children}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</CodeBlockContext.Provider>
|
||||
@@ -94,8 +84,8 @@ export const CodeBlockCopyButton = ({
|
||||
const { code } = useContext(CodeBlockContext);
|
||||
|
||||
const copyToClipboard = async () => {
|
||||
if (typeof window === "undefined" || !navigator?.clipboard?.writeText) {
|
||||
onError?.(new Error("Clipboard API not available"));
|
||||
if (typeof window === 'undefined' || !navigator?.clipboard?.writeText) {
|
||||
onError?.(new Error('Clipboard API not available'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -112,13 +102,7 @@ export const CodeBlockCopyButton = ({
|
||||
const Icon = isCopied ? CheckIcon : CopyIcon;
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn("shrink-0", className)}
|
||||
onClick={copyToClipboard}
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
<Button className={cn('shrink-0', className)} onClick={copyToClipboard} size="icon" variant="ghost" {...props}>
|
||||
{children ?? <Icon size={14} />}
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { Button } from "../ui/button";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { ArrowDownIcon, UserIcon } from "lucide-react";
|
||||
import type { ComponentProps } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";
|
||||
import { Button } from '../ui/button';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { ArrowDownIcon, UserIcon } from 'lucide-react';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
import { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom';
|
||||
|
||||
export type ConversationProps = ComponentProps<typeof StickToBottom>;
|
||||
|
||||
export const Conversation = ({ className, ...props }: ConversationProps) => (
|
||||
<StickToBottom
|
||||
className={cn("relative flex-1 overflow-y-hidden overflow-x-hidden", className)}
|
||||
className={cn('relative flex-1 overflow-y-hidden overflow-x-hidden', className)}
|
||||
initial="smooth"
|
||||
resize="smooth"
|
||||
role="log"
|
||||
@@ -19,21 +19,16 @@ export const Conversation = ({ className, ...props }: ConversationProps) => (
|
||||
/>
|
||||
);
|
||||
|
||||
export type ConversationContentProps = ComponentProps<
|
||||
typeof StickToBottom.Content
|
||||
>;
|
||||
export type ConversationContentProps = ComponentProps<typeof StickToBottom.Content>;
|
||||
|
||||
export const ConversationContent = ({
|
||||
className,
|
||||
...props
|
||||
}: ConversationContentProps) => (
|
||||
export const ConversationContent = ({ className, ...props }: ConversationContentProps) => (
|
||||
<StickToBottom.Content
|
||||
className={cn("mx-auto flex max-w-3xl flex-col gap-2 px-4 py-8 sm:px-8 sm:py-12 min-w-0", className)}
|
||||
className={cn('mx-auto flex max-w-3xl flex-col gap-2 px-4 py-8 sm:px-8 sm:py-12 min-w-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ConversationEmptyStateProps = ComponentProps<"div"> & {
|
||||
export type ConversationEmptyStateProps = ComponentProps<'div'> & {
|
||||
title?: string;
|
||||
description?: string;
|
||||
icon?: React.ReactNode;
|
||||
@@ -41,17 +36,14 @@ export type ConversationEmptyStateProps = ComponentProps<"div"> & {
|
||||
|
||||
export const ConversationEmptyState = ({
|
||||
className,
|
||||
title = "No messages yet",
|
||||
description = "Start a conversation to see messages here",
|
||||
title = 'No messages yet',
|
||||
description = 'Start a conversation to see messages here',
|
||||
icon,
|
||||
children,
|
||||
...props
|
||||
}: ConversationEmptyStateProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex size-full flex-col items-center justify-center gap-4 p-8 text-center",
|
||||
className
|
||||
)}
|
||||
className={cn('flex size-full flex-col items-center justify-center gap-4 p-8 text-center', className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
@@ -59,9 +51,7 @@ export const ConversationEmptyState = ({
|
||||
{icon && <div className="text-text-muted">{icon}</div>}
|
||||
<div className="space-y-2">
|
||||
<h3 className="font-semibold text-base font-display text-text-primary">{title}</h3>
|
||||
{description && (
|
||||
<p className="text-text-muted text-sm leading-relaxed max-w-xs">{description}</p>
|
||||
)}
|
||||
{description && <p className="text-text-muted text-sm leading-relaxed max-w-xs">{description}</p>}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@@ -76,10 +66,7 @@ export type ConversationScrollButtonProps = ComponentProps<typeof Button>;
|
||||
* When used standalone, it handles its own visibility based on isAtBottom.
|
||||
* When used in ConversationScrollButtons, the container manages visibility.
|
||||
*/
|
||||
export const ConversationScrollButton = ({
|
||||
className,
|
||||
...props
|
||||
}: ConversationScrollButtonProps) => {
|
||||
export const ConversationScrollButton = ({ className, ...props }: ConversationScrollButtonProps) => {
|
||||
const { scrollToBottom } = useStickToBottomContext();
|
||||
|
||||
const handleScrollToBottom = useCallback(() => {
|
||||
@@ -88,10 +75,7 @@ export const ConversationScrollButton = ({
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn(
|
||||
"rounded-full",
|
||||
className
|
||||
)}
|
||||
className={cn('rounded-full', className)}
|
||||
onClick={handleScrollToBottom}
|
||||
size="icon"
|
||||
type="button"
|
||||
@@ -108,7 +92,7 @@ export const ConversationScrollButton = ({
|
||||
* Data attribute used to mark the last user message element.
|
||||
* ChatInterface adds this attribute to the last user message for scroll targeting.
|
||||
*/
|
||||
export const LAST_USER_MESSAGE_ATTR = "data-last-user-message";
|
||||
export const LAST_USER_MESSAGE_ATTR = 'data-last-user-message';
|
||||
|
||||
export type ConversationScrollToLastUserMessageButtonProps = ComponentProps<typeof Button>;
|
||||
|
||||
@@ -124,16 +108,13 @@ export const ConversationScrollToLastUserMessageButton = ({
|
||||
// Find the last user message element by data attribute
|
||||
const lastUserMessage = document.querySelector(`[${LAST_USER_MESSAGE_ATTR}="true"]`);
|
||||
if (lastUserMessage) {
|
||||
lastUserMessage.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
lastUserMessage.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn(
|
||||
"rounded-full",
|
||||
className
|
||||
)}
|
||||
className={cn('rounded-full', className)}
|
||||
onClick={handleScrollToLastUserMessage}
|
||||
size="icon"
|
||||
type="button"
|
||||
@@ -146,7 +127,7 @@ export const ConversationScrollToLastUserMessageButton = ({
|
||||
);
|
||||
};
|
||||
|
||||
export type ConversationScrollButtonsProps = ComponentProps<"div"> & {
|
||||
export type ConversationScrollButtonsProps = ComponentProps<'div'> & {
|
||||
/** Whether there are user messages to scroll to */
|
||||
hasUserMessages?: boolean;
|
||||
};
|
||||
@@ -166,16 +147,9 @@ export const ConversationScrollButtons = ({
|
||||
if (isAtBottom) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className={cn('absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2', className)} {...props}>
|
||||
{hasUserMessages && <ConversationScrollToLastUserMessageButton />}
|
||||
<ConversationScrollButton />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
export * from "./code-block";
|
||||
export * from "./conversation";
|
||||
export * from "./message";
|
||||
export * from "./permission-request";
|
||||
export * from "./prompt-input";
|
||||
export * from "./reasoning";
|
||||
export * from "./shimmer";
|
||||
export * from "./tool";
|
||||
|
||||
export * from './code-block'
|
||||
export * from './conversation'
|
||||
export * from './message'
|
||||
export * from './permission-request'
|
||||
export * from './prompt-input'
|
||||
export * from './reasoning'
|
||||
export * from './shimmer'
|
||||
export * from './tool'
|
||||
|
||||
@@ -1,39 +1,26 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
ButtonGroup,
|
||||
ButtonGroupText,
|
||||
} from "../ui/button-group";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "../ui/tooltip";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import type { FileUIPart, UIMessage } from "ai";
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
PaperclipIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes, ReactElement } from "react";
|
||||
import { createContext, lazy, memo, Suspense, useContext, useEffect, useState } from "react";
|
||||
import { Button } from '../ui/button';
|
||||
import { ButtonGroup, ButtonGroupText } from '../ui/button-group';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import type { FileUIPart, UIMessage } from 'ai';
|
||||
import { ChevronLeftIcon, ChevronRightIcon, PaperclipIcon, XIcon } from 'lucide-react';
|
||||
import type { ComponentProps, HTMLAttributes, ReactElement } from 'react';
|
||||
import { createContext, lazy, memo, Suspense, useContext, useEffect, useState } from 'react';
|
||||
|
||||
const LazyStreamdown = lazy(() => import("streamdown").then((m) => ({ default: m.Streamdown })));
|
||||
const LazyStreamdown = lazy(() => import('streamdown').then(m => ({ default: m.Streamdown })));
|
||||
|
||||
export type MessageProps = HTMLAttributes<HTMLDivElement> & {
|
||||
from: UIMessage["role"];
|
||||
from: UIMessage['role'];
|
||||
};
|
||||
|
||||
export const Message = ({ className, from, ...props }: MessageProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"group flex w-full max-w-[85%] min-w-0 flex-col gap-2",
|
||||
from === "user" ? "is-user ml-auto justify-end" : "is-assistant",
|
||||
className
|
||||
'group flex w-full max-w-[85%] min-w-0 flex-col gap-2',
|
||||
from === 'user' ? 'is-user ml-auto justify-end' : 'is-assistant',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
@@ -41,33 +28,25 @@ export const Message = ({ className, from, ...props }: MessageProps) => (
|
||||
|
||||
export type MessageContentProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const MessageContent = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: MessageContentProps) => (
|
||||
export const MessageContent = ({ children, className, ...props }: MessageContentProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"is-user:dark flex w-fit max-w-full flex-col gap-2 overflow-hidden text-sm break-words",
|
||||
"group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground",
|
||||
"group-[.is-assistant]:text-foreground",
|
||||
className
|
||||
'is-user:dark flex w-fit max-w-full flex-col gap-2 overflow-hidden text-sm break-words',
|
||||
'group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground',
|
||||
'group-[.is-assistant]:text-foreground',
|
||||
className,
|
||||
)}
|
||||
style={{ overflowWrap: "anywhere" }}
|
||||
style={{ overflowWrap: 'anywhere' }}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type MessageActionsProps = ComponentProps<"div">;
|
||||
export type MessageActionsProps = ComponentProps<'div'>;
|
||||
|
||||
export const MessageActions = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: MessageActionsProps) => (
|
||||
<div className={cn("flex items-center gap-1", className)} {...props}>
|
||||
export const MessageActions = ({ className, children, ...props }: MessageActionsProps) => (
|
||||
<div className={cn('flex items-center gap-1', className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
@@ -81,8 +60,8 @@ export const MessageAction = ({
|
||||
tooltip,
|
||||
children,
|
||||
label,
|
||||
variant = "ghost",
|
||||
size = "icon-sm",
|
||||
variant = 'ghost',
|
||||
size = 'icon-sm',
|
||||
...props
|
||||
}: MessageActionProps) => {
|
||||
const button = (
|
||||
@@ -117,17 +96,13 @@ type MessageBranchContextType = {
|
||||
setBranches: (branches: ReactElement[]) => void;
|
||||
};
|
||||
|
||||
const MessageBranchContext = createContext<MessageBranchContextType | null>(
|
||||
null
|
||||
);
|
||||
const MessageBranchContext = createContext<MessageBranchContextType | null>(null);
|
||||
|
||||
const useMessageBranch = () => {
|
||||
const context = useContext(MessageBranchContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
"MessageBranch components must be used within MessageBranch"
|
||||
);
|
||||
throw new Error('MessageBranch components must be used within MessageBranch');
|
||||
}
|
||||
|
||||
return context;
|
||||
@@ -138,12 +113,7 @@ export type MessageBranchProps = HTMLAttributes<HTMLDivElement> & {
|
||||
onBranchChange?: (branchIndex: number) => void;
|
||||
};
|
||||
|
||||
export const MessageBranch = ({
|
||||
defaultBranch = 0,
|
||||
onBranchChange,
|
||||
className,
|
||||
...props
|
||||
}: MessageBranchProps) => {
|
||||
export const MessageBranch = ({ defaultBranch = 0, onBranchChange, className, ...props }: MessageBranchProps) => {
|
||||
const [currentBranch, setCurrentBranch] = useState(defaultBranch);
|
||||
const [branches, setBranches] = useState<ReactElement[]>([]);
|
||||
|
||||
@@ -153,14 +123,12 @@ export const MessageBranch = ({
|
||||
};
|
||||
|
||||
const goToPrevious = () => {
|
||||
const newBranch =
|
||||
currentBranch > 0 ? currentBranch - 1 : branches.length - 1;
|
||||
const newBranch = currentBranch > 0 ? currentBranch - 1 : branches.length - 1;
|
||||
handleBranchChange(newBranch);
|
||||
};
|
||||
|
||||
const goToNext = () => {
|
||||
const newBranch =
|
||||
currentBranch < branches.length - 1 ? currentBranch + 1 : 0;
|
||||
const newBranch = currentBranch < branches.length - 1 ? currentBranch + 1 : 0;
|
||||
handleBranchChange(newBranch);
|
||||
};
|
||||
|
||||
@@ -175,20 +143,14 @@ export const MessageBranch = ({
|
||||
|
||||
return (
|
||||
<MessageBranchContext.Provider value={contextValue}>
|
||||
<div
|
||||
className={cn("grid w-full gap-2 [&>div]:pb-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
<div className={cn('grid w-full gap-2 [&>div]:pb-0', className)} {...props} />
|
||||
</MessageBranchContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageBranchContentProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const MessageBranchContent = ({
|
||||
children,
|
||||
...props
|
||||
}: MessageBranchContentProps) => {
|
||||
export const MessageBranchContent = ({ children, ...props }: MessageBranchContentProps) => {
|
||||
const { currentBranch, setBranches, branches } = useMessageBranch();
|
||||
const childrenArray = Array.isArray(children) ? children : [children];
|
||||
|
||||
@@ -201,10 +163,7 @@ export const MessageBranchContent = ({
|
||||
|
||||
return childrenArray.map((branch, index) => (
|
||||
<div
|
||||
className={cn(
|
||||
"grid gap-2 overflow-hidden [&>div]:pb-0",
|
||||
index === currentBranch ? "block" : "hidden"
|
||||
)}
|
||||
className={cn('grid gap-2 overflow-hidden [&>div]:pb-0', index === currentBranch ? 'block' : 'hidden')}
|
||||
key={branch.key}
|
||||
{...props}
|
||||
>
|
||||
@@ -214,14 +173,10 @@ export const MessageBranchContent = ({
|
||||
};
|
||||
|
||||
export type MessageBranchSelectorProps = HTMLAttributes<HTMLDivElement> & {
|
||||
from: UIMessage["role"];
|
||||
from: UIMessage['role'];
|
||||
};
|
||||
|
||||
export const MessageBranchSelector = ({
|
||||
className,
|
||||
from,
|
||||
...props
|
||||
}: MessageBranchSelectorProps) => {
|
||||
export const MessageBranchSelector = ({ className, from, ...props }: MessageBranchSelectorProps) => {
|
||||
const { totalBranches } = useMessageBranch();
|
||||
|
||||
// Don't render if there's only one branch
|
||||
@@ -240,10 +195,7 @@ export const MessageBranchSelector = ({
|
||||
|
||||
export type MessageBranchPreviousProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const MessageBranchPrevious = ({
|
||||
children,
|
||||
...props
|
||||
}: MessageBranchPreviousProps) => {
|
||||
export const MessageBranchPrevious = ({ children, ...props }: MessageBranchPreviousProps) => {
|
||||
const { goToPrevious, totalBranches } = useMessageBranch();
|
||||
|
||||
return (
|
||||
@@ -263,11 +215,7 @@ export const MessageBranchPrevious = ({
|
||||
|
||||
export type MessageBranchNextProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const MessageBranchNext = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: MessageBranchNextProps) => {
|
||||
export const MessageBranchNext = ({ children, className, ...props }: MessageBranchNextProps) => {
|
||||
const { goToNext, totalBranches } = useMessageBranch();
|
||||
|
||||
return (
|
||||
@@ -287,18 +235,12 @@ export const MessageBranchNext = ({
|
||||
|
||||
export type MessageBranchPageProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const MessageBranchPage = ({
|
||||
className,
|
||||
...props
|
||||
}: MessageBranchPageProps) => {
|
||||
export const MessageBranchPage = ({ className, ...props }: MessageBranchPageProps) => {
|
||||
const { currentBranch, totalBranches } = useMessageBranch();
|
||||
|
||||
return (
|
||||
<ButtonGroupText
|
||||
className={cn(
|
||||
"border-none bg-transparent text-muted-foreground shadow-none",
|
||||
className
|
||||
)}
|
||||
className={cn('border-none bg-transparent text-muted-foreground shadow-none', className)}
|
||||
{...props}
|
||||
>
|
||||
{currentBranch + 1} of {totalBranches}
|
||||
@@ -309,22 +251,16 @@ export const MessageBranchPage = ({
|
||||
export type MessageResponseProps = {
|
||||
children?: string;
|
||||
className?: string;
|
||||
mode?: "static" | "streaming";
|
||||
mode?: 'static' | 'streaming';
|
||||
};
|
||||
|
||||
export const MessageResponse = memo(
|
||||
({ className, children, ...props }: MessageResponseProps) => (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className={cn("whitespace-pre-wrap break-words", className)}>
|
||||
{children}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Suspense fallback={<div className={cn('whitespace-pre-wrap break-words', className)}>{children}</div>}>
|
||||
<LazyStreamdown
|
||||
className={cn(
|
||||
"size-full break-words [overflow-wrap:anywhere] [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
|
||||
className
|
||||
'size-full break-words [overflow-wrap:anywhere] [&>*:first-child]:mt-0 [&>*:last-child]:mb-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -332,10 +268,10 @@ export const MessageResponse = memo(
|
||||
</LazyStreamdown>
|
||||
</Suspense>
|
||||
),
|
||||
(prevProps, nextProps) => prevProps.children === nextProps.children
|
||||
(prevProps, nextProps) => prevProps.children === nextProps.children,
|
||||
);
|
||||
|
||||
MessageResponse.displayName = "MessageResponse";
|
||||
MessageResponse.displayName = 'MessageResponse';
|
||||
|
||||
export type MessageAttachmentProps = HTMLAttributes<HTMLDivElement> & {
|
||||
data: FileUIPart;
|
||||
@@ -343,30 +279,18 @@ export type MessageAttachmentProps = HTMLAttributes<HTMLDivElement> & {
|
||||
onRemove?: () => void;
|
||||
};
|
||||
|
||||
export function MessageAttachment({
|
||||
data,
|
||||
className,
|
||||
onRemove,
|
||||
...props
|
||||
}: MessageAttachmentProps) {
|
||||
const filename = data.filename || "";
|
||||
const mediaType =
|
||||
data.mediaType?.startsWith("image/") && data.url ? "image" : "file";
|
||||
const isImage = mediaType === "image";
|
||||
const attachmentLabel = filename || (isImage ? "Image" : "Attachment");
|
||||
export function MessageAttachment({ data, className, onRemove, ...props }: MessageAttachmentProps) {
|
||||
const filename = data.filename || '';
|
||||
const mediaType = data.mediaType?.startsWith('image/') && data.url ? 'image' : 'file';
|
||||
const isImage = mediaType === 'image';
|
||||
const attachmentLabel = filename || (isImage ? 'Image' : 'Attachment');
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group relative size-24 overflow-hidden rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className={cn('group relative size-24 overflow-hidden rounded-lg', className)} {...props}>
|
||||
{isImage ? (
|
||||
<>
|
||||
<img
|
||||
alt={filename || "attachment"}
|
||||
alt={filename || 'attachment'}
|
||||
className="size-full object-cover"
|
||||
height={100}
|
||||
src={data.url}
|
||||
@@ -376,7 +300,7 @@ export function MessageAttachment({
|
||||
<Button
|
||||
aria-label="Remove attachment"
|
||||
className="absolute top-2 right-2 size-6 rounded-full bg-background/80 p-0 opacity-0 backdrop-blur-sm transition-opacity hover:bg-background group-hover:opacity-100 [&>svg]:size-3"
|
||||
onClick={(e) => {
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
onRemove();
|
||||
}}
|
||||
@@ -404,7 +328,7 @@ export function MessageAttachment({
|
||||
<Button
|
||||
aria-label="Remove attachment"
|
||||
className="size-6 shrink-0 rounded-full p-0 opacity-0 transition-opacity hover:bg-accent group-hover:opacity-100 [&>svg]:size-3"
|
||||
onClick={(e) => {
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
onRemove();
|
||||
}}
|
||||
@@ -421,45 +345,24 @@ export function MessageAttachment({
|
||||
);
|
||||
}
|
||||
|
||||
export type MessageAttachmentsProps = ComponentProps<"div">;
|
||||
export type MessageAttachmentsProps = ComponentProps<'div'>;
|
||||
|
||||
export function MessageAttachments({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: MessageAttachmentsProps) {
|
||||
export function MessageAttachments({ children, className, ...props }: MessageAttachmentsProps) {
|
||||
if (!children) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"ml-auto flex w-fit flex-wrap items-start gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className={cn('ml-auto flex w-fit flex-wrap items-start gap-2', className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type MessageToolbarProps = ComponentProps<"div">;
|
||||
export type MessageToolbarProps = ComponentProps<'div'>;
|
||||
|
||||
export const MessageToolbar = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: MessageToolbarProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"mt-4 flex w-full items-center justify-between gap-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
export const MessageToolbar = ({ className, children, ...props }: MessageToolbarProps) => (
|
||||
<div className={cn('mt-4 flex w-full items-center justify-between gap-4', className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { Button } from "../ui/button";
|
||||
import { ShieldAlertIcon, CheckIcon, XIcon } from "lucide-react";
|
||||
import type { PermissionOption } from "../../src/acp/types";
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Button } from '../ui/button';
|
||||
import { ShieldAlertIcon, CheckIcon, XIcon } from 'lucide-react';
|
||||
import type { PermissionOption } from '../../src/acp/types';
|
||||
|
||||
// Get button variant based on option kind
|
||||
function getButtonVariant(kind: PermissionOption["kind"]): "default" | "destructive" | "outline" | "secondary" {
|
||||
function getButtonVariant(kind: PermissionOption['kind']): 'default' | 'destructive' | 'outline' | 'secondary' {
|
||||
switch (kind) {
|
||||
case "allow_once":
|
||||
case "allow_always":
|
||||
return "default";
|
||||
case "reject_once":
|
||||
case "reject_always":
|
||||
return "destructive";
|
||||
case 'allow_once':
|
||||
case 'allow_always':
|
||||
return 'default';
|
||||
case 'reject_once':
|
||||
case 'reject_always':
|
||||
return 'destructive';
|
||||
default:
|
||||
return "outline";
|
||||
return 'outline';
|
||||
}
|
||||
}
|
||||
|
||||
// Get button icon based on option kind
|
||||
function getButtonIcon(kind: PermissionOption["kind"]) {
|
||||
function getButtonIcon(kind: PermissionOption['kind']) {
|
||||
switch (kind) {
|
||||
case "allow_once":
|
||||
case "allow_always":
|
||||
case 'allow_once':
|
||||
case 'allow_always':
|
||||
return <CheckIcon className="size-4" />;
|
||||
case "reject_once":
|
||||
case "reject_always":
|
||||
case 'reject_once':
|
||||
case 'reject_always':
|
||||
return <XIcon className="size-4" />;
|
||||
default:
|
||||
return null;
|
||||
@@ -37,7 +37,7 @@ function getButtonIcon(kind: PermissionOption["kind"]) {
|
||||
export interface ToolPermissionButtonsProps {
|
||||
requestId: string;
|
||||
options: PermissionOption[];
|
||||
onRespond: (requestId: string, optionId: string | null, optionKind: PermissionOption["kind"] | null) => void;
|
||||
onRespond: (requestId: string, optionId: string | null, optionKind: PermissionOption['kind'] | null) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
@@ -47,15 +47,13 @@ export function ToolPermissionButtons({ requestId, options, onRespond, className
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn("p-3 border-t border-warning-border/30 bg-warning-bg/50", className)}>
|
||||
<div className={cn('p-3 border-t border-warning-border/30 bg-warning-bg/50', className)}>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<ShieldAlertIcon className="size-4 text-warning-text" />
|
||||
<span className="text-xs font-medium text-warning-text">
|
||||
Permission Required
|
||||
</span>
|
||||
<span className="text-xs font-medium text-warning-text">Permission Required</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{options.map((option) => (
|
||||
{options.map(option => (
|
||||
<Button
|
||||
key={option.optionId}
|
||||
variant={getButtonVariant(option.kind)}
|
||||
@@ -71,4 +69,3 @@ export function ToolPermissionButtons({ requestId, options, onRespond, className
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,12 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { useControllableState } from "@radix-ui/react-use-controllable-state";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "../ui/collapsible";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { BrainIcon, ChevronDownIcon } from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createContext, memo, useCallback, useContext, useEffect, useState } from "react";
|
||||
import { Shimmer } from "./shimmer";
|
||||
import { useControllableState } from '@radix-ui/react-use-controllable-state';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '../ui/collapsible';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { BrainIcon, ChevronDownIcon } from 'lucide-react';
|
||||
import type { ComponentProps, ReactNode } from 'react';
|
||||
import { createContext, memo, useCallback, useContext, useEffect, useState } from 'react';
|
||||
import { Shimmer } from './shimmer';
|
||||
|
||||
interface ReasoningContextValue {
|
||||
isStreaming: boolean;
|
||||
@@ -24,7 +20,7 @@ const ReasoningContext = createContext<ReasoningContextValue | null>(null);
|
||||
export const useReasoning = () => {
|
||||
const context = useContext(ReasoningContext);
|
||||
if (!context) {
|
||||
throw new Error("Reasoning components must be used within Reasoning");
|
||||
throw new Error('Reasoning components must be used within Reasoning');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
@@ -78,8 +74,8 @@ export const Reasoning = memo(
|
||||
|
||||
// Auto-open when streaming starts, auto-close when streaming ends (once only)
|
||||
// Respect prefers-reduced-motion: skip animation auto-close
|
||||
const prefersReducedMotion = typeof window !== "undefined"
|
||||
&& window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
const prefersReducedMotion =
|
||||
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
useEffect(() => {
|
||||
if (!prefersReducedMotion && defaultOpen && !isStreaming && isOpen && !hasAutoClosed) {
|
||||
@@ -97,11 +93,9 @@ export const Reasoning = memo(
|
||||
};
|
||||
|
||||
return (
|
||||
<ReasoningContext.Provider
|
||||
value={{ isStreaming, isOpen: isOpen ?? false, setIsOpen, duration }}
|
||||
>
|
||||
<ReasoningContext.Provider value={{ isStreaming, isOpen: isOpen ?? false, setIsOpen, duration }}>
|
||||
<Collapsible
|
||||
className={cn("not-prose mb-4", className)}
|
||||
className={cn('not-prose mb-4', className)}
|
||||
onOpenChange={handleOpenChange}
|
||||
open={isOpen}
|
||||
{...props}
|
||||
@@ -110,12 +104,10 @@ export const Reasoning = memo(
|
||||
</Collapsible>
|
||||
</ReasoningContext.Provider>
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export type ReasoningTriggerProps = ComponentProps<
|
||||
typeof CollapsibleTrigger
|
||||
> & {
|
||||
export type ReasoningTriggerProps = ComponentProps<typeof CollapsibleTrigger> & {
|
||||
getThinkingMessage?: (isStreaming: boolean, duration?: number) => ReactNode;
|
||||
};
|
||||
|
||||
@@ -130,19 +122,14 @@ const defaultGetThinkingMessage = (isStreaming: boolean, duration?: number) => {
|
||||
};
|
||||
|
||||
export const ReasoningTrigger = memo(
|
||||
({
|
||||
className,
|
||||
children,
|
||||
getThinkingMessage = defaultGetThinkingMessage,
|
||||
...props
|
||||
}: ReasoningTriggerProps) => {
|
||||
({ className, children, getThinkingMessage = defaultGetThinkingMessage, ...props }: ReasoningTriggerProps) => {
|
||||
const { isStreaming, isOpen, duration } = useReasoning();
|
||||
|
||||
return (
|
||||
<CollapsibleTrigger
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",
|
||||
className
|
||||
'flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -150,41 +137,31 @@ export const ReasoningTrigger = memo(
|
||||
<>
|
||||
<BrainIcon className="size-4" />
|
||||
{getThinkingMessage(isStreaming, duration)}
|
||||
<ChevronDownIcon
|
||||
className={cn(
|
||||
"size-4 transition-transform",
|
||||
isOpen ? "rotate-180" : "rotate-0"
|
||||
)}
|
||||
/>
|
||||
<ChevronDownIcon className={cn('size-4 transition-transform', isOpen ? 'rotate-180' : 'rotate-0')} />
|
||||
</>
|
||||
)}
|
||||
</CollapsibleTrigger>
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export type ReasoningContentProps = ComponentProps<
|
||||
typeof CollapsibleContent
|
||||
> & {
|
||||
export type ReasoningContentProps = ComponentProps<typeof CollapsibleContent> & {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export const ReasoningContent = memo(
|
||||
({ className, children, ...props }: ReasoningContentProps) => (
|
||||
<CollapsibleContent
|
||||
className={cn(
|
||||
"mt-4 text-sm",
|
||||
"data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</CollapsibleContent>
|
||||
)
|
||||
);
|
||||
|
||||
Reasoning.displayName = "Reasoning";
|
||||
ReasoningTrigger.displayName = "ReasoningTrigger";
|
||||
ReasoningContent.displayName = "ReasoningContent";
|
||||
export const ReasoningContent = memo(({ className, children, ...props }: ReasoningContentProps) => (
|
||||
<CollapsibleContent
|
||||
className={cn(
|
||||
'mt-4 text-sm',
|
||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</CollapsibleContent>
|
||||
));
|
||||
|
||||
Reasoning.displayName = 'Reasoning';
|
||||
ReasoningTrigger.displayName = 'ReasoningTrigger';
|
||||
ReasoningContent.displayName = 'ReasoningContent';
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
type ElementType,
|
||||
type JSX,
|
||||
memo,
|
||||
} from "react";
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { motion } from 'motion/react';
|
||||
import { type ElementType, type JSX, memo } from 'react';
|
||||
|
||||
export interface TextShimmerProps {
|
||||
children: string;
|
||||
@@ -16,27 +12,17 @@ export interface TextShimmerProps {
|
||||
spread?: number;
|
||||
}
|
||||
|
||||
const ShimmerComponent = ({
|
||||
children,
|
||||
as: Component = "p",
|
||||
className,
|
||||
duration = 2,
|
||||
}: TextShimmerProps) => {
|
||||
const MotionComponent = motion.create(
|
||||
Component as keyof JSX.IntrinsicElements
|
||||
);
|
||||
const ShimmerComponent = ({ children, as: Component = 'p', className, duration = 2 }: TextShimmerProps) => {
|
||||
const MotionComponent = motion.create(Component as keyof JSX.IntrinsicElements);
|
||||
|
||||
return (
|
||||
<MotionComponent
|
||||
animate={{ opacity: [0.5, 1, 0.5] }}
|
||||
className={cn(
|
||||
"relative inline-block text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
className={cn('relative inline-block text-muted-foreground', className)}
|
||||
transition={{
|
||||
repeat: Number.POSITIVE_INFINITY,
|
||||
duration,
|
||||
ease: "easeInOut",
|
||||
ease: 'easeInOut',
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -1,67 +1,56 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { Badge } from "../ui/badge";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "../ui/collapsible";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import type { ToolUIPart } from "ai";
|
||||
import {
|
||||
CheckCircleIcon,
|
||||
ChevronDownIcon,
|
||||
CircleIcon,
|
||||
ClockIcon,
|
||||
WrenchIcon,
|
||||
XCircleIcon,
|
||||
} from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { isValidElement } from "react";
|
||||
import { CodeBlock } from "./code-block";
|
||||
import { Badge } from '../ui/badge';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '../ui/collapsible';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import type { ToolUIPart } from 'ai';
|
||||
import { CheckCircleIcon, ChevronDownIcon, CircleIcon, ClockIcon, WrenchIcon, XCircleIcon } from 'lucide-react';
|
||||
import type { ComponentProps, ReactNode } from 'react';
|
||||
import { isValidElement } from 'react';
|
||||
import { CodeBlock } from './code-block';
|
||||
|
||||
export type ToolProps = ComponentProps<typeof Collapsible>;
|
||||
|
||||
export const Tool = ({ className, ...props }: ToolProps) => (
|
||||
<Collapsible
|
||||
className={cn("not-prose mb-4 w-full max-w-full overflow-hidden rounded-md border", className)}
|
||||
className={cn('not-prose mb-4 w-full max-w-full overflow-hidden rounded-md border', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
// Extended state type to include our custom states
|
||||
export type ExtendedToolState = ToolUIPart["state"] | "waiting-for-confirmation" | "rejected";
|
||||
export type ExtendedToolState = ToolUIPart['state'] | 'waiting-for-confirmation' | 'rejected';
|
||||
|
||||
export type ToolHeaderProps = {
|
||||
title?: string;
|
||||
type: ToolUIPart["type"];
|
||||
type: ToolUIPart['type'];
|
||||
state: ExtendedToolState;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: ExtendedToolState) => {
|
||||
const labels: Record<ExtendedToolState, string> = {
|
||||
"input-streaming": "Pending",
|
||||
"input-available": "Running",
|
||||
"approval-requested": "Awaiting Approval",
|
||||
"approval-responded": "Responded",
|
||||
"output-available": "Completed",
|
||||
"output-error": "Error",
|
||||
"output-denied": "Denied",
|
||||
"waiting-for-confirmation": "Awaiting Approval",
|
||||
"rejected": "Rejected",
|
||||
'input-streaming': 'Pending',
|
||||
'input-available': 'Running',
|
||||
'approval-requested': 'Awaiting Approval',
|
||||
'approval-responded': 'Responded',
|
||||
'output-available': 'Completed',
|
||||
'output-error': 'Error',
|
||||
'output-denied': 'Denied',
|
||||
'waiting-for-confirmation': 'Awaiting Approval',
|
||||
rejected: 'Rejected',
|
||||
};
|
||||
|
||||
const icons: Record<ExtendedToolState, ReactNode> = {
|
||||
"input-streaming": <CircleIcon className="size-4" />,
|
||||
"input-available": <ClockIcon className="size-4 animate-pulse" />,
|
||||
"approval-requested": <ClockIcon className="size-4 text-yellow-600" />,
|
||||
"approval-responded": <CheckCircleIcon className="size-4 text-blue-600" />,
|
||||
"output-available": <CheckCircleIcon className="size-4 text-green-600" />,
|
||||
"output-error": <XCircleIcon className="size-4 text-red-600" />,
|
||||
"output-denied": <XCircleIcon className="size-4 text-orange-600" />,
|
||||
"waiting-for-confirmation": <ClockIcon className="size-4 text-yellow-600" />,
|
||||
"rejected": <XCircleIcon className="size-4 text-orange-600" />,
|
||||
'input-streaming': <CircleIcon className="size-4" />,
|
||||
'input-available': <ClockIcon className="size-4 animate-pulse" />,
|
||||
'approval-requested': <ClockIcon className="size-4 text-yellow-600" />,
|
||||
'approval-responded': <CheckCircleIcon className="size-4 text-blue-600" />,
|
||||
'output-available': <CheckCircleIcon className="size-4 text-green-600" />,
|
||||
'output-error': <XCircleIcon className="size-4 text-red-600" />,
|
||||
'output-denied': <XCircleIcon className="size-4 text-orange-600" />,
|
||||
'waiting-for-confirmation': <ClockIcon className="size-4 text-yellow-600" />,
|
||||
rejected: <XCircleIcon className="size-4 text-orange-600" />,
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -72,25 +61,11 @@ const getStatusBadge = (status: ExtendedToolState) => {
|
||||
);
|
||||
};
|
||||
|
||||
export const ToolHeader = ({
|
||||
className,
|
||||
title,
|
||||
type,
|
||||
state,
|
||||
...props
|
||||
}: ToolHeaderProps) => (
|
||||
<CollapsibleTrigger
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-4 p-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
export const ToolHeader = ({ className, title, type, state, ...props }: ToolHeaderProps) => (
|
||||
<CollapsibleTrigger className={cn('flex w-full items-center justify-between gap-4 p-3', className)} {...props}>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<WrenchIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate font-medium text-sm">
|
||||
{title ?? type.split("-").slice(1).join("-")}
|
||||
</span>
|
||||
<span className="truncate font-medium text-sm">{title ?? type.split('-').slice(1).join('-')}</span>
|
||||
{getStatusBadge(state)}
|
||||
</div>
|
||||
<ChevronDownIcon className="size-4 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
|
||||
@@ -102,64 +77,53 @@ export type ToolContentProps = ComponentProps<typeof CollapsibleContent>;
|
||||
export const ToolContent = ({ className, ...props }: ToolContentProps) => (
|
||||
<CollapsibleContent
|
||||
className={cn(
|
||||
"data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",
|
||||
className
|
||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ToolInputProps = ComponentProps<"div"> & {
|
||||
input: ToolUIPart["input"];
|
||||
export type ToolInputProps = ComponentProps<'div'> & {
|
||||
input: ToolUIPart['input'];
|
||||
};
|
||||
|
||||
export const ToolInput = ({ className, input, ...props }: ToolInputProps) => (
|
||||
<div className={cn("space-y-2 overflow-hidden p-4 max-w-full", className)} {...props}>
|
||||
<h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
|
||||
Parameters
|
||||
</h4>
|
||||
<div className={cn('space-y-2 overflow-hidden p-4 max-w-full', className)} {...props}>
|
||||
<h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">Parameters</h4>
|
||||
<div className="rounded-md bg-muted/50 overflow-hidden">
|
||||
<CodeBlock code={JSON.stringify(input, null, 2)} language="json" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export type ToolOutputProps = ComponentProps<"div"> & {
|
||||
output: ToolUIPart["output"];
|
||||
errorText: ToolUIPart["errorText"];
|
||||
export type ToolOutputProps = ComponentProps<'div'> & {
|
||||
output: ToolUIPart['output'];
|
||||
errorText: ToolUIPart['errorText'];
|
||||
};
|
||||
|
||||
export const ToolOutput = ({
|
||||
className,
|
||||
output,
|
||||
errorText,
|
||||
...props
|
||||
}: ToolOutputProps) => {
|
||||
export const ToolOutput = ({ className, output, errorText, ...props }: ToolOutputProps) => {
|
||||
if (!(output || errorText)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let Output = <div>{output as ReactNode}</div>;
|
||||
|
||||
if (typeof output === "object" && !isValidElement(output)) {
|
||||
Output = (
|
||||
<CodeBlock code={JSON.stringify(output, null, 2)} language="json" />
|
||||
);
|
||||
} else if (typeof output === "string") {
|
||||
if (typeof output === 'object' && !isValidElement(output)) {
|
||||
Output = <CodeBlock code={JSON.stringify(output, null, 2)} language="json" />;
|
||||
} else if (typeof output === 'string') {
|
||||
Output = <CodeBlock code={output} language="json" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("space-y-2 p-4 max-w-full overflow-hidden", className)} {...props}>
|
||||
<div className={cn('space-y-2 p-4 max-w-full overflow-hidden', className)} {...props}>
|
||||
<h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
|
||||
{errorText ? "Error" : "Result"}
|
||||
{errorText ? 'Error' : 'Result'}
|
||||
</h4>
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden rounded-md text-xs [&_table]:w-full",
|
||||
errorText
|
||||
? "bg-destructive/10 text-destructive"
|
||||
: "bg-muted/50 text-foreground"
|
||||
'overflow-hidden rounded-md text-xs [&_table]:w-full',
|
||||
errorText ? 'bg-destructive/10 text-destructive' : 'bg-muted/50 text-foreground',
|
||||
)}
|
||||
>
|
||||
{errorText && <div className="p-2">{errorText}</div>}
|
||||
@@ -168,4 +132,3 @@ export const ToolOutput = ({
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { useState, useRef, useCallback, type KeyboardEvent, type ClipboardEvent } from "react";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { Send, Square, Paperclip, Slash } from "lucide-react";
|
||||
import type { ChatInputMessage, UserMessageImage } from "../../src/lib/types";
|
||||
import type { AvailableCommand } from "../../src/acp/types";
|
||||
import { CommandMenu } from "./CommandMenu";
|
||||
import imageCompression from "browser-image-compression";
|
||||
import { useState, useRef, useCallback, type KeyboardEvent, type ClipboardEvent } from 'react';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Send, Square, Paperclip, Slash } from 'lucide-react';
|
||||
import type { ChatInputMessage, UserMessageImage } from '../../src/lib/types';
|
||||
import type { AvailableCommand } from '../../src/acp/types';
|
||||
import { CommandMenu } from './CommandMenu';
|
||||
import imageCompression from 'browser-image-compression';
|
||||
|
||||
// 图片压缩配置
|
||||
const IMAGE_COMPRESSION_OPTIONS = {
|
||||
maxSizeMB: 2,
|
||||
maxWidthOrHeight: 2048,
|
||||
useWebWorker: true,
|
||||
fileType: "image/jpeg" as const,
|
||||
fileType: 'image/jpeg' as const,
|
||||
};
|
||||
|
||||
// =============================================================================
|
||||
@@ -36,15 +36,15 @@ export function ChatInput({
|
||||
isLoading = false,
|
||||
onInterrupt,
|
||||
disabled = false,
|
||||
placeholder = "给 Claude 发送消息…",
|
||||
placeholder = '给 Claude 发送消息…',
|
||||
supportsImages = false,
|
||||
commands,
|
||||
className,
|
||||
}: ChatInputProps) {
|
||||
const [text, setText] = useState("");
|
||||
const [text, setText] = useState('');
|
||||
const [images, setImages] = useState<UserMessageImage[]>([]);
|
||||
const [showCommandMenu, setShowCommandMenu] = useState(false);
|
||||
const [commandFilter, setCommandFilter] = useState("");
|
||||
const [commandFilter, setCommandFilter] = useState('');
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
@@ -53,37 +53,37 @@ export function ChatInput({
|
||||
if ((!trimmed && images.length === 0) || disabled) return;
|
||||
|
||||
onSubmit({ text: trimmed, images: images.length > 0 ? images : undefined });
|
||||
setText("");
|
||||
setText('');
|
||||
setImages([]);
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
setCommandFilter('');
|
||||
// 重置 textarea 高度
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = "auto";
|
||||
textareaRef.current.style.height = 'auto';
|
||||
}
|
||||
}, [text, images, disabled, onSubmit]);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (showCommandMenu) {
|
||||
if (e.key === "Escape") {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setShowCommandMenu(false);
|
||||
return;
|
||||
}
|
||||
// Arrow keys and Enter are handled by CommandMenu via document-level listener
|
||||
// Don't submit or move cursor when menu is open
|
||||
if (e.key === "ArrowUp" || e.key === "ArrowDown" || e.key === "Enter") {
|
||||
if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (e.key === "Tab") {
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
setShowCommandMenu(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
e.preventDefault();
|
||||
if (isLoading) {
|
||||
onInterrupt?.();
|
||||
@@ -95,35 +95,41 @@ export function ChatInput({
|
||||
[handleSubmit, isLoading, onInterrupt, showCommandMenu],
|
||||
);
|
||||
|
||||
const handleInput = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const value = e.target.value;
|
||||
setText(value);
|
||||
const handleInput = useCallback(
|
||||
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const value = e.target.value;
|
||||
setText(value);
|
||||
|
||||
// 检测 slash 命令模式:仅在输入开头输入 / 时触发
|
||||
if (value.startsWith("/") && commands && commands.length > 0) {
|
||||
setShowCommandMenu(true);
|
||||
setCommandFilter(value.slice(1).split(/\s/)[0] || "");
|
||||
} else if (showCommandMenu) {
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
}
|
||||
// 检测 slash 命令模式:仅在输入开头输入 / 时触发
|
||||
if (value.startsWith('/') && commands && commands.length > 0) {
|
||||
setShowCommandMenu(true);
|
||||
setCommandFilter(value.slice(1).split(/\s/)[0] || '');
|
||||
} else if (showCommandMenu) {
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter('');
|
||||
}
|
||||
|
||||
// 自动调整高度
|
||||
const el = e.target;
|
||||
el.style.height = "auto";
|
||||
el.style.height = Math.min(el.scrollHeight, 200) + "px";
|
||||
}, [commands, showCommandMenu]);
|
||||
// 自动调整高度
|
||||
const el = e.target;
|
||||
el.style.height = 'auto';
|
||||
el.style.height = Math.min(el.scrollHeight, 200) + 'px';
|
||||
},
|
||||
[commands, showCommandMenu],
|
||||
);
|
||||
|
||||
// 粘贴图片
|
||||
const handlePaste = useCallback(async (e: ClipboardEvent) => {
|
||||
if (!supportsImages) return;
|
||||
const files = Array.from(e.clipboardData.files).filter((f) => f.type.startsWith("image/"));
|
||||
if (files.length === 0) return;
|
||||
const handlePaste = useCallback(
|
||||
async (e: ClipboardEvent) => {
|
||||
if (!supportsImages) return;
|
||||
const files = Array.from(e.clipboardData.files).filter(f => f.type.startsWith('image/'));
|
||||
if (files.length === 0) return;
|
||||
|
||||
e.preventDefault();
|
||||
const newImages = await processImageFiles(files);
|
||||
setImages((prev) => [...prev, ...newImages]);
|
||||
}, [supportsImages]);
|
||||
e.preventDefault();
|
||||
const newImages = await processImageFiles(files);
|
||||
setImages(prev => [...prev, ...newImages]);
|
||||
},
|
||||
[supportsImages],
|
||||
);
|
||||
|
||||
// 选择文件
|
||||
const handleFileSelect = useCallback(async () => {
|
||||
@@ -132,32 +138,32 @@ export function ChatInput({
|
||||
if (!files || files.length === 0) return;
|
||||
|
||||
const newImages = await processImageFiles(Array.from(files));
|
||||
setImages((prev) => [...prev, ...newImages]);
|
||||
setImages(prev => [...prev, ...newImages]);
|
||||
// 清空 input 以便重复选择
|
||||
fileInputRef.current.value = "";
|
||||
fileInputRef.current.value = '';
|
||||
}, []);
|
||||
|
||||
const removeImage = useCallback((index: number) => {
|
||||
setImages((prev) => prev.filter((_, i) => i !== index));
|
||||
setImages(prev => prev.filter((_, i) => i !== index));
|
||||
}, []);
|
||||
|
||||
const handleCommandSelect = useCallback((command: AvailableCommand) => {
|
||||
setText(`/${command.name} `);
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
setCommandFilter('');
|
||||
textareaRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
const toggleCommandMenu = useCallback(() => {
|
||||
if (showCommandMenu) {
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
setCommandFilter('');
|
||||
} else {
|
||||
if (!text.startsWith("/")) {
|
||||
setText("/" + text);
|
||||
if (!text.startsWith('/')) {
|
||||
setText('/' + text);
|
||||
}
|
||||
setShowCommandMenu(true);
|
||||
setCommandFilter(text.startsWith("/") ? text.slice(1).split(/\s/)[0] || "" : "");
|
||||
setCommandFilter(text.startsWith('/') ? text.slice(1).split(/\s/)[0] || '' : '');
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
}, [showCommandMenu, text]);
|
||||
@@ -165,7 +171,7 @@ export function ChatInput({
|
||||
const canSend = (text.trim() || images.length > 0) && !disabled;
|
||||
|
||||
return (
|
||||
<div className={cn("w-full max-w-3xl mx-auto px-4 sm:px-8 pb-4 pt-2", className)}>
|
||||
<div className={cn('w-full max-w-3xl mx-auto px-4 sm:px-8 pb-4 pt-2', className)}>
|
||||
<div className="relative">
|
||||
{/* Slash command menu — floating above input */}
|
||||
{showCommandMenu && commands && commands.length > 0 && (
|
||||
@@ -175,127 +181,124 @@ export function ChatInput({
|
||||
onSelect={handleCommandSelect}
|
||||
onClose={() => {
|
||||
setShowCommandMenu(false);
|
||||
setCommandFilter("");
|
||||
setCommandFilter('');
|
||||
}}
|
||||
className="absolute bottom-full left-0 right-0 mb-1 z-50"
|
||||
/>
|
||||
)}
|
||||
<div className={cn(
|
||||
"rounded-xl border border-border bg-surface-2 overflow-hidden",
|
||||
"focus-within:border-brand/50 focus-within:shadow-[0_0_0_3px_rgba(217,119,87,0.15)] transition-all",
|
||||
)}>
|
||||
{/* 图片预览 */}
|
||||
{images.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 px-3 pt-3">
|
||||
{images.map((img, i) => (
|
||||
<div key={i} className="relative group">
|
||||
<img
|
||||
src={`data:${img.mimeType};base64,${img.data}`}
|
||||
alt={`Attached image ${i + 1}`}
|
||||
className="h-14 w-14 object-cover rounded-lg border border-border"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-xl border border-border bg-surface-2 overflow-hidden',
|
||||
'focus-within:border-brand/50 focus-within:shadow-[0_0_0_3px_rgba(217,119,87,0.15)] transition-all',
|
||||
)}
|
||||
>
|
||||
{/* 图片预览 */}
|
||||
{images.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 px-3 pt-3">
|
||||
{images.map((img, i) => (
|
||||
<div key={i} className="relative group">
|
||||
<img
|
||||
src={`data:${img.mimeType};base64,${img.data}`}
|
||||
alt={`Attached image ${i + 1}`}
|
||||
className="h-14 w-14 object-cover rounded-lg border border-border"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeImage(i)}
|
||||
className="absolute -top-1.5 -right-1.5 min-h-[32px] min-w-[32px] h-5 w-5 rounded-full bg-surface-2 border border-border flex items-center justify-center text-text-muted hover:text-text-primary text-xs opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
aria-label={`Remove image ${i + 1}`}
|
||||
>
|
||||
{'\u00D7'}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 输入区域 — Anthropic 单行紧凑布局 */}
|
||||
<div className="flex items-end gap-2 px-3 py-2.5">
|
||||
{/* 左侧附件按钮 */}
|
||||
{supportsImages && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeImage(i)}
|
||||
className="absolute -top-1.5 -right-1.5 min-h-[32px] min-w-[32px] h-5 w-5 rounded-full bg-surface-2 border border-border flex items-center justify-center text-text-muted hover:text-text-primary text-xs opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
aria-label={`Remove image ${i + 1}`}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg text-text-muted hover:text-text-secondary hover:bg-surface-1/50 transition-colors"
|
||||
disabled={disabled}
|
||||
>
|
||||
{"\u00D7"}
|
||||
<Paperclip className="h-4 w-4" />
|
||||
<span className="sr-only">Attach file</span>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 输入区域 — Anthropic 单行紧凑布局 */}
|
||||
<div className="flex items-end gap-2 px-3 py-2.5">
|
||||
{/* 左侧附件按钮 */}
|
||||
{supportsImages && (
|
||||
<>
|
||||
{/* Slash 命令按钮 */}
|
||||
{commands && commands.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg text-text-muted hover:text-text-secondary hover:bg-surface-1/50 transition-colors"
|
||||
onClick={toggleCommandMenu}
|
||||
className={cn(
|
||||
'flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg transition-colors',
|
||||
showCommandMenu
|
||||
? 'bg-brand/15 text-brand'
|
||||
: 'text-text-muted hover:text-text-secondary hover:bg-surface-1/50',
|
||||
)}
|
||||
disabled={disabled}
|
||||
title="命令列表"
|
||||
>
|
||||
<Paperclip className="h-4 w-4" />
|
||||
<span className="sr-only">Attach file</span>
|
||||
<Slash className="h-4 w-4" />
|
||||
</button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
)}
|
||||
|
||||
{/* Slash 命令按钮 */}
|
||||
{commands && commands.length > 0 && (
|
||||
{/* Textarea — Poppins font */}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={text}
|
||||
onChange={handleInput}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
rows={1}
|
||||
className={cn(
|
||||
'flex-1 resize-none border-none bg-transparent outline-none',
|
||||
'text-sm text-text-primary placeholder:text-text-muted font-display',
|
||||
'max-h-[200px] min-h-[24px] leading-normal',
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* 右侧发送/取消按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleCommandMenu}
|
||||
onClick={isLoading ? onInterrupt : handleSubmit}
|
||||
disabled={!isLoading && !canSend}
|
||||
className={cn(
|
||||
"flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg transition-colors",
|
||||
showCommandMenu
|
||||
? "bg-brand/15 text-brand"
|
||||
: "text-text-muted hover:text-text-secondary hover:bg-surface-1/50",
|
||||
'flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg transition-all',
|
||||
isLoading
|
||||
? 'bg-text-primary text-surface-2 hover:bg-text-secondary'
|
||||
: canSend
|
||||
? 'bg-brand text-white hover:bg-brand-light hover:scale-[1.05] active:scale-[0.97]'
|
||||
: 'bg-surface-1 text-text-muted',
|
||||
)}
|
||||
disabled={disabled}
|
||||
title="命令列表"
|
||||
>
|
||||
<Slash className="h-4 w-4" />
|
||||
{isLoading ? <Square className="h-3.5 w-3.5" fill="currentColor" /> : <Send className="h-4 w-4" />}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Textarea — Poppins font */}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={text}
|
||||
onChange={handleInput}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
rows={1}
|
||||
className={cn(
|
||||
"flex-1 resize-none border-none bg-transparent outline-none",
|
||||
"text-sm text-text-primary placeholder:text-text-muted font-display",
|
||||
"max-h-[200px] min-h-[24px] leading-normal",
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* 右侧发送/取消按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={isLoading ? onInterrupt : handleSubmit}
|
||||
disabled={!isLoading && !canSend}
|
||||
className={cn(
|
||||
"flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-lg transition-all",
|
||||
isLoading
|
||||
? "bg-text-primary text-surface-2 hover:bg-text-secondary"
|
||||
: canSend
|
||||
? "bg-brand text-white hover:bg-brand-light hover:scale-[1.05] active:scale-[0.97]"
|
||||
: "bg-surface-1 text-text-muted",
|
||||
)}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Square className="h-3.5 w-3.5" fill="currentColor" />
|
||||
) : (
|
||||
<Send className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>{/* end relative */}
|
||||
{/* end relative */}
|
||||
|
||||
{/* 提示文本 */}
|
||||
<div className="text-center mt-1.5">
|
||||
<span className="text-[11px] text-text-muted font-display">
|
||||
Enter 发送,Shift+Enter 换行
|
||||
</span>
|
||||
<span className="text-[11px] text-text-muted font-display">Enter 发送,Shift+Enter 换行</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -316,23 +319,23 @@ async function processImageFiles(files: File[]): Promise<UserMessageImage[]> {
|
||||
if (file.size > 2 * 1024 * 1024) {
|
||||
const compressed = await imageCompression(file, IMAGE_COMPRESSION_OPTIONS);
|
||||
blob = compressed;
|
||||
mimeType = "image/jpeg";
|
||||
mimeType = 'image/jpeg';
|
||||
}
|
||||
|
||||
const base64 = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const result = reader.result as string;
|
||||
const commaIdx = result.indexOf(",");
|
||||
const commaIdx = result.indexOf(',');
|
||||
resolve(commaIdx >= 0 ? result.slice(commaIdx + 1) : result);
|
||||
};
|
||||
reader.onerror = () => reject(new Error("FileReader error"));
|
||||
reader.onerror = () => reject(new Error('FileReader error'));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
|
||||
results.push({ mimeType, data: base64 });
|
||||
} catch (err) {
|
||||
console.error("Failed to process image:", err);
|
||||
console.error('Failed to process image:', err);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import type { ThreadEntry, ToolCallEntry, PlanDisplayEntry } from "../../src/lib/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { UserBubble, AssistantBubble } from "./MessageBubble";
|
||||
import { ToolCallGroup } from "./ToolCallGroup";
|
||||
import { PlanDisplay } from "./PlanView";
|
||||
import { Conversation, ConversationContent, ConversationEmptyState, ConversationScrollButtons } from "../ai-elements/conversation";
|
||||
import type { ThreadEntry, ToolCallEntry, PlanDisplayEntry } from '../../src/lib/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { UserBubble, AssistantBubble } from './MessageBubble';
|
||||
import { ToolCallGroup } from './ToolCallGroup';
|
||||
import { PlanDisplay } from './PlanView';
|
||||
import {
|
||||
Conversation,
|
||||
ConversationContent,
|
||||
ConversationEmptyState,
|
||||
ConversationScrollButtons,
|
||||
} from '../ai-elements/conversation';
|
||||
|
||||
// =============================================================================
|
||||
// 统一聊天视图 — Anthropic 编辑式排版
|
||||
@@ -22,28 +27,25 @@ export function ChatView({
|
||||
entries,
|
||||
isLoading = false,
|
||||
onPermissionRespond,
|
||||
emptyTitle = "开始对话",
|
||||
emptyDescription = "输入消息开始聊天",
|
||||
emptyTitle = '开始对话',
|
||||
emptyDescription = '输入消息开始聊天',
|
||||
}: ChatViewProps) {
|
||||
// 将相邻的 ToolCallEntry 合并为一组
|
||||
const grouped = groupToolCalls(entries);
|
||||
const hasMessages = entries.length > 0;
|
||||
|
||||
// 检查是否正在加载(最后一个条目是用户消息)
|
||||
const showThinking = isLoading && entries.length > 0 && entries[entries.length - 1]?.type === "user_message";
|
||||
const showThinking = isLoading && entries.length > 0 && entries[entries.length - 1]?.type === 'user_message';
|
||||
|
||||
return (
|
||||
<Conversation className="flex-1">
|
||||
<ConversationContent>
|
||||
{!hasMessages ? (
|
||||
<ConversationEmptyState
|
||||
title={emptyTitle}
|
||||
description={emptyDescription}
|
||||
/>
|
||||
<ConversationEmptyState title={emptyTitle} description={emptyDescription} />
|
||||
) : (
|
||||
<>
|
||||
{grouped.map((item, i) => {
|
||||
if (item.type === "single") {
|
||||
if (item.type === 'single') {
|
||||
return (
|
||||
<div key={`entry-${i}`} className={cn(entrySpacing(entries, i))}>
|
||||
<EntryRenderer entry={item.entry} isLoading={isLoading} onPermissionRespond={onPermissionRespond} />
|
||||
@@ -63,19 +65,25 @@ export function ChatView({
|
||||
<div className="flex gap-4 items-start">
|
||||
<div className="w-8 h-8 rounded-lg bg-brand/8 flex items-center justify-center flex-shrink-0">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="var(--color-brand)" fillRule="nonzero" />
|
||||
<path
|
||||
d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"
|
||||
fill="var(--color-brand)"
|
||||
fillRule="nonzero"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 pt-2">
|
||||
<span className="chat-typing-indicator" aria-hidden="true">
|
||||
<span></span><span></span><span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<ConversationScrollButtons hasUserMessages={entries.some((e) => e.type === "user_message")} />
|
||||
<ConversationScrollButtons hasUserMessages={entries.some(e => e.type === 'user_message')} />
|
||||
</ConversationContent>
|
||||
</Conversation>
|
||||
);
|
||||
@@ -88,22 +96,22 @@ export function ChatView({
|
||||
function entrySpacing(entries: ThreadEntry[], index: number): string {
|
||||
const entry = entries[index];
|
||||
// 用户消息前后大留白 — Claude.ai 式宽松间距
|
||||
if (entry?.type === "user_message") {
|
||||
return "pt-10 pb-3";
|
||||
if (entry?.type === 'user_message') {
|
||||
return 'pt-10 pb-3';
|
||||
}
|
||||
// 助手消息 — 工具调用紧贴,否则多留白
|
||||
if (entry?.type === "assistant_message") {
|
||||
if (entry?.type === 'assistant_message') {
|
||||
const next = entries[index + 1];
|
||||
if (next?.type === "tool_call") {
|
||||
return "pt-3 pb-1";
|
||||
if (next?.type === 'tool_call') {
|
||||
return 'pt-3 pb-1';
|
||||
}
|
||||
return "pt-3 pb-8";
|
||||
return 'pt-3 pb-8';
|
||||
}
|
||||
// Plan 条目
|
||||
if (entry?.type === "plan") {
|
||||
return "pt-3 pb-3";
|
||||
if (entry?.type === 'plan') {
|
||||
return 'pt-3 pb-3';
|
||||
}
|
||||
return "py-2";
|
||||
return 'py-2';
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
@@ -120,18 +128,13 @@ function EntryRenderer({
|
||||
onPermissionRespond?: (requestId: string, optionId: string | null, optionKind: string | null) => void;
|
||||
}) {
|
||||
switch (entry.type) {
|
||||
case "user_message":
|
||||
case 'user_message':
|
||||
return <UserBubble entry={entry} />;
|
||||
case "assistant_message":
|
||||
case 'assistant_message':
|
||||
return <AssistantBubble entry={entry} isStreaming={isLoading} />;
|
||||
case "tool_call":
|
||||
return (
|
||||
<ToolCallGroup
|
||||
entries={[entry as ToolCallEntry]}
|
||||
onPermissionRespond={onPermissionRespond}
|
||||
/>
|
||||
);
|
||||
case "plan":
|
||||
case 'tool_call':
|
||||
return <ToolCallGroup entries={[entry as ToolCallEntry]} onPermissionRespond={onPermissionRespond} />;
|
||||
case 'plan':
|
||||
return <PlanDisplay entry={entry as PlanDisplayEntry} />;
|
||||
default:
|
||||
return null;
|
||||
@@ -142,9 +145,7 @@ function EntryRenderer({
|
||||
// 工具调用分组逻辑
|
||||
// =============================================================================
|
||||
|
||||
type GroupedItem =
|
||||
| { type: "single"; entry: ThreadEntry }
|
||||
| { type: "tool_group"; entries: ToolCallEntry[] };
|
||||
type GroupedItem = { type: 'single'; entry: ThreadEntry } | { type: 'tool_group'; entries: ToolCallEntry[] };
|
||||
|
||||
function groupToolCalls(entries: ThreadEntry[]): GroupedItem[] {
|
||||
const result: GroupedItem[] = [];
|
||||
@@ -152,19 +153,19 @@ function groupToolCalls(entries: ThreadEntry[]): GroupedItem[] {
|
||||
|
||||
const flushToolGroup = () => {
|
||||
if (currentToolGroup.length === 1) {
|
||||
result.push({ type: "single", entry: currentToolGroup[0] });
|
||||
result.push({ type: 'single', entry: currentToolGroup[0] });
|
||||
} else if (currentToolGroup.length > 1) {
|
||||
result.push({ type: "tool_group", entries: currentToolGroup });
|
||||
result.push({ type: 'tool_group', entries: currentToolGroup });
|
||||
}
|
||||
currentToolGroup = [];
|
||||
};
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.type === "tool_call") {
|
||||
if (entry.type === 'tool_call') {
|
||||
currentToolGroup.push(entry);
|
||||
} else {
|
||||
flushToolGroup();
|
||||
result.push({ type: "single", entry });
|
||||
result.push({ type: 'single', entry });
|
||||
}
|
||||
}
|
||||
flushToolGroup();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo, useRef, useEffect, useState } from "react";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import type { AvailableCommand } from "../../src/acp/types";
|
||||
import { useMemo, useRef, useEffect, useState } from 'react';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import type { AvailableCommand } from '../../src/acp/types';
|
||||
|
||||
// =============================================================================
|
||||
// Slash command picker — floating above ChatInput
|
||||
@@ -23,22 +23,14 @@ function prefixMatch(query: string, text: string): boolean {
|
||||
return text.toLowerCase().startsWith(query.toLowerCase());
|
||||
}
|
||||
|
||||
export function CommandMenu({
|
||||
commands,
|
||||
filter,
|
||||
onSelect,
|
||||
onClose,
|
||||
className,
|
||||
}: CommandMenuProps) {
|
||||
export function CommandMenu({ commands, filter, onSelect, onClose, className }: CommandMenuProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
|
||||
// Filter commands by current input
|
||||
const filtered = useMemo(() => {
|
||||
if (!filter) return commands;
|
||||
return commands.filter(
|
||||
(cmd) => prefixMatch(filter, cmd.name),
|
||||
);
|
||||
return commands.filter(cmd => prefixMatch(filter, cmd.name));
|
||||
}, [commands, filter]);
|
||||
|
||||
// Reset active index when filter changes
|
||||
@@ -53,8 +45,8 @@ export function CommandMenu({
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener("mousedown", handleClick);
|
||||
return () => document.removeEventListener("mousedown", handleClick);
|
||||
document.addEventListener('mousedown', handleClick);
|
||||
return () => document.removeEventListener('mousedown', handleClick);
|
||||
}, [onClose]);
|
||||
|
||||
// Handle keyboard navigation (ArrowUp/ArrowDown/Enter) via document-level listener
|
||||
@@ -62,21 +54,21 @@ export function CommandMenu({
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (filtered.length === 0) return;
|
||||
|
||||
if (e.key === "ArrowDown") {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
setActiveIndex((prev) => (prev + 1) % filtered.length);
|
||||
} else if (e.key === "ArrowUp") {
|
||||
setActiveIndex(prev => (prev + 1) % filtered.length);
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setActiveIndex((prev) => (prev - 1 + filtered.length) % filtered.length);
|
||||
} else if (e.key === "Enter" && !e.shiftKey) {
|
||||
setActiveIndex(prev => (prev - 1 + filtered.length) % filtered.length);
|
||||
} else if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
const cmd = filtered[activeIndex];
|
||||
if (cmd) onSelect(cmd);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("keydown", handleKeyDown, true); // capture phase
|
||||
return () => document.removeEventListener("keydown", handleKeyDown, true);
|
||||
document.addEventListener('keydown', handleKeyDown, true); // capture phase
|
||||
return () => document.removeEventListener('keydown', handleKeyDown, true);
|
||||
}, [filtered, activeIndex, onSelect]);
|
||||
|
||||
// Scroll active item into view
|
||||
@@ -84,22 +76,14 @@ export function CommandMenu({
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
const active = container.querySelector("[data-active='true']");
|
||||
active?.scrollIntoView({ block: "nearest" });
|
||||
active?.scrollIntoView({ block: 'nearest' });
|
||||
}, [activeIndex]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
"rounded-xl border border-border bg-surface-2 shadow-lg",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div ref={containerRef} className={cn('rounded-xl border border-border bg-surface-2 shadow-lg', className)}>
|
||||
<div className="max-h-[320px] overflow-y-auto py-1">
|
||||
{filtered.length === 0 ? (
|
||||
<div className="text-xs text-text-muted font-display py-3 text-center">
|
||||
没有匹配的命令
|
||||
</div>
|
||||
<div className="text-xs text-text-muted font-display py-3 text-center">没有匹配的命令</div>
|
||||
) : (
|
||||
filtered.map((cmd, index) => (
|
||||
<button
|
||||
@@ -109,25 +93,15 @@ export function CommandMenu({
|
||||
onClick={() => onSelect(cmd)}
|
||||
onMouseEnter={() => setActiveIndex(index)}
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2 px-3 py-2 cursor-pointer rounded-lg mx-1 text-left",
|
||||
"transition-colors",
|
||||
index === activeIndex
|
||||
? "bg-brand/10 text-text-primary"
|
||||
: "text-text-secondary hover:bg-surface-1/50",
|
||||
'flex w-full items-center gap-2 px-3 py-2 cursor-pointer rounded-lg mx-1 text-left',
|
||||
'transition-colors',
|
||||
index === activeIndex ? 'bg-brand/10 text-text-primary' : 'text-text-secondary hover:bg-surface-1/50',
|
||||
)}
|
||||
style={{ width: "calc(100% - 8px)" }}
|
||||
style={{ width: 'calc(100% - 8px)' }}
|
||||
>
|
||||
<span className="text-sm font-display font-medium text-brand">
|
||||
/{cmd.name}
|
||||
</span>
|
||||
<span className="text-xs text-text-muted truncate flex-1">
|
||||
{cmd.description}
|
||||
</span>
|
||||
{cmd.input?.hint && (
|
||||
<span className="text-[10px] text-text-muted italic">
|
||||
{cmd.input.hint}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-sm font-display font-medium text-brand">/{cmd.name}</span>
|
||||
<span className="text-xs text-text-muted truncate flex-1">{cmd.description}</span>
|
||||
{cmd.input?.hint && <span className="text-[10px] text-text-muted italic">{cmd.input.hint}</span>}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useState, useRef, useEffect, useCallback } from "react";
|
||||
import type { UserMessageEntry, AssistantMessageEntry, UserMessageImage } from "../../src/lib/types";
|
||||
import { cn, esc } from "../../src/lib/utils";
|
||||
import { MessageResponse } from "../ai-elements/message";
|
||||
import { Reasoning, ReasoningTrigger, ReasoningContent } from "../ai-elements/reasoning";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import type { UserMessageEntry, AssistantMessageEntry, UserMessageImage } from '../../src/lib/types';
|
||||
import { cn, esc } from '../../src/lib/utils';
|
||||
import { MessageResponse } from '../ai-elements/message';
|
||||
import { Reasoning, ReasoningTrigger, ReasoningContent } from '../ai-elements/reasoning';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
|
||||
// 用户消息折叠最大高度(px)
|
||||
const COLLAPSED_MAX_HEIGHT = 200;
|
||||
@@ -48,7 +48,7 @@ export function UserBubble({ entry }: UserBubbleProps) {
|
||||
<div
|
||||
ref={contentRef}
|
||||
className={cn(
|
||||
"px-5 py-3 text-sm text-white whitespace-pre-wrap font-display leading-relaxed",
|
||||
'px-5 py-3 text-sm text-white whitespace-pre-wrap font-display leading-relaxed',
|
||||
!expanded && overflowing && `max-h-[${COLLAPSED_MAX_HEIGHT}px]`,
|
||||
)}
|
||||
style={!expanded && overflowing ? { maxHeight: `${COLLAPSED_MAX_HEIGHT}px` } : undefined}
|
||||
@@ -90,7 +90,11 @@ export function AssistantBubble({ entry, isStreaming }: AssistantBubbleProps) {
|
||||
{/* Orange triangle avatar */}
|
||||
<div className="w-8 h-8 rounded-lg bg-brand/8 flex items-center justify-center flex-shrink-0 mt-0.5">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="var(--color-brand)" fillRule="nonzero" />
|
||||
<path
|
||||
d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"
|
||||
fill="var(--color-brand)"
|
||||
fillRule="nonzero"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/* 内容 — 无卡片背景,直接排版 */}
|
||||
@@ -98,16 +102,14 @@ export function AssistantBubble({ entry, isStreaming }: AssistantBubbleProps) {
|
||||
{/* Sender label */}
|
||||
<span className="text-sm font-semibold text-text-primary font-display">Claude</span>
|
||||
{entry.chunks.map((chunk, i) => {
|
||||
if (chunk.type === "thought") {
|
||||
if (chunk.type === 'thought') {
|
||||
const isLastChunk = i === entry.chunks.length - 1;
|
||||
const isThoughtStreaming = isStreaming && isLastChunk;
|
||||
return (
|
||||
<Reasoning key={i} isStreaming={isThoughtStreaming}>
|
||||
<ReasoningTrigger />
|
||||
<ReasoningContent>
|
||||
<div className="text-sm text-text-secondary leading-relaxed">
|
||||
{chunk.text}
|
||||
</div>
|
||||
<div className="text-sm text-text-secondary leading-relaxed">{chunk.text}</div>
|
||||
</ReasoningContent>
|
||||
</Reasoning>
|
||||
);
|
||||
@@ -135,17 +137,13 @@ function ImageThumbnail({ image }: { image: UserMessageImage }) {
|
||||
type="button"
|
||||
className="rounded-lg overflow-hidden border border-border hover:border-brand/40 transition-colors cursor-pointer"
|
||||
onClick={() => {
|
||||
const w = window.open("");
|
||||
const w = window.open('');
|
||||
if (w) {
|
||||
w.document.write(`<img src="${dataUrl}" style="max-width:100%;max-height:100%" />`);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={dataUrl}
|
||||
alt="Uploaded image"
|
||||
className="h-20 w-20 object-cover"
|
||||
/>
|
||||
<img src={dataUrl} alt="Uploaded image" className="h-20 w-20 object-cover" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PendingPermission } from "../../src/lib/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { ShieldAlert, Check, X } from "lucide-react";
|
||||
import type { PendingPermission } from '../../src/lib/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { ShieldAlert, Check, X } from 'lucide-react';
|
||||
|
||||
// =============================================================================
|
||||
// 权限请求面板 — 固定在输入框上方(Anthropic warm token style)
|
||||
@@ -16,14 +16,10 @@ export function PermissionPanel({ requests, onRespond, className }: PermissionPa
|
||||
if (requests.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={cn("w-full max-w-3xl mx-auto px-4", className)}>
|
||||
<div className={cn('w-full max-w-3xl mx-auto px-4', className)}>
|
||||
<div className="space-y-2">
|
||||
{requests.map((req) => (
|
||||
<PermissionCard
|
||||
key={req.requestId}
|
||||
request={req}
|
||||
onRespond={onRespond}
|
||||
/>
|
||||
{requests.map(req => (
|
||||
<PermissionCard key={req.requestId} request={req} onRespond={onRespond} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -44,13 +40,9 @@ function PermissionCard({ request, onRespond }: PermissionCardProps) {
|
||||
<div className="flex items-center gap-3 rounded-xl border border-warning-border/30 bg-warning-bg/50 px-4 py-3">
|
||||
<ShieldAlert className="h-5 w-5 text-warning-text flex-shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-warning-text">
|
||||
{request.toolName}
|
||||
</div>
|
||||
<div className="text-sm font-medium text-warning-text">{request.toolName}</div>
|
||||
{request.description && (
|
||||
<div className="text-xs text-warning-text/80 mt-0.5 truncate">
|
||||
{request.description}
|
||||
</div>
|
||||
<div className="text-xs text-warning-text/80 mt-0.5 truncate">{request.description}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useState } from "react";
|
||||
import type { PlanDisplayEntry } from "../../src/lib/types";
|
||||
import type { PlanEntry, PlanEntryPriority, PlanEntryStatus } from "../../src/acp/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { CheckCircle2, Loader2, Circle } from "lucide-react";
|
||||
import { useState } from 'react';
|
||||
import type { PlanDisplayEntry } from '../../src/lib/types';
|
||||
import type { PlanEntry, PlanEntryPriority, PlanEntryStatus } from '../../src/acp/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { CheckCircle2, Loader2, Circle } from 'lucide-react';
|
||||
|
||||
// =============================================================================
|
||||
// Plan 展示组件 — 执行计划可视化
|
||||
@@ -18,7 +18,7 @@ export function PlanDisplay({ entry }: PlanDisplayProps) {
|
||||
|
||||
if (entries.length === 0) return null;
|
||||
|
||||
const completed = entries.filter((e) => e.status === "completed").length;
|
||||
const completed = entries.filter(e => e.status === 'completed').length;
|
||||
const total = entries.length;
|
||||
const percentage = total > 0 ? Math.round((completed / total) * 100) : 0;
|
||||
|
||||
@@ -36,14 +36,12 @@ export function PlanDisplay({ entry }: PlanDisplayProps) {
|
||||
height="12"
|
||||
viewBox="0 0 12 12"
|
||||
fill="none"
|
||||
className={cn("transition-transform text-text-muted flex-shrink-0", collapsed && "rotate-90")}
|
||||
className={cn('transition-transform text-text-muted flex-shrink-0', collapsed && 'rotate-90')}
|
||||
>
|
||||
<path d="M4 2L8 6L4 10" stroke="currentColor" strokeWidth="1.5" fill="none" />
|
||||
</svg>
|
||||
|
||||
<span className="text-xs font-display font-medium text-text-secondary">
|
||||
执行计划
|
||||
</span>
|
||||
<span className="text-xs font-display font-medium text-text-secondary">执行计划</span>
|
||||
|
||||
<span className="text-[10px] text-text-muted font-mono">
|
||||
{completed}/{total}
|
||||
@@ -57,17 +55,14 @@ export function PlanDisplay({ entry }: PlanDisplayProps) {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span className="text-[10px] text-text-muted font-mono">
|
||||
{percentage}%
|
||||
</span>
|
||||
<span className="text-[10px] text-text-muted font-mono">{percentage}%</span>
|
||||
</button>
|
||||
|
||||
{/* Entry list */}
|
||||
{!collapsed && (
|
||||
<div className={cn(
|
||||
"border-t border-border px-3 py-1.5 space-y-0.5",
|
||||
total > 5 && "max-h-64 overflow-y-auto",
|
||||
)}>
|
||||
<div
|
||||
className={cn('border-t border-border px-3 py-1.5 space-y-0.5', total > 5 && 'max-h-64 overflow-y-auto')}
|
||||
>
|
||||
{entries.map((planEntry, i) => (
|
||||
<PlanEntryRow key={i} entry={planEntry} />
|
||||
))}
|
||||
@@ -88,11 +83,13 @@ function PlanEntryRow({ entry }: { entry: PlanEntry }) {
|
||||
<span className="flex-shrink-0 mt-0.5">
|
||||
<StatusIcon status={entry.status} />
|
||||
</span>
|
||||
<span className={cn(
|
||||
"text-xs leading-relaxed flex-1",
|
||||
entry.status === "completed" ? "text-text-muted line-through" : "text-text-secondary",
|
||||
entry.status === "in_progress" && "text-text-primary font-medium",
|
||||
)}>
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs leading-relaxed flex-1',
|
||||
entry.status === 'completed' ? 'text-text-muted line-through' : 'text-text-secondary',
|
||||
entry.status === 'in_progress' && 'text-text-primary font-medium',
|
||||
)}
|
||||
>
|
||||
{entry.content}
|
||||
</span>
|
||||
<PriorityBadge priority={entry.priority} />
|
||||
@@ -106,11 +103,11 @@ function PlanEntryRow({ entry }: { entry: PlanEntry }) {
|
||||
|
||||
function StatusIcon({ status }: { status: PlanEntryStatus }) {
|
||||
switch (status) {
|
||||
case "completed":
|
||||
case 'completed':
|
||||
return <CheckCircle2 className="h-3.5 w-3.5 text-status-active" />;
|
||||
case "in_progress":
|
||||
return <Loader2 className="h-3.5 w-3.5 text-brand animate-spin" style={{ animationDuration: "2s" }} />;
|
||||
case "pending":
|
||||
case 'in_progress':
|
||||
return <Loader2 className="h-3.5 w-3.5 text-brand animate-spin" style={{ animationDuration: '2s' }} />;
|
||||
case 'pending':
|
||||
return <Circle className="h-3.5 w-3.5 text-text-muted" />;
|
||||
}
|
||||
}
|
||||
@@ -121,22 +118,21 @@ function StatusIcon({ status }: { status: PlanEntryStatus }) {
|
||||
|
||||
function PriorityBadge({ priority }: { priority: PlanEntryPriority }) {
|
||||
const styles: Record<PlanEntryPriority, string> = {
|
||||
high: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",
|
||||
medium: "bg-brand/10 text-brand dark:bg-brand/20",
|
||||
low: "bg-surface-1 text-text-muted",
|
||||
high: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
|
||||
medium: 'bg-brand/10 text-brand dark:bg-brand/20',
|
||||
low: 'bg-surface-1 text-text-muted',
|
||||
};
|
||||
|
||||
const labels: Record<PlanEntryPriority, string> = {
|
||||
high: "高",
|
||||
medium: "中",
|
||||
low: "低",
|
||||
high: '高',
|
||||
medium: '中',
|
||||
low: '低',
|
||||
};
|
||||
|
||||
return (
|
||||
<span className={cn(
|
||||
"text-[9px] font-display rounded-full px-1.5 py-0.5 flex-shrink-0 leading-none",
|
||||
styles[priority],
|
||||
)}>
|
||||
<span
|
||||
className={cn('text-[9px] font-display rounded-full px-1.5 py-0.5 flex-shrink-0 leading-none', styles[priority])}
|
||||
>
|
||||
{labels[priority]}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { Plus, MessageSquare, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import type { SessionListItem } from "../../src/lib/types";
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Plus, MessageSquare, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import type { SessionListItem } from '../../src/lib/types';
|
||||
|
||||
// =============================================================================
|
||||
// 会话侧边栏 — Anthropic 分段式:今天/昨天/更早 + 橙色活跃态
|
||||
@@ -15,13 +15,7 @@ interface SessionSidebarProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function SessionSidebar({
|
||||
sessions,
|
||||
activeId,
|
||||
onSelect,
|
||||
onNew,
|
||||
className,
|
||||
}: SessionSidebarProps) {
|
||||
export function SessionSidebar({ sessions, activeId, onSelect, onNew, className }: SessionSidebarProps) {
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
|
||||
// 按日期分组
|
||||
@@ -30,8 +24,8 @@ export function SessionSidebar({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"hidden md:flex flex-col border-r border-border bg-surface-1 transition-all duration-200",
|
||||
collapsed ? "w-12" : "w-64",
|
||||
'hidden md:flex flex-col border-r border-border bg-surface-1 transition-all duration-200',
|
||||
collapsed ? 'w-12' : 'w-64',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
@@ -55,11 +49,7 @@ export function SessionSidebar({
|
||||
onClick={() => setCollapsed(!collapsed)}
|
||||
className="h-7 w-7 flex items-center justify-center rounded-lg text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors"
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
)}
|
||||
{collapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronLeft className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -67,30 +57,28 @@ export function SessionSidebar({
|
||||
{/* 会话列表 — 分段 */}
|
||||
{!collapsed && (
|
||||
<nav className="flex-1 overflow-y-auto py-2" aria-label="历史会话">
|
||||
{groups.map((group) => (
|
||||
{groups.map(group => (
|
||||
<div key={group.label}>
|
||||
<div className="px-3 py-1.5">
|
||||
<span className="text-[10px] font-display font-medium uppercase tracking-widest text-text-muted">
|
||||
{group.label}
|
||||
</span>
|
||||
</div>
|
||||
{group.sessions.map((session) => (
|
||||
{group.sessions.map(session => (
|
||||
<button
|
||||
key={session.id}
|
||||
type="button"
|
||||
onClick={() => onSelect?.(session.id)}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2 px-3 py-2 text-left transition-colors",
|
||||
'w-full flex items-center gap-2 px-3 py-2 text-left transition-colors',
|
||||
session.id === activeId
|
||||
? "bg-brand/10 text-text-primary"
|
||||
: "text-text-secondary hover:bg-surface-1/50 hover:text-text-primary",
|
||||
? 'bg-brand/10 text-text-primary'
|
||||
: 'text-text-secondary hover:bg-surface-1/50 hover:text-text-primary',
|
||||
)}
|
||||
title={session.title || session.id}
|
||||
>
|
||||
<MessageSquare className="h-3.5 w-3.5 shrink-0 text-text-muted" />
|
||||
<span className="text-sm font-display truncate">
|
||||
{session.title || session.id.slice(0, 8)}
|
||||
</span>
|
||||
<span className="text-sm font-display truncate">{session.title || session.id.slice(0, 8)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -121,9 +109,9 @@ function groupByRecency(sessions: SessionListItem[]): SessionGroup[] {
|
||||
const yesterday = new Date(today.getTime() - 86400000);
|
||||
|
||||
const groups: SessionGroup[] = [
|
||||
{ label: "今天", sessions: [] },
|
||||
{ label: "昨天", sessions: [] },
|
||||
{ label: "更早", sessions: [] },
|
||||
{ label: '今天', sessions: [] },
|
||||
{ label: '昨天', sessions: [] },
|
||||
{ label: '更早', sessions: [] },
|
||||
];
|
||||
|
||||
for (const session of sessions) {
|
||||
@@ -137,5 +125,5 @@ function groupByRecency(sessions: SessionListItem[]): SessionGroup[] {
|
||||
}
|
||||
}
|
||||
|
||||
return groups.filter((g) => g.sessions.length > 0);
|
||||
return groups.filter(g => g.sessions.length > 0);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import type { ToolCallEntry, ToolCallData } from "../../src/lib/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { ToolPermissionButtons } from "../ai-elements/permission-request";
|
||||
import { useState } from 'react';
|
||||
import type { ToolCallEntry, ToolCallData } from '../../src/lib/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { ToolPermissionButtons } from '../ai-elements/permission-request';
|
||||
|
||||
// =============================================================================
|
||||
// 工具调用折叠组 — Anthropic: subtle card, left-border accent, compact layout
|
||||
@@ -21,11 +21,7 @@ export function ToolCallGroup({ entries, onPermissionRespond }: ToolCallGroupPro
|
||||
if (entries.length === 1) {
|
||||
return (
|
||||
<div className="pl-10">
|
||||
<SingleToolCard
|
||||
tool={entries[0].toolCall}
|
||||
compact
|
||||
onPermissionRespond={onPermissionRespond}
|
||||
/>
|
||||
<SingleToolCard tool={entries[0].toolCall} compact onPermissionRespond={onPermissionRespond} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -47,7 +43,7 @@ export function ToolCallGroup({ entries, onPermissionRespond }: ToolCallGroupPro
|
||||
height="12"
|
||||
viewBox="0 0 12 12"
|
||||
fill="none"
|
||||
className={cn("transition-transform text-text-muted", expanded && "rotate-90")}
|
||||
className={cn('transition-transform text-text-muted', expanded && 'rotate-90')}
|
||||
>
|
||||
<path d="M4 2L8 6L4 10" stroke="currentColor" strokeWidth="1.5" fill="none" />
|
||||
</svg>
|
||||
@@ -87,27 +83,28 @@ function SingleToolCard({ tool, compact, onPermissionRespond }: SingleToolCardPr
|
||||
|
||||
const statusIcon = (() => {
|
||||
switch (tool.status) {
|
||||
case "running":
|
||||
case 'running':
|
||||
return <span className="text-status-running text-[10px]">▶</span>;
|
||||
case "complete":
|
||||
case 'complete':
|
||||
return <span className="text-status-active text-[10px]">✓</span>;
|
||||
case "error":
|
||||
case 'error':
|
||||
return <span className="text-status-error text-[10px]">✕</span>;
|
||||
case "waiting_for_confirmation":
|
||||
case 'waiting_for_confirmation':
|
||||
return <span className="text-brand text-[10px]">⍻</span>;
|
||||
case "canceled":
|
||||
case 'canceled':
|
||||
return <span className="text-text-muted text-[10px]">—</span>;
|
||||
case "rejected":
|
||||
case 'rejected':
|
||||
return <span className="text-status-error text-[10px]">✕</span>;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
const hasOutput = tool.status !== "running" && tool.status !== "waiting_for_confirmation" && (tool.rawOutput || tool.content);
|
||||
const hasOutput =
|
||||
tool.status !== 'running' && tool.status !== 'waiting_for_confirmation' && (tool.rawOutput || tool.content);
|
||||
|
||||
return (
|
||||
<div className={cn("px-3 py-2", compact && "py-1.5")}>
|
||||
<div className={cn('px-3 py-2', compact && 'py-1.5')}>
|
||||
{/* 标题行 — 单行紧凑 */}
|
||||
<button
|
||||
type="button"
|
||||
@@ -118,13 +115,11 @@ function SingleToolCard({ tool, compact, onPermissionRespond }: SingleToolCardPr
|
||||
<span className="text-xs font-display font-medium text-text-secondary group-hover:text-text-primary transition-colors truncate">
|
||||
{tool.title}
|
||||
</span>
|
||||
{tool.status === "running" && (
|
||||
<span className="text-[10px] text-status-running animate-pulse">running</span>
|
||||
)}
|
||||
{tool.status === 'running' && <span className="text-[10px] text-status-running animate-pulse">running</span>}
|
||||
</button>
|
||||
|
||||
{/* 权限请求按钮 */}
|
||||
{tool.status === "waiting_for_confirmation" && tool.permissionRequest && (
|
||||
{tool.status === 'waiting_for_confirmation' && tool.permissionRequest && (
|
||||
<div className="mt-1.5 ml-4">
|
||||
<ToolPermissionButtons
|
||||
requestId={tool.permissionRequest.requestId}
|
||||
@@ -146,10 +141,12 @@ function SingleToolCard({ tool, compact, onPermissionRespond }: SingleToolCardPr
|
||||
)}
|
||||
{hasOutput && (
|
||||
<div>
|
||||
<pre className={cn(
|
||||
"text-[11px] rounded-md p-2 overflow-x-auto font-mono max-h-36",
|
||||
tool.status === "error" ? "bg-status-error/10 text-status-error" : "bg-surface-1 text-text-secondary",
|
||||
)}>
|
||||
<pre
|
||||
className={cn(
|
||||
'text-[11px] rounded-md p-2 overflow-x-auto font-mono max-h-36',
|
||||
tool.status === 'error' ? 'bg-status-error/10 text-status-error' : 'bg-surface-1 text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{formatOutput(tool)}
|
||||
</pre>
|
||||
</div>
|
||||
@@ -179,7 +176,7 @@ function buildSummary(entries: ToolCallEntry[]): string {
|
||||
|
||||
if (parts.length === 0) return `${entries.length} 个工具调用`;
|
||||
if (parts.length === 1) return parts[0];
|
||||
return `${entries.length} 个工具: ${parts.join("、")}`;
|
||||
return `${entries.length} 个工具: ${parts.join('、')}`;
|
||||
}
|
||||
|
||||
/** 简化工具名称 */
|
||||
@@ -192,17 +189,17 @@ function simplifyToolName(title: string): string {
|
||||
function formatOutput(tool: ToolCallData): string {
|
||||
if (tool.content && tool.content.length > 0) {
|
||||
const texts = tool.content
|
||||
.filter((c): c is Extract<typeof c, { type: "content" }> => c.type === "content")
|
||||
.filter((c) => c.content.type === "text" && "text" in c.content)
|
||||
.map((c) => (c.content as { text: string }).text);
|
||||
if (texts.length > 0) return truncate(texts.join("\n"), 2000);
|
||||
.filter((c): c is Extract<typeof c, { type: 'content' }> => c.type === 'content')
|
||||
.filter(c => c.content.type === 'text' && 'text' in c.content)
|
||||
.map(c => (c.content as { text: string }).text);
|
||||
if (texts.length > 0) return truncate(texts.join('\n'), 2000);
|
||||
}
|
||||
if (tool.rawOutput && Object.keys(tool.rawOutput).length > 0) {
|
||||
return truncate(JSON.stringify(tool.rawOutput, null, 2), 2000);
|
||||
}
|
||||
return "";
|
||||
return '';
|
||||
}
|
||||
|
||||
function truncate(str: string, max: number): string {
|
||||
return str.length > max ? str.slice(0, max) + "..." : str;
|
||||
return str.length > max ? str.slice(0, max) + '...' : str;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
export { ChatView } from "./ChatView";
|
||||
export { UserBubble, AssistantBubble } from "./MessageBubble";
|
||||
export { ToolCallGroup } from "./ToolCallGroup";
|
||||
export { PlanDisplay } from "./PlanView";
|
||||
export { ChatInput } from "./ChatInput";
|
||||
export { PermissionPanel } from "./PermissionPanel";
|
||||
export { SessionSidebar } from "./SessionSidebar";
|
||||
export { CommandMenu } from "./CommandMenu";
|
||||
export { ChatView } from './ChatView'
|
||||
export { UserBubble, AssistantBubble } from './MessageBubble'
|
||||
export { ToolCallGroup } from './ToolCallGroup'
|
||||
export { PlanDisplay } from './PlanView'
|
||||
export { ChatInput } from './ChatInput'
|
||||
export { PermissionPanel } from './PermissionPanel'
|
||||
export { SessionSidebar } from './SessionSidebar'
|
||||
export { CommandMenu } from './CommandMenu'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export * from "./ACPConnect";
|
||||
export * from "./ACPMain";
|
||||
export * from "./ChatInterface";
|
||||
export * from "./ChatMessage";
|
||||
export * from "./ThreadHistory";
|
||||
export * from "./model-selector";
|
||||
export * from './ACPConnect'
|
||||
export * from './ACPMain'
|
||||
export * from './ChatInterface'
|
||||
export * from './ChatMessage'
|
||||
export * from './ThreadHistory'
|
||||
export * from './model-selector'
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
import { useState, useMemo } from "react";
|
||||
import { Check } from "lucide-react";
|
||||
import {
|
||||
Command,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
} from "../ui/command";
|
||||
import type { ModelInfo } from "../../src/acp/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { useState, useMemo } from 'react';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from '../ui/command';
|
||||
import type { ModelInfo } from '../../src/acp/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
interface ModelSelectorPickerProps {
|
||||
models: ModelInfo[];
|
||||
@@ -51,33 +44,24 @@ export function ModelSelectorPicker({
|
||||
showSearch = true,
|
||||
isMobile = false,
|
||||
}: ModelSelectorPickerProps) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [search, setSearch] = useState('');
|
||||
// On mobile, don't auto-select first item (no keyboard navigation needed)
|
||||
// Use a non-existent value to prevent any item from being selected
|
||||
const [selectedValue, setSelectedValue] = useState(isMobile ? "__none__" : undefined);
|
||||
const [selectedValue, setSelectedValue] = useState(isMobile ? '__none__' : undefined);
|
||||
|
||||
// Filter models using fuzzy search
|
||||
const filteredModels = useMemo(() => {
|
||||
if (!search) return models;
|
||||
return models.filter((model) =>
|
||||
fuzzyMatch(search, model.name) ||
|
||||
fuzzyMatch(search, model.modelId)
|
||||
);
|
||||
return models.filter(model => fuzzyMatch(search, model.name) || fuzzyMatch(search, model.modelId));
|
||||
}, [models, search]);
|
||||
|
||||
return (
|
||||
<Command shouldFilter={false} value={selectedValue} onValueChange={setSelectedValue}>
|
||||
{showSearch && (
|
||||
<CommandInput
|
||||
placeholder="Select a model…"
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
/>
|
||||
)}
|
||||
{showSearch && <CommandInput placeholder="Select a model…" value={search} onValueChange={setSearch} />}
|
||||
<CommandList>
|
||||
<CommandEmpty>No models found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{filteredModels.map((model) => (
|
||||
{filteredModels.map(model => (
|
||||
<CommandItem
|
||||
key={model.modelId}
|
||||
value={model.modelId}
|
||||
@@ -87,16 +71,11 @@ export function ModelSelectorPicker({
|
||||
<div className="flex flex-col gap-0.5 min-w-0">
|
||||
<span className="truncate font-medium">{model.name}</span>
|
||||
{model.description && (
|
||||
<span className="text-xs text-muted-foreground truncate">
|
||||
{model.description}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground truncate">{model.description}</span>
|
||||
)}
|
||||
</div>
|
||||
<Check
|
||||
className={cn(
|
||||
"h-4 w-4 shrink-0",
|
||||
currentModelId === model.modelId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
className={cn('h-4 w-4 shrink-0', currentModelId === model.modelId ? 'opacity-100' : 'opacity-0')}
|
||||
/>
|
||||
</CommandItem>
|
||||
))}
|
||||
@@ -105,4 +84,3 @@ export function ModelSelectorPicker({
|
||||
</Command>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useState } from "react";
|
||||
import { ChevronDown, ChevronUp, Loader2 } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
|
||||
import { ModelSelectorPicker } from "./ModelSelectorPicker";
|
||||
import type { ACPClient } from "../../src/acp/client";
|
||||
import type { ModelInfo } from "../../src/acp/types";
|
||||
import { useModels } from "../../src/hooks/useModels";
|
||||
import { useState } from 'react';
|
||||
import { ChevronDown, ChevronUp, Loader2 } from 'lucide-react';
|
||||
import { Button } from '../ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
|
||||
import { ModelSelectorPicker } from './ModelSelectorPicker';
|
||||
import type { ACPClient } from '../../src/acp/client';
|
||||
import type { ModelInfo } from '../../src/acp/types';
|
||||
import { useModels } from '../../src/hooks/useModels';
|
||||
|
||||
interface ModelSelectorPopoverProps {
|
||||
/** ACPClient instance for model state management */
|
||||
@@ -18,25 +18,15 @@ interface ModelSelectorPopoverProps {
|
||||
* Model selector popover component.
|
||||
* Reference: Zed's AcpModelSelectorPopover that shows current model and allows switching.
|
||||
*/
|
||||
export function ModelSelectorPopover({
|
||||
client,
|
||||
onModelSelect,
|
||||
}: ModelSelectorPopoverProps) {
|
||||
export function ModelSelectorPopover({ client, onModelSelect }: ModelSelectorPopoverProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const {
|
||||
supportsModelSelection,
|
||||
availableModels,
|
||||
currentModel,
|
||||
setModel,
|
||||
isLoading,
|
||||
} = useModels(client);
|
||||
const { supportsModelSelection, availableModels, currentModel, setModel, isLoading } = useModels(client);
|
||||
|
||||
// Always show the button — disable dropdown when no models available
|
||||
const hasModels = supportsModelSelection && availableModels.length > 0;
|
||||
|
||||
// Check if we're on a mobile device (touch-only)
|
||||
const isMobile = typeof window !== "undefined" &&
|
||||
window.matchMedia("(hover: none) and (pointer: coarse)").matches;
|
||||
const isMobile = typeof window !== 'undefined' && window.matchMedia('(hover: none) and (pointer: coarse)').matches;
|
||||
|
||||
const handleSelect = async (model: ModelInfo) => {
|
||||
try {
|
||||
@@ -44,7 +34,7 @@ export function ModelSelectorPopover({
|
||||
onModelSelect?.(model.modelId);
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
console.error("[ModelSelector] Failed to set model:", error);
|
||||
console.error('[ModelSelector] Failed to set model:', error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -57,17 +47,9 @@ export function ModelSelectorPopover({
|
||||
className="gap-1.5 text-muted-foreground hover:text-foreground h-7 px-2"
|
||||
disabled={!hasModels || isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : null}
|
||||
<span className="max-w-32 truncate">
|
||||
{currentModel?.name ?? "Select Model"}
|
||||
</span>
|
||||
{open ? (
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
)}
|
||||
{isLoading ? <Loader2 className="h-3 w-3 animate-spin" /> : null}
|
||||
<span className="max-w-32 truncate">{currentModel?.name ?? 'Select Model'}</span>
|
||||
{open ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-72 p-0" align="end">
|
||||
@@ -82,4 +64,3 @@ export function ModelSelectorPopover({
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
export { ModelSelectorPopover } from "./ModelSelectorPopover";
|
||||
export { ModelSelectorPicker } from "./ModelSelectorPicker";
|
||||
|
||||
export { ModelSelectorPopover } from './ModelSelectorPopover'
|
||||
export { ModelSelectorPicker } from './ModelSelectorPicker'
|
||||
|
||||
@@ -1,47 +1,36 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-full 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",
|
||||
'inline-flex items-center justify-center rounded-full 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",
|
||||
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",
|
||||
'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",
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
}: React.ComponentProps<'span'> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : 'span';
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return <Comp data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { Separator } from "./separator"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Separator } from './separator';
|
||||
|
||||
const buttonGroupVariants = cva(
|
||||
"flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
|
||||
@@ -10,22 +10,22 @@ const buttonGroupVariants = cva(
|
||||
variants: {
|
||||
orientation: {
|
||||
horizontal:
|
||||
"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
|
||||
'[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none',
|
||||
vertical:
|
||||
"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
|
||||
'flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
orientation: "horizontal",
|
||||
orientation: 'horizontal',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function ButtonGroup({
|
||||
className,
|
||||
orientation,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
|
||||
}: React.ComponentProps<'div'> & VariantProps<typeof buttonGroupVariants>) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
@@ -34,51 +34,42 @@ function ButtonGroup({
|
||||
className={cn(buttonGroupVariants({ orientation }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ButtonGroupText({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
asChild?: boolean
|
||||
}: React.ComponentProps<'div'> & {
|
||||
asChild?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
const Comp = asChild ? Slot : 'div';
|
||||
|
||||
return (
|
||||
<Comp
|
||||
className={cn(
|
||||
"bg-muted flex items-center gap-2 rounded-md border px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ButtonGroupSeparator({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
orientation = 'vertical',
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="button-group-separator"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto",
|
||||
className
|
||||
)}
|
||||
className={cn('bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ButtonGroup,
|
||||
ButtonGroupSeparator,
|
||||
ButtonGroupText,
|
||||
buttonGroupVariants,
|
||||
);
|
||||
}
|
||||
|
||||
export { ButtonGroup, ButtonGroupSeparator, ButtonGroupText, buttonGroupVariants };
|
||||
|
||||
@@ -1,40 +1,38 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/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",
|
||||
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",
|
||||
'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 shadow-xs 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",
|
||||
'border bg-background shadow-xs 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",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
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',
|
||||
'icon-sm': 'size-8',
|
||||
'icon-lg': 'size-10',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
variant: 'default',
|
||||
size: 'default',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function Button({
|
||||
className,
|
||||
@@ -42,20 +40,13 @@ function Button({
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
}: React.ComponentProps<'button'> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
asChild?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return <Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props} />;
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
|
||||
export { Button, buttonVariants };
|
||||
|
||||
@@ -1,93 +1,56 @@
|
||||
import * as React from "react"
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
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 py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
className={cn('bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
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-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
'@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-title" className={cn('leading-none font-semibold', className)} {...props} />;
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-description" className={cn('text-muted-foreground text-sm', className)} {...props} />;
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
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
|
||||
)}
|
||||
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">) {
|
||||
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-content" className={cn('px-6', className)} {...props} />;
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
<div data-slot="card-footer" className={cn('flex items-center px-6 [.border-t]:pt-6', className)} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
|
||||
|
||||
@@ -1,34 +1,17 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
import * as CollapsiblePrimitive from '@radix-ui/react-collapsible';
|
||||
|
||||
function Collapsible({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
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 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}
|
||||
/>
|
||||
)
|
||||
function CollapsibleContent({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />;
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
|
||||
|
||||
@@ -1,44 +1,35 @@
|
||||
import * as React from "react"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { Command as CommandPrimitive } from 'cmdk';
|
||||
import { SearchIcon } from 'lucide-react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "./dialog"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './dialog';
|
||||
|
||||
function Command({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive>) {
|
||||
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
|
||||
'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...",
|
||||
title = 'Command Palette',
|
||||
description = 'Search for a command to run...',
|
||||
children,
|
||||
className,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string
|
||||
description?: string
|
||||
className?: string
|
||||
showCloseButton?: boolean
|
||||
title?: string;
|
||||
description?: string;
|
||||
className?: string;
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
@@ -46,127 +37,89 @@ function CommandDialog({
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogContent
|
||||
className={cn("overflow-hidden p-0", className)}
|
||||
showCloseButton={showCloseButton}
|
||||
>
|
||||
<DialogContent className={cn('overflow-hidden p-0', className)} showCloseButton={showCloseButton}>
|
||||
<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>) {
|
||||
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"
|
||||
>
|
||||
<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
|
||||
'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>) {
|
||||
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
|
||||
)}
|
||||
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 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>) {
|
||||
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
|
||||
'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>) {
|
||||
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)}
|
||||
className={cn('bg-border -mx-1 h-px', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CommandItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
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
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function CommandShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
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
|
||||
)}
|
||||
className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -179,5 +132,4 @@ export {
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import type { ConnectionState } from "../../src/acp/types";
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import type { ConnectionState } from '../../src/acp/types';
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
// Shared styles for connection state dots
|
||||
const connectionDotStyles: Record<ConnectionState, string> = {
|
||||
disconnected: "bg-gray-400",
|
||||
connecting: "bg-yellow-400 animate-pulse",
|
||||
connected: "bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)]",
|
||||
error: "bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.6)]",
|
||||
disconnected: 'bg-gray-400',
|
||||
connecting: 'bg-yellow-400 animate-pulse',
|
||||
connected: 'bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)]',
|
||||
error: 'bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.6)]',
|
||||
};
|
||||
|
||||
// Shared labels for connection states
|
||||
const connectionStateLabels: Record<ConnectionState, string> = {
|
||||
disconnected: "Disconnected",
|
||||
connecting: "Connecting...",
|
||||
connected: "Connected",
|
||||
error: "Error",
|
||||
disconnected: 'Disconnected',
|
||||
connecting: 'Connecting...',
|
||||
connected: 'Connected',
|
||||
error: 'Error',
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -28,33 +28,17 @@ export function getConnectionStateLabel(state: ConnectionState): string {
|
||||
* A small dot indicator for connection state
|
||||
* Used in status bars and headers
|
||||
*/
|
||||
export function StatusDot({
|
||||
state,
|
||||
className,
|
||||
}: {
|
||||
state: ConnectionState;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<span
|
||||
className={cn("w-2 h-2 rounded-full", connectionDotStyles[state], className)}
|
||||
/>
|
||||
);
|
||||
export function StatusDot({ state, className }: { state: ConnectionState; className?: string }) {
|
||||
return <span className={cn('w-2 h-2 rounded-full', connectionDotStyles[state], className)} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* A status indicator with dot and label
|
||||
* Used in cards and detailed views
|
||||
*/
|
||||
export function StatusIndicator({
|
||||
state,
|
||||
className,
|
||||
}: {
|
||||
state: ConnectionState;
|
||||
className?: string;
|
||||
}) {
|
||||
export function StatusIndicator({ state, className }: { state: ConnectionState; className?: string }) {
|
||||
return (
|
||||
<span className={cn("flex items-center gap-2 text-sm font-normal", className)}>
|
||||
<span className={cn('flex items-center gap-2 text-sm font-normal', className)}>
|
||||
<StatusDot state={state} />
|
||||
{state}
|
||||
</span>
|
||||
@@ -74,17 +58,12 @@ export function ConnectionStatusBar({
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("flex items-center gap-2", className)}>
|
||||
<div className={cn('flex items-center gap-2', className)}>
|
||||
<StatusDot state={state} />
|
||||
<span className="text-sm font-medium">
|
||||
{getConnectionStateLabel(state)}
|
||||
</span>
|
||||
{state === "connected" && displayUrl && (
|
||||
<span className="text-xs text-muted-foreground truncate max-w-[150px]">
|
||||
{displayUrl}
|
||||
</span>
|
||||
<span className="text-sm font-medium">{getConnectionStateLabel(state)}</span>
|
||||
{state === 'connected' && displayUrl && (
|
||||
<span className="text-xs text-muted-foreground truncate max-w-[150px]">{displayUrl}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,49 +1,38 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { XIcon } from 'lucide-react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
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 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 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 DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
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
|
||||
'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({
|
||||
@@ -52,7 +41,7 @@ function DialogContent({
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
@@ -60,8 +49,8 @@ function DialogContent({
|
||||
<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
|
||||
'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}
|
||||
>
|
||||
@@ -77,56 +66,47 @@ function DialogContent({
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
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)}
|
||||
className={cn('flex flex-col gap-2 text-center sm:text-left', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
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
|
||||
)}
|
||||
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>) {
|
||||
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)}
|
||||
className={cn('text-lg leading-none font-semibold', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
className={cn('text-muted-foreground text-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -140,5 +120,4 @@ export {
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
@@ -1,32 +1,19 @@
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
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 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 DropdownMenuTrigger({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
@@ -40,31 +27,27 @@ function DropdownMenuContent({
|
||||
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
|
||||
'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 DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
variant = 'default',
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
inset?: boolean;
|
||||
variant?: 'default' | 'destructive';
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
@@ -73,11 +56,11 @@ function DropdownMenuItem({
|
||||
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
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
@@ -91,7 +74,7 @@ function DropdownMenuCheckboxItem({
|
||||
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
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
@@ -103,18 +86,11 @@ function DropdownMenuCheckboxItem({
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function DropdownMenuRadioGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
@@ -127,7 +103,7 @@ function DropdownMenuRadioItem({
|
||||
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
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -138,7 +114,7 @@ function DropdownMenuRadioItem({
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
@@ -146,54 +122,40 @@ function DropdownMenuLabel({
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
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
|
||||
)}
|
||||
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>) {
|
||||
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)}
|
||||
className={cn('bg-border -mx-1 my-1 h-px', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
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
|
||||
)}
|
||||
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 DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
@@ -202,7 +164,7 @@ function DropdownMenuSubTrigger({
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
@@ -210,14 +172,14 @@ function DropdownMenuSubTrigger({
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 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
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
@@ -228,12 +190,12 @@ function DropdownMenuSubContent({
|
||||
<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
|
||||
'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 {
|
||||
@@ -252,5 +214,4 @@ export {
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
@@ -1,27 +1,21 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
|
||||
import * as React from 'react';
|
||||
import * as HoverCardPrimitive from '@radix-ui/react-hover-card';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function HoverCard({
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
|
||||
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
|
||||
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 HoverCardTrigger({ ...props }: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
|
||||
return <HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function HoverCardContent({
|
||||
className,
|
||||
align = "center",
|
||||
align = 'center',
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
|
||||
@@ -32,14 +26,13 @@ function HoverCardContent({
|
||||
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
|
||||
'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 }
|
||||
|
||||
export { HoverCard, HoverCardTrigger, HoverCardContent };
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
export * from "./badge"
|
||||
export * from "./connection-status"
|
||||
export * from "./button-group"
|
||||
export * from "./button"
|
||||
export * from "./card"
|
||||
export * from "./collapsible"
|
||||
export * from "./command"
|
||||
export * from "./dialog"
|
||||
export * from "./dropdown-menu"
|
||||
export * from "./hover-card"
|
||||
export * from "./input-group"
|
||||
export * from "./input"
|
||||
export * from "./label"
|
||||
export * from "./resizable"
|
||||
export * from "./scroll-area"
|
||||
export * from "./select"
|
||||
export * from "./separator"
|
||||
export * from "./tabs"
|
||||
export * from "./textarea"
|
||||
export * from "./theme-toggle"
|
||||
export * from "./tooltip"
|
||||
export * from "./popover"
|
||||
export * from './badge'
|
||||
export * from './connection-status'
|
||||
export * from './button-group'
|
||||
export * from './button'
|
||||
export * from './card'
|
||||
export * from './collapsible'
|
||||
export * from './command'
|
||||
export * from './dialog'
|
||||
export * from './dropdown-menu'
|
||||
export * from './hover-card'
|
||||
export * from './input-group'
|
||||
export * from './input'
|
||||
export * from './label'
|
||||
export * from './resizable'
|
||||
export * from './scroll-area'
|
||||
export * from './select'
|
||||
export * from './separator'
|
||||
export * from './tabs'
|
||||
export * from './textarea'
|
||||
export * from './theme-toggle'
|
||||
export * from './tooltip'
|
||||
export * from './popover'
|
||||
|
||||
@@ -1,39 +1,39 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { Button } from "./button"
|
||||
import { Input } from "./input"
|
||||
import { Textarea } from "./textarea"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
import { Button } from './button';
|
||||
import { Input } from './input';
|
||||
import { Textarea } from './textarea';
|
||||
|
||||
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
function InputGroup({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="input-group"
|
||||
role="group"
|
||||
className={cn(
|
||||
"group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none",
|
||||
"h-9 min-w-0 has-[>textarea]:h-auto",
|
||||
'group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none',
|
||||
'h-9 min-w-0 has-[>textarea]:h-auto',
|
||||
|
||||
// Variants based on alignment.
|
||||
"has-[>[data-align=inline-start]]:[&>input]:pl-2",
|
||||
"has-[>[data-align=inline-end]]:[&>input]:pr-2",
|
||||
"has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3",
|
||||
"has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3",
|
||||
'has-[>[data-align=inline-start]]:[&>input]:pl-2',
|
||||
'has-[>[data-align=inline-end]]:[&>input]:pr-2',
|
||||
'has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3',
|
||||
'has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3',
|
||||
|
||||
// Focus state.
|
||||
"has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]",
|
||||
'has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]',
|
||||
|
||||
// Error state.
|
||||
"has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",
|
||||
'has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40',
|
||||
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const inputGroupAddonVariants = cva(
|
||||
@@ -41,70 +41,62 @@ const inputGroupAddonVariants = cva(
|
||||
{
|
||||
variants: {
|
||||
align: {
|
||||
"inline-start":
|
||||
"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]",
|
||||
"inline-end":
|
||||
"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]",
|
||||
"block-start":
|
||||
"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5",
|
||||
"block-end":
|
||||
"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5",
|
||||
'inline-start': 'order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]',
|
||||
'inline-end': 'order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]',
|
||||
'block-start':
|
||||
'order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5',
|
||||
'block-end': 'order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
align: "inline-start",
|
||||
align: 'inline-start',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function InputGroupAddon({
|
||||
className,
|
||||
align = "inline-start",
|
||||
align = 'inline-start',
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
|
||||
}: React.ComponentProps<'div'> & VariantProps<typeof inputGroupAddonVariants>) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
data-slot="input-group-addon"
|
||||
data-align={align}
|
||||
className={cn(inputGroupAddonVariants({ align }), className)}
|
||||
onClick={(e) => {
|
||||
if ((e.target as HTMLElement).closest("button")) {
|
||||
return
|
||||
onClick={e => {
|
||||
if ((e.target as HTMLElement).closest('button')) {
|
||||
return;
|
||||
}
|
||||
e.currentTarget.parentElement?.querySelector("input")?.focus()
|
||||
e.currentTarget.parentElement?.querySelector('input')?.focus();
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const inputGroupButtonVariants = cva(
|
||||
"text-sm shadow-none flex gap-2 items-center",
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
xs: "h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",
|
||||
sm: "h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5",
|
||||
"icon-xs":
|
||||
"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0",
|
||||
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
|
||||
},
|
||||
const inputGroupButtonVariants = cva('text-sm shadow-none flex gap-2 items-center', {
|
||||
variants: {
|
||||
size: {
|
||||
xs: "h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",
|
||||
sm: 'h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5',
|
||||
'icon-xs': 'size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0',
|
||||
'icon-sm': 'size-8 p-0 has-[>svg]:p-0',
|
||||
},
|
||||
defaultVariants: {
|
||||
size: "xs",
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
defaultVariants: {
|
||||
size: 'xs',
|
||||
},
|
||||
});
|
||||
|
||||
function InputGroupButton({
|
||||
className,
|
||||
type = "button",
|
||||
variant = "ghost",
|
||||
size = "xs",
|
||||
type = 'button',
|
||||
variant = 'ghost',
|
||||
size = 'xs',
|
||||
...props
|
||||
}: Omit<React.ComponentProps<typeof Button>, "size"> &
|
||||
VariantProps<typeof inputGroupButtonVariants>) {
|
||||
}: Omit<React.ComponentProps<typeof Button>, 'size'> & VariantProps<typeof inputGroupButtonVariants>) {
|
||||
return (
|
||||
<Button
|
||||
type={type}
|
||||
@@ -113,59 +105,45 @@ function InputGroupButton({
|
||||
className={cn(inputGroupButtonVariants({ size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
|
||||
function InputGroupText({ className, ...props }: React.ComponentProps<'span'>) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"text-muted-foreground flex items-center gap-2 text-sm [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function InputGroupInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"input">) {
|
||||
function InputGroupInput({ className, ...props }: React.ComponentProps<'input'>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="input-group-control"
|
||||
className={cn(
|
||||
"flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",
|
||||
className
|
||||
'flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function InputGroupTextarea({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"textarea">) {
|
||||
function InputGroupTextarea({ className, ...props }: React.ComponentProps<'textarea'>) {
|
||||
return (
|
||||
<Textarea
|
||||
data-slot="input-group-control"
|
||||
className={cn(
|
||||
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",
|
||||
className
|
||||
'flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
InputGroup,
|
||||
InputGroupAddon,
|
||||
InputGroupButton,
|
||||
InputGroupText,
|
||||
InputGroupInput,
|
||||
InputGroupTextarea,
|
||||
);
|
||||
}
|
||||
|
||||
export { InputGroup, InputGroupAddon, InputGroupButton, InputGroupText, InputGroupInput, InputGroupTextarea };
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
import * as React from "react"
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
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 h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs 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
|
||||
'file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs 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 }
|
||||
|
||||
export { Input };
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import * as React from "react";
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from "../../src/lib/utils";
|
||||
import { cn } from '../../src/lib/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",
|
||||
'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}
|
||||
@@ -19,4 +19,3 @@ function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimiti
|
||||
}
|
||||
|
||||
export { Label };
|
||||
|
||||
|
||||
@@ -1,23 +1,19 @@
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
import * as React from 'react';
|
||||
import * as PopoverPrimitive from '@radix-ui/react-popover';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
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 PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
align = 'center',
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
@@ -28,20 +24,17 @@ function PopoverContent({
|
||||
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 rounded-md border p-4 shadow-md outline-none",
|
||||
className
|
||||
'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 rounded-md border p-4 shadow-md outline-none',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
|
||||
|
||||
@@ -1,28 +1,22 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import { GripVerticalIcon } from "lucide-react"
|
||||
import * as ResizablePrimitive from "react-resizable-panels"
|
||||
import { GripVerticalIcon } from 'lucide-react';
|
||||
import * as ResizablePrimitive from 'react-resizable-panels';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function ResizablePanelGroup({
|
||||
className,
|
||||
...props
|
||||
}: ResizablePrimitive.GroupProps) {
|
||||
function ResizablePanelGroup({ className, ...props }: ResizablePrimitive.GroupProps) {
|
||||
return (
|
||||
<ResizablePrimitive.Group
|
||||
data-slot="resizable-panel-group"
|
||||
className={cn(
|
||||
"flex h-full w-full aria-[orientation=vertical]:flex-col",
|
||||
className
|
||||
)}
|
||||
className={cn('flex h-full w-full aria-[orientation=vertical]:flex-col', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ResizablePanel({ ...props }: ResizablePrimitive.PanelProps) {
|
||||
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />
|
||||
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />;
|
||||
}
|
||||
|
||||
function ResizableHandle({
|
||||
@@ -30,14 +24,14 @@ function ResizableHandle({
|
||||
className,
|
||||
...props
|
||||
}: ResizablePrimitive.SeparatorProps & {
|
||||
withHandle?: boolean
|
||||
withHandle?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<ResizablePrimitive.Separator
|
||||
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 aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2 [&[aria-orientation=horizontal]>div]:rotate-90",
|
||||
className
|
||||
'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 aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2 [&[aria-orientation=horizontal]>div]:rotate-90',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -47,7 +41,7 @@ function ResizableHandle({
|
||||
</div>
|
||||
)}
|
||||
</ResizablePrimitive.Separator>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { ResizableHandle, ResizablePanel, ResizablePanelGroup }
|
||||
export { ResizableHandle, ResizablePanel, ResizablePanelGroup };
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
import * as React from "react"
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
||||
import * as React from 'react';
|
||||
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
function ScrollArea({ className, children, ...props }: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Root data-slot="scroll-area" className={cn('relative', className)} {...props}>
|
||||
{/*
|
||||
Workaround for Radix ScrollArea bug #926:
|
||||
The Viewport's inner div uses display:table which breaks text-overflow:ellipsis.
|
||||
@@ -29,12 +21,12 @@ function ScrollArea({
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
orientation = 'vertical',
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
@@ -42,12 +34,10 @@ function ScrollBar({
|
||||
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
|
||||
'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}
|
||||
>
|
||||
@@ -56,8 +46,7 @@ function ScrollBar({
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
|
||||
@@ -1,36 +1,30 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import * as SelectPrimitive from '@radix-ui/react-select';
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
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 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 SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
size = 'default',
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
size?: 'sm' | 'default';
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
@@ -38,7 +32,7 @@ function SelectTrigger({
|
||||
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-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs 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
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -47,14 +41,14 @@ function SelectTrigger({
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
align = "center",
|
||||
position = 'popper',
|
||||
align = 'center',
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
@@ -62,10 +56,10 @@ function SelectContent({
|
||||
<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
|
||||
'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}
|
||||
align={align}
|
||||
@@ -74,9 +68,9 @@ function SelectContent({
|
||||
<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"
|
||||
'p-1',
|
||||
position === 'popper' &&
|
||||
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
@@ -84,33 +78,26 @@ function SelectContent({
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
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)}
|
||||
className={cn('text-muted-foreground px-2 py-1.5 text-xs', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
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
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -121,38 +108,29 @@ function SelectItem({
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
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)}
|
||||
className={cn('bg-border pointer-events-none -mx-1 my-1 h-px', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
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
|
||||
)}
|
||||
className={cn('flex cursor-default items-center justify-center py-1', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
@@ -162,15 +140,12 @@ function SelectScrollDownButton({
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
className={cn('flex cursor-default items-center justify-center py-1', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -184,5 +159,4 @@ export {
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
import * as React from 'react';
|
||||
import * as SeparatorPrimitive from '@radix-ui/react-separator';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
orientation = 'horizontal',
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
@@ -15,13 +15,12 @@ function Separator({
|
||||
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
|
||||
'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 }
|
||||
|
||||
export { Separator };
|
||||
|
||||
@@ -1,49 +1,41 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Tabs as TabsPrimitive } from "radix-ui"
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { Tabs as TabsPrimitive } from 'radix-ui';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
function Tabs({ className, orientation = 'horizontal', ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
data-orientation={orientation}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
|
||||
className
|
||||
)}
|
||||
className={cn('group/tabs flex gap-2 data-[orientation=horizontal]:flex-col', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const tabsListVariants = cva(
|
||||
"rounded-lg p-[3px] group-data-[orientation=horizontal]/tabs:h-9 data-[variant=line]:rounded-none group/tabs-list text-muted-foreground inline-flex w-fit items-center justify-center group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col",
|
||||
'rounded-lg p-[3px] group-data-[orientation=horizontal]/tabs:h-9 data-[variant=line]:rounded-none group/tabs-list text-muted-foreground inline-flex w-fit items-center justify-center group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-muted",
|
||||
line: "gap-1 bg-transparent",
|
||||
default: 'bg-muted',
|
||||
line: 'gap-1 bg-transparent',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
variant = "default",
|
||||
variant = 'default',
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List> &
|
||||
VariantProps<typeof tabsListVariants>) {
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List> & VariantProps<typeof tabsListVariants>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
@@ -51,26 +43,23 @@ function TabsList({
|
||||
className={cn(tabsListVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring text-foreground/60 hover:text-foreground dark:text-muted-foreground dark:hover:text-foreground relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
|
||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 data-[state=active]:text-foreground",
|
||||
"after:bg-foreground after:absolute after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
|
||||
className
|
||||
'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent',
|
||||
'data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 data-[state=active]:text-foreground',
|
||||
'after:bg-foreground after:absolute after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
@@ -85,14 +74,14 @@ function TabsContent({
|
||||
data-slot="tabs-content"
|
||||
forceMount={forceMount}
|
||||
className={cn(
|
||||
"flex-1 outline-none",
|
||||
'flex-1 outline-none',
|
||||
// When forceMount is used, hide inactive tabs
|
||||
forceMount && "data-[state=inactive]:hidden",
|
||||
className
|
||||
forceMount && 'data-[state=inactive]:hidden',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import * as React from "react"
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"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-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
'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-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
|
||||
export { Textarea };
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import { Moon, Sun, Monitor } from "lucide-react";
|
||||
import { useTheme, type Theme } from "../../src/lib/theme";
|
||||
import { Button } from "./button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "./dropdown-menu";
|
||||
import { Moon, Sun, Monitor } from 'lucide-react';
|
||||
import { useTheme, type Theme } from '../../src/lib/theme';
|
||||
import { Button } from './button';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from './dropdown-menu';
|
||||
|
||||
const themeOptions: { value: Theme; label: string; icon: React.ReactNode }[] = [
|
||||
{ value: "light", label: "Light", icon: <Sun className="h-4 w-4" /> },
|
||||
{ value: "dark", label: "Dark", icon: <Moon className="h-4 w-4" /> },
|
||||
{ value: "system", label: "System", icon: <Monitor className="h-4 w-4" /> },
|
||||
{ value: 'light', label: 'Light', icon: <Sun className="h-4 w-4" /> },
|
||||
{ value: 'dark', label: 'Dark', icon: <Moon className="h-4 w-4" /> },
|
||||
{ value: 'system', label: 'System', icon: <Monitor className="h-4 w-4" /> },
|
||||
];
|
||||
|
||||
export function ThemeToggle() {
|
||||
@@ -21,20 +16,16 @@ export function ThemeToggle() {
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
{resolvedTheme === "dark" ? (
|
||||
<Moon className="h-4 w-4" />
|
||||
) : (
|
||||
<Sun className="h-4 w-4" />
|
||||
)}
|
||||
{resolvedTheme === 'dark' ? <Moon className="h-4 w-4" /> : <Sun className="h-4 w-4" />}
|
||||
<span className="sr-only">Toggle theme</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{themeOptions.map((option) => (
|
||||
{themeOptions.map(option => (
|
||||
<DropdownMenuItem
|
||||
key={option.value}
|
||||
onClick={() => setTheme(option.value)}
|
||||
className={theme === option.value ? "bg-accent" : ""}
|
||||
className={theme === option.value ? 'bg-accent' : ''}
|
||||
>
|
||||
{option.icon}
|
||||
<span className="ml-2">{option.label}</span>
|
||||
@@ -44,4 +35,3 @@ export function ThemeToggle() {
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,35 +1,22 @@
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
import * as React from 'react';
|
||||
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
|
||||
|
||||
import { cn } from "../../src/lib/utils"
|
||||
import { cn } from '../../src/lib/utils';
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
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>) {
|
||||
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 TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
@@ -44,8 +31,8 @@ function TooltipContent({
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-foreground text-background 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
|
||||
'bg-foreground text-background 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}
|
||||
>
|
||||
@@ -53,8 +40,7 @@ function TooltipContent({
|
||||
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||
|
||||
Reference in New Issue
Block a user