mirror of
https://github.com/dograh-hq/dograh.git
synced 2026-06-22 08:38:13 +02:00
Initial Commit 🚀 🚀
This commit is contained in:
commit
4f2a629340
444 changed files with 76863 additions and 0 deletions
115
ui/src/components/DailyUsageTable.tsx
Normal file
115
ui/src/components/DailyUsageTable.tsx
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import type { DailyUsageBreakdownResponse } from '@/client/types.gen';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
|
||||
interface DailyUsageTableProps {
|
||||
data: DailyUsageBreakdownResponse | null;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function DailyUsageTable({ data, isLoading }: DailyUsageTableProps) {
|
||||
// Format date for display
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Daily Usage Breakdown</CardTitle>
|
||||
<CardDescription>Last 7 days of usage</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="animate-pulse space-y-3">
|
||||
{[...Array(7)].map((_, i) => (
|
||||
<div key={i} className="h-12 bg-gray-200 rounded"></div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data || !data.breakdown || data.breakdown.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Daily Usage Breakdown</CardTitle>
|
||||
<CardDescription>Last 7 days of usage</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-center py-8 text-gray-500">No usage data available</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Daily Usage Breakdown</CardTitle>
|
||||
<CardDescription>Last 7 days of usage</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="bg-white border rounded-lg overflow-hidden shadow-sm">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="bg-gray-50">
|
||||
<TableHead className="font-semibold">Date</TableHead>
|
||||
<TableHead className="font-semibold text-right">Usage (minutes)</TableHead>
|
||||
<TableHead className="font-semibold text-right">Cost (USD)</TableHead>
|
||||
<TableHead className="font-semibold text-right">Calls</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.breakdown.map((day) => (
|
||||
<TableRow key={day.date}>
|
||||
<TableCell className="font-medium">
|
||||
{formatDate(day.date)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{day.minutes.toFixed(1)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium">
|
||||
${(day.cost_usd || 0).toFixed(2)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{day.call_count}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow className="bg-gray-50 font-semibold">
|
||||
<TableCell>Total</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{data.total_minutes.toFixed(1)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
${(data.total_cost_usd || 0).toFixed(2)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{data.breakdown.reduce((sum, day) => sum + day.call_count, 0)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
158
ui/src/components/MediaPreviewDialog.tsx
Normal file
158
ui/src/components/MediaPreviewDialog.tsx
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
'use client';
|
||||
|
||||
import { FileText, Loader2, Video } from 'lucide-react';
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { downloadFile, getSignedUrl } from '@/lib/files';
|
||||
|
||||
interface MediaPreviewDialogProps {
|
||||
accessToken: string | null;
|
||||
}
|
||||
|
||||
export function MediaPreviewDialog({ accessToken }: MediaPreviewDialogProps) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [mediaType, setMediaType] = useState<'audio' | 'transcript' | null>(null);
|
||||
const [mediaSignedUrl, setMediaSignedUrl] = useState<string | null>(null);
|
||||
const [selectedRunId, setSelectedRunId] = useState<number | null>(null);
|
||||
const [mediaDownloadKey, setMediaDownloadKey] = useState<string | null>(null);
|
||||
const [mediaLoading, setMediaLoading] = useState(false);
|
||||
|
||||
const openAudioModal = useCallback(
|
||||
async (fileKey: string | null, runId: number) => {
|
||||
if (!fileKey || !accessToken) return;
|
||||
setMediaLoading(true);
|
||||
const signed = await getSignedUrl(fileKey, accessToken);
|
||||
if (signed) {
|
||||
setMediaType('audio');
|
||||
setMediaSignedUrl(signed);
|
||||
setMediaDownloadKey(fileKey);
|
||||
setSelectedRunId(runId);
|
||||
setIsOpen(true);
|
||||
}
|
||||
setMediaLoading(false);
|
||||
},
|
||||
[accessToken],
|
||||
);
|
||||
|
||||
const openTranscriptModal = useCallback(
|
||||
async (fileKey: string | null, runId: number) => {
|
||||
if (!fileKey || !accessToken) return;
|
||||
setMediaLoading(true);
|
||||
const signed = await getSignedUrl(fileKey, accessToken, true);
|
||||
if (signed) {
|
||||
setMediaType('transcript');
|
||||
setMediaSignedUrl(signed);
|
||||
setMediaDownloadKey(fileKey);
|
||||
setSelectedRunId(runId);
|
||||
setIsOpen(true);
|
||||
}
|
||||
setMediaLoading(false);
|
||||
},
|
||||
[accessToken],
|
||||
);
|
||||
|
||||
return {
|
||||
openAudioModal,
|
||||
openTranscriptModal,
|
||||
dialog: (
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DialogContent className="sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{mediaType === 'audio' ? 'Recording Preview' : 'Transcript Preview'}
|
||||
{selectedRunId && ` - Run #${selectedRunId}`}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{mediaLoading && (
|
||||
<div className="flex items-center justify-center py-8 space-x-2">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
<span>Loading...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!mediaLoading && mediaType === 'audio' && mediaSignedUrl && (
|
||||
<audio src={mediaSignedUrl} controls autoPlay className="w-full mt-4" />
|
||||
)}
|
||||
|
||||
{!mediaLoading && mediaType === 'transcript' && mediaSignedUrl && (
|
||||
<iframe
|
||||
src={mediaSignedUrl}
|
||||
title="Transcript"
|
||||
className="w-full h-[60vh] border rounded-md mt-4"
|
||||
/>
|
||||
)}
|
||||
|
||||
<DialogFooter className="pt-4">
|
||||
<DialogClose asChild>
|
||||
<Button variant="secondary">Close</Button>
|
||||
</DialogClose>
|
||||
{mediaDownloadKey && accessToken && (
|
||||
<Button onClick={() => downloadFile(mediaDownloadKey, accessToken)}>Download</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
interface MediaPreviewButtonsProps {
|
||||
recordingUrl: string | null | undefined;
|
||||
transcriptUrl: string | null | undefined;
|
||||
runId: number;
|
||||
onOpenAudio: (fileKey: string | null, runId: number) => void;
|
||||
onOpenTranscript: (fileKey: string | null, runId: number) => void;
|
||||
onSelect?: (runId: number) => void;
|
||||
}
|
||||
|
||||
export function MediaPreviewButtons({
|
||||
recordingUrl,
|
||||
transcriptUrl,
|
||||
runId,
|
||||
onOpenAudio,
|
||||
onOpenTranscript,
|
||||
onSelect,
|
||||
}: MediaPreviewButtonsProps) {
|
||||
const handleOpenAudio = () => {
|
||||
onSelect?.(runId);
|
||||
onOpenAudio(recordingUrl ?? null, runId);
|
||||
};
|
||||
|
||||
const handleOpenTranscript = () => {
|
||||
onSelect?.(runId);
|
||||
onOpenTranscript(transcriptUrl ?? null, runId);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex space-x-2">
|
||||
{recordingUrl && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleOpenAudio}
|
||||
>
|
||||
<Video className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{transcriptUrl && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleOpenTranscript}
|
||||
>
|
||||
<FileText className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
46
ui/src/components/PostHogIdentify.tsx
Normal file
46
ui/src/components/PostHogIdentify.tsx
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
'use client';
|
||||
|
||||
import posthog from 'posthog-js';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import { useAuth } from '@/lib/auth';
|
||||
|
||||
/**
|
||||
* PostHogIdentify
|
||||
* ---------------
|
||||
* A tiny client-side component that calls `posthog.identify` once the
|
||||
* authenticated user object is available. It also resets PostHog when the
|
||||
* user logs out or switches accounts.
|
||||
*
|
||||
* This component is intended to be rendered high in the React tree (e.g. in
|
||||
* `app/layout.tsx`) so that PostHog always knows which user is active for the
|
||||
* current browser session.
|
||||
*/
|
||||
export default function PostHogIdentify() {
|
||||
const { user } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
// Only run if PostHog is enabled
|
||||
if (process.env.NEXT_PUBLIC_ENABLE_POSTHOG !== 'true') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (user) {
|
||||
try {
|
||||
// Identify the user in PostHog with their unique id and useful traits
|
||||
posthog.identify(String(user.id ?? ''));
|
||||
} catch (err) {
|
||||
// Silently ignore identification errors so they don't break the app
|
||||
|
||||
console.warn('Failed to identify user in PostHog', err);
|
||||
}
|
||||
} else {
|
||||
// If the user logs out, clear the PostHog identity so future anonymous
|
||||
// interactions aren't associated with the previous account.
|
||||
posthog.reset();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// This component does not render anything
|
||||
return null;
|
||||
}
|
||||
340
ui/src/components/ServiceConfiguration.tsx
Normal file
340
ui/src/components/ServiceConfiguration.tsx
Normal file
|
|
@ -0,0 +1,340 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { getDefaultConfigurationsApiV1UserConfigurationsDefaultsGet } from '@/client/sdk.gen';
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { useUserConfig } from "@/context/UserConfigContext";
|
||||
|
||||
type ServiceSegment = "llm" | "tts" | "stt";
|
||||
|
||||
interface SchemaProperty {
|
||||
type?: string;
|
||||
default?: string | number | boolean;
|
||||
enum?: string[];
|
||||
$ref?: string;
|
||||
description?: string;
|
||||
format?: string;
|
||||
}
|
||||
|
||||
interface ProviderSchema {
|
||||
properties: Record<string, SchemaProperty>;
|
||||
required?: string[];
|
||||
$defs?: Record<string, SchemaProperty>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
interface FormValues {
|
||||
[key: string]: string | number | boolean;
|
||||
}
|
||||
|
||||
export default function ServiceConfiguration() {
|
||||
const [apiError, setApiError] = useState<string | null>(null);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const { userConfig, saveUserConfig } = useUserConfig();
|
||||
const [schemas, setSchemas] = useState<Record<ServiceSegment, Record<string, ProviderSchema>>>({
|
||||
llm: {},
|
||||
tts: {},
|
||||
stt: {}
|
||||
});
|
||||
const [serviceProviders, setServiceProviders] = useState<Record<ServiceSegment, string>>({
|
||||
llm: "",
|
||||
tts: "",
|
||||
stt: ""
|
||||
});
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
reset,
|
||||
getValues,
|
||||
setValue,
|
||||
watch
|
||||
} = useForm();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchConfigurations = async () => {
|
||||
const response = await getDefaultConfigurationsApiV1UserConfigurationsDefaultsGet();
|
||||
if (response.data) {
|
||||
setSchemas({
|
||||
llm: response.data.llm as Record<string, ProviderSchema>,
|
||||
tts: response.data.tts as Record<string, ProviderSchema>,
|
||||
stt: response.data.stt as Record<string, ProviderSchema>
|
||||
});
|
||||
} else {
|
||||
console.error("Failed to fetch configurations");
|
||||
return;
|
||||
}
|
||||
|
||||
const defaultValues: Record<string, string | number | boolean> = {};
|
||||
const selectedProviders: Record<ServiceSegment, string> = {
|
||||
llm: response.data.default_providers.llm,
|
||||
tts: response.data.default_providers.tts,
|
||||
stt: response.data.default_providers.stt
|
||||
};
|
||||
|
||||
const setServicePropertyValues = (service: ServiceSegment) => {
|
||||
/*
|
||||
sets service properties like api_key, model etc. from default configurations
|
||||
if not present in user configurations
|
||||
|
||||
service - llm/ tts/ stt
|
||||
|
||||
|
||||
userConfig['llm'] = {
|
||||
provider: 'openai',
|
||||
api_key: 'sk-...'
|
||||
}
|
||||
|
||||
response.data.llm = {
|
||||
openai: {
|
||||
properties: {
|
||||
provider: 'openai'
|
||||
api_key: 'sk-...'
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
if (userConfig?.[service]?.provider) {
|
||||
Object.entries(userConfig?.[service]).forEach(([field, value]) => {
|
||||
if (field !== "provider") {
|
||||
defaultValues[`${service}_${field}`] = value;
|
||||
}
|
||||
});
|
||||
selectedProviders[service] = userConfig?.[service]?.provider as string;
|
||||
} else {
|
||||
// response.data['service'] will all providers for the given service
|
||||
// selectedProviders[service] will have the provider name
|
||||
const properties = response.data[service]?.[selectedProviders[service]]?.properties as Record<string, SchemaProperty>;
|
||||
if (properties) {
|
||||
Object.entries(properties).forEach(([field, schema]) => {
|
||||
if (field !== "provider" && schema.default) {
|
||||
defaultValues[`${service}_${field}`] = schema.default;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setServicePropertyValues("llm");
|
||||
setServicePropertyValues("tts");
|
||||
setServicePropertyValues("stt");
|
||||
|
||||
setServiceProviders(selectedProviders);
|
||||
|
||||
reset(defaultValues);
|
||||
};
|
||||
fetchConfigurations();
|
||||
}, [reset, userConfig]);
|
||||
|
||||
const handleProviderChange = (service: ServiceSegment, providerName: string) => {
|
||||
/*
|
||||
service can be llm/ tts/ stt
|
||||
providerName is openAI/ Deepgram etc.
|
||||
*/
|
||||
if (!providerName) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentValues = getValues();
|
||||
const preservedValues: Record<string, string | number | boolean> = {};
|
||||
|
||||
// Preserve values from other services
|
||||
Object.keys(currentValues).forEach(key => {
|
||||
if (!key.startsWith(`${service}_`)) {
|
||||
preservedValues[key] = currentValues[key];
|
||||
}
|
||||
});
|
||||
|
||||
// Set default values from schema
|
||||
if (schemas?.[service]?.[providerName]) {
|
||||
const providerSchema = schemas[service][providerName];
|
||||
Object.entries(providerSchema.properties).forEach(([field, schema]: [string, SchemaProperty]) => {
|
||||
if (field !== "provider" && schema.default !== undefined) {
|
||||
preservedValues[`${service}_${field}`] = schema.default;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
preservedValues[`${service}_provider`] = providerName;
|
||||
reset(preservedValues);
|
||||
setServiceProviders(prev => ({ ...prev, [service]: providerName }));
|
||||
}
|
||||
|
||||
|
||||
const onSubmit = async (data: FormValues) => {
|
||||
/*
|
||||
data contains form values like llm_api_key: "sk...", llm_model: "gpt-4o" etc.
|
||||
extract the values in relevant form
|
||||
*/
|
||||
setApiError(null);
|
||||
setIsSaving(true);
|
||||
|
||||
const userConfig = {
|
||||
llm: {
|
||||
provider: serviceProviders.llm,
|
||||
api_key: data.llm_api_key as string,
|
||||
model: data.llm_model as string
|
||||
},
|
||||
tts: {
|
||||
provider: serviceProviders.tts,
|
||||
api_key: data.tts_api_key as string
|
||||
},
|
||||
stt: {
|
||||
provider: serviceProviders.stt,
|
||||
api_key: data.stt_api_key as string
|
||||
}
|
||||
};
|
||||
|
||||
// Add any extra properties in the payload
|
||||
Object.entries(data).forEach(([property, value]) => {
|
||||
const parts = property.split('_');
|
||||
const service = parts[0] as ServiceSegment;
|
||||
const field = parts.slice(1).join('_'); // Join all parts after the service name
|
||||
|
||||
if (userConfig[service] && !(field in userConfig[service])) {
|
||||
(userConfig[service] as Record<string, string>)[field] = value as string;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
await saveUserConfig({
|
||||
llm: userConfig.llm,
|
||||
tts: userConfig.tts,
|
||||
stt: userConfig.stt
|
||||
});
|
||||
setApiError(null);
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
setApiError(error.message);
|
||||
} else {
|
||||
setApiError('An unknown error occurred');
|
||||
}
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const renderServiceSegmentFields = (service: ServiceSegment) => {
|
||||
// Segment is segments like llm, tts and stt
|
||||
const currentProvider = serviceProviders[service];
|
||||
const providerSchema = schemas?.[service]?.[currentProvider];
|
||||
const availableProviders = schemas?.[service] ? Object.keys(schemas[service]) : [];
|
||||
|
||||
return (
|
||||
<Card className="mb-6">
|
||||
<CardHeader>
|
||||
<CardTitle>{service.toUpperCase()} Configuration</CardTitle>
|
||||
<CardDescription>
|
||||
Configure your {service.toUpperCase()} service
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Provider</Label>
|
||||
<Select
|
||||
value={currentProvider}
|
||||
onValueChange={(providerName) => {
|
||||
handleProviderChange(service, providerName);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={`Select ${service.toUpperCase()} provider`} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableProviders.map((provider) => (
|
||||
<SelectItem key={provider} value={provider}>
|
||||
{provider}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{currentProvider && providerSchema && (
|
||||
<div className="space-y-4">
|
||||
{Object.entries(providerSchema.properties).map(([field, schema]: [string, SchemaProperty]) => {
|
||||
// Handle $ref fields by getting the actual schema from $defs
|
||||
const actualSchema = schema.$ref && providerSchema.$defs
|
||||
? providerSchema.$defs[schema.$ref.split('/').pop() || '']
|
||||
: schema;
|
||||
|
||||
// Skip provider field as it's handled separately
|
||||
return field !== "provider" && (
|
||||
<div key={`${service}_${field}_${currentProvider}`} className="space-y-2">
|
||||
<Label>{field}</Label>
|
||||
{actualSchema?.enum ? (
|
||||
<Select
|
||||
value={watch(`${service}_${field}`) as string || ""}
|
||||
onValueChange={(value) => {
|
||||
setValue(`${service}_${field}`, value, { shouldDirty: true });
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={`Select ${field}`} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{actualSchema.enum.map((value: string) => (
|
||||
<SelectItem key={value} value={value}>
|
||||
{value}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<Input
|
||||
type={actualSchema?.type === "number" ? "number" : "text"}
|
||||
{...(actualSchema?.type === "number" && { step: "any" })}
|
||||
placeholder={`Enter ${field}`}
|
||||
{...register(`${service}_${field}`, {
|
||||
required: providerSchema.required?.includes(field),
|
||||
valueAsNumber: actualSchema?.type === "number"
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
{errors[`${service}_${field}`] && (
|
||||
<p className="text-sm text-red-500">
|
||||
{typeof errors[`${service}_${field}`]?.message === 'string'
|
||||
? String(errors[`${service}_${field}`]?.message)
|
||||
: "This field is required"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-4xl mx-auto py-8">
|
||||
<h1 className="text-2xl font-bold mb-6">Service Configuration</h1>
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
||||
{renderServiceSegmentFields("llm")}
|
||||
{renderServiceSegmentFields("tts")}
|
||||
{renderServiceSegmentFields("stt")}
|
||||
|
||||
{apiError && <p className="text-red-500">{apiError}</p>}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isSaving}>
|
||||
{isSaving ? "Saving..." : "Save Configuration"}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
27
ui/src/components/SignInClient.tsx
Normal file
27
ui/src/components/SignInClient.tsx
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
"use client";
|
||||
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
// Only load Stack's SignIn component when Stack provider is active
|
||||
const SignIn = dynamic(
|
||||
() => import('@stackframe/stack').then(mod => ({ default: mod.SignIn })),
|
||||
{ ssr: false, loading: () => <Loader2 className="w-5 h-5 animate-spin text-gray-600" /> }
|
||||
);
|
||||
|
||||
export default function SignInClient() {
|
||||
const authProvider = process.env.NEXT_PUBLIC_AUTH_PROVIDER || 'stack';
|
||||
|
||||
if (authProvider !== 'stack') {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold mb-4">Local Authentication</h1>
|
||||
<p className="text-gray-600">Local authentication is enabled. No sign-in required.</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <SignIn />;
|
||||
}
|
||||
9
ui/src/components/SpinLoader.tsx
Normal file
9
ui/src/components/SpinLoader.tsx
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { Loader2 } from "lucide-react";
|
||||
|
||||
export default function SpinLoader(){
|
||||
return(
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<Loader2 className="w-15 h-15 animate-spin" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
29
ui/src/components/ThemeSwitcher.tsx
Normal file
29
ui/src/components/ThemeSwitcher.tsx
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
"use client";
|
||||
|
||||
import { Moon,Sun } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function ThemeToggle() {
|
||||
const [theme, setTheme] = useState("light");
|
||||
|
||||
useEffect(() => {
|
||||
const storedTheme = localStorage.getItem("theme") || "light";
|
||||
setTheme(storedTheme);
|
||||
document.documentElement.classList.toggle("dark", storedTheme === "dark");
|
||||
}, []);
|
||||
|
||||
const toggleTheme = () => {
|
||||
const newTheme = theme === "light" ? "dark" : "light";
|
||||
setTheme(newTheme);
|
||||
localStorage.setItem("theme", newTheme);
|
||||
document.documentElement.classList.toggle("dark", newTheme === "dark");
|
||||
};
|
||||
|
||||
return (
|
||||
<Button variant="outline" className="absolute top-4 right-4" onClick={toggleTheme}>
|
||||
{theme === "light" ? <Moon className="h-5 w-5" /> : <Sun className="h-5 w-5" />}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
169
ui/src/components/filters/DateRangeFilter.tsx
Normal file
169
ui/src/components/filters/DateRangeFilter.tsx
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
import { CalendarIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Calendar } from "@/components/ui/calendar";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { getDatePresetValue } from "@/lib/filters";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { DateRangeValue } from "@/types/filters";
|
||||
|
||||
interface DateRangeFilterProps {
|
||||
value: DateRangeValue;
|
||||
onChange: (value: DateRangeValue) => void;
|
||||
error?: string;
|
||||
presets?: string[];
|
||||
}
|
||||
|
||||
export const DateRangeFilter: React.FC<DateRangeFilterProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
presets = [],
|
||||
}) => {
|
||||
const [isFromOpen, setIsFromOpen] = useState(false);
|
||||
const [isToOpen, setIsToOpen] = useState(false);
|
||||
|
||||
const formatDate = (date: Date | null) => {
|
||||
if (!date) return "Select date";
|
||||
return date.toLocaleDateString() + " " + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
};
|
||||
|
||||
const handlePresetClick = (preset: string) => {
|
||||
const presetValue = getDatePresetValue(preset);
|
||||
onChange(presetValue);
|
||||
};
|
||||
|
||||
const handleFromChange = (date: Date | undefined) => {
|
||||
if (date) {
|
||||
// Keep the time from the existing date if available
|
||||
if (value.from) {
|
||||
date.setHours(value.from.getHours(), value.from.getMinutes());
|
||||
}
|
||||
onChange({ ...value, from: date });
|
||||
}
|
||||
setIsFromOpen(false);
|
||||
};
|
||||
|
||||
const handleToChange = (date: Date | undefined) => {
|
||||
if (date) {
|
||||
// Set to end of day by default
|
||||
date.setHours(23, 59, 59, 999);
|
||||
onChange({ ...value, to: date });
|
||||
}
|
||||
setIsToOpen(false);
|
||||
};
|
||||
|
||||
const handleTimeChange = (type: 'from' | 'to', timeString: string) => {
|
||||
const [hours, minutes] = timeString.split(':').map(Number);
|
||||
const date = type === 'from' ? value.from : value.to;
|
||||
if (date) {
|
||||
const newDate = new Date(date);
|
||||
newDate.setHours(hours, minutes);
|
||||
onChange({ ...value, [type]: newDate });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{presets.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{presets.map((preset) => (
|
||||
<Button
|
||||
key={preset}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePresetClick(preset)}
|
||||
>
|
||||
{preset.charAt(0).toUpperCase() + preset.slice(1).replace(/(\d+)/, ' $1 ')}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-2">
|
||||
<Label>From</Label>
|
||||
<Popover open={isFromOpen} onOpenChange={setIsFromOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
"w-full justify-start text-left font-normal",
|
||||
!value.from && "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{formatDate(value.from)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={value.from || undefined}
|
||||
onSelect={handleFromChange}
|
||||
initialFocus
|
||||
/>
|
||||
{value.from && (
|
||||
<div className="p-3 border-t">
|
||||
<Label htmlFor="from-time">Time</Label>
|
||||
<input
|
||||
id="from-time"
|
||||
type="time"
|
||||
className="w-full mt-1 px-3 py-2 border rounded-md"
|
||||
value={value.from.toTimeString().slice(0, 5)}
|
||||
onChange={(e) => handleTimeChange('from', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>To</Label>
|
||||
<Popover open={isToOpen} onOpenChange={setIsToOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
"w-full justify-start text-left font-normal",
|
||||
!value.to && "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{formatDate(value.to)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={value.to || undefined}
|
||||
onSelect={handleToChange}
|
||||
initialFocus
|
||||
disabled={(date) => value.from ? date < value.from : false}
|
||||
/>
|
||||
{value.to && (
|
||||
<div className="p-3 border-t">
|
||||
<Label htmlFor="to-time">Time</Label>
|
||||
<input
|
||||
id="to-time"
|
||||
type="time"
|
||||
className="w-full mt-1 px-3 py-2 border rounded-md"
|
||||
value={value.to.toTimeString().slice(0, 5)}
|
||||
onChange={(e) => handleTimeChange('to', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500 mt-1">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
455
ui/src/components/filters/FilterBuilder.tsx
Normal file
455
ui/src/components/filters/FilterBuilder.tsx
Normal file
|
|
@ -0,0 +1,455 @@
|
|||
import { AlertCircle, Calendar, CheckSquare, Hash, Radio, RefreshCw, Tag, X } from "lucide-react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { DateRangeFilter } from "@/components/filters/DateRangeFilter";
|
||||
import { MultiSelectFilter } from "@/components/filters/MultiSelectFilter";
|
||||
import { NumberFilter } from "@/components/filters/NumberFilter";
|
||||
import { NumberRangeFilter } from "@/components/filters/NumberRangeFilter";
|
||||
import { RadioFilter } from "@/components/filters/RadioFilter";
|
||||
import { TagInputFilter } from "@/components/filters/TagInputFilter";
|
||||
import { TextFilter } from "@/components/filters/TextFilter";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { formatDateRange, formatNumberRange, getDefaultValue, validateFilter } from "@/lib/filters";
|
||||
import { ActiveFilter, DateRangeValue, FilterAttribute, FilterTemplate, filterTemplates, FilterValue, MultiSelectValue, NumberRangeValue, NumberValue, RadioValue, TextValue } from "@/types/filters";
|
||||
|
||||
interface FilterBuilderProps {
|
||||
availableAttributes: FilterAttribute[];
|
||||
activeFilters: ActiveFilter[];
|
||||
onFiltersChange: (filters: ActiveFilter[]) => void;
|
||||
onApplyFilters: () => void;
|
||||
onClearFilters?: () => void;
|
||||
isExecuting?: boolean;
|
||||
autoRefresh?: boolean;
|
||||
onAutoRefreshChange?: (enabled: boolean) => void;
|
||||
}
|
||||
|
||||
export const FilterBuilder: React.FC<FilterBuilderProps> = ({
|
||||
availableAttributes,
|
||||
activeFilters,
|
||||
onFiltersChange,
|
||||
onApplyFilters,
|
||||
onClearFilters,
|
||||
isExecuting = false,
|
||||
autoRefresh = false,
|
||||
onAutoRefreshChange,
|
||||
}) => {
|
||||
const [selectedAttribute, setSelectedAttribute] = useState<string>("");
|
||||
const [expandedFilters, setExpandedFilters] = useState<Set<number>>(new Set());
|
||||
|
||||
// Auto-expand new filters
|
||||
useEffect(() => {
|
||||
if (activeFilters.length > 0) {
|
||||
setExpandedFilters(new Set([activeFilters.length - 1]));
|
||||
}
|
||||
}, [activeFilters.length]);
|
||||
|
||||
// Handle Command+Enter (Mac) or Ctrl+Enter (Windows/Linux) to apply filters
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
const isMac = navigator.userAgent.toUpperCase().indexOf('MAC') >= 0;
|
||||
const isModifierPressed = isMac ? event.metaKey : event.ctrlKey;
|
||||
|
||||
if (isModifierPressed && event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
const allFiltersValid = activeFilters.every(f => f.isValid);
|
||||
if (activeFilters.length > 0 && allFiltersValid && !isExecuting) {
|
||||
onApplyFilters();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [activeFilters, isExecuting, onApplyFilters]);
|
||||
|
||||
const addFilter = useCallback((attributeId: string) => {
|
||||
const attribute = availableAttributes.find(attr => attr.id === attributeId);
|
||||
if (!attribute) return;
|
||||
|
||||
const defaultValue = getDefaultValue(attribute.type);
|
||||
const newFilter: ActiveFilter = {
|
||||
attribute,
|
||||
value: defaultValue,
|
||||
isValid: false,
|
||||
};
|
||||
|
||||
onFiltersChange([...activeFilters, newFilter]);
|
||||
setSelectedAttribute("");
|
||||
}, [availableAttributes, activeFilters, onFiltersChange]);
|
||||
|
||||
const updateFilter = useCallback((index: number, value: FilterValue) => {
|
||||
const newFilters = [...activeFilters];
|
||||
newFilters[index].value = value;
|
||||
newFilters[index].isValid = validateFilter(newFilters[index]) === null;
|
||||
onFiltersChange(newFilters);
|
||||
}, [activeFilters, onFiltersChange]);
|
||||
|
||||
const removeFilter = useCallback((index: number) => {
|
||||
onFiltersChange(activeFilters.filter((_, i) => i !== index));
|
||||
setExpandedFilters(prev => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(index);
|
||||
return newSet;
|
||||
});
|
||||
}, [activeFilters, onFiltersChange]);
|
||||
|
||||
const clearAllFilters = useCallback(() => {
|
||||
onFiltersChange([]);
|
||||
setExpandedFilters(new Set());
|
||||
if (onClearFilters) {
|
||||
onClearFilters();
|
||||
}
|
||||
}, [onFiltersChange, onClearFilters]);
|
||||
|
||||
const applyTemplate = useCallback((template: FilterTemplate) => {
|
||||
const newFilters: ActiveFilter[] = template.filters.map(filterConfig => {
|
||||
const attribute = availableAttributes.find(attr => attr.id === filterConfig.attributeId);
|
||||
if (!attribute) {
|
||||
console.warn(`Attribute ${filterConfig.attributeId} not found`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const filter: ActiveFilter = {
|
||||
attribute,
|
||||
value: filterConfig.value,
|
||||
isValid: false,
|
||||
};
|
||||
filter.isValid = validateFilter(filter) === null;
|
||||
return filter;
|
||||
}).filter((f): f is ActiveFilter => f !== null);
|
||||
|
||||
onFiltersChange(newFilters);
|
||||
setExpandedFilters(new Set());
|
||||
}, [availableAttributes, onFiltersChange]);
|
||||
|
||||
const toggleFilterExpanded = (index: number) => {
|
||||
setExpandedFilters(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(index)) {
|
||||
newSet.delete(index);
|
||||
} else {
|
||||
newSet.add(index);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
const getFilterIcon = (type: FilterAttribute["type"]) => {
|
||||
switch (type) {
|
||||
case "dateRange":
|
||||
return <Calendar className="h-4 w-4" />;
|
||||
case "multiSelect":
|
||||
return <CheckSquare className="h-4 w-4" />;
|
||||
case "number":
|
||||
case "numberRange":
|
||||
return <Hash className="h-4 w-4" />;
|
||||
case "radio":
|
||||
return <Radio className="h-4 w-4" />;
|
||||
case "tags":
|
||||
return <Tag className="h-4 w-4" />;
|
||||
case "text":
|
||||
return <Hash className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getFilterSummary = (filter: ActiveFilter): string => {
|
||||
switch (filter.attribute.type) {
|
||||
case "dateRange":
|
||||
return formatDateRange(filter.value as DateRangeValue);
|
||||
case "multiSelect": {
|
||||
const value = filter.value as MultiSelectValue;
|
||||
if (value.codes.length === 0) return "No options selected";
|
||||
if (value.codes.length <= 3) return value.codes.join(", ");
|
||||
return `${value.codes.slice(0, 3).join(", ")} +${value.codes.length - 3} more`;
|
||||
}
|
||||
case "number": {
|
||||
const value = filter.value as NumberValue;
|
||||
return value.value !== null ? value.value.toString() : "No value";
|
||||
}
|
||||
case "numberRange":
|
||||
return formatNumberRange(filter.value as NumberRangeValue, filter.attribute.config.unit);
|
||||
case "radio": {
|
||||
const value = filter.value as RadioValue;
|
||||
const option = filter.attribute.config.radioOptions?.find(opt => opt.value === value.status);
|
||||
return option?.label || value.status;
|
||||
}
|
||||
case "tags": {
|
||||
const value = filter.value as MultiSelectValue;
|
||||
if (value.codes.length === 0) return "No tags";
|
||||
if (value.codes.length <= 3) return value.codes.join(", ");
|
||||
return `${value.codes.slice(0, 3).join(", ")} +${value.codes.length - 3} more`;
|
||||
}
|
||||
case "text": {
|
||||
const value = filter.value as TextValue;
|
||||
return value.value || "No value";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const renderFilterInput = (filter: ActiveFilter, index: number) => {
|
||||
const error = filter.isValid ? undefined : validateFilter(filter) || undefined;
|
||||
|
||||
switch (filter.attribute.type) {
|
||||
case "dateRange":
|
||||
return (
|
||||
<DateRangeFilter
|
||||
value={filter.value as DateRangeValue}
|
||||
onChange={(value) => updateFilter(index, value)}
|
||||
error={error}
|
||||
presets={filter.attribute.config.datePresets}
|
||||
/>
|
||||
);
|
||||
case "multiSelect":
|
||||
return (
|
||||
<MultiSelectFilter
|
||||
options={filter.attribute.config.options || []}
|
||||
value={filter.value as MultiSelectValue}
|
||||
onChange={(value) => updateFilter(index, value)}
|
||||
error={error}
|
||||
showSelectAll={filter.attribute.config.showSelectAll}
|
||||
searchable={filter.attribute.config.searchable}
|
||||
/>
|
||||
);
|
||||
case "number":
|
||||
return (
|
||||
<NumberFilter
|
||||
value={filter.value as NumberValue}
|
||||
onChange={(value) => updateFilter(index, value)}
|
||||
error={error}
|
||||
placeholder={filter.attribute.config.placeholder}
|
||||
min={filter.attribute.config.min}
|
||||
max={filter.attribute.config.max}
|
||||
step={filter.attribute.config.step}
|
||||
/>
|
||||
);
|
||||
case "numberRange":
|
||||
return (
|
||||
<NumberRangeFilter
|
||||
value={filter.value as NumberRangeValue}
|
||||
onChange={(value) => updateFilter(index, value)}
|
||||
error={error}
|
||||
unit={filter.attribute.config.unit}
|
||||
min={filter.attribute.config.min}
|
||||
max={filter.attribute.config.max}
|
||||
step={filter.attribute.config.step}
|
||||
presets={filter.attribute.config.numberPresets}
|
||||
/>
|
||||
);
|
||||
case "radio":
|
||||
return (
|
||||
<RadioFilter
|
||||
value={filter.value as RadioValue}
|
||||
onChange={(value) => updateFilter(index, value)}
|
||||
error={error}
|
||||
options={filter.attribute.config.radioOptions || []}
|
||||
/>
|
||||
);
|
||||
case "tags":
|
||||
return (
|
||||
<TagInputFilter
|
||||
value={filter.value as MultiSelectValue}
|
||||
onChange={(value) => updateFilter(index, value)}
|
||||
error={error}
|
||||
/>
|
||||
);
|
||||
case "text":
|
||||
return (
|
||||
<TextFilter
|
||||
value={filter.value as TextValue}
|
||||
onChange={(value) => updateFilter(index, value)}
|
||||
error={error}
|
||||
placeholder={filter.attribute.config.placeholder}
|
||||
maxLength={filter.attribute.config.maxLength}
|
||||
/>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const allFiltersValid = activeFilters.every(f => f.isValid);
|
||||
const availableAttributesForAdding = availableAttributes.filter(
|
||||
attr => !activeFilters.some(f => f.attribute.id === attr.id)
|
||||
);
|
||||
|
||||
return (
|
||||
<Card className="mb-6">
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Filter Workflow Runs</CardTitle>
|
||||
<CardDescription>
|
||||
Build custom filters to find specific workflow runs
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
Templates
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-[250px]">
|
||||
<DropdownMenuLabel>Filter Templates</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{filterTemplates.map((template) => (
|
||||
<DropdownMenuItem
|
||||
key={template.id}
|
||||
onClick={() => applyTemplate(template)}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{template.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{template.description}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
{/* Add Filter Row */}
|
||||
<div className="flex gap-2">
|
||||
<Select value={selectedAttribute} onValueChange={(value) => {
|
||||
addFilter(value);
|
||||
}}>
|
||||
<SelectTrigger className="flex-1">
|
||||
<SelectValue placeholder="Select attribute to filter by" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableAttributesForAdding.map((attr) => (
|
||||
<SelectItem key={attr.id} value={attr.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
{getFilterIcon(attr.type)}
|
||||
<span>{attr.label}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Active Filters */}
|
||||
{activeFilters.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="text-sm font-medium">Active Filters</h4>
|
||||
{activeFilters.length > 1 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={clearAllFilters}
|
||||
>
|
||||
Clear All
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{activeFilters.map((filter, index) => (
|
||||
<Card key={index} className={filter.isValid ? "" : "border-red-200"}>
|
||||
<CardHeader className="pb-3">
|
||||
<div
|
||||
className="flex items-center justify-between cursor-pointer"
|
||||
onClick={() => toggleFilterExpanded(index)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{getFilterIcon(filter.attribute.type)}
|
||||
<span className="font-medium">{filter.attribute.label}</span>
|
||||
{!filter.isValid && (
|
||||
<AlertCircle className="h-4 w-4 text-red-500" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{!expandedFilters.has(index) && (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{getFilterSummary(filter)}
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
removeFilter(index);
|
||||
}}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
{expandedFilters.has(index) && (
|
||||
<CardContent>
|
||||
{renderFilterInput(filter, index)}
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Apply Filters Button */}
|
||||
{activeFilters.length > 0 && (
|
||||
<div className="flex justify-between items-center gap-2 pt-2">
|
||||
{/* Auto-refresh toggle on the left */}
|
||||
{onAutoRefreshChange && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
checked={autoRefresh}
|
||||
onCheckedChange={onAutoRefreshChange}
|
||||
id="auto-refresh"
|
||||
/>
|
||||
<label htmlFor="auto-refresh" className="text-sm font-medium cursor-pointer">
|
||||
Auto-refresh every 5s
|
||||
</label>
|
||||
{autoRefresh && (
|
||||
<RefreshCw className="h-4 w-4 text-gray-500 animate-spin" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Buttons on the right */}
|
||||
<div className="flex gap-2 ml-auto">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={clearAllFilters}
|
||||
>
|
||||
Clear All
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onApplyFilters}
|
||||
disabled={!allFiltersValid || isExecuting}
|
||||
title={"Apply filters"}
|
||||
>
|
||||
{isExecuting ? "Applying..." : `Apply (${navigator.userAgent.toUpperCase().indexOf('MAC') >= 0 ? '⌘' : 'Ctrl'}+Enter)`}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
154
ui/src/components/filters/MultiSelectFilter.tsx
Normal file
154
ui/src/components/filters/MultiSelectFilter.tsx
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { ChevronDown, Search } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { MultiSelectValue } from "@/types/filters";
|
||||
|
||||
interface MultiSelectFilterProps {
|
||||
options: string[];
|
||||
value: MultiSelectValue;
|
||||
onChange: (value: MultiSelectValue) => void;
|
||||
error?: string;
|
||||
showSelectAll?: boolean;
|
||||
searchable?: boolean;
|
||||
}
|
||||
|
||||
export const MultiSelectFilter: React.FC<MultiSelectFilterProps> = ({
|
||||
options,
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
showSelectAll = true,
|
||||
searchable = true,
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
|
||||
const filteredOptions = searchable
|
||||
? options.filter(option =>
|
||||
option.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
)
|
||||
: options;
|
||||
|
||||
const handleSelectAll = () => {
|
||||
onChange({ codes: options });
|
||||
};
|
||||
|
||||
const handleSelectNone = () => {
|
||||
onChange({ codes: [] });
|
||||
};
|
||||
|
||||
const handleToggleOption = (option: string) => {
|
||||
const newCodes = value.codes.includes(option)
|
||||
? value.codes.filter(code => code !== option)
|
||||
: [...value.codes, option];
|
||||
onChange({ codes: newCodes });
|
||||
};
|
||||
|
||||
const getDisplayText = () => {
|
||||
if (value.codes.length === 0) return "Select options";
|
||||
if (value.codes.length <= 3) return value.codes.join(", ");
|
||||
return `${value.codes.slice(0, 3).join(", ")} +${value.codes.length - 3} more`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label>Select Options</Label>
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={isOpen}
|
||||
className={cn(
|
||||
"w-full justify-between",
|
||||
value.codes.length === 0 && "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{getDisplayText()}</span>
|
||||
<ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-full p-0">
|
||||
<div className="p-2 space-y-2">
|
||||
{searchable && (
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search options..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showSelectAll && (
|
||||
<div className="flex gap-2 pb-2 border-b">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleSelectAll}
|
||||
className="flex-1"
|
||||
>
|
||||
Select All
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleSelectNone}
|
||||
className="flex-1"
|
||||
>
|
||||
Select None
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-h-[200px] overflow-auto space-y-1">
|
||||
{filteredOptions.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-2">
|
||||
No options found
|
||||
</p>
|
||||
) : (
|
||||
filteredOptions.map((option) => (
|
||||
<div
|
||||
key={option}
|
||||
className="flex items-center space-x-2 p-2 hover:bg-accent rounded-sm cursor-pointer"
|
||||
onClick={() => handleToggleOption(option)}
|
||||
>
|
||||
<Checkbox
|
||||
checked={value.codes.includes(option)}
|
||||
onCheckedChange={() => handleToggleOption(option)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
<Label
|
||||
htmlFor={option}
|
||||
className="text-sm font-normal cursor-pointer flex-1"
|
||||
>
|
||||
{option}
|
||||
</Label>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{value.codes.length} selected
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500 mt-1">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
55
ui/src/components/filters/NumberFilter.tsx
Normal file
55
ui/src/components/filters/NumberFilter.tsx
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NumberValue } from "@/types/filters";
|
||||
|
||||
interface NumberFilterProps {
|
||||
value: NumberValue;
|
||||
onChange: (value: NumberValue) => void;
|
||||
error?: string;
|
||||
placeholder?: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
}
|
||||
|
||||
export const NumberFilter: React.FC<NumberFilterProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
placeholder = "Enter value",
|
||||
min,
|
||||
max,
|
||||
step = 1,
|
||||
}) => {
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value;
|
||||
if (newValue === '') {
|
||||
onChange({ value: null });
|
||||
} else {
|
||||
const num = parseInt(newValue, 10);
|
||||
if (!isNaN(num)) {
|
||||
onChange({ value: num });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="number-filter">Value</Label>
|
||||
<Input
|
||||
id="number-filter"
|
||||
type="number"
|
||||
value={value.value ?? ''}
|
||||
onChange={handleChange}
|
||||
placeholder={placeholder}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
className={error ? "border-red-500" : ""}
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-xs text-red-500">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
97
ui/src/components/filters/NumberRangeFilter.tsx
Normal file
97
ui/src/components/filters/NumberRangeFilter.tsx
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NumberRangeValue } from "@/types/filters";
|
||||
|
||||
interface NumberRangeFilterProps {
|
||||
value: NumberRangeValue;
|
||||
onChange: (value: NumberRangeValue) => void;
|
||||
error?: string;
|
||||
unit?: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
presets?: { label: string; min: number; max: number }[];
|
||||
}
|
||||
|
||||
export const NumberRangeFilter: React.FC<NumberRangeFilterProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
unit,
|
||||
min = 0,
|
||||
max = 999999,
|
||||
step = 1,
|
||||
presets = [],
|
||||
}) => {
|
||||
const handleMinChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value === "" ? null : Number(e.target.value);
|
||||
onChange({ ...value, min: newValue });
|
||||
};
|
||||
|
||||
const handleMaxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value === "" ? null : Number(e.target.value);
|
||||
onChange({ ...value, max: newValue });
|
||||
};
|
||||
|
||||
const handlePresetClick = (preset: { min: number; max: number }) => {
|
||||
onChange({ min: preset.min, max: preset.max });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{presets.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{presets.map((preset, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePresetClick(preset)}
|
||||
>
|
||||
{preset.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="min-value">
|
||||
Min {unit && `(${unit})`}
|
||||
</Label>
|
||||
<Input
|
||||
id="min-value"
|
||||
type="number"
|
||||
placeholder={`Min ${unit || 'value'}`}
|
||||
value={value.min ?? ""}
|
||||
onChange={handleMinChange}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max-value">
|
||||
Max {unit && `(${unit})`}
|
||||
</Label>
|
||||
<Input
|
||||
id="max-value"
|
||||
type="number"
|
||||
placeholder={`Max ${unit || 'value'}`}
|
||||
value={value.max ?? ""}
|
||||
onChange={handleMaxChange}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500 mt-1">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
41
ui/src/components/filters/RadioFilter.tsx
Normal file
41
ui/src/components/filters/RadioFilter.tsx
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { Label } from "@/components/ui/label";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { RadioValue } from "@/types/filters";
|
||||
|
||||
interface RadioFilterProps {
|
||||
value: RadioValue;
|
||||
onChange: (value: RadioValue) => void;
|
||||
error?: string;
|
||||
options: { label: string; value: string }[];
|
||||
}
|
||||
|
||||
export const RadioFilter: React.FC<RadioFilterProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
options,
|
||||
}) => {
|
||||
const handleChange = (newValue: string) => {
|
||||
onChange({ status: newValue });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Label>Select Status</Label>
|
||||
<RadioGroup value={value.status} onValueChange={handleChange}>
|
||||
{options.map((option) => (
|
||||
<div key={option.value} className="flex items-center space-x-2">
|
||||
<RadioGroupItem value={option.value} id={option.value} />
|
||||
<Label htmlFor={option.value} className="font-normal cursor-pointer">
|
||||
{option.label}
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500 mt-1">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
37
ui/src/components/filters/TagInputFilter.tsx
Normal file
37
ui/src/components/filters/TagInputFilter.tsx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { ChangeEvent, useState } from "react";
|
||||
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { MultiSelectValue } from "@/types/filters";
|
||||
|
||||
interface TagInputFilterProps {
|
||||
value: MultiSelectValue;
|
||||
onChange: (value: MultiSelectValue) => void;
|
||||
error?: string;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export const TagInputFilter: React.FC<TagInputFilterProps> = ({ value, onChange, error, placeholder="Enter tags (comma separated)" }) => {
|
||||
const [text, setText] = useState(value.codes.join(", "));
|
||||
|
||||
const handleBlur = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const tags = e.target.value
|
||||
.split(/[,\n]/)
|
||||
.map((tag) => tag.trim())
|
||||
.filter((tag) => tag.length > 0);
|
||||
onChange({ codes: Array.from(new Set(tags)) });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label>Tags</Label>
|
||||
<Input
|
||||
value={text}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onBlur={handleBlur}
|
||||
/>
|
||||
{error && <p className="text-sm text-red-500 mt-1">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
32
ui/src/components/filters/TextFilter.tsx
Normal file
32
ui/src/components/filters/TextFilter.tsx
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { Input } from "@/components/ui/input";
|
||||
import { TextValue } from "@/types/filters";
|
||||
|
||||
interface TextFilterProps {
|
||||
value: TextValue;
|
||||
onChange: (value: TextValue) => void;
|
||||
error?: string;
|
||||
placeholder?: string;
|
||||
maxLength?: number;
|
||||
}
|
||||
|
||||
export const TextFilter: React.FC<TextFilterProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
placeholder = "Enter text",
|
||||
maxLength,
|
||||
}) => {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
type="text"
|
||||
value={value.value || ""}
|
||||
onChange={(e) => onChange({ value: e.target.value })}
|
||||
placeholder={placeholder}
|
||||
maxLength={maxLength}
|
||||
className={error ? "border-red-500" : ""}
|
||||
/>
|
||||
{error && <p className="text-sm text-red-500">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
105
ui/src/components/flow/AddNodePanel.tsx
Normal file
105
ui/src/components/flow/AddNodePanel.tsx
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
import { Globe, Headset, OctagonX, Play, X } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
import { NodeType } from './types';
|
||||
|
||||
type AddNodePanelProps = {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onNodeSelect: (nodeType: NodeType) => void;
|
||||
};
|
||||
|
||||
const NODE_TYPES = [
|
||||
{
|
||||
type: NodeType.START_CALL,
|
||||
label: 'Start Call',
|
||||
description: 'Create a start call node',
|
||||
icon: Play
|
||||
},
|
||||
{
|
||||
type: NodeType.AGENT_NODE,
|
||||
label: 'Agent Node',
|
||||
description: 'Create an agent node',
|
||||
icon: Headset
|
||||
},
|
||||
{
|
||||
type: NodeType.END_CALL,
|
||||
label: 'End Call',
|
||||
description: 'Create an end call node',
|
||||
icon: OctagonX
|
||||
}
|
||||
];
|
||||
|
||||
const GLOBAL_NODE_TYPES = [
|
||||
{
|
||||
type: NodeType.GLOBAL_NODE,
|
||||
label: 'Global Node',
|
||||
description: 'Create a global node',
|
||||
icon: Globe
|
||||
}
|
||||
]
|
||||
|
||||
export default function AddNodePanel({ isOpen, onNodeSelect, onClose }: AddNodePanelProps) {
|
||||
return (
|
||||
<div
|
||||
className={`fixed z-51 right-0 top-0 h-full w-80 bg-white shadow-lg transform transition-transform duration-300 ease-in-out ${isOpen ? 'translate-x-0' : 'translate-x-full'
|
||||
}`}
|
||||
>
|
||||
<div className="p-4">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-lg font-semibold">Add New Node</h2>
|
||||
<Button variant="ghost" size="icon" onClick={onClose}>
|
||||
<X className="w-5 h-5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<h1 className="text-sm text-gray-500 mb-2">Agent Nodes</h1>
|
||||
|
||||
<div className="space-y-2">
|
||||
{NODE_TYPES.map((node) => (
|
||||
<Button
|
||||
key={node.type}
|
||||
variant="outline"
|
||||
className="w-full justify-start p-4 h-auto"
|
||||
onClick={() => onNodeSelect(node.type)}
|
||||
>
|
||||
<div className="flex items-center">
|
||||
<div className="bg-gray-100 p-2 rounded-lg mr-3 border border-gray-200">
|
||||
<node.icon className="h-6 w-6" />
|
||||
</div>
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="font-medium">{node.label}</span>
|
||||
<span className="text-sm text-gray-500">{node.description}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<h1 className="text-sm text-gray-500 mb-2">Global Nodes</h1>
|
||||
|
||||
<div className="space-y-2">
|
||||
{GLOBAL_NODE_TYPES.map((node) => (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start p-4 h-auto"
|
||||
key={node.type}
|
||||
onClick={() => onNodeSelect(node.type)}
|
||||
>
|
||||
<div className="flex items-center">
|
||||
<div className="bg-gray-100 p-2 rounded-lg mr-3 border border-gray-200">
|
||||
<node.icon className="h-6 w-6" />
|
||||
</div>
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="font-medium">{node.label}</span>
|
||||
<span className="text-sm text-gray-500">{node.description}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
188
ui/src/components/flow/edges/CustomEdge.tsx
Normal file
188
ui/src/components/flow/edges/CustomEdge.tsx
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
import { BaseEdge, type Edge, EdgeLabelRenderer, type EdgeProps, getSmoothStepPath, useReactFlow } from '@xyflow/react';
|
||||
import { AlertCircle, Pencil } from 'lucide-react';
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
import { useWorkflow } from "@/app/workflow/[workflowId]/contexts/WorkflowContext";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { FlowEdge, FlowEdgeData, FlowNode } from '../types';
|
||||
type CustomEdge = Edge<{ value: number }, 'custom'>;
|
||||
|
||||
|
||||
interface EdgeDetailsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
data?: FlowEdgeData;
|
||||
onSave: (value: FlowEdgeData) => void;
|
||||
}
|
||||
|
||||
const EdgeDetailsDialog = ({ open, onOpenChange, data, onSave }: EdgeDetailsDialogProps) => {
|
||||
const [condition, setCondition] = useState(data?.condition ?? '');
|
||||
const [label, setLabel] = useState(data?.label ?? '');
|
||||
|
||||
const handleSave = () => {
|
||||
onSave({ condition: condition, label: label });
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Condition</DialogTitle>
|
||||
{data?.invalid && data.validationMessage && (
|
||||
<div className="mt-2 flex items-center gap-2 rounded-md bg-red-50 p-2 text-sm text-red-500 border border-red-200">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<span>{data.validationMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label>Condition Label</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Enter a short label which helps identify this pathway in logs
|
||||
</Label>
|
||||
<Input
|
||||
type="text"
|
||||
value={label}
|
||||
maxLength={64}
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
/>
|
||||
<div className="text-xs text-gray-500">
|
||||
{label.length}/64 characters
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>Condition</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Describe a condition that will be evaluated to determine if this pathway should be taken
|
||||
</Label>
|
||||
<Textarea
|
||||
value={condition}
|
||||
onChange={(e) => setCondition(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
|
||||
<Button onClick={handleSave}>Save</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
interface CustomEdgeProps extends EdgeProps {
|
||||
data: FlowEdgeData;
|
||||
}
|
||||
|
||||
export default function CustomEdge(props: CustomEdgeProps) {
|
||||
const { id, source, target, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, data } = props;
|
||||
|
||||
const { getEdges, setEdges } = useReactFlow<FlowNode, FlowEdge>();
|
||||
const { saveWorkflow } = useWorkflow();
|
||||
const parallel = getEdges().filter(
|
||||
(e) =>
|
||||
(e.source === source && e.target === target) ||
|
||||
(e.source === target && e.target === source)
|
||||
);
|
||||
|
||||
// 2) if there are two, sort by id and pick an index
|
||||
let offsetX = 0;
|
||||
let offsetY = 0;
|
||||
if (parallel.length > 1) {
|
||||
const sorted = parallel.slice().sort((a, b) => a.id.localeCompare(b.id));
|
||||
const idx = sorted.findIndex((e) => e.id === id);
|
||||
|
||||
// first edge (idx 0) moves right & down;
|
||||
// second edge (idx 1) moves left & up
|
||||
if (idx === 0) {
|
||||
offsetX = 100;
|
||||
offsetY = 0;
|
||||
} else {
|
||||
offsetX = 0;
|
||||
offsetY = -50;
|
||||
}
|
||||
}
|
||||
|
||||
// 3) draw the straight path + get label coords
|
||||
const [edgePath, labelX, labelY] = getSmoothStepPath({
|
||||
sourceX,
|
||||
sourceY,
|
||||
sourcePosition,
|
||||
targetX,
|
||||
targetY,
|
||||
targetPosition,
|
||||
});
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const handleSaveEdgeData = useCallback(async (updatedData: FlowEdgeData) => {
|
||||
// Update the node data in the ReactFlow nodes state
|
||||
setEdges((edges) => {
|
||||
const updatedEdges = edges.map((edge) =>
|
||||
edge.id === id
|
||||
? { ...edge, data: updatedData }
|
||||
: edge
|
||||
)
|
||||
return updatedEdges;
|
||||
}
|
||||
);
|
||||
// Save the workflow after updating edge data with a small delay to ensure state is updated
|
||||
setTimeout(async () => {
|
||||
await saveWorkflow();
|
||||
}, 100);
|
||||
}, [id, setEdges, saveWorkflow]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<BaseEdge
|
||||
id={id}
|
||||
path={edgePath}
|
||||
/>
|
||||
<EdgeLabelRenderer>
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
pointerEvents: 'all',
|
||||
transformOrigin: 'center',
|
||||
transform: `translate(-50%, -50%) translate(${labelX + offsetX}px, ${labelY + offsetY}px)`,
|
||||
}}
|
||||
className="nodrag nopan"
|
||||
>
|
||||
<div className={cn(
|
||||
"flex items-center gap-2 bg-white pl-3 pr-1 py-1 rounded-md border shadow-sm",
|
||||
data?.invalid ? "border-red-500/30 shadow-[0_0_10px_rgba(239,68,68,0.5)]" : "border-gray-200"
|
||||
)}>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm">{data?.label || data?.condition || 'Set Condition'}</span>
|
||||
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 p-0"
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</EdgeLabelRenderer>
|
||||
<EdgeDetailsDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
data={data}
|
||||
onSave={handleSaveEdgeData}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
298
ui/src/components/flow/nodes/AgentNode.tsx
Normal file
298
ui/src/components/flow/nodes/AgentNode.tsx
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
import { NodeProps, NodeToolbar, Position } from "@xyflow/react";
|
||||
import { Edit, Headset, PlusIcon,Trash2Icon } from "lucide-react";
|
||||
import { memo, useState } from "react";
|
||||
|
||||
import { useWorkflow } from "@/app/workflow/[workflowId]/contexts/WorkflowContext";
|
||||
import { ExtractionVariable,FlowNodeData } from "@/components/flow/types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
|
||||
import { NodeContent } from "./common/NodeContent";
|
||||
import { NodeEditDialog } from "./common/NodeEditDialog";
|
||||
import { useNodeHandlers } from "./common/useNodeHandlers";
|
||||
|
||||
interface AgentNodeEditFormProps {
|
||||
nodeData: FlowNodeData;
|
||||
prompt: string;
|
||||
setPrompt: (value: string) => void;
|
||||
name: string;
|
||||
setName: (value: string) => void;
|
||||
allowInterrupt: boolean;
|
||||
setAllowInterrupt: (value: boolean) => void;
|
||||
extractionEnabled: boolean;
|
||||
setExtractionEnabled: (value: boolean) => void;
|
||||
extractionPrompt: string;
|
||||
setExtractionPrompt: (value: string) => void;
|
||||
variables: ExtractionVariable[];
|
||||
setVariables: (vars: ExtractionVariable[]) => void;
|
||||
addGlobalPrompt: boolean;
|
||||
setAddGlobalPrompt: (value: boolean) => void;
|
||||
}
|
||||
|
||||
interface AgentNodeProps extends NodeProps {
|
||||
data: FlowNodeData;
|
||||
}
|
||||
|
||||
export const AgentNode = memo(({ data, selected, id }: AgentNodeProps) => {
|
||||
const { open, setOpen, handleSaveNodeData, handleDeleteNode } = useNodeHandlers({ id });
|
||||
const { saveWorkflow } = useWorkflow();
|
||||
|
||||
// Form state
|
||||
const [prompt, setPrompt] = useState(data.prompt);
|
||||
const [name, setName] = useState(data.name);
|
||||
const [allowInterrupt, setAllowInterrupt] = useState(data.allow_interrupt ?? true);
|
||||
|
||||
// Variable Extraction state
|
||||
const [extractionEnabled, setExtractionEnabled] = useState(data.extraction_enabled ?? false);
|
||||
const [extractionPrompt, setExtractionPrompt] = useState(data.extraction_prompt ?? "");
|
||||
const [variables, setVariables] = useState<ExtractionVariable[]>(data.extraction_variables ?? []);
|
||||
const [addGlobalPrompt, setAddGlobalPrompt] = useState(data.add_global_prompt ?? true);
|
||||
|
||||
const handleSave = async () => {
|
||||
handleSaveNodeData({
|
||||
...data,
|
||||
prompt,
|
||||
name,
|
||||
allow_interrupt: allowInterrupt,
|
||||
extraction_enabled: extractionEnabled,
|
||||
extraction_prompt: extractionPrompt,
|
||||
extraction_variables: variables,
|
||||
add_global_prompt: addGlobalPrompt,
|
||||
});
|
||||
setOpen(false);
|
||||
// Save the workflow after updating node data with a small delay to ensure state is updated
|
||||
setTimeout(async () => {
|
||||
await saveWorkflow();
|
||||
}, 100);
|
||||
};
|
||||
|
||||
// Reset form state when dialog opens
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (newOpen) {
|
||||
setPrompt(data.prompt);
|
||||
setName(data.name);
|
||||
setAllowInterrupt(data.allow_interrupt ?? true);
|
||||
setExtractionEnabled(data.extraction_enabled ?? false);
|
||||
setExtractionPrompt(data.extraction_prompt ?? "");
|
||||
setVariables(data.extraction_variables ?? []);
|
||||
setAddGlobalPrompt(data.add_global_prompt ?? true);
|
||||
}
|
||||
setOpen(newOpen);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<NodeContent
|
||||
selected={selected}
|
||||
invalid={data.invalid}
|
||||
title={data.name || 'Agent'}
|
||||
icon={<Headset />}
|
||||
bgColor="bg-blue-300"
|
||||
hasSourceHandle={true}
|
||||
hasTargetHandle={true}
|
||||
>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{data.prompt?.length > 30 ? `${data.prompt.substring(0, 30)}...` : data.prompt}
|
||||
</div>
|
||||
</NodeContent>
|
||||
|
||||
<NodeToolbar isVisible={selected} position={Position.Right}>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Button onClick={() => setOpen(true)} variant="outline" size="icon">
|
||||
<Edit />
|
||||
</Button>
|
||||
<Button onClick={handleDeleteNode} variant="outline" size="icon">
|
||||
<Trash2Icon />
|
||||
</Button>
|
||||
</div>
|
||||
</NodeToolbar>
|
||||
|
||||
<NodeEditDialog
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
nodeData={data}
|
||||
title="Edit Agent"
|
||||
onSave={handleSave}
|
||||
>
|
||||
{open && (
|
||||
<AgentNodeEditForm
|
||||
nodeData={data}
|
||||
prompt={prompt}
|
||||
setPrompt={setPrompt}
|
||||
name={name}
|
||||
setName={setName}
|
||||
allowInterrupt={allowInterrupt}
|
||||
setAllowInterrupt={setAllowInterrupt}
|
||||
extractionEnabled={extractionEnabled}
|
||||
setExtractionEnabled={setExtractionEnabled}
|
||||
extractionPrompt={extractionPrompt}
|
||||
setExtractionPrompt={setExtractionPrompt}
|
||||
variables={variables}
|
||||
setVariables={setVariables}
|
||||
addGlobalPrompt={addGlobalPrompt}
|
||||
setAddGlobalPrompt={setAddGlobalPrompt}
|
||||
/>
|
||||
)}
|
||||
</NodeEditDialog>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
const AgentNodeEditForm = ({
|
||||
prompt,
|
||||
setPrompt,
|
||||
name,
|
||||
setName,
|
||||
allowInterrupt,
|
||||
setAllowInterrupt,
|
||||
extractionEnabled,
|
||||
setExtractionEnabled,
|
||||
extractionPrompt,
|
||||
setExtractionPrompt,
|
||||
variables,
|
||||
setVariables,
|
||||
addGlobalPrompt,
|
||||
setAddGlobalPrompt,
|
||||
}: AgentNodeEditFormProps) => {
|
||||
const handleVariableNameChange = (idx: number, value: string) => {
|
||||
const newVars = [...variables];
|
||||
newVars[idx] = { ...newVars[idx], name: value };
|
||||
setVariables(newVars);
|
||||
};
|
||||
|
||||
const handleVariableTypeChange = (idx: number, value: 'string' | 'number' | 'boolean') => {
|
||||
const newVars = [...variables];
|
||||
newVars[idx] = { ...newVars[idx], type: value };
|
||||
setVariables(newVars);
|
||||
};
|
||||
|
||||
const handleVariablePromptChange = (idx: number, value: string) => {
|
||||
const newVars = [...variables];
|
||||
newVars[idx] = { ...newVars[idx], prompt: value };
|
||||
setVariables(newVars);
|
||||
};
|
||||
|
||||
const handleRemoveVariable = (idx: number) => {
|
||||
const newVars = variables.filter((_, i) => i !== idx);
|
||||
setVariables(newVars);
|
||||
};
|
||||
|
||||
const handleAddVariable = () => {
|
||||
setVariables([...variables, { name: '', type: 'string', prompt: '' }]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<Label>Name</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
The name of the agent that will be used to identify the agent in the call logs. It should be short and should identify the step in the call.
|
||||
</Label>
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
|
||||
<div className="flex items-center space-x-2 p-2 border rounded-md bg-muted/20">
|
||||
<Switch id="allow-interrupt" checked={allowInterrupt} onCheckedChange={setAllowInterrupt} />
|
||||
<Label htmlFor="allow-interrupt">Allow Interruption</Label>
|
||||
<Label className="text-xs text-gray-500 ml-2">
|
||||
Whether you would like user to be able to interrupt the bot.
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2 p-2 border rounded-md bg-muted/20">
|
||||
<Switch id="add-global-prompt" checked={addGlobalPrompt} onCheckedChange={setAddGlobalPrompt} />
|
||||
<Label htmlFor="add-global-prompt">Add Global Prompt</Label>
|
||||
<Label className="text-xs text-gray-500 ml-2">
|
||||
Whether you want to add global prompt with this node's prompt.
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="pt-2 space-y-2">
|
||||
<Label>Prompt</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Enter the prompt for the agent. This will be used to generate the agent's response. Prompt engineering's best practices apply.
|
||||
</Label>
|
||||
<Textarea
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
className="min-h-[100px] max-h-[300px] resize-none"
|
||||
style={{
|
||||
overflowY: 'auto'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Variable Extraction Section */}
|
||||
<div className="flex items-center space-x-2 pt-2">
|
||||
<Switch id="enable-extraction" checked={extractionEnabled} onCheckedChange={setExtractionEnabled} />
|
||||
<Label htmlFor="enable-extraction">Enable Variable Extraction</Label>
|
||||
<Label className="text-xs text-gray-500 ml-2">
|
||||
Are there any variables you would like to extract from the conversation?
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{extractionEnabled && (
|
||||
<div className="border rounded-md p-3 mt-2 space-y-2 bg-muted/20">
|
||||
<Label>Extraction Prompt</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Provide an overall extraction prompt that guides how variables should be extracted from the conversation.
|
||||
</Label>
|
||||
<Textarea
|
||||
value={extractionPrompt}
|
||||
onChange={(e) => setExtractionPrompt(e.target.value)}
|
||||
className="min-h-[80px] max-h-[200px] resize-none"
|
||||
style={{ overflowY: 'auto' }}
|
||||
/>
|
||||
|
||||
<Label>Variables</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Define each variable you want to extract along with its data type.
|
||||
</Label>
|
||||
|
||||
{variables.map((v, idx) => (
|
||||
<div key={idx} className="space-y-2 border rounded-md p-2 bg-background">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Variable name"
|
||||
value={v.name}
|
||||
onChange={(e) => handleVariableNameChange(idx, e.target.value)}
|
||||
/>
|
||||
<select
|
||||
className="border rounded-md p-2 text-sm bg-background"
|
||||
value={v.type}
|
||||
onChange={(e) => handleVariableTypeChange(idx, e.target.value as 'string' | 'number' | 'boolean')}
|
||||
>
|
||||
<option value="string">String</option>
|
||||
<option value="number">Number</option>
|
||||
<option value="boolean">Boolean</option>
|
||||
</select>
|
||||
<Button variant="outline" size="icon" onClick={() => handleRemoveVariable(idx)}>
|
||||
<Trash2Icon className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Textarea
|
||||
placeholder="Extraction prompt for this variable"
|
||||
value={v.prompt ?? ''}
|
||||
onChange={(e) => handleVariablePromptChange(idx, e.target.value)}
|
||||
className="min-h-[60px] resize-none"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<Button variant="outline" size="sm" className="w-fit" onClick={handleAddVariable}>
|
||||
<PlusIcon className="w-4 h-4 mr-1" /> Add Variable
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
AgentNode.displayName = "AgentNode";
|
||||
|
||||
26
ui/src/components/flow/nodes/BaseHandle.tsx
Normal file
26
ui/src/components/flow/nodes/BaseHandle.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { Handle, HandleProps } from "@xyflow/react";
|
||||
import { forwardRef } from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type BaseHandleProps = HandleProps;
|
||||
|
||||
export const BaseHandle = forwardRef<HTMLDivElement, BaseHandleProps>(
|
||||
({ className, children, ...props }, ref) => {
|
||||
return (
|
||||
<Handle
|
||||
ref={ref}
|
||||
{...props}
|
||||
className={cn(
|
||||
"h-[11px] w-[11px] rounded-full border border-slate-300 bg-slate-100 transition dark:border-secondary dark:bg-secondary",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</Handle>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
BaseHandle.displayName = "BaseHandle";
|
||||
26
ui/src/components/flow/nodes/BaseNode.tsx
Normal file
26
ui/src/components/flow/nodes/BaseNode.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { forwardRef, HTMLAttributes } from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const BaseNode = forwardRef<
|
||||
HTMLDivElement,
|
||||
HTMLAttributes<HTMLDivElement> & {
|
||||
selected?: boolean;
|
||||
invalid?: boolean;
|
||||
}
|
||||
>(({ className, selected, invalid, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative rounded-md border bg-card p-5 text-card-foreground min-w-[300px] min-h-[100px]",
|
||||
className,
|
||||
selected ? "border-muted-foreground shadow-lg" : "",
|
||||
invalid ? "border-red-500 shadow-[0_0_10px_rgba(239,68,68,0.5)]" : "",
|
||||
"hover:ring-1",
|
||||
)}
|
||||
tabIndex={0}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
|
||||
BaseNode.displayName = "BaseNode";
|
||||
283
ui/src/components/flow/nodes/EndCall.tsx
Normal file
283
ui/src/components/flow/nodes/EndCall.tsx
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
import { NodeProps, NodeToolbar, Position } from "@xyflow/react";
|
||||
import { Edit, OctagonX, PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import { memo, useState } from "react";
|
||||
|
||||
import { useWorkflow } from "@/app/workflow/[workflowId]/contexts/WorkflowContext";
|
||||
import { ExtractionVariable, FlowNodeData } from "@/components/flow/types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
|
||||
import { NodeContent } from "./common/NodeContent";
|
||||
import { NodeEditDialog } from "./common/NodeEditDialog";
|
||||
import { useNodeHandlers } from "./common/useNodeHandlers";
|
||||
|
||||
interface EndCallEditFormProps {
|
||||
nodeData: FlowNodeData;
|
||||
prompt: string;
|
||||
setPrompt: (value: string) => void;
|
||||
isStatic: boolean;
|
||||
setIsStatic: (value: boolean) => void;
|
||||
name: string;
|
||||
setName: (value: string) => void;
|
||||
extractionEnabled: boolean;
|
||||
setExtractionEnabled: (value: boolean) => void;
|
||||
extractionPrompt: string;
|
||||
setExtractionPrompt: (value: string) => void;
|
||||
variables: ExtractionVariable[];
|
||||
setVariables: (vars: ExtractionVariable[]) => void;
|
||||
addGlobalPrompt: boolean;
|
||||
setAddGlobalPrompt: (value: boolean) => void;
|
||||
}
|
||||
|
||||
interface EndCallNodeProps extends NodeProps {
|
||||
data: FlowNodeData;
|
||||
}
|
||||
|
||||
export const EndCall = memo(({ data, selected, id }: EndCallNodeProps) => {
|
||||
const { open, setOpen, handleSaveNodeData } = useNodeHandlers({
|
||||
id,
|
||||
additionalData: { is_end: true }
|
||||
});
|
||||
const { saveWorkflow } = useWorkflow();
|
||||
|
||||
// Form state
|
||||
const [prompt, setPrompt] = useState(data.prompt);
|
||||
const [isStatic, setIsStatic] = useState(data.is_static ?? true);
|
||||
const [name, setName] = useState(data.name);
|
||||
|
||||
// Variable Extraction state
|
||||
const [extractionEnabled, setExtractionEnabled] = useState(data.extraction_enabled ?? false);
|
||||
const [extractionPrompt, setExtractionPrompt] = useState(data.extraction_prompt ?? "");
|
||||
const [variables, setVariables] = useState<ExtractionVariable[]>(data.extraction_variables ?? []);
|
||||
const [addGlobalPrompt, setAddGlobalPrompt] = useState(data.add_global_prompt ?? true);
|
||||
|
||||
const handleSave = async () => {
|
||||
handleSaveNodeData({
|
||||
...data,
|
||||
prompt,
|
||||
is_static: isStatic,
|
||||
name,
|
||||
allow_interrupt: false, // Always set to false for end nodes
|
||||
extraction_enabled: extractionEnabled,
|
||||
extraction_prompt: extractionPrompt,
|
||||
extraction_variables: variables,
|
||||
add_global_prompt: addGlobalPrompt,
|
||||
});
|
||||
setOpen(false);
|
||||
// Save the workflow after updating node data with a small delay to ensure state is updated
|
||||
setTimeout(async () => {
|
||||
await saveWorkflow();
|
||||
}, 100);
|
||||
};
|
||||
|
||||
// Reset form state when dialog opens
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (newOpen) {
|
||||
setPrompt(data.prompt);
|
||||
setIsStatic(data.is_static ?? true);
|
||||
setName(data.name);
|
||||
setExtractionEnabled(data.extraction_enabled ?? false);
|
||||
setExtractionPrompt(data.extraction_prompt ?? "");
|
||||
setVariables(data.extraction_variables ?? []);
|
||||
setAddGlobalPrompt(data.add_global_prompt ?? true);
|
||||
}
|
||||
setOpen(newOpen);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<NodeContent
|
||||
selected={selected}
|
||||
invalid={data.invalid}
|
||||
title="End Call"
|
||||
icon={<OctagonX />}
|
||||
bgColor="bg-red-300"
|
||||
hasTargetHandle={true}
|
||||
>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{data.prompt?.length > 30 ? `${data.prompt.substring(0, 30)}...` : data.prompt}
|
||||
</div>
|
||||
</NodeContent>
|
||||
|
||||
<NodeToolbar isVisible={selected} position={Position.Right}>
|
||||
<Button onClick={() => setOpen(true)} variant="outline" size="icon">
|
||||
<Edit />
|
||||
</Button>
|
||||
</NodeToolbar>
|
||||
|
||||
<NodeEditDialog
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
nodeData={data}
|
||||
title="End Call"
|
||||
onSave={handleSave}
|
||||
>
|
||||
{open && (
|
||||
<EndCallEditForm
|
||||
nodeData={data}
|
||||
prompt={prompt}
|
||||
setPrompt={setPrompt}
|
||||
isStatic={isStatic}
|
||||
setIsStatic={setIsStatic}
|
||||
name={name}
|
||||
setName={setName}
|
||||
extractionEnabled={extractionEnabled}
|
||||
setExtractionEnabled={setExtractionEnabled}
|
||||
extractionPrompt={extractionPrompt}
|
||||
setExtractionPrompt={setExtractionPrompt}
|
||||
variables={variables}
|
||||
setVariables={setVariables}
|
||||
addGlobalPrompt={addGlobalPrompt}
|
||||
setAddGlobalPrompt={setAddGlobalPrompt}
|
||||
/>
|
||||
)}
|
||||
</NodeEditDialog>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
const EndCallEditForm = ({
|
||||
prompt,
|
||||
setPrompt,
|
||||
isStatic,
|
||||
setIsStatic,
|
||||
name,
|
||||
setName,
|
||||
extractionEnabled,
|
||||
setExtractionEnabled,
|
||||
extractionPrompt,
|
||||
setExtractionPrompt,
|
||||
variables,
|
||||
setVariables,
|
||||
addGlobalPrompt,
|
||||
setAddGlobalPrompt,
|
||||
}: EndCallEditFormProps) => {
|
||||
const handleVariableNameChange = (idx: number, value: string) => {
|
||||
const newVars = [...variables];
|
||||
newVars[idx] = { ...newVars[idx], name: value };
|
||||
setVariables(newVars);
|
||||
};
|
||||
|
||||
const handleVariableTypeChange = (idx: number, value: 'string' | 'number' | 'boolean') => {
|
||||
const newVars = [...variables];
|
||||
newVars[idx] = { ...newVars[idx], type: value };
|
||||
setVariables(newVars);
|
||||
};
|
||||
|
||||
const handleVariablePromptChange = (idx: number, value: string) => {
|
||||
const newVars = [...variables];
|
||||
newVars[idx] = { ...newVars[idx], prompt: value };
|
||||
setVariables(newVars);
|
||||
};
|
||||
|
||||
const handleRemoveVariable = (idx: number) => {
|
||||
const newVars = variables.filter((_, i) => i !== idx);
|
||||
setVariables(newVars);
|
||||
};
|
||||
|
||||
const handleAddVariable = () => {
|
||||
setVariables([...variables, { name: '', type: 'string', prompt: '' }]);
|
||||
};
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<Label>Name</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
The name of the agent that will be used to identify the agent in the call logs. It should be short and should identify the step in the call.
|
||||
</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} />
|
||||
|
||||
<Label>{isStatic ? "Text" : "Prompt"}</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
What would you like the agent to say when the call ends? Its a good idea to have a static goodbye message.
|
||||
</Label>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch id="static-text" checked={isStatic} onCheckedChange={setIsStatic} />
|
||||
<Label htmlFor="static-text">Static Text</Label>
|
||||
</div>
|
||||
<Textarea
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
className="min-h-[100px] max-h-[300px] resize-none"
|
||||
style={{
|
||||
overflowY: 'auto'
|
||||
}}
|
||||
placeholder={isStatic ? "Thank you for calling Dograh. Have a great day!" : "Enter a dynamic prompt"}
|
||||
/>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch id="add-global-prompt" checked={addGlobalPrompt} onCheckedChange={setAddGlobalPrompt} />
|
||||
<Label htmlFor="add-global-prompt">Add Global Prompt</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Whether you want to add global prompt with this node's prompt.
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{/* Variable Extraction Section */}
|
||||
<div className="flex items-center space-x-2 pt-2">
|
||||
<Switch id="enable-extraction" checked={extractionEnabled} onCheckedChange={setExtractionEnabled} />
|
||||
<Label htmlFor="enable-extraction">Enable Variable Extraction</Label>
|
||||
<Label className="text-xs text-gray-500 ml-2">
|
||||
Are there any variables you would like to extract from the conversation?
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{extractionEnabled && (
|
||||
<div className="border rounded-md p-3 mt-2 space-y-2 bg-muted/20">
|
||||
<Label>Extraction Prompt</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Provide an overall extraction prompt that guides how variables should be extracted from the conversation.
|
||||
</Label>
|
||||
<Textarea
|
||||
value={extractionPrompt}
|
||||
onChange={(e) => setExtractionPrompt(e.target.value)}
|
||||
className="min-h-[80px] max-h-[200px] resize-none"
|
||||
style={{ overflowY: 'auto' }}
|
||||
/>
|
||||
|
||||
<Label>Variables</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Define each variable you want to extract along with its data type.
|
||||
</Label>
|
||||
|
||||
{variables.map((v, idx) => (
|
||||
<div key={idx} className="space-y-2 border rounded-md p-2 bg-background">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Variable name"
|
||||
value={v.name}
|
||||
onChange={(e) => handleVariableNameChange(idx, e.target.value)}
|
||||
/>
|
||||
<select
|
||||
className="border rounded-md p-2 text-sm bg-background"
|
||||
value={v.type}
|
||||
onChange={(e) => handleVariableTypeChange(idx, e.target.value as 'string' | 'number' | 'boolean')}
|
||||
>
|
||||
<option value="string">String</option>
|
||||
<option value="number">Number</option>
|
||||
<option value="boolean">Boolean</option>
|
||||
</select>
|
||||
<Button variant="outline" size="icon" onClick={() => handleRemoveVariable(idx)}>
|
||||
<Trash2Icon className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Textarea
|
||||
placeholder="Extraction prompt for this variable"
|
||||
value={v.prompt ?? ''}
|
||||
onChange={(e) => handleVariablePromptChange(idx, e.target.value)}
|
||||
className="min-h-[60px] resize-none"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<Button variant="outline" size="sm" className="w-fit" onClick={handleAddVariable}>
|
||||
<PlusIcon className="w-4 h-4 mr-1" /> Add Variable
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
EndCall.displayName = "EndCall";
|
||||
139
ui/src/components/flow/nodes/GlobalNode.tsx
Normal file
139
ui/src/components/flow/nodes/GlobalNode.tsx
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import { NodeProps, NodeToolbar, Position } from "@xyflow/react";
|
||||
import { Edit, Headset, Trash2Icon } from "lucide-react";
|
||||
import { memo, useState } from "react";
|
||||
|
||||
import { useWorkflow } from "@/app/workflow/[workflowId]/contexts/WorkflowContext";
|
||||
import { FlowNodeData } from "@/components/flow/types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
|
||||
import { NodeContent } from "./common/NodeContent";
|
||||
import { NodeEditDialog } from "./common/NodeEditDialog";
|
||||
import { useNodeHandlers } from "./common/useNodeHandlers";
|
||||
|
||||
interface GlobalNodeEditFormProps {
|
||||
nodeData: FlowNodeData;
|
||||
prompt: string;
|
||||
setPrompt: (value: string) => void;
|
||||
name: string;
|
||||
setName: (value: string) => void;
|
||||
}
|
||||
|
||||
interface GlobalNodeProps extends NodeProps {
|
||||
data: FlowNodeData;
|
||||
}
|
||||
|
||||
export const GlobalNode = memo(({ data, selected, id }: GlobalNodeProps) => {
|
||||
const { open, setOpen, handleSaveNodeData, handleDeleteNode } = useNodeHandlers({ id });
|
||||
const { saveWorkflow } = useWorkflow();
|
||||
|
||||
// Form state
|
||||
const [prompt, setPrompt] = useState(data.prompt);
|
||||
const [name, setName] = useState(data.name);
|
||||
|
||||
const handleSave = async () => {
|
||||
handleSaveNodeData({
|
||||
...data,
|
||||
prompt,
|
||||
is_static: false,
|
||||
name
|
||||
});
|
||||
setOpen(false);
|
||||
// Save the workflow after updating node data with a small delay to ensure state is updated
|
||||
setTimeout(async () => {
|
||||
await saveWorkflow();
|
||||
}, 100);
|
||||
};
|
||||
|
||||
// Reset form state when dialog opens
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (newOpen) {
|
||||
setPrompt(data.prompt);
|
||||
setName(data.name);
|
||||
}
|
||||
setOpen(newOpen);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<NodeContent
|
||||
selected={selected}
|
||||
invalid={data.invalid}
|
||||
title={data.name || 'Global'}
|
||||
icon={<Headset />}
|
||||
bgColor="bg-orange-300"
|
||||
>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{data.prompt?.length > 30 ? `${data.prompt.substring(0, 30)}...` : data.prompt}
|
||||
</div>
|
||||
</NodeContent>
|
||||
|
||||
<NodeToolbar isVisible={selected} position={Position.Right}>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Button onClick={() => setOpen(true)} variant="outline" size="icon">
|
||||
<Edit />
|
||||
</Button>
|
||||
<Button onClick={handleDeleteNode} variant="outline" size="icon">
|
||||
<Trash2Icon />
|
||||
</Button>
|
||||
</div>
|
||||
</NodeToolbar>
|
||||
|
||||
<NodeEditDialog
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
nodeData={data}
|
||||
title="Edit Global Node"
|
||||
onSave={handleSave}
|
||||
>
|
||||
{open && (
|
||||
<GlobalNodeEditForm
|
||||
nodeData={data}
|
||||
prompt={prompt}
|
||||
setPrompt={setPrompt}
|
||||
name={name}
|
||||
setName={setName}
|
||||
/>
|
||||
)}
|
||||
</NodeEditDialog>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
const GlobalNodeEditForm = ({
|
||||
prompt,
|
||||
setPrompt,
|
||||
name,
|
||||
setName
|
||||
}: GlobalNodeEditFormProps) => {
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<Label>Name</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
The name of the global node.
|
||||
</Label>
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
|
||||
<Label>Prompt</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
This is the global prompt. This will be added to the system prompt of all the agents.
|
||||
</Label>
|
||||
<Textarea
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
className="min-h-[100px] max-h-[300px] resize-none"
|
||||
style={{
|
||||
overflowY: 'auto'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
GlobalNode.displayName = "GlobalNode";
|
||||
|
||||
193
ui/src/components/flow/nodes/NodeHeader.tsx
Normal file
193
ui/src/components/flow/nodes/NodeHeader.tsx
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { useNodeId, useReactFlow } from "@xyflow/react";
|
||||
import { EllipsisVertical, Trash } from "lucide-react";
|
||||
import { forwardRef, HTMLAttributes, ReactNode,useCallback } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/* NODE HEADER -------------------------------------------------------------- */
|
||||
|
||||
export type NodeHeaderProps = HTMLAttributes<HTMLElement>;
|
||||
|
||||
/**
|
||||
* A container for a consistent header layout intended to be used inside the
|
||||
* `<BaseNode />` component.
|
||||
*/
|
||||
export const NodeHeader = forwardRef<HTMLElement, NodeHeaderProps>(
|
||||
({ className, ...props }, ref) => {
|
||||
return (
|
||||
<header
|
||||
ref={ref}
|
||||
{...props}
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-2 px-3 py-2",
|
||||
// Remove or modify these classes if you modify the padding in the
|
||||
// `<BaseNode />` component.
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
NodeHeader.displayName = "NodeHeader";
|
||||
|
||||
/* NODE HEADER TITLE -------------------------------------------------------- */
|
||||
|
||||
export type NodeHeaderTitleProps = HTMLAttributes<HTMLHeadingElement> & {
|
||||
asChild?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The title text for the node. To maintain a native application feel, the title
|
||||
* text is not selectable.
|
||||
*/
|
||||
export const NodeHeaderTitle = forwardRef<
|
||||
HTMLHeadingElement,
|
||||
NodeHeaderTitleProps
|
||||
>(({ className, asChild, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "h3";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
{...props}
|
||||
className={cn(className, "user-select-none flex-1 font-semibold")}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
NodeHeaderTitle.displayName = "NodeHeaderTitle";
|
||||
|
||||
/* NODE HEADER ICON --------------------------------------------------------- */
|
||||
|
||||
export type NodeHeaderIconProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const NodeHeaderIcon = forwardRef<HTMLSpanElement, NodeHeaderIconProps>(
|
||||
({ className, ...props }, ref) => {
|
||||
return (
|
||||
<span ref={ref} {...props} className={cn(className, "[&>*]:size-5")} />
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
NodeHeaderIcon.displayName = "NodeHeaderIcon";
|
||||
|
||||
/* NODE HEADER ACTIONS ------------------------------------------------------ */
|
||||
|
||||
export type NodeHeaderActionsProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
/**
|
||||
* A container for right-aligned action buttons in the node header.
|
||||
*/
|
||||
export const NodeHeaderActions = forwardRef<
|
||||
HTMLDivElement,
|
||||
NodeHeaderActionsProps
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
{...props}
|
||||
className={cn(
|
||||
"ml-auto flex items-center gap-1 justify-self-end",
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
NodeHeaderActions.displayName = "NodeHeaderActions";
|
||||
|
||||
/* NODE HEADER ACTION ------------------------------------------------------- */
|
||||
|
||||
export type NodeHeaderActionProps = React.ComponentProps<"button"> & {
|
||||
label: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A thin wrapper around the `<Button />` component with a fixed sized suitable
|
||||
* for icons.
|
||||
*
|
||||
* Because the `<NodeHeaderAction />` component is intended to render icons, it's
|
||||
* important to provide a meaningful and accessible `label` prop that describes
|
||||
* the action.
|
||||
*/
|
||||
export const NodeHeaderAction = forwardRef<
|
||||
HTMLButtonElement,
|
||||
NodeHeaderActionProps
|
||||
>(({ className, label, title, ...props }, ref) => {
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
aria-label={label}
|
||||
title={title ?? label}
|
||||
className={cn(className, "nodrag size-6 p-1")}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
NodeHeaderAction.displayName = "NodeHeaderAction";
|
||||
|
||||
//
|
||||
|
||||
export type NodeHeaderMenuActionProps = Omit<
|
||||
NodeHeaderActionProps,
|
||||
"onClick"
|
||||
> & {
|
||||
trigger?: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders a header action that opens a dropdown menu when clicked. The dropdown
|
||||
* trigger is a button with an ellipsis icon. The trigger's content can be changed
|
||||
* by using the `trigger` prop.
|
||||
*
|
||||
* Any children passed to the `<NodeHeaderMenuAction />` component will be rendered
|
||||
* inside the dropdown menu. You can read the docs for the shadcn dropdown menu
|
||||
* here: https://ui.shadcn.com/docs/components/dropdown-menu
|
||||
*
|
||||
*/
|
||||
export const NodeHeaderMenuAction = forwardRef<
|
||||
HTMLButtonElement,
|
||||
NodeHeaderMenuActionProps
|
||||
>(({ trigger, children, ...props }, ref) => {
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<NodeHeaderAction ref={ref} {...props}>
|
||||
{trigger ?? <EllipsisVertical />}
|
||||
</NodeHeaderAction>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>{children}</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
});
|
||||
|
||||
NodeHeaderMenuAction.displayName = "NodeHeaderMenuAction";
|
||||
|
||||
/* NODE HEADER DELETE ACTION --------------------------------------- */
|
||||
|
||||
export const NodeHeaderDeleteAction = () => {
|
||||
const id = useNodeId();
|
||||
const { setNodes } = useReactFlow();
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
setNodes((prevNodes) => prevNodes.filter((node) => node.id !== id));
|
||||
}, [id, setNodes]);
|
||||
|
||||
return (
|
||||
<NodeHeaderAction onClick={handleClick} label="Delete node">
|
||||
<Trash />
|
||||
</NodeHeaderAction>
|
||||
);
|
||||
};
|
||||
|
||||
NodeHeaderDeleteAction.displayName = "NodeHeaderDeleteAction";
|
||||
292
ui/src/components/flow/nodes/StartCall.tsx
Normal file
292
ui/src/components/flow/nodes/StartCall.tsx
Normal file
|
|
@ -0,0 +1,292 @@
|
|||
import { NodeProps, NodeToolbar, Position } from "@xyflow/react";
|
||||
import { Edit, Play } from "lucide-react";
|
||||
import { memo, useState } from "react";
|
||||
|
||||
import { useWorkflow } from "@/app/workflow/[workflowId]/contexts/WorkflowContext";
|
||||
import { FlowNodeData } from "@/components/flow/types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
|
||||
import { NodeContent } from "./common/NodeContent";
|
||||
import { NodeEditDialog } from "./common/NodeEditDialog";
|
||||
import { useNodeHandlers } from "./common/useNodeHandlers";
|
||||
|
||||
interface StartCallEditFormProps {
|
||||
nodeData: FlowNodeData;
|
||||
prompt: string;
|
||||
setPrompt: (value: string) => void;
|
||||
isStatic: boolean;
|
||||
setIsStatic: (value: boolean) => void;
|
||||
name: string;
|
||||
setName: (value: string) => void;
|
||||
allowInterrupt: boolean;
|
||||
setAllowInterrupt: (value: boolean) => void;
|
||||
addGlobalPrompt: boolean;
|
||||
setAddGlobalPrompt: (value: boolean) => void;
|
||||
waitForUserResponse: boolean;
|
||||
setWaitForUserResponse: (value: boolean) => void;
|
||||
detectVoicemail: boolean;
|
||||
setDetectVoicemail: (value: boolean) => void;
|
||||
delayedStart: boolean;
|
||||
setDelayedStart: (value: boolean) => void;
|
||||
delayedStartDuration: number;
|
||||
setDelayedStartDuration: (value: number) => void;
|
||||
}
|
||||
|
||||
interface StartCallNodeProps extends NodeProps {
|
||||
data: FlowNodeData;
|
||||
}
|
||||
|
||||
export const StartCall = memo(({ data, selected, id }: StartCallNodeProps) => {
|
||||
const { open, setOpen, handleSaveNodeData } = useNodeHandlers({
|
||||
id,
|
||||
additionalData: { is_start: true }
|
||||
});
|
||||
const { saveWorkflow } = useWorkflow();
|
||||
|
||||
// Form state
|
||||
const [prompt, setPrompt] = useState(data.prompt ?? "");
|
||||
const [isStatic, setIsStatic] = useState(data.is_static ?? true);
|
||||
const [name, setName] = useState(data.name);
|
||||
const [allowInterrupt, setAllowInterrupt] = useState(data.allow_interrupt ?? true);
|
||||
const [addGlobalPrompt, setAddGlobalPrompt] = useState(data.add_global_prompt ?? true);
|
||||
const [waitForUserResponse, setWaitForUserResponse] = useState(data.wait_for_user_response ?? false);
|
||||
const [detectVoicemail, setDetectVoicemail] = useState(data.detect_voicemail ?? true);
|
||||
const [delayedStart, setDelayedStart] = useState(data.delayed_start ?? false);
|
||||
const [delayedStartDuration, setDelayedStartDuration] = useState(data.delayed_start_duration ?? 2);
|
||||
|
||||
const handleSave = async () => {
|
||||
handleSaveNodeData({
|
||||
...data,
|
||||
prompt,
|
||||
is_static: isStatic,
|
||||
name,
|
||||
allow_interrupt: allowInterrupt,
|
||||
add_global_prompt: addGlobalPrompt,
|
||||
wait_for_user_response: waitForUserResponse,
|
||||
detect_voicemail: detectVoicemail,
|
||||
delayed_start: delayedStart,
|
||||
delayed_start_duration: delayedStart ? delayedStartDuration : undefined
|
||||
});
|
||||
setOpen(false);
|
||||
// Save the workflow after updating node data with a small delay to ensure state is updated
|
||||
setTimeout(async () => {
|
||||
await saveWorkflow();
|
||||
}, 100);
|
||||
};
|
||||
|
||||
// Reset form state when dialog opens
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (newOpen) {
|
||||
setPrompt(data.prompt ?? "");
|
||||
setIsStatic(data.is_static ?? true);
|
||||
setName(data.name);
|
||||
setAllowInterrupt(data.allow_interrupt ?? true);
|
||||
setAddGlobalPrompt(data.add_global_prompt ?? true);
|
||||
setWaitForUserResponse(data.wait_for_user_response ?? false);
|
||||
setDetectVoicemail(data.detect_voicemail ?? true);
|
||||
setDelayedStart(data.delayed_start ?? false);
|
||||
setDelayedStartDuration(data.delayed_start_duration ?? 3);
|
||||
}
|
||||
setOpen(newOpen);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<NodeContent
|
||||
selected={selected}
|
||||
invalid={data.invalid}
|
||||
title="Start Call"
|
||||
icon={<Play />}
|
||||
bgColor="bg-green-300"
|
||||
hasSourceHandle={true}
|
||||
>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{data.prompt?.length > 30 ? `${data.prompt.substring(0, 30)}...` : data.prompt}
|
||||
</div>
|
||||
</NodeContent>
|
||||
|
||||
<NodeToolbar isVisible={selected} position={Position.Right}>
|
||||
<Button onClick={() => setOpen(true)} variant="outline" size="icon">
|
||||
<Edit />
|
||||
</Button>
|
||||
</NodeToolbar>
|
||||
|
||||
<NodeEditDialog
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
nodeData={data}
|
||||
title="Start Call"
|
||||
onSave={handleSave}
|
||||
>
|
||||
{open && (
|
||||
<StartCallEditForm
|
||||
nodeData={data}
|
||||
prompt={prompt}
|
||||
setPrompt={setPrompt}
|
||||
isStatic={isStatic}
|
||||
setIsStatic={setIsStatic}
|
||||
name={name}
|
||||
setName={setName}
|
||||
allowInterrupt={allowInterrupt}
|
||||
setAllowInterrupt={setAllowInterrupt}
|
||||
addGlobalPrompt={addGlobalPrompt}
|
||||
setAddGlobalPrompt={setAddGlobalPrompt}
|
||||
waitForUserResponse={waitForUserResponse}
|
||||
setWaitForUserResponse={setWaitForUserResponse}
|
||||
detectVoicemail={detectVoicemail}
|
||||
setDetectVoicemail={setDetectVoicemail}
|
||||
delayedStart={delayedStart}
|
||||
setDelayedStart={setDelayedStart}
|
||||
delayedStartDuration={delayedStartDuration}
|
||||
setDelayedStartDuration={setDelayedStartDuration}
|
||||
/>
|
||||
)}
|
||||
</NodeEditDialog>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
const StartCallEditForm = ({
|
||||
prompt,
|
||||
setPrompt,
|
||||
isStatic,
|
||||
setIsStatic,
|
||||
name,
|
||||
setName,
|
||||
allowInterrupt,
|
||||
setAllowInterrupt,
|
||||
addGlobalPrompt,
|
||||
setAddGlobalPrompt,
|
||||
waitForUserResponse,
|
||||
setWaitForUserResponse,
|
||||
detectVoicemail,
|
||||
setDetectVoicemail,
|
||||
delayedStart,
|
||||
setDelayedStart,
|
||||
delayedStartDuration,
|
||||
setDelayedStartDuration
|
||||
}: StartCallEditFormProps) => {
|
||||
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<Label>Name</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
The name of the agent that will be used to identify the agent in the call logs. It should be short and should identify the step in the call.
|
||||
</Label>
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
|
||||
<Label>{isStatic ? "Text" : "Prompt"}</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
What would you like the agent to say when the call starts? Its a good idea to have a static greeting that can be used to identify the call.
|
||||
</Label>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch id="static-text" checked={isStatic} onCheckedChange={setIsStatic} />
|
||||
<Label htmlFor="static-text">Static Text</Label>
|
||||
</div>
|
||||
<Textarea
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
className="min-h-[100px] max-h-[300px] resize-none"
|
||||
style={{
|
||||
overflowY: 'auto'
|
||||
}}
|
||||
placeholder={isStatic ? "Hello, welcome to Dograh. How can I help you today?" : "Enter a dynamic prompt"}
|
||||
/>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch id="allow-interrupt" checked={allowInterrupt} onCheckedChange={setAllowInterrupt} />
|
||||
<Label htmlFor="allow-interrupt">Allow Interruption</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Whether you would like user to be able to interrupt the bot.
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="add-global-prompt"
|
||||
checked={addGlobalPrompt}
|
||||
onCheckedChange={setAddGlobalPrompt}
|
||||
disabled={isStatic}
|
||||
/>
|
||||
<Label htmlFor="add-global-prompt" className={isStatic ? "opacity-50" : ""}>
|
||||
Add Global Prompt
|
||||
</Label>
|
||||
<Label className={`text-xs text-gray-500 ${isStatic ? "opacity-50" : ""}`}>
|
||||
{isStatic
|
||||
? "Not applicable for static text"
|
||||
: "Whether you want to add global prompt with this node's prompt."}
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="wait-for-user-response"
|
||||
checked={waitForUserResponse}
|
||||
onCheckedChange={setWaitForUserResponse}
|
||||
disabled={!isStatic}
|
||||
/>
|
||||
<Label htmlFor="wait-for-user-response" className={!isStatic ? "opacity-50" : ""}>
|
||||
Wait for user's response
|
||||
</Label>
|
||||
<Label className={`text-xs text-gray-500 ${!isStatic ? "opacity-50" : ""}`}>
|
||||
{!isStatic
|
||||
? "Only applicable for static text"
|
||||
: "Wait for user to respond before disconnecting the call."}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="detect-voicemail"
|
||||
checked={detectVoicemail}
|
||||
onCheckedChange={setDetectVoicemail}
|
||||
/>
|
||||
<Label htmlFor="detect-voicemail">
|
||||
Detect Voicemail
|
||||
</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Automatically detect and end call if voicemail is reached.
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="delayed-start"
|
||||
checked={delayedStart}
|
||||
onCheckedChange={setDelayedStart}
|
||||
/>
|
||||
<Label htmlFor="delayed-start">
|
||||
Delayed Start
|
||||
</Label>
|
||||
<Label className="text-xs text-gray-500">
|
||||
Introduce a delay before the agent starts speaking.
|
||||
</Label>
|
||||
</div>
|
||||
{delayedStart && (
|
||||
<div className="ml-6 flex items-center space-x-2">
|
||||
<Label htmlFor="delay-duration" className="text-sm">
|
||||
Delay (seconds):
|
||||
</Label>
|
||||
<Input
|
||||
id="delay-duration"
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="0.1"
|
||||
max="10"
|
||||
value={delayedStartDuration}
|
||||
onChange={(e) => setDelayedStartDuration(parseFloat(e.target.value) || 3)}
|
||||
className="w-20"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
StartCall.displayName = "StartCall";
|
||||
44
ui/src/components/flow/nodes/common/NodeContent.tsx
Normal file
44
ui/src/components/flow/nodes/common/NodeContent.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { Position } from "@xyflow/react";
|
||||
import { ReactNode } from "react";
|
||||
|
||||
import { BaseHandle } from "@/components/flow/nodes/BaseHandle";
|
||||
import { BaseNode } from "@/components/flow/nodes/BaseNode";
|
||||
import { NodeHeader, NodeHeaderIcon, NodeHeaderTitle } from "@/components/flow/nodes/NodeHeader";
|
||||
|
||||
interface NodeContentProps {
|
||||
selected: boolean;
|
||||
invalid?: boolean;
|
||||
title: string;
|
||||
icon: ReactNode;
|
||||
bgColor: string;
|
||||
hasSourceHandle?: boolean;
|
||||
hasTargetHandle?: boolean;
|
||||
children?: ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const NodeContent = ({
|
||||
selected,
|
||||
invalid,
|
||||
title,
|
||||
icon,
|
||||
bgColor,
|
||||
hasSourceHandle = false,
|
||||
hasTargetHandle = false,
|
||||
children,
|
||||
className = "",
|
||||
}: NodeContentProps) => {
|
||||
return (
|
||||
<BaseNode selected={selected} invalid={invalid} className={`p-0 overflow-hidden ${className}`}>
|
||||
{hasTargetHandle && <BaseHandle type="target" position={Position.Top} />}
|
||||
<NodeHeader className={`px-3 py-2 border-b ${bgColor}`}>
|
||||
<NodeHeaderIcon>{icon}</NodeHeaderIcon>
|
||||
<NodeHeaderTitle>{title}</NodeHeaderTitle>
|
||||
</NodeHeader>
|
||||
<div className="p-3">
|
||||
{children}
|
||||
</div>
|
||||
{hasSourceHandle && <BaseHandle type="source" position={Position.Bottom} />}
|
||||
</BaseNode>
|
||||
);
|
||||
};
|
||||
63
ui/src/components/flow/nodes/common/NodeEditDialog.tsx
Normal file
63
ui/src/components/flow/nodes/common/NodeEditDialog.tsx
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { AlertCircle } from "lucide-react";
|
||||
import { ReactNode } from "react";
|
||||
|
||||
import { FlowNodeData } from "@/components/flow/types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
|
||||
interface NodeEditDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
nodeData: FlowNodeData;
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
onSave?: () => void;
|
||||
}
|
||||
|
||||
export const NodeEditDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
nodeData,
|
||||
title,
|
||||
children,
|
||||
onSave
|
||||
}: NodeEditDialogProps) => {
|
||||
const handleClose = () => onOpenChange(false);
|
||||
|
||||
const handleSave = () => {
|
||||
if (onSave) {
|
||||
onSave();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
className="max-h-[85vh] overflow-y-auto"
|
||||
style={{ maxWidth: "1200px", width: "95vw" }}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure the settings for this node in your workflow.
|
||||
</DialogDescription>
|
||||
{nodeData.invalid && nodeData.validationMessage && (
|
||||
<div className="mt-2 flex items-center gap-2 rounded-md bg-red-50 p-2 text-sm text-red-500 border border-red-200">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<span>{nodeData.validationMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
{children}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" onClick={handleClose}>Cancel</Button>
|
||||
<Button onClick={handleSave}>Save</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
39
ui/src/components/flow/nodes/common/useNodeHandlers.ts
Normal file
39
ui/src/components/flow/nodes/common/useNodeHandlers.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { useReactFlow } from "@xyflow/react";
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
import { FlowEdge, FlowNode, FlowNodeData } from "@/components/flow/types";
|
||||
|
||||
interface UseNodeHandlersProps {
|
||||
id: string;
|
||||
additionalData?: Record<string, string | boolean>;
|
||||
}
|
||||
|
||||
export const useNodeHandlers = ({ id, additionalData = {} }: UseNodeHandlersProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { setNodes } = useReactFlow<FlowNode, FlowEdge>();
|
||||
|
||||
const handleSaveNodeData = useCallback(
|
||||
(updatedData: FlowNodeData) => {
|
||||
setNodes((nodes) => {
|
||||
const updatedNodes = nodes.map((node) =>
|
||||
node.id === id
|
||||
? { ...node, data: { ...node.data, ...updatedData, ...additionalData } }
|
||||
: node
|
||||
);
|
||||
return updatedNodes;
|
||||
});
|
||||
},
|
||||
[id, setNodes, additionalData]
|
||||
);
|
||||
|
||||
const handleDeleteNode = useCallback(() => {
|
||||
setNodes((nodes) => nodes.filter((node) => node.id !== id));
|
||||
}, [id, setNodes]);
|
||||
|
||||
return {
|
||||
open,
|
||||
setOpen,
|
||||
handleSaveNodeData,
|
||||
handleDeleteNode,
|
||||
};
|
||||
};
|
||||
4
ui/src/components/flow/nodes/index.ts
Normal file
4
ui/src/components/flow/nodes/index.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export * from './AgentNode';
|
||||
export * from './EndCall';
|
||||
export * from './GlobalNode';
|
||||
export * from './StartCall';
|
||||
86
ui/src/components/flow/types.ts
Normal file
86
ui/src/components/flow/types.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
export enum NodeType {
|
||||
START_CALL = 'startCall',
|
||||
AGENT_NODE = 'agentNode',
|
||||
END_CALL = 'endCall',
|
||||
GLOBAL_NODE = 'globalNode'
|
||||
}
|
||||
|
||||
export type FlowNodeData = {
|
||||
prompt: string;
|
||||
name: string;
|
||||
is_start?: boolean;
|
||||
is_static?: boolean;
|
||||
is_end?: boolean;
|
||||
invalid?: boolean;
|
||||
validationMessage?: string | null;
|
||||
allow_interrupt?: boolean;
|
||||
extraction_enabled?: boolean;
|
||||
extraction_prompt?: string;
|
||||
extraction_variables?: ExtractionVariable[];
|
||||
add_global_prompt?: boolean;
|
||||
wait_for_user_response?: boolean;
|
||||
wait_for_user_response_timeout?: number;
|
||||
wait_for_user_greeting?: boolean;
|
||||
detect_voicemail?: boolean;
|
||||
delayed_start?: boolean;
|
||||
delayed_start_duration?: number;
|
||||
}
|
||||
|
||||
export type FlowNode = {
|
||||
id: string;
|
||||
type: string;
|
||||
position: { x: number; y: number };
|
||||
data: FlowNodeData;
|
||||
measured?: {
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
selected?: boolean;
|
||||
dragging?: boolean;
|
||||
};
|
||||
|
||||
export type FlowEdgeData = {
|
||||
condition: string;
|
||||
label: string;
|
||||
invalid?: boolean;
|
||||
validationMessage?: string | null;
|
||||
}
|
||||
|
||||
export type FlowEdge = {
|
||||
id: string;
|
||||
source: string;
|
||||
target: string;
|
||||
type?: string;
|
||||
data: FlowEdgeData;
|
||||
animated?: boolean;
|
||||
invalid?: boolean;
|
||||
};
|
||||
|
||||
export interface WorkflowDefinition {
|
||||
nodes: FlowNode[];
|
||||
edges: FlowEdge[];
|
||||
viewport: {
|
||||
x: number;
|
||||
y: number;
|
||||
zoom: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface WorkflowData {
|
||||
name: string;
|
||||
workflow_definition: WorkflowDefinition;
|
||||
}
|
||||
|
||||
export type WorkflowValidationError = {
|
||||
kind: 'node' | 'edge' | 'workflow';
|
||||
id: string;
|
||||
field: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type ExtractionVariable = {
|
||||
name: string;
|
||||
type: 'string' | 'number' | 'boolean';
|
||||
prompt?: string;
|
||||
};
|
||||
|
||||
138
ui/src/components/header/BaseHeader.tsx
Normal file
138
ui/src/components/header/BaseHeader.tsx
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
"use client";
|
||||
|
||||
import { CircleDollarSign, Loader2 } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import React from 'react';
|
||||
|
||||
import { useUserConfig } from '@/context/UserConfigContext';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
|
||||
// Conditionally load Stack components only when using Stack auth
|
||||
const StackUserButton = React.lazy(() =>
|
||||
import('@stackframe/stack').then(mod => ({ default: mod.UserButton }))
|
||||
);
|
||||
const StackTeamSwitcher = React.lazy(() =>
|
||||
import('@stackframe/stack').then(mod => ({ default: mod.SelectedTeamSwitcher }))
|
||||
);
|
||||
|
||||
interface BaseHeaderProps {
|
||||
headerActions?: React.ReactNode,
|
||||
backButton?: React.ReactNode,
|
||||
showFeaturesNav?: boolean
|
||||
}
|
||||
|
||||
export default function BaseHeader({ headerActions, backButton, showFeaturesNav = true }: BaseHeaderProps) {
|
||||
const { loading, permissions } = useUserConfig();
|
||||
const { provider, user } = useAuth();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
|
||||
const isActive = (path: string) => {
|
||||
return pathname.startsWith(path);
|
||||
};
|
||||
|
||||
const hasAdminPermission = Array.isArray(permissions) && permissions.some(p => p.id === 'admin');
|
||||
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-50 w-full border-b border-gray-200 bg-white">
|
||||
<div className="container mx-auto px-4 py-4">
|
||||
<nav className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link href="/" className="text-xl font-semibold text-gray-800 hover:text-gray-600">
|
||||
Dograh
|
||||
</Link>
|
||||
{backButton}
|
||||
{showFeaturesNav && (
|
||||
<div className="flex items-center gap-4 ml-8">
|
||||
{hasAdminPermission && (
|
||||
<>
|
||||
<Link
|
||||
href="/workflow"
|
||||
className={`text-sm font-medium transition-colors hover:text-primary ${isActive('/workflow') ? 'text-primary' : 'text-gray-600'
|
||||
}`}
|
||||
>
|
||||
Workflows
|
||||
</Link>
|
||||
<Link
|
||||
href="/campaigns"
|
||||
className={`text-sm font-medium transition-colors hover:text-primary ${isActive('/campaigns') ? 'text-primary' : 'text-gray-600'
|
||||
}`}
|
||||
>
|
||||
Campaigns
|
||||
</Link>
|
||||
<Link
|
||||
href="/automation"
|
||||
className={`text-sm font-medium transition-colors hover:text-primary ${isActive('/automation') ? 'text-primary' : 'text-gray-600'
|
||||
}`}
|
||||
>
|
||||
Automation
|
||||
</Link>
|
||||
<Link
|
||||
href="/looptalk"
|
||||
className={`text-sm font-medium transition-colors hover:text-primary ${isActive('/looptalk') ? 'text-primary' : 'text-gray-600'
|
||||
}`}
|
||||
>
|
||||
LoopTalk
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
<Link
|
||||
href="/usage"
|
||||
className={`text-sm font-medium transition-colors hover:text-primary ${isActive('/usage') ? 'text-primary' : 'text-gray-600'
|
||||
}`}
|
||||
>
|
||||
Usage
|
||||
</Link>
|
||||
<Link
|
||||
href="/reports"
|
||||
className={`text-sm font-medium transition-colors hover:text-primary ${isActive('/reports') ? 'text-primary' : 'text-gray-600'
|
||||
}`}
|
||||
>
|
||||
Reports
|
||||
</Link>
|
||||
<Link
|
||||
href="/api-keys"
|
||||
className={`text-sm font-medium transition-colors hover:text-primary ${isActive('/api-keys') ? 'text-primary' : 'text-gray-600'
|
||||
}`}
|
||||
>
|
||||
Developers
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 flex justify-center">
|
||||
{headerActions}
|
||||
</div>
|
||||
|
||||
{/* Use key to force remount when user changes to avoid hooks issues */}
|
||||
<div className="flex items-center gap-5" key={user ? 'logged-in' : 'logged-out'}>
|
||||
{provider === 'stack' ? (
|
||||
<React.Suspense fallback={<Loader2 className="w-5 h-5 animate-spin text-gray-600" />}>
|
||||
{!loading && (
|
||||
<StackTeamSwitcher
|
||||
onChange={() => {
|
||||
router.refresh();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<StackUserButton
|
||||
extraItems={[{
|
||||
text: 'Usage',
|
||||
icon: <CircleDollarSign strokeWidth={2} size={16} />,
|
||||
onClick: () => router.push('/usage')
|
||||
}]}
|
||||
/>
|
||||
</React.Suspense>
|
||||
) : (
|
||||
<div className="text-sm text-gray-600">
|
||||
Github Star Link
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
130
ui/src/components/looptalk/ConversationsList.tsx
Normal file
130
ui/src/components/looptalk/ConversationsList.tsx
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
'use client';
|
||||
|
||||
import { format } from 'date-fns';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { getTestSessionConversationApiV1LooptalkTestSessionsTestSessionIdConversationGet } from '@/client/sdk.gen';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import logger from '@/lib/logger';
|
||||
|
||||
import { Conversation } from './types';
|
||||
|
||||
interface ConversationsListProps {
|
||||
testSessionId: number;
|
||||
}
|
||||
|
||||
export function ConversationsList({ testSessionId }: ConversationsListProps) {
|
||||
const [conversations, setConversations] = useState<Conversation[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { user, getAccessToken } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchConversations = async () => {
|
||||
if (!user) return;
|
||||
try {
|
||||
const accessToken = await getAccessToken();
|
||||
const response = await getTestSessionConversationApiV1LooptalkTestSessionsTestSessionIdConversationGet({
|
||||
path: {
|
||||
test_session_id: testSessionId
|
||||
},
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
// API returns { conversation: Conversation | null }
|
||||
const responseData = response.data as { conversation: Conversation | null } | null;
|
||||
|
||||
if (responseData?.conversation) {
|
||||
setConversations([responseData.conversation]);
|
||||
} else {
|
||||
setConversations([]);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('Error fetching conversations:', err);
|
||||
setError('Failed to load conversations');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchConversations();
|
||||
|
||||
// Poll for updates every 5 seconds
|
||||
const interval = setInterval(fetchConversations, 5000);
|
||||
return () => clearInterval(interval);
|
||||
}, [testSessionId, user, getAccessToken]);
|
||||
|
||||
if (loading && conversations.length === 0) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{Array.from({ length: 3 }, (_, i) => (
|
||||
<Card key={i} className="h-24 bg-gray-200 animate-pulse" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-red-500">
|
||||
{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (conversations.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="text-center py-8">
|
||||
<div className="text-gray-500 mb-2">
|
||||
No conversations started yet
|
||||
</div>
|
||||
<p className="text-sm text-gray-400">
|
||||
Start the test session to begin agent conversations
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const getStatusBadgeVariant = (status: string) => {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return 'default';
|
||||
case 'completed':
|
||||
return 'secondary';
|
||||
case 'failed':
|
||||
return 'destructive';
|
||||
default:
|
||||
return 'outline';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{conversations.map((conversation) => (
|
||||
<Card key={conversation.id}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-lg">
|
||||
Conversation {conversation.conversation_pair_id || conversation.id}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Started: {format(new Date(conversation.created_at), 'h:mm:ss a')}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant={getStatusBadgeVariant(conversation.status)}>
|
||||
{conversation.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
181
ui/src/components/looptalk/CreateTestSessionButton.tsx
Normal file
181
ui/src/components/looptalk/CreateTestSessionButton.tsx
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
'use client';
|
||||
|
||||
import { Plus } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { createTestSessionApiV1LooptalkTestSessionsPost } from '@/client/sdk.gen';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import logger from '@/lib/logger';
|
||||
|
||||
export function CreateTestSessionButton() {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { user, getAccessToken } = useAuth();
|
||||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
description: '',
|
||||
test_type: 'single',
|
||||
actor_workflow_id: '',
|
||||
adversary_workflow_id: '',
|
||||
concurrent_pairs: 1,
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
if (!user) return;
|
||||
const accessToken = await getAccessToken();
|
||||
const response = await createTestSessionApiV1LooptalkTestSessionsPost({
|
||||
body: {
|
||||
name: formData.name,
|
||||
actor_workflow_id: parseInt(formData.actor_workflow_id),
|
||||
adversary_workflow_id: parseInt(formData.adversary_workflow_id),
|
||||
config: {
|
||||
test_type: formData.test_type,
|
||||
description: formData.description,
|
||||
concurrent_pairs: formData.test_type === 'load_test' ? formData.concurrent_pairs : undefined
|
||||
}
|
||||
},
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
toast.success('Test session created successfully');
|
||||
setOpen(false);
|
||||
if (response.data?.id) {
|
||||
router.push(`/looptalk/${response.data.id}`);
|
||||
} else {
|
||||
router.push('/looptalk');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error creating test session:', error);
|
||||
toast.error('Failed to create test session');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Test Session
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[525px]">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create Test Session</DialogTitle>
|
||||
<DialogDescription>
|
||||
Set up a new LoopTalk test session to test conversations between agents.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="name">Test Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
placeholder="My Test Session"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="description">Description</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
value={formData.description}
|
||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||
placeholder="Optional description of the test"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="test_type">Test Type</Label>
|
||||
<Select
|
||||
value={formData.test_type}
|
||||
onValueChange={(value) => setFormData({ ...formData, test_type: value })}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="single">Single Test</SelectItem>
|
||||
{/* <SelectItem value="load_test">Load Test</SelectItem> */}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="actor_workflow">Actor Workflow ID</Label>
|
||||
<Input
|
||||
id="actor_workflow"
|
||||
type="number"
|
||||
value={formData.actor_workflow_id}
|
||||
onChange={(e) => setFormData({ ...formData, actor_workflow_id: e.target.value })}
|
||||
placeholder="Enter workflow ID"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="adversary_workflow">Adversary Workflow ID</Label>
|
||||
<Input
|
||||
id="adversary_workflow"
|
||||
type="number"
|
||||
value={formData.adversary_workflow_id}
|
||||
onChange={(e) => setFormData({ ...formData, adversary_workflow_id: e.target.value })}
|
||||
placeholder="Enter workflow ID"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{formData.test_type === 'load_test' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="concurrent_pairs">Concurrent Pairs</Label>
|
||||
<Input
|
||||
id="concurrent_pairs"
|
||||
type="number"
|
||||
min="1"
|
||||
max="10"
|
||||
value={formData.concurrent_pairs}
|
||||
onChange={(e) => setFormData({ ...formData, concurrent_pairs: parseInt(e.target.value) || 1 })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? 'Creating...' : 'Create Test Session'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
370
ui/src/components/looptalk/LiveAudioPlayer.tsx
Normal file
370
ui/src/components/looptalk/LiveAudioPlayer.tsx
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
'use client';
|
||||
|
||||
import { Pause, Play, Volume2, VolumeX } from 'lucide-react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import logger from '@/lib/logger';
|
||||
|
||||
interface LiveAudioPlayerProps {
|
||||
testSessionId: number;
|
||||
sessionStatus: 'pending' | 'running' | 'completed' | 'failed';
|
||||
autoStart?: boolean;
|
||||
}
|
||||
|
||||
type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'error';
|
||||
type AudioRole = 'mixed' | 'actor' | 'adversary';
|
||||
|
||||
export function LiveAudioPlayer({
|
||||
testSessionId,
|
||||
sessionStatus,
|
||||
autoStart = false
|
||||
}: LiveAudioPlayerProps) {
|
||||
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('disconnected');
|
||||
const [audioRole, setAudioRole] = useState<AudioRole>(() => {
|
||||
// Load saved preference from localStorage
|
||||
if (typeof window !== 'undefined') {
|
||||
const saved = localStorage.getItem('looptalk-audio-role');
|
||||
return (saved as AudioRole) || 'mixed';
|
||||
}
|
||||
return 'mixed';
|
||||
});
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
const [volume, setVolume] = useState(0.8);
|
||||
const [bufferedDuration, setBufferedDuration] = useState(0);
|
||||
const [audioLevel, setAudioLevel] = useState(0);
|
||||
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const gainNodeRef = useRef<GainNode | null>(null);
|
||||
const analyserRef = useRef<AnalyserNode | null>(null);
|
||||
const audioQueueRef = useRef<AudioBufferSourceNode[]>([]);
|
||||
const nextStartTimeRef = useRef(0);
|
||||
const animationFrameRef = useRef<number | undefined>(undefined);
|
||||
const isConnectingRef = useRef(false);
|
||||
const { user, getAccessToken } = useAuth();
|
||||
|
||||
// Auto-start streaming when session starts
|
||||
useEffect(() => {
|
||||
if (sessionStatus === 'running' && autoStart && !isPlaying) {
|
||||
setIsPlaying(true);
|
||||
}
|
||||
}, [sessionStatus, autoStart, isPlaying]);
|
||||
|
||||
// Save audio role preference
|
||||
useEffect(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('looptalk-audio-role', audioRole);
|
||||
}
|
||||
}, [audioRole]);
|
||||
|
||||
// Audio level monitoring
|
||||
const monitorAudioLevel = useCallback(() => {
|
||||
if (!analyserRef.current) return;
|
||||
|
||||
const dataArray = new Uint8Array(analyserRef.current.frequencyBinCount);
|
||||
analyserRef.current.getByteFrequencyData(dataArray);
|
||||
|
||||
// Calculate average level
|
||||
const average = dataArray.reduce((a, b) => a + b, 0) / dataArray.length;
|
||||
setAudioLevel(average / 255); // Normalize to 0-1
|
||||
|
||||
animationFrameRef.current = requestAnimationFrame(monitorAudioLevel);
|
||||
}, []);
|
||||
|
||||
const connectWebSocket = useCallback(async () => {
|
||||
// Check if already connected or connecting
|
||||
if (wsRef.current && (wsRef.current.readyState === WebSocket.OPEN || wsRef.current.readyState === WebSocket.CONNECTING)) {
|
||||
logger.debug('WebSocket already connected or connecting, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
// Prevent multiple concurrent connection attempts
|
||||
if (isConnectingRef.current) {
|
||||
logger.debug('Already attempting to connect, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
isConnectingRef.current = true;
|
||||
|
||||
try {
|
||||
setConnectionStatus('connecting');
|
||||
|
||||
if (!user) return;
|
||||
// Get auth token
|
||||
const accessToken = await getAccessToken();
|
||||
|
||||
// Create WebSocket connection
|
||||
const baseUrl = process.env.NEXT_PUBLIC_BACKEND_URL?.replace('http', 'ws') || 'ws://localhost:8000';
|
||||
const wsUrl = `${baseUrl}/api/v1/looptalk/test-sessions/${testSessionId}/audio-stream?role=${audioRole}&token=${encodeURIComponent(accessToken || '')}`;
|
||||
const ws = new WebSocket(wsUrl);
|
||||
wsRef.current = ws;
|
||||
|
||||
// Create AudioContext with gain control and analyser
|
||||
if (!audioContextRef.current) {
|
||||
audioContextRef.current = new AudioContext();
|
||||
gainNodeRef.current = audioContextRef.current.createGain();
|
||||
analyserRef.current = audioContextRef.current.createAnalyser();
|
||||
analyserRef.current.fftSize = 256;
|
||||
|
||||
// Connect gain -> analyser -> destination
|
||||
gainNodeRef.current.connect(analyserRef.current);
|
||||
analyserRef.current.connect(audioContextRef.current.destination);
|
||||
|
||||
// Set initial volume
|
||||
gainNodeRef.current.gain.value = volume;
|
||||
}
|
||||
|
||||
ws.onopen = () => {
|
||||
setConnectionStatus('connected');
|
||||
logger.info('Audio stream connected');
|
||||
monitorAudioLevel();
|
||||
};
|
||||
|
||||
ws.onmessage = async (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
if (data.type === 'audio' && data.audio) {
|
||||
// Decode base64 audio data
|
||||
const audioBytes = Uint8Array.from(atob(data.audio), c => c.charCodeAt(0));
|
||||
|
||||
// Create audio buffer from PCM data
|
||||
const samplesPerChannel = audioBytes.length / (data.num_channels * 2);
|
||||
const audioBuffer = audioContextRef.current!.createBuffer(
|
||||
data.num_channels,
|
||||
samplesPerChannel,
|
||||
data.sample_rate
|
||||
);
|
||||
|
||||
// Convert PCM to float samples
|
||||
const dataView = new DataView(audioBytes.buffer);
|
||||
for (let channel = 0; channel < data.num_channels; channel++) {
|
||||
const channelData = audioBuffer.getChannelData(channel);
|
||||
for (let i = 0; i < samplesPerChannel; i++) {
|
||||
const sampleIndex = i * data.num_channels + channel;
|
||||
const sample = dataView.getInt16(sampleIndex * 2, true) / 32768.0;
|
||||
channelData[i] = sample;
|
||||
}
|
||||
}
|
||||
|
||||
// Schedule audio buffer playback
|
||||
const source = audioContextRef.current!.createBufferSource();
|
||||
source.buffer = audioBuffer;
|
||||
source.connect(gainNodeRef.current!);
|
||||
|
||||
// Schedule seamless playback
|
||||
const currentTime = audioContextRef.current!.currentTime;
|
||||
if (nextStartTimeRef.current < currentTime) {
|
||||
nextStartTimeRef.current = currentTime;
|
||||
}
|
||||
source.start(nextStartTimeRef.current);
|
||||
nextStartTimeRef.current += audioBuffer.duration;
|
||||
|
||||
// Track scheduled sources
|
||||
audioQueueRef.current.push(source);
|
||||
source.onended = () => {
|
||||
const index = audioQueueRef.current.indexOf(source);
|
||||
if (index > -1) {
|
||||
audioQueueRef.current.splice(index, 1);
|
||||
}
|
||||
};
|
||||
|
||||
setBufferedDuration(nextStartTimeRef.current - currentTime);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error processing audio data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = (error) => {
|
||||
logger.error('WebSocket error:', error);
|
||||
setConnectionStatus('error');
|
||||
};
|
||||
|
||||
ws.onclose = (event) => {
|
||||
setConnectionStatus('disconnected');
|
||||
logger.info('Audio stream disconnected', { code: event.code, reason: event.reason });
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
}
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error connecting to audio stream:', error);
|
||||
setConnectionStatus('error');
|
||||
} finally {
|
||||
isConnectingRef.current = false;
|
||||
}
|
||||
}, [testSessionId, audioRole, user, getAccessToken, volume, monitorAudioLevel]); // Removed connectionStatus to avoid loops
|
||||
|
||||
const disconnect = useCallback(() => {
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close();
|
||||
wsRef.current = null;
|
||||
}
|
||||
|
||||
// Stop all scheduled audio
|
||||
audioQueueRef.current.forEach(source => {
|
||||
try {
|
||||
source.stop();
|
||||
} catch {
|
||||
// Ignore if already stopped
|
||||
}
|
||||
});
|
||||
audioQueueRef.current = [];
|
||||
nextStartTimeRef.current = 0;
|
||||
setBufferedDuration(0);
|
||||
setAudioLevel(0);
|
||||
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Handle play/pause
|
||||
useEffect(() => {
|
||||
if (isPlaying && sessionStatus === 'running') {
|
||||
connectWebSocket();
|
||||
} else {
|
||||
disconnect();
|
||||
}
|
||||
|
||||
return () => {
|
||||
disconnect();
|
||||
};
|
||||
}, [isPlaying, sessionStatus, connectWebSocket, disconnect]); // Include stable callbacks
|
||||
|
||||
// Handle audio role changes
|
||||
useEffect(() => {
|
||||
// Use ref to check connection state to avoid dependency issues
|
||||
if (isPlaying && wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
||||
logger.info('Audio role changed, reconnecting with new role:', audioRole);
|
||||
// Reconnect with new role
|
||||
disconnect();
|
||||
// Set a flag to prevent double connections
|
||||
const timer = setTimeout(() => {
|
||||
if (isPlaying) {
|
||||
connectWebSocket();
|
||||
}
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [audioRole, isPlaying, connectWebSocket, disconnect]); // Include all dependencies
|
||||
|
||||
// Update volume
|
||||
useEffect(() => {
|
||||
if (gainNodeRef.current) {
|
||||
gainNodeRef.current.gain.value = volume;
|
||||
}
|
||||
}, [volume]);
|
||||
|
||||
|
||||
const getStatusColor = () => {
|
||||
switch (connectionStatus) {
|
||||
case 'connected': return 'bg-green-500';
|
||||
case 'connecting': return 'bg-yellow-500';
|
||||
case 'error': return 'bg-red-500';
|
||||
default: return 'bg-gray-500';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Volume2 className="h-5 w-5" />
|
||||
Live Audio Stream
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={`w-2 h-2 rounded-full ${getStatusColor()}`} />
|
||||
<Badge variant={connectionStatus === 'connected' ? 'default' : 'secondary'}>
|
||||
{connectionStatus}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Play/Pause Controls */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button
|
||||
onClick={() => setIsPlaying(!isPlaying)}
|
||||
disabled={sessionStatus !== 'running'}
|
||||
size="sm"
|
||||
variant={isPlaying ? 'default' : 'outline'}
|
||||
>
|
||||
{isPlaying ? (
|
||||
<>
|
||||
<Pause className="h-4 w-4 mr-2" />
|
||||
Pause
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="h-4 w-4 mr-2" />
|
||||
Play
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Audio Role Selector */}
|
||||
<div className="flex gap-1">
|
||||
{(['mixed', 'actor', 'adversary'] as const).map((role) => (
|
||||
<Button
|
||||
key={role}
|
||||
size="sm"
|
||||
variant={audioRole === role ? 'default' : 'outline'}
|
||||
onClick={() => setAudioRole(role)}
|
||||
className="capitalize"
|
||||
>
|
||||
{role}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Volume Control */}
|
||||
<div className="flex items-center gap-4">
|
||||
<VolumeX className="h-4 w-4 text-gray-500" />
|
||||
<input
|
||||
type="range"
|
||||
value={volume}
|
||||
onChange={(e) => setVolume(parseFloat(e.target.value))}
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.01"
|
||||
className="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
|
||||
/>
|
||||
<Volume2 className="h-4 w-4 text-gray-500" />
|
||||
</div>
|
||||
|
||||
{/* Audio Level Meter */}
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm text-gray-500">Audio Level</div>
|
||||
<div className="h-2 bg-gray-200 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-green-500 transition-all duration-100"
|
||||
style={{ width: `${audioLevel * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Status Info */}
|
||||
<div className="text-sm text-gray-500">
|
||||
{connectionStatus === 'connected' && (
|
||||
<>Streaming... (buffered: {bufferedDuration.toFixed(1)}s)</>
|
||||
)}
|
||||
{connectionStatus === 'connecting' && 'Connecting to audio stream...'}
|
||||
{connectionStatus === 'error' && 'Failed to connect to audio stream'}
|
||||
{connectionStatus === 'disconnected' && sessionStatus === 'running' && 'Click play to start streaming'}
|
||||
{sessionStatus === 'pending' && 'Waiting for session to start...'}
|
||||
{sessionStatus === 'completed' && 'Session completed'}
|
||||
{sessionStatus === 'failed' && 'Session failed'}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
103
ui/src/components/looptalk/LoopTalkTestSessionsList.tsx
Normal file
103
ui/src/components/looptalk/LoopTalkTestSessionsList.tsx
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { listTestSessionsApiV1LooptalkTestSessionsGet } from '@/client/sdk.gen';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import logger from '@/lib/logger';
|
||||
|
||||
import { TestSessionCard } from './TestSessionCard';
|
||||
import { TestSession } from './types';
|
||||
|
||||
interface LoopTalkTestSessionsListProps {
|
||||
status?: 'active' | 'completed' | 'failed';
|
||||
}
|
||||
|
||||
export function LoopTalkTestSessionsList({ status }: LoopTalkTestSessionsListProps) {
|
||||
const [sessions, setSessions] = useState<TestSession[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { user, getAccessToken } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSessions = async () => {
|
||||
if (!user) return;
|
||||
try {
|
||||
const accessToken = await getAccessToken();
|
||||
const response = await listTestSessionsApiV1LooptalkTestSessionsGet({
|
||||
query: status ? { status } : undefined,
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
// Transform API response to match UI types
|
||||
const transformedSessions = (response.data || []).map(session => ({
|
||||
id: session.id,
|
||||
name: session.name,
|
||||
description: '', // API doesn't return description
|
||||
test_type: session.test_index !== null ? 'load_test' : 'single',
|
||||
status: session.status,
|
||||
actor_workflow_name: `Workflow ${session.actor_workflow_id}`,
|
||||
adversary_workflow_name: `Workflow ${session.adversary_workflow_id}`,
|
||||
created_at: session.created_at,
|
||||
updated_at: session.created_at, // API doesn't have updated_at
|
||||
test_metadata: session.config
|
||||
}));
|
||||
|
||||
setSessions(transformedSessions);
|
||||
} catch (err) {
|
||||
logger.error('Error fetching test sessions:', err);
|
||||
setError('Failed to load test sessions');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchSessions();
|
||||
}, [status, user, getAccessToken]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 3 }, (_, i) => (
|
||||
<div key={i} className="bg-gray-200 rounded-lg h-40 animate-pulse"></div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-red-500">
|
||||
{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (sessions.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-12 px-4">
|
||||
<div className="text-gray-500 mb-2">
|
||||
No {status ? `${status} ` : ''}test sessions found
|
||||
</div>
|
||||
{!status && (
|
||||
<p className="text-sm text-gray-400">
|
||||
Create a new test session to start testing agent conversations
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{sessions.map((session) => (
|
||||
<TestSessionCard
|
||||
key={session.id}
|
||||
session={session}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
187
ui/src/components/looptalk/SimpleAudioPlayer.tsx
Normal file
187
ui/src/components/looptalk/SimpleAudioPlayer.tsx
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
'use client';
|
||||
|
||||
import { Volume2 } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import logger from '@/lib/logger';
|
||||
|
||||
interface SimpleAudioPlayerProps {
|
||||
testSessionId: number;
|
||||
}
|
||||
|
||||
export function SimpleAudioPlayer({ testSessionId }: SimpleAudioPlayerProps) {
|
||||
const [connectionStatus, setConnectionStatus] = useState<'connecting' | 'connected' | 'error'>('connecting');
|
||||
const [audioRole, setAudioRole] = useState<'mixed' | 'actor' | 'adversary'>('mixed');
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const [bufferedDuration, setBufferedDuration] = useState(0);
|
||||
const { user, getAccessToken } = useAuth();
|
||||
const audioQueueRef = useRef<AudioBufferSourceNode[]>([]);
|
||||
const nextStartTimeRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const connectWebSocket = async () => {
|
||||
try {
|
||||
if (!user) return;
|
||||
// Get auth token
|
||||
const accessToken = await getAccessToken();
|
||||
|
||||
// Create WebSocket connection - pass token as query param since WebSocket doesn't support headers
|
||||
const baseUrl = process.env.NEXT_PUBLIC_API_URL?.replace('http', 'ws') || 'ws://localhost:8000';
|
||||
const wsUrl = `${baseUrl}/api/v1/looptalk/test-sessions/${testSessionId}/audio-stream?role=${audioRole}&token=${encodeURIComponent(accessToken || '')}`;
|
||||
const ws = new WebSocket(wsUrl);
|
||||
wsRef.current = ws;
|
||||
|
||||
// Create AudioContext
|
||||
audioContextRef.current = new AudioContext();
|
||||
|
||||
ws.onopen = () => {
|
||||
setConnectionStatus('connected');
|
||||
};
|
||||
|
||||
ws.onmessage = async (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
if (data.type === 'audio' && data.audio) {
|
||||
// Decode base64 audio data
|
||||
const audioBytes = Uint8Array.from(atob(data.audio), c => c.charCodeAt(0));
|
||||
|
||||
// Create audio buffer from PCM data
|
||||
const samplesPerChannel = audioBytes.length / (data.num_channels * 2); // 16-bit samples
|
||||
const audioBuffer = audioContextRef.current!.createBuffer(
|
||||
data.num_channels,
|
||||
samplesPerChannel,
|
||||
data.sample_rate
|
||||
);
|
||||
|
||||
// Convert PCM to float samples for each channel
|
||||
const dataView = new DataView(audioBytes.buffer);
|
||||
for (let channel = 0; channel < data.num_channels; channel++) {
|
||||
const channelData = audioBuffer.getChannelData(channel);
|
||||
for (let i = 0; i < samplesPerChannel; i++) {
|
||||
// Interleaved PCM data: L,R,L,R,... for stereo
|
||||
const sampleIndex = i * data.num_channels + channel;
|
||||
const sample = dataView.getInt16(sampleIndex * 2, true) / 32768.0;
|
||||
channelData[i] = sample;
|
||||
}
|
||||
}
|
||||
|
||||
// Schedule audio buffer playback
|
||||
const source = audioContextRef.current!.createBufferSource();
|
||||
source.buffer = audioBuffer;
|
||||
source.connect(audioContextRef.current!.destination);
|
||||
|
||||
// Schedule seamless playback
|
||||
const currentTime = audioContextRef.current!.currentTime;
|
||||
if (nextStartTimeRef.current < currentTime) {
|
||||
nextStartTimeRef.current = currentTime;
|
||||
}
|
||||
source.start(nextStartTimeRef.current);
|
||||
nextStartTimeRef.current += audioBuffer.duration;
|
||||
|
||||
// Keep track of scheduled sources for cleanup
|
||||
audioQueueRef.current.push(source);
|
||||
source.onended = () => {
|
||||
const index = audioQueueRef.current.indexOf(source);
|
||||
if (index > -1) {
|
||||
audioQueueRef.current.splice(index, 1);
|
||||
}
|
||||
};
|
||||
|
||||
setBufferedDuration(prev => prev + audioBuffer.duration);
|
||||
} else if (data.type === 'keepalive') {
|
||||
// Connection is alive
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error processing audio data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = (error) => {
|
||||
logger.error('WebSocket error:', error);
|
||||
setConnectionStatus('error');
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
setConnectionStatus('error');
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error connecting to audio stream:', error);
|
||||
setConnectionStatus('error');
|
||||
}
|
||||
};
|
||||
|
||||
connectWebSocket();
|
||||
|
||||
// Cleanup
|
||||
return () => {
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close();
|
||||
}
|
||||
// Stop all scheduled audio
|
||||
audioQueueRef.current.forEach(source => {
|
||||
try {
|
||||
source.stop();
|
||||
} catch {
|
||||
// Ignore if already stopped
|
||||
}
|
||||
});
|
||||
audioQueueRef.current = [];
|
||||
nextStartTimeRef.current = 0;
|
||||
setBufferedDuration(0);
|
||||
if (audioContextRef.current) {
|
||||
audioContextRef.current.close();
|
||||
}
|
||||
};
|
||||
}, [testSessionId, audioRole, user, getAccessToken]);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-4">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Volume2 className="h-5 w-5 text-gray-600" />
|
||||
<span className="font-medium">Live Audio Stream</span>
|
||||
</div>
|
||||
<Badge variant={connectionStatus === 'connected' ? 'default' : connectionStatus === 'error' ? 'destructive' : 'secondary'}>
|
||||
{connectionStatus}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 mb-4">
|
||||
<button
|
||||
className={`px-3 py-1 rounded text-sm ${audioRole === 'mixed' ? 'bg-primary text-white' : 'bg-gray-200'}`}
|
||||
onClick={() => setAudioRole('mixed')}
|
||||
>
|
||||
Mixed
|
||||
</button>
|
||||
<button
|
||||
className={`px-3 py-1 rounded text-sm ${audioRole === 'actor' ? 'bg-primary text-white' : 'bg-gray-200'}`}
|
||||
onClick={() => setAudioRole('actor')}
|
||||
>
|
||||
Actor Only
|
||||
</button>
|
||||
<button
|
||||
className={`px-3 py-1 rounded text-sm ${audioRole === 'adversary' ? 'bg-primary text-white' : 'bg-gray-200'}`}
|
||||
onClick={() => setAudioRole('adversary')}
|
||||
>
|
||||
Adversary Only
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="text-sm text-gray-500">
|
||||
{connectionStatus === 'connected' && (
|
||||
<>Audio streaming... (buffered: {bufferedDuration.toFixed(1)}s)</>
|
||||
)}
|
||||
{connectionStatus === 'connecting' && 'Connecting to audio stream...'}
|
||||
{connectionStatus === 'error' && 'Failed to connect to audio stream'}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
103
ui/src/components/looptalk/TestSessionCard.tsx
Normal file
103
ui/src/components/looptalk/TestSessionCard.tsx
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
'use client';
|
||||
|
||||
import { format } from 'date-fns';
|
||||
import { Eye, Pause, Play, Users } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
|
||||
import { TestSession } from './types';
|
||||
|
||||
interface TestSessionCardProps {
|
||||
session: TestSession;
|
||||
}
|
||||
|
||||
export function TestSessionCard({ session }: TestSessionCardProps) {
|
||||
const router = useRouter();
|
||||
|
||||
const handleViewDetails = () => {
|
||||
router.push(`/looptalk/${session.id}`);
|
||||
};
|
||||
|
||||
const getStatusBadgeVariant = (status: string) => {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return 'default';
|
||||
case 'completed':
|
||||
return 'secondary';
|
||||
case 'failed':
|
||||
return 'destructive';
|
||||
default:
|
||||
return 'outline';
|
||||
}
|
||||
};
|
||||
|
||||
const getTestTypeIcon = (type: string) => {
|
||||
switch (type) {
|
||||
case 'load_test':
|
||||
return <Users className="h-4 w-4" />;
|
||||
default:
|
||||
return <Play className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="hover:shadow-lg transition-shadow cursor-pointer" onClick={handleViewDetails}>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<CardTitle className="text-lg">{session.name}</CardTitle>
|
||||
<Badge variant={getStatusBadgeVariant(session.status)}>
|
||||
{session.status}
|
||||
</Badge>
|
||||
</div>
|
||||
{session.description && (
|
||||
<CardDescription>{session.description}</CardDescription>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600">
|
||||
{getTestTypeIcon(session.test_type)}
|
||||
<span className="capitalize">{session.test_type.replace('_', ' ')}</span>
|
||||
</div>
|
||||
<div className="text-sm text-gray-500">
|
||||
Created: {format(new Date(session.created_at), 'MMM d, yyyy h:mm a')}
|
||||
</div>
|
||||
{session.test_metadata?.concurrent_pairs && (
|
||||
<div className="text-sm text-gray-600">
|
||||
Concurrent pairs: {session.test_metadata.concurrent_pairs}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-4 flex gap-2">
|
||||
{session.status === 'active' && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
// TODO: Implement pause functionality
|
||||
}}
|
||||
>
|
||||
<Pause className="h-4 w-4 mr-1" />
|
||||
Pause
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleViewDetails();
|
||||
}}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-1" />
|
||||
View
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
120
ui/src/components/looptalk/TestSessionControls.tsx
Normal file
120
ui/src/components/looptalk/TestSessionControls.tsx
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
'use client';
|
||||
|
||||
import { Play, RotateCcw, Square } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import {
|
||||
startTestSessionApiV1LooptalkTestSessionsTestSessionIdStartPost,
|
||||
stopTestSessionApiV1LooptalkTestSessionsTestSessionIdStopPost
|
||||
} from '@/client/sdk.gen';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import logger from '@/lib/logger';
|
||||
|
||||
interface TestSessionControlsProps {
|
||||
session: {
|
||||
id: number;
|
||||
status: string;
|
||||
test_type: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function TestSessionControls({ session }: TestSessionControlsProps) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { user, getAccessToken } = useAuth();
|
||||
|
||||
const handleStart = async () => {
|
||||
if (!user) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const accessToken = await getAccessToken();
|
||||
await startTestSessionApiV1LooptalkTestSessionsTestSessionIdStartPost({
|
||||
path: {
|
||||
test_session_id: session.id
|
||||
},
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
toast.success('Test session started');
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
logger.error('Error starting test session:', error);
|
||||
toast.error('Failed to start test session');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStop = async () => {
|
||||
if (!user) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const accessToken = await getAccessToken();
|
||||
await stopTestSessionApiV1LooptalkTestSessionsTestSessionIdStopPost({
|
||||
path: {
|
||||
test_session_id: session.id
|
||||
},
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
toast.success('Test session stopped');
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
logger.error('Error stopping test session:', error);
|
||||
toast.error('Failed to stop test session');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="mt-4">
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex gap-2">
|
||||
{session.status === 'pending' && (
|
||||
<Button
|
||||
onClick={handleStart}
|
||||
disabled={loading}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Play className="h-4 w-4" />
|
||||
Start Test
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{session.status === 'active' && (
|
||||
<>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleStop}
|
||||
disabled={loading}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Square className="h-4 w-4" />
|
||||
Stop Test
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{session.status === 'completed' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleStart}
|
||||
disabled={loading}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
Restart Test
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
71
ui/src/components/looptalk/TestSessionDetails.tsx
Normal file
71
ui/src/components/looptalk/TestSessionDetails.tsx
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
'use client';
|
||||
|
||||
import { format } from 'date-fns';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
|
||||
import { TestSession } from './types';
|
||||
|
||||
interface TestSessionDetailsProps {
|
||||
session: TestSession;
|
||||
}
|
||||
|
||||
export function TestSessionDetails({ session }: TestSessionDetailsProps) {
|
||||
const getStatusBadgeVariant = (status: string) => {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return 'default';
|
||||
case 'completed':
|
||||
return 'secondary';
|
||||
case 'failed':
|
||||
return 'destructive';
|
||||
default:
|
||||
return 'outline';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="text-2xl">{session.name}</CardTitle>
|
||||
{session.description && (
|
||||
<CardDescription className="mt-2">{session.description}</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
<Badge variant={getStatusBadgeVariant(session.status)} className="text-lg px-3 py-1">
|
||||
{session.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm text-gray-600 mb-1">Test Type</h3>
|
||||
<p className="capitalize">{session.test_type.replace('_', ' ')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm text-gray-600 mb-1">Created</h3>
|
||||
<p>{format(new Date(session.created_at), 'MMM d, yyyy h:mm a')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm text-gray-600 mb-1">Actor Workflow</h3>
|
||||
<p>{session.actor_workflow_name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm text-gray-600 mb-1">Adversary Workflow</h3>
|
||||
<p>{session.adversary_workflow_name}</p>
|
||||
</div>
|
||||
{session.test_metadata?.concurrent_pairs && (
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm text-gray-600 mb-1">Concurrent Pairs</h3>
|
||||
<p>{session.test_metadata.concurrent_pairs}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
24
ui/src/components/looptalk/types.ts
Normal file
24
ui/src/components/looptalk/types.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
export interface TestSession {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string;
|
||||
test_type: string;
|
||||
status: string;
|
||||
actor_workflow_name: string;
|
||||
adversary_workflow_name: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
test_metadata?: {
|
||||
concurrent_pairs?: number;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Conversation {
|
||||
id: number;
|
||||
test_session_id: number;
|
||||
conversation_pair_id?: string;
|
||||
status: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
45
ui/src/components/ui/badge.tsx
Normal file
45
ui/src/components/ui/badge.tsx
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
|
||||
outline: "text-foreground",
|
||||
success:
|
||||
"border-transparent bg-green-500 text-white hover:bg-green-600",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> { }
|
||||
|
||||
const Badge = React.forwardRef<HTMLDivElement, BadgeProps>(
|
||||
({ className, variant, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
Badge.displayName = "Badge"
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
59
ui/src/components/ui/button.tsx
Normal file
59
ui/src/components/ui/button.tsx
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer 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 shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs 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 shadow-xs 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",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
213
ui/src/components/ui/calendar.tsx
Normal file
213
ui/src/components/ui/calendar.tsx
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
"use client"
|
||||
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react"
|
||||
import * as React from "react"
|
||||
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
|
||||
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
captionLayout = "label",
|
||||
buttonVariant = "ghost",
|
||||
formatters,
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
return (
|
||||
<DayPicker
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn(
|
||||
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
formatters={{
|
||||
formatMonthDropdown: (date) =>
|
||||
date.toLocaleString("default", { month: "short" }),
|
||||
...formatters,
|
||||
}}
|
||||
classNames={{
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn(
|
||||
"flex gap-4 flex-col md:flex-row relative",
|
||||
defaultClassNames.months
|
||||
),
|
||||
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
|
||||
defaultClassNames.nav
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
|
||||
defaultClassNames.month_caption
|
||||
),
|
||||
dropdowns: cn(
|
||||
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
|
||||
defaultClassNames.dropdowns
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"absolute bg-popover inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
table: "w-full border-collapse",
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
|
||||
defaultClassNames.weekday
|
||||
),
|
||||
week: cn("flex w-full mt-2", defaultClassNames.week),
|
||||
week_number_header: cn(
|
||||
"select-none w-(--cell-size)",
|
||||
defaultClassNames.week_number_header
|
||||
),
|
||||
week_number: cn(
|
||||
"text-[0.8rem] select-none text-muted-foreground",
|
||||
defaultClassNames.week_number
|
||||
),
|
||||
day: cn(
|
||||
"relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn(
|
||||
"rounded-l-md bg-accent",
|
||||
defaultClassNames.range_start
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||
today: cn(
|
||||
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
|
||||
defaultClassNames.today
|
||||
),
|
||||
outside: cn(
|
||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||
defaultClassNames.outside
|
||||
),
|
||||
disabled: cn(
|
||||
"text-muted-foreground opacity-50",
|
||||
defaultClassNames.disabled
|
||||
),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
Root: ({ className, rootRef, ...props }) => {
|
||||
return (
|
||||
<div
|
||||
data-slot="calendar"
|
||||
ref={rootRef}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return (
|
||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
return (
|
||||
<ChevronRightIcon
|
||||
className={cn("size-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
},
|
||||
DayButton: CalendarDayButton,
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
return (
|
||||
<td {...props}>
|
||||
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||
{children}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CalendarDayButton({
|
||||
className,
|
||||
day,
|
||||
modifiers,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayButton>) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null)
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus()
|
||||
}, [modifiers.focused])
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-day={day.date.toLocaleDateString()}
|
||||
data-selected-single={
|
||||
modifiers.selected &&
|
||||
!modifiers.range_start &&
|
||||
!modifiers.range_end &&
|
||||
!modifiers.range_middle
|
||||
}
|
||||
data-range-start={modifiers.range_start}
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
79
ui/src/components/ui/card.tsx
Normal file
79
ui/src/components/ui/card.tsx
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Card = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"rounded-lg border bg-card text-card-foreground shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Card.displayName = "Card"
|
||||
|
||||
const CardHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex flex-col space-y-1.5 p-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardHeader.displayName = "CardHeader"
|
||||
|
||||
const CardTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-xl font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardTitle.displayName = "CardTitle"
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardDescription.displayName = "CardDescription"
|
||||
|
||||
const CardContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
||||
))
|
||||
CardContent.displayName = "CardContent"
|
||||
|
||||
const CardFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex items-center p-6 pt-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardFooter.displayName = "CardFooter"
|
||||
|
||||
export { Card, CardContent,CardDescription, CardFooter, CardHeader, CardTitle }
|
||||
32
ui/src/components/ui/checkbox.tsx
Normal file
32
ui/src/components/ui/checkbox.tsx
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
"use client"
|
||||
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="flex items-center justify-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
34
ui/src/components/ui/choice-chips.tsx
Normal file
34
ui/src/components/ui/choice-chips.tsx
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface ChoiceChipsProps {
|
||||
options: {
|
||||
value: string;
|
||||
label: string;
|
||||
}[];
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ChoiceChips({ options, value, onChange, className }: ChoiceChipsProps) {
|
||||
return (
|
||||
<div className={cn("flex gap-2 p-4", className)}>
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
onClick={() => onChange(option.value)}
|
||||
className={cn(
|
||||
"px-4 py-2 rounded-full text-sm font-medium transition-all",
|
||||
value === option.value
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-secondary text-secondary-foreground hover:bg-secondary/80"
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
136
ui/src/components/ui/dialog.tsx
Normal file
136
ui/src/components/ui/dialog.tsx
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
"use client"
|
||||
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
onOpenAutoFocus={e => e.preventDefault()}
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
257
ui/src/components/ui/dropdown-menu.tsx
Normal file
257
ui/src/components/ui/dropdown-menu.tsx
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
"use client"
|
||||
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger,
|
||||
}
|
||||
21
ui/src/components/ui/input.tsx
Normal file
21
ui/src/components/ui/input.tsx
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border 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 }
|
||||
24
ui/src/components/ui/label.tsx
Normal file
24
ui/src/components/ui/label.tsx
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
"use client"
|
||||
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/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",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
48
ui/src/components/ui/popover.tsx
Normal file
48
ui/src/components/ui/popover.tsx
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
"use client"
|
||||
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
export { Popover, PopoverAnchor,PopoverContent, PopoverTrigger }
|
||||
31
ui/src/components/ui/progress.tsx
Normal file
31
ui/src/components/ui/progress.tsx
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
"use client"
|
||||
|
||||
import * as ProgressPrimitive from "@radix-ui/react-progress"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Progress({
|
||||
className,
|
||||
value,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
|
||||
return (
|
||||
<ProgressPrimitive.Root
|
||||
data-slot="progress"
|
||||
className={cn(
|
||||
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
data-slot="progress-indicator"
|
||||
className="bg-primary h-full w-full flex-1 transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Progress }
|
||||
45
ui/src/components/ui/radio-group.tsx
Normal file
45
ui/src/components/ui/radio-group.tsx
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"use client"
|
||||
|
||||
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
|
||||
import { CircleIcon } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function RadioGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Root
|
||||
data-slot="radio-group"
|
||||
className={cn("grid gap-3", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function RadioGroupItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Item
|
||||
data-slot="radio-group-item"
|
||||
className={cn(
|
||||
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<RadioGroupPrimitive.Indicator
|
||||
data-slot="radio-group-indicator"
|
||||
className="relative flex items-center justify-center"
|
||||
>
|
||||
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
|
||||
</RadioGroupPrimitive.Indicator>
|
||||
</RadioGroupPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
export { RadioGroup, RadioGroupItem }
|
||||
185
ui/src/components/ui/select.tsx
Normal file
185
ui/src/components/ui/select.tsx
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
"use client"
|
||||
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-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
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
28
ui/src/components/ui/separator.tsx
Normal file
28
ui/src/components/ui/separator.tsx
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
"use client"
|
||||
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator-root"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
139
ui/src/components/ui/sheet.tsx
Normal file
139
ui/src/components/ui/sheet.tsx
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
"use client"
|
||||
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||
}
|
||||
|
||||
function SheetClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||
}
|
||||
|
||||
function SheetPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left"
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
side === "right" &&
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
side === "left" &&
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "top" &&
|
||||
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||
side === "bottom" &&
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
}
|
||||
726
ui/src/components/ui/sidebar.tsx
Normal file
726
ui/src/components/ui/sidebar.tsx
Normal file
|
|
@ -0,0 +1,726 @@
|
|||
"use client"
|
||||
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva,VariantProps } from "class-variance-authority"
|
||||
import { PanelLeftIcon } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}) {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer text-sidebar-foreground hidden md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("size-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("bg-background h-8 w-full shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("bg-sidebar-border mx-2 w-auto", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-label"
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-action"
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function SidebarMenuButton({
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-button"
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!tooltip) {
|
||||
return button
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
asChild = false,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-action"
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
asChild = false,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-sub-button"
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
13
ui/src/components/ui/skeleton.tsx
Normal file
13
ui/src/components/ui/skeleton.tsx
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
25
ui/src/components/ui/sonner.tsx
Normal file
25
ui/src/components/ui/sonner.tsx
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
"use client"
|
||||
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
31
ui/src/components/ui/switch.tsx
Normal file
31
ui/src/components/ui/switch.tsx
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
"use client"
|
||||
|
||||
import * as SwitchPrimitive from "@radix-ui/react-switch"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
className={cn(
|
||||
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className={cn(
|
||||
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Switch }
|
||||
114
ui/src/components/ui/table.tsx
Normal file
114
ui/src/components/ui/table.tsx
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Table = React.forwardRef<
|
||||
HTMLTableElement,
|
||||
React.HTMLAttributes<HTMLTableElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table
|
||||
ref={ref}
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
Table.displayName = "Table"
|
||||
|
||||
const TableHeader = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
||||
))
|
||||
TableHeader.displayName = "TableHeader"
|
||||
|
||||
const TableBody = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tbody
|
||||
ref={ref}
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TableBody.displayName = "TableBody"
|
||||
|
||||
const TableFooter = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tfoot
|
||||
ref={ref}
|
||||
className={cn("bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TableFooter.displayName = "TableFooter"
|
||||
|
||||
const TableRow = React.forwardRef<
|
||||
HTMLTableRowElement,
|
||||
React.HTMLAttributes<HTMLTableRowElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TableRow.displayName = "TableRow"
|
||||
|
||||
const TableHead = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.ThHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<th
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TableHead.displayName = "TableHead"
|
||||
|
||||
const TableCell = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.TdHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<td
|
||||
ref={ref}
|
||||
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TableCell.displayName = "TableCell"
|
||||
|
||||
const TableCaption = React.forwardRef<
|
||||
HTMLTableCaptionElement,
|
||||
React.HTMLAttributes<HTMLTableCaptionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<caption
|
||||
ref={ref}
|
||||
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TableCaption.displayName = "TableCaption"
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
}
|
||||
18
ui/src/components/ui/textarea.tsx
Normal file
18
ui/src/components/ui/textarea.tsx
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
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
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
61
ui/src/components/ui/tooltip.tsx
Normal file
61
ui/src/components/ui/tooltip.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"use client"
|
||||
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipContent, TooltipProvider,TooltipTrigger }
|
||||
22
ui/src/components/workflow/CreateWorkflowButton.tsx
Normal file
22
ui/src/components/workflow/CreateWorkflowButton.tsx
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
'use client';
|
||||
|
||||
import { PlusIcon } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export function CreateWorkflowButton() {
|
||||
const router = useRouter();
|
||||
const handleClick = () => {
|
||||
router.push('/create-workflow');
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
>
|
||||
<PlusIcon className="w-4 h-4" />
|
||||
Create Workflow
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
82
ui/src/components/workflow/TemplateCard.tsx
Normal file
82
ui/src/components/workflow/TemplateCard.tsx
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
'use client';
|
||||
|
||||
import { Copy } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { duplicateWorkflowTemplateApiV1WorkflowTemplatesDuplicatePost } from '@/client/sdk.gen';
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import logger from '@/lib/logger';
|
||||
|
||||
interface DuplicateWorkflowTemplateProps {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string;
|
||||
serverAccessToken?: string | null;
|
||||
}
|
||||
|
||||
export function DuplicateWorkflowTemplate({ id, title, description, serverAccessToken }: DuplicateWorkflowTemplateProps) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
const { user, getAccessToken } = useAuth();
|
||||
|
||||
const handleDuplicate = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// Use server-provided token if available, otherwise try to get from client auth
|
||||
let accessToken = serverAccessToken;
|
||||
|
||||
if (!accessToken) {
|
||||
if (!user) {
|
||||
logger.error('User not authenticated and no server token provided');
|
||||
return;
|
||||
}
|
||||
accessToken = await getAccessToken();
|
||||
}
|
||||
|
||||
if (!accessToken) {
|
||||
logger.error('No access token available');
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await duplicateWorkflowTemplateApiV1WorkflowTemplatesDuplicatePost({
|
||||
body: {
|
||||
template_id: id,
|
||||
workflow_name: title,
|
||||
},
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.data) {
|
||||
logger.info('Workflow created successfully from template');
|
||||
// Redirect to the new workflow
|
||||
router.push(`/workflow/${response.data.id}`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Error creating workflow from template: ${error}`);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white border rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-shadow p-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">{title}</h3>
|
||||
<p className="text-gray-600 mb-4">{description}</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={handleDuplicate}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Copy className="w-4 h-4 mr-2" />
|
||||
{isLoading ? 'Creating...' : 'Duplicate Workflow Template'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
133
ui/src/components/workflow/UploadWorkflowButton.tsx
Normal file
133
ui/src/components/workflow/UploadWorkflowButton.tsx
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
'use client';
|
||||
|
||||
import { Upload } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
import { createWorkflowApiV1WorkflowCreateDefinitionPost } from '@/client/sdk.gen';
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import logger from '@/lib/logger';
|
||||
import { getRandomId } from '@/lib/utils';
|
||||
|
||||
import { WorkflowData } from '../flow/types';
|
||||
|
||||
export function UploadWorkflowButton() {
|
||||
const router = useRouter();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { user, getAccessToken } = useAuth();
|
||||
|
||||
const handleFileUpload = useCallback(async (file: File) => {
|
||||
try {
|
||||
const text = await file.text();
|
||||
const workflowData: WorkflowData = JSON.parse(text);
|
||||
|
||||
if (!workflowData.workflow_definition?.nodes ||
|
||||
!workflowData.workflow_definition?.edges ||
|
||||
!workflowData.workflow_definition?.viewport) {
|
||||
throw new Error('Invalid workflow data structure');
|
||||
}
|
||||
|
||||
if (!user) return;
|
||||
const accessToken = await getAccessToken();
|
||||
const response = await createWorkflowApiV1WorkflowCreateDefinitionPost({
|
||||
body: {
|
||||
name: workflowData.name || `WF-${getRandomId()}`,
|
||||
workflow_definition: workflowData.workflow_definition as unknown as { [key: string]: unknown },
|
||||
},
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.data?.id) {
|
||||
router.push(`/workflow/${response.data.id}`);
|
||||
setIsOpen(false);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Failed to upload workflow. Please check if the file is valid.');
|
||||
logger.error(`Error uploading workflow: ${err}`);
|
||||
}
|
||||
}, [router, user, getAccessToken]);
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
setError(null);
|
||||
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file && file.type === 'application/json') {
|
||||
handleFileUpload(file);
|
||||
} else {
|
||||
setError('Please upload a valid JSON file');
|
||||
}
|
||||
}, [handleFileUpload]);
|
||||
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
}, []);
|
||||
|
||||
const handleFileInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
handleFileUpload(file);
|
||||
}
|
||||
}, [handleFileUpload]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={() => setIsOpen(true)}
|
||||
variant="outline"
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Upload Workflow
|
||||
</Button>
|
||||
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Upload Workflow</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div
|
||||
className={`mt-4 border-2 border-dashed rounded-lg p-8 text-center ${isDragging ? 'border-primary bg-primary/5' : 'border-gray-300'
|
||||
}`}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
>
|
||||
<Upload className="w-8 h-8 mx-auto mb-4 text-gray-400" />
|
||||
<p className="text-sm text-gray-600 mb-4">
|
||||
Drag and drop your Workflow JSON File here, or Click to Select
|
||||
</p>
|
||||
<input
|
||||
type="file"
|
||||
accept=".json"
|
||||
onChange={handleFileInput}
|
||||
className="hidden"
|
||||
id="workflow-upload"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => document.getElementById('workflow-upload')?.click()}
|
||||
>
|
||||
Select File
|
||||
</Button>
|
||||
{error && (
|
||||
<p className="mt-4 text-sm text-red-600">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
31
ui/src/components/workflow/WorkflowCard.tsx
Normal file
31
ui/src/components/workflow/WorkflowCard.tsx
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
interface WorkflowCardProps {
|
||||
id: number;
|
||||
name: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export function WorkflowCard({ id, name, createdAt }: WorkflowCardProps) {
|
||||
const router = useRouter();
|
||||
|
||||
const handleClick = () => {
|
||||
router.push(`/workflow/${id}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="bg-white border rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-all duration-200 p-4 cursor-pointer transform hover:-translate-y-1"
|
||||
onClick={handleClick}
|
||||
>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">{name}</h3>
|
||||
<p className="text-gray-600 mb-2">
|
||||
Created: {new Date(createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
160
ui/src/components/workflow/WorkflowTable.tsx
Normal file
160
ui/src/components/workflow/WorkflowTable.tsx
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
'use client';
|
||||
|
||||
import { Archive, Eye, RotateCcw } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState, useTransition } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { updateWorkflowStatusApiV1WorkflowWorkflowIdStatusPut } from '@/client/sdk.gen';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { useUserConfig } from '@/context/UserConfigContext';
|
||||
|
||||
interface Workflow {
|
||||
id: number;
|
||||
name: string;
|
||||
status: string;
|
||||
created_at: string;
|
||||
total_runs?: number | null;
|
||||
}
|
||||
|
||||
interface WorkflowTableProps {
|
||||
workflows: Workflow[];
|
||||
showArchived: boolean;
|
||||
}
|
||||
|
||||
export function WorkflowTable({ workflows, showArchived }: WorkflowTableProps) {
|
||||
const router = useRouter();
|
||||
const { accessToken } = useUserConfig();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [loadingWorkflowId, setLoadingWorkflowId] = useState<number | null>(null);
|
||||
|
||||
const handleView = (id: number) => {
|
||||
router.push(`/workflow/${id}`);
|
||||
};
|
||||
|
||||
const handleArchiveToggle = async (id: number, currentStatus: string) => {
|
||||
if (!accessToken) {
|
||||
toast.error('Authentication required');
|
||||
return;
|
||||
}
|
||||
|
||||
const newStatus = currentStatus === 'active' ? 'archived' : 'active';
|
||||
const action = currentStatus === 'active' ? 'Archive' : 'Restore';
|
||||
|
||||
setLoadingWorkflowId(id);
|
||||
|
||||
try {
|
||||
const response = await updateWorkflowStatusApiV1WorkflowWorkflowIdStatusPut({
|
||||
path: {
|
||||
workflow_id: id,
|
||||
},
|
||||
body: {
|
||||
status: newStatus,
|
||||
},
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.data) {
|
||||
toast.success(`Workflow ${action.toLowerCase()}d successfully`);
|
||||
startTransition(() => {
|
||||
router.refresh();
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error ${action.toLowerCase()}ing workflow:`, error);
|
||||
toast.error(`Failed to ${action.toLowerCase()} workflow`);
|
||||
} finally {
|
||||
setLoadingWorkflowId(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white border rounded-lg overflow-hidden shadow-sm">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="bg-gray-50">
|
||||
<TableHead className="font-semibold">Workflow Name</TableHead>
|
||||
<TableHead className="font-semibold">Created At</TableHead>
|
||||
<TableHead className="font-semibold text-center">Total Runs</TableHead>
|
||||
<TableHead className="font-semibold text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{workflows.map((workflow) => (
|
||||
<TableRow
|
||||
key={workflow.id}
|
||||
className={`hover:bg-gray-50 transition-colors ${showArchived ? 'opacity-60' : ''}`}
|
||||
>
|
||||
<TableCell className="font-medium">
|
||||
{workflow.name}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{new Date(workflow.created_at).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<span className="inline-flex items-center justify-center min-w-[2rem] px-2 py-1 text-sm font-semibold bg-gray-100 rounded-full">
|
||||
{workflow.total_runs || 0}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleView(workflow.id)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Eye size={16} />
|
||||
View
|
||||
</Button>
|
||||
<Button
|
||||
variant={showArchived ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => handleArchiveToggle(workflow.id, workflow.status)}
|
||||
disabled={loadingWorkflowId === workflow.id || isPending}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{loadingWorkflowId === workflow.id ? (
|
||||
<>
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
|
||||
{showArchived ? 'Restoring...' : 'Archiving...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{showArchived ? (
|
||||
<>
|
||||
<RotateCcw size={16} />
|
||||
Restore
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Archive size={16} />
|
||||
Archive
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue