Spaces:
Paused
Paused
Download frontend/apps/internal/src/components/KnowledgeBase.tsx from 3SCError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 35.3 kB
-
https://huggingface.co/spaces/3SCError404/nexus/resolve/main/frontend/apps/internal/src/components/KnowledgeBase.tsx
- Command line
-
hf download hf://spaces/3SCError404/nexus/frontend/apps/internal/src/components/KnowledgeBase.tsx
-
curl -L -o KnowledgeBase.tsx https://huggingface.co/spaces/3SCError404/nexus/resolve/main/frontend/apps/internal/src/components/KnowledgeBase.tsx
35.3 kB
| import React, { useState, useEffect, useCallback } 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 { Search, Plus, X, Trash2, Edit3, ShieldCheck, Zap, Info, Radio, ChevronLeft, ChevronRight, Eye, Send, Lock, Globe, Sparkles } from 'lucide-react'; | |
| import { motion, AnimatePresence } from 'framer-motion'; | |
| import { api, useAuth } from '@nexus/shared'; | |
| import mermaid from 'mermaid'; | |
| import styles from './KnowledgeBase.module.css'; | |
| // Pre-defined role groups for UI visibility | |
| const SHRED_ROLES = ['3sc_admin', '3sc_lead', '3sc_agent']; | |
| const EDIT_ROLES = ['3sc_admin', '3sc_lead', '3sc_agent']; | |
| // Initialize Mermaid | |
| mermaid.initialize({ | |
| startOnLoad: false, | |
| theme: 'dark', | |
| securityLevel: 'loose', | |
| fontFamily: 'Inter, system-ui, sans-serif', | |
| }); | |
| // Enhanced Mermaid Component | |
| const Mermaid: React.FC<{ chart: string }> = ({ chart }) => { | |
| const [svg, setSvg] = useState<string>(''); | |
| const [error, setError] = useState<string | null>(null); | |
| const [isRendering, setIsRendering] = useState(true); | |
| const [showRaw, setShowRaw] = useState(false); | |
| const [id] = useState(() => `mermaid-${Math.random().toString(36).substr(2, 9)}`); | |
| useEffect(() => { | |
| let isMounted = true; | |
| const renderChart = async () => { | |
| if (!chart) return; | |
| setIsRendering(true); | |
| setError(null); | |
| // Sanitize input to handle model artifacts or accidental wrappers | |
| const sanitized = chart | |
| .replace(/```mermaid/g, '') | |
| .replace(/```/g, '') | |
| .trim(); | |
| try { | |
| // Clear previous error and SVG before re-rendering | |
| const { svg: renderedSvg } = await mermaid.render(id, sanitized); | |
| if (isMounted) { | |
| setSvg(renderedSvg); | |
| setIsRendering(false); | |
| setError(null); | |
| } | |
| } catch (err: any) { | |
| console.error("Mermaid synthesis failed:", err); | |
| if (isMounted) { | |
| setError(err.message || 'The diagram syntax is incompatible with the Nexus rendering engine.'); | |
| setIsRendering(false); | |
| } | |
| } | |
| }; | |
| renderChart(); | |
| return () => { isMounted = false; }; | |
| }, [chart, id]); | |
| if (isRendering) { | |
| return ( | |
| <div className={styles.mermaidContainer}> | |
| <div className={styles.mermaidLoading}> | |
| <div className={styles.loaderPulse} /> | |
| <span style={{ fontSize: '12px', fontWeight: 800, letterSpacing: '0.05em' }}>SYNTHESIZING ARCHITECTURE...</span> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| if (error) { | |
| return ( | |
| <div className={styles.mermaidContainer}> | |
| <div className={styles.mermaidError}> | |
| <div className={styles.errorHeader}> | |
| <span className={styles.errorBadge}>SYNTHESIS FAILURE</span> | |
| <h4 className={styles.errorTitle}>Diagram Engine Interrupted</h4> | |
| </div> | |
| <p className={styles.errorMessage}>{error}</p> | |
| <button | |
| type="button" | |
| className={styles.rawSchemaToggle} | |
| onClick={() => setShowRaw(!showRaw)} | |
| > | |
| <Edit3 size={14} /> {showRaw ? 'HIDE RAW SCHEMA' : 'INSPECT RAW SCHEMA'} | |
| </button> | |
| <AnimatePresence> | |
| {showRaw && ( | |
| <motion.div | |
| initial={{ height: 0, opacity: 0 }} | |
| animate={{ height: 'auto', opacity: 1 }} | |
| exit={{ height: 0, opacity: 0 }} | |
| className={styles.rawSchemaBox} | |
| > | |
| {chart} | |
| </motion.div> | |
| )} | |
| </AnimatePresence> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| return ( | |
| <div | |
| className={styles.mermaidContainer} | |
| dangerouslySetInnerHTML={{ __html: svg }} | |
| /> | |
| ); | |
| }; | |
| 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 { | |
| workspaceId?: string; | |
| } | |
| export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) => { | |
| const { user } = useAuth(); | |
| const canEdit = user?.role && EDIT_ROLES.includes(user.role); | |
| const canShred = user?.role && SHRED_ROLES.includes(user.role); | |
| const [articles, setArticles] = useState<Article[]>([]); | |
| const [categories, setCategories] = useState<string[]>(['All']); | |
| const [loading, setLoading] = useState(true); | |
| // Search State | |
| const [searchInput, setSearchInput] = useState(''); | |
| const [activeQuery, setActiveQuery] = useState(''); | |
| const [selectedCategory, setSelectedCategory] = useState('All'); | |
| // Pagination State | |
| const [currentPage, setCurrentPage] = useState(1); | |
| const itemsPerPage = 4; | |
| // Dossier State | |
| const [drawerOpen, setDrawerOpen] = useState(false); | |
| const [selectedArticle, setSelectedArticle] = useState<Article | null>(null); | |
| const [selectedInsight, setSelectedInsight] = useState<any | null>(null); | |
| const [isEditing, setIsEditing] = useState(false); | |
| // Edit Buffer | |
| const [editTitle, setEditTitle] = useState(''); | |
| const [editContent, setEditContent] = useState(''); | |
| const [editCategory, setEditCategory] = useState(''); | |
| const [editPublished, setEditPublished] = useState(true); | |
| // AI Search Enhanced State | |
| const [suggestions, setSuggestions] = useState<string[]>([]); | |
| const [aiSuggestion, setAiSuggestion] = useState<string | null>(null); | |
| const [aiAnswer, setAiAnswer] = useState<string | null>(null); | |
| const [isAiSynthetic, setIsAiSynthetic] = useState(false); | |
| // AI Growth Center State | |
| const [activeTab, setActiveTab] = useState<'library' | 'growth'>('library'); | |
| const [insights, setInsights] = useState<any[]>([]); | |
| const [insightsLoading, setInsightsLoading] = useState(false); | |
| // 1. Fetch Categories | |
| const fetchCategories = useCallback(async () => { | |
| try { | |
| const resp = await api.get('kb/categories/', { | |
| params: { workspace_id: workspaceId } | |
| }); | |
| setCategories(['All', ...resp.data]); | |
| } catch (err) { | |
| console.error('Failed to fetch categories:', err); | |
| } | |
| }, [workspaceId]); | |
| // 2. Fetch Articles | |
| const fetchArticles = useCallback(async (query: string = '', cat: string = 'All') => { | |
| setLoading(true); | |
| try { | |
| const params: any = { workspace_id: workspaceId }; | |
| if (cat !== 'All') 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 }); | |
| setArticles(resp.data || []); | |
| setSuggestions([]); | |
| setAiSuggestion(null); | |
| setAiAnswer(null); | |
| setIsAiSynthetic(false); | |
| } | |
| setCurrentPage(1); // Reset to first page on search/filter | |
| } catch (err) { | |
| console.error('Failed to fetch articles:', err); | |
| } finally { | |
| setLoading(false); | |
| } | |
| }, [workspaceId]); | |
| // 3. Fetch Insights | |
| const fetchInsights = useCallback(async () => { | |
| setInsightsLoading(true); | |
| try { | |
| const resp = await api.get('kb/insights/', { | |
| params: { workspace_id: workspaceId } | |
| }); | |
| setInsights(resp.data); | |
| } catch (err) { | |
| console.error('Failed to fetch insights:', err); | |
| } finally { | |
| setInsightsLoading(false); | |
| } | |
| }, [workspaceId]); | |
| useEffect(() => { | |
| fetchCategories(); | |
| fetchArticles('', 'All'); | |
| }, [fetchCategories, fetchArticles]); | |
| // Reactive Search Reset | |
| useEffect(() => { | |
| if (searchInput.trim() === '') { | |
| setActiveQuery(''); | |
| setAiAnswer(null); | |
| setSuggestions([]); | |
| setAiSuggestion(null); | |
| setIsAiSynthetic(false); | |
| // Optional: fetchArticles('', selectedCategory); | |
| // But fetchArticles is already called by the next useEffect if we change activeQuery | |
| } | |
| }, [searchInput]); | |
| useEffect(() => { | |
| if (activeTab === 'growth') { | |
| fetchInsights(); | |
| } | |
| }, [activeTab, fetchInsights]); | |
| const handleSearchTrigger = (e?: React.FormEvent) => { | |
| if (e) e.preventDefault(); | |
| setActiveQuery(searchInput); | |
| fetchArticles(searchInput, selectedCategory); | |
| }; | |
| // Article Actions | |
| const openDossier = (article: Article) => { | |
| setSelectedArticle(article); | |
| setSelectedInsight(null); | |
| setEditTitle(article.title); | |
| setEditContent(article.content); | |
| setEditCategory(article.category); | |
| setEditPublished(article.is_published); | |
| setIsEditing(false); | |
| setDrawerOpen(true); | |
| }; | |
| const openInsightDossier = (insight: any) => { | |
| setSelectedInsight(insight); | |
| setSelectedArticle(null); | |
| setEditTitle(insight.suggested_title); | |
| setEditContent(insight.suggested_content); | |
| setEditCategory(insight.category || 'General'); | |
| setEditPublished(false); | |
| setIsEditing(false); | |
| setDrawerOpen(true); | |
| }; | |
| const handleCreateNew = () => { | |
| setSelectedArticle(null); | |
| setSelectedInsight(null); | |
| setEditTitle('NEW STRATEGIC ASSET'); | |
| setEditContent('# Technical Directive\n\nStart your documentation here...\n\n```mermaid\ngraph TD;\n A-->B;\n```'); | |
| setEditCategory('General'); | |
| setEditPublished(false); | |
| setIsEditing(true); | |
| setDrawerOpen(true); | |
| }; | |
| const [isSaving, setIsSaving] = useState(false); | |
| const [saveStatus, setSaveStatus] = useState<'idle' | 'success' | 'error'>('idle'); | |
| const handleSaveDossier = async () => { | |
| setIsSaving(true); | |
| setSaveStatus('idle'); | |
| try { | |
| if (selectedInsight) { | |
| // Save Insight Edit | |
| const payload = { | |
| suggested_title: editTitle, | |
| suggested_content: editContent, | |
| category: editCategory | |
| }; | |
| const resp = await api.patch(`kb/insights/${selectedInsight.id}/`, payload); | |
| setInsights(prev => prev.map(i => i.id === selectedInsight.id ? { ...i, ...resp.data } : i)); | |
| setSelectedInsight({ ...selectedInsight, ...resp.data }); | |
| } else if (selectedArticle?.id) { | |
| // Save Article Update | |
| const payload = { | |
| title: editTitle, | |
| content: editContent, | |
| category: editCategory, | |
| is_published: editPublished | |
| }; | |
| const resp = await api.patch(`kb/${selectedArticle.id}`, payload); | |
| setArticles(prev => prev.map(a => a.id === selectedArticle.id ? { ...a, ...resp.data } : a)); | |
| setSelectedArticle({ ...selectedArticle, ...resp.data }); | |
| } else { | |
| // Create New Article | |
| const payload = { | |
| title: editTitle, | |
| content: editContent, | |
| category: editCategory, | |
| is_published: editPublished | |
| }; | |
| const resp = await api.post('kb/', payload); | |
| setArticles(prev => [resp.data, ...prev]); | |
| setSelectedArticle(resp.data); | |
| } | |
| setSaveStatus('success'); | |
| setTimeout(() => { | |
| setIsEditing(false); | |
| setSaveStatus('idle'); | |
| }, 1000); | |
| fetchCategories(); | |
| } catch (err) { | |
| console.error('Dossier save failed:', err); | |
| setSaveStatus('error'); | |
| } finally { | |
| setIsSaving(false); | |
| } | |
| }; | |
| const handleDeleteArticle = async (id: string) => { | |
| if (!window.confirm('Retract this strategic asset from the library?')) return; | |
| try { | |
| await api.delete(`/kb/${id}`); | |
| setArticles(prev => prev.filter(a => a.id !== id)); | |
| setDrawerOpen(false); | |
| } catch (err) { | |
| console.error('Retraction failed:', err); | |
| } | |
| }; | |
| // Insight Actions | |
| const handleApplyInsight = async (insight: any) => { | |
| try { | |
| await api.post(`kb/insights/${insight.id}/apply/`); | |
| setInsights(prev => prev.filter(i => i.id !== insight.id)); | |
| setActiveTab('library'); | |
| fetchArticles('', selectedCategory); | |
| } catch (err) { | |
| console.error('Failed to apply insight:', err); | |
| } | |
| }; | |
| const handleDismissInsight = async (id: string) => { | |
| try { | |
| await api.post(`kb/insights/${id}/dismiss/`); | |
| setInsights(prev => prev.filter(i => i.id !== id)); | |
| } catch (err) { | |
| console.error('Failed to dismiss insight:', err); | |
| } | |
| }; | |
| // Pagination Logic | |
| const totalPages = Math.ceil(articles.length / itemsPerPage); | |
| const paginatedArticles = articles.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage); | |
| return ( | |
| <div className={styles.container}> | |
| <header className={styles.missionBanner}> | |
| <div className={styles.bannerContent}> | |
| <div className={styles.headerMainRow}> | |
| <h1>{activeTab === 'library' ? 'KNOWLEDGE LIBRARY' : 'KNOWLEDGE GROWTH'}</h1> | |
| <div className={styles.headerTabs}> | |
| <button | |
| className={`${styles.tab} ${activeTab === 'library' ? styles.activeTab : ''}`} | |
| onClick={() => setActiveTab('library')} | |
| > | |
| <Globe size={14} /> LIBRARY | |
| </button> | |
| <button | |
| className={`${styles.tab} ${activeTab === 'growth' ? styles.activeTab : ''}`} | |
| onClick={() => setActiveTab('growth')} | |
| > | |
| <Sparkles size={14} /> AI GROWTH CENTER | |
| </button> | |
| </div> | |
| </div> | |
| <p className={styles.description}> | |
| {activeTab === 'library' | |
| ? 'Strategic intelligence gathering and architectural documentation.' | |
| : 'AI-detected blindspots and documentation suggestions.'} | |
| </p> | |
| <form className={styles.searchControls} onSubmit={handleSearchTrigger}> | |
| <div className={styles.searchWrapper}> | |
| <Search className={styles.searchIcon} size={20} /> | |
| <input | |
| type="text" | |
| placeholder="Type query and press Enter..." | |
| value={searchInput} | |
| onChange={(e) => setSearchInput(e.target.value)} | |
| /> | |
| {loading && searchInput.length > 0 && ( | |
| <div className={styles.searchPulse}> | |
| <Radio size={14} className={styles.pulseIcon} /> | |
| <span>NEURAL SCANNING</span> | |
| </div> | |
| )} | |
| </div> | |
| {canEdit && ( | |
| <button type="button" className={styles.newIntelBtn} onClick={handleCreateNew}> | |
| <Plus size={18} /> NEW INTEL | |
| </button> | |
| )} | |
| </form> | |
| <AnimatePresence> | |
| {suggestions.length > 0 && ( | |
| <motion.div | |
| className={styles.suggestions} | |
| initial={{ opacity: 0, y: -10 }} | |
| animate={{ opacity: 1, y: 0 }} | |
| > | |
| <span className={styles.sLabel}>SUGGESTIONS:</span> | |
| {suggestions.map(s => ( | |
| <button | |
| key={s} | |
| className={styles.sChip} | |
| onClick={() => { setSearchInput(s); setActiveQuery(s); fetchArticles(s, selectedCategory); }} | |
| > | |
| {s} | |
| </button> | |
| ))} | |
| </motion.div> | |
| )} | |
| </AnimatePresence> | |
| </div> | |
| </header> | |
| <nav className={styles.categoryNav}> | |
| {categories.map(cat => ( | |
| <button | |
| key={cat} | |
| className={`${styles.navItem} ${selectedCategory === cat ? styles.active : ''}`} | |
| onClick={() => { setSelectedCategory(cat); fetchArticles(activeQuery, cat); }} | |
| > | |
| {cat} | |
| </button> | |
| ))} | |
| </nav> | |
| <div className={styles.contentArea}> | |
| <AnimatePresence mode="wait"> | |
| {activeTab === 'growth' ? ( | |
| <motion.div | |
| key="growth" | |
| className={styles.growthGrid} | |
| initial={{ opacity: 0, y: 20 }} | |
| animate={{ opacity: 1, y: 0 }} | |
| exit={{ opacity: 0, y: -20 }} | |
| > | |
| {insightsLoading ? ( | |
| <div className={styles.emptyState}> | |
| <div className={styles.loadingPulse} /> | |
| <p>Scanning knowledge topology for gaps...</p> | |
| </div> | |
| ) : insights.length === 0 ? ( | |
| <motion.div | |
| key="growth-empty" | |
| initial={{ opacity: 0, scale: 0.95 }} | |
| animate={{ opacity: 1, scale: 1 }} | |
| className={styles.emptyState} | |
| > | |
| <div className={styles.emptyVisual} style={{ background: 'var(--bg2)', borderRadius: '50%', padding: '40px', marginBottom: '24px' }}> | |
| <ShieldCheck size={64} color="var(--primary)" /> | |
| </div> | |
| <h3>Knowledge Equilibrium Reached</h3> | |
| <p style={{ maxWidth: 450, margin: '0 auto' }}> | |
| The AI Sentinel has analyzed all recent ticket resolutions and historical patterns. | |
| No critical knowledge blindspots or documentation gaps are currently detected. | |
| </p> | |
| <div className={styles.searchPulse} style={{ marginTop: '30px', position: 'static', transform: 'none' }}> | |
| <Radio size={14} className={styles.pulseIcon} /> | |
| <span>CONTINUOUS MONITORING ACTIVE</span> | |
| </div> | |
| </motion.div> | |
| ) : ( | |
| insights.map((insight) => ( | |
| <motion.div key={insight.id} className={styles.insightCard} onClick={() => openInsightDossier(insight)}> | |
| <div className={styles.insightHeaderRow}> | |
| <span className={styles.insightType}>{insight.insight_type.replace('_', ' ')}</span> | |
| <span className={styles.insightDept}>{insight.category}</span> | |
| </div> | |
| <div className={styles.insightContent}> | |
| <h3>{insight.suggested_title}</h3> | |
| <div className={styles.reasoningBox}> | |
| <span className={styles.reasoningLabel}>AI REASONING</span> | |
| <p className={styles.reasoningText}>{insight.reasoning}</p> | |
| </div> | |
| </div> | |
| <div className={styles.confidenceSection}> | |
| <div className={styles.confHeader}> | |
| <label>CONFIDENCE LEVEL</label> | |
| <span className={styles.confValue}>{Math.round(insight.confidence_score * 100)}%</span> | |
| </div> | |
| <div className={styles.confMeter}> | |
| <div | |
| className={styles.confFill} | |
| style={{ width: `${insight.confidence_score * 100}%` }} | |
| /> | |
| </div> | |
| </div> | |
| <div className={styles.insightActions}> | |
| <button | |
| className={styles.applyBtn} | |
| onClick={(e) => { e.stopPropagation(); handleApplyInsight(insight); }} | |
| > | |
| <Send size={14} /> DEPLOY | |
| </button> | |
| <button | |
| className={styles.dismissBtn} | |
| onClick={(e) => { e.stopPropagation(); handleDismissInsight(insight.id); }} | |
| > | |
| DISMISS | |
| </button> | |
| </div> | |
| </motion.div> | |
| )) | |
| )} | |
| </motion.div> | |
| ) : loading && articles.length === 0 ? ( | |
| <motion.div key="loading" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className={styles.emptyState}> | |
| <div className={styles.loadingPulse} /> | |
| <p>RECONNAISSANCE IN PROGRESS...</p> | |
| </motion.div> | |
| ) : articles.length === 0 ? ( | |
| <motion.div key="empty" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className={styles.emptyState}> | |
| <div className={styles.emptyVisual}><ShieldCheck size={64} /></div> | |
| <h3>Intelligence Pool Clear</h3> | |
| <p>No documentation found matching current operational filters.</p> | |
| {aiSuggestion && ( | |
| <div className={styles.queryNudge}> | |
| Did you mean: <button onClick={() => { setSearchInput(aiSuggestion); fetchArticles(aiSuggestion, selectedCategory); }}>{aiSuggestion}</button>? | |
| </div> | |
| )} | |
| </motion.div> | |
| ) : ( | |
| <div className={styles.resultsContainer}> | |
| <AnimatePresence> | |
| {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.syntheticLag}>GENERATED IN REAL-TIME</span>} | |
| </div> | |
| <div className={styles.answerText}> | |
| <ReactMarkdown remarkPlugins={[remarkGfm]}> | |
| {aiAnswer} | |
| </ReactMarkdown> | |
| </div> | |
| <div className={styles.spotlightFooter}> | |
| Based on the top documentation matches below. | |
| </div> | |
| </motion.div> | |
| )} | |
| </AnimatePresence> | |
| <motion.div | |
| key="grid" | |
| className={styles.articlesGrid} | |
| initial={{ opacity: 0 }} | |
| animate={{ opacity: 1 }} | |
| > | |
| {paginatedArticles.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={() => openDossier(article)} | |
| > | |
| <div className={styles.cardHeader}> | |
| <div className={styles.typeBadge}> | |
| {article.match_type === 'visual' ? <Zap size={10} /> : <Info size={10} />} | |
| {article.match_type?.toUpperCase() || 'DOCUMENT'} | |
| </div> | |
| <div className={`${styles.statusDot} ${article.is_published ? styles.live : styles.draft}`} /> | |
| </div> | |
| <div className={styles.cardBody}> | |
| <span className={styles.catBadge}>{article.category}</span> | |
| <h3>{article.title}</h3> | |
| <p className={styles.snippet}> | |
| {article.snippet || article.content.replace(/[#*`|>\-]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 140)}... | |
| </p> | |
| </div> | |
| <div className={styles.cardFooter}> | |
| <div className={styles.telemetry}> | |
| <span>TELEMETRY: {new Date(article.updated_at).toLocaleDateString()}</span> | |
| {article.score && <span>MATCH: {Math.round(article.score)}%</span>} | |
| </div> | |
| </div> | |
| </motion.div> | |
| ))} | |
| </motion.div> | |
| </div> | |
| )} | |
| </AnimatePresence> | |
| {totalPages > 1 && ( | |
| <div className={styles.pagination}> | |
| <button | |
| disabled={currentPage === 1} | |
| onClick={() => setCurrentPage(p => p - 1)} | |
| className={styles.pageBtn} | |
| > | |
| <ChevronLeft size={18} /> | |
| </button> | |
| <div className={styles.pageInfo}> | |
| <span>PAGE</span> | |
| <span className={styles.pageNum}>{currentPage}</span> | |
| <span>OF</span> | |
| <span className={styles.pageNum}>{totalPages}</span> | |
| </div> | |
| <button | |
| disabled={currentPage === totalPages} | |
| onClick={() => setCurrentPage(p => p + 1)} | |
| className={styles.pageBtn} | |
| > | |
| <ChevronRight size={18} /> | |
| </button> | |
| </div> | |
| )} | |
| </div> | |
| {/* STRATEGIC DOSSIER DRAWER */} | |
| <AnimatePresence> | |
| {drawerOpen && ( | |
| <> | |
| <motion.div | |
| className={styles.drawerBackdrop} | |
| initial={{ opacity: 0 }} | |
| animate={{ opacity: 1 }} | |
| exit={{ opacity: 0 }} | |
| onClick={() => setDrawerOpen(false)} | |
| /> | |
| <motion.div | |
| className={styles.dossierDrawer} | |
| initial={{ x: '100%' }} | |
| animate={{ x: 0 }} | |
| exit={{ x: '100%' }} | |
| transition={{ type: 'spring', damping: 25, stiffness: 200 }} | |
| > | |
| <header className={styles.dossierHeader}> | |
| <div className={styles.dossierMeta}> | |
| <div className={styles.metaTop}> | |
| <span className={styles.metaLabel}>{selectedInsight ? 'AI KNOWLEDGE INSIGHT' : 'DOCUMENT INTEL'}</span> | |
| <div className={styles.headerRight}> | |
| {canEdit && ( | |
| <div className={styles.modeToggle}> | |
| <button | |
| className={`${styles.modeBtn} ${!isEditing ? styles.activeMode : ''}`} | |
| onClick={() => setIsEditing(false)} | |
| > | |
| <Eye size={14} /> VIEW | |
| </button> | |
| <button | |
| className={`${styles.modeBtn} ${isEditing ? styles.activeMode : ''}`} | |
| onClick={() => setIsEditing(true)} | |
| > | |
| <Edit3 size={14} /> EDIT | |
| </button> | |
| </div> | |
| )} | |
| <button className={styles.closeDrawer} onClick={() => setDrawerOpen(false)}> | |
| <X size={18} /> | |
| </button> | |
| </div> | |
| </div> | |
| {isEditing ? ( | |
| <div className={styles.titleEditRow}> | |
| <input | |
| className={styles.editTitleInput} | |
| value={editTitle} | |
| onChange={e => setEditTitle(e.target.value)} | |
| placeholder="Article Title" | |
| /> | |
| <button | |
| className={`${styles.deployBtn} ${saveStatus === 'success' ? styles.btnSuccess : ''} ${saveStatus === 'error' ? styles.btnError : ''}`} | |
| onClick={handleSaveDossier} | |
| disabled={isSaving} | |
| > | |
| {isSaving ? <Radio size={14} className={styles.spin} /> : <Send size={14} />} | |
| {saveStatus === 'success' ? 'UPDATED' : saveStatus === 'error' ? 'RETRY' : 'SAVE DRAFT'} | |
| </button> | |
| </div> | |
| ) : ( | |
| <div className={styles.titleViewRow}> | |
| <h2>{editTitle}</h2> | |
| {selectedInsight ? ( | |
| <button className={styles.deployInsightBtn} onClick={() => handleApplyInsight(selectedInsight)}> | |
| <Send size={14} /> DEPLOY TO KB | |
| </button> | |
| ) : ( | |
| <span className={`${styles.statusBadge} ${selectedArticle?.is_published ? styles.badgeLive : styles.badgeDraft}`}> | |
| {selectedArticle?.is_published ? <Globe size={12} /> : <Lock size={12} />} | |
| {selectedArticle?.is_published ? 'LIVE' : 'DRAFT'} | |
| </span> | |
| )} | |
| </div> | |
| )} | |
| </div> | |
| </header> | |
| <div className={styles.dossierBody}> | |
| {isEditing ? ( | |
| <div className={styles.editInterface}> | |
| <div className={styles.compactToolbar}> | |
| <div className={styles.toolbarGroup}> | |
| <label>CAT</label> | |
| <select value={editCategory} onChange={e => setEditCategory(e.target.value)}> | |
| {categories.filter(c => c !== 'All').map(c => <option key={c} value={c}>{c}</option>)} | |
| {!categories.includes('General') && <option value="General">General</option>} | |
| </select> | |
| </div> | |
| <div className={styles.toolbarGroup}> | |
| <label>VISIBILITY</label> | |
| <div className={styles.miniToggles}> | |
| <button | |
| className={`${styles.miniToggle} ${editPublished ? styles.activeToggle : ''}`} | |
| onClick={() => setEditPublished(true)} | |
| > | |
| <Globe size={12} /> LIVE | |
| </button> | |
| <button | |
| className={`${styles.miniToggle} ${!editPublished ? styles.activeToggle : ''}`} | |
| onClick={() => setEditPublished(false)} | |
| > | |
| <Lock size={12} /> DRAFT | |
| </button> | |
| </div> | |
| </div> | |
| {canShred && ( | |
| <button className={styles.miniRetract} onClick={() => selectedArticle && handleDeleteArticle(selectedArticle.id)}> | |
| <Trash2 size={12} /> SHRED | |
| </button> | |
| )} | |
| </div> | |
| <div className={styles.editScrollArea}> | |
| <textarea | |
| className={styles.editArea} | |
| value={editContent} | |
| onChange={e => setEditContent(e.target.value)} | |
| placeholder="Enter strategic content in Markdown..." | |
| /> | |
| </div> | |
| </div> | |
| ) : ( | |
| <div className={styles.viewInterface}> | |
| <div className={styles.telemetryBar}> | |
| <div className={styles.telItem}> | |
| <label>{selectedInsight ? 'CONFIDENCE' : 'AUTHOR ID'}</label> | |
| <span>{selectedInsight ? `${Math.round(selectedInsight.confidence_score * 100)}%` : (selectedArticle?.author_id || 'REDACTED')}</span> | |
| </div> | |
| <div className={styles.telItem}> | |
| <label>{selectedInsight ? 'EVIDENCE COUNT' : 'LAST SYNC'}</label> | |
| <span>{selectedInsight ? selectedInsight.evidence_count : (selectedArticle ? new Date(selectedArticle.updated_at).toLocaleString() : 'N/A')}</span> | |
| </div> | |
| <div className={styles.telItem}> | |
| <label>MATCH SCORE</label> | |
| <span>{(selectedInsight ? selectedInsight.confidence_score : selectedArticle?.score) ? `${Math.round((selectedInsight ? selectedInsight.confidence_score : selectedArticle!.score) * 100)}%` : 'STATIC'}</span> | |
| </div> | |
| </div> | |
| <div className={styles.viewScrollArea}> | |
| <AnimatePresence> | |
| {(selectedArticle?.summary || selectedInsight?.reasoning) && ( | |
| <motion.div | |
| className={styles.aiInsightBox} | |
| initial={{ opacity: 0, y: -20 }} | |
| animate={{ opacity: 1, y: 0 }} | |
| > | |
| <div className={styles.insightHeader}> | |
| <Sparkles size={14} className={styles.zapIcon} /> | |
| <span className={styles.insightLabel}>{selectedInsight ? 'AI GAP ANALYSIS' : 'AI INSIGHT'}</span> | |
| </div> | |
| <p className={styles.insightText}>{selectedInsight ? selectedInsight.reasoning : selectedArticle?.summary}</p> | |
| </motion.div> | |
| )} | |
| </AnimatePresence> | |
| <div className={`${styles.markdownContent} ${styles.markdownBody}`}> | |
| <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 || editContent} | |
| </ReactMarkdown> | |
| </div> | |
| </div> | |
| </div> | |
| )} | |
| </div> | |
| </motion.div> | |
| </> | |
| )} | |
| </AnimatePresence> | |
| </div> | |
| ); | |
| }; | |