Spaces:
Paused
Paused
File size: 16,918 Bytes
5df0bfe 515d292 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe dfcbb7c 5df0bfe dfcbb7c 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 dfcbb7c 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe dfcbb7c 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 dfcbb7c 5df0bfe 79a5f2f 5df0bfe dfcbb7c 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe 5eb4857 5df0bfe f3292d9 5df0bfe dfcbb7c 5df0bfe d02993d 5df0bfe 5eb4857 d02993d 5df0bfe d02993d 5df0bfe d02993d 5df0bfe d02993d 5df0bfe d02993d 5df0bfe d02993d 5df0bfe d02993d 5df0bfe d02993d 5df0bfe d02993d 5df0bfe d02993d dfcbb7c d02993d 5df0bfe d02993d 5df0bfe d02993d dfcbb7c d02993d 5eb4857 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | 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>
);
};
|