Spaces:
Paused
Paused
Download frontend/apps/customer/src/components/KnowledgeBase.tsx from 3SCError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 19.5 kB
-
https://huggingface.co/spaces/3SCError404/nexus/resolve/main/frontend/apps/customer/src/components/KnowledgeBase.tsx
- Command line
-
hf download hf://spaces/3SCError404/nexus/frontend/apps/customer/src/components/KnowledgeBase.tsx
-
curl -L -o KnowledgeBase.tsx https://huggingface.co/spaces/3SCError404/nexus/resolve/main/frontend/apps/customer/src/components/KnowledgeBase.tsx
19.5 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) { | |
| // Robust sanitization to handle model-generated formatting artifacts | |
| const sanitized = chart | |
| .replace(/```mermaid/g, '') | |
| .replace(/```/g, '') | |
| .trim(); | |
| const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`; | |
| mermaid.render(id, sanitized).then((res) => { | |
| if (ref.current) ref.current.innerHTML = res.svg; | |
| }).catch(err => { | |
| console.error("Mermaid render failed:", err); | |
| if (ref.current) { | |
| ref.current.innerHTML = `<div style="color: #ef4444; font-size: 12px; font-weight: 700; padding: 20px; background: rgba(239, 68, 68, 0.1); border-radius: 12px; border: 1px solid rgba(239, 68, 68, 0.2)"> | |
| ⚠️ DIAGRAM ENGINE ERROR: Invalid Diagram Syntax | |
| <pre style="margin-top: 10px; font-size: 10px; opacity: 0.7">${sanitized.slice(0, 100)}...</pre> | |
| </div>`; | |
| } | |
| }); | |
| } | |
| }, [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[]>(() => { | |
| try { | |
| const cached = sessionStorage.getItem('nexus_kb_articles_v1'); | |
| return cached ? JSON.parse(cached) : []; | |
| } catch { return []; } | |
| }); | |
| const [categories, setCategories] = useState<string[]>(() => { | |
| try { | |
| const cached = sessionStorage.getItem('nexus_kb_categories_v1'); | |
| return cached ? JSON.parse(cached) : ['All Documentation']; | |
| } catch { return ['All Documentation']; } | |
| }); | |
| const [loading, setLoading] = useState(articles.length === 0); | |
| 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/'); | |
| const cats = ['All Documentation', ...resp.data]; | |
| setCategories(cats); | |
| sessionStorage.setItem('nexus_kb_categories_v1', JSON.stringify(cats)); | |
| } 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); | |
| // Cache main listing | |
| if (cat === 'All Documentation') { | |
| sessionStorage.setItem('nexus_kb_articles_v1', JSON.stringify(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> | |
| <div className={styles.zenArticleContainer}> | |
| <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: 'var(--text-muted)', fontSize: 13, opacity: 0.7 }}> | |
| <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: 'var(--primary)', 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" | |
| wrapLongLines={true} | |
| customStyle={{ | |
| borderRadius: '16px', | |
| padding: '24px', | |
| fontSize: '14px', | |
| lineHeight: '1.6', | |
| background: 'rgba(15, 23, 42, 0.9)', | |
| border: '1px solid rgba(255, 255, 255, 0.05)', | |
| boxShadow: '0 20px 40px rgba(0,0,0,0.2)' | |
| }} | |
| {...props} | |
| > | |
| {String(children).replace(/\n$/, '')} | |
| </SyntaxHighlighter> | |
| ) : ( | |
| <code className={className} {...props}> | |
| {children} | |
| </code> | |
| ); | |
| } | |
| }} | |
| > | |
| {selectedArticle.content} | |
| </ReactMarkdown> | |
| </div> | |
| </div> | |
| <div style={{ marginTop: 60, padding: 48, background: 'rgba(255, 255, 255, 0.02)', borderRadius: 24, textAlign: 'center', border: '1px dashed var(--border-subtle)' }}> | |
| <h3 style={{ fontSize: 20, fontWeight: 800, color: 'var(--text-main)', marginBottom: 8, fontFamily: 'var(--font-header)' }}>Was this guide helpful?</h3> | |
| <p style={{ fontSize: 15, color: 'var(--text-muted)', marginBottom: 32, maxWidth: 460, margin: '0 auto 24px' }}>Our tactical response teams are available 24/7 if you require further technical intelligence.</p> | |
| <button | |
| onClick={onNewTicket} | |
| style={{ | |
| background: 'var(--primary)', color: '#fff', border: 'none', | |
| padding: '14px 28px', borderRadius: 12, cursor: 'pointer', | |
| fontWeight: 800, fontSize: 14, boxShadow: '0 8px 24px rgba(0,0,0,0.3)', | |
| transition: 'all 0.2s' | |
| }} | |
| onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'} | |
| onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'} | |
| > | |
| Initiate 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: 10, fontWeight: 900, color: 'var(--text-muted)', letterSpacing: '0.1em', opacity: 0.6 }}>SORT BY:</span> | |
| <select | |
| className={styles.navItem} | |
| style={{ padding: '8px 12px', background: 'rgba(255,255,255,0.03)', border: '1px solid var(--border-subtle)', borderRadius: 8, marginRight: 0, color: 'var(--text-main)', outline: 'none' }} | |
| value={sortBy} | |
| onChange={e => setSortBy(e.target.value as any)} | |
| > | |
| <option value="newest">Latest Intel</option> | |
| <option value="oldest">Historical</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 var(--border-subtle)', 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> | |
| <div className={styles.answerText}> | |
| <ReactMarkdown remarkPlugins={[remarkGfm]}> | |
| {aiAnswer} | |
| </ReactMarkdown> | |
| </div> | |
| <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: 800, color: 'var(--text-main)', marginBottom: 8, fontFamily: 'var(--font-header)' }}>No matching intelligence</h3> | |
| {aiSuggestion && ( | |
| <div style={{ marginTop: 16, color: 'var(--text-muted)' }}> | |
| Suggesting search: <button onClick={() => { setSearchInput(aiSuggestion); fetchArticles(aiSuggestion, selectedCategory); }} style={{ color: 'var(--primary)', fontWeight: 800, 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: 'var(--primary)', fontSize: 11, fontWeight: 900, 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> | |
| ); | |
| }; | |