Spaces:
Paused

nexus / frontend /apps /customer /src /components /KnowledgeBase.tsx
dushyantsingh0
fix: remove unused imports causing TS build failure
515d292
Raw History Blame Contribute Delete
16.9 kB
import React, { useState, useEffect, useCallback, useRef } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { motion, AnimatePresence } from 'framer-motion';
import { Search, ChevronLeft, ChevronRight, Sparkles, Radio, Clock, User as UserIcon } from 'lucide-react';
import { api } from '@nexus/shared';
import mermaid from 'mermaid';
import styles from './KnowledgeBase.module.css';
// Initialize Mermaid
mermaid.initialize({
startOnLoad: true,
theme: 'dark',
securityLevel: 'loose',
});
// Mermaid Component
const Mermaid: React.FC<{ chart: string }> = ({ chart }) => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (ref.current && chart) {
const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`;
mermaid.render(id, chart).then((res) => {
if (ref.current) ref.current.innerHTML = res.svg;
}).catch(err => {
console.error("Mermaid render failed:", err);
});
}
}, [chart]);
return <div ref={ref} className={styles.mermaidContainer} />;
};
interface Article {
id: string;
title: string;
content: string;
category: string;
author_id: string;
is_published: boolean;
created_at: string;
updated_at: string;
summary?: string;
score?: number;
match_type?: string;
snippet?: string;
}
interface KnowledgeBaseProps {
onNewTicket?: () => void;
}
export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ onNewTicket }) => {
const [articles, setArticles] = useState<Article[]>([]);
const [categories, setCategories] = useState<string[]>(['All Documentation']);
const [loading, setLoading] = useState(true);
const [isScanning, setIsScanning] = useState(false);
// Search State
const [searchInput, setSearchInput] = useState('');
const [activeQuery, setActiveQuery] = useState('');
const [selectedCategory, setSelectedCategory] = useState('All Documentation');
// AI Direct Answer State
const [aiAnswer, setAiAnswer] = useState<string | null>(null);
const [isAiSynthetic, setIsAiSynthetic] = useState(false);
const [suggestions, setSuggestions] = useState<string[]>([]);
const [aiSuggestion, setAiSuggestion] = useState<string | null>(null);
// UI State
const [page, setPage] = useState(1);
const ITEMS_PER_PAGE = 4;
const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);
const [sortBy, setSortBy] = useState<'newest' | 'oldest'>('newest');
const fetchCategories = useCallback(async () => {
try {
const resp = await api.get('kb/categories/');
setCategories(['All Documentation', ...resp.data]);
} catch (err) {
console.error('Failed to fetch categories:', err);
}
}, []);
const fetchArticles = useCallback(async (query: string = '', cat: string = 'All Documentation') => {
setLoading(true);
if (query.length > 0) setIsScanning(true);
try {
const params: any = {};
if (cat !== 'All Documentation') params.category = cat;
if (query.trim().length > 0) {
params.q = query;
const resp = await api.get('kb/search/', { params });
setArticles(resp.data.results || []);
setSuggestions(resp.data.expanded_queries || []);
setAiSuggestion(resp.data.suggestion || null);
setAiAnswer(resp.data.answer || null);
setIsAiSynthetic(resp.data.is_ai_synthetic || false);
} else {
const resp = await api.get('kb/', { params });
let data = resp.data || [];
data.sort((a: any, b: any) => {
const dateA = new Date(a.created_at).getTime();
const dateB = new Date(b.created_at).getTime();
return sortBy === 'newest' ? dateB - dateA : dateA - dateB;
});
setArticles(data);
setSuggestions([]);
setAiAnswer(null);
setIsAiSynthetic(false);
setAiSuggestion(null);
}
setPage(1);
} catch (err) {
console.error('Failed to fetch articles:', err);
} finally {
setLoading(false);
setIsScanning(false);
}
}, [sortBy]);
useEffect(() => {
fetchCategories();
fetchArticles('', 'All Documentation');
}, [fetchCategories, fetchArticles]);
// Reactive Search Reset
useEffect(() => {
if (searchInput.trim() === '') {
setActiveQuery('');
if (articles.length > 0 && activeQuery !== '') {
fetchArticles('', selectedCategory);
}
}
}, [searchInput, selectedCategory, fetchArticles]);
const handleSearchTrigger = (e?: React.FormEvent) => {
if (e) e.preventDefault();
setActiveQuery(searchInput);
fetchArticles(searchInput, selectedCategory);
};
const paginated = articles.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
const totalPages = Math.ceil(articles.length / ITEMS_PER_PAGE);
if (selectedArticle) {
return (
<motion.div
className={styles.articleDetail}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
>
<button className={styles.backBtn} onClick={() => setSelectedArticle(null)}>
<ChevronLeft size={16} /> Back to Library
</button>
<header style={{ marginBottom: 40 }}>
<div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 16 }}>
<span className={styles.categoryBadge}>{selectedArticle.category || 'General'}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, color: '#6B7280', fontSize: 13 }}>
<UserIcon size={14} /> <span>Admin</span>
<Clock size={14} style={{ marginLeft: 8 }} />
<span>{new Date(selectedArticle.created_at).toLocaleDateString()}</span>
</div>
</div>
<h1 className={styles.articleTitle} style={{ fontSize: 42 }}>{selectedArticle.title}</h1>
<div style={{ width: 60, height: 4, background: '#1E40AF', borderRadius: 2, marginTop: 24 }} />
</header>
{selectedArticle.summary && (
<div className={styles.aiSpotlight} style={{ margin: '0 0 48px 0', padding: '24px 32px' }}>
<div className={styles.spotlightHeader} style={{ marginBottom: 16 }}>
<div className={styles.spotlightBadge}>
<Sparkles size={14} /> AI GENERATED SUMMARY
</div>
</div>
<p className={styles.answerText} style={{ fontSize: 16 }}>{selectedArticle.summary}</p>
</div>
)}
<div className={styles.markdownContent}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
code({node, inline, className, children, ...props}: any) {
const match = /language-(\w+)/.exec(className || '');
if (!inline && match && match[1] === 'mermaid') {
return <Mermaid chart={String(children)} />;
}
return !inline && match ? (
<SyntaxHighlighter
style={vscDarkPlus}
language={match[1]}
PreTag="div"
{...props}
>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>
{children}
</code>
);
}
}}
>
{selectedArticle.content}
</ReactMarkdown>
</div>
<div style={{ marginTop: 60, padding: 32, background: '#F9FAFB', borderRadius: 16, textAlign: 'center', border: '1px dashed #D1D5DB' }}>
<h3 style={{ fontSize: 18, fontWeight: 700, color: '#111827', marginBottom: 8 }}>Found this guide useful?</h3>
<p style={{ fontSize: 14, color: '#4B5563', marginBottom: 24 }}>If you still need assistance, our support team is available 24/7.</p>
<button
onClick={onNewTicket}
style={{ background: '#1E40AF', color: '#fff', border: 'none', padding: '12px 24px', borderRadius: 10, cursor: 'pointer', fontWeight: 700, boxShadow: '0 4px 12px rgba(30,64,175,0.2)' }}
>
Submit a Support Ticket
</button>
</div>
</motion.div>
);
}
return (
<div className={styles.container}>
<header className={styles.searchHero}>
<h1>Knowledge Base</h1>
<p className={styles.description}>Expert guides and troubleshooting for everything Nexus.</p>
<form className={styles.searchControls} onSubmit={handleSearchTrigger}>
<div className={styles.searchWrapper}>
<Search className={styles.searchIcon} size={20} />
<input
type="text"
className={styles.searchInput}
placeholder="How can we help you today?"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
/>
{isScanning && (
<div className={styles.searchPulse}>
<Radio size={14} className={styles.pulseIcon} />
<span>NEURAL SCANNING</span>
</div>
)}
<button type="submit" className={styles.searchBtn}>Search</button>
</div>
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
<span style={{ fontSize: 11, fontWeight: 800, color: '#9CA3AF', letterSpacing: '0.05em' }}>SORT BY:</span>
<select
className={styles.navItem}
style={{ padding: '8px 12px', background: '#fff', border: '1px solid #E5E7EB', borderRadius: 8, marginRight: 0 }}
value={sortBy}
onChange={e => setSortBy(e.target.value as any)}
>
<option value="newest">Newest First</option>
<option value="oldest">Oldest First</option>
</select>
</div>
</form>
<AnimatePresence>
{suggestions.length > 0 && (
<motion.div
className={styles.suggestions}
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
style={{ marginTop: 24, display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}
>
<span className={styles.categoryBadge}>Suggestions:</span>
{suggestions.map(s => (
<button
key={s}
onClick={() => { setSearchInput(s); fetchArticles(s, selectedCategory); }}
className={styles.regularMatch}
style={{ padding: '6px 14px', borderRadius: 20, border: '1px solid #1E40AF22', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}
>
{s}
</button>
))}
</motion.div>
)}
</AnimatePresence>
</header>
<nav className={styles.categoryNav}>
{categories.map(cat => (
<button
key={cat}
className={`${styles.navItem} ${selectedCategory === cat ? styles.navItemActive : ''}`}
onClick={() => { setSelectedCategory(cat); fetchArticles(activeQuery, cat); }}
>
{cat}
</button>
))}
</nav>
<div className={styles.resultsContainer}>
<AnimatePresence mode="wait">
{aiAnswer && (
<motion.div
className={styles.aiSpotlight}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95 }}
>
<div className={styles.spotlightHeader}>
<div className={styles.spotlightBadge}>
<Sparkles size={14} /> AI DIRECT ANSWER
</div>
{isAiSynthetic && <span className={styles.syntheticFlag}>REAL-TIME SYNTHESIS</span>}
</div>
<p className={styles.answerText}>{aiAnswer}</p>
<div className={styles.spotlightFooter}>Based on the documentation below.</div>
</motion.div>
)}
</AnimatePresence>
{loading && articles.length === 0 ? (
<div className={styles.articlesGrid}>
{[1, 2, 3, 4].map(i => (
<div key={i} className={styles.articleCard} style={{ opacity: 0.5 }}>
<div style={{ height: 12, width: '30%', background: '#F3F4F6', borderRadius: 4, marginBottom: 16 }} />
<div style={{ height: 24, width: '80%', background: '#F3F4F6', borderRadius: 4, marginBottom: 12 }} />
<div style={{ height: 16, width: '100%', background: '#F3F4F6', borderRadius: 4, marginBottom: 8 }} />
<div style={{ height: 16, width: '60%', background: '#F3F4F6', borderRadius: 4, marginBottom: 24 }} />
</div>
))}
</div>
) : articles.length === 0 ? (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
style={{ padding: '100px 0', textAlign: 'center' }}
>
<div style={{ fontSize: 48, marginBottom: 20 }}>🔍</div>
<h3 style={{ fontSize: 20, fontWeight: 700, color: '#111827', marginBottom: 8 }}>We couldn't find that</h3>
{aiSuggestion && (
<div style={{ marginTop: 16, color: '#6B7280' }}>
Did you mean: <button onClick={() => { setSearchInput(aiSuggestion); fetchArticles(aiSuggestion, selectedCategory); }} style={{ color: '#1E40AF', fontWeight: 700, background: 'none', border: 'none', cursor: 'pointer' }}>{aiSuggestion}</button>?
</div>
)}
</motion.div>
) : (
<>
<motion.div
className={styles.articlesGrid}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
>
{paginated.map((article, i) => (
<motion.div
key={article.id}
className={styles.articleCard}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: i * 0.05 }}
onClick={() => setSelectedArticle(article)}
>
<div className={styles.cardHeader}>
<span className={styles.categoryBadge}>{article.category || 'General'}</span>
{article.score && (
<span className={`${styles.matchBadge} ${article.score > 80 ? styles.highMatch : styles.regularMatch}`}>
{Math.round(article.score)}% MATCH
</span>
)}
</div>
<h3 className={styles.articleTitle}>{article.title}</h3>
<p className={styles.articleSnippet}>
{article.snippet ? (
<span><strong style={{ color: '#1E40AF', fontSize: 11, marginRight: 6 }}>[MATCH]</strong> {article.snippet}</span>
) : article.summary || article.content.replace(/[#*`]/g, '').slice(0, 160) + '...'}
</p>
<div className={styles.cardFooter}>
<span className={styles.articleDate}>Published {new Date(article.created_at).toLocaleDateString()}</span>
<span className={styles.readMore}>Read Guide →</span>
</div>
</motion.div>
))}
</motion.div>
{totalPages > 1 && (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 24, marginTop: 60 }}>
<button
disabled={page === 1}
onClick={() => setPage(p => p - 1)}
className={styles.navItem}
style={{ border: '1px solid #E5E7EB', borderRadius: 12, padding: '10px 24px', opacity: page === 1 ? 0.3 : 1 }}
>
<ChevronLeft size={16} />
</button>
<div style={{ fontSize: 14, fontWeight: 600, color: '#6B7280' }}>Page {page} of {totalPages}</div>
<button
disabled={page === totalPages}
onClick={() => setPage(p => p + 1)}
className={styles.navItem}
style={{ border: '1px solid #E5E7EB', borderRadius: 12, padding: '10px 24px', opacity: page === totalPages ? 0.3 : 1 }}
>
<ChevronRight size={16} />
</button>
</div>
)}
</>
)}
</div>
</div>
);
};